使用 GPT-4o 模型生成结构化输出#

本指南演示了如何使用 GPT-4o 模型获取结构化输出。OpenAI beta 客户端 SDK 提供了一个解析助手,允许您使用自己的 Pydantic 模型,从而无需定义 JSON 模式。对于受支持的模型,推荐使用此方法。

目前支持此功能的模型有:

  • OpenAI 上的 gpt-4o-mini

  • OpenAI 上的 gpt-4o-2024-08-06

  • Azure 上的 gpt-4o-2024-08-06

让我们定义一个简单的消息类型,用于携带数学问题的解释和输出

from pydantic import BaseModel


class MathReasoning(BaseModel):
    class Step(BaseModel):
        explanation: str
        output: str

    steps: list[Step]
    final_answer: str
import os

# 设置环境变量
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://YOUR_ENDPOINT_DETAILS.openai.azure.com/"
os.environ["AZURE_OPENAI_API_KEY"] = "YOUR_API_KEY"
os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"] = "gpt-4o-2024-08-06"
os.environ["AZURE_OPENAI_API_VERSION"] = "2024-08-01-preview"
import json
import os
from typing import Optional

from autogen_core.models import UserMessage
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient


# 获取环境变量并确保其不为 None 的函数
def get_env_variable(name: str) -> str:
    value = os.getenv(name)
    if value is None:
        raise ValueError(f"Environment variable {name} is not set")
    return value


# 使用经过类型检查的环境变量创建客户端
client = AzureOpenAIChatCompletionClient(
    azure_deployment=get_env_variable("AZURE_OPENAI_DEPLOYMENT_NAME"),
    model=get_env_variable("AZURE_OPENAI_MODEL"),
    api_version=get_env_variable("AZURE_OPENAI_API_VERSION"),
    azure_endpoint=get_env_variable("AZURE_OPENAI_ENDPOINT"),
    api_key=get_env_variable("AZURE_OPENAI_API_KEY"),
)
# 定义用户消息
messages = [
    UserMessage(content="What is 16 + 32?", source="user"),
]

# 在客户端调用create方法,传入消息和额外参数。
# extra_create_args字典包含我们上面定义的MathReasoning模型作为响应格式。
# 提供响应格式和pydantic模型将使用beta SDK中的新parse方法
response = await client.create(messages=messages, extra_create_args={"response_format": MathReasoning})

# 在加载前确保响应内容是有效的JSON字符串
response_content: Optional[str] = response.content if isinstance(response.content, str) else None
if response_content is None:
    raise ValueError("Response content is not a valid JSON string")

# 将响应内容作为JSON加载后打印出来
print(json.loads(response_content))

# 使用MathReasoning模型验证响应内容
MathReasoning.model_validate(json.loads(response_content))
{'steps': [{'explanation': 'Start by aligning the numbers vertically.', 'output': '\n  16\n+ 32'}, {'explanation': 'Add the units digits: 6 + 2 = 8.', 'output': '\n  16\n+ 32\n   8'}, {'explanation': 'Add the tens digits: 1 + 3 = 4.', 'output': '\n  16\n+ 32\n  48'}], 'final_answer': '48'}
MathReasoning(steps=[Step(explanation='Start by aligning the numbers vertically.', output='\n  16\n+ 32'), Step(explanation='Add the units digits: 6 + 2 = 8.', output='\n  16\n+ 32\n   8'), Step(explanation='Add the tens digits: 1 + 3 = 4.', output='\n  16\n+ 32\n  48')], final_answer='48')