gateway: bring back Mistral's prompt_cache_key, which d31988c95 undid
d31988c95(the Mac title bar at first show) also carried, unnamed, the reverse of1648fcfe2and95eab9a66: withMistralCacheKey and isMistral were taken out of gateway.go, mistral_cache_key_test.go was deleted, and TestOwnCacheKey lost its two Mistral rows. Its body names only the title bar. So Mistral users lost the cache key daoche_wuzui asked for (poor cache hits on X) with no commit saying so. This restores those four gateway files to what95eab9a66left; the title bar change (internal/gui) is kept as it is. Run (mica): gofmt clean; go vet ./internal/gateway on darwin, GOOS=windows and GOOS=linux -tags nogui ok; go test -run 'Mistral|OwnCacheKey|CacheKey|DesktopProbe|PromptCache' ./internal/gateway ok. Not tried: the full suite, a real Mistral 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,49 @@ 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))
|
||||
// written in ahead of the first member, so the client's own bytes
|
||||
// (and the order its messages were sent in, for the cache) stay as sent
|
||||
i := bytes.IndexByte(body, '{')
|
||||
if i < 0 || len(bytes.TrimSpace(body[:i])) > 0 {
|
||||
return body
|
||||
}
|
||||
rest := bytes.TrimLeft(body[i+1:], " \t\r\n")
|
||||
sep := ","
|
||||
if len(rest) == 0 || rest[0] == '}' {
|
||||
sep = ""
|
||||
}
|
||||
out := make([]byte, 0, len(body)+96)
|
||||
out = append(out, body[:i+1]...)
|
||||
out = append(out, `"`+cacheKeyField+`":"`+hex.EncodeToString(sum[:])+`"`+sep...)
|
||||
return append(out, body[i+1:]...)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
// field it doesn't know: 422 extra_forbidden, every such field listed.
|
||||
func mistralRefuse(body []byte) (int, string) {
|
||||
known := []string{"model", "messages", "stream", "stream_options", "max_tokens", "temperature", "top_p", "tools", "tool_choice",
|
||||
"parallel_tool_calls", "response_format", "stop", "random_seed", "presence_penalty", "frequency_penalty", "n", "reasoning_effort"}
|
||||
"parallel_tool_calls", "response_format", "stop", "random_seed", "presence_penalty", "frequency_penalty", "n", "reasoning_effort", "prompt_cache_key"}
|
||||
var m map[string]json.RawMessage
|
||||
json.Unmarshal(body, &m)
|
||||
var detail []string
|
||||
|
||||
Reference in New Issue
Block a user