400 的特点是可复现:同样的请求体,每次都会失败。所以它不难修,难在定位——尤其是请求体由多层代码拼装、中间还有一层模板或网关改写的时候。
排查 400 的第一件事,是把请求体砍到最小。下面这个结构在绝大多数 OpenAI 兼容接口上都能跑通;如果它失败,问题在认证或端点,不在参数。
{
"model": "deepseek-chat",
"messages": [
{"role": "user", "content": "用一句话说明什么是向量检索"}
],
"max_tokens": 128,
"temperature": 0.3
}| # | 错误写法 | 为什么错 | 改法 |
|---|---|---|---|
| 1 | "content": "" 或 null | 空 content 在部分厂商会被判非法 | 至少给一个空格,或干脆不传该条 |
| 2 | role: "human" / "bot" | 那是别家协议的写法 | system / user / assistant / tool |
| 3 | 连续两条 system | 多数实现只接受首条 system | 合并成一条 |
| 4 | 连续两条 user 未合并 | 部分厂商要求严格交替 | 合并为一条,或插入 assistant 占位 |
| 5 | tool 消息缺 tool_call_id | 无法与调用配对 | 把上一步的 id 原样带回 |
| 6 | 图片 base64 带 data:image/png;base64, 前缀 | 有的接口要纯 base64,有的要完整 data URL | 按文档试两种,别混 |
| 7 | max_tokens 超过模型输出上限 | 每个模型上限不同,写死 8192 必炸 | 按模型配置表取值 |
| 8 | temperature > 2 或为负 | 取值范围 [0,2] | 夹在合法区间;推理模型直接不传 |
| 9 | tools[].function.parameters 不是合法 schema | 少 type、properties 写成数组 | 用 jsonschema 校验一遍再发 |
| 10 | response_format 用了 json_schema 但模型不支持 | 各厂商支持度不同 | 退回 json_object + 提示词约束 + 本地校验 |
| 11 | 流式 + n>1 同时用 | 多数实现不支持 | 拆成两次请求 |
| 12 | 数字被序列化成字符串 | 强类型校验的厂商会拒 | 统一用 json.dumps 而不是手拼字符串 |
param 字段会直接点名出错的字段路径,例如 messages[3].content。把这个路径和你的拼装代码对上,通常 30 秒能定位。没有 param 时,用二分法砍请求体:先砍 tools,再砍历史,最后只剩单条消息。线上 400 的根因很少是「参数写错」,而是「拼装逻辑在某个分支产生了非法结构」:历史为空时插入了空 content、检索没命中时塞了 None、多轮里出现了两条连续 system。与其在出口处兜底,不如在拼装函数里断言。
def build_messages(system, history, question, max_turns=8):
msgs = []
if system and system.strip():
msgs.append({"role": "system", "content": system.strip()})
for m in history[-max_turns:]:
role, content = m.get("role"), (m.get("content") or "").strip()
if role not in ("user", "assistant") or not content:
continue # 脏历史直接丢弃,不要送给模型
if msgs and msgs[-1]["role"] == role:
msgs[-1]["content"] += "\n" + content # 合并同角色,避免连续 user
else:
msgs.append({"role": role, "content": content})
q = (question or "").strip()
if not q:
raise ValueError("empty question") # 早失败,别把 400 留给用户
msgs.append({"role": "user", "content": q})
return msgs这段代码做了三件事:过滤空内容、合并同角色、拒绝空问题。三行防御能消掉大部分「偶发 400」。
tools 的 schema 做一次 jsonschema.Draft7Validator.check_schema。model、max_tokens、temperature 从代码里挪到配置表,换模型时不用改代码。param,否则只能猜。