# Audio generations Source: https://www.airouter.in/docs/api-reference/audio-generations > POST /v1/audio/generations — generate music or sound effects from a text description, billed per second of generated audio. ``` POST https://api.airouter.in/v1/audio/generations ``` Describe the music or sound you want and get an audio file back. For speaking a script aloud, use [audio speech](https://www.airouter.in/docs/api-reference/audio-speech) instead. Requires an API key and a [paid plan](https://www.airouter.in/docs/concepts/plans). No streaming and no `Idempotency-Key` support. Zero data retention does not apply: every response carries `X-AIRouter-ZDR: false`, and a `zdr` field is ignored. Rate limit: 60 requests per minute per key. ## Request ```bash curl https://api.airouter.in/v1/audio/generations \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "elevenlabs/music-v2.5", "prompt": "Warm lo-fi hip hop beat with soft piano chords.", "duration_seconds": 30, "instrumental": true }' | jq -r .audio | base64 -d > music.mp3 ``` A sound effect: ```bash curl https://api.airouter.in/v1/audio/generations \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "elevenlabs/sound-effects-v2", "prompt": "A wooden door slams shut.", "duration_seconds": 2 }' | jq -r .audio | base64 -d > door.mp3 ``` ### Body | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `model` | `string` | Yes | | Must be a model of type audio. Anything else returns 400. | | `prompt` | `string` | Yes | | A description of the music or sound, up to 4,000 characters. Prompts that name an artist are refused by the provider. | | `duration_seconds` | `number` | No | | Length of the audio. Music: 3 to 300, default 15. Sound effects: 0.5 to 30; omit it to let the model choose. | | `response_format` | `"mp3" \| "wav"` | No | | Default mp3. Music models produce mp3 only. | | `instrumental` | `boolean` | No | | Music only. Leave out vocals. | | `loop` | `boolean` | No | | Sound effects only. Make a clip that repeats without a gap. | | `prompt_influence` | `number` | No | | Sound effects only, 0 to 1. How closely the result follows the prompt. | ## Models | Model | Makes | Price / min | Length | Formats | | --- | --- | --- | --- | --- | | `elevenlabs/music-v2.5` | Music | $0.15 | 3–300 s, default 15 | mp3 | | `elevenlabs/music-v2` | Music | $0.15 | 3–300 s, default 15 | mp3 | | `elevenlabs/sound-effects-v2` | Sound effects | $0.12 | 0.5–30 s, or the model's choice | mp3, wav | Prices were current in November 2026; the [models page](https://www.airouter.in/models?type=audio) always shows the live price. 300 seconds of music took about 25 seconds to generate in testing. ## Response ```json { "id": "gen_6f1c3b2e-8a4d-4f0e-9b7a-2c5d1e3f4a6b", "object": "audio.generation", "model": "elevenlabs/music-v2.5", "format": "mp3", "content_type": "audio/mpeg", "duration_seconds": 30.04, "audio": "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYx...", "usage": { "seconds": 30.04 } } ``` `audio` is the file, base64-encoded. Decode it and save it with the `format` extension. `usage.seconds` is the length billed. A slow generation still returns `200`. After 90 seconds the response starts with whitespace while the audio is prepared; JSON parsers ignore it. ## Billing Billed **per second of generated audio**, at the price listed on the [models page](https://www.airouter.in/models?type=audio). The length you ask for is what you get, within a few hundredths of a second, so a 30-second track at $0.0025 per second costs about $0.075. When a sound effect's length is left to the model, credits for 30 seconds are held during the request and only the real length is charged. A `loop` clip can come out slightly longer than requested (2 s gave 2.25 s); the real length is what is billed. ## Errors | Status | Example message | | --- | --- | | `400` | `prompt is required: a description of the music or sound to generate` | | `400` | `Unsupported parameter: input. The description goes in "prompt".` | | `400` | `Model "elevenlabs/music-v2.5" makes 3 to 300 seconds of audio.` | | `400` | `Model "elevenlabs/music-v2.5" produces only mp3 audio.` | | `400` | `loop is only used by sound-effect models; "elevenlabs/music-v2.5" is a music model.` | | `400` | `Model "openai/tts-1" is a text-to-speech model. Use POST /v1/audio/speech instead.` | | `400` | `Audio generation failed for "...": the provider returned HTTP 400: Your prompt appears to have violated our Terms of Service. ...` | | `401` | `Invalid, disabled, or revoked API key` | | `402` | `Insufficient credits. This request requires up to $0.061710.` | | `403` | `Audio generation requires a paid plan. Add credits to unlock all models.` | | `429` | `Too many concurrent requests for this API key (max 20).` | | `429` | `API key spending limit reached` | | `502` | `Audio generation failed for "...": the provider returned HTTP : ` | | `504` | `Audio generation for "..." did not finish within 300 seconds. You were not charged.` | Validation errors carry the failing field in `param`. A failed request is never charged: the credits reserved for it are returned. # Audio speech Source: https://www.airouter.in/docs/api-reference/audio-speech > POST /v1/audio/speech — turn text into spoken audio with one of 19 text-to-speech models, in OpenAI's request format, billed per character. ``` POST https://api.airouter.in/v1/audio/speech ``` Send text and get an audio file back. The request is OpenAI's `audio/speech` format, so the OpenAI SDK's `client.audio.speech.create()` works with only the base URL and key changed. The response body is the audio file itself, not JSON. Requires an API key and a [paid plan](https://www.airouter.in/docs/concepts/plans). Up to 5,000 characters per request (less on some [models](#models)). No streaming and no `Idempotency-Key` support. Zero data retention does not apply: every response carries `X-AIRouter-ZDR: false`, and a `zdr` field is ignored. Rate limit: 60 requests per minute per key. ## Request ```bash curl https://api.airouter.in/v1/audio/speech \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/tts-1", "input": "Welcome to AI Router. One key for every model.", "voice": "nova", "response_format": "mp3" }' \ --output speech.mp3 ``` With the OpenAI SDK: ```ts import OpenAI from "openai"; import { writeFile } from "node:fs/promises"; const client = new OpenAI({ baseURL: "https://api.airouter.in/v1", apiKey: process.env.AIROUTER_API_KEY, }); const speech = await client.audio.speech.create({ model: "microsoft/mai-voice-2-flash", input: "Welcome to AI Router. One key for every model.", voice: "en-US-Harper", response_format: "mp3", }); await writeFile("speech.mp3", Buffer.from(await speech.arrayBuffer())); ``` ### Body | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `model` | `string` | Yes | | Must be a model of type speech. Anything else returns 400. | | `input` | `string` | Yes | | The text to speak. Up to 5,000 characters; 4,096 on OpenAI models and 2,500 on eleven-v3 and eleven-v4. | | `voice` | `string` | No | | A voice name or id for the model's provider (see Voices). Optional: each model has a default voice. | | `response_format` | `"mp3" \| "opus" \| "aac" \| "flac" \| "wav"` | No | | Audio format. Default mp3. Each model supports only some formats (see Models); opus is returned in an Ogg container. | | `speed` | `number` | No | | Speaking speed, where 1 is normal. Only on models that support it, within their range (see Models). | `instructions`, `stream_format: "sse"` and `response_format: "pcm"` return `400`. None of the models follow instructions, and raw PCM has a different sample rate on each model. Use `wav`, which carries the same audio with a header. ## Models | Model | Price / 1K chars | Formats | Speed | Max chars | | --- | --- | --- | --- | --- | | `fish-audio/drama-3` | $0.01 | mp3, opus, wav | 0.5–2 | 5,000 | | `fish-audio/s1` | $0.015 | mp3, opus, wav | 0.5–2 | 5,000 | | `fish-audio/s2-pro` | $0.015 | mp3, opus, wav | 0.5–2 | 5,000 | | `fish-audio/s2.1-pro` | $0.015 | mp3, opus, wav | 0.5–2 | 5,000 | | `microsoft/mai-voice-2-flash` | $0.015 | mp3, opus, wav | 0.5–2 | 5,000 | | `microsoft/mai-voice-2.1-flash` | $0.015 | mp3, opus, wav | 0.5–2 | 5,000 | | `openai/tts-1` | $0.015 | mp3, opus, aac, flac, wav | 0.25–4 | 4,096 | | `spacexai/grok-tts` | $0.015 | mp3, wav | 0.7–1.5 | 5,000 | | `mistral/voxtral-mini-tts-3` | $0.016 | mp3, opus, flac, wav | — | 5,000 | | `microsoft/mai-voice-2` | $0.022 | mp3, opus, wav | 0.5–2 | 5,000 | | `microsoft/mai-voice-2.1` | $0.022 | mp3, opus, wav | 0.5–2 | 5,000 | | `openai/tts-1-hd` | $0.03 | mp3, opus, aac, flac, wav | 0.25–4 | 4,096 | | `elevenlabs/eleven-flash-v2` | $0.04 | mp3, wav | 0.7–1.2 | 5,000 | | `elevenlabs/eleven-flash-v2.5` | $0.04 | mp3, wav | 0.7–1.2 | 5,000 | | `elevenlabs/eleven-v3-conversational` | $0.04 | mp3, wav | — | 5,000 | | `elevenlabs/eleven-v4-turbo` | $0.04 | mp3, wav | — | 5,000 | | `elevenlabs/eleven-multilingual-v2` | $0.08 | mp3, wav | 0.7–1.2 | 5,000 | | `elevenlabs/eleven-v3` | $0.08 | mp3, wav | — | 2,500 | | `elevenlabs/eleven-v4` | $0.08 | mp3, wav | — | 2,500 | Prices were current in November 2026; the [models page](https://www.airouter.in/models?type=speech) always shows the live price. A format, speed or length a model does not support returns `400` before anything is charged. The 2,500-character limit on eleven-v3 and eleven-v4 is there because they take about a minute per 2,500 characters, and the audio has to arrive within two minutes. ## Voices Each provider has its own voices. These are verified to work; the provider's own voice library has more. | Provider | Default | Example voices | | --- | --- | --- | | OpenAI | `alloy` | `alloy`, `ash`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, `shimmer` | | Microsoft | `en-US-Harper` | `en-US-Harper`, `en-US-Ethan`, `de-DE-Mia`, `es-MX-Valeria`. The locale sets the language | | xAI | `eve` | `eve`, `ara`, `rex`, `sal`, `leo` | | Mistral | `en_paul_neutral` | `en_paul_neutral`, `en_paul_happy`, `fr_marie_neutral` | | ElevenLabs | provider default | Voice ids such as `21m00Tcm4TlvDq8ikWAM`, `EXAVITQu4vr4xnSDxMaL`, `JBFqnCBsd6RMkjVDRZzb` | | Fish Audio | provider default | Voice ids such as `802e3bc2b27e49c2995d23ef70e6ac89` | An unknown voice returns the provider's error (a `400` or `404`) and is not charged. ## Response The body is the audio file. `Content-Type` matches the format: `audio/mpeg`, `audio/ogg` (opus), `audio/aac`, `audio/flac` or `audio/wav`. | Header | Meaning | | --- | --- | | `X-Request-Id` | Generation id, e.g. `gen_4757b0e3-...`. Quote it in support requests | | `X-AIRouter-Characters` | Characters billed | | `X-AIRouter-ZDR` | Always `false` | Errors are JSON, as on every other endpoint. ## Billing Text-to-speech is billed **per input character**, at the price listed on the [models page](https://www.airouter.in/models?type=speech). Providers count characters differently, and you are billed the way the model's provider counts: - Fish Audio counts bytes of UTF-8. Text outside the Latin alphabet costs more there: a 25-character Hindi sentence is billed as 65. - ElevenLabs counts each emoji as one character. OpenAI, Microsoft, xAI and Mistral count most emoji as two. `X-AIRouter-Characters` and the dashboard logs show the exact count and cost. ## Errors | Status | Example message | | --- | --- | | `400` | `model is required` | | `400` | `input is required: the text to turn into speech` | | `400` | `Unsupported parameter: voices.` | | `400` | `Model "elevenlabs/eleven-flash-v2.5" does not produce opus audio. Use one of: mp3, wav.` | | `400` | `Model "elevenlabs/eleven-flash-v2.5" supports speed from 0.7 to 1.2.` | | `400` | `input is 4097 characters; "openai/tts-1" accepts up to 4096. Split the text into several requests.` | | `400` | `Model "openai/gpt-5.2" is not a text-to-speech model. See GET /v1/models?type=speech.` | | `401` | `Invalid, disabled, or revoked API key` | | `402` | `Insufficient credits. This request requires up to $0.000725.` | | `403` | `Text-to-speech requires a paid plan. Add credits to unlock all models.` | | `404` | `Speech failed for "spacexai/grok-tts": the provider returned HTTP 404: TTS synthesis failed: Voice '...' not found. You were not charged.` | | `429` | `Too many concurrent requests for this API key (max 20).` | | `429` | `API key spending limit reached` | | `502` | `The provider returned almost no audio (0.05 s) for "...". It charged $0.000690 for the attempt, so this request was billed. Send the request again.` | | `502` | `The provider returned no usable audio for "...". You were not charged. Send the request again.` | | `504` | `Speech for "..." did not finish within 110 seconds. You were not charged. Try a shorter input.` | Validation errors carry the failing field in `param`. A failed request is not charged, with one exception: when the provider returns almost no audio but reports a charge for it, that request is billed, the message says how much, and the response carries `x-should-retry: false` so SDKs do not retry it automatically. If the provider reports no charge, it is refunded. Passing a text-to-speech model to `/v1/chat/completions` returns `400` with a pointer back to this endpoint. # Audio transcriptions Source: https://www.airouter.in/docs/api-reference/audio-transcriptions > POST /v1/audio/transcriptions — turn an audio file into text with one of eight speech-to-text models, with optional timestamps and speaker labels, billed per second of audio. ``` POST https://api.airouter.in/v1/audio/transcriptions ``` Send a complete audio file and get its text back. Optionally ask for timestamps and speaker labels (diarization), on the [models](#models) that support them. Live, streaming transcription is not available. Requires an API key and a [paid plan](https://www.airouter.in/docs/concepts/plans). Files can be up to 19 MB and 2 hours long. No streaming and no `Idempotency-Key` support. Zero data retention does not apply: every response carries `X-AIRouter-ZDR: false`, and a `zdr` field is ignored. Rate limit: 60 requests per minute per key. The request uses OpenAI's `audio/transcriptions` fields, so the OpenAI SDK's `client.audio.transcriptions.create()` works with only the base URL and key changed. AIRouter adds speaker labels (`diarize`) and a JSON body option. Send the audio in one of two ways: - **multipart/form-data** with the audio in a `file` field. Best for files on disk. - **application/json** with the audio as base64 in `audio`. Base64 is about a third larger than the file, so JSON carries files up to about 14 MB. 19 MB holds about 20 minutes of 128 kbps MP3, or about 80 minutes of 32 kbps mono Opus or MP3. Speech transcribes just as well at low bit rates, so compress long recordings, or split them into parts. ## Request With the OpenAI SDK: ```ts import OpenAI from "openai"; import fs from "node:fs"; const client = new OpenAI({ baseURL: "https://api.airouter.in/v1", apiKey: process.env.AIROUTER_API_KEY, }); const transcription = await client.audio.transcriptions.create({ file: fs.createReadStream("meeting.mp3"), model: "elevenlabs/scribe-v2", response_format: "verbose_json", timestamp_granularities: ["word", "segment"], }); console.log(transcription.text); ``` With curl: ```bash curl https://api.airouter.in/v1/audio/transcriptions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -F model=elevenlabs/scribe-v2 \ -F file=@meeting.mp3 \ -F diarize=true ``` The same request as JSON: ```bash curl https://api.airouter.in/v1/audio/transcriptions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d "{ \"model\": \"elevenlabs/scribe-v2\", \"audio\": \"$(base64 < meeting.mp3 | tr -d '\n')\", \"format\": \"mp3\", \"diarize\": true }" ``` ### Body | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `model` | `string` | Yes | | Must be a model of type transcription. Anything else returns 400. | | `file` | `file` | No | | multipart/form-data only, required there. The audio file. Exactly one file per request. | | `audio` | `string` | No | | JSON only, required there. The audio as base64, or a data URL such as "data:audio/mpeg;base64,...". URLs to remote files are not supported. | | `format` | `string` | No | | mp3, wav, m4a, webm, ogg, flac or aac. Optional: the format is detected from the file itself. | | `language` | `string` | No | | ISO 639-1 or ISO 639-3 code, e.g. "en" or "hin". Omit it to detect the language automatically. | | `response_format` | `"json" \| "verbose_json" \| "text" \| "srt" \| "vtt"` | No | | Default json. See Response formats. srt and vtt need a model with timestamps. | | `timestamp_granularities` | `("word" \| "segment")[]` | No | | With json or verbose_json. "word" needs a word-level model; "segment" works on every model with timestamps. In multipart, send timestamp_granularities[] once per value. | | `prompt` | `string` | No | | Words or context the audio contains, e.g. product names, up to 1,000 characters. Used by OpenAI, Mistral and Microsoft models; others return 400. | | `temperature` | `number` | No | | 0 to 1. Passed to OpenAI and Mistral models; the others ignore it. | | `timestamps` | `boolean` | No | | AIRouter extension. Return words[] with the start and end time of every word, in seconds. Default false. | | `diarize` | `boolean` | No | | AIRouter extension. Label who is speaking: a speaker number on every word and segment. Default false. | | `num_speakers` | `integer` | No | | AIRouter extension. Expected number of speakers, 1 to 32. Only with diarize: true. Omit it to let the model decide. | In multipart requests, booleans are sent as the strings `true` or `false` and `num_speakers` as a number string. `language`, `prompt`, timestamps, `diarize` and `num_speakers` work only on the models that support them (see [Models](#models)). Sending one to a model that does not returns `400` naming the models that do, before anything is charged. `stream: true` and `response_format: "diarized_json"` return `400`. ## Models | Model | Price / min | `language` | Timestamps | `prompt` | `diarize` | `num_speakers` | Formats not accepted | | --- | --- | --- | --- | --- | --- | --- | --- | | `microsoft/mai-transcribe-2` | $0.0017 | Yes | Words | Yes | Yes | No | m4a, aac, webm | | `spacexai/grok-stt` | $0.0017 | Yes | Words | No | Yes | No | — | | `mistral/voxtral-mini-transcribe-3` | $0.0035 | Yes | Segments | Yes | Yes | No | — | | `elevenlabs/scribe-v2` | $0.0037 | Yes | Words | No | Yes | Yes | — | | `mistral/voxtral-small-transcribe-3` | $0.0040 | Yes | Segments | Yes | Yes | No | — | | `openai/gpt-transcribe` | $0.0045 | Yes | No | Yes | No | No | aac | | `fish-audio/transcribe-1` | $0.0060 | No (auto-detects) | Words | No | No | No | — | | `openai/whisper-1` | $0.0060 | Yes | Words | Yes | No | No | aac | Prices were current in November 2026; the [models page](https://www.airouter.in/models?type=transcription) always shows the live price. "Words" models give a timing for every word, and sentence segments built from those words. "Segments" models give sentence timings only, so `timestamp_granularities: ["word"]` returns `400` on them. Some providers bill the audio rounded to whole seconds: `openai/gpt-transcribe` rounds up and the Mistral models round down. `usage.seconds` shows what was billed. ### Supported formats `mp3`, `wav`, `m4a` (MP4 audio), `webm`, `ogg` (including Opus), `flac` and `aac`. A file whose contents match none of these returns `415`, whatever its name or `format` says. ## Response formats | `response_format` | Body | | --- | --- | | `json` (default) | AIRouter's JSON, below. Contains OpenAI's `text` | | `verbose_json` | OpenAI's shape: `task`, `language` (`"english"`), `duration`, `text`, `segments` and/or `words` (`{ word, start, end }`), `usage` | | `text` | The transcript as plain text | | `srt` | SubRip subtitles, one cue per segment | | `vtt` | WebVTT subtitles, one cue per segment | `verbose_json` returns segments by default, and words with `timestamp_granularities: ["word"]`. With `diarize`, each word and segment also carries `speaker`. `text`, `srt` and `vtt` are plain text and must finish within 110 seconds, because a plain-text reply cannot be kept open with JSON whitespace like the others. For long files use `json` or `verbose_json`, which allow 300 seconds. ## Response ```json { "id": "gen_4757b0e3-1562-4c2f-b49c-cf7ea1aec197", "object": "transcription", "model": "elevenlabs/scribe-v2", "text": "Meet AI Router. Every AI model behind one API.", "language": "en", "duration_seconds": 4.383, "words": [ { "text": "Meet", "start": 0.08, "end": 0.26, "speaker": 0 }, { "text": "AI", "start": 0.42, "end": 0.7, "speaker": 0 } ], "usage": { "seconds": 4.383 } } ``` | Field | Meaning | | --- | --- | | `text` | The full transcript | | `language` | The language spoken, as a two-letter ISO 639-1 code such as `en` or `hi`. The language you sent, if the model does not report one | | `duration_seconds` | Length of the audio, in seconds | | `words` | Per-word timings, on word-level models. Present only with `timestamps` or `diarize` | | `segments` | Per-sentence timings, on segment-level models (and MAI with `diarize`). Present only with `timestamps` or `diarize` | | `speaker` | On each word or segment, only with `diarize`. Speakers are numbered from `0` in the order they first speak, on every model | | `usage.seconds` | Seconds of audio billed | Speech-to-text is billed **per second of audio**, at the price listed on the [models page](https://www.airouter.in/models?type=transcription). There is no charge per token. The response does not echo a cost; the dashboard logs show the exact amount and the audio length. Quote the `id` in support requests. Long files can take more than a minute. Set your client timeout to at least 5 minutes. For `json` and `verbose_json`, past 90 seconds the response starts with whitespace while the transcript is prepared; JSON parsers ignore it. ## Errors | Status | Example message | | --- | --- | | `400` | `model is required` | | `400` | `file is required: the audio file in a field named "file"` | | `400` | `Unsupported parameter: langauge.` | | `400` | `Model "spacexai/grok-stt" does not use a prompt. Omit it, or use one of: ...` | | `400` | `Model "mistral/voxtral-mini-transcribe-3" returns sentence (segment) timings only, not word timings. ...` | | `400` | `Model "openai/gpt-transcribe" does not return timestamps, so it cannot produce srt subtitles. ...` | | `400` | `stream is not supported: the transcript is returned when the whole file is done. Omit stream.` | | `400` | `language must be an ISO 639-1 or ISO 639-3 code, e.g. "en" or "hin". ...` | | `400` | `num_speakers is only used with diarize: true` | | `400` | `Audio is 150 minutes long. The maximum is 2 hours; split it into shorter parts.` | | `400` | `Model "openai/gpt-5.2" is not a speech-to-text model. See GET /v1/models?type=transcription.` | | `400` | `Model "openai/whisper-1" does not label speakers. Use one of: elevenlabs/scribe-v2, microsoft/mai-transcribe-2, ...` | | `400` | `Model "fish-audio/transcribe-1" detects the language automatically and does not accept "language". ...` | | `400` | `Transcription failed for "...": the provider returned HTTP 400: File is corrupted. Please ensure it is playable audio. ...` | | `401` | `Invalid, disabled, or revoked API key` | | `402` | `Insufficient credits. This request requires up to $0.002856.` | | `403` | `Speech-to-text requires a paid plan. Add credits to unlock all models.` | | `413` | `Audio file is larger than 19 MB. Split it into shorter parts.` | | `413` | `Request body is too large (limit 19 MiB). Base64 in a JSON body is about a third larger than the file, ...` | | `415` | `Unsupported or unrecognized audio format. Supported formats: mp3, wav, m4a, webm, ogg, flac, aac.` | | `415` | `Model "microsoft/mai-transcribe-2" does not accept m4a audio. Use one of: mp3, wav, ogg, flac.` | | `429` | `Too many concurrent requests for this API key (max 20).` | | `429` | `API key spending limit reached` | | `502` | `Transcription failed for "...": the provider returned HTTP : ` | | `504` | `Transcription for "..." did not finish within 300 seconds. You were not charged.` | Validation errors carry the failing field in `param`. A failed request is never charged: the credits reserved for it are returned. Passing a speech-to-text model to `/v1/chat/completions` returns `400` with a pointer back to this endpoint. # Chat Completions Source: https://www.airouter.in/docs/api-reference/chat-completions > POST /v1/chat/completions — OpenAI-compatible chat and completions across every model in the catalog, streaming or buffered. ``` POST https://api.airouter.in/v1/chat/completions ``` Requires an API key. Accepts bodies up to 16 MiB. Supports streaming and `Idempotency-Key`. Add `"zdr": true` (or the `X-AIRouter-ZDR: true` header) to serve the request only from providers with [zero data retention](https://www.airouter.in/docs/concepts/zero-data-retention); `Idempotency-Key` is ignored in that mode. ## Request **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) response = client.chat.completions.create( model="openai/gpt-5.2", messages=[ {"role": "system", "content": "You are a concise assistant."}, {"role": "user", "content": "Explain idempotency in one sentence."}, ], max_tokens=200, temperature=0.7, ) print(response.choices[0].message.content) print(response.usage.total_tokens) ``` **Node.js** ```ts import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [ { role: "system", content: "You are a concise assistant." }, { role: "user", content: "Explain idempotency in one sentence." }, ], max_tokens: 200, temperature: 0.7, }); console.log(response.choices[0].message.content); console.log(response.usage?.total_tokens); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [ {"role": "system", "content": "You are a concise assistant."}, {"role": "user", "content": "Explain idempotency in one sentence."} ], "max_tokens": 200, "temperature": 0.7 }' ``` ### Body | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `model` | `string` | Yes | | Slug in provider/model form, e.g. openai/gpt-5.2. | | `messages` | `Message[]` | Yes | | Must be non-empty. Each role is system, user, or assistant. content is a string or the OpenAI content-part array. | | `max_tokens` | `integer` | No | | Clamped down to the model's maximum output. Defaults to min(16384, model maximum) when neither token field is sent. | | `max_completion_tokens` | `integer` | No | | Use instead of max_tokens on the GPT-5, o1 and o3 families, which reject max_tokens. | | `temperature` | `number` | No | | Sampling temperature. | | `top_p` | `number` | No | | Nucleus sampling threshold. | | `stop` | `string \| string[]` | No | | Sequences that halt generation. | | `stream` | `boolean` | No | `false` | When true, the response is a server-sent event stream. | `messages[].content` accepts either a string or the OpenAI content-part array, so vision requests with `image_url` parts work as they do against OpenAI. **Note: Other OpenAI fields pass straight through.** The body is forwarded to the upstream provider almost untouched, so `tools`, `tool_choice`, `response_format`, `seed`, `reasoning` and similar fields work wherever the underlying model supports them. AIRouter does not validate them — an unsupported field surfaces as that provider's own `400`. ### How output length is decided This is the one place AIRouter rewrites your request, and it is worth understanding because it affects both truncation and cost: - Send `max_tokens` **or** `max_completion_tokens` and it is clamped down to the model's ceiling. The other field is removed, since GPT-5 / o1 / o3 reject `max_tokens` while older models reject `max_completion_tokens`. - Send neither and `max_tokens` is set to `min(16384, model maximum)`. Without this, some providers default to their full output ceiling, which would force a much larger credit reservation than the request needs. If you want more than 16,384 output tokens, ask for it explicitly. ## Response ```json { "id": "gen-8f3c1d42-9a7b-4c11-b0e5-2f6d8a1c4e77", "object": "chat.completion", "created": 1759000000, "model": "openai/gpt-5.2", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "An operation is idempotent when repeating it has no additional effect." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 24, "completion_tokens": 14, "total_tokens": 38, "total_cost": 0.00019 } } ``` `id` is AIRouter's own generation id and is also returned as the `X-Request-Id` header. `usage.total_cost` is the USD amount deducted from your balance. ### Models that return images Some language models emit images as well as text — the `google/gemini-*-image` family. They run **here**, not on the images endpoint, and put their output in `message.images[]` while leaving `message.content` empty: ```json { "choices": [ { "message": { "role": "assistant", "content": "", "images": [ { "image_url": { "url": "data:image/png;base64,iVBORw0KGgo..." } } ] } } ] } ``` The value is a complete data URL, so strip the `data:image/png;base64,` prefix before decoding. **Note: Use the last image.** `google/gemini-3-pro-image` and `google/gemini-nano-banana-2.1` think before they draw, and can return their draft images too. `message.images[]` then holds more than one entry, and **the final image is the last one**. A draft can be smaller than the size you asked for, for example `1K` for a `2K` request. You are billed once, for the final image. Read `message.images[-1]` rather than `[0]`. When streaming, keep the last image that arrives. Dedicated image-only models such as `openai/gpt-image-2` are rejected here with a `400` — see [Image Generation](https://www.airouter.in/docs/api-reference/images#which-endpoint-for-which-model) for the full split and the differing response shapes. ### Image size and aspect ratio Set the resolution and shape with `image_config`: ```json { "model": "google/gemini-3-pro-image", "messages": [{ "role": "user", "content": "An isometric data centre at dusk" }], "image_config": { "image_size": "4K", "aspect_ratio": "16:9" } } ``` Top-level `image_size` and `aspect_ratio` fields are accepted too. Both are optional: without `image_size` the image is 1K, and without `aspect_ratio` the model picks the shape. Values are not case-sensitive (`"4k"` works). | Model | `image_size` | Extra aspect ratios | | --- | --- | --- | | `google/gemini-3-pro-image` | `1K`, `2K`, `4K` | — | | `google/gemini-3.1-flash-image`, `-preview` | `512`, `1K`, `2K`, `4K` | `1:8`, `8:1`, `1:4`, `4:1` | | `google/gemini-nano-banana-2.1` | `1K`, `2K`, `4K` | `1:8`, `8:1`, `1:4`, `4:1` | | `google/gemini-3.1-flash-lite-image` | `1K` | `1:8`, `8:1`, `1:4`, `4:1` | | `google/gemini-2.5-flash-image` | fixed size, `image_size` not accepted | — | Every model accepts `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9` and `21:9`. Larger sizes cost more per image, and the credit held while the request runs is based on the size you ask for. A value a model does not support, or the same setting given twice with different values, is rejected with a `400` before anything is generated or charged: | `code` | When | | --- | --- | | `unsupported_image_size` | `image_size` is not in the model's list | | `unsupported_aspect_ratio` | `aspect_ratio` is not in the model's list | | `image_config_conflict` | Two different values for the same setting, for example `image_size: "2K"` and `image_config.image_size: "4K"` | | `invalid_image_config` | Not a string, or an unknown key inside `image_config` | `2K` and `4K` images are large, and only a limited number are generated at the same time. When that limit is reached, a new `2K` or `4K` request gets a `429` with code `high_resolution_capacity_busy` and `Retry-After: 15`; nothing is reserved or charged. The OpenAI SDKs retry a `429` automatically. `1K` and `512` are not affected. ### Billing for image models - **Prefer non-streaming.** Streaming gives no benefit here: the whole image arrives in one frame at the end. - **Disconnecting does not cancel the charge.** Once generation starts the image is billed in full, streaming or not. It is kept for 24 hours; fetch it by its generation ID (the response `id`, also in `X-Request-Id`) as described in [recovering an image](https://www.airouter.in/docs/api-reference/images#recovering-an-image). - **A reply can come back without an image.** These models sometimes answer with text, a tool call, or an empty message instead — for example when they read the prompt as a question or decline it. That response is returned as it is and billed at the provider's cost, so check `message.images` before reading it. ## Streaming Set `stream: true`. The response is `text/event-stream` carrying standard OpenAI delta frames, which every OpenAI SDK consumes natively. **Python** ```python stream = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Count to five."}], stream=True, ) for chunk in stream: delta = chunk.choices[0].delta.content if delta: print(delta, end="", flush=True) ``` **Node.js** ```ts const stream = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [{ role: "user", content: "Count to five." }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content ?? ""); } ``` **cURL** ```bash curl -N https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Count to five."}], "stream": true }' ``` Frames look like this, terminated by `[DONE]`: ``` data: {"id":"gen-8f3c...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"One"}}]} data: {"id":"gen-8f3c...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":", two"}}]} data: [DONE] ``` **Warning: Streams can fail after a 200.** Headers are sent before the first token, so a provider failure mid-generation cannot change the HTTP status — it is already `200`. The failure arrives as a frame in the body instead: ```json { "error": { "message": "Stream interrupted: upstream closed", "type": "server_error" } } ``` A total dispatch failure appears the same way with `"All routers failed"`. Inspect every frame for an `error` key; code that only checks the status will read a truncated answer as a complete one. ### Cancelling a stream Disconnecting stops delivery but **does not** make the request free. The upstream provider has already generated those tokens and bills us for them, so AIRouter keeps reading for up to 90 seconds to capture the real usage figure and charges you that amount. When the provider never reports usage, cost is estimated from the characters actually delivered and capped at the request's reservation. A non-streaming request you disconnect from still runs to completion and is billed for what the provider generated; nothing is charged if no provider answered. ## Routing and failover Each request is attempted against a primary gateway and, if that fails before any bytes are sent, a secondary one. A provider with no equivalent of the requested model slug is skipped. Once the first byte has been sent, failover is impossible — that is why a mid-stream failure surfaces in the body rather than being retried. Buffered requests have 600 seconds in total, streams 120 seconds to first byte, and image models 600 seconds to produce their image. A buffered response that takes longer than 90 seconds starts with whitespace and reports any later failure inside a `200`; see [long non-streaming requests](https://www.airouter.in/docs/concepts/streaming#long-non-streaming-requests). ## Errors | Status | Example message | | --- | --- | | `400` | `model and messages are required` | | `400` | `Model "foo/bar" is not supported` | | `400` | `Model "openai/text-embedding-3-small" is an embedding model. Use POST /v1/embeddings instead.` | | `400` | `Model "openai/gpt-image-2" is an image generation model and cannot be used with chat completions. Use POST /v1/images/generations instead.` | | `400` | `image_size "4K" is not supported by model "google/gemini-3.1-flash-lite-image". Supported: 1K.` | | `400` | `Conflicting image_size values: image_size = "2K", image_config.image_size = "4K". Send image_size once, or the same value everywhere.` | | `401` | `Invalid, disabled, or revoked API key` | | `402` | `Insufficient credits. This request requires up to $0.042500.` | | `403` | `This model requires a paid plan. Add credits to unlock all models.` | | `413` | `Request body is too large (limit 16 MiB).` | | `429` | `Too many concurrent requests for this API key (max 20).` | | `429` | `Too many large-image requests are running right now. Retry in 15 seconds, or use image_size "1K". Nothing was charged.` | | `502` | `Request failed for "openai/gpt-5.2": the provider returned HTTP : ` | A `413` is usually not caused by the message you just typed. OpenAI-compatible clients resend the whole conversation every turn, so it is the accumulated history plus tool output that crosses the limit. Hitting an API key's spending limit returns `429` with extra detail: ```json { "error": { "message": "API key spending limit reached. Key limit: $10.00, used: $9.98, remaining: $0.02, this request requires up to $0.042500.", "type": "api_key_reservation_exceeds_limit", "code": "api_key_reservation_exceeds_limit", "details": { "key_limit": 10, "key_usage": 9.98, "key_remaining": 0.02, "required_reservation": 0.0425 } } } ``` ## Why a request can cost less than it reserved Before calling the provider, AIRouter reserves an upper bound on what the request could cost and deducts it from your balance. When the response arrives, the difference between the reservation and the real cost is refunded in the same database transaction that records the usage. Two consequences worth knowing: a `402` quotes the *maximum* a request could cost, not what it would actually have cost, and a very large `max_tokens` on a low balance can be rejected even though the real reply would have been cheap. Lower `max_tokens` to reserve less. # Decisions Source: https://www.airouter.in/docs/api-reference/decisions > POST /v1/decisions — ask a decision model typed questions (yes/no, pick one, score) about some input and get answers with probabilities, billed from the same credit balance. ``` POST https://api.airouter.in/v1/decisions ``` A decision model does not write text. You give it some input and a list of questions, and it answers each one with a typed value and the probabilities behind it. Use it to triage support tickets, route requests, moderate content, or score anything against criteria you define. Requires an API key and a [paid plan](https://www.airouter.in/docs/concepts/plans). Accepts bodies up to 16 MiB. No streaming and no `Idempotency-Key` support. Zero data retention does not apply: every response carries `X-AIRouter-ZDR: false`, and a `zdr` field in the body is ignored. ## Request ```bash curl https://api.airouter.in/v1/decisions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "typesafe-ai/jev", "input": "The package arrived with a broken screen. I want my money back.", "questions": [ { "type": "predicate", "name": "damaged", "instructions": "Does the customer report a damaged item?" }, { "type": "choice", "name": "queue", "instructions": "Which team should handle this ticket?", "choices": [ { "value": "billing", "description": "Refunds and payments" }, { "value": "shipping", "description": "Delivery and damaged items" } ] }, { "type": "score", "name": "urgency", "instructions": "How urgent is this ticket?", "levels": [{ "label": "low" }, { "label": "medium" }, { "label": "high" }] } ] }' ``` ### Body | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `model` | `string` | Yes | | Must be a model of type decision. Anything else returns 400. | | `input` | `string \| message[]` | Yes | | What the questions are about. A string, or an array of user messages whose content is a string or a list of input_text and input_image parts. Every question is asked about the whole input. | | `questions` | `question[]` | Yes | | One or more questions. Answers come back in the same order. | | `safety_identifier` | `string` | No | | Opaque end-user identifier for abuse detection. Must not be empty. | ### Questions Every question needs a `type` and `instructions`. `name` is optional, but names must be unique within a request, and an unnamed question comes back with `name: null`. | `type` | Extra request fields | Answer fields | | --- | --- | --- | | `predicate` | none | `probability` that the answer is yes | | `choice` | `choices`: 1 to 255 items, each with a string or boolean `value` and an optional `description` | `choice`, `confidence`, `probabilities` | | `score` | `levels`: 2 to 10 items, each with a `label` and an optional `description` | `score`, `confidence`, `probabilities` | A score is the probability-weighted average of the level indexes, starting at `0`. `confidence` and `probabilities` appear when the model returns them. ## Images Models that accept images take `input_image` parts. The image must be a base64-encoded data URL. External URLs and file IDs are not supported, and a request can include at most 128 images. `detail` is optional and one of `low`, `high`, `auto`, or `original`. ```bash curl https://api.airouter.in/v1/decisions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-luna-decisions", "input": [ { "role": "user", "content": [ { "type": "input_text", "text": "Inspect the product in this photo." }, { "type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo...", "detail": "high" } ] } ], "questions": [ { "type": "predicate", "name": "visible_damage", "instructions": "Does the product have visible damage?" } ] }' ``` **Note: Not every model reads images.** Image support depends on the model. A model that only accepts text returns `400` for a request with images. The models listed with image input on the [models page](https://www.airouter.in/models?type=decision) accept them. ## Response ```json { "answers": [ { "type": "predicate", "name": "damaged", "probability": 0.98 }, { "type": "choice", "name": "queue", "choice": "shipping", "confidence": 0.81, "probabilities": [ { "value": "billing", "probability": 0.19 }, { "value": "shipping", "probability": 0.81 } ] }, { "type": "score", "name": "urgency", "score": 1.45, "confidence": 0.29, "probabilities": [ { "value": 0, "label": "low", "probability": 0.01 }, { "value": 1, "label": "medium", "probability": 0.53 }, { "value": 2, "label": "high", "probability": 0.46 } ] } ], "model": "typesafe-ai/jev", "usage": { "input_tokens": 379, "output_tokens": 63, "total_tokens": 442 }, "id": "gen_219fc8c2-bc4d-4465-b6d8-ef1f596269e8" } ``` If a model declines to answer a question, that answer is `{ "type": "refusal", "name": "..." }` in the question's position and the other questions are answered normally. The request is still billed for its input. Decision models bill **input tokens only**. The response does not echo a cost. AIRouter charges the cost the upstream gateway reports for the request, and the dashboard logs show the exact amount. Quote the `id` in support requests. ## Errors | Status | Example message | | --- | --- | | `400` | `model is required` | | `400` | `questions must be a non-empty array` | | `400` | `Question name "x" is used more than once.` | | `400` | `A score question needs between 2 and 10 levels` | | `400` | `Images must be base64-encoded image data URLs. External URLs and file IDs are not supported.` | | `400` | `Model "openai/gpt-5.2" is not a supported decision model` | | `400` | `Unsupported parameter: providerOptions.gateway.models. Fallback model lists are not supported. ...` | | `401` | `Invalid, disabled, or revoked API key` | | `402` | `Insufficient credits. This request requires up to $0.000012.` | | `403` | `Decision models require a paid plan. Add credits to unlock all models.` | | `413` | `Request body is too large (limit 16 MiB). Decision requests carry images as base64, ...` | | `429` | `Too many concurrent requests for this API key (max 20).` | | `429` | `API key spending limit reached` | | `502` | `Decision request failed for "...": the provider returned HTTP : ` | | `504` | `Decision request timed out for "...". Nothing was charged.` | Validation errors carry the failing field in `param`, for example `"param": "questions[1].name"`. A failed request is never charged: the credits reserved for it are returned. Passing a chat model here returns `400` rather than silently routing it, and passing a decision model to `/v1/chat/completions` returns `400` with a pointer back to this endpoint. # Embeddings Source: https://www.airouter.in/docs/api-reference/embeddings > POST /v1/embeddings — vector embeddings from OpenAI, Google, Cohere, Voyage, Mistral and more, billed from the same credit balance. ``` POST https://api.airouter.in/v1/embeddings ``` Requires an API key. Accepts bodies up to 16 MiB. No streaming and no `Idempotency-Key` support — embedding calls are cheap and naturally repeatable. ## Request **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) response = client.embeddings.create( model="openai/text-embedding-3-small", input="The quick brown fox jumps over the lazy dog", ) vector = response.data[0].embedding print(vector[:5]) print("dimensions:", len(vector)) ``` **Node.js** ```ts import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const response = await client.embeddings.create({ model: "openai/text-embedding-3-small", input: "The quick brown fox jumps over the lazy dog", }); const vector = response.data[0].embedding; console.log(vector.slice(0, 5)); console.log("dimensions:", vector.length); ``` **cURL** ```bash curl https://api.airouter.in/v1/embeddings \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/text-embedding-3-small", "input": "The quick brown fox jumps over the lazy dog" }' ``` ### Body | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `model` | `string` | Yes | | Must be a model of type embedding. Anything else returns 400. | | `input` | `string \| string[]` | Yes | | Must not be empty. An array embeds a batch of documents in one call. | | `encoding_format` | `"float" \| "base64"` | No | `"float"` | Encoding of the returned vectors. | | `dimensions` | `integer` | No | | Truncate vectors to this many dimensions. Only on models that support it. | | `user` | `string` | No | | Opaque end-user identifier, forwarded upstream. | ## Batching Pass an array to embed many documents in one request. Each input gets its own result object, and `index` tells you which input it came from — the order of `data` is not guaranteed to match your input order, so key off `index` rather than position. **Python** ```python docs = [ "Postgres is a relational database.", "Redis is an in-memory data store.", "S3 is an object store.", ] response = client.embeddings.create( model="openai/text-embedding-3-small", input=docs, ) vectors = [d.embedding for d in sorted(response.data, key=lambda d: d.index)] print(len(vectors), "vectors") print("tokens billed:", response.usage.prompt_tokens) ``` **Node.js** ```ts const docs = [ "Postgres is a relational database.", "Redis is an in-memory data store.", "S3 is an object store.", ]; const response = await client.embeddings.create({ model: "openai/text-embedding-3-small", input: docs, }); const vectors = [...response.data] .sort((a, b) => a.index - b.index) .map((d) => d.embedding); console.log(vectors.length, "vectors"); console.log("tokens billed:", response.usage.prompt_tokens); ``` **cURL** ```bash curl https://api.airouter.in/v1/embeddings \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/text-embedding-3-small", "input": [ "Postgres is a relational database.", "Redis is an in-memory data store.", "S3 is an object store." ] }' ``` **Note: Batch size is bounded by the body limit.** A single request may be up to 16 MiB. Larger batches return `413` — split them into several calls. Each individual input is separately bounded by the model's own context window (typically around 8K tokens). ## Response The provider's response is returned unchanged: ```json { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [0.0023, -0.0089, 0.0156, "..."] } ], "model": "openai/text-embedding-3-small", "usage": { "prompt_tokens": 9, "total_tokens": 9 } } ``` **Note.** Unlike chat, embedding responses usually carry **no** `usage.total_cost`. The upstream gateway does not report a price for this endpoint, so AIRouter computes the charge from `usage.prompt_tokens` times the model's input price. Billing is unaffected; the figure just isn't echoed back. Check the dashboard logs for the exact amount. ## Errors | Status | Example message | | --- | --- | | `400` | `model and input are required` | | `400` | `input must not be empty` | | `400` | `input array must not be empty` | | `400` | `Model "openai/gpt-5.2" is not a supported embedding model` | | `401` | `Invalid, disabled, or revoked API key` | | `402` | `Insufficient credits. This request requires up to $0.000012.` | | `403` | `Embedding models require a paid plan. Add credits to unlock all models.` | | `413` | `Request body is too large (limit 16 MiB). Embedding requests accept an array of inputs; split the batch into smaller requests.` | | `429` | `Too many concurrent requests for this API key (max 20).` | | `429` | `API key spending limit reached` | | `502` | `Embedding request failed for "...": the provider returned HTTP : ` | | `504` | `Embedding request timed out for "..." after 115 seconds. Nothing was charged.` | Passing a chat model here returns `400` rather than silently routing it — the model must be of type `embedding` in the catalog. # Image Generation Source: https://www.airouter.in/docs/api-reference/images > POST /v1/images/generations — OpenAI-compatible image generation returning base64 PNGs, with idempotency support for slow, expensive calls. ``` POST https://api.airouter.in/v1/images/generations ``` Requires an API key. No streaming: `stream: true` and `partial_images` are rejected with a `400` before anything is charged. If your connection drops, you don't need to generate the image again: fetch it by its generation ID, as described in [recovering an image](#recovering-an-image). `Idempotency-Key` is supported too, so a retry with the same key returns the original image. ## Request **Python** ```python import base64 from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) response = client.images.generate( model="openai/gpt-image-2", prompt="An isometric illustration of a data centre at dusk", size="1024x1024", quality="medium", n=1, ) with open("out.png", "wb") as f: f.write(base64.b64decode(response.data[0].b64_json)) ``` **Node.js** ```ts import { writeFile } from "node:fs/promises"; import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const response = await client.images.generate({ model: "openai/gpt-image-2", prompt: "An isometric illustration of a data centre at dusk", size: "1024x1024", quality: "medium", n: 1, }); const b64 = response.data[0].b64_json!; await writeFile("out.png", Buffer.from(b64, "base64")); ``` **cURL** ```bash curl https://api.airouter.in/v1/images/generations \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: render-3f2b8c1e-5d4a-4e7b-9c2a-1b6f8e0d7a55" \ -d '{ "model": "openai/gpt-image-2", "prompt": "An isometric illustration of a data centre at dusk", "size": "1024x1024", "quality": "medium", "n": 1 }' | jq -r '.data[0].b64_json' | base64 --decode > out.png ``` ### Body | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `model` | `string` | Yes | | An image-only model. Multimodal models that emit images belong on /v1/chat/completions. | | `prompt` | `string` | Yes | | Must be a non-empty string. | | `n` | `integer` | No | `1` | Number of images to generate. Must be between 1 and 10, or at most 2 when size is larger than 1536x1024. See Large sizes below. | | `size` | `"WIDTHxHEIGHT" \| "auto"` | No | `"auto"` | gpt-image-2, gpt-image-2.5 and gpt-image-2.6 accept any WIDTHxHEIGHT within the limits below. gpt-image-1.5 and gpt-image-1-mini accept 1024x1024, 1536x1024 and 1024x1536. | | `quality` | `"low" \| "medium" \| "high" \| "xhigh" \| "max" \| "auto"` | No | `"auto"` | xhigh and max are for the gpt-image-2.5 and gpt-image-2.6 models only. Drives the output-token count, and therefore the price. | | `output_format` | `"png" \| "jpeg" \| "webp"` | No | `"png"` | File type of the returned image. It doesn't change the price. Any other value returns 400 unsupported_output_format. | For `openai/gpt-image-2` and the `openai/gpt-image-2.5-*` and `openai/gpt-image-2.6-*` models, a custom `size` must have both edges divisible by 16, a longest edge of at most 3840, an aspect ratio of at most 3:1, and between 655,360 and 8,294,400 pixels in total. For example, `1536x864`, `2048x2048`, `2880x2880` and `3840x2160` are all valid. ### Size and quality affect cost You are billed for input and output tokens. An image's output-token count is set by its size and quality, not by your prompt. Measured figures for `openai/gpt-image-2`: | Quality | `1024x1024` | `2880x2880` | | --- | --- | --- | | `low` | 196 | 659 | | `medium` | 1,756 | 5,930 | | `high` | 7,024 | 23,719 | With `n` greater than 1, every image is billed separately, including its own copy of the prompt's input tokens. **Note: How much credit a request holds.** Before generating, AIRouter holds the most the request can cost, then charges what the model provider reports and returns the rest. For `gpt-image-2`, `gpt-image-2.5` and `gpt-image-2.6` the hold uses the exact output-token count for the size and quality you ask for, so it is close to the real cost for any valid size. With `size: "auto"` or no size, the hold is for the most expensive valid size; with `quality: "auto"` or no quality, for the highest quality. A request with neither holds the price of the largest high-quality image, so on a low balance it can return `402` for an image that would have cost far less. Send an explicit `size` and `quality` to hold only what that image costs. `gpt-image-1.5` and `gpt-image-1-mini` hold 12,000 output tokens per image. ### Large sizes: up to 2 images per request When `size` has more pixels than `1536x1024` (1,572,864 pixels), `n` can be at most `2`. A single image at the largest sizes is around 20 MB of base64, so bigger batches have to be split across requests. | `size` | Maximum `n` | | --- | --- | | `1024x1024`, `1536x1024`, `1024x1536` | 10 | | `"auto"` or omitted | 10 | | Anything larger, for example `2048x2048`, `2560x1440`, `2880x2880`, `3840x2160` | 2 | The limit depends only on the pixel count, not on `quality`. A request over the limit is rejected with a `400` before anything is generated, so nothing is reserved or charged: ```json { "error": { "message": "n must be 2 or less when size is larger than 1536x1024 (1,572,864 pixels). You asked for 4 images at 2880x2880. Split the batch into requests of up to 2 images each.", "type": "invalid_request_error", "param": "n", "code": "too_many_high_resolution_images" } } ``` To get more images at a large size, send several requests with `n` of 2 or less. Large-image requests are also limited by how many are running at the same time. When that limit is reached, a new large-image request gets a `429` with code `high_resolution_capacity_busy` and a `Retry-After: 15` header. Nothing is reserved or charged, and the `Idempotency-Key` is released, so retrying with the same key is safe. The OpenAI SDKs retry a `429` automatically and wait for the `Retry-After` time. Sizes of `1536x1024` and smaller are not affected. ## Response ```json { "id": "gen-8f3c1d42-9a7b-4c11-b0e5-2f6d8a1c4e77", "created": 1759000000, "data": [ { "b64_json": "iVBORw0KGgoAAAANSUhEUg..." } ], "usage": { "input_tokens": 22, "output_tokens": 1056 } } ``` Images always come back base64-encoded in `b64_json`; there are no hosted URLs to fetch. Usage is reported as `input_tokens` / `output_tokens`, not the `prompt_tokens` / `completion_tokens` used by chat. No cost field is included; the charge is what the model provider reports for these tokens. `id` is the generation ID. It is also sent in the `X-Request-Id` and `X-AIRouter-Generation-Id` headers, which arrive before the body. Keep it: it is how you [recover the image](#recovering-an-image) if the response is lost. ### Long requests If an image is not ready after 90 seconds, the response headers are sent and the body starts with whitespace while the image is generated. JSON parsers ignore it, and it stops proxies on the way from closing the connection. Past that point the HTTP status is already `200`, so a failure is reported in the body instead, with the status it would have had: ```json { "error": { "message": "Image generation for \"openai/gpt-image-2\" did not finish within 600 seconds. You were not charged.", "type": "server_error", "code": "image_generation_timeout" }, "status": 504 } ``` Check for an `error` key even on a `200`. A request that has no answer after 600 seconds is stopped and not charged. ### When no image comes back Rarely, the model provider answers without an image. That is returned as a `502` with code `no_image_returned`. Usually nothing is charged and the message says "You were not charged." If the provider charged for the attempt, the same cost is billed and the message states the amount; that response also carries `x-should-retry: false`, so the OpenAI SDKs do not retry it automatically. ## Disconnecting does not cancel the charge Once generation starts, the image is billed in full whether or not you are still connected. AIRouter lets it finish and keeps a copy for 24 hours, so if your connection drops, [recover it](#recovering-an-image) instead of generating it again. ## Recovering an image Every generated image is kept for **24 hours**. Fetch it with the same API key that created it: ```bash # By generation ID curl https://api.airouter.in/v1/images/generations/$GENERATION_ID/result \ -H "Authorization: Bearer $AIROUTER_API_KEY" -o out.png # By the Idempotency-Key you sent curl https://api.airouter.in/v1/images/generations/result \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Idempotency-Key: render-3f2b8c1e-5d4a-4e7b-9c2a-1b6f8e0d7a55" -o out.png ``` | Query | Returns | | --- | --- | | (none) | The first image as raw bytes, with its image `Content-Type` | | `?index=N` | Image `N` (0-based) when the request used `n` greater than 1 | | `?format=json` | The original JSON response, base64 included | Fetching a stored image does not generate or charge anything. After 24 hours, or with a different API key, the result endpoints return `404`. Images from the image models on `/v1/chat/completions` are recoverable the same way, by their generation ID. ## Retrying safely Send an `Idempotency-Key` and a retry after a timeout returns the original image instead of generating and charging for a second one. The guarantee lasts **24 hours** from the first request. ```python import uuid key = f"render-{uuid.uuid4()}" response = client.images.generate( model="openai/gpt-image-2", prompt="An isometric illustration of a data centre at dusk", size="1024x1024", quality="medium", extra_headers={"Idempotency-Key": key}, ) ``` Reuse the *same* key when retrying the *same* request; generate a new one for a new request. Keys are scoped to the API key that created them, so two keys can safely use the same string. The `render-` prefix is only a label for your logs — the API ignores it. See [idempotency](https://www.airouter.in/docs/concepts/idempotency#generate-a-key) for a key generator. | Response | Meaning | What to do | | --- | --- | --- | | `200` + `idempotent-replayed: true` | The original result, rebuilt from the stored copy | Nothing — it's the same image | | `409` | The first call is still generating | Wait and retry the same key | | `410` | The first call finished, but its stored copy is no longer available | Retrying the key will not generate or charge again; contact support with the generation ID | | `422` | Key already used with a different body | Use a new key for a different request | | `400` | Malformed key | Must be printable ASCII, 255 characters or fewer | A failed attempt does not burn the key. If the request errors before producing an image, the reservation is refunded and the key is released, so the same key can be retried cleanly. The one exception is a `no_image_returned` error that was charged: it is stored against the key, so a retry returns the same error instead of charging again. ## Which endpoint for which model There is no overlap. Every image-capable model belongs to exactly one endpoint, and calling the other one fails. | Model | `/v1/chat/completions` | `/v1/images/generations` | | --- | --- | --- | | `openai/gpt-image-2.6-sunburst` | — | Yes | | `openai/gpt-image-2.6-flare` | — | Yes | | `openai/gpt-image-2.5-sunburst` | — | Yes | | `openai/gpt-image-2.5-flare` | — | Yes | | `openai/gpt-image-2` | — | Yes | | `openai/gpt-image-1.5` | — | Yes | | `openai/gpt-image-1-mini` | — | Yes | | `google/gemini-3-pro-image` | Yes | — | | `google/gemini-3.1-flash-image` | Yes | — | | `google/gemini-3.1-flash-lite-image` | Yes | — | | `google/gemini-nano-banana-2.1` | Yes | — | | `google/gemini-2.5-flash-image` | Yes | — | The `openai/gpt-image-*` models are image-only. The Gemini models are language models that happen to emit images, so they run on the chat endpoint. **Warning: You cannot swap these models by changing the model string.** The endpoint differs **and so does the response shape**, so moving between the two means changing the URL and the parsing: ``` /v1/images/generations → data[0].b64_json (bare base64) /v1/chat/completions → choices[0].message.images[0].image_url.url (data: URL) ``` The chat form is a complete data URL — `data:image/png;base64,...` — so you must strip the prefix before decoding, which the `images` endpoint does not require. ### Generating an image on the chat endpoint ```python response = client.chat.completions.create( model="google/gemini-3-pro-image", messages=[{"role": "user", "content": "An isometric data centre at dusk"}], extra_body={"image_config": {"image_size": "2K", "aspect_ratio": "16:9"}}, ) # The last image is the final one: some models also return drafts first. data_url = response.choices[0].message.images[-1]["image_url"]["url"] header, b64 = data_url.split(",", 1) # strip "data:image/png;base64," with open("out.png", "wb") as f: f.write(base64.b64decode(b64)) ``` Note that `message.content` is typically an empty string for these models — the payload is entirely in `message.images[]`. `google/gemini-3-pro-image` and `google/gemini-nano-banana-2.1` can return draft images before the final one, which is why the example reads the last entry; see [models that return images](https://www.airouter.in/docs/api-reference/chat-completions#models-that-return-images). Sizes and aspect ratios per model are listed in [Chat Completions](https://www.airouter.in/docs/api-reference/chat-completions#image-size-and-aspect-ratio). ### Both directions are rejected locally AIRouter checks which endpoint a model belongs to before doing anything else, so a wrong call fails at once with no credit reserved: ``` POST /v1/chat/completions model=openai/gpt-image-2 400 ...cannot be used with chat completions. Use POST /v1/images/generations instead. POST /v1/images/generations model=google/gemini-3-pro-image 400 ...is not an image-only model. Multimodal models that generate images are served on POST /v1/chat/completions and return the image in choices[0].message.images[]. ``` ## Errors | Status | Example message | | --- | --- | | `400` | `model is required` | | `400` | `prompt is required and must be a non-empty string` | | `400` | `n must be an integer between 1 and 10` | | `400` | `stream and partial_images are not supported on POST /v1/images/generations. This endpoint does not stream: it returns one JSON response with the final image. Remove stream and partial_images and send the request again.` | | `400` | `n must be 2 or less when size is larger than 1536x1024 (1,572,864 pixels). You asked for 4 images at 2880x2880. Split the batch into requests of up to 2 images each.` | | `400` | `Model "foo/bar" is not a supported image generation model` | | `400` | `Model "google/gemini-3-pro-image" is not an image-only model. Multimodal models that generate images are served on POST /v1/chat/completions and return the image in choices[0].message.images[].` | | `401` | `Invalid, disabled, or revoked API key` | | `402` | `Insufficient credits. This request requires up to $0.711630.` | | `403` | `Image generation requires a paid plan. Add credits to unlock all models.` | | `404` | `No recoverable image found for generation "gen-...". It may have expired, or it was created with a different API key.` | | `409` | `A request with Idempotency-Key "..." is already in progress or cannot be replayed` | | `410` | `This request completed successfully, but its recovery copy is no longer available. Retrying the same Idempotency-Key will not generate or charge for another image.` | | `422` | `Idempotency-Key "..." was previously used with a different request body` | | `429` | `Too many concurrent requests for this API key (max 20).` | | `429` | `API key spending limit reached` | | `429` | `Too many large-image requests are running right now. Retry in 15 seconds, or use a size of 1536x1024 or smaller. Nothing was charged.` | | `502` | `Model "openai/gpt-image-2" returned no image for this request. You were not charged.` | | `504` | `Image generation for "openai/gpt-image-2" did not finish within 600 seconds. You were not charged.` | # Overview Source: https://www.airouter.in/docs/api-reference > Base URL, authentication, shared headers, and the error envelope used by every AIRouter endpoint. Every endpoint lives under one base URL and speaks the OpenAI wire format, so the official OpenAI SDKs work unmodified. ``` https://api.airouter.in/v1 ``` ## Endpoints | Method | Path | Auth | Streaming | | --- | --- | --- | --- | | `POST` | [`/v1/chat/completions`](https://www.airouter.in/docs/api-reference/chat-completions) | API key | Yes | | `POST` | [`/v1/embeddings`](https://www.airouter.in/docs/api-reference/embeddings) | API key | No | | `POST` | [`/v1/images/generations`](https://www.airouter.in/docs/api-reference/images) | API key | No | | `POST` | [`/v1/decisions`](https://www.airouter.in/docs/api-reference/decisions) | API key | No | | `POST` | [`/v1/audio/transcriptions`](https://www.airouter.in/docs/api-reference/audio-transcriptions) | API key | No | | `POST` | [`/v1/audio/speech`](https://www.airouter.in/docs/api-reference/audio-speech) | API key | No | | `POST` | [`/v1/audio/generations`](https://www.airouter.in/docs/api-reference/audio-generations) | API key | No | | `GET` | [`/v1/models`](https://www.airouter.in/docs/api-reference/models) | None | — | | `GET` | [`/v1/models/status`](https://www.airouter.in/docs/api-reference/models#get-v1modelsstatus) | None | — | ## Authentication Pass your key as a bearer token. Keys always begin `sk-air-v1-`. ```bash Authorization: Bearer sk-air-v1-... ``` A malformed or missing header fails immediately with `401`: ```json { "error": { "message": "Missing or invalid API key. Use Authorization: Bearer sk-air-v1-...", "type": "auth_error" } } ``` Keys carry an optional spending limit and an optional expiry, and can be disabled or revoked from the dashboard. There are no per-endpoint scopes — a key grants access to every inference endpoint for its owner. ## Client setup **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) ``` **Node.js** ```ts import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); ``` **cURL** ```bash export AIROUTER_API_KEY="sk-air-v1-..." export AIROUTER_BASE_URL="https://api.airouter.in/v1" ``` **Note: Browser clients work.** `/v1/chat/completions` and `/v1/models` send permissive CORS headers, so browser-based front ends can call them directly. Only do this with a key you are willing to expose — anyone who can read the page can read the key. ## Response headers | Header | Endpoints | Meaning | | --- | --- | --- | | `X-Request-Id` | chat, images | Generation id, e.g. `gen-8f3c...`. Quote it in support requests. | | `idempotency-key` | chat, images | Echo of the key you sent | | `idempotent-replayed` | chat, images | `true` when the body came from cache instead of a fresh call | | `x-ratelimit-limit` | all | Requests allowed in the current window | | `x-ratelimit-remaining` | all | Requests left in the current window | | `x-ratelimit-reset` | all | Seconds until the window resets | | `retry-after` | all | Present on `429` | There is no cost header. Cost is reported in the response body. ## Rate limits | Scope | Limit | | --- | --- | | Per IP, all endpoints | 300 requests / minute | | `POST /v1/chat/completions` | 120 requests / minute per key | | `POST /v1/embeddings` | 120 requests / minute per key | | `POST /v1/images/generations` | 30 requests / minute per key | | `POST /v1/decisions` | 120 requests / minute per key | | `POST /v1/audio/transcriptions` | 60 requests / minute per key | | `POST /v1/audio/speech` | 60 requests / minute per key | | `POST /v1/audio/generations` | 60 requests / minute per key | | Concurrent in-flight requests | 20 per key | Hitting these limits regularly? Email [support@airouter.in](mailto:support@airouter.in) with your use case and we'll help. Details in [rate limits](https://www.airouter.in/docs/concepts/rate-limits). ## Idempotency `POST /v1/chat/completions` and `POST /v1/images/generations` accept an `Idempotency-Key` header so a timed-out request can be retried without double-charging. ```bash -H "Idempotency-Key: completion-3f2b8c1e-5d4a-4e7b-9c2a-1b6f8e0d7a55" ``` Keys are at most 255 printable ASCII characters, scoped to the API key that sent them, and live for 24 hours. | Situation | Result | | --- | --- | | First use | Request runs normally | | Replay, same body | Cached status and body, with `idempotent-replayed: true` | | Replay, different body | `422` | | Replay while the first call is still running | `409` | **Warning.** Streamed responses are never cached — a stream cannot be replayed byte-for-byte. On a streaming request the key acts purely as a lock, so retrying after the stream finished returns `409` rather than the original output. ## Errors Every error uses the same envelope. `code` and `details` appear only on certain errors. ```json { "error": { "message": "Model \"foo/bar\" is not supported", "type": "invalid_request_error" } } ``` | Status | `type` | Cause | | --- | --- | --- | | `400` | `invalid_request_error` | Missing field, unknown model, model used on the wrong endpoint, malformed `Idempotency-Key` | | `401` | `auth_error` | Missing, malformed, invalid, disabled, revoked, or expired key | | `402` | `billing_error` | Not enough credits for the request's maximum cost | | `403` | `plan_restricted` | Model requires a paid plan | | `409` | `conflict_error` | A request with this `Idempotency-Key` is in flight or cannot be replayed | | `413` | `invalid_request_error` (`code: request_body_too_large`) | Body over 16 MiB | | `422` | `invalid_request_error` | `Idempotency-Key` reused with a different body | | `429` | `rate_limit_error` | Rate limit, concurrency cap, or API-key spending limit | | `500` | `server_error` | Pricing unavailable for the model | | `502` | `server_error` | All upstream providers failed | The `402` message states the exact amount required: ```json { "error": { "message": "Insufficient credits. This request requires up to $0.042500.", "type": "billing_error" } } ``` Upstream `4xx` responses are passed through with their original status and labelled `invalid_request_error`, so SDK retry logic does not retry a request that will be rejected identically every time. Anything else becomes `502` with the provider's own message appended after `::`. ## Cost reporting Chat responses include the exact amount deducted from your balance: ```json { "usage": { "prompt_tokens": 12, "completion_tokens": 48, "total_tokens": 60, "total_cost": 0.00042 } } ``` `total_cost` is USD. It is present whenever the upstream gateway reports a price — reliably on chat, and usually absent on embeddings and image generation, where the cost is computed server-side from token counts. Billing is identical either way; only the echo differs. Use the dashboard logs, or the `X-Request-Id`, for authoritative per-request cost. # Models Source: https://www.airouter.in/docs/api-reference/models > GET /v1/models — the live model catalog with per-token pricing, context windows and capabilities. No authentication required. ``` GET https://api.airouter.in/v1/models ``` No authentication. This is the authoritative source for model slugs and pricing — prefer fetching it over hardcoding a list, since the catalog is resynced every 6 hours. ## Request **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) for model in client.models.list(): print(model.id) ``` Or without the SDK, since no key is needed: ```python import httpx data = httpx.get("https://api.airouter.in/v1/models").json()["data"] for m in sorted(data, key=lambda m: m["id"]): print(f'{m["id"]:<45} in ${m["pricing"]["prompt"]:>8} / out ${m["pricing"]["completion"]}') ``` **Node.js** ```ts import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const models = await client.models.list(); for (const model of models.data) { console.log(model.id); } ``` Or without the SDK, since no key is needed: ```ts const res = await fetch("https://api.airouter.in/v1/models"); const { data } = await res.json(); for (const m of data) { console.log(m.id, m.pricing.prompt, m.pricing.completion); } ``` **cURL** ```bash # full JSON curl https://api.airouter.in/v1/models # all models curl -s https://api.airouter.in/v1/models | jq -r '.data[].id' # chat models curl -s "https://api.airouter.in/v1/models?type=language" | jq -r '.data[].id' # embedding models curl -s "https://api.airouter.in/v1/models?type=embedding" | jq -r '.data[].id' # image-generating models curl -s "https://api.airouter.in/v1/models?type=image" | jq -r '.data[].id' # decision models curl -s "https://api.airouter.in/v1/models?type=decision" | jq -r '.data[].id' # speech-to-text models curl -s "https://api.airouter.in/v1/models?type=transcription" | jq -r '.data[].id' # text-to-speech models curl -s "https://api.airouter.in/v1/models?type=speech" | jq -r '.data[].id' # music and sound-effect models curl -s "https://api.airouter.in/v1/models?type=audio" | jq -r '.data[].id' ``` ### Query parameters | Field | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `type` | `"language" \| "embedding" \| "image" \| "decision" \| "transcription" \| "speech" \| "audio"` | No | | Filters by model type. Omit to return the entire catalog. Use language for chat models. Case-insensitive. | `?type=` is the only query parameter. There is no pagination — the full list comes back in one response. **Note: type=image does not tell you the endpoint.** Most `image` models are multimodal chat models that return images inside a chat response, so they are called on `/v1/chat/completions`. Image-only models such as `openai/gpt-image-2` are called on `/v1/images/generations` instead. Both appear under `?type=image`. The [image generation reference](https://www.airouter.in/docs/api-reference/images#which-endpoint-for-which-model) shows which endpoint each one uses. ## Response ```json { "object": "list", "data": [ { "id": "openai/gpt-5.2", "object": "model", "owned_by": "openai", "name": "GPT-5.2", "description": "...", "type": "language", "context_length": 400000, "max_tokens": 128000, "tags": ["reasoning", "vision"], "free": false, "pricing": { "prompt": "1.25", "completion": "10", "cache_read": "0.125", "cache_write": null }, "released": "2026-08-07T00:00:00.000Z" } ] } ``` | Field | Meaning | | --- | --- | | `id` | The slug to pass as `model`. Always `provider/model` | | `owned_by` | Model vendor | | `type` | `language`, `embedding`, `image`, or `decision` | | `context_length` | Total context window in tokens | | `max_tokens` | Maximum output tokens, or `null` if unspecified | | `free` | Always `false`. Kept for compatibility; the free program has ended | | `pricing.*` | **Strings**, USD per 1M tokens. `cache_read` / `cache_write` may be `null` | | `pricing.audio_second` | Speech-to-text models: **string**, USD per second of input audio. Audio (music and sound-effect) models: USD per second of generated audio. Their token prices are `"0"` | | `pricing.character` | Text-to-speech models only: **string**, USD per input character. Their token prices are `"0"` | | `released` | ISO 8601 timestamp, or `null` | **Warning: Pricing values are strings.** `pricing` fields are JSON strings rather than numbers. Parse them explicitly (for example with `parseFloat`) before doing arithmetic. ## Looking up a single model There is no single-model endpoint — `GET /v1/models/{id}` returns `404`. That means the OpenAI SDK's `client.models.retrieve("openai/gpt-5.2")` does **not** work. Fetch the list and pick the model out of it instead: **Python** ```python import httpx models = httpx.get("https://api.airouter.in/v1/models").json()["data"] model = next((m for m in models if m["id"] == "openai/gpt-5.2"), None) if model is None: raise ValueError("model not in catalog") print(model["context_length"], model["pricing"]) ``` **Node.js** ```ts const res = await fetch("https://api.airouter.in/v1/models"); const { data } = await res.json(); const model = data.find((m: { id: string }) => m.id === "openai/gpt-5.2"); if (!model) throw new Error("model not in catalog"); console.log(model.context_length, model.pricing); ``` **cURL** ```bash curl -s https://api.airouter.in/v1/models \ | jq '.data[] | select(.id == "openai/gpt-5.2")' ``` ## `GET /v1/models/status` Reports the freshness of the catalog cache. No authentication. Useful for confirming a newly added model has propagated. ```bash curl https://api.airouter.in/v1/models/status ``` ```json { "count": 312, "loadedAt": "2026-09-28T09:00:00.000Z", "nextRefreshAt": "2026-09-28T10:00:00.000Z", "lastError": null } ``` # Authentication Source: https://www.airouter.in/docs/concepts/authentication > How AIRouter API keys are formatted, passed, stored, scoped, and revoked — and what each 401 actually means. Every inference request authenticates with a bearer token in the `Authorization` header. There is no other scheme, no cookie session, and no query-parameter fallback. ```bash Authorization: Bearer sk-air-v1-... ``` ## Key format Keys are the literal prefix `sk-air-v1-` followed by 64 lowercase hex characters (32 random bytes). The prefix is enforced before anything else happens. A header that does not begin `Bearer sk-air-v1-` is rejected immediately, without a database lookup — so a request carrying an OpenAI or Anthropic key fails fast rather than producing a confusing error further down: ```json { "error": { "message": "Missing or invalid API key. Use Authorization: Bearer sk-air-v1-...", "type": "auth_error" } } ``` ## Creating and managing keys Keys are created on the [API keys page](https://www.airouter.in/workspaces/default/keys) (`/workspaces/default/keys`). The full key is displayed **once**, at creation. After that only a hint is stored — the first 10 characters and the last 4 — which is enough to identify a key in a list but not to use it. If you lose a key, you cannot recover it. Create a new one and revoke the old. **Warning.** Anyone holding a key can spend your credits. Keep keys out of version control, out of client-side JavaScript, and out of screenshots and support tickets. ## What a key can do A key grants access to every inference endpoint for the account that owns it. There are no per-endpoint scopes or read-only keys. What you *can* control per key: | Control | Effect | | --- | --- | | Spending limit | Rejects requests once cumulative spend on that key would exceed the limit | | Expiry | Key stops working after a timestamp you choose | | Disable | Reversible off switch | | Revoke | Permanent | A spending limit is the main tool for containing a leaked or experimental key. It is enforced atomically at reservation time, so concurrent requests cannot race past it. Hitting it returns `429` with the numbers included: ```json { "error": { "message": "API key spending limit reached. Key limit: $10.00, used: $9.98, remaining: $0.02, this request requires up to $0.042500.", "type": "api_key_reservation_exceeds_limit", "code": "api_key_reservation_exceeds_limit", "details": { "key_limit": 10, "key_usage": 9.98, "key_remaining": 0.02, "required_reservation": 0.0425 } } } ``` Because the check is against the request's *maximum* possible cost, a request can be refused while the limit still has headroom. See [pricing and credits](https://www.airouter.in/docs/concepts/pricing-and-credits) for why. ## Every 401, and what it means | Message | Cause | | --- | --- | | `Missing or invalid API key. Use Authorization: Bearer sk-air-v1-...` | No header, or it does not start with the required prefix | | `Invalid, disabled, or revoked API key` | Prefix was fine but the key is unknown, disabled, or revoked | | `API key has expired` | Key is valid but past its `expiresAt` | The three are deliberately distinct — the first means "you sent the wrong kind of credential", the second "this credential is not usable", the third "this credential was usable until recently". ## How keys are stored Keys are never stored in plaintext. What is stored is a keyed hash: `HMAC-SHA256(server pepper, key)`. Because the pepper lives outside the database, a leaked database dump does not let an attacker verify guessed keys against it. Older keys were stored as a plain SHA-256 digest. Those still work and are transparently re-hashed to the keyed form the next time they are used, so no action is needed on your side. ## Propagation delay on revoke Key lookups are cached for 60 seconds to keep authentication off the hot path. Disabling or revoking a key **explicitly invalidates that cache**, so the change takes effect immediately rather than after the TTL. That matters when responding to a leak: revoking is effective at once, not up to a minute later. ## Signup restrictions There are none. Accounts can be created, and API keys issued, from any country. A new account starts with a $0 balance; requests need credits — see [plans](https://www.airouter.in/docs/concepts/plans). ## Browser use `/v1/chat/completions` and `/v1/models` send permissive CORS headers, so a browser front end can call them directly. That is intentional — it makes AIRouter usable from web playgrounds and browser-based chat clients. It does not make it safe to ship a key to a browser. Anything in page source or network traffic is readable by the user. For production front ends, proxy through your own backend and keep the key server-side. # Errors Source: https://www.airouter.in/docs/concepts/errors > The error envelope, every status code and type AIRouter returns, which are worth retrying, and the two endpoints that deviate. Errors use an OpenAI-compatible envelope. `code` and `details` appear only on specific errors. ```json { "error": { "message": "Model \"foo/bar\" is not supported", "type": "invalid_request_error" } } ``` **Note: Branch on type, not status.** Several distinct failures share a status code — `429` covers three unrelated problems, and `403` two. `error.type` is the field that actually identifies what went wrong. ## Status codes | Status | `type` | Cause | Retry? | | --- | --- | --- | --- | | `400` | `invalid_request_error` | Missing field, unknown model, wrong endpoint for the model, malformed idempotency key | No | | `400` | `invalid_request_error` (code `unsupported_parameter`) | A parameter AIRouter doesn't support, such as a fallback `models` list. `param` names it; remove it and send again | No | | `401` | `auth_error` | Missing, malformed, invalid, disabled, revoked, or expired key | No | | `402` | `billing_error` | Balance below the request's maximum cost | After topping up | | `403` | `plan_restricted` | Model requires a paid plan | After adding credits | | `409` | `conflict_error` | Idempotency key in flight, or result not replayable | Yes, with the same key | | `413` | `invalid_request_error` | Body over the endpoint's limit | No | | `422` | `invalid_request_error` | Idempotency key reused with a different body | No | | `429` | `rate_limit_error` | Request rate or concurrency cap | Yes, with backoff | | `429` | `api_key_reservation_exceeds_limit` | Key spending limit | No | | `500` | `server_error` | Pricing unavailable for the model | Yes | | `502` | `server_error` | Every upstream provider failed | Yes, with backoff | | `503` | `server_error` | Payment provider unavailable | Yes | | `400` | `zdr_model_unavailable` | [Zero data retention](https://www.airouter.in/docs/concepts/zero-data-retention) requested for a model without a zero-retention provider | No | | `400` | `zdr_unsupported_feature` | Zero data retention requested with plugins or server-side tools | No | | `503` | `zdr_unavailable` | Zero data retention temporarily unavailable | Yes, with backoff | | `503` | `zdr_model_unavailable` | No zero-retention provider is up for this model right now | Yes, with backoff | ## Which are safe to retry **Retry with backoff:** `429` (`rate_limit_error`), `502`, `503`, `500`, and network timeouts. **Do not retry:** `400`, `401`, `413`, `422`, `403`, and `429` with type `api_key_reservation_exceeds_limit`. These are deterministic — the same request fails identically every time. **Retry with the same idempotency key:** `409`. Rotating the key here defeats the protection. See [idempotency](https://www.airouter.in/docs/concepts/idempotency). Upstream `4xx` responses are passed through with their original status and typed `invalid_request_error`, while `5xx` becomes `502` typed `server_error`. That distinction exists so SDK retry logic behaves — most SDKs retry `5xx` and not `4xx`, and mislabelling a rejected request as a server error would cause pointless retries against a provider that will reject it every time. ## Errors with extra detail Two carry more than a message. The spending-limit `429`: ```json { "error": { "message": "API key spending limit reached. Key limit: $10.00, used: $9.98, remaining: $0.02, this request requires up to $0.042500.", "type": "api_key_reservation_exceeds_limit", "code": "api_key_reservation_exceeds_limit", "details": { "key_limit": 10, "key_usage": 9.98, "key_remaining": 0.02, "required_reservation": 0.0425 } } } ``` And the oversized-body `413`, whose message is tailored to the endpoint — chat advises trimming conversation history, embeddings advises splitting the batch. ## A 402 quotes the maximum, not the likely cost ```json { "error": { "message": "Insufficient credits. This request requires up to $0.042500.", "type": "billing_error" } } ``` The figure is the **upper bound** on what the request could cost, reserved before the provider is called. A large `max_tokens` on a modest balance is refused even when the real reply would be cheap. Lowering `max_tokens` lowers the reservation. Full explanation in [pricing and credits](https://www.airouter.in/docs/concepts/pricing-and-credits#why-a-request-reserves-more-than-it-costs). ## Streaming errors are not HTTP errors Once a stream has started, the status is `200` and cannot change. Failures arrive as frames in the body: ```json { "error": { "message": "Stream interrupted: upstream closed", "type": "server_error" } } ``` Status-only error handling silently treats these as success. See [streaming](https://www.airouter.in/docs/concepts/streaming#errors-arrive-inside-a-200). ## Wrong-endpoint errors These `400`s name the endpoint you should have used, because the fix is a different URL rather than a different parameter: | Sent | Response | | --- | --- | | Embedding model to `/v1/chat/completions` | `... is an embedding model. Use POST /v1/embeddings instead.` | | Image-only model to `/v1/chat/completions` | `... cannot be used with chat completions. Use POST /v1/images/generations instead.` | | Multimodal image model to `/v1/images/generations` | `... is not an image-only model. Multimodal models that generate images are served on POST /v1/chat/completions ...` | | Chat model to `/v1/embeddings` | `... is not a supported embedding model` | ## Two endpoints deviate from the envelope Documented because inconsistency is worse when undocumented: - `POST /v1/billing/webhook` returns **plain text** on failure, not JSON. It is called by Razorpay, not by you. - `GET /v1/logs` returns `{"error": ""}` — a bare string rather than the object — for invalid date ranges. It is a console endpoint. Neither is part of the public inference surface. Everything under `/v1/chat/completions`, `/v1/embeddings`, `/v1/images/generations` and `/v1/models` uses the standard envelope. ## Reporting a problem Every chat and image response carries `X-Request-Id` — also the `id` in the response body and every stream frame: ``` X-Request-Id: gen-8f3c1d42-9a7b-4c11-b0e5-2f6d8a1c4e77 ``` Log it. Quoting it in a support request lets the exact generation be found, including which gateway served it and what it was billed. Without it, investigating a single bad response among thousands is guesswork. ## Handling errors in practice ```python from openai import APIStatusError, APITimeoutError try: response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello!"}], ) except APIStatusError as err: kind = (err.body or {}).get("error", {}).get("type") if kind == "billing_error": alert("AIRouter credits exhausted") elif kind == "api_key_reservation_exceeds_limit": alert("API key spending limit reached — will not resolve on retry") elif kind == "rate_limit_error": pass # transient; the SDK already retried elif kind == "plan_restricted": alert("model requires a paid plan") else: raise except APITimeoutError: # Outcome unknown — retry with an idempotency key, not blindly. raise ``` # Idempotency Source: https://www.airouter.in/docs/concepts/idempotency > Retry a timed-out request without paying twice — the header, the four outcomes, and why streams behave differently. A request that times out client-side has an unknown outcome: it may have completed and been billed, or never arrived. Retrying blindly risks paying twice. An idempotency key removes the ambiguity. ```bash -H "Idempotency-Key: completion-3f2b8c1e-5d4a-4e7b-9c2a-1b6f8e0d7a55" ``` Supported on `POST /v1/chat/completions` and `POST /v1/images/generations`. Both are opt-in — without the header, nothing changes. **Note: Not available in zero data retention mode.** Requests running in [zero data retention](https://www.airouter.in/docs/concepts/zero-data-retention) mode never store or replay a response, so `Idempotency-Key` is ignored on them. The response carries `X-AIRouter-Idempotency: ignored-zdr`. Retrying a timed-out ZDR request runs it again and is billed again. ## Key rules | Rule | Value | | --- | --- | | Maximum length | 255 characters | | Allowed characters | Printable ASCII, no spaces | | Scope | The API key that sent it | | Lifetime | 24 hours | Scoping means two API keys can use the same string without colliding. Reuse the **same** key when retrying the **same** request. Generate a new one for a new request. ## Generate a key Any unique string that follows the rules above works. A random UUID is the usual choice. Generate one here for testing with cURL or Postman: _(The web page has an interactive key generator here. Any random UUID works as a key — see the code below.)_ In an application, generate the key in code, **once per request**, before the first attempt, and send that same key on every retry. Never change it between attempts — a new key per attempt is treated as a new request and charged again. The `completion-` prefix below is only a label to make keys easy to spot in your logs. The API does not read it, so use any prefix you like, or none. **Python** ```python import uuid key = f"completion-{uuid.uuid4()}" response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello!"}], extra_headers={"Idempotency-Key": key}, ) ``` **Node.js** ```ts import { randomUUID } from "node:crypto"; const key = `completion-${randomUUID()}`; const response = await client.chat.completions.create( { model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello!" }], }, { headers: { "Idempotency-Key": key } }, ); ``` **cURL** ```bash KEY="completion-$(uuidgen)" curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $KEY" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello!"}] }' ``` Run the same `curl` again with the same `$KEY` to retry safely. `uuidgen` ships with macOS and most Linux distributions. **Note: Keys from your own IDs.** If the request already has a stable ID of its own — an order, a job, a queue message — build the key from it instead of a random UUID, for example `order-4417`. Then every retry of that job uses the same key automatically, even after a crash or a restart, because nothing had to be remembered. The request body must be identical on every retry, or the retry gets `422`. Watch for values that change between attempts, such as a timestamp inside the prompt. ## The four outcomes | Response | Meaning | | --- | --- | | Normal response | First use of this key | | `200` + `idempotent-replayed: true` | Cached result, no second charge | | `409` | The first attempt is still running, or its result cannot be replayed | | `410` | An image request finished, but its stored copy is no longer available | | `422` | This key was used before with a **different** request body | The `422` exists to catch a bug on your side: reusing a key across genuinely different requests would otherwise return the wrong cached answer. Bodies are compared by hash, with object keys sorted first, so key order and whitespace do not matter. ```json { "error": { "message": "Idempotency-Key \"abc123\" was previously used with a different request body", "type": "invalid_request_error" } } ``` ## Streaming is a lock, not a cache A stream cannot be replayed byte-for-byte, so streamed responses are never cached. The key still functions as a lock — which has a consequence worth internalising: **Warning.** On a streaming request, retrying with the same key returns `409` **even after the stream completed successfully**. There is no cached body to serve. For streams, the key protects you from a concurrent duplicate, not from having to re-run a request whose output you lost. If you need the output to survive a dropped connection, buffer it on your side as it arrives. ## Image responses replay from a stored copy Generated images are kept for 24 hours, so a retry with the same key rebuilds the original response from that copy, whatever its size. If the copy is no longer available, the retry returns `410` and does not generate or charge again. A streamed image can't be replayed through the key, but the image itself can still be fetched by its generation ID. Details in [the images reference](https://www.airouter.in/docs/api-reference/images#recovering-an-image). ## Failed attempts do not burn the key If a request errors before producing anything — a gateway failure, a rejected parameter, a concurrency `429` — the reservation is refunded and the key is released. The same key can then be retried cleanly. This is deliberate: a key that stayed locked after a failure would force you to invent a new one for a retry, defeating the purpose. ## A complete retry loop ```python import time, uuid from openai import APITimeoutError, APIStatusError key = f"completion-{uuid.uuid4()}" def complete_once(): return client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Summarise this contract."}], extra_headers={"Idempotency-Key": key}, ) for attempt in range(4): try: response = complete_once() break except APITimeoutError: # Outcome unknown. The same key makes the retry safe: either it # replays the first result or it runs for the first time. time.sleep(2 ** attempt) except APIStatusError as err: if err.status_code == 409: # First attempt still in flight — wait, do not rotate the key. time.sleep(2 ** attempt) continue raise else: raise RuntimeError(f"gave up; investigate Idempotency-Key {key}") ``` Two things this gets right: the key is created **outside** the loop, and a `409` waits rather than generating a fresh key. ## When to bother Worth it whenever a retry would cost real money or produce a duplicate side effect: - **Image generation.** Slow, and billed in full once it starts. A lost image can also be fetched by its generation ID; see [recovering an image](https://www.airouter.in/docs/api-reference/images#recovering-an-image). - **Long non-streaming completions**, where a client timeout is plausible. - **Queue and webhook consumers**, which retry on any failure by design. Deriving the key from the message id makes redelivery free. Less useful for short interactive chat, where a retry is cheap and a user is waiting anyway. # Request Limits Source: https://www.airouter.in/docs/concepts/limits > The 16 MiB body cap, how output length is rewritten, and why a reply stops earlier than you asked for. Two limits shape a request beyond rate limiting: how large the body may be, and how many output tokens the model is actually told to produce. ## Body size `POST /v1/chat/completions`, `POST /v1/embeddings` and `POST /v1/decisions` accept up to **16 MiB**. `POST /v1/audio/transcriptions` accepts audio files up to **19 MB** as multipart/form-data. As base64 in a JSON body, which is a third larger than the file, it accepts files up to about 14 MB. Every other endpoint uses the 1 MiB default. Exceeding it returns `413` before authentication or billing run: ```json { "error": { "message": "Request body is too large (limit 16 MiB). Chat clients resend the entire conversation on every request, so this is usually caused by accumulated history rather than the latest message. Start a new conversation, or remove older messages, tool results, and attachments.", "type": "invalid_request_error", "code": "request_body_too_large" } } ``` **Note: It is rarely the message you just sent.** OpenAI-compatible clients are stateless: they resend the **whole conversation** on every turn. A long thread with tool results and base64 images grows until it crosses the cap, so the request that fails is not the one that caused the problem. Trim old turns, drop large tool outputs once consumed, or start a new conversation. For embeddings, split the `input` array into smaller batches. Because the check happens during body parsing, a `413` costs you nothing — no credits are reserved. ## Output length AIRouter rewrites the output-token field on your request. This is the one place your body is modified, and it explains most "why did the reply stop early" reports. **If you send `max_tokens` or `max_completion_tokens`:** the value is clamped down to the model's maximum output, and the *other* field is removed. The GPT-5, o1 and o3 families reject `max_tokens`, while older models reject `max_completion_tokens`, so sending both fails somewhere — AIRouter keeps the one you set. **If you send neither:** `max_tokens` is set to `min(16384, model maximum)`. That default exists for billing reasons. Left unspecified, some providers default to the model's full output ceiling — which can be hundreds of thousands of tokens — and the credit reservation has to match. You would hit `402` on a request whose real reply was 200 tokens. The bounded default keeps reservations proportionate. **Warning: Ask explicitly for long outputs.** If you need more than 16,384 output tokens, set `max_tokens` yourself. A reply truncating at roughly 16k tokens with `finish_reason: "length"` is this default, not a model limitation. ## Context versus output Two different numbers from the catalog: | Field | Meaning | | --- | --- | | `context_length` | Total tokens the model can hold — prompt **plus** output | | `max_tokens` | Largest output it will generate. May be `null` | Prompt and output share the context window. A 200,000-token context with a 190,000-token prompt leaves 10,000 for the reply regardless of what `max_tokens` says. Exceeding the context window is rejected by the provider and surfaces as a `400` with its message attached. ## Unknown fields pass through The request body is forwarded to the provider almost untouched. `tools`, `tool_choice`, `response_format`, `seed`, `reasoning` and vision content parts all work wherever the model supports them, even though they are not in AIRouter's own type definitions. The trade-off: **AIRouter does not validate them.** A typo in a field name is not caught here — it is either ignored by the provider or rejected with the provider's own `400`, passed through with its original status. If a parameter seems to have no effect, check the model actually supports it. ## Batch sizes `POST /v1/embeddings` takes a string or an array. The array is bounded only by the 16 MiB body cap, but each individual input is bounded by the model's own context window — typically around 8,000 tokens. Batching is the right default: the request-rate limit counts requests, not tokens, so one call with 100 inputs costs one unit of your 120/minute budget rather than 100. ## Timeouts | Phase | Ceiling | | --- | --- | | Non-streaming request | 600 seconds in total, including any fallback | | Streaming, to first byte | 120 seconds per attempt | | Streaming, after first byte | No limit | | Image models | 600 seconds to produce the image, streaming or not | | Decision models | 120 seconds in total; a timeout returns `504` and is not charged | Set your client timeout comfortably above the relevant ceiling — a client timeout of 60 seconds on a non-streaming call will abandon requests that were going to succeed, and you are still billed for them. ## Summary | Limit | Value | | --- | --- | | Chat / embeddings / decisions body | 16 MiB | | Speech-to-text audio file | 19 MB multipart (about 14 MB as JSON base64), 2 hours | | Text-to-speech input | 5,000 characters (4,096 on OpenAI, 2,500 on eleven-v3 and eleven-v4) | | Generated audio length | Music 3–300 s, sound effects 0.5–30 s | | Other endpoints body | 1 MiB | | Default output tokens | `min(16384, model maximum)` | | Images per request | 1–10; at most 2 when `size` is larger than 1536x1024 | | Idempotency key length | 255 characters | | Generated images kept for recovery | 24 hours | | Credit purchase | $1–$500 | # Models Source: https://www.airouter.in/docs/concepts/models > Slug conventions, how the catalog stays in sync, and which endpoint each model type belongs to. Models are addressed by a `provider/model` slug. The provider prefix is the vendor that owns the model, not the gateway that serves it — so a model reachable through more than one upstream still has exactly one slug. Example using `openai/gpt-5.2`. Any model slug from `GET https://api.airouter.in/v1/models` works in its place. **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello!"}], ) print(response.choices[0].message.content) ``` **Node.js** ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer sk-air-v1-..." \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ## The catalog is the source of truth `GET /v1/models` is public, requires no key, and is resynced every 6 hours. Fetch it rather than hardcoding a list. Models are added and retired continuously. A slug that worked last month can disappear, and a hardcoded slug then fails with a `400` at request time. The catalog is the only reliable answer to "what can I call right now". ```bash # all models curl -s https://api.airouter.in/v1/models | jq -r '.data[].id' # chat models (use with /v1/chat/completions) curl -s "https://api.airouter.in/v1/models?type=language" | jq -r '.data[].id' # embedding models (use with /v1/embeddings) curl -s "https://api.airouter.in/v1/models?type=embedding" | jq -r '.data[].id' # image-generating models curl -s "https://api.airouter.in/v1/models?type=image" | jq -r '.data[].id' ``` See the [models API reference](https://www.airouter.in/docs/api-reference/models) for the full response shape. ## Model types decide the endpoint Each model has a `type`, and the type determines which endpoint accepts it. Sending a model to the wrong endpoint is a `400`, not a silent reroute. | `type` | Endpoint | Notes | | --- | --- | --- | | `language` | `POST /v1/chat/completions` | Chat models | | `embedding` | `POST /v1/embeddings` | Vectors, not text | | `image` | Depends on the model | See below | `image` is the one type that does not map to a single endpoint. Multimodal models that return images inside a chat response use `/v1/chat/completions`, while image-only models such as `openai/gpt-image-2` use `/v1/images/generations` with a different request shape. The [image generation reference](https://www.airouter.in/docs/api-reference/images#which-endpoint-for-which-model) has the full breakdown. ## Zero data retention `GET /v1/models` adds a `zdr` boolean to chat models that can be served in [zero data retention](https://www.airouter.in/docs/concepts/zero-data-retention) mode. `GET /v1/zdr/models` returns only those models. ## Pricing fields `pricing` values are **strings**, quoted in USD per 1 million tokens: ```json { "pricing": { "prompt": "1.25", "completion": "10", "cache_read": "0.125", "cache_write": null } } ``` `cache_read` and `cache_write` are `null` on models without prompt caching. ## Free versus paid access Every model carries a `free` boolean. The free program has ended, so it is always `false`; the field is kept so existing code that reads it keeps working. Every model in the catalog is available to paid accounts. An account that has not bought credits yet gets `403` on any model: ```json { "error": { "message": "This model requires a paid plan. Add credits to unlock all models.", "type": "plan_restricted" } } ``` See [plans](https://www.airouter.in/docs/concepts/plans). ## Output limits and context Two separate numbers, easily confused: - `context_length` — total tokens the model can consider, prompt plus output. - `max_tokens` — the largest output it will produce. May be `null` if the upstream does not publish one. AIRouter clamps a requested output length down to `max_tokens`, and injects a bounded default when you ask for nothing. That behaviour is described in [limits](https://www.airouter.in/docs/concepts/limits), and it is the usual explanation for a reply that stops earlier than expected. ## Checking catalog freshness ```bash curl https://api.airouter.in/v1/models/status ``` Returns the model count, when the cache was last loaded, when it refreshes next, and the last refresh error if there was one. Useful for confirming a newly added model has propagated before you depend on it. # Plans Source: https://www.airouter.in/docs/concepts/plans > There is no free tier. A new account can create API keys, and the first credit purchase unlocks every model. There is no subscription and no free tier. A new account has a $0 balance and can create API keys, but it cannot call any model until you add credits. Your first credit purchase moves the account to the **paid plan**, which unlocks the whole catalog. | | Before your first purchase | Paid plan | | --- | --- | --- | | API keys | Can be created | Can be created | | Models | None — requests return `403` | The entire catalog | | Billing | — | Per token, from your credit balance | | Balance expiry | Kept | Does not expire | | Monthly fee | None | None | **Note: Not a free tier.** Internally, an account that has not bought credits yet is labelled `free`. That label is only a state: it carries no balance, no free usage and no models. It is the reason requests are refused with `plan_restricted` until your first purchase. ## Becoming a paid account Your **first successful credit purchase** promotes the account. From that moment every model in the catalog is unlocked and your balance is spendable. There is no separate upgrade step, no plan picker, and no minimum commitment. The minimum purchase is $1. You can sign up and create API keys before paying, so you can wire up your integration first and add credits when you are ready to send requests. ## Before you add credits Requests from an account that has not bought credits yet return `403` `plan_restricted` with an upgrade prompt. The message differs slightly per endpoint: | Endpoint | Message | | --- | --- | | `/v1/chat/completions` | `This model requires a paid plan. Add credits to unlock all models.` | | `/v1/embeddings` | `Embedding models require a paid plan. Add credits to unlock all models.` | | `/v1/images/generations` | `Image generation requires a paid plan. Add credits to unlock all models.` | | `/v1/decisions` | `Decision models require a paid plan. Add credits to unlock all models.` | | `/v1/audio/transcriptions` | `Speech-to-text requires a paid plan. Add credits to unlock all models.` | | `/v1/audio/speech` | `Text-to-speech requires a paid plan. Add credits to unlock all models.` | | `/v1/audio/generations` | `Audio generation requires a paid plan. Add credits to unlock all models.` | **Note: The earlier free program has ended.** AIRouter previously ran a time-boxed free program with a $1 signup credit and the `airouter/free` model. Both have been retired. Any credit left over from that program is kept on your account and becomes usable after your first purchase. Every model it covered is still available on the paid plan. The `free` field on [`GET /v1/models`](https://www.airouter.in/docs/api-reference/models) is still returned for compatibility and is now always `false`. ## Where you can sign up Sign-up is open in every country. Payments run through Razorpay in ₹ — see the [quickstart](https://www.airouter.in/docs/quickstart) for supported payment methods. # Pricing and Credits Source: https://www.airouter.in/docs/concepts/pricing-and-credits > How per-token billing works, why a request reserves more than it costs, and how to track what you spend. You prepay for credits in USD and spend them per token. There is no subscription, no monthly minimum, and no expiry once you are on the paid plan. Add credits on the [credits page](https://www.airouter.in/settings/credits) (`/settings/credits`). ## What a request costs Chat responses report the exact amount deducted: ```json { "usage": { "prompt_tokens": 24, "completion_tokens": 14, "total_tokens": 38, "total_cost": 0.00019 } } ``` `total_cost` is USD. Per-token rates come from the catalog, quoted in USD per 1M tokens — see [models](https://www.airouter.in/docs/concepts/models#pricing-fields). **Note.** `total_cost` appears whenever the upstream gateway reports a price. That is reliable on chat and generally **absent** on embeddings and image generation, where AIRouter computes the charge from token counts instead. Billing is identical either way; only the echo differs. The dashboard logs are authoritative — correlate using the `X-Request-Id` header. ## Why a request reserves more than it costs This is the single most surprising part of billing, and it explains a class of `402` that otherwise looks wrong. Before calling the provider, AIRouter cannot know what a request will cost — output length is not known until the model has finished. So it computes an **upper bound** and deducts that from your balance up front. When the response arrives, the difference between the reservation and the real cost is refunded in the same transaction that records the usage. ``` reserve max possible cost → balance decreases call provider refund reserved − actual → balance partially restored ``` Two consequences: **A `402` quotes the maximum, not the likely cost.** ```json { "error": { "message": "Insufficient credits. This request requires up to $0.042500.", "type": "billing_error" } } ``` **A large `max_tokens` on a small balance gets refused even when the real reply would be cheap.** Asking for 100,000 output tokens reserves for 100,000 output tokens. If you are hitting `402` with credits remaining, lower `max_tokens`. The same logic applies to per-key spending limits, which is why a key can be refused while its limit still shows headroom. ## Tracking spend - `usage.total_cost` on each chat response, for per-request attribution. - `X-Request-Id` on the response, matching the generation id in your logs. - The [logs page](https://www.airouter.in/logs) (`/logs`), filterable by model, key, and date, with a total. - Per-key spending limits, if you want a hard ceiling rather than a report. # Rate Limits Source: https://www.airouter.in/docs/concepts/rate-limits > The four independent limits, the three distinct causes of a 429, and how to tell them apart. Four limits apply independently. Any one of them can produce a `429`, and the remedies differ, so the message matters. | Limit | Scope | Value | | --- | --- | --- | | Global | Per IP, all endpoints | 300 requests / minute | | Chat | Per API key | 120 requests / minute | | Embeddings | Per API key | 120 requests / minute | | Images | Per API key | 30 requests / minute | | Concurrency | Per API key | 20 in flight | Per-key limits are keyed on the key itself, not the account — so two keys get two independent buckets, and a runaway script on one key does not throttle another. **Note: Need higher limits?.** If you keep hitting rate limits, email us at [support@airouter.in](mailto:support@airouter.in) with your use case and the limits you need, and we'll help. ## Headers Standard rate-limit headers are returned on every response: | Header | Meaning | | --- | --- | | `x-ratelimit-limit` | Requests permitted in the window | | `x-ratelimit-remaining` | Requests left | | `x-ratelimit-reset` | Seconds until the window resets | | `retry-after` | Present on `429` — seconds to wait | Honour `retry-after` when it is present rather than guessing a backoff. ## Telling the three 429s apart They share a status code and nothing else. **Request rate exceeded** — too many requests per minute. Carries `retry-after`. **Concurrency cap** — 20 requests already in flight on this key: ```json { "error": { "message": "Too many concurrent requests for this API key (max 20).", "type": "rate_limit_error" } } ``` Waiting for an in-flight request to finish clears this; waiting for a clock window does not. It is the limit long-running streams hit most. **Spending limit** — not a rate limit at all, despite the status: ```json { "error": { "message": "API key spending limit reached. Key limit: $10.00, used: $9.98, remaining: $0.02, this request requires up to $0.042500.", "type": "api_key_reservation_exceeds_limit", "code": "api_key_reservation_exceeds_limit" } } ``` Retrying will never succeed. Raise or remove the key's limit — see [authentication](https://www.airouter.in/docs/concepts/authentication#what-a-key-can-do). **Warning.** Branch on `error.type`, not on the status code. A retry loop that treats every `429` as transient will spin forever against a spending limit, and burn its retry budget against a concurrency cap it is itself causing. ## Handling limits well Use the SDK's built-in retry where you can — it already implements exponential backoff with jitter and respects `retry-after`: ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", max_retries=4, ) ``` Beyond that: **Bound your own concurrency.** A semaphore at 20 or below turns concurrency `429`s into queueing, which is almost always what you wanted. ```python import asyncio sem = asyncio.Semaphore(16) async def complete(prompt: str): async with sem: return await client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": prompt}], ) ``` **Batch embeddings instead of looping.** `input` accepts an array, so a hundred documents can be one request rather than a hundred — the request-rate limit counts calls, not tokens. See [the embeddings reference](https://www.airouter.in/docs/api-reference/embeddings#batching). **Do not retry `4xx` other than `429`.** They are deterministic. ## Long streams and the concurrency cap A slot is held for the entire life of a request, and a stream can run for minutes. Twenty concurrent streams saturate the cap even at a trivial request rate — this is the limit interactive applications hit first, and the fix is queueing rather than retrying. Cancelled streams release their slot when the connection closes, though note that a cancelled stream is still billed for what was generated. See [streaming](https://www.airouter.in/docs/concepts/streaming#cancellation-and-cost). ## Requests that never reach a limit `GET /v1/models` and `GET /v1/models/status` are public and need no key, so they fall under the global per-IP limit only. They are cheap and safe to poll, although the catalog only changes every 6 hours — caching it locally is kinder and faster than refetching. # Routing and Failover Source: https://www.airouter.in/docs/concepts/routing-and-failover > How a request is dispatched across upstream gateways, when a retry happens automatically, and what a 502 actually tells you. A model slug does not name a connection. AIRouter decides which upstream gateway serves each request, and transparently tries another when the first fails — as long as nothing has been sent to you yet. ## The attempt order Each request is attempted against an ordered list of gateways: a configured primary, then the remaining one as a fallback. A gateway is skipped entirely when either - it has no credentials configured, or - it carries no equivalent of the requested model slug. The second case matters because coverage differs between gateways. A model available on only one of them simply has a one-entry attempt list, and a failure there is terminal. ## When failover happens | Situation | Behaviour | | --- | --- | | Primary fails before sending any bytes | Fallback is tried, invisibly to you | | Primary fails after the first byte | No retry possible | | Primary returns a `4xx` | Passed through to you, not retried | | Every gateway fails | `502` with the last upstream message | A `4xx` from a provider means the request itself was rejected — a malformed parameter, a content filter, an unsupported combination. Retrying it against another gateway would produce the same rejection, so it is surfaced immediately with its original status. This also keeps SDK retry logic honest: the error `type` is set to `invalid_request_error` for `4xx` and `server_error` for `5xx`, and most SDKs only retry the latter. ## Why post-first-byte failures cannot be retried Once a byte has reached your connection, the response is partly delivered. Switching gateways at that point would concatenate the beginning of one generation with the middle of another. So the failure is reported in-band instead — for streams, as an error frame inside a response whose status is already `200`. That mechanism is described in [streaming](https://www.airouter.in/docs/concepts/streaming#errors-arrive-inside-a-200), and it is the main reason streaming clients need to inspect frames rather than status codes. ## Reading a 502 ```json { "error": { "message": "Request failed for \"openai/gpt-5.2\": the provider returned HTTP 503: service temporarily unavailable", "type": "server_error" } } ``` The text after the HTTP status is the upstream provider's own message. That is usually the actionable part — it distinguishes a provider outage from a rejected parameter from a model being temporarily overloaded. A `502` means every eligible provider route was tried and none succeeded. Retrying is reasonable, with backoff. ## Timeouts | Phase | Ceiling | | --- | --- | | Non-streaming request | 600 seconds in total, including any fallback | | Streaming, to first byte | 120 seconds per attempt | | Streaming, after first byte | No limit | | Image models | 600 seconds to produce the image, streaming or not | A streaming request that falls back can exceed 120 seconds before its first byte in total. Set your own client timeout above the ceiling for the mode you are using, or you will abandon requests the server is still successfully handling. Non-streaming responses that take longer than 90 seconds start with whitespace; see [long non-streaming requests](https://www.airouter.in/docs/concepts/streaming#long-non-streaming-requests). ## Billing across failover You are charged for what was served, once. A failed attempt that produced nothing is not billed — the reservation is released and either retried elsewhere or refunded. If the provider resolves your slug to a different model internally, that resolution is recorded in your logs, so an unexpected cost or behaviour change can be traced. ## What you cannot control There is no per-request gateway override, no `provider` parameter, and no way to pin a request to a specific upstream. Routing is an operational concern, and the primary can change without notice. The practical implication: do not build logic that depends on which gateway served you. Depend on the model slug, which is stable, and on the response shape, which is normalised. ## Idempotency across retries Automatic failover is internal and safe — one request, one charge, regardless of how many gateways were tried. **Your own** retries are the ones that risk a double charge, which is what [idempotency keys](https://www.airouter.in/docs/concepts/idempotency) exist for. # Streaming Source: https://www.airouter.in/docs/concepts/streaming > SSE frame format, why a failed stream still returns 200, and what cancelling mid-stream costs you. Set `stream: true` on a chat completion and the response is a `text/event-stream` of standard OpenAI delta frames. Every OpenAI SDK consumes them natively. Example using `openai/gpt-5.2`. Any model slug from `GET https://api.airouter.in/v1/models` works in its place. **Python** ```python stream = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Count to five."}], stream=True, ) for chunk in stream: delta = chunk.choices[0].delta.content if delta: print(delta, end="", flush=True) ``` **Node.js** ```typescript const stream = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [{ role: "user", content: "Count to five." }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content ?? ""); } ``` **cURL** ```bash curl -N https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer sk-air-v1-..." \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Count to five."}], "stream": true }' ``` ## Response headers Written before the first token is generated: ``` Content-Type: text/event-stream Cache-Control: no-cache Connection: keep-alive X-Request-Id: gen-8f3c1d42-9a7b-4c11-b0e5-2f6d8a1c4e77 ``` ## Frame format Upstream frames are forwarded unchanged, except that each `id` is rewritten to AIRouter's own generation id so it matches `X-Request-Id`: ``` data: {"id":"gen-8f3c...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"}}]} data: {"id":"gen-8f3c...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"One"}}]} data: {"id":"gen-8f3c...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":", two"}}]} data: [DONE] ``` ## Keepalive comments When nothing has been sent for 15 seconds, for example while a model is thinking, the stream sends an SSE comment line: ``` : keepalive ``` This stops proxies on the way from closing a quiet connection. A stream is never closed for being quiet: it ends when the model finishes, when an error frame is sent, or when you disconnect. SSE clients, including the OpenAI SDKs, ignore lines that start with `:`. If you parse the stream yourself, skip every line that starts with `:`. ## Errors arrive inside a 200 This is the most important thing to know about streaming here, and the easiest thing to get wrong. Response headers are committed before generation starts. Once they are sent the HTTP status is fixed at `200` and cannot be changed — so a provider failure partway through a generation **cannot** be reported as a `5xx`. It is delivered as a frame in the body instead: ```json { "error": { "message": "Stream interrupted: upstream closed", "type": "server_error" } } ``` A failure to reach any provider at all looks the same way: ```json { "error": { "message": "All routers failed", "type": "server_error" } } ``` **Warning: Check every frame for an error key.** Client code that inspects only the HTTP status will treat a truncated answer as a complete one. A user sees a reply that stops mid-sentence and no error is logged anywhere in your system. ```python stream = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Explain SSE."}], stream=True, ) chunks = [] for chunk in stream: # The SDK surfaces unrecognised frames as raw dicts; an error frame has no # `choices`, so guard before reading it. err = getattr(chunk, "error", None) if err: raise RuntimeError(f"stream failed after {len(chunks)} chunks: {err}") if chunk.choices and chunk.choices[0].delta.content: chunks.append(chunk.choices[0].delta.content) print("".join(chunks)) ``` ## No failover once bytes are sent AIRouter attempts a second provider when the first fails — but only while no frame has been written to your connection yet. Keepalive comments don't count. After the first frame, the response is already partly delivered and switching providers would splice two different generations together. That is the mechanical reason mid-stream errors surface in the body rather than being retried. A pre-first-byte failure is invisible to you and gets retried elsewhere; a post-first-byte failure is yours to handle. Related: [routing and failover](https://www.airouter.in/docs/concepts/routing-and-failover). ## Cancellation and cost Disconnecting stops delivery. It does **not** stop the charge. The upstream provider has already generated those tokens and bills us for them regardless of whether you are still listening. So on disconnect AIRouter keeps reading the upstream response for up to **90 seconds** to capture the real usage figure, and bills you that amount. If the usage frame never arrives, cost is estimated from the characters actually delivered and **capped at the request's reservation**, so a cancel can never cost more than the request could have. | Request type | Client disconnects | Outcome | | --- | --- | --- | | Streaming | Mid-generation | Billed for what the provider generated | | Non-streaming | Before the response | The request still runs to completion and is billed for what the provider generated. Nothing is charged if no provider answered. | | Image models, streaming or not | At any time | The image is still generated and billed in full, and kept for 24 hours so you can [recover it](https://www.airouter.in/docs/api-reference/images#recovering-an-image) | A cancelled request is recorded with `status: cancelled` in your logs, so it is distinguishable from a completed one after the fact. **Note: Image models: prefer non-streaming.** Streaming gives no benefit for models that return images. The whole image arrives in one frame at the end, and it is billed in full either way. While you wait, an image stream sends `: keepalive` comment lines every 15 seconds, which SSE clients ignore. **Note.** If you cancel streams frequently — an interactive UI with a stop button, say — this is real spend. Lowering `max_tokens` limits how much a cancelled generation can cost, because the provider stops sooner. ## Time limits A streaming attempt has 120 seconds to produce its first byte. After that the deadline is disarmed and a long generation can continue as long as it needs. Non-streaming requests have 600 seconds in total, including any retry on a second provider. Image models have 600 seconds to produce their image, streaming or not. ### Long non-streaming requests If a non-streaming response is not ready after 90 seconds, the headers are sent with status `200` and the body starts with whitespace until the result is ready. JSON parsers ignore the whitespace, and it stops proxies on the way from closing an idle connection. Because the status is already `200` by then, a failure after that point is reported in the body, together with the status it would have had: ```json { "error": { "message": "...", "type": "server_error" }, "status": 502 } ``` Check for an `error` key even when the status is `200`. ## What does not support streaming `POST /v1/embeddings` returns a single JSON body. Passing `stream: true` to it has no effect. `POST /v1/images/generations` also returns a single JSON body, with the final image. It rejects `stream: true` and `partial_images` with a `400` (`streaming_not_supported`) before anything is generated or charged, so a client that expects an event stream gets a clear error instead of an empty stream. `stream: false` and `partial_images: 0` are accepted. # Zero Data Retention Source: https://www.airouter.in/docs/concepts/zero-data-retention > Run chat completions only on providers that do not store or train on your prompts. How to turn it on, what it covers, and what changes. Zero data retention (ZDR) mode restricts a chat request to providers that have committed not to retain your prompts or completions and not to train on them. It is off by default. **Warning: Chat completions only.** ZDR covers `POST /v1/chat/completions`. Embeddings and image generation have no ZDR route and **run normally** even when ZDR is enabled on your account. Those responses carry `X-AIRouter-ZDR: false` so you can tell. ## Turn it on There are three switches. ZDR applies to a request if **any** of them is on. | Switch | Where | Scope | | --- | --- | --- | | Account setting | [Privacy](https://www.airouter.in/settings/privacy) page | Every chat request on the account | | Body field | `"zdr": true` in the request JSON | That request | | Header | `X-AIRouter-ZDR: true` | That request | A request cannot turn the account setting off. `"zdr": false` or `X-AIRouter-ZDR: false` on an account with ZDR enabled still runs in ZDR mode. The account setting takes effect on the next request. | Account setting | Body / header | Result | | --- | --- | --- | | Off | not sent, or `false` | Normal | | Off | `true` | ZDR | | On | not sent | ZDR | | On | `false` | ZDR | `zdr` must be a boolean and the header must be `true` or `false`. Anything else returns `400`. Both do the same thing. The header is usually easier, because OpenAI SDKs take extra headers natively while an extra body field needs an escape hatch. ### Header **Python** ```python response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello!"}], extra_headers={"X-AIRouter-ZDR": "true"}, ) ``` **Node.js** ```ts const response = await client.chat.completions.create( { model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello!" }], }, { headers: { "X-AIRouter-ZDR": "true" } }, ); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -H "X-AIRouter-ZDR: true" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ### Body field `zdr` is not part of the OpenAI schema, so SDKs need to be told to pass it through. **Python** ```python response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello!"}], extra_body={"zdr": True}, ) ``` **Node.js** ```ts import type OpenAI from "openai"; const body = { model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello!" }], zdr: true, }; // The SDK's types do not know about `zdr`, but it is sent as-is. const response = await client.chat.completions.create( body as unknown as OpenAI.ChatCompletionCreateParamsNonStreaming, ); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello!"}], "zdr": true }' ``` Every chat response states what happened in `X-AIRouter-ZDR` (`true` or `false`). Browser clients can read it. ## Which models support it Not every model has a zero-retention provider. List the ones that do: ```bash curl https://api.airouter.in/v1/zdr/models ``` The response has the same shape as `GET /v1/models`. The list is public and changes as providers change their terms. `GET /v1/models` also marks each model with a `zdr` boolean. Requesting a model that is not on the list returns `400` with type `zdr_model_unavailable`. It is never silently served in normal mode. ## What changes in ZDR mode - **No fallback.** A ZDR request is served only by a zero-retention provider. If none is available, the request fails rather than falling back to a normal route. See [routing and failover](https://www.airouter.in/docs/concepts/routing-and-failover). - **Fewer models.** Only models returned by `/v1/zdr/models`. - **No server-side tools.** Requests using `plugins`, `web_search_options`, or non-function tools are rejected with `zdr_unsupported_feature`, because those can run on third-party services outside the guarantee. Ordinary function tools work. - **Provider preferences stay strict.** Provider preferences you send can narrow routing but cannot weaken the zero-retention requirement. - **Idempotency is ignored.** Replaying a response needs the response to be stored, which ZDR forbids. `Idempotency-Key` is not stored or replayed, and the response carries `X-AIRouter-Idempotency: ignored-zdr`. See [idempotency](https://www.airouter.in/docs/concepts/idempotency). - **Error details are generic.** Provider error bodies are not logged and errors do not name the underlying service. Billing, rate limits and streaming work as usual. ## What we still keep ZDR is about prompt and completion content at the provider. AIRouter still keeps the metadata needed to bill you and show your logs: model, token counts, cost, timing, status, and a `zdr` flag marking the request. Prompt and completion text is not stored by AIRouter. ## Errors | Status | `type` | Meaning | | --- | --- | --- | | `400` | `invalid_request_error` | `zdr` or `X-AIRouter-ZDR` has an invalid value | | `400` | `zdr_model_unavailable` | Model has no zero-retention provider | | `400` | `zdr_unsupported_feature` | Request uses plugins or server-side tools | | `503` | `zdr_unavailable` | ZDR is temporarily unavailable. Retry shortly | | `503` | `zdr_model_unavailable` | No zero-retention provider is up for this model right now. Retry later or choose another model | `zdr_model_unavailable` appears under both statuses, and the status is what tells you whether to retry. `400` means the model is not in the ZDR catalog at all, so retrying is pointless — pick another model. `503` means the model is ZDR-capable but nothing is serving it at this moment, so a retry can succeed. The two `503`s differ in scope: `zdr_unavailable` affects every ZDR request, while `zdr_model_unavailable` affects only that model, so switching models is worth trying. See [errors](https://www.airouter.in/docs/concepts/errors) for the full list. # Introduction Source: https://www.airouter.in/docs > AIRouter is an OpenAI-compatible gateway to hundreds of AI models behind a single API key, billed per token in credits you can top up with UPI. AIRouter exposes one OpenAI-compatible endpoint in front of every model we carry. Point any OpenAI SDK at our base URL, pass an AIRouter key, and change the model slug — nothing else about your code has to change. ``` https://api.airouter.in/v1 ``` ## Your first request Pick any model from the live catalog — the sample updates to match. Example using `openai/gpt-5.2`. Any model slug from `GET https://api.airouter.in/v1/models` works in its place. **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello!"}], ) print(response.choices[0].message.content) ``` **Node.js** ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer sk-air-v1-..." \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello!"}] }' ``` **Warning: Treat keys like passwords.** Keys are shown once at creation. Never commit one to git, never ship one in client-side JavaScript, and never paste one into a shared document. Anyone holding the key can spend your credits. ## What you can call | Endpoint | Purpose | | --- | --- | | `POST /v1/chat/completions` | Chat and completions, streaming or buffered | | `POST /v1/embeddings` | Vector embeddings | | `POST /v1/images/generations` | Image generation | | `POST /v1/decisions` | Typed questions answered with probabilities | | `POST /v1/audio/transcriptions` | Speech-to-text for an audio file | | `POST /v1/audio/speech` | Text-to-speech, returns an audio file | | `POST /v1/audio/generations` | Music and sound effects from a description | | `GET /v1/models` | The live model catalog, no auth required | Model slugs are always `provider/model` — `openai/gpt-5.2`, `anthropic/claude-sonnet-4.5`, `google/gemini-3-flash`. Fetch `GET /v1/models` for the authoritative list and current per-token pricing. ## How billing works Requests are priced per token and drawn from a prepaid credit balance. Every response carries its own cost: ```json { "usage": { "prompt_tokens": 12, "completion_tokens": 48, "total_tokens": 60, "total_cost": 0.00042 } } ``` Credits are bought in USD and paid in INR — UPI, net banking, or debit card through Razorpay, with no international card required. ## See it in action Video: [AIRouter demo: buy OpenAI, Claude and Gemini APIs with UPI](https://www.youtube.com/watch?v=xVcf6eInIgQ) ## Next steps - [Quickstart](https://www.airouter.in/docs/quickstart) — Account to first API call in five minutes. - [Browse models](https://www.airouter.in/models) — Every model we carry, with live pricing. # Migrating from OpenAI Source: https://www.airouter.in/docs/migrating-from-openai > Two lines change. Here is the diff, plus the handful of behavioural differences worth knowing before you ship. AIRouter implements the OpenAI wire format, so migration is a configuration change rather than a rewrite. Keep your SDK, your request shapes, and your response parsing. ## The diff **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", # was OPENAI_API_KEY base_url="https://api.airouter.in/v1", # added ) response = client.chat.completions.create( model="openai/gpt-5.2", # was "gpt-5.2" messages=[{"role": "user", "content": "Hello!"}], ) ``` **Node.js** ```ts import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", // was OPENAI_API_KEY baseURL: "https://api.airouter.in/v1", // added }); const response = await client.chat.completions.create({ model: "openai/gpt-5.2", // was "gpt-5.2" messages: [{ role: "user", content: "Hello!" }], }); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer sk-air-v1-..." \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello!"}] }' ``` If your code already reads configuration from the environment, there is no code change at all: ```bash export OPENAI_API_KEY="sk-air-v1-..." export OPENAI_BASE_URL="https://api.airouter.in/v1" ``` ## Model names gain a provider prefix The one change that touches application code: every slug is `provider/model`. | OpenAI | AIRouter | | --- | --- | | `gpt-5.2` | `openai/gpt-5.2` | | `text-embedding-3-small` | `openai/text-embedding-3-small` | Models from other vendors follow the same rule — `anthropic/claude-sonnet-4.5`, `google/gemini-3-flash` — which is the point: one key and one base URL reach all of them. Fetch [`GET /v1/models`](https://www.airouter.in/docs/api-reference/models) for the authoritative list; do not hardcode slugs, since models are retired over time. Example using `openai/gpt-5.2`. Any model slug from `GET https://api.airouter.in/v1/models` works in its place. **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello!"}], ) print(response.choices[0].message.content) ``` **Node.js** ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer sk-air-v1-..." \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ## What works unchanged - Chat completions, buffered and streaming - Embeddings, single and batched - `tools` and `tool_choice` - `response_format`, including JSON mode and structured outputs - Vision via `image_url` content parts - `seed`, `stop`, `temperature`, `top_p`, `logprobs` - The official Python and Node SDKs, LangChain, LlamaIndex, the Vercel AI SDK, and anything else that accepts a base URL Request bodies are forwarded to the provider nearly untouched, so parameters we do not document still work wherever the underlying model supports them. ## Differences worth knowing ### `usage.total_cost` is added Chat responses include the exact USD amount deducted: ```json { "usage": { "prompt_tokens": 24, "completion_tokens": 14, "total_tokens": 38, "total_cost": 0.00019 } } ``` An extra field, so existing parsing is unaffected. OpenAI gives you no per-request cost at all, which makes attribution easier here. ### Output length gets a default Send no `max_tokens` and AIRouter sets `min(16384, model maximum)` rather than letting the provider pick its own ceiling. If you relied on unbounded output, set `max_tokens` explicitly. Reasoning in [request limits](https://www.airouter.in/docs/concepts/limits#output-length). ### Errors use types you should branch on The envelope matches OpenAI's, with additional `type` values specific to a gateway — `plan_restricted`, `billing_error`, `api_key_reservation_exceeds_limit`. Notably `429` covers three unrelated problems, only one of which is worth retrying. See [errors](https://www.airouter.in/docs/concepts/errors). ### Insufficient credits is a 402 OpenAI bills after the fact; AIRouter is prepaid. A `402` means top up on the [credits page](https://www.airouter.in/settings/credits) (`/settings/credits`). It quotes the request's *maximum* cost, not its likely cost, so a large `max_tokens` on a small balance can be refused for a reply that would have been cheap. ### Streaming failures arrive inside a 200 Headers are sent before generation, so a mid-stream provider failure appears as an error frame in the body while the status stays `200`. Status-only error handling will read a truncated reply as a complete one. This is the most common real migration bug — details in [streaming](https://www.airouter.in/docs/concepts/streaming#errors-arrive-inside-a-200). ### Rate limits differ 120 requests/minute and 20 concurrent per key, rather than OpenAI's tier system. Long-lived streams hit the concurrency cap before the request rate. See [rate limits](https://www.airouter.in/docs/concepts/rate-limits). ## Not implemented | OpenAI feature | Status | | --- | --- | | Assistants, Threads, Runs | Not available | | Files, vector stores, retrieval | Not available | | Fine-tuning | Not available | | Batch API | Not available | | Moderations | Not available | | Audio (speech, transcription) | Not available | | `/v1/images/edits`, `/v1/images/variations` | Not available | | Realtime API | Not available | | `/v1/responses` | Not available — use `/v1/chat/completions` | AIRouter covers chat completions, embeddings, and image generation. Anything built on Assistants or the Responses API needs reworking onto chat completions first. ## Running both side by side Because configuration is per client instance, you can route selectively while you evaluate: ```python from openai import OpenAI openai_client = OpenAI(api_key="sk-...") airouter_client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) def complete(prompt: str, via_airouter: bool = False): client = airouter_client if via_airouter else openai_client model = "openai/gpt-5.2" if via_airouter else "gpt-5.2" return client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}], ) ``` ## Migration checklist ### Add the base URL and key Set `OPENAI_BASE_URL` and `OPENAI_API_KEY`, or pass them to the client. ### Prefix your model slugs Add the provider prefix, and verify each slug against `GET /v1/models`. ### Fix streaming error handling Check each frame for an `error` key rather than relying on the HTTP status. ### Set `max_tokens` where you need long output Anything above 16,384 output tokens must now be requested explicitly. ### Handle 402 and the three kinds of 429 Branch on `error.type`. Only `rate_limit_error` is worth retrying. ### Log `X-Request-Id` It is the only handle for investigating a specific generation later. ## Next steps - [API Reference](https://www.airouter.in/docs/api-reference) — Every endpoint, parameter, and error. - [Errors](https://www.airouter.in/docs/concepts/errors) — What to retry and what never will succeed. - [Browse models](https://www.airouter.in/models) — The full catalog with live pricing. # Use AIRouter with Opencode Source: https://www.airouter.in/docs/opencode > Add AIRouter to Opencode as a custom OpenAI-compatible provider, with setup steps for macOS, Linux and Windows. [Opencode](https://opencode.ai) is a terminal coding agent. It can use any OpenAI-compatible API through a custom provider, and AIRouter is one. You pay with UPI credits and pick any model from the AIRouter catalogue, such as `deepseek/deepseek-v4.1-flash`. You need an AIRouter API key (`sk-air-v1-...`) with credits. See the [quickstart](https://www.airouter.in/docs/quickstart) if you don't have one yet. ### Install Opencode Follow the [Opencode install guide](https://opencode.ai/docs/) for your system, then check that it runs: ```bash opencode --version ``` ### Save your API key as an environment variable The config below reads the key from `AIROUTER_API_KEY`, so it never sits in a file you might commit. **macOS / Linux** macOS uses zsh by default, so add the line to `~/.zshrc`. On Linux with bash, use `~/.bashrc` instead. ```bash echo 'export AIROUTER_API_KEY="sk-air-v1-..."' >> ~/.zshrc source ~/.zshrc ``` **Windows** In PowerShell, store the key for your user account: ```powershell setx AIROUTER_API_KEY "sk-air-v1-..." ``` `setx` only affects terminals opened afterwards, so close PowerShell and open a new window. To use the key in the current window only, run this instead: ```powershell $env:AIROUTER_API_KEY = "sk-air-v1-..." ``` ### Add AIRouter to your Opencode config Opencode reads a global config for all projects, and an optional `opencode.json` in a project's root folder that overrides it. Use the global file unless you want AIRouter in one project only. **macOS / Linux** The global file is `~/.config/opencode/opencode.json`. Opencode also accepts `opencode.jsonc` in the same folder. If one already exists, edit it instead of creating a second file. ```bash mkdir -p ~/.config/opencode open -e ~/.config/opencode/opencode.json # macOS: opens TextEdit ``` On Linux, open the same path in any editor, for example `nano ~/.config/opencode/opencode.json`. **Note.** `.config` is a hidden folder. In Finder, press `Cmd+Shift+.` to show hidden folders, or press `Cmd+Shift+G` and paste `~/.config/opencode`. `ls` in a terminal also hides it. Use `ls -a ~` to see it. **Windows** The global file is `.config\opencode\opencode.json` inside your user folder, which is `%USERPROFILE%\.config\opencode\opencode.json`. Opencode also accepts `opencode.jsonc` in the same folder. If one already exists, edit it instead of creating a second file. ```powershell New-Item -ItemType Directory -Force "$env:USERPROFILE\.config\opencode" notepad "$env:USERPROFILE\.config\opencode\opencode.json" ``` If you'd rather not depend on that location, create `opencode.json` in your project's root folder instead. It works the same way. Put this in the file. If the file already has content, merge the `provider` block into it and keep your existing settings: ```json { "$schema": "https://opencode.ai/config.json", "provider": { "airouter": { "npm": "@ai-sdk/openai-compatible", "name": "AIRouter", "options": { "baseURL": "https://api.airouter.in/v1", "apiKey": "{env:AIROUTER_API_KEY}" }, "models": { "deepseek/deepseek-v4.1-flash": { "name": "DeepSeek V4.1 Flash" } } } } } ``` | Field | What it does | |---|---| | `airouter` | The provider ID. Any string works. | | `npm` | `@ai-sdk/openai-compatible` is Opencode's adapter for OpenAI-compatible APIs. | | `baseURL` | Must end in `/v1`. Opencode appends `/chat/completions` itself. | | `apiKey` | `{env:AIROUTER_API_KEY}` reads the variable from step 2. | | `models` | Each key must match an `id` from [`GET /v1/models`](https://www.airouter.in/docs/api-reference/models). | ### Pick the model and test it Start Opencode from a project folder: ```bash opencode ``` Run `/models` and choose **AIRouter → DeepSeek V4.1 Flash**. Then send a small request, such as "list the files in this folder". Opencode needs the model to call tools, so this confirms the setup end to end. To see the config Opencode actually loaded, run: ```bash opencode debug config ``` ## Add more models Add one entry under `models` per model. The key must be the exact `id` from the catalogue. List the IDs with: **macOS / Linux** ```bash curl https://api.airouter.in/v1/models ``` **Windows** ```powershell curl.exe https://api.airouter.in/v1/models ``` ## Test your key without Opencode If Opencode returns an error, check the key and credits directly. A reply here means the problem is in the Opencode config, not the key. **macOS / Linux** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer $AIROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model":"deepseek/deepseek-v4.1-flash","messages":[{"role":"user","content":"Say hello"}]}' ``` **Windows** ```powershell curl.exe https://api.airouter.in/v1/chat/completions ` -H "Authorization: Bearer $env:AIROUTER_API_KEY" ` -H "Content-Type: application/json" ` -d '{\"model\":\"deepseek/deepseek-v4.1-flash\",\"messages\":[{\"role\":\"user\",\"content\":\"Say hello\"}]}' ``` ## Troubleshooting | Symptom | Likely cause | |---|---| | AIRouter missing from `/models` | The config file is in the wrong folder or has a JSON syntax error. Run `opencode debug config`. | | `401` | `AIROUTER_API_KEY` is empty in this terminal. On Windows, open a new window after `setx`. | | `402` | Out of credits. Add credits in the dashboard. | | `model not found` | The key under `models` doesn't match an `id` from `/v1/models`. | | Requests go to the wrong URL | `baseURL` is missing `/v1`, or has an extra `/chat/completions`. | See [errors](https://www.airouter.in/docs/concepts/errors) for the full list of error types. # Quickstart Source: https://www.airouter.in/docs/quickstart > Sign up, add credits with UPI, and make your first AI API call in five minutes — Python, Node.js, or cURL. Five minutes from nothing to a working call. You need an email address, a UPI app, and any HTTP client. ### Create an account Sign up at [airouter.in](https://www.airouter.in/) from any country. No credit card, no international payment method. Requests need a credit balance, so add credits before making your first call. ### Add credits Go to the [credits page](https://www.airouter.in/settings/credits) (`/settings/credits`) and top up. The minimum is $1, charged in ₹ at the current exchange rate. Payments run through Razorpay — UPI (GPay, PhonePe, Paytm), net banking, or debit card. AIRouter never sees or stores your payment credentials. Video: [AIRouter demo: buy OpenAI, Claude and Gemini APIs with UPI](https://www.youtube.com/watch?v=xVcf6eInIgQ) ### Create an API key Go to the [API keys page](https://www.airouter.in/workspaces/default/keys) (`/workspaces/default/keys`) and click **Create Key**. You'll get a key shaped like `sk-air-v1-...`. **Warning.** The key is displayed once. Copy it into a password manager or your environment variables before closing the dialog. ### Make the call Set `base_url` and `api_key`. That's the whole integration. **Python** ```python from openai import OpenAI client = OpenAI( api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) response = client.chat.completions.create( model="openai/gpt-5.2", messages=[{"role": "user", "content": "Hello from India!"}], ) print(response.choices[0].message.content) ``` **Node.js** ```ts import OpenAI from "openai"; const client = new OpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); const response = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello from India!" }], }); console.log(response.choices[0].message.content); ``` **cURL** ```bash curl https://api.airouter.in/v1/chat/completions \ -H "Authorization: Bearer sk-air-v1-..." \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-5.2", "messages": [{"role": "user", "content": "Hello from India!"}] }' ``` ## Streaming Pass `stream: true` for server-sent events. Any OpenAI SDK consumes them natively. ```ts const stream = await client.chat.completions.create({ model: "openai/gpt-5.2", messages: [{ role: "user", content: "Hello!" }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content ?? ""); } ``` **Warning: Check stream frames for errors.** If a provider fails *after* the first byte, the HTTP status is already `200` and the failure arrives as a frame in the stream body: ```json { "error": { "message": "Stream interrupted: ...", "type": "server_error" } } ``` Code that only inspects the status will treat a truncated response as a successful one. Check each frame for an `error` key. ## Works with your tooling Anything that speaks the OpenAI API works. Set the base URL and key: **Vercel AI SDK** ```ts import { createOpenAI } from "@ai-sdk/openai"; const airouter = createOpenAI({ apiKey: "sk-air-v1-...", baseURL: "https://api.airouter.in/v1", }); ``` **LangChain** ```python from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="openai/gpt-5.2", api_key="sk-air-v1-...", base_url="https://api.airouter.in/v1", ) ``` **LlamaIndex** ```python from llama_index.llms.openai import OpenAI llm = OpenAI( model="openai/gpt-5.2", api_key="sk-air-v1-...", api_base="https://api.airouter.in/v1", ) ``` **Cursor / VS Code** ```text API Base URL: https://api.airouter.in/v1 API Key: sk-air-v1-... Model: openai/gpt-5.2 ``` **Opencode** Opencode accepts any OpenAI-compatible provider. Export your key, then add AIRouter as a custom provider in `opencode.json` (project root) or in your global config at `~/.config/opencode/opencode.json`: ```bash export AIROUTER_API_KEY="sk-air-v1-..." ``` ```json { "$schema": "https://opencode.ai/config.json", "provider": { "airouter": { "npm": "@ai-sdk/openai-compatible", "name": "AIRouter", "options": { "baseURL": "https://api.airouter.in/v1", "apiKey": "{env:AIROUTER_API_KEY}" }, "models": { "deepseek/deepseek-v4.1-flash": { "name": "DeepSeek V4.1 Flash" } } } } } ``` Start `opencode`, run `/models`, and pick the model under AIRouter. Each key under `models` must match an `id` from [`GET /v1/models`](https://www.airouter.in/docs/api-reference/models). To add more models, list them there with the same ID format. For Windows steps and troubleshooting, see the [full Opencode guide](https://www.airouter.in/docs/opencode). ### Using AIRouter in VS Code A walkthrough of connecting VS Code to AIRouter and switching between GPT-5, Claude, Gemini, DeepSeek and more with one key: Video: [Use any AI model in VS Code: GPT-5, Claude, Gemini, DeepSeek and more](https://www.youtube.com/watch?v=njLYipS1Bqc) ## Provider-specific guides Walkthroughs for individual providers and editors, each including the UPI payment step. - [Claude API in India with UPI](https://www.airouter.in/blog/buy-claude-api-india-upi-no-credit-card) — Get Anthropic's Claude models without an international card. - [OpenAI API with UPI in India](https://www.airouter.in/blog/buy-openai-api-with-upi-india) — Call GPT models and pay in rupees. - [Embeddings API from India](https://www.airouter.in/blog/ai-embeddings-api-india-upi-no-credit-card) — Vector embeddings for search and RAG, paid with UPI. - [Any AI model inside VS Code](https://www.airouter.in/blog/use-any-ai-model-in-vscode-without-subscription) — Use GPT, Claude and Gemini in your editor without a subscription. ## Common errors | Status | Meaning | What to do | | --- | --- | --- | | `400` | Unknown or unsupported model slug | Check the slug against [the catalog](https://www.airouter.in/models) | | `401` | Invalid, disabled, revoked, or expired key | Create a fresh key | | `402` | Insufficient credits | Top up on the [credits page](https://www.airouter.in/settings/credits) (`/settings/credits`) | | `403` | Model requires a paid plan | Add credits to unlock all models | | `413` | Request body over 16 MiB | Trim conversation history or split the batch | | `429` | Rate or spend limit hit | Back off; limits are 120 req/min and 20 concurrent per key. Still stuck? Email [support@airouter.in](mailto:support@airouter.in) | Every error uses the same envelope: ```json { "error": { "message": "Model \"foo/bar\" is not supported", "type": "invalid_request_error" } } ``` ## Next steps - [Browse models](https://www.airouter.in/models) — Compare capabilities and per-token pricing. - [Pricing](https://www.airouter.in/pricing) — How per-token costs and credit top-ups work. - [Support](https://www.airouter.in/support) — Billing questions, bug reports, and help getting started.