PHPackages                             alvincoded/grok-php-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. alvincoded/grok-php-client

ActiveLibrary[API Development](/categories/api)

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

v1.3.0(1y ago)531MITPHPPHP ^8.2CI passing

Since Jan 27Pushed 1y ago1 watchersCompare

[ Source](https://github.com/AlvinCoded/grok-php-client)[ Packagist](https://packagist.org/packages/alvincoded/grok-php-client)[ RSS](/packages/alvincoded-grok-php-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (11)Versions (4)Used By (0)

Grok PHP: The 2-in-1 PHP SDK for Grok AI
========================================

[](#grok-php-the-2-in-1-php-sdk-for-grok-ai)

 [ ![Latest Version](https://camo.githubusercontent.com/840e32d8aec31e623713fe51513cff69898d7b9cc6fff0c67ce909ba9850e510/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c76696e636f6465642f67726f6b2d7068702d636c69656e74) ](https://packagist.org/packages/alvincoded/grok-php-client) [ ![PHP Version](https://camo.githubusercontent.com/187240af044d09d5b14a1d9d9ebdf3f7a993e4c7bc09bdb46b4ba661a891bf5b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d626c7565) ](https://php.net) [ ![PHP Version](https://camo.githubusercontent.com/0171c541f6433dcec81b1736e87bba993ce6d1b126d0954ece853c872cc659f7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31312532422d726564) ](https://laravel.com) [ ![Tests Passing](https://github.com/alvincoded/grok-php-client/actions/workflows/test.yml/badge.svg) ](https://github.com/alvincoded/grok-php-client/actions/workflows/test.yml) [ ![License](https://camo.githubusercontent.com/88e1dabf4d223df0950e0985948e231325fefca9fa7fe9e446cf8b1c5e9d9e47/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e) ](LICENSE.md)

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
--------

[](#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
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11+ *(For Laravel applications)*
- [Composer](https://getcomposer.org)
- [Grok AI API key](https://docs.x.ai/docs/overview)

Installation
------------

[](#installation)

Install Grok PHP via Composer:

```
composer require alvincoded/grok-php-client
```

[![New](https://camo.githubusercontent.com/15252d63e30dfe2dd4481de4d3347888e822efe630b1c2bc2365f4c0e33583f8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6e65772d627269676874677265656e)](https://camo.githubusercontent.com/15252d63e30dfe2dd4481de4d3347888e822efe630b1c2bc2365f4c0e33583f8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6e65772d627269676874677265656e) *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 `.env` file.

Quick Start
-----------

[](#quick-start)

*****Framework-agnostic PHP Usage :*****

##### *Chat Completion*

[](#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*

[](#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*

[](#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*

[](#embeddings)

```
use GrokPHP\Client\GrokClient;

$client = new GrokClient($apiKey);

$embeddingResponse = $client->embeddings()->create('Hello, world!');
$embeddings = $embeddingResponse->getEmbeddings();
```

##### *Model-specific executions*

[](#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*

[](#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)*

[](#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];
```

[![New](https://camo.githubusercontent.com/15252d63e30dfe2dd4481de4d3347888e822efe630b1c2bc2365f4c0e33583f8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6e65772d627269676874677265656e)](https://camo.githubusercontent.com/15252d63e30dfe2dd4481de4d3347888e822efe630b1c2bc2365f4c0e33583f8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6e65772d627269676874677265656e) *****Laravel Usage :*****

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
-----------------

[](#response-handling)

#### *Chat/Completion Response Methods*

[](#chatcompletion-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*

[](#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*

[](#embedding-response-methods)

```
$response->getEmbeddings();    // Get embeddings
$response->getUsage();         // Get token usage
```

Error Handling
--------------

[](#error-handling)

```
use GrokPHP\Exceptions\GrokException;

try {
    $response = $client->chat()->generate("Your prompt");
} catch (GrokException $e) {
    echo "Error: " . $e->getMessage();
}
```

Supported Models
----------------

[](#supported-models)

ModelSupports StreamingSupports Functionsgrok-betaYesYesgrok-2-vision-1212NoNogrok-2-1212YesYes
Supported Parameters
--------------------

[](#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
---------------------

[](#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
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Contributions are highly aappreciated! Please see the [Contributing Guide](CONTRIBUTING.md) for details.

Security
--------

[](#security)

Please review the [security policy](SECURITY.md) on how to report security vulnerabilities.

License
-------

[](#license)

Grok PHP is an open-sourced software licensed under the [MIT license](LICENSE).

Support
-------

[](#support)

If you encounter any issues or have questions, please [open an issue](https://github.com/alvincoded/grok-php-client/issues) on the GitHub repository.

---

Built with ❤️ for the AI community.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance44

Moderate activity, may be stable

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~21 days

Total

3

Last Release

434d ago

PHP version history (2 changes)1.0.0PHP ^8.1

v1.3.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/8d379c04911007be24e6b04ca9d4dcbcf549b58aecfbae5a78a4295bc4ba58e7?d=identicon)[AlvinCoded](/maintainers/AlvinCoded)

---

Top Contributors

[![AlvinCoded](https://avatars.githubusercontent.com/u/112624931?v=4)](https://github.com/AlvinCoded "AlvinCoded (23 commits)")

---

Tags

aiapiapi-clientartificial-intelligencegrokgrok-aiphpsdksdk-phpxaiapilaravelsdkaimachine learningartificial intelligencegrokx.ai

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/alvincoded-grok-php-client/health.svg)

```
[![Health](https://phpackages.com/badges/alvincoded-grok-php-client/health.svg)](https://phpackages.com/packages/alvincoded-grok-php-client)
```

###  Alternatives

[deepseek-php/deepseek-php-client

deepseek PHP client is a robust and community-driven PHP client library for seamless integration with the Deepseek API, offering efficient access to advanced AI and data processing capabilities.

47073.9k5](/packages/deepseek-php-deepseek-php-client)[gemini-api-php/laravel

Gemini API client for Laravel

8915.7k](/packages/gemini-api-php-laravel)[mozex/anthropic-php

Anthropic PHP is a supercharged community-maintained PHP API client that allows you to interact with Anthropic API.

46365.1k13](/packages/mozex-anthropic-php)[softcreatr/php-mistral-ai-sdk

A powerful and easy-to-use PHP SDK for the Mistral AI API, allowing seamless integration of advanced AI-powered features into your PHP projects.

1517.9k](/packages/softcreatr-php-mistral-ai-sdk)[softcreatr/php-perplexity-ai-sdk

A powerful and easy-to-use PHP SDK for the pplx (Perplexity) API, allowing seamless integration of advanced AI-powered features into your PHP projects..

149.1k](/packages/softcreatr-php-perplexity-ai-sdk)[bushlanov-dev/max-bot-api-client-php

Max Bot API Client library

281.6k](/packages/bushlanov-dev-max-bot-api-client-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
