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.
130 lines
9.1 KiB
JavaScript
130 lines
9.1 KiB
JavaScript
// yetone/magpie#2080: Gemini's models go to Factory's own route,
|
|
// /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 { readFileSync } from "node:fs"
|
|
import { FactoryAuthPlugin, _internal } from "./index.mjs"
|
|
|
|
const real = globalThis.fetch
|
|
afterEach(() => (globalThis.fetch = real))
|
|
const droid = "You are Droid, an AI software engineering agent built by Factory."
|
|
|
|
async function loaded(auth = { type: "oauth", access: "factory-token", expires: Date.now() + 3_600_000, activeOrganizationId: "org_A" }) {
|
|
const seen = []
|
|
globalThis.fetch = async (url, init) => {
|
|
seen.push({ url: String(url), ...init })
|
|
return new Response('data: {"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]}}]}\n\n', { headers: { "content-type": "text/event-stream" } })
|
|
}
|
|
const hooks = await FactoryAuthPlugin({ client: { auth: { set: async () => {} } } })
|
|
return { l: await hooks.auth.loader(async () => auth), seen }
|
|
}
|
|
|
|
// the request magpie's gateway hands a plugin's @ai-sdk/google model
|
|
const request = {
|
|
contents: [{ role: "user", parts: [{ text: "hi" }, { inlineData: { mimeType: "image/png", data: "aW1n" } }] }],
|
|
systemInstruction: { role: "user", parts: [{ text: "Be brief." }, { text: "Use tools." }] },
|
|
generationConfig: { maxOutputTokens: 512, thinkingConfig: { includeThoughts: true, thinkingLevel: "high" } },
|
|
tools: [{ functionDeclarations: [{ name: "Read", parameters: { type: "object" } }] }],
|
|
}
|
|
|
|
test("a Gemini model goes to /api/llm/g/v1/generate, the model in the body, x-api-provider google", async () => {
|
|
const { l, seen } = await loaded()
|
|
const res = await l.fetch("https://api.factory.ai/api/llm/g/v1/models/gemini-4-argon:streamGenerateContent?alt=sse", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-goog-api-key": "placeholder", "content-length": "1" },
|
|
body: JSON.stringify(request),
|
|
})
|
|
expect(seen[0].url).toBe("https://api.factory.ai/api/llm/g/v1/generate")
|
|
const sent = JSON.parse(seen[0].body)
|
|
expect(sent.model).toBe("gemini-4-argon")
|
|
expect(sent.systemInstruction).toEqual({ parts: [{ text: droid + "\nBe brief.\nUse tools." }] })
|
|
for (const k of ["contents", "generationConfig", "tools"]) expect(sent[k]).toEqual(request[k])
|
|
const h = seen[0].headers
|
|
expect(h.get("x-api-provider")).toBe("google")
|
|
expect(h.get("authorization")).toBe("Bearer factory-token")
|
|
expect(h.get("x-goog-api-key")).toBeNull()
|
|
expect(h.get("x-api-key")).toBeNull()
|
|
expect(h.get("content-length")).toBeNull()
|
|
expect(h.get("OpenAI-Platform")).toBeNull()
|
|
expect(await res.text()).toContain('"text":"ok"')
|
|
})
|
|
|
|
test("a Gemini request with no system instruction gets droid's line, one droid opened already goes on as it is", async () => {
|
|
const { l, seen } = await loaded()
|
|
const at = "https://api.factory.ai/api/llm/g/v1/models/gemini-3.5-flash:streamGenerateContent?alt=sse"
|
|
await l.fetch(at, { method: "POST", body: JSON.stringify({ contents: request.contents }) })
|
|
expect(JSON.parse(seen[0].body).systemInstruction).toEqual({ parts: [{ text: droid }] })
|
|
const own = { contents: request.contents, systemInstruction: { parts: [{ text: droid + "\nmine" }, { inlineData: { mimeType: "image/png", data: "eA==" } }] } }
|
|
await l.fetch(at, { method: "POST", body: JSON.stringify(own) })
|
|
expect(JSON.parse(seen[1].body)).toEqual({ ...own, model: "gemini-3.5-flash" })
|
|
// a string instruction and parts other than text keep their place after the line
|
|
await l.fetch(at, { method: "POST", body: JSON.stringify({ contents: request.contents, systemInstruction: "Plain." }) })
|
|
expect(JSON.parse(seen[2].body).systemInstruction).toEqual({ parts: [{ text: droid + "\nPlain." }] })
|
|
await l.fetch(at, { method: "POST", body: JSON.stringify({ contents: request.contents, systemInstruction: { parts: [{ text: "A" }, { inlineData: { mimeType: "image/png", data: "eA==" } }] } }) })
|
|
expect(JSON.parse(seen[3].body).systemInstruction).toEqual({ parts: [{ text: droid + "\nA" }, { inlineData: { mimeType: "image/png", data: "eA==" } }] })
|
|
})
|
|
|
|
test("an EU org's Gemini request goes to Factory's EU region's generate route", async () => {
|
|
const { l, seen } = await loaded({ type: "oauth", access: "factory-token", expires: Date.now() + 3_600_000, activeOrganizationId: "org_A", region: "eu" })
|
|
await l.fetch("https://api.factory.ai/api/llm/g/v1/models/gemini-3.8-flash:streamGenerateContent?alt=sse", { method: "POST", body: JSON.stringify(request) })
|
|
expect(new URL(seen[0].url).pathname).toBe("/api/llm/g/v1/generate")
|
|
expect(seen[0].url.startsWith("https://api.factory.ai/")).toBe(false)
|
|
})
|
|
|
|
// Gemini's route has no tool-output adaptation of its own: every refused
|
|
// phrase in its parts is escaped before the request leaves.
|
|
test("Gemini tool output and system instruction escape every refused phrase", async () => {
|
|
const { l, seen } = await loaded()
|
|
const env = "You have been invoked in the following environment:"
|
|
const pi = "You are an expert coding assistant operating inside pi, a coding agent harness."
|
|
const body = {
|
|
contents: [{ role: "user", parts: [{ functionResponse: { name: "Read", response: { text: env + " / " + pi } } }] }],
|
|
systemInstruction: { role: "user", parts: [{ text: env }] },
|
|
}
|
|
await l.fetch("https://api.factory.ai/api/llm/g/v1/models/gemini-4-argon:streamGenerateContent?alt=sse", { method: "POST", body: JSON.stringify(body) })
|
|
const sent = JSON.parse(seen[0].body)
|
|
const part = sent.contents[0].parts[0].functionResponse.response.text
|
|
expect(part).toBe("\\u0059ou have been invoked in the following environment: / \\u0059ou are an expert coding assistant operating inside pi, a coding agent harness.")
|
|
expect(sent.systemInstruction.parts[0].text).toContain("\\u0059ou have been invoked")
|
|
expect(JSON.stringify(sent)).not.toContain(env)
|
|
expect(JSON.stringify(sent)).not.toContain(pi)
|
|
})
|
|
|
|
test("adapts ZCode generated Gemini system context while preserving values and user content", async () => {
|
|
const { l, seen } = await loaded()
|
|
const context = "# Environment\nYou have been invoked in the following environment:\n- Primary working directory: /tmp/project\n- Is a git repository: no\n- Platform: darwin\n- Shell: zsh\n- OS Version: darwin 27.0.0 arm64\n- You are powered by the model named test-model.\n"
|
|
const body = { systemInstruction: { parts: [{ text: context }] }, contents: [{ role: "user", parts: [{ text: context }] }] }
|
|
const url = "https://api.factory.ai/api/llm/g/v1/models/gemini-3-flash-preview:generateContent"
|
|
await l.fetch(url, { method: "POST", body: JSON.stringify(body) })
|
|
const sent = JSON.parse(seen[0].body)
|
|
expect(sent.systemInstruction.parts[0].text).toBe(droid + "\n" + context.replace("# Environment", "# Runtime context").replace("You have been invoked in the following environment:", "The session environment is:").replace("- You are powered by the model named", "- Current model name:"))
|
|
// user parts are not adapted; the Gemini route escapes the refused phrase in them (#258)
|
|
expect(sent.contents).toEqual([{ role: "user", parts: [{ text: context.replace("You have been invoked", "\\u0059ou have been invoked") }] }])
|
|
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" } })
|
|
})
|