代码

cookbook/agent_concepts/async/structured_output.py
import asyncio
from typing import List

from agno.agent import Agent, RunResponse  # noqa
from agno.models.openai import OpenAIChat
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=OpenAIChat(id="gpt-4o"),
    description="你写电影剧本。",
    response_model=MovieScript,
)

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


asyncio.run(json_mode_agent.aprint_response("New York"))
asyncio.run(structured_output_agent.aprint_response("New York"))

用法

1

创建虚拟环境

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

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

安装库

pip install -U openai agno
3

运行 Agent

python cookbook/agent_concepts/async/structured_output.py