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

# Structured output

> Generate reliable JSON with JSON mode or JSON schema and validate every model response in your application.

Structured output makes model responses easier to parse and integrate. Depending on the selected model, use JSON object mode or a strict JSON schema.

## Request a JSON object

Tell the model to produce JSON and set `response_format`. Some models require an explicit instruction containing the word “JSON.”

<CodeGroup>
  ```bash Curl theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl https://api.yelu.ai/v1/chat/completions \
    -H "Authorization: Bearer $YELU_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-4o-mini",
      "messages": [
        {"role":"system","content":"Return valid JSON with keys summary and priority."},
        {"role":"user","content":"The checkout API returns 503 for five percent of requests."}
      ],
      "response_format": {"type":"json_object"},
      "temperature": 0
    }'
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await fetch('https://api.yelu.ai/v1/chat/completions', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.YELU_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [
        { role: 'system', content: 'Return valid JSON with keys summary and priority.' },
        { role: 'user', content: 'The checkout API returns 503 for five percent of requests.' },
      ],
      response_format: { type: 'json_object' },
      temperature: 0,
    }),
  });
  if (!response.ok) throw new Error(await response.text());
  const result = JSON.parse((await response.json()).choices[0].message.content);
  console.log(result);
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import json
  import os
  import requests

  response = requests.post(
      "https://api.yelu.ai/v1/chat/completions",
      headers={"Authorization": f"Bearer {os.environ['YELU_API_KEY']}"},
      json={
          "model": "gpt-4o-mini",
          "messages": [
              {"role": "system", "content": "Return valid JSON with keys summary and priority."},
              {"role": "user", "content": "The checkout API returns 503 for five percent of requests."},
          ],
          "response_format": {"type": "json_object"},
          "temperature": 0,
      },
      timeout=60,
  )
  response.raise_for_status()
  result = json.loads(response.json()["choices"][0]["message"]["content"])
  print(result)
  ```
</CodeGroup>

## Use JSON schema

On models that support strict structured output, send `response_format.type = json_schema` with a named schema:

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "type": "json_schema",
  "json_schema": {
    "name": "incident_triage",
    "strict": true,
    "schema": {
      "type": "object",
      "properties": {
        "summary": {"type": "string"},
        "priority": {"type": "string", "enum": ["low", "medium", "high", "critical"]}
      },
      "required": ["summary", "priority"],
      "additionalProperties": false
    }
  }
}
```

## Validate at the boundary

Even strict output can be interrupted by content filtering, output limits, network failure, or provider-specific behavior. Your application should:

1. check the HTTP response and finish status;
2. parse JSON with size and depth limits;
3. validate against the same schema used in the request;
4. reject unknown fields when they are unsafe;
5. apply domain validation, such as ranges and cross-field rules;
6. handle refusals and truncated output separately from schema failures.

## JSON mode versus schema

| Capability              | JSON object                        | JSON schema                               |
| ----------------------- | ---------------------------------- | ----------------------------------------- |
| Valid JSON syntax       | Intended                           | Intended                                  |
| Required keys and types | Prompt-dependent                   | Enforced when strict support is available |
| Model availability      | Broader                            | Narrower                                  |
| Best use                | Flexible extraction and prototypes | Production data contracts                 |

<Warning>
  Never interpolate model-produced JSON into SQL, shell commands, HTML, or authorization rules without context-specific escaping and validation.
</Warning>
