Execute a tool by name with parameters
(
&self,
name: &str,
params: &Bound<'_, PyDict>,
py: Python<'_>,
)
| 249 | |
| 250 | /// Execute a tool by name with parameters |
| 251 | pub fn execute_tool( |
| 252 | &self, |
| 253 | name: &str, |
| 254 | params: &Bound<'_, PyDict>, |
| 255 | py: Python<'_>, |
| 256 | ) -> PyResult<ToolResult> { |
| 257 | let start_time = Instant::now(); |
| 258 | |
| 259 | // Get the tool function |
| 260 | let function = { |
| 261 | let tools = self.tools.read().map_err(|e| { |
| 262 | PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!( |
| 263 | "Failed to acquire tools lock: {}", |
| 264 | e |
| 265 | )) |
| 266 | })?; |
| 267 | |
| 268 | tools.get(name).map(|f| f.clone_ref(py)).ok_or_else(|| { |
| 269 | PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!("Tool '{}' not found", name)) |
| 270 | })? |
| 271 | }; |
| 272 | |
| 273 | // Convert parameters to string for logging |
| 274 | let params_str = params.repr()?.to_string(); |
| 275 | |
| 276 | // Execute the tool |
| 277 | let result = match function.call(py, (), Some(params)) { |
| 278 | Ok(result) => { |
| 279 | let duration = start_time.elapsed().as_millis() as u64; |
| 280 | let output = result.to_string(); |
| 281 | |
| 282 | // Record execution in metadata |
| 283 | self.record_tool_execution(name, duration)?; |
| 284 | |
| 285 | let tool_result = ToolResult::new(name.to_string(), params_str, output, duration); |
| 286 | |
| 287 | // Add to execution history |
| 288 | self.add_to_history(tool_result.clone())?; |
| 289 | |
| 290 | tool_result |
| 291 | } |
| 292 | Err(e) => { |
| 293 | let duration = start_time.elapsed().as_millis() as u64; |
| 294 | let error_msg = format!("Tool execution failed: {}", e); |
| 295 | |
| 296 | let tool_result = |
| 297 | ToolResult::failure(name.to_string(), params_str, error_msg, duration); |
| 298 | |
| 299 | // Add to execution history even for failures |
| 300 | self.add_to_history(tool_result.clone())?; |
| 301 | |
| 302 | tool_result |
| 303 | } |
| 304 | }; |
| 305 | |
| 306 | Ok(result) |
| 307 | } |
| 308 |