@@ -419,3 +419,52 @@ async def fake_run(
419419
420420 with pytest .raises (RuntimeError , match = "test failure" ):
421421 await tool .on_invoke_tool (tool_context , '{"input": "hello"}' )
422+
423+
424+ @pytest .mark .asyncio
425+ async def test_agent_as_tool_failure_error_function_custom_handler (
426+ monkeypatch : pytest .MonkeyPatch ,
427+ ) -> None :
428+ """Custom failure_error_function should be used to convert exceptions into tool output."""
429+ agent = Agent (name = "failing_agent" )
430+
431+ async def fake_run (
432+ cls ,
433+ starting_agent ,
434+ input ,
435+ * ,
436+ context ,
437+ max_turns ,
438+ hooks ,
439+ run_config ,
440+ previous_response_id ,
441+ conversation_id ,
442+ session ,
443+ ):
444+ assert starting_agent is agent
445+ assert input == "hello"
446+ raise ValueError ("test failure" )
447+
448+ monkeypatch .setattr (Runner , "run" , classmethod (fake_run ))
449+
450+ def custom_failure_handler (ctx : RunContextWrapper [Any ], error : Exception ) -> str :
451+ return f"handled:{ type (error ).__name__ } :{ error } "
452+
453+ tool = agent .as_tool (
454+ tool_name = "failing_agent_tool" ,
455+ tool_description = "Agent tool that raises" ,
456+ is_enabled = True ,
457+ failure_error_function = custom_failure_handler ,
458+ )
459+
460+ assert isinstance (tool , FunctionTool )
461+
462+ tool_context = ToolContext (
463+ context = None ,
464+ tool_name = "failing_agent_tool" ,
465+ tool_call_id = "call_1" ,
466+ tool_arguments = '{"input": "hello"}' ,
467+ )
468+
469+ result = await tool .on_invoke_tool (tool_context , '{"input": "hello"}' )
470+ assert result == "handled:ValueError:test failure"
0 commit comments