← All articles

Inference · June 26, 2026 · 3 min read

Structured JSON output from open models

Learn how to enforce JSON schemas on open-weight LLMs using Pydantic and deploy them as scalable serverless functions on Podstack's GPU cloud.

In the current era of LLM integration, getting a model to "chat" is easy. Getting a model to act as a reliable component in a software pipeline is significantly harder. For developers building autonomous agents or automated data extractors, the biggest hurdle isn't the model’s reasoning—it's the format of its response.

If your application expects a valid JSON object with specific keys but the model returns conversational filler or trailing commas, your code breaks. Achieving structured JSON output is the key to turning an unpredictable LLM into a reliable API.

In this guide, we’ll explore how to enforce structured outputs using open-weight models like Llama 3 or Mixtral, and how to deploy these workflows as high-performance endpoints.

Why Structured Output Matters

Modern applications rarely consume raw text. Whether you are generating a list of UI components, extracting entities from a document, or determining which tool an agent should call, you need data in a machine-readable format.

While proprietary models often have built-in "JSON mode," open models offer more flexibility. By using techniques like Grammar-based sampling or Pydantic validation, you can ensure the model's output strictly adheres to a predefined schema, preventing parsing errors entirely.

Implementation: The Pydantic Approach

The most robust way to handle structured data in Python is through Pydantic. By defining a class that represents your desired output, you create a contract between your logic and the model.

Here is a practical implementation using a FastAPI-style structure that you can deploy as a serverless function. We use a library like instructor or the native json_schema capabilities of inference engines to force the model's hand.

import os
from pydantic import BaseModel, Field
from typing import List
from podstack import PodstackClient

# Define the schema
class SentimentAnalysis(BaseModel):
    sentiment: str = Field(description="The emotional tone: positive, negative, or neutral")
    confidence_score: float = Field(ge=0, le=1)
    topics: List[str] = Field(description="Key topics mentioned in the text")

# Initialize the Podstack client
client = PodstackClient(api_key=os.getenv("PODSTACK_API_KEY"))

def analyze_review(text: str):
    prompt = f"Analyze the following user review and return only JSON: {text}"
    
    # Using a high-performance open model endpoint
    response = client.inference.create(
        model="llama-3-70b-instruct",
        messages=[{"role": "user", "content": prompt}],
        response_format={
            "type": "json_object",
            "schema": SentimentAnalysis.model_json_schema()
        }
    )
    
    # Parse and validate the output
    data = SentimentAnalysis.model_validate_json(response.choices[0].message.content)
    return data

review = "The GPU cold-start times are incredibly fast, but the documentation needs more examples."
print(analyze_review(review))

Practical Tips for Reliability

  1. System Prompts: Even with schema enforcement, a clear system prompt helps. Use: "You are a data extraction engine. Always return valid JSON that conforms to the provided schema. Do not include markdown formatting or conversational text."
  2. Schema Simplification: Large schemas can confuse smaller models (like 7B or 8B variants). If you have a complex nested object, consider breaking it into multiple smaller inference calls.
  3. Handling Hallucinations: Structured output doesn't prevent factual errors; it only prevents formatting errors. Always include a confidence_score field in your schema to allow your application to flag uncertain extractions for human review.
  4. Temperature Settings: When generating JSON, keep your temperature low (between 0.0 and 0.2). This makes the model more deterministic and less likely to wander outside the schema boundaries.

Scaling with Serverless GPU Functions

Once you have your logic ready, you need to run it at scale. Running a heavy model like Llama 3 locally is slow, and managing persistent clusters for sporadic traffic is expensive.

This is where serverless GPU functions become a game-changer. Instead of managing a virtual machine, you can package your extraction logic as a job or an endpoint that scales automatically.

Using the Podstack API, you can deploy your structured output function in seconds:

Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key.

Why Podstack?

Reliable structured output requires low latency and high availability. Podstack provides the infrastructure to run these models on demand, billed per second of actual usage.

Whether you are running a batch job to process millions of records or hosting an inference endpoint for a real-time app, our platform ensures you have access to the latest GPUs (like H100s and A100s) without the overhead of infrastructure management. By combining Python’s Pydantic ecosystem with Podstack’s serverless GPU functions, you can build production-ready ML features that are both robust and cost-effective.

Try it on Podstack

Per-second GPUs and pay-per-token models. Add $5, get $10 on your first top-up.

Start building