模型能力
流式传输
所有具备文本输出能力的模型(Chat、Image Understanding 等)都支持流式输出。具备图像输出能力的模型(Image Generation)不支持该功能。
流式输出使用 Server-Sent Events(SSE),使服务器可以在事件流中返回内容增量。
流式响应可以提供实时反馈,并允许文本在生成时立即显示,从而增强用户交互体验。
要启用流式传输,必须在请求中设置 "stream": true。
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.7")
chat.append(
system("You are Grok, a helpful and useful AI built by xAI."),
)
chat.append(
user("Explain how neural networks learn in two sentences.")
)
for response, chunk in chat.stream():
print(chunk.content, end="", flush=True)
print()
print(response.content)你将获得如下事件流:
data: {
"id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,
"model":"grok-4.7",
"choices":[{"index":0,"delta":{"reasoning_content":"The","role":"assistant"}}],
"usage":{"prompt_tokens":41,"completion_tokens":1,"total_tokens":42,
"prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},
"system_fingerprint":"fp_xxxxxxxxxx"
}
data: {
"id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,
"model":"grok-4.7",
"choices":[{"index":0,"delta":{"content":"Ah","role":"assistant"}}],
"usage":{"prompt_tokens":41,"completion_tokens":1,"total_tokens":42,
"prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},
"system_fingerprint":"fp_xxxxxxxxxx"
}
data: {
"id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,
"model":"grok-4.7",
"choices":[{"index":0,"delta":{"content":",","role":"assistant"}}],
"usage":{"prompt_tokens":41,"completion_tokens":2,"total_tokens":43,
"prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},
"system_fingerprint":"fp_xxxxxxxxxx"
}
data: [DONE]建议使用客户端 SDK 解析事件流。
Python/Javascript 中的流式响应示例:
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.最后更新:2026 年 9 月 17 日