Back to Blog

Gemini API JSON Streaming: Fix Partial-Chunk Parse Errors

Tutorials and Guides9096
Gemini API JSON Streaming: Fix Partial-Chunk Parse Errors

Your non-streaming Gemini request produces a valid JSON object. You enable streaming to make the interface feel faster, pass each chunk into a JSON parser, and suddenly the same task starts failing. One chunk contains an opening brace. Another ends halfway through a quoted product name. A third looks like a complete object, but the connection has not finished.

The immediate fix is to separate transport events from the model's generated JSON. Collect the text deltas for one intended output, verify that the operation completed successfully, and parse the assembled document. Validate the resulting data before updating application state.

Google's structured-output documentation describes streaming chunks as partial JSON strings that can be concatenated into the final object. That does not mean each text fragment is independently parseable as your business object.

This article builds a small local experiment around that distinction. It is useful for developers integrating Gemini directly or through an AI API relay. The goal is reliable acceptance of one structured result, not a general Gemini introduction or a new schema-design tutorial. For the latter, start with the existing Gemini JSON extraction guide.

Experiment one: a valid document, three invalid fragments

Consider this synthetic response:

json
{"sku":"MUG-01","quantity":2}

The network and API implementation do not owe your application a chunk boundary after each complete JSON value. Your application could receive the generated text in pieces like these:

