优化工具调用

This commit is contained in:
2026-03-13 22:22:14 +08:00
parent 083afe583c
commit 2d2992d66d
6 changed files with 498 additions and 46 deletions
+4 -1
View File
@@ -179,7 +179,10 @@ class AgentRuntime:
tool_event = {
"tool_name": tool_call.name,
"arguments": tool_call.arguments,
"result": result,
"result": result.as_dict(
name=tool_call.name,
arguments=tool_call.arguments,
),
"run_id": inbound.run_id,
}
tool_events.append(tool_event)
+9 -2
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
import json
from typing import Callable
from prompt_toolkit import PromptSession
@@ -263,8 +264,8 @@ def _build_key_bindings() -> KeyBindings:
def _render_tool_event(event: dict, index: int) -> Panel:
arguments = str(event.get("arguments") or "{}")
result = str(event.get("result") or "")
arguments = _stringify_tool_payload(event.get("arguments") or {})
result = _stringify_tool_payload(event.get("result") or {})
if len(result) > 800:
result = result[:800] + "\n...[truncated]"
@@ -279,6 +280,12 @@ def _render_tool_event(event: dict, index: int) -> Panel:
)
def _stringify_tool_payload(value: object) -> str:
if isinstance(value, (dict, list)):
return json.dumps(value, ensure_ascii=False, indent=2)
return str(value)
def _build_reply_subtitle(result: dict) -> str:
tool_count = len(result.get("tool_events") or [])
provider = result.get("provider_id") or "?"
+203 -11
View File
@@ -3,11 +3,40 @@
from __future__ import annotations
import json
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any
class ToolValidationError(ValueError):
"""Raised when tool arguments fail local validation."""
@dataclass(slots=True)
class ToolResult:
"""Structured tool execution result."""
ok: bool
data: Any = None
error: dict[str, Any] | None = None
meta: dict[str, Any] = field(default_factory=dict)
def as_dict(self, *, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
payload: dict[str, Any] = {
"tool": name,
"arguments": arguments,
"ok": self.ok,
}
if self.data is not None:
payload["data"] = self.data
if self.error is not None:
payload["error"] = self.error
if self.meta:
payload["meta"] = self.meta
return payload
class Tool(ABC):
"""Base tool definition."""
@@ -16,9 +45,12 @@ class Tool(ABC):
parameters: dict[str, Any]
@abstractmethod
def execute(self, arguments: dict[str, Any]) -> str:
def execute(self, arguments: dict[str, Any]) -> ToolResult:
"""Execute a tool call."""
def validate_arguments(self, arguments: dict[str, Any]) -> None:
validate_object_schema(arguments, self.parameters)
def schema(self) -> dict[str, Any]:
return {
"type": "function",
@@ -29,6 +61,29 @@ class Tool(ABC):
},
}
@staticmethod
def success(
data: Any = None,
*,
meta: dict[str, Any] | None = None,
) -> ToolResult:
return ToolResult(ok=True, data=data, meta=meta or {})
@staticmethod
def failure(
code: str,
message: str,
*,
data: Any = None,
meta: dict[str, Any] | None = None,
) -> ToolResult:
return ToolResult(
ok=False,
data=data,
error={"code": code, "message": message},
meta=meta or {},
)
@dataclass(slots=True)
class ToolRegistry:
@@ -45,24 +100,161 @@ class ToolRegistry:
def summaries(self) -> list[str]:
return [f"{tool.name}: {tool.description}" for tool in self._tools.values()]
def execute(self, name: str, arguments: dict[str, Any]) -> str:
def execute(self, name: str, arguments: dict[str, Any]) -> ToolResult:
tool = self._tools.get(name)
if tool is None:
return f"Tool '{name}' is not registered."
return Tool.failure(
"tool_not_registered",
f"Tool '{name}' is not registered.",
)
try:
tool.validate_arguments(arguments)
return tool.execute(arguments)
except ToolValidationError as exc:
return Tool.failure("validation_error", str(exc))
except Exception as exc:
return f"Tool '{name}' failed: {exc}"
return Tool.failure(
"execution_error",
f"Tool '{name}' failed: {exc}",
meta={"exception_type": type(exc).__name__},
)
@staticmethod
def stringify_result(name: str, arguments: dict[str, Any], result: str) -> str:
preview = result if len(result) <= 4000 else result[:4000] + "\n...[truncated]"
def stringify_result(
name: str,
arguments: dict[str, Any],
result: ToolResult,
) -> str:
return json.dumps(
{
"tool": name,
"arguments": arguments,
"result": preview,
},
result.as_dict(name=name, arguments=arguments),
ensure_ascii=False,
indent=2,
)
def paginate_items(
items: list[Any],
*,
page: int,
page_size: int,
) -> tuple[list[Any], dict[str, Any]]:
"""Return one page from a list-like payload."""
if page < 1:
raise ValueError("page must be greater than or equal to 1")
if page_size < 1:
raise ValueError("page_size must be greater than or equal to 1")
total_items = len(items)
total_pages = max(1, math.ceil(total_items / page_size)) if total_items else 1
if page > total_pages:
raise ValueError(
f"page {page} is out of range; valid pages are 1..{total_pages}"
)
start = (page - 1) * page_size
end = start + page_size
return items[start:end], {
"page": page,
"page_size": page_size,
"total_pages": total_pages,
"total_items": total_items,
"has_next_page": page < total_pages,
"has_previous_page": page > 1,
}
def paginate_text(
text: str,
*,
page: int,
page_size: int,
) -> tuple[str, dict[str, Any]]:
"""Return one page from a text payload."""
if page < 1:
raise ValueError("page must be greater than or equal to 1")
if page_size < 1:
raise ValueError("page_size must be greater than or equal to 1")
total_chars = len(text)
total_pages = max(1, math.ceil(total_chars / page_size)) if total_chars else 1
if page > total_pages:
raise ValueError(
f"page {page} is out of range; valid pages are 1..{total_pages}"
)
start = (page - 1) * page_size
end = start + page_size
return text[start:end], {
"page": page,
"page_size": page_size,
"total_pages": total_pages,
"total_chars": total_chars,
"has_next_page": page < total_pages,
"has_previous_page": page > 1,
}
def validate_object_schema(arguments: dict[str, Any], schema: dict[str, Any]) -> None:
"""Validate a small JSON-schema-like object payload."""
if not isinstance(arguments, dict):
raise ToolValidationError("arguments must be an object")
issues: list[str] = []
properties = schema.get("properties") or {}
required = schema.get("required") or []
for key in required:
if key not in arguments:
issues.append(f"missing required field '{key}'")
if schema.get("additionalProperties") is False:
unknown = sorted(key for key in arguments if key not in properties)
if unknown:
issues.append(
"unexpected fields: " + ", ".join(f"'{key}'" for key in unknown)
)
for key, value in arguments.items():
property_schema = properties.get(key)
if property_schema is None:
continue
_validate_value(path=key, value=value, schema=property_schema, issues=issues)
if issues:
raise ToolValidationError("; ".join(issues))
def _validate_value(
*,
path: str,
value: Any,
schema: dict[str, Any],
issues: list[str],
) -> None:
expected_type = schema.get("type")
if expected_type == "string":
if not isinstance(value, str):
issues.append(f"field '{path}' must be a string")
return
min_length = schema.get("minLength")
if isinstance(min_length, int) and len(value) < min_length:
issues.append(
f"field '{path}' must be at least {min_length} characters long"
)
elif expected_type == "integer":
if isinstance(value, bool) or not isinstance(value, int):
issues.append(f"field '{path}' must be an integer")
return
minimum = schema.get("minimum")
if isinstance(minimum, int) and value < minimum:
issues.append(f"field '{path}' must be greater than or equal to {minimum}")
maximum = schema.get("maximum")
if isinstance(maximum, int) and value > maximum:
issues.append(f"field '{path}' must be less than or equal to {maximum}")
elif expected_type == "object":
if not isinstance(value, dict):
issues.append(f"field '{path}' must be an object")
return
enum_values = schema.get("enum")
if isinstance(enum_values, list) and value not in enum_values:
issues.append(
f"field '{path}' must be one of: "
+ ", ".join(repr(item) for item in enum_values)
)
+78 -11
View File
@@ -5,48 +5,89 @@ from __future__ import annotations
from pathlib import Path
from typing import Any
from voidbot.tools.base import Tool
from voidbot.tools.base import Tool, paginate_items, paginate_text
class ListDirTool(Tool):
name = "list_dir"
description = "List files and directories under a relative path."
description = "List files and directories under a relative path with pagination."
parameters = {
"type": "object",
"additionalProperties": False,
"properties": {
"path": {
"type": "string",
"description": "Relative path inside the workspace.",
},
"page": {
"type": "integer",
"description": "1-based result page.",
"minimum": 1,
},
"page_size": {
"type": "integer",
"description": "Number of directory entries per page.",
"minimum": 1,
"maximum": 500,
},
},
}
def __init__(self, workspace: Path):
self.workspace = workspace
def execute(self, arguments: dict[str, Any]) -> str:
def execute(self, arguments: dict[str, Any]):
target = _resolve_workspace_path(
self.workspace, str(arguments.get("path") or ".")
)
if not target.exists():
return f"{target} does not exist."
return self.failure("not_found", f"{target} does not exist.")
rows = []
for child in sorted(target.iterdir(), key=lambda item: item.name):
suffix = "/" if child.is_dir() else ""
rows.append(f"{child.relative_to(self.workspace)}{suffix}")
return "\n".join(rows) or "(empty directory)"
page = int(arguments.get("page") or 1)
page_size = int(arguments.get("page_size") or 100)
try:
entries, pagination = paginate_items(rows, page=page, page_size=page_size)
except ValueError as exc:
return self.failure("page_out_of_range", str(exc))
relative_path = (
"."
if target == self.workspace
else str(target.relative_to(self.workspace))
)
return self.success(
data={
"path": relative_path,
"entries": entries,
},
meta={"pagination": pagination},
)
class ReadFileTool(Tool):
name = "read_file"
description = "Read a UTF-8 text file inside the workspace."
description = "Read a UTF-8 text file inside the workspace with pagination."
parameters = {
"type": "object",
"additionalProperties": False,
"properties": {
"path": {
"type": "string",
"description": "Relative path inside the workspace.",
},
"page": {
"type": "integer",
"description": "1-based result page.",
"minimum": 1,
},
"page_size": {
"type": "integer",
"description": "Number of UTF-8 characters per page.",
"minimum": 256,
"maximum": 12000,
},
},
"required": ["path"],
}
@@ -54,9 +95,27 @@ class ReadFileTool(Tool):
def __init__(self, workspace: Path):
self.workspace = workspace
def execute(self, arguments: dict[str, Any]) -> str:
def execute(self, arguments: dict[str, Any]):
target = _resolve_workspace_path(self.workspace, str(arguments["path"]))
return target.read_text(encoding="utf-8")
content = target.read_text(encoding="utf-8")
page = int(arguments.get("page") or 1)
page_size = int(arguments.get("page_size") or 2000)
try:
page_content, pagination = paginate_text(
content,
page=page,
page_size=page_size,
)
except ValueError as exc:
return self.failure("page_out_of_range", str(exc))
return self.success(
data={
"path": str(target.relative_to(self.workspace)),
"encoding": "utf-8",
"content": page_content,
},
meta={"pagination": pagination},
)
class WriteFileTool(Tool):
@@ -64,6 +123,7 @@ class WriteFileTool(Tool):
description = "Write a UTF-8 text file inside the workspace."
parameters = {
"type": "object",
"additionalProperties": False,
"properties": {
"path": {
"type": "string",
@@ -77,11 +137,18 @@ class WriteFileTool(Tool):
def __init__(self, workspace: Path):
self.workspace = workspace
def execute(self, arguments: dict[str, Any]) -> str:
def execute(self, arguments: dict[str, Any]):
target = _resolve_workspace_path(self.workspace, str(arguments["path"]))
content = str(arguments["content"])
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(str(arguments["content"]), encoding="utf-8")
return f"wrote {target.relative_to(self.workspace)}"
target.write_text(content, encoding="utf-8")
return self.success(
data={
"path": str(target.relative_to(self.workspace)),
"bytes_written": len(content.encode("utf-8")),
"encoding": "utf-8",
}
)
def _resolve_workspace_path(workspace: Path, raw_path: str) -> Path:
+122 -21
View File
@@ -3,49 +3,150 @@
from __future__ import annotations
import subprocess
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from voidbot.tools.base import Tool
from voidbot.tools.base import Tool, ToolValidationError, paginate_text
@dataclass(slots=True)
class CommandExecutionRecord:
"""Stored command execution for follow-up pagination requests."""
execution_id: str
command: str
exit_code: int
stdout: str
stderr: str
class RunCommandTool(Tool):
name = "run_command"
description = (
"Run a shell command inside the workspace and capture stdout and stderr."
"Run a shell command inside the workspace and capture paginated stdout/stderr."
)
parameters = {
"type": "object",
"additionalProperties": False,
"properties": {
"command": {"type": "string", "description": "Shell command to execute."},
"command": {
"type": "string",
"description": "Shell command to execute for a new run.",
"minLength": 1,
},
"execution_id": {
"type": "string",
"description": "Existing command execution id for reading another page.",
"minLength": 1,
},
"stream": {
"type": "string",
"description": "Which output stream to read.",
"enum": ["combined", "stdout", "stderr"],
},
"timeout": {
"type": "integer",
"description": "Timeout in seconds.",
"minimum": 1,
"maximum": 600,
},
"page": {
"type": "integer",
"description": "1-based output page.",
"minimum": 1,
},
"page_size": {
"type": "integer",
"description": "Number of characters per page.",
"minimum": 256,
"maximum": 12000,
},
},
"required": ["command"],
}
def __init__(self, workspace: Path):
self.workspace = workspace
self._executions: dict[str, CommandExecutionRecord] = {}
def execute(self, arguments: dict[str, Any]) -> str:
timeout = int(arguments.get("timeout") or 120)
completed = subprocess.run(
arguments["command"],
cwd=self.workspace,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
stdout = completed.stdout.strip()
stderr = completed.stderr.strip()
return (
f"exit_code: {completed.returncode}\n"
f"stdout:\n{stdout or '(empty)'}\n"
f"stderr:\n{stderr or '(empty)'}"
def validate_arguments(self, arguments: dict[str, Any]) -> None:
super().validate_arguments(arguments)
has_command = "command" in arguments
has_execution_id = "execution_id" in arguments
if has_command == has_execution_id:
raise ToolValidationError(
"provide exactly one of 'command' or 'execution_id'"
)
if has_execution_id and "timeout" in arguments:
raise ToolValidationError(
"field 'timeout' can only be used when 'command' is provided"
)
def execute(self, arguments: dict[str, Any]):
stream = str(arguments.get("stream") or "combined")
page = int(arguments.get("page") or 1)
page_size = int(arguments.get("page_size") or 2000)
if "execution_id" in arguments:
record = self._executions.get(str(arguments["execution_id"]))
if record is None:
return self.failure(
"not_found",
f"execution_id '{arguments['execution_id']}' was not found",
)
else:
timeout = int(arguments.get("timeout") or 120)
completed = subprocess.run(
str(arguments["command"]),
cwd=self.workspace,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
record = CommandExecutionRecord(
execution_id=uuid.uuid4().hex,
command=str(arguments["command"]),
exit_code=completed.returncode,
stdout=completed.stdout.strip(),
stderr=completed.stderr.strip(),
)
self._executions[record.execution_id] = record
try:
content, pagination = paginate_text(
_render_stream(record, stream),
page=page,
page_size=page_size,
)
except ValueError as exc:
return self.failure("page_out_of_range", str(exc))
return self.success(
data={
"execution_id": record.execution_id,
"command": record.command,
"exit_code": record.exit_code,
"stream": stream,
"content": content,
},
meta={
"pagination": pagination,
"stdout_chars": len(record.stdout),
"stderr_chars": len(record.stderr),
},
)
def _render_stream(record: CommandExecutionRecord, stream: str) -> str:
if stream == "stdout":
return record.stdout or "(empty)"
if stream == "stderr":
return record.stderr or "(empty)"
return (
f"exit_code: {record.exit_code}\n"
f"stdout:\n{record.stdout or '(empty)'}\n"
f"stderr:\n{record.stderr or '(empty)'}"
)
+82
View File
@@ -0,0 +1,82 @@
from __future__ import annotations
import sys
import tempfile
import unittest
from pathlib import Path
from voidbot.tools import build_default_tool_registry
class ToolRegistryTests(unittest.TestCase):
def test_validation_rejects_unexpected_fields(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
(workspace / "hello.txt").write_text("hello", encoding="utf-8")
registry = build_default_tool_registry(workspace)
result = registry.execute(
"read_file",
{"path": "hello.txt", "unexpected": True},
)
self.assertFalse(result.ok)
self.assertEqual(result.error, {"code": "validation_error", "message": "unexpected fields: 'unexpected'"})
def test_read_file_returns_paginated_structured_result(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
content = "a" * 2500
(workspace / "big.txt").write_text(content, encoding="utf-8")
registry = build_default_tool_registry(workspace)
result = registry.execute(
"read_file",
{"path": "big.txt", "page": 2, "page_size": 1000},
)
self.assertTrue(result.ok)
self.assertEqual(result.data["path"], "big.txt")
self.assertEqual(result.data["content"], content[1000:2000])
self.assertEqual(result.meta["pagination"]["page"], 2)
self.assertEqual(result.meta["pagination"]["total_pages"], 3)
self.assertTrue(result.meta["pagination"]["has_next_page"])
def test_run_command_supports_follow_up_pagination_without_rerun(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
workspace = Path(temp_dir)
registry = build_default_tool_registry(workspace)
command = (
f'{sys.executable} -c '
"\"print(''.join(str(i % 10) for i in range(5000)))\""
)
first = registry.execute(
"run_command",
{"command": command, "stream": "stdout", "page_size": 1999},
)
self.assertTrue(first.ok)
execution_id = first.data["execution_id"]
second = registry.execute(
"run_command",
{
"execution_id": execution_id,
"stream": "stdout",
"page": 2,
"page_size": 1999,
},
)
self.assertTrue(second.ok)
self.assertEqual(second.data["execution_id"], execution_id)
self.assertEqual(second.meta["pagination"]["page"], 2)
self.assertEqual(second.meta["pagination"]["total_pages"], 3)
self.assertEqual(len(first.data["content"]), 1999)
self.assertEqual(len(second.data["content"]), 1999)
self.assertNotEqual(first.data["content"], second.data["content"])
if __name__ == "__main__":
unittest.main()