PHPackages                             alexpago/grok-php - 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. alexpago/grok-php

ActiveLibrary[API Development](/categories/api)

alexpago/grok-php
=================

PHP library for interacting with the Grok API. Supports: grok-3, grok-3-mini, grok-4, grok-2-image (and other models).

1.0.3(8mo ago)078MITPHPPHP ^8.1

Since Aug 29Pushed 8mo agoCompare

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

READMEChangelog (4)Dependencies (4)Versions (5)Used By (0)

GrokChat PHP Library
====================

[](#grokchat-php-library)

**GrokChat** is a PHP library for interacting with the [Grok API](https://x.ai/).
It provides a simple, object-oriented interface for sending chat messages, managing multi-turn conversations, handling responses, and streaming results.

---

✨ Features
----------

[](#-features)

- Supports: grok-3, grok-3-mini, grok-4, grok-2-image (and other models)
- Simple API for sending chat messages:

    ```
    $chat->query('Hello world')->run();
    ```
- Multi-turn conversations:

    ```
    $chat->query('Hello. I am Lucas')
         ->query('Who are you?')
         ->run();
    ```
- Supports image understanding

```
  $chat->queryImage(
    image: '',
    text: 'Describe the image'
  )
```

- Supports image generation

```
  $generate->generate('A beautiful sunset over a calm ocean')->getImage()
```

- Streaming responses with custom handlers:

    ```
    $chat->query('Let\'s talk about science')
         ->stream(function ($chunk) { ... });
    ```
- Supports roles (`Role::USER`, `Role::SYSTEM`)
- Configurable (temperature, model, roles, etc.)
- PSR-4 autoloading via Composer

---

📦 Installation
--------------

[](#-installation)

Install via Composer:

```
composer require alexpago/grok-php
```

---

🚀 Quick Start
-------------

[](#-quick-start)

> **Tip:**
>
> - Use `send()` when you only need the **message text** (string or `null`).
> - Use `run()` when you need the **full response object** (`ChatResponse` or `ChatErrorResponse`).

---

### 1. Start a Simple Chat

[](#1-start-a-simple-chat)

```
use Pago\Grok\Client\GrokChat;

$chat = new GrokChat('apikey');
$text = $chat->query('Hello! How are you?')->send();
```

> `send()` returns the text response (`string|null`).

---

### 2. Chat with Multiple Messages

[](#2-chat-with-multiple-messages)

```
use Pago\Grok\Client\GrokChat;
use Pago\Grok\Enums\Role;

$chat = new GrokChat('apikey');
$text = $chat
    ->query('Hello! I am Lucas')
    ->query('Hello. I am Grok. How are you?', Role::SYSTEM)
    ->send();
```

> Available roles: `Role::USER` (default) and `Role::SYSTEM`.

---

### 3. Get the Full Response

[](#3-get-the-full-response)

```
use Pago\Grok\Client\GrokChat;
use Pago\Grok\Responses\ChatErrorResponse;
use Pago\Grok\Responses\ChatResponse;

$chat = new GrokChat('apikey');
$response = $chat->query('Hello!')->run();

if ($response instanceof ChatErrorResponse) {
    throw new RuntimeException(
        $response->getMessage(),
        $response->getCode()
    );
}

// Grok's answer
$text = $response->getContent();

// Full response as array
$responseData = $response->toArray();
```

---

### 4. Chat with Options

[](#4-chat-with-options)

```
use Pago\Grok\Client\GrokChat;
use Pago\Grok\Enums\Model;

$chat = new GrokChat('apikey');
$response = $chat
    ->query('2+2')
    ->setTemperature(0.3)   // accepts float or Temperature enum
    ->setModel(Model::GROK_4) // default: "grok-4"
    ->run();

if ($response instanceof ChatErrorResponse) {
    throw new RuntimeException(
        $response->getMessage(),
        $response->getCode()
    );
}

$text = $response->getContent();
$responseData = $response->toArray();
```

> **Temperature:**Lower = focused &amp; reliable Higher = creative &amp; diverse (Regular ChatGPT default ≈ `1.3`)

---

### 5. Image understanding

[](#5-image-understanding)

You can use the `queryImage` method to use "Grok Understanding". First argument accepts an external image URL or a base64-encoded string. Support only JPEG and PNG formats are supported. Maximum size is 20 MB.

```
use Pago\Grok\Client\GrokChat;
use Pago\Grok\Enums\ImageDetail;

$chat = new GrokChat('apikey');
$chat = $chat->queryImage(
    'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
    ImageDetail::LOW,
    'Describe the image'
);
$describe = $chat->send();
```

---

### 6. Image generation

[](#6-image-generation)

To generate an image, use `GrokImageGeneration` class instead of GrokChat.

```
use Pago\Grok\Client\GrokImageGeneration;

$chat = new GrokImageGeneration('apikey');
$image = $generate->generate('A beautiful sunset over a calm ocean')->getImage();
```

---

### 7. Streaming Results

[](#7-streaming-results)

Use a custom callback to process streaming chunks:

```
use Pago\Grok\Client\GrokChat;
use Pago\Grok\Enums\Role;
use Psr\Http\Message\StreamInterface;

$chat = new GrokChat('apikey');
$chat
    ->query('Hello! I am Lucas')
    ->query('Hello. I am Grok. How are you?', Role::SYSTEM)
    ->stream(function (StreamInterface $body) {
        // Read chunks from the response
        $line = trim($body->read(1024));
        if ($line === '' || !str_starts_with($line, 'data: ')) {
            return;
        }
        if ($line === 'data: [DONE]') {
            return;
        }

        // Remove prefix "data: "
        $json = substr($line, 6);

        // Convert to array
        $chunk = json_decode($json, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return;
        }

        if (!empty($chunk['choices'][0]['delta']['content'])) {
            $piece = $chunk['choices'][0]['delta']['content'];
            echo $piece;
            ob_flush();
            flush();
        }
    });
```

---

⚙️ Requirements
---------------

[](#️-requirements)

- PHP 8.1+
- Composer

---

📜 License
---------

[](#-license)

MIT License.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance59

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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 ~0 days

Total

4

Last Release

261d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7a973ee59fdf6496e08bd8c96c834a154b762a7547a9c9ea6cd678a011c497ab?d=identicon)[alexpago](/maintainers/alexpago)

---

Top Contributors

[![alexpago](https://avatars.githubusercontent.com/u/177669099?v=4)](https://github.com/alexpago "alexpago (9 commits)")

---

Tags

apiaichatChatGptGrok AIgrokgrok-php-clientGrok AI APIgrok ai sdkgrok ai clientgrok ai phpgrok ai php sdkgrok ai php clientx.aigrok-phpgrok-php-sdkgrok-chatgrok-chat-apigrok-chat-sdkgrok-chat-clientgrok-chat-phpgrok-chat-php-sdkgrok-chat-php-client

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[get-stream/stream-chat

A PHP client for Stream Chat (https://getstream.io/chat/)

301.8M2](/packages/get-stream-stream-chat)[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5010.8k](/packages/claude-php-claude-php-sdk-laravel)

PHPackages © 2026

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