Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat(agent-tools): format ValidationError as model-friendly tool result

xf gongfa1db45fc772
diff --git a/cubepi/agent/tools.py b/cubepi/agent/tools.py
index 1bea0f7..59d2790 100644
--- a/cubepi/agent/tools.py
+++ b/cubepi/agent/tools.py
@@ -67,6 +67,50 @@ def _error_result(message: str) -> AgentToolResult:
return AgentToolResult(content=[TextContent(text=message)])
+def _format_validation_error(exc: ValidationError, tool_name: str) -> str:
+ """Render a pydantic ValidationError as text the LLM can act on.
+
+ The default ``str(exc)`` leaks pydantic-internal model names and a
+ documentation URL — the model can read it but cannot reliably extract
+ the fix from it. This produces one short line per error, naming the
+ field path, the constraint, and (for discriminated unions) the allowed
+ discriminator values, so the model can correct the call without
+ another round-trip.
+ """
+ lines = [f"Invalid arguments for tool '{tool_name}':"]
+ for err in exc.errors():
+ loc_parts = [str(p) for p in err.get("loc", ())]
+ loc = ".".join(loc_parts) if loc_parts else "<root>"
+ etype = err.get("type", "")
+ msg = err.get("msg", "")
+ ctx = err.get("ctx") or {}
+
+ if etype == "union_tag_not_found":
+ # pydantic stores discriminator wrapped in single quotes, e.g.
+ # "'operation'" — strip for readability. expected_tags is not
+ # populated for this error type; the model has the JSON Schema
+ # to enumerate allowed values.
+ disc = str(ctx.get("discriminator", "?")).strip("'\"")
+ lines.append(f"- {loc}: missing required discriminator key '{disc}'")
+ elif etype == "union_tag_invalid":
+ disc = str(ctx.get("discriminator", "?")).strip("'\"")
+ tag = ctx.get("tag", "")
+ allowed = ctx.get("expected_tags") or ""
+ lines.append(
+ f"- {loc}: discriminator '{disc}'={tag!r} is not one of: {allowed}"
+ )
+ elif etype == "missing":
+ lines.append(f"- {loc}: field required")
+ elif etype == "literal_error":
+ expected = ctx.get("expected", "")
+ lines.append(f"- {loc}: must be one of {expected}")
+ elif etype == "extra_forbidden":
+ lines.append(f"- {loc}: unexpected field")
+ else:
+ lines.append(f"- {loc}: {msg}")
+ return "\n".join(lines)
+
+
def _merge_hitl_details(base: Any, hitl: dict | None) -> Any:
if hitl is None:
return base
@@ -114,7 +158,10 @@ async def _prepare_tool_call(
try:
validated_args = tool.parameters.model_validate(tool_call.arguments)
except ValidationError as exc:
- return _ImmediateOutcome(result=_error_result(str(exc)), is_error=True)
+ return _ImmediateOutcome(
+ result=_error_result(_format_validation_error(exc, tool.name)),
+ is_error=True,
+ )
except Exception as exc: # pragma: no cover — defensive
return _ImmediateOutcome(result=_error_result(str(exc)), is_error=True)
@@ -149,7 +196,10 @@ async def _prepare_tool_call(
before_result.edited_args
)
except ValidationError as exc: # pragma: no cover — defensive
- return _ImmediateOutcome(result=_error_result(str(exc)), is_error=True)
+ return _ImmediateOutcome(
+ result=_error_result(_format_validation_error(exc, tool.name)),
+ is_error=True,
+ )
hitl_trace_carry = before_result.hitl_trace if before_result else None
else:
diff --git a/tests/agent/test_tools.py b/tests/agent/test_tools.py
index f1af592..8ceebf4 100644
--- a/tests/agent/test_tools.py
+++ b/tests/agent/test_tools.py
@@ -372,6 +372,124 @@ class TestToolExecutionError:
assert batch.messages[0].is_error
+class TestValidationErrorFormatting:
+ """Pin the contract that ValidationError text is model-friendly.
+
+ A raw str(ValidationError) names pydantic's internal model class and
+ points at the pydantic docs site, which the LLM cannot act on. The
+ formatter must produce field-path-anchored lines the model can use to
+ self-correct without a second round-trip.
+ """
+
+ async def test_missing_required_field_names_the_field(self):
+ tool = make_echo_tool()
+ ctx = make_context([tool])
+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={})])
+
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential", emit=lambda e: None
+ )
+
+ text = batch.messages[0].content[0].text
+ assert "Invalid arguments for tool 'echo'" in text
+ assert "value" in text
+ assert "field required" in text
+ # Raw pydantic decoration must NOT leak to the model.
+ assert "errors.pydantic.dev" not in text
+ assert "validation error" not in text.lower()[: len("validation error")] or (
+ "validation error" not in text.lower().split("\n")[0]
+ )
+
+ async def test_discriminator_failure_lists_allowed_tags(self):
+ from typing import Annotated, Literal, Union
+
+ from pydantic import Field, RootModel
+
+ class ListOp(BaseModel):
+ operation: Literal["list"]
+
+ class CreateOp(BaseModel):
+ operation: Literal["create"]
+ name: str
+
+ union_type = Annotated[
+ Union[ListOp, CreateOp],
+ Field(discriminator="operation"),
+ ]
+ union_root = RootModel[union_type]
+
+ async def execute_fn(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="ok")])
+
+ tool = AgentTool(
+ name="opt",
+ description="discriminated tool",
+ parameters=union_root,
+ execute=execute_fn,
+ )
+ ctx = make_context([tool])
+
+ msg = make_assistant_msg(
+ [ToolCall(id="t1", name="opt", arguments={"operation": "delete"})]
+ )
+
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential", emit=lambda e: None
+ )
+
+ text = batch.messages[0].content[0].text
+ assert "discriminator" in text
+ # Allowed tags must be enumerated so the model can self-correct.
+ assert "list" in text
+ assert "create" in text
+
+ async def test_missing_discriminator_key_is_named(self):
+ from typing import Annotated, Literal, Union
+
+ from pydantic import Field, RootModel
+
+ class ListOp(BaseModel):
+ operation: Literal["list"]
+
+ class CreateOp(BaseModel):
+ operation: Literal["create"]
+ name: str
+
+ union_type = Annotated[
+ Union[ListOp, CreateOp],
+ Field(discriminator="operation"),
+ ]
+ union_root = RootModel[union_type]
+
+ async def execute_fn(tool_call_id, params, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text="ok")])
+
+ tool = AgentTool(
+ name="opt",
+ description="discriminated tool",
+ parameters=union_root,
+ execute=execute_fn,
+ )
+ ctx = make_context([tool])
+
+ # Wrong top-level key — pydantic raises union_tag_not_found.
+ # That error type does not carry expected_tags in its ctx, but the
+ # error must still name the discriminator key so the model can find
+ # it in the tool's JSON Schema and self-correct.
+ msg = make_assistant_msg(
+ [ToolCall(id="t1", name="opt", arguments={"action": "list"})]
+ )
+
+ batch = await execute_tool_calls(
+ ctx, msg, tool_execution="sequential", emit=lambda e: None
+ )
+
+ text = batch.messages[0].content[0].text
+ assert "missing required discriminator key 'operation'" in text
+ # Surrounding quotes from pydantic's ctx must be stripped.
+ assert "''operation''" not in text
+
+
class TestTermination:
async def test_all_terminate_stops_loop(self):
async def term_execute(tool_call_id, params, *, signal=None, on_update=None):