跳转到内容

OpenAI Agents SDK:托管式编排

  • 理解「Agent 是配置、Runner 是执行者」的分离设计
  • handoff 实现「前台分诊 → 转交专家」的多 Agent 路由
  • 知道 Runner.run(异步)和 Runner.run_sync 的区别

OpenAI Agents SDK 的设计原则是「原语足够少,学得快」。核心心智模型是前台分诊转交专家:一个 Triage Agent 握着「可交接对象」清单,自己判断问题该转给谁。Runner 替你管理整个 agent loop(调模型 → 执行工具 → 交接 → 护栏 → 会话),你只写配置。

最小程序:Agent 只是一份「配置」,Runner 负责真正跑。

# 安装: pip install openai-agents (设置 OPENAI_API_KEY 环境变量)
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.run 是 async 的

多 Agent 路由(handoff,本章的核心模式):

from agents import Agent, Runner
# 1) 两个「专家」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.",
)
# 2) 一个「分诊」Agent:手里握着可交接对象清单,自己判断转给谁
triage_agent = Agent(
name="Triage Agent",
instructions="Route each homework question to the right specialist.",
handoffs=[history_tutor_agent, math_tutor_agent],
)
# 3) 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__":
import asyncio
asyncio.run(main())

加工具用 @tool 装饰器,docstring 就是给模型的「说明书」:

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],
)
result = Runner.run_sync(agent, "Tell me something surprising about ancient life on Earth.")
print(result.final_output)

新手最容易混的三个点:Agent(...) 创建完不会自己跑(必须 Runner.run);Runner.run 是 async 的(想要同步一行调用用 run_sync);多个 Agent 不会自动对话(要么 handoff 转交,要么把 Agent 当工具 as_tool() 调用)。

先自己回答,再看答案:

  1. 为什么说「Agent 只是配置」?
  2. handoff 和「把 Agent 当工具调用」的区别是什么?
  3. Runner.runRunner.run_sync 有什么区别?
参考答案
  1. Agent 对象只声明指令/工具/交接等配置,不会自己执行;真正跑循环的是 Runner。
  2. handoff 是交出对话控制权(底层是一个 transfer_to_xxx 工具);把 Agent 当工具(as_tool())是主控方原地调用专家,控制权不转移。
  3. run 是 async 函数(脚本里 await 或配 asyncio.run),run_sync 是同步封装,一行调用。
  • 原语极少:Agent(配置)+ Runner(执行)+ handoff(交接)+ guardrail(护栏)
  • 多 Agent 协作必须显式设计:handoff 路由或 agent-as-tool
  • 同步/异步别混:run 要 await,一行同步用 run_sync
OpenAI Agents SDK 小测
x
1 / 3

OpenAI Agents SDK 中真正执行 Agent 循环的是?