feat(messages): stream /v1/messages responses

A request with "stream": true on POST /v1/messages now gets the
Anthropic Messages event stream instead of a 400. Claude Code streams
every call, so the route must stream before it can front an
OpenAI-compatible cluster.

For openai and gemini providers, the gateway asks the upstream for a
stream with include_usage and translates each chunk as it arrives. It
emits message_start, one content block group per text or tool_use
block, then message_delta and message_stop. Tool call arguments arrive
as input_json_delta. The stop reason uses the non-streaming mapping.

For anthropic providers, the gateway relays each upstream event and
rewrites only message.model in message_start. An upstream error event
reaches the client once, as sent.

Billing uses the stream usage. An error before the stream starts gets
the normal JSON error. An error after the start ends the stream with an
error event. Streams are never cached. yaegi-check now drives a
streamed request under the interpreter.
This commit is contained in:
2026-11-27 01:00:14 +00:00
parent df1ca8cde2
commit e5f8e352b9
11 changed files with 1169 additions and 168 deletions
+31 -15
View File
@@ -2424,22 +2424,38 @@ A few translation specifics worth knowing:
target; the gateway logs a warning naming the dropped field rather
than discarding it silently.
### Streaming is not yet supported
### Streaming
`"stream"` set to anything other than the JSON literal `false`, `null`,
or an absent key gets a clean **400** `invalid_request_error` — never
silently ignored, never answered non-streamed. `null` is treated the
same as unset, so an SDK that serializes an unset optional field as
explicit `null` never gets a false-positive rejection on an ordinary
non-streaming call. This is deliberately a 400, not a 501: Anthropic's
own SDKs retry any status ≥ 500, so a 501 here would turn every
streaming call — the default for Claude Code — into a multi-request
retry storm against the caller's own request-rate limit. The rejection
happens *before* the rate limiter runs, so a streaming-rejected request
never consumes budget either. A follow-up release adds the Anthropic SSE
event translator (`message_start`/`content_block_delta`/`message_stop`)
— a genuinely different event model from OpenAI's own stream shape this
plugin already forwards on `/v1/chat/completions`.
Set `"stream": true` and the route answers with the Anthropic Messages
event stream (`text/event-stream`). Any value other than `false`, `null`
or an absent key counts as streaming. The gateway flushes each event as
it arrives and never buffers the whole stream.
- **`openai` and `gemini` providers:** the gateway asks the upstream for a
stream with `stream_options.include_usage: true` and translates each
chunk. The client sees `message_start`, then one
`content_block_start`/`content_block_delta`/`content_block_stop` group
per block, then `message_delta` (stop reason, token usage) and
`message_stop`. Text arrives as `text_delta`. Each OpenAI tool call
becomes a `tool_use` block whose arguments arrive as
`input_json_delta`. The stop reason uses the same mapping as a
non-streaming answer. `message.model` is the model the client asked
for. OpenAI reports prompt tokens only in its last chunk, so
`message_start` carries `input_tokens: 0` and `message_delta` carries
the real `input_tokens` and `output_tokens`.
- **`anthropic` providers:** the gateway relays each upstream event
unchanged, except that `message.model` in `message_start` becomes the
model the client asked for. An upstream `error` event reaches the
client as is.
- **Billing** uses the stream's own usage: the last OpenAI usage chunk,
or the `message_start` input and cache tokens plus the `message_delta`
output tokens for an Anthropic stream. A stream that reports no usage
is accounted like a stream on `/v1/chat/completions`.
- **Errors:** an upstream error before the stream starts gets the normal
Anthropic JSON error. After the stream starts, the gateway sends
`event: error` with `{"type":"error","error":{"type":"api_error",...}}`
and ends the stream without `message_stop`.
- Streams are never cached.
### Route takeover
+3
View File
@@ -15,6 +15,9 @@ import (
// later tasks' SSE streaming depends on Flush passing through.
type statusTrackingWriter struct {
http.ResponseWriter
// sseError, when set, writes a mid-stream failure in the route's own SSE
// error shape instead of the OpenAI one.
sseError func(msg string)
wroteHeader bool
}
+403
View File
@@ -0,0 +1,403 @@
package traefikllmgateway
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
// anthropicStreamErrorType is the error.type of an in-stream Anthropic error event.
const anthropicStreamErrorType = "api_error"
const (
streamModeUnset = iota
streamModeSSE
streamModeJSON
)
// openAIStreamChunk is the subset of one OpenAI chat.completion.chunk the
// Anthropic translator reads. Null "content" and "finish_reason" decode to "".
type openAIStreamChunk struct {
ID string `json:"id"`
Error json.RawMessage `json:"error"`
Usage *chatStreamUsage `json:"usage"`
Choices []struct {
FinishReason string `json:"finish_reason"`
Delta struct {
Content string `json:"content"`
ToolCalls []struct {
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
ID string `json:"id"`
Index int `json:"index"`
} `json:"tool_calls"`
} `json:"delta"`
} `json:"choices"`
}
type streamToolBlock struct {
id string
block int
}
// anthropicStreamWriter is the http.ResponseWriter handed to a provider
// adapter's chatCompletion on a streaming /v1/messages request. The adapter
// writes OpenAI chunk frames; this writer re-emits them as the Anthropic
// Messages event sequence, flushing per event. Reusing the adapter keeps
// upstream calls, retries, timeouts and usage capture identical across
// every non-anthropic provider type.
type anthropicStreamWriter struct {
rw http.ResponseWriter
tools map[int]*streamToolBlock
sse *sseWriter
model string
finishR string
raw bytes.Buffer
mode int
next int
openIdx int
started bool
done bool
hasOpen bool
textOpen bool
}
func newAnthropicStreamWriter(rw http.ResponseWriter, model string) *anthropicStreamWriter {
return &anthropicStreamWriter{rw: rw, model: model, tools: map[int]*streamToolBlock{}}
}
// Header implements http.ResponseWriter.
func (s *anthropicStreamWriter) Header() http.Header { return s.rw.Header() }
// Flush implements http.Flusher.
func (s *anthropicStreamWriter) Flush() {
if f, ok := s.rw.(http.Flusher); ok {
f.Flush()
}
}
// detectMode runs on the first WriteHeader/Write: an upstream that ignored
// stream=true answers JSON, which finish replays as events.
func (s *anthropicStreamWriter) detectMode() {
if s.mode != streamModeUnset {
return
}
ct := strings.ToLower(s.rw.Header().Get("Content-Type"))
if ct != "" && !strings.Contains(ct, "text/event-stream") {
s.mode = streamModeJSON
return
}
s.mode = streamModeSSE
s.sse = newSSEWriter(s.rw)
}
// WriteHeader implements http.ResponseWriter.
func (s *anthropicStreamWriter) WriteHeader(status int) {
s.detectMode()
if s.mode == streamModeSSE {
s.rw.WriteHeader(status)
}
}
// Write implements http.ResponseWriter. Each call carries whole frames:
// sseWriter emits one frame per Write.
func (s *anthropicStreamWriter) Write(b []byte) (int, error) {
s.detectMode()
if s.mode == streamModeJSON {
return s.raw.Write(b)
}
for _, frame := range bytes.Split(b, []byte("\n\n")) {
data, ok := sseFrameData(frame)
if !ok || string(data) == sseDoneMarker {
continue
}
if err := s.handleChunk(data); err != nil {
return 0, err
}
}
return len(b), nil
}
// sseFrameData joins a frame's "data:" lines; ok is false for a frame with none.
func sseFrameData(frame []byte) (data []byte, ok bool) {
var parts [][]byte
for _, line := range bytes.Split(frame, []byte("\n")) {
if v, found := bytes.CutPrefix(line, []byte("data:")); found {
parts = append(parts, bytes.TrimPrefix(v, []byte(" ")))
}
}
if len(parts) == 0 {
return nil, false
}
return bytes.Join(parts, []byte("\n")), true
}
func (s *anthropicStreamWriter) emit(name string, payload map[string]any) error {
b, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal %s event: %w", name, err)
}
return s.sse.writeEvent(name, b)
}
func (s *anthropicStreamWriter) start(id string, inputTokens int64) error {
if s.started {
return nil
}
s.started = true
return s.emit("message_start", map[string]any{
"type": "message_start",
"message": map[string]any{
"id": id,
"type": "message",
"role": "assistant",
"model": s.model,
"content": []any{},
"stop_reason": nil,
"stop_sequence": nil,
"usage": map[string]any{"input_tokens": inputTokens, "output_tokens": 0},
},
})
}
func (s *anthropicStreamWriter) openBlock(block map[string]any) error {
if err := s.closeBlock(); err != nil {
return err
}
s.hasOpen = true
s.openIdx = s.next
s.next++
return s.emit("content_block_start", map[string]any{"type": "content_block_start", "index": s.openIdx, "content_block": block})
}
func (s *anthropicStreamWriter) closeBlock() error {
if !s.hasOpen {
return nil
}
s.hasOpen = false
s.textOpen = false
return s.emit("content_block_stop", map[string]any{"type": "content_block_stop", "index": s.openIdx})
}
func (s *anthropicStreamWriter) delta(index int, delta map[string]any) error {
return s.emit("content_block_delta", map[string]any{"type": "content_block_delta", "index": index, "delta": delta})
}
func (s *anthropicStreamWriter) handleChunk(data []byte) error {
var c openAIStreamChunk
if err := json.Unmarshal(data, &c); err != nil {
return fmt.Errorf("%w: decode openai stream chunk: %w", errUpstream, err)
}
if e := bytes.TrimSpace(c.Error); len(e) > 0 && string(e) != "null" {
return fmt.Errorf("%w: upstream stream error: %s", errUpstream, e)
}
var input int64
if c.Usage != nil {
input = c.Usage.PromptTokens
}
if err := s.start(anthropicMessageIDFromOpenAI(c.ID), input); err != nil {
return err
}
if len(c.Choices) == 0 {
return nil
}
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 {
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 ch.FinishReason != "" {
s.finishR = ch.FinishReason
}
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.
func (s *anthropicStreamWriter) finish(u usage) error {
s.detectMode()
if s.done {
return nil
}
s.done = true
if s.mode == streamModeJSON {
return s.replayJSON()
}
if err := s.start("", 0); err != nil {
return err
}
return s.stop(anthropicStopReasonFromOpenAI(s.finishR), u.prompt, u.completion)
}
func (s *anthropicStreamWriter) stop(stopReason string, input, output int64) error {
if err := s.closeBlock(); 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},
"usage": map[string]any{"input_tokens": input, "output_tokens": output},
})
if err != nil {
return err
}
return s.emit("message_stop", map[string]any{"type": "message_stop"})
}
// replayJSON turns a buffered non-streaming OpenAI response into the event sequence.
func (s *anthropicStreamWriter) replayJSON() error {
out, err := anthropicResponseFromOpenAI(s.raw.Bytes(), s.model)
if err != nil {
return &responseTranslationError{err: err}
}
s.sse = newSSEWriter(s.rw)
usageMap, _ := out["usage"].(map[string]any)
input, _ := usageMap["input_tokens"].(int64)
output, _ := usageMap["output_tokens"].(int64)
id, _ := out["id"].(string)
if err := s.start(id, input); err != nil {
return err
}
blocks, _ := out["content"].([]any)
for _, b := range blocks {
block, _ := b.(map[string]any)
if block["type"] == "text" {
text, _ := block["text"].(string)
if err := s.openBlock(map[string]any{"type": "text", "text": ""}); err != nil {
return err
}
if err := s.delta(s.openIdx, map[string]any{"type": "text_delta", "text": text}); err != nil {
return err
}
continue
}
args, mErr := json.Marshal(block["input"])
if mErr != nil {
return &responseTranslationError{err: mErr}
}
if err := s.openBlock(map[string]any{"type": "tool_use", "id": block["id"], "name": block["name"], "input": map[string]any{}}); err != nil {
return err
}
if err := s.delta(s.openIdx, map[string]any{"type": "input_json_delta", "partial_json": string(args)}); err != nil {
return err
}
}
stopReason, _ := out["stop_reason"].(string)
return s.stop(stopReason, input, output)
}
// writeAnthropicStreamError emits an Anthropic error event on an already-started stream.
func writeAnthropicStreamError(w http.ResponseWriter, msg string) {
b, err := json.Marshal(map[string]any{
"type": "error",
"error": map[string]any{"type": anthropicStreamErrorType, "message": msg},
})
if err != nil {
return
}
_ = newSSEWriter(w).writeEvent("error", b) // best-effort: the connection may already be gone
}
// rewriteMessageStartModel replaces message.model in a message_start
// payload, leaving every other byte untouched.
func rewriteMessageStartModel(data []byte, model string) ([]byte, error) {
dec := json.NewDecoder(bytes.NewReader(data))
if tok, err := dec.Token(); err != nil || tok != json.Delim('{') {
return nil, fmt.Errorf("message_start is not a JSON object")
}
for dec.More() {
keyTok, err := dec.Token()
if err != nil {
return nil, fmt.Errorf("read message_start key: %w", err)
}
var val json.RawMessage
if derr := dec.Decode(&val); derr != nil {
return nil, fmt.Errorf("read message_start value: %w", derr)
}
if keyTok != "message" {
continue
}
rewritten, err := rewriteModelField(val, model)
if err != nil {
return nil, err
}
end := int(dec.InputOffset())
start := end - len(val)
var out bytes.Buffer
out.Write(data[:start])
out.Write(rewritten)
out.Write(data[end:])
return out.Bytes(), nil
}
return nil, fmt.Errorf("message_start has no message object")
}
// errStreamErrorRelayed marks a stream whose upstream error event already
// reached the client, so the route must not write a second one.
var errStreamErrorRelayed = errors.New("upstream stream error relayed to client")
// relayAnthropicMessagesStream forwards an Anthropic Messages stream event by
// event. Only message_start changes: its message.model becomes the client's
// alias. Usage comes from the same parser the chat route uses for this
// provider type.
func relayAnthropicMessagesStream(w http.ResponseWriter, body io.Reader, model string) (usage, error) {
st := newAnthropicStreamState(model, 0)
sw := newSSEWriter(w)
relayed := false
err := readSSE(body, func(ev sseEvent) error {
data := ev.data
if ev.event == "message_start" {
out, rerr := rewriteMessageStartModel(data, model)
if rerr != nil {
return rerr
}
data = out
}
if werr := sw.writeEvent(ev.event, data); werr != nil {
return werr
}
relayed = ev.event == "error"
_, terr := st.translate(ev)
return terr
})
if err == nil {
return st.usage(), nil
}
if relayed {
return st.usage(), fmt.Errorf("%w: %w", errStreamErrorRelayed, err)
}
return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, err)
}
+271
View File
@@ -0,0 +1,271 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// sseUpstream answers every request with frames, flushing after each one,
// and records the decoded request body.
func sseUpstream(t *testing.T, gotBody *map[string]any, calls *int32, frames ...string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls != nil {
atomic.AddInt32(calls, 1)
}
if gotBody != nil {
b, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(b, gotBody)
}
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
f, _ := w.(http.Flusher)
for _, fr := range frames {
_, _ = io.WriteString(w, fr)
if f != nil {
f.Flush()
}
}
}))
}
func streamMessagesBody(model string) map[string]any {
return map[string]any{
"model": model, "max_tokens": 64, "stream": true,
"messages": []any{map[string]any{"role": "user", "content": "weather in Paris?"}},
}
}
func serveMessages(t *testing.T, gw *Gateway, body map[string]any) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, newMessagesRequest(t, body, "x-api-key", "sk-alice"))
return rec
}
func userTokens(t *testing.T, gw *Gateway) (in, out int64) {
t.Helper()
in, _ = gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now())
out, _ = gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
return in, out
}
var openAITextAndToolFrames = []string{
"data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"\"}}]}\n\n",
"data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Let me \"}}]}\n\n",
"data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"check.\"}}]}\n\n",
"data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_7\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"\"}}]}}]}\n\n",
"data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\"}}]}}]}\n\n",
"data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
"data: {\"id\":\"chatcmpl-9\",\"choices\":[],\"usage\":{\"prompt_tokens\":11,\"completion_tokens\":7,\"total_tokens\":18}}\n\n",
"data: [DONE]\n\n",
}
func TestHandleMessages_Stream_OpenAIProvider_Translates(t *testing.T) {
var got map[string]any
srv := sseUpstream(t, &got, nil, openAITextAndToolFrames...)
defer srv.Close()
gw := newMessagesTestGateway(t, "", srv.URL)
rec := serveMessages(t, gw, streamMessagesBody("gpt-test"))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, "text/event-stream") {
t.Fatalf("Content-Type = %q, want text/event-stream", ct)
}
if got["stream"] != true {
t.Errorf("upstream stream = %v, want true", got["stream"])
}
if so, _ := got["stream_options"].(map[string]any); so["include_usage"] != true {
t.Errorf("upstream stream_options = %v, want include_usage true", got["stream_options"])
}
evs := parseAnthropicEvents(t, rec.Body.String())
want := []string{
"message_start",
"content_block_start", "content_block_delta", "content_block_delta", "content_block_stop",
"content_block_start", "content_block_delta", "content_block_stop",
"message_delta", "message_stop",
}
if names := eventNames(evs); !equalStrings(names, want) {
t.Fatalf("events = %v, want %v", names, want)
}
msg := sub(evs[0].data, "message")
if msg["model"] != "gpt-test" || msg["role"] != "assistant" {
t.Errorf("message_start message = %v, want model gpt-test role assistant", msg)
}
text := sub(evs[2].data, "delta")["text"].(string) + sub(evs[3].data, "delta")["text"].(string)
if text != "Let me check." {
t.Errorf("text = %q", text)
}
tool := sub(evs[5].data, "content_block")
if tool["type"] != "tool_use" || tool["id"] != "call_7" || tool["name"] != "get_weather" {
t.Errorf("tool block = %v", tool)
}
if pj := sub(evs[6].data, "delta")["partial_json"]; pj != `{"city":"Paris"}` {
t.Errorf("partial_json = %v", pj)
}
if d := sub(evs[8].data, "delta"); d["stop_reason"] != "tool_use" {
t.Errorf("stop_reason = %v, want tool_use", d["stop_reason"])
}
if u := sub(evs[8].data, "usage"); u["output_tokens"] != float64(7) || u["input_tokens"] != float64(11) {
t.Errorf("message_delta usage = %v, want input 11 output 7", u)
}
if in, out := userTokens(t, gw); in != 11 || out != 7 {
t.Errorf("billed tokens in/out = %d/%d, want 11/7", in, out)
}
}
const anthropicStreamUpstream = "event: message_start\n" +
`data: {"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","model":"claude-real-20260101","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"cache_creation_input_tokens":100,"cache_read_input_tokens":50,"output_tokens":1}}}` + "\n\n" +
"event: ping\n" + `data: {"type":"ping"}` + "\n\n" +
"event: content_block_start\n" + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" +
"event: content_block_delta\n" + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hi there"}}` + "\n\n" +
"event: content_block_stop\n" + `data: {"type":"content_block_stop","index":0}` + "\n\n" +
"event: message_delta\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":6}}` + "\n\n" +
"event: message_stop\n" + `data: {"type":"message_stop"}` + "\n\n"
func TestHandleMessages_Stream_AnthropicProvider_Relays(t *testing.T) {
var got map[string]any
srv := sseUpstream(t, &got, nil, anthropicStreamUpstream)
defer srv.Close()
gw := newMessagesTestGateway(t, srv.URL, "")
rec := serveMessages(t, gw, streamMessagesBody("claude-test"))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
if got["stream"] != true {
t.Errorf("upstream stream = %v, want true", got["stream"])
}
wantBody := strings.Replace(anthropicStreamUpstream, `"model":"claude-real-20260101"`, `"model":"claude-test"`, 1)
if rec.Body.String() != wantBody {
t.Fatalf("relayed body differs from upstream with only the model rewritten:\n got: %q\nwant: %q", rec.Body.String(), wantBody)
}
if in, out := userTokens(t, gw); in != 162 || out != 6 {
t.Errorf("billed tokens in/out = %d/%d, want 162/6 (12 + 100 cache write + 50 cache read; output 6)", in, out)
}
}
func TestHandleMessages_Stream_NeverCached(t *testing.T) {
var calls int32
srv := sseUpstream(t, nil, &calls, openAITextAndToolFrames...)
defer srv.Close()
cfg := CreateConfig()
cfg.Cache = CacheConfig{Enabled: true, TTL: "1m"}
cacheOn := true
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: providerTypeOpenAI, BaseURL: srv.URL, APIKey: "sk-oai-up", Models: []string{"gpt-test"}}}
cfg.Groups = map[string]*GroupConfig{"default": {Cache: &cacheOn}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice"}}}
h, err := New(context.Background(), http.NotFoundHandler(), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
gw := h.(*Gateway)
for i := 0; i < 2; i++ {
rec := serveMessages(t, gw, streamMessagesBody("gpt-test"))
if rec.Code != http.StatusOK || rec.Header().Get("X-Llmgw-Cache") == "hit" {
t.Fatalf("request %d: status %d cache %q", i, rec.Code, rec.Header().Get("X-Llmgw-Cache"))
}
}
if n := atomic.LoadInt32(&calls); n != 2 {
t.Fatalf("upstream calls = %d, want 2: a stream must never be served from cache", n)
}
}
func TestHandleMessages_Stream_PreStreamErrorIsJSON(t *testing.T) {
var calls int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&calls, 1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"error":{"message":"bad prompt","type":"invalid_request_error"}}`)
}))
defer srv.Close()
gw := newMessagesTestGateway(t, "", srv.URL)
rec := serveMessages(t, gw, streamMessagesBody("gpt-test"))
if rec.Code < 400 {
t.Fatalf("status = %d, want an error status", rec.Code)
}
if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, "application/json") {
t.Fatalf("Content-Type = %q, want application/json before the stream starts", ct)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body["type"] != "error" {
t.Fatalf("body = %s, want an Anthropic error object", rec.Body.String())
}
if atomic.LoadInt32(&calls) == 0 || !strings.Contains(rec.Body.String(), "bad prompt") {
t.Fatalf("body = %s, want the upstream's own error after a real upstream call", rec.Body.String())
}
}
func TestHandleMessages_Stream_MidStreamErrorEvent_Translated(t *testing.T) {
srv := sseUpstream(t, nil, nil,
"data: {\"id\":\"chatcmpl-9\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"partial\"}}]}\n\n",
"data: {not json\n\n",
)
defer srv.Close()
gw := newMessagesTestGateway(t, "", srv.URL)
rec := serveMessages(t, gw, streamMessagesBody("gpt-test"))
evs := parseAnthropicEvents(t, rec.Body.String())
names := eventNames(evs)
if len(names) == 0 || names[len(names)-1] != "error" {
t.Fatalf("events = %v, want the stream to end with an error event", names)
}
if e := sub(evs[len(evs)-1].data, "error"); e["type"] != anthropicStreamErrorType {
t.Errorf("error = %v, want type %s", e, anthropicStreamErrorType)
}
for _, n := range names {
if n == "message_stop" {
t.Fatal("a failed stream must not send message_stop")
}
}
}
func TestHandleMessages_Stream_MidStreamErrorEvent_AnthropicRelayedOnce(t *testing.T) {
srv := sseUpstream(t, nil, nil,
"event: message_start\n"+`data: {"type":"message_start","message":{"id":"msg_02","type":"message","role":"assistant","model":"claude-real","content":[],"usage":{"input_tokens":3,"output_tokens":0}}}`+"\n\n",
"event: error\n"+`data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`+"\n\n",
)
defer srv.Close()
gw := newMessagesTestGateway(t, srv.URL, "")
rec := serveMessages(t, gw, streamMessagesBody("claude-test"))
evs := parseAnthropicEvents(t, rec.Body.String())
if names := eventNames(evs); !equalStrings(names, []string{"message_start", "error"}) {
t.Fatalf("events = %v, want [message_start error]", names)
}
if e := sub(evs[1].data, "error"); e["type"] != "overloaded_error" {
t.Errorf("error = %v, want the upstream overloaded_error relayed as is", e)
}
}
func TestHandleMessages_StreamingShapesAllStream(t *testing.T) {
for _, stream := range []any{true, "true", float64(1)} {
var got map[string]any
srv := sseUpstream(t, &got, nil, anthropicStreamUpstream)
gw := newMessagesTestGateway(t, srv.URL, "")
body := streamMessagesBody("claude-test")
body["stream"] = stream
rec := serveMessages(t, gw, body)
srv.Close()
if rec.Code != http.StatusOK || !strings.Contains(rec.Header().Get("Content-Type"), "text/event-stream") {
t.Errorf("stream=%v: status %d Content-Type %q, want a 200 event stream", stream, rec.Code, rec.Header().Get("Content-Type"))
}
if got["stream"] != true {
t.Errorf("stream=%v: upstream stream = %v, want true", stream, got["stream"])
}
}
}
+322
View File
@@ -0,0 +1,322 @@
package traefikllmgateway
import (
"bytes"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
)
// anthEvent is one decoded Anthropic SSE event: its name and JSON payload.
type anthEvent struct {
data map[string]any
name string
}
func parseAnthropicEvents(t *testing.T, body string) []anthEvent {
t.Helper()
var out []anthEvent
err := readSSE(strings.NewReader(body), func(ev sseEvent) error {
var m map[string]any
if err := json.Unmarshal(ev.data, &m); err != nil {
t.Fatalf("event %q data is not JSON: %v (%s)", ev.event, err, ev.data)
}
if m["type"] != ev.event {
t.Errorf("event name %q != data.type %v", ev.event, m["type"])
}
out = append(out, anthEvent{name: ev.event, data: m})
return nil
})
if err != nil {
t.Fatalf("readSSE: %v", err)
}
return out
}
func eventNames(evs []anthEvent) []string {
names := make([]string, len(evs))
for i, e := range evs {
names[i] = e.name
}
return names
}
func sub(m map[string]any, key string) map[string]any {
v, _ := m[key].(map[string]any)
return v
}
func oaiFrame(payload string) []byte { return []byte("data: " + payload + "\n\n") }
// runStreamWriter feeds frames into a fresh translator and finishes it.
func runStreamWriter(t *testing.T, u usage, frames ...string) (*httptest.ResponseRecorder, []anthEvent) {
t.Helper()
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "my-alias")
for _, f := range frames {
if _, err := sw.Write(oaiFrame(f)); err != nil {
t.Fatalf("Write(%s): %v", f, err)
}
}
if err := sw.finish(u); err != nil {
t.Fatalf("finish: %v", err)
}
return rec, parseAnthropicEvents(t, rec.Body.String())
}
func equalStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func TestAnthropicStreamWriter_TextOnly(t *testing.T) {
rec, evs := runStreamWriter(t, usage{prompt: 11, completion: 3},
`{"id":"chatcmpl-abc","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`,
`{"id":"chatcmpl-abc","choices":[{"index":0,"delta":{"content":"Hel"}}]}`,
`{"id":"chatcmpl-abc","choices":[{"index":0,"delta":{"content":"lo"}}]}`,
`{"id":"chatcmpl-abc","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`,
`{"id":"chatcmpl-abc","choices":[],"usage":{"prompt_tokens":11,"completion_tokens":3}}`,
)
want := []string{"message_start", "content_block_start", "content_block_delta", "content_block_delta", "content_block_stop", "message_delta", "message_stop"}
if got := eventNames(evs); !equalStrings(got, want) {
t.Fatalf("events = %v, want %v", got, want)
}
if ct := rec.Header().Get("Content-Type"); ct != "text/event-stream" {
t.Errorf("Content-Type = %q, want text/event-stream", ct)
}
msg := sub(evs[0].data, "message")
if msg["id"] != "msg_abc" || msg["type"] != "message" || msg["role"] != "assistant" || msg["model"] != "my-alias" {
t.Errorf("message_start.message = %v", msg)
}
if c, ok := msg["content"].([]any); !ok || len(c) != 0 {
t.Errorf("message_start content = %v, want empty array", msg["content"])
}
if _, ok := sub(msg, "usage")["input_tokens"]; !ok {
t.Errorf("message_start usage lacks input_tokens: %v", msg["usage"])
}
if cb := sub(evs[1].data, "content_block"); cb["type"] != "text" || cb["text"] != "" || evs[1].data["index"] != float64(0) {
t.Errorf("content_block_start = %v", evs[1].data)
}
if d := sub(evs[2].data, "delta"); d["type"] != "text_delta" || d["text"] != "Hel" {
t.Errorf("first delta = %v", evs[2].data)
}
if d := sub(evs[3].data, "delta"); d["text"] != "lo" {
t.Errorf("second delta = %v", evs[3].data)
}
if evs[4].data["index"] != float64(0) {
t.Errorf("content_block_stop index = %v", evs[4].data["index"])
}
md := evs[5].data
if d := sub(md, "delta"); d["stop_reason"] != "end_turn" {
t.Errorf("message_delta delta = %v", d)
}
if u := sub(md, "usage"); u["output_tokens"] != float64(3) || u["input_tokens"] != float64(11) {
t.Errorf("message_delta usage = %v", u)
}
}
func TestAnthropicStreamWriter_ToolUse(t *testing.T) {
_, evs := runStreamWriter(t, usage{prompt: 20, completion: 9},
`{"id":"chatcmpl-t","choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"get_weather","arguments":""}}]}}]}`,
`{"id":"chatcmpl-t","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"city\":"}}]}}]}`,
`{"id":"chatcmpl-t","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"Paris\"}"}}]}}]}`,
`{"id":"chatcmpl-t","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
)
want := []string{"message_start", "content_block_start", "content_block_delta", "content_block_delta", "content_block_stop", "message_delta", "message_stop"}
if got := eventNames(evs); !equalStrings(got, want) {
t.Fatalf("events = %v, want %v", got, want)
}
cb := sub(evs[1].data, "content_block")
if cb["type"] != "tool_use" || cb["id"] != "call_1" || cb["name"] != "get_weather" {
t.Errorf("content_block = %v", cb)
}
if in, ok := cb["input"].(map[string]any); !ok || len(in) != 0 {
t.Errorf("tool_use start input = %v, want {}", cb["input"])
}
var args string
for _, e := range evs[2:4] {
d := sub(e.data, "delta")
if d["type"] != "input_json_delta" {
t.Errorf("delta type = %v", d["type"])
}
args += d["partial_json"].(string)
}
if args != `{"city":"Paris"}` {
t.Errorf("reassembled arguments = %q", args)
}
if d := sub(evs[5].data, "delta"); d["stop_reason"] != "tool_use" {
t.Errorf("stop_reason = %v, want tool_use", d["stop_reason"])
}
}
func TestAnthropicStreamWriter_TwoToolCalls(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
`{"id":"c","choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_a","function":{"name":"a","arguments":""}}]}}]}`,
`{"id":"c","choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{}"}}]}}]}`,
`{"id":"c","choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_b","function":{"name":"b","arguments":""}}]}}]}`,
`{"id":"c","choices":[{"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"x\":1}"}}]}}]}`,
`{"id":"c","choices":[{"delta":{},"finish_reason":"tool_calls"}]}`,
)
want := []string{
"message_start",
"content_block_start", "content_block_delta", "content_block_stop",
"content_block_start", "content_block_delta", "content_block_stop",
"message_delta", "message_stop",
}
if got := eventNames(evs); !equalStrings(got, want) {
t.Fatalf("events = %v, want %v", got, want)
}
if evs[1].data["index"] != float64(0) || evs[2].data["index"] != float64(0) || evs[3].data["index"] != float64(0) {
t.Errorf("first block indexes wrong: %v %v %v", evs[1].data, evs[2].data, evs[3].data)
}
if evs[4].data["index"] != float64(1) || evs[5].data["index"] != float64(1) || evs[6].data["index"] != float64(1) {
t.Errorf("second block indexes wrong: %v %v %v", evs[4].data, evs[5].data, evs[6].data)
}
if cb := sub(evs[4].data, "content_block"); cb["id"] != "call_b" || cb["name"] != "b" {
t.Errorf("second tool block = %v", cb)
}
}
func TestAnthropicStreamWriter_TextThenToolCall(t *testing.T) {
_, evs := runStreamWriter(t, usage{},
`{"id":"c","choices":[{"delta":{"content":"Checking."}}]}`,
`{"id":"c","choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_a","function":{"name":"lookup","arguments":"{}"}}]}}]}`,
`{"id":"c","choices":[{"delta":{},"finish_reason":"tool_calls"}]}`,
)
want := []string{
"message_start",
"content_block_start", "content_block_delta", "content_block_stop",
"content_block_start", "content_block_delta", "content_block_stop",
"message_delta", "message_stop",
}
if got := eventNames(evs); !equalStrings(got, want) {
t.Fatalf("events = %v, want %v", got, want)
}
if cb := sub(evs[1].data, "content_block"); cb["type"] != "text" {
t.Errorf("block 0 = %v, want text", cb)
}
if cb := sub(evs[4].data, "content_block"); cb["type"] != "tool_use" || evs[4].data["index"] != float64(1) {
t.Errorf("block 1 = %v (index %v), want tool_use at 1", cb, evs[4].data["index"])
}
}
func TestAnthropicStreamWriter_StopReasonMatchesNonStreaming(t *testing.T) {
for _, finish := range []string{"stop", "length", "tool_calls", "content_filter", "function_call", ""} {
frames := []string{`{"id":"c","choices":[{"delta":{"content":"x"}}]}`}
if finish != "" {
frames = append(frames, `{"id":"c","choices":[{"delta":{},"finish_reason":"`+finish+`"}]}`)
}
_, evs := runStreamWriter(t, usage{}, frames...)
got := sub(evs[len(evs)-2].data, "delta")["stop_reason"]
if want := anthropicStopReasonFromOpenAI(finish); got != want {
t.Errorf("finish_reason %q: stop_reason = %v, want %v", finish, got, want)
}
}
}
func TestAnthropicStreamWriter_UsageFromFinish(t *testing.T) {
_, evs := runStreamWriter(t, usage{prompt: 123, completion: 45},
`{"id":"c","choices":[{"delta":{"content":"x"}}]}`,
)
u := sub(evs[len(evs)-2].data, "usage")
if u["input_tokens"] != float64(123) || u["output_tokens"] != float64(45) {
t.Errorf("message_delta usage = %v, want input 123 output 45", u)
}
}
func TestAnthropicStreamWriter_EmptyStreamStillWellFormed(t *testing.T) {
_, evs := runStreamWriter(t, usage{})
want := []string{"message_start", "message_delta", "message_stop"}
if got := eventNames(evs); !equalStrings(got, want) {
t.Fatalf("events = %v, want %v", got, want)
}
}
func TestAnthropicStreamWriter_DoneAndKeepAliveIgnored(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "a")
if _, err := sw.Write([]byte(": keepalive\n\n")); err != nil {
t.Fatal(err)
}
if _, err := sw.Write(oaiFrame(`{"id":"c","choices":[{"delta":{"content":"x"}}]}`)); err != nil {
t.Fatal(err)
}
if _, err := sw.Write(oaiFrame("[DONE]")); err != nil {
t.Fatal(err)
}
if err := sw.finish(usage{}); err != nil {
t.Fatal(err)
}
if strings.Contains(rec.Body.String(), "DONE") {
t.Errorf("[DONE] leaked into the Anthropic stream: %s", rec.Body.String())
}
}
func TestAnthropicStreamWriter_UpstreamErrorChunkFailsStream(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "a")
_, err := sw.Write(oaiFrame(`{"error":{"message":"boom","type":"server_error"}}`))
if err == nil {
t.Fatal("Write returned nil for an upstream error chunk, want an error")
}
}
func TestAnthropicStreamWriter_MalformedChunkFailsStream(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "a")
if _, err := sw.Write(oaiFrame(`{not json`)); err == nil {
t.Fatal("Write returned nil for malformed JSON, want an error")
}
}
func TestAnthropicStreamWriter_JSONFallbackWhenUpstreamIgnoresStream(t *testing.T) {
rec := httptest.NewRecorder()
sw := newAnthropicStreamWriter(rec, "my-alias")
sw.Header().Set("Content-Type", "application/json")
sw.WriteHeader(200)
body := `{"id":"chatcmpl-j","choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":4,"completion_tokens":2}}`
if _, err := sw.Write([]byte(body)); err != nil {
t.Fatal(err)
}
if err := sw.finish(usage{}); err != nil {
t.Fatal(err)
}
evs := parseAnthropicEvents(t, rec.Body.String())
want := []string{"message_start", "content_block_start", "content_block_delta", "content_block_stop", "message_delta", "message_stop"}
if got := eventNames(evs); !equalStrings(got, want) {
t.Fatalf("events = %v, want %v", got, want)
}
if d := sub(evs[2].data, "delta"); d["text"] != "hi" {
t.Errorf("text delta = %v", d)
}
if u := sub(evs[4].data, "usage"); u["output_tokens"] != float64(2) {
t.Errorf("usage = %v", u)
}
}
func TestRewriteMessageStartModel_PreservesOtherBytes(t *testing.T) {
in := []byte(`{"type":"message_start","message":{"id":"msg_1","model":"claude-real","big":12345678901234567890,"usage":{"input_tokens":3}}}`)
got, err := rewriteMessageStartModel(in, "alias")
if err != nil {
t.Fatal(err)
}
want := `{"type":"message_start","message":{"id":"msg_1","model":"alias","big":12345678901234567890,"usage":{"input_tokens":3}}}`
if !bytes.Equal(got, []byte(want)) {
t.Errorf("got %s\nwant %s", got, want)
}
if _, err := rewriteMessageStartModel([]byte(`{"type":"message_start"}`), "a"); err == nil {
t.Error("want error when message object is missing")
}
}
+20 -42
View File
@@ -55,20 +55,9 @@ var anthropicPassthroughForwardedHeaders = []string{"anthropic-beta"}
// (Anthropic's {"type":"error","error":{...}}, not OpenAI's
// {"error":{...}} — see writeAnthropicError and its callers, below).
//
// ORDERING (item 2 fix, 2026-08-22 review): body admission + decode run
// BEFORE admitRequestForRoute (the rate-limit check) on THIS route — the
// opposite order from runUnified's own finding 1a. anthropic-sdk-python
// retries any status >= 500, and Claude Code streams on every call: the
// previous ordering (admitRequestForRoute first, streaming rejected only
// after decode) meant every real client hitting this not-yet-streaming-capable
// route burned three requests of rate-limit budget per logical call —
// verified repro: requestsPerMinute 2, three attempts -> 501, 501, 429,
// day counter reads 3. Deciding "is this streaming" requires the decoded
// body, so decode has to happen first; the trade-off finding 1a accepts
// for runUnified (an adversarial caller paying nothing to retry a
// malformed body) does not apply here, since the common case hitting
// this ordering is not adversarial retries but every legitimate
// streaming-capable client that exists today.
// Body admission and decode run before admitRequestForRoute, the reverse of
// runUnified: Anthropic SDKs retry any status >= 500, so a request that
// fails before reaching a provider must not spend rate-limit budget.
func (g *Gateway) handleMessages(w http.ResponseWriter, r *http.Request, u *user, grp *group) {
sw := &statusTrackingWriter{ResponseWriter: w}
@@ -83,25 +72,11 @@ func (g *Gateway) handleMessages(w http.ResponseWriter, r *http.Request, u *user
return
}
// Streaming is rejected cleanly and explicitly here, before the
// rate-limit check, model resolution, or any upstream call: this cut
// of the route ships non-streaming only (brief scope) — a follow-up
// branch adds the Anthropic SSE event translator (message_start/
// content_block_delta/message_stop), a genuinely different event
// model from OpenAI's stream shape this route already knows how to
// forward. A caller that asked for streaming must see a clear, typed
// error, never a silently-ignored flag answered non-streamed.
//
// 400, not 501 (item 2 fix, 2026-08-22 review): anthropic-sdk-python's
// retry classifies purely on status code and retries anything >= 500
// — a 501 here turned every streaming call into an SDK-driven retry
// storm against this route's own rate limit (this function's own doc
// comment above has the verified repro). 400 maps to the SDK's
// non-retryable BadRequestError, and invalid_request_error is already
// the correct error type for a 400.
// Normalized so runMeteredCall and the adapters, which read a bool, see
// every shape isStreamingRequested accepts as streaming.
if isStreamingRequested(req) {
writeAnthropicError(sw, http.StatusBadRequest, "invalid_request_error", "streaming is not yet supported on /v1/messages")
return
req["stream"] = true
sw.sseError = func(msg string) { writeAnthropicStreamError(sw, msg) }
}
scopes, ok := g.admitRequestForRoute(r.Context(), sw, u, grp, writeAnthropicError, routeMessages, int64(len(body)), "")
@@ -243,6 +218,10 @@ func (g *Gateway) callAnthropicMessagesPassthrough(ctx context.Context, w http.R
return usage{}, newProviderHTTPError(resp)
}
if isStreamingRequested(req) && isEventStreamResponse(resp) {
return relayAnthropicMessagesStream(w, resp.Body, requestedModel)
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
if err != nil {
// F5 fix, 2026-08-23 review: the upstream already answered 200
@@ -413,19 +392,18 @@ func (g *Gateway) callTranslatedMessages(ctx context.Context, w http.ResponseWri
g.applyTranslatedPromptCacheKey(openaiReq, req, adapter.name())
if streaming, _ := openaiReq["stream"].(bool); streaming {
aw := newAnthropicStreamWriter(w, requestedModel)
streamed, serr := adapter.chatCompletion(ctx, aw, openaiReq)
if serr != nil {
return streamed, serr
}
return streamed, aw.finish(streamed)
}
rec := newMessagesResponseRecorder()
result, err := adapter.chatCompletion(ctx, rec, openaiReq)
if err != nil {
// result, not usage{} (F5 fix, 2026-08-23 review): harmless today
// — streaming is rejected before this route ever reaches here, so
// chatCompletion's non-streaming contract already guarantees
// usage{} on any error. It matters the day streaming lands: a
// streaming chatCompletion call (forwardStream) CAN return
// nonzero usage alongside an error — a usage chunk that arrived
// just before a dropped connection must still be billed — and
// discarding it here would reintroduce item 1's original
// CRITICAL (usage silently dropped on an error path) the moment
// this route gains streaming support.
return result, err
}
-92
View File
@@ -297,98 +297,6 @@ func TestHandleMessages_Auth(t *testing.T) {
}
}
// TestHandleMessages_StreamingRejected table-drives every "stream" shape
// this route must reject cleanly, with a typed, Anthropic-shaped error,
// before any upstream call is made or any rate-limit budget is spent —
// never silently ignored, never answered non-streamed. Covers a real
// boolean true and, per item 9's fix (2026-08-22 review), a non-bool
// truthy value ("stream":"true", a string, and "stream":1, a number) that
// a bare req["stream"].(bool) assertion would previously have silently
// treated as false and forwarded upstream.
func TestHandleMessages_StreamingRejected(t *testing.T) {
cases := []struct {
stream any
name string
}{
{name: "boolean true", stream: true},
{name: "string \"true\" (non-bool, item 9)", stream: "true"},
{name: "number 1 (non-bool, item 9)", stream: float64(1)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
called := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
// requestsPerMinute: 1 so a second wrongly-counted request
// would 429 — proving the rejection happens before
// admitRequestForRoute ever runs (item 2 fix): both requests below
// must succeed at the "not yet counted" stage.
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"anthropic": {Type: providerTypeAnthropic, BaseURL: srv.URL, APIKey: "sk-ant-up", Models: []string{"claude-test"}}} // #nosec G101 -- test fixture literal, not a real credential
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{RequestsPerMinute: 1}}}} // #nosec G101 -- test fixture literal, not a real credential
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
h, err := New(context.Background(), next, cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
gw, ok := h.(*Gateway)
if !ok {
t.Fatal("handler is not *Gateway")
}
body := map[string]any{"model": "claude-test", "max_tokens": 10, "stream": tc.stream, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
for attempt := 1; attempt <= 2; attempt++ {
req := newMessagesRequest(t, body, "x-api-key", "sk-alice")
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, req)
// 400, not 501 (item 2 fix): anthropic-sdk-python's retry
// classifies purely on status code and retries anything
// >= 500 — a 501 here turns every streaming call into a
// three-request SDK retry storm against this route's own
// rate limit.
if rec.Code != http.StatusBadRequest {
t.Fatalf("attempt %d: status = %d, want 400, body=%s", attempt, rec.Code, rec.Body.String())
}
var got map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("decode error body: %v", err)
}
if got["type"] != "error" {
t.Errorf(`response["type"] = %v, want "error"`, got["type"])
}
errObj, _ := got["error"].(map[string]any)
if errObj["type"] != "invalid_request_error" {
t.Errorf("error.type = %v, want invalid_request_error", errObj["type"])
}
msg, _ := errObj["message"].(string)
if !strings.Contains(msg, "stream") {
t.Errorf("error message = %q, want it to mention streaming is not supported", msg)
}
}
if called {
t.Error("upstream was called; streaming must be rejected before any upstream request")
}
// item 2's actual fix: TWO streaming-rejected attempts against
// a requestsPerMinute:1 user must BOTH succeed (as 400s, not
// as a 429 on the second one) — proving admitRequestForRoute's
// checkAndCount never ran for either.
reqCount, ok := gw.limiter.getCounter("user", "alice", metricReq, windowMin, time.Now())
if !ok || reqCount != 0 {
t.Errorf("user req:min counter = %d (ok=%v), want 0 — a streaming-rejected request must never consume rate-limit budget", reqCount, ok)
}
})
}
}
// TestHandleMessages_NullStream_IsNotStreaming is the regression for F7
// (2026-08-23 review): isStreamingRequested's item-9 fix ("anything not
// the literal false is streaming") had the side effect of also
+7
View File
@@ -1350,8 +1350,15 @@ func (g *Gateway) handleAdapterErrorEnvelope(sw *statusTrackingWriter, err error
if sw.wroteHeader {
g.errorf("%s: adapter error after response started (provider %q): %v", logPrefix, providerName, err)
if errors.Is(err, errStreamErrorRelayed) {
return
}
if msg, errType, ok := midStreamErrorMessage(err, providerName); ok &&
strings.Contains(strings.ToLower(sw.Header().Get("Content-Type")), "text/event-stream") {
if sw.sseError != nil {
sw.sseError(msg)
return
}
errBody, _ := json.Marshal(map[string]any{ // json.Marshal on a literal map[string]any of strings never fails
"error": map[string]any{"message": msg, "type": errType},
})
+30
View File
@@ -55,6 +55,8 @@ var errSSEEventTooLarge = errors.New("llmgateway: sse event data exceeded the ma
// event payload, per the text/event-stream wire format.
const sseDataPrefix = "data: "
const sseEventPrefix = "event: "
// sseBOM is the UTF-8 byte-order mark. Some proxies still add one at the
// start of a stream. Left in place, it attaches to the first field name.
// "data:" becomes "\ufeffdata:", and readSSE drops the first event as an
@@ -285,6 +287,34 @@ func splitSSELines(b []byte) [][]byte {
}
}
// writeEvent writes one frame with an "event:" line ahead of the data, the
// framing the Anthropic Messages stream uses. event must not contain a line
// terminator; an empty event writes a bare data frame.
func (s *sseWriter) writeEvent(event string, b []byte) error {
if event == "" {
return s.writeData(b)
}
lines := splitSSELines(b)
buf := make([]byte, 0, len(sseEventPrefix)+len(event)+len(b)+len(lines)*len(sseDataPrefix)+len(lines)+2)
buf = append(buf, sseEventPrefix...)
buf = append(buf, event...)
buf = append(buf, '\n')
for _, line := range lines {
buf = append(buf, sseDataPrefix...)
buf = append(buf, line...)
buf = append(buf, '\n')
}
buf = append(buf, '\n')
if _, err := s.w.Write(buf); err != nil {
return err
}
if s.f != nil {
s.f.Flush()
}
return nil
}
// writeData writes one SSE data event as a single Write call, flushing
// when the underlying writer supports that.
//
+79 -10
View File
@@ -323,6 +323,11 @@ func run() error {
// is respecified here too, identical apiKey/group, rather than
// silently dropped).
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqBody, _ := io.ReadAll(r.Body)
if bytes.Contains(reqBody, []byte(`"stream":true`)) {
writeFakeChatStream(w)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":"c1","object":"chat.completion","model":"gpt-test","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`))
@@ -2301,18 +2306,10 @@ func exerciseMessagesRoute(handler http.Handler) error {
return err
}
// 4. "stream": true is rejected explicitly, in the Anthropic shape,
// as a 400 (item 2 fix, 2026-08-22 review) — NOT 501: a 501 makes
// anthropic-sdk-python (which retries any status >= 500) turn every
// streaming call into a three-request retry storm against this
// route's own rate limit. 400 maps to the SDK's non-retryable
// BadRequestError.
// 4. "stream": true streams the translated Anthropic event sequence.
streamRec := postMessages(handler, "x-api-key", testDataUserAPIKey,
`{"model":"`+testDataWantModel+`","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"ping"}]}`)
if streamRec.Code != http.StatusBadRequest {
return fmt.Errorf("POST /v1/messages with stream=true: status = %d, want 400, body=%s", streamRec.Code, streamRec.Body.String())
}
if err := assertAnthropicErrorShape("stream rejection", streamRec.Body.Bytes()); err != nil {
if err := assertAnthropicStream(streamRec); err != nil {
return err
}
@@ -4263,3 +4260,75 @@ func latestEventKindAndStatus(handler http.Handler) (kind string, status int, er
s, _ := first["status"].(float64)
return k, int(s), nil
}
// writeFakeChatStream answers a streaming chat completion with one text
// chunk, one tool call split over two chunks, the finish chunk, the usage
// chunk and [DONE], flushing after each frame.
func writeFakeChatStream(w http.ResponseWriter) {
frames := []string{
`{"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"}}]}`,
`{"id":"c1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":"}}]}}]}`,
`{"id":"c1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"Paris\"}"}}]}}]}`,
`{"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
`{"id":"c1","choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1}}`,
`[DONE]`,
}
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
f, _ := w.(http.Flusher)
for _, fr := range frames {
_, _ = io.WriteString(w, "data: "+fr+"\n\n")
if f != nil {
f.Flush()
}
}
}
// assertAnthropicStream checks a streamed /v1/messages answer to
// writeFakeChatStream: event order, the text and tool_use blocks, the
// stop reason and the usage.
func assertAnthropicStream(rec *httptest.ResponseRecorder) error {
if rec.Code != http.StatusOK || !strings.Contains(rec.Header().Get("Content-Type"), "text/event-stream") {
return fmt.Errorf("POST /v1/messages stream: status = %d, Content-Type = %q, body=%s", rec.Code, rec.Header().Get("Content-Type"), rec.Body.String())
}
var names []string
var datas []map[string]any
for _, frame := range strings.Split(strings.TrimSpace(rec.Body.String()), "\n\n") {
var name, data string
for _, line := range strings.Split(frame, "\n") {
if v, ok := strings.CutPrefix(line, "event: "); ok {
name = v
}
if v, ok := strings.CutPrefix(line, "data: "); ok {
data = v
}
}
var m map[string]any
if err := json.Unmarshal([]byte(data), &m); err != nil || m["type"] != name {
return fmt.Errorf("POST /v1/messages stream: bad frame %q", frame)
}
names = append(names, name)
datas = append(datas, m)
}
want := "message_start content_block_start content_block_delta content_block_stop content_block_start content_block_delta content_block_delta content_block_stop message_delta message_stop"
if got := strings.Join(names, " "); got != want {
return fmt.Errorf("POST /v1/messages stream: events = %s, want %s", got, want)
}
field := func(i int, key string) map[string]any { v, _ := datas[i][key].(map[string]any); return v }
if field(0, "message")["model"] != testDataWantModel || field(2, "delta")["text"] != "hi" {
return fmt.Errorf("POST /v1/messages stream: message_start/text = %v / %v", datas[0], datas[2])
}
if tool := field(4, "content_block"); tool["type"] != "tool_use" || tool["name"] != "get_weather" {
return fmt.Errorf("POST /v1/messages stream: tool block = %v", tool)
}
args, _ := field(5, "delta")["partial_json"].(string)
more, _ := field(6, "delta")["partial_json"].(string)
if args+more != `{"city":"Paris"}` {
return fmt.Errorf("POST /v1/messages stream: tool arguments = %q", args+more)
}
if field(8, "delta")["stop_reason"] != "tool_use" || field(8, "usage")["output_tokens"] != float64(1) {
return fmt.Errorf("POST /v1/messages stream: message_delta = %v", datas[8])
}
fmt.Println("yaegi-check: /v1/messages streamed text and tool_use events, interpreted")
return nil
}
+3 -9
View File
@@ -1493,15 +1493,9 @@ func openAIRequestFromAnthropic(req map[string]any) (map[string]any, []string, e
if seqs, ok := req["stop_sequences"].([]any); ok && len(seqs) > 0 {
out["stop"] = seqs
}
// L10 fix: no "stream" copy here — routes_messages.go's
// isStreamingRequested check (its own doc comment) rejects any
// streaming /v1/messages request with a 400 before
// openAIRequestFromAnthropic ever runs, so req["stream"] reaching
// this point can only be absent, false, or null. Copying it through
// was dead code with no observable effect (the downstream adapter's
// own `streaming, _ := req["stream"].(bool)` treats all three
// identically to omitting the field outright) — removed rather than
// left in place, per this repo's dead-code-hygiene rule.
if isStreamingRequested(req) {
out["stream"] = true
}
if toolsRaw, ok := req["tools"].([]any); ok {
out["tools"] = openAIToolsFromAnthropic(toolsRaw)