processAIStream
( _ *gin.Context, w http.ResponseWriter, id, model string, client *openai.Client, aiReq openai.ChatCompletionRequest, messages []openai.ChatCompletionMessage)
| 470 | |
| 471 | // processAIStream |
| 472 | func (c *AIController) processAIStream( |
| 473 | _ *gin.Context, w http.ResponseWriter, id, model string, client *openai.Client, aiReq openai.ChatCompletionRequest, messages []openai.ChatCompletionMessage) ( |
| 474 | []openai.ToolCall, []openai.ChatCompletionMessage, bool, string) { |
| 475 | stream, err := client.CreateChatCompletionStream(context.Background(), aiReq) |
| 476 | if err != nil { |
| 477 | log.Errorf("Failed to create stream: %v", err) |
| 478 | c.sendErrorResponse(w, id, model, "Failed to create AI stream") |
| 479 | return nil, messages, true, "" |
| 480 | } |
| 481 | defer func() { |
| 482 | _ = stream.Close() |
| 483 | }() |
| 484 | |
| 485 | var currentToolCalls []openai.ToolCall |
| 486 | var accumulatedContent strings.Builder |
| 487 | var accumulatedMessage openai.ChatCompletionMessage |
| 488 | toolCallsMap := make(map[int]*openai.ToolCall) |
| 489 | |
| 490 | for { |
| 491 | response, err := stream.Recv() |
| 492 | if err != nil { |
| 493 | if err.Error() == "EOF" { |
| 494 | log.Info("Stream finished") |
| 495 | break |
| 496 | } |
| 497 | log.Errorf("Stream error: %v", err) |
| 498 | break |
| 499 | } |
| 500 | |
| 501 | if len(response.Choices) == 0 { |
| 502 | continue |
| 503 | } |
| 504 | |
| 505 | choice := response.Choices[0] |
| 506 | |
| 507 | if len(choice.Delta.ToolCalls) > 0 { |
| 508 | for _, deltaToolCall := range choice.Delta.ToolCalls { |
| 509 | index := *deltaToolCall.Index |
| 510 | |
| 511 | if _, exists := toolCallsMap[index]; !exists { |
| 512 | toolCallsMap[index] = &openai.ToolCall{ |
| 513 | ID: deltaToolCall.ID, |
| 514 | Type: deltaToolCall.Type, |
| 515 | Function: openai.FunctionCall{ |
| 516 | Name: deltaToolCall.Function.Name, |
| 517 | Arguments: deltaToolCall.Function.Arguments, |
| 518 | }, |
| 519 | } |
| 520 | } else { |
| 521 | if deltaToolCall.Function.Arguments != "" { |
| 522 | toolCallsMap[index].Function.Arguments += deltaToolCall.Function.Arguments |
| 523 | } |
| 524 | if deltaToolCall.Function.Name != "" { |
| 525 | toolCallsMap[index].Function.Name = deltaToolCall.Function.Name |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | } |
no test coverage detected