AIYINGFrom AI Awareness to Accomplishment
Showing posts with label OpenAI API. Show all posts
Showing posts with label OpenAI API. Show all posts

Sunday, October 25, 2026

DO this AI Thing Now #015 | Structured Outputs — Stop Broken JSON in AI Applications

DO this AI Thing Now | #015 | INNOVATION

FOR AI ENGINEERS & DEVELOPERS

Stop Broken JSON! Build Reliable AI Applications with Structured Outputs

Your LLM generates JSON. But can your application depend on its structure? Learn how to enforce a schema, validate responses, and handle failures.

1. The Real Engineering Problem

Large language models often produce useful information in unpredictable formats. A response may contain extra commentary, missing fields, inconsistent data types, or JSON that cannot be parsed.

These issues become important when LLM outputs feed APIs, databases, dashboards, automation workflows, or AI agents.

Unreliable output:
{
  task: "Write report",
  priority: high,
  valid: true,
}

This is not valid JSON. Property names must be quoted, the value high is not a valid unquoted JSON value, and the final property has a trailing comma.

Valid structured result:
{
  "task": "Write report",
  "priority": 1,
  "valid": true
}

The second example is valid JSON and matches the field types in our example schema. However, formatting correctness does not prove that the generated information is factually accurate.

2. What Are Structured Outputs?

Structured Outputs allow developers to specify an expected response structure using a supported JSON Schema and request that a compatible model produce data conforming to that structure.

This is different from merely including the instruction "Please respond in JSON" in a prompt.

  • Prompt-only JSON: Asks the model to follow a format.
  • JSON mode: Helps ensure syntactically valid JSON, but does not necessarily enforce your complete schema.
  • Structured Outputs: Uses supported schema constraints to enforce the expected response structure.
  • Application validation: Independently checks the result and its business rules.

3. Practical Example: AI Task Extraction

Imagine an application that reads a short message and extracts a task, priority, and validity flag.

Input:

"Please prepare the quarterly report. It is urgent."

Desired output:

{
  "task": "Prepare the quarterly report",
  "priority": 1,
  "valid": true
}

For this demonstration, priority 1 means high urgency, priority 2 means normal urgency, and priority 3 means low urgency. The valid field indicates whether the input contains an actionable task. These are application-specific conventions.

4. Define the JSON Schema

Here is a schema defining the exact fields and data types.

{
  "type": "object",
  "properties": {
    "task": {
      "type": "string"
    },
    "priority": {
      "type": "integer",
      "enum": [1, 2, 3]
    },
    "valid": {
      "type": "boolean"
    }
  },
  "required": [
    "task",
    "priority",
    "valid"
  ],
  "additionalProperties": false
}

This schema specifies three required fields, constrains priority to the values 1, 2, or 3, and disallows unexpected properties.

5. Hands-On Python Demonstration

The following example uses the OpenAI Python SDK and a compatible structured-output model. It also performs independent application-side validation.

Install dependencies:

pip install -U openai jsonschema

Configure your OPENAI_API_KEY as an environment variable. Never place API keys directly inside published source code.

Python example:

import os
import json

from openai import OpenAI
from jsonschema import validate

client = OpenAI(
    api_key=os.environ["OPENAI_API_KEY"]
)

schema = {
    "type": "object",
    "properties": {
        "task": {"type": "string"},
        "priority": {
            "type": "integer",
            "enum": [1, 2, 3]
        },
        "valid": {"type": "boolean"}
    },
    "required": [
        "task", "priority", "valid"
    ],
    "additionalProperties": False
}

response = client.responses.create(
    model="gpt-4.1-mini",
    instructions=(
        "Extract the actionable task. "
        "Use priority 1 for urgent, "
        "2 for normal, 3 for low. "
        "Set valid to true if an "
        "actionable task exists. "
        "Otherwise use an empty task "
        "and set valid to false."
    ),
    input=(
        "Please prepare the quarterly "
        "report. It is urgent."
    ),
    text={
        "format": {
            "type": "json_schema",
            "name": "task_extraction",
            "strict": True,
            "schema": schema
        }
    }
)

if response.status != "completed":
    raise RuntimeError(
        f"Response status: {response.status}"
    )

if not response.output_text:
    raise RuntimeError(
        "No structured text returned"
    )

data = json.loads(response.output_text)

validate(instance=data, schema=schema)

if data["valid"] and not data["task"].strip():
    raise ValueError(
        "Valid tasks must not be empty"
    )

print(json.dumps(data, indent=2))

This example uses the Responses API structured-output configuration. It assumes the request completes successfully and returns text rather than a refusal. Production systems must also handle API errors, refusals, incomplete responses, and retry policies. Confirm current model support and API syntax in the official documentation.

Illustrative result:

{
  "task": "Prepare the quarterly report",
  "priority": 1,
  "valid": true
}

The output above illustrates the expected result; it is not a claim that the example was executed during publication.

6. Test the Output

Reliable AI engineering requires more than one successful example. Test both the expected structure and your application rules.

from jsonschema import (
    validate,
    ValidationError
)

