From 3ec45e7155c50656eca1d72dea22e50f62517f97 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 14 Oct 2026 16:39:26 +0800 Subject: [PATCH] gateway: a json_schema an upstream turns away is asked for as a JSON object, the schema in the system prompt, before the format is told in words alone (#2126) klarkxy's Codex on Xiaomi MiMo's Token Plan got back "text.format type 'json_schema' is not supported, only 'text' and 'json_object' are supported" and the turn ended there. Codex's /responses reaches the upstream by passthrough when the protocols match, and passthrough never looked at a format refusal; the translated path did, but only by moving the whole format into the system prompt, which drops the object requirement the vendor would have kept. Now, on either path, a json_schema the upstream turns away is asked again as {"type":"json_object"} with the schema appended to the system prompt (Responses instructions, Chat's first system/developer message, Anthropic system). If json_object is turned away too, the format field goes and only the words stay. Each step is remembered per provider, model and protocol once a request with it is taken, so later turns go out already rewritten. Anthropic's output_config.format has no object mode, so it goes straight to words. DeepSeek, which takes json_object only, gains the same middle step on the translated path. Run: - format_refused_test.go, new: - TestPassthroughSchemaRefusedAskedAsObject replays the reporter's exact error and probe body through /backend-api/codex/responses. It covers object taken (2 asks, then json_object) and object refused too (3 asks, then no format). Turn 2 is checked to take 1 ask, the instructions to keep "You are Codex." first, and the input to be unchanged. - TestPassthroughFormatRefusedChatAndAnthropic. - TestRefusedFormatToldInWords was rewritten for both outcomes on the translated path. - Break check: with the old gateway.go, the passthrough test gets back the reporter's exact error. - gofmt -l is clean. go vet passes for darwin, GOOS=linux -tags nogui and GOOS=windows. go test ./internal/gateway/ -count=1 is ok (1017s). Not tried: a real Xiaomi MiMo key (none here; the error envelope is assumed to be OpenAI's), and Gemini passthrough, which has no rewrite. --- internal/gateway/format.go | 139 +++++++++++++++- internal/gateway/format_refused_test.go | 205 ++++++++++++++++++++++++ internal/gateway/format_test.go | 82 +++++----- internal/gateway/gateway.go | 56 ++++++- 4 files changed, 437 insertions(+), 45 deletions(-) create mode 100644 internal/gateway/format_refused_test.go diff --git a/internal/gateway/format.go b/internal/gateway/format.go index 7c01fd897..7b5e1ef4f 100644 --- a/internal/gateway/format.go +++ b/internal/gateway/format.go @@ -1,8 +1,13 @@ package gateway import ( + "bytes" "encoding/json" "regexp" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" ) // Format is the shape a client asked the answer to come in (structured @@ -21,6 +26,9 @@ type Format struct { Schema json.RawMessage // Strict is the client's strict, nil when it said none. Strict *bool + // told is a JSON object asked for in place of a schema the system + // prompt already holds (asObject). + told bool } // formatName is the name a schema goes under when the client's API names @@ -126,10 +134,9 @@ func (r *Request) inSystem() *Request { } q := *r q.Format = nil - if q.System != "" { - q.System += "\n\n" + if !r.Format.told { + q.System = withLine(q.System, r.Format.instruction()) } - q.System += r.Format.instruction() return &q } @@ -148,3 +155,129 @@ var formatRefusal = regexp.MustCompile(`(?i)response_format|json_schema|json_obj func refusesFormat(status int, body []byte) bool { return (status == 400 || status == 422) && formatRefusal.Match(body) } + +// schemaRefused is how unfit remembers a provider turning away a schema +// while it takes any JSON object (Xiaomi MiMo's Token Plan: "text.format +// type 'json_schema' is not supported, only 'text' and 'json_object' are +// allowed", #2126), so it is asked for a JSON object, the schema told in +// the system prompt, from then on. +func schemaRefused(model string) string { return "json_schema:" + model } + +// asObject is r asking for any JSON object, its schema told in the system +// prompt; r itself when it asks for no schema. +func (r *Request) asObject() *Request { + if r.Format == nil || r.Format.Type != "json_schema" { + return r + } + q := *r + q.Format = &Format{Type: "json_object", told: true} + q.System = withLine(q.System, r.Format.instruction()) + return &q +} + +// withLine is a system prompt with s said at its end. +func withLine(system, s string) string { + if system != "" { + system += "\n\n" + } + return system + s +} + +// bodyFormat is the format a body passed through as the client sent it +// asks for, nil when it asks for none: Responses' text.format, Chat's +// response_format, Anthropic's output_config.format. +func bodyFormat(proto provider.Protocol, body []byte) *Format { + switch proto { + case provider.Responses: + return openAIFormat(json.RawMessage(gjson.GetBytes(body, "text.format").Raw)) + case provider.Chat: + return openAIFormat(json.RawMessage(gjson.GetBytes(body, "response_format").Raw)) + case provider.Anthropic: + if f := gjson.GetBytes(body, "output_config.format"); f.Get("type").String() == "json_schema" && f.Get("schema").IsObject() { + return &Format{Type: "json_schema", Name: formatName, Schema: json.RawMessage(f.Get("schema").Raw)} + } + } + return nil +} + +// formatInBody is a passed-through body asking for its format less, the +// rest told in the system prompt: with object, a schema as any JSON object +// (asObject); without, no format field at all (inSystem). Anthropic's +// output_config.format takes a schema only, so it is never asked for an +// object. The body and false when there is nothing to change. +func formatInBody(proto provider.Protocol, body []byte, object bool) ([]byte, bool) { + f := bodyFormat(proto, body) + if f == nil || object && (proto == provider.Anthropic || f.Type != "json_schema") { + return body, false + } + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + var m map[string]any + if dec.Decode(&m) != nil { + return body, false + } + line := f.instruction() + switch proto { + case provider.Responses: + text, _ := m["text"].(map[string]any) + if text == nil { + return body, false + } + if object { + text["format"] = map[string]any{"type": "json_object"} + } else if delete(text, "format"); len(text) == 0 { + delete(m, "text") + } + s, _ := m["instructions"].(string) + m["instructions"] = withLine(s, line) + case provider.Chat: + if object { + m["response_format"] = map[string]any{"type": "json_object"} + } else { + delete(m, "response_format") + } + m["messages"] = withSystemLine(m["messages"], line) + case provider.Anthropic: + oc, _ := m["output_config"].(map[string]any) + if delete(oc, "format"); len(oc) == 0 { + delete(m, "output_config") + } + switch s := m["system"].(type) { + case []any: + m["system"] = append(s, map[string]any{"type": "text", "text": line}) + case string: + m["system"] = withLine(s, line) + default: + m["system"] = line + } + } + var out bytes.Buffer + enc := json.NewEncoder(&out) + enc.SetEscapeHTML(false) // <, > and & as the agent wrote them + if enc.Encode(m) != nil { + return body, false + } + return bytes.TrimSuffix(out.Bytes(), []byte("\n")), true +} + +// withSystemLine is a chat's messages with s said at the end of its first +// system (or developer) message, or in one of its own ahead of the rest +// when it has none. +func withSystemLine(v any, s string) []any { + msgs, _ := v.([]any) + for _, raw := range msgs { + msg, ok := raw.(map[string]any) + if !ok || msg["role"] != "system" && msg["role"] != "developer" { + continue + } + switch c := msg["content"].(type) { + case string: + msg["content"] = withLine(c, s) + return msgs + case []any: + msg["content"] = append(c, map[string]any{"type": "text", "text": s}) + return msgs + } + } + return append([]any{map[string]any{"role": "system", "content": s}}, msgs...) +} diff --git a/internal/gateway/format_refused_test.go b/internal/gateway/format_refused_test.go new file mode 100644 index 000000000..5515384b8 --- /dev/null +++ b/internal/gateway/format_refused_test.go @@ -0,0 +1,205 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// mimoSchemaRefusal is Xiaomi MiMo's Token Plan turning away a schema +// (klarkxy, #2126: Codex's memory_consolidation and thread_title). The +// message is the reporter's, word for word; the envelope around it is +// OpenAI's, which MiMo's API follows. +const mimoSchemaRefusal = `{"error":{"message":"text.format type 'json_schema' is not supported, only 'text' and 'json_object' are allowed.","type":"invalid_request_error","param":null,"code":"400"}}` + +// mimoProbe is the request #2126 gives to reproduce it, with an +// instructions field as Codex sends one. +const mimoProbe = `{"model":"xiaomi/mimo-v2.6-flash","stream":true,"reasoning":{"effort":"low"},"instructions":"You are Codex.","input":"Return a JSON object whose ok field is true.","text":{"format":{"type":"json_schema","name":"compat_probe","strict":true,"schema":{"type":"object","properties":{"ok":{"type":"boolean"}},"required":["ok"],"additionalProperties":false}}}}` + +// formatRefuser answers as an upstream that takes no json_schema, and with +// object no json_object either: Responses, Chat and Anthropic Messages. +type formatRefuser struct { + mu sync.Mutex + bodies []map[string]any + object bool +} + +func (v *formatRefuser) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var m map[string]any + json.Unmarshal(b, &m) + v.mu.Lock() + v.bodies = append(v.bodies, m) + v.mu.Unlock() + var f map[string]any + switch { + case strings.HasSuffix(r.URL.Path, "/responses"): + t, _ := m["text"].(map[string]any) + f, _ = t["format"].(map[string]any) + case strings.HasSuffix(r.URL.Path, "/chat/completions"): + f, _ = m["response_format"].(map[string]any) + default: + oc, _ := m["output_config"].(map[string]any) + f, _ = oc["format"].(map[string]any) + } + if f != nil && (f["type"] == "json_schema" || v.object && f["type"] == "json_object") { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + if strings.HasSuffix(r.URL.Path, "/messages") { + io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"output_config.format: Extra inputs are not permitted"}}`) + return + } + if v.object { + io.WriteString(w, `{"error":{"message":"This response_format type is unavailable now","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}`) + return + } + io.WriteString(w, mimoSchemaRefusal) + return + } + text, _ := json.Marshal(`{"ok":true}`) + w.Header().Set("Content-Type", "text/event-stream") + switch { + case strings.HasSuffix(r.URL.Path, "/responses"): + io.WriteString(w, sse(`data: {"type":"response.output_text.delta","delta":`+string(text)+`}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":`+string(text)+`}]}]}}`)) + case strings.HasSuffix(r.URL.Path, "/chat/completions"): + io.WriteString(w, sse(`data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":`+string(text)+`}}]}`, + `data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`)) + default: + io.WriteString(w, sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":`+string(text)+`}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)) + } +} + +func (v *formatRefuser) all() []map[string]any { + v.mu.Lock() + defer v.mu.Unlock() + return append([]map[string]any(nil), v.bodies...) +} + +// A request passed through as the client sent it (Codex's Responses to +// Xiaomi MiMo's Responses API, #2126) whose schema the upstream turns away +// is asked again for any JSON object, the schema in its instructions, and +// so from then on; one whose object is turned away too, with the format in +// the instructions alone. Before, the 400 went to the client. +func TestPassthroughSchemaRefusedAskedAsObject(t *testing.T) { + for _, c := range []struct { + name string + object bool // json_object turned away too + first int // requests on the first turn + want any // text.format sent once it is taken + }{ + {"object taken", false, 2, map[string]any{"type": "json_object"}}, + {"object refused too", true, 3, nil}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + up := &formatRefuser{object: c.object} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "xiaomi", Name: "Xiaomi MiMo", Preset: "xiaomi", Key: "tp-k", Models: []string{"mimo-v2.6-flash"}, Responses: srv.URL + "/v1"}); err != nil { + t.Fatal(err) + } + h := New().Handler() + // the first turn as the reporter's probe, the second where Codex + // sends its memory_consolidation + for turn, path := range []string{"/v1/responses", CodexPath + "/responses"} { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(mimoProbe))) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `ok`) { + t.Fatalf("turn %d: status %d: %s", turn, rec.Code, rec.Body.String()) + } + bodies := up.all() + if turn == 0 && len(bodies) != c.first { + t.Fatalf("%d requests on the first turn, want %d", len(bodies), c.first) + } + if turn == 1 && len(bodies) != c.first+1 { + t.Fatalf("second turn took %d requests, want 1: the refusal wasn't remembered", len(bodies)-c.first) + } + last := bodies[len(bodies)-1] + text, _ := last["text"].(map[string]any) + if jsonOf(text["format"]) != jsonOf(c.want) { + t.Fatalf("turn %d: text.format = %s, want %s", turn, jsonOf(text["format"]), jsonOf(c.want)) + } + ins, _ := last["instructions"].(string) + if !strings.HasPrefix(ins, "You are Codex.\n\n") || !strings.Contains(ins, `matching this JSON schema`) || !strings.Contains(ins, `"required":["ok"]`) { + t.Fatalf("turn %d: schema not told in the instructions: %q", turn, ins) + } + if last["input"] != "Return a JSON object whose ok field is true." { + t.Fatalf("turn %d: input changed: %s", turn, jsonOf(last["input"])) + } + } + }) + } +} + +// The same on Chat's response_format, passed through to a Chat upstream, +// and on Anthropic's output_config.format, which takes a schema only and +// so goes to the system prompt at once. +func TestPassthroughFormatRefusedChatAndAnthropic(t *testing.T) { + t.Run("chat", func(t *testing.T) { + fresh(t) + up := &formatRefuser{} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "xiaomi", Name: "Xiaomi MiMo", Key: "tp-k", Models: []string{"mimo-v2.6-flash"}, Chat: srv.URL + "/v1"}); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(strings.Replace(sdkChatParse, "%s", "xiaomi/mimo-v2.6-flash", 1)))) + if rec.Code != 200 { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + bodies := up.all() + last := bodies[len(bodies)-1] + if len(bodies) != 2 || jsonOf(last["response_format"]) != `{"type":"json_object"}` { + t.Fatalf("%d requests, last response_format %s", len(bodies), jsonOf(last["response_format"])) + } + msgs, _ := last["messages"].([]any) + first, _ := msgs[0].(map[string]any) + if len(msgs) != 2 || first["role"] != "system" || !strings.HasPrefix(first["content"].(string), "Extract the event information.\n\n") || !strings.Contains(first["content"].(string), `"CalendarEvent"`) { + t.Fatalf("messages = %s", jsonOf(msgs)) + } + }) + t.Run("anthropic", func(t *testing.T) { + fresh(t) + up := &formatRefuser{} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "xiaomi", Name: "Xiaomi MiMo", Key: "tp-k", Models: []string{"mimo-v2.6-flash"}, Anthropic: srv.URL}); err != nil { + t.Fatal(err) + } + body := `{"model":"xiaomi/mimo-v2.6-flash","max_tokens":100,"stream":true,"system":[{"type":"text","text":"Extract the event information."}],"messages":[{"role":"user","content":"Alice and Bob are going to a science fair on Friday."}],"output_config":{"effort":"low","format":{"type":"json_schema","schema":` + calendarSchema + `}}}` + h := New().Handler() + for turn := range 2 { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("turn %d: status %d: %s", turn, rec.Code, rec.Body.String()) + } + } + bodies := up.all() + if len(bodies) != 3 { + t.Fatalf("%d requests, want 3: one refused, then two told in words", len(bodies)) + } + last := bodies[2] + if jsonOf(last["output_config"]) != `{"effort":"low"}` { + t.Fatalf("output_config = %s", jsonOf(last["output_config"])) + } + sys := jsonOf(last["system"]) + if !strings.Contains(sys, "Extract the event information.") || !strings.Contains(sys, "matching this JSON schema") { + t.Fatalf("system = %s", sys) + } + }) +} diff --git a/internal/gateway/format_test.go b/internal/gateway/format_test.go index cb82efb41..f53fb1fa6 100644 --- a/internal/gateway/format_test.go +++ b/internal/gateway/format_test.go @@ -35,7 +35,6 @@ type formatVendor struct { mu sync.Mutex bodies []map[string]any paths []string - refuse bool } func (v *formatVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -45,18 +44,11 @@ func (v *formatVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { v.mu.Lock() v.bodies = append(v.bodies, m) v.paths = append(v.paths, r.URL.Path) - refuse := v.refuse v.mu.Unlock() text, _ := json.Marshal(calendarAnswer) w.Header().Set("Content-Type", "text/event-stream") switch { case strings.HasSuffix(r.URL.Path, "/chat/completions"): - if rf, _ := m["response_format"].(map[string]any); refuse && rf["type"] == "json_schema" { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(400) - io.WriteString(w, `{"error":{"message":"This response_format type is unavailable now","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}`) - return - } io.WriteString(w, sse(`data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":`+string(text)+`}}]}`, `data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":5,"total_tokens":10}}`, `data: [DONE]`)) @@ -213,38 +205,50 @@ func TestResponsesTextKeepsVerbosityBesideFormat(t *testing.T) { } } -// An upstream that turns the format away (DeepSeek: "This response_format -// type is unavailable now") is asked again with the format in the system -// prompt, and so from then on, rather than the client getting a 400 for a -// field the model could have been told in words. +// An upstream that turns a schema away but takes any JSON object +// (DeepSeek: "This response_format type is unavailable now"; Xiaomi MiMo's +// Token Plan, #2126) is asked again for an object, the schema in the +// system prompt; one that turns the object away too, with the format in +// the system prompt alone. Each from then on, rather than the client +// getting a 400 for a field the model could have been told in words. func TestRefusedFormatToldInWords(t *testing.T) { - fresh(t) - up := &formatVendor{refuse: true} - srv := httptest.NewServer(up) - t.Cleanup(srv.Close) - if err := provider.Save(provider.Provider{ID: "ds", Name: "DS", Key: "k", Chat: srv.URL + "/v1", Models: []string{"deepseek-chat"}}); err != nil { - t.Fatal(err) - } - h := New().Handler() - for i := range 2 { - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(strings.Replace(sdkResponsesParse, "%s", "ds/deepseek-chat", 1)))) - if rec.Code != 200 { - t.Fatalf("turn %d: status %d: %s", i, rec.Code, rec.Body.String()) - } - _, sent := up.sent() - if sent["response_format"] != nil { - t.Fatalf("turn %d: response_format still sent: %s", i, jsonOf(sent["response_format"])) - } - if !strings.Contains(jsonOf(sent["messages"]), "matching this JSON schema") { - t.Fatalf("turn %d: format not told in words: %s", i, jsonOf(sent["messages"])) - } - } - up.mu.Lock() - n := len(up.bodies) - up.mu.Unlock() - if n != 3 { - t.Fatalf("%d requests, want 3: one refused, then two told in words", n) + for _, c := range []struct { + name string + object bool // json_object turned away too + first int // requests on the first turn + want any // response_format once it is taken + }{ + {"object taken", false, 2, map[string]any{"type": "json_object"}}, + {"object refused too", true, 3, nil}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + up := &formatRefuser{object: c.object} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "ds", Name: "DS", Key: "k", Chat: srv.URL + "/v1", Models: []string{"deepseek-chat"}}); err != nil { + t.Fatal(err) + } + h := New().Handler() + for i := range 2 { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(strings.Replace(sdkResponsesParse, "%s", "ds/deepseek-chat", 1)))) + if rec.Code != 200 { + t.Fatalf("turn %d: status %d: %s", i, rec.Code, rec.Body.String()) + } + bodies := up.all() + sent := bodies[len(bodies)-1] + if jsonOf(sent["response_format"]) != jsonOf(c.want) { + t.Fatalf("turn %d: response_format %s, want %s", i, jsonOf(sent["response_format"]), jsonOf(c.want)) + } + if m := jsonOf(sent["messages"]); !strings.Contains(m, "matching this JSON schema") || strings.Count(m, "Respond with a single JSON") != 1 { + t.Fatalf("turn %d: format not told in words once: %s", i, m) + } + } + if n := len(up.all()); n != c.first+1 { + t.Fatalf("%d requests, want %d: refused on the first turn, then remembered", n, c.first+1) + } + }) } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index f567167b3..6b713ea54 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3770,6 +3770,13 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if !s.fits(p.ID, toolStrictRefused, proto) { body, _ = withoutToolStrict(proto, body) } + // structured output an upstream turned away before (#2126): a schema + // as any JSON object, or the format told in the system prompt alone + if !s.fits(p.ID, formatRefused(model), proto) { + body, _ = formatInBody(proto, body, false) + } else if !s.fits(p.ID, schemaRefused(model), proto) { + body, _ = formatInBody(proto, body, true) + } // a Grok subscription is given Codex's namespaced functions flat // (grokBody), and Zed's plugin likewise (ZedBody); a call to one goes // back under its namespace (#404) @@ -3781,6 +3788,38 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if err != nil { return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true } + // structured output turned away (Xiaomi MiMo's Token Plan takes no + // json_schema, only text and json_object, #2126): a schema is asked + // for as any JSON object with the schema in the system prompt, and if + // that is turned away too the format is told there alone; each, once + // it is taken, from then on. What the client asked for still reaches + // the model, in words + for _, object := range []bool{true, false} { + if !badRequest(res.StatusCode) || bodyFormat(proto, body) == nil { + break + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(b)) + if !refusesFormat(res.StatusCode, b) { + break + } + nb, ok := formatInBody(proto, body, object) + if !ok { + continue + } + mark := formatRefused(model) + if object { + mark = schemaRefused(model) + } + body = nb + if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil { + return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true + } + if res.StatusCode < 400 { + s.markUnfit(p.ID, mark, proto) + } + } // a vendor that turns away the fields it doesn't know (Mistral's // extra_forbidden for OpenCode's store, #393) is asked again without // the optional ones it named, and not sent them again once that works @@ -4329,6 +4368,8 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to } if req.Format != nil && !s.fits(p.ID, formatRefused(model), to) { req = req.inSystem() + } else if req.Format != nil && to != provider.Anthropic && !s.fits(p.ID, schemaRefused(model), to) { + req = req.asObject() } if req.LastIsTurn && !req.Resume && req.endsWithAssistant() && !s.fits(p.ID, prefillRefused(model), to) { // a model that takes no prefill is asked to answer after the @@ -4501,10 +4542,19 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to } } if req.Format != nil && refusesFormat(res.StatusCode, b) { + if to != provider.Anthropic && req.Format.Type == "json_schema" { + // a schema turned away by an upstream that takes any + // JSON object (DeepSeek; Xiaomi MiMo's Token Plan, + // #2126): asked again for an object, the schema in the + // system prompt, and so from then on + s.markUnfit(p.ID, schemaRefused(model), to) + req = req.asObject() + continue + } // structured output turned away by the model or the relay in - // front of it (DeepSeek takes json_object only; a schema - // Anthropic can't hold): asked again with the format in the - // system prompt, and so from then on + // front of it (a schema Anthropic can't hold, an object + // refused too): asked again with the format in the system + // prompt, and so from then on s.markUnfit(p.ID, formatRefused(model), to) req = req.inSystem() continue