import asyncio
from typing import List
from agno.agent import Agent
from agno.models.ollama import Ollama
from pydantic import BaseModel, Field
class MovieScript(BaseModel):
name: str = Field(..., description="为这部电影起个名字")
setting: str = Field(
..., description="为这部大片提供一个不错的场景设定。"
)
ending: str = Field(
...,
description="电影的结局。如果不可用,请提供一个快乐的结局。",
)
genre: str = Field(
...,
description="电影的类型。如果不可用,请选择动作、惊悚或浪漫喜剧。",
)
characters: List[str] = Field(..., description="这部电影的角色名字。")
storyline: str = Field(
..., description="电影的故事情节,共3句话。要够刺激!"
)
# 返回结构化输出的代理
structured_output_agent = Agent(
model=Ollama(id="llama3.2"),
description="你负责编写电影剧本。",
response_model=MovieScript,
)
# 同步运行代理
structured_output_agent.print_response("Llamas ruling the world")
# 异步运行代理
async def run_agents_async():
await structured_output_agent.aprint_response("Llamas ruling the world")
asyncio.run(run_agents_async())
创建虚拟环境
打开 Terminal
并创建一个 python 虚拟环境。
python3 -m venv .venv
source .venv/bin/activate
安装 Ollama
请遵循安装指南并运行:
ollama pull llama3.2
安装库
pip install -U ollama agno
运行代理
python cookbook/models/ollama/structured_output.py