// Gemini as the in-page agent's model: generateContent with function calling, called from the browser on the // person's Gemini API key (Google AI Studio). Gemini 4 Hydrogen is the model the Gemini Robotics plugin runs // its agent on. The model's turns go back exactly as they came, with their thought signatures, which Gemini 3 // and 4 check on every function call; pictures go back inside the function responses. import { GEMINI_API, GEMINI_MODEL } from "./perception.js"; export const GEMINI_AGENT_DEFAULT = GEMINI_MODEL; /** A failed response as something to tell the person. */ export async function geminiError(response) { let detail = ""; try { const body = await response.json(); const e = Array.isArray(body) ? body[0]?.error : body.error; detail = e?.message ?? JSON.stringify(body); } catch { detail = await response.text().catch(() => ""); } const hint = /api key/i.test(detail) ? " Check the Gemini API key under Perception." : response.status === 429 ? " (the key's quota or rate limit)" : ""; return `Gemini ${response.status}: ${String(detail).slice(0, 300)}${hint}`; } let pictures = 0; // names for the pictures sent back, unique in a conversation /** A function's result as the part that answers its call: the JSON, and the picture by reference. */ function answer(fc, result, image) { const response = { name: fc.name, ...(fc.id ? { id: fc.id } : {}), response: result }; if (image) { const [, mimeType = "image/jpeg", data = ""] = /^data:([^;,]+)?(?:;base64)?,(.*)$/s.exec(image) ?? []; const displayName = `picture_${++pictures}.${mimeType === "image/png" ? "png" : "jpg"}`; response.response = { ...result, image: { $ref: displayName } }; response.parts = [{ inlineData: { mimeType, data, displayName } }]; } return { functionResponse: response }; } /** * One user turn with Gemini: its function calls run through `call(name, args)`, their results go back, until * it answers without a call or `maxSteps` requests are used. `history` is the generateContent conversation * ({role, parts} contents) and grows in place; a turn cut short (stopped, or an error) is taken out again, * so that the next one starts from complete turns. */ export async function geminiTurn({ apiKey, model, thinking, system, specs, history, text, call, on, signal, maxSteps, fetchImpl = globalThis.fetch }) { const start = history.length; const declarations = specs.map((s) => ({ name: s.name, description: s.description, parametersJsonSchema: s.parameters })); history.push({ role: "user", parts: [{ text }] }); try { for (let step = 0; step < maxSteps; step++) { const response = await fetchImpl(`${GEMINI_API}/models/${encodeURIComponent(model)}:generateContent`, { method: "POST", headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey }, body: JSON.stringify({ systemInstruction: { parts: [{ text: system }] }, contents: history, tools: [{ functionDeclarations: declarations }], toolConfig: { functionCallingConfig: { mode: "AUTO" } }, generationConfig: { thinkingConfig: { thinkingLevel: thinking || "medium" } }, }), signal, }); if (!response.ok) throw new Error(await geminiError(response)); const body = await response.json(); const candidate = body.candidates?.[0]; const parts = candidate?.content?.parts; if (!parts?.length) throw new Error(`Gemini gave no answer (${candidate?.finishReason ?? body.promptFeedback?.blockReason ?? "empty"})`); history.push({ role: "model", parts }); // unchanged: the thought signatures ride along const said = parts.filter((p) => typeof p.text === "string" && !p.thought).map((p) => p.text).join("").trim(); if (said) on({ type: "assistant", text: said }); const calls = parts.filter((p) => p.functionCall).map((p) => p.functionCall); if (!calls.length) return; const answers = []; for (const fc of calls) { if (signal.aborted) throw new DOMException("stopped", "AbortError"); const args = fc.args ?? {}; on({ type: "tool", name: fc.name, args }); const result = await call(fc.name, args); const { image, ...rest } = result ?? {}; if (image) on({ type: "image", url: image }); on({ type: "result", name: fc.name, result: rest }); answers.push(answer(fc, rest, image)); } history.push({ role: "user", parts: answers }); } on({ type: "assistant", text: `(stopped after ${maxSteps} steps)` }); // the last calls' results went in; the model has not seen them: let it, next turn, with the user's words history.push({ role: "model", parts: [{ text: `(stopped after ${maxSteps} steps)` }] }); } catch (error) { history.length = start; throw error; } }