executeSingleToolCommand executes a single tool command and returns the output.
(ctx context.Context, toolMap map[string]tools.Tool, toolName, argsStr string)
| 241 | |
| 242 | // executeSingleToolCommand executes a single tool command and returns the output. |
| 243 | func executeSingleToolCommand(ctx context.Context, toolMap map[string]tools.Tool, toolName, argsStr string) string { |
| 244 | slog.DebugContext(ctx, "Executing tool command", "tool", toolName, "args", argsStr) |
| 245 | |
| 246 | tool, exists := toolMap[toolName] |
| 247 | if !exists { |
| 248 | slog.WarnContext(ctx, "Tool not found for command execution", "tool", toolName) |
| 249 | return "Error: tool '" + toolName + "' not found" |
| 250 | } |
| 251 | if tool.Handler == nil { |
| 252 | slog.WarnContext(ctx, "Tool has no handler", "tool", toolName) |
| 253 | return "Error: tool '" + toolName + "' has no handler" |
| 254 | } |
| 255 | |
| 256 | argsJSON, err := json.Marshal(parseToolArgs(argsStr)) |
| 257 | if err != nil { |
| 258 | slog.WarnContext(ctx, "Failed to marshal tool arguments", "tool", toolName, "error", err) |
| 259 | return "Error: failed to marshal arguments for '" + toolName + "'" |
| 260 | } |
| 261 | |
| 262 | toolCall := tools.ToolCall{ |
| 263 | ID: "cmd_" + toolName, |
| 264 | Type: "function", |
| 265 | Function: tools.FunctionCall{ |
| 266 | Name: toolName, |
| 267 | Arguments: string(argsJSON), |
| 268 | }, |
| 269 | } |
| 270 | |
| 271 | toolCtx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 272 | defer cancel() |
| 273 | |
| 274 | result, err := tool.Handler(toolCtx, toolCall) |
| 275 | if err != nil { |
| 276 | slog.WarnContext(ctx, "Tool execution failed", "tool", toolName, "error", err) |
| 277 | return "Error executing '" + toolName + "': " + err.Error() |
| 278 | } |
| 279 | |
| 280 | output := strings.TrimSpace(result.Output) |
| 281 | slog.DebugContext(ctx, "Tool command output", "tool", toolName, "output_length", len(output)) |
| 282 | return output |
| 283 | } |
| 284 | |
| 285 | // parseToolArgs parses key=value pairs from a tool command argument string. |
| 286 | func parseToolArgs(argsStr string) map[string]any { |
no test coverage detected