Skip to content

Commit e976aff

Browse files
docs: Add a comprehensive example for handling function tool errors. (#1354)
1 parent 65cb91c commit e976aff

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

docs/tools.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,4 +319,25 @@ When you create a function tool via `@function_tool`, you can pass a `failure_er
319319
- If you pass your own error function, it runs that instead, and sends the response to the LLM.
320320
- If you explicitly pass `None`, then any tool call errors will be re-raised for you to handle. This could be a `ModelBehaviorError` if the model produced invalid JSON, or a `UserError` if your code crashed, etc.
321321

322+
```python
323+
from agents import function_tool, RunContextWrapper
324+
from typing import Any
325+
326+
def my_custom_error_function(context: RunContextWrapper[Any], error: Exception) -> str:
327+
"""A custom function to provide a user-friendly error message."""
328+
print(f"A tool call failed with the following error: {error}")
329+
return "An internal server error occurred. Please try again later."
330+
331+
@function_tool(failure_error_function=my_custom_error_function)
332+
def get_user_profile(user_id: str) -> str:
333+
"""Fetches a user profile from a mock API.
334+
This function demonstrates a 'flaky' or failing API call.
335+
"""
336+
if user_id == "user_123":
337+
return "User profile for user_123 successfully retrieved."
338+
else:
339+
raise ValueError(f"Could not retrieve profile for user_id: {user_id}. API returned an error.")
340+
341+
```
342+
322343
If you are manually creating a `FunctionTool` object, then you must handle errors inside the `on_invoke_tool` function.

0 commit comments

Comments
 (0)