diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a07caf206..265d0458b 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1713,10 +1713,14 @@ func conversationID(in http.Header, body []byte) string { var m struct { Messages []json.RawMessage `json:"messages"` Input json.RawMessage `json:"input"` + Contents []json.RawMessage `json:"contents"` } // An undecodable body still gets an id: the hash of the whole body. _ = json.Unmarshal(body, &m) items := m.Messages + if len(items) == 0 { + items = m.Contents // Gemini generateContent repeats the first user turn. + } if len(items) == 0 && len(m.Input) > 0 && m.Input[0] == '[' { // A malformed input array leaves items empty, and the whole body is hashed. _ = json.Unmarshal(m.Input, &items) diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 843338d5b..aeab14f7c 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -931,6 +931,14 @@ func TestConversationID(t *testing.T) { if r1 != r2 { t.Errorf("responses ids: %q %q", r1, r2) } + // Gemini requests have contents, not messages or input. Later turns repeat + // the first user content even as the system instruction and history grow. + g1 := conversationID(http.Header{}, []byte(`{"model":"m","contents":[{"role":"user","parts":[{"text":"fix the bug"}]}]}`)) + g2 := conversationID(http.Header{}, []byte(`{"model":"m","systemInstruction":{"parts":[{"text":"help"}]},"contents":[{"role":"user","parts":[{"text":"fix the bug"}]},{"role":"model","parts":[{"text":"done"}]},{"role":"user","parts":[{"text":"thanks"}]}]}`)) + gOther := conversationID(http.Header{}, []byte(`{"model":"m","contents":[{"role":"user","parts":[{"text":"write docs"}]}]}`)) + if g1 != g2 || g1 == gOther || !strings.HasPrefix(g1, "magpie-") { + t.Errorf("gemini derived ids: %q %q %q", g1, g2, gOther) + } } func TestSessionOf(t *testing.T) { diff --git a/internal/gateway/group_test.go b/internal/gateway/group_test.go index 1edbfe9e2..8a36a258c 100644 --- a/internal/gateway/group_test.go +++ b/internal/gateway/group_test.go @@ -377,3 +377,47 @@ func TestKeyPoolsByProtocol(t *testing.T) { t.Fatalf("aside key: %d %s, tried %v", code, body, v.tried) } } + +// A Gemini client without a recognized session header keeps its provider key +// across turns even when the request's contents, model and instructions grow. +func TestGeminiFallbackSessionAffinity(t *testing.T) { + fresh(t) + v := &geminiKeyed{} + serveOn(t, "aff", "k1", []string{"m"}, v, "k2") + provider.SetAffinity("aff", provider.AffinitySession) + s := New() + for _, body := range []string{ + `{"contents":[{"role":"user","parts":[{"text":"fix the bug"}]}]}`, + `{"systemInstruction":{"parts":[{"text":"help"}]},"contents":[{"role":"user","parts":[{"text":"fix the bug"}]},{"role":"model","parts":[{"text":"done"}]},{"role":"user","parts":[{"text":"thanks"}]}]}`, + } { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1beta/models/aff/m:generateContent", strings.NewReader(body)) + s.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("Gemini request: %d %s", rec.Code, rec.Body.String()) + } + } + if len(v.tried) != 2 || v.tried[0] != v.tried[1] { + t.Fatalf("Gemini turns changed key: %v", v.tried) + } + r := s.trace.routes[len(s.trace.routes)-1] + if r.Affinity == nil || !r.Affinity.Kept || r.Affinity.Why != "session" { + t.Fatalf("Gemini turn did not keep session affinity: %+v", r.Affinity) + } +} + +// Gemini is translated to a streamed Chat response by the gateway. +type geminiKeyed struct{ tried []string } + +func (k *geminiKeyed) ServeHTTP(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + k.tried = append(k.tried, key) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"id":"x","choices":[{"delta":{"content":"from `+key+`"}}]}`, + `data: {"id":"x","choices":[{"delta":{},"finish_reason":"stop"}]}`, + `data: {"id":"x","choices":[],"usage":{"prompt_tokens":3000,"completion_tokens":5,"prompt_tokens_details":{"cached_tokens":2500}}}`, + `data: [DONE]`, + )) +}