|
| 1 | +"""Recovering from a model that calls a tool that doesn't exist. |
| 2 | +
|
| 3 | +Large models occasionally "hallucinate" a tool name that isn't registered on the agent -- |
| 4 | +for example they call ``search_linkedin`` when only ``search_web`` is available. Without a |
| 5 | +handler, the SDK raises ``ModelBehaviorError`` and the entire run is lost. |
| 6 | +
|
| 7 | +Registering a ``tool_not_found`` error handler lets you turn that crash into a recoverable |
| 8 | +nudge: the handler returns a ``ToolNotFoundAction`` with an error message, the runner |
| 9 | +injects that message as a synthetic tool output, and the model self-corrects on the next |
| 10 | +turn. |
| 11 | +
|
| 12 | +This example uses a tiny scripted ``Model`` subclass so it runs offline -- no API key |
| 13 | +needed. See issue #325 for the real-world report that motivated this API. |
| 14 | +
|
| 15 | + $ python examples/basic/tool_not_found_handler.py |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import asyncio |
| 21 | +from collections.abc import AsyncIterator |
| 22 | +from typing import Any |
| 23 | + |
| 24 | +from openai.types.responses import ResponseFunctionToolCall, ResponseOutputMessage |
| 25 | + |
| 26 | +from agents import ( |
| 27 | + Agent, |
| 28 | + ModelResponse, |
| 29 | + Runner, |
| 30 | + ToolNotFoundAction, |
| 31 | + ToolNotFoundErrorHandlerInput, |
| 32 | + Usage, |
| 33 | + function_tool, |
| 34 | +) |
| 35 | +from agents.agent_output import AgentOutputSchemaBase |
| 36 | +from agents.handoffs import Handoff |
| 37 | +from agents.items import TResponseInputItem, TResponseStreamEvent |
| 38 | +from agents.model_settings import ModelSettings |
| 39 | +from agents.models.interface import Model, ModelTracing |
| 40 | +from agents.tool import Tool |
| 41 | + |
| 42 | + |
| 43 | +@function_tool |
| 44 | +def search_web(query: str) -> str: |
| 45 | + """The only real tool on the agent.""" |
| 46 | + return f"results for: {query}" |
| 47 | + |
| 48 | + |
| 49 | +class ScriptedModel(Model): |
| 50 | + """Plays back a fixed script of model responses so the example runs offline.""" |
| 51 | + |
| 52 | + def __init__(self, scripted_outputs: list[list[Any]]) -> None: |
| 53 | + self._outputs = list(scripted_outputs) |
| 54 | + |
| 55 | + async def get_response(self, *args: Any, **kwargs: Any) -> ModelResponse: |
| 56 | + output = self._outputs.pop(0) if self._outputs else [] |
| 57 | + return ModelResponse(output=output, usage=Usage(), response_id="scripted") |
| 58 | + |
| 59 | + def stream_response( # pragma: no cover - not exercised here |
| 60 | + self, |
| 61 | + system_instructions: str | None, |
| 62 | + input: str | list[TResponseInputItem], |
| 63 | + model_settings: ModelSettings, |
| 64 | + tools: list[Tool], |
| 65 | + output_schema: AgentOutputSchemaBase | None, |
| 66 | + handoffs: list[Handoff], |
| 67 | + tracing: ModelTracing, |
| 68 | + *, |
| 69 | + previous_response_id: str | None = None, |
| 70 | + conversation_id: str | None = None, |
| 71 | + prompt: Any | None = None, |
| 72 | + ) -> AsyncIterator[TResponseStreamEvent]: |
| 73 | + raise NotImplementedError("streaming not used in this example") |
| 74 | + |
| 75 | + |
| 76 | +def on_tool_not_found(data: ToolNotFoundErrorHandlerInput[Any]) -> ToolNotFoundAction: |
| 77 | + """Build a model-visible error so the model can pick a valid tool on its next step.""" |
| 78 | + available = ", ".join(data.available_tools) or "(none)" |
| 79 | + return ToolNotFoundAction( |
| 80 | + error_message=( |
| 81 | + f"Tool {data.tool_name!r} is not registered on this agent. " |
| 82 | + f"Available tools: [{available}]. Pick one of those and try again." |
| 83 | + ) |
| 84 | + ) |
| 85 | + |
| 86 | + |
| 87 | +async def main() -> None: |
| 88 | + # Turn 1: the model hallucinates a tool that doesn't exist. |
| 89 | + # Turn 2: after the handler injects the error, the model recovers with a final answer. |
| 90 | + scripted_model = ScriptedModel( |
| 91 | + [ |
| 92 | + [ |
| 93 | + ResponseFunctionToolCall( |
| 94 | + id="call-1", |
| 95 | + call_id="call-1", |
| 96 | + type="function_call", |
| 97 | + name="search_linkedin", # intentionally unknown |
| 98 | + arguments='{"query": "Anthropic"}', |
| 99 | + ) |
| 100 | + ], |
| 101 | + [ |
| 102 | + ResponseOutputMessage.model_validate( |
| 103 | + { |
| 104 | + "id": "msg-1", |
| 105 | + "type": "message", |
| 106 | + "role": "assistant", |
| 107 | + "status": "completed", |
| 108 | + "content": [ |
| 109 | + { |
| 110 | + "type": "output_text", |
| 111 | + "text": "Sorry, I used the wrong tool. Here's what I got from search_web instead.", |
| 112 | + "annotations": [], |
| 113 | + "logprobs": [], |
| 114 | + } |
| 115 | + ], |
| 116 | + } |
| 117 | + ) |
| 118 | + ], |
| 119 | + ] |
| 120 | + ) |
| 121 | + |
| 122 | + agent = Agent( |
| 123 | + name="recoverable_agent", |
| 124 | + instructions="You are a helpful assistant.", |
| 125 | + model=scripted_model, |
| 126 | + tools=[search_web], |
| 127 | + ) |
| 128 | + |
| 129 | + result = await Runner.run( |
| 130 | + agent, |
| 131 | + input="find me profiles related to Anthropic", |
| 132 | + error_handlers={"tool_not_found": on_tool_not_found}, |
| 133 | + ) |
| 134 | + |
| 135 | + print("Final output:") |
| 136 | + print(result.final_output) |
| 137 | + |
| 138 | + |
| 139 | +if __name__ == "__main__": |
| 140 | + asyncio.run(main()) |
0 commit comments