Repository navigation
Expand file tree
/
Copy pathexecutor.py
More file actions
117 lines (96 loc) · 3.94 KB
/
Copy pathexecutor.py
File metadata and controls
117 lines (96 loc) · 3.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""Safe execution engine for running registered tools with isolation and limits."""
import asyncio
import time
from typing import TYPE_CHECKING, Any
from pydantic import ValidationError
from agentkit.tools.models import ToolCall, ToolResult
if TYPE_CHECKING:
from agentkit.tools.registry import ToolRegistry
def _truncate_output(output: str, max_chars: int) -> str:
"""Keep a truncation notice inside the configured output character budget."""
marker = f"\n[Output truncated: exceeded {max_chars} character limit]"
if max_chars <= len(marker):
return marker[:max_chars]
return output[: max_chars - len(marker)] + marker
async def execute_tool(
registry: "ToolRegistry",
tool_call: ToolCall,
default_timeout_s: float = 15.0,
max_chars: int = 2000,
) -> ToolResult:
"""Safely execute a tool call against the registry.
Enforces argument validation, timeouts, sync/async dispatch, output truncation,
and catches all exceptions without raising into the caller.
Args:
registry: The ToolRegistry containing registered tools.
tool_call: The tool call request with name and arguments.
default_timeout_s: Maximum execution duration allowed in seconds.
max_chars: Maximum character length for output before truncation.
Returns:
Structured ToolResult.
"""
start_time = time.perf_counter()
def get_latency_ms() -> int:
return max(0, int((time.perf_counter() - start_time) * 1000))
# 1. Lookup tool in registry
entry = registry.get(tool_call.name)
if entry is None:
return ToolResult.failure(
f"Tool '{tool_call.name}' is not registered.",
latency_ms=get_latency_ms(),
)
# 2. Validate arguments with dynamic Pydantic model
try:
validated_args = entry.args_model(**tool_call.arguments)
kwargs = validated_args.model_dump()
except ValidationError as exc:
return ToolResult.failure(
f"Validation error for tool '{tool_call.name}': {exc}",
latency_ms=get_latency_ms(),
)
except Exception as exc:
return ToolResult.failure(
f"Argument parsing error for tool '{tool_call.name}': {exc}",
latency_ms=get_latency_ms(),
)
# 3. Execute tool with per-tool timeout
try:
async with asyncio.timeout(default_timeout_s):
if entry.is_async:
raw_output: Any = await entry.func(**kwargs)
else:
raw_output = await asyncio.to_thread(entry.func, **kwargs)
latency_ms = get_latency_ms()
if isinstance(raw_output, ToolResult):
updates: dict[str, Any] = {}
if raw_output.latency_ms == 0:
updates["latency_ms"] = latency_ms
if raw_output.ok and len(raw_output.output) > max_chars:
updates["output"] = _truncate_output(raw_output.output, max_chars)
updates["truncated"] = True
return raw_output.model_copy(update=updates) if updates else raw_output
# Format output as string
output_str = raw_output if isinstance(raw_output, str) else str(raw_output)
# Truncate if output exceeds max_chars limit
if len(output_str) > max_chars:
truncated_str = _truncate_output(output_str, max_chars)
return ToolResult.success(
truncated_str,
latency_ms=latency_ms,
truncated=True,
)
return ToolResult.success(
output_str,
latency_ms=latency_ms,
truncated=False,
)
except TimeoutError:
return ToolResult.failure(
f"Tool '{tool_call.name}' timed out after {default_timeout_s}s.",
latency_ms=get_latency_ms(),
)
except Exception as exc:
return ToolResult.failure(
f"Error executing tool '{tool_call.name}': {exc}",
latency_ms=get_latency_ms(),
)