代码

cookbook/models/openai/responses/structured_output.py
from typing import List

from agno.agent import Agent, RunResponse  # noqa
from agno.models.openai import OpenAIResponses
from pydantic import BaseModel, Field
from rich.pretty import pprint  # noqa


class MovieScript(BaseModel):
    setting: str = Field(
        ..., description="为一部大片提供一个绝佳的场景。"
    )
    ending: str = Field(
        ...,
        description="电影的结局。如果不可用,请提供一个圆满的结局。",
    )
    genre: str = Field(
        ...,
        description="电影的类型。如果不可用,请选择动作片、惊悚片或浪漫喜剧。",
    )
    name: str = Field(..., description="给这部电影起个名字")
    characters: List[str] = Field(..., description="这部电影的角色名字。")
    storyline: str = Field(
        ..., description="电影的故事梗概,共 3 句话。要够刺激!"
    )


# 使用 JSON 模式的 Agent
json_mode_agent = Agent(
    model=OpenAIResponses(id="gpt-4o"),
    description="你负责编写电影剧本。",
    response_model=MovieScript,
    use_json_mode=True,
)

# 使用结构化输出的 Agent
structured_output_agent = Agent(
    model=OpenAIResponses(id="gpt-4o"),  
    description="你负责编写电影剧本。",
    response_model=MovieScript,
)


# 将响应获取到变量中
# json_mode_response: RunResponse = json_mode_agent.run("New York")
# pprint(json_mode_response.content)
# structured_output_response: RunResponse = structured_output_agent.run("New York")
# pprint(structured_output_response.content)

json_mode_agent.print_response("New York")
structured_output_agent.print_response("New York")

用法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

设置您的 API 密钥

export OPENAI_API_KEY=xxx
3

安装库

pip install -U openai agno
4

运行 Agent

python cookbook/models/openai/responses/structured_output.py