ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Agno Agent 输入输出 Cookbook 套件:9 个 I/O 实战示例的测试验证与逐项实现解析

2026/9/6 23:09:08 拓冰建站 浏览量
Agno Agent 输入输出 Cookbook 套件:9 个 I/O 实战示例的测试验证与逐项实现解析 Agno Agent 输入输出 Cookbook 套件9 个 I/O 实战示例的测试验证与逐项实现解析【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno本篇基于 agno 仓库cookbook/02_agents/02_input_output/目录下的测试日志TEST_LOG.md梳理该目录下 9 个 Agent 输入/输出示例的验证结果、运行环境与耗时基线并逐一还原每个示例的代码实现与对应的Agent参数帮助读者快速掌握 agno 中 expected_output、input_schema、output_schema、parser_model、output_model、流式响应、结果落盘等输入输出机制的完整用法。一、测试套件概览环境、基线与验证结果TEST_LOG.md 记录了该套件的测试元信息测试日期2026-02-13运行环境.venvs/demo/bin/pythonpgvector 服务处于运行状态结果9 个示例全部PASS均标记为untagged层级未指定优先级标签各示例的验证结果与实测耗时如下直接取自测试日志示例文件状态层级说明实测耗时expected_output.pyPASSuntagged使用 expected_output 引导回复格式4sinput_formats.pyPASSuntagged演示多种输入格式2sinput_schema.pyPASSuntagged演示输入 schema 校验101soutput_model.pyPASSuntagged使用独立 output model 精修输出49soutput_schema.pyPASSuntagged演示结构化输出 schema18sparser_model.pyPASSuntagged演示 parser model 结构化抽取46sresponse_as_variable.pyPASSuntagged将 Agent 响应捕获为变量12ssave_to_file.pyPASSuntagged自动保存响应到文件10sstreaming.pyPASSuntagged逐 token 流式输出响应9s从耗时分布可以直观看出各示例对模型调用链路的差异input_formats.py2s与expected_output.py4s只走单次生成而input_schema.py101s涉及 HackerNews 工具调用的多轮推理output_model.py49s与parser_model.py46s则包含“主模型 第二模型”的双重调用耗时自然更长。运行前置条件与运行方式根据同目录的 README.md运行该套件需要使用direnv allow加载环境变量其中包含OPENAI_API_KEY执行./scripts/demo_setup.sh创建演示环境然后用.venvs/demo/bin/python运行各 cookbook 脚本部分示例需要可选的本地服务如 pgvector或特定服务商的 API key。单文件运行命令为.venvs/demo/bin/python cookbook/02_agents/02_input_output/file.py二、expected_output用“目标提示”约束回复形态expected_output.py 演示了expected_output参数——它给 Agent 提供一个明确的“回复应该长什么样”的目标from agno.agent import Agent from agno.models.openai import OpenAIResponses agent Agent( modelOpenAIResponses(idgpt-5.2), # expected_output gives the agent a clear target for what the response should look like expected_outputA numbered list of exactly 5 items, each with a title and one-sentence description., markdownTrue, ) if __name__ __main__: agent.print_response( What are the most important principles of clean code?, streamTrue, )expected_output与instructions的区别在于前者不是行为规则而是对回复成品形态的规格说明如“恰好 5 条、每条含标题和一句话描述”。在 Agent 源码 中该字段声明为expected_output: Optional[str] None默认不启用。实测中该示例 4 秒内完成一次流式生成验证了参数注入不会改变运行链路仅影响最终回复结构。三、input_formats结构化消息与多模态输入[ input_formats.py ] 演示了向 Agent 传递结构化消息字典而非纯字符串的能力此处是一个带图片 URL 的多模态输入from agno.agent import Agent agent Agent() if __name__ __main__: agent.print_response( { role: user, content: [ {type: text, text: Whats in this image?}, { type: image_url, image_url: { url: https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg, }, }, ], }, streamTrue, markdownTrue, )关键点在于print_response的入参既可以是字符串也可以是符合消息格式role 多段content列表的字典从而在程序侧直接构造图文混合输入。该示例是全套件中耗时最短的2s说明结构化输入在解析层开销极低。四、input_schema用 Pydantic 模型做输入校验[ input_schema.py ] 展示了如何用 Pydantic 模型定义结构化输入契约并让 Agent 接收字典或模型实例两种形式from typing import List from agno.agent import Agent from agno.models.openai import OpenAIResponses from agno.tools.hackernews import HackerNewsTools from pydantic import BaseModel, Field class ResearchTopic(BaseModel): Structured research topic with specific requirements topic: str focus_areas: List[str] Field(descriptionSpecific areas to focus on) target_audience: str Field(descriptionWho this research is for) sources_required: int Field(descriptionNumber of sources needed, default5) hackernews_agent Agent( nameHackernews Agent, modelOpenAIResponses(idgpt-5-mini), tools[HackerNewsTools()], roleExtract key insights and content from Hackernews posts, input_schemaResearchTopic, ) if __name__ __main__: # 方式一传入符合 schema 的字典 hackernews_agent.print_response( input{ topic: AI, focus_areas: [AI, Machine Learning], target_audience: Developers, sources_required: 5, } ) # 方式二直接传入 Pydantic 模型实例 hackernews_agent.print_response( inputResearchTopic( topicAI, focus_areas[AI, Machine Learning], target_audienceDevelopers, sources_required5, ) )值得注意的细节字典方式下sources_required传的是字符串5而模型字段类型是int——测试日志记录该示例 101s 内 PASS说明 agno 对字典输入做了兼容处理Pydantic 的宽松类型转换。在源码中 input_schema 字段 声明为input_schema: Optional[Type[BaseModel]] None即只接受 Pydantic 模型类不支持裸字典定义。该示例耗时最长101s原因是配置了HackerNewsTools后 Agent 会进行真实工具检索属于多轮推理而非单次生成。五、output_model双模型协作精修最终回复[ output_model.py ] 演示了 agno 的一个特色机制用独立的 output model 替换主模型输出。from agno.agent import Agent, RunOutput from agno.models.openai import OpenAIResponses from rich.pretty import pprint agent Agent( modelOpenAIResponses(idgpt-5-mini), descriptionYou are a helpful chef that provides detailed recipe information., output_modelOpenAIResponses(idgpt-5.2), output_model_promptYou are a world-class culinary writer. Rewrite the recipe with vivid descriptions, pro tips, and elegant formatting., ) if __name__ __main__: run: RunOutput agent.run(Give me a recipe for pad thai.) pprint(run.content)文件头注释说明了其适用场景output_model 接收同样的对话并生成自己的回复替换主模型的输出。典型用法是让便宜模型如 gpt-5-mini负责推理与工具调用再交给更强的模型如 gpt-5.2产出精修的最终答案从而在成本与质量之间取得平衡。注释同时提醒结构化 JSON 输出应改用parser_model见下一节。对应源码字段为 output_model默认None。六、output_schema 与 parser_model结构化输出的两种路径output_schema模型直接产出结构化数据[ output_schema.py ] 用output_schema让 Agent 的run.content直接成为符合 Pydantic 模型的结构化对象class BreakingNewsSummary(BaseModel): topic: str Field(..., descriptionThe topic or region being summarized) summary: str Field(..., descriptionA concise summary of the latest developments) key_updates: List[str] Field(..., descriptionImportant updates or headlines related to the topic) overall_sentiment: str Field(..., descriptionOverall tone of the news coverage, such as positive or mixed) agent Agent( modelOpenAIResponses(idgpt-5.2), descriptionYou summarize current events into clean structured outputs., output_schemaBreakingNewsSummary, ) if __name__ __main__: run: RunOutput agent.run(Latest news from France?) pprint(run.content)源码中 output_schema 的类型为Optional[Union[Type[BaseModel], Dict[str, Any]]]即同时支持 Pydantic 模型类和 JSON Schema 字典两种写法。parser_model用第二模型做结构化抽取[ parser_model.py ] 则展示了output_schema parser_model的组合主模型正常推理甚至可以使用工具由单独的 parser 模型负责把结果解析为目标结构。示例定义了一个包含 11 个字段的NationalParkAdventure模型园区名、最佳季节、招牌景点、推荐步道、野生动物、摄影点、露营选项、安全提示、隐藏亮点、难度评级ge1, le5、建议天数ge1, le14、特殊许可并利用Field(ge..., le...)约束数值范围agent Agent( modelOpenAIResponses(idgpt-5.2), descriptionYou help people plan amazing national park adventures and provide detailed park guides., output_schemaNationalParkAdventure, parser_modelOpenAIResponses(idgpt-5.2), ) if __name__ __main__: run: RunOutput agent.run(national_parks[random.randint(0, len(national_parks) - 1)]) pprint(run.content)两个示例的分工以源码结构看output_schema让主模型直接按结构作答parser_model源码字段则把“结构化抽取”这一职责交给一个独立的模型调用适合主模型输出不可控或主模型本身弱于格式遵循的场景。两者在测试日志中分别以 18s 与 46s 完成均验证了端到端链路。七、response_as_variable 与 save_to_file响应的捕获与持久化把响应捕获为变量[ response_as_variable.py ] 演示了用agent.run()而非print_response()将完整RunOutput对象捕获到变量中便于后续程序化处理agent Agent( modelOpenAIResponses(idgpt-5.2), tools[YFinanceTools()], instructions[Use tables where possible], markdownTrue, ) if __name__ __main__: run_response: RunOutput agent.run(What is the stock price of NVDA) pprint(run_response) # run_response_strem: Iterator[RunOutputEvent] agent.run(..., streamTrue) # for response in run_response_strem: # pprint(response)代码中注释保留了流式变体写法agent.run(..., streamTrue)返回Iterator[RunOutputEvent]可迭代处理每个流式事件。自动落盘[ save_to_file.py ] 展示了save_response_to_file参数——Agent 每次运行后自动把响应写入指定文件agent Agent( modelOpenAIResponses(idgpt-5.2), save_response_to_filetmp/agent_output.md, markdownTrue, ) if __name__ __main__: os.makedirs(tmp, exist_okTrue) agent.print_response(Write a brief guide on Python virtual environments., streamTrue) print(f\nResponse saved to: {agent.save_response_to_file})注意示例中显式os.makedirs(tmp, exist_okTrue)创建父目录说明落盘目标目录需要自行保证存在源码中该字段 声明为save_response_to_file: Optional[str] None默认不落盘。八、streaming逐 token 流式输出[ streaming.py ] 是流式用法的最小示例from agno.agent import Agent from agno.models.openai import OpenAIResponses agent Agent( modelOpenAIResponses(idgpt-5.2), markdownTrue, ) if __name__ __main__: # Stream the response token by token agent.print_response( Explain the difference between concurrency and parallelism., streamTrue, )核心就是一个参数print_response(..., streamTrue)。print_response内部完成富文本渲染与逐 token 打印适合交互式演示生产集成中则如第七节所述改用run(..., streamTrue)手动消费事件流。该示例 9s 完成与测试日志记录一致。九、源码层参数对照与延伸说明将上述 9 个示例涉及的Agent字段汇总全部可在 libs/agno/agno/agent/agent.py 的字段声明中找到一一对应参数源码声明行对应示例作用expected_outputL252expected_output.py以自然语言描述回复成品形态input_schemaL300input_schema.py限定输入必须为符合该 Pydantic 模型的数据output_schemaL303output_schema.py / parser_model.py限定输出为结构化数据模型类或 JSON Schema 字典parser_modelL305parser_model.py指定独立的解析模型完成结构化抽取output_modelL309output_model.py用第二模型替换主模型输出做精修save_response_to_fileL320save_to_file.py响应自动写入指定文件补充两点边界说明测试日志覆盖范围TEST_LOG.md 记录了 9 个示例的验证结果目录下还存在 followup_suggestions.py 与 followup_suggestions_streaming.py 两个未纳入该日志的示例。前者演示了followupsTrue开关与num_followups默认 3源码校验其必须 ≥ 1见 agent.py L648-L650等参数可作为本套件的延伸阅读。耗时数据的使用前提表中耗时来自 2026-02-13 在.venvs/demo/bin/python pgvector 环境的单次实测依赖具体模型与网络状态只能作为链路复杂度的相对参考不应视为性能承诺。十、小结cookbook/02_agents/02_input_output/套件 9 个示例在 2026-02-13 的测试中全部 PASS构成 agno Agent 输入输出能力的完整验证基线输入侧掌握expected_output形态约束、消息字典输入多模态与input_schemaPydantic 校验三种手段输出侧掌握output_schema直接结构化、parser_model独立解析模型、output_model双模型精修三条路径可按成本与可控性需求选型运行侧通过run()/print_response()捕获变量、事件流或经save_response_to_file自动落盘。按 README.md 的前置步骤配置好direnv与 demo 环境后即可用.venvs/demo/bin/python cookbook/02_agents/02_input_output/file.py逐一复现本文覆盖的全部行为。【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考