diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 839b19cf2..f6a9613d6 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -299,6 +299,7 @@ recorded as a prediction failure (`noPrediction`). - `/v1/models` and `/v1/models/{id}` give each model magpie knows a price of its `pricing` in OpenRouter's shape, USD a token as decimal strings: `prompt` and `completion` always (a price set at 0 included), `input_cache_read` and `input_cache_write` only when that part has a price (`catalog.OpenRouterPricing`, `catalog.PerToken` in [`openrouter.go`](../../internal/catalog/openrouter.go), which an agent plugin's `connect` is given too; cleary5779 on Discord, an agent showing what a call costs). The price is the one the Usage page counts the model at (`provider.EntryPricer`, as `EntryPriceIn`: the user's own, else the provider's list price or its maker's at its price rate; a subscription's model at its list price; a group only when every member costs the same), the base price only (no `Tiers`, no 1-hour write). A model no price is known for has no `pricing` key, never a 0. It is told to the callers `magpie_price` is (`local` or `sharedWith`), whether they ask or not. The list reads the settings, groups and providers once (`EntryPricer`), and `catalog.PricedBy` and `AtEndpoint` look a model up in indexes built once a catalog load (`priceIndexOf`, `endpoints`), not by walking every models.dev model a look-up: a 755-model list went from about 38ms to 18ms with pricing on, against about 10ms without, at load 65 (`TestModelsListPricing`, `TestPerToken`). Claude Desktop's, Claude Science's, Muse Code's, Codex's and Ollama's lists, the decision, image and video models carry no `pricing`: their clients read a shape of their own, and an image's price isn't a token's. - `/v1/models` and `/v1/models/{id}` say each chat model takes tools, a routing group included (`toolsTold`): models.dev's `tool_call: true`, beside its `reasoning`, and OpenRouter's `supported_parameters` (`tools`, `tool_choice`, and `reasoning` when it thinks), which Kilo's and Cline's lists are read by. A client that judges a model by what its list says found nothing for a group, whose id is the user's own name (psikent on Discord: an SSH client), and gave it no tools. magpie has no model that takes none (a call written as text is read back as one, `textcalls.go`), so every member of a group takes them and the group says so. No `capabilities` key is added: Cursor Private Inference reads it as an object (`cursorLocalModel`), Ollama and LM Studio as arrays of their own words, and no reader of an OpenAI-shaped list agrees on one (`TestGroupListedTakesTools`). A group's window and output stay its largest member's, its images any member's (#712, #756): the gateway sends a longer conversation, a longer reply or an image only to the members that hold it (`roomy`, `withRoom`, `withMaxOutput`), and the editor's Context hint names the member a longer conversation skips when the windows differ (windy on Discord). - A request that names no reply limit, translated to Anthropic's Messages API, which needs `max_tokens` (`forwardTranslated`), is sent the model's published limit (`askedOutput` in [`maxoutput.go`](../../internal/gateway/maxoutput.go)): the user's Max output, else the vendor's list or models.dev, within the window. `anthropicBody`'s `defaultMaxTokens` (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: `stop_reason: max_tokens` reaches a Responses client as `incomplete_details.reason: "max_output_tokens"` (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (`TestAnthropicMaxTokensIsTheModels`). +- A Chat Completions request's reply length goes under the name the vendor reads (`chatTokenField`, `retryTokenField` in [`token_field.go`](../../internal/gateway/token_field.go), on every request through `forwardOnce`): `max_completion_tokens` on OpenAI's own API (`provider.OpenAIHost`), whose newer models answer max_tokens with 400 "Use 'max_completion_tokens' instead" (GoxxKintBlade on X), and on Azure and Bedrock (`asCompletionTokens`); `max_tokens` on DeepSeek (`deepseekTokenField`); as the client sent it elsewhere, since Zhipu and most relays read `max_tokens` alone. A 400 whose words name the other field as the one to use (`provider.TokenFieldWanted`; a limit on the value is not one) is asked once more with that name, the key renamed in place (`provider.WithTokenField`), and the provider remembered in `unfit`, so its next request goes so at once (`TestChatTokenFieldRetriedWhenNamed`). A model's test does the same (`tinyBody`, `probe`; `TestProbeRetriesTokenFieldNamed`). - A restart to update on a Mac or Linux hands the listening socket to the new version ([GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over), [`handover.go`](../../internal/gateway/handover.go)). `Inherit` gives the diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 12f1f9666..34e9d34d9 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -525,7 +525,7 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte { out["service_tier"] = r.Tier } if r.MaxTokens > 0 { - if strings.HasSuffix(host, "openai.com") { + if provider.OpenAIHost(host) { out["max_completion_tokens"] = r.MaxTokens } else { out["max_tokens"] = r.MaxTokens diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b623aa5ae..4b99899b5 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4351,6 +4351,9 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P if err == nil && mantleRoutes(p, to) { res, err = s.mantleReroute(ctx, p, to, path, body, in, res) } + if err == nil { + res, err = s.retryTokenField(ctx, p, to, path, body, in, res) + } if err == nil && (res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusBadRequest) && p.Retries() { // an account that can mend what the refusal names (a Factory org // the server won't take; a model Copilot's Auto picked that the @@ -4399,6 +4402,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid body = deepseekToolPatterns(p, to, body) body = grokToolPatterns(p, to, body) body = deepseekTokenField(p, to, body) + body = s.chatTokenField(p, to, body) body = toolOneOfAsAnyOf(p, to, body) body = kimiToolEnumTypes(p, to, body) body = kimiToolRefTypes(p, to, body) diff --git a/internal/gateway/token_field.go b/internal/gateway/token_field.go new file mode 100644 index 000000000..a5e288a7a --- /dev/null +++ b/internal/gateway/token_field.go @@ -0,0 +1,75 @@ +package gateway + +import ( + "bytes" + "context" + "io" + "log" + "net/http" + + "github.com/yetone/magpie/internal/provider" +) + +// tokenFieldRefused is the unfit entry for a provider whose Chat +// Completions turned a reply-length field away, naming the other as the +// one to send: tokenFieldRefused+"max_tokens" means max_tokens is refused. +const tokenFieldRefused = "token-field-refused:" + +// chatTokenField names a Chat Completions request's reply length as p's +// API reads it: max_completion_tokens on OpenAI's own API, whose newer +// models turn max_tokens away (GoxxKintBlade on X: a client's, or +// magpie's image describer's, max_tokens 400 "Use 'max_completion_tokens' +// instead"), and on any other the name it asked for once it turned the +// other away (forward). Every other vendor's body goes as it came: +// DeepSeek, Zhipu and most relays read max_tokens alone. +func (s *Server) chatTokenField(p provider.Provider, to provider.Protocol, body []byte) []byte { + if to != provider.Chat { + return body + } + want := "" + switch { + case !s.fits(p.ID, tokenFieldRefused+provider.CompletionTokField, to): + want = provider.MaxTokensField + case !s.fits(p.ID, tokenFieldRefused+provider.MaxTokensField, to) || provider.OpenAIHost(provider.HostOf(p.Base(to))): + want = provider.CompletionTokField + default: + return body + } + out, _ := provider.WithTokenField(body, want) + return out +} + +// retryTokenField asks a Chat Completions request once more when its 400 +// names the other reply-length field as the one to send, and remembers +// that for p, so the next request goes with it at once (chatTokenField). +func (s *Server) retryTokenField(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header, res *http.Response) (*http.Response, error) { + if to != provider.Chat || !badRequest(res.StatusCode) { + return res, nil + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(b)) + want := provider.TokenFieldWanted(b) + if want == "" { + return res, nil + } + if _, ok := provider.WithTokenField(body, want); !ok { + return res, nil + } + refused := provider.MaxTokensField + if want == provider.MaxTokensField { + refused = provider.CompletionTokField + } + log.Printf("gateway: %s turned away %s (%d); asked with %s from now on", p.ID, refused, res.StatusCode, want) + s.mu.Lock() + s.unfit[p.ID+"\x00"+tokenFieldRefused+refused+"\x00"+string(to)] = true + delete(s.unfit, p.ID+"\x00"+tokenFieldRefused+want+"\x00"+string(to)) + s.mu.Unlock() + again, err := s.forwardOnce(ctx, p, to, path, body, in) + if err != nil { + // the refusal stands + res.Body = io.NopCloser(bytes.NewReader(b)) + return res, nil + } + return again, nil +} diff --git a/internal/gateway/token_field_test.go b/internal/gateway/token_field_test.go new file mode 100644 index 000000000..5b544aba1 --- /dev/null +++ b/internal/gateway/token_field_test.go @@ -0,0 +1,130 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// openAIRefusal is OpenAI's own 400 for max_tokens on its newer models +// (GoxxKintBlade on X, gpt-6.1-sol). +const openAIRefusal = `{"error":{"message":"Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead.","type":"invalid_request_error","param":"max_tokens","code":"unsupported_parameter"}}` + +// A Chat Completions request to OpenAI's own API names its reply length +// max_completion_tokens; DeepSeek's, Zhipu's and a relay's go as they came. +func TestOpenAIChatGetsMaxCompletionTokens(t *testing.T) { + fresh(t) + s := New() + body := []byte(`{"model":"m","max_tokens":4096,"messages":[{"role":"user","content":"what is \"max_tokens\"?"}]}`) + for _, c := range []struct { + base string + want string + }{ + {"https://api.openai.com/v1", "max_completion_tokens"}, + {"https://api.deepseek.com/v1", "max_tokens"}, + {"https://open.bigmodel.cn/api/paas/v4", "max_tokens"}, + {"https://relay.example/v1", "max_tokens"}, + {"https://notopenai.com/v1", "max_tokens"}, + } { + p := provider.Provider{ID: "x", Chat: c.base} + got := s.chatTokenField(p, provider.Chat, body) + if n := gjson.GetBytes(got, c.want).Int(); n != 4096 { + t.Errorf("%s: sent %s", c.base, got) + } + if c.want == "max_tokens" && string(got) != string(body) { + t.Errorf("%s: body changed: %s", c.base, got) + } + if !strings.Contains(string(got), `what is \"max_tokens\"?`) { + t.Errorf("%s: message text changed: %s", c.base, got) + } + } + // another API's body is never touched + p := provider.Provider{ID: "x", Chat: "https://api.openai.com/v1"} + if got := s.chatTokenField(p, provider.Anthropic, body); string(got) != string(body) { + t.Errorf("anthropic body changed: %s", got) + } +} + +// A relay in front of OpenAI's newer models passes on its 400 for +// max_tokens: the request is asked once more with max_completion_tokens, +// and the next one goes with it at once. A vendor that takes max_tokens +// gets the body as it came, in one request. +func TestChatTokenFieldRetriedWhenNamed(t *testing.T) { + fresh(t) + ok := sse( + `data: {"id":"test","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ok"}}]}`, + `data: {"id":"test","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`, + ) + var bodies [][]byte + f := &fake{reply: ok, refuse: func(b []byte) (int, string) { + bodies = append(bodies, b) + if gjson.GetBytes(b, "max_tokens").Exists() { + return http.StatusBadRequest, openAIRefusal + } + return 0, "" + }} + up := httptest.NewServer(f) + defer up.Close() + var otherGot [][]byte + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + otherGot = append(otherGot, b) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, ok) + })) + defer other.Close() + for _, p := range []provider.Provider{ + {ID: "relay", Name: "Relay", Key: "k", Chat: up.URL + "/v1", Models: []string{"gpt-6.1-sol"}}, + {ID: "zhipu-like", Name: "Other", Key: "k", Chat: other.URL + "/v1", Models: []string{"glm-5"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + h := New().Handler() + ask := func(path, body string) { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%s: HTTP %d: %s", body, rec.Code, rec.Body.String()) + } + } + chat := `{"model":"relay/gpt-6.1-sol","stream":true,"max_tokens":4096,"messages":[{"role":"user","content":"hi"}]}` + ask("/v1/chat/completions", chat) + if len(bodies) != 2 { + t.Fatalf("relay asked %d times: %q", len(bodies), bodies) + } + last := bodies[1] + if gjson.GetBytes(last, "max_tokens").Exists() || gjson.GetBytes(last, "max_completion_tokens").Int() != 4096 { + t.Fatalf("retry sent %s", last) + } + // remembered: the next request, translated from Claude's API, goes + // with max_completion_tokens at once + ask("/v1/messages", `{"model":"relay/gpt-6.1-sol","stream":true,"max_tokens":300,"messages":[{"role":"user","content":"hi"}]}`) + if len(bodies) != 3 { + t.Fatalf("relay asked %d times: %q", len(bodies), bodies) + } + if gjson.GetBytes(bodies[2], "max_tokens").Exists() || !gjson.GetBytes(bodies[2], "max_completion_tokens").Exists() { + t.Fatalf("second request sent %s", bodies[2]) + } + // another vendor, which reads max_tokens, gets it as sent + ask("/v1/chat/completions", `{"model":"zhipu-like/glm-5","stream":true,"max_tokens":4096,"messages":[{"role":"user","content":"hi"}]}`) + if len(otherGot) != 1 { + t.Fatalf("other asked %d times", len(otherGot)) + } + var sent map[string]any + if err := json.Unmarshal(otherGot[0], &sent); err != nil { + t.Fatal(err) + } + if sent["max_tokens"] != float64(4096) || sent["max_completion_tokens"] != nil { + t.Fatalf("other got %s", otherGot[0]) + } +} diff --git a/internal/provider/test.go b/internal/provider/test.go index 94c3c5705..2d834bdd4 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -197,7 +197,10 @@ func (p Provider) mantleBase(base, model string) string { func tinyBody(q Provider, proto Protocol, model string) (url, body string) { switch proto { case Chat: - if q.IsBedrock() || q.IsAzure() { + if q.IsBedrock() || q.IsAzure() || OpenAIHost(HostOf(q.Base(Chat))) { + // OpenAI's own API, Azure's and Bedrock's turn max_tokens away + // on their reasoning models (GoxxKintBlade on X: every model + // of an OpenAI key red, "Use 'max_completion_tokens' instead") return q.mantleBase(q.Chat, model) + "/chat/completions", fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hi"}],"max_completion_tokens":16}`, model) } return q.Base(Chat) + "/chat/completions", fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hi"}],"max_tokens":16}`, model) @@ -557,7 +560,21 @@ func (p Provider) ownRequests(ctx context.Context, kind string) context.Context // it: the vendor's error, a stream's error after its 200 too. Do would // write the status alone, so a failed test's row said nothing of why // (ysm119 on Discord: "no answer", and no error to find anywhere). -func probe(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) (r Result) { +func probe(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) Result { + r := probeOnce(ctx, p, proto, url, body, model, wait) + if proto == Chat && r.Status == http.StatusBadRequest { + // a vendor whose 400 names the other reply-length field as the + // one to send (a relay in front of OpenAI's reasoning models, or + // one that reads max_tokens alone) is asked once more with it, as + // the gateway asks it (forward) + if b, ok := WithTokenField(body, TokenFieldWanted([]byte(r.Error))); ok { + return probeOnce(ctx, p, proto, url, b, model, wait) + } + } + return r +} + +func probeOnce(ctx context.Context, p Provider, proto Protocol, url string, body []byte, model string, wait time.Duration) (r Result) { r = Result{Protocol: proto, Model: model} if model == "" { r.Error = "no model to try: expose one, or refresh the model list" diff --git a/internal/provider/token_field.go b/internal/provider/token_field.go new file mode 100644 index 000000000..53c0944c3 --- /dev/null +++ b/internal/provider/token_field.go @@ -0,0 +1,93 @@ +package provider + +import ( + "bytes" + "encoding/json" + "regexp" + "strings" + + "github.com/tidwall/gjson" +) + +// Chat Completions has two names for a reply's length. OpenAI's own API +// reads max_completion_tokens and turns max_tokens away on its newer +// models ("Unsupported parameter: 'max_tokens' is not supported with this +// model. Use 'max_completion_tokens' instead.", GoxxKintBlade on X), while +// DeepSeek, Zhipu and most OpenAI-compatible relays read max_tokens alone. +const ( + MaxTokensField = "max_tokens" + CompletionTokField = "max_completion_tokens" +) + +// OpenAIHost is whether host is OpenAI's own API (api.openai.com), whose +// Chat Completions takes max_completion_tokens on every model; not Azure +// OpenAI (*.openai.azure.com) and not a relay. +func OpenAIHost(host string) bool { + host = strings.ToLower(host) + return host == "openai.com" || strings.HasSuffix(host, ".openai.com") +} + +// tokenFieldAsked matches a vendor's 400 that names the other field as +// the one to send: OpenAI's "Use 'max_completion_tokens' instead", and a +// vendor that says the reverse ("use max_tokens instead"). +var tokenFieldAsked = regexp.MustCompile("(?i)\\buse\\s+['\"`]?(max_completion_tokens|max_tokens)['\"`]?") + +// TokenFieldWanted is the field a Chat Completions refusal asks for in +// place of the one sent, or "": only when its words name it as the one to +// use, so a limit too high ("max_tokens must be at most 32768") is not +// read as the wrong name. +func TokenFieldWanted(msg []byte) string { + m := tokenFieldAsked.FindSubmatch(msg) + if m == nil { + return "" + } + return strings.ToLower(string(m[1])) +} + +// WithTokenField is body with its reply length named want (MaxTokensField +// or CompletionTokField), and whether it changed. The key is renamed in +// place, so the rest of the body keeps its bytes; a body that names both +// keeps want's value and drops the other. +func WithTokenField(body []byte, want string) ([]byte, bool) { + from := MaxTokensField + if want == MaxTokensField { + from = CompletionTokField + } else if want != CompletionTokField { + return body, false + } + if !bytes.Contains(body, []byte(`"`+from+`"`)) { + return body, false + } + v := gjson.GetBytes(body, from) + if !v.Exists() || v.Index <= 0 { + return body, false + } + if gjson.GetBytes(body, want).Exists() { + // both named: the one the vendor reads stays + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + var m map[string]any + if dec.Decode(&m) != nil { + return body, false + } + delete(m, from) + var out bytes.Buffer + enc := json.NewEncoder(&out) + enc.SetEscapeHTML(false) + if enc.Encode(m) != nil { + return body, false + } + return bytes.TrimSuffix(out.Bytes(), []byte("\n")), true + } + // the key is the last string before its value: only a colon and + // spaces lie between them + quoted := `"` + from + `"` + key := bytes.LastIndex(body[:v.Index], []byte(quoted)) + if key < 0 || strings.Trim(string(body[key+len(quoted):v.Index]), " \t\r\n:") != "" { + return body, false + } + out := make([]byte, 0, len(body)+len(want)-len(from)) + out = append(out, body[:key]...) + out = append(out, `"`+want+`"`...) + return append(out, body[key+len(quoted):]...), true +} diff --git a/internal/provider/token_field_test.go b/internal/provider/token_field_test.go new file mode 100644 index 000000000..cdcd6e109 --- /dev/null +++ b/internal/provider/token_field_test.go @@ -0,0 +1,122 @@ +package provider + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/tidwall/gjson" +) + +// openAIRefusal is OpenAI's own 400 for max_tokens on its newer models +// (GoxxKintBlade on X: "4 个模型中有 4 个没有响应;gpt-6.1-sol:400"). +const openAIRefusal = `{"error":{"message":"Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead.","type":"invalid_request_error","param":"max_tokens","code":"unsupported_parameter"}}` + +// A model's test on OpenAI's own Chat Completions names its reply length +// max_completion_tokens; DeepSeek's, Zhipu's and a relay's keep +// max_tokens, which they read. +func TestOpenAIProbeAsksMaxCompletionTokens(t *testing.T) { + for _, c := range []struct { + base, want string + }{ + {"https://api.openai.com/v1", "max_completion_tokens"}, + {"https://api.deepseek.com/v1", "max_tokens"}, + {"https://open.bigmodel.cn/api/paas/v4", "max_tokens"}, + {"https://relay.example/v1", "max_tokens"}, + {"https://notopenai.com/v1", "max_tokens"}, + } { + _, body := tinyBody(Provider{ID: "x", Chat: c.base}, Chat, "gpt-6.1-sol") + if gjson.Get(body, c.want).Int() != 16 { + t.Errorf("%s: %s", c.base, body) + } + other := "max_tokens" + if c.want == other { + other = "max_completion_tokens" + } + if gjson.Get(body, other).Exists() { + t.Errorf("%s: both named: %s", c.base, body) + } + } +} + +// A relay that passes on OpenAI's 400 for max_tokens has the test asked +// once more with max_completion_tokens, and the model is green; a refusal +// of the value is asked once. +func TestProbeRetriesTokenFieldNamed(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + var mu sync.Mutex + var got []string + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + got = append(got, string(b)) + mu.Unlock() + switch { + case gjson.GetBytes(b, "model").String() == "capped": + rw.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(rw, `{"error":{"message":"max_tokens must be at most 8"}}`) + case gjson.GetBytes(b, "max_tokens").Exists(): + rw.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(rw, openAIRefusal) + default: + _, _ = io.WriteString(rw, `{"choices":[{"message":{"content":"hi"}}]}`) + } + })) + defer srv.Close() + p := Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1", Key: "k", Models: []string{"gpt-6.1-sol", "capped"}} + rs := p.TestModels(context.Background(), []string{"gpt-6.1-sol"}) + if !rs[0].OK { + t.Fatalf("%+v", rs[0]) + } + if len(got) != 2 || gjson.Get(got[1], "max_completion_tokens").Int() != 16 || gjson.Get(got[1], "max_tokens").Exists() { + t.Fatalf("asked %q", got) + } + got = nil + rs = p.TestModels(context.Background(), []string{"capped"}) + if rs[0].OK || rs[0].Status != 400 || len(got) != 1 { + t.Fatalf("%+v, asked %q", rs[0], got) + } +} + +func TestTokenFieldWanted(t *testing.T) { + for msg, want := range map[string]string{ + openAIRefusal: "max_completion_tokens", + "Unsupported parameter: 'max_completion_tokens'. Please use `max_tokens` instead.": "max_tokens", + "Use max_tokens instead of max_completion_tokens": "max_tokens", + "max_tokens must be at most 8192": "", + "max_completion_tokens is too large: 200000": "", + "input length and `max_tokens` exceed context limit: 1 + 2 > 2": "", + } { + if got := TokenFieldWanted([]byte(msg)); got != want { + t.Errorf("%q: %q, want %q", msg, got, want) + } + } +} + +func TestWithTokenField(t *testing.T) { + in := `{"model":"m", "max_tokens" : 16,"messages":[{"role":"user","content":" max_tokens"}]}` + out, ok := WithTokenField([]byte(in), CompletionTokField) + if !ok || string(out) != strings.Replace(in, `"max_tokens" :`, `"max_completion_tokens" :`, 1) { + t.Fatalf("%v %s", ok, out) + } + back, ok := WithTokenField(out, MaxTokensField) + if !ok || string(back) != in { + t.Fatalf("%v %s", ok, back) + } + if _, ok := WithTokenField([]byte(`{"messages":[{"max_tokens":1}]}`), CompletionTokField); ok { + t.Fatal("a nested key renamed") + } + both, ok := WithTokenField([]byte(`{"max_tokens":7,"max_completion_tokens":5}`), CompletionTokField) + if !ok || gjson.GetBytes(both, "max_tokens").Exists() || gjson.GetBytes(both, "max_completion_tokens").Int() != 5 { + t.Fatalf("%v %s", ok, both) + } +}