OpenAI は 2026 年 4 月に Agents SDK の大規模アップデートを発表しました。これは Swarm 実験プロジェクト以来の最大のアップグレードです。新機能にはネイティブサンドボックス実行、モデルネイティブハーネスフレームワーク、MCP プロトコルサポートなどが含まれます。この記事では、入門から本番まで、OpenAI Agents SDK 2026 のコア機能と実践テクニックを完全にマスターできるようご案内します。
OpenAI Agents SDK とは?
OpenAI Agents SDK は、OpenAI が公式に提供する Python ライブラリで、本番級の AI エージェントアプリケーションを構築するために使用されます。シンプルながら強力な API を提供し、開発者がツール呼び出し、マルチターン対話、セキュリティ保護などの機能を備えたエージェントを迅速に作成できるようにします。
Swarm から Agents SDK への進化
2024 年、OpenAI は Swarm を実験的なマルチエージェントフレームワークとして発表しました。Swarm はマルチエージェント協力の可能性を示しましたが、本番環境では必要なセキュリティメカニズムと永続化サポートが欠けていました。
2026 年 4 月、OpenAI は全く新しい Agents SDK をリリースし、アーキテクチャを完全に再構築しました:
- ネイティブサンドボックス実行:コードが隔離された環境で実行され、悪意のある操作を防ぐ
- モデルネイティブハーネス:設定可能なメモリとオーケストレーション機能
- MCP プロトコルサポート:外部ツールエコシステムとのシームレスな統合
- エンタープライズ級セキュリティ:組み込みの Guardrails と入力検証
コア設計原則
Agents SDK は以下の設計原則に従っています:
- シンプルさ優先:最小限のコードで複雑な機能を実現
- セキュリティ第一:デフォルトでセキュリティ保護メカニズムを有効化
- 拡張可能:カスタムツールとミドルウェアをサポート
- 本番対応:内蔵のトレーシング、モニタリング、エラー処理
2026 年 4 月の重大アップデート詳細
サンドボックス実行(Sandbox Execution)
サンドボックス実行は Agents SDK 2026 の最も重要な機能です。エージェントが隔離された環境でコードを安全に実行でき、セキュリティリスクを心配する必要がありません。
コア機能:
- 隔離環境:各エージェントは独立したコンテナで実行
- ファイルシステムアクセス:一時ファイルの読み書き、依存関係のインストールをサポート
- ネットワーク制御:ネットワークアクセス権限を設定可能
- リソース制限:CPU、メモリ、実行時間を制限可能
Agents SDK は現在、複数のサンドボックスプロバイダーをサポートしています:
モデルネイティブハーネスアーキテクチャ
ハーネスは Agents SDK のコアオーケストレーションレイヤーで、エージェントの実行フローを管理します:
設定可能なメモリ(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
)
サンドボックス対応オーケストレーション:
ハーネスはサンドボックス環境をいつ起動する必要があるかをインテリジェントに判断し、リソースのライフサイクルを自動的に管理します。
MCP プロトコルのネイティブサポート
MCP(Model Context Protocol) は、Anthropic が推進するオープンプロトコルで、AI モデルと外部ツールの相互作用を標準化します。OpenAI Agents SDK 2026 は MCP をネイティブにサポートしており、这意味着你可以:
- 任意の MCP 互換ツールを使用
- Claude Code とツールエコシステムを共有
- ポータブルなエージェントアプリケーションを構築
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()
)
クイックスタート:最初のエージェントを構築
環境インストールと設定
まず、OpenAI API Key があることを確認してください。次に Agents SDK をインストールします:
pip install openai-agents
環境変数を設定:
export OPENAI_API_KEY="your-api-key-here"
Hello World 例
最もシンプルなエージェントを作成:
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.")
print(result.final_output)
出力例:
Code calls itself deep,
Infinite mirrors reflect—
Base case breaks the loop.
ツール呼び出しを追加
エージェントに実際の能力を持たせる:
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(
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)
実践:サンドボックス付きコードレビューエージェントを構築
シナリオ説明
Python コードをレビューできるエージェントを構築します。次のことができます:
- サンドボックス環境でコードを実行
- コードスタイルと潜在的な問題をチェック
- 詳細なレビューレポートを生成
完全なコード実装
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
# コードレビューエージェントを作成
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)
### 実行とテスト
上記のコードを実行すると、エージェントは:
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 キー、パスワードなどを削除
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:
# エージェント内部エラー
return f"Agent error: {e.message}"
except Exception as e:
# 未知のエラー
return f"Unexpected error: {str(e)}"
Agents SDK vs 他のフレームワーク
vs LangGraph
| 特性 | Agents SDK | LangGraph |
|---|---|---|
| 学習曲線 | 低い | 高い |
| マルチエージェントオーケストレーション | 内蔵 | 設定が必要 |
| サンドボックスサポート | ネイティブ | 統合が必要 |
| MCP サポート | ネイティブ | 適応が必要 |
| 可視化 | 内蔵トレーシング | LangSmith |
| 適用シナリオ | 迅速な開発 | 複雑なワークフロー |
選択のアドバイス:迅速なプロトタイプ開発には Agents SDK を、複雑なエンタープライズワークフローには LangGraph を選択。
vs CrewAI
CrewAI はマルチエージェント協力シナリオに特化しています:
- Agents SDK:単一エージェントの能力が強く、サンドボックス実行が優位
- CrewAI:マルチエージェントのロールプレイとタスク委任がより成熟
選択のアドバイス:ロールプレイとエージェント協力が必要な場合は CrewAI を、安全なコード実行が必要な場合は Agents SDK を選択。
vs Claude Code SDK
Anthropic の Claude Code もエージェント機能を提供しています:
- Agents SDK:OpenAI モデルと深く統合され、ツールエコシステムが豊富
- Claude Code:Claude 3.5/3.7 Sonnet との連携が最適で、コード理解力が強い
選択のアドバイス:OpenAI モデルを使用する場合は Agents SDK を、Claude モデルを使用する場合は Claude Code を選択。
本番環境デプロイのアドバイス
永続化と状態管理
本番環境ではエージェントの状態を永続化する必要があります:
from agents import Agent, Memory, RedisStorage
# Redis を状態ストレージとして使用
storage = RedisStorage(
host="localhost",
port=6379,
db=0,
password="your-password"
)
memory = Memory(
type="persistent",
storage=storage,
ttl=86400 # 24時間有効
)
agent = Agent(
name="Stateful Agent",
instructions="You remember previous conversations",
memory=memory
)
モニタリングとトレーシング
Agents SDK には内蔵のトレーシング機能があります:
from agents import Agent, Runner, Tracing
# 詳細なトレーシングを有効化
Tracing.configure(
enabled=True,
endpoint="https://api.openai.com/v1/traces",
sample_rate=1.0 # 100% サンプリング
)
# 実行時にすべてのステップが自動的に記録される
result = Runner.run_sync(agent, "Hello")
# トレーシング情報を表示
print(result.trace_id) # OpenAI プラットフォームで詳細なトレーシングを確認するために使用
コストコントロール
エージェントアプリケーションは高額な API 費用を生み出しやすいため、次のことをお勧めします:
- 適切なモデルを使用:単純なタスクには GPT-4o-mini、複雑なタスクには GPT-4o
- トークン制限を設定:
agent = Agent(
name="Cost-conscious Agent",
instructions="Be concise in your responses",
model_settings={
"max_tokens": 500,
"temperature": 0.3 # ランダム性を低減し、トークン消費を削減
}
)
- 一般的な応答をキャッシュ:
from functools import lru_cache
@lru_cache(maxsize=1000)
def cached_agent_run(prompt: str) -> str:
result = Runner.run_sync(agent, prompt)
return result.final_output
まとめと展望
コアポイントの振り返り
OpenAI Agents SDK 2026 は革命的なアップデートをもたらしました:
- サンドボックス実行:コードを安全に実行し、セキュリティリスクを排除
- MCP サポート:外部ツールエコシステムとシームレスに統合
- ハーネスアーキテクチャ:設定可能なメモリとオーケストレーション機能
- 本番対応:内蔵のセキュリティ保護とモニタリングトレーシング
近日公開予定の機能
OpenAI 公式アナウンス によると、以下の機能が近日公開予定です:
- Subagents:サブエージェントサポート、より複雑なエージェント階層を実現
- Code Mode:コード生成と編集に特化したモード
- TypeScript サポート:現在は Python のみ、TS バージョンは近日公開
学習リソース推奨
関連記事
- LangGraph マルチエージェントオーケストレーション完全ガイド
- Claude Code CLI 完全ガイド
- 2026 年の 11 大 AI エージェントフレームワーク比較
- MCP ツール実践ガイド
OpenAI Agents SDK 2026 は、本番級 AI エージェントを構築するための最良の選択肢の一つです。迅速なプロトタイプ開発であれ、エンタープライズ級アプリケーションの構築であれ、必要な機能とセキュリティを提供します。今すぐあなたの Agents SDK の旅を始めましょう!