mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
perf(gemini): stop copying the emitted prefix on every stream delta
computeGeminiTextDelta returned seen+incoming for each incremental chunk, so a long thinking, text or tool-argument block copied its whole prefix per chunk and grew quadratically. Keep the emitted text in a strings.Builder per block. Only storage changes: the cumulative, duplicate/rewind and delta decisions and the returned deltas are identical, verified against the previous implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d446c4a6bb
commit
00660a227a
3 files changed
+99
-27
No files matched your search
@@ -596,11 +596,11 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
|
||||
nextBlockIndex := 0
|
||||
openBlockIndex := -1
|
||||
openBlockType := ""
|
||||
seenText := ""
|
||||
seenThought := ""
|
||||
var seenText geminiTextDelta
|
||||
var seenThought geminiTextDelta
|
||||
openToolIndex := -1
|
||||
openToolName := ""
|
||||
seenToolJSON := ""
|
||||
var seenToolJSON geminiTextDelta
|
||||
|
||||
closeOpenBlock := func() bool {
|
||||
if openBlockIndex < 0 {
|
||||
@@ -618,7 +618,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
|
||||
disconnected := emitAnthropicEvent(&apicompat.AnthropicStreamEvent{Type: "content_block_stop"})
|
||||
openToolIndex = -1
|
||||
openToolName = ""
|
||||
seenToolJSON = ""
|
||||
seenToolJSON.reset()
|
||||
return disconnected
|
||||
}
|
||||
|
||||
@@ -653,8 +653,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
|
||||
|
||||
for _, part := range extractGeminiParts(geminiResp) {
|
||||
if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) {
|
||||
delta, newSeen := computeGeminiTextDelta(seenThought, text)
|
||||
seenThought = newSeen
|
||||
delta := seenThought.next(text)
|
||||
if delta == "" {
|
||||
continue
|
||||
}
|
||||
@@ -693,8 +692,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
|
||||
return streamResult(), nil
|
||||
}
|
||||
}
|
||||
delta, newSeen := computeGeminiTextDelta(seenText, text)
|
||||
seenText = newSeen
|
||||
delta := seenText.next(text)
|
||||
if delta == "" {
|
||||
continue
|
||||
}
|
||||
@@ -774,8 +772,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
|
||||
argsJSONText = string(b)
|
||||
}
|
||||
}
|
||||
delta, newSeen := computeGeminiTextDelta(seenToolJSON, argsJSONText)
|
||||
seenToolJSON = newSeen
|
||||
delta := seenToolJSON.next(argsJSONText)
|
||||
if delta != "" {
|
||||
if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{
|
||||
Type: "content_block_delta",
|
||||
|
||||
@@ -2209,12 +2209,12 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
|
||||
nextBlockIndex := 0
|
||||
openBlockIndex := -1
|
||||
openBlockType := ""
|
||||
seenText := ""
|
||||
seenThought := ""
|
||||
var seenText geminiTextDelta
|
||||
var seenThought geminiTextDelta
|
||||
openToolIndex := -1
|
||||
openToolID := ""
|
||||
openToolName := ""
|
||||
seenToolJSON := ""
|
||||
var seenToolJSON geminiTextDelta
|
||||
|
||||
reader := newBoundedSSELineReader(resp.Body, s.cfg)
|
||||
for {
|
||||
@@ -2269,8 +2269,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
|
||||
parts := extractGeminiParts(geminiResp)
|
||||
for _, part := range parts {
|
||||
if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) {
|
||||
delta, newSeen := computeGeminiTextDelta(seenThought, text)
|
||||
seenThought = newSeen
|
||||
delta := seenThought.next(text)
|
||||
if delta == "" {
|
||||
continue
|
||||
}
|
||||
@@ -2281,7 +2280,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
|
||||
})
|
||||
openToolIndex = -1
|
||||
openToolName = ""
|
||||
seenToolJSON = ""
|
||||
seenToolJSON.reset()
|
||||
}
|
||||
if openBlockType != "thinking" {
|
||||
if openBlockIndex >= 0 {
|
||||
@@ -2332,11 +2331,10 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
|
||||
})
|
||||
openToolIndex = -1
|
||||
openToolName = ""
|
||||
seenToolJSON = ""
|
||||
seenToolJSON.reset()
|
||||
}
|
||||
|
||||
delta, newSeen := computeGeminiTextDelta(seenText, text)
|
||||
seenText = newSeen
|
||||
delta := seenText.next(text)
|
||||
if delta == "" {
|
||||
continue
|
||||
}
|
||||
@@ -2402,7 +2400,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
|
||||
})
|
||||
openToolIndex = -1
|
||||
openToolName = ""
|
||||
seenToolJSON = ""
|
||||
seenToolJSON.reset()
|
||||
}
|
||||
|
||||
if openToolIndex < 0 {
|
||||
@@ -2438,8 +2436,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
|
||||
}
|
||||
}
|
||||
|
||||
delta, newSeen := computeGeminiTextDelta(seenToolJSON, argsJSONText)
|
||||
seenToolJSON = newSeen
|
||||
delta := seenToolJSON.next(argsJSONText)
|
||||
if delta != "" {
|
||||
writeSSE(c.Writer, "content_block_delta", map[string]any{
|
||||
"type": "content_block_delta",
|
||||
@@ -3426,22 +3423,38 @@ func extractGeminiParts(geminiResp map[string]any) []map[string]any {
|
||||
return nil
|
||||
}
|
||||
|
||||
func computeGeminiTextDelta(seen, incoming string) (delta, newSeen string) {
|
||||
// geminiTextDelta tracks the text already emitted for one stream block. Only the
|
||||
// storage differs from concatenating strings: appends are amortized, so
|
||||
// delta-mode streams no longer copy the whole prefix on every chunk.
|
||||
type geminiTextDelta struct {
|
||||
seen strings.Builder
|
||||
}
|
||||
|
||||
// next returns the part of incoming that has not been emitted yet.
|
||||
func (d *geminiTextDelta) next(incoming string) string {
|
||||
incoming = strings.TrimSuffix(incoming, "\u0000")
|
||||
if incoming == "" {
|
||||
return "", seen
|
||||
return ""
|
||||
}
|
||||
seen := d.seen.String()
|
||||
|
||||
// Cumulative mode: incoming contains full text so far.
|
||||
if strings.HasPrefix(incoming, seen) {
|
||||
return strings.TrimPrefix(incoming, seen), incoming
|
||||
delta := incoming[len(seen):]
|
||||
_, _ = d.seen.WriteString(delta)
|
||||
return delta
|
||||
}
|
||||
// Duplicate/rewind: ignore.
|
||||
if strings.HasPrefix(seen, incoming) {
|
||||
return "", seen
|
||||
return ""
|
||||
}
|
||||
// Delta mode: treat incoming as incremental chunk.
|
||||
return incoming, seen + incoming
|
||||
_, _ = d.seen.WriteString(incoming)
|
||||
return incoming
|
||||
}
|
||||
|
||||
func (d *geminiTextDelta) reset() {
|
||||
d.seen.Reset()
|
||||
}
|
||||
|
||||
func mapGeminiFinishReasonToClaudeStopReason(finishReason string) string {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// legacyComputeGeminiTextDelta is the previous string-concatenating
|
||||
// implementation, kept as the oracle for the storage-only change.
|
||||
func legacyComputeGeminiTextDelta(seen, incoming string) (delta, newSeen string) {
|
||||
incoming = strings.TrimSuffix(incoming, "\u0000")
|
||||
if incoming == "" {
|
||||
return "", seen
|
||||
}
|
||||
if strings.HasPrefix(incoming, seen) {
|
||||
return strings.TrimPrefix(incoming, seen), incoming
|
||||
}
|
||||
if strings.HasPrefix(seen, incoming) {
|
||||
return "", seen
|
||||
}
|
||||
return incoming, seen + incoming
|
||||
}
|
||||
|
||||
func TestGeminiTextDeltaMatchesLegacy(t *testing.T) {
|
||||
sequences := [][]string{
|
||||
{"Hel", "Hello", "Hello, wor", "Hello, world"}, // cumulative
|
||||
{"Hel", "lo", ", wor", "ld"}, // incremental
|
||||
{"The", " cat", "The", " sat"}, // delta equal to an emitted prefix
|
||||
{"abc", "abc", "ab", "abcd", "x"}, // duplicate, rewind, extend, diverge
|
||||
{"", "\u0000", "a\u0000", "ab", "", "abc\u0000"}, // empty and NUL-terminated chunks
|
||||
{"{\"a\":", "{\"a\":1", "}", "{\"a\":1}"}, // tool args mixing modes
|
||||
{"多字节", "多字节文本", "😀", "多字节文本😀继续"}, // non-ASCII
|
||||
}
|
||||
for _, seq := range sequences {
|
||||
var state geminiTextDelta
|
||||
legacySeen := ""
|
||||
for i, chunk := range seq {
|
||||
wantDelta, newSeen := legacyComputeGeminiTextDelta(legacySeen, chunk)
|
||||
legacySeen = newSeen
|
||||
require.Equal(t, wantDelta, state.next(chunk), "sequence %q chunk %d", seq, i)
|
||||
require.Equal(t, legacySeen, state.seen.String(), "sequence %q chunk %d", seq, i)
|
||||
}
|
||||
state.reset()
|
||||
require.Equal(t, "", state.seen.String())
|
||||
require.Equal(t, "fresh", state.next("fresh"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiTextDeltaIncrementalAllocationsStayLinear(t *testing.T) {
|
||||
chunk := strings.Repeat("x", 100)
|
||||
const chunks = 2000
|
||||
allocs := testing.AllocsPerRun(5, func() {
|
||||
var state geminiTextDelta
|
||||
for i := 0; i < chunks; i++ {
|
||||
_ = state.next(chunk)
|
||||
}
|
||||
})
|
||||
// Concatenation allocates once per chunk; amortized growth needs O(log n).
|
||||
require.Less(t, allocs, float64(100), "allocs per stream: %v", allocs)
|
||||
}
|
||||
Reference in new issue
Block a user