跳转到内容

模型能力

聊天补全

WARNING

Chat Completions 作为遗留端点提供。新功能将首先在 Responses API 中推出。如需迁移,请查看 迁移到 Responses API 指南。

文本输入,文本输出。聊天是 xAI API 上最受欢迎的功能,可用于从总结文章、生成创意写作、回答问题、提供客户支持到协助编码任务等各种场景。

先决条件

xAI Console API 密钥页面 上创建 API 密钥。在您的环境中设置 API 密钥:

bash
export XAI_API_KEY="your_api_key"

基本的聊天补全示例

您也可以流式传输响应,这将在 流式响应 中介绍。

用户向 xAI API 端点发送请求。API 处理该请求并返回完整响应。

python
import os

from xai_sdk import Client
from xai_sdk.chat import user, system

client = Client(
    api_key=os.getenv("XAI_API_KEY"),
    timeout=3600, # Override default timeout with longer timeout for reasoning models
)

chat = client.chat.create(model="grok-4.5")
chat.append(system("You are a PhD-level mathematician."))
chat.append(user("What is 2 + 2?"))

response = chat.sample()
print(response.content)
python
import os
import httpx
from openai import OpenAI

client = OpenAI(
    api_key="<YOUR_XAI_API_KEY_HERE>",
    base_url="https://api.x.ai/v1",
    timeout=httpx.Timeout(3600.0), # Override default timeout with longer timeout for reasoning models
)

completion = client.chat.completions.create(
    model="grok-4.5",
    messages=[
        {"role": "system", "content": "You are a PhD-level mathematician."},
        {"role": "user", "content": "What is 2 + 2?"},
    ],
)

print(completion.choices[0].message)
javascript
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: "<api key>",
    baseURL: "https://api.x.ai/v1",
    timeout: 360000, // Override default timeout with longer timeout for reasoning models
});

const completion = await client.chat.completions.create({
    model: "grok-4.5",
    messages: [
        {
            role: "system",
            content: "You are Grok, a helpful and maximally truthful AI built by xAI."
        },
        {
            role: "user",
            content: "Explain how neural networks learn in two sentences."
        },
    ],
});

console.log(completion.choices[0].message);
javascript
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';

const result = await generateText({
  model: xai('grok-4.5'),
  system:
    "You are Grok, a helpful and maximally truthful AI built by xAI.",
  prompt: 'Explain how neural networks learn in two sentences.',
});

console.log(result.text);
bash
curl https://api.x.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-m 3600 \
-d '{
    "messages": [
        {
            "role": "system",
            "content": "You are Grok, a helpful and maximally truthful AI built by xAI."
        },
        {
            "role": "user",
            "content": "Explain how neural networks learn in two sentences."
        }
    ],
    "model": "grok-4.5",
    "stream": false
}'

响应:

python
'2 + 2 equals 4.'
python
ChatCompletionMessage(
  content='2 + 2 equals 4.',
  refusal=None,
  role='assistant',
  audio=None,
  function_call=None,
  tool_calls=None
)
javascript
{
  role: 'assistant',
  content: `Neural networks learn by adjusting connection weights to minimize prediction error. Through backpropagation, they propagate gradients backward through layers so each weight updates in the direction that improves accuracy on training data.`
  refusal: null
}
javascript
// result object structure
{
  text: "Neural networks learn by adjusting connection weights...",
  finishReason: "stop",
  usage: {
    inputTokens: 716,
    outputTokens: 126,
    totalTokens: 1009,
    reasoningTokens: 167
  },
  totalUsage: { /* same as usage */ }
}
bash
{
  "id": "0daf962f-a275-4a3c-839a-047854645532",
  "object": "chat.completion",
  "created": 1739301120,
  "model": "grok-4.5",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Neural networks learn by adjusting connection weights to minimize prediction error. Through backpropagation, they propagate gradients backward through layers so each weight updates in the direction that improves accuracy on training data.",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 41,
    "completion_tokens": 104,
    "total_tokens": 145,
    "prompt_tokens_details": {
      "text_tokens": 41,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 0
    }
  },
  "system_fingerprint": "fp_84ff176447"
}

对话

xAI API 是无状态的,不会根据您之前的请求历史记录来处理新请求。

但是,您可以将之前的聊天生成提示和结果提供给新的聊天生成请求,以便模型在考虑上下文的情况下处理您的新请求。

