> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sudoapp.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Structured Output

> JSON schema validation and structured data extraction

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

## Basic Structured Output

### Simple JSON Schema

<CodeGroup dropdown>
  ```typescript TypeScript theme={null}
  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();
  ```

  ```python Python theme={null}
  import os
  import json
  from sudo import Sudo

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

  with Sudo(
      server_url="https://sudoapp.dev/api",
      api_key=os.getenv("SUDO_API_KEY"),
  ) as client:
      response = client.router.create(
          model="gpt-4o",
          messages=[
              {
                  "role": "user",
                  "content": "Create a person profile for a software engineer named Alice"
              }
          ],
          response_format={
              "type": "json_schema",
              "json_schema": {
                  "name": "person",
                  "schema": person_schema,
                  "strict": True
              }
          }
      )
      
      # Parse the structured response
      person_data = json.loads(response.choices[0].message.content)
      print(f"Name: {person_data['name']}")
      print(f"Age: {person_data['age']}")
      print(f"Email: {person_data['email']}")
      print(f"Skills: {', '.join(person_data['skills'])}")
  ```
</CodeGroup>

## Complex Data Extraction

### Product Information Extraction

<CodeGroup dropdown>
  ```typescript TypeScript theme={null}
  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();
  ```

  ```python Python theme={null}
  import os
  import json
  from sudo import Sudo

  # Complex schema for product data
  product_schema = {
      "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},
                      "in_stock": {"type": "boolean"}
                  },
                  "required": ["name", "price", "category", "in_stock"]
              }
          },
          "total_count": {"type": "integer"},
          "average_price": {"type": "number"}
      },
      "required": ["products", "total_count"]
  }

  def extract_product_data(text):
      """Extract structured product data from text"""
      with Sudo(
          server_url="https://sudoapp.dev/api",
          api_key=os.getenv("SUDO_API_KEY"),
      ) as client:
          response = client.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": f"Extract product data from this text: {text}"
                  }
              ],
              response_format={
                  "type": "json_schema",
                  "json_schema": {
                      "name": "product_extraction",
                      "schema": product_schema,
                      "strict": True
                  }
              }
          )
          
          return json.loads(response.choices[0].message.content)

  # Example usage
  product_text = """
  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
  """

  result = extract_product_data(product_text)
  print(f"Found {result['total_count']} products:")
  for product in result['products']:
      print(f"- {product['name']}: ${product['price']} ({'In Stock' if product['in_stock'] else 'Limited Stock'})")
  ```
</CodeGroup>

## Next Steps

1. **[Image Input](/sdk/sudo-sdk/image-input)** - Work with multimodal inputs
2. **[Reasoning](/sdk/sudo-sdk/reasoning)** - Advanced reasoning capabilities
3. **[CRUD Operations](/sdk/sudo-sdk/crud-operations)** - Manage stored completions

<Note>
  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.
</Note>
