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

# Structured Outputs

# No More JSON Roulette

*When "close enough" isn't good enough for production*

Tired of AI models returning creative interpretations of your data schema? Structured outputs enforce JSON Schema validation so you get exactly what you ask for, every single time. No more parsing nightmares, no more defensive coding, no more production bugs from hallucinated field names.

## 🎯 The Problem with "Creative" AI

*When flexibility becomes a liability*

**The AI says:** "Sure, I'll return JSON!"\
**What you get:** `{"tempurature": 72, "wheather": "sunny", "humididty": "kinda high"}`\
**What you needed:** `{"temperature": 72, "weather": "sunny", "humidity": 65}`

**The result:** Your parser breaks, your app crashes, your users complain, your weekend disappears.

**Structured outputs fix this forever.**

## ✨ What You Get with Structured Outputs

### 🛡️ **Schema Enforcement**

The model MUST return exactly what you define—no creative license allowed.

### 🎯 **Type Safety**

Numbers are numbers, strings are strings, enums are enums. Period.

### 🚫 **Zero Hallucinated Fields**

`additionalProperties: false` means exactly what it says.

### ⚡ **Production-Ready Parsing**

Skip the defensive coding and error handling—just parse and go.

## 🚀 Getting Started: Your First Structured Response

### The Basic Setup

*From chaos to structure in one request*

```json theme={"system"}
{
  "model": "openai/gpt-4o-2024-11-20",
  "messages": [
    {
      "role": "user",
      "content": "What's the weather like in London today?"
    }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "weather_response",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "City and country (e.g., 'London, UK')"
          },
          "temperature": {
            "type": "number", 
            "description": "Temperature in Celsius"
          },
          "conditions": {
            "type": "string",
            "enum": ["sunny", "cloudy", "rainy", "snowy", "partly-cloudy"]
          },
          "humidity": {
            "type": "number",
            "minimum": 0,
            "maximum": 100,
            "description": "Humidity percentage"
          }
        },
        "required": ["location", "temperature", "conditions"],
        "additionalProperties": false
      }
    }
  }
}
```

**What you get back:**

```json theme={"system"}
{
  "location": "London, UK",
  "temperature": 18,
  "conditions": "cloudy", 
  "humidity": 72
}
```

**Every. Single. Time.** No surprises, no typos, no creative interpretations.

## 💻 Production-Ready Python Implementation

### The Complete Example

*Copy, paste, customize, ship*

```python theme={"system"}
import requests
from typing import Dict, Any, Optional

class StructuredAIClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.anyapi.ai/v1/chat/completions"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    def extract_product_review(self, review_text: str) -> Dict[str, Any]:
        """Extract structured data from product reviews"""
        payload = {
            "model": "openai/gpt-4o-2024-11-20",
            "messages": [
                {
                    "role": "user",
                    "content": f"Extract key information from this product review: {review_text}"
                }
            ],
            "response_format": {
                "type": "json_schema",
                "json_schema": {
                    "name": "product_review_analysis",
                    "strict": True,
                    "schema": {
                        "type": "object",
                        "properties": {
                            "product_type": {
                                "type": "string",
                                "description": "Type of product being reviewed"
                            },
                            "sentiment": {
                                "type": "string",
                                "enum": ["positive", "negative", "neutral"],
                                "description": "Overall sentiment of the review"
                            },
                            "rating": {
                                "type": "number",
                                "minimum": 1,
                                "maximum": 5,
                                "description": "Inferred rating from 1-5 stars"
                            },
                            "specs": {
                                "type": "object",
                                "properties": {
                                    "ram": {"type": "string"},
                                    "processor": {"type": "string"},
                                    "battery_life": {"type": "string"},
                                    "storage": {"type": "string"}
                                },
                                "additionalProperties": False
                            },
                            "price": {
                                "type": "number",
                                "description": "Price mentioned in the review"
                            },
                            "pros": {
                                "type": "array",
                                "items": {"type": "string"},
                                "description": "Positive aspects mentioned"
                            },
                            "cons": {
                                "type": "array", 
                                "items": {"type": "string"},
                                "description": "Negative aspects mentioned"
                            },
                            "recommended": {
                                "type": "boolean",
                                "description": "Whether the reviewer recommends the product"
                            }
                        },
                        "required": ["product_type", "sentiment", "rating", "recommended"],
                        "additionalProperties": False
                    }
                }
            }
        }
        
        response = requests.post(self.base_url, headers=self.headers, json=payload)
        response.raise_for_status()
        
        return response.json()["choices"][0]["message"]["content"]

# Usage
client = StructuredAIClient("your-api-key")

review = """
This laptop is incredible! The M2 chip blazes through everything I throw at it. 
16GB RAM handles multiple browser tabs and video editing smoothly. Battery easily 
lasts 10+ hours of real work. The 512GB SSD is plenty fast. At $1,299, it's 
expensive but worth every penny. Highly recommend for developers and creators!
"""

result = client.extract_product_review(review)
print(result)
# Guaranteed to match your schema exactly
```

