qoder 0.2.63: max_tokens never goes above the model's ceiling (#822)
Qoder CN's QoDuck (lmodel) refuses a max_tokens above 131072 with a 400 "Error in upstream response: Range of max_tokens should be [1, 131072]". qoderBody sent the client's budget unchanged (a DeepSeek-sized 384K from DeepSeek Harness / pi), and failure() read every "Error in upstream response" as the vendor's transient 502, so magpie retried on each account and rested them all with backoff; lmodel never answered. - qoderBody holds max_tokens to the model's ceiling and never raises a smaller one: what a refusal named for that model key, else the listing entry's max_output_tokens, else OUTPUT_CAPS (lmodel 131072). The context_length window is counted with the held value. - failure() reads "Range of max_tokens should be [lo, hi]" before the upstream-failed 502 as the request's 400 (signIn ""), with Qoder's words and the ceiling. - ask and askLingma send such a refusal again once at that ceiling and remember it for the model, so a model with no known ceiling (any other Qoder, Qoder CN or Lingma model) answers too. Refused again, the 400 goes back as Qoder said it. Siblings: one body builder (qoderBody) serves every site (qoder, qoder-cn, QwenWork, enterprise, VPC, dedicated, Lingma) and both stream=true/false; the plugin has no Responses path. The HTTP reply and the stream's envelope both go through failure(). Run (mote): packages/qoder bun test 417 pass; bun scripts/check.mjs qoder ok; repo HOME=$(mktemp -d) bun test 6662 pass 0 fail. Fixtures use the issue's literal error text. Broken by hand: without the clamp 19 of the new tests red; without the range read 11 red; without the resend 10 red. Not tried: a real qoder-cn account on lmodel (none here); whether Qoder also validates context_length (the issue could not capture the body); the learned ceiling is kept per model key in the process, not per site. Reported-by: Gruu6y
This commit is contained in:
@@ -192,6 +192,7 @@ itself.
|
||||
| Busy or queued for the model (code 10605) | Since 0.2.28 the request waits in Qoder's queue as Qoder's client does (below), then is sent again; since 0.2.62 a streamed request is answered 200 at once and kept alive with SSE comments for up to an hour, its outcome in the stream; past the wait, 503 with `Retry-After` from Qoder's `retryAfterSeconds` (30s when it gives none). Since 0.2.40, when magpie has another candidate after this request (`x-magpie-fallback: 1`), the 503 comes at once, saying the queue and how many are ahead, and magpie asks the next. The sign-in is untouched |
|
||||
| A refusal of the request itself (codes 406, 416, 430, 80411, 80412, 100400–100403) | 400, with Qoder's words |
|
||||
| "Error in upstream response", the model's own vendor behind Qoder failing, which Qoder sends as a 400 (since 0.2.24) | 502, so magpie asks again or another account; the sign-in is untouched |
|
||||
| "Range of max_tokens should be [1, N]" behind "Error in upstream response" (since 0.2.63) | Asked again once with max_tokens N, which later requests for that model are sent from the start; refused again, 400 with Qoder's words, the sign-in untouched. QoDuck (`lmodel`) is never sent more than 131072, and a model whose listing entry names `max_output_tokens` never more than that; a smaller max_tokens goes as asked |
|
||||
| A failure before the answer starts | Qoder's status |
|
||||
| A failure after the answer has started | The stream ends with an error |
|
||||
|
||||
|
||||
@@ -1501,7 +1501,9 @@ function qoderBody(chat, m, named = "", task, site) {
|
||||
const sys = { type: "text", text: sysText }
|
||||
const budget = chat.max_completion_tokens || chat.max_tokens || 0
|
||||
const [thinking, effort] = effortFor(chat.reasoning_effort, m, typeof budget === "number" ? budget : 0)
|
||||
const params = { enable_thinking: thinking, max_tokens: chat.max_completion_tokens || chat.max_tokens || 32000 }
|
||||
const asked = chat.max_completion_tokens || chat.max_tokens || 32000
|
||||
const cap = outputCap(m)
|
||||
const params = { enable_thinking: thinking, max_tokens: cap > 0 && asked > cap ? cap : asked }
|
||||
if (effort) params.reasoning_effort = effort
|
||||
const window = windowFor(chat, m, params.max_tokens)
|
||||
if (window > 0) params.context_length = window
|
||||
@@ -1530,6 +1532,42 @@ function qoderBody(chat, m, named = "", task, site) {
|
||||
return body
|
||||
}
|
||||
|
||||
// OUTPUT_CAPS are the largest max_tokens a model takes where its listing
|
||||
// entry names none: Qoder CN's QoDuck (lmodel) answers a larger one with a
|
||||
// 400 "Error in upstream response: Range of max_tokens should be [1,
|
||||
// 131072]", whatever the account (plugins#822, Gruu6y). A client asking
|
||||
// DeepSeek's 384K output was refused on every try, and each refusal rested
|
||||
// another account.
|
||||
const OUTPUT_CAPS = { lmodel: 131072 }
|
||||
// LEARNED_CAPS are the ceilings Qoder named in such a refusal, by model
|
||||
// key, for a model whose entry and OUTPUT_CAPS give none or a wrong one: the
|
||||
// refused request is asked again once at that ceiling, and later ones are
|
||||
// sent it from the start.
|
||||
const LEARNED_CAPS = new Map()
|
||||
// MAX_TOKENS_RANGE is that refusal's own words.
|
||||
const MAX_TOKENS_RANGE = /\brange of max_tokens should be \[\s*(\d+)\s*,\s*(\d+)\s*\]/i
|
||||
|
||||
// outputCap is the largest max_tokens model m takes, 0 when none is known:
|
||||
// what a refusal named, which is Qoder's own word, else its listing
|
||||
// entry's own (max_output_tokens), else OUTPUT_CAPS. A request's max_tokens is never sent above it, and one
|
||||
// asked lower is sent as asked.
|
||||
function outputCap(m) {
|
||||
const n = (v) => (Number.isInteger(v) && v > 0 ? v : 0)
|
||||
const raw = m?.config ?? {}
|
||||
return n(LEARNED_CAPS.get(m?.key)) || n(raw.max_output_tokens) || n(raw.maxOutputTokens) || n(OUTPUT_CAPS[m?.key])
|
||||
}
|
||||
|
||||
// reclamp is whether the request body was refused for a max_tokens above
|
||||
// model m's ceiling (failure's maxTokens), lowered to it if so: the
|
||||
// ceiling is remembered for the model, and the caller asks again once.
|
||||
function reclamp(f, body, m) {
|
||||
const cap = f?.maxTokens
|
||||
if (!(cap > 0) || !(body?.parameters?.max_tokens > cap)) return false
|
||||
if (m?.key) LEARNED_CAPS.set(m.key, cap)
|
||||
body.parameters.max_tokens = cap
|
||||
return true
|
||||
}
|
||||
|
||||
// failure is the status and message for a Qoder failure. Qoder's own code
|
||||
// says what it is, read as Qoder's client reads it (QoderErrorCode in the
|
||||
// app's qoder-agent-sdk worker): only 105 (loginExpired) is a lapsed
|
||||
@@ -1598,6 +1636,11 @@ function failure(status, text) {
|
||||
}
|
||||
if (QUOTA_CODES.has(code)) return { status: 429, message: "usage limit reached: " + msg, signIn: "" }
|
||||
if (REQUEST_CODES.has(code)) return { status: 400, message: `Qoder refused the request (${code}): ${msg}`, signIn: "" }
|
||||
// a max_tokens above the model's ceiling, said behind "Error in upstream
|
||||
// response": the request's fault on every account, so a 400 that rests
|
||||
// none, with the ceiling for ask to send again at (plugins#822)
|
||||
const range = MAX_TOKENS_RANGE.exec(msg)
|
||||
if (range) return { status: 400, message: `Qoder refused the request's max_tokens: ${msg}`, signIn: "", maxTokens: Number(range[2]) }
|
||||
if (UPSTREAM_FAILED.test(msg)) return { status: 502, message: msg, signIn: "" }
|
||||
// a refused chat is the built-in's 401, which never marked the account
|
||||
// lapsed: only a refused refresh did (errorResponse says kept). Qoder's
|
||||
@@ -3458,6 +3501,7 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
let m
|
||||
let relogged = false
|
||||
let renamed = false
|
||||
let reclamped = false
|
||||
const listed = (ms) => ms.find((x) => x.key === chat.model)
|
||||
try {
|
||||
m = listed(await models(cred)) ?? listed(await models(cred, true))
|
||||
@@ -3552,6 +3596,11 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
renamed = true
|
||||
continue
|
||||
}
|
||||
// a max_tokens above the model's ceiling: asked again once at it
|
||||
if (!reclamped && reclamp(f, body, m)) {
|
||||
reclamped = true
|
||||
continue
|
||||
}
|
||||
// an answered call moves its task on, as Qoder's client moves it
|
||||
if (!f) task.answered = true
|
||||
// with another account, provider or group member after this one
|
||||
@@ -3592,6 +3641,7 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
const task = taskOf(sessionOf(chat, named), chat)
|
||||
const tools = chat.tool_choice !== "none" ? (chat.tools ?? []).filter((t) => t?.type === "function") : []
|
||||
let relogged = false
|
||||
let reclamped = false
|
||||
for (let i = 0; ; ) {
|
||||
const m = order[i]
|
||||
const s = siteOf(site, cred)
|
||||
@@ -3630,6 +3680,10 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
}
|
||||
return errorResponse({ status: 401, message: `the sign-in lapsed — open Qoder CN IDE so it signs in again (${String(f.message).slice(0, 300)})` })
|
||||
}
|
||||
if (!reclamped && reclamp(f, body, m)) {
|
||||
reclamped = true
|
||||
continue
|
||||
}
|
||||
if (f && LINGMA_NOT_HERE.test(f.message) && i + 1 < order.length) {
|
||||
console.warn(`qoder-cn: ${s.dedicated} doesn't serve ${m.key}; asking ${order[i + 1].key}`)
|
||||
i++
|
||||
@@ -3945,4 +3999,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
|
||||
export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
|
||||
|
||||
// for tests
|
||||
export const _internal = { fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
|
||||
export const _internal = { OUTPUT_CAPS, LEARNED_CAPS, outputCap, fetchListing, accountIdentity, deviceRefreshBody, qwenworkClientHeaders, freeView, maskPhone, phoneLabelOf, realEmailOf, chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, dedicatedOrigin, dedicatedHost, dedicatedSite, lingmaRoots, lingmaDecode, lingmaSite, lingmaHeaders, LINGMA_MODELS, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
|
||||
|
||||
@@ -272,3 +272,23 @@ test("its models are the IDE's, and usage and check-in ask the domain nothing",
|
||||
expect((await hooks.auth.checkin(s.get)).outcome).toBe("inactive")
|
||||
expect(seen).toEqual([])
|
||||
})
|
||||
|
||||
// plugins#822: a max_tokens above the model's ceiling, which Qoder says
|
||||
// behind "Error in upstream response", is asked again once at that ceiling
|
||||
// on a Lingma domain too, before the next model is tried
|
||||
test("a Lingma domain's max_tokens range refusal is asked again at the ceiling it named", async () => {
|
||||
_internal.LEARNED_CAPS.clear()
|
||||
const RANGE = frame({ message: "Error in upstream response", details: JSON.stringify({ error: { message: "Range of max_tokens should be [1, 131072]" } }) }, 400)
|
||||
const maxOf = (s) => JSON.parse(_internal.decodeBody(s.body)).parameters.max_tokens
|
||||
route = (at, { body }) => {
|
||||
if (at !== HOST + CHAT) return new Response("", { status: 404 })
|
||||
return sse(JSON.parse(_internal.decodeBody(body)).parameters.max_tokens > 131072 ? RANGE : OK)
|
||||
}
|
||||
const s = store(signedIn())
|
||||
const opts = await (await QoderCNAuthPlugin({ client: s.client })).auth.loader(s.get)
|
||||
const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ ...ask, max_tokens: 384000 }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(chats().map(sentModel)).toEqual(["qmodel_latest", "qmodel_latest"])
|
||||
expect(chats().map(maxOf)).toEqual([384000, 131072])
|
||||
_internal.LEARNED_CAPS.clear()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// A request's max_tokens is never sent above the model's own ceiling: Qoder
|
||||
// CN's QoDuck (lmodel) answered a client's DeepSeek-sized budget with a 400
|
||||
// "Error in upstream response: Range of max_tokens should be [1, 131072]"
|
||||
// on every account, which reached magpie as a 502 and rested each account
|
||||
// in turn (plugins#822, Gruu6y). A value the client asked lower goes as
|
||||
// asked.
|
||||
import { afterEach, beforeEach, expect, test } from "bun:test"
|
||||
import { QoderAuthPlugin, QoderCNAuthPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const { qoderBody, modelInfo, failure, LEARNED_CAPS } = _internal
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
beforeEach(() => LEARNED_CAPS.clear())
|
||||
|
||||
// the issue's own words, as Qoder CN said them behind its 400
|
||||
const RANGE = "Range of max_tokens should be [1, 131072]"
|
||||
const UPSTREAM = "Error in upstream response"
|
||||
const REFUSED = JSON.stringify({ message: UPSTREAM, details: JSON.stringify({ error: { message: RANGE } }) })
|
||||
|
||||
const lmodel = modelInfo({ key: "lmodel", display_name: "QoDuck", enable: true, max_input_tokens: 1048576 })
|
||||
const dfmodel = modelInfo({ key: "dfmodel", display_name: "DeepSeek-Flash", enable: true, max_input_tokens: 1048576 })
|
||||
const sent = (m, extra) => qoderBody({ messages: [{ role: "user", content: "hi" }], ...extra }, m).parameters.max_tokens
|
||||
|
||||
test("lmodel's max_tokens is held to 131072, never raised", () => {
|
||||
expect(sent(lmodel, { max_tokens: 384000 })).toBe(131072)
|
||||
expect(sent(lmodel, { max_completion_tokens: 200000 })).toBe(131072)
|
||||
expect(sent(lmodel, { max_tokens: 131072 })).toBe(131072)
|
||||
expect(sent(lmodel, { max_tokens: 8000 })).toBe(8000)
|
||||
expect(sent(lmodel, {})).toBe(32000)
|
||||
})
|
||||
|
||||
test("a model with no known ceiling is sent what was asked; its entry's own ceiling is kept", () => {
|
||||
expect(sent(dfmodel, { max_tokens: 384000 })).toBe(384000)
|
||||
const named = modelInfo({ key: "xmodel", enable: true, max_output_tokens: 65536 })
|
||||
expect(sent(named, { max_tokens: 384000 })).toBe(65536)
|
||||
expect(sent(named, { max_tokens: 1000 })).toBe(1000)
|
||||
})
|
||||
|
||||
test("Qoder's range refusal is the request's 400 with the ceiling, and still readable", () => {
|
||||
for (const [how, text] of [
|
||||
["Qoder's JSON", REFUSED],
|
||||
["details as an object", JSON.stringify({ message: UPSTREAM, details: { error: { message: RANGE } } })],
|
||||
["plain text", `${UPSTREAM}: ${RANGE}`],
|
||||
]) {
|
||||
const f = failure(400, text)
|
||||
expect([how, f.status, f.signIn, f.maxTokens]).toEqual([how, 400, "", 131072])
|
||||
expect(f.message).toContain(`${UPSTREAM}: ${RANGE}`)
|
||||
}
|
||||
// the vendor's own failure stays a 502 for magpie to ask again
|
||||
expect(failure(400, JSON.stringify({ message: UPSTREAM }))).toEqual({ status: 502, message: UPSTREAM, signIn: "" })
|
||||
})
|
||||
|
||||
// a loader on site create whose chat refuses any max_tokens above cap as
|
||||
// Qoder CN did, in the HTTP reply or in the stream's envelope
|
||||
async function loader(create, cap, inStream = false, said = cap) {
|
||||
const asked = []
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
const u = new URL(String(url))
|
||||
if (u.pathname.endsWith("/model/list")) return Response.json({ chat: [{ key: "lmodel", display_name: "QoDuck", enable: true, max_input_tokens: 1048576 }, { key: "nmodel", display_name: "N", enable: true }] })
|
||||
if (u.pathname === "/api/v1/jobToken/refresh") return Response.json({ token: "jt", refresh_token: "rt", expires_in: 3_600_000 })
|
||||
if (!String(url).includes("agent_chat_generation")) throw new Error("unexpected " + url)
|
||||
const body = JSON.parse(_internal.decodeBody(init.body))
|
||||
asked.push(body.parameters.max_tokens)
|
||||
if (body.parameters.max_tokens > cap) {
|
||||
const text = REFUSED.replace("131072", String(said))
|
||||
if (inStream) return new Response(`data: ${JSON.stringify({ headers: {}, body: text, statusCodeValue: 400, statusCode: "BAD_REQUEST" })}\n\n`, { headers: { "Content-Type": "text/event-stream" } })
|
||||
return new Response(text, { status: 400 })
|
||||
}
|
||||
const chunk = { choices: [{ delta: { content: "OK" }, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1 } }
|
||||
return new Response(`data: ${JSON.stringify({ body: JSON.stringify(chunk) })}\n\ndata: ${JSON.stringify({ body: "[DONE]" })}\n\n`, { headers: { "Content-Type": "text/event-stream" } })
|
||||
}
|
||||
const auth = { type: "oauth", access: "jt", refresh: "rt", expires: Date.now() + 3_600_000, uid: "u1", machineId: "m1" }
|
||||
const hooks = await create({ client: { auth: { set: async () => {} } } })
|
||||
const l = await hooks.auth.loader(async () => auth)
|
||||
const ask = (model, max_tokens, stream = false) =>
|
||||
l.fetch("https://test.invalid/chat/completions", { method: "POST", body: JSON.stringify({ model, stream, max_tokens, messages: [{ role: "user", content: "hi" }] }) })
|
||||
return { ask, asked }
|
||||
}
|
||||
|
||||
for (const [site, create] of [["qoder-cn", QoderCNAuthPlugin], ["qoder", QoderAuthPlugin]]) {
|
||||
for (const inStream of [false, true]) {
|
||||
for (const stream of [false, true]) {
|
||||
const how = `${site}, refused ${inStream ? "in the stream" : "over HTTP"}, stream=${stream}`
|
||||
test(`${how}: lmodel is sent 131072 first and answered`, async () => {
|
||||
const { ask, asked } = await loader(create, 131072, inStream)
|
||||
const res = await ask("lmodel", 384000, stream)
|
||||
expect(res.status).toBe(200)
|
||||
expect(asked).toEqual([131072])
|
||||
})
|
||||
test(`${how}: a model whose ceiling Qoder names is asked again once at it, and sent it from then on`, async () => {
|
||||
const { ask, asked } = await loader(create, 65536, inStream)
|
||||
expect((await ask("nmodel", 200000, stream)).status).toBe(200)
|
||||
expect(asked).toEqual([200000, 65536])
|
||||
expect((await ask("nmodel", 200000, stream)).status).toBe(200)
|
||||
expect((await ask("nmodel", 4000, stream)).status).toBe(200)
|
||||
expect(asked).toEqual([200000, 65536, 65536, 4000])
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("a refusal that holds at the ceiling it named is said as Qoder said it, a 400 that rests no account", async () => {
|
||||
const { ask, asked } = await loader(QoderCNAuthPlugin, 1000, false, 65536)
|
||||
const res = await ask("nmodel", 200000)
|
||||
expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([400, null])
|
||||
expect((await res.json()).error.message).toContain(`${UPSTREAM}: Range of max_tokens should be [1, 65536]`)
|
||||
expect(asked).toEqual([200000, 65536])
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-qoder-auth",
|
||||
"version": "0.2.62",
|
||||
"version": "0.2.63",
|
||||
"description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
Reference in New Issue
Block a user