factory: a Gemini request opens with its model, as droid's does (0.1.49)
marovole on X, on 0.1.48 (magpie v0.1.4504, Droid BYOK, Factory API key
sign-in): three gemini-4-hydrogen requests came back 400 "Invalid model
ID in request body", each again on 2 or 3 retries, while the same setup
went through 83 times on hydrogen and 28 each on carbon and sonnet that
day. The failing bodies were 0.6 to 1.6 MB, long Droid sessions. 0.1.48's
per-conversation x-session-id did not change it.
What differs from droid, and grows with the body, is where the model
sits. droid 1.14.0 builds its Gemini request as {model, contents,
systemInstruction, tools, generationConfig} (testdata/droid-1.14.0-
gemini-body.txt, from the release binary). magpie's gateway marshals a
Gemini body from a Go map, so its keys come sorted: contents,
generationConfig, model, ... The plugin's geminiBody set m.model on that
object, which keeps the key where it was, after the contents; a body
from the AI SDK's Google package has no model, so it went last. Either
way the model came after the whole conversation. A route that
reads the model from the first part of a body would find droid's at
once and miss ours past some size, every retry alike, which is the
reported pattern.
geminiBody now writes the fields in droid's order (GEMINI_ORDER), the
model first, and any other field (toolConfig, safetySettings) after them
in its own order. Only the Gemini route changes; droid's Chat body puts
messages before model, so the other routes keep theirs.
Not proven: there is no Factory account here, so the 400 was not
reproduced against Factory, and Factory's server code is not readable.
The cause is the one byte-layout difference from droid that matches
"Gemini only, large only, every retry". The reporter is asked for the
raw lines to confirm.
Run (HOME a fresh folder; the focused runs on mote, the suite on the
Linux box, magpie-desktop, as mote and mica each had a full Go suite
running):
- bun test packages/factory/gemini.test.mjs size.test.mjs
session.test.mjs request.test.mjs: 86 pass, 0 fail.
- The new test on the old index.mjs: red (the body did not open with
{"model":"gemini-4-hydrogen","contents":), the other 5 Gemini tests
green.
- The root bun test (Bun 1.4.2): 9060 pass, 19 skip, 0 fail (9079
tests, 636 files); scripts/check.mjs ok.
This commit is contained in:
@@ -2,7 +2,8 @@
|
||||
// /api/llm/g/v1/generate, as magpie's built-in sends them (buildGemini,
|
||||
// factoryDroidGoogle in internal/provider/factory_client.go).
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { FactoryAuthPlugin } from "./index.mjs"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { FactoryAuthPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
@@ -102,3 +103,27 @@ test("adapts ZCode generated Gemini system context while preserving values and u
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify(sent) })
|
||||
expect(JSON.parse(seen[1].body)).toEqual(sent)
|
||||
})
|
||||
|
||||
// marovole on X: gemini-4-hydrogen requests of 0.6 to 1.6 MB came back 400
|
||||
// "Invalid model ID in request body", every retry alike. magpie's gateway
|
||||
// sends a Gemini body's fields sorted, so the model came after the
|
||||
// contents, a long session's megabytes; droid sends it first.
|
||||
test("a large Gemini request opens with the model, its fields in droid's order", async () => {
|
||||
const droidBody = readFileSync(new URL("./testdata/droid-1.14.0-gemini-body.txt", import.meta.url), "utf8")
|
||||
const droidOrder = [...droidBody.match(/ar=\{(.*)\}/)[1].matchAll(/(?:^|,)(\w+):/g)].map((m) => m[1])
|
||||
.filter((k) => k !== "parts" && k !== "text" && k !== "functionDeclarations")
|
||||
expect(droidOrder).toEqual(_internal.GEMINI_ORDER)
|
||||
|
||||
const { l, seen } = await loaded()
|
||||
const big = "x".repeat(1_600_000)
|
||||
// as buildGemini in magpie's gateway marshals it: Go sorts a map's keys
|
||||
const sorted = `{"contents":[{"role":"user","parts":[{"text":"${big}"}]}],"generationConfig":{"maxOutputTokens":512},"model":"gemini-4-hydrogen","systemInstruction":{"parts":[{"text":"Be brief."}]},"toolConfig":{"functionCallingConfig":{"mode":"AUTO"}},"tools":[{"functionDeclarations":[{"name":"Read"}]}]}`
|
||||
await l.fetch("https://api.factory.ai/api/llm/g/v1/models/gemini-4-hydrogen:streamGenerateContent?alt=sse", { method: "POST", body: sorted })
|
||||
// the AI SDK's Google package names no model in the body at all
|
||||
await l.fetch("https://api.factory.ai/api/llm/g/v1/models/gemini-4-hydrogen:streamGenerateContent?alt=sse", { method: "POST", body: JSON.stringify({ ...request, contents: [{ role: "user", parts: [{ text: big }] }] }) })
|
||||
for (const s of seen) {
|
||||
expect(s.body.startsWith('{"model":"gemini-4-hydrogen","contents":')).toBe(true)
|
||||
expect(Object.keys(JSON.parse(s.body))).toEqual([..._internal.GEMINI_ORDER, ...(s === seen[0] ? ["toolConfig"] : [])])
|
||||
}
|
||||
expect(JSON.parse(seen[0].body).toolConfig).toEqual({ functionCallingConfig: { mode: "AUTO" } })
|
||||
})
|
||||
|
||||
@@ -716,6 +716,17 @@ const GEMINI_CALL = /\/models\/([^/:]+):(?:stream)?generateContent$/i
|
||||
// instruction without a role and opening with droid's line, as one text part
|
||||
// of droid's line and the instruction's text parts joined with "\n", then
|
||||
// its other parts. A body that can't be read goes on as it is.
|
||||
//
|
||||
// Its fields go in droid's order (GEMINI_ORDER), the model first. magpie's
|
||||
// gateway sends them sorted (contents, generationConfig, model, ...) and
|
||||
// the AI SDK has no model at all, so the model came after the contents,
|
||||
// most of a long session's bytes. Factory answered such a request of
|
||||
// 0.6 to 1.6 MB with 400 "Invalid model ID in request body", every retry
|
||||
// alike, while the same conversation's smaller requests went through and
|
||||
// no other route failed (marovole on X, gemini-4-hydrogen, 0.1.48). The
|
||||
// model's place is the one difference from droid that grows with the body:
|
||||
// droid always sends it first (testdata/droid-1.14.0-gemini-body.txt).
|
||||
const GEMINI_ORDER = ["model", "contents", "systemInstruction", "tools", "generationConfig"]
|
||||
function geminiBody(model, body) {
|
||||
const text = bodyText(body)
|
||||
if (text == null) return body
|
||||
@@ -749,7 +760,10 @@ function geminiBody(model, body) {
|
||||
// Gemini's route has no tool-output adaptation: escape every refused
|
||||
// phrase in its parts (functionResponse, systemInstruction) here.
|
||||
escapeDeep(m, REFUSED_PHRASES)
|
||||
return JSON.stringify(m)
|
||||
const ordered = {}
|
||||
for (const k of GEMINI_ORDER) if (m[k] !== undefined) ordered[k] = m[k]
|
||||
for (const [k, v] of Object.entries(m)) if (!(k in ordered)) ordered[k] = v
|
||||
return JSON.stringify(ordered)
|
||||
}
|
||||
|
||||
// ---- request size -------------------------------------------------------------
|
||||
@@ -2271,4 +2285,4 @@ export const FactoryAuthPlugin = async ({ client, magpie }) => {
|
||||
}
|
||||
|
||||
// for tests
|
||||
export const _internal = { CONVERSATION, sessionId, STANDARD_ONLY, contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels }
|
||||
export const _internal = { CONVERSATION, sessionId, STANDARD_ONLY, contentRefused, explain, fastBody, FAST_BETA, limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, GEMINI_ORDER, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT, MODELS, PROMOTIONS, rateOf, configModels, providerModel, providerModels }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-factory-auth",
|
||||
"version": "0.1.48",
|
||||
"version": "0.1.49",
|
||||
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// The Gemini request droid builds for Factory's /api/llm/g/v1/generate, from
|
||||
// https://downloads.factory.ai/factory-cli/releases/1.14.0/darwin/arm64/droid
|
||||
// SHA-256 e3e173bb091f139c30df6df7664b67aa7fb16bca95b9d737c71b3fdcf98bf33b
|
||||
kr=s4(Kt,Fn.generationConfig),hr=!ia(Kt),ar={model:Kt,contents:Hn,systemInstruction:Sn?{parts:[{text:Sn}]}:void 0,tools:hr&&un.length>0?[{functionDeclarations:un}]:void 0,generationConfig:kr}
|
||||
Reference in New Issue
Block a user