Azure OpenAI结合openai Python库实现结构化输出报错求助
解决Azure OpenAI结构化输出的400错误问题
问题背景
你在Azure OpenAI中尝试实现结构化输出时,先后用了OpenAI官方文档的Pydantic模型方案、Cookbook的json_schema方案,但都触发400错误,报错明确指出response_format只能是json_object或text。你已升级openai库至1.40.1版本,使用Python 3.11。
核心原因
Azure OpenAI对结构化输出的支持逻辑和OpenAI原生API存在差异:目前Azure尚未全面支持json_schema类型的response_format参数,也未开放beta.chat.completions.parse方法,仅接受response_format设为{"type": "json_object"}或{"type": "text"},这是报错的直接原因。
解决方案
方案一:用json_object配合提示词约束结构(兼容所有Azure部署)
这是当前最稳妥的实现方式,通过指定response_format={"type": "json_object"},同时在系统提示词中明确要求模型输出符合指定JSON结构,后续自行用Pydantic解析结果即可。
修改后的代码示例:
from pydantic import BaseModel, ValidationError from openai import AzureOpenAI class Step(BaseModel): explanation: str output: str class MathResponse(BaseModel): steps: list[Step] final_answer: str client = AzureOpenAI( api_key='[redacted]', api_version='2024-05-01-preview', azure_endpoint='[redacted]' ) completion = client.chat.completions.create( model="gpt-4omini-2024-07-18-name", messages=[ {"role": "system", "content": "你是数学辅导老师,必须严格按照以下JSON格式输出,不能添加任何额外内容:{\"steps\": [{\"explanation\": \"步骤推理说明\", \"output\": \"步骤对应的等式\"}], \"final_answer\": \"最终计算结果\"}"}, {"role": "user", "content": "solve 8x + 31 = 2"}, ], response_format={"type": "json_object"}, ) # 验证并解析返回的JSON try: math_result = MathResponse.model_validate_json(completion.choices[0].message.content) print("解题步骤:", math_result.steps) print("最终答案:", math_result.final_answer) except ValidationError as e: print("JSON结构验证失败:", e)
方案二:使用Azure官方支持的结构化输出(需满足特定条件)
如果想使用OpenAI原生的json_schema或Pydantic自动解析功能,需要满足以下两个前提:
- 部署的模型为GPT-4o mini 2024-08-06及以后版本,或其他Azure已官宣支持结构化输出的模型
- 使用的API版本至少为
2024-08-01-preview或更高版本
满足条件后,可参考Azure官方文档调整参数格式,或使用beta.chat.completions.parse方法(需确认Azure已开放该接口权限)。
内容的提问来源于stack exchange,提问作者Franck Dernoncourt
相关产品推荐
相关产品推荐

