Gemini response and error mapping
Treat completion as a contract
A response adapter translates provider-specific response details into application states. An empty string could mean a safety block, a tool request, a truncated answer, or a completed response with no useful text. Never infer the cause solely from missing text. The following adapter consumes already normalized outcomes from a fictional upstream mapper. These strings are application labels, not Google API status enums. In a real Interactions integration inspect interaction status, typed steps, error details and completion; in generateContent inspect prompt feedback, candidates and finish reasons. The fixture prints four distinct states. Unknown outcomes fail closed instead of being presented as success.
def app_state(outcome, text): # Application vocabulary, NOT Gemini status enum values. if outcome in {"blocked", "incomplete", "tool_requested", "retryable", "fatal"}: return outcome if outcome != "complete": return "unknown" return "ready" if isinstance(text, str) and text.strip() else "empty"
for outcome, text in [("blocked", ""), ("complete", ""), ("complete", "July"), ("incomplete", "Jul")]: print(app_state(outcome, text))Keep provider and application layers separate
Interactions supports typed steps and text output access; generateContent uses candidate contents and parts. When migrating, implement a new mapper and test it using version-specific recorded fixtures. A safety block requires a safe user-facing explanation, not automatic retry or a workaround. An incomplete result may be retried only within an explicit output/time/cost budget; do not silently persist partial data. For HTTP failures, distinguish transient transport, throttling or server errors from invalid requests and authentication/permission failures. Retry eligible failures with capped backoff and jitter, honor documented retry hints, and avoid multiplying SDK retries with app retries. A timeout does not prove the provider did nothing; do not replay side effects automatically. Record request IDs and aggregate usage without logging raw private prompts.
Validate structured output and evidence
The Interactions structured-output guide configures response_format with type text, MIME application/json and a supported JSON schema. The older generateContent mode has different configuration. Schema-conforming JSON may still contain wrong values. This example parses a completed local response, rejects duplicate keys, requires exactly month and units, rejects bool as an integer, and compares the extracted value with a trusted synthetic chart. The first result is 12; the wrong count and boolean return None. This is a narrow business validator, not a general JSON Schema engine or an image reader. If evidence is unavailable, route to review rather than inventing an expected value. Bound response size before parsing in real applications.
import json
def chart_value(text, month, expected): # Narrow local contract; expected is trusted synthetic evidence. def unique(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("duplicate key") result[key] = value return result try: data = json.loads(text, object_pairs_hook=unique) except (ValueError, TypeError): return None if not isinstance(data, dict) or set(data) != {"month", "units"}: return None if data["month"] != month or type(data["units"]) is not int: return None if data["units"] < 0 or data["units"] != expected: return None return data["units"]
print(chart_value('{"month":"July","units":12}', "July", 12))print(chart_value('{"month":"July","units":21}', "July", 12))print(chart_value('{"month":"July","units":true}', "July", 1))Function calls and streaming are separate workflows
Interactions accepts function declarations in tools; a function-call step proposes a name and arguments. Validate a complete call against a tool allowlist, argument schema, user authorization and remaining budget before executing anything. Return a result correlated to the original call using the exact documented API mode; preserve required context. Never treat model text as executable code. Streaming sends partial events; buffer until completion and parse only complete structured data. Display provisional text as provisional, discard failed/incomplete drafts and cap bytes, steps and elapsed time. The examples here do not execute or simulate a provider tool call, nor do they parse streaming events. Verify actual model support before combining structured output, modalities, streaming and tools.
Practice: a chart extraction gateway
Use the project fixtures to gate the request before dispatch, normalize the outcome, then validate the completed JSON. A blocked response must stay blocked even if its fixture contains plausible JSON; a ready response still needs evidence checking. Test missing keys, negative units, duplicate keys and a valid zero. Explain why schema conformance, authorization and factual accuracy are three different checks. Consult the current migration, function-calling and structured-output guides before any live implementation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Gemini response and error mapping quiz
Apply the Gemini integration contract.
A normalized blocked response contains nonempty text. What state does the example return?
Which result is accepted for July with trusted units 12?
What should happen when a function-call step arrives?
When should streamed JSON be parsed as a final record?
Does valid JSON prove the extracted value is correct?