# Structured outputs

> Use response_format to make the model answer with JSON that matches your schema, or with any valid JSON object, so your code can use the result directly.

When a program consumes the model's answer, you want JSON in a known shape rather than free text. That is what `response_format` is for. Lykia accepts the field in OpenAI's format. OpenAI-compatible providers receive it as it is; for Anthropic and Google AI Studio, Lykia translates it into their own format (Anthropic has no equivalent of `json_object`, so that mode is dropped there). If the model supports it, the answer follows the schema you gave.

There are two modes:

- **`json_schema`**: the answer matches the JSON Schema you provide, including field names, types and required fields.
- **`json_object`**: the answer is a valid JSON object, but its shape is not constrained by a schema; you describe the shape in the prompt.

## Pick a model that supports it

A model supports `json_schema` when `structured_outputs` appears in its `supported_parameters`, and accepts the `response_format` field when `response_format` does. Filter the catalog by these values:

```bash
# Models whose supported_parameters include "structured_outputs"
curl "https://api.getlykia.com/v1/models?supported_parameters=structured_outputs" \
  -H "Authorization: Bearer $LYKIA_API_KEY"
```

What happens if you send `response_format` to a model without support depends on the model and the provider. Choose from this list up front, and check your fallback models too if you use them.

## With a JSON Schema

Set `response_format.type` to `"json_schema"` and put your schema under `json_schema.schema`:

**Request**

cURL

```bash
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [
      { "role": "user", "content": "Extract the order: two large lattes and one croissant, to go." }
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "order",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "items": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "name": { "type": "string" },
                  "quantity": { "type": "integer" },
                  "size": { "type": ["string", "null"] }
                },
                "required": ["name", "quantity", "size"],
                "additionalProperties": false
              }
            },
            "takeaway": { "type": "boolean" }
          },
          "required": ["items", "takeaway"],
          "additionalProperties": false
        }
      }
    }
  }'
```

Python

```python
import json
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

schema = {
    "type": "object",
    "properties": {
        "items": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "quantity": {"type": "integer"},
                    "size": {"type": ["string", "null"]},
                },
                "required": ["name", "quantity", "size"],
                "additionalProperties": False,
            },
        },
        "takeaway": {"type": "boolean"},
    },
    "required": ["items", "takeaway"],
    "additionalProperties": False,
}

completion = client.chat.completions.create(
    model="openai/gpt-4o-mini",
    messages=[{"role": "user", "content": "Extract the order: two large lattes and one croissant, to go."}],
    response_format={"type": "json_schema", "json_schema": {"name": "order", "strict": True, "schema": schema}},
)

order = json.loads(completion.choices[0].message.content)
print(order["items"], order["takeaway"])
```

TypeScript

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

const schema = {
  type: "object",
  properties: {
    items: {
      type: "array",
      items: {
        type: "object",
        properties: {
          name: { type: "string" },
          quantity: { type: "integer" },
          size: { type: ["string", "null"] },
        },
        required: ["name", "quantity", "size"],
        additionalProperties: false,
      },
    },
    takeaway: { type: "boolean" },
  },
  required: ["items", "takeaway"],
  additionalProperties: false,
};

const completion = await client.chat.completions.create({
  model: "openai/gpt-4o-mini",
  messages: [{ role: "user", content: "Extract the order: two large lattes and one croissant, to go." }],
  response_format: { type: "json_schema", json_schema: { name: "order", strict: true, schema } },
});

const order = JSON.parse(completion.choices[0].message.content ?? "{}");
console.log(order.items, order.takeaway);
```

**Response (200)**

```json
{
  "id": "gen-1795373697-8Qya37ShK5Hzkwlz",
  "object": "chat.completion",
  "created": 1795373697,
  "model": "openai/gpt-4o-mini",
  "provider": "openai",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"items\":[{\"name\":\"latte\",\"quantity\":2,\"size\":\"large\"},{\"name\":\"croissant\",\"quantity\":1,\"size\":null}],\"takeaway\":true}"
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 96,
    "completion_tokens": 31,
    "total_tokens": 127,
    "cost": 0.000033,
    "is_byok": false,
    "cost_details": {
      "upstream_cost": 0.000033,
      "platform_fee": 0,
      "is_byok": false
    },
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "cache_write_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0
    }
  },
  "system_fingerprint": "fp_560af6e559"
}
```

The JSON comes back as a **string** in `message.content`; parse it before use.

- `response_format` (object) — The shape of the answer.
  - `type` (string, required) — `"json_schema"` or `"json_object"`.
  - `json_schema` (object) — Required when `type` is `"json_schema"`.
    - `name` (string, required) — Name of the schema: letters, digits, underscores and dashes.
    - `strict` (boolean) — When `true`, the model follows the schema exactly. In strict mode every object must list all of its properties in `required` and set `additionalProperties: false`; model an optional field with a type like `["string", "null"]`.
    - `schema` (object) — The JSON Schema.

## JSON object mode

If you do not need a specific schema, ask for any valid JSON object with `{ "type": "json_object" }`. In this mode, say in the prompt that you expect JSON and which keys you want:

```bash
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [
      { "role": "system", "content": "Reply with a JSON object with the keys \"language\" and \"confidence\"." },
      { "role": "user", "content": "Bugün hava çok güzel." }
    ],
    "response_format": { "type": "json_object" }
  }'
```

## Practical notes

- **Validate anyway.** Even with support, an answer cut off by `max_tokens` is incomplete JSON (`finish_reason: "length"`). Catch parse errors and validate against your schema.
- **Keep schemas lean.** Deep nesting and long `enum` lists add prompt tokens.
- **Describe your fields.** `description` entries in the schema help the model fill fields correctly.
- **Tools or structured output?** If you want the model to ask your code to run a function, use [tool calling](https://www.getlykia.com/en/docs/guides/tool-calling). If you want the answer itself in a fixed shape, use structured outputs.

## Next steps

- [Tool calling](https://www.getlykia.com/en/docs/guides/tool-calling): let the model call your functions.
- [Models](https://www.getlykia.com/en/docs/models): read model capabilities from the catalog.
- [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions): reference for `response_format`.
