一天一个开源项目(第45篇):OpenAI Agents SDK Python - 轻量级多 Agent 工作流框架,支持 100+ LLM 与实时语音

引言

"A lightweight, powerful framework for multi-agent workflows."

这是「一天一个开源项目」系列的第 45 篇文章。今天介绍的项目是 OpenAI Agents SDK PythonGitHub)。

构建多 Agent 工作流时,需要处理 Agent 编排、工具调用、会话管理、追踪调试等复杂问题?OpenAI Agents SDK Python 是 OpenAI 开源的轻量级多 Agent 工作流框架 :支持 OpenAI Responses 和 Chat Completions APIs ,以及 100+ 其他 LLM (通过 LiteLLM),内置追踪可视化会话管理GuardrailsHuman-in-the-loop实时语音 Agent 。基于 PydanticPydanticAI,提供简洁 API,适合生产环境。

为什么值得看?

  • 🚀 轻量级框架:简洁 API,快速上手,适合生产环境
  • 🤖 多 Agent 编排:支持 Agents as tools、Handoffs、并行执行等模式
  • 🔧 100+ LLM 支持:通过 LiteLLM 统一接口,支持 OpenAI、Anthropic、Google、开源模型等
  • 📊 内置追踪:可视化、调试、监控,支持评估和微调
  • 🎤 实时语音:支持实时语音 Agent,自动中断检测和上下文管理
  • 🔒 Guardrails:输入/输出验证和安全检查
  • 💬 会话管理:持久化记忆层,维护上下文
  • 👤 Human-in-the-loop:内置人工介入机制

你将学到什么

  • OpenAI Agents SDK 的核心概念(Agents、Tools、Handoffs、Guardrails、Sessions、Tracing)
  • 多 Agent 编排模式:LLM 自主编排 vs 代码确定性编排
  • Agent 配置:instructions、tools、handoffs、guardrails、structured outputs
  • 工具系统:函数工具、MCP 工具、托管工具
  • 会话管理和追踪可视化
  • 实时语音 Agent 的使用
  • 与 LangChain、CrewAI、PydanticAI 等的对比

前置知识

  • 了解 Python 3.10+ 的基本使用
  • 对 AI Agent 有基本了解
  • 了解 LLM API 调用(可选)
  • 对多 Agent 系统有基本认识(可选)

项目背景

项目简介

OpenAI Agents SDK Python 是 OpenAI 开源的轻量级多 Agent 工作流框架,用于构建生产级 Agent 应用。它不是重型框架,而是提供简洁 API 和核心功能,让开发者快速构建多 Agent 系统。

核心特点

  • 轻量级:简洁 API,最小化配置,快速上手
  • 多 LLM 支持:支持 OpenAI API 和 100+ 其他 LLM(通过 LiteLLM)
  • 多 Agent 编排:支持 Agents as tools、Handoffs、并行执行等模式
  • 生产就绪:内置追踪、会话管理、Guardrails、Human-in-the-loop
  • 实时语音:支持实时语音 Agent,自动中断检测
  • 可扩展:基于 Pydantic,易于扩展和定制

解决的核心问题

  • 多 Agent 工作流的复杂编排
  • 不同 LLM 提供商的统一接口
  • Agent 执行过程的追踪和调试
  • 会话上下文的管理和持久化
  • 输入/输出的安全验证
  • 人工介入机制

面向的用户

  • 需要构建多 Agent 应用的开发者
  • 需要支持多种 LLM 的团队
  • 需要生产级 Agent 系统的企业
  • 需要实时语音 Agent 的应用
  • 希望快速上手 Agent 开发的初学者

作者/团队介绍

  • 团队OpenAIGitHub
  • 背景:OpenAI 官方维护,与 OpenAI API 深度集成
  • 理念:提供轻量级、生产就绪的多 Agent 框架
  • 官网openai.github.io/openai-agen...

项目数据

技术栈

  • 语言: Python(99.8%)
  • 核心依赖: Pydantic、PydanticAI、LiteLLM
  • 工具: uv、ruff、MkDocs、Griffe
  • Python 版本: 3.10+

主要功能

核心作用

