gateway: Mistral requests carry a prompt_cache_key of their conversation (daoche_wuzui on X)
Mistral routes a request by prompt_cache_key to the server holding its prompt cache; magpie sent none, so cache hits were poor. A Chat request bound for Mistral (preset or api.mistral.ai) with no key gets the sha256 hex of the session, else the conversation id: opaque, stable per conversation, never the raw id. A client's own key and a user's extraBody key are kept; translated requests get it through ownCacheKey (its refusal retry applies). Other vendors are unchanged. Run (mote): TestMistralPromptCacheKey, TestOwnCacheKey, CacheKey tests, then gofmt, go vet on darwin/windows/linux nogui, and the gateway package. TestMistralPromptCacheKey was red on the old code (no key). Not tried: a real Mistral API key.
This commit is contained in:
@@ -158,6 +158,8 @@ func TestOwnCacheKey(t *testing.T) {
|
||||
}{
|
||||
{provider.Provider{ID: "relay", Chat: "https://relay.example/v1"}, true},
|
||||
{provider.Provider{ID: "openai", Preset: "openai", Responses: "https://api.openai.com/v1"}, true},
|
||||
{provider.Provider{ID: "mistral", Preset: "mistral", Chat: "https://api.mistral.ai/v1"}, true},
|
||||
{provider.Provider{ID: "mistral-own", Chat: "https://api.mistral.ai/v1", ExtraBody: provider.ExtraBody{"prompt_cache_key": json.RawMessage(`"k"`)}}, false},
|
||||
{provider.Provider{ID: "deepseek", Preset: "deepseek", Chat: "https://api.deepseek.com/v1"}, false},
|
||||
{provider.Provider{ID: "codex", Account: &provider.Account{}, Responses: "https://chatgpt.com/backend-api/codex"}, false},
|
||||
{provider.Provider{ID: "relay-own", Chat: "https://relay.example/v1", ExtraBody: provider.ExtraBody{"prompt_cache_key": json.RawMessage(`"${sessionId}"`)}}, false},
|
||||
|
||||
@@ -6463,6 +6463,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
}
|
||||
upstream := provider.UpstreamNameIn(wiresOf(r.Context()), p.ID, model)
|
||||
body = rewriteModel(body, upstream)
|
||||
if proto == provider.Chat {
|
||||
body = withMistralCacheKey(p, r.Header, body)
|
||||
}
|
||||
if proto == provider.Responses {
|
||||
// Claude's blocks magpie gave a Responses client go back to Claude
|
||||
// alone; to this API the item is its summary, as before
|
||||
@@ -8566,7 +8569,9 @@ const cacheKeyField = "prompt_cache_key"
|
||||
// client's never has one): OpenAI's API routes a conversation by it to
|
||||
// where its prompt is cached, and a relay in front of it can refuse a
|
||||
// request without it ("prompt_cache_key is required", CyberCaius's
|
||||
// AnyRouter on Discord). Only OpenAI's own API with a key, and a provider
|
||||
// AnyRouter on Discord). Only OpenAI's own API with a key, Mistral's
|
||||
// (its prompt_cache_key keeps a conversation on the server that holds its
|
||||
// cache; daoche_wuzui on X), and a provider
|
||||
// the user added by its address, which may be such a relay: a vendor's
|
||||
// preset, a signed-in account (the ChatGPT backend gets its own, as Codex
|
||||
// CLI sends it), a plugin, Bedrock and Vertex are sent nothing they didn't
|
||||
@@ -8584,13 +8589,35 @@ func ownCacheKey(p provider.Provider) bool {
|
||||
if _, ok := p.ExtraBody["!"+cacheKeyField]; ok {
|
||||
return false
|
||||
}
|
||||
if p.AddedByAddress() {
|
||||
if p.AddedByAddress() || isMistral(p) {
|
||||
return true
|
||||
}
|
||||
h := p.VendorHost()
|
||||
return h == "api.openai.com" || strings.HasSuffix(h, ".api.openai.com")
|
||||
}
|
||||
|
||||
func isMistral(p provider.Provider) bool {
|
||||
return p.Preset == "mistral" || p.Host() == "api.mistral.ai"
|
||||
}
|
||||
|
||||
// withMistralCacheKey gives a Chat body bound for Mistral the
|
||||
// prompt_cache_key Mistral routes a conversation by to where its prompt is
|
||||
// cached (daoche_wuzui on X: poor cache hits). The key is a hash of the
|
||||
// session or conversation, never the id itself, and a key the client sent,
|
||||
// or the user's extraBody, is the one kept. A body with no conversation to
|
||||
// name gets none.
|
||||
func withMistralCacheKey(p provider.Provider, in http.Header, body []byte) []byte {
|
||||
if !isMistral(p) || !ownCacheKey(p) || gjson.GetBytes(body, cacheKeyField).Exists() {
|
||||
return body
|
||||
}
|
||||
id := cmp.Or(sessionOf(in), conversationID(in, body))
|
||||
if id == "" {
|
||||
return body
|
||||
}
|
||||
sum := sha256.Sum256([]byte("mistral\x00" + id))
|
||||
return withFields(body, map[string]any{cacheKeyField: hex.EncodeToString(sum[:])})
|
||||
}
|
||||
|
||||
// cacheKeyOf is the prompt cache key of the conversation req is a turn
|
||||
// of: the session the client names (sessionOf), else its first user
|
||||
// message, which every later turn repeats, hashed into a UUID's shape, so
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Mistral reads prompt_cache_key to keep a conversation on the server that
|
||||
// holds its cache (daoche_wuzui on X). A turn without one gets an opaque
|
||||
// hash of its conversation; a client's own key and other vendors are left
|
||||
// as they were.
|
||||
func TestMistralPromptCacheKey(t *testing.T) {
|
||||
const msg = `{"model":"m1","messages":[{"role":"user","content":"hello there"}]}`
|
||||
run := func(preset, body, session string) string {
|
||||
f := &fake{t: t, reply: deepseekReply}
|
||||
up := setup(t, provider.Chat, f)
|
||||
p, _ := provider.Find("fake")
|
||||
p.Preset, p.Chat = preset, up.URL+"/v1"
|
||||
if err := provider.Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := map[string]string{}
|
||||
if session != "" {
|
||||
h["X-Session-Id"] = session
|
||||
}
|
||||
rec, _ := postWith(t, "/v1/chat/completions", body, h)
|
||||
if rec != 200 {
|
||||
t.Fatalf("status %d", rec)
|
||||
}
|
||||
return string(f.got)
|
||||
}
|
||||
a := gjson.Get(run("mistral", msg, "sess-secret-1"), "prompt_cache_key").String()
|
||||
b := gjson.Get(run("mistral", msg, "sess-secret-1"), "prompt_cache_key").String()
|
||||
c := gjson.Get(run("mistral", msg, "sess-secret-2"), "prompt_cache_key").String()
|
||||
if a == "" || a != b || a == c {
|
||||
t.Errorf("keys %q %q %q: want the same for one session, another for another", a, b, c)
|
||||
}
|
||||
if strings.Contains(a, "sess-secret") {
|
||||
t.Errorf("key %q holds the session id", a)
|
||||
}
|
||||
if got := gjson.Get(run("mistral", strings.Replace(msg, `"messages"`, `"prompt_cache_key":"mine","messages"`, 1), "s"), "prompt_cache_key").String(); got != "mine" {
|
||||
t.Errorf("client key became %q", got)
|
||||
}
|
||||
if got := run("deepseek", msg, "s"); strings.Contains(got, "prompt_cache_key") {
|
||||
t.Errorf("another vendor got a key: %s", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user