示例消息:

json
{
  "role": "system",
  "content": [{ "type": "text", "text": "You are a helpful and funny assistant."}]
}
{
  "role": "user",
  "content": [{ "type": "text", "text": "Why don't eggs tell jokes?" }]
},
{
  "role": "assistant",
  "content": [{ "type": "text", "text": "They'd crack up!" }]
},
{
  "role": "user",
  "content": [{"type": "text", "text": "Can you explain the joke?"}],
}

通过指定角色,您可以改变模型处理内容的方式。 system 角色内容应以指导性语调定义模型应该如何响应用户请求。 user 角色内容通常用于用户请求或发送给模型的数据。 assistant 角色内容通常是模型的响应,或者在提示中发送时,表示作为对话历史一部分的模型响应。

图像理解

某些模型允许在输入中包含图像。模型在生成响应时会考虑图像上下文。

构建消息体 - 与纯文本提示的区别

图像理解请求消息类似于纯文本提示。主要区别在于文本输入:

json
[
{
    "role": "user",
    "content": "What is in this image?"
}
]

我们将 content 作为对象列表发送:

json
[
{
    "role": "user",
    "content": [
{
    "type": "image_url",
    "image_url": {
    "url": "data:image/jpeg;base64,<base64_image_string>",
    "detail": "high"
}
},
{
    "type": "text",
    "text": "What is in this image?"
}
    ]
}
]

image_url.url 也可以是互联网上的图像 URL。

图像理解示例

python
import os

from xai_sdk import Client
from xai_sdk.chat import user, image

client = Client(api_key=os.getenv('XAI_API_KEY'))

image_url = "https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png"

chat = client.chat.create(model="grok-4")
chat.append(
    user(
        "What's in this image?",
        image(image_url=image_url, detail="high"),
    )
)

response = chat.sample()
print(response.content)
python
import os
from openai import OpenAI

XAI_API_KEY = os.getenv("XAI_API_KEY")
image_url = (
"https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png"
)

client = OpenAI(
    api_key=XAI_API_KEY,
    base_url="https://api.x.ai/v1",
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": image_url,
                    "detail": "high",
                },
            },
            {
                "type": "text",
                "text": "What's in this image?",
            },
        ],
    },
]

completion = client.chat.completions.create(
    model="grok-4",
    messages=messages,
)

print(completion.choices[0].message.content)
javascript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.XAI_API_KEY,
baseURL: "https://api.x.ai/v1",
});

const image_url =
"https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png";

const completion = await openai.chat.completions.create({
    model: "grok-4",
    messages: [
        {
            role: "user",
            content: [
                {
                    type: "image_url",
                    image_url: {
                        url: image_url,
                        detail: "high",
                    },
                },
                {
                    type: "text",
                    text: "What's in this image?",
                },
            ],
        },
    ],
});

console.log(completion.choices[0].message.content);
javascript
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';

const result = await generateText({
model: xai('grok-4'),
messages: [
        {
            role: 'user',
            content: [
                {
                    type: 'image',
                    image: new URL(
                        'https://science.nasa.gov/wp-content/uploads/2023/09/web-first-images-release.png',
                    ),
                },
                {
                    type: 'text',
                    text: "What's in this image?",
                },
            ],
        },
    ],
});

console.log(result.text);

图像输入一般限制

  • 最大图像大小:20MiB
  • 最大图像数量:无限制
  • 支持的图像文件类型:jpg/jpegpng
  • 任何图像/文本输入顺序均可接受(例如文本提示可以在图像提示之前)

图像细节级别

"detail" 字段控制应用于将提供给模型的图像的预处理级别。它是可选的,并决定图像被处理的分辨率。"detail" 的可能值为:

  • "auto":系统将自动决定要使用的图像分辨率。这是默认设置,根据模型的评估在速度和细节之间取得平衡。
  • "low":系统将处理图像的低分辨率版本。此选项速度更快,消耗的 token 更少,更具成本效益,但可能会错过更精细的细节。
  • "high":系统将处理图像的高分辨率版本。此选项在 token 使用方面较慢且成本更高,但它允许模型关注图像中更细微的细节。

本文档为 docs.x.ai 全站中文翻译,由 AI 自动翻译生成。代码示例请以原文为准。