## 🏗️ Advanced Schema Patterns

### Complex Nested Structures

*For when your data gets sophisticated*

```json theme={"system"}
{
  "response_format": {
    "type": "json_schema", 
    "json_schema": {
      "name": "financial_analysis",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "company": {
            "type": "object",
            "properties": {
              "name": {"type": "string"},
              "ticker": {"type": "string"},
              "sector": {"type": "string", "enum": ["tech", "finance", "healthcare", "energy", "retail"]}
            },
            "required": ["name", "ticker", "sector"],
            "additionalProperties": false
          },
          "metrics": {
            "type": "object", 
            "properties": {
              "revenue": {"type": "number", "minimum": 0},
              "profit_margin": {"type": "number", "minimum": -1, "maximum": 1},
              "debt_to_equity": {"type": "number", "minimum": 0}
            },
            "required": ["revenue"],
            "additionalProperties": false
          },
          "analysis": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "category": {"type": "string", "enum": ["growth", "profitability", "valuation", "risk"]},
                "score": {"type": "number", "minimum": 1, "maximum": 10},
                "reasoning": {"type": "string"},
                "confidence": {"type": "number", "minimum": 0, "maximum": 1}
              },
              "required": ["category", "score", "reasoning"],
              "additionalProperties": false
            }
          },
          "recommendation": {
            "type": "string",
            "enum": ["strong_buy", "buy", "hold", "sell", "strong_sell"]
          },
          "target_price": {"type": "number", "minimum": 0}
        },
        "required": ["company", "metrics", "analysis", "recommendation"],
        "additionalProperties": false
      }
    }
  }
}
```

### Data Extraction Powerhouse

*Turn messy text into clean, structured data*

```python theme={"system"}
def extract_invoice_data(invoice_text: str):
    """Extract structured data from invoice text"""
    schema = {
        "type": "json_schema",
        "json_schema": {
            "name": "invoice_extraction",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "invoice_number": {"type": "string"},
                    "date": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
                    "vendor": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string"},
                            "address": {"type": "string"},
                            "tax_id": {"type": "string"}
                        },
                        "required": ["name"],
                        "additionalProperties": False
                    },
                    "line_items": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "description": {"type": "string"},
                                "quantity": {"type": "number", "minimum": 0},
                                "unit_price": {"type": "number", "minimum": 0},
                                "total": {"type": "number", "minimum": 0}
                            },
                            "required": ["description", "quantity", "unit_price", "total"],
                            "additionalProperties": False
                        }
                    },
                    "subtotal": {"type": "number", "minimum": 0},
                    "tax_amount": {"type": "number", "minimum": 0},
                    "total_amount": {"type": "number", "minimum": 0}
                },
                "required": ["invoice_number", "date", "vendor", "line_items", "total_amount"],
                "additionalProperties": False
            }
        }
    }
    
    # Your extraction logic here
    return structured_request(invoice_text, schema)
```

## 🎯 Real-World Use Cases

### E-commerce Product Categorization

```python theme={"system"}
product_schema = {
    "type": "object", 
    "properties": {
        "category": {"type": "string", "enum": ["electronics", "clothing", "home", "books", "sports"]},
        "subcategory": {"type": "string"},
        "price_range": {"type": "string", "enum": ["budget", "mid_range", "premium", "luxury"]},
        "target_audience": {"type": "string", "enum": ["men", "women", "children", "unisex"]},
        "tags": {"type": "array", "items": {"type": "string"}},
        "confidence": {"type": "number", "minimum": 0, "maximum": 1}
    },
    "required": ["category", "price_range", "confidence"],
    "additionalProperties": False
}
```

### Customer Support Ticket Classification

```python theme={"system"}
support_schema = {
    "type": "object",
    "properties": {
        "urgency": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
        "category": {"type": "string", "enum": ["billing", "technical", "feature_request", "bug_report"]},
        "sentiment": {"type": "string", "enum": ["frustrated", "neutral", "satisfied"]},
        "requires_escalation": {"type": "boolean"},
        "estimated_resolution_time": {"type": "string", "enum": ["minutes", "hours", "days", "weeks"]},
        "key_issues": {"type": "array", "items": {"type": "string"}},
        "suggested_actions": {"type": "array", "items": {"type": "string"}}
    },
    "required": ["urgency", "category", "sentiment", "requires_escalation"],
    "additionalProperties": False
}
```

