ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

openai-agents-python 快速上手指南:从零构建多智能体工作流

openai-agents-python 快速上手指南:从零构建多智能体工作流 openai-agents-python 快速上手指南从零构建多智能体工作流【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python本指南带你走完 openai-agents-pythonAgents SDK的完整起步流程从创建项目、安装 SDK、配置 API Key到定义第一个 Agent、运行它、给它挂上工具最后通过 Handoffs 编排一个多智能体路由系统。读完本文你将掌握Agent、Runner、RunResult、tool装饰器与handoffs的核心用法并了解多轮对话中三种记忆策略的取舍以及如何在 OpenAI Dashboard 中查看每次运行的 Traces。环境准备创建项目与虚拟环境创建项目目录与虚拟环境这一步只需执行一次。打开终端创建项目目录并建立 Python 虚拟环境mkdir my_project cd my_project python -m venv .venv激活虚拟环境每次打开新的终端会话都需要重新激活。macOS / Linux 使用source .venv/bin/activateWindows 使用.venv\Scripts\activate安装 Agents SDK在激活的虚拟环境中安装pip install openai-agents # or uv add openai-agents, etc本仓库即该 SDK 的完整源码pyproject.toml 定义了包结构与依赖安装的是发布到 PyPI 的openai-agents包其源码包名对应仓库中的src/agents目录核心模块包括Agent、Runner、handoffs、tools、guardrails、models等。设置 OpenAI API Key如果没有 API Key需要先在 OpenAI 平台创建。以下命令仅为当前终端会话设置环境变量macOS / Linuxexport OPENAI_API_KEYsk-...Windows PowerShell$env:OPENAI_API_KEY sk-...Windows Command Promptset OPENAI_API_KEYsk-...创建你的第一个 AgentAgent 是 SDK 的核心抽象一个配置了name名称、instructions指令以及可选配置如指定模型的 AI 模型封装。最简单的定义方式from agents import Agent agent Agent( nameHistory Tutor, instructionsYou answer history questions clearly and concisely., )从源码看Agent 类 是一个泛型数据类核心字段包括instructions即系统提示词system prompt可以是一个字符串也可以是接收RunContextWrapper与Agent实例、动态返回字符串的函数SDK 强烈建议传入它nameAgent 的名称handoff_description人类可读的功能描述当该 Agent 被用作 Handoff 目标时路由 LLM 靠它判断何时委派model使用的模型默认取agents.models.get_default_model()配置的默认模型当前默认值为gpt-5.6-lunamodel_settings模型调参配置如 temperature、top_p接受ModelSettings实例或包含其字段的字典tools该 Agent 可用的工具列表handoffs该 Agent 可委派给的子 Agent 列表input_guardrails/output_guardrails输入/输出护栏output_type输出对象类型默认输出为str。仓库中的最小可运行示例见 examples/basic/hello_world.py它定义了一个只用俳句回答的 Agentimport asyncio from agents import Agent, Runner async def main(): agent Agent( nameAssistant, instructionsYou only respond in haikus., ) result await Runner.run(agent, Tell me about recursion in programming.) print(result.final_output) # Function calls itself, # Looping in smaller pieces, # Endless by design. if __name__ __main__: asyncio.run(main())运行你的第一个 Agent使用Runner执行 Agent并取回一个RunResultimport asyncio from agents import Agent, Runner agent Agent( nameHistory Tutor, instructionsYou answer history questions clearly and concisely., ) async def main(): result await Runner.run(agent, When did the Roman Empire fall?) print(result.final_output) if __name__ __main__: asyncio.run(main())Runner 的执行循环从 Runner.run 的源码注释 可以看到Agent 会循环执行直到产出最终输出以给定输入调用 Agent若产生最终输出类型匹配agent.output_type循环终止若发生 Handoff则用新 Agent 重新运行循环否则执行工具调用如果有然后继续循环。Runner.run的完整签名还支持context上下文对象、max_turns最大轮数默认值DEFAULT_MAX_TURNS、hooks生命周期回调、run_config全局运行配置、error_handlers错误处理器、previous_response_id/conversation_id/session三种记忆策略等参数。RunResult上最有用的字段/方法final_output最后一个 Agent 的输出last_agent实际完成对话的 Agent多智能体场景下判断谁回答的to_input_list()把本轮运行转成下一轮的输入列表用于手动续接对话。开启第二轮对话三种记忆策略要进行第二轮对话你可以把result.to_input_list()传回Runner.run(...)挂载一个 session由 SDK 负责加载/保存历史复用 OpenAI 服务端托管状态使用conversation_id或previous_response_id。官方建议的取舍原则需求起步方案完全手动控制、且历史记录与模型提供商无关result.to_input_list()让 SDK 帮你加载/保存历史session...由 OpenAI 服务端托管续接previous_response_id或conversation_id更详细的权衡与精确行为参见 Running agents。关于各种策略的深入对比还可以阅读 running_agents.md 与 sessions。何时该用 Sandbox agents如果任务主要依赖提示词、工具和对话状态用普通AgentRunner即可如果 Agent 需要在隔离的工作区中检查或修改真实文件请转去阅读 Sandbox agents 快速上手。给 Agent 配备工具给 Agent 挂上工具它就能查资料或执行动作。用tool装饰器把普通 Python 函数变成工具import asyncio from agents import Agent, Runner from agents.decorators import tool tool def history_fun_fact() - str: Return a short history fact. return Sharks are older than trees. agent Agent( nameHistory Tutor, instructionsAnswer history questions clearly. Use history_fun_fact when it helps., tools[history_fun_fact], ) async def main(): result await Runner.run( agent, Tell me something surprising about ancient life on Earth., ) print(result.final_output) if __name__ __main__: asyncio.run(main())要点说明tool在 decorators.py 中是function_tool的别名两者等价函数的 docstring 会被作为工具描述提供给模型帮助模型判断何时调用函数签名参数名 类型注解会被自动转换为 JSON Schema因此建议为参数添加类型注解。仓库示例 examples/basic/tools.py 展示了更完整的用法——返回 Pydantic 模型并使用Annotated描述参数from typing import Annotated from pydantic import BaseModel, Field from agents import Agent, Runner from agents.decorators import tool class Weather(BaseModel): city: str Field(descriptionThe city name) temperature_range: str Field(descriptionThe temperature range in Celsius) conditions: str Field(descriptionThe weather conditions) tool def get_weather(city: Annotated[str, The city to get the weather for]) - Weather: Get the current weather information for a specified city. print([debug] get_weather called) return Weather(citycity, temperature_range14-20C, conditionsSunny with wind.) agent Agent( nameHello world, instructionsYou are a helpful agent., tools[get_weather], ) async def main(): result await Runner.run(agent, inputWhats the weather in Tokyo?) print(result.final_output) # The weather in Tokyo is sunny. if __name__ __main__: asyncio.run(main())添加更多 Agent多智能体模式的选择在引入多智能体模式之前先决定谁拥有最终答案Handoffs交接由专家 Agent 接管对话中属于它的那一段Agents as toolsAgent 作为工具由编排者orchestrator保持控制权把专家 Agent 当作工具来调用。本快速上手继续用Handoffs演示因为它是最短的入门示例。Manager 风格的模式见 Agent orchestration 和 Tools: agents as tools。额外定义 Agent 的方式与第一个完全相同。handoff_description为路由 Agent 提供额外的上下文帮助它判断何时委派from agents import Agent history_tutor_agent Agent( nameHistory Tutor, handoff_descriptionSpecialist agent for historical questions, instructionsYou answer history questions clearly and concisely., ) math_tutor_agent Agent( nameMath Tutor, handoff_descriptionSpecialist agent for math questions, instructionsYou explain math step by step and include worked examples., )定义 Handoffs在 Agent 上可以定义一个对外交接清单handoff 选项池让它在解决任务时自主选择triage_agent Agent( nameTriage Agent, instructionsRoute each homework question to the right specialist., handoffs[history_tutor_agent, math_tutor_agent], )从 Agent 类定义 看handoffs接受Agent[Any] | Handoff[TContext, Any]的列表——既可以像上面这样直接传入子 Agent也可以传入带自定义工具名、输入过滤器等高级配置的Handoff对象。Handoff 相关的工具名生成与 MCP 预留名处理逻辑见 agent.py。运行多智能体编排Runner 负责执行单个 Agent、所有 Handoff 以及所有工具调用import asyncio from agents import Runner async def main(): result await Runner.run( triage_agent, Who was the first president of the United States?, ) print(result.final_output) print(fAnswered by: {result.last_agent.name}) if __name__ __main__: asyncio.run(main())result.last_agent返回真正完成回答的 Agentresult.py 中的last_agent属性在路由场景下可以用来确认这个问题被分配给了哪个专家。仓库中有一个更完整的流式路由示例 examples/agent_patterns/routing.py它定义了法语、西班牙语、英语三个专家 Agent由一个triage_agent根据请求语言交接并通过Runner.run_streamedstream_events()逐字输出增量文本还用trace()把每一轮对话串进同一个conversation_idgroup_id方便在 Dashboard 中按会话查看完整链路。参考示例仓库为上述核心模式提供了可直接运行的完整脚本examples/basic/hello_world.py第一次运行 Agentexamples/basic/tools.py函数工具examples/agent_patterns/routing.py多智能体路由。查看你的 Traces要复盘一次 Agent 运行中发生了什么可以进入 OpenAI Dashboard 的 Trace viewerhttps://platform.openai.com/traces查看每次 agent run 的轨迹——包括模型调用、工具调用、Handoff 以及各步骤耗时等细节。SDK 会在每次运行时自动生成 trace你也可以像 routing 示例那样用trace()上下文管理器手动分组。下一步继续构建更复杂的 Agent 流程学习如何配置 Agents学习 running agents 与 sessions如果任务需要在真实工作区中执行学习 Sandbox agents学习 tools、guardrails 和 models。【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表