GoxxKintBlade on X (tweet 2116038360645206158, v0.1.2145) and Jothulmo (tweet 2116045916549652992): an OpenAI API key provider's test was red for every model, "gpt-6.1-sol: 400 Unsupported parameter: 'max_tokens' is not supported with this model. Use 'max_completion_tokens' instead." Cause: the model test's Chat body (provider.tinyBody) sent max_tokens to every host but Bedrock and Azure. The gateway had the same gap on a pass-through: a chat client's max_tokens (and magpie's own image describer and classifier, which ask the gateway in Chat with max_tokens) went to api.openai.com as sent. Only the Anthropic/Responses-to-Chat translator (buildChat) already used max_completion_tokens there. Fix, scoped by vendor: - provider.OpenAIHost: openai.com and *.openai.com only (not Azure, not "notopenai.com", not a relay). - The test's Chat body asks OpenAI's own API with max_completion_tokens. - The gateway's forwardOnce, the one place every upstream request passes, renames max_tokens to max_completion_tokens for OpenAI's own API (chatTokenField). DeepSeek (deepseekTokenField), Zhipu and relays get the body as the client sent it. - A Chat 400 whose words name the other field as the one to use (provider.TokenFieldWanted: "use 'max_completion_tokens'" or "use max_tokens"; a limit on the value is not one) is asked once more with that name, in the model test (probe) and in the gateway (forward, retryTokenField), and the gateway remembers it per provider in unfit. That covers a relay in front of OpenAI's reasoning models. The key is renamed in place (provider.WithTokenField), so the rest of the body keeps its bytes. Tests (new): TestOpenAIProbeAsksMaxCompletionTokens, TestProbeRetriesTokenFieldNamed, TestTokenFieldWanted, TestWithTokenField (internal/provider); TestOpenAIChatGetsMaxCompletionTokens, TestChatTokenFieldRetriedWhenNamed (internal/gateway). The last one also checks that a vendor reading max_tokens gets the body as sent, in one request; TestDeepSeekChatGetsMaxTokens still passes unchanged. Broken by hand: OpenAIHost taken out of tinyBody, probe's retry turned off, chatTokenField and retryTokenField returning early. All four new behavior tests went red with real FAILs (the probe test: "Status:400 ... Use 'max_completion_tokens' instead."; the gateway retry test: HTTP 400 from the relay), and green again with the change put back. Run on mote (mote-run): gofmt -l internal/ (nothing), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... (VET-OK), go test -timeout 45m -count=1 ./internal/provider ./internal/gateway at basedca3e2d71: internal/provider ok (340s); internal/gateway was still running at push time. Rebased ontoe8d42c02d(6 commits, which change both packages), then at this head on mote: gofmt -l (nothing), linux and windows go vet ./internal/... (VET-OK), and go test -count=1 -run "TokenField|OpenAIProbe|OpenAIChat|DeepSeekChatGetsMaxTokens| Bedrock|Azure|Mantle|TestModels|TestTest" on both packages: ok. Not tried: a real OpenAI key (no real network in tests; the fixture is OpenAI's own 400 text from the report). The full ./... suite runs on mote after the push.
94 lines
3.1 KiB
Go
94 lines
3.1 KiB
Go
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
|
|
}
|