什么是 OpenAI Agents SDK
OpenAI Agents SDK 是一个轻量而强大的多智能体工作流框架。它设计为 provider-agnostic(提供商无关),不仅支持 OpenAI 的 Responses API 和 Chat Completions API,还能通过适配器支持 100+ 其他大语言模型。
与直接调用 LLM API 相比,Agents SDK 的核心价值在于编排(Orchestration):
- Agent + Runner 让 SDK 自动管理对话轮次、工具调用、安全防护、交接和会话
- 如果你希望自己完全控制循环,可以直接使用 Responses API
- 如果你需要开箱即用的多 Agent 协作、工具管理和状态追踪,Agents SDK 是最佳选择
核心概念一览
SDK 围绕以下 9 大核心概念构建:
| 概念 | 说明 |
|---|---|
| Agents | 配置了指令、工具、防护栏和交接的 LLM |
| Sandbox Agents | 预配置在容器中执行长期任务的 Agent |
| Agents as tools / Handoffs | 将任务委托给其他 Agent |
| Tools | 让 Agent 执行动作(函数、MCP、托管工具) |
| Guardrails | 可配置的输入/输出安全校验 |
| Human in the loop | 在 Agent 运行中介入人工审批 |
| Sessions | 跨多次运行的自动对话历史管理 |
| Tracing | 内置的 Agent 运行追踪、调试和优化 |
| Realtime Agents | 基于 gpt-realtime-1.5 的语音 Agent |
安装
Python 3.10+ 是必需的。
# 使用 pip
pip install openai-agents
# 使用 uv
uv add openai-agents
# 语音支持
pip install 'openai-agents[voice]'
# Redis 会话支持
pip install 'openai-agents[redis]'第一个 Agent
from agents import Agent, Runner
import asyncio
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())项目结构
openai-agents-python/
├── src/agents/ # 核心源码
│ ├── agent.py # Agent 定义
│ ├── run.py # Runner 执行
│ ├── tool.py # 工具系统
│ ├── handoffs/ # 交接机制
│ ├── guardrail.py # 防护栏
│ ├── tracing/ # 追踪系统
│ ├── sandbox/ # 沙箱 Agent
│ ├── realtime/ # 实时语音
│ └── models/ # 模型适配
├── examples/ # 示例代码
├── docs/ # 文档
└── tests/ # 测试下一步
准备好深入了吗?接下来我们将从环境配置开始,逐步掌握 Agents SDK 的每一个核心模块。