OpenAI 代理 SDK
OpenAI Agents SDK 是一个轻量但强大的框架,用于构建多代理工作流。它与提供者无关,支持 OpenAI Responses 和 Chat Completions API,以及其他 100 种 LLM。
寻找 JavaScript/TypeScript 版本?请查看 Agents SDK JS/TS。
核心概念:
- 代理:配置了指令、工具、防护措施和交接的LLM
- 沙盒代理:预配置为与容器协作以在较长时间范围内执行工作的代理。
- Realtime agents: Build powerful voice agents with
gpt-realtime-2.1and full agent features - 语音代理:构建结合语音转文字、代理工作流和文字转语音的语音流程
- 代理作为工具 / 交接:将特定任务委托给其他代理
- 工具:各种工具允许代理执行操作(函数、MCP、托管工具)
- 安全防护:用于输入和输出验证的可配置安全检查
- 人为干预:内置机制,可在代理运行中让人类参与
- 会话:在代理运行中自动管理对话历史
- 追踪:内置代理运行跟踪功能,允许您查看、调试和优化工作流程
探索 示例 目录以查看 SDK 的实际应用,并阅读我们的 文档 获取更多详情。
入门
要入门,请设置您的 Python 环境(需 Python 3.10 或更新版本),然后安装 OpenAI Agents SDK 包。
虚拟环境
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install openai-agents
要支持语音,请使用可选的 voice 组安装:pip install 'openai-agents[voice]'。要支持 Redis 会话,请使用可选的 redis 组安装:pip install 'openai-agents[redis]'。
紫外线
如果您熟悉 uv,安装该软件包会更容易:
uv init
uv add openai-agents
要支持语音,请安装可选的 voice 组:uv add 'openai-agents[voice]'。要支持 Redis 会话,请安装可选的 redis 组:uv add 'openai-agents[redis]'。
运行您的第一个代理
SDK 支持四种主要方式来运行代理。在运行以下任何示例之前,请设置 OPENAI_API_KEY 环境变量。
运行文本代理
对于不需要持久实时连接或沙箱工作区的工作流,请使用文本 Agent。
from agents import Agent, Runner
agent = Agent(name="Assistant", instructions="You are a helpful assistant")
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.
(_对于 Jupyter 笔记本用户,请参见 hello_world_jupyter.ipynb_)
运行沙箱代理
当代理需要检查文件、运行命令、应用补丁或在较长任务中保持工作区状态时,请使用 SandboxAgent。
此示例使用 UnixLocalSandboxClient,macOS 和 Linux 支持该组件。在 Windows 上,请改用 DockerSandboxClient 并搭配 openai-agents[docker] 额外组件或使用托管沙箱客户端;有关设置详情,请参见 沙箱客户端。
from agents import Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.sandbox.entries import GitRepo
from agents.sandbox.sandboxes import UnixLocalSandboxClient
agent = SandboxAgent(
name="Workspace Assistant",
instructions="Inspect the sandbox workspace before answering.",
default_manifest=Manifest(entries={"repo": GitRepo(repo="openai/openai-agents-python", ref="main")}),
)
result = Runner.run_sync(
agent,
"Inspect the repo README and summarize what this project does.",
run_config=RunConfig(sandbox=SandboxRunConfig(client=UnixLocalSandboxClient())),
)
print(result.final_output)
运行实时代理
使用 RealtimeAgent 通过 WebSocket 提供低延迟的服务器端语音和多模态体验。
import asyncio
from agents.realtime import RealtimeAgent, RealtimeRunner
async def main() -> None:
agent = RealtimeAgent(name="Assistant", instructions="You are a helpful voice assistant. Keep responses short.")
runner = RealtimeRunner(starting_agent=agent)
session = await runner.run()
async with session:
await session.send_message("Say hello in one short sentence.")
async for event in session:
if event.type == "audio":
# Forward or play event.audio.data.
pass
elif event.type == "history_added":
print(event.item)
elif event.type == "agent_end":
break
if __name__ == "__main__":
asyncio.run(main())
运行语音代理
使用 VoicePipeline 将音频转换为文本,运行代理工作流程,并流式传输生成的语音。
import asyncio
import numpy as np
from agents import Agent
from agents.voice import AudioInput, SingleAgentVoiceWorkflow, VoicePipeline
async def main() -> None:
agent = Agent(name="Assistant", instructions="You are a helpful voice assistant.")
pipeline = VoicePipeline(workflow=SingleAgentVoiceWorkflow(agent))
audio_input = AudioInput(buffer=np.zeros(24000 * 3, dtype=np.int16))
result = await pipeline.run(audio_input)
async for event in result.stream():
if event.type == "voice_stream_event_audio":
# Forward or play event.data.
pass
if __name__ == "__main__":
asyncio.run(main())
Please browse the [examples] (https://github.com/openai/openai-agents-python/tree/main/examples) directory to see the actual operation of the SDK, and read our [documentation] (https://openai.github.io/openai-agents-python/) for more details.
致谢
我们要特别感谢开源社区的杰出工作:
该库具有以下可选依赖:
我们还依赖以下工具来管理项目:
- UV和[Ruff](汪)声(https://github.com/astral-sh/ruff)
- mypy 和 Pyright
- pytest 和 Coverage.py
- Mk文档
我们致力于继续构建Agents SDK作为开源框架,以便社区中的其他人能够扩展我们的方法。