Structured Outputs with GPT-6.1 Sol

Structured Outputs with GPT-6.1 Sol

Published on

1

views

This article demonstrates how to request and validate structured JSON outputs from the GPT-6.1 Sol model using FastAPI and Pydantic. It highlights minimal implementation details, schema enforcement, application-side validation, and essential logging practices, helping you turn unstructured model responses into reliable, typed application data without unnecessary agent complexity.

You can already call the model, get a free-text summary, and store the result. The next practical need is getting the model to return data that your application can actually parse and trust—JSON that matches a schema, not a paragraph that happens to look like JSON.

This article shows a minimal, honest way to request structured outputs from GPT-6.1 Sol, validate them on the application side, and treat schema-valid data as necessary but never sufficient. We stay with a single deterministic call. No agents, no multi-step loops.

The Short Answer

Low-angle shot of a backend engineer reviewing a single-step, deterministic API call on a laptop screen.

Ask the model for a response that conforms to a JSON Schema (or the equivalent structured-output mode your client supports), parse the result, run it through your own schema validator, and reject anything that fails. Log the raw content and the validation outcome. Never assume that a schema-valid object is factually correct or complete for your use case.

What Product Problem This Solves

Free-text summaries are fine for human eyes. The moment you want to store fields, route on a status value, or feed the result into another function, free text becomes a liability. Structured outputs turn the model response into data your code can handle without brittle string parsing or hopeful regex.

The catch is that structure is not the same as correctness. A response can be perfectly valid JSON and still be wrong, incomplete, or unsafe. The application must still verify the values before it acts on them.

Minimal Working Implementation

We will extend the existing FastAPI service with a new endpoint that requests a structured summary object. The example uses the OpenAI client’s structured-output support (adjust the exact parameter names to match the current SDK and model documentation).

Python

import logging
from typing import Optional, Literal
from pydantic import BaseModel, Field, ValidationError
from fastapi import FastAPI, HTTPException, Depends
from openai import OpenAI, APIError, APITimeoutError

logger = logging.getLogger(__name__)

# The shape we actually want in our application
class StructuredSummary(BaseModel):
    title: str = Field(..., min_length=1, max_length=120)
    summary: str = Field(..., min_length=10, max_length=800)
    key_points: list[str] = Field(..., min_length=1, max_length=6)
    sentiment: Literal["positive", "neutral", "negative"]
    confidence: float = Field(..., ge=0.0, le=1.0)

class StructuredRequest(BaseModel):
    text: str = Field(..., min_length=20, max_length=6000)

class StructuredResponse(BaseModel):
    data: StructuredSummary
    finish_reason: str
    model: str
    usage: dict
    request_id: Optional[str] = None
    raw_content: Optional[str] = None  # kept for debugging only

SYSTEM_PROMPT = """
You are a structured extraction assistant.
Return a JSON object that matches the provided schema exactly.
Do not include markdown, code fences, or any text outside the JSON object.
"""

@app.post("/v1/structured-summary", response_model=StructuredResponse)
async def structured_summary(
    body: StructuredRequest,
    openai_client: OpenAI = Depends(get_client),
):
    try:
        response = openai_client.chat.completions.create(
            model="gpt-6.1-sol",
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": body.text},
            ],
            response_format={
                "type": "json_schema",
                "json_schema": {
                    "name": "structured_summary",
                    "schema": StructuredSummary.model_json_schema(),
                    "strict": True,
                },
            },
            max_tokens=400,
            temperature=0.1,
            timeout=25.0,
        )
    except APITimeoutError:
        raise HTTPException(status_code=504, detail="Model request timed out")
    except APIError as e:
        logger.error("Model API error: %s", str(e))
        raise HTTPException(status_code=502, detail="Upstream model error")

    choice = response.choices[0]
    raw_content = choice.message.content or ""
    finish_reason = choice.finish_reason or "unknown"

    usage = {
        "prompt_tokens": response.usage.prompt_tokens,
        "completion_tokens": response.usage.completion_tokens,
        "total_tokens": response.usage.total_tokens,
    }

    logger.info(
        "finish_reason=%s total_tokens=%s content_length=%s request_id=%s",
        finish_reason,
        usage["total_tokens"],
        len(raw_content),
        response.id,
    )

    if not raw_content.strip():
        raise HTTPException(
            status_code=502,
            detail=f"Empty content (finish_reason={finish_reason})",
        )

    # Application-level validation – never skip this
    try:
        parsed = StructuredSummary.model_validate_json(raw_content)
    except ValidationError as e:
        logger.warning("Schema validation failed: %s", e)
        raise HTTPException(
            status_code=502,
            detail="Model returned data that failed schema validation",
        )

    return StructuredResponse(
        data=parsed,
        finish_reason=finish_reason,
        model=response.model,
        usage=usage,
        request_id=response.id,
        raw_content=raw_content,  # remove or gate in production
    )

