Gemini API returns undefined response causing "candidate.content.parts" error in production

I’m using Google’s Gemini 2.5 Computer Use API (google/gemini-2.5-computer-use-preview-10-2025) through the Stagehand browser automation library, and intermittently the API returns undefined instead of a valid response, crashing my application.

Error Message:

Raw response from Google: undefined
Error: undefined is not an object (evaluating ‘candidate.content.parts’)

Context:

  • Model: gemini-2.5-computer-use-preview-10-2025
  • Library: Stagehand (browser automation with AI)
  • Environment: Production (E2B sandbox)
  • Frequency: Happens randomly, ~5-10% of requests

What I Expected:

The API should always return a valid response object with candidate.content.parts, even if it’s empty or contains an error/refusal message.

What Actually Happens:

Sometimes the entire response is undefined, causing the code to crash when trying to access candidate.content.parts.

My Questions:

  1. Why does Gemini API return undefined? Is this rate limiting, safety filtering, or an API bug?
  2. What’s the proper way to handle this? Should I:
    • Add null checks before accessing candidate.content.parts?
    • Implement retry logic?
    • Check for specific API error codes?
  3. Is this documented behavior? I couldn’t find any mention of undefined responses in the Gemini API docs.

Code Context (simplified):

const result = await generateText({
model: gemini(‘gemini-2.5-computer-use-preview-10-2025’),
messages: messageHistory,
// … other config
});

// Sometimes result.response is undefined
// Crashes when code tries: candidate.content.parts

Any insights on why this happens and the recommended error handling pattern would be greatly appreciated!

Hi @Manas_Bam, apologies for the delayed response.

Preview models are prone to errors Gemini Compute Use - Note , meaning it is subject to lower available guarantees and higher error rates than stable models.

To handle this,

  1. Implementing null checks are always good.
  2. As you correctly identified, most common cause of an undefined response is the API returning a response object that has no content because it was blocked by a safety filter Gemini Safety Feedback When this happens, the API returns a finishReason of SAFETY and an empty content field. If your code tries to access response.candidates[0].content, it crashes. So, you must check Candidate.finishReason before trying to read the content.
  3. As transient errors are expected in preview models, a retry loop with exponential back off is recommended.

Thank you!