一条完整的 Chat Completions JSON 需要哪些字段?
查看完整题解
参考回答
直接回答
请求体最少要有 model 与 messages。后者是按时间排列的消息列表,每条有角色和内容。想控制长度、思考模式或流式,再加 max_tokens、thinking、stream 等可选字段。
讲清原理
请求短时先只写必需项。只有业务明确需要才加参数,避免旧教程里的默认值无意改变当前模型的行为。OpenAI SDK 中自定义的 DeepSeek 字段可放进 extra_body,线上收到的是 JSON 顶层字段。
例子与易错点
下面在内存中捕获一次真实 SDK 的 JSON 请求,确认 thinking 平铺在请求体里。
import json
import httpx
from openai import OpenAI
events = []
def fake_service(request):
body = json.loads(request.content)
events.append((request, body))
return httpx.Response(200, json={
"id": "local-chat", "object": "chat.completion", "created": 0,
"model": body["model"], "choices": [{
"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "收到"},
}],
})
with OpenAI(api_key="local-test-key", base_url="https://api.deepseek.com",
http_client=httpx.Client(transport=httpx.MockTransport(fake_service)),
max_retries=0) as client:
client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "system", "content": "只输出一句话"},
{"role": "user", "content": "请回答收到"},
],
max_tokens=64,
extra_body={"thinking": {"type": "disabled"}},
)
_, body = events[0]
assert body["thinking"] == {"type": "disabled"} and "extra_body" not in body
assert body["max_tokens"] == 64 and body["messages"][0]["role"] == "system"
print("model, messages, max_tokens and top-level thinking were sent")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。