Structured output ensures AI responses conform to specific JSON schemas, enabling reliable data extraction and integration with applications.

Basic Structured Output

Simple JSON Schema

TypeScript
import { Sudo } from "sudo-ai";

const sudo = new Sudo({
  serverURL: "https://sudoapp.dev/api",
  apiKey: process.env.SUDO_API_KEY ?? "",
});

// Define a JSON schema for a person
const personSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "integer" },
    email: { type: "string", format: "email" },
    skills: {
      type: "array",
      items: { type: "string" }
    }
  },
  required: ["name", "age", "email"]
};

// Define TypeScript interface for type safety
interface Person {
  name: string;
  age: number;
  email: string;
  skills: string[];
}

async function basicStructuredOutput() {
  try {
    const response = await sudo.router.create({
      model: "gpt-4o",
      messages: [
        {
          role: "user",
          content: "Create a person profile for a software engineer named Alice"
        }
      ],
      responseFormat: {
        type: "json_schema",
        jsonSchema: {
          name: "person",
          schema: personSchema,
          strict: true
        }
      }
    });
    
    // Parse the structured response
    const personData: Person = JSON.parse(response.choices[0].message.content);
    console.log(`Name: ${personData.name}`);
    console.log(`Age: ${personData.age}`);
    console.log(`Email: ${personData.email}`);
    console.log(`Skills: ${personData.skills.join(', ')}`);
  } catch (error) {
    console.error("Structured output error:", error);
  }
}

basicStructuredOutput();

Complex Data Extraction

Product Information Extraction

TypeScript
import { Sudo } from "sudo-ai";

const sudo = new Sudo({
  serverURL: "https://sudoapp.dev/api",
  apiKey: process.env.SUDO_API_KEY ?? "",
});

// Complex schema for product data
const productSchema = {
  type: "object",
  properties: {
    products: {
      type: "array",
      items: {
        type: "object",
        properties: {
          name: { type: "string" },
          price: { type: "number" },
          category: { type: "string" },
          features: {
            type: "array",
            items: { type: "string" }
          },
          rating: { type: "number", minimum: 0, maximum: 5 },
          inStock: { type: "boolean" }
        },
        required: ["name", "price", "category", "inStock"]
      }
    },
    totalCount: { type: "integer" },
    averagePrice: { type: "number" }
  },
  required: ["products", "totalCount"]
};

// Define TypeScript interfaces for type safety
interface Product {
  name: string;
  price: number;
  category: string;
  features?: string[];
  rating?: number;
  inStock: boolean;
}

interface ProductExtraction {
  products: Product[];
  totalCount: number;
  averagePrice?: number;
}

async function extractProductData(text: string): Promise<ProductExtraction | null> {
  try {
    const response = await sudo.router.create({
      model: "gpt-4o",
      messages: [
        {
          role: "system",
          content: "Extract product information from the given text and format it according to the specified schema."
        },
        {
          role: "user",
          content: `Extract product data from this text: ${text}`
        }
      ],
      responseFormat: {
        type: "json_schema",
        jsonSchema: {
          name: "product_extraction",
          schema: productSchema,
          strict: true
        }
      }
    });
    
    return JSON.parse(response.choices[0].message.content) as ProductExtraction;
  } catch (error) {
    console.error("Product extraction error:", error);
    return null;
  }
}

// Example usage
async function productExtractionExample() {
  const productText = `
We have several laptops available:
1. MacBook Pro 16" - $2499, excellent performance, 16GB RAM, M2 chip, in stock
2. Dell XPS 13 - $1299, ultraportable, 8GB RAM, Intel i7, limited stock
3. ThinkPad X1 - $1899, business laptop, 16GB RAM, excellent keyboard, in stock
`;

  const result = await extractProductData(productText);
  if (result) {
    console.log(`Found ${result.totalCount} products:`);
    result.products.forEach(product => {
      console.log(`- ${product.name}: $${product.price} (${product.inStock ? 'In Stock' : 'Limited Stock'})`);
    });
  }
}

productExtractionExample();

Next Steps

  1. Image Input - Work with multimodal inputs
  2. Reasoning - Advanced reasoning capabilities
  3. CRUD Operations - Manage stored completions
Structured output works best with models that support JSON schema validation like GPT-4o, Claude Sonnet-4, and other recent models. Both TypeScript and Python SDKs provide excellent type safety and validation capabilities for structured data extraction.