OpenAI Agents SDK for Python 完全ガイド——Function Calling実装とプラクティス【2026年版】
Agents SDKとは——OpenAI最新エージェント実装の仕組み
OpenAI Agents SDKは、ChatGPT APIを使ってAIエージェント(自動的に判断・実行するプログラム)を構築するための公式Pythonライブラリです。Function Calling機能を活用して、AIモデルが関数を選んで実行し、その結果をもとに次のアクションを決定するフローを実現します。
従来のChatGPT APIは「質問と回答」のシンプルなやり取りが中心でしたが、Agents SDKを使うと以下のような複雑な処理が可能になります。
- 複数の関数から最適なものを選択させる: ユーザーの質問に応じて、天気取得API・カレンダー検索・メール送信など、複数の外部機能の中から適切なものを自動選択
- 逐次処理(ステップバイステップ実行): 1つの質問に対して複数のステップが必要な場合、AIが自動的に順番に関数を呼び出す
- エラー時の自動回復: APIエラーやタイムアウトが起きても、AIが自動的に別の方法を試す
- 監査可能なログ: すべてのエージェント実行ステップを記録でき、何をどの順序で実行したかが追跡可能
2026年現在、ChatGPT APIの開発者向け検索需要の大部分がこのAgents SDK実装に集中しており、従来のFunction Callingの書き方(openai.ChatCompletion)は既にバージョン1.0.0以上では非推奨になっています。
必要な環境と準備作業
システム要件
- Python 3.8以上
- pip(Pythonパッケージマネージャー)
- OpenAI APIキー(OpenAI公式サイトで無料アカウント登録時に取得可能)
Python環境の確認
ターミナル/コマンドプロンプトで以下を実行し、Pythonのバージョンを確認します。
python3 --version
バージョン3.8以上が出力されればOKです。
OpenAI APIキーの取得と設定
- OpenAI公式サイトにアクセスし、アカウントにログインします
- 左メニューから「API keys」をクリック
- 「Create new secret key」ボタンで新しいキーを生成
- 生成されたキーをコピー(二度と表示されないため必ずメモ)
APIキーをPython環境に設定するには、以下いずれかの方法を使います。
方法1:環境変数として設定(推奨)
# macOS / Linux
export OPENAI_API_KEY="sk-..."
# Windows PowerShell
$env:OPENAI_API_KEY="sk-..."
# Windows コマンドプロンプト
set OPENAI_API_KEY=sk-...
方法2:Pythonコード内で直接設定
import os
os.environ['OPENAI_API_KEY'] = 'sk-...'
方法3:.envファイルで管理(本番環境推奨)
プロジェクトルートに.envファイルを作成:
OPENAI_API_KEY=sk-...
Python内で読み込み:
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
必要なライブラリのインストール
pip install openai python-dotenv
2026年現在、openaiパッケージのバージョンは1.0.0以上が標準です。バージョンを確認するには:
pip show openai
Function Callngの基本——シンプルな例から始める
Function Callingの動作フロー
Function Callingの本質は「AIにコード実行させる権限を与える」ことです。処理フローは以下の通りです。
- ユーザーが質問を入力(例:「今日の天気は?」)
- AIが「この質問に対しては weather_api を呼び出すべき」と判断
- AIが天気関数を呼び出すように指示
- プログラムが実際に天気APIを呼び出し
- 結果をAIに返す
- AIが結果を人間が理解しやすい文章にまとめて返答
最小限の実装例
以下は、シンプルな計算機能を持つエージェントです。
from openai import OpenAI
import json
# OpenAIクライアント初期化
client = OpenAI()
# ステップ1: 実行可能な関数を定義
def multiply(a: int, b: int) -> int:
"""2つの数を掛け算する"""
return a * b
def add(a: int, b: int) -> int:
"""2つの数を足す"""
return a + b
# ステップ2: 関数の定義をAIに伝える形式に変換
tools = [
{
"type": "function",
"function": {
"name": "multiply",
"description": "2つの整数を掛け算します",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "integer",
"description": "最初の数"
},
"b": {
"type": "integer",
"description": "2番目の数"
}
},
"required": ["a", "b"]
}
}
},
{
"type": "function",
"function": {
"name": "add",
"description": "2つの整数を足します",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "integer",
"description": "最初の数"
},
"b": {
"type": "integer",
"description": "2番目の数"
}
},
"required": ["a", "b"]
}
}
}
]
# ステップ3: ユーザーの質問を送信
messages = [
{"role": "user", "content": "12と5を掛けてください"}
]
response = client.chat.completions.create(
model="gpt-4o", # 2026年のデフォルトモデル
messages=messages,
tools=tools,
tool_choice="auto"
)
print("AI返答:", response.choices[0].message.content)
# ステップ4: AIが関数呼び出しを指示してきた場合、実際に実行
if response.choices[0].message.tool_calls:
for tool_call in response.choices[0].message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
if function_name == "multiply":
result = multiply(function_args["a"], function_args["b"])
elif function_name == "add":
result = add(function_args["a"], function_args["b"])
print(f"関数実行: {function_name}({function_args}) = {result}")
実行結果:
関数実行: multiply({'a': 12, 'b': 5}) = 60
AI返答: 12と5を掛けると60になります。
実践的なエージェント実装——複数ステップの自動処理
ユースケース:天気情報+アラート機能
実際の開発では、単一の関数呼び出しではなく、複数のステップを組み合わせる必要があります。以下は、天気情報を取得して、気温が高い場合は警告メールを送る例です。
from openai import OpenAI
import json
from typing import Any
client = OpenAI()
# 実装する関数たち
def get_weather(city: str) -> dict:
"""指定都市の天気情報を取得(ダミー実装)"""
weather_data = {
"Tokyo": {"temp": 28, "condition": "晴れ"},
"Osaka": {"temp": 25, "condition": "曇り"},
"Hokkaido": {"temp": 15, "condition": "雨"}
}
return weather_data.get(city, {"temp": 20, "condition": "不明"})
def send_alert_email(recipient: str, message: str) -> bool:
"""アラートメールを送信(ダミー実装)"""
print(f"📧 メール送信: {recipient} に '{message}' を送信")
return True
def check_alert_threshold(temperature: int) -> bool:
"""気温が警告しきい値を超えているか確認"""
threshold = 27
return temperature > threshold
# AIに提供する関数定義
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "指定された都市の天気情報を取得します",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "都市名(例:Tokyo, Osaka)"
}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "send_alert_email",
"description": "警告メールを送信します",
"parameters": {
"type": "object",
"properties": {
"recipient": {
"type": "string",
"description": "受信者のメールアドレス"
},
"message": {
"type": "string",
"description": "メールの内容"
}
},
"required": ["recipient", "message"]
}
}
},
{
"type": "function",
"function": {
"name": "check_alert_threshold",
"description": "気温が警告しきい値を超えているか確認",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "現在の気温(摂氏)"
}
},
"required": ["temperature"]
}
}
}
]
# メイン処理:複数ステップのエージェント実行
def run_weather_agent(user_query: str, user_email: str):
"""
ユーザーの質問に基づいて天気確認&アラート判定を自動実行
"""
messages = [
{
"role": "user",
"content": f"{user_query}。気温が27℃を超えていたら {user_email} にアラートメールを送ってください。"
}
]
print(f"\n🤖 エージェント開始: {user_query}\n")
# ループ:AIが「もう関数は不要」と判断するまで繰り返す
while True:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
# AIの応答をメッセージ履歴に追加
assistant_message = response.choices[0].message
messages.append({"role": "assistant", "content": assistant_message.content})
# Function Callがない場合はループを抜ける
if not assistant_message.tool_calls:
print(f"✅ AI最終返答: {assistant_message.content}\n")
break
# Function Callを実行
for tool_call in assistant_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
print(f"🔧 関数実行: {function_name}({function_args})")
# 関数を実行して結果を取得
if function_name == "get_weather":
result = get_weather(function_args["city"])
print(f" 結果: {result}")
elif function_name == "send_alert_email":
result = send_alert_email(
function_args["recipient"],
function_args["message"]
)
print(f" 結果: メール送信完了")
elif function_name == "check_alert_threshold":
result = check_alert_threshold(function_args["temperature"])
print(f" 結果: 警告が必要={result}")
# 関数実行結果をメッセージ履歴に追加
messages.append({
"role": "user",
"content": json.dumps({"function_result": result})
})
# 実行例
run_weather_agent("東京の天気を教えてください", "admin@example.com")
run_weather_agent("大阪の天気を教えてください", "admin@example.com")
実行出力例:
🤖 エージェント開始: 東京の天気を教えてください
🔧 関数実行: get_weather({'city': 'Tokyo'})
結果: {'temp': 28, 'condition': '晴れ'}
🔧 関数実行: check_alert_threshold({'temperature': 28})
結果: 警告が必要=True
🔧 関数実行: send_alert_email({'recipient': 'admin@example.com', 'message': '東京の気温が28℃に達しています。高温注意'})
📧 メール送信: admin@example.com に '東京の気温が28℃に達しています。高温注意' を送信
結果: メール送信完了
✅ AI最終返答: 東京は現在晴れで、気温は28℃です。警告しきい値を超えているため、アラートメールを送信しました。
🤖 エージェント開始: 大阪の天気を教えてください
🔧 関数実行: get_weather({'city': 'Osaka'})
結果: {'temp': 25, 'condition': '曇り'}
✅ AI最終返答: 大阪は現在曇りで、気温は25℃です。警告しきい値以下のため、アラートメールは送信していません。
Agents SDKで起きやすいエラーと対処法
エラー1:「InvalidRequestError: Unrecognized request argument supplied: messages」
このエラーは通常、古いバージョンのopenaiライブラリで新しいAPI仕様を使う場合に発生します。
原因
openai < 1.0.0(古いバージョン)を使っている場合、APIコールの方法が異なります。
解決策
pip install --upgrade openai
アップグレード後、以下の書き方を使用してください:
from openai import OpenAI
client = OpenAI() # 新しい書き方
response = client.chat.completions.create(
model="gpt-4o",
messages=[...],
tools=[...]
)
古い書き方(非推奨):
# これは使わない(バージョン1.0.0以上では動作しません)
import openai
openai.ChatCompletion.create(...)
エラー2:Function CallがNoneで返される
AIが関数呼び出しを判断せず、常にtool_calls=Noneになる場合があります。
原因
- 関数定義(tools)がAIに正しく伝わっていない
- ユーザー質問が関数呼び出しを必要としない内容
- tool_choiceパラメータの設定が「auto」になっていない
解決策
# ✅ 推奨:関数呼び出しを強制
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="required" # 必ず関数を呼び出させる
)
# または「auto」で自動判定(デフォルト)
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
エラー3:関数の引数パースエラー
Function Callの引数がJSON形式で返されるため、パースに失敗することがあります。
原因
json.loads()で不正なJSON文字列を処理しようとしている
安全な実装
import json
try:
function_args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError as e:
print(f"JSON解析エラー: {e}")
print(f"引数文字列: {tool_call.function.arguments}")
function_args = {}
エラー4:「Too many requests」が頻発する
API呼び出しが多すぎる場合、レート制限に引っかかります。
原因
短時間に大量のAPI呼び出しをしている
解決策
import time
# 関数実行の間に遅延を挿入
for tool_call in assistant_message.tool_calls:
# 処理...
time.sleep(0.5) # 500ms待機
ベストプラクティス——本番環境での実装ガイドライン
1. 関数定義を外部ファイルで管理
複数の関数定義がある場合、tools配列を別ファイルに分離します。
tools_config.py:
TOOLS = [
{
"type": "function",
"function": {
"name": "get_user_profile",
"description": "ユーザープロフィール情報を取得します",
"parameters": {
"type": "object",
"properties": {
"user_id": {
"type": "string",
"description": "ユーザーID"
}
},
"required": ["user_id"]
}
}
},
# 他の関数定義...
]
メインスクリプト:
from tools_config import TOOLS
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=TOOLS
)
2. 実行結果を詳細にログ記録
監査(どのような判断・実行が行われたか)のため、すべてのステップをログに記録します。
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
for tool_call in assistant_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
logger.info(f"Function call: {function_name}")
logger.debug(f"Arguments: {function_args}")
result = execute_function(function_name, function_args)
logger.info(f"Result: {result}")
3. タイムアウト設定とリトライロジック
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10)
)
def call_openai_with_retry(messages, tools):
return client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
timeout=30
)
response = call_openai_with_retry(messages, tools)
4. 関数実行結果の型チェック
AIが指定した関数の引数が正しい型であることを確認します。
def validate_function_args(function_name: str, args: dict) -> bool:
"""関数の引数が有効な型であるか確認"""
expected_types = {
"get_weather": {"city": str},
"send_email": {"recipient": str, "message": str},
}
if function_name not in expected_types:
return False
for arg_name, expected_type in expected_types[function_name].items():
if arg_name not in args or not isinstance(args[arg_name], expected_type):
return False
return True
# 使用例
if validate_function_args(function_name, function_args):
result = execute_function(function_name, function_args)
else:
logger.warning(f"Invalid arguments for {function_name}: {function_args}")
result = {"error": "Invalid arguments"}
トラブルシューティング──よくある質問と回答
Q:複数のエージェントを並列実行できますか?
A:できます。asyncioを使って並列実行可能です:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def run_agent_async(query: str):
response = await client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": query}],
tools=tools
)
return response
# 複数のエージェントを同時実行
tasks = [
run_agent_async("東京の天気は?"),
run_agent_async("大阪の天気は?"),
run_agent_async("京都の天気は?"),
]
results = asyncio.run(asyncio.gather(*tasks))
Q:画像を処理するFunction Callingは?
A:テキスト入力と同様に、base64エンコードされた画像データを渡せます:
import base64
with open("image.jpg", "rb") as img_file:
image_data = base64.b64encode(img_file.read()).decode("utf-8")
messages = [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{image_data}"
}
},
{
"type": "text",
"text": "この画像に何が写っていますか?"
}
]
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
Q:長いテキスト入力(1000字以上)でのFunction Callingは?
A:トークンの制限内であれば、制限なく長いテキストを渡せます。ただし、長すぎるとレスポンス時間が増加する可能性があります:
# 長いテキストをそのまま渡す
long_text = "(1000字以上のテキスト)"
messages = [
{"role": "user", "content": f"以下のテキストを分析して、要約してください:\n{long_text}"}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
まとめ——Agents SDK導入で実現できることと次のステップ
OpenAI Agents SDKを習得すると、以下のような実務的なアプリケーションが開発可能になります:
- カスタマーサポート自動化: ユーザー質問に対して自動的にデータベース検索・メール送信・チケット作成を実行するチャットボット
- ワークフロー自動化: 複雑な業務フロー(承認→請求書生成→メール通知)を自動化
- データ分析パイプライン: ユーザーのクエリに基づいて自動的にデータ取得→集計→レポート生成
- マルチモーダル処理: テキスト・画像・音声データを組み合わせた複合的なエージェント
2026年のOpenAI生態系では、Function Calling + Agents SDKが標準的な実装パターンになっています。本記事で紹介した基本パターンをベースに、自社の業務に合わせてカスタマイズすることで、生産性大幅向上を実現できます。
あわせて読みたい
- Claude OpusとSonnetを1つのAPIで連携させる方法|コスト削減&高速化
- PythonでMCPサーバーを構築する方法【2026年版】5ステップ実装ガイド
- LangChainで複数AIエージェント連携|CI/CD自動化【実装3ステップ】
参考ソース
- 10 AI Tools Every Developer Should Try in 2026
- Auditable Agent Context
- OpenAI API error: You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0
- Upload an image to chat gpt using the API?
- How to continue incomplete response of openai API
- How to send longer text inputs to ChatGPT API?
- OpenAI Chat Completions API error: InvalidRequestError: Unrecognized request argument supplied: messages