fix: optimize Gemini stream parsing to support real-time streaming of JSON arrays
This commit is contained in:
@@ -3,6 +3,7 @@ package providers
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gophergate/internal/models"
|
||||
@@ -209,3 +210,57 @@ func TestEmitGeminiChunk_ToolCalls(t *testing.T) {
|
||||
t.Fatalf("expected response on channel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamGeminiJSONArrayStream(t *testing.T) {
|
||||
input := `[
|
||||
{
|
||||
"candidates": [
|
||||
{
|
||||
"content": {
|
||||
"parts": [
|
||||
{"text": "Hello"}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"candidates": [
|
||||
{
|
||||
"content": {
|
||||
"parts": [
|
||||
{"text": " world"}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"usageMetadata": {
|
||||
"promptTokenCount": 5,
|
||||
"candidatesTokenCount": 2,
|
||||
"totalTokenCount": 7
|
||||
}
|
||||
}
|
||||
]`
|
||||
|
||||
ch := make(chan *models.ChatCompletionStreamResponse, 5)
|
||||
defer close(ch)
|
||||
|
||||
streamGeminiJSONArrayStream(strings.NewReader(input), ch, "gemini-2.5-flash")
|
||||
|
||||
var texts []string
|
||||
for i := 0; i < 2; i++ {
|
||||
select {
|
||||
case resp := <-ch:
|
||||
if len(resp.Choices) > 0 && resp.Choices[0].Delta.Content != nil {
|
||||
texts = append(texts, *resp.Choices[0].Delta.Content)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("expected chunk %d", i+1)
|
||||
}
|
||||
}
|
||||
|
||||
joined := strings.Join(texts, "")
|
||||
if joined != "Hello world" {
|
||||
t.Errorf("expected 'Hello world', got %q", joined)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user