Skip to content

Commit 8fd9a7c

Browse files
feat: support run-wide tool exception formatting (#5326)
* feat: support run-wide tool exception formatting * fix: preserve tool formatter policies across factories and namespaces * fix: preserve released tool factory error policies
1 parent 71c2da4 commit 8fd9a7c

3 files changed

Lines changed: 601 additions & 2 deletions

File tree

‎src/agents/run_config.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class CallModelData(Generic[TContext]):
8383
class ToolErrorFormatterArgs(Generic[TContext]):
8484
"""Data passed to ``RunConfig.tool_error_formatter`` callbacks."""
8585

86-
kind: Literal["approval_rejected", "tool_not_found"]
86+
kind: Literal["approval_rejected", "tool_not_found", "tool_exception"]
8787
"""The category of tool error being formatted."""
8888

8989
tool_type: Literal["function", "computer", "shell", "apply_patch", "custom"]
@@ -101,6 +101,13 @@ class ToolErrorFormatterArgs(Generic[TContext]):
101101
run_context: RunContextWrapper[TContext]
102102
"""The active run context for the current execution."""
103103

104+
error: Exception | None = None
105+
"""The original exception for ``tool_exception``; otherwise ``None``.
106+
107+
This exception can contain sensitive data. Return only application-approved details;
108+
the SDK does not include the original exception in handled-error traces for this policy.
109+
"""
110+
104111

105112
ToolErrorFormatter = Callable[[ToolErrorFormatterArgs[Any]], MaybeAwaitable[str | None]]
106113

@@ -459,6 +466,15 @@ class RunConfig:
459466
"""Optional callback that formats tool error messages returned to the model.
460467
461468
Returning ``None`` falls back to the SDK default message.
469+
470+
For ordinary function-tool exceptions, this callback applies only when the tool uses
471+
the implicit default failure handler. Explicit per-tool handlers, including ``None``
472+
(propagate errors), take precedence. Tools created by ``Agent.as_tool()`` and local MCP
473+
factories retain their existing ``failure_error_function`` policies; this callback
474+
does not format their exceptions. Timeouts, cancellation, and schema-backed
475+
program-call failures retain their existing policies. A callback failure falls back
476+
to the default message. Returned messages may enter model input, history, and traces;
477+
return only application-approved details.
462478
"""
463479

464480
session_settings: SessionSettings | None = None

‎src/agents/tool.py‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
)
7474
from .computer import AsyncComputer, Computer
7575
from .editor import ApplyPatchEditor, ApplyPatchOperation
76-
from .exceptions import ModelBehaviorError, ToolTimeoutError, UserError
76+
from .exceptions import MCPToolCancellationError, ModelBehaviorError, ToolTimeoutError, UserError
7777
from .function_schema import DocstringStyle, function_schema, generate_func_documentation
7878
from .logger import log_tool_action_warning, logger
7979
from .run_context import RunContextWrapper
@@ -2091,6 +2091,36 @@ async def maybe_invoke_function_tool_failure_error_function(
20912091
result = await result
20922092
if function_tool._use_default_failure_error_function and isinstance(context, ToolContext):
20932093
setattr(context, _DEFAULT_FAILURE_HANDLED_ATTR, True)
2094+
if (
2095+
isinstance(error, Exception)
2096+
and not isinstance(error, MCPToolCancellationError)
2097+
and context.run_config is not None
2098+
and context.run_config.tool_error_formatter is not None
2099+
):
2100+
# Keep the default failure policy identity: approving model feedback must not
2101+
# opt the original exception into handled-error traces.
2102+
from .run_config import ToolErrorFormatterArgs
2103+
2104+
try:
2105+
message = context.run_config.tool_error_formatter(
2106+
ToolErrorFormatterArgs(
2107+
kind="tool_exception",
2108+
tool_type="function",
2109+
tool_name=context.qualified_tool_name,
2110+
call_id=context.tool_call_id,
2111+
default_message=result,
2112+
run_context=context,
2113+
error=error,
2114+
)
2115+
)
2116+
message = await message if inspect.isawaitable(message) else message
2117+
except Exception as exc:
2118+
log_tool_action_warning(logger, "Tool error formatter failed", exc)
2119+
else:
2120+
if isinstance(message, str):
2121+
return message
2122+
if message is not None:
2123+
logger.warning("Tool error formatter returned a non-string value")
20942124
return result
20952125

20962126

0 commit comments

Comments
 (0)