Skip to content

Commit c0cea52

Browse files
committed
Handle tool exceptions and report them as incomplete outputs
1 parent 59e01cc commit c0cea52

File tree

1 file changed

+53
-25
lines changed

1 file changed

+53
-25
lines changed

coagent/agents/react_agent/agent.py

Lines changed: 53 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -374,32 +374,60 @@ async def handle_function_call(
374374
result: mcputil.Result = await func.call(
375375
call_id=function_call.call_id, **args
376376
)
377-
async for event in result.events():
378-
if isinstance(event, mcputil.ProgressEvent):
379-
# Report progress to the context.
380-
tool_ctx.report_progress(
381-
progress=event.progress or 0,
382-
total=event.total or 0,
383-
message=event.message or "",
384-
)
385-
elif isinstance(event, mcputil.OutputEvent):
386-
return ToolCallOutputItem(
387-
raw_item=ResponseFunctionToolCallOutputItem(
388-
id="",
389-
call_id=function_call.call_id,
390-
output=str(event.output),
391-
type="function_call_output",
392-
status="completed",
393-
),
394-
output=event.output,
395-
type="tool_call_output_item",
396-
)
377+
try:
378+
async for event in result.events():
379+
if isinstance(event, mcputil.ProgressEvent):
380+
# Report progress to the context.
381+
tool_ctx.report_progress(
382+
progress=event.progress or 0,
383+
total=event.total or 0,
384+
message=event.message or "",
385+
)
386+
elif isinstance(event, mcputil.OutputEvent):
387+
return ToolCallOutputItem(
388+
raw_item=ResponseFunctionToolCallOutputItem(
389+
id="",
390+
call_id=function_call.call_id,
391+
output=str(event.output),
392+
type="function_call_output",
393+
status="completed",
394+
),
395+
output=event.output,
396+
type="tool_call_output_item",
397+
)
398+
except Exception as exc:
399+
# Handle tool exceptions and report them as incomplete outputs.
400+
return ToolCallOutputItem(
401+
raw_item=ResponseFunctionToolCallOutputItem(
402+
id="",
403+
call_id=function_call.call_id,
404+
output=str(exc),
405+
type="function_call_output",
406+
status="incomplete",
407+
),
408+
output=str(exc),
409+
type="tool_call_output_item",
410+
)
397411
else:
398-
raw_result = func(**args)
399-
if inspect.isawaitable(raw_result):
400-
result = await raw_result
401-
else:
402-
result = raw_result
412+
try:
413+
raw_result = func(**args)
414+
if inspect.isawaitable(raw_result):
415+
result = await raw_result
416+
else:
417+
result = raw_result
418+
except Exception as exc:
419+
# Handle tool exceptions and report them as incomplete outputs.
420+
return ToolCallOutputItem(
421+
raw_item=ResponseFunctionToolCallOutputItem(
422+
id="",
423+
call_id=function_call.call_id,
424+
output=str(exc),
425+
type="function_call_output",
426+
status="incomplete",
427+
),
428+
output=str(exc),
429+
type="tool_call_output_item",
430+
)
403431

404432
return ToolCallOutputItem(
405433
raw_item=ResponseFunctionToolCallOutputItem(

0 commit comments

Comments
 (0)