mirror of
https://github.com/CJackHwang/ds2api.git
synced 2026-05-05 17:05:32 +08:00
Preserve SSE frame delimiters when injecting Gemini usage
This commit is contained in:
@@ -162,6 +162,13 @@ func injectStreamUsageMetadata(chunk []byte, target sdktranslator.Format, usage
|
||||
if target != sdktranslator.FormatGemini {
|
||||
return chunk
|
||||
}
|
||||
suffix := ""
|
||||
switch {
|
||||
case bytes.HasSuffix(chunk, []byte("\n\n")):
|
||||
suffix = "\n\n"
|
||||
case bytes.HasSuffix(chunk, []byte("\n")):
|
||||
suffix = "\n"
|
||||
}
|
||||
text := strings.TrimSpace(string(chunk))
|
||||
if text == "" {
|
||||
return chunk
|
||||
@@ -194,7 +201,10 @@ func injectStreamUsageMetadata(chunk []byte, target sdktranslator.Format, usage
|
||||
return chunk
|
||||
}
|
||||
if hasDataPrefix {
|
||||
return []byte("data: " + string(b))
|
||||
return []byte("data: " + string(b) + suffix)
|
||||
}
|
||||
if suffix != "" {
|
||||
return append(b, []byte(suffix)...)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
@@ -63,3 +63,15 @@ func TestOpenAIStreamTranslatorWriterPreservesKeepAliveComment(t *testing.T) {
|
||||
t.Fatalf("expected keep-alive comment passthrough, got %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectStreamUsageMetadataPreservesSSEFrameTerminator(t *testing.T) {
|
||||
chunk := []byte("data: {\"candidates\":[{\"index\":0}],\"model\":\"gemini-2.5-pro\"}\n\n")
|
||||
usage := openAIUsage{PromptTokens: 11, CompletionTokens: 29, TotalTokens: 40}
|
||||
got := injectStreamUsageMetadata(chunk, sdktranslator.FormatGemini, usage)
|
||||
if !strings.HasSuffix(string(got), "\n\n") {
|
||||
t.Fatalf("expected injected chunk to preserve \\n\\n frame terminator, got %q", string(got))
|
||||
}
|
||||
if !strings.Contains(string(got), `"usageMetadata"`) {
|
||||
t.Fatalf("expected usageMetadata injected, got %q", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user