# Structured output

Get answers as JSON that follows your schema.

When code reads the answer, ask for JSON. On [chat completions](https://ewest.ai/docs/chat), `response_format` tells the model to answer in JSON, and with a schema, in JSON of the shape you describe. The answer is then in `choices[0].message.content` as a string that you parse.

## The two formats

| response_format | What you get | Use it when |
| --- | --- | --- |
| `{"type": "json_schema", "json_schema": {...}}` | JSON that follows your schema. `json_schema` needs a `name` (1 to 64 letters, digits, `_` or `-`) and a `schema` (a JSON Schema object). `strict: true` is recommended. | You know the fields you need. This is the one to use. |
| `{"type": "json_object"}` | A JSON object, but with no fixed shape. Describe the fields you want in the prompt, and the word JSON helps. | You cannot write a schema. Expect a code fence around the JSON from some models, and fields of the wrong type. |

cURL:

```bash
curl https://api.ewest.ai/v1/chat/completions \
  -H "Authorization: Bearer $EWEST_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "ewest/gemini-flash",
       "max_tokens": 1024,
       "messages": [{"role": "user", "content": "Extract the person: Ana is 31 years old."}],
       "response_format": {
         "type": "json_schema",
         "json_schema": {
           "name": "person",
           "strict": true,
           "schema": {
             "type": "object",
             "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
             "required": ["name", "age"],
             "additionalProperties": false}}}}'
```

Python:

```python
import json, os, requests

PERSON = {
    "name": "person",
    "strict": True,
    "schema": {
        "type": "object",
        "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
        "required": ["name", "age"],
        "additionalProperties": False,
    },
}

def extract(text):
    res = requests.post(
        "https://api.ewest.ai/v1/chat/completions",
        headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"},
        json={
            "model": "ewest/gemini-flash",
            "max_tokens": 1024,
            "messages": [{"role": "user", "content": f"Extract the person: {text}"}],
            "response_format": {"type": "json_schema", "json_schema": PERSON},
        },
        timeout=100,
    )
    res.raise_for_status()
    choice = res.json()["choices"][0]
    if choice["finish_reason"] != "stop":  # "length" means the JSON was cut off: raise max_tokens
        raise RuntimeError(f"incomplete answer: {choice['finish_reason']}")
    data = json.loads(choice["message"]["content"])
    # Check what your code relies on, even when the schema is strict.
    if not isinstance(data.get("name"), str) or not isinstance(data.get("age"), int):
        raise ValueError(f"unexpected shape: {data}")
    return data

print(extract("Ana is 31 years old."))
```

JavaScript:

```javascript
const person = {
  name: "person",
  strict: true,
  schema: {
    type: "object",
    properties: { name: { type: "string" }, age: { type: "integer" } },
    required: ["name", "age"],
    additionalProperties: false,
  },
};

async function extract(text) {
  const res = await fetch("https://api.ewest.ai/v1/chat/completions", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "ewest/gemini-flash",
      max_tokens: 1024,
      messages: [{ role: "user", content: `Extract the person: ${text}` }],
      response_format: { type: "json_schema", json_schema: person },
    }),
  });
  if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
  const choice = (await res.json()).choices[0];
  // "length" means the JSON was cut off: raise max_tokens.
  if (choice.finish_reason !== "stop") throw new Error(`incomplete answer: ${choice.finish_reason}`);
  const data = JSON.parse(choice.message.content);
  // Check what your code relies on, even when the schema is strict.
  if (typeof data.name !== "string" || !Number.isInteger(data.age)) throw new Error(`unexpected shape: ${JSON.stringify(data)}`);
  return data;
}

console.log(await extract("Ana is 31 years old."));
```

## Which models

There is no `supports_*` flag for structured output in the catalog, so it cannot be read from the model data. We ran the `json_schema` request above against these chat models, and each returned JSON that matched: `ewest/claude-haiku`, `ewest/claude-sonnet`, `ewest/claude-opus`, `ewest/claude-haiku-5.5`, `ewest/gemini-flash` and `ewest/deepseek-v4.1-flash`. A schema with an enum, an array and nested objects also matched on `ewest/claude-haiku`, `ewest/gemini-flash` and `ewest/deepseek-v4.1-flash`. Not yet tested: `ewest/gemini-3.8-flash` and `ewest/gemini-4-argon`, so do not assume they behave the same. A model may write the keys in a different order than your schema. With `json_object`, the Claude models answered with the JSON inside a Markdown code fence, and `ewest/gemini-flash` wrote a number as a string, so parse defensively. Test your own schema on the model you plan to use before you rely on it.

## Strict schemas

- Set `strict: true`, list every property under `required`, and set `additionalProperties: false` on each object.
- Stay with plain types: object, array, string, number, integer, boolean, `enum` and nesting. Rules such as `minimum` or `pattern` are hints at best: models can ignore them, so check those values in your code.
- A schema does not make the content true. The model can fill a valid field with a wrong value, so validate what matters to you.
- Streaming works with `response_format`: the JSON arrives in pieces, and is complete only at the end, so parse it once the stream is done.

## When it goes wrong

- **Cut off:** if the answer hits `max_tokens` it has `finish_reason: "length"` and the JSON stops half-way, so it will not parse. Check `finish_reason` first and raise `max_tokens`. Models that think first use part of the limit for it; 1024 is a good start, and more if you set `reasoning_effort` (a limit that is too small for it is a `400` that names the minimum).
- **Not valid or not the right shape:** wrap `JSON.parse` / `json.loads` in a try, check the fields you use, and on failure retry once or twice. A retry can give a different answer. Do not retry a `400`, which means the request itself must change (see [Errors](https://ewest.ai/docs/errors)).
- **A malformed format:** `type` must be `text` (the default), `json_object` or `json_schema`. We check the format before any model is called and answer `400` with `param` pointing at the problem, such as `response_format.json_schema.schema`, and code `invalid_value`, `invalid_type` or `missing_required_parameter`. Fix the request; do not retry it. The same checks apply to `text.format` on Responses, where the fields are flat (`param` such as `text.format.schema`). We do not check the schema itself, so parse every answer, even when the request looked right.
- **Other endpoints:** `POST /v1/responses` takes the same schema as `text.format` (`{"type": "json_schema", "name", "strict", "schema"}`). For tool arguments in a fixed shape, see [Tool calling](https://ewest.ai/docs/tool-calling).

Source: https://ewest.ai/docs/structured-output
