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

Open Beginner friendly
#10,641 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@abhiramshaji-cyber is already working on this.

Since Nov 17, 2026.

  • #10649 by @abhiramshaji-cyber — open

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
node.js, typescript

Research direction

Start with packages/ai/src/requests/response-helpers.ts and packages/ai/src/methods/chat-session-base.ts, then trace getFunctionCalls and the _getCallableFunctionCalls calls in sendMessage and sendMessageStream. Reproduce with the mocked blocked response from the issue, including the response with a candidate missing content. Done when both chat methods handle blocked responses without a TypeError and preserve the promptFeedback details.

Written by the indexing model from the issue text.

Description

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.

Dominant language
TypeScript
Stars
5.2k
Forks
1k
Avg merge
2d 2h
Merged PRs (30d)
77

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from firebase/firebase-js-sdk

All issues in firebase/firebase-js-sdk

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.