response_format 能保证 JSON 字段也正确吗?
查看完整题解
参考回答
直接回答
Chat Completions 可设置 response_format={"type":"json_object"},提示里也要明确要求 JSON。拿到内容后要解析,并验证必填字段、类型和业务规则。
讲清原理
可解析是第一关。空白响应和 finish_reason=length 要先拦住。字段既可能缺失,也可能填上从输入无法推出的内容,需要按业务校验。
例子与易错点
下面用本地校验器模拟成功、缺字段、空白和截断四种结果,核对哪些会被接收。
import json
def decode(content, finish_reason):
if finish_reason != "stop" or not content.strip():
return None
try:
value = json.loads(content)
except json.JSONDecodeError:
return None
if not isinstance(value, dict) or type(value.get("count")) is not int:
return None
return value if value["count"] >= 0 else None
assert decode('{"count":2}', "stop") == {"count": 2}
assert decode('{"other":2}', "stop") is None
assert decode(" ", "stop") is None
assert decode('{"count":', "length") is None
print("accepted only valid data with the required field")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。