Skip to main content

Stream partial json generated by LLMs into valid json responses

Project description

Struct Strm Logo
CI/CD CI - Test CI - Build
Package PyPI - Version PyPI - Python Version
Meta Codestyle - Black License: MIT Coverage

Structured Streamer

struct_strm (structured streamer) is a Python package that makes it easy to stream partial json generated by LLMs into valid json responses. This enables partial rendering of UI components without needing to wait for a full response, drastically reducing the time to the first word on the user's screen.

Why Use Structured Streamer?

JSON format is the standard when dealing with structured responses from LLMs. In the early days of LLM structured generation we had to validate the JSON response only after the whole JSON response had been returned. Modern approaches use constrained decoding to ensure that only valid json is returned, eliminating the need for post generation validation, and allowing us to use the response imediately. However, the streamed json response is incomplete, so it can't be parsed using traditional methods. This library aims to make it easier to handle this partially generated json to provide a better end user experience.
See the benchmarks section in the docs for more details about how this library can speed up your structured response processing.


You can learn more about constrained decoding and context free grammar here: XGrammar - Achieving Efficient, Flexible, and Portable Structured Generation with XGrammar

Installation

pip install struct-strm

Dependency Requirements and Comparison with Similar Libraries

struct-strm is lightweight by design and has minimal dependencies compared to other structured-output libraries.

Dependencies:

  • Built-in support for dataclasses — no need for Pydantic or any third-party model framework.
  • Compatible with any OpenAI/Ollama-style async streaming client.

Compared to other libraries:

  • Unlike libraries such as instructor, which validate responses only after full completion, struct-strm focuses on incremental JSON streaming - making it better suited for real-time or UI-driven applications.
  • No extra heavy dependencies or post-generation validation layers - only what’s required for structured streaming.

Main Features

The primary feature is to wrap LLM outputs to produce valid incremental JSON from partial invalid JSON based on user provided structures. Effectively this acts as a wrapper for your LLM calls. Due to the nature of this library (it is primarily inteded for use in web servers), it is expected that it will be used in async workflows, and is async first.

The library also provides simple HTML templates that serve as examples of how you can integrate the streams in your own components.

Due to the nature of partial json streaming, there can be "wrong" ways to stream responses that are not effective for partial rendering of responeses in the UI. The library also provides examples of tested ways to apply the library to get good results.

High Level Flow
High level flow

Example Component

This is an example of a form component being incrementally rendered. By using a structured query response from an LLM, in this case a form with form field names and field placeholders, we can stream the form results directly to a HTML component. This drastically reduces the time to first token, and the precieved time that a user needs to wait. More advanced components are under development.

from stuct_strm import parse_openai
from pydantic import BaseModel
from openai import AsyncOpenAI

...

class DefaultFormItem(BaseModel):
    field_name: str = ""
    field_placeholder: str = ""

class DefaultFormStruct(BaseModel):
    form_fields: List[DefaultFormItem] = []


stream_response = client.beta.chat.completions.stream(
    model="gpt-4.1",
    messages=messages,
    response_format=DefaultFormStruct,
    temperature=0.0,
) 

form_struct_response = parse_openai(DefaultFormStruct, stream_response)
async for instance in form_struct_response:
    async for formstruct in instance:
        print(formstruct)

Fully formed python classes are returned:

>>>  DefaultFormStruct(form_fields=[DefaultFormItem(field_name="fruits", field_placeholder="")])
>>>  DefaultFormStruct(form_fields=[DefaultFormItem(field_name="fruits", field_placeholder="apple ")])
>>>  DefaultFormStruct(form_fields=[DefaultFormItem(field_name="fruits", field_placeholder="apple orange strawberry")])
>>>  etc....

And the corresponding incomplete json string streams would have looked like:

>>> "{"form_fields": [{"field_name": "fruits"
>>> "{"form_fields": [{"field_name": "fruits", "field_placeholder": "apple "
>>> "{"form_fields": [{"field_name": "fruits", "field_placeholder": "apple orange strawberry"}
>>> etc...

Component Streaming

The structured responses can then be easily used to generate incrementally rendered web components.
For example this form:

Example Form Streaming


Or we can return data in a grid in more interesting ways.
For example this rubric:

Example Rubric Streaming

Other

I started struct_strm to support another project I'm working on to provide an easy entrypoint for Teachers to use LLM tools in their workflows. Check it out if you're interested - Teachers PET

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

struct_strm-0.0.14.tar.gz (21.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

struct_strm-0.0.14-py3-none-any.whl (39.4 kB view details)

Uploaded Python 3

File details

Details for the file struct_strm-0.0.14.tar.gz.

File metadata

  • Download URL: struct_strm-0.0.14.tar.gz
  • Upload date:
  • Size: 21.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for struct_strm-0.0.14.tar.gz
Algorithm Hash digest
SHA256 2e75554a97925d2da87c4f2ffcb5b2953f5d2b43b873e0af6a09785ce40fa71e
MD5 c056981a51e716bc968645d9a5c5841a
BLAKE2b-256 b4c0554e70473f982fa0576db4db1aa357a7fbd158ad7117130d1d8a674969a6

See more details on using hashes here.

Provenance

The following attestation bundles were made for struct_strm-0.0.14.tar.gz:

Publisher: release.yaml on PrestonBlackburn/structured_streamer

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file struct_strm-0.0.14-py3-none-any.whl.

File metadata

  • Download URL: struct_strm-0.0.14-py3-none-any.whl
  • Upload date:
  • Size: 39.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for struct_strm-0.0.14-py3-none-any.whl
Algorithm Hash digest
SHA256 631e49602d6563f96e527b37e7c43a582f2212084589baec5651fcece34abf2b
MD5 c3df7a1f532f1bdce2228c47773d487c
BLAKE2b-256 39778c39a396a7f5ed1a72b8bce071c4c47bedd4757f610bd60990003655daa2

See more details on using hashes here.

Provenance

The following attestation bundles were made for struct_strm-0.0.14-py3-none-any.whl:

Publisher: release.yaml on PrestonBlackburn/structured_streamer

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page