Skip to content
AI Engineering #structured-outputs#pydantic#vllm#streaming#python#jiter

Streaming Structured JSON Outputs with Pydantic and vLLM

S

S L Manikanta

Nov 28, 2026 • 6 min read

bolt Key Takeaways

  • Calling Pydantic model_validate_json() on incremental SSE chunks raises ValidationError because streamed JSON strings are syntactically incomplete until the final token.
  • Use jiter.from_json(..., partial_mode='trailing-strings') to parse incomplete JSON buffers in Rust-speed microseconds, then hydrate partial UI models with model_construct().
  • Always run strict model_validate_json() once finish_reason == 'stop' to enforce full schema constraints, enums, and custom field validators.
  • Reject or retry streams ending with finish_reason == 'length' before validation, since truncated JSON can never satisfy required closing fields.
✉ Newsletter

Want to build production-ready AI?

Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.

Quick Solution: Incremental JSON Parsing with jiter + pydantic

Calling Model.model_validate_json(buffer) during an LLM SSE stream throws pydantic_core.ValidationError: EOF while parsing a string on every chunk until the final closing brace arrives. To stream typed fields incrementally in real time, parse the growing buffer with jiter.from_json(..., partial_mode="trailing-strings") (jiter==0.8.2, pydantic==2.10.6, openai==1.61.0), then run strict model_validate_json() once finish_reason == "stop".

import jiter
from pydantic import BaseModel, Field


class AnalysisChunk(BaseModel):
    summary: str = ""
    confidence: float = Field(default=0.0, ge=0.0, le=1.0)
    risks: list[str] = Field(default_factory=list)


def parse_partial_model(raw_buffer: str) -> AnalysisChunk | None:
    """Parse incomplete streamed JSON into a partial Pydantic model."""
    if not raw_buffer.strip():
        return None
    parsed = jiter.from_json(
        raw_buffer.encode("utf-8"),
        partial_mode="trailing-strings",
    )
    if not isinstance(parsed, dict):
        return None
    # model_construct skips strict validation on missing required fields mid-stream
    return AnalysisChunk.model_construct(**parsed)
flowchart LR
    Stream["vLLM / OpenAI SSE Chunks"] -->|"Append Token"| Buf["UTF-8 JSON Buffer"]
    Buf -->|"Each Token"| Jiter["jiter.from_json(partial_mode='trailing-strings')"]
    Jiter -->|"Valid Partial Dict"| UI["Progressive UI / Agent Preview"]
    Stream -->|"finish_reason == 'stop'"| Strict["Model.model_validate_json(buffer)"]
    Stream -->|"finish_reason == 'length'"| Err["TruncatedOutputError (Retry / Increase max_tokens)"]

Why Naive Streaming Breaks Structured Outputs

Constrained decoding guarantees that every token emitted by the model is a valid prefix of your JSON Schema, but a valid prefix is still syntactically incomplete until the final token.

Engines like vLLM (via Outlines / xgrammar) and SGLang (via Jump-Forward Decoding) enforce grammar constraints at logits sampling time. Even with grammar enforcement enabled, two runtime failures hit production streaming pipelines:

  1. Premature Validation Crashes: Developers pass accumulated delta strings into json.loads() or model_validate_json() inside async for chunk in stream:, crashing on chunk #1.
  2. Silent Truncation on max_tokens: If max_tokens is too small for the schema, the engine stops mid-array (finish_reason="length"). Without an explicit finish_reason guard, the application either hangs or logs an opaque ValidationError instead of surfacing a token-budget error.

To compare how vLLM and SGLang enforce grammar constraints under the hood, read our SGLang Jump-Forward Decoding vs vLLM Outlines guide and PydanticAI vs Instructor structured outputs benchmark.


Partial JSON Streaming Approaches Compared

ApproachParse Latency (per 1KB chunk)Handles Incomplete StringsEnforces Final ValidatorsExternal Dependencies
json.loads() in try/exceptFails until EOFNoManualStdlib
jiter (partial_mode="trailing-strings")~12 microseconds (Rust)YesYes (at finish_reason="stop")jiter>=0.8.0 (already a pydantic dependency)
OpenAI beta.chat.completions.stream~20-40 microsecondsYesYesopenai>=1.50 (SDK-coupled)
Custom regex / brace-closing hack~50+ microsecondsFragile on escaped quotesManualNone (high bug risk)

Because jiter is already installed as a core dependency of pydantic-core, using jiter.from_json() adds zero extra bloat to your container image.


Complete Production Streaming Client for vLLM & OpenAI

The following runnable script (openai==1.61.0, pydantic==2.10.6, jiter==0.8.2, Python 3.11+) connects to any OpenAI-compatible server (local vLLM 0.8+ or OpenAI API), enforces json_schema decoding, streams partial TradeSignal updates safely, and validates the final object only on a clean stop.

import asyncio
import os
from typing import AsyncGenerator, Literal
import jiter
from openai import AsyncOpenAI, APIConnectionError, RateLimitError
from pydantic import BaseModel, Field, ValidationError


class TradeSignal(BaseModel):
    ticker: str = Field(..., min_length=1, max_length=10)
    action: Literal["BUY", "HOLD", "SELL"]
    conviction: float = Field(..., ge=0.0, le=1.0)
    rationale: str = Field(..., min_length=10)
    key_catalysts: list[str] = Field(default_factory=list)


class TruncatedStreamError(RuntimeError):
    """Raised when the model hits max_tokens before closing the JSON object."""


