运行前必须设置 OPENAI_API_KEY 环境变量;语音支持需装 openai-agents[voice],Redis 会话需 openai-agents[redis];Windows 上沙箱示例需改用 DockerSandboxClient 并装 openai-agents[docker]

python -m venv .venv
source .venv/bin/activate
pip install openai-agentsREADME 未说明显存或 GPU 要求;需 Python 3.10 或更新版本,模型推理在云端 API 完成
OpenAI 官方轻量级多智能体工作流框架,支持 100+ 种 LLM,可快速搭建 Agent 编排
轻量级 Python 框架,用于编排多智能体工作流,帮助开发者快速搭建基于 LLM 的协作式 Agent 系统。
核心能力
- 用 Agent 配置指令、工具、护栏与交接
- 支持 Agents as tools 与 handoff 委派子任务
- 内置输入输出护栏做安全校验
- Sessions 自动管理多轮对话历史
- 内置 Tracing 追踪调试 Agent 运行
容易踩的坑
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
- v0.24.0-alpha.7Agents SDK v0.24.0-alpha.7pre-release2026-11-08 · 2026-11-08 07:05 UTC
查看更新说明
Agents SDK v0.24.0-alpha.7
Highlights
- Use Classic workflows alongside native execution. Import the retained v0 runtime through
agents.classic. This alpha also changes executor write defaults; review the upgrade actions before opening existing environments. - Keep conversations in your own storage. Add durable root Sessions with
CustomStorage, and reconcile uncertain tool effects before resuming work. - Add voice and hosted tools to native agents. Connect speech workflows to a Session, or use
FileSearch,CodeInterpreter, andImageGenerationthrough compatible Responses providers. - Control context, completion, and usage. Transform model input, retain selected context during compaction, review proposed answers, and limit observed root usage.
Upgrading from 0.24.0-alpha.6
- Review Environment write policies. New Environments default to
write_policy="strict", which requires a compatible Linux or macOS executor. The working directory remains writable; usewritable_rootsfor additional directories. To retain the previous remote policy, including on Windows executors, setwrite_policy="legacy"and leavewritable_roots=None. Local execution requires strict mode. When restoring legacy remote checkpoints or profiles, select legacy explicitly; reopening does not upgrade their policy. See the executor policy and restore rules. - Check implicit reasoning settings. The bundled model catalog changes the default reasoning effort from
lowtomediumforgpt-6-astra,gpt-6.1-sol, andgpt-5.6-sol. Setmodel_settings={"reasoning_effort": "low"}explicitly if you need the previous effort. This describes bundled metadata; an explicit setting or provider model metadata can select another value. (#5517) - Rename MCP approval modes. Replace
approval_mode="auto"with"native", and"approve"with"preapproved". The old values are rejected; the new names preserve their respective approval behavior. - Update child step callbacks.
NativeAgents.before_stepnow receives oneChildStepContext, withcontext,child, andstep_index, instead of separate child and step-index arguments. Rootbefore_stepcallbacks keep their existing signature. - Handle MCP forms and URLs separately.
ElicitationRequestis now the unionFormRequest | UrlRequest. UseFormRequest.reply()orrespond()for forms; useUrlRequest.reply_url_accept()oraccept_url()for URL consent.
Added
- Application-owned conversation storage.
SessionStore,SQLiteSessionStore, andCustomStoragepersist root history and automatic Python tool results. This initial profile excludes native tools, Environments, children, planning tools, generated-code execution, manual tools, and portable checkpoints.SQLiteSessionStorerequires one host and a local POSIX filesystem. Both local profiles and custom stores can report uncertain root calls for explicit reconciliation; neither automatically replays those effects. (#5514, #5502) - Provider-hosted tools and storage. Add
FileSearch,CodeInterpreter, andImageGeneration, Code Interpreter caller policies, and provider-managed storage. Hosted tools require an API-key provider and a compatible standard Responses model; they exclude Responses Lite and Codex login. Hosted web search adds domain and location controls and retains citations. (#5576, hosted-tool guide) - Context and completion hooks.
Agent.transform_contextchanges sampled input without changing stored history.before_compactand selected-item retention control compaction.before_completecan accept, returnContinueTurn, or stop a proposed answer; rejected text may already have streamed and remai
- Use Classic workflows alongside native execution. Import the retained v0 runtime through
- v0.24.0-alpha.6Agents SDK v0.24.0-alpha.6pre-release2026-11-03 · 2026-11-03 16:44 UTC
查看更新说明
Install the preview
Use standard CPython 3.10–3.14 in a virtual environment. These wheels include the native runtime; no Rust toolchain or source build is needed. This preview is distributed through GitHub Releases, not PyPI.
Run the command for your platform:
Linux x86_64 (glibc 2.39 or newer)
python -m pip install "https://github.com/openai/openai-agents-python/releases/download/v0.24.0-alpha.6/openai_agents-0.24.0a6-cp310-abi3-manylinux_2_39_x86_64.whl"macOS 11 or newer on Apple Silicon
python -m pip install "https://github.com/openai/openai-agents-python/releases/download/v0.24.0-alpha.6/openai_agents-0.24.0a6-cp310-abi3-macosx_11_0_arm64.whl"Windows x64
python -m pip install "https://github.com/openai/openai-agents-python/releases/download/v0.24.0-alpha.6/openai_agents-0.24.0a6-cp310-abi3-win_amd64.whl"Wheels are not provided for Intel Macs, ARM Linux, ARM Windows, Alpine/musl, PyPy or free-threaded Python. The
cp310-abi3filenames also support standard CPython 3.11–3.14.Check the installed version and native module:
python -c "from importlib.metadata import version; import agents._native; print(version('openai-agents'))"Expect
0.24.0-alpha.6or its equivalent Python packaging spelling,0.24.0a6.SHA256SUMScontains checksums for all three wheels.Release notes
Changes since
0.24.0-alpha.5. This preview expands conversation control, state recovery, and tool policies, and includes public API changes.Added
- Control submitted work through a captured
Turn, withget_result(), passiveevents(), manual request handling, steering, and cancellation. Queue prompts withSession.submit(..., if_busy="queue"), or steer the active Turn withif_busy="steer". - Add
LocalStorageto reopen conversations from a local profile, and extend portableSessionStatecapture and recovery. Add idle forks, caller-supplied compaction summaries, and checks for feature support and checkpoint readiness.LocalStorageprofiles cannot export portable checkpoints. - Add
NativeOutputfor native strict output andPromptedOutputfor JSON validated in Python. Optionalmax_retriesperforms bounded corrections without tools or replaying the task.LocalStoragerequiresmax_retries=0. - Handle live manual tool requests and resume supported pending requests from checkpoints. Add experimental external-job recovery through
agents.experimental.deferredand an optional MCP Tasks adapter. - Select tools for each submission or model step within the Session's opening permissions. Add native web search, native child checklists, and native goals for local-storage Sessions.
- Validate Python tool return annotations and add tool policies for inspecting arguments and results. Extend native MCP support with argument replacement, result transforms, and application-managed form and URL interactions over supported HTTP, stdio, and model WebSocket paths.
- Add
NetworkPolicyfor native commands on supported Linux and macOS executors, subject to each platform's network and Unix socket limits. Manage remote executor lifetimes through anEnvironmentsupplied when opening a Session or running an Agent. - Enable native child approvals and form requests with
NativeAgents(interactions=True). Children continue to share the Session's tools and application context. - Configure native OpenTelemetry export and inspect typed observations.
NativeErrornow exposes available provider status codes, error codes, request IDs, and failure categories. - Test real SDK sessions and Python tools against local scripted responses with
agents.testing.ScriptedResponses, without a live model or API key.
API changes
- Use
Agent.run()orAgent.run_sync()for one-shot calls; the redundantRunneraliases have been removed. - Replace
Turn.wait()andSession.wait()withTurn.get_result()on the captured Turn. - Replace
Session.interrupt()withTurn.cancel()for o
- Control submitted work through a captured
- v0.24.0最新正式版2026-10-15 · 2026-10-15 02:20 UTC
0.24.0 (2026-10-15)
Features
- expose MCP annotations on converted tools (#5356) (75813f8)
- support run-wide tool exception formatting (#5326) (8fd9a7c)
Bug Fixes
- batch OpenAI conversation session writes within the API limit (#5334) (26345c1)
- defer automatic compaction for pending approvals (#5363) (5eb47a5)
- deps-dev: bump fastapi from 0.139.2 to 0.141.1 (#5312) (cdf23bd)
- deps-dev: bump grpcio from 1.83.1 to 1.84.0 (#5310) (a85487e)
- deps-dev: bump pymdown-extensions from 11.0.2 to 12.1 (#5314) (d9758b0)
- deps-dev: bump pymongo from 4.18.1 to 4.18.2 (#5313) (858856f)
- deps: bump boto3 from 1.42.75 to 1.43.109 (#5378) (7da6a92)
- deps: bump filelock from 3.20.3 to 4.0.12 (#5375) (14f4553)
- deps: bump fsspec from 2025.7.0 to 2026.6.0 (#5317) (66504e9)
- deps: bump redis from 7.0.1 to 8.1.0 (#5379) (24ebf1c)
- deps: bump temporalio from 1.33.0 to 1.34.0 (#5377) (c148280)
- deps: bump vercel-sandbox from 0.7.0 to 0.8.0 (#5374) (2938d87)
- deps: update fastapi requirement from >=0.141.1 to >=0.142.2 in /examples/realtime/twilio_sip (#5372) (f47d2c3)
- deps: update fastapi requirement in /examples/realtime/twilio_sip (f47d2c3)
- deps: update openai requirement from <4,>=3.19.1 to >=3.20.0,<4 in /examples/realtime/twilio_sip (#5308) ([f346950](https:/
- v0.23.12026-10-02 · 2026-10-02 15:19 UTC
查看更新说明
0.23.1 (2026-10-02)
Bug Fixes
Release readiness review (v0.23.0 -> TARGET 0a5a08b21cd44808d73e8a9e732212dd33b3690d)
This is a release readiness report done by
$final-release-reviewskill.Diff
Release intent
- Review mode: final candidate
- Intended release: patch, 0.23.1
- Minimum required release type: patch
- Versioning verdict: compatible
Release call
🟢 GREEN LIGHT TO SHIP this exact candidate. No concrete release-blocking regression was identified. Human approval and normal repository protections still apply.
Scope summary
- 28 files changed (+622/-42): release automation, test fixtures, integration/example tooling, and release metadata.
- The clean candidate contains current main
a575a6e637feb9aea1b591237b007dd4991ddfbaplus only six release-owned metadata files. Package, lockfile, manifest, source version and API baseline agree on 0.23.1. Snapshot sourceb31b9f8d13d49142a64f8873f2cc2ee40441a795is an ancestor of the candidate. - Relative to v0.23.0, SDK runtime source changes only its version string. API snapshot content, dependencies, Python support and persisted schemas are unchanged.
Risk assessment (ordered by impact)
-
First PyPI publication of the 0.23 series includes earlier migration requirements
- Risk: 🟢 LOW with the previously reviewed migration paths. Users upgrading from 0.22.3 receive the 0.23.0 behavior changes as well as this patch.
- Evidence: PyPI has neither 0.23.0 nor 0.23.1. The 0.23.0 release assessment in #5226 covers strict tools, approval restoration, encrypted history, resource limits, voice defaults and provider changes; this candidate does not alter those runtime paths.
- Files:
CHANGELOG.md,src/agents/version.py; unchanged 0.23.0 runtime contracts assessed in #5226. - Action: Carry forward the 0.23.0 migration guidance in the 0.23.1 announcement, particularly explicit strict-tool parameters, fresh legacy approvals, trusted encrypted-history import, resource-limit overrides and the explicit prior voice-model override.
-
Release checks recover without changing package behavior
- Risk: 🟢 LOW. Test-loop initialization and required-check ownership are corrected while publication authorization remains intact.
- Evidence: OS mocks are installed after event-loop initialization and restored before teardown. Authorized review events rerun the current PR-triggered readiness check instead of replacing or cancelling it. Source validation, native human approval, isolated builds and OIDC publishing remain unchanged.
- Files:
tests/sandbox/test_unix_local_user_file_io.py,.github/scripts/release_automation.py,.github/workflows/release-readiness-refresh.yml,.github/workflows/release-readiness.yml. - Action: Submit the exact-head human approval, allow readiness to refresh, merge through normal protections, and verify the publisher and uploaded provenance.
-
External-provider coverage now requires explicit maintainer intent
- Risk: 🟢 LOW with an existing opt-in path. Default integration and automatic example runs no longer implicitly select the affected external-provider cases.
- Evidence: Integration bootstrap resets inherited enable flags, removes the listed external-provider credentials by default, and rejects external model overrides without opt-in. External cases are deselected by default; automatic examples use the expanded skip list. Manual example selection remains available.
- Files: `.github/scripts/run_integration_t
- v0.23.02026-10-02 · 2026-10-02 01:08 UTC
查看更新说明
0.23.0 (2026-10-01)
Features
- mcp: add configurable MCP listing page limits (#5133) (9a21ab1)
- sandbox: add opt-in Docker removal protection (#5116) (ae5803f)
- sandbox: allow configuring memory consolidation turns (#5135) (daa1bcb)
- sessions: add an opt-in encrypted history scan budget (#5118) (a2fdb94)
Bug Fixes
- avoid awaiting cleanup during coroutine closure (#5163) (719c4e7)
- ci: update and group CodeQL actions together (#5262) (f76153c)
- ci: validate release source before building distributions (#5220) (2747c1c)
- core/extensions: respect sensitive trace capture for model metadata (#5129) (88b722d)
- core: bound agent tool streaming callback backlogs (#5106) (f23da76)
- core: isolate nested agent tool state across fresh runs (#5123) (46cc8d8)
- core: preserve closed parent constraints in singleton allOf (#5131) (f010d18)
- core: preserve guarded final outputs in agent tools (#5115) (f3a15f6)
- core: preserve structured guardrail diagnostics and agent output during persistence (#5016) (51bcea7)
- core: preserve tool identity during asynchronous enablement (#5136) (f2ae64c)
- core: redact default tool failure details (#5112) (40956e0)
- core: redact streaming task exception tracebacks (#5121) (c329e92)
- core: reject silently discarded kwargs tool argum
OpenAI Agents SDK 
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows. It is provider-agnostic, supporting the OpenAI Responses and Chat Completions APIs, as well as 100+ other LLMs.
[!NOTE] Looking for the JavaScript/TypeScript version? Check out Agents SDK JS/TS.
Core concepts:
- Agents: LLMs configured with instructions, tools, guardrails, and handoffs
- Sandbox agents: Agents preconfigured to work with a container to perform work over long time horizons.
- Realtime agents: Build powerful voice agents with
gpt-realtime-2.1and full agent features - Voice agents: Build voice pipelines that combine speech-to-text, an agent workflow, and text-to-speech
- Agents as tools / Handoffs: Delegating to other agents for specific tasks
- Tools: Various Tools let agents take actions (functions, MCP, hosted tools)
- Guardrails: Configurable safety checks for input and output validation
- Human in the loop: Built-in mechanisms for involving humans across agent runs
- Sessions: Automatic conversation history management across agent runs
- Tracing: Built-in tracking of agent runs, allowing you to view, debug and optimize your workflows
Explore the examples directory to see the SDK in action, and read our documentation for more details.
Get started
To get started, set up your Python environment (Python 3.10 or newer required), and then install OpenAI Agents SDK package.
venv
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install openai-agents
For voice support, install with the optional voice group: pip install 'openai-agents[voice]'. For Redis session support, install with the optional redis group: pip install 'openai-agents[redis]'.
uv
If you're familiar with uv, installing the package would be even easier:
uv init
uv add openai-agents
For voice support, install with the optional voice group: uv add 'openai-agents[voice]'. For Redis session support, install with the optional redis group: uv add 'openai-agents[redis]'.
Run your first agents
The SDK supports four primary ways to run agents. Set the OPENAI_API_KEY environment variable before running any of these examples.
Run a text agent
Use a text Agent for workflows that do not need a persistent realtime connection or a sandbox workspace.
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.
(For Jupyter notebook users, see hello_world_jupyter.ipynb)
Run a sandbox agent
Use a SandboxAgent when the agent needs to inspect files, run commands, apply patches, or preserve workspace state across longer tasks.
This example uses UnixLocalSandboxClient, which is supported on macOS and Linux. On Windows, use DockerSandboxClient with the openai-agents[docker] extra or a hosted sandbox client instead; see Sandbox clients for setup details.
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)
Run a realtime agent
Use a RealtimeAgent for low-latency, server-side voice and multimodal experiences over 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())
Run a voice agent
Use a VoicePipeline to turn audio into text, run an agent workflow, and stream generated speech.
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())
Explore the examples directory to see the SDK in action, and read our documentation for more details.
Contributing
Please share bug reports and feature requests through GitHub issues. Pull requests are limited to repository collaborators; we do not accept pull requests from non-collaborators. See CONTRIBUTING.md for the contribution policy and development guide. For security vulnerabilities, follow SECURITY.md.
Acknowledgements
We'd like to acknowledge the excellent work of the open-source community, especially:
This library has these optional dependencies:
We also rely on the following tools to manage the project:
We're committed to continuing to build the Agents SDK as an open source framework so others in the community can expand on our approach.