fix(messages): keep tool argument deltas on the open block

Blocks that follow an open tool_use block are queued and emitted at
stream end, so every delta targets the one open block.
This commit is contained in:
2026-11-29 00:24:57 +00:00
parent c3adbfe073
commit 7de4448b7d
2 changed files with 261 additions and 23 deletions
+114 -23
View File
@@ -45,8 +45,18 @@ type openAIStreamChunk struct {
}
type streamToolBlock struct {
id string
block int
queued *queuedBlock
id string
block int
}
// queuedBlock is a block that arrived while a tool_use block was open. It is
// emitted at stream end so every delta targets the one open block.
type queuedBlock struct {
typ string
id string
name string
buf strings.Builder
}
// anthropicStreamWriter is the http.ResponseWriter handed to a provider
@@ -61,7 +71,10 @@ type anthropicStreamWriter struct {
sse *sseWriter
model string
finishR string
queue []*queuedBlock
raw bytes.Buffer
queueCap int
queued int
mode int
next int
openIdx int
@@ -69,10 +82,11 @@ type anthropicStreamWriter struct {
done bool
hasOpen bool
textOpen bool
toolOpen bool
}
func newAnthropicStreamWriter(rw http.ResponseWriter, model string) *anthropicStreamWriter {
return &anthropicStreamWriter{rw: rw, model: model, tools: map[int]*streamToolBlock{}}
return &anthropicStreamWriter{rw: rw, model: model, tools: map[int]*streamToolBlock{}, queueCap: maxResponseBytes}
}
// Header implements http.ResponseWriter.
@@ -185,6 +199,7 @@ func (s *anthropicStreamWriter) closeBlock() error {
}
s.hasOpen = false
s.textOpen = false
s.toolOpen = false
return s.emit("content_block_stop", map[string]any{"type": "content_block_stop", "index": s.openIdx})
}
@@ -213,31 +228,14 @@ func (s *anthropicStreamWriter) handleChunk(data []byte) error {
ch := c.Choices[0]
if ch.Delta.Content != "" {
if !s.textOpen {
if err := s.openBlock(map[string]any{"type": "text", "text": ""}); err != nil {
return err
}
s.textOpen = true
}
if err := s.delta(s.openIdx, map[string]any{"type": "text_delta", "text": ch.Delta.Content}); err != nil {
if err := s.handleText(ch.Delta.Content); err != nil {
return err
}
}
for _, tc := range ch.Delta.ToolCalls {
tb, known := s.tools[tc.Index]
if !known || (tc.ID != "" && tb.id != "" && tc.ID != tb.id) {
err := s.openBlock(map[string]any{"type": "tool_use", "id": tc.ID, "name": tc.Function.Name, "input": map[string]any{}})
if err != nil {
return err
}
tb = &streamToolBlock{block: s.openIdx, id: tc.ID}
s.tools[tc.Index] = tb
}
if tc.Function.Arguments != "" {
if err := s.delta(tb.block, map[string]any{"type": "input_json_delta", "partial_json": tc.Function.Arguments}); err != nil {
return err
}
if err := s.handleToolCall(tc.Index, tc.ID, tc.Function.Name, tc.Function.Arguments); err != nil {
return err
}
}
@@ -247,6 +245,96 @@ func (s *anthropicStreamWriter) handleChunk(data []byte) error {
return nil
}
func (s *anthropicStreamWriter) handleText(text string) error {
if s.toolOpen {
tail := len(s.queue) - 1
if tail < 0 || s.queue[tail].typ != "text" {
s.queue = append(s.queue, &queuedBlock{typ: "text"})
tail++
}
return s.appendQueued(s.queue[tail], text)
}
if !s.textOpen {
if err := s.openBlock(map[string]any{"type": "text", "text": ""}); err != nil {
return err
}
s.textOpen = true
}
return s.delta(s.openIdx, map[string]any{"type": "text_delta", "text": text})
}
func (s *anthropicStreamWriter) handleToolCall(index int, id, name, args string) error {
tb, known := s.tools[index]
if !known || (id != "" && tb.id != "" && id != tb.id) {
tb = &streamToolBlock{id: id}
if s.toolOpen {
q := &queuedBlock{typ: "tool_use", id: id, name: name}
if err := s.reserveQueue(len(id) + len(name)); err != nil {
return err
}
s.queue = append(s.queue, q)
tb.queued = q
} else {
err := s.openBlock(map[string]any{"type": "tool_use", "id": id, "name": name, "input": map[string]any{}})
if err != nil {
return err
}
s.toolOpen = true
tb.block = s.openIdx
}
s.tools[index] = tb
}
if args == "" {
return nil
}
if tb.queued != nil {
return s.appendQueued(tb.queued, args)
}
return s.delta(tb.block, map[string]any{"type": "input_json_delta", "partial_json": args})
}
func (s *anthropicStreamWriter) reserveQueue(n int) error {
s.queued += n
if s.queued > s.queueCap {
return fmt.Errorf("%w: queued content blocks exceed %d bytes", errUpstream, s.queueCap)
}
return nil
}
func (s *anthropicStreamWriter) appendQueued(q *queuedBlock, text string) error {
if err := s.reserveQueue(len(text)); err != nil {
return err
}
q.buf.WriteString(text)
return nil
}
// flushQueue emits the blocks held back behind a tool_use block, in arrival order.
func (s *anthropicStreamWriter) flushQueue() error {
queue := s.queue
s.queue = nil
for _, q := range queue {
block := map[string]any{"type": "text", "text": ""}
deltaType, field := "text_delta", "text"
if q.typ == "tool_use" {
block = map[string]any{"type": "tool_use", "id": q.id, "name": q.name, "input": map[string]any{}}
deltaType, field = "input_json_delta", "partial_json"
}
if err := s.openBlock(block); err != nil {
return err
}
if q.buf.Len() > 0 {
if err := s.delta(s.openIdx, map[string]any{"type": deltaType, field: q.buf.String()}); err != nil {
return err
}
}
if err := s.closeBlock(); err != nil {
return err
}
}
return nil
}
// finish closes the open block and writes message_delta and message_stop.
// u is the adapter's final usage. On a JSON-mode upstream it replays the
// buffered response as events. Idempotent.
@@ -269,6 +357,9 @@ func (s *anthropicStreamWriter) stop(stopReason string, input, output int64) err
if err := s.closeBlock(); err != nil {
return err
}
if err := s.flushQueue(); err != nil {
return err
}
err := s.emit("message_delta", map[string]any{
"type": "message_delta",
"delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nil},
+147
View File
@@ -0,0 +1,147 @@
package traefikllmgateway
import (
"errors"
"fmt"
"net/http/httptest"
"strings"
"testing"
)
// assertAnthropicBlockSequence checks start/delta/stop nesting: a delta must
// target the one open block, blocks never overlap, indexes run 0..n-1.
// It returns the joined delta payload per block index.
func assertAnthropicBlockSequence(t *testing.T, events []anthEvent) map[int]string {
t.Helper()
joined := map[int]string{}
open := -1
next := 0
for i, e := range events {
idx, _ := e.data["index"].(float64)
switch e.name {
case "content_block_start":
if open != -1 {
t.Fatalf("event %d: start %d while block %d open", i, int(idx), open)
}
if int(idx) != next {
t.Fatalf("event %d: start index %d, want %d", i, int(idx), next)
}
open = int(idx)
next++
case "content_block_delta":
if int(idx) != open {
t.Fatalf("event %d: delta for block %d while open block is %d", i, int(idx), open)
}
d := sub(e.data, "delta")
for _, k := range []string{"partial_json", "text"} {
if v, ok := d[k].(string); ok {
joined[open] += v
}
}
case "content_block_stop":
if int(idx) != open {
t.Fatalf("event %d: stop %d while open block is %d", i, int(idx), open)
}
open = -1
case "message_delta":
if open != -1 {
t.Fatalf("event %d: message_delta with block %d open", i, open)
}
}
}
return joined
}
func toolFrame(index int, id, name, args string) string {
return fmt.Sprintf(`{"id":"c1","choices":[{"delta":{"tool_calls":[{"index":%d,"id":%q,"function":{"name":%q,"arguments":%q}}]}}]}`, index, id, name, args)
}
func textFrame(text string) string {
return fmt.Sprintf(`{"id":"c1","choices":[{"delta":{"content":%q}}]}`, text)
}
func blockStarts(evs []anthEvent) []map[string]any {
var out []map[string]any
for _, e := range evs {
if e.name == "content_block_start" {
out = append(out, sub(e.data, "content_block"))
}
}
return out
}
func TestAnthropicStreamWriter_InterleavedToolArgumentsStayOnOpenBlock(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
toolFrame(0, "call_a", "alpha", ""),
toolFrame(1, "call_b", "beta", ""),
toolFrame(0, "", "", `{"a":`),
toolFrame(1, "", "", `{"b":2}`),
toolFrame(0, "", "", `1}`),
)
joined := assertAnthropicBlockSequence(t, evs)
starts := blockStarts(evs)
if len(starts) != 2 || starts[0]["name"] != "alpha" || starts[1]["name"] != "beta" {
t.Fatalf("starts = %v", starts)
}
if joined[0] != `{"a":1}` || joined[1] != `{"b":2}` {
t.Fatalf("joined = %v", joined)
}
}
func TestAnthropicStreamWriter_TextAfterToolCallThenMoreArguments(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
toolFrame(0, "call_a", "alpha", `{"a":`),
textFrame("hello "),
textFrame("world"),
toolFrame(0, "", "", `1}`),
)
joined := assertAnthropicBlockSequence(t, evs)
starts := blockStarts(evs)
if len(starts) != 2 || starts[0]["type"] != "tool_use" || starts[1]["type"] != "text" {
t.Fatalf("starts = %v", starts)
}
if joined[0] != `{"a":1}` || joined[1] != "hello world" {
t.Fatalf("joined = %v", joined)
}
}
func TestAnthropicStreamWriter_SequentialToolCallsKeepAllArguments(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
toolFrame(0, "call_a", "alpha", `{"a":1}`),
toolFrame(1, "call_b", "beta", `{"b":2}`),
)
joined := assertAnthropicBlockSequence(t, evs)
starts := blockStarts(evs)
if len(starts) != 2 || starts[0]["name"] != "alpha" || starts[1]["name"] != "beta" {
t.Fatalf("starts = %v", starts)
}
if joined[0] != `{"a":1}` || joined[1] != `{"b":2}` {
t.Fatalf("joined = %v", joined)
}
}
func TestAnthropicStreamWriter_SingleToolCallStreamsLive(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "my-alias")
for _, f := range []string{toolFrame(0, "call_a", "alpha", ""), toolFrame(0, "", "", `{"a":1}`)} {
if _, err := sw.Write(oaiFrame(f)); err != nil {
t.Fatal(err)
}
}
if !strings.Contains(rec.Body.String(), `partial_json`) {
t.Fatalf("no delta written before finish: %s", rec.Body.String())
}
}
func TestAnthropicStreamWriter_QueuedBlocksOverCapFail(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "my-alias")
sw.queueCap = 8
if _, err := sw.Write(oaiFrame(toolFrame(0, "call_a", "alpha", ""))); err != nil {
t.Fatal(err)
}
_, err := sw.Write(oaiFrame(textFrame("this text is longer than the cap")))
if !errors.Is(err, errUpstream) {
t.Fatalf("err = %v, want errUpstream", err)
}
}