File size: 5,331 Bytes
2b9a95b | 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | """
API Tool Executor for CausalGame agent.
This module provides the APIToolExecutor class that executes tool calls
against the CanyonClient. The client is explicitly passed in - no hidden injection.
"""
import json
from dataclasses import dataclass
from enum import Enum
from typing import Dict, Any, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from agent.client import CanyonClient
class ToolResultStatus(Enum):
"""Status of a tool execution result."""
SUCCESS = "success"
ERROR = "error"
NOT_FOUND = "not_found"
@dataclass
class ToolResult:
"""
Structured result from a tool execution.
Attributes:
status: Execution status (success, error, not_found)
data: The actual result data (dict, list, etc.)
error: Error message if status is error
tool_name: Name of the tool that was executed
"""
status: ToolResultStatus
data: Optional[Any] = None
error: Optional[str] = None
tool_name: str = ""
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for JSON serialization."""
result = {
"status": self.status.value,
"tool_name": self.tool_name,
}
if self.data is not None:
result["data"] = self.data
if self.error:
result["error"] = self.error
return result
def to_string(self) -> str:
"""Convert to string representation for LLM consumption."""
if self.status == ToolResultStatus.ERROR:
return f"Error executing {self.tool_name}: {self.error}"
elif self.status == ToolResultStatus.NOT_FOUND:
return f"Unknown tool: {self.tool_name}"
else:
# Format data nicely
if isinstance(self.data, (dict, list)):
return json.dumps(self.data, indent=2, default=str)
return str(self.data)
class APIToolExecutor:
"""
Executes API tool calls against the Canyon backend.
The CanyonClient is explicitly passed in during initialization,
ensuring clear dependency management with no hidden injection.
"""
def __init__(self, client: "CanyonClient"):
"""
Initialize the executor with an explicit client reference.
Args:
client: The CanyonClient instance to use for API calls
"""
self._client = client
@property
def client(self) -> "CanyonClient":
"""Get the underlying client (read-only access)."""
return self._client
def execute(self, tool_name: str, params: Dict[str, Any]) -> ToolResult:
"""
Execute a tool call and return structured result.
Args:
tool_name: Name of the tool to execute
params: Parameters for the tool call
Returns:
ToolResult with status, data, and any errors
"""
try:
# Dispatch to appropriate method
handler = self._get_handler(tool_name)
if handler is None:
return ToolResult(
status=ToolResultStatus.NOT_FOUND,
tool_name=tool_name,
error=f"Unknown tool: {tool_name}",
)
data = handler(params)
return ToolResult(
status=ToolResultStatus.SUCCESS,
data=data,
tool_name=tool_name,
)
except Exception as e:
return ToolResult(
status=ToolResultStatus.ERROR,
tool_name=tool_name,
error=str(e),
)
def _get_handler(self, tool_name: str):
"""Get the handler function for a tool."""
handlers = {
"get_status": self._handle_get_status,
"get_history": self._handle_get_history,
"get_action_space": self._handle_get_action_space,
"deploy_drone": self._handle_deploy_drone,
"submit_final_design": self._handle_submit_final_design,
}
return handlers.get(tool_name)
# =========================================================================
# Tool Handlers
# =========================================================================
def _handle_get_status(self, params: Dict[str, Any]) -> Dict[str, Any]:
"""Handle get_status tool call."""
return self._client.get_status()
def _handle_get_history(self, params: Dict[str, Any]) -> Any:
"""Handle get_history tool call."""
return self._client.get_history()
def _handle_get_action_space(self, params: Dict[str, Any]) -> Dict[str, Any]:
"""Handle get_action_space tool call."""
return self._client.get_action_space()
def _handle_deploy_drone(self, params: Dict[str, Any]) -> Dict[str, Any]:
"""Handle deploy_drone tool call."""
design = params.get("design", {})
count = params.get("count", 1)
equipment = params.get("equipment")
return self._client.deploy_drone(design, count, equipment)
def _handle_submit_final_design(self, params: Dict[str, Any]) -> Dict[str, Any]:
"""Handle submit_final_design tool call."""
design = params.get("design", {})
equipment = params.get("equipment")
return self._client.submit_final_design(design, equipment)
|