def is_schema_valid(value):
    try:
        validate(
            instance=value,
            schema=schema
        )
        return True
    except ValidationError:
        return False

assert is_schema_valid({
    "task": "Write report",
    "priority": 1,
    "valid": True
})

assert not is_schema_valid({
    "task": "Write report",
    "priority": "high",
    "valid": True
})

assert not is_schema_valid({
    "task": "Write report",
    "priority": 1
})

assert not is_schema_valid({
    "task": "Write report",
    "priority": 1,
    "valid": True,
    "extra": "unexpected"
})

print("Schema tests passed")

These tests check a valid response, an incorrect type, a missing required field, and an unexpected extra property.

7. Where Structured Outputs Are Useful

Document Processing

Extract invoice fields, dates, categories, and entities into defined structures.

AI Agents

Produce structured plans, classifications, and intermediate results for workflows.

Business Applications

Generate task records, support classifications, and CRM-ready information.

Evaluation Systems

Collect model assessments and test outcomes using consistent field definitions.

8. Engineering Limitations

Structured Outputs are useful, but they are not a complete reliability or security solution.

  • Semantic errors: A schema-valid priority may still be wrong.
  • Refusals: Safety-related refusals may not follow the requested schema.
  • Incomplete generation: Token limits or interruptions may prevent a complete result.
  • Schema support: Not every JSON Schema feature is supported by every model or API.
  • Security: Structured outputs do not eliminate prompt injection or unsafe downstream actions.
  • Business rules: Additional validation may be necessary for dates, identifiers, permissions, and domain-specific constraints.
  • Cost and latency: Model selection and schema complexity may affect performance.

9. Practical Engineering Checklist

☐ Define the exact data contract.

☐ Choose a compatible model and API.

☐ Enable schema-enforced structured outputs.

☐ Validate the returned JSON independently.

☐ Check semantic and business-rule correctness.

☐ Handle refusals, incomplete outputs, and API errors.

☐ Test valid, invalid, and adversarial inputs.

☐ Monitor failures and maintain versioned schemas.

10. Further Learning

Official OpenAI Structured Outputs Guide:
https://platform.openai.com/docs/guides/structured-outputs

OpenAI API Reference:
Responses API Reference

JSON Schema Documentation:
https://json-schema.org/

11. Your AI Action Now

10-Minute Challenge
  1. Choose one LLM feature in an application or prototype.
  2. Define three output fields and their expected types.
  3. Enforce the structure with a compatible API.
  4. Test one valid and three invalid responses.
  5. Document what schema validation does not catch.

One schema. One test. One more reliable AI integration.

DO this AI Thing Now

Less AI talk. More AI action.

Explore practical AI actions, tools, and innovations for students, teachers, professionals, developers, engineers, researchers, and organizations.

Explore the YouTube Playlist

AIYING — Accomplishing with AI
https://dastikop.blogspot.com

Saturday, October 3, 2026

The Minimalist Responses API: Responses API Explained in 100 Words

The Minimalist Responses API - Responses API Explained in 100 Words by Ravindra Dastikop

THE MINIMALIST RESPONSES API

Responses API Explained in 100 Words

Ravindra Dastikop

Understand less. Accomplish more.


Why This Book?

The Responses API is becoming complicated.

Inputs.
Models.
Outputs.
Tools.
Conversations.
Multimodal.
Streaming.
State.
Judgment.

But using the Responses API does not have to begin with complexity.

This book strips the Responses API down to what matters.

10 ideas.
10 words each.
100 words.
Enough to begin.


How to Read This Book

Read one idea.

Stop.

Think about it.

Try it with AI.

Then move to the next.

The purpose is not to know everything about the Responses API.

The purpose is to understand enough to accomplish something with the Responses API.


01 — RESPONSES

Responses provides OpenAI's unified interface for building intelligent applications today.

The Responses API is a central OpenAI API surface for building applications with models.

You send input.

Choose a model.

Give it instructions.

Optionally provide tools.

The model processes the request.

The API returns a response.

A response can involve more than generated text.

It can include messages, reasoning, tool calls, and other output items.

The important shift is simple.

You describe what needs to be accomplished and let the model work through the available capabilities.

INPUT → RESPONSES API → OUTPUT

02 — INPUT

Input supplies text, images, files, or other information for processing.

Every response begins with input.

Input tells the model what it has to work with.

That might include:

Text.
Images.
Files.
Instructions.
Previous interaction items.
Information returned from tools.

Good input gives the model useful material for accomplishing the task.

The important question is:

What information does the model need to do this work?

INPUT → MODEL → RESPONSE

03 — MODEL

Models process supplied inputs and generate useful outputs or actions.

The model provides the intelligence behind the response.

It processes the supplied input.

Interprets instructions.

Works with available context.

Reasons when appropriate.

Generates output.

And may decide to use available tools.

The API provides the interface.

The model performs the intelligence work.

INPUT → MODEL → OUTPUT

04 — OUTPUT

Output contains generated messages, tool calls, and other response items.

