Skip to content

xAI Grok API完全指南

Grok以其幽默风格和实时信息获取能力著称,是xAI推出的强大AI模型

概述

xAI是Elon Musk创立的AI公司,其Grok模型以幽默风格、实时信息获取能力和强大的推理能力著称。本教程将带你全面掌握Grok API的使用方法。

为什么选择Grok?

优势说明
实时信息通过X(Twitter)获取实时信息
幽默风格独特的幽默回答风格
强大推理复杂推理任务表现出色
代码能力代码生成和理解能力强

Grok模型概览

Grok模型家族:

grok-2系列(最新)
├── grok-2-1212         # 最新版本,能力最强
├── grok-2-vision-1212  # 多模态版本
└── grok-beta           # 测试版本

grok-1系列(经典)
└── grok-1              # 首代模型

基本概念

API Key

php
<?php
// 在xAI官网获取API Key
// https://console.x.ai/

// API Key格式
// xai-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

$apiKey = getenv('XAI_API_KEY');

兼容性

Grok API兼容OpenAI API格式,可以轻松迁移:

php
<?php
// Grok API使用与OpenAI相同的接口格式
// 只需更改base_url和API Key即可

环境准备

创建xAI客户端

php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class XAIClient
{
    private $client;
    private $apiKey;
    private $baseUrl = 'https://api.x.ai/v1';

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = new Client([
            'base_uri' => $this->baseUrl,
            'timeout' => 60,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
        ]);
    }

    public function chat(
        array $messages,
        string $model = 'grok-2-1212',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        if (isset($options['temperature'])) {
            $params['temperature'] = $options['temperature'];
        }

        if (isset($options['max_tokens'])) {
            $params['max_tokens'] = $options['max_tokens'];
        }

        if (isset($options['top_p'])) {
            $params['top_p'] = $options['top_p'];
        }

        try {
            $response = $this->client->post('/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('xAI API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$apiKey = getenv('XAI_API_KEY');
$client = new XAIClient($apiKey);

$result = $client->chat([
    ['role' => 'user', 'content' => '请用一句话介绍PHP语言']
]);

echo $result['choices'][0]['message']['content'];

运行结果:

PHP是一种开源的服务器端脚本语言,专为Web开发而生,能让你用最少的代码做最多的事——当然,也可能用最少的代码制造最多的bug,这取决于程序员是谁。

高级参数配置

完整参数示例

php
<?php
class XAIClient
{
    // ... 前面的代码 ...

    public function chatAdvanced(
        array $messages,
        string $model = 'grok-2-1212',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        $optionalParams = ['temperature', 'max_tokens', 'top_p', 'top_k', 'stop', 'frequency_penalty', 'presence_penalty'];

        foreach ($optionalParams as $param) {
            if (isset($options[$param])) {
                $params[$param] = $options[$param];
            }
        }

        try {
            $response = $this->client->post('/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('xAI API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$result = $client->chatAdvanced(
    [['role' => 'user', 'content' => '写一首关于程序员的诗']],
    'grok-2-1212',
    [
        'temperature' => 0.8,
        'max_tokens' => 500,
    ]
);

echo $result['choices'][0]['message']['content'];

参数详解

参数范围默认值说明
temperature0-21控制随机性
max_tokens1-模型上限无限制最大输出Token
top_p0-11核采样参数
top_k1-100-只考虑前K个候选词
stop字符串或数组-停止序列
frequency_penalty0-20频率惩罚
presence_penalty0-20存在惩罚

流式响应处理

php
<?php
class XAIClient
{
    // ... 前面的代码 ...

    public function chatStream(
        array $messages,
        string $model = 'grok-2-1212'
    ): Generator {
        $response = $this->client->post('/chat/completions', [
            'json' => [
                'model' => $model,
                'messages' => $messages,
                'stream' => true,
            ],
            'stream' => true,
        ]);

        $body = $response->getBody();
        $buffer = '';

        while (!$body->eof()) {
            $chunk = $body->read(1024);
            $buffer .= $chunk;

            while (($pos = strpos($buffer, "\n")) !== false) {
                $line = substr($buffer, 0, $pos);
                $buffer = substr($buffer, $pos + 1);

                $line = trim($line);
                if (empty($line) || $line === 'data: [DONE]') {
                    continue;
                }

                if (strpos($line, 'data: ') === 0) {
                    $json = substr($line, 6);
                    $data = json_decode($json, true);

                    if (isset($data['choices'][0]['delta']['content'])) {
                        yield $data['choices'][0]['delta']['content'];
                    }
                }
            }
        }
    }
}

// 使用示例
echo "Grok回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
    echo $chunk;
    flush();
}

多轮对话实现

php
<?php
class GrokChatSession
{
    private XAIClient $client;
    private array $messages = [];
    private string $model;

    public function __construct(XAIClient $client, string $model = 'grok-2-1212')
    {
        $this->client = $client;
        $this->model = $model;
    }

    public function setSystemPrompt(string $prompt): void
    {
        $this->messages = [
            ['role' => 'system', 'content' => $prompt]
        ];
    }

    public function chat(string $userMessage): string
    {
        $this->messages[] = ['role' => 'user', 'content' => $userMessage];

        $response = $this->client->chat($this->messages, $this->model);
        $assistantMessage = $response['choices'][0]['message']['content'];

        $this->messages[] = ['role' => 'assistant', 'content' => $assistantMessage];

        return $assistantMessage;
    }

    public function getHistory(): array
    {
        return $this->messages;
    }

    public function clearHistory(): void
    {
        $systemMessage = $this->messages[0] ?? null;
        $this->messages = $systemMessage ? [$systemMessage] : [];
    }
}

// 使用示例
$session = new GrokChatSession($client);
$session->setSystemPrompt('你是一个幽默的AI助手,用风趣的方式回答问题。');

echo "用户:PHP有什么优点?\n";
echo "Grok:" . $session->chat('PHP有什么优点?') . "\n";

常见错误与踩坑点

错误1:API Key格式错误

php
<?php
// ❌ 错误做法:使用错误的API Key格式
$apiKey = 'sk-xxxxx'; // 这是OpenAI格式

// ✅ 正确做法:使用xAI格式的API Key
$apiKey = 'xai-xxxxx'; // xAI格式

错误2:忽略模型名称

php
<?php
// ❌ 错误做法:使用不存在的模型
$result = $client->chat($messages, 'gpt-4');

// ✅ 正确做法:使用正确的Grok模型
$result = $client->chat($messages, 'grok-2-1212');

错误3:忽略速率限制

php
<?php
// ❌ 错误做法:快速连续请求
foreach ($prompts as $prompt) {
    $result = $client->chat([['role' => 'user', 'content' => $prompt]]);
}

// ✅ 正确做法:添加请求间隔
foreach ($prompts as $prompt) {
    $result = $client->chat([['role' => 'user', 'content' => $prompt]]);
    usleep(500000); // 500ms间隔
}

常见应用场景

场景1:实时信息查询

php
<?php
class RealTimeInfoAssistant
{
    private XAIClient $client;

    public function __construct(XAIClient $client)
    {
        $this->client = $client;
    }

    public function getLatestNews(string $topic): string
    {
        $result = $this->client->chat([
            ['role' => 'user', 'content' => "请告诉我关于{$topic}的最新动态"]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function getCurrentEvents(): string
    {
        $result = $this->client->chat([
            ['role' => 'user', 'content' => '今天有什么重要新闻?']
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景2:幽默内容生成

php
<?php
class HumorContentGenerator
{
    private XAIClient $client;

    public function generateJoke(string $topic): string
    {
        $result = $this->client->chat([
            ['role' => 'user', 'content' => "请讲一个关于{$topic}的笑话"]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function generateFunnyStory(string $theme): string
    {
        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一个幽默的故事创作者,用风趣幽默的方式讲述故事。'
            ],
            [
                'role' => 'user',
                'content' => "请创作一个关于{$theme}的幽默短故事"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景3:代码助手

php
<?php
class GrokCodeAssistant
{
    private XAIClient $client;

    public function generateCode(string $description, string $language = 'PHP'): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请生成{$language}代码:{$description}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function explainCode(string $code): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请解释以下代码:\n```\n{$code}\n```"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function debugCode(string $code, string $error): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "以下代码出错,请帮我修复:\n代码:\n```\n{$code}\n```\n错误:{$error}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景4:智能问答

php
<?php
class GrokQA
{
    private XAIClient $client;

    public function answer(string $question, bool $humorous = false): string
    {
        $systemPrompt = $humorous
            ? '你是一个幽默的AI助手,用风趣的方式回答问题。'
            : '你是一个专业的AI助手,用准确的方式回答问题。';

        $result = $this->client->chat([
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $question]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function compareAnswers(string $question): array
    {
        $normalAnswer = $this->answer($question, false);
        $humorousAnswer = $this->answer($question, true);

        return [
            'normal' => $normalAnswer,
            'humorous' => $humorousAnswer,
        ];
    }
}

场景5:内容创作

php
<?php
class GrokContentCreator
{
    private XAIClient $client;

    public function writeArticle(string $topic, string $style = '幽默'): string
    {
        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => "你是一个{$style}风格的内容创作者。"
            ],
            [
                'role' => 'user',
                'content' => "请写一篇关于{$topic}的文章"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function generateHeadlines(string $topic, int $count = 5): array
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请为{$topic}生成{$count}个吸引人的标题,以JSON数组格式返回"
            ]
        ]);

        return json_decode($result['choices'][0]['message']['content'], true);
    }
}

企业级进阶应用场景

场景1:构建社交媒体监控助手

php
<?php
class SocialMediaMonitor
{
    private XAIClient $client;

    public function analyzeTrend(string $topic): array
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请分析{$topic}在社交媒体上的趋势,包括:1. 热度变化 2. 主要观点 3. 情感倾向"
            ]
        ]);

        return [
            'analysis' => $result['choices'][0]['message']['content'],
            'timestamp' => date('Y-m-d H:i:s'),
        ];
    }

    public function generateResponse(string $post, string $tone = 'friendly'): string
    {
        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => "你是一个社交媒体运营专家,用{$tone}的语气回复。"
            ],
            [
                'role' => 'user',
                'content' => "请为以下帖子生成一个回复:\n{$post}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景2:构建智能客服系统

php
<?php
class GrokCustomerService
{
    private XAIClient $client;
    private array $knowledgeBase = [];

    public function addKnowledge(string $category, string $content): void
    {
        $this->knowledgeBase[$category] = $content;
    }

    public function handleQuery(string $query): string
    {
        $context = '';
        foreach ($this->knowledgeBase as $category => $content) {
            $context .= "【{$category}】\n{$content}\n\n";
        }

        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一个友好的客服助手。请根据知识库回答问题,如果不知道答案,请诚实说明。'
            ],
            [
                'role' => 'user',
                'content' => "知识库:\n{$context}\n\n客户问题:{$query}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

常见问题答疑(FAQ)

Q1:Grok和其他模型有什么区别?

回答

特点GrokGPTClaude
实时信息✅ 通过X获取❌ 知识截止❌ 知识截止
幽默风格✅ 默认幽默❌ 需要提示❌ 需要提示
长上下文❌ 较短✅ 128K✅ 200K
安全性中等

Q2:如何获取实时信息?

回答

php
<?php
// Grok可以访问X平台的实时信息
$result = $client->chat([
    ['role' => 'user', 'content' => '今天有什么热门话题?']
]);

// 结果会包含最新的信息
echo $result['choices'][0]['message']['content'];

Q3:如何控制幽默程度?

回答

php
<?php
// 通过系统提示控制
$result = $client->chat([
    ['role' => 'system', 'content' => '请用严肃专业的方式回答问题。'],
    ['role' => 'user', 'content' => '什么是PHP?']
]);

// 或者
$result = $client->chat([
    ['role' => 'system', 'content' => '请用幽默风趣的方式回答问题。'],
    ['role' => 'user', 'content' => '什么是PHP?']
]);

Q4:如何处理API错误?

回答

php
<?php
function handleXAIError(Exception $e): string
{
    $message = $e->getMessage();

    if (strpos($message, 'invalid_api_key') !== false) {
        return 'API Key无效';
    }
    if (strpos($message, 'rate_limit') !== false) {
        return '请求过于频繁';
    }
    if (strpos($message, 'insufficient_quota') !== false) {
        return '配额不足';
    }

    return '服务暂时不可用';
}

Q5:如何选择合适的模型?

回答

场景推荐模型原因
实时信息grok-2-1212可获取实时信息
幽默内容grok-2-1212默认幽默风格
代码生成grok-2-1212代码能力强
图像理解grok-2-vision-1212多模态支持

Q6:如何优化Token使用?

回答

php
<?php
// 1. 设置max_tokens限制
$result = $client->chat($messages, 'grok-2-1212', ['max_tokens' => 500]);

// 2. 使用简洁的提示
$prompt = "用50字解释:{$topic}";

// 3. 实现缓存
class CachedXAIClient extends XAIClient
{
    private array $cache = [];

    public function chatWithCache(array $messages, string $model = 'grok-2-1212'): array
    {
        $key = md5($model . serialize($messages));
        if (isset($this->cache[$key])) {
            return $this->cache[$key];
        }

        $result = $this->chat($messages, $model);
        $this->cache[$key] = $result;
        return $result;
    }
}

实战练习

基础练习

练习1:编写一个简单的Grok聊天程序。

参考代码

php
<?php
$apiKey = getenv('XAI_API_KEY');
$client = new XAIClient($apiKey);

echo "Grok聊天助手 (输入 'quit' 退出)\n";

while (true) {
    echo "\n你: ";
    $input = trim(fgets(STDIN));

    if ($input === 'quit') {
        break;
    }

    $result = $client->chat([['role' => 'user', 'content' => $input]]);
    echo "Grok: " . $result['choices'][0]['message']['content'] . "\n";
}

进阶练习

练习2:实现一个实时新闻摘要工具。

参考代码

php
<?php
class NewsSummarizer
{
    private XAIClient $client;

    public function getDailySummary(): string
    {
        $result = $this->client->chat([
            ['role' => 'user', 'content' => '请总结今天的重要新闻,按类别分类列出。']
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function getTopicNews(string $topic): string
    {
        $result = $this->client->chat([
            ['role' => 'user', 'content' => "请总结关于{$topic}的最新动态。"]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

挑战练习

练习3:构建一个社交媒体内容生成器。

参考代码

php
<?php
class SocialMediaGenerator
{
    private XAIClient $client;

    public function generatePost(string $topic, string $platform = 'twitter'): string
    {
        $limits = [
            'twitter' => 280,
            'weibo' => 140,
            'linkedin' => 700,
        ];

        $limit = $limits[$platform] ?? 280;

        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => "你是一个社交媒体内容专家,为{$platform}创作内容。"
            ],
            [
                'role' => 'user',
                'content' => "请为{$topic}创作一条{$platform}帖子,不超过{$limit}字符。"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function generateThread(string $topic, int $count = 5): array
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请为{$topic}创作一个{$count}条的推文串,以JSON数组格式返回。"
            ]
        ]);

        return json_decode($result['choices'][0]['message']['content'], true);
    }
}

知识点总结

核心要点

  1. API兼容:兼容OpenAI API格式,易于迁移
  2. 实时信息:通过X平台获取实时信息
  3. 幽默风格:独特的幽默回答风格
  4. 强大推理:复杂推理任务表现出色
  5. 代码能力:代码生成和理解能力强

易错点回顾

易错点正确做法
API Key格式错误使用xai-开头的API Key
模型名称错误使用grok-2-1212等正确模型名
忽略速率限制添加请求间隔
不处理错误完善的错误处理机制

拓展参考资料

官方文档

进阶学习路径

  1. 本知识点 → xAI Grok API基础使用
  2. 下一步Mistral AI API
  3. 进阶错误处理与重试
  4. 高级并发与限流

💡 记住:Grok的独特优势在于实时信息获取和幽默风格,善用这些特性可以构建更有趣的AI应用。