text
{"sku":
"MUG-01","quan
tity":2}

The fragments become meaningful together. Parsing the first fragment fails for an entirely ordinary reason: the value has not arrived. Asking Gemini to regenerate the response because that fragment is incomplete converts a normal streaming condition into an unnecessary retry.

There are also two different JSON layers to keep apart. A transport event may be a valid JSON object containing metadata and a text delta. The delta inside that event can still be only a fragment of the generated document. Successfully decoding the event envelope does not mean the business response is ready.

If you handle raw server-sent events, use an appropriate event parser. Network reads can split event boundaries, and event data has its own framing rules. The WHATWG server-sent events specification defines that transport. Do not split arbitrary socket reads and assume every piece is one complete event.

For most integrations, a supported SDK should handle that layer. Your application then works with decoded events or chunks, while retaining responsibility for selecting the correct generated text and deciding when it is safe to accept it.

The experiment needs a precise scope

The example below accepts one small JSON object containing a product identifier and a quantity. It is deliberately not a universal parser for every Gemini response type. It does not combine multiple candidates, mix tool arguments with ordinary text, or infer which of several output steps the application intended to use.

That scope matters because a gateway may expose a native Gemini interface or an OpenAI-compatible interface. Those are different event contracts. An adapter must first map the chosen route into the application's expected input. A model family name alone does not identify the event schema.

Google documents the Interactions API, while the Google Gen AI Python SDK documents its supported client behavior. Match the adapter to the interface and version you actually use. Do not copy an Interactions event selector into a Chat Completions stream and expect the field names to match.

For account and route discovery, the 4SAPI Gemini access-verification guide is the relevant starting point. The local collector below begins only after that route has been identified.

Build a collector that cannot confuse parsing with completion

Save this example as collect_json.py. Its input records are application-defined normalized events, not native Gemini API events. Your route adapter must emit delta, complete, or error according to the documented upstream outcome. Emit complete only for a successfully completed, intended output; a socket closing is not enough.

python
import json


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("Duplicate JSON key: " + key)
        result[key] = value
    return result


def reject_constant(value):
    raise ValueError("Non-JSON numeric constant: " + value)


def collect_order(events, limit_bytes=100_000):
    fragments = []
    size = 0
    completed = False
    for event in events:
        if completed:
            raise ValueError("Unexpected event after completion")
        kind = event.get("kind")
        if kind == "error":
            raise ValueError("Upstream operation failed")
        if kind == "complete":
            completed = True
        elif kind == "delta":
            text = event.get("text")
            if not isinstance(text, str):
                raise ValueError("Text delta must be a string")
            size += len(text.encode("utf-8"))
            if size > limit_bytes:
                raise ValueError("Response exceeds application limit")
            fragments.append(text)
        else:
            raise ValueError("Unknown normalized event")

    if not completed:
        raise ValueError("No successful completion was observed")
    data = json.loads(
        "".join(fragments),
        object_pairs_hook=unique_object,
        parse_constant=reject_constant,
    )
    if not isinstance(data, dict) or set(data) != {"sku", "quantity"}:
        raise ValueError("Unexpected response fields")
    if not isinstance(data["sku"], str) or not data["sku"].strip():
        raise ValueError("SKU must be a nonempty string")
    quantity = data["quantity"]
    if type(quantity) is not int or not 1 <= quantity <= 100:
        raise ValueError("Quantity must be an integer from 1 to 100")
    return data


if __name__ == "__main__":
    fragments = ['{"sku":', '"MUG-01","quan', 'tity":2}']
    events = [{"kind": "delta", "text": part} for part in fragments]
    events.append({"kind": "complete"})
    print(collect_order(events))

The one-hundred-unit rule and byte limit are example application policies. They are not Gemini service limits. Replace them with requirements appropriate to your product, and separately verify the service's model and response limits.

The collector rejects duplicate object keys and nonstandard numeric constants explicitly. Python's JSON documentation describes decoder behavior and customization hooks. Application validation should be deliberate rather than relying on whatever a default parser happens to tolerate.

Notice that the collector never tries to repair incomplete JSON by adding a closing brace. Such a repair could turn a truncated answer into a plausible but incomplete record. A failed generation should remain a failed generation until a new, separately tracked attempt succeeds.

Experiment two: parseable text without a successful operation

Now send the complete JSON text but omit the normalized completion record. The collector rejects it. That may initially seem strict: if the document parses, why not use it?

Because syntax and lifecycle answer different questions. Syntax tells you whether the text forms a document. Completion tells you whether the upstream operation reached the outcome your adapter recognizes as successful. A transport interruption can occur after some usable-looking content has arrived. Your application should not silently choose a different acceptance standard depending on where the connection broke.

For a preview interface, displaying tentative text can be reasonable. For a stock reservation, billing decision, or database mutation, use a separate committed state. Label the preview as provisional and replace it only after the final checks pass.

This also makes support easier. A record can show stream_started, preview_updated, operation_completed, and validated as distinct milestones. A customer who saw a preview but received no saved record then has an explainable outcome rather than an apparently random disappearance.

Do not count every preview as a successful API result in your analytics. Doing so inflates completion metrics and hides the exact failures this workflow is meant to expose.

Experiment three: a complete object with the wrong meaning

Change the quantity to true. Python treats booleans as a subclass of integers, so a loose integer check can accept the wrong value. The example uses an exact type check and rejects it. Change the quantity to a negative number and it is rejected for a different reason.

These tests demonstrate why a streaming fix cannot stop at “JSON parsing works.” A syntactically valid record may violate a business rule, omit a required identifier, or contain an unsupported value. The model's structured-output configuration and the application's validation serve related but separate purposes.

If the request itself fails because of nullable fields or optional properties, use the Gemini schema-migration guide. That is an input-contract problem. The collector in this article addresses the lifecycle of an output that arrives incrementally.

Keep those two troubleshooting paths separate in code and in error messages. “Schema rejected before generation” is more useful than “JSON failed.” So is “stream ended before successful completion.” Clear categories prevent developers from changing prompts when the real defect is a missing completion check.

Connect the collector to one documented route

An adapter has four responsibilities. It selects the intended candidate or text step, extracts only generated text deltas, observes the documented terminal outcome, and converts failures into an explicit error. Everything else should remain outside the collector.

For an Interactions integration, current Google examples show text deltas within streaming events. For another interface, the nesting and terminal signals can differ. Read the current Gemini text-generation guide alongside the SDK version installed in your project. Pin that version in your application and preserve a small recorded fixture when upgrading.

Do not concatenate reasoning text, tool arguments, and the final structured answer into one buffer. Do not merge two candidates. Do not append an entire repeated snapshot when the adapter expects a delta. Each of those mistakes can produce invalid JSON even when the model generated a correct result.

For a gateway migration, run the same synthetic task through the old and new route, then compare the normalized events and final accepted record. You are testing adapter correctness, not proving that the routes have identical model behavior. The Gemini API parameter-migration guide covers adjacent request-side changes.

The small test set that catches expensive mistakes

Before enabling streaming for users, keep fixtures for a complete response, an empty response, an interrupted stream, a declared upstream failure, a duplicate JSON key, an invalid quantity, an oversized document, and an event arriving after completion. Also split one document at every character boundary in a local test. Chunk boundaries should not change the accepted result.

These are deterministic parser tests. They do not require spending tokens on thousands of repeated model requests. After they pass, perform a limited integration test against the actual account-enabled route to confirm the adapter's interpretation of live events.

Observe time to first preview separately from time to validated result. Streaming may improve perceived responsiveness without reducing total generation time. Do not advertise a latency improvement based only on the first visible fragment, especially when the user cannot act until the final structured output is accepted.

When recording diagnostics, retain event categories, sizes, timing, and safe identifiers. Store raw customer content only when your application policy permits it. A useful trace usually does not require exposing API keys or complete source documents.

From a working fixture to a 4SAPI integration

To evaluate this workflow through 4SAPI, register an account, verify the available Gemini model and interface, and run one small structured-output request. Then repeat it with streaming enabled on the same confirmed route. Check both the event adapter and the final validated object before connecting a production database.

If the model identifier is an alias, preserve the route's reported metadata; the Gemini model-version audit guide explains that verification step. The existence of a model in a dashboard should not be treated as proof that every native streaming feature is passed through unchanged.

Your first useful milestone is modest and concrete: one supported model, one documented streaming contract, one completed output, and one accepted business record. Once that path works, reuse the collector and add route-specific fixtures as your integration grows. Users get a responsive preview, while your backend keeps a clear boundary between text that is arriving and data it is ready to trust.

Tags:Gemini APIJSONStreamingPython4SAPI

Recommended reading

Explore more frontier insights and industry know-how.