OpenAI Agents SDK 完全入門ガイド【2026年版】
— 初めてのAIエージェント構築
OpenAI Agents SDKは、AIエージェントを本番環境で動かすための公式フレームワークです。本記事では背景から主要コンセプト、実際のPythonコード例まで、ゼロから理解できるよう徹底解説します。
1. OpenAI Agents SDK とは?
2025年3月、OpenAIはAgents SDK(旧称:Swarm)を正式にリリースしました。これはOpenAIが提供するオープンソースのPythonライブラリで、AIエージェントを構築・実行・オーケストレーションするための公式ツールキットです。
なぜ今これほど注目されているのでしょうか?理由は明確です。これまでの「ChatGPT」のような単一応答型AIとは異なり、エージェントは複数ステップの推論・ツール呼び出し・自律的な意思決定を繰り返して複雑なタスクをこなせます。2026年時点で、エージェントは単なる研究対象ではなく、実務のワークフローに組み込まれる技術へと進化しました。
OpenAI Agents SDKの特徴をまとめると:
- 軽量設計:コアとなる抽象化は最小限。学習コストが低く、既存のPythonコードとシームレスに統合できる
- OpenAI公式サポート:Function Calling、ファイル検索、コードインタープリターなどOpenAIネイティブ機能との深い連携
- 本番環境対応:トレーシング・ガードレール・ハンドオフなど、実運用に必要な機能を標準装備
- マルチエージェント対応:複数のエージェントを協調動作させるオーケストレーションを簡潔に記述可能
📦 インストール:pip install openai-agents で即座に使えます(Python 3.9以上が必要)。
2. 旧 Assistants API との違い
OpenAIにはすでにAssistants APIが存在していました。なぜ新しいSDKが必要なのか?両者の違いを整理します。
| 比較項目 | Assistants API | Agents SDK |
|---|---|---|
| アーキテクチャ | サーバー側ステート管理(OpenAIがThreadを保持) | クライアント側制御(開発者がループを管理) |
| 柔軟性 | OpenAI提供のツール(File Search, Code Interpreter)に限定 | 任意のPython関数をツールとして登録可能 |
| マルチエージェント | 非対応(単一エージェントのみ) | Handoff機能で複数エージェントを連携 |
| デバッグ | ブラックボックス的。内部ループが見えにくい | フルコントロール。各ステップをログ・トレース可能 |
| コスト予測 | Thread保持のためコスト計算が複雑 | 各API呼び出しが透明。コスト制御が容易 |
| モデル縛り | OpenAIモデルのみ | OpenAI推奨だが、LiteLLM経由で他モデルも利用可 |
一言でまとめると:Assistants APIは手軽だが不透明、Agents SDKは手間がかかるが透明で柔軟。複雑なエージェントロジックやマルチエージェント構成には、Agents SDKが圧倒的に適しています。
3. 主要コンセプト:Agent / Tool / Handoff / Guardrail
Agents SDKは4つのコアコンセプトを中心に設計されています。それぞれを具体的に理解しましょう。
3-1. Agent(エージェント)
Agentは、特定の目的を持ったAIアシスタントです。名前・指示(システムプロンプト)・利用できるツール・モデルを設定して定義します。エージェントは自律的にループを回し、ツール呼び出しと応答生成を繰り返して最終結果を出力します。
from agents import Agent
agent = Agent(
name="リサーチアシスタント",
instructions="""あなたは優秀なリサーチアシスタントです。
ユーザーの質問に対して、正確で詳細な情報を提供してください。
不明な点は率直に伝え、推測と事実を明確に区別してください。""",
model="gpt-4o",
)
3-2. Tool(ツール)
Toolは、エージェントが呼び出せる機能です。Pythonの関数に@function_toolデコレーターを付けるだけで登録できます。型ヒントとdocstringがそのままOpenAI Function CallingのスキーマとなるのがAgents SDKの優れた設計です。
from agents import function_tool
@function_tool
def search_web(query: str) -> str:
"""指定されたキーワードでウェブを検索し、上位5件の要約を返す。
Args:
query: 検索クエリ文字列
Returns:
検索結果の要約テキスト
"""
# 実際の実装ではSerpAPIなどを呼び出す
return f"'{query}' の検索結果: [結果1, 結果2, ...]"
@function_tool
def calculate(expression: str) -> str:
"""数式を計算して結果を返す。安全な評価のみ実行する。
Args:
expression: 計算したい数式 (例: "2 + 3 * 4")
Returns:
計算結果の文字列
"""
try:
result = eval(expression, {"__builtins__": {}}, {})
return str(result)
except Exception as e:
return f"計算エラー: {e}"
3-3. Handoff(ハンドオフ)
Handoffは、あるエージェントが別のエージェントにタスクを委譲する仕組みです。これにより、専門領域ごとに特化したエージェントを組み合わせたマルチエージェントシステムを構築できます。Handoffが発生すると、会話コンテキストはそのまま引き継がれます。
from agents import Agent
# 専門エージェントを定義
billing_agent = Agent(
name="請求サポートエージェント",
instructions="請求・支払い・サブスクリプションに関する問い合わせを専門的に処理します。",
model="gpt-4o-mini",
)
tech_agent = Agent(
name="技術サポートエージェント",
instructions="技術的な問題、バグ報告、機能リクエストを処理します。",
model="gpt-4o",
)
# トリアージエージェント(振り分け担当)
triage_agent = Agent(
name="カスタマーサポートトリアージ",
instructions="""ユーザーの問い合わせ内容を分析し、適切な専門エージェントに転送してください。
- 請求・支払い関連 → billing_agent
- 技術的な問題 → tech_agent
転送前に必ず理由を簡潔に説明してください。""",
handoffs=[billing_agent, tech_agent],
model="gpt-4o-mini",
)
3-4. Guardrail(ガードレール)
Guardrailは、エージェントの入出力を検証・フィルタリングする安全機構です。入力ガードレール(Input Guardrail)と出力ガードレール(Output Guardrail)の2種類があります。有害なリクエストのブロック、PII(個人識別情報)の除去、コンテンツポリシーの強制などに活用します。
from agents import Agent, GuardrailFunctionOutput, input_guardrail
from pydantic import BaseModel
class SafetyCheck(BaseModel):
is_safe: bool
reason: str
@input_guardrail
async def safety_guardrail(ctx, agent, input_text):
"""不適切なコンテンツや有害なリクエストをブロックする"""
# ここでは簡易的なキーワードチェック(実際はLLMで分類するのが望ましい)
harmful_keywords = ["ハッキング方法", "爆発物", "不正アクセス"]
for keyword in harmful_keywords:
if keyword in input_text:
return GuardrailFunctionOutput(
output_info=SafetyCheck(is_safe=False, reason=f"有害なキーワードを検出: {keyword}"),
tripwire_triggered=True, # エージェントの実行を停止
)
return GuardrailFunctionOutput(
output_info=SafetyCheck(is_safe=True, reason="安全なリクエストです"),
tripwire_triggered=False,
)
safe_agent = Agent(
name="安全エージェント",
instructions="ユーザーの質問に丁寧に答えます。",
input_guardrails=[safety_guardrail],
)
4. クイックスタート:最初のエージェントを5分で作る
それでは実際に動くエージェントを作りましょう。前提として以下が必要です:
- Python 3.9以上
- OpenAI APIキー(環境変数
OPENAI_API_KEYに設定)
Step 1: インストール
pip install openai-agents
Step 2: 環境変数の設定
# Linux/Mac
export OPENAI_API_KEY="sk-proj-xxxxxxxxxxxxxxxx"
# Windows (PowerShell)
$env:OPENAI_API_KEY = "sk-proj-xxxxxxxxxxxxxxxx"
Step 3: 最初のエージェントを作成・実行
# hello_agent.py
import asyncio
from agents import Agent, Runner
# エージェントを定義
agent = Agent(
name="HelloAgent",
instructions="""あなたは親切なアシスタントです。
ユーザーの質問に日本語で、簡潔かつ正確に答えてください。
技術的な質問には具体的なコード例も提供してください。""",
model="gpt-4o-mini", # コスト削減にはmini版がおすすめ
)
async def main():
# Runner.run() でエージェントを実行
result = await Runner.run(
agent,
input="Pythonでフィボナッチ数列を生成するコードを教えてください",
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
Step 4: 実行
python hello_agent.py
出力例:
Pythonでフィボナッチ数列を生成するコード例です:
def fibonacci(n):
"""n番目までのフィボナッチ数列をリストで返す"""
if n <= 0:
return []
elif n == 1:
return [0]
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
print(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Step 5: ツール付きエージェント
次に、実際にツールを使うエージェントを作ります。天気情報を返す(モック)ツールを例に示します。
# tool_agent.py
import asyncio
from agents import Agent, Runner, function_tool
@function_tool
def get_weather(city: str) -> str:
"""指定した都市の現在の天気情報を取得する。
Args:
city: 都市名(日本語または英語)
Returns:
天気情報の文字列
"""
# 実際はOpenWeatherMap APIなどを呼び出す
weather_data = {
"東京": "晴れ、気温22°C、湿度58%",
"大阪": "曇り、気温20°C、湿度65%",
"札幌": "雪、気温-2°C、湿度80%",
}
return weather_data.get(city, f"{city}の天気データが見つかりませんでした。")
@function_tool
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""通貨換算を行う。
Args:
amount: 換算する金額
from_currency: 元の通貨コード (例: "USD", "JPY")
to_currency: 換算後の通貨コード
Returns:
換算結果の文字列
"""
# 簡易的なレート(実際はAPIから取得)
rates = {"USD_JPY": 150.5, "JPY_USD": 0.0066, "EUR_JPY": 163.2}
key = f"{from_currency}_{to_currency}"
rate = rates.get(key, 1.0)
result = amount * rate
return f"{amount} {from_currency} = {result:.2f} {to_currency}"
assistant = Agent(
name="マルチツールアシスタント",
instructions="""あなたは天気情報と通貨換算ができるアシスタントです。
ユーザーの依頼に応じて適切なツールを呼び出してください。
ツールの結果を分かりやすく説明してください。""",
tools=[get_weather, convert_currency],
model="gpt-4o",
)
async def main():
result = await Runner.run(
assistant,
input="東京の天気を教えて。それと100ドルは何円ですか?",
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
💡 ポイント:Agents SDKは関数のdocstringと型ヒントから自動的にOpenAI Function CallingのJSONスキーマを生成します。これにより、ボイラープレートコードが大幅に削減されます。
5. 実用例
5-1. ウェブ検索エージェント
OpenAIが公式提供しているWebSearchTool(または自前のSerpAPI統合)を使った、本格的なリサーチエージェントの例です。
# web_research_agent.py
import asyncio
from agents import Agent, Runner, WebSearchTool
research_agent = Agent(
name="ウェブリサーチエージェント",
instructions="""あなたは優秀なリサーチアナリストです。
以下の手順でタスクを実行してください:
1. ユーザーのリクエストを分析し、必要な検索クエリを決定する
2. WebSearchToolを使って複数の視点から情報を収集する(3〜5回の検索)
3. 収集した情報を整理・分析し、矛盾点を特定する
4. 日本語で、構造化されたレポート(要約・詳細・参考情報)として回答する
5. 情報の信頼性に不確かさがある場合は必ず明示する""",
tools=[WebSearchTool()],
model="gpt-4o",
)
async def main():
query = "2026年のOpenAI Agents SDKの主な新機能と、LangChainとの比較を教えてください"
print(f"リサーチ開始: {query}\n")
result = await Runner.run(
research_agent,
input=query,
)
print("=== リサーチ結果 ===")
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
5-2. コードレビューエージェント
コードを自動でレビューし、改善提案を行う実用的なエージェントです。セキュリティ・パフォーマンス・可読性の3つの観点からレビューします。
# code_review_agent.py
import asyncio
from agents import Agent, Runner, function_tool
from typing import Literal
@function_tool
def analyze_code_complexity(code: str) -> str:
"""コードの複雑度を分析する(行数、関数数、ネスト深さ)。
Args:
code: 分析対象のPythonコード
Returns:
複雑度の分析結果
"""
lines = code.split('\n')
func_count = sum(1 for line in lines if line.strip().startswith('def '))
class_count = sum(1 for line in lines if line.strip().startswith('class '))
max_indent = max((len(line) - len(line.lstrip())) // 4
for line in lines if line.strip()) if lines else 0
return f"""コード複雑度分析:
- 総行数: {len(lines)}行
- 関数数: {func_count}個
- クラス数: {class_count}個
- 最大インデント深さ: {max_indent}レベル
- 評価: {'複雑度高(リファクタリング推奨)' if max_indent > 4 or func_count > 20 else '適切な複雑度'}"""
@function_tool
def check_security_issues(code: str) -> str:
"""コードの一般的なセキュリティ問題をチェックする。
Args:
code: 検査対象のPythonコード
Returns:
セキュリティ問題のリスト
"""
issues = []
if 'eval(' in code and '__builtins__' not in code:
issues.append("⚠️ 安全でない eval() の使用が検出されました")
if 'exec(' in code:
issues.append("⚠️ exec() の使用 — 入力を必ずサニタイズしてください")
if 'os.system(' in code:
issues.append("⚠️ os.system() は subprocess に置き換えることを推奨します")
if 'password' in code.lower() and ('=' in code) and ('"' in code or "'" in code):
issues.append("🔴 ハードコードされたパスワードの可能性があります")
if 'pickle.loads(' in code:
issues.append("⚠️ pickle.loads() は信頼できないデータには使用しないでください")
return '\n'.join(issues) if issues else "✅ 重大なセキュリティ問題は検出されませんでした"
code_reviewer = Agent(
name="コードレビューエージェント",
instructions="""あなたはベテランのPythonエンジニアです。
提供されたコードを以下の観点でレビューしてください:
1. **セキュリティ**: check_security_issues ツールを使用してセキュリティ問題を検出
2. **複雑度**: analyze_code_complexity ツールで複雑度を測定
3. **コードスタイル**: PEP 8準拠、命名規則、コメントの適切さ
4. **パフォーマンス**: 非効率なアルゴリズム、不必要なループ、メモリの問題
5. **改善提案**: 具体的なコードで改善案を提示
レビュー結果は以下の形式でまとめてください:
- 総合評価(A〜F)
- 重要度別の問題リスト(Critical / Warning / Info)
- 改善後のコード例(必要な場合)""",
tools=[analyze_code_complexity, check_security_issues],
model="gpt-4o",
)
async def review_code(code: str):
result = await Runner.run(
code_reviewer,
input=f"以下のコードをレビューしてください:\n\n```python\n{code}\n```",
)
return result.final_output
async def main():
sample_code = '''
import os
import pickle
def process_user_data(user_id, data):
# ユーザーデータを処理
password = "admin123" # TODO: 後で修正
query = f"SELECT * FROM users WHERE id = {user_id}"
result = eval(data["formula"])
with open(f"cache/{user_id}.pkl", "rb") as f:
cached = pickle.loads(f.read())
for i in range(len(cached)):
for j in range(len(cached)):
if cached[i] == cached[j]:
os.system(f"echo {cached[i]}")
return result
'''
print("コードレビュー開始...\n")
review = await review_code(sample_code)
print(review)
if __name__ == "__main__":
asyncio.run(main())
⚠️ 注意:上のサンプルコードはレビュー対象として意図的に問題を含んでいます。実際のプロダクションコードには使用しないでください。
5-3. マルチエージェント:カスタマーサポートシステム
Handoff機能を活用した、実用的なマルチエージェントカスタマーサポートシステムです。
# multi_agent_support.py
import asyncio
from agents import Agent, Runner, handoff, function_tool
@function_tool
def lookup_order(order_id: str) -> str:
"""注文IDから注文情報を取得する。"""
# 実際はDBを参照
orders = {
"ORD-001": "商品: ノートPC, 金額: 150,000円, 状態: 発送済み",
"ORD-002": "商品: マウス, 金額: 3,000円, 状態: 処理中",
}
return orders.get(order_id, "注文が見つかりません")
@function_tool
def process_refund(order_id: str, reason: str) -> str:
"""返金処理を開始する。"""
return f"注文 {order_id} の返金処理を開始しました。理由: {reason}。3〜5営業日でご返金します。"
@function_tool
def create_bug_report(title: str, description: str, severity: str) -> str:
"""バグレポートを作成する。"""
ticket_id = f"BUG-{hash(title) % 10000:04d}"
return f"バグレポート作成完了。チケットID: {ticket_id}, 重要度: {severity}"
# 専門エージェント
order_agent = Agent(
name="注文サポートエージェント",
instructions="""注文・配送・返金に関する問い合わせを処理します。
lookup_order で注文情報を確認し、必要に応じて process_refund で返金処理を実行してください。
常に注文IDを確認してから回答してください。""",
tools=[lookup_order, process_refund],
model="gpt-4o-mini",
)
tech_support_agent = Agent(
name="技術サポートエージェント",
instructions="""技術的な問題を処理します。
問題が再現可能なバグの場合は create_bug_report でレポートを作成してください。
トラブルシューティングの手順を段階的に説明してください。""",
tools=[create_bug_report],
model="gpt-4o",
)
# トリアージ(振り分け)エージェント
triage_agent = Agent(
name="サポートトリアージ",
instructions="""カスタマーサポートの問い合わせを受け付け、内容に応じて適切な専門チームに転送します。
転送ルール:
- 注文・支払い・返金に関する問い合わせ → order_agent に転送
- 技術的な問題・バグ・機能リクエスト → tech_support_agent に転送
- 転送前に必ず「~についてお調べします。担当チームにご連絡いたします。」と伝えること
- 転送後は担当エージェントが対応します
一般的な挨拶や情報提供は自分で対応してください。""",
handoffs=[order_agent, tech_support_agent],
model="gpt-4o-mini",
)
async def main():
queries = [
"注文ORD-001の状況を教えてください",
"アプリが起動しません。Windowsを再起動しても直りません",
"先月の請求が間違っているので返金してほしい(注文番号:ORD-002)",
]
for query in queries:
print(f"\n{'='*50}")
print(f"ユーザー: {query}")
print(f"{'='*50}")
result = await Runner.run(triage_agent, input=query)
print(f"サポート: {result.final_output}")
if __name__ == "__main__":
asyncio.run(main())
6. 他フレームワーク(LangChain / CrewAI)との比較
2026年時点で主要なエージェントフレームワークを比較します。
| 比較項目 | OpenAI Agents SDK | LangChain / LangGraph | CrewAI |
|---|---|---|---|
| 学習コスト | ⭐⭐⭐⭐⭐ 最も低い | ⭐⭐⭐ 中程度(LCEL/Graphの習得が必要) | ⭐⭐⭐⭐ 低め(YAML設定) |
| OpenAIとの統合 | ⭐⭐⭐⭐⭐ ネイティブ最高品質 | ⭐⭐⭐⭐ 優れた統合 | ⭐⭐⭐⭐ 良好 |
| マルチLLM対応 | ⭐⭐⭐ LiteLLM経由で対応 | ⭐⭐⭐⭐⭐ 最多のLLM統合 | ⭐⭐⭐⭐ 幅広く対応 |
| マルチエージェント | ⭐⭐⭐⭐⭐ Handoffで簡潔 | ⭐⭐⭐⭐ LangGraphで強力 | ⭐⭐⭐⭐⭐ コアの強み |
| 本番運用 | ⭐⭐⭐⭐ トレーシング標準装備 | ⭐⭐⭐⭐⭐ LangSmithで業界最強 | ⭐⭐⭐ まだ発展途上 |
| コミュニティ | ⭐⭐⭐⭐ 急成長中 | ⭐⭐⭐⭐⭐ 最大のコミュニティ | ⭐⭐⭐⭐ 活発 |
| ベストな用途 | OpenAI中心・シンプルなマルチエージェント | 複雑なRAG・マルチLLM・本番大規模 | 役割分担明確なマルチエージェント |
どれを選ぶべきか?
- OpenAI Agents SDK:OpenAI APIを主に使い、シンプルに始めたい場合。学習コストが最低で、公式サポートが手厚い
- LangChain/LangGraph:複数のLLMを使い分けたい、RAGパイプラインが必要、本番環境でのオブザーバビリティが重要な場合
- CrewAI:それぞれ明確な役割を持つ複数のエージェントが協調して作業する(例:ライター・エディター・レビュアーが分業)場合
💬 現実的なアドバイス:フレームワーク選定に迷いすぎないでください。OpenAI Agents SDKで始めて、LangGraph/CrewAIの機能が本当に必要になったら移行する——これが2026年の現実的なアプローチです。
7. まとめ・次のステップ
OpenAI Agents SDKは、AIエージェント開発の民主化を加速する重要なツールです。本記事で解説した内容を振り返ります:
- ✅ Agent:目的・指示・ツール・モデルを持つAIアシスタント
- ✅ Tool:
@function_toolデコレーターで簡単に定義できる拡張機能 - ✅ Handoff:専門エージェントへの委譲でマルチエージェントを実現
- ✅ Guardrail:入出力の安全性を保証するフィルタリング機構
次のステップとして以下をお勧めします:
- 本記事のコード例を実際に動かしてみる(
pip install openai-agentsから5分で動く!) - 公式ドキュメントでStreaming・トレーシング・Structured Outputsを学ぶ
- 自分のユースケースに合わせてツールを実装し、実際のAPIを組み合わせる
- AgDexのエージェントツールカタログで補完的なライブラリを発見する
🔍 AIエージェント関連の300以上のツール・フレームワーク・プラットフォームは AgDexディレクトリ で探せます。用途・言語・価格帯でフィルタリングできます。
OpenAI Agents SDK: The Complete Beginner's Guide (2026)
— Build Your First AI Agent
OpenAI Agents SDK is the official Python framework for building, running, and orchestrating AI agents in production. This guide takes you from zero to a working multi-agent system with real Python code examples.
1. What Is OpenAI Agents SDK?
Released officially in March 2025 (originally as "Swarm"), the OpenAI Agents SDK is an open-source Python library that provides the official, first-party toolkit for building AI agents. Unlike the simple "question → answer" pattern of ChatGPT, agents can perform multi-step reasoning, tool calls, and autonomous decision-making to complete complex tasks.
By 2026, agents have moved from research curiosity to production reality. The Agents SDK gives you:
- Minimal abstraction: Low learning curve, integrates seamlessly with existing Python code
- Native OpenAI features: Function Calling, File Search, Code Interpreter — all first-class citizens
- Production-ready primitives: Tracing, guardrails, and handoffs are built in
- Multi-agent orchestration: Coordinate multiple specialized agents with clean, readable code
📦 Install: pip install openai-agents (requires Python 3.9+)
2. Assistants API vs Agents SDK
OpenAI already had the Assistants API. Why a new SDK? The key differences:
- Control: Assistants API manages state server-side (OpenAI holds the Thread). Agents SDK gives you full client-side control of the run loop.
- Flexibility: Assistants API limits you to OpenAI's built-in tools. Agents SDK lets you register any Python function as a tool.
- Multi-agent: Assistants API is single-agent only. Agents SDK has first-class Handoff support for multi-agent architectures.
- Debuggability: Assistants API is a black box. Agents SDK exposes every step for logging and tracing.
Rule of thumb: Use Assistants API for simple single-agent tasks where you want OpenAI to manage state. Use Agents SDK for complex workflows, multi-agent systems, or when you need full control.
3. Core Concepts: Agent / Tool / Handoff / Guardrail
Agent
An Agent is an AI assistant with a defined purpose. You configure its name, instructions (system prompt), tools, and model. Agents autonomously loop through tool calls and reasoning until they reach a final answer.
from agents import Agent
agent = Agent(
name="ResearchAssistant",
instructions="You are a thorough research assistant. Provide accurate, detailed information with sources when possible.",
model="gpt-4o",
)
Tool
A Tool is any Python function decorated with @function_tool. Type hints and docstrings automatically become the OpenAI Function Calling schema — no manual JSON schema required.
from agents import function_tool
@function_tool
def search_web(query: str) -> str:
"""Search the web for the given query and return top results.
Args:
query: Search query string
Returns:
Summary of top search results
"""
# In production, call SerpAPI, Tavily, or similar
return f"Search results for '{query}': [result1, result2, ...]"
Handoff
A Handoff transfers control from one agent to another, passing the full conversation context. This enables sophisticated multi-agent pipelines where specialists handle their domain.
from agents import Agent
billing_agent = Agent(
name="BillingAgent",
instructions="Handle billing, payments, and subscription queries.",
model="gpt-4o-mini",
)
triage_agent = Agent(
name="TriageAgent",
instructions="Route customer queries to the appropriate specialist. Billing questions → billing_agent.",
handoffs=[billing_agent],
model="gpt-4o-mini",
)
Guardrail
A Guardrail validates inputs and outputs, allowing you to block harmful requests, strip PII, or enforce content policies before they reach (or leave) your agent.
from agents import input_guardrail, GuardrailFunctionOutput
from pydantic import BaseModel
class SafetyResult(BaseModel):
is_safe: bool
reason: str
@input_guardrail
async def content_safety_guardrail(ctx, agent, input_text):
"""Block obviously harmful requests."""
if any(kw in input_text.lower() for kw in ["hack", "exploit", "malware"]):
return GuardrailFunctionOutput(
output_info=SafetyResult(is_safe=False, reason="Potentially harmful request"),
tripwire_triggered=True,
)
return GuardrailFunctionOutput(
output_info=SafetyResult(is_safe=True, reason="Safe"),
tripwire_triggered=False,
)
4. Quickstart: Your First Agent in 5 Minutes
# Install
# pip install openai-agents
# Set API key
# export OPENAI_API_KEY="sk-proj-..."
import asyncio
from agents import Agent, Runner, function_tool
@function_tool
def get_weather(city: str) -> str:
"""Get current weather for a city.
Args:
city: City name
Returns:
Weather description
"""
# Replace with real API call
return f"Weather in {city}: Sunny, 22°C, humidity 60%"
assistant = Agent(
name="WeatherBot",
instructions="You are a helpful weather assistant. Use the get_weather tool to answer weather questions.",
tools=[get_weather],
model="gpt-4o-mini",
)
async def main():
result = await Runner.run(assistant, input="What's the weather in Tokyo?")
print(result.final_output)
asyncio.run(main())
5. Practical Examples
Web Research Agent
Using OpenAI's built-in WebSearchTool for real-time information retrieval:
from agents import Agent, Runner, WebSearchTool
import asyncio
research_agent = Agent(
name="WebResearcher",
instructions="""You are a thorough research analyst.
1. Break down complex questions into 3-5 targeted searches
2. Cross-reference information from multiple sources
3. Synthesize findings into a structured report
4. Always cite uncertainty when present""",
tools=[WebSearchTool()],
model="gpt-4o",
)
async def main():
result = await Runner.run(
research_agent,
input="What are the key differences between OpenAI Agents SDK and LangGraph in 2026?",
)
print(result.final_output)
asyncio.run(main())
Code Review Agent
from agents import Agent, Runner, function_tool
import asyncio
@function_tool
def check_security(code: str) -> str:
"""Check Python code for common security vulnerabilities.
Args:
code: Python source code to analyze
Returns:
List of security issues found
"""
issues = []
if "eval(" in code:
issues.append("WARNING: Unsafe eval() detected")
if "exec(" in code:
issues.append("WARNING: exec() usage found — sanitize inputs")
if "pickle.loads(" in code:
issues.append("WARNING: pickle.loads() is unsafe with untrusted data")
return "\n".join(issues) if issues else "No critical security issues found"
code_reviewer = Agent(
name="CodeReviewer",
instructions="""You are a senior Python engineer.
Review the provided code for: security issues (use check_security tool),
performance problems, PEP 8 compliance, and provide specific improvement suggestions with code examples.""",
tools=[check_security],
model="gpt-4o",
)
async def main():
code = '''
def process(data, user_input):
result = eval(user_input) # Dangerous!
return result
'''
result = await Runner.run(code_reviewer, input=f"Review this code:\n```python{code}```")
print(result.final_output)
asyncio.run(main())
6. OpenAI Agents SDK vs LangChain vs CrewAI
| Feature | OpenAI Agents SDK | LangChain/LangGraph | CrewAI |
|---|---|---|---|
| Learning curve | ⭐⭐⭐⭐⭐ Lowest | ⭐⭐⭐ Medium | ⭐⭐⭐⭐ Low |
| OpenAI integration | ⭐⭐⭐⭐⭐ Native | ⭐⭐⭐⭐ Excellent | ⭐⭐⭐⭐ Good |
| Multi-LLM support | ⭐⭐⭐ Via LiteLLM | ⭐⭐⭐⭐⭐ Best | ⭐⭐⭐⭐ Wide |
| Multi-agent | ⭐⭐⭐⭐⭐ Handoffs | ⭐⭐⭐⭐ LangGraph | ⭐⭐⭐⭐⭐ Core strength |
| Observability | ⭐⭐⭐⭐ Built-in tracing | ⭐⭐⭐⭐⭐ LangSmith | ⭐⭐⭐ Developing |
| Best for | OpenAI-first, clean multi-agent | Complex RAG, multi-LLM, production scale | Role-based crew workflows |
Choose OpenAI Agents SDK when: You're using OpenAI models, want the lowest learning curve, and need clean multi-agent handoffs. Choose LangChain when you need multi-LLM flexibility or complex RAG. Choose CrewAI when you're modeling a human team with distinct roles.
7. Summary & Next Steps
OpenAI Agents SDK makes building production AI agents accessible to any Python developer. You've learned:
- ✅ Agent: The AI worker with instructions, tools, and a model
- ✅ Tool: Any Python function registered with
@function_tool - ✅ Handoff: Delegation between specialized agents
- ✅ Guardrail: Input/output safety and validation
Next steps: Run the examples above, explore the official docs for Streaming and Structured Outputs, and browse the AgDex directory for complementary tools.
🔍 Find 400+ AI agent tools, frameworks, and platforms in the AgDex directory.
OpenAI Agents SDK: Guía Completa para Principiantes (2026)
— Construye tu Primer Agente de IA
OpenAI Agents SDK es el framework Python oficial para construir, ejecutar y orquestar agentes de IA en producción. Esta guía te lleva desde cero hasta un sistema multiagente funcional con ejemplos reales en Python.
1. ¿Qué es OpenAI Agents SDK?
Lanzado oficialmente en marzo de 2025 (originalmente llamado "Swarm"), el OpenAI Agents SDK es una biblioteca Python de código abierto que proporciona el kit de herramientas oficial de primera parte para construir agentes de IA. A diferencia del patrón simple "pregunta → respuesta" de ChatGPT, los agentes pueden realizar razonamiento en múltiples pasos, llamadas a herramientas y toma de decisiones autónoma para completar tareas complejas.
Para 2026, los agentes han pasado de ser curiosidades de investigación a ser una realidad en producción. El Agents SDK te proporciona:
- Abstracción mínima: Curva de aprendizaje baja, se integra perfectamente con código Python existente
- Características nativas de OpenAI: Function Calling, File Search, Code Interpreter como ciudadanos de primera clase
- Primitivas listas para producción: Trazado, guardrails y handoffs incluidos de serie
- Orquestación multiagente: Coordina múltiples agentes especializados con código limpio y legible
📦 Instalación: pip install openai-agents (requiere Python 3.9+)
2. Assistants API vs Agents SDK
OpenAI ya tenía la Assistants API. ¿Por qué un nuevo SDK? Las diferencias clave son:
- Control: La Assistants API gestiona el estado en el servidor (OpenAI mantiene el Thread). El Agents SDK te da control completo del lado del cliente sobre el bucle de ejecución.
- Flexibilidad: La Assistants API te limita a las herramientas integradas de OpenAI. El Agents SDK te permite registrar cualquier función Python como herramienta.
- Multiagente: La Assistants API es solo de un agente. El Agents SDK tiene soporte de primera clase para Handoff en arquitecturas multiagente.
- Depurabilidad: La Assistants API es una caja negra. El Agents SDK expone cada paso para registro y trazado.
3. Conceptos Principales: Agent / Tool / Handoff / Guardrail
Agent (Agente)
Un Agent es un asistente de IA con un propósito definido. Configuras su nombre, instrucciones (prompt del sistema), herramientas y modelo. Los agentes realizan bucles autónomos de llamadas a herramientas y razonamiento hasta alcanzar una respuesta final.
from agents import Agent
agente = Agent(
name="AsistenteInvestigacion",
instructions="""Eres un asistente de investigación exhaustivo.
Proporciona información precisa y detallada con fuentes cuando sea posible.
Distingue claramente entre hechos y suposiciones.""",
model="gpt-4o",
)
Tool (Herramienta)
Una Tool es cualquier función Python decorada con @function_tool. Los type hints y docstrings se convierten automáticamente en el esquema de Function Calling de OpenAI, sin necesidad de JSON manual.
from agents import function_tool
@function_tool
def buscar_web(consulta: str) -> str:
"""Busca en la web la consulta dada y devuelve los principales resultados.
Args:
consulta: Cadena de búsqueda
Returns:
Resumen de los principales resultados de búsqueda
"""
return f"Resultados de búsqueda para '{consulta}': [resultado1, resultado2, ...]"
Handoff (Transferencia)
Un Handoff transfiere el control de un agente a otro, pasando el contexto completo de la conversación. Esto permite pipelines multiagente donde los especialistas manejan su dominio.
from agents import Agent
agente_facturacion = Agent(
name="AgenteFacturacion",
instructions="Gestiona consultas de facturación, pagos y suscripciones.",
model="gpt-4o-mini",
)
agente_triage = Agent(
name="AgenteTriage",
instructions="Dirige las consultas al especialista apropiado. Preguntas de facturación → agente_facturacion.",
handoffs=[agente_facturacion],
model="gpt-4o-mini",
)
Guardrail (Barrera de seguridad)
Un Guardrail valida entradas y salidas, permitiéndote bloquear solicitudes dañinas, eliminar información personal o aplicar políticas de contenido antes de que lleguen a tu agente (o salgan de él).
4. Inicio Rápido: Tu Primer Agente en 5 Minutos
# Instalación: pip install openai-agents
# Variable de entorno: export OPENAI_API_KEY="sk-proj-..."
import asyncio
from agents import Agent, Runner, function_tool
@function_tool
def obtener_clima(ciudad: str) -> str:
"""Obtiene el clima actual para una ciudad.
Args:
ciudad: Nombre de la ciudad
Returns:
Descripción del clima
"""
return f"Clima en {ciudad}: Soleado, 22°C, humedad 60%"
asistente = Agent(
name="BotClima",
instructions="Eres un asistente meteorológico útil. Usa la herramienta obtener_clima para responder preguntas sobre el tiempo.",
tools=[obtener_clima],
model="gpt-4o-mini",
)
async def main():
resultado = await Runner.run(asistente, input="¿Qué tiempo hace en Madrid?")
print(resultado.final_output)
asyncio.run(main())
5. Ejemplos Prácticos
Agente de Investigación Web
from agents import Agent, Runner, WebSearchTool
import asyncio
agente_investigacion = Agent(
name="InvestigadorWeb",
instructions="""Eres un analista de investigación exhaustivo.
1. Divide las preguntas complejas en 3-5 búsquedas específicas
2. Contrasta información de múltiples fuentes
3. Sintetiza los hallazgos en un informe estructurado
4. Siempre indica la incertidumbre cuando esté presente""",
tools=[WebSearchTool()],
model="gpt-4o",
)
async def main():
resultado = await Runner.run(
agente_investigacion,
input="¿Cuáles son las diferencias principales entre OpenAI Agents SDK y LangGraph en 2026?",
)
print(resultado.final_output)
asyncio.run(main())
Agente de Revisión de Código
from agents import Agent, Runner, function_tool
import asyncio
@function_tool
def verificar_seguridad(codigo: str) -> str:
"""Verifica el código Python en busca de vulnerabilidades de seguridad comunes.
Args:
codigo: Código fuente Python a analizar
Returns:
Lista de problemas de seguridad encontrados
"""
problemas = []
if "eval(" in codigo:
problemas.append("ADVERTENCIA: eval() inseguro detectado")
if "exec(" in codigo:
problemas.append("ADVERTENCIA: uso de exec() encontrado — sanea las entradas")
if "pickle.loads(" in codigo:
problemas.append("ADVERTENCIA: pickle.loads() es inseguro con datos no confiables")
return "\n".join(problemas) if problemas else "No se encontraron problemas de seguridad críticos"
revisor_codigo = Agent(
name="RevisorCodigo",
instructions="""Eres un ingeniero Python senior.
Revisa el código proporcionado para: problemas de seguridad (usa la herramienta verificar_seguridad),
problemas de rendimiento, cumplimiento de PEP 8, y proporciona sugerencias específicas de mejora con ejemplos de código.""",
tools=[verificar_seguridad],
model="gpt-4o",
)
async def main():
codigo = '''
def procesar(datos, entrada_usuario):
resultado = eval(entrada_usuario) # ¡Peligroso!
return resultado
'''
resultado = await Runner.run(revisor_codigo, input=f"Revisa este código:\n```python{codigo}```")
print(resultado.final_output)
asyncio.run(main())
6. OpenAI Agents SDK vs LangChain vs CrewAI
| Característica | OpenAI Agents SDK | LangChain/LangGraph | CrewAI |
|---|---|---|---|
| Curva de aprendizaje | ⭐⭐⭐⭐⭐ Más baja | ⭐⭐⭐ Media | ⭐⭐⭐⭐ Baja |
| Integración OpenAI | ⭐⭐⭐⭐⭐ Nativa | ⭐⭐⭐⭐ Excelente | ⭐⭐⭐⭐ Buena |
| Soporte multi-LLM | ⭐⭐⭐ Via LiteLLM | ⭐⭐⭐⭐⭐ El mejor | ⭐⭐⭐⭐ Amplio |
| Multiagente | ⭐⭐⭐⭐⭐ Handoffs | ⭐⭐⭐⭐ LangGraph | ⭐⭐⭐⭐⭐ Fortaleza principal |
| Mejor para | OpenAI-first, multiagente limpio | RAG complejo, multi-LLM, escala de producción | Flujos de trabajo con roles definidos |
7. Resumen y Próximos Pasos
OpenAI Agents SDK hace que construir agentes de IA en producción sea accesible para cualquier desarrollador Python. Has aprendido:
- ✅ Agent: El trabajador de IA con instrucciones, herramientas y un modelo
- ✅ Tool: Cualquier función Python registrada con
@function_tool - ✅ Handoff: Delegación entre agentes especializados
- ✅ Guardrail: Seguridad y validación de entrada/salida
Próximos pasos: Ejecuta los ejemplos anteriores, explora la documentación oficial y navega por el directorio AgDex para encontrar herramientas complementarias.
🔍 Encuentra más de 300 herramientas, frameworks y plataformas de agentes de IA en el directorio AgDex.
OpenAI Agents SDK: Der vollständige Einsteiger-Leitfaden (2026)
— Baue deinen ersten KI-Agenten
Das OpenAI Agents SDK ist das offizielle Python-Framework zum Erstellen, Ausführen und Orchestrieren von KI-Agenten in der Produktion. Dieser Leitfaden führt dich von null zu einem funktionierenden Multi-Agenten-System mit echten Python-Codebeispielen.
1. Was ist das OpenAI Agents SDK?
Das im März 2025 offiziell veröffentlichte OpenAI Agents SDK (ursprünglich "Swarm" genannt) ist eine Open-Source-Python-Bibliothek, die das offizielle First-Party-Toolkit für die Entwicklung von KI-Agenten bereitstellt. Im Gegensatz zum einfachen "Frage → Antwort"-Muster von ChatGPT können Agenten mehrstufiges Schlussfolgern, Tool-Aufrufe und autonome Entscheidungsfindung durchführen, um komplexe Aufgaben zu bewältigen.
Im Jahr 2026 haben sich Agenten von einer Forschungskuriosität zur Produktionsrealität entwickelt. Das Agents SDK bietet dir:
- Minimale Abstraktion: Geringe Lernkurve, nahtlose Integration mit bestehendem Python-Code
- Native OpenAI-Features: Function Calling, File Search, Code Interpreter als erstklassige Bürger
- Produktionsreife Primitive: Tracing, Guardrails und Handoffs sind standardmäßig integriert
- Multi-Agenten-Orchestrierung: Mehrere spezialisierte Agenten mit sauberem, lesbarem Code koordinieren
📦 Installation: pip install openai-agents (erfordert Python 3.9+)
2. Assistants API vs. Agents SDK
OpenAI hatte bereits die Assistants API. Warum also ein neues SDK? Die wichtigsten Unterschiede:
- Kontrolle: Die Assistants API verwaltet den Zustand serverseitig (OpenAI hält den Thread). Das Agents SDK gibt dir die vollständige clientseitige Kontrolle über die Run-Schleife.
- Flexibilität: Die Assistants API begrenzt dich auf OpenAIs integrierte Tools. Das Agents SDK lässt dich jede Python-Funktion als Tool registrieren.
- Multi-Agent: Die Assistants API unterstützt nur einen einzigen Agenten. Das Agents SDK hat erstklassige Handoff-Unterstützung für Multi-Agenten-Architekturen.
- Debugbarkeit: Die Assistants API ist eine Black Box. Das Agents SDK legt jeden Schritt für Logging und Tracing offen.
3. Kernkonzepte: Agent / Tool / Handoff / Guardrail
Agent
Ein Agent ist ein KI-Assistent mit einem definierten Zweck. Du konfigurierst seinen Namen, Anweisungen (System-Prompt), Tools und Modell. Agenten durchlaufen autonom Schleifen aus Tool-Aufrufen und Überlegungen, bis sie eine endgültige Antwort erreichen.
from agents import Agent
agent = Agent(
name="Forschungsassistent",
instructions="""Du bist ein gründlicher Forschungsassistent.
Liefere genaue, detaillierte Informationen mit Quellen wenn möglich.
Unterscheide klar zwischen Fakten und Vermutungen.""",
model="gpt-4o",
)
Tool (Werkzeug)
Ein Tool ist jede Python-Funktion, die mit @function_tool dekoriert ist. Type Hints und Docstrings werden automatisch zum OpenAI Function Calling Schema — kein manuelles JSON erforderlich.
from agents import function_tool
@function_tool
def web_suche(anfrage: str) -> str:
"""Durchsucht das Web nach der gegebenen Anfrage und gibt Top-Ergebnisse zurück.
Args:
anfrage: Suchstring
Returns:
Zusammenfassung der wichtigsten Suchergebnisse
"""
return f"Suchergebnisse für '{anfrage}': [Ergebnis1, Ergebnis2, ...]"
Handoff (Übergabe)
Ein Handoff überträgt die Kontrolle von einem Agenten auf einen anderen und leitet dabei den vollständigen Gesprächskontext weiter. Dies ermöglicht ausgefeilte Multi-Agenten-Pipelines, in denen Spezialisten ihre Domäne bearbeiten.
from agents import Agent
abrechnungs_agent = Agent(
name="Abrechnungsagent",
instructions="Bearbeite Anfragen zu Abrechnung, Zahlungen und Abonnements.",
model="gpt-4o-mini",
)
triage_agent = Agent(
name="Triage-Agent",
instructions="Leite Kundenanfragen an den entsprechenden Spezialisten weiter. Abrechnungsfragen → abrechnungs_agent.",
handoffs=[abrechnungs_agent],
model="gpt-4o-mini",
)
Guardrail (Schutzschranke)
Ein Guardrail validiert Ein- und Ausgaben, sodass du schädliche Anfragen blockieren, personenbezogene Daten entfernen oder Inhaltsrichtlinien durchsetzen kannst, bevor sie deinen Agenten erreichen oder verlassen.
4. Schnellstart: Dein erster Agent in 5 Minuten
# Installation: pip install openai-agents
# Umgebungsvariable: export OPENAI_API_KEY="sk-proj-..."
import asyncio
from agents import Agent, Runner, function_tool
@function_tool
def wetter_abfragen(stadt: str) -> str:
"""Ruft das aktuelle Wetter für eine Stadt ab.
Args:
stadt: Stadtname
Returns:
Wetterbeschreibung
"""
return f"Wetter in {stadt}: Sonnig, 22°C, Luftfeuchtigkeit 60%"
assistent = Agent(
name="WetterBot",
instructions="Du bist ein hilfreicher Wetterassistent. Verwende das wetter_abfragen-Tool, um Wetterfragen zu beantworten.",
tools=[wetter_abfragen],
model="gpt-4o-mini",
)
async def main():
ergebnis = await Runner.run(assistent, input="Wie ist das Wetter in Berlin?")
print(ergebnis.final_output)
asyncio.run(main())
5. Praktische Beispiele
Web-Recherche-Agent
from agents import Agent, Runner, WebSearchTool
import asyncio
recherche_agent = Agent(
name="WebRechercheur",
instructions="""Du bist ein gründlicher Forschungsanalyst.
1. Teile komplexe Fragen in 3-5 gezielte Suchanfragen auf
2. Überprüfe Informationen aus mehreren Quellen
3. Fasse die Erkenntnisse in einem strukturierten Bericht zusammen
4. Weise immer auf Unsicherheiten hin""",
tools=[WebSearchTool()],
model="gpt-4o",
)
async def main():
ergebnis = await Runner.run(
recherche_agent,
input="Was sind die wichtigsten Unterschiede zwischen OpenAI Agents SDK und LangGraph im Jahr 2026?",
)
print(ergebnis.final_output)
asyncio.run(main())
Code-Review-Agent
from agents import Agent, Runner, function_tool
import asyncio
@function_tool
def sicherheit_pruefen(code: str) -> str:
"""Prüft Python-Code auf häufige Sicherheitslücken.
Args:
code: Zu analysierender Python-Quellcode
Returns:
Liste gefundener Sicherheitsprobleme
"""
probleme = []
if "eval(" in code:
probleme.append("WARNUNG: Unsicheres eval() erkannt")
if "exec(" in code:
probleme.append("WARNUNG: exec()-Verwendung gefunden — Eingaben bereinigen")
if "pickle.loads(" in code:
probleme.append("WARNUNG: pickle.loads() ist unsicher mit nicht vertrauenswürdigen Daten")
return "\n".join(probleme) if probleme else "Keine kritischen Sicherheitsprobleme gefunden"
code_reviewer = Agent(
name="CodeReviewer",
instructions="""Du bist ein erfahrener Python-Ingenieur.
Überprüfe den bereitgestellten Code auf: Sicherheitsprobleme (verwende das sicherheit_pruefen-Tool),
Leistungsprobleme, PEP 8-Konformität und gib spezifische Verbesserungsvorschläge mit Codebeispielen.""",
tools=[sicherheit_pruefen],
model="gpt-4o",
)
async def main():
code = '''
def verarbeiten(daten, benutzereingabe):
ergebnis = eval(benutzereingabe) # Gefährlich!
return ergebnis
'''
ergebnis = await Runner.run(code_reviewer, input=f"Überprüfe diesen Code:\n```python{code}```")
print(ergebnis.final_output)
asyncio.run(main())
6. OpenAI Agents SDK vs. LangChain vs. CrewAI
| Merkmal | OpenAI Agents SDK | LangChain/LangGraph | CrewAI |
|---|---|---|---|
| Lernkurve | ⭐⭐⭐⭐⭐ Am niedrigsten | ⭐⭐⭐ Mittel | ⭐⭐⭐⭐ Niedrig |
| OpenAI-Integration | ⭐⭐⭐⭐⭐ Nativ | ⭐⭐⭐⭐ Ausgezeichnet | ⭐⭐⭐⭐ Gut |
| Multi-LLM-Support | ⭐⭐⭐ Via LiteLLM | ⭐⭐⭐⭐⭐ Bestes | ⭐⭐⭐⭐ Breit |
| Multi-Agent | ⭐⭐⭐⭐⭐ Handoffs | ⭐⭐⭐⭐ LangGraph | ⭐⭐⭐⭐⭐ Kernstärke |
| Am besten für | OpenAI-first, saubere Multi-Agenten | Komplexes RAG, multi-LLM, Produktionsskala | Rollenbasierte Team-Workflows |
7. Zusammenfassung & Nächste Schritte
Das OpenAI Agents SDK macht die Erstellung von KI-Agenten in der Produktion für jeden Python-Entwickler zugänglich. Du hast gelernt:
- ✅ Agent: Der KI-Arbeiter mit Anweisungen, Tools und einem Modell
- ✅ Tool: Jede Python-Funktion, die mit
@function_toolregistriert wird - ✅ Handoff: Delegation zwischen spezialisierten Agenten
- ✅ Guardrail: Sicherheit und Validierung von Ein-/Ausgaben
Nächste Schritte: Führe die obigen Beispiele aus, erkunde die offizielle Dokumentation und durchsuche das AgDex-Verzeichnis nach ergänzenden Tools.
🔍 Finde über 300 KI-Agent-Tools, Frameworks und Plattformen im AgDex-Verzeichnis.
🔍 Explore AI Agent Tools on AgDex
Browse 400+ curated AI agent tools, frameworks, and platforms — filtered by category, language, and use case.
Browse the Directory →