娱乐盒子
79.37M · 2026-03-10
这是「一天一个开源项目」系列的第 45 篇文章。今天介绍的项目是 OpenAI Agents SDK Python(GitHub)。
构建多 Agent 工作流时,需要处理 Agent 编排、工具调用、会话管理、追踪调试等复杂问题?OpenAI Agents SDK Python 是 OpenAI 开源的轻量级多 Agent 工作流框架:支持 OpenAI Responses 和 Chat Completions APIs,以及 100+ 其他 LLM(通过 LiteLLM),内置追踪可视化、会话管理、Guardrails、Human-in-the-loop、实时语音 Agent。基于 Pydantic 和 PydanticAI,提供简洁 API,适合生产环境。
为什么值得看?
OpenAI Agents SDK Python 是 OpenAI 开源的轻量级多 Agent 工作流框架,用于构建生产级 Agent 应用。它不是重型框架,而是提供简洁 API 和核心功能,让开发者快速构建多 Agent 系统。
核心特点:
解决的核心问题:
面向的用户:
技术栈:
OpenAI Agents SDK 的核心作用是:提供一个轻量级、生产就绪的多 Agent 工作流框架,让开发者能够:
多 Agent 协作系统
LLM 应用开发
生产级 Agent 系统
实时语音应用
研究和实验
安装:
# 使用 venv
python -m venv .venv
source .venv/bin/activate # Windows: .venvScriptsactivate
pip install openai-agents
# 语音支持(可选)
pip install 'openai-agents[voice]'
# Redis 会话支持(可选)
pip install 'openai-agents[redis]'
# 使用 uv(推荐)
uv init
uv add openai-agents
uv add 'openai-agents[voice]' # 语音支持
uv add 'openai-agents[redis]' # Redis 会话
第一个 Agent:
from agents import Agent, Runner
# 创建 Agent
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant"
)
# 运行 Agent
result = Runner.run_sync(
agent,
"Write a haiku about recursion in programming."
)
print(result.final_output)
# 输出:
# Code within the code,
# Functions calling themselves,
# Infinite loop's dance.
使用工具:
from agents import Agent, Runner, Tool
# 定义工具函数
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression."""
return str(eval(expression))
# 创建带工具的 Agent
agent = Agent(
name="Calculator",
instructions="You are a helpful calculator assistant.",
tools=[Tool(calculate)]
)
# 运行
result = Runner.run_sync(agent, "What is 15 * 23?")
print(result.final_output)
Agents(Agent 配置)
Agents as Tools / Handoffs(Agent 编排)
Tools(工具系统)
Guardrails(安全验证)
Human-in-the-Loop(人工介入)
Sessions(会话管理)
Tracing(追踪)
Realtime Agents(实时语音)
| 对比项 | OpenAI Agents SDK | LangChain | CrewAI | PydanticAI |
|---|---|---|---|---|
| 学习曲线 | 轻量级,快速上手 | ️ 陡峭,概念多 | ️ 中等,需理解团队概念 | ️ 中等 |
| LLM 支持 | 100+ LLM(LiteLLM) | ️ 需手动集成 | ️ 有限 | ️ 需手动集成 |
| 多 Agent 编排 | Agents as tools、Handoffs | ️ LangGraph 需额外学习 | 团队编排 | ️ 需手动实现 |
| 追踪和调试 | 内置可视化 | ️ LangSmith(付费) | ️ 有限 | ️ 有限 |
| 会话管理 | 内置 Sessions | ️ 需手动实现 | ️ 需手动实现 | ️ 需手动实现 |
| Guardrails | 内置支持 | ️ 需手动实现 | ️ 需手动实现 | ️ 需手动实现 |
| 实时语音 | 内置支持 | 无 | 无 | 无 |
| 生产就绪 | 官方维护,生产就绪 | ️ 社区维护 | ️ 社区维护 | ️ 社区维护 |
为什么选择 OpenAI Agents SDK?
OpenAI Agents SDK 采用轻量级、模块化设计,基于 Pydantic 和 PydanticAI,通过 LiteLLM 统一 LLM 接口。
核心组件:
OpenAI Agents SDK
├── Agent(Agent 配置)
│ ├── name、instructions(必需)
│ ├── model、tools、handoffs(可选)
│ ├── guardrails、structured outputs(可选)
│ └── temperature、top_p(可选)
├── Runner(执行引擎)
│ ├── run_sync(同步执行)
│ ├── run_async(异步执行)
│ └── 流式响应支持
├── Tools(工具系统)
│ ├── 函数工具(自动转换)
│ ├── MCP 工具(Model Context Protocol)
│ └── 托管工具
├── Sessions(会话管理)
│ ├── 手动历史管理
│ ├── Sessions(持久化)
│ └── OpenAI 服务端状态
├── Tracing(追踪)
│ ├── 可视化界面
│ ├── 调试和监控
│ └── 评估和微调
└── Realtime(实时语音)
├── 语音 Agent
├── 中断检测
└── 上下文管理
设计原则:
OpenAI Agents SDK 支持两种编排模式:
1. LLM 自主编排(Orchestrating via LLM)
LLM 自主规划和决定 Agent 流程,使用 tools 和 handoffs:
from agents import Agent, Runner
# Manager Agent
manager = Agent(
name="Manager",
instructions="You coordinate tasks and delegate to specialists.",
tools=[
# Specialist Agents as tools
Agent(
name="Researcher",
instructions="You research topics thoroughly."
),
Agent(
name="Writer",
instructions="You write clear, engaging content."
)
]
)
# LLM 自主决定调用哪个 Specialist
result = Runner.run_sync(
manager,
"Research and write about quantum computing."
)
2. 代码确定性编排(Orchestrating via Code)
使用 Python 原语(如 asyncio.gather)进行确定性流程:
import asyncio
from agents import Agent, Runner
# 定义多个 Agent
researcher = Agent(name="Researcher", instructions="...")
writer = Agent(name="Writer", instructions="...")
reviewer = Agent(name="Reviewer", instructions="...")
# 并行执行
async def workflow(topic: str):
# 并行研究
research_result = await Runner.run_async(
researcher, f"Research: {topic}"
)
# 并行写作
write_result = await Runner.run_async(
writer, f"Write about: {research_result.final_output}"
)
# 并行审查
review_result = await Runner.run_async(
reviewer, f"Review: {write_result.final_output}"
)
return review_result
# 执行
result = asyncio.run(workflow("quantum computing"))
核心模式:
函数工具(自动转换):
from agents import Agent, Runner, Tool
def get_weather(city: str) -> str:
"""Get current weather for a city."""
# 实现逻辑
return f"Weather in {city}: Sunny, 25°C"
agent = Agent(
name="WeatherBot",
instructions="You help users get weather information.",
tools=[Tool(get_weather)] # 自动转换,自动生成 schema
)
result = Runner.run_sync(agent, "What's the weather in Beijing?")
MCP 工具(Model Context Protocol):
from agents import Agent, Runner
from agents.tools import MCPTool
# MCP 工具集成
mcp_tool = MCPTool(
server_name="my-mcp-server",
tool_name="search"
)
agent = Agent(
name="MCPBot",
instructions="You use MCP tools to help users.",
tools=[mcp_tool]
)
手动历史管理:
from agents import Agent, Runner
agent = Agent(name="ChatBot", instructions="...")
# 手动管理历史
history = []
result1 = Runner.run_sync(agent, "Hello", history=history)
history.append({"role": "user", "content": "Hello"})
history.append({"role": "assistant", "content": result1.final_output})
result2 = Runner.run_sync(agent, "What did I say?", history=history)
Sessions(持久化):
from agents import Agent, Runner, Session
agent = Agent(name="ChatBot", instructions="...")
# 创建 Session
session = Session.create()
# 使用 Session
result = Runner.run_sync(
agent,
"Hello",
session_id=session.id
)
# Session 自动维护历史
result2 = Runner.run_sync(
agent,
"What did I say?",
session_id=session.id # 自动包含之前的对话
)
OpenAI Agents SDK 内置追踪功能,提供可视化界面:
from agents import Agent, Runner
agent = Agent(name="DebugBot", instructions="...")
# 运行 Agent(自动追踪)
result = Runner.run_sync(agent, "Debug this code...")
# 查看追踪
# 访问追踪 UI:
# 或使用 API 获取追踪数据
追踪功能包括:
from agents import Agent, RealtimeAgent
# 创建实时语音 Agent
agent = Agent(
name="VoiceAssistant",
instructions="You are a helpful voice assistant."
)
# 启动实时语音
realtime_agent = RealtimeAgent(agent)
# 连接和交互
realtime_agent.connect()
# 自动处理语音输入、中断检测、上下文管理
实时语音功能:
学习价值:
欢迎来我中的个人主页找到更多有用的知识和有趣的产品