Gemini Empty Candidates Need a Typed Blocked-Response Path
Gemini GenerateContent can return no candidates when the prompt is blocked. Candidate validation must classify that response before any candidates[0] access, preserve prompt feedback, and distinguish a documented block from malformed JSON, transport failure, candidate filtering, and application rejection.

Gemini GenerateContentResponse can carry an empty candidates array as a documented outcome. Google's response contract says the API returns all requested candidates or none, and returns no candidates when something was wrong with the prompt. When Google sets the nested prompt block reason, the prompt was blocked and no candidates were returned. Any handler that reaches for candidates[0] before classifying the envelope has already lost the response semantics.
I want that absence represented as a typed application outcome. It should never arrive in production as a generic 500 or a fabricated empty candidate. Cannot read properties of undefined is equally unacceptable.
TL;DR
- Validate the response envelope and candidate count before any
candidates[0]access. - Treat zero candidates plus
promptFeedback.blockReasonas a typed prompt-block outcome. - Keep absent and malformed candidate states separate from empty and contradictory ones.
- Inspect
finishReasonandsafetyRatingsonly after a real candidate exists. - Assign retries and recovery to explicit application policy. Do the same for user messaging and retention.
Empty candidates are part of the response contract
Google's GenerateContent response reference defines candidates as an array and states that the API returns either all requested candidates or none. It directs clients to promptFeedback when no candidates are returned. The nested blockReason field is optional; when set, Google says the prompt was blocked and no candidates are returned.
This creates a required branch before candidate parsing. First validate that the provider body is a JSON object with the fields your integration accepts. Then determine whether candidates is present and is an array. A non-empty array can enter candidate validation. An empty array enters response-outcome classification. A missing field or non-array value enters a malformed-provider-response path.
Keep those states separate because [] and an omitted property carry different evidence from null and a string containing "blocked", although all four look equally unusable to an index operation. The AI audit log schema can hold the provider shape and parser version alongside the route policy and local disposition without inventing candidate content.
The validator needs an ordered decision tree
Gemini blocked response candidate validation should run in this order:
- Confirm the HTTP status and content type, then check the body size and JSON parsing outcome.
- Validate the response object and the type of
candidates. - If the array is empty, inspect
promptFeedback.blockReasonand its prompt safety ratings. - If the array contains entries, validate each candidate before selection or delivery.
- Record the provider evidence and the application's separate disposition.
For zero candidates with a recognized block reason, emit a typed value such as prompt_blocked. Keep the raw reason beside it. For zero candidates without a block reason, use a distinct outcome such as empty_candidates_unexplained and hold the response under route policy. A block reason paired with one or more candidates contradicts the documented contract and belongs in quarantine.
Collapsing optional candidate content to an empty string in production is negligent. It converts four operational states into one blank value, then invites downstream code to treat provider refusal as valid content.
The prompt feedback block reason guide covers reason-specific dispositions.
Candidate filtering starts after cardinality validation
A non-empty candidate array moves the operation into a different layer. Google's Candidate reference places finishReason and safetyRatings on each candidate. The finish reason explains why token generation stopped. Safety ratings report category-level provider evidence. Neither field belongs on a synthetic candidate created to simplify the parser.
Candidate filtering can produce unusable output even when an array entry exists. A safety stop or token limit needs its own route behavior. So does a malformed function call, unexpected tool call, or unknown terminal reason. The Gemini finish reason policy handles those candidate-level states after existence has been established.
Keep the layers explicit in data. Response classification records candidate_count: 0 or the observed count. Candidate validation records the selected index and content shape beside the finish reason and local acceptance decision. Prompt feedback remains response-level evidence. That division prevents a dashboard from reporting a prompt block as candidate zero with a safety finish reason that Google never returned.
On a review screen, show a gray outlined card reading 0 candidates beside an amber prompt blocked badge. Do not render a blank green candidate panel. The empty rectangle tells an on-call engineer exactly which branch executed.
Safety evidence cannot repair a missing candidate
Google's safety settings guide describes adjustable filter categories and probability-based thresholds. It also describes built-in protections for core harms. Those controls do not authorize the application to manufacture output when GenerateContentResponse contains no candidates.
For a prompt block, preserve the raw promptFeedback.blockReason and any prompt safety ratings allowed by the route's retention policy. For a returned candidate, preserve its own finish reason and category ratings. The Gemini safety ratings audit guide explains that candidate-level evidence in detail.
Avoid inferring SAFETY from absence alone. The current block-reason enum also includes blocklist, prohibited-content, image-safety, other, and an unspecified value. An unexplained empty array might also expose a provider change or SDK transformation, as well as a proxy defect or parser mismatch. Preserve the body or a protected digest and response ID. Keep the model version, requested model, and parser version with them. Let named evidence drive the classification.
Application code owns recovery and side effects
The application owns the typed result model. A useful result union includes accepted candidates and prompt blocked, candidate withheld and malformed provider response, plus incomplete transport and unknown provider state. Each member should declare which fields are present and which side effects are permitted. It should also declare which client error code is returned.
It also owns candidate selection, user-facing language, retry rules, human review, raw-content retention, and every tool or database action triggered after acceptance. A prompt block is a completed provider decision, so a blind retry repeats the same rejected request. If the user edits the prompt, create a new operation and retain the parent attempt ID. The safe idempotent LLM retries guide covers ambiguous transport outcomes, which require different handling.
Downstream consumers should receive no candidate object for a zero-candidate result. Make them match the typed outcome before accessing content. Tool execution and structured-output parsing should accept only an application-approved candidate type. The same restriction applies to persistence and user delivery, rather than a raw provider object.
Release fixtures must destroy the happy-path assumption
Put a controllable Gemini-compatible stub behind the deployed authenticated HTTP route. Start with a normal response containing one candidate and verify that validation reaches selection. Then return an empty candidates array with promptFeedback.blockReason: SAFETY. The handler should emit prompt_blocked and preserve the raw reason. It should skip candidate parsing and return the route's approved client message.
Next, remove candidates entirely or set it to null. Then replace it with an object or return an empty array without prompt feedback. Each fixture needs a distinct malformed or unexplained outcome. Add a contradictory body containing both a block reason and a candidate. Delivery and tool execution must remain stopped.
Finish with two non-empty candidate fixtures. Give one a natural STOP with valid content. Give the other a safety finish reason and no deliverable content. These prove the validator separates response cardinality from candidate acceptance.
Assert the audit row and client status for every case. Also assert the retry decision, delivered byte count, and downstream write count. A passing unit test around optional chaining proves almost nothing here. The destructive fixture must show that no candidate-dependent function ran when the count was zero.
DeepInspect
DeepInspect can inspect Gemini responses on authenticated user or agent HTTP traffic deliberately routed through its stateless proxy. It can enforce the zero-candidate branch before response delivery and bind the provider evidence to caller identity and route policy. It can also stop contradictory responses and write a per-decision audit record at the AI request boundary.
The application owns the typed result union, candidate selection, UI wording, prompt editing, retries, human review, content retention, and every local side effect after an approved response leaves the routed exchange. Direct Gemini calls and local processing that bypass the proxy remain outside DeepInspect's enforcement and evidence.
Book a technical deep dive at deepinspect.ai.
Frequently asked questions
- Can Gemini return HTTP 200 with no candidates?
Yes. The GenerateContent response schema documents a response-level path where no candidates are returned and directs the client to inspect
promptFeedback. Transport success only opens response validation. It says nothing about candidate availability or application acceptance.- Should an empty candidates array be treated as an error?
Treat it as a typed outcome first. Zero candidates plus a set block reason is a documented prompt-block result. Zero candidates without supporting prompt feedback is unexplained and should enter a fail-closed hold or malformed-response path according to the route policy.
- Is candidates[0] safe after checking promptFeedback?
Only after validating that
candidatesexists and is an array. It must also contain at least one entry, and every selected entry must match the expected candidate shape. Prompt feedback alone cannot establish candidate existence or content validity.- Should a blocked response be retried automatically?
A deterministic prompt block should not trigger a blind retry. Offer prompt editing where the product permits it and create a new operation for the revised request. Reserve automatic retry policy for explicitly classified transient or ambiguous transport outcomes.