{"id":24727181,"url":"https://github.com/AlvinCoded/grok-php-client","last_synced_at":"2025-10-09T21:32:17.824Z","repository":{"id":274400354,"uuid":"922784789","full_name":"AlvinCoded/grok-php-client","owner":"AlvinCoded","description":"The 2-in-1 PHP SDK offering seamless integration with Grok AI API for both framework-agnostic PHP and Laravel 11+ applications.","archived":false,"fork":false,"pushed_at":"2025-03-12T11:03:17.000Z","size":122,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-06T22:43:16.419Z","etag":null,"topics":["ai","api","api-client","artificial-intelligence","grok","grok-ai","php","sdk","sdk-php","xai"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AlvinCoded.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-01-27T04:03:01.000Z","updated_at":"2025-03-10T15:41:27.000Z","dependencies_parsed_at":null,"dependency_job_id":"9792f091-ffb1-499d-8ef5-bb81dfc9e482","html_url":"https://github.com/AlvinCoded/grok-php-client","commit_stats":null,"previous_names":["alvincoded/php-grok-ai","alvincoded/grok-php-client"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/AlvinCoded/grok-php-client","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvinCoded%2Fgrok-php-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvinCoded%2Fgrok-php-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvinCoded%2Fgrok-php-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvinCoded%2Fgrok-php-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AlvinCoded","download_url":"https://codeload.github.com/AlvinCoded/grok-php-client/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlvinCoded%2Fgrok-php-client/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279002051,"owners_count":26083286,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-09T02:00:07.460Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","api","api-client","artificial-intelligence","grok","grok-ai","php","sdk","sdk-php","xai"],"created_at":"2025-01-27T14:58:10.147Z","updated_at":"2025-10-09T21:32:17.819Z","avatar_url":"https://github.com/AlvinCoded.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003eGrok PHP: The 2-in-1 PHP SDK for Grok AI\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://packagist.org/packages/alvincoded/grok-php-client\"\u003e\n      \u003cimg src=\"https://img.shields.io/packagist/v/alvincoded/grok-php-client\" alt=\"Latest Version\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://php.net\"\u003e\n      \u003cimg src=\"https://img.shields.io/badge/PHP-8.2%2B-blue\" alt=\"PHP Version\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://laravel.com\"\u003e\n      \u003cimg src=\"https://img.shields.io/badge/Laravel-11%2B-red\" alt=\"PHP Version\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/alvincoded/grok-php-client/actions/workflows/test.yml\"\u003e\n      \u003cimg src=\"https://github.com/alvincoded/grok-php-client/actions/workflows/test.yml/badge.svg\" alt=\"Tests Passing\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"LICENSE.md\"\u003e\n      \u003cimg src=\"https://img.shields.io/badge/license-MIT-brightgreen\" alt=\"License\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\nGrok PHP is a 2-in-1 PHP SDK offering seamless integration with Grok AI API for both **framework-agnostic PHP** and **Laravel 11+** applications.\n\n## Features\n\n- **Dual Architecture**: Use as framework-agnostic PHP library or first-class Laravel package with extensive error handling\n- **Full API Coverage**: Chat, completions, images, embeddings, and structured outputs\n- **Modern PHP**: Strict types, enums, and attributes for schema definition\n- **Laravel Integration**: Auto-discovery, config publishing, and facade support\n- **Advanced Chat Capabilities:** Full support for multi-turn conversations and real-time streaming\n- **Model Flexibility:** Support for multiple Grok models (Grok-2, Grok-2-Vision, etc.)\n- **Enterprise Ready:** Secure API handling with proper authentication\n- **Easy Configuration:** Simple setup with minimal dependencies\n\n## Requirements\n\n- PHP 8.2 or higher\n- Laravel 11+ _(For Laravel applications)_\n- [Composer](https://getcomposer.org)\n- [Grok AI API key](https://docs.x.ai/docs/overview)\n\n## Installation\n\nInstall Grok PHP via Composer:\n\n```bash\ncomposer require alvincoded/grok-php-client\n```\n\u003cimg src=\"https://img.shields.io/badge/new-brightgreen\" alt=\"New\" width='20'\u003e _Do the following with __Laravel applications only__:_\n```bash\nphp artisan grok:install\n```\n\u003e **Note:** This command publishes the configuration file and adds the relevant environment variables to your `.env` file.\n\n\n## Quick Start\n\n__***Framework-agnostic PHP Usage :***__\n\n##### _Chat Completion_\n\n```php\nuse GrokPHP\\Client\\GrokClient;\nuse GrokPHP\\Params;\n\n$client = new GrokClient($apiKey);\n\n// Simple chat\n$response = $client-\u003echat()-\u003egenerate(\"Tell me a joke about AI\");\necho $response-\u003egetContent();\n\n// With system message\n$response = $client-\u003echat()-\u003egenerate(\n    \"What's the best programming language?\",\n    Params::create()\n    -\u003esystemMessage('You are an experienced programmer.')\n    -\u003etemperature(0.7)\n);\n\n// Streaming response\n$client-\u003echat()-\u003estreamChat(\n    'Tell me something about Grok PHP',\n    function (ChatMessage $chunk) {\n        echo $chunk-\u003etext();\n    }\n);\n\n// Multi-turn conversation\n$chat = $client-\u003ebeginConvo();\n\n$response = $chat-\u003esend('What is machine learning?');\necho $response-\u003etext();\n\n$response = $chat-\u003esend('Give me an example');\necho $response-\u003etext();\n```\n\n##### _Text Completions_\n\n```php\nuse GrokPHP\\Client\\GrokClient;\nuse GrokPHP\\Params;\n\n$client = new GrokClient($apiKey);\n\n// Basic completion\n$response = $client-\u003ecompletions()-\u003ecreate(\n    \"The future of AI will\",\n    Params::create()-\u003emaxTokens(100)-\u003etemperature(0.7)\n);\n\n// Multiple completions\n$responses = $client-\u003ecompletions()-\u003ecreateMultiple(\n    \"Write a creative title for a sci-fi novel\",\n    3,\n    Params::create()-\u003etemperature(1.0)\n);\n\n// Get token count\n$tokenCount = $client-\u003ecompletions()-\u003egetTokenCount(\"Sample text\");\n```\n\n##### _Image Understanding_\n\n```php\nuse GrokPHP\\Client\\GrokClient;\nuse GrokPHP\\Params;\n\n$client = new GrokClient($apiKey);\n\n// Basic image analysis\n$response = $client-\u003eimages()-\u003eanalyze('https://picsum.photos/200/300');\n\n// Detailed analysis with prompt\n$response = $client-\u003eimages()-\u003eanalyze(\n    'https://picsum.photos/200/300',\n    'What objects can you identify in this image?',\n    Params::create()-\u003emaxTokens(300)-\u003etemperature(0.8)\n);\n\n// Check image content\n$containsPeople = $response-\u003econtainsContent('person');\n```\n##### _Embeddings_\n\n```php\nuse GrokPHP\\Client\\GrokClient;\n\n$client = new GrokClient($apiKey);\n\n$embeddingResponse = $client-\u003eembeddings()-\u003ecreate('Hello, world!');\n$embeddings = $embeddingResponse-\u003egetEmbeddings();\n```\n\n##### _Model-specific executions_\n\n```php\nuse GrokPHP\\Client\\GrokClient;\nuse GrokPHP\\Enums\\Model;\n\n$client = new GrokClient($apiKey);\n\n// Simple chat (with model specification)\n$response = $client-\u003emodel(Model::GROK_2_1212)-\u003egenerate('Tell me a joke about AI');\necho $response-\u003etext();\n\n// Get model capabilities\n$model = Model::GROK_2_1212\n$config = $client-\u003egetConfig();\n\necho $config-\u003egetModelMaxTokens($model)      // 32,768\necho $config-\u003emodelSupportsStreaming($model) // true\necho $config-\u003emodelSupportsFunctions($model) // false\n```\n\n##### _Structured Output_\n```php\nuse GrokPHP\\Client\\GrokClient;\nuse GrokPHP\\Enums\\Model;\n\n// Scenario example: A university library needs to process 50,000 research papers into their new digital repository.\n// Each entry requires consistent metadata fields.\n\n// 1. Define schema once\n$jsonSchema = [\n    \"type\" =\u003e \"object\",\n    \"properties\" =\u003e [\n        \"title\" =\u003e [\"type\" =\u003e \"string\"],\n        \"authors\" =\u003e [\"type\" =\u003e \"array\", \"items\" =\u003e [\"type\" =\u003e \"string\"]],\n        \"publication_year\" =\u003e [\"type\" =\u003e \"integer\"],\n        \"doi\" =\u003e [\"type\" =\u003e \"string\"],\n        \"keywords\" =\u003e [\"type\" =\u003e \"array\", \"items\" =\u003e [\"type\" =\u003e \"string\"]],\n        \"citation_count\" =\u003e [\"type\" =\u003e \"integer\"]\n    ],\n    \"required\" =\u003e [\"title\", \"authors\"]\n];\n\n\n// 2. Process documents\n$client = new GrokClient($apiKey);\n\nforeach ($researchPapers as $paperText) {\n    $metadata = $client-\u003echat()-\u003egenerateStructured($paperText, $jsonSchema);\n    \n    // 3. Directly store structured data\n    $this-\u003edatabase-\u003einsertPaper(\n        title: $metadata['title'],\n        authors: $metadata['authors'],\n        year: $metadata['publication_year'] ?? null,\n        doi: $metadata['doi'] ?? '',\n        keywords: $metadata['keywords'] ?? []\n    );\n}\n```\n\n##### _Structured Output (alt. option with PHP class)_\n\n```php\n// Define your schema as a PHP class\nclass ResearchPaper extends \\GrokPHP\\Utils\\DataModel \n{\n    #[SchemaProperty(type: 'string', description: 'Paper title')]\n    public string $title;\n    \n    #[SchemaProperty(type: 'array', description: 'List of authors')]\n    public array $authors;\n    \n    #[SchemaProperty(type: 'integer', description: 'Year of publication', required: false)]\n    public int $publicationYear;\n}\n\n// ...then, in your application code\n$result = $client-\u003echat()-\u003egenerateStructured(\n            \"Extract research paper details\", \n             ResearchPaper::class\n          );\n\n// ...and finally, get typed properties\necho $result-\u003etitle;\necho $result-\u003eauthors[0];\n\n```\n\n\u003cimg src=\"https://img.shields.io/badge/new-brightgreen\" alt=\"New\" width='20'\u003e __***Laravel Usage :***__\n\nThe 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! ✨\n\n```php\nuse GrokPHP\\Enums\\Model;\nuse GrokPHP\\Facades\\Grok;\nuse GrokPHP\\Client\\GrokClient;\nuse GrokPHP\\Params;\n\npublic function __construct(\nprivate GrokClient $grok\n) {}\n\npublic function analyzeImage(): Response\n{\n    return $this-\u003egrok-\u003emodel(Model::GROK_2_VISION_1212)-\u003eimages()-\u003eanalyze('https://picsum.photos/200/300.jpg');\n}\n\n// Using the facade\npublic function ask(): Response\n{\n    $prompt = \"Do you know the muffin man?\";\n    $params =  Params::create()-\u003emaxTokens(300)-\u003etemperature(0.8);\n\n    return Grok::model(Model::GROK_2_1212)-\u003echat()-\u003egenerate($prompt, $params);\n}\n```\n\n\n## Response Handling\n\n#### _Chat/Completion Response Methods_\n\n```php\n$response-\u003egetContent();       // Get response content\n$response-\u003egetRole();          // Get message role\n$response-\u003egetFinishReason();  // Get completion finish reason\n$response-\u003egetId();            // Get response ID\n$response-\u003egetModel();         // Get model used\n$response-\u003egetUsage();         // Get token usage statistics\n```\n\n#### _Image Analysis Response Methods_\n\n```php\n$response-\u003egetAnalysis();      // Get analysis text\n$response-\u003egetImageUrl();      // Get analyzed image URL\n$response-\u003egetMetadata();      // Get image metadata\n$response-\u003egetUsage();         // Get token usage\n```\n\n#### _Embedding Response Methods_\n```php\n$response-\u003egetEmbeddings();    // Get embeddings\n$response-\u003egetUsage();         // Get token usage\n```\n\n## Error Handling\n\n```php\nuse GrokPHP\\Exceptions\\GrokException;\n\ntry {\n    $response = $client-\u003echat()-\u003egenerate(\"Your prompt\");\n} catch (GrokException $e) {\n    echo \"Error: \" . $e-\u003egetMessage();\n}\n```\n\n## Supported Models\n\n| Model               | Supports Streaming | Supports Functions |\n|---------------------|--------------------|--------------------|\n| grok-beta           | Yes                | Yes                |\n| grok-2-vision-1212  | No                 | No                 |\n| grok-2-1212         | Yes                | Yes                |\n\n\u003cbr\u003e\n\n## Supported Parameters\n\n\n- `temperature(float $value)`: Sets the temperature for sampling the next token.\n- `maxTokens(int $value)`: Sets the maximum number of tokens to generate in the completion.\n- `topP(float $value)`: Sets the top P value for nucleus sampling.\n- `stream(bool $value)`: Sets the presence of streaming responses.\n- `systemMessage(string $message)`: Sets the system message for the AI model.\n- `n(int $value)`: Sets the number of completions to generate.\n- `presencePenalty(float $value)`: Sets the presence penalty.\n- `frequencyPenalty(float $value)`: Sets the frequency penalty.\n- `logitBias(array $values)`: Sets the logit bias for the completion.\n- `stop(array $values)`: Sets the stop sequence for the completion.\n- `logprobs(int $value)`: Sets the logprobs parameter.\n- `dimensions(int $value)`: Sets the dimensions parameter for embedding.\n- `echo(bool $value)`: Sets the echo parameter.\n- `user(string $value)`: Sets the user parameter.\n- `suffix(string $value)`: Sets the suffix that is appended to the completion.\n\n\u003cbr\u003e\n\n## Environment Variables\nAdd the following to your `.env` file:\n```bash\nGROK_API_KEY=your-api-key\n\n# Include if Laravel is used\nGROK_DEFAULT_MODEL=grok-2-latest\nGROK_BASE_URL=https://api.x.ai\n```\n\u003cbr\u003e\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nContributions are highly aappreciated! Please see the [Contributing Guide](CONTRIBUTING.md) for details.\n\n## Security\n\nPlease review the [security policy](SECURITY.md) on how to report security vulnerabilities.\n\n## License\n\nGrok PHP is an open-sourced software licensed under the [MIT license](LICENSE).\n\n## Support\n\nIf you encounter any issues or have questions, please [open an issue](https://github.com/alvincoded/grok-php-client/issues) on the GitHub repository.\n\n---\n\u003c/br\u003e\n\n\u003cp align='center'\u003eBuilt with ❤️ for the AI community.\u003c/p\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAlvinCoded%2Fgrok-php-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAlvinCoded%2Fgrok-php-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAlvinCoded%2Fgrok-php-client/lists"}