OpenAI Agents SDK 的核心作用是:提供一个轻量级、生产就绪的多 Agent 工作流框架,让开发者能够:

  1. 快速构建 Agent:简洁 API,最小化配置
  2. 多 Agent 编排:支持 Agents as tools、Handoffs、并行执行等模式
  3. 统一 LLM 接口:通过 LiteLLM 支持 100+ LLM 提供商
  4. 追踪和调试:内置可视化、调试、监控工具
  5. 会话管理:持久化记忆层,维护上下文
  6. 安全验证:Guardrails 进行输入/输出验证
  7. 人工介入:Human-in-the-loop 机制
  8. 实时语音:支持实时语音 Agent

使用场景

  1. 多 Agent 协作系统

    • 使用 Agents as tools 模式,Manager Agent 调用 Specialist Agents
    • 使用 Handoffs 模式,Specialist Agent 接管对话
    • 并行执行多个 Agent 任务
  2. LLM 应用开发

    • 需要支持多种 LLM 提供商的应用
    • 需要统一接口切换不同模型
    • 需要追踪和调试 LLM 调用
  3. 生产级 Agent 系统

    • 需要会话管理和上下文维护
    • 需要输入/输出安全验证
    • 需要人工介入机制
  4. 实时语音应用

    • 构建实时语音 Agent
    • 自动中断检测和上下文管理
    • 语音交互应用
  5. 研究和实验

    • 快速原型开发
    • Agent 行为评估和优化
    • 多 Agent 模式实验

快速开始

安装

bash 复制代码
# 使用 venv
python -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate
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

python 复制代码
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.

使用工具

python 复制代码
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)

核心特性

  1. Agents(Agent 配置)

    • 必需:name、instructions
    • 可选:model、tools、handoffs、guardrails、structured outputs、temperature、top_p
    • 支持自定义模型配置
  2. Agents as Tools / Handoffs(Agent 编排)

    • Agents as tools:Manager Agent 调用 Specialist Agents,保留控制权
    • Handoffs:Specialist Agent 接管对话
    • 可组合使用:Triage Agent 可以 Handoff 到 Specialist,Specialist 仍可调用其他 Agents as tools
  3. Tools(工具系统)

    • 函数工具:Python 函数自动转换为工具,自动生成 schema
    • MCP 工具:Model Context Protocol 工具调用支持
    • 托管工具:支持托管的外部工具
    • 自动函数调用和参数验证
  4. Guardrails(安全验证)

    • 输入验证:验证用户输入
    • 输出验证:验证 Agent 输出
    • 可配置的安全检查
    • 防止不当内容
  5. Human-in-the-Loop(人工介入)

    • 内置人工介入机制
    • 支持审批流程
    • 人工反馈集成
  6. Sessions(会话管理)

    • 自动对话历史管理
    • 持久化记忆层
    • 支持手动历史管理、Sessions、OpenAI 管理的服务端状态
    • Redis 支持(可选)
  7. Tracing(追踪)

    • 内置可视化界面
    • 调试和监控
    • 支持评估和微调
    • Agent 运行追踪
  8. Realtime Agents(实时语音)

    • 实时语音 Agent
    • 自动中断检测
    • 上下文管理
    • 语音交互支持

项目优势

对比项 OpenAI Agents SDK LangChain CrewAI PydanticAI
学习曲线 ✅ 轻量级,快速上手 ⚠️ 陡峭,概念多 ⚠️ 中等,需理解团队概念 ⚠️ 中等
LLM 支持 ✅ 100+ LLM(LiteLLM) ⚠️ 需手动集成 ⚠️ 有限 ⚠️ 需手动集成
多 Agent 编排 ✅ Agents as tools、Handoffs ⚠️ LangGraph 需额外学习 ✅ 团队编排 ⚠️ 需手动实现
追踪和调试 ✅ 内置可视化 ⚠️ LangSmith(付费) ⚠️ 有限 ⚠️ 有限
会话管理 ✅ 内置 Sessions ⚠️ 需手动实现 ⚠️ 需手动实现 ⚠️ 需手动实现
Guardrails ✅ 内置支持 ⚠️ 需手动实现 ⚠️ 需手动实现 ⚠️ 需手动实现
实时语音 ✅ 内置支持 ❌ 无 ❌ 无 ❌ 无
生产就绪 ✅ 官方维护,生产就绪 ⚠️ 社区维护 ⚠️ 社区维护 ⚠️ 社区维护

