OpenAI 於 2026 年 4 月發佈了 Agents SDK 的重大更新,這是自 Swarm 實驗專案以來的最大升級。新功能包括原生沙盒執行、模型原生執行框架、MCP 協議支援等。本文將帶你從入門到生產,全面掌握 OpenAI Agents SDK 2026 的核心特性與實戰技巧。
什麼是 OpenAI Agents SDK?
OpenAI Agents SDK 是 OpenAI 官方推出的 Python 庫,用於構建生產級的 AI Agent 應用。它提供了一套簡潔而強大的 API,讓開發者能夠快速建立具備工具呼叫、多輪對話、安全防護等能力的智慧體。
從 Swarm 到 Agents SDK 的演進
2024 年,OpenAI 發佈了 Swarm 作為實驗性多智慧體框架。雖然 Swarm 展示了多 Agent 協作的可能性,但在生產環境中缺乏必要的安全機制和持久化支援。
2026 年 4 月,OpenAI 推出了全新的 Agents SDK,徹底重構了架構:
- 原生沙盒執行:程式碼在隔離環境中執行,防止惡意操作
- 模型原生 Harness:配置化記憶和編排能力
- MCP 協議支援:與外部工具生態無縫整合
- 企業級安全:內建 Guardrails 和輸入驗證
核心設計原則
Agents SDK 遵循以下設計原則:
- 簡潔優先:用最少的程式碼實現複雜功能
- 安全第一:預設啟用安全防護機制
- 可擴充套件:支援自訂工具和中間件
- 生產就緒:內建追蹤、監控和錯誤處理
2026 年 4 月重大更新詳解
沙盒執行(Sandbox Execution)
沙盒執行是 Agents SDK 2026 最重磅的功能。它允許 Agent 在隔離環境中安全地執行程式碼,無需擔心安全風險。
核心特性:
- 隔離環境:每個 Agent 執行在獨立的容器中
- 檔案系統存取:可讀寫臨時檔案,支援依賴安裝
- 網路控制:可配置網路存取權限
- 資源限制:CPU、記憶體、執行時間均可限制
Agents SDK 目前支援多家沙盒提供商:
模型原生 Harness 架構
Harness 是 Agents SDK 的核心編排層,它負責管理 Agent 的執行流程:
配置化記憶(Configurable Memory):
from agents import Agent, Runner, Memory
# 配置持久化記憶
memory = Memory(
type="persistent",
storage="redis", # 支援 redis、postgres、sqlite
ttl=3600 # 記憶過期時間
)
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant",
memory=memory
)
沙盒感知編排:
Harness 能夠智慧判斷何時需要啟動沙盒環境,自動管理資源生命週期。
MCP 協議原生支援
MCP(Model Context Protocol) 是 Anthropic 推出的開放協議,用於標準化 AI 模型與外部工具的互動。OpenAI Agents SDK 2026 原生支援 MCP,這意味著你可以:
- 使用任何相容 MCP 的工具
- 與 Claude Code 共享工具生態
- 構建可移植的 Agent 應用
from agents import Agent, MCPTools
# 連線到 MCP 伺服器
mcp_tools = MCPTools.from_server("http://localhost:3000/sse")
agent = Agent(
name="MCP Agent",
instructions="Use available tools to help the user",
tools=mcp_tools.get_tools()
)
快速入門:構建你的第一個 Agent
環境安裝與配置
首先,確保你有一個 OpenAI API Key。然後安裝 Agents SDK:
pip install openai-agents
設定環境變數:
export OPENAI_API_KEY="your-api-key-here"
Hello World 範例
建立一個最簡單的 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.")
print(result.final_output)
輸出範例:
Code calls itself deep,
Infinite mirrors reflect—
Base case breaks the loop.
新增工具呼叫
讓 Agent 具備實際能力:
from agents import Agent, Runner, function_tool
from pydantic import BaseModel
# 定義工具參數
class WeatherInput(BaseModel):
city: str
unit: str = "celsius"
@function_tool
async def get_weather(input: WeatherInput) -> str:
"""Get weather information for a city."""
# 這裡可以呼叫真實的天氣 API
return f"The weather in {input.city} is 22°{input.unit[0].upper()}"
# 建立帶工具的 Agent
agent = Agent(
name="Weather Assistant",
instructions="You help users with weather information.",
tools=[get_weather]
)
# 執行
result = Runner.run_sync(agent, "What's the weather like in Tokyo?")
print(result.final_output)
實戰:構建一個帶沙盒的程式碼審查 Agent
場景描述
我們將構建一個能夠審查 Python 程式碼的 Agent,它可以:
- 在沙盒環境中執行程式碼
- 檢查程式碼風格和潛在問題
- 生成詳細的審查報告
完整程式碼實現
import asyncio
from agents import Agent, Runner, SandboxAgent, function_tool
from pydantic import BaseModel
from typing import List
class CodeReviewInput(BaseModel):
code: str
filename: str = "script.py"
class CodeReviewResult(BaseModel):
issues: List[str]
suggestions: List[str]
execution_output: str
passed: bool
@function_tool
async def run_code_in_sandbox(input: CodeReviewInput) -> str:
"""Execute Python code in a secure sandbox environment."""
# 使用 SandboxAgent 執行程式碼
sandbox = SandboxAgent(
provider="e2b", # 使用 E2B 沙盒
timeout=30, # 30 秒超時
memory_limit="512mb",
cpu_limit=1.0
)
# 寫入程式碼檔案
await sandbox.write_file(f"/home/user/{input.filename}", input.code)
# 執行程式碼
result = await sandbox.execute(
f"python /home/user/{input.filename}",
env={"PYTHONUNBUFFERED": "1"}
)
return result.stdout + result.stderr
@function_tool
async def analyze_code_style(code: str) -> List[str]:
"""Analyze code style using pylint in sandbox."""
sandbox = SandboxAgent(provider="e2b")
# 安裝 pylint
await sandbox.execute("pip install pylint -q")
# 寫入程式碼
await sandbox.write_file("/home/user/temp.py", code)
# 執行 pylint
result = await sandbox.execute("pylint /home/user/temp.py --output-format=text")
issues = []
for line in result.stdout.split("\n"):
if ":" in line and any(severity in line for severity in ["E", "W", "C", "R"]):
issues.append(line.strip())
return issues
# 建立程式碼審查 Agent
code_reviewer = Agent(
name="Code Reviewer",
instructions="""You are an expert Python code reviewer. Your task is to:
1. Run the code in a sandbox to check for runtime errors
2. Analyze code style and best practices
3. Provide actionable suggestions for improvement
4. Generate a comprehensive review report
Be thorough but constructive in your feedback.""",
tools=[run_code_in_sandbox, analyze_code_style],
model="gpt-4o" # 使用更強的模型進行程式碼分析
)
async def review_code(user_code: str, filename: str = "script.py"):
"""Review code using the Code Reviewer Agent."""
prompt = f"""Please review the following Python code:
Filename: {filename}
```python
{user_code}
Please:
- Run the code and report any execution errors
- Check code style issues
- Provide specific suggestions for improvement
- Give an overall assessment (PASS or FAIL)
Format your response as a structured code review report."""
result = await Runner.run(code_reviewer, prompt)
return result.final_output
範例程式碼進行審查
sample_code = ''' def calculate_sum(numbers): total = 0 for n in numbers: total = total + n return total
result = calculate_sum([1, 2, 3, 4, 5]) print(f”Sum: {result}”) '''
執行審查
if name == “main”: review = asyncio.run(review_code(sample_code, “calculate_sum.py”)) print(review)
### 執行與測試
執行上述程式碼,Agent 將:
1. 在 E2B 沙盒中執行程式碼
2. 使用 pylint 檢查程式碼風格
3. 生成包含執行結果、風格問題和改進建議的完整報告
**輸出範例**:
Code Review Report for calculate_sum.py
Execution Results ✅
- Status: Success
- Output: Sum: 15
- Runtime: 0.23s
Style Analysis ⚠️
- Missing module docstring
- Function lacks type hints
- Variable ‘total’ could use augmented assignment (total += n)
Suggestions for Improvement
- Add type hints:
def calculate_sum(numbers: List[int]) -> int: - Use built-in
sum()function for simplicity - Add docstring explaining the function’s purpose
- Consider handling empty list edge case
Overall Assessment: PASS with recommendations
## 安全防護與最佳實踐
### Guardrails 配置
Agents SDK 提供多層安全防護:
```python
from agents import Agent, Guardrails, InputGuardrail, OutputGuardrail
# 輸入驗證
def validate_input(context) -> bool:
"""Check if input is safe to process."""
forbidden_patterns = ["rm -rf", "exec(", "eval("]
return not any(pattern in context.user_input for pattern in forbidden_patterns)
# 輸出過濾
def filter_output(response) -> str:
"""Filter sensitive information from output."""
# 移除可能的 API keys、密碼等
import re
response = re.sub(r'sk-[a-zA-Z0-9]{48}', '[API_KEY_REDACTED]', response)
return response
agent = Agent(
name="Safe Agent",
instructions="You are a helpful assistant",
guardrails=Guardrails(
input_guardrails=[InputGuardrail(check=validate_input)],
output_guardrails=[OutputGuardrail(filter=filter_output)]
)
)
輸入驗證
使用 Pydantic 進行嚴格的輸入驗證:
from pydantic import BaseModel, Field, validator
class SafeCodeInput(BaseModel):
code: str = Field(..., max_length=5000)
language: str = Field(default="python", regex="^(python|javascript|bash)$")
@validator('code')
def check_forbidden_patterns(cls, v):
forbidden = ['import os', 'import subprocess', '__import__']
for pattern in forbidden:
if pattern in v.lower():
raise ValueError(f"Forbidden pattern detected: {pattern}")
return v
錯誤處理
生產環境中必須做好錯誤處理:
from agents import Agent, Runner
from agents.exceptions import AgentError, ToolError, SandboxError
async def safe_run(agent: Agent, prompt: str):
try:
result = await Runner.run(agent, prompt)
return result.final_output
except SandboxError as e:
# 沙盒執行失敗
return f"Sandbox execution failed: {e.message}"
except ToolError as e:
# 工具呼叫失敗
return f"Tool execution error: {e.message}"
except AgentError as e:
# Agent 內部錯誤
return f"Agent error: {e.message}"
except Exception as e:
# 未知錯誤
return f"Unexpected error: {str(e)}"
Agents SDK vs 其他框架
vs LangGraph
| 特性 | Agents SDK | LangGraph |
|---|---|---|
| 學習曲線 | 低 | 高 |
| 多 Agent 編排 | 內建 | 需配置 |
| 沙盒支援 | 原生 | 需整合 |
| MCP 支援 | 原生 | 需適配 |
| 視覺化 | 內建追蹤 | LangSmith |
| 適用場景 | 快速開發 | 複雜工作流 |
選擇建議:快速原型開發選 Agents SDK,複雜企業工作流選 LangGraph。
vs CrewAI
CrewAI 專注於多 Agent 協作場景:
- Agents SDK:單 Agent 能力強,沙盒執行是優勢
- CrewAI:多 Agent 角色扮演和任務委託更成熟
選擇建議:需要角色扮演和 Agent 協作選 CrewAI,需要安全程式碼執行選 Agents SDK。
vs Claude Code SDK
Anthropic 的 Claude Code 也提供 Agent 能力:
- Agents SDK:與 OpenAI 模型深度整合,工具生態豐富
- Claude Code:與 Claude 3.5/3.7 Sonnet 配合最佳,程式碼理解能力強
選擇建議:使用 OpenAI 模型選 Agents SDK,使用 Claude 模型選 Claude Code。
生產環境部署建議
持久化與狀態管理
生產環境中需要持久化 Agent 狀態:
from agents import Agent, Memory, RedisStorage
# 使用 Redis 作為狀態儲存
storage = RedisStorage(
host="localhost",
port=6379,
db=0,
password="your-password"
)