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

ActiveLibrary[API Development](/categories/api)

grok-php/client
===============

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

v1.3.0(1y ago)317.4k—7.7%10[2 issues](https://github.com/grok-php/client/issues)[3 PRs](https://github.com/grok-php/client/pulls)4MITPHPPHP ^8.2 || ^8.3 || ^8.4

Since Feb 6Pushed 1y ago1 watchersCompare

[ Source](https://github.com/grok-php/client)[ Packagist](https://packagist.org/packages/grok-php/client)[ Docs](https://github.com/grok-php/client)[ GitHub Sponsors](https://github.com/thefeqy)[ RSS](/packages/grok-php-client/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (6)Versions (6)Used By (4)

🧠 Grok PHP Client
=================

[](#-grok-php-client)

[![Grok PHP Client](assets/images/grok-client.png)](assets/images/grok-client.png)

**A lightweight, framework-agnostic PHP client for interacting with Grok AI APIs.**Supports **PHP 8.2+**, built with **OOP best practices**, and **fully type-safe**.

[![Latest Version](https://camo.githubusercontent.com/c6b36dcad103e114f14443da0acf83df71c4e1252e15023968c6c60372359397/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f67726f6b2d7068702f636c69656e74)](https://packagist.org/packages/grok-php/client)[![PHP Version](https://camo.githubusercontent.com/187240af044d09d5b14a1d9d9ebdf3f7a993e4c7bc09bdb46b4ba661a891bf5b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d626c7565)](https://php.net)[![Total Downloads](https://camo.githubusercontent.com/9b33d737b3965564ab5878dbc729f319c0f7156f43b48452f91d24629fbb731d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f67726f6b2d7068702f636c69656e74)](https://packagist.org/packages/grok-php/client)[![GitHub Workflow Status](https://github.com/grok-php/client/actions/workflows/run-tests.yml/badge.svg)](https://github.com/grok-php/client/actions/workflows/run-tests.yml/badge.svg)[![License](https://camo.githubusercontent.com/88e1dabf4d223df0950e0985948e231325fefca9fa7fe9e446cf8b1c5e9d9e47/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e)](LICENSE)

---

📖 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
    - [Basic Usage](#basic-usage)
    - [Vision Analysis](#vision-analysis-image-recognition)
    - [Advanced Configuration](#advanced-configuration)
- [Available Grok AI Models](#available-grok-ai-models)
- [Streaming Responses](#streaming-responses)
- [Response format](#response-format)
- [Error Handling](#error-handling)
- [Testing](#testing)
- [Security](#security)
- [Contributing](#contributing)
- [License](#license)

---

**Features**
------------

[](#features)

[![Grok PHP Client Demo](assets/images/demo.gif)](assets/images/demo.gif)

- **Easy Integration** – Seamlessly connects with Grok AI APIs.
- **Modern PHP Features** – Utilizes PHP 8.2+ features like enums and traits.
- **Framework Agnostic** – Works with any PHP project, CLI scripts, or web applications.
- **Streaming Support** – Built-in support for real-time responses.
- **Lightweight &amp; Efficient** – Optimized with PSR-4 autoloading and minimal dependencies.

---

**Installation**
----------------

[](#installation)

Install via Composer:

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

### **Requirements:**

[](#requirements)

- PHP 8.2+
- Composer 2.0+

---

**Quick Start**
---------------

[](#quick-start)

### **Basic Usage**

[](#basic-usage)

```
use GrokPHP\Client\Clients\GrokClient;
use GrokPHP\Client\Config\GrokConfig;
use GrokPHP\Client\Config\ChatOptions;
use GrokPHP\Client\Enums\Model;

// Initialize the client
$config = new GrokConfig('your-api-key');
$client = new GrokClient($config);

// Define messages
$messages = [
    ['role' => 'system', 'content' => 'You are an AI assistant.'],
    ['role' => 'user', 'content' => 'Tell me a joke!']
];

// Call API
$options = new ChatOptions(model: Model::GROK_2, temperature: 0.7, stream: false);
$response = $client->chat($messages, $options);

echo "AI Response: " . $response['choices'][0]['message']['content'];
```

### **Defaults Used:**

[](#defaults-used)

- Model: `grok-2`
- Temperature: `0.7`
- Streaming: `false`

---

### Vision Analysis (Image Recognition)

[](#vision-analysis-image-recognition)

The **Vision API** allows you to send images for analysis using **Grok-2-Vision** models.

```
use GrokPHP\Client\Clients\GrokClient;
use GrokPHP\Client\Config\GrokConfig;

// Initialize the client
$config = new GrokConfig('your-api-key');
$client = new GrokClient($config);

// Use the Vision API to analyze an image
$response = $client->vision()->analyze('https://example.com/image.jpg', 'Describe this image.');

echo "Vision Response: " . $response['choices'][0]['message']['content'];
```

#### Supported Models for Vision

[](#supported-models-for-vision)

Model EnumAPI Model NameDescription`Model::GROK_2_VISION`grok-2-visionBase Vision Model`Model::GROK_2_VISION_LATEST`grok-2-vision-latestLatest Vision Model`Model::GROK_2_VISION_1212`grok-2-vision-1212Default model for image analysis**Note:** If you attempt to use an **unsupported model** for vision, an exception will be thrown.

---

### **Advanced Configuration**

[](#advanced-configuration)

```
use GrokPHP\Client\Clients\GrokClient;
use GrokPHP\Client\Config\GrokConfig;
use GrokPHP\Client\Config\ChatOptions;
use GrokPHP\Client\Enums\Model;

// Load API key from environment
$apiKey = getenv('GROK_API_KEY');

$config = new GrokConfig($apiKey);
$client = new GrokClient($config);

// Define messages
$messages = [
    ['role' => 'system', 'content' => 'You are a helpful assistant.'],
    ['role' => 'user', 'content' => 'How do black holes form?']
];

// Custom API settings
$options = new ChatOptions(
    model: Model::GROK_2_LATEST,
    temperature: 1.2,
    stream: false
);

$response = $client->chat($messages, $options);
echo "AI Says: " . $response['choices'][0]['message']['content'];
```

---

**Available Grok AI Models**
----------------------------

[](#available-grok-ai-models)

Grok AI offers multiple models optimized for different use cases. These models are available in the `Model` enum inside our package: 📄 `src/Enums/Model.php`

Model EnumAPI Model NameDescription`Model::GROK_VISION_BETA`grok-vision-betaExperimental vision-enabled model`Model::GROK_2_VISION`grok-2-visionAdvanced multi-modal vision model`Model::GROK_2_VISION_LATEST`grok-2-vision-latestLatest iteration of Grok vision models`Model::GROK_2_VISION_1212`grok-2-vision-1212Enhanced vision model with performance improvements`Model::GROK_2_1212`grok-2-1212Optimized chat model`Model::GROK_2`grok-2Default general-purpose Grok model`Model::GROK_2_LATEST`grok-2-latestLatest iteration of Grok-2`Model::GROK_BETA`grok-betaExperimental beta model#### **Default model used:** `Model::GROK_2`

[](#default-model-used-modelgrok_2)

---

**Streaming Responses**
-----------------------

[](#streaming-responses)

The Grok API supports streaming responses for real-time interaction. Enable it by setting `stream: true`:

```
$options = new ChatOptions(model: Model::GROK_2, temperature: 0.7, stream: true);
$response = $client->chat($messages, $options);
```

Streaming can be useful for chatbots, real-time applications, and CLI assistants.

---

**Response format**
-------------------

[](#response-format)

The Grok API supports setting a response format, also refered to structured outputs, for the `grok-2-1212` model.

```
$options = new ChatOptions(model: Model::GROK_2_1212, temperature: 0.7, stream: false, responseFormat: ['type' => 'json_object']);
$response = $client->chat($messages, $options);
```

---

**Error Handling**
------------------

[](#error-handling)

This package includes built-in error handling with a dedicated exception class. Common errors and their messages:

Error TypeHTTP CodeMessage`Invalid API Key`400No API key provided. Specify your API key.`Invalid Request`400Client specified an invalid argument.`Invalid Role`422Unknown role variant provided in messages.Example of handling exceptions:

```
use GrokPHP\Client\Exceptions\GrokException;

try {
    $response = $client->chat($messages, $options);
} catch (GrokException $e) {
    echo "Error: " . $e->getMessage();
}
```

---

**Testing**
-----------

[](#testing)

**Run the tests with PHPUnit:**

```
composer test
```

Or run PHPUnit manually:

```
vendor/bin/phpunit
```

---

**Security**
------------

[](#security)

If you discover a security vulnerability, please report it via email: 📩

---

**Contributing**
----------------

[](#contributing)

Want to improve this package? Check out [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines.

---

**License**
-----------

[](#license)

This package is open-source software licensed under the [MIT License](LICENSE).

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance40

Moderate activity, may be stable

Popularity37

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 95.4% 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 ~4 days

Total

5

Last Release

493d ago

PHP version history (3 changes)1.0.0PHP &gt;=8.1

1.1.1PHP &gt;=8.2

v1.2.0PHP ^8.2 || ^8.3 || ^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/fc3f838af3b2510ebffcdd78a70884a6d15677a9b8051246c86670ca51da13a9?d=identicon)[thefeqy](/maintainers/thefeqy)

---

Top Contributors

[![thefeqy](https://avatars.githubusercontent.com/u/44809366?v=4)](https://github.com/thefeqy "thefeqy (62 commits)")[![jeffreyvr](https://avatars.githubusercontent.com/u/9550079?v=4)](https://github.com/jeffreyvr "jeffreyvr (3 commits)")

---

Tags

ai-apiai-chatbotai-clientai-developer-toolsai-integrationai-powered-applicationsai-sdkai-text-generationgenerative-aigrok-aimachine-learningphp-ai-sdkrest-apix-aix-ai-grokx-ai-grok-2REST APInlpApi Wrappermachine learningtext-processingartificial intelligencenatural language processingai apiai clientAI SDKDeep learninggenerative-aiai-integrationai-developer-toolsai chatbotGrok AIPHP AI SDKLarge Language ModelAI Text GenerationAI-powered ApplicationsLanguage ModelAI Research

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[grok-php/laravel

Seamlessly integrate Grok AI into Laravel applications with an elegant, developer-friendly package. Leverage powerful AI models for chat, automation, and NLP while maintaining Laravel's expressive simplicity.

1673.9k](/packages/grok-php-laravel)[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.

46688.8k5](/packages/deepseek-php-deepseek-php-client)[rubix/ml

A high-level machine learning and deep learning library for the PHP language.

2.2k1.5M28](/packages/rubix-ml)[qwen-php/qwen-php-client

robust and community-driven PHP SDK library for seamless integration with the qwen AI API, offering efficient access to advanced AI and data processing capabilities

203.3k1](/packages/qwen-php-qwen-php-client)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3741.3M47](/packages/tencentcloud-tencentcloud-sdk-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.

1621.5k](/packages/softcreatr-php-mistral-ai-sdk)

PHPackages © 2026

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