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

# Create chat completion

> Generate a response for the given chat conversation

Call 100+ models from different providers through one API. Set `model` to `auto` to choose a model automatically based on criteria such as price, latency, or performance.

For conditional routing, A/B testing across variants, or reusable configurations, [**create a router**](https://docs.inworld.ai/api-reference/routerAPI/routerservice/create-router.md). Set the `model` field to `inworld/<router-id>`, for example `inworld/my-router`.

To use web search in an answer, set [`web_search`](https://docs.inworld.ai/router/capabilities/web-search.md) at the top level of the request or, with the OpenAI SDK, in `extra_body`.

To generate and save images, see [Image generation](https://docs.inworld.ai/router/image-generation.md), including reference images and model-specific output settings.

For voice output, see [Voice responses](https://docs.inworld.ai/router/guides/llm-plus-tts.md), including [optional word or character timestamps](https://docs.inworld.ai/router/guides/llm-plus-tts.md#optional-timestamps).

## API reference

**Endpoint:** `POST https://api.inworld.ai/v1/chat/completions`

### Authorization

- `Authorization` (string; required) — Your [authentication](../../../api-reference/introduction) credentials. For Basic authentication, please populate `Basic $INWORLD_API_KEY`.
  
  A standard API key can call chat completions, the Responses and Messages APIs, moderation and Decisions. To create, update or delete routers, the key also needs [write permissions for the Router API](https://docs.inworld.ai/portal/api-keys.md#key-permissions). You can create a key in one command with the [Inworld CLI](../../../developer-tools/inworld-cli): `inworld workspace add-key`.

### Request body

Content type: `application/json`

- `model` (string; required) — The model to use, which can be:
  - A model id (e.g., `deepseek-v4-flash`). The best provider is [automatically selected](https://docs.inworld.ai/router/capabilities/provider-routing.md) by latency, or you can control provider selection via `extra_body.provider`. See [Models](https://docs.inworld.ai/api-reference/modelsAPI/modelservice/list-models.md) for available models.
  - A provider-prefixed model id (e.g., `openai/gpt-5.4`): the List models entry's `provider`, `/`, then its `model`. This specifies the provider and model to use. When the model name itself contains a `/`, keep the provider in front (e.g., `groq/openai/gpt-oss-120b`): the router reads the part before the first `/` as the provider when it names one, so `openai/gpt-oss-120b` asks the provider `openai` for it.
  - A model hosted by Inworld, as `inworld/models/<name>` (e.g., `inworld/models/deepseek-v4-flash`).
  - `auto` for automatic model selection based on criteria like price, latency, or intelligence
  - A router, which is specified by `inworld/<router-name>`. The router `name` must be prefixed by `inworld/`.
  
  See [Model ids](https://docs.inworld.ai/router/capabilities/request-level.md#model-ids).
- `messages` (object[]; required) — A list of messages comprising the conversation so far.
  
  If using a router where a prompt is specified, these messages will be appended to the prompt.
  - `role` (enum<string>; required; options: "system", "user", "assistant", "tool") — The role of the message author.
  - `content` (oneOf) — The content of the message. Can be a string for text-only messages, an array of content parts for multimodal messages, or null for assistant messages with tool_calls.
  - `tool_calls` (object[]) — Tool calls generated by the model (assistant messages only).
    - `id` (string; required) — ID of the tool call.
    - `type` (enum<string>; required; options: "function") — The type of the tool call. Always 'function'.
    - `function` (object; required) — The function that the model called.
      - `name` (string; required) — The name of the function to call.
      - `arguments` (string; required) — The arguments to call the function with, as a JSON string.
  - `tool_call_id` (string) — Tool call ID this message is responding to (tool role only).
  - `cache_control` (object) — Marks this whole message as the end of a block to cache, for Anthropic and Google models, when `content` is a string. For multipart content, put `cache_control` on a content part. See [Prompt caching](https://docs.inworld.ai/router/capabilities/caching.md#tools-whole-messages-and-the-whole-request).
    - `type` (enum<string>; options: "ephemeral")
    - `ttl` (string) — Cache lifetime, such as `5m` or `1h`. Anthropic accepts only `5m` and `1h`. Without it, the provider's default applies.
    - `cache_id` (string) — Google models only: keeps a separate cache for each value. Without it, a workspace has one explicit cache per model.
  - `compression` (object) — Prompt compression for this message only. Ignored when the request or the router variant sets `compression`, which applies to every compressible message instead. Tool-result messages are never compressed. See [Prompt compression](https://docs.inworld.ai/router/capabilities/prompt-compression.md).
    - `aggressiveness` (number; default: 0.5) — How strongly to compress this message. Higher values save more tokens but may reduce fidelity. `0` disables compression.
- `stream` (boolean; default: false) — If true, partial message deltas will be sent as server-sent events. For image output, Google AI Studio and OpenAI support streaming; Google Vertex requires false. Read image output from `choices[].delta.images`. See [Image generation](https://docs.inworld.ai/router/image-generation.md#stream-image-output).
- `stream_options` (object) — Streaming options. Usage is streamed whenever the provider reports it, with or without this field. `include_usage: true` only changes the shape of the usage chunk: its `choices` array is empty, as in OpenAI's API. Without it, that chunk has one choice with an empty `delta`. See [Streaming](https://docs.inworld.ai/router/capabilities/streaming.md#usage).
  - `include_usage` (boolean)
- `temperature` (number; default: 1) — Sampling temperature between 0 and 2. Higher values make output more random.
- `top_p` (number) — Nucleus sampling parameter. Must be greater than 0.
- `max_tokens` (integer) — Maximum number of tokens to generate.
- `max_completion_tokens` (integer) — Maximum number of completion tokens to generate.
- `presence_penalty` (number; default: 0) — Penalizes tokens based on presence in the text.
- `frequency_penalty` (number; default: 0) — Penalizes tokens based on frequency in the text.
- `seed` (integer) — Random seed for generation.
- `stop` (oneOf) — A sequence, or a list of sequences, where the model stops generating.
- `logit_bias` (object) — Map of token id (as a string) to a bias from -100 to 100, as in OpenAI's API. Values outside that range are clamped.
- `tools` (object[]) — Tools the model may call, in OpenAI's format (`{"type": "function", "function": {...}}`). `function.strict` is sent only to models whose provider enforces it; other models do not receive it. See [Tool calling](https://docs.inworld.ai/router/capabilities/tool-calling.md#differences-from-openai).
- `parallel_tool_calls` (boolean) — Set to `false` to ask for at most one tool call per turn. Sent to the provider only when the request has `tools`. OpenAI and Anthropic models honor it; Google models ignore it.
- `tool_choice` (oneOf) — `auto`, `none`, `required`, a named tool (`{"type": "function", "function": {"name": "..."}}`) or an `allowed_tools` object, as in OpenAI's API. `any` is read as `required`. Any other value returns `400`. Some models cannot be forced to call a tool; see [Tool calling](https://docs.inworld.ai/router/capabilities/tool-calling.md#control-when-tools-are-called).
- `response_format` (object) — Structured output: `{"type": "json_object"}` or `{"type": "json_schema", "json_schema": {...}}`, as in OpenAI's API. Anthropic models have no JSON mode: they drop `json_object`, without an error, and answer in ordinary text. Use `json_schema` with a schema there. See [Structured outputs](https://docs.inworld.ai/router/capabilities/structured-outputs.md#provider-behavior).
- `n` (integer) — Not supported. Only one choice is returned; the parameter is ignored. For image output, set the number of images with `image_config.n`.
- `logprobs` (boolean) — Not supported. The parameter is ignored.
- `top_logprobs` (integer) — Not supported. The parameter is ignored, like `logprobs`. It is still validated: without `logprobs: true`, or outside 0 to 20, the request returns `400`.
- `top_k` (integer) — Sample from the k most likely tokens, for models that support it.
- `min_p` (number) — Minimum token probability relative to the most likely token, for models that support it.
- `repetition_penalty` (number) — Penalty for repeated tokens, for models that support it.
- `prompt_cache_key` (string) — OpenAI's prompt cache key. What it does depends on the model generation: on earlier OpenAI models it helps route requests that share a prefix to the same cache, and on newer ones it keeps cache accounting separate, for example per customer; see [OpenAI's prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching#prompt-cache-keys). Passed to OpenAI and Azure OpenAI models only; other providers do not receive it. See [Prompt caching](https://docs.inworld.ai/router/capabilities/caching.md#implicit-caching).
- `prompt_cache_retention` (string) — OpenAI's prompt cache retention policy, such as `in_memory` or `24h`. Passed to OpenAI and Azure OpenAI models only. Accepted values depend on the model; see [OpenAI's prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching).
- `cache_control` (object) — Anthropic models only: one request-wide cache breakpoint. Anthropic puts it on the last cacheable block and moves it forward as the conversation grows. Other providers ignore it. To mark a block yourself, put `cache_control` on a text content part, on a message whose `content` is a string, or on a `tools` entry instead. See [Prompt caching](https://docs.inworld.ai/router/capabilities/caching.md#tools-whole-messages-and-the-whole-request).
  - `type` (enum<string>; options: "ephemeral")
  - `ttl` (string) — Cache lifetime: `5m` (the default) or `1h`.
- `compression` (object) — Prompt compression for this request. Compresses every compressible message and overrides a router variant's setting; `{"aggressiveness": 0}` turns compression off. Compression is not billed; `usage.prompt_tokens` counts the compressed prompt. It currently drops `cache_control` on the parts it rewrites. Can also be sent in `extra_body`. See [Prompt compression](https://docs.inworld.ai/router/capabilities/prompt-compression.md).
  - `aggressiveness` (number; default: 0.5) — How strongly to compress. Higher values save more tokens but may reduce fidelity. `0` disables compression.
- `session` (string) — An optional session id for grouping the requests of one conversation. Printable ASCII, up to 128 characters; `default` is reserved. Can also be sent in `extra_body`.
- `metadata` (object) — Request metadata, available to a saved router's [conditional routing](https://docs.inworld.ai/router/capabilities/conditional-routing.md) expressions and prompt templates. Can also be sent in `extra_body`.
- `reasoning_effort` (enum<string>; options: "none", "minimal", "low", "medium", "high", "xhigh", "max") — How much reasoning the model does, for models that support it. Case-insensitive. An unrecognized value is ignored, and for a model that does not support reasoning effort the parameter is dropped with a warning in `metadata.attempts[].warnings`. Takes precedence over `extra_body.reasoning.effort`.
- `user` (string) — A stable id for your end user. When `model` is a saved router, it keeps a user on the same traffic-splitting variant; without it, the variant is chosen at random per request. It is not forwarded to the provider.
- `web_search` (object) — Web search configuration, at the top level or in `extra_body`. With a router-run engine (`exa`, `brave` or `google`), the LLM calls a search engine in a tool-calling loop, then synthesizes a grounded answer with `url_citation` annotations; this works with any LLM that supports tool calling. With `engine: "native"`, the provider's built-in search is used. Mutually exclusive with `web_search_options`. See [Web search](https://docs.inworld.ai/router/capabilities/web-search.md) for details.
  - `engine` (enum<string>; default: "exa"; options: "exa", "brave", "google", "native") — Search backend: `exa`, `brave` or `google`, or `native` for the provider's built-in search.
  - `max_results` (integer; default: 3) — Search results per search call, 1 to 10.
  - `max_steps` (integer; default: 1) — Maximum search rounds before the final answer, 1 to 5.
- `web_search_options` (object) — Native web search using the provider's built-in search grounding (no tool loop). Supported by OpenAI, Azure OpenAI (search models only), Anthropic, Google / Vertex AI, and Groq. Mutually exclusive with `web_search`. See [Web Search](https://docs.inworld.ai/router/capabilities/web-search.md) for details.
  - `search_context_size` (enum<string>; options: "low", "medium", "high") — How much web context to retrieve. Defaults to `medium`. Used by OpenAI and Azure OpenAI; on Anthropic it sets how many searches the model can run; Google and Groq ignore it.
- `modalities` (enum<string>[]) — Output modalities to generate. Include `"image"` to request image generation (e.g., `["text", "image"]`); `["image"]` alone also works. Supported by models whose `spec.outputModalities` in the [List models API](https://docs.inworld.ai/api-reference/modelsAPI/modelservice/list-models.md) includes `image` (filter with `?output_modalities=image`). When omitted, a model that generates images uses its catalog output modalities, so it still returns images; other models return text. When set without `"image"`, an image model returns no images.
- `image_config` (object) — Configuration for image output. Optional; applies when `modalities` includes `"image"`, or when `modalities` is omitted and the model generates images.
  - `aspect_ratio` (string) — Aspect ratio for the generated image (e.g., `1:1`, `16:9`, `9:16`). Supported by Google models only, when the request has no reference image. Inworld ignores it, without an error, for other providers and when the request includes a reference image.
  - `image_size` (string) — Size of the generated image. 
    - Google: model-specific sizes such as `1K` or `2K`.
    - OpenAI: pixel dimensions as WxH (e.g., `1024x1024`).
  - `partial_images` (integer) — Number of partial/progressive image previews during streaming, from 0 to 3. Only used with `stream: true`. When unset, OpenAI sends no previews, only the final image. Supported by OpenAI models only. Inworld passes the value to the provider as sent; OpenAI rejects a value outside 0 to 3, and other providers ignore the field.
  - `n` (integer) — Number of images to generate. In a non-streaming response, every image is in `choices[0].message.images`; Inworld returns one choice.
    - Google: image models return one image. Inworld passes a larger value to Google, which can reject it.
    - OpenAI: 1 to 10.
- `extra_body` (object) — Optional parameters for model routing and optimization.
  - `models` (string[]) — Model ids for fallbacks, or the candidate pool for `auto`. Fallbacks are tried in the order listed unless `sort` is set. A bare provider name (for example `openai`) stands for all of that provider's models. Write a model hosted by Inworld as `inworld/<name>` here, the form responses use. `auto` is not allowed here: at the top level it returns 400, and inside `extra_body` it matches no model.
  - `ignore` (string[]) — Providers or models to exclude from selection. A `provider/model` named in `model` is never excluded; for a bare model id, `ignore` can exclude its providers. Without `models`, and with any `model` but `auto` or a saved router, setting `ignore` also adds every other catalog model it doesn't exclude as a fallback, so it can reach other providers. With `model: "inworld/<router-id>"`, the router replaces the request's `models`, `ignore`, `sort` and `provider` with the selected variant's settings, so request-level `ignore` has no effect. See [Use only one provider](https://docs.inworld.ai/router/capabilities/provider-routing.md#use-only-one-provider). `auto` is not allowed here: at the top level it returns 400, and inside `extra_body` it matches no model.
  - `sort` (string[]) — The sorting strategy for `auto` selection, fallbacks, and the providers of a model named without a provider prefix: `price`, `latency`, `throughput`, `intelligence`, `math`, `coding`. Add `_asc` or `_desc` to set the direction (for example `latency_desc`). In a request, `sort` is an array of strings; a saved router's `model_selection.sort` uses `SortCriteria` objects instead.
  - `reasoning` (object) — Reasoning configuration. `effort` applies only when the top-level `reasoning_effort` is not set.
    - `effort` (enum<string>; options: "none", "minimal", "low", "medium", "high", "xhigh", "max")
    - `max_tokens` (integer) — Reasoning token budget, for models that take one.
    - `exclude` (boolean) — Leave the reasoning text out of the response. Only Anthropic models act on it; other models ignore it. See [Reasoning](https://docs.inworld.ai/router/capabilities/reasoning.md#read-the-reasoning).
  - `provider` (object) — Provider routing configuration. Works on any request; no router is needed. Use when `model` is specified without a provider prefix (e.g., `deepseek-v4-flash`) to control which providers are tried and in what order. Ignored when `model` has a provider prefix or is `auto`. See [Provider routing](https://docs.inworld.ai/router/capabilities/provider-routing.md).
    - `order` (string[]) — Explicit list of providers to try, in order. Example: ["deepseek", "inworld"]. When specified, providers are tried in this exact order (`sort` criteria will be ignored), and providers not in the list are not used.
    - `allow_fallbacks` (boolean; default: true) — Whether to allow falling back to the next provider if the current one fails. Defaults to true.
  - `prompt_variables` (object) — Variables for the prompt templates of a [saved router](https://docs.inworld.ai/api-reference/routerAPI/routerservice/create-router.md) (not for messages sent with each request). Values can be any JSON type. They are also available to conditional routing expressions, where `metadata` wins on a name clash. See [prompt templates](https://docs.inworld.ai/router/core-concepts/overview.md#prompt-templates).
  - `web_search` (object) — For OpenAI SDK compatibility, pass `web_search` via `extra_body` (equivalent to setting it at the top level). Web search configuration. Mutually exclusive with `web_search_options`. See [Web Search](https://docs.inworld.ai/router/capabilities/web-search.md) for details.
    - `engine` (enum<string>; default: "exa"; options: "exa", "brave", "google", "native") — Search backend: `exa`, `brave` or `google`, or `native` for the provider's built-in search.
    - `max_results` (integer; default: 3) — Search results per search call, 1 to 10.
    - `max_steps` (integer; default: 1) — Maximum search rounds before the final answer, 1 to 5.
  - `web_search_options` (object) — For OpenAI SDK compatibility, pass `web_search_options` via `extra_body` (equivalent to setting it at the top level). Native web search grounding. Mutually exclusive with `web_search`. See [Web Search](https://docs.inworld.ai/router/capabilities/web-search.md) for details.
    - `search_context_size` (enum<string>; options: "low", "medium", "high") — How much web context to retrieve. Defaults to `medium`. Used by OpenAI and Azure OpenAI; on Anthropic it sets how many searches the model can run; Google and Groq ignore it.
  - `fallback` (object) — Fall back to the next model when the first token is slow.
    - `ttft_timeout` (string; required) — A duration of at least `300ms`, for example `"800ms"` or `"1.5s"`.
  - `session` (string) — Same as the top-level `session`.
  - `metadata` (object) — Same as the top-level `metadata`.
  - `compression` (object) — Prompt compression for this request. See [prompt compression](https://docs.inworld.ai/router/capabilities/prompt-compression.md).
- `audio` (object) — Convert the generated text to Inworld TTS audio. Supports streaming and non-streaming requests. See [LLM + TTS](https://docs.inworld.ai/router/guides/llm-plus-tts.md).
  - `voice` (string; required) — Voice ID for speech synthesis.
  - `model` (string; required) — Inworld TTS model ID; must start with inworld-. Independent of the top-level LLM model.
  - `format` (enum<string>; default: "pcm16"; options: "pcm16", "mulaw", "alaw") — Encoding of the returned audio: pcm16 (16-bit signed little-endian PCM), mulaw (G.711 µ-law) or alaw (G.711 A-law). All are mono and headerless. Any other value returns 400.
  - `sample_rate` (integer) — Output sample rate in Hz. pcm16 accepts 8000, 16000, 22050, 24000, 32000, 44100 or 48000 (default 48000); mulaw and alaw accept 8000 only, the default. Any other value returns 400.
  - `timestamp_type` (enum<string>; options: "word", "character") — Opt into timing entries for words or characters. Values are lowercase. Omit to disable timestamps. Alignment can add latency.

#### Request example

```json
{
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ],
  "extra_body": {
    "models": [
      "openai/gpt-4o-mini",
      "google-ai-studio/gemini-2.5-flash-lite"
    ],
    "sort": [
      "price"
    ]
  }
}
```

### Response

Status: `200`. Content type: `application/json`.

- `id` (string) — Unique identifier for the chat completion.
- `object` (string) — Object type, always 'chat.completion'.
- `created` (integer) — Unix timestamp when the completion was created.
- `model` (string) — The model that was actually used.
- `choices` (object[]) — List of chat completion choices.
  - `index` (integer)
  - `message` (object)
    - `role` (string) — Always 'assistant' for responses.
    - `content` (string) — The generated text. Can be empty when the model returns image output without accompanying text, only tool calls, or Inworld TTS audio (read `audio.transcript` for the spoken text).
    - `images` (object[]) — Generated images, when image output is requested. Several images from `image_config.n` share this one array. An image may be returned without text in `content`. See [Image generation](https://docs.inworld.ai/router/image-generation.md) for saving images.
      - `type` (enum<string>; options: "image_url")
      - `image_url` (object)
        - `url` (string) — A base64 image data URL, such as `data:image/png;base64,...`, or a download URL. The format is the one the model returns, usually PNG, and a data URL names it in its media type. No request field chooses the output format.
    - `tool_calls` (object[]) — Tool calls generated by the model (when using tools).
      - `id` (string)
      - `type` (string)
      - `function` (object)
        - `name` (string)
        - `arguments` (string)
    - `audio` (object) — Synthesized Inworld TTS audio in a non-streaming completion. The message content is empty; the spoken text is in transcript.
      - `id` (string) — Identifier for the generated audio.
      - `data` (string) — Base64-encoded mono, headerless audio in the requested audio.format, at the requested audio.sample_rate. Defaults: pcm16 (16-bit little-endian) at 48,000 Hz; mulaw and alaw are always 8,000 Hz.
      - `transcript` (string) — The synthesized text.
      - `timestamps` (object[]) — Timing entries when audio.timestamp_type was requested and alignment is available. Times refer to the complete response audio.
        - `token` (string; required) — Word or character associated with this timing entry.
        - `start_time` (number; required) — Start time in seconds from the beginning of the complete response audio, including preceding sentences.
        - `end_time` (number; required) — End time in seconds from the beginning of the complete response audio, including preceding sentences.
    - `reasoning` (string) — The model's reasoning text, for reasoning models that return it.
    - `annotations` (object[]) — Citations, for example `url_citation` entries from [web search](https://docs.inworld.ai/router/capabilities/web-search.md).
  - `finish_reason` (enum<string>; options: "stop", "length", "tool_calls", "content_filter") — Why the model stopped.
- `usage` (object) — Token usage statistics.
  - `prompt_tokens` (integer) — Tokens in the prompt.
  - `completion_tokens` (integer) — Tokens in the completion.
  - `total_tokens` (integer) — Total tokens used.
  - `prompt_tokens_details` (object) — Always includes `cached_tokens` (prompt tokens read from cache). `cache_write_tokens`, `audio_tokens`, `image_tokens` and `text_tokens` appear when nonzero.
    - `cached_tokens` (integer) — Prompt tokens read from the cache, billed at the model's `pricing.promptCacheReadToken`. `0` when nothing was read. See [Prompt caching](https://docs.inworld.ai/router/capabilities/caching.md#how-caching-is-billed).
    - `cache_write_tokens` (integer) — Prompt tokens written to a new cache entry, billed at the model's `pricing.promptCacheWriteToken`. On Google models with explicit caching, the request that writes the cache also reads it, so `cached_tokens` reports the same tokens. Inworld bills nothing for how long a cache is kept.
    - `audio_tokens` (integer) — Prompt tokens from audio input, when the provider reports them. Part of `prompt_tokens`.
    - `image_tokens` (integer) — Prompt tokens from image input, such as reference images for image generation, when the provider reports them. Part of `prompt_tokens`, billed at `pricing.promptToken`.
    - `text_tokens` (integer) — Prompt tokens from text, when the provider reports them. Part of `prompt_tokens`.
  - `completion_tokens_details` (object) — `reasoning_tokens`, `audio_tokens`, `image_tokens` and `text_tokens` appear when nonzero. For image output, `image_tokens` counts the tokens of the generated images. They are part of `completion_tokens` and billed at the model's output rate (`pricing.completionToken` in the List models API).
    - `reasoning_tokens` (integer) — Output tokens spent on reasoning. Part of `completion_tokens`.
    - `audio_tokens` (integer) — Output tokens of generated audio, when the provider reports them. Part of `completion_tokens`.
    - `image_tokens` (integer) — Output tokens of generated images, when the provider reports them. Part of `completion_tokens`, billed at `pricing.completionToken`.
    - `text_tokens` (integer) — Output tokens of generated text, when the provider reports them. Part of `completion_tokens`.
- `metadata` (object) — Routing metadata providing transparency into model selection decisions.
  - `attempts` (object[]) — List of model attempts, including both successful and failed attempts.
    - `model` (string) — The `provider/model` identifier that was attempted, for example `openai/gpt-5.2`. The prefix is the provider.
    - `success` (boolean) — Whether this attempt succeeded.
    - `time_to_first_token_ms` (integer) — Time to receive the first token in milliseconds.
    - `status_code` (integer) — HTTP status of a failed attempt.
    - `error` (string) — Why the attempt failed.
    - `duration_ms` (number) — Duration of the attempt in milliseconds.
    - `warnings` (string[]) — Notes about the attempt, for example parameters skipped because the model does not support them.
  - `generation_id` (string) — Unique identifier for tracing this request in the Inworld Portal.
  - `reasoning` (string) — Human-readable explanation of why a model was selected based on the routing strategy.
  - `total_duration_ms` (integer) — Total request duration in milliseconds. Not included on streamed responses, where `metadata` arrives on the first chunk.
  - `route_id` (string) — The saved router's route that was chosen, when `model` is a saved router.
  - `variant_id` (string) — The saved router's variant that was chosen, when `model` is a saved router.
  - `compression_warnings` (string[]) — Warnings from [prompt compression](https://docs.inworld.ai/router/capabilities/prompt-compression.md), when it ran. Non-streaming responses only.
  - `compression` (object) — Stats from [prompt compression](https://docs.inworld.ai/router/capabilities/prompt-compression.md), present when at least one message was compressed. Non-streaming responses only.
    - `original_tokens` (integer)
    - `compressed_tokens` (integer)
    - `saved_tokens` (integer)

### Response examples

#### 200: Direct model call

```json
{
  "id": "chatcmpl-1772347141924",
  "object": "chat.completion",
  "created": 1772347141,
  "model": "openai/gpt-4o",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I assist you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 9,
    "total_tokens": 18
  },
  "metadata": {
    "attempts": [
      {
        "model": "openai/gpt-4o",
        "success": true,
        "time_to_first_token_ms": 428
      }
    ],
    "generation_id": "9b365b38-f09f-96d1-8c77-99b28c8b74bf",
    "reasoning": "Using specified model: 'openai/gpt-4o' - success",
    "total_duration_ms": 472
  }
}
```

#### 200: Auto model selection

```json
{
  "id": "chatcmpl-339374ec-d6f8-464b-ab93-fc2dcb14fecd",
  "object": "chat.completion",
  "created": 1767996520,
  "model": "google-ai-studio/gemini-2.5-flash-lite",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 2,
    "completion_tokens": 10,
    "total_tokens": 12
  },
  "metadata": {
    "attempts": [
      {
        "model": "google-ai-studio/gemini-2.5-flash-lite",
        "success": true,
        "time_to_first_token_ms": 245
      }
    ],
    "generation_id": "019bb4a8-5523-789b-a795-12b47052a2d9",
    "reasoning": "Auto-selected 'google-ai-studio/gemini-2.5-flash-lite', from specified models, sorted by lowest price - success",
    "total_duration_ms": 312
  }
}
```

#### 200: Using a router

```json
{
  "id": "chatcmpl-1772348076987",
  "object": "chat.completion",
  "created": 1772348076,
  "model": "google-ai-studio/gemini-3-flash-preview",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 3,
    "completion_tokens": 98,
    "total_tokens": 101
  },
  "metadata": {
    "attempts": [
      {
        "model": "google-ai-studio/gemini-3-flash-preview",
        "success": true,
        "time_to_first_token_ms": 1037
      }
    ],
    "generation_id": "1360075d-3ca3-9248-897a-5cb78df2ee7d",
    "reasoning": "Using specified model: 'google-ai-studio/gemini-3-flash-preview' - success",
    "route_id": "default",
    "variant_id": "gemini",
    "total_duration_ms": 1038
  }
}
```

#### 200: Web search (tool-based)

```json
{
  "id": "chatcmpl-1774895681858",
  "object": "chat.completion",
  "created": 1774895681,
  "model": "openai/gpt-4o",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Recent developments in Mars exploration have revealed significant discoveries by NASA's Perseverance rover...",
        "annotations": [
          {
            "type": "url_citation",
            "url_citation": {
              "content": "NASA's Perseverance Rover Finds Ancient River Delta on Mars...",
              "title": "NASA's Perseverance Rover Finds Ancient River Delta on Mars",
              "url": "https://example.com/mars-exploration"
            }
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 2829,
    "completion_tokens": 384,
    "total_tokens": 3213
  },
  "metadata": {
    "attempts": [
      {
        "model": "openai/gpt-4o",
        "success": true,
        "time_to_first_token_ms": 4645
      }
    ],
    "generation_id": "896d6bb3-0e1b-4fc5-b9fd-3340e60e9033",
    "reasoning": "Using specified model: 'openai/gpt-4o' - success",
    "total_duration_ms": 4645
  }
}
```

#### 400: default_response

```json
{
  "error": {
    "message": "'model' field is required",
    "type": "invalid_request_error",
    "code": "string",
    "param": "string"
  }
}
```

#### 401: default_response

```json
"Unauthorized"
```

#### 402: default_response

```json
{
  "error": {
    "message": "'model' field is required",
    "type": "invalid_request_error",
    "code": "string",
    "param": "string"
  }
}
```

#### 404: default_response

```json
{
  "error": {
    "message": "'model' field is required",
    "type": "invalid_request_error",
    "code": "string",
    "param": "string"
  }
}
```

#### 415: default_response

```json
{
  "error": {
    "message": "'model' field is required",
    "type": "invalid_request_error",
    "code": "string",
    "param": "string"
  }
}
```

#### 429: default_response

```json
{
  "error": {
    "message": "'model' field is required",
    "type": "invalid_request_error",
    "code": "string",
    "param": "string"
  }
}
```

#### 503: default_response

```json
{
  "error": {
    "message": "'model' field is required",
    "type": "invalid_request_error",
    "code": "string",
    "param": "string"
  }
}
```

#### 504: default_response

```json
{
  "error": {
    "message": "'model' field is required",
    "type": "invalid_request_error",
    "code": "string",
    "param": "string"
  }
}
```

### Code examples

#### cURL

```curl
curl --request POST \
  --url https://api.inworld.ai/v1/chat/completions \
  --header 'Authorization: <api_key>' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ],
  "extra_body": {
    "models": [
      "openai/gpt-4o-mini",
      "google-ai-studio/gemini-2.5-flash-lite"
    ],
    "sort": [
      "price"
    ]
  }
}'
```

#### Python

```python
import requests

url = "https://api.inworld.ai/v1/chat/completions"
payload = {
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ],
  "extra_body": {
    "models": [
      "openai/gpt-4o-mini",
      "google-ai-studio/gemini-2.5-flash-lite"
    ],
    "sort": [
      "price"
    ]
  }
}
headers = {
  "Authorization": "<api_key>",
  "Content-Type": "application/json"
}

response = requests.request("POST", url, json=payload, headers=headers)

print(response.text)
```

#### JavaScript

```javascript
const options = {method: 'POST', headers: {"Authorization":"<api_key>","Content-Type":"application/json"}, body: JSON.stringify({
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ],
  "extra_body": {
    "models": [
      "openai/gpt-4o-mini",
      "google-ai-studio/gemini-2.5-flash-lite"
    ],
    "sort": [
      "price"
    ]
  }
})};

fetch('https://api.inworld.ai/v1/chat/completions', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));
```

#### Direct model call

```bash
curl --location 'https://api.inworld.ai/v1/chat/completions' \
--header "Authorization: Basic $INWORLD_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "openai/gpt-4o",
  "messages": [{"role": "user", "content": "Hello!"}]
}'
```

#### Auto model selection

```bash
curl --location 'https://api.inworld.ai/v1/chat/completions' \
--header "Authorization: Basic $INWORLD_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "auto",
  "messages": [{"role": "user", "content": "Hello!"}],
  "extra_body": {
    "models": ["openai/gpt-4o-mini", "google-ai-studio/gemini-2.5-flash-lite"],
    "sort": ["price"]
  }
}'
```

#### Using a router

```bash
curl --location 'https://api.inworld.ai/v1/chat/completions' \
--header "Authorization: Basic $INWORLD_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "inworld/my-router",
  "messages": [{"role": "user", "content": "Hello!"}]
}'
```

#### Image generation

```bash
curl --location 'https://api.inworld.ai/v1/chat/completions' \
--header "Authorization: Basic $INWORLD_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "google-ai-studio/gemini-nano-banana-2.1",
  "messages": [{"role": "user", "content": "Generate an image of a cat"}],
  "modalities": ["text", "image"],
  "image_config": {
    "aspect_ratio": "16:9"
  }
}'
```

#### Web search (tool-based)

```bash
curl --location 'https://api.inworld.ai/v1/chat/completions' \
--header "Authorization: Basic $INWORLD_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "openai/gpt-4o",
  "messages": [{"role": "user", "content": "Latest news on Mars exploration"}],
  "web_search": {
    "engine": "exa",
    "max_results": 5,
    "max_steps": 2
  }
}'
```
