Back to Prompting Recipes

Structured Output

FormatJSON

Format

Constrain model outputs to specific formats for reliable parsing and integration.

Summary

Structured Output prompting ensures LLM responses conform to predefined schemas or formats. By specifying output structures (JSON, XML, specific formats), outputs become machine-readable and directly usable in downstream systems. This technique reduces parsing errors and enables reliable integration with APIs and databases.

Common formats

  • JSON: API responses, data structures
  • Markdown: Documentation, formatted text
  • Tables: Tabular data presentation
  • Code blocks: Programming language output

Implementation approaches

  1. Explicit instruction: Describe format in natural language
  2. Schema specification: Provide JSON schema or type definition
  3. Few-shot examples: Show desired output format
  4. Constrained decoding: Use API-level format controls

Validation checklist

  • Schema matches actual output
  • Required fields are present
  • Type constraints are respected
  • Edge cases are handled
  • Error recovery is planned
Code View

Structured Output Implementation

// Structured Output recipe using OpenAI
// Install: bun add openai

import OpenAI from "openai";

async function main() {
  const input = "Add your prompt here.";
  const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
  const system = "You are a senior AI engineer and technical writer. Use the prompting technique to answer the request clearly and precisely. Recipe: Structured Output. Description: Constrain model outputs to specific formats for reliable parsing and integration. Focus: Format Provide actionable, implementation-ready guidance.";
  const user = `Request: ${input}`;

  const openaiResponse = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      { role: "system", content: system },
      { role: "user", content: user },
    ],
  });

  const openaiText = openaiResponse.choices[0]?.message?.content?.trim() ?? "";

  console.log(openaiText);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});