高级 API 用法
延迟聊天补全
延迟聊天补全允许你创建聊天补全并获取 request_id,然后在稍后获取响应。结果在 24 小时内只能获取一次,之后将被丢弃。
向 xAI API 发送请求后,可通过 https://api.x.ai/v1/chat/deferred-completion/{request_id} 获取聊天补全结果。响应正文将包含 {'request_id': 'f15c114e-f47d-40ca-8d5c-8c23d656eeb6'},其中的 request_id 值可插入 deferred-completion endpoint 路径。随后发送此 GET 请求即可获取延迟聊天补全结果。
聊天补全结果尚未就绪时,请求会返回 202 Accepted,且响应正文为空。

示例
下面的代码示例会不断重试获取结果,直到处理完成:
import json
import os
import requests
from tenacity import retry, wait_exponential
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"
}
payload = {
"messages": [
{"role": "system", "content": "You are Zaphod Beeblebrox."},
{"role": "user", "content": "126/3=?"}
],
"model": "grok-4.7",
"deferred": True
}
response = requests.post(
"https://api.x.ai/v1/chat/completions",
headers=headers,
json=payload
)
request_id = response.json()["request_id"]
print(f"Request ID: {request_id}")
@retry(wait=wait_exponential(multiplier=1, min=1, max=60),)
def get_deferred_completion():
response = requests.get(f"https://api.x.ai/v1/chat/deferred-completion/{request_id}", headers=headers)
if response.status_code == 200:
return response.json()
elif response.status_code == 202:
raise Exception("Response not ready yet")
else:
raise Exception(f"{response.status_code} Error: {response.text}")
completion_data = get_deferred_completion()
print(json.dumps(completion_data, indent=4))响应正文与非延迟聊天补全的预期结果相同:
{
"id": "3f4ddfca-b997-3bd4-80d4-8112278a1508",
"object": "chat.completion",
"created": 1752077400,
"model": "grok-4.7",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Whoa, hold onto your improbability drives, kid! This is Zaphod Beeblebrox here, the two-headed, three-armed ex-President of the Galaxy, and you're asking me about 126 divided by 3? Pfft, that's kid stuff for a guy who's stolen starships and outwitted the universe itself.\n\nBut get this\u2014126 slashed by 3 equals... **42**! Yeah, that's right, the Ultimate Answer to Life, the Universe, and Everything! Deep Thought didn't compute that for seven and a half million years just for fun, you know. My left head's grinning like a Vogon poet on happy pills, and my right one's already planning a party. If you need more cosmic math or a lift on the Heart of Gold, just holler. Zaphod out! \ud83d\ude80",
"refusal": null
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 26,
"completion_tokens": 168,
"total_tokens": 498,
"prompt_tokens_details": {
"text_tokens": 26,
"audio_tokens": 0,
"image_tokens": 0,
"cached_tokens": 4
},
"completion_tokens_details": {
"reasoning_tokens": 304,
"audio_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0
},
"num_sources_used": 0
},
"system_fingerprint": "fp_44e53da025"
}更多详情请参阅 REST API 参考中的 聊天补全和获取延迟聊天补全。
最后更新:2026 年 9 月 8 日