Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions python/copilot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
from .tools import (
Tool,
ToolBinaryResult,
ToolError,
ToolInvocation,
ToolResult,
ToolResultType,
Expand Down Expand Up @@ -223,6 +224,7 @@
"TelemetryConfig",
"Tool",
"ToolBinaryResult",
"ToolError",
"ToolInvocation",
"ToolResult",
"ToolResultType",
Expand Down
15 changes: 15 additions & 0 deletions python/copilot/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@
ToolResultType = Literal["success", "failure", "rejected", "denied", "timeout"]


class ToolError(Exception):
"""
Exception raised by tool handlers to return a failure result to the LLM.
Unlike other exceptions, the message is intentionally surfaced to the LLM.
"""


@dataclass
class ToolBinaryResult:
"""Binary content returned by a tool."""
Expand Down Expand Up @@ -215,6 +222,14 @@ async def wrapped_handler(invocation: ToolInvocation) -> ToolResult:

return _normalize_result(result)

except ToolError as exc:
msg = str(exc)
return ToolResult(
text_result_for_llm=msg,
result_type="failure",
error=msg,
)
Comment thread
idryzhov marked this conversation as resolved.

except Exception as exc:
# Don't expose detailed error information to the LLM for security reasons.
# The actual error is stored in the 'error' field for debugging.
Expand Down
25 changes: 25 additions & 0 deletions python/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from copilot import define_tool
from copilot.tools import (
ToolError,
ToolInvocation,
ToolResult,
_normalize_result,
Expand Down Expand Up @@ -197,6 +198,30 @@ def failing_tool(params: Params, invocation: ToolInvocation) -> str:
# But the actual error is stored internally
assert result.error == "secret error message"

async def test_tool_error_is_surfaced_to_llm(self):
class Params(BaseModel):
pass

@define_tool("failing", description="A failing tool")
def failing_tool(params: Params, invocation: ToolInvocation) -> str:
raise ToolError("public error message")

invocation = ToolInvocation(
session_id="s1",
tool_call_id="c1",
tool_name="failing",
arguments={},
)

result = await failing_tool.handler(invocation)

assert result.result_type == "failure"
assert result.text_result_for_llm == "public error message"
assert result.error == "public error message"
# ToolError must take the deliberate-failure path so the structured
# result reaches the LLM verbatim.
assert result._from_exception is False

async def test_function_style_api(self):
class Params(BaseModel):
value: str
Expand Down