A response is not necessarily one block of text.

The Responses API can return different kinds of output items.

These can represent:

Messages.
Reasoning.
Tool calls.
Function calls.
Other response items.

This matters because an AI application may need to do more than display an answer.

It may need to interpret an item.

Execute a tool.

Continue a workflow.

Or present the final result.

MODEL → OUTPUT ITEMS → APPLICATION

05 — TOOLS

Tools extend models with search, files, code, computers, and MCP.

Models can generate information.

Tools let them do more.

Depending on the model and configuration, tools can provide capabilities such as:

Web search.
File search.
Code execution.
Computer interaction.
Function calling.
MCP connections.

Tools allow the model to interact with capabilities beyond language generation alone.

The question becomes:

What capability does the model need to accomplish this task?

MODEL + TOOLS → CAPABILITY

06 — CONVERSATION

Conversations maintain related input and output items across multiple interactions.

Useful AI work often takes more than one turn.

You ask.

The model responds.

You add information.

The model continues.

The Responses API supports continuing related interactions rather than treating every request as completely isolated.

That enables:

Follow-up questions.
Corrections.
Refinement.
Additional context.
Continuing work.

Conversation turns individual responses into an evolving interaction.

INPUT → RESPONSE → CONTINUE

07 — MULTIMODAL

Multimodal capabilities let models process text and images within requests.

Human information does not exist only as text.

Sometimes the model needs to work with an image.

A document.

Or another supported form of information.

Multimodal capabilities allow applications to provide different forms of input to compatible models.

An application might combine:

Instructions.

Text.

Images.

Files.

And other supported inputs.

The interaction becomes richer than text alone.

TEXT + IMAGE → MODEL → RESPONSE

08 — STREAMING

Streaming delivers response events progressively while model generation continues asynchronously.

Some responses take time.

Applications do not always need to wait until everything is finished.

Streaming allows response events to arrive while generation continues.

That can include:

Text updates.
Tool-related events.
Completion events.
Other response events.

This can make an application feel more responsive.

Instead of:

Wait → Complete response.

You can have:

Generate → Stream → Receive.

GENERATE → STREAM → RECEIVE

09 — STATE

State preserves relevant interaction information across connected model responses automatically.

Many useful AI tasks continue over several responses.

The system therefore needs a way to preserve relevant interaction information.

State allows later responses to build on earlier work.

That can support:

Follow-up questions.
Refinement.
Continuing reasoning.
Tool workflows.
Longer tasks.

Without state, every request risks becoming an isolated interaction.

With state, responses can become connected work.

RESPONSE → STATE → NEXT RESPONSE

10 — JUDGMENT

Human judgment determines which generated outputs and actions deserve acceptance.

The Responses API can make applications powerful.

Models can generate.

Reason.

Use tools.

Retrieve information.

And trigger actions.

But capability does not eliminate responsibility.

Humans and organizations still need to determine:

Is the output accurate?

Is the tool appropriate?

Should this action occur?

Does sensitive information require protection?

Should the result be trusted?

Should the workflow continue?

AI generates and acts within configured capabilities.

Humans remain responsible for deciding what should move forward.

AI RESPONDS → HUMAN JUDGES

The Entire Book in 100 Words

RESPONSES
Responses provides OpenAI's unified interface for building intelligent applications today.

INPUT
Input supplies text, images, files, or other information for processing.

MODEL
Models process supplied inputs and generate useful outputs or actions.

OUTPUT
Output contains generated messages, tool calls, and other response items.

TOOLS
Tools extend models with search, files, code, computers, and MCP.

CONVERSATION
Conversations maintain related input and output items across multiple interactions.

MULTIMODAL
Multimodal capabilities let models process text and images within requests.

STREAMING
Streaming delivers response events progressively while model generation continues asynchronously.

STATE
State preserves relevant interaction information across connected model responses automatically.

JUDGMENT
Human judgment determines which generated outputs and actions deserve acceptance.


The Minimalist Responses API

You do not need to understand everything about the Responses API before you begin using it.

Remember ten things:

Responses.

Input.

Model.

Output.

Tools.

Conversation.

Multimodal.

Streaming.

State.

Judgment.

Everything else can come later.

Start with the input.

Choose the model.

Understand the output.

Add tools when needed.

Continue through conversation.

Use multimodal inputs when useful.

Stream responses when appropriate.

Maintain state across connected work.

Apply human judgment.

Then accomplish something.


One Final Question

The next time you build with the Responses API, don't begin with:

“Which API parameters should I use?”

Begin with:

“What do I want the model to accomplish?”

Then build the response.


Accomplish with AI

Powered by Blogger.

Featured post

AI Engineering Hands-On Lab #001 — Build an AI Answer Reliability Test Bench Without Code

AIYING | Daily 24 — Post 009 AI Engineering Hands-On Lab #001 Build an AI Answer Reliability Test Bench — Without Writing Code Lea...

Search This Blog

List of blogs

Search This Blog

About

Translate

Instant Stories

Read in Your Language

Test

share this

ShareThis

Popular Posts