OpenAI Agents SDK のエージェントが使用可能なツールの種類と使用方法についての説明です。
OpenAI Agents SDK : ツール
作成 : クラスキャット・セールスインフォメーション
作成日時 : 03/21/2025
* 本記事は openai.github.io/openai-agents-python の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
OpenAI Agents SDK : ツール
ツールはエージェントにアクションを実行させます : データの取得、コードの実行、外部 API の呼び出し、更にはコンピュータの使用のようなものです。Agent SDK には 3 つのクラスのツールがあります。
- ホスト型ツール (Hosted tools) : これらは AI モデルとともに LLM サーバ上で実行されます。OpenAI はホスト型ツールとして、検索、web 検索とコンピュータの使用を提供しています。
- 関数呼び出し : これらはツールとして任意の Python 関数を使用することを可能にします。
- ツールとしてのエージェント : これはエージェントをツールとして使用することを可能にします、エージェントが他のエージェントにハンドオフすることなく呼び出せます。
ホスト型ツール
OpenAI は OpenAIResponsesModel を使用する時、いくつかの組み込みツールを提供します :
- WebSearchTool はエージェントに web 検索させます。
- FileSearchTool は OpenAI ベクトルストアから情報を取得できます。
- ComputerTool はコンピュータ使用タスクを自動化できます。
from agents import Agent, FileSearchTool, Runner, WebSearchTool
agent = Agent(
name="Assistant",
tools=[
WebSearchTool(),
FileSearchTool(
max_num_results=3,
vector_store_ids=["VECTOR_STORE_ID"],
),
],
)
async def main():
result = await Runner.run(agent, "Which coffee shop should I go to, taking into account my preferences and the weather today in SF?")
print(result.final_output)
関数ツール
任意の Python 関数をツールとして使用できます。Agents SDK はツールを自動的にセットアップします :
- ツールの名前は Python 関数の名前になります (or 名前を提供できます)
- ツールの説明は関数の docstring から取得されます (or 説明を提供できます)
- 関数入力のスキーマは関数の引数から自動的に作成されます
- 各入力の説明は、無効にされない限り、関数の docstring から取得されます
関数シグネチャを抽出するために Python の inspect モジュールを使用し、docstrings の解析には griffe、そしてスキーマ作成には pydantic を使用します。
import json
from typing_extensions import TypedDict, Any
from agents import Agent, FunctionTool, RunContextWrapper, function_tool
class Location(TypedDict):
lat: float
long: float
@function_tool
async def fetch_weather(location: Location) -> str:
"""Fetch the weather for a given location.
Args:
location: The location to fetch the weather for.
"""
# In real life, we'd fetch the weather from a weather API
return "sunny"
@function_tool(name_override="fetch_data")
def read_file(ctx: RunContextWrapper[Any], path: str, directory: str | None = None) -> str:
"""Read the contents of a file.
Args:
path: The path to the file to read.
directory: The directory to read the file from.
"""
# In real life, we'd read the file from the file system
return ""
agent = Agent(
name="Assistant",
tools=[fetch_weather, read_file],
)
for tool in agent.tools:
if isinstance(tool, FunctionTool):
print(tool.name)
print(tool.description)
print(json.dumps(tool.params_json_schema, indent=2))
print()
出力
fetch_weather
Fetch the weather for a given location.
{
"$defs": {
"Location": {
"properties": {
"lat": {
"title": "Lat",
"type": "number"
},
"long": {
"title": "Long",
"type": "number"
}
},
"required": [
"lat",
"long"
],
"title": "Location",
"type": "object"
}
},
"properties": {
"location": {
"$ref": "#/$defs/Location",
"description": "The location to fetch the weather for."
}
},
"required": [
"location"
],
"title": "fetch_weather_args",
"type": "object"
}
fetch_data
Read the contents of a file.
{
"properties": {
"path": {
"description": "The path to the file to read.",
"title": "Path",
"type": "string"
},
"directory": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"description": "The directory to read the file from.",
"title": "Directory"
}
},
"required": [
"path"
],
"title": "fetch_data_args",
"type": "object"
}
カスタム関数ツール
ツールとして Python 関数を使用したくない場合があります。必要に応じて FunctionTool を直接作成することができます。以下を提供する必要があります :
- name
- description
- params_json_schema, これは引数の JSON スキーマです
- on_invoke_tool, これは非同期関数で、コンテキストと引数を JSON 文字列として受け取り、ツール出力を文字列として返す必要があります。
from typing import Any
from pydantic import BaseModel
from agents import RunContextWrapper, FunctionTool
def do_some_work(data: str) -> str:
return "done"
class FunctionArgs(BaseModel):
username: str
age: int
async def run_function(ctx: RunContextWrapper[Any], args: str) -> str:
parsed = FunctionArgs.model_validate_json(args)
return do_some_work(data=f"{parsed.username} is {parsed.age} years old")
tool = FunctionTool(
name="process_user",
description="Processes extracted user data",
params_json_schema=FunctionArgs.model_json_schema(),
on_invoke_tool=run_function,
)
自動引数と docstring 解析
前述のように、関数シグネチャを自動的に解析してツールのスキーマを抽出し、そして docstring を解析してツールと個々の引数の説明を抽出します。それについて幾つかの注意点があります :
- シグネチャ解析は inspect モジュール経由で行われます。引数の型を理解するために型アノテーションを使用し、そして全体的なスキーマを表すために Pydantic モデルを動的に構築します。Python プリミティブ、Pydantic モデル、TypedDicts 等を含む、殆どの型をサポートします。
- docstring を解析するために griffe を使用します。サポートされる docstring 形式は google, sphinx と numpy です。docstring 形式を自動的に検出することを試みますが、これはベストエフォートで、function_tool を呼び出すときに明示的にそれを設定できます。use_docstring_info を False に設定して docstring 解析を無効にすることもできます。
スキーマ抽出のコードは agents.function_schema にあります。
ツールとしてのエージェント
ワークフローによっては、制御をハンドオフする代わりに、中央 (cenrtral) エージェントが専門エージェントのネットワークを編成することを望む場合があります。これはエージェントをツールとしてモデル化することで行うことができます。
from agents import Agent, Runner
import asyncio
spanish_agent = Agent(
name="Spanish agent",
instructions="You translate the user's message to Spanish",
)
french_agent = Agent(
name="French agent",
instructions="You translate the user's message to French",
)
orchestrator_agent = Agent(
name="orchestrator_agent",
instructions=(
"You are a translation agent. You use the tools given to you to translate."
"If asked for multiple translations, you call the relevant tools."
),
tools=[
spanish_agent.as_tool(
tool_name="translate_to_spanish",
tool_description="Translate the user's message to Spanish",
),
french_agent.as_tool(
tool_name="translate_to_french",
tool_description="Translate the user's message to French",
),
],
)
async def main():
result = await Runner.run(orchestrator_agent, input="Say 'Hello, how are you?' in Spanish.")
print(result.final_output)
関数ツールにおけるエラー処理
@function_tool 経由で関数ツールを作成するとき、failure_error_function を渡すことができます。これは、ツール呼び出しがクラッシュした場合にエラー応答を LLM に提供する関数です。
- デフォルトでは (i.e. なにも渡さない場合)、LLM にエラーの発生を知らせる default_tool_error_function を実行します。
- 独自のエラー関数を渡す場合、代わりにそれを実行し、レスポンスを LLM に送信します。
- None を明示的に渡すと、任意のツール呼び出しエラーは処理するために再度あげられます。これは、モデルが無効な JSON を生成した場合には ModelBehaviorError、コードがクラッシュした場合には UserError になるなどです。
手動で FunctionTool オブジェクトを作成する場合には、on_invoke_tool 関数の内部でエラーを処理する必要があります。
以上