AI: ChatSession.sendMessage / sendMessageStream throw TypeError on blocked prompts (empty candidates) when tools are set

Aperta Adatta ai principianti
#10,641 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@abhiramshaji-cyber ci sta già lavorando.

Dal 17/11/2026.

  • #10649 di @abhiramshaji-cyber — aperta

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

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

api: firebaseai
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.

https://github.com/firebase/firebase-js-sdk/blob/79b89f2939e584da90d3670dc576852fd1a6f4a7/packages/ai/src/requests/response-helpers.ts#L109-L115

Current behavior

  1. Start a chat with tools: [{ functionDeclarations: [...] }] (a functionReference isn't needed).
  2. Send a prompt that the Google AI backend blocks. It answers {"candidates":[],"promptFeedback":{"blockReason":"SAFETY"}}.
  3. sendMessage calls _getCallableFunctionCalls(result.response) before its own candidates.length > 0 check (L181), and sendMessageStream does the same with result.firstValue (L275).
  4. That reaches getFunctionCalls, which reads response.candidates?.[0].content. The ?. is on candidates, not on [0], so with an empty array [0] is undefined and .content throws.
  5. Both methods reject with TypeError: Cannot read properties of undefined (reading 'content').

https://github.com/firebase/firebase-js-sdk/blob/79b89f2939e584da90d3670dc576852fd1a6f4a7/packages/ai/src/requests/response-helpers.ts#L239

The same candidates?.[0].content pattern is also at L214 and L264.

getFunctionCalls and its callers
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:

https://github.com/firebase/firebase-js-sdk/blob/79b89f2939e584da90d3670dc576852fd1a6f4a7/packages/ai/src/methods/chat-session-base.ts#L190

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

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di firebase/firebase-js-sdk

Tutte le issue di firebase/firebase-js-sdk

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.