模型能力
Chat Completions
输入文本,输出文本。Chat 是 xAI API 上最常用的功能,可用于总结文章、生成创意写作、回答问题、提供客户支持以及辅助编码任务等各种场景。
前置条件
在xAI Console API Keys 页面创建 API Key,并在环境中设置该 API Key:
export XAI_API_KEY="your_api_key"基础 Chat Completions 示例
你也可以使用 streaming response,详情请参阅Streaming Response。
用户向 xAI API endpoint 发送请求。API 处理请求并返回完整响应。
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)响应:
'2 + 2 equals 4.'对话
xAI API 是 stateless 的,不会结合之前的请求历史 context 处理新请求。
不过,你可以在新的 chat generation 请求中提供之前的 prompt 和结果,让模型结合这些 context 处理新请求。
示例消息:
{
"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?"}],
}通过指定 role,可以改变模型接收内容的方式。
systemrole 的内容应以指令性语气定义模型响应用户请求的方式。
userrole 的内容通常用于用户请求或发送给模型的数据。
assistantrole 的内容通常来自模型响应;当它随 prompt 一起发送时,表示对话历史中的模型响应。
图像理解
部分模型允许在 input 中使用图像。模型生成响应时会考虑图像 context。
构造 message body:与纯文本 prompt 的区别
图像理解的 request message 与纯文本 prompt 类似。主要区别是,不再使用以下文本 input:
[
{
"role": "user",
"content": "What is in this image?"
}
]而是将content作为 object list 发送:
[
{
"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。
图像理解示例
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)图像 Input 通用限制
最大图像大小:
20MiB最大图像数量:无限制
支持的图像文件类型:
jpg/jpeg或png。接受任意图像/文本 input 顺序(例如,文本 prompt 可以位于图像 prompt 之前)
图像 Detail Levels
该 "detail"field 控制对提供给模型的图像应用的预处理级别。该字段为 optional,并决定处理图像时使用的分辨率。"detail"的可选值为:
"auto":系统会自动确定使用的图像分辨率。这是默认设置,会根据模型判断在速度和细节之间取得平衡。"low":系统会处理图像的低分辨率版本。此选项速度更快、消耗的 tokens 更少,因此更具成本效益,但可能遗漏精细细节。"high":系统会处理图像的高分辨率版本。此选项速度较慢,token 成本更高,但可以让模型关注图像中更细微的细节。