mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
A streaming unified request that failed after output reached the client recorded zero completion tokens. The gateway now estimates them from the forwarded output bytes and marks the usage as estimated. Streams that report usage, and streams that end cleanly, are unchanged.
191 lines
7.9 KiB
Go
191 lines
7.9 KiB
Go
package traefikllmgateway
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// hangupServer writes frames, flushes, then closes the connection without a terminator.
|
|
func hangupServer(t *testing.T, contentType string, frames []string) *httptest.Server {
|
|
t.Helper()
|
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", contentType)
|
|
w.WriteHeader(http.StatusOK)
|
|
fl, ok := w.(http.Flusher)
|
|
if !ok {
|
|
t.Error("upstream writer cannot flush")
|
|
return
|
|
}
|
|
for _, f := range frames {
|
|
_, _ = w.Write([]byte(f))
|
|
fl.Flush()
|
|
}
|
|
hj, ok := w.(http.Hijacker)
|
|
if !ok {
|
|
t.Error("upstream writer cannot hijack")
|
|
return
|
|
}
|
|
if conn, _, err := hj.Hijack(); err == nil {
|
|
_ = conn.Close()
|
|
}
|
|
}))
|
|
}
|
|
|
|
func newStreamBillingGateway(t *testing.T, providerType, baseURL, model string) *Gateway {
|
|
t.Helper()
|
|
cfg := CreateConfig()
|
|
cfg.Providers = map[string]*ProviderConfig{
|
|
"up": {Type: providerType, BaseURL: baseURL, APIKey: "k", Models: []string{model}},
|
|
}
|
|
cfg.Groups = map[string]*GroupConfig{"default": {}}
|
|
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
|
|
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
|
|
if err != nil {
|
|
t.Fatalf("New: %v", err)
|
|
}
|
|
gw, ok := h.(*Gateway)
|
|
if !ok {
|
|
t.Fatal("handler is not *Gateway")
|
|
}
|
|
return gw
|
|
}
|
|
|
|
func aliceTokens(gw *Gateway) (int64, int64) {
|
|
in, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now())
|
|
out, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
|
|
return in, out
|
|
}
|
|
|
|
func openAIContentFrames(n int) []string {
|
|
frames := make([]string, 0, n)
|
|
for i := 0; i < n; i++ {
|
|
frames = append(frames, `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"delta":{"content":"hello world, this is a chunk of text "}}]}`+"\n\n")
|
|
}
|
|
return frames
|
|
}
|
|
|
|
func anthropicFrames(deltas int, withMessageDelta bool) []string {
|
|
frames := []string{
|
|
"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"usage\":{\"input_tokens\":100}}}\n\n",
|
|
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
|
|
}
|
|
for i := 0; i < deltas; i++ {
|
|
frames = append(frames, "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hello world, this is a chunk of text \"}}\n\n")
|
|
}
|
|
if withMessageDelta {
|
|
frames = append(frames,
|
|
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5000}}\n\n",
|
|
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")
|
|
}
|
|
return frames
|
|
}
|
|
|
|
func TestOpenAIStreamHangup_BillsEstimatedCompletion(t *testing.T) {
|
|
srv := hangupServer(t, "text/event-stream", openAIContentFrames(12))
|
|
defer srv.Close()
|
|
gw := newStreamBillingGateway(t, providerTypeOpenAI, srv.URL, "gpt-test")
|
|
body := map[string]any{"model": "gpt-test", "stream": true, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
|
|
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
|
|
in, out := aliceTokens(gw)
|
|
if in <= 0 || out <= 0 {
|
|
t.Fatalf("tokin/tokout = %d/%d, want both > 0 after a hang-up that followed forwarded output", in, out)
|
|
}
|
|
}
|
|
|
|
func TestOpenAIStreamFullRead_BillsReportedUsage(t *testing.T) {
|
|
frames := append(openAIContentFrames(3),
|
|
`data: {"id":"c1","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":3000}}`+"\n\n",
|
|
"data: [DONE]\n\n")
|
|
srv := hangupServer(t, "text/event-stream", frames)
|
|
defer srv.Close()
|
|
gw := newStreamBillingGateway(t, providerTypeOpenAI, srv.URL, "gpt-test")
|
|
body := map[string]any{"model": "gpt-test", "stream": true, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
|
|
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
|
|
if in, out := aliceTokens(gw); in != 9 || out != 3000 {
|
|
t.Fatalf("tokin/tokout = %d/%d, want 9/3000", in, out)
|
|
}
|
|
}
|
|
|
|
func TestAnthropicChatStreamHangup_BillsEstimatedCompletion(t *testing.T) {
|
|
srv := hangupServer(t, "text/event-stream", anthropicFrames(20, false))
|
|
defer srv.Close()
|
|
gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test")
|
|
body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
|
|
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
|
|
in, out := aliceTokens(gw)
|
|
if in != 100 || out <= 0 {
|
|
t.Fatalf("tokin/tokout = %d/%d, want 100 / >0", in, out)
|
|
}
|
|
}
|
|
|
|
func TestAnthropicMessagesRelayHangup_BillsEstimatedCompletion(t *testing.T) {
|
|
srv := hangupServer(t, "text/event-stream", anthropicFrames(20, false))
|
|
defer srv.Close()
|
|
gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test")
|
|
body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
|
|
gw.ServeHTTP(httptest.NewRecorder(), newMessagesRequest(t, body, "x-api-key", "sk-alice"))
|
|
in, out := aliceTokens(gw)
|
|
if in != 100 || out <= 0 {
|
|
t.Fatalf("tokin/tokout = %d/%d, want 100 / >0", in, out)
|
|
}
|
|
}
|
|
|
|
func TestAnthropicStreamFullRead_BillsReportedUsage(t *testing.T) {
|
|
srv := hangupServer(t, "text/event-stream", anthropicFrames(3, true))
|
|
defer srv.Close()
|
|
gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test")
|
|
body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
|
|
gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body))
|
|
if in, out := aliceTokens(gw); in != 100 || out != 5000 {
|
|
t.Fatalf("tokin/tokout = %d/%d, want 100/5000", in, out)
|
|
}
|
|
}
|
|
|
|
func TestAnthropicStreamState_UsageOnAbortKeepsReportedCompletion(t *testing.T) {
|
|
st := newAnthropicStreamState("m", 1)
|
|
for _, ev := range []sseEvent{
|
|
{event: "message_start", data: []byte(`{"message":{"id":"x","usage":{"input_tokens":10}}}`)},
|
|
{event: "content_block_delta", data: []byte(`{"index":0,"delta":{"type":"text_delta","text":"abcdefgh"}}`)},
|
|
} {
|
|
if _, err := st.translate(ev); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if u := st.usageOnAbort(); u.completion != 2 || !u.estimated {
|
|
t.Fatalf("before message_delta: completion=%d estimated=%v, want 2/true", u.completion, u.estimated)
|
|
}
|
|
if _, err := st.translate(sseEvent{event: "message_delta", data: []byte(`{"delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":77}}`)}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if u := st.usageOnAbort(); u.completion != 77 || u.estimated {
|
|
t.Fatalf("after message_delta: completion=%d estimated=%v, want 77/false", u.completion, u.estimated)
|
|
}
|
|
}
|
|
|
|
type failingReader struct{}
|
|
|
|
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("hang-up") }
|
|
|
|
// Pin only: Gemini reports usageMetadata on every chunk, so an abort keeps the last one.
|
|
func TestGeminiStreamHangup_PinsLastUsageMetadata(t *testing.T) {
|
|
a, err := newGeminiAdapter("p1", "http://unused", "k")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
frame := fmt.Sprintf("data: %s\n\n", `{"candidates":[{"content":{"role":"model","parts":[{"text":"hello there"}]}}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":4}}`)
|
|
u, err := a.forwardStream(httptest.NewRecorder(), io.MultiReader(strings.NewReader(frame), failingReader{}), "g", false)
|
|
if err == nil {
|
|
t.Fatal("want a stream error")
|
|
}
|
|
if u.prompt != 10 || u.completion != 4 {
|
|
t.Fatalf("usage = %d/%d, want 10/4 (report to integrator if completion is 0)", u.prompt, u.completion)
|
|
}
|
|
}
|