rohitg00/agentmemory · error · Error
Gemini embedding failed (${response.status}): ${err}
Error message
Gemini embedding failed (${response.status}): ${err} What it means
`embedBatch` in the Gemini provider throws when Google's embedding endpoint returns a non-ok HTTP status, including the status code and raw response body in the message. The key was present (constructor passed) but the API call itself failed — auth, quota, model, or request-shape problems.
Source
Thrown at src/providers/embedding/gemini.ts:43
const results: Float32Array[] = [];
for (let i = 0; i < texts.length; i += BATCH_LIMIT) {
const chunk = texts.slice(i, i + BATCH_LIMIT);
const response = await fetchWithTimeout(`${API_BASE}?key=${this.apiKey}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
requests: chunk.map((t) => ({
model: MODEL,
content: { parts: [{ text: t }] },
outputDimensionality: this.dimensions,
})),
}),
});
if (!response.ok) {
const err = await response.text();
throw new Error(`Gemini embedding failed (${response.status}): ${err}`);
}
const data = (await response.json()) as {
embeddings: Array<{ values: number[] }>;
};
for (const emb of data.embeddings) {
results.push(l2Normalize(new Float32Array(emb.values)));
}
}
return results;
}
}
let zeroNormWarned = false;
function l2Normalize(vec: Float32Array): Float32Array {View on GitHub (pinned to e04ba88819)
Solutions
- Inspect the response body embedded in the error — Google's message names the exact cause (API key invalid, quota exceeded, model not found).
- If 401/403: generate a new key at Google AI Studio and ensure the Generative Language API is enabled/not restricted for it.
- If 429: implement backoff-and-retry, lower request rate and batch size, or upgrade from the free tier.
- If 400: verify the model name is a valid embedding model and texts are non-empty and within token limits.
- If 5xx: retry with exponential backoff; check Google's status dashboard if it persists.
Example fix
// before
const vec = await provider.embed(text); // throws on 429 with body
// after
for (let attempt = 0; attempt < 3; attempt++) {
try { return await provider.embed(text); }
catch (e) {
if (!/\(429\)|\(5\d\d\)/.test(e.message) || attempt === 2) throw e;
await sleep(2 ** attempt * 500);
}
} Defensive patterns
Strategy: retry
Validate before calling
// Preflight the key against a cheap endpoint before embedding batches
const res = await fetch(`https://generativelanguage.googleapis.com/v1/models?key=${process.env.GEMINI_API_KEY}`);
if (!res.ok) throw new Error(`GEMINI_API_KEY preflight failed: ${res.status}`); Try / catch
async function embedWithRetry(text: string, tries = 3) {
for (let i = 0; i < tries; i++) {
try { return await provider.embed(text); }
catch (e) {
const m = e instanceof Error ? e.message : String(e);
const status = Number(/Gemini embedding failed \((\d+)\)/.exec(m)?.[1]);
if (status === 401 || status === 403 || (status >= 400 && status < 500 && status !== 429)) throw e;
await new Promise(r => setTimeout(r, 2 ** i * 500 + Math.random() * 250));
}
}
throw new Error("Gemini embed: retries exhausted");
} Prevention
- Restrict the API key correctly in Google Cloud (allow Generative Language API) and verify permissions before deploy.
- Throttle batch embedding to stay under Gemini free-tier/paid quota; cache embeddings to reduce calls.
- Pin a valid embedding model name and validate it with a single test embed at startup.
- Read the response body in the error message — Google states the exact rejection reason.
When it happens
Trigger: Any `embed()`/`embedBatch()` call where the Gemini embeddings endpoint responds 400 (malformed request, unsupported model like a non-embedding model name), 401/403 (bad/missing permissions on the key), 429 (quota/rate limit), or 5xx (Google-side outage).
Common situations: Key restricted by API restrictions in Google Cloud console (Generative Language API not allowed); free-tier per-minute quota exhausted under batch load; using `models/embedding-001` vs newer `gemini-embedding` naming mismatch; request disabled via API key restrictions or region not enabled.
Related errors
- Cohere embedding failed (${response.status}): ${err}
- POST ${url} failed: ${res.status} ${res.statusText}${suffix}
- ${init?.method || "GET"} ${path} -> ${res.status} ${res.stat
- MiniMax API error ${response.status}: ${text}
- OpenAI API error (${response.status}): ${text}
AI-assisted analysis of rohitg00/agentmemory@e04ba88819 (2026-08-30).
Data as JSON: /api/errors/ef70433c9a2acda4.
Report an issue: GitHub.