openai-agents-python 快速上手指南:从零构建多智能体工作流
【免费下载链接】openai-agents-pythonA lightweight, powerful framework for multi-agent workflows项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-python
本指南带你走完 openai-agents-python(Agents 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 / Linux:
export OPENAI_API_KEY=sk-...Windows PowerShell:
$env:OPENAI_API_KEY = "sk-..."Windows Command Prompt:
set "OPENAI_API_KEY=sk-..."创建你的第一个 Agent
Agent 是 SDK 的核心抽象:一个配置了name(名称)、instructions(指令)以及可选配置(如指定模型)的 AI 模型封装。最简单的定义方式:
from agents import Agent agent = Agent( name="History Tutor", instructions="You answer history questions clearly and concisely.", )从源码看,Agent 类 是一个泛型数据类,核心字段包括:
instructions:即系统提示词(system prompt),可以是一个字符串,也可以是接收RunContextWrapper与Agent实例、动态返回字符串的函数;SDK 强烈建议传入它;name:Agent 的名称;handoff_description:人类可读的功能描述,当该 Agent 被用作 Handoff 目标时,路由 LLM 靠它判断何时委派;model:使用的模型,默认取agents.models.get_default_model()配置的默认模型(当前默认值为"gpt-5.6-luna");model_settings:模型调参配置(如 temperature、top_p),接受ModelSettings实例或包含其字段的字典;tools:该 Agent 可用的工具列表;handoffs:该 Agent 可委派给的子 Agent 列表;input_guardrails/output_guardrails:输入/输出护栏;output_type:输出对象类型,默认输出为str。
仓库中的最小可运行示例见 examples/basic/hello_world.py,它定义了一个"只用俳句回答"的 Agent:
import asyncio from agents import Agent, Runner async def main(): agent = Agent( name="Assistant", instructions="You 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,并取回一个RunResult:
import asyncio from agents import Agent, Runner agent = Agent( name="History Tutor", instructions="You 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:如果任务主要依赖提示词、工具和对话状态,用普通
Agent+Runner即可;如果 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( name="History Tutor", instructions="Answer 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(description="The city name") temperature_range: str = Field(description="The temperature range in Celsius") conditions: str = Field(description="The 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(city=city, temperature_range="14-20C", conditions="Sunny with wind.") agent = Agent( name="Hello world", instructions="You are a helpful agent.", tools=[get_weather], ) async def main(): result = await Runner.run(agent, input="What's 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 tools(Agent 作为工具):由编排者(orchestrator)保持控制权,把专家 Agent 当作工具来调用。
本快速上手继续用Handoffs演示,因为它是最短的入门示例。Manager 风格的模式见 Agent orchestration 和 Tools: agents as tools。
额外定义 Agent 的方式与第一个完全相同。handoff_description为路由 Agent 提供额外的上下文,帮助它判断何时委派:
from agents import Agent history_tutor_agent = Agent( name="History Tutor", handoff_description="Specialist agent for historical questions", instructions="You answer history questions clearly and concisely.", ) math_tutor_agent = Agent( name="Math Tutor", handoff_description="Specialist agent for math questions", instructions="You explain math step by step and include worked examples.", )定义 Handoffs
在 Agent 上可以定义一个"对外交接清单"(handoff 选项池),让它在解决任务时自主选择:
triage_agent = Agent( name="Triage Agent", instructions="Route 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(f"Answered by: {result.last_agent.name}") if __name__ == "__main__": asyncio.run(main())result.last_agent返回真正完成回答的 Agent(result.py 中的last_agent属性),在路由场景下可以用来确认"这个问题被分配给了哪个专家"。
仓库中有一个更完整的流式路由示例 examples/agent_patterns/routing.py:它定义了法语、西班牙语、英语三个专家 Agent,由一个triage_agent根据请求语言交接,并通过Runner.run_streamed+stream_events()逐字输出增量文本,还用trace()把每一轮对话串进同一个conversation_id(group_id),方便在 Dashboard 中按会话查看完整链路。
参考示例
仓库为上述核心模式提供了可直接运行的完整脚本:
examples/basic/hello_world.py:第一次运行 Agent;examples/basic/tools.py:函数工具;examples/agent_patterns/routing.py:多智能体路由。
查看你的 Traces
要复盘一次 Agent 运行中发生了什么,可以进入 OpenAI Dashboard 的 Trace viewer(https://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),仅供参考