## 🛡️ Pro Tips for Schema Design

### ✅ **Do This:**

```json theme={"system"}
{
  "properties": {
    "temperature": {
      "type": "number",
      "minimum": -50,
      "maximum": 60,
      "description": "Temperature in Celsius, realistic range for weather"
    },
    "status": {
      "type": "string", 
      "enum": ["active", "inactive", "pending"],
      "description": "Current status, must be one of the predefined values"
    }
  }
}
```

### ❌ **Avoid This:**

```json theme={"system"}
{
  "properties": {
    "temperature": {"type": "string"},  // Use proper types!
    "status": {"type": "string"},       // Use enums for limited values!
    "extra_field": {}                   // Define everything explicitly!
  },
  "additionalProperties": true          // This defeats the purpose!
}
```

### 🎯 **Schema Design Principles:**

1. **Be Specific:** Use enums, ranges, and patterns liberally
2. **Add Descriptions:** Guide the model with clear field descriptions
3. **Enforce Types:** Don't accept strings when you need numbers
4. **Block Extras:** Always use `"additionalProperties": false`
5. **Require What Matters:** Mark critical fields as required
6. **Validate Constraints:** Use min/max, patterns, and format validations

## 🚨 Model Compatibility & Error Handling

### Compatible Models

**✅ Full Support:**

* OpenAI GPT-4 series ([gpt-4o](https://anyapi.ai/ai-models/openai-gpt-4o), [gpt-4-turbo](https://anyapi.ai/ai-models/openai-gpt-4-turbo))
* Anthropic [Claude 3.5 Sonnet](https://anyapi.ai/ai-models/anthropic-claude-3-5-sonnet)
* Select fine-tuned models

**⚠️ Limited Support:**

* Some open-source models
* Older model versions

**❌ No Support:**

* Legacy models (GPT-3.5 and older)
* Many specialized/smaller models

### Bulletproof Error Handling

```python theme={"system"}
def safe_structured_request(content: str, schema: dict, model: str = "openai/gpt-4o"):
    """Make structured requests with proper error handling"""
    try:
        response = make_structured_request(content, schema, model)
        return {"success": True, "data": response}
        
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 400:
            error_data = e.response.json()
            if "structured outputs not supported" in error_data.get("error", {}).get("message", ""):
                return {
                    "success": False, 
                    "error": "Model doesn't support structured outputs",
                    "suggestion": "Try openai/gpt-4o or anthropic/claude-3.5-sonnet"
                }
            else:
                return {
                    "success": False,
                    "error": "Invalid schema", 
                    "details": error_data
                }
        else:
            raise  # Re-raise other HTTP errors
            
    except Exception as e:
        return {"success": False, "error": f"Unexpected error: {e}"}
```

## 💡 Advanced Patterns

### Schema Composition

```python theme={"system"}
# Reusable schema components
ADDRESS_SCHEMA = {
    "type": "object",
    "properties": {
        "street": {"type": "string"},
        "city": {"type": "string"},
        "country": {"type": "string", "pattern": "^[A-Z]{2}$"}
    },
    "required": ["street", "city", "country"],
    "additionalProperties": False
}

PERSON_SCHEMA = {
    "type": "object", 
    "properties": {
        "name": {"type": "string"},
        "email": {"type": "string", "format": "email"},
        "address": ADDRESS_SCHEMA  # Compose schemas
    },
    "required": ["name", "email"],
    "additionalProperties": False
}
```

### Dynamic Schema Generation

```python theme={"system"}
def generate_extraction_schema(fields: list) -> dict:
    """Generate extraction schemas dynamically"""
    properties = {}
    required = []
    
    for field in fields:
        if field["required"]:
            required.append(field["name"])
            
        properties[field["name"]] = {
            "type": field["type"],
            "description": field["description"]
        }
        
        if field.get("enum"):
            properties[field["name"]]["enum"] = field["enum"]
    
    return {
        "type": "object",
        "properties": properties,
        "required": required,
        "additionalProperties": False
    }

# Usage
fields = [
    {"name": "product_name", "type": "string", "required": True, "description": "Name of the product"},
    {"name": "category", "type": "string", "required": True, "enum": ["electronics", "clothing"], "description": "Product category"},
    {"name": "price", "type": "number", "required": False, "description": "Product price"}
]

schema = generate_extraction_schema(fields)
```

***

*Ready to eliminate JSON parsing nightmares? Start enforcing structure with AnyAPI structured outputs.*
