Responses API 支持有状态交互 — 之前的输入提示、推理内容和模型响应会被保存在 xAI 服务器上。 你可以通过附加新的提示消息来继续交互,而无需重新发送完整对话。 此行为默认开启。响应将存储 30 天。
前提条件
在 xAI Console API Keys 页面创建 API Key,并设置环境变量:
export XAI_API_KEY="your_api_key"创建新的模型响应
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,
)
chat = client.chat.create(model="grok-4.5")
chat.append(system("You are Grok, an AI agent built to answer helpful questions."))
chat.append(user("How big is the universe?"))
response = chat.sample()
print(response)
print(response.id) # 用于后续继续对话的响应 ID禁用服务器端存储
如果你不想在服务器上存储之前的请求/响应,可以在请求中设置 store: false:
Python
chat = client.chat.create(model="grok-4.5", store_messages=False)
chat.append(system("You are Grok, an AI agent built to answer helpful questions."))
chat.append(user("How big is the universe?"))
response = chat.sample()继续之前的对话
由于 Responses API 是有状态的,你可以使用之前响应的 ID 来继续对话, 而无需重新发送完整的历史记录:
Python (OpenAI)
# 使用之前的响应 ID 继续对话
response2 = client.responses.create(
model="grok-4.5",
input="What about the observable universe?",
previous_response_id=response.id,
)添加加密推理内容
对于推理模型(如 grok-4.5),你可以通过传递 include: ["reasoning.encrypted_content"]来获取加密的推理内容。这允许你在后续请求中传回加密内容,为模型提供更多上下文。
SDK 选择
对于 Python,我们还提供 xAI SDK, 它涵盖所有功能并使用 gRPC 以获得最佳性能。可以混合使用两种 SDK。 xAI SDK 允许你与所有产品交互(如集合、语音 API、API Key 管理等), 而 Responses API 更适合聊天机器人和 RESTful API 使用。