MCPcopy Index your code
hub / github.com/apache/answer / processAIStream

Method processAIStream

internal/controller/ai_controller.go:472–589  ·  view source on GitHub ↗

processAIStream

(
	_ *gin.Context, w http.ResponseWriter, id, model string, client *openai.Client, aiReq openai.ChatCompletionRequest, messages []openai.ChatCompletionMessage)

Source from the content-addressed store, hash-verified

470
471// processAIStream
472func (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 }

Callers 1

handleAIConversationMethod · 0.95

Calls 4

sendErrorResponseMethod · 0.95
sendStreamDataFunction · 0.85
CloseMethod · 0.65
InfoMethod · 0.65

Tested by

no test coverage detected