async def stream_structured_output(
    client: AsyncOpenAI,
    model: str,
    prompt: str,
    max_tokens: int = 512,
) -> AsyncGenerator[tuple[bool, TradeSignal], None]:
    """Yield (is_final, TradeSignal) tuples as tokens arrive."""
    schema = TradeSignal.model_json_schema()
    buffer_parts: list[str] = []
    finish_reason: str | None = None

    try:
        stream = await client.chat.completions.create(
            model=model,
            messages=[
                {"role": "system", "content": "Respond strictly using the provided JSON schema."},
                {"role": "user", "content": prompt},
            ],
            response_format={
                "type": "json_schema",
                "json_schema": {
                    "name": "trade_signal",
                    "strict": True,
                    "schema": schema,
                },
            },
            max_tokens=max_tokens,
            temperature=0.0,
            stream=True,
        )

        async for chunk in stream:
            if not chunk.choices:
                continue
            choice = chunk.choices[0]
            if choice.finish_reason is not None:
                finish_reason = choice.finish_reason

            delta = choice.delta.content
            if not delta:
                continue

            buffer_parts.append(delta)
            raw_so_far = "".join(buffer_parts)

            try:
                partial_dict = jiter.from_json(
                    raw_so_far.encode("utf-8"),
                    partial_mode="trailing-strings",
                )
                if isinstance(partial_dict, dict):
                    yield False, TradeSignal.model_construct(**partial_dict)
            except ValueError:
                # Leading whitespace or pre-brace token; wait for next chunk
                continue

    except (APIConnectionError, RateLimitError) as exc:
        raise RuntimeError(f"Upstream inference error during stream: {exc}") from exc

    full_payload = "".join(buffer_parts)
    if finish_reason == "length":
        raise TruncatedStreamError(
            f"Stream truncated at max_tokens={max_tokens}. Partial buffer length: {len(full_payload)} chars."
        )

    try:
        final_model = TradeSignal.model_validate_json(full_payload)
    except ValidationError as exc:
        raise RuntimeError(f"Final schema validation failed: {exc}") from exc

    yield True, final_model


async def main() -> None:
    # Point base_url to local vLLM (http://localhost:8000/v1) or OpenAI
    client = AsyncOpenAI(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:8000/v1"),
        api_key=os.environ.get("LLM_API_KEY", "EMPTY"),
        timeout=30.0,
    )

    async for is_final, model in stream_structured_output(
        client=client,
        model=os.environ.get("LLM_MODEL", "Qwen/Qwen2.5-32B-Instruct"),
        prompt="Analyze NVDA near-term data center demand and output a structured signal.",
    ):
        tag = "FINAL" if is_final else "PARTIAL"
        print(f"[{tag}] ticker={getattr(model, 'ticker', None)} rationale_len={len(getattr(model, 'rationale', ''))}")


if __name__ == "__main__":
    asyncio.run(main())

Guardrails for Production Deployments

  1. Avoid "".join(buffer_parts) on Every Chunk for Huge Payloads: For responses above 50KB, append into a bytearray and throttle jiter.from_json() calls to every 5-10 tokens (or every 50ms) to keep CPU usage flat under high concurrency.
  2. Check Token Budgets Early: Estimate your schema overhead before setting max_tokens using our LLM Token Counter tool so long rationales don’t trigger TruncatedStreamError.
  3. Deterministic Validation: Pair temperature=0.0 with strict post-stream validation as part of your deterministic GenAI systems architecture. If you are running local models on Ollama or vLLM, you can also test this pattern against local Bedrock emulation with MiniStack and Ollama.

Frequently Asked Questions

Why does Pydantic raise ValidationError when streaming structured JSON?

Standard JSON parsers and Pydantic model_validate_json() require a complete, balanced JSON object with closing braces and all required fields. During token-by-token SSE streaming, intermediate buffers like '{"title": "Ana' are invalid JSON and fail immediately.

How does jiter partial_mode work for LLM token streaming?

jiter (Pydantic’s Rust JSON parser) supports partial_mode='trailing-strings', which auto-closes open strings, arrays, and objects on the fly. You get a valid Python dict at every token boundary, allowing progressive UI rendering before the LLM finishes generating.

Does OpenAI’s beta.chat.completions.stream() work with vLLM?

Yes, vLLM 0.7+ and 0.8+ implement OpenAI-compatible response_format json_schema and guided_json. However, for portable streaming across vLLM, SGLang, and OpenAI without SDK-specific wrapper lock-in, parsing raw SSE chunks with jiter gives you deterministic control over partial states.

What happens if an LLM hits max_tokens while streaming structured JSON?

When finish_reason equals 'length', the JSON output is truncated mid-object. jiter can still extract the partial fields received so far for logging, but final model_validate_json() will fail. Always check finish_reason before passing the final payload downstream.

✉ Newsletter

Want to build production-ready AI?

Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.

S

Written by S L Manikanta

AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.

Related Articles

AI Engineering
Designing Deterministic GenAI Systems in a Probabilistic World

Enforce consistent, repeatable outputs from probabilistic LLMs using Pydantic schemas, bounded validation loops, canonicalization, and fallbacks.

AI Engineering
FastEmbed vs Sentence Transformers: Local Embeddings Benchmark

Benchmark Qdrant FastEmbed against PyTorch Sentence Transformers on CPU memory, cold start, and throughput for production RAG pipelines.

AI Engineering
Emulate the Amazon Bedrock Runtime API Locally with MiniStack and Ollama

Emulate the Amazon Bedrock Runtime API locally using MiniStack and Ollama. Test standard Boto3 SDK calls against local LLMs with zero AWS charges.