# Generate Structured Output

These instructions apply to the legacy Admin Console.

The native Generate API, `POST /generate`, can return JSON instead of text. You describe the shape in one of two ways:

* **An inline JSON Schema**, in `schema`. Use it for any shape that your code needs, such as fields extracted from an invoice.
* **An Object Type**, in `objectType`. The API generates data for a new Record of that Object Type, based on the Object Type's current data schema.

The response has `generationType` set to `object`, and the result is in `object`. The examples use the base URL `https://ai-gateway.<tenant-id>.my.contextual.io/api/v1` and the request format in [Example request](https://docs.contextual.io/legacy/tenants/tenant-apis/ai-gateway-api.md#example-request).

## Choose a schema source

| | Inline JSON Schema | Object Type |
| --- | --- | --- |
| Request field | `schema` | `objectType` |
| Shape comes from | Your request | The Object Type's current data schema |
| Checked against the shape | Only if you set `validation.output` to `true` | Always |
| Generate only some fields | Write a smaller schema | List them in `objectType.fields` |
| Chat Completions endpoint | Supported, as a `json_schema` response format | Not supported |

The API never creates or changes Records. To save the result, send it to the [Native Object API](https://docs.contextual.io/legacy/tenants/tenant-apis/native-object-api.md) yourself.

## Generate JSON from a schema

Set `schema` to a JSON Schema. The API sends it to the provider as you wrote it, including optional properties and `additionalProperties`. This request extracts invoice details:

```json
{
  "route": "<ai-route-id>",
  "system": "Extract the invoice details from the text.",
  "prompt": "Invoice INV-2041 from Northwind Traders is due on 2026-12-01. The total is 1,250.00 USD.",
  "schemaName": "invoice",
  "schemaDescription": "Details of one invoice",
  "schema": {
    "type": "object",
    "properties": {
      "invoiceNumber": { "type": "string" },
      "vendor": { "type": "string" },
      "dueDate": { "type": "string", "description": "Due date as YYYY-MM-DD" },
      "total": { "type": "number" },
      "currency": { "type": "string" }
    },
    "required": ["invoiceNumber", "vendor", "total"],
    "additionalProperties": false
  },
  "validation": { "output": true }
}
```

A successful response includes fields like these. The values depend on the model:

```json
{
  "generationType": "object",
  "object": {
    "invoiceNumber": "INV-2041",
    "vendor": "Northwind Traders",
    "dueDate": "2026-12-01",
    "total": 1250,
    "currency": "USD"
  },
  "finishReason": "stop"
}
```

* **Names and descriptions:** `schemaName` and `schemaDescription` are optional. Some providers use them as extra guidance.
* **Lists:** To generate a list, set `output` to `array`. `schema` then describes one item, and `object` holds an array.
* **Validation:** Without `validation.output`, you receive the JSON as the model produced it. Set `validation.output` to `true` to check it against `schema`. Output that fails the check counts as a failed attempt, so the AI Route's retries and fallbacks apply. If the schema cannot be compiled, the API returns `400` before it calls a provider.
* **Provider support:** Providers support different parts of JSON Schema. Test your schema with each provider that your AI Route can select.

## Generate Record data for an Object Type

Set `objectType` to the Object Type's ID. This request generates data for a new Record of the `support-cases` Object Type:

```json
{
  "route": "<ai-route-id>",
  "system": "Create a support case from the customer's email.",
  "prompt": "Subject: Damaged item. My replacement blender arrived with a cracked jar. Order A-1001. - Dana Lee, dana@example.com",
  "objectType": { "id": "support-cases" }
}
```

When the request runs, the API reads the Object Type's current definition with your access token. Your token needs permission to read the definition, as listed in the [Native Object Registry API permissions](https://docs.contextual.io/legacy/tenants/tenant-apis/native-object-registry-api.md#authentication-and-permissions).

The result in `object` is a create payload: the body of a request that creates a Record. It leaves out:

* `_metaData`.
* Fields that the Native Object API generates when it creates the Record.
* Optional fields that the model left empty.

The API always checks the result against the payload that the Object Type accepts. Output that fails the check counts as a failed attempt, so the AI Route's retries and fallbacks apply.

The response's `objectType` field records the definition that the API used: its `id`, `version`, and `hash`, and a `schemaDigest` of the schema that the result was checked against. Compare `version` or `hash` with the definition you expect before you save the result.

To generate several payloads, set `output` to `array`. `object` then holds an array of payloads.

### Generate only some fields

To generate part of a Record, add `fields` to `objectType`. List each field as a path of field names:

```json
{
  "objectType": {
    "id": "invoices",
    "fields": [["invoiceNumber"], ["vendor", "name"], ["lineItems", "sku"]]
  }
}
```

* `["invoiceNumber"]` selects a top-level field.
* `["vendor", "name"]` selects `name` inside the `vendor` object.
* `["lineItems", "sku"]` passes through the `lineItems` array and selects `sku` in each item.

Every selected field is present in the result, and the result holds only the selected fields. It is not a complete Record, so combine it with your other data before you create a Record, or use it to update part of an existing Record.

You can't select a field that the Native Object API generates. If a selection can't be used, the API returns `422` and describes the problem. For example, a path can't pass through a part of the schema that uses `anyOf`. Select the containing field whole instead.

### Save the result as a Record

Send `object` as the body of a create request to the Object Type's endpoint in the Native Object API. The [generated reference](https://docs.contextual.io/legacy/tenants/tenant-apis/native-object-api.md#generated-reference-and-openapi) shows the create operation and the permission it needs. The Native Object API checks the data again when it creates the Record.

### Handle Object Type errors

| Status | Cause |
| --- | --- |
| `403` | Your token isn't allowed to read the Object Type. |
| `404` | The Object Type doesn't exist. |
| `422` | The Object Type's schema, or the selected fields, can't be used for structured output. |
| `502` | The API couldn't read the Object Type. |
| `503` | Object Type output isn't available on this server. |

## Set the output length

`maxTokens` is optional. If you omit it, the output limit depends on the provider and model. Set `maxTokens` to request an explicit output limit within the provider and model's supported limits. If the limit stops the model before the JSON is complete, the attempt fails, and the AI Route's fallbacks apply. Set the limit high enough for the largest result you expect.

## Handle the response

* **Pending tool calls:** If the request has `tools` and `finishReason` is `tool-calls`, the response has no `object` yet. Run the tools and continue, as described in [Run client tools over HTTP](https://docs.contextual.io/legacy/tenants/tenant-apis/ai-gateway-api/streaming-and-tool-calling.md#run-client-tools-over-http).
* **Warnings:** Check `warnings` for problems that did not stop generation, such as a setting that the provider ignored.
* **Files:** If the model generated files, such as images, `files` holds each one as base64 with its media type.
* **Response size:** `steps` contains each full provider request and response. To leave out the raw provider request bodies and response headers, set `sanitizeResponse` to `true`.
* **Streaming:** With `Accept: text/event-stream`, the API sends no partial JSON. The result arrives whole in the final `generate.response` event.

## Use the Chat Completions endpoint

If your code uses the [Chat Completions endpoint](https://docs.contextual.io/legacy/tenants/tenant-apis/ai-gateway-api.md#use-an-openai-chat-completions-client), set `response_format` to `{ "type": "json_schema", "json_schema": { "name": "invoice", "schema": { ... } } }`. The JSON arrives as text in `message.content`. Set `json_schema.strict` to `true` to check the output against the schema. The endpoint does not support Object Type output.
