AI: ChatSession.sendMessage / sendMessageStream throw TypeError on blocked prompts (empty candidates) when tools are set
I maintainer di solito rispondono entro 1 giorno
Valutazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Idoneità per principianti
- 78/100
- Tipo di issue
- Bug
- Chiarezza
- Specificata chiaramente
- Stato di attività
- Attiva
- Stack tecnologico
- node.js, typescript
- Ambito
- backend-api-design
Direzione di ricerca
Inizia da packages/ai/src/requests/response-helpers.ts e packages/ai/src/methods/chat-session-base.ts, poi segui getFunctionCalls e le chiamate a _getCallableFunctionCalls in sendMessage e sendMessageStream. Riproduci il problema con la risposta bloccata simulata dell’issue, inclusa la risposta con un candidato privo di content. Il lavoro è completato quando entrambi i metodi di chat gestiscono le risposte bloccate senza TypeError e conservano i dettagli di promptFeedback.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Operating System
Any (reproduced on macOS 26.6)
Environment (if applicable)
Node.js v26.13.0, but nothing here is environment specific, so any Node or browser should hit it
Firebase SDK Version
13.3.0 (@firebase/ai 3.1.0)
Firebase SDK Product(s)
AI
Project Tooling
Plain Node script (TypeScript) with fetch mocked to return the backend response
Detailed Problem Description
Hi team, hope you're doing well!
When a chat has a functionDeclarations tool and the Google AI backend blocks the prompt, ChatSession.sendMessage and sendMessageStream reject with a raw TypeError instead of handling the blocked response the way they do without tools.
What the code is for
getFunctionCalls pulls the function calls out of the first candidate, and the chat session uses it (through _getCallableFunctionCalls) to decide whether to run automatic function calling. The SDK already knows the empty candidates case well. There's a nice guard in response-helpers.ts with a comment saying Google AI can return an empty candidates array when the prompt is blocked, and #10591 made sure promptFeedback is mapped for those responses. Thanks for both, they made this one easy to trace.
Current behavior
- Start a chat with
tools: [{ functionDeclarations: [...] }](afunctionReferenceisn't needed). - Send a prompt that the Google AI backend blocks. It answers
{"candidates":[],"promptFeedback":{"blockReason":"SAFETY"}}. sendMessagecalls_getCallableFunctionCalls(result.response)before its owncandidates.length > 0check (L181), andsendMessageStreamdoes the same withresult.firstValue(L275).- That reaches
getFunctionCalls, which readsresponse.candidates?.[0].content. The?.is oncandidates, not on[0], so with an empty array[0]isundefinedand.contentthrows. - Both methods reject with
TypeError: Cannot read properties of undefined (reading 'content').
The same candidates?.[0].content pattern is also at L214 and L264.

getFunctionCalls and its callers, Functions view in Architect
flowchart LR
A["Blocked prompt: candidates is empty"] --> B["sendMessage or sendMessageStream"]
B -->|no tools| C["candidates check, then SAFETY warning"]
B -->|functionDeclarations tool| D["getFunctionCalls runs first"]
D --> E["TypeError reading content"]
Expected behavior
The same as the no tools path: the chat resolves and logs sendMessage() was unsuccessful. Response was blocked due to SAFETY. Inspect response object for details. (and the matching sendMessageStream() warning), so the caller can read promptFeedback. For comparison, generateContent with the same response surfaces AIError: AI: Text not available. Response was blocked due to SAFETY (AI/response-error) from response.text().
A second, related case
The non streaming sendMessage also throws when a candidate comes back with no content, for example {"candidates":[{"finishReason":"SAFETY","index":0}]}. This one happens with or without tools, at candidates?.[0].content.parts here:
It rejects with TypeError: Cannot read properties of undefined (reading 'parts'). sendMessageStream handles that response fine.
A question on the fix
I'd love to hear which direction you'd prefer, if any. One option is guarding inside getFunctionCalls (and the two siblings) with candidates?.[0]?.content, which would also cover any other caller. Another is moving the _getCallableFunctionCalls call after the chat's own candidates check, so blocked responses go down the existing warning path. Or maybe there's a better place I'm missing? Happy to put up a PR for whichever you like, and any tips are very welcome.
Steps and code to reproduce issue
Run against firebase 13.3.0 with fetch mocked to return the blocked response:
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
const blocked = '{"candidates":[],"promptFeedback":{"blockReason":"SAFETY"}}';
globalThis.fetch = async (url: RequestInfo | URL) =>
new Response(
String(url).includes("stream") ? `data: ${blocked}\r\n\r\n` : blocked,
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
const app = initializeApp({
apiKey: "fake",
projectId: "demo",
appId: "1:1:web:1",
});
const ai = getAI(app, { backend: new GoogleAIBackend() });
const model = getGenerativeModel(ai, {
model: "gemini-2.5-flash",
tools: [
{ functionDeclarations: [{ name: "getWeather", description: "weather" }] },
],
});
await model.startChat().sendMessage("hi");
Output:
TypeError: Cannot read properties of undefined (reading 'content')
(await model.startChat().sendMessageStream('hi')).response rejects with the same error. Dropping tools makes both resolve and log the SAFETY warning instead. Swapping the body for {"candidates":[{"finishReason":"SAFETY","index":0}]} gives the second case, TypeError: Cannot read properties of undefined (reading 'parts') from sendMessage, with or without tools.
- Lingua principale
- TypeScript
- Stelle
- 5.2k
- Fork
- 1k
- Merge medio
- 2g 2h
- PR unite (30g)
- 77
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di firebase/firebase-js-sdk
-
api: firestore needs-attention question Repro Needed
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
firebase/firebase-js-sdk#10595 ·
I maintainer di solito rispondono entro 1 giorno
-
api: installations api: performance bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 85/100
firebase/firebase-js-sdk#10526 · 3 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
@firebase/firestore pins @grpc/grpc-js to ~1.9.0, holding consumers on a flagged releaseForse già presa @cherylEnkidu l’ha presa 50 giorni fa. Apertaapi: firestore needs-attention question stack:Angular
Difficoltà 2/5 1-3 ore Idoneità per principianti 65/100
firebase/firebase-js-sdk#10400 · 4 commenti · 9 reazioni · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
-
Some (sub) package.json do not list the licences which lead to tools like syft report unknown licenceForse già presa @phoekerson l’ha presa 84 giorni fa. Apertaquestion
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
firebase/firebase-js-sdk#9326 · 5 commenti ·
I maintainer di solito rispondono entro 1 giorno
-
AI: ONLY_ON_DEVICE falls back to the cloud when the LanguageModel API is missingForse già presa @hsubox76 l’ha presa 2 giorni fa. Apertaapi: firebaseai
Difficoltà 3/5 1-2 giorni Idoneità per principianti 35/100
firebase/firebase-js-sdk#10635 · 1 commento · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di firebase/firebase-js-sdk
Issue simili
-
bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
I maintainer di solito rispondono entro 2 giorni
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
inabagumi/shinju-date#7406 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
umami-software/umami#4787 ·
I maintainer di solito rispondono entro 3 giorni
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
I maintainer di solito rispondono entro 1 giorno