定制 alexpago/grok-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

alexpago/grok-php

Composer 安装命令:

composer require 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).

README 文档

README

GrokChat is a PHP library for interacting with the Grok API.
It provides a simple, object-oriented interface for sending chat messages, managing multi-turn conversations, handling responses, and streaming results.

✨ 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: '<external URL or base64>', 
    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

Install via Composer:

composer require alexpago/grok-php

🚀 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

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

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

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

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 & reliable Higher = creative & diverse (Regular ChatGPT default ≈ 1.3)

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

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

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

  • PHP 8.1+
  • Composer

📜 License

MIT License.

alexpago/grok-php 适用场景与选型建议

alexpago/grok-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 83 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 08 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「chat」 「ai」 「grok」 「ChatGpt」 「Grok AI」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 alexpago/grok-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 alexpago/grok-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 alexpago/grok-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 83
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 25
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-29