OpenAI 的 /v1/chat/completions 事实上已经成为行业通用协议。理解它的字段语义,等于拿到了所有厂商的通用说明书。
POST /v1/chat/completions
Authorization: Bearer <KEY>
Content-Type: application/json
{
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "你是一名严谨的技术编辑。"},
{"role": "user", "content": "用三句话解释什么是向量检索。"}
],
"temperature": 0.3,
"max_tokens": 800,
"stream": false
}| 字段 | 作用 | 常见坑 |
|---|---|---|
| model | 模型标识 | 各厂命名规则不同,且会下线旧名;不要写死在业务代码 |
| messages | 对话数组,含 role 与 content | system 只能有一条且通常需在首位;部分厂商把 system 提到顶层 |
| role | system / user / assistant / tool | tool 消息必须与 tool_call_id 对应,否则 400 |
| temperature | 随机性,0~2 | 推理模型常忽略此参数;设为 0 也不保证完全确定 |
| top_p | 核采样 | 与 temperature 同时调会互相干扰,一般只调一个 |
| max_tokens | 输出上限 | 不设会用默认值,长文任务容易被截断 |
| stream | 是否流式 | 开启后返回 SSE,不再是单个 JSON |
| stop | 停止词 | 部分厂商对 stop 的支持不完整 |
| tools | 工具定义数组 | schema 写错不会报错,只会「模型不用工具」 |
| response_format | 输出格式约束 | 要求 json_object 时,prompt 里必须出现 json 字样 |
{
"id": "chatcmpl-xxx",
"object": "chat.completion",
"created": 1763800000,
"model": "deepseek-chat",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "……"},
"finish_reason": "stop"
}
],
"usage": {"prompt_tokens": 42, "completion_tokens": 118, "total_tokens": 160}
}finish_reason 是最容易被忽略但最该处理的一个字段:
| 值 | 含义 | 处置 |
|---|---|---|
| stop | 正常结束 | 直接用 |
| length | 达到 max_tokens 被截断 | 内容不完整,需要续写或提高上限 |
| tool_calls | 模型要求调用工具 | 执行工具并回填结果,继续对话 |
| content_filter | 被内容安全策略拦截 | 提示用户改写,不要重试 |
「兼容」通常只覆盖 chat/completions 的基础字段。以下能力各家实现差异较大,迁移时逐个验证:
json_schema 的严格模式是否支持image_url 还是别的error.message / error.type 结构(很多厂商不遵循)error.message / error.type / error.code,很多国产厂商返回的是完全不同的结构,直接取 resp[error][message] 会二次崩溃。def chat(role_cfg, messages, **kw):
payload = {
"model": role_cfg["model"],
"messages": messages,
"max_tokens": kw.get("max_tokens", 1200),
"temperature": kw.get("temperature", 0.3),
}
if kw.get("tools"):
payload["tools"] = kw["tools"]
payload["tool_choice"] = "auto"
r = session.post(role_cfg["base_url"] + "/chat/completions",
json=payload, timeout=(5, role_cfg["timeout"]))
if r.status_code != 200:
raise ApiError(normalize_error(r))
d = r.json()
ch = d["choices"][0]
return {
"text": ch["message"].get("content") or "",
"tool_calls": ch["message"].get("tool_calls", []),
"finish": ch.get("finish_reason"),
"usage": d.get("usage", {}),
}这 20 行就是「不锁定」的核心:业务层只认 text / tool_calls / finish / usage 四个键,换供应商时改配置即可。