为什么选择 OpenAI Agents SDK?

  • 轻量级框架:简洁 API,快速上手
  • 多 LLM 支持:通过 LiteLLM 统一接口,支持 100+ LLM
  • 内置功能:追踪、会话、Guardrails、Human-in-the-loop 开箱即用
  • 生产就绪:OpenAI 官方维护,适合生产环境
  • 实时语音:内置实时语音 Agent 支持

项目详细剖析

架构设计

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
    ├── 中断检测
    └── 上下文管理

设计原则

  • 轻量级:最小化依赖,简洁 API
  • 模块化:各组件独立,可单独使用
  • 可扩展:基于 Pydantic,易于扩展
  • 生产就绪:内置追踪、会话、Guardrails

多 Agent 编排模式

OpenAI Agents SDK 支持两种编排模式:

1. LLM 自主编排(Orchestrating via LLM)

LLM 自主规划和决定 Agent 流程,使用 tools 和 handoffs:

python 复制代码
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)进行确定性流程:

python 复制代码
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"))

核心模式

  • Agents as tools:Manager Agent 调用 Specialist Agents,保留控制权
  • Handoffs:Specialist Agent 接管对话
  • 组合模式:Triage Agent 可以 Handoff 到 Specialist,Specialist 仍可调用其他 Agents as tools

工具系统

函数工具(自动转换)

python 复制代码
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)

python 复制代码
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]
)

会话管理

手动历史管理

python 复制代码
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(持久化)

python 复制代码
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 内置追踪功能,提供可视化界面:

python 复制代码
from agents import Agent, Runner

agent = Agent(name="DebugBot", instructions="...")

# 运行 Agent(自动追踪)
result = Runner.run_sync(agent, "Debug this code...")

# 查看追踪
# 访问追踪 UI:http://localhost:8000/trace
# 或使用 API 获取追踪数据

追踪功能包括:

  • Agent 运行可视化
  • 工具调用追踪
  • LLM 调用追踪
  • 性能监控
  • 评估和微调支持

实时语音 Agent

python 复制代码
from agents import Agent, RealtimeAgent

# 创建实时语音 Agent
agent = Agent(
    name="VoiceAssistant",
    instructions="You are a helpful voice assistant."
)

# 启动实时语音
realtime_agent = RealtimeAgent(agent)

# 连接和交互
realtime_agent.connect()
# 自动处理语音输入、中断检测、上下文管理

实时语音功能:

  • 自动中断检测
  • 上下文管理
  • 语音输入/输出
  • 实时交互

项目地址与资源

官方资源

相关资源

适用人群

  • 多 Agent 应用开发者:需要构建多 Agent 协作系统
  • LLM 应用开发者:需要支持多种 LLM 提供商
  • 生产环境用户:需要生产级 Agent 系统,内置追踪、会话、Guardrails
  • 实时语音应用:需要构建实时语音 Agent
  • 快速原型开发:希望快速上手 Agent 开发

学习价值

  • ✅ 多 Agent 编排模式和实践
  • ✅ LiteLLM 统一 LLM 接口的使用
  • ✅ Agent 追踪和调试方法
  • ✅ 会话管理和上下文维护
  • ✅ Guardrails 和安全验证
  • ✅ 实时语音 Agent 开发

欢迎来我中的个人主页找到更多有用的知识和有趣的产品

相关推荐
小兵张健2 小时前
两个配置让 Codex 效率翻倍
人工智能·程序员·github copilot
kymjs张涛3 小时前
OpenClaw 学习小组:初识
android·linux·人工智能
yangpow23 小时前
拆解 OpenClaw 的 Skills 机制:一个为 AI Agent 设计的"包管理器"
人工智能
warm3snow4 小时前
AI 重塑产品管理工具:从 Jira 到智能体项目经理的终极演进
人工智能·ai·excel·项目管理·飞书·产品经理·jira·协同·tapd
吴佳浩4 小时前
OpenClaw macOS 完整安装与本地模型配置教程(实战版)
人工智能·macos·agent
吴佳浩4 小时前
OpenClaw 2026.3.2 — 2026.3.8 权限变更与安全加固
人工智能·openai·agent
左右用AI5 小时前
将openclaw接入飞书:10分钟,让你的AI员工直接操作你的文档和表格!
人工智能
新智元5 小时前
OpenClaw 燃爆魔都!千亿赛道遇上龙虾局,来现场剥虾写代码
openai
阿里云云原生6 小时前
Team 版 OpenClaw:HiClaw 开源,5 分钟完成本地安装
开源