gateway: a reply limit filled in stays within the window; OpenRouter's "maximum context length" refusal is read (H1_B1_K1 on X)
Codex through an OpenRouter DeepSeek model (window 1048576, catalog output 943718) failed every long turn. Checked against the code, the report's four claims hold: the catalog gives that output; magpie translates the Responses turn to Chat Completions; Codex names no max_output_tokens and the translation fills in askedOutput (fillsOutput); and replyLeft, which asks again for what the window has left, read only DeepSeek/vLLM/Anthropic wording, not OpenRouter's "(N of text input, M of tool input, K in the output)". - replyLeft reads OpenRouter's message (every "N of <kind> input" is the prompt). - The filled-in limit (translated turns, and withOwnOutput for DeepSeek's own API) is lowered to window minus the prompt estimated from its size, when that leaves at least 8192; otherwise as before. Anthropic's fill is unchanged: its refusal wording was already read. Run (mote, at this head): gofmt clean; go vet darwin, linux nogui, windows for internal/gateway; go test ./internal/gateway ok. New tests TestReplyLeftOpenRouter and TestOpenRouterReplyFitsTheWindow use the report's literal message. Broken by hand: with the regex changed both fail (replyLeft 0, HTTP 400 with the report's text); with roomedOutput returning n unchanged the second test fails (asked [943718]). Not tried: a real OpenRouter account; the full suite (started after tag).
This commit is contained in:
@@ -8102,7 +8102,12 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
|
||||
// the model gives (fillsOutput), unless it turned the one filled
|
||||
// in away before
|
||||
if req.MaxTokens <= 0 && fillsOutput(p, to) && (to == provider.Anthropic || s.fits(p.ID, outputFillRefused(model), to)) {
|
||||
if n := askedOutput(p, model); n > 0 {
|
||||
n := askedOutput(p, model)
|
||||
if to != provider.Anthropic {
|
||||
// the window holds the prompt and the reply together
|
||||
n = roomedOutput(n, contextOf(p, model), estimate(req))
|
||||
}
|
||||
if n > 0 {
|
||||
r := *req
|
||||
r.MaxTokens, req = n, &r
|
||||
filledOutput = to != provider.Anthropic
|
||||
|
||||
@@ -139,6 +139,12 @@ func replyLeft(msg []byte) int {
|
||||
} else if m := inputPlusReply.FindSubmatch(msg); m != nil {
|
||||
prompt, _ = strconv.Atoi(string(m[1]))
|
||||
window, _ = strconv.Atoi(string(m[2]))
|
||||
} else if m := routerWindow.FindSubmatch(msg); m != nil {
|
||||
window, _ = strconv.Atoi(string(m[1]))
|
||||
for _, part := range routerInput.FindAllSubmatch(m[2], -1) {
|
||||
n, _ := strconv.Atoi(string(part[1]))
|
||||
prompt += n
|
||||
}
|
||||
}
|
||||
if window <= 0 || prompt <= 0 || prompt >= window {
|
||||
return 0
|
||||
@@ -152,11 +158,49 @@ func replyLeft(msg []byte) int {
|
||||
// tokens".
|
||||
var windowAndPrompt = lazyre.New(`(?is)maximum context length is (\d+) tokens.{0,200}?(?:\((\d+) in the messages, \d+ in the completion\)|your prompt contains at least (\d+) input tokens)`)
|
||||
|
||||
// routerWindow matches OpenRouter's refusal, which splits the prompt by
|
||||
// kind and counts the reply in the window: "This endpoint's maximum
|
||||
// context length is 1048576 tokens. However, you requested about 1050086
|
||||
// tokens (101187 of text input, 5181 of tool input, 943718 in the output)".
|
||||
// Group 2 is the parenthesis; routerInput reads each "N of <kind> input".
|
||||
var routerWindow = lazyre.New(`(?is)maximum context length is (\d+) tokens\..{0,100}?requested about \d+ tokens \(([^)]{0,200}?\d+ in the output)\)`)
|
||||
var routerInput = lazyre.New(`(?i)(\d+) of [a-z ]{1,20}? input`)
|
||||
|
||||
// inputPlusReply is Anthropic's words for the same, which an endpoint
|
||||
// speaking its API may answer with: "input length and `max_tokens` exceed
|
||||
// context limit: 197202 + 21333 > 200000".
|
||||
var inputPlusReply = lazyre.New(`(?i)input length and .{0,3}max_tokens.{0,3} exceed context limit:\s*(\d+)\s*\+\s*\d+\s*>\s*(\d+)`)
|
||||
|
||||
// roomedOutput is the reply limit n a request is filled in with, lowered
|
||||
// to what a window holds with a prompt of about promptTokens: the model's
|
||||
// own limit may be nearly the whole window (OpenRouter lists 943718 for a
|
||||
// DeepSeek model of 1048576), and a vendor that counts the reply in the
|
||||
// window refuses the pair (H1_B1_K1 on X). The prompt is sized from its
|
||||
// bytes, rounded up; room under leastReplyLeft leaves n as it was, and the
|
||||
// refusal tells the agent to compact. An unknown window leaves n alone.
|
||||
func roomedOutput(n, window, promptTokens int) int {
|
||||
if n <= 0 || window <= 0 {
|
||||
return n
|
||||
}
|
||||
room := window - promptTokens*5/4 - 1024
|
||||
if room >= leastReplyLeft && room < n {
|
||||
return room
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// contextOf is the context window of p's model, 0 when unknown.
|
||||
func contextOf(p provider.Provider, model string) int {
|
||||
cat := provider.Served()
|
||||
for i := range cat {
|
||||
e := &cat[i]
|
||||
if e.Group == "" && e.Provider.ID == p.ID && (e.Model == model || e.ID == model) {
|
||||
return e.Context
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// leastReplyLeft is the least room left for a reply that is worth asking
|
||||
// for: less, and the conversation needs compacting, which the refusal
|
||||
// tells the agent as it is (DeepSeek's own default reply is 8K).
|
||||
@@ -244,7 +288,7 @@ func withOwnOutput(p provider.Provider, model string, proto provider.Protocol, b
|
||||
if !shortByDefault(p) || namesOutput(proto, body) {
|
||||
return body
|
||||
}
|
||||
n := askedOutput(p, model)
|
||||
n := roomedOutput(askedOutput(p, model), contextOf(p, model), len(body)/4)
|
||||
if n <= 0 {
|
||||
return body
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// openrouterWindow is a fake of OpenRouter's chat API that counts the
|
||||
// reply asked for in the window with the prompt, and refuses in
|
||||
// OpenRouter's words (H1_B1_K1 on X) a request whose two pass it.
|
||||
type openrouterWindow struct {
|
||||
mu sync.Mutex
|
||||
window int
|
||||
text, tool int
|
||||
asked []int64
|
||||
}
|
||||
|
||||
func (o *openrouterWindow) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
n := int64(-1)
|
||||
if v := gjson.GetBytes(b, "max_tokens"); v.Exists() {
|
||||
n = v.Int()
|
||||
}
|
||||
o.mu.Lock()
|
||||
o.asked = append(o.asked, n)
|
||||
o.mu.Unlock()
|
||||
if n < 0 || o.text+o.tool+int(n) > o.window {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
fmt.Fprintf(w, `{"error":{"message":"This endpoint's maximum context length is %d tokens. However, you requested about %d tokens (%d of text input, %d of tool input, %d in the output). Please reduce the length of either one, or use the context-compression plugin to compress your prompt automatically.","code":400}}`,
|
||||
o.window, o.text+o.tool+int(n), o.text, o.tool, n)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, 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]`,
|
||||
))
|
||||
}
|
||||
|
||||
func (o *openrouterWindow) took() string {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
s := fmt.Sprint(o.asked)
|
||||
o.asked = nil
|
||||
return s
|
||||
}
|
||||
|
||||
const openRouterRefusal = "This endpoint's maximum context length is 1048576 tokens. However, you requested about 1050086 tokens (101187 of text input, 5181 of tool input, 943718 in the output). Please reduce the length of either one, or use the context-compression plugin to compress your prompt automatically."
|
||||
|
||||
func TestReplyLeftOpenRouter(t *testing.T) {
|
||||
// the report's literal message: 1048576 - (101187 + 5181)
|
||||
if got := replyLeft([]byte(openRouterRefusal)); got != 942208 {
|
||||
t.Errorf("replyLeft(report) = %d, want 942208", got)
|
||||
}
|
||||
// an image part is a prompt part too
|
||||
msg := "This endpoint's maximum context length is 200000 tokens. However, you requested about 210000 tokens (10000 of text input, 4000 of image input, 196000 in the output)."
|
||||
if got := replyLeft([]byte(msg)); got != 186000 {
|
||||
t.Errorf("replyLeft(image) = %d, want 186000", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Codex names no max_output_tokens, magpie translates its Responses turn
|
||||
// to OpenRouter's chat API and fills in the model's own limit, which the
|
||||
// catalog gives as 943718 of a 1048576 window; OpenRouter counts it with
|
||||
// the prompt and refused every turn, and magpie did not read its words to
|
||||
// ask again. The first ask now stays within the window, and a refusal that
|
||||
// still comes is read.
|
||||
func TestOpenRouterReplyFitsTheWindow(t *testing.T) {
|
||||
fresh(t)
|
||||
o := &openrouterWindow{window: 1048576, text: 101187, tool: 5181}
|
||||
up := httptest.NewServer(o)
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "orx", Name: "OR", Key: "k", Chat: up.URL + "/v1", Models: []string{"deepseek/deepseek-v4-pro"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := catalog.SaveLive("orx", up.URL+"/v1", []catalog.Model{{ID: "deepseek/deepseek-v4-pro", Context: 1048576, Output: 943718}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(catalog.Reset)
|
||||
body := `{"model":"orx/deepseek/deepseek-v4-pro","stream":true,"input":"hi"}`
|
||||
|
||||
// a small real prompt, which the fake counts as 106368: the first ask
|
||||
// is the model's own, refused, and asked again for what is left
|
||||
code, reply := post(t, "/v1/responses", body)
|
||||
if code != 200 {
|
||||
t.Fatalf("HTTP %d: %s", code, reply)
|
||||
}
|
||||
if got := o.took(); got != "[943718 942208]" {
|
||||
t.Fatalf("OpenRouter was asked max_tokens %s, want [943718 942208]", got)
|
||||
}
|
||||
|
||||
// a real prompt of ~100K tokens: the first ask already leaves it room
|
||||
o.text, o.tool = 1, 1
|
||||
big := strings.Repeat("word ", 80000) // ~100K tokens by bytes
|
||||
code, reply = post(t, "/v1/responses", `{"model":"orx/deepseek/deepseek-v4-pro","stream":true,"input":"`+big+`"}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("HTTP %d: %s", code, reply)
|
||||
}
|
||||
got := o.took()
|
||||
var n int
|
||||
if _, err := fmt.Sscanf(got, "[%d]", &n); err != nil || n >= 943718 || n < 8192 || n+len(big)/4 > 1048576 {
|
||||
t.Fatalf("OpenRouter was asked max_tokens %s, want one ask within the window", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user