ツール
ツールは エージェント にアクションを取らせます。たとえばデータの取得、コードの実行、外部 API の呼び出し、さらにはコンピュータの使用などです。Agents SDK には 3 つのツールクラスがあります。
- Hosted tools: これらは AI モデルと並行して LLM サーバー上で実行されます。OpenAI は retrieval、Web 検索、コンピュータ操作 をホスト型ツールとして提供しています。
- Function calling: 任意の Python 関数をツールとして使用できます。
- Agents as tools: エージェント をツールとして使用でき、ハンドオフ せずに他の エージェント を呼び出せます。
ホスト型ツール
OpenAIResponsesModel を使用する場合、OpenAI はいくつかの組み込みツールを提供しています。
WebSearchToolは エージェント に Web を検索させます。FileSearchToolは OpenAI ベクトルストア から情報を取得できます。ComputerToolは コンピュータ操作 を自動化できます。CodeInterpreterToolは LLM がサンドボックス環境でコードを実行できるようにします。HostedMCPToolはリモートの MCP サーバーのツールをモデルに公開します。ImageGenerationToolはプロンプトから画像を生成します。LocalShellToolはローカルマシン上でシェルコマンドを実行します。
fromagentsimportAgent,FileSearchTool,Runner,WebSearchToolagent=Agent(name="Assistant",tools=[WebSearchTool(),FileSearchTool(max_num_results=3,vector_store_ids=["VECTOR_STORE_ID"],),],)asyncdefmain():result=awaitRunner.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 関数名になります(任意で名前を指定可能)
- ツールの説明は関数の docstring から取得されます(任意で説明を指定可能)
- 関数入力のスキーマは関数の引数から自動生成されます
- 各入力の説明は、無効化しない限り、関数の docstring から取得されます
Python のinspect モジュールで関数シグネチャを抽出し、griffe で docstring を解析、スキーマ作成にはpydantic を使用します。
importjsonfromtyping_extensionsimportTypedDict,AnyfromagentsimportAgent,FunctionTool,RunContextWrapper,function_toolclassLocation(TypedDict):lat:floatlong:float@function_tool# (1)!asyncdeffetch_weather(location:Location)->str:# (2)!"""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 APIreturn"sunny"@function_tool(name_override="fetch_data")# (3)!defread_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 systemreturn"<file contents>"agent=Agent(name="Assistant",tools=[fetch_weather,read_file],# (4)!)fortoolinagent.tools:ifisinstance(tool,FunctionTool):print(tool.name)print(tool.description)print(json.dumps(tool.params_json_schema,indent=2))print()- 関数の引数には任意の Python 型を使用でき、関数は同期/非同期どちらでも構いません。
- docstring がある場合、説明および引数の説明の取得に使用します。
- 関数は任意で
contextを最初の引数として受け取れます。ツール名、説明、docstring スタイルなどのオーバーライドも設定できます。 - デコレートした関数をツールのリストに渡せます。
出力を表示
fetch_weatherFetch 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_dataRead 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"}関数ツールからの画像やファイルの返却
テキスト出力に加えて、関数ツールの出力として 1 つまたは複数の画像やファイルを返すことができます。次のいずれかを返却できます。
- 画像:
ToolOutputImage(または TypedDict 版のToolOutputImageDict) - ファイル:
ToolOutputFileContent(または TypedDict 版のToolOutputFileContentDict) - テキスト: 文字列または文字列化可能なオブジェクト、または
ToolOutputText(または TypedDict 版のToolOutputTextDict)
カスタム関数ツール
Python 関数をツールとして使いたくない場合もあります。必要に応じて直接FunctionTool を作成できます。次を指定する必要があります。
namedescription- 引数用の JSON スキーマである
params_json_schema ToolContextと引数(JSON 文字列)を受け取り、ツール出力を文字列で返す非同期関数on_invoke_tool
fromtypingimportAnyfrompydanticimportBaseModelfromagentsimportRunContextWrapper,FunctionTooldefdo_some_work(data:str)->str:return"done"classFunctionArgs(BaseModel):username:strage:intasyncdefrun_function(ctx:RunContextWrapper[Any],args:str)->str:parsed=FunctionArgs.model_validate_json(args)returndo_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 モデル、TypedDict など、ほとんどの型をサポートします。 - docstring の解析には
griffeを使用します。サポートされる docstring フォーマットはgoogle、sphinx、numpyです。docstring 形式は自動検出を試みますがベストエフォートであり、function_tool呼び出し時に明示的に設定できます。use_docstring_infoをFalseに設定すると docstring 解析を無効化できます。
スキーマ抽出のコードはagents.function_schema にあります。
ツールとしての エージェント
一部のワークフローでは、制御をハンドオフ する代わりに、中央の エージェント が専門化された エージェント 群のオーケストレーションを行いたい場合があります。エージェント をツールとしてモデル化することで実現できます。
fromagentsimportAgent,Runnerimportasynciospanish_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",),],)asyncdefmain():result=awaitRunner.run(orchestrator_agent,input="Say 'Hello, how are you?' in Spanish.")print(result.final_output)ツール化したエージェントのカスタマイズ
agent.as_tool 関数は、エージェント をツールに変換しやすくするための便利メソッドです。ただし、すべての設定をサポートしているわけではありません。たとえばmax_turns は設定できません。高度なユースケースでは、ツール実装内で直接Runner.run を使用してください。
@function_toolasyncdefrun_my_agent()->str:"""A tool that runs the agent with custom configs"""agent=Agent(name="My agent",instructions="...")result=awaitRunner.run(agent,input="...",max_turns=5,run_config=...)returnstr(result.final_output)カスタム出力抽出
場合によっては、中央の エージェント に返す前にツール化した エージェント の出力を変更したいことがあります。次のような場合に役立ちます。
- サブエージェントのチャット履歴から特定の情報(例: JSON ペイロード)を抽出する。
- エージェント の最終回答を変換・再整形する(例: Markdown をプレーンテキストや CSV に変換)。
- 出力を検証し、エージェント の応答が欠落または不正な場合にフォールバック値を提供する。
これは、as_tool メソッドにcustom_output_extractor 引数を渡すことで行えます。
asyncdefextract_json_payload(run_result:RunResult)->str:# Scan the agent’s outputs in reverse order until we find a JSON-like message from a tool call.foriteminreversed(run_result.new_items):ifisinstance(item,ToolCallOutputItem)anditem.output.strip().startswith("{"):returnitem.output.strip()# Fallback to an empty JSON object if nothing was foundreturn"{}"json_tool=data_agent.as_tool(tool_name="get_data_json",tool_description="Run the data agent and return only its JSON payload",custom_output_extractor=extract_json_payload,)ネストしたエージェント実行のストリーミング
as_tool にon_stream コールバックを渡すと、ストリーム完了後に最終出力を返しつつ、ネストされた エージェント が発行する ストリーミング イベントを購読できます。
fromagentsimportAgentToolStreamEventasyncdefhandle_stream(event:AgentToolStreamEvent)->None:# Inspect the underlying StreamEvent along with agent metadata.print(f"[stream]{event['agent']['name']} ::{event['event'].type}")billing_agent_tool=billing_agent.as_tool(tool_name="billing_helper",tool_description="Answer billing questions.",on_stream=handle_stream,# Can be sync or async.)想定される挙動:
- イベントタイプは
StreamEvent["type"]を反映します:raw_response_event、run_item_stream_event、agent_updated_stream_event。 on_streamを指定すると、ネストされた エージェント は自動的にストリーミングモードで実行され、最終出力を返す前にストリームが読み尽くされます。- ハンドラーは同期/非同期のいずれでも構いません。各イベントは到着順に配信されます。
- ツールがモデルのツール呼び出し経由で呼ばれた場合は
tool_call_idが含まれます。直接呼び出しではNoneの場合があります。 - 実行可能な完全なサンプルは
examples/agent_patterns/agents_as_tools_streaming.pyを参照してください。
条件付きツール有効化
実行時にis_enabled パラメーターを使用して エージェント のツールを条件付きで有効化または無効化できます。これにより、コンテキスト、ユーザー の希望、実行時の条件に基づいて、LLM で利用可能なツールを動的にフィルタリングできます。
importasynciofromagentsimportAgent,AgentBase,Runner,RunContextWrapperfrompydanticimportBaseModelclassLanguageContext(BaseModel):language_preference:str="french_spanish"deffrench_enabled(ctx:RunContextWrapper[LanguageContext],agent:AgentBase)->bool:"""Enable French for French+Spanish preference."""returnctx.context.language_preference=="french_spanish"# Create specialized agentsspanish_agent=Agent(name="spanish_agent",instructions="You respond in Spanish. Always reply to the user's question in Spanish.",)french_agent=Agent(name="french_agent",instructions="You respond in French. Always reply to the user's question in French.",)# Create orchestrator with conditional toolsorchestrator=Agent(name="orchestrator",instructions=("You are a multilingual assistant. You use the tools given to you to respond to users. ""You must call ALL available tools to provide responses in different languages. ""You never respond in languages yourself, you always use the provided tools."),tools=[spanish_agent.as_tool(tool_name="respond_spanish",tool_description="Respond to the user's question in Spanish",is_enabled=True,# Always enabled),french_agent.as_tool(tool_name="respond_french",tool_description="Respond to the user's question in French",is_enabled=french_enabled,),],)asyncdefmain():context=RunContextWrapper(LanguageContext(language_preference="french_spanish"))result=awaitRunner.run(orchestrator,"How are you?",context=context.context)print(result.final_output)asyncio.run(main())is_enabled パラメーターは次を受け付けます。
- Boolean 値:
True(常に有効)またはFalse(常に無効) - Callable 関数:
(context, agent)を受け取り boolean を返す関数 - Async 関数: 複雑な条件ロジック向けの非同期関数
無効化されたツールは実行時に LLM から完全に隠されるため、次の用途に有用です。
- ユーザー 権限に基づく機能ゲーティング
- 環境別のツール可用性(dev と prod)
- ツール構成の A/B テスト
- 実行時の状態に基づく動的ツールフィルタリング
関数ツールでのエラー処理
@function_tool で関数ツールを作成する際に、failure_error_function を渡せます。これは、ツール呼び出しがクラッシュした場合に LLM へエラーレスポンスを提供する関数です。
- 既定(何も渡さない)では、エラーが発生したことを LLM に通知する
default_tool_error_functionを実行します。 - 独自のエラー関数を渡すと、それが実行され、そのレスポンスが LLM に送信されます。
- 明示的に
Noneを渡すと、ツール呼び出しのエラーは再スローされ、あなたが処理できます。モデルが不正な JSON を生成した場合はModelBehaviorError、あなたのコードがクラッシュした場合はUserErrorなどになり得ます。
fromagentsimportfunction_tool,RunContextWrapperfromtypingimportAnydefmy_custom_error_function(context:RunContextWrapper[Any],error:Exception)->str:"""A custom function to provide a user-friendly error message."""print(f"A tool call failed with the following error:{error}")return"An internal server error occurred. Please try again later."@function_tool(failure_error_function=my_custom_error_function)defget_user_profile(user_id:str)->str:"""Fetches a user profile from a mock API. This function demonstrates a 'flaky' or failing API call. """ifuser_id=="user_123":return"User profile for user_123 successfully retrieved."else:raiseValueError(f"Could not retrieve profile for user_id:{user_id}. API returned an error.")FunctionTool オブジェクトを手動で作成している場合は、on_invoke_tool 関数内でエラーを処理する必要があります。