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!