完整文档索引请参考 llms.txt。本页也提供 Markdown 版本。结构化输出(Structured Outputs)允许使用 schema 来控制和定义模型响应的格式,从而轻松实现一致性强制、保证 JSON 有效性以及程序化解析结果。下文介绍两种方法:使用 json_object 实现简单的 JSON 输出,以及使用 Pydantic 类实现完全验证的结构化输出。
简单 JSON 示例
对于仅需模型返回格式良好 JSON 的简单结构化响应,JSON 输出是理想选择。
启用 JSON 输出时,用户应执行以下操作:
- 将 response_format 参数设置为 {'type': 'json_object'}。
- 在系统或用户 prompt 中包含单词 "json",并提供目标 JSON 格式的示例,以引导模型输出有效 JSON。
- 合理设置 max_tokens 参数,防止 JSON 字符串中途截断。
import json
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://api.arcee.ai/api/v1"
)
system_prompt = """
The user will provide some exam text. Please parse the "question" and "answer" and output them in JSON format.
EXAMPLE INPUT:
Which is the highest mountain in the world? Mount Everest.
EXAMPLE JSON OUTPUT:
{
"question": "What is the capital of France?",
"answer": "Paris"
}
"""
user_prompt = "What is the capital of Italy?"
messages = [{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}]
response = client.chat.completions.create(
model="MODEL_NAME",
messages=messages,
response_format={
'type': 'json_object'
}
)
print(json.loads(response.choices[0].message.content))
上一页:函数调用(Function Calling) 下一页:推理轨迹(Reasoning Traces) 最后更新于 6 个月前