Developing Precise JSON Parsing Workflows

KeyFreeAPIOpenAI · Updated 2026-11-24 · 9 min read

Coding setup for structured output
Setting up the environment for structured JSON output

Getting a language model to return clean, parseable JSON is often harder than generating the text itself. While commercial models like GPT-4 are trained extensively on structured data, smaller open-weight models can struggle with strict formatting, often adding trailing commas or wrapping the output in markdown code blocks that break standard parsers.

This guide shows you how to enforce structure using the OpenAI-compatible SDKs, specifically tailored for free, keyless endpoints. We will use a free, keyless API that requires no account or API key, making it ideal for prototyping and lightweight applications without the overhead of billing management.

By defining clear Pydantic models and handling response parsing explicitly, you can ensure your Python applications receive exactly the data structure they expect. We will also explore how to measure the reliability of these outputs on your own tasks, rather than relying on generic leaderboards, to find the right balance between cost and quality.

Frequently asked questions

What is structured output in LLMs?

Structured output refers to forcing a language model to generate data in a specific format, such as JSON, XML, or YAML, rather than free-form text. This allows programmatic parsing of the response, enabling integration with databases, UIs, or other software systems without manual text cleaning.

How does JSON mode differ from free-text generation?

In free-text mode, the model generates natural language, which may include explanations, markdown, or inconsistent formatting. JSON mode constrains the model’s vocabulary and syntax, ensuring the output strictly adheres to a schema. This reduces parsing errors but may slightly increase latency due to the constraint enforcement.

Which is better: Pydantic or manual regex parsing?

Pydantic is generally better for complex structures because it validates data types and provides clear error messages if the schema is violated. Regex is faster and simpler for very basic patterns but becomes fragile with nested objects or optional fields. For most Python applications, Pydantic offers the best balance of robustness and maintainability.

What is the role of the 'free-ai' model in this context?

The 'free-ai' model is an independent open-weight model available via a keyless API. It is not affiliated with OpenAI and does not use OpenAI's infrastructure. It is fine-tuned to refuse less than commercial assistants, making it suitable for generating structured data without the strict safety filters that might alter output format.

How do I handle parsing errors in Python?

You should wrap your parsing logic in try-except blocks to catch JSONDecodeError or Pydantic ValidationError. If parsing fails, you can retry the request or fall back to a regex-based extraction as a last resort. Logging the raw response helps in debugging why the model deviated from the expected format.

Can I use this with local models like llama.cpp?

Yes, the principles of structured output apply to local models as well. However, local models may require more explicit prompting or post-processing to ensure strict JSON compliance. You can test the same Pydantic schemas with local models to compare their adherence to structure against remote APIs.

What are the limits of the free API for structured output?

The free API allows up to 10,000 requests or 10 million tokens per day per IP. It supports a context window of 32,000 tokens and can generate up to 16,000 tokens in a single response. These limits are reset daily at 00:00 UTC, making it suitable for moderate-scale applications.

Is this service affiliated with OpenAI?

The service is not affiliated with OpenAI. It provides an OpenAI-compatible API interface but runs on its own infrastructure. The 'free-ai' model is an independent model, not a variant of GPT. Users should not assume access to OpenAI’s specific models or keys when using this endpoint.

Step by step

  1. Define Schema — Create Pydantic models to define the expected JSON structure. Use field descriptions to guide the model.
  2. Configure Client — Initialize the OpenAI client with the free API base URL and a dummy key. Set the model to 'free-ai'.
  3. Send Request — Make a chat completion request with response_format set to 'json_object'. Include a system message requesting JSON.
  4. Parse Response — Parse the response string using Pydantic's model_validate_json. Handle errors with try-except blocks.

Setting Up the Environment

To begin, you need a Python environment with the necessary libraries installed. The most common approach is to use the 'openai' Python package, which is compatible with many OpenAI-compatible endpoints. You can install it using pip: pip install openai. This package provides a high-level interface for making requests to the API.

You also need to define the structure of your output using Pydantic. Pydantic is a data validation library that uses type hints to specify the expected format of the data. By defining a Pydantic model, you can ensure that the model’s output matches your expected schema, reducing the need for manual parsing.

Installing Dependencies

Install the openai package and pydantic using pip. Ensure you have Python 3.8 or higher for full type hint support. These libraries are standard in the Python ecosystem and provide robust tools for API interaction and data validation.

Defining the Schema

Create a Pydantic model that represents the structure of your desired output. Use field descriptions to guide the model. For example, define a class for a 'ReasoningStep' with fields for step number and content. This schema will be used to validate the response.

from pydantic import BaseModel, Field

class ReasoningStep(BaseModel):
    step_number: int = Field(description="Step index starting from 1", ge=1)
    content: str = Field(description="Description of the reasoning step")

class Scratchpad(BaseModel):
    content: list[str] = Field(description="Intermediate notes or thoughts used during reasoning")

Configuring the API Client

The free API endpoint is https://api.keyfreeapiopenai.com/v1. You can initialize the OpenAI client with this base URL and a dummy API key, as the service is keyless. The model name is 'free-ai'. This configuration allows you to use the standard OpenAI SDK methods without modification.

It is important to note that this service is not affiliated with OpenAI. The 'free-ai' model is an independent model, so it may have different behavior compared to GPT models. You should test your prompts thoroughly to ensure they work as expected with this specific model.

Initializing the Client

Create an OpenAI client instance with the base URL and a dummy key. This allows you to use the standard SDK methods. The client will handle the HTTP requests and response parsing for you.

Setting Request Parameters

Configure the request parameters, such as the model name, temperature, and max tokens. Use a low temperature for more deterministic output. Set max tokens to a value that accommodates your expected response length.

import openai

client = openai.OpenAI(
    base_url="https://api.keyfreeapiopenai.com/v1",
    api_key="free-ai-key"
)

response = client.chat.completions.create(
    model="free-ai",
    messages=[{"role": "user", "content": "Generate a reasoning step."}],
    response_format={"type": "json_object"},
    temperature=0.1
)
Pydantic model definition
Defining the schema with Pydantic

Enforcing JSON Structure

To ensure the model returns valid JSON, you can use the 'response_format' parameter in the API request. Setting this to 'json_object' instructs the model to output a JSON object. This is supported by the OpenAI SDK and many other compatible clients.

However, not all models support this parameter equally. The 'free-ai' model is fine-tuned to refuse less, but it still benefits from explicit instructions in the prompt. You should include a system message that specifies the expected format, such as 'Return only a JSON object.'

Using Response Format

Set the response_format parameter to 'json_object' in your API call. This tells the model to constrain its output to valid JSON. This is the most reliable way to get structured output from modern models.

Prompt Engineering for JSON

Include a system message that explicitly requests JSON output. For example, 'Return only a JSON object with the following schema: ...'. This helps guide the model, especially if the response_format parameter is not strictly enforced.

response = client.chat.completions.create(
    model="free-ai",
    messages=[
        {"role": "system", "content": "Return only a JSON object."},
        {"role": "user", "content": "Generate a reasoning step."}
    ],
    response_format={"type": "json_object"}
)

Parsing the Response

Once you receive the response, you need to parse the JSON string into a Pydantic model. The OpenAI SDK returns the response as a string, which you can parse using the 'json' module or Pydantic's 'model_validate_json' method.

Pydantic's 'model_validate_json' method is preferred because it validates the data against the schema and raises an error if the format is incorrect. This ensures that your application receives data in the expected format.

Parsing with Pydantic

Use Pydantic's 'model_validate_json' method to parse the response string. This method validates the data against the schema and returns a model instance. If the data is invalid, it raises a ValidationError.

Handling Parsing Errors

Wrap the parsing logic in a try-except block to catch ValidationError. If parsing fails, you can retry the request or log the error for debugging. This ensures that your application handles unexpected output gracefully.

import json

try:
    data = json.loads(response.choices[0].message.content)
    step = ReasoningStep.model_validate(data)
except json.JSONDecodeError as e:
    print(f"JSON parsing error: {e}")
except Exception as e:
    print(f"Validation error: {e}")
Data flow diagram
Flow of data from API to application

Handling Edge Cases

Even with JSON mode, models can sometimes produce output that is not strictly valid JSON. Common issues include trailing commas, missing quotes, or markdown code blocks wrapping the JSON. You need to handle these cases to ensure robust parsing.

One approach is to use a regex to extract the JSON object from the response. This can be useful if the model adds markdown formatting or other text around the JSON. However, this is less reliable than using Pydantic validation.

Extracting JSON with Regex

Use a regex to extract the JSON object from the response string. This is useful if the model adds markdown formatting. The regex should match the opening and closing braces of the JSON object.

Retrying on Failure

If parsing fails, you can retry the request with a slightly different prompt or temperature. This can help the model converge on the correct format. However, avoid infinite loops by setting a maximum number of retries.

import re

json_pattern = re.compile(r'\{.*\}', re.DOTALL)
match = json_pattern.search(response.choices[0].message.content)
if match:
    data = json.loads(match.group())
    step = ReasoningStep.model_validate(data)

Streaming Structured Output

Streaming is useful for real-time applications, but it complicates structured output because the JSON object is not complete until the end of the stream. You need to accumulate the tokens and parse the JSON only when the stream is complete.

The free API supports streaming with Server-Sent Events (SSE). You can use the OpenAI SDK to stream the response and accumulate the tokens. Once the stream is complete, you can parse the accumulated string as JSON.

Accumulating Tokens

Use the streaming API to accumulate tokens. The SDK provides a stream object that yields chunks of the response. You can concatenate these chunks to form the complete response string.

Parsing After Stream

Once the stream is complete, parse the accumulated string as JSON. Use Pydantic to validate the data. This ensures that the structured output is correct even when using streaming.

stream = client.chat.completions.create(
    model="free-ai",
    messages=[{"role": "user", "content": "Generate a reasoning step."}],
    stream=True
)

accumulated = ""
for chunk in stream:
    if chunk.choices[0].delta.content:
        accumulated += chunk.choices[0].delta.content

step = ReasoningStep.model_validate_json(accumulated)
Books on AI and Python
Resources for learning about AI and Python

Testing and Validation

Testing structured output is crucial to ensure reliability. You should test your prompts with a variety of inputs to see how well the model adheres to the schema. Use a test suite to automate this process.

You can also compare the performance of different models by measuring the success rate of parsing. This helps you choose the best model for your use case. The free API is a good option for testing because it is free and easy to access.

Writing Test Cases

Write test cases that cover various input scenarios. Check if the model returns valid JSON and if the data matches the schema. Use assertions to verify the output.

Measuring Success Rate

Measure the success rate of parsing by running multiple requests and counting the number of successful parses. This gives you a quantitative measure of the model's reliability. You can compare this with other models to make an informed decision.

  • Test with diverse inputs
  • Measure parsing success rate
  • Compare with other models

Best Practices for Production

In production, you should implement retry logic with exponential backoff to handle transient errors. The free API has rate limits, so you need to manage these carefully to avoid 429 errors.

It is also important to log the responses for debugging and analysis. This helps you identify patterns in failures and improve your prompts over time. You can use the /llms.txt endpoint to get more information about the API.

Implementing Retry Logic

Use exponential backoff to retry failed requests. This helps handle rate limits and transient errors. The SDK provides utilities for this, or you can implement it manually.

Logging and Monitoring

Log the responses and errors for debugging. This helps you identify issues and improve your prompts. You can use the /llms.txt endpoint to get more information about the API.

import time

for attempt in range(3):
    try:
        response = client.chat.completions.create(...)
        break
    except Exception as e:
        time.sleep(2 ** attempt)
else:
    print("Max retries reached")
API network diagram
Network of API endpoints
Try the free API

Test the free 35B model with your own prompts and see how it handles your specific tasks before committing to paid plans.

Read also