executeToolCalls
(ctx *gin.Context, _ http.ResponseWriter, _, _ string, toolCalls []openai.ToolCall, messages []openai.ChatCompletionMessage)
| 590 | |
| 591 | // executeToolCalls |
| 592 | func (c *AIController) executeToolCalls(ctx *gin.Context, _ http.ResponseWriter, _, _ string, toolCalls []openai.ToolCall, messages []openai.ChatCompletionMessage) []openai.ChatCompletionMessage { |
| 593 | validToolCalls := make([]openai.ToolCall, 0) |
| 594 | for _, toolCall := range toolCalls { |
| 595 | if toolCall.ID == "" || toolCall.Function.Name == "" { |
| 596 | log.Errorf("Invalid tool call: missing required fields. ID: %s, Function: %v", toolCall.ID, toolCall.Function) |
| 597 | continue |
| 598 | } |
| 599 | |
| 600 | if toolCall.Function.Arguments == "" { |
| 601 | toolCall.Function.Arguments = "{}" |
| 602 | } |
| 603 | |
| 604 | validToolCalls = append(validToolCalls, toolCall) |
| 605 | log.Debugf("Valid tool call: ID=%s, Name=%s, Arguments=%s", toolCall.ID, toolCall.Function.Name, toolCall.Function.Arguments) |
| 606 | } |
| 607 | |
| 608 | if len(validToolCalls) == 0 { |
| 609 | log.Warn("No valid tool calls found") |
| 610 | return messages |
| 611 | } |
| 612 | |
| 613 | assistantMsg := openai.ChatCompletionMessage{ |
| 614 | Role: openai.ChatMessageRoleAssistant, |
| 615 | ToolCalls: validToolCalls, |
| 616 | } |
| 617 | messages = append(messages, assistantMsg) |
| 618 | |
| 619 | for _, toolCall := range validToolCalls { |
| 620 | if toolCall.Function.Name != "" { |
| 621 | var args map[string]any |
| 622 | if err := json.Unmarshal([]byte(toolCall.Function.Arguments), &args); err != nil { |
| 623 | log.Errorf("Failed to parse tool arguments for %s: %v, arguments: %s", toolCall.Function.Name, err, toolCall.Function.Arguments) |
| 624 | errorResult := fmt.Sprintf("Error parsing tool arguments: %v", err) |
| 625 | toolMessage := openai.ChatCompletionMessage{ |
| 626 | Role: openai.ChatMessageRoleTool, |
| 627 | Content: errorResult, |
| 628 | ToolCallID: toolCall.ID, |
| 629 | } |
| 630 | messages = append(messages, toolMessage) |
| 631 | continue |
| 632 | } |
| 633 | |
| 634 | result, err := c.callMCPTool(ctx, toolCall.Function.Name, args) |
| 635 | if err != nil { |
| 636 | log.Errorf("Failed to call MCP tool %s: %v", toolCall.Function.Name, err) |
| 637 | result = fmt.Sprintf("Error calling tool %s: %v", toolCall.Function.Name, err) |
| 638 | } |
| 639 | |
| 640 | toolMessage := openai.ChatCompletionMessage{ |
| 641 | Role: openai.ChatMessageRoleTool, |
| 642 | Content: result, |
| 643 | ToolCallID: toolCall.ID, |
| 644 | } |
| 645 | messages = append(messages, toolMessage) |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | return messages |
no test coverage detected