微信扫码
添加专属顾问
我要投稿
今天OpenAI的API新增加了一个功能,支持结构化输出,通俗的来说API的输出支持稳定的JSON模式。
为什么强调稳定呢?其实在去年的DevDay,OpenAI就介绍了JSON models,尽管它提高了模型输出是JSON的可靠性,但它不能百分之百确保输出是JSON。而今天提出的结构化输出终于确保API输出是JSON模式了。
其实这个功能非常非常有用,对于调用API的应用程序来说,从非结构化输入生成结构化输出是最核心的用例,想当年我们在调用OpenAI接口的时候,通过prompt让接口输出JSON,可有的时候行,有的时候又不行,根本找不到规律,现在这个问题终于解决了!
OpenAI经过测试,gpt-4o-2024-08-06支持结构化输出,其输出JSON的稳定性是100%,而gpt-4-0613得分不到40%,如下图:
说了这么多,如何使用API的结构化输出呢?有两种模式。
1:Function calling
在函数定义中设置 strict: true,即可通过tools进行结构化输出,如下图:
其输出大概如下:
2:response_format 参数
上述Function calling的方式个人觉得非常复杂,所以也可以在API中使用新增的response_format 参数:
POST /v1/chat/completions{"model": "gpt-4o-2024-08-06","messages": [{"role": "system","content": "You are a helpful math tutor."},{"role": "user","content": "solve 8x + 31 = 2"}],"response_format": {"type": "json_schema","json_schema": {"name": "math_response","strict": true,"schema": {"type": "object","properties": {"steps": {"type": "array","items": {"type": "object","properties": {"explanation": {"type": "string"},"output": {"type": "string"}},"required": ["explanation", "output"],"additionalProperties": false}},"final_answer": {"type": "string"}},"required": ["steps", "final_answer"],"additionalProperties": false}}}}
输出如下:
{"steps": [{"explanation": "Subtract 31 from both sides to isolate the term with x.","output": "8x + 31 - 31 = 2 - 31"},{"explanation": "This simplifies to 8x = -29.","output": "8x = -29"},{"explanation": "Divide both sides by 8 to solve for x.","output": "x = -29 / 8"}],"final_answer": "x = -29 / 8"}
虽然API request看上去很复杂,比如Python官方包做了封装,实现上述功能的代码如下:
from pydantic import BaseModel
from openai import OpenAI
class Step(BaseModel):
explanation: str
output: str
class MathResponse(BaseModel):
steps: list[Step]
final_answer: str
client = OpenAI()
completion = client.beta.chat.completions.parse(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "You are a helpful math tutor."},
{"role": "user", "content": "solve 8x + 31 = 2"},
],
response_format=MathResponse,
)
message = completion.choices[0].message
if message.parsed:
print(message.parsed.steps)
print(message.parsed.final_answer)
else:
print(message.refusal)
此外OpenAI特别强调了结构化输出功能是安全的,必须符合现有的安全策略,所以特别在API中新增加了一个输出字段refusal,用于描述是不符合JSON还是不安全!
这篇文章描述了如何使用结构化输出功能,其实OpenAI也介绍了如何实现该功能,这个有机会再讲,对于理解模型训练很有帮助!
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-04-19
DeepSeek+Dify 构建本地知识库,真香!
2025-04-19
微软开源实时交互模型:提升Agent动态复杂处理能力
2025-04-19
微软最新 Playwright MCP 服务器强势来袭?
2025-04-18
OpenManus:开源版 Manus,无需邀请码,5 分钟极速体验!
2025-04-18
OpenAI开源34页Agents最佳实践白皮书~
2025-04-18
OpenAI推出终端编码智能体Codex CLI了
2025-04-18
“开源版coze”爆火,融资超 4.6 亿!如今 Docker 拉取量超 1 亿,斩获 77.5k star
2025-04-18
【开源看AI】GitDiagram:AI帮你理解任意代码库的架构
2025-01-01
2024-07-25
2025-01-21
2024-05-06
2024-09-20
2024-07-20
2024-06-12
2024-07-11
2024-08-13
2024-12-26