alvincoded/grok-php-client
Composer 安装命令:
composer require alvincoded/grok-php-client
包简介
A 2-in-1 PHP SDK to interact with the Grok AI API for both framework-agnostic PHP and Laravel applications
README 文档
README
Grok PHP is a 2-in-1 PHP SDK offering seamless integration with Grok AI API for both framework-agnostic PHP and Laravel 11+ applications.
Features
- Dual Architecture: Use as framework-agnostic PHP library or first-class Laravel package with extensive error handling
- Full API Coverage: Chat, completions, images, embeddings, and structured outputs
- Modern PHP: Strict types, enums, and attributes for schema definition
- Laravel Integration: Auto-discovery, config publishing, and facade support
- Advanced Chat Capabilities: Full support for multi-turn conversations and real-time streaming
- Model Flexibility: Support for multiple Grok models (Grok-2, Grok-2-Vision, etc.)
- Enterprise Ready: Secure API handling with proper authentication
- Easy Configuration: Simple setup with minimal dependencies
Requirements
- PHP 8.2 or higher
- Laravel 11+ (For Laravel applications)
- Composer
- Grok AI API key
Installation
Install Grok PHP via Composer:
composer require alvincoded/grok-php-client
Do the following with Laravel applications only:
php artisan grok:install
Note: This command publishes the configuration file and adds the relevant environment variables to your
.envfile.
Quick Start
Framework-agnostic PHP Usage :
Chat Completion
use GrokPHP\Client\GrokClient; use GrokPHP\Params; $client = new GrokClient($apiKey); // Simple chat $response = $client->chat()->generate("Tell me a joke about AI"); echo $response->getContent(); // With system message $response = $client->chat()->generate( "What's the best programming language?", Params::create() ->systemMessage('You are an experienced programmer.') ->temperature(0.7) ); // Streaming response $client->chat()->streamChat( 'Tell me something about Grok PHP', function (ChatMessage $chunk) { echo $chunk->text(); } ); // Multi-turn conversation $chat = $client->beginConvo(); $response = $chat->send('What is machine learning?'); echo $response->text(); $response = $chat->send('Give me an example'); echo $response->text();
Text Completions
use GrokPHP\Client\GrokClient; use GrokPHP\Params; $client = new GrokClient($apiKey); // Basic completion $response = $client->completions()->create( "The future of AI will", Params::create()->maxTokens(100)->temperature(0.7) ); // Multiple completions $responses = $client->completions()->createMultiple( "Write a creative title for a sci-fi novel", 3, Params::create()->temperature(1.0) ); // Get token count $tokenCount = $client->completions()->getTokenCount("Sample text");
Image Understanding
use GrokPHP\Client\GrokClient; use GrokPHP\Params; $client = new GrokClient($apiKey); // Basic image analysis $response = $client->images()->analyze('https://picsum.photos/200/300'); // Detailed analysis with prompt $response = $client->images()->analyze( 'https://picsum.photos/200/300', 'What objects can you identify in this image?', Params::create()->maxTokens(300)->temperature(0.8) ); // Check image content $containsPeople = $response->containsContent('person');
Embeddings
use GrokPHP\Client\GrokClient; $client = new GrokClient($apiKey); $embeddingResponse = $client->embeddings()->create('Hello, world!'); $embeddings = $embeddingResponse->getEmbeddings();
Model-specific executions
use GrokPHP\Client\GrokClient; use GrokPHP\Enums\Model; $client = new GrokClient($apiKey); // Simple chat (with model specification) $response = $client->model(Model::GROK_2_1212)->generate('Tell me a joke about AI'); echo $response->text(); // Get model capabilities $model = Model::GROK_2_1212 $config = $client->getConfig(); echo $config->getModelMaxTokens($model) // 32,768 echo $config->modelSupportsStreaming($model) // true echo $config->modelSupportsFunctions($model) // false
Structured Output
use GrokPHP\Client\GrokClient; use GrokPHP\Enums\Model; // Scenario example: A university library needs to process 50,000 research papers into their new digital repository. // Each entry requires consistent metadata fields. // 1. Define schema once $jsonSchema = [ "type" => "object", "properties" => [ "title" => ["type" => "string"], "authors" => ["type" => "array", "items" => ["type" => "string"]], "publication_year" => ["type" => "integer"], "doi" => ["type" => "string"], "keywords" => ["type" => "array", "items" => ["type" => "string"]], "citation_count" => ["type" => "integer"] ], "required" => ["title", "authors"] ]; // 2. Process documents $client = new GrokClient($apiKey); foreach ($researchPapers as $paperText) { $metadata = $client->chat()->generateStructured($paperText, $jsonSchema); // 3. Directly store structured data $this->database->insertPaper( title: $metadata['title'], authors: $metadata['authors'], year: $metadata['publication_year'] ?? null, doi: $metadata['doi'] ?? '', keywords: $metadata['keywords'] ?? [] ); }
Structured Output (alt. option with PHP class)
// Define your schema as a PHP class class ResearchPaper extends \GrokPHP\Utils\DataModel { #[SchemaProperty(type: 'string', description: 'Paper title')] public string $title; #[SchemaProperty(type: 'array', description: 'List of authors')] public array $authors; #[SchemaProperty(type: 'integer', description: 'Year of publication', required: false)] public int $publicationYear; } // ...then, in your application code $result = $client->chat()->generateStructured( "Extract research paper details", ResearchPaper::class ); // ...and finally, get typed properties echo $result->title; echo $result->authors[0];
The coolest part about using Laravel with Grok PHP? You don't have to learn any new tricks! Just use it the same way you would with the framework-agnostic PHP and you're good to go. It's like magic, but better! ✨
use GrokPHP\Enums\Model; use GrokPHP\Facades\Grok; use GrokPHP\Client\GrokClient; use GrokPHP\Params; public function __construct( private GrokClient $grok ) {} public function analyzeImage(): Response { return $this->grok->model(Model::GROK_2_VISION_1212)->images()->analyze('https://picsum.photos/200/300.jpg'); } // Using the facade public function ask(): Response { $prompt = "Do you know the muffin man?"; $params = Params::create()->maxTokens(300)->temperature(0.8); return Grok::model(Model::GROK_2_1212)->chat()->generate($prompt, $params); }
Response Handling
Chat/Completion Response Methods
$response->getContent(); // Get response content $response->getRole(); // Get message role $response->getFinishReason(); // Get completion finish reason $response->getId(); // Get response ID $response->getModel(); // Get model used $response->getUsage(); // Get token usage statistics
Image Analysis Response Methods
$response->getAnalysis(); // Get analysis text $response->getImageUrl(); // Get analyzed image URL $response->getMetadata(); // Get image metadata $response->getUsage(); // Get token usage
Embedding Response Methods
$response->getEmbeddings(); // Get embeddings $response->getUsage(); // Get token usage
Error Handling
use GrokPHP\Exceptions\GrokException; try { $response = $client->chat()->generate("Your prompt"); } catch (GrokException $e) { echo "Error: " . $e->getMessage(); }
Supported Models
| Model | Supports Streaming | Supports Functions |
|---|---|---|
| grok-beta | Yes | Yes |
| grok-2-vision-1212 | No | No |
| grok-2-1212 | Yes | Yes |
Supported Parameters
temperature(float $value): Sets the temperature for sampling the next token.maxTokens(int $value): Sets the maximum number of tokens to generate in the completion.topP(float $value): Sets the top P value for nucleus sampling.stream(bool $value): Sets the presence of streaming responses.systemMessage(string $message): Sets the system message for the AI model.n(int $value): Sets the number of completions to generate.presencePenalty(float $value): Sets the presence penalty.frequencyPenalty(float $value): Sets the frequency penalty.logitBias(array $values): Sets the logit bias for the completion.stop(array $values): Sets the stop sequence for the completion.logprobs(int $value): Sets the logprobs parameter.dimensions(int $value): Sets the dimensions parameter for embedding.echo(bool $value): Sets the echo parameter.user(string $value): Sets the user parameter.suffix(string $value): Sets the suffix that is appended to the completion.
Environment Variables
Add the following to your .env file:
GROK_API_KEY=your-api-key
# Include if Laravel is used
GROK_DEFAULT_MODEL=grok-2-latest
GROK_BASE_URL=https://api.x.ai
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Contributions are highly aappreciated! Please see the Contributing Guide for details.
Security
Please review the security policy on how to report security vulnerabilities.
License
Grok PHP is an open-sourced software licensed under the MIT license.
Support
If you encounter any issues or have questions, please open an issue on the GitHub repository.
Built with ❤️ for the AI community.
alvincoded/grok-php-client 适用场景与选型建议
alvincoded/grok-php-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 34 次下载、GitHub Stars 达 5, 最近一次更新时间为 2025 年 02 月 03 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「sdk」 「laravel」 「artificial intelligence」 「machine learning」 「ai」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 alvincoded/grok-php-client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 alvincoded/grok-php-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 alvincoded/grok-php-client 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A PSR-7 compatible library for making CRUD API endpoints
Alfabank REST API integration
Laravel package for Accurate Online API integration.
A lightweight plain-PHP framework for database-backed CRUD APIs.
Shared RCX Laravel DataTables UI and configuration helpers.
Boot a Laravel project on any machine with one command: app:serve installs missing tools (PHP, Node, Composer, Herd, Docker), creates .env, sets up the database, runs migrations, builds assets, starts a queue worker and serves via Herd, Sail or artisan serve; app:down cleanly stops everything it sta
统计信息
- 总下载量: 34
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 5
- 点击次数: 30
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-02-03