This is the smallest version that still answers the product question: “Can I get a typed object back instead of free text?”

What Schema Validation Does and Does Not Prove

Schema validation proves the response is well-formed and matches the shape you declared. It does not prove:

  • the title is accurate

  • the key points are complete or correctly ordered

  • the sentiment label is appropriate

  • the confidence score is calibrated

  • the content is safe to show to a user or store permanently

I once received a perfectly valid object whose key_points list contained three near-identical sentences and a confidence of 0.97 for a clearly mixed-sentiment paragraph. The schema passed. The data was still poor. The application must decide what additional checks are required before the object is trusted.

Why We Still Validate on the Application Side

Even when the model is instructed (or constrained) to return schema-compliant JSON, the application remains the last line of defense. Network proxies, SDK bugs, or future model changes can still produce unexpected content. Running the same Pydantic model on the way in is cheap insurance.

Treat the model’s structured output as a suggestion that has passed a format check. Your code still owns the decision to accept, reject, or further verify the values.

Logging and Observability

Log the finish reason, token counts, and whether validation succeeded. In early development it is useful to keep the raw content (gated behind a debug flag) so you can inspect failures. In production the raw payload should be truncated or stored only in a secure debug store.

The same task-persistence pattern from earlier articles can be extended to store the structured fields once they pass validation. That gives you an audit trail of both the operational metadata and the extracted data.

Wide-angle shot of an engineer monitoring structured API request logs and status codes in a dim operations room.

What Was Tested and What Remains Uncertain

I tested the endpoint with short and medium inputs, forced max-token truncations, and deliberately malformed responses (by temporarily disabling the schema constraint). Validation failures were caught and returned as 502s. Valid objects were returned with the expected shape.

I have not exhaustively tested every possible JSON Schema feature, nor have I measured behavior under concurrent load or against every future model revision. Exact parameter names for structured outputs, strict-mode behavior, and token accounting must be verified against current official documentation before production use. Confidence scores in particular should be treated as uncalibrated until you have measured them against real data.

When a Simpler Approach Is Enough

If the only consumer is a human reading a summary, free text is still simpler. The moment another part of the system needs to branch on a field, store a list, or feed the result into a typed function, structured outputs become the smaller useful version.

Before adding an agent, see whether a deterministic structured call is enough. Before adding multi-step repair loops, see whether clearer prompting and application-side validation already solve the problem. The extra complexity has to earn its place.

Practical Conclusion

Structured outputs with GPT-6.1 Sol give you data instead of prose. That is valuable. It is not a guarantee of correctness. Request the schema, parse the result, validate it again in your application, and only then decide whether the object is usable.

Start with the smallest version that can answer the product question. In this case the question is “Can I reliably get a typed object I can parse and store?” The endpoint above is that version.

The model can produce the JSON; your application still has to verify every step.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

Validate Model-Generated Data Before Saving It

Validate Model-Generated Data Before Saving It

This article explains why schema validation alone is not enough to ensure AI data quality. It demonstrates how to implement a practical second validation layer using business rules and Pydantic validators in Python. By checking domain logic, checking for placeholder text, and logging rejections before database persistence, you can keep bad data out of your system.

0
Build a Safe Tool-Calling Workflow with FastAPI

Build a Safe Tool-Calling Workflow with FastAPI

This article demonstrates how to build a safe, production-ready tool-calling workflow inside a FastAPI service. It covers essential security practices including explicit tool registries, permission flags, Pydantic argument validation, and strict four-gate execution checks, ensuring the model only proposes actions while your application retains full control over execution and logging.

0
What to Do When a Tool Call Has Invalid Arguments

What to Do When a Tool Call Has Invalid Arguments

This article explains how a FastAPI service should handle invalid tool-call arguments from language models. It covers rejecting bad arguments instead of auto-correcting, implementing Pydantic validation checks, structuring error responses, and logging exact failure details. This ensures predictable application behavior and maintains strict control over execution boundaries during AI tool interactions.

0