# Quickstart > Get started with OpenRouter's unified API for hundreds of AI models. Learn how to integrate using OpenAI SDK, direct API calls, or third-party frameworks. OpenRouter provides a unified API that gives you access to hundreds of AI models through a single endpoint, while automatically handling fallbacks and selecting the most cost-effective options. Get started with just a few lines of code using your preferred SDK or framework. Want to chat with our docs? Download an LLM-friendly text file of our [full documentation](/docs/llms-full.txt) and include it in your system prompt. In the examples below, the OpenRouter-specific headers are optional. Setting them allows your app to appear on the OpenRouter leaderboards. ## Using the OpenAI SDK ```python title="Python" from openai import OpenAI client = OpenAI( base_url="https://openrouter.ai/api/v1", api_key="", ) completion = client.chat.completions.create( extra_headers={ "HTTP-Referer": "", # Optional. Site URL for rankings on openrouter.ai. "X-Title": "", # Optional. Site title for rankings on openrouter.ai. }, model="openai/gpt-4o", messages=[ { "role": "user", "content": "What is the meaning of life?" } ] ) print(completion.choices[0].message.content) ``` ```typescript title="TypeScript" import OpenAI from 'openai'; const openai = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: '', defaultHeaders: { 'HTTP-Referer': '', // Optional. Site URL for rankings on openrouter.ai. 'X-Title': '', // Optional. Site title for rankings on openrouter.ai. }, }); async function main() { const completion = await openai.chat.completions.create({ model: 'openai/gpt-4o', messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }); console.log(completion.choices[0].message); } main(); ``` ## Using the OpenRouter API directly ```python title="Python" import requests import json response = requests.post( url="https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": "Bearer ", "HTTP-Referer": "", # Optional. Site URL for rankings on openrouter.ai. "X-Title": "", # Optional. Site title for rankings on openrouter.ai. }, data=json.dumps({ "model": "openai/gpt-4o", # Optional "messages": [ { "role": "user", "content": "What is the meaning of life?" } ] }) ) ``` ```typescript title="TypeScript" fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer ', 'HTTP-Referer': '', // Optional. Site URL for rankings on openrouter.ai. 'X-Title': '', // Optional. Site title for rankings on openrouter.ai. 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o', messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }), }); ``` ```shell title="Shell" curl https://openrouter.ai/api/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -d '{ "model": "openai/gpt-4o", "messages": [ { "role": "user", "content": "What is the meaning of life?" } ] }' ``` The API also supports [streaming](/docs/api-reference/streaming). ## Using third-party SDKs For information about using third-party SDKs and frameworks with OpenRouter, please [see our frameworks documentation.](/docs/community/frameworks) # Principles > Learn about OpenRouter's guiding principles and mission. Understand our commitment to price optimization, standardized APIs, and high availability in AI model deployment. OpenRouter helps developers source and optimize AI usage. We believe the future is multi-model and multi-provider. ## Why OpenRouter? **Price and Performance**. OpenRouter scouts for the best prices, the lowest latencies, and the highest throughput across dozens of providers, and lets you choose how to [prioritize](/docs/features/provider-routing) them. **Standardized API**. No need to change code when switching between models or providers. You can even let your users [choose and pay for their own](/docs/use-cases/oauth-pkce). **Real-World Insights**. Be the first to take advantage of new models. See real-world data of [how often models are used](https://openrouter.ai/rankings) for different purposes. Keep up to date in our [Discord channel](https://discord.com/channels/1091220969173028894/1094454198688546826). **Consolidated Billing**. Simple and transparent billing, regardless of how many providers you use. **Higher Availability**. Fallback providers, and automatic, smart routing means your requests still work even when providers go down. **Higher Rate Limits**. OpenRouter works directly with providers to provide better rate limits and more throughput. # Models > Access over 300 AI models through OpenRouter's unified API. Browse available models, compare capabilities, and integrate with your preferred provider. OpenRouter strives to provide access to every potentially useful text-based AI model. We currently support over 300 models endpoints. If there are models or providers you are interested in that OpenRouter doesn't have, please tell us about them in our [Discord channel](https://discord.gg/fVyRaUDgxW). Some models break up text into chunks of multiple characters (GPT, Claude, Llama, etc), while others tokenize by character (PaLM). This means that token counts (and therefore costs) will vary between models, even when inputs and outputs are the same. Costs are displayed and billed according to the tokenizer for the model in use. Explore and browse 300+ models and providers [on our website](https://openrouter.ai/models), or [with our API](/docs/api-reference/list-available-models). ## For Providers If you're interested in working with OpenRouter, you can learn more on our [providers page](/docs/use-cases/for-providers). # Model Routing > Route requests dynamically between AI models. Learn how to use OpenRouter's Auto Router and model fallback features for optimal performance and reliability. OpenRouter provides two options for model routing. ## Auto Router The [Auto Router](https://openrouter.ai/openrouter/auto), a special model ID that you can use to choose between selected high-quality models based on your prompt, powered by [NotDiamond](https://www.notdiamond.ai/). ```json { "model": "openrouter/auto", ... // Other params } ``` The resulting generation will have `model` set to the model that was used. ## The `models` parameter The `models` parameter lets you automatically try other models if the primary model's providers are down, rate-limited, or refuse to reply due to content moderation. ```json { "models": ["anthropic/claude-3.5-sonnet", "gryphe/mythomax-l2-13b"], ... // Other params } ``` If the model you selected returns an error, OpenRouter will try to use the fallback model instead. If the fallback model is down or returns an error, OpenRouter will return that error. By default, any error can trigger the use of a fallback model, including context length validation errors, moderation flags for filtered models, rate-limiting, and downtime. Requests are priced using the model that was ultimately used, which will be returned in the `model` attribute of the response body. If no fallback model is specified but `route: "fallback"` is included, OpenRouter will try the most appropriate open-source model available, with pricing less than the primary model (or very close to it). ## Using with OpenAI SDK To use the `models` array with the OpenAI SDK, include it in the `extra_body` parameter. In the example below, gpt-4o will be tried first, and the `models` array will be tried in order as fallbacks. ```typescript import OpenAI from 'openai'; const openrouterClient = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', // API key and headers }); async function main() { // @ts-expect-error const completion = await openrouterClient.chat.completions.create({ model: 'openai/gpt-4o', extra_body: { models: ['anthropic/claude-3.5-sonnet', 'gryphe/mythomax-l2-13b'], }, messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }); console.log(completion.choices[0].message); } main(); ``` # Provider Routing > Route AI model requests across multiple providers intelligently. Learn how to optimize for cost, performance, and reliability with OpenRouter's provider routing. OpenRouter routes requests to the best available providers for your model. By default, [requests are load balanced](#load-balancing-default-strategy) across the top providers to maximize uptime. You can customize how your requests are routed using the `provider` object in the request body for [Chat Completions](/docs/api-reference/chat-completion) and [Completions](/docs/api-reference/completion). For a complete list of valid provider names to use in the API, see the [full provider schema](#json-schema-for-provider-preferences). The `provider` object can contain the following fields: | Field | Type | Default | Description | | -------------------- | ----------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- | | `order` | string\[] | - | List of provider names to try in order (e.g. `["Anthropic", "OpenAI"]`). [Learn more](#ordering-specific-providers) | | `allow_fallbacks` | boolean | `true` | Whether to allow backup providers when the primary is unavailable. [Learn more](#disabling-fallbacks) | | `require_parameters` | boolean | `false` | Only use providers that support all parameters in your request. [Learn more](#requiring-providers-to-support-all-parameters-beta) | | `data_collection` | "allow" \| "deny" | "allow" | Control whether to use providers that may store data. [Learn more](#requiring-providers-to-comply-with-data-policies) | | `ignore` | string\[] | - | List of provider names to skip for this request. [Learn more](#ignoring-providers) | | `quantizations` | string\[] | - | List of quantization levels to filter by (e.g. `["int4", "int8"]`). [Learn more](#quantization) | | `sort` | string | - | Sort providers by price or throughput. (e.g. `"price"` or `"throughput"`). [Learn more](#provider-sorting) | ## Price-Based Load Balancing (Default Strategy) For each model in your request, OpenRouter's default behavior is to load balance requests across providers, prioritizing price. If you are more sensitive to throughput than price, you can use the `sort` field to explicitly prioritize throughput. When you send a request with `tools` or `tool_choice`, OpenRouter will only route to providers that support tool use. Similarly, if you set a `max_tokens`, then OpenRouter will only route to providers that support a response of that length. Here is OpenRouter's default load balancing strategy: 1. Prioritize providers that have not seen significant outages in the last 30 seconds. 2. For the stable providers, look at the lowest-cost candidates and select one weighted by inverse square of the price (example below). 3. Use the remaining providers as fallbacks. If Provider A costs \$1 per million tokens, Provider B costs \$2, and Provider C costs \$3, and Provider B recently saw a few outages. * Your request is routed to Provider A. Provider A is 9x more likely to be first routed to Provider A than Provider C because $(1 / 3^2 = 1/9)$ (inverse square of the price). * If Provider A fails, then Provider C will be tried next. * If Provider C also fails, Provider B will be tried last. If you have `sort` or `order` set in your provider preferences, load balancing will be disabled. ## Provider Sorting As described above, OpenRouter load balances based on price, while taking uptime into account. If you instead want to *explicitly* prioritize a particular provider attribute, you can include the `sort` field in the `provider` preferences. Load balancing will be disabled, and the router will try providers in order. The three sort options are: * `"price"`: prioritize lowest price * `"throughput"`: prioritize highest throughput * `"latency"`: prioritize lowest latency To *always* prioritize low prices, and not apply any load balancing, set `sort` to `"price"`. To *always* prioritize low latency, and not apply any load balancing, set `sort` to `"latency"`. ## Nitro Shortcut You can append `:nitro` to any model slug as a shortcut to sort by throughput. This is exactly equivalent to setting `provider.sort` to `"throughput"`. ## Floor Price Shortcut You can append `:floor` to any model slug as a shortcut to sort by price. This is exactly equivalent to setting `provider.sort` to `"price"`. ## Ordering Specific Providers You can set the providers that OpenRouter will prioritize for your request using the `order` field. | Field | Type | Default | Description | | ------- | --------- | ------- | ------------------------------------------------------------------------ | | `order` | string\[] | - | List of provider names to try in order (e.g. `["Anthropic", "OpenAI"]`). | The router will prioritize providers in this list, and in this order, for the model you're using. If you don't set this field, the router will [load balance](#load-balancing-default-strategy) across the top providers to maximize uptime. OpenRouter will try them one at a time and proceed to other providers if none are operational. If you don't want to allow any other providers, you should [disable fallbacks](#disabling-fallbacks) as well. ### Example: Specifying providers with fallbacks This example skips over OpenAI (which doesn't host Mixtral), tries Together, and then falls back to the normal list of providers on OpenRouter: ### Example: Specifying providers with fallbacks disabled Here's an example with `allow_fallbacks` set to `false` that skips over OpenAI (which doesn't host Mixtral), tries Together, and then fails if Together fails: ## Requiring Providers to Support All Parameters (beta) You can restrict requests only to providers that support all parameters in your request using the `require_parameters` field. | Field | Type | Default | Description | | -------------------- | ------- | ------- | --------------------------------------------------------------- | | `require_parameters` | boolean | `false` | Only use providers that support all parameters in your request. | With the default routing strategy, providers that don't support all the [LLM parameters](/docs/api-reference/parameters) specified in your request can still receive the request, but will ignore unknown parameters. When you set `require_parameters` to `true`, the request won't even be routed to that provider. ### Example: Excluding providers that don't support JSON formatting For example, to only use providers that support JSON formatting: ## Requiring Providers to Comply with Data Policies You can restrict requests only to providers that comply with your data policies using the `data_collection` field. | Field | Type | Default | Description | | ----------------- | ----------------- | ------- | ----------------------------------------------------- | | `data_collection` | "allow" \| "deny" | "allow" | Control whether to use providers that may store data. | * `allow`: (default) allow providers which store user data non-transiently and may train on it * `deny`: use only providers which do not collect user data Some model providers may log prompts, so we display them with a **Data Policy** tag on model pages. This is not a definitive source of third party data policies, but represents our best knowledge. This is also available as an account-wide setting in [your privacy settings](https://openrouter.ai/settings/privacy). You can disable third party model providers that store inputs for training. ### Example: Excluding providers that don't comply with data policies To exclude providers that don't comply with your data policies, set `data_collection` to `deny`: ## Disabling Fallbacks To guarantee that your request is only served by the top (lowest-cost) provider, you can disable fallbacks. This is combined with the `order` field from [Ordering Specific Providers](#ordering-specific-providers) to restrict the providers that OpenRouter will prioritize to just your chosen list. ## Ignoring Providers You can ignore providers for a request by setting the `ignore` field in the `provider` object. | Field | Type | Default | Description | | -------- | --------- | ------- | ------------------------------------------------ | | `ignore` | string\[] | - | List of provider names to skip for this request. | Ignoring multiple providers may significantly reduce fallback options and limit request recovery. You can ignore providers for all account requests by configuring your [preferences](/settings/preferences). This configuration applies to all API requests and chatroom messages. Note that when you ignore providers for a specific request, the list of ignored providers is merged with your account-wide ignored providers. ### Example: Ignoring Azure for a request calling GPT-4 Omni Here's an example that will ignore Azure for a request calling GPT-4 Omni: ## Quantization Quantization reduces model size and computational requirements while aiming to preserve performance. Most LLMs today use FP16 or BF16 for training and inference, cutting memory requirements in half compared to FP32. Some optimizations use FP8 or quantization to reduce size further (e.g., INT8, INT4). | Field | Type | Default | Description | | --------------- | --------- | ------- | ----------------------------------------------------------------------------------------------- | | `quantizations` | string\[] | - | List of quantization levels to filter by (e.g. `["int4", "int8"]`). [Learn more](#quantization) | Quantized models may exhibit degraded performance for certain prompts, depending on the method used. Providers can support various quantization levels for open-weight models. ### Quantization Levels By default, requests are load-balanced across all available providers, ordered by price. To filter providers by quantization level, specify the `quantizations` field in the `provider` parameter with the following values: * `int4`: Integer (4 bit) * `int8`: Integer (8 bit) * `fp6`: Floating point (6 bit) * `fp8`: Floating point (8 bit) * `fp16`: Floating point (16 bit) * `bf16`: Brain floating point (16 bit) * `fp32`: Floating point (32 bit) * `unknown`: Unknown ### Example: Requesting FP8 Quantization Here's an example that will only use providers that support FP8 quantization: ## Terms of Service You can view the terms of service for each provider below. You may not violate the terms of service or policies of third-party providers that power the models on OpenRouter. * `OpenAI`: [https://openai.com/policies/row-terms-of-use/](https://openai.com/policies/row-terms-of-use/) * `Anthropic`: [https://www.anthropic.com/legal/commercial-terms](https://www.anthropic.com/legal/commercial-terms) * `Google Vertex`: [https://cloud.google.com/terms/](https://cloud.google.com/terms/) * `Google AI Studio`: [https://cloud.google.com/terms/](https://cloud.google.com/terms/) * `Amazon Bedrock`: [https://aws.amazon.com/service-terms/](https://aws.amazon.com/service-terms/) * `Groq`: [https://groq.com/terms-of-use/](https://groq.com/terms-of-use/) * `SambaNova`: [https://sambanova.ai/terms-and-conditions](https://sambanova.ai/terms-and-conditions) * `Cohere`: [https://cohere.com/terms-of-use](https://cohere.com/terms-of-use) * `Mistral`: [https://mistral.ai/terms/#terms-of-use](https://mistral.ai/terms/#terms-of-use) * `Together`: [https://www.together.ai/terms-of-service](https://www.together.ai/terms-of-service) * `Together (lite)`: [https://www.together.ai/terms-of-service](https://www.together.ai/terms-of-service) * `Fireworks`: [https://fireworks.ai/terms-of-service](https://fireworks.ai/terms-of-service) * `DeepInfra`: [https://deepinfra.com/docs/data](https://deepinfra.com/docs/data) * `Lepton`: [https://www.lepton.ai/policies/tos](https://www.lepton.ai/policies/tos) * `NovitaAI`: [https://novita.ai/legal/terms-of-service](https://novita.ai/legal/terms-of-service) * `Avian.io`: [https://avian.io/privacy](https://avian.io/privacy) * `Lambda`: [https://lambdalabs.com/legal/privacy-policy](https://lambdalabs.com/legal/privacy-policy) * `Azure`: [https://www.microsoft.com/en-us/legal/terms-of-use?oneroute=true](https://www.microsoft.com/en-us/legal/terms-of-use?oneroute=true) * `Modal`: [https://modal.com/legal/terms](https://modal.com/legal/terms) * `AnyScale`: [https://www.anyscale.com/terms](https://www.anyscale.com/terms) * `Replicate`: [https://replicate.com/terms](https://replicate.com/terms) * `Perplexity`: [https://www.perplexity.ai/hub/legal/perplexity-api-terms-of-service](https://www.perplexity.ai/hub/legal/perplexity-api-terms-of-service) * `Recursal`: [https://featherless.ai/terms](https://featherless.ai/terms) * `OctoAI`: [https://octo.ai/docs/faqs/privacy-and-security](https://octo.ai/docs/faqs/privacy-and-security) * `DeepSeek`: [https://chat.deepseek.com/downloads/DeepSeek%20Terms%20of%20Use.html](https://chat.deepseek.com/downloads/DeepSeek%20Terms%20of%20Use.html) * `Infermatic`: [https://infermatic.ai/privacy-policy/](https://infermatic.ai/privacy-policy/) * `AI21`: [https://studio.ai21.com/privacy-policy](https://studio.ai21.com/privacy-policy) * `Featherless`: [https://featherless.ai/terms](https://featherless.ai/terms) * `Inflection`: [https://developers.inflection.ai/tos](https://developers.inflection.ai/tos) * `xAI`: [https://x.ai/legal/terms-of-service](https://x.ai/legal/terms-of-service) * `Cloudflare`: [https://www.cloudflare.com/service-specific-terms-developer-platform/#developer-platform-terms](https://www.cloudflare.com/service-specific-terms-developer-platform/#developer-platform-terms) * `SF Compute`: [https://inference.sfcompute.com/privacy](https://inference.sfcompute.com/privacy) * `Minimax`: [https://intl.minimaxi.com/protocol/terms-of-service](https://intl.minimaxi.com/protocol/terms-of-service) * `Nineteen`: [https://nineteen.ai/tos](https://nineteen.ai/tos) * `Liquid`: [https://www.liquid.ai/terms-conditions](https://www.liquid.ai/terms-conditions) * `inference.net`: [https://inference.net/terms](https://inference.net/terms) * `Friendli`: [https://friendli.ai/terms-of-service](https://friendli.ai/terms-of-service) * `AionLabs`: [https://www.aionlabs.ai/terms/](https://www.aionlabs.ai/terms/) * `Alibaba`: [https://www.alibabacloud.com/help/en/legal/latest/alibaba-cloud-international-website-product-terms-of-service-v-3-8-0](https://www.alibabacloud.com/help/en/legal/latest/alibaba-cloud-international-website-product-terms-of-service-v-3-8-0) * `Nebius AI Studio`: [https://docs.nebius.com/legal/studio/terms-of-use/](https://docs.nebius.com/legal/studio/terms-of-use/) * `Chutes`: [https://chutes.ai/tos](https://chutes.ai/tos) * `kluster.ai`: [https://www.kluster.ai/terms-of-use](https://www.kluster.ai/terms-of-use) * `Crusoe`: [https://legal.crusoe.ai/open-router#managed-inference-tos-open-router](https://legal.crusoe.ai/open-router#managed-inference-tos-open-router) * `Targon`: [https://targon.com/terms](https://targon.com/terms) * `01.AI`: [https://platform.01.ai/privacypolicy](https://platform.01.ai/privacypolicy) * `HuggingFace`: [https://huggingface.co/terms-of-service](https://huggingface.co/terms-of-service) * `Mancer`: [https://mancer.tech/terms](https://mancer.tech/terms) * `Mancer (private)`: [https://mancer.tech/terms](https://mancer.tech/terms) * `Hyperbolic`: [https://hyperbolic.xyz/privacy](https://hyperbolic.xyz/privacy) * `Hyperbolic (quantized)`: [https://hyperbolic.xyz/privacy](https://hyperbolic.xyz/privacy) * `Lynn`: [https://api.lynn.app/policy](https://api.lynn.app/policy) ## JSON Schema for Provider Preferences For a complete list of options, see this JSON schema: # Prompt Caching > Reduce your AI model costs with OpenRouter's prompt caching feature. Learn how to cache and reuse responses across OpenAI, Anthropic Claude, and DeepSeek models. To save on inference costs, you can enable prompt caching on supported providers and models. Most providers automatically enable prompt caching, but note that some (see Anthropic below) require you to enable it on a per-message basis. Note that prompt caching does not work when switching between providers. In order to cache the prompt, LLM engines must store a memory snapshot of the processed prompt, which is not shared with other providers. ## Inspecting cache usage To see how much caching saved on each generation, you click the detail button on the [Activity](/activity) page, or you can use the `/api/v1/generation` API, [documented here](/api-reference/overview#querying-cost-and-stats). The `cache_discount` field in the response body will tell you how much the response saved on cache usage. Some providers, like Anthropic, will have a negative discount on cache writes, but a positive discount (which reduces total cost) on cache reads. ## OpenAI Caching price changes: * **Cache writes**: no cost * **Cache reads**: charged at {OPENAI_CACHE_READ_MULTIPLIER}x the price of the original input pricing Prompt caching with OpenAI is automated and does not require any additional configuration. There is a minimum prompt size of 1024 tokens. [Click here to read more about OpenAI prompt caching and its limitation.](https://openai.com/index/api-prompt-caching/) ## Anthropic Claude Caching price changes: * **Cache writes**: charged at {ANTHROPIC_CACHE_WRITE_MULTIPLIER}x the price of the original input pricing * **Cache reads**: charged at {ANTHROPIC_CACHE_READ_MULTIPLIER}x the price of the original input pricing Prompt caching with Anthropic requires the use of `cache_control` breakpoints. There is a limit of four breakpoints, and the cache will expire within five minutes. Therefore, it is recommended to reserve the cache breakpoints for large bodies of text, such as character cards, CSV data, RAG data, book chapters, etc. [Click here to read more about Anthropic prompt caching and its limitation.](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching) The `cache_control` breakpoint can only be inserted into the text part of a multipart message. System message caching example: ```json { "messages": [ { "role": "system", "content": [ { "type": "text", "text": "You are a historian studying the fall of the Roman Empire. You know the following book very well:" }, { "type": "text", "text": "HUGE TEXT BODY", "cache_control": { "type": "ephemeral" } } ] }, { "role": "user", "content": [ { "type": "text", "text": "What triggered the collapse?" } ] } ] } ``` User message caching example: ```json { "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Given the book below:" }, { "type": "text", "text": "HUGE TEXT BODY", "cache_control": { "type": "ephemeral" } }, { "type": "text", "text": "Name all the characters in the above book" } ] } ] } ``` ## DeepSeek Caching price changes: * **Cache writes**: charged at the same price as the original input pricing * **Cache reads**: charged at {DEEPSEEK_CACHE_READ_MULTIPLIER}x the price of the original input pricing Prompt caching with DeepSeek is automated and does not require any additional configuration. # Structured Outputs > Enforce JSON Schema validation on AI model responses. Get consistent, type-safe outputs and avoid parsing errors with OpenRouter's structured output feature. OpenRouter supports structured outputs for compatible models, ensuring responses follow a specific JSON Schema format. This feature is particularly useful when you need consistent, well-formatted responses that can be reliably parsed by your application. ## Overview Structured outputs allow you to: * Enforce specific JSON Schema validation on model responses * Get consistent, type-safe outputs * Avoid parsing errors and hallucinated fields * Simplify response handling in your application ## Using Structured Outputs To use structured outputs, include a `response_format` parameter in your request, with `type` set to `json_schema` and the `json_schema` object containing your schema: ```typescript { "messages": [ { "role": "user", "content": "What's the weather like in London?" } ], "response_format": { "type": "json_schema", "json_schema": { "name": "weather", "strict": true, "schema": { "type": "object", "properties": { "location": { "type": "string", "description": "City or location name" }, "temperature": { "type": "number", "description": "Temperature in Celsius" }, "conditions": { "type": "string", "description": "Weather conditions description" } }, "required": ["location", "temperature", "conditions"], "additionalProperties": false } } } } ``` The model will respond with a JSON object that strictly follows your schema: ```json { "location": "London", "temperature": 18, "conditions": "Partly cloudy with light drizzle" } ``` ## Model Support Structured outputs are supported by select models. You can find a list of models that support structured outputs on the [models page](https://openrouter.ai/models?order=newest\&supported_parameters=structured_outputs). * OpenAI models (GPT-4o and later versions) [Docs](https://platform.openai.com/docs/guides/structured-outputs) * All Fireworks provided models [Docs](https://docs.fireworks.ai/structured-responses/structured-response-formatting#structured-response-modes) To ensure your chosen model supports structured outputs: 1. Check the model's supported parameters on the [models page](https://openrouter.ai/models) 2. Set `require_parameters: true` in your provider preferences (see [Provider Routing](/docs/features/provider-routing)) 3. Include `response_format` and set `type: json_schema` in the required parameters ## Best Practices 1. **Include descriptions**: Add clear descriptions to your schema properties to guide the model 2. **Use strict mode**: Always set `strict: true` to ensure the model follows your schema exactly ## Example Implementation Here's a complete example using the Fetch API: ```typescript title="With TypeScript" const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer {{API_KEY_REF}}', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4', messages: [ { role: 'user', content: 'What is the weather like in London?' }, ], response_format: { type: 'json_schema', json_schema: { name: 'weather', strict: true, schema: { type: 'object', properties: { location: { type: 'string', description: 'City or location name', }, temperature: { type: 'number', description: 'Temperature in Celsius', }, conditions: { type: 'string', description: 'Weather conditions description', }, }, required: ['location', 'temperature', 'conditions'], additionalProperties: false, }, }, }, }), }); const data = await response.json(); const weatherInfo = data.choices[0].message.content; ``` ## Streaming with Structured Outputs Structured outputs are also supported with streaming responses. The model will stream valid partial JSON that, when complete, forms a valid response matching your schema. To enable streaming with structured outputs, simply add `stream: true` to your request: ```typescript { "stream": true, "response_format": { "type": "json_schema", // ... rest of your schema } } ``` ## Error Handling When using structured outputs, you may encounter these scenarios: 1. **Model doesn't support structured outputs**: The request will fail with an error indicating lack of support 2. **Invalid schema**: The model will return an error if your JSON Schema is invalid # Message Transforms > Transform and optimize messages before sending them to AI models. Learn about middle-out compression and context window optimization with OpenRouter. To help with prompts that exceed the maximum context size of a model, OpenRouter supports a custom parameter called `transforms`: ```typescript { transforms: ["middle-out"], // Compress prompts that are > context size. messages: [...], model // Works with any model } ``` This can be useful for situations where perfect recall is not required. The transform works by removing or truncating messages from the middle of the prompt, until the prompt fits within the model's context window. In some cases, the issue is not the token context length, but the actual number of messages. The transform addresses this as well: For instance, Anthropic's Claude models enforce a maximum of {anthropicMaxMessagesCount} messages. When this limit is exceeded with middle-out enabled, the transform will keep half of the messages from the start and half from the end of the conversation. When middle-out compression is enabled, OpenRouter will first try to find models whose context length is at least half of your total required tokens (input + completion). For example, if your prompt requires 10,000 tokens total, models with at least 5,000 context length will be considered. If no models meet this criteria, OpenRouter will fall back to using the model with the highest available context length. The compression will then attempt to fit your content within the chosen model's context window by removing or truncating content from the middle of the prompt. If middle-out compression is disabled and your total tokens exceed the model's context length, the request will fail with an error message suggesting you either reduce the length or enable middle-out compression. [All OpenRouter endpoints](/models) with 8k (8,192 tokens) or less context length will default to using `middle-out`. To disable this, set `transforms: []` in the request body. The middle of the prompt is compressed because [LLMs pay less attention](https://arxiv.org/abs/2307.03172) to the middle of sequences. # Uptime Optimization > Learn how OpenRouter maximizes AI model uptime through real-time monitoring, intelligent routing, and automatic fallbacks across multiple providers. OpenRouter continuously monitors the health and availability of AI providers to ensure maximum uptime for your applications. We track response times, error rates, and availability across all providers in real-time, and route based on this feedback. ## How It Works OpenRouter tracks response times, error rates, and availability across all providers in real-time. This data helps us make intelligent routing decisions and provides transparency about service reliability. ## Uptime Example: Claude 3.5 Sonnet ## Uptime Example: Llama 3.3 70B Instruct ## Customizing Provider Selection While our smart routing helps maintain high availability, you can also customize provider selection using request parameters. This gives you control over which providers handle your requests while still benefiting from automatic fallback when needed. Learn more about customizing provider selection in our [Provider Routing documentation](/docs/features/provider-routing). # Web Search > Enable real-time web search capabilities in your AI model responses. Add factual, up-to-date information to any model's output with OpenRouter's web search feature. You can incorporate relevant web search results for *any* model on OpenRouter by activating and customizing the `web` plugin, or by appending `:online` to the model slug: ```json { "model": "openai/gpt-4o:online" } ``` This is a shortcut for using the `web` plugin, and is exactly equivalent to: ```json { "model": "openrouter/auto", "plugins": [{ "id": "web" }] } ``` The web search plugin is powered by [Exa](https://exa.ai) and uses their ["auto"](https://docs.exa.ai/reference/how-exa-search-works#combining-neural-and-keyword-the-best-of-both-worlds-through-exa-auto-search) method (a combination of keyword search and embeddings-based web search) to find the most relevant results and augment/ground your prompt. ## Customizing the Web Plugin The maximum results allowed by the web plugin and the prompt used to attach them to your message stream can be customized: ```json { "model": "openai/gpt-4o:online", "plugins": [ { "id": "web", "max_results": 1, // Defaults to 5 "search_prompt": "Some relevant web results:" // See default below } ] } ``` By default, the web plugin uses the following search prompt, using the current date: ``` A web search was conducted on `date`. Incorporate the following web search results into your response. IMPORTANT: Cite them using markdown links named using the domain of the source. Example: [nytimes.com](https://nytimes.com/some-page). ``` ## Pricing The web plugin uses your OpenRouter credits and charges *\$4 per 1000 results*. By default, `max_results` set to 5, this comes out to a maximum of \$0.02 per request, in addition to the LLM usage for the search result prompt tokens. # API Reference > Comprehensive guide to OpenRouter's API. Learn about request/response schemas, authentication, parameters, and integration with multiple AI model providers. OpenRouter's request and response schemas are very similar to the OpenAI Chat API, with a few small differences. At a high level, **OpenRouter normalizes the schema across models and providers** so you only need to learn one. ## Requests ### Completions Request Format Here is the request schema as a TypeScript type. This will be the body of your `POST` request to the `/api/v1/chat/completions` endpoint (see the [quick start](/docs/quick-start) above for an example). For a complete list of parameters, see the [Parameters](/docs/api-reference/parameters). ```typescript title="Request Schema" // Definitions of subtypes are below type Request = { // Either "messages" or "prompt" is required messages?: Message[]; prompt?: string; // If "model" is unspecified, uses the user's default model?: string; // See "Supported Models" section // Allows to force the model to produce specific output format. // See models page and note on this docs page for which models support it. response_format?: { type: 'json_object' }; stop?: string | string[]; stream?: boolean; // Enable streaming // See LLM Parameters (openrouter.ai/docs/api-reference/parameters) max_tokens?: number; // Range: [1, context_length) temperature?: number; // Range: [0, 2] // Tool calling // Will be passed down as-is for providers implementing OpenAI's interface. // For providers with custom interfaces, we transform and map the properties. // Otherwise, we transform the tools into a YAML template. The model responds with an assistant message. // See models supporting tool calling: openrouter.ai/models?supported_parameters=tools tools?: Tool[]; tool_choice?: ToolChoice; // Advanced optional parameters seed?: number; // Integer only top_p?: number; // Range: (0, 1] top_k?: number; // Range: [1, Infinity) Not available for OpenAI models frequency_penalty?: number; // Range: [-2, 2] presence_penalty?: number; // Range: [-2, 2] repetition_penalty?: number; // Range: (0, 2] logit_bias?: { [key: number]: number }; top_logprobs: number; // Integer only min_p?: number; // Range: [0, 1] top_a?: number; // Range: [0, 1] // Reduce latency by providing the model with a predicted output // https://platform.openai.com/docs/guides/latency-optimization#use-predicted-outputs prediction?: { type: 'content'; content: string }; // OpenRouter-only parameters // See "Prompt Transforms" section: openrouter.ai/docs/transforms transforms?: string[]; // See "Model Routing" section: openrouter.ai/docs/model-routing models?: string[]; route?: 'fallback'; // See "Provider Routing" section: openrouter.ai/docs/provider-routing provider?: ProviderPreferences; }; // Subtypes: type TextContent = { type: 'text'; text: string; }; type ImageContentPart = { type: 'image_url'; image_url: { url: string; // URL or base64 encoded image data detail?: string; // Optional, defaults to "auto" }; }; type ContentPart = TextContent | ImageContentPart; type Message = | { role: 'user' | 'assistant' | 'system'; // ContentParts are only for the "user" role: content: string | ContentPart[]; // If "name" is included, it will be prepended like this // for non-OpenAI models: `{name}: {content}` name?: string; } | { role: 'tool'; content: string; tool_call_id: string; name?: string; }; type FunctionDescription = { description?: string; name: string; parameters: object; // JSON Schema object }; type Tool = { type: 'function'; function: FunctionDescription; }; type ToolChoice = | 'none' | 'auto' | { type: 'function'; function: { name: string; }; }; ``` The `response_format` parameter ensures you receive a structured response from the LLM. The parameter is only supported by OpenAI models, Nitro models, and some others - check the providers on the model page on openrouter.ai/models to see if it's supported, and set `require_parameters` to true in your Provider Preferences. See [Provider Routing](/docs/features/provider-routing) ### Headers OpenRouter allows you to specify some optional headers to identify your app and make it discoverable to users on our site. * `HTTP-Referer`: Identifies your app on openrouter.ai * `X-Title`: Sets/modifies your app's title ```typescript title="TypeScript" fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer ', 'HTTP-Referer': '', // Optional. Site URL for rankings on openrouter.ai. 'X-Title': '', // Optional. Site title for rankings on openrouter.ai. 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o', messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }), }); ``` If the `model` parameter is omitted, the user or payer's default is used. Otherwise, remember to select a value for `model` from the [supported models](/models) or [API](/api/v1/models), and include the organization prefix. OpenRouter will select the least expensive and best GPUs available to serve the request, and fall back to other providers or GPUs if it receives a 5xx response code or if you are rate-limited. [Server-Sent Events (SSE)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format) are supported as well, to enable streaming *for all models*. Simply send `stream: true` in your request body. The SSE stream will occasionally contain a "comment" payload, which you should ignore (noted below). If the chosen model doesn't support a request parameter (such as `logit_bias` in non-OpenAI models, or `top_k` for OpenAI), then the parameter is ignored. The rest are forwarded to the underlying model API. ### Assistant Prefill OpenRouter supports asking models to complete a partial response. This can be useful for guiding models to respond in a certain way. To use this features, simply include a message with `role: "assistant"` at the end of your `messages` array. ```typescript title="TypeScript" fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer ', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o', messages: [ { role: 'user', content: 'What is the meaning of life?' }, { role: 'assistant', content: "I'm not sure, but my best guess is" }, ], }), }); ``` ### Images & Multimodal Multimodal requests are only available via the `/api/v1/chat/completions` API with a multi-part `messages` parameter. The `image_url` can either be a URL or a data-base64 encoded image. ```typescript "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What's in this image?" }, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } } ] } ] ``` Sample LLM response: ```json { "choices": [ { "role": "assistant", "content": "This image depicts a scenic natural landscape featuring a long wooden boardwalk that stretches out through an expansive field of green grass. The boardwalk provides a clear path and invites exploration through the lush environment. The scene is surrounded by a variety of shrubbery and trees in the background, indicating a diverse plant life in the area." } ] } ``` #### Uploading base64 encoded images For locally stored images, you can send them to the model using base64 encoding. Here's an example: ```typescript TypeScript import { readFile } from "fs/promises"; const getFlowerImage = async (): Promise => { const imagePath = new URL("flower.jpg", import.meta.url); const imageBuffer = await readFile(imagePath); const base64Image = imageBuffer.toString("base64"); return `data:image/jpeg;base64,${base64Image}`; }; ... "messages": [ { role: "user", content: [ { type: "text", text: "What's in this image?", }, { type: "image_url", image_url: { url: `${await getFlowerImage()}`, }, }, ], }, ]; ``` When sending data-base64 string, ensure it contains the content-type of the image. Example: ```txt data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII ``` Supported content types are: * `image/png` * `image/jpeg` * `image/webp` ### Tool Calls Tool calls (also known as function calling) allow you to give an LLM access to external tools. The LLM does not call the tools directly. Instead, it suggests the tool to call. The user then calls the tool separately and provides the results back to the LLM. Finally, the LLM formats the response into an answer to the user's original question. An example of the five-turn sequence: 1. The user asks a question, while supplying a list of available `tools` in a JSON schema format: ```json ... "messages": [{ "role": "user", "content": "What is the weather like in Boston?" }], "tools": [{ "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit" ] } }, "required": [ "location" ] } } }] ``` 2. The LLM responds with tool suggestion, together with appropriate arguments: ```json // Some models might include their reasoning in content "message": { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_9pw1qnYScqvGrCH58HWCvFH6", "type": "function", "function": { "name": "get_current_weather", "arguments": "{ \"location\": \"Boston, MA\"}" } } ] }, ``` 3. The user calls the tool separately: ```typescript const weather = await getWeather({ location: 'Boston, MA' }); console.log(weather); // { "temperature": "22", "unit": "celsius", "description": "Sunny"} ``` 4. The user provides the tool results back to the LLM: ```json ... "messages": [ { "role": "user", "content": "What is the weather like in Boston?" }, { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_9pw1qnYScqvGrCH58HWCvFH6", "type": "function", "function": { "name": "get_current_weather", "arguments": "{ \"location\": \"Boston, MA\"}" } } ] }, { "role": "tool", "name": "get_current_weather", "tool_call_id": "call_9pw1qnYScqvGrCH58HWCvFH6", "content": "{\"temperature\": \"22\", \"unit\": \"celsius\", \"description\": \"Sunny\"}" } ] ``` 5. The LLM formats the tool result into a natural language response: ```json ... "message": { "role": "assistant", "content": "The current weather in Boston, MA is sunny with a temperature of 22°C." } ``` OpenRouter standardizes the tool calling interface. However, different providers and models may support less tool calling features and arguments. (ex: `tool_choice`, `tool_use`, `tool_result`) ## Responses ### CompletionsResponse Format OpenRouter normalizes the schema across models and providers to comply with the [OpenAI Chat API](https://platform.openai.com/docs/api-reference/chat). This means that `choices` is always an array, even if the model only returns one completion. Each choice will contain a `delta` property if a stream was requested and a `message` property otherwise. This makes it easier to use the same code for all models. Here's the response schema as a TypeScript type: ```typescript TypeScript // Definitions of subtypes are below type Response = { id: string; // Depending on whether you set "stream" to "true" and // whether you passed in "messages" or a "prompt", you // will get a different output shape choices: (NonStreamingChoice | StreamingChoice | NonChatChoice)[]; created: number; // Unix timestamp model: string; object: 'chat.completion' | 'chat.completion.chunk'; system_fingerprint?: string; // Only present if the provider supports it // Usage data is always returned for non-streaming. // When streaming, you will get one usage object at // the end accompanied by an empty choices array. usage?: ResponseUsage; }; ``` ```typescript // If the provider returns usage, we pass it down // as-is. Otherwise, we count using the GPT-4 tokenizer. type ResponseUsage = { /** Including images and tools if any */ prompt_tokens: number; /** The tokens generated */ completion_tokens: number; /** Sum of the above two fields */ total_tokens: number; }; ``` ```typescript // Subtypes: type NonChatChoice = { finish_reason: string | null; text: string; error?: ErrorResponse; }; type NonStreamingChoice = { finish_reason: string | null; native_finish_reason: string | null; message: { content: string | null; role: string; tool_calls?: ToolCall[]; }; error?: ErrorResponse; }; type StreamingChoice = { finish_reason: string | null; native_finish_reason: string | null; delta: { content: string | null; role?: string; tool_calls?: ToolCall[]; }; error?: ErrorResponse; }; type ErrorResponse = { code: number; // See "Error Handling" section message: string; metadata?: Record; // Contains additional error information such as provider details, the raw error message, etc. }; type ToolCall = { id: string; type: 'function'; function: FunctionCall; }; ``` Here's an example: ```json { "id": "gen-xxxxxxxxxxxxxx", "choices": [ { "finish_reason": "stop", // Normalized finish_reason "native_finish_reason": "stop", // The raw finish_reason from the provider "message": { // will be "delta" if streaming "role": "assistant", "content": "Hello there!" } } ], "usage": { "prompt_tokens": 0, "completion_tokens": 4, "total_tokens": 4 }, "model": "openai/gpt-3.5-turbo" // Could also be "anthropic/claude-2.1", etc, depending on the "model" that ends up being used } ``` ### Finish Reason OpenRouter normalizes each model's `finish_reason` to one of the following values: `tool_calls`, `stop`, `length`, `content_filter`, `error`. Some models and providers may have additional finish reasons. The raw finish\_reason string returned by the model is available via the `native_finish_reason` property. ### Querying Cost and Stats The token counts that are returned in the completions API response are **not** counted via the model's native tokenizer. Instead it uses a normalized, model-agnostic count (accomplished via the GPT4o tokenizer). This is because some providers do not reliably return native token counts. This behavior is becoming more rare, however, and we may add native token counts to the response object in the future. Credit usage and model pricing are based on the **native** token counts (not the 'normalized' token counts returned in the API response). For precise token accounting using the model's native tokenizer, you can retrieve the full generation information via the `/api/v1/generation` endpoint. You can use the returned `id` to query for the generation stats (including token counts and cost) after the request is complete. This is how you can get the cost and tokens for *all models and requests*, streaming and non-streaming. ```typescript title="Query Generation Stats" const generation = await fetch( 'https://openrouter.ai/api/v1/generation?id=$GENERATION_ID', { headers }, ); const stats = await generation.json(); ``` ```json Example response { "data": { "id": "gen-nNPYi0ZB6GOK5TNCUMHJGgXo", "model": "openai/gpt-4-32k", "streamed": false, "generation_time": 2, "tokens_prompt": 24, "tokens_completion": 29, "total_cost": 0.00492 // ... additional stats } } ``` Note that token counts are also available in the `usage` field of the response body for non-streaming completions. # Streaming > Learn how to implement streaming responses with OpenRouter's API. Complete guide to Server-Sent Events (SSE) and real-time model outputs. The OpenRouter API allows streaming responses from *any model*. This is useful for building chat interfaces or other applications where the UI should update as the model generates the response. To enable streaming, you can set the `stream` parameter to `true` in your request. The model will then stream the response to the client in chunks, rather than returning the entire response at once. Here is an example of how to stream a response, and process it: ```python Python import requests import json question = "How would you build the tallest building ever?" url = "https://openrouter.ai/api/v1/chat/completions" headers = { "Authorization": f"Bearer {{API_KEY_REF}}", "Content-Type": "application/json" } payload = { "model": "{{MODEL}}", "messages": [{"role": "user", "content": question}], "stream": True } buffer = "" with requests.post(url, headers=headers, json=payload, stream=True) as r: for chunk in r.iter_content(chunk_size=1024, decode_unicode=True): buffer += chunk while True: try: # Find the next complete SSE line line_end = buffer.find('\n') if line_end == -1: break line = buffer[:line_end].strip() buffer = buffer[line_end + 1:] if line.startswith('data: '): data = line[6:] if data == '[DONE]': break try: data_obj = json.loads(data) content = data_obj["choices"][0]["delta"].get("content") if content: print(content, end="", flush=True) except json.JSONDecodeError: pass except Exception: break ``` ```typescript TypeScript const question = 'How would you build the tallest building ever?'; const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${{{API_KEY_REF}}}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: '{{MODEL}}', messages: [{ role: 'user', content: question }], stream: true, }), }); const reader = response.body?.getReader(); if (!reader) { throw new Error('Response body is not readable'); } const decoder = new TextDecoder(); let buffer = ''; try { while (true) { const { done, value } = await reader.read(); if (done) break; // Append new chunk to buffer buffer += decoder.decode(value, { stream: true }); // Process complete lines from buffer while (true) { const lineEnd = buffer.indexOf('\n'); if (lineEnd === -1) break; const line = buffer.slice(0, lineEnd).trim(); buffer = buffer.slice(lineEnd + 1); if (line.startsWith('data: ')) { const data = line.slice(6); if (data === '[DONE]') break; try { const parsed = JSON.parse(data); const content = parsed.choices[0].delta.content; if (content) { console.log(content); } } catch (e) { // Ignore invalid JSON } } } } } finally { reader.cancel(); } ``` ### Additional Information For SSE (Server-Sent Events) streams, OpenRouter occasionally sends comments to prevent connection timeouts. These comments look like: ```text : OPENROUTER PROCESSING ``` Comment payload can be safely ignored per the [SSE specs](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation). However, you can leverage it to improve UX as needed, e.g. by showing a dynamic loading indicator. Some SSE client implementations might not parse the payload according to spec, which leads to an uncaught error when you `JSON.stringify` the non-JSON payloads. We recommend the following clients: * [eventsource-parser](https://github.com/rexxars/eventsource-parser) * [OpenAI SDK](https://www.npmjs.com/package/openai) * [Vercel AI SDK](https://www.npmjs.com/package/ai) ### Stream Cancellation Streaming requests can be cancelled by aborting the connection. For supported providers, this immediately stops model processing and billing. **Supported** * OpenAI, Azure, Anthropic * Fireworks, Mancer, Recursal * AnyScale, Lepton, OctoAI * Novita, DeepInfra, Together * Cohere, Hyperbolic, Infermatic * Avian, XAI, Cloudflare * SFCompute, Nineteen, Liquid * Friendli, Chutes, DeepSeek **Not Currently Supported** * AWS Bedrock, Groq, Modal * Google, Google AI Studio, Minimax * HuggingFace, Replicate, Perplexity * Mistral, AI21, Featherless * Lynn, Lambda, Reflection * SambaNova, Inflection, ZeroOneAI * AionLabs, Alibaba, Nebius * Kluster, Targon, InferenceNet To implement stream cancellation: ```python Python import requests from threading import Event, Thread def stream_with_cancellation(prompt: str, cancel_event: Event): with requests.Session() as session: response = session.post( "https://openrouter.ai/api/v1/chat/completions", headers={"Authorization": f"Bearer {{API_KEY_REF}}"}, json={"model": "{{MODEL}}", "messages": [{"role": "user", "content": prompt}], "stream": True}, stream=True ) try: for line in response.iter_lines(): if cancel_event.is_set(): response.close() return if line: print(line.decode(), end="", flush=True) finally: response.close() # Example usage: cancel_event = Event() stream_thread = Thread(target=lambda: stream_with_cancellation("Write a story", cancel_event)) stream_thread.start() # To cancel the stream: cancel_event.set() ``` ```typescript TypeScript const controller = new AbortController(); try { const response = await fetch( 'https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${{{API_KEY_REF}}}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: '{{MODEL}}', messages: [{ role: 'user', content: 'Write a story' }], stream: true, }), signal: controller.signal, }, ); // Process the stream... } catch (error) { if (error.name === 'AbortError') { console.log('Stream cancelled'); } else { throw error; } } // To cancel the stream: controller.abort(); ``` Cancellation only works for streaming requests with supported providers. For non-streaming requests or unsupported providers, the model will continue processing and you will be billed for the complete response. # Authentication > Learn how to authenticate with OpenRouter using API keys and Bearer tokens. Complete guide to secure authentication methods and best practices. You can cover model costs with OpenRouter API keys. Our API authenticates requests using Bearer tokens. This allows you to use `curl` or the [OpenAI SDK](https://platform.openai.com/docs/frameworks) directly with OpenRouter. API keys on OpenRouter are more powerful than keys used directly for model APIs. They allow users to set credit limits for apps, and they can be used in [OAuth](/docs/use-cases/oauth-pkce) flows. ## Using an API key To use an API key, [first create your key](https://openrouter.ai/keys). Give it a name and you can optionally set a credit limit. If you're calling the OpenRouter API directly, set the `Authorization` header to a Bearer token with your API key. If you're using the OpenAI Typescript SDK, set the `api_base` to `https://openrouter.ai/api/v1` and the `apiKey` to your API key. ```typescript title="TypeScript (Bearer Token)" fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer ', 'HTTP-Referer': '', // Optional. Site URL for rankings on openrouter.ai. 'X-Title': '', // Optional. Site title for rankings on openrouter.ai. 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o', messages: [ { role: 'user', content: 'What is the meaning of life?', }, ], }), }); ``` ```typescript title="TypeScript (OpenAI SDK)" import OpenAI from 'openai'; const openai = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: '', defaultHeaders: { 'HTTP-Referer': '', // Optional. Site URL for rankings on openrouter.ai. 'X-Title': '', // Optional. Site title for rankings on openrouter.ai. }, }); async function main() { const completion = await openai.chat.completions.create({ model: 'openai/gpt-4o', messages: [{ role: 'user', content: 'Say this is a test' }], }); console.log(completion.choices[0].message); } main(); ``` ```python title="Python" import openai openai.api_base = "https://openrouter.ai/api/v1" openai.api_key = "" response = openai.ChatCompletion.create( model="openai/gpt-4o", messages=[...], headers={ "HTTP-Referer": "", # Optional. Site URL for rankings on openrouter.ai. "X-Title": "", # Optional. Site title for rankings on openrouter.ai. }, ) reply = response.choices[0].message ``` ```shell title="Shell" curl https://openrouter.ai/api/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ -d '{ "model": "openai/gpt-4o", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"} ] }' ``` To stream with Python, [see this example from OpenAI](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb). ## If your key has been exposed You must protect your API keys and never commit them to public repositories. OpenRouter is a GitHub secret scanning partner, and has other methods to detect exposed keys. If we determine that your key has been compromised, you will receive an email notification. If you receive such a notification or suspect your key has been exposed, immediately visit [your key settings page](https://openrouter.ai/settings/keys) to delete the compromised key and create a new one. Using environment variables and keeping keys out of your codebase is strongly recommended. # Parameters > Learn about all available parameters for OpenRouter API requests. Configure temperature, max tokens, top_p, and other model-specific settings. Sampling parameters shape the token generation process of the model. You may send any parameters from the following list, as well as others, to OpenRouter. OpenRouter will default to the values listed below if certain parameters are absent from your request (for example, `temperature` to 1.0). We will also transmit some provider-specific parameters, such as `safe_prompt` for Mistral or `raw_mode` for Hyperbolic directly to the respective providers if specified. Please refer to the model’s provider section to confirm which parameters are supported. For detailed guidance on managing provider-specific parameters, [click here](/docs/features/provider-routing#requiring-providers-to-support-all-parameters-beta). ## Temperature * Key: `temperature` * Optional, **float**, 0.0 to 2.0 * Default: 1.0 * Explainer Video: [Watch](https://youtu.be/ezgqHnWvua8) This setting influences the variety in the model's responses. Lower values lead to more predictable and typical responses, while higher values encourage more diverse and less common responses. At 0, the model always gives the same response for a given input. ## Top P * Key: `top_p` * Optional, **float**, 0.0 to 1.0 * Default: 1.0 * Explainer Video: [Watch](https://youtu.be/wQP-im_HInk) This setting limits the model's choices to a percentage of likely tokens: only the top tokens whose probabilities add up to P. A lower value makes the model's responses more predictable, while the default setting allows for a full range of token choices. Think of it like a dynamic Top-K. ## Top K * Key: `top_k` * Optional, **integer**, 0 or above * Default: 0 * Explainer Video: [Watch](https://youtu.be/EbZv6-N8Xlk) This limits the model's choice of tokens at each step, making it choose from a smaller set. A value of 1 means the model will always pick the most likely next token, leading to predictable results. By default this setting is disabled, making the model to consider all choices. ## Frequency Penalty * Key: `frequency_penalty` * Optional, **float**, -2.0 to 2.0 * Default: 0.0 * Explainer Video: [Watch](https://youtu.be/p4gl6fqI0_w) This setting aims to control the repetition of tokens based on how often they appear in the input. It tries to use less frequently those tokens that appear more in the input, proportional to how frequently they occur. Token penalty scales with the number of occurrences. Negative values will encourage token reuse. ## Presence Penalty * Key: `presence_penalty` * Optional, **float**, -2.0 to 2.0 * Default: 0.0 * Explainer Video: [Watch](https://youtu.be/MwHG5HL-P74) Adjusts how often the model repeats specific tokens already used in the input. Higher values make such repetition less likely, while negative values do the opposite. Token penalty does not scale with the number of occurrences. Negative values will encourage token reuse. ## Repetition Penalty * Key: `repetition_penalty` * Optional, **float**, 0.0 to 2.0 * Default: 1.0 * Explainer Video: [Watch](https://youtu.be/LHjGAnLm3DM) Helps to reduce the repetition of tokens from the input. A higher value makes the model less likely to repeat tokens, but too high a value can make the output less coherent (often with run-on sentences that lack small words). Token penalty scales based on original token's probability. ## Min P * Key: `min_p` * Optional, **float**, 0.0 to 1.0 * Default: 0.0 Represents the minimum probability for a token to be considered, relative to the probability of the most likely token. (The value changes depending on the confidence level of the most probable token.) If your Min-P is set to 0.1, that means it will only allow for tokens that are at least 1/10th as probable as the best possible option. ## Top A * Key: `top_a` * Optional, **float**, 0.0 to 1.0 * Default: 0.0 Consider only the top tokens with "sufficiently high" probabilities based on the probability of the most likely token. Think of it like a dynamic Top-P. A lower Top-A value focuses the choices based on the highest probability token but with a narrower scope. A higher Top-A value does not necessarily affect the creativity of the output, but rather refines the filtering process based on the maximum probability. ## Seed * Key: `seed` * Optional, **integer** If specified, the inferencing will sample deterministically, such that repeated requests with the same seed and parameters should return the same result. Determinism is not guaranteed for some models. ## Max Tokens * Key: `max_tokens` * Optional, **integer**, 1 or above This sets the upper limit for the number of tokens the model can generate in response. It won't produce more than this limit. The maximum value is the context length minus the prompt length. ## Logit Bias * Key: `logit_bias` * Optional, **map** Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. ## Logprobs * Key: `logprobs` * Optional, **boolean** Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned. ## Top Logprobs * Key: `top_logprobs` * Optional, **integer** An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used. ## Response Format * Key: `response_format` * Optional, **map** Forces the model to produce specific output format. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. **Note**: when using JSON mode, you should also instruct the model to produce JSON yourself via a system or user message. ## Structured Outputs * Key: `structured_outputs` * Optional, **boolean** If the model can return structured outputs using response\_format json\_schema. ## Stop * Key: `stop` * Optional, **array** Stop generation immediately if the model encounter any token specified in the stop array. ## Tools * Key: `tools` * Optional, **array** Tool calling parameter, following OpenAI's tool calling request shape. For non-OpenAI providers, it will be transformed accordingly. [Click here to learn more about tool calling](/docs/requests#tool-calls) ## Tool Choice * Key: `tool_choice` * Optional, **array** Controls which (if any) tool is called by the model. 'none' means the model will not call any tool and instead generates a message. 'auto' means the model can pick between generating a message or calling one or more tools. 'required' means the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. ## Max Price * Key: `max_price` * Optional, **map** A JSON object specifying the highest provider pricing you will accept. For example, the value `{"completion": "1", "prompt": "2"}` will route to any provider with a price of `<= $1/m` prompt tokens, and `<= $2/m` completion tokens or less. Some providers support per request pricing, in which case you can use the "request" attribute of max\_price. Lastly, "image" is also available, which specifies the max price per image you will accept. Practically, this field is often combined with a provider "sort" to e.g. state "Use the provider with the highest throughput, as long as it doesn't cost more than `$x/m` tokens." ## Include Reasoning * Key: `include_reasoning` * Optional, **boolean** * Default: **false** If the endpoint can return reasoning explicitly, setting this parameter will include reasoning tokensin the response. They will be available as text in a field called `reasoning`, within a message or message delta, alongside an empty `content` field. # Limits > Learn about OpenRouter's API rate limits, credit-based quotas, and DDoS protection. Configure and monitor your model usage limits effectively. If you need a lot of inference, making additional accounts or API keys *makes no difference*. We manage the rate limit globally. We do however have different rate limits for different models, so you can share the load that way if you do run into issues. If you start getting rate limited -- [tell us](https://discord.gg/fVyRaUDgxW)! We are here to help. If you are able, don't specify providers; that will let us load balance it better. ## Rate Limits and Credits Remaining To check the rate limit or credits left on an API key, make a GET request to `https://openrouter.ai/api/v1/auth/key`. ```typescript title="TypeScript" const response = await fetch('https://openrouter.ai/api/v1/auth/key', { method: 'GET', headers: { Authorization: 'Bearer {{API_KEY_REF}}', }, }); ``` If you submit a valid API key, you should get a response of the form: ```typescript title="TypeScript" type Key = { data: { label: string; usage: number; // Number of credits used limit: number | null; // Credit limit for the key, or null if unlimited is_free_tier: boolean; // Whether the user has paid for credits before rate_limit: { requests: number; // Number of requests allowed... interval: string; // in this interval, e.g. "10s" }; }; }; ``` There are a few rate limits that apply to certain types of requests, regardless of account status: 1. **Free limit**: If you are using a free model variant (with an ID ending in {sep}{Variant.Free}), then you will be limited to {freeModelRateLimitRPM} requests per minute and {freeModelRateLimitRPD} requests per day. 2. **DDoS protection**: Cloudflare's DDoS protection will block requests that dramatically exceed reasonable usage. For all other requests, rate limits are a function of the number of credits remaining on the key or account. Partial credits round up in your favor. For the credits available on your API key, you can make **1 request per credit per second** up to the surge limit (typically 500 requests per second, but you can go higher). For example: * 0.5 credits → 1 req/s (minimum) * 5 credits → 5 req/s * 10 credits → 10 req/s * 500 credits → 500 req/s * 1000 credits → Contact us if you see ratelimiting from OpenRouter If your account has a negative credit balance, you may see {HTTPStatus.S402_Payment_Required} errors, including for free models. Adding credits to put your balance above zero allows you to use those models again. # Errors > Learn how to handle errors in OpenRouter API interactions. Comprehensive guide to error codes, messages, and best practices for error handling. For errors, OpenRouter returns a JSON response with the following shape: ```typescript type ErrorResponse = { error: { code: number; message: string; metadata?: Record; }; }; ``` The HTTP Response will have the same status code as `error.code`, forming a request error if: * Your original request is invalid * Your API key/account is out of credits Otherwise, the returned HTTP response status will be {HTTPStatus.S200_OK} and any error occurred while the LLM is producing the output will be emitted in the response body or as an SSE data event. Example code for printing errors in JavaScript: ```typescript const request = await fetch('https://openrouter.ai/...'); console.log(request.status); // Will be an error code unless the model started processing your request const response = await request.json(); console.error(response.error?.status); // Will be an error code console.error(response.error?.message); ``` ## Error Codes * **{HTTPStatus.S400_Bad_Request}**: Bad Request (invalid or missing params, CORS) * **{HTTPStatus.S401_Unauthorized}**: Invalid credentials (OAuth session expired, disabled/invalid API key) * **{HTTPStatus.S402_Payment_Required}**: Your account or API key has insufficient credits. Add more credits and retry the request. * **{HTTPStatus.S403_Forbidden}**: Your chosen model requires moderation and your input was flagged * **{HTTPStatus.S408_Request_Timeout}**: Your request timed out * **{HTTPStatus.S429_Too_Many_Requests}**: You are being rate limited * **{HTTPStatus.S502_Bad_Gateway}**: Your chosen model is down or we received an invalid response from it * **{HTTPStatus.S503_Service_Unavailable}**: There is no available model provider that meets your routing requirements ## Moderation Errors If your input was flagged, the `error.metadata` will contain information about the issue. The shape of the metadata is as follows: ```typescript type ModerationErrorMetadata = { reasons: string[]; // Why your input was flagged flagged_input: string; // The text segment that was flagged, limited to 100 characters. If the flagged input is longer than 100 characters, it will be truncated in the middle and replaced with ... provider_name: string; // The name of the provider that requested moderation model_slug: string; }; ``` ## Provider Errors If the model provider encounters an error, the `error.metadata` will contain information about the issue. The shape of the metadata is as follows: ```typescript type ProviderErrorMetadata = { provider_name: string; // The name of the provider that encountered the error raw: unknown; // The raw error from the provider }; ``` ## When No Content is Generated Occasionally, the model may not generate any content. This typically occurs when: * The model is warming up from a cold start * The system is scaling up to handle more requests Warm-up times usually range from a few seconds to a few minutes, depending on the model and provider. If you encounter persistent no-content issues, consider implementing a simple retry mechanism or trying again with a different provider or model that has more recent activity. Additionally, be aware that in some cases, you may still be charged for the prompt processing cost by the upstream provider, even if no content is generated. # Completion ```http POST https://openrouter.ai/api/v1/completions Content-Type: application/json ``` Send a completion request to a selected model (text-only format) ## Response Body - 200: Successful completion ## Examples ```shell curl -X POST https://openrouter.ai/api/v1/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "model": "model", "prompt": "prompt" }' ``` # Chat completion ```http POST https://openrouter.ai/api/v1/chat/completions Content-Type: application/json ``` Send a chat completion request to a selected model ## Response Body - 200: Successful completion ## Examples ```shell curl -X POST https://openrouter.ai/api/v1/chat/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-3.5-turbo", "messages": [ { "role": "user", "content": "What is the meaning of life?" } ] }' ``` # Get a generation ```http GET https://openrouter.ai/api/v1/generation ``` Returns metadata about a specific generation request ## Query Parameters - Id (required) ## Response Body - 200: Returns the request metadata for this generation ## Examples ```shell curl -G https://openrouter.ai/api/v1/generation \ -H "Authorization: Bearer " \ -d id=id ``` # List available models ```http GET https://openrouter.ai/api/v1/models ``` Returns a list of models available through the API ## Response Body - 200: List of available models ## Examples ```shell curl https://openrouter.ai/api/v1/models ``` # List endpoints for a model ```http GET https://openrouter.ai/api/v1/models/{author}/{slug}/endpoints ``` ## Path Parameters - Author (required) - Slug (required) ## Response Body - 200: List of endpoints for the model ## Examples ```shell curl https://openrouter.ai/api/v1/models/author/slug/endpoints ``` # Get credits ```http GET https://openrouter.ai/api/v1/credits ``` Returns the total credits purchased and used for the authenticated user ## Response Body - 200: Returns the total credits purchased and used ## Examples ```shell curl https://openrouter.ai/api/v1/credits \ -H "Authorization: Bearer " ``` # Create a Coinbase charge ```http POST https://openrouter.ai/api/v1/credits/coinbase Content-Type: application/json ``` Creates and hydrates a Coinbase Commerce charge for cryptocurrency payments ## Response Body - 200: Returns the calldata to fulfill the transaction ## Examples ```shell curl -X POST https://openrouter.ai/api/v1/credits/coinbase \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "amount": 1.1, "sender": "sender", "chain_id": 1 }' ``` # BYOK > Learn how to use your existing AI provider keys with OpenRouter. Integrate your own API keys while leveraging OpenRouter's unified interface and features. ## Bring your own API Keys OpenRouter supports both OpenRouter credits and the option to bring your own provider keys (BYOK). When you use OpenRouter credits, your rate limits for each provider are managed by OpenRouter. Using provider keys enables direct control over rate limits and costs via your provider account. Your provider keys are securely encrypted and used for all requests routed through the specified provider. Manage keys in your [account settings](/settings/integrations). The cost of using custom provider keys on OpenRouter is **5% of what the same model/provider would cost normally on OpenRouter** and will be deducted from your OpenRouter credits. ### Automatic Fallback You can configure individual keys to act as fallbacks. When "Use this key as a fallback" is enabled for a key, OpenRouter will prioritize using your credits. If it hits a rate limit or encounters a failure, it will then retry with your key. Conversely, if "Use this key as a fallback" is disabled for a key, OpenRouter will prioritize using your key. If it hits a rate limit or encounters a failure, it will then retry with your credits. ### Azure API Keys To use Azure AI Services with OpenRouter, you'll need to provide your Azure API key configuration in JSON format. Each key configuration requires the following fields: ```json { "model_slug": "the-openrouter-model-slug", "endpoint_url": "https://.services.ai.azure.com/deployments//chat/completions?api-version=", "api_key": "your-azure-api-key", "model_id": "the-azure-model-id" } ``` You can find these values in your Azure AI Services resource: 1. **endpoint\_url**: Navigate to your Azure AI Services resource in the Azure portal. In the "Overview" section, you'll find your endpoint URL. Make sure to append `/chat/completions` to the base URL. You can read more in the [Azure Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/model-inference/concepts/endpoints?tabs=python). 2. **api\_key**: In the same "Overview" section of your Azure AI Services resource, you can find your API key under "Keys and Endpoint". 3. **model\_id**: This is the name of your model deployment in Azure AI Services. 4. **model\_slug**: This is the OpenRouter model identifier you want to use this key for. Since Azure supports multiple model deployments, you can provide an array of configurations for different models: ```json [ { "model_slug": "mistralai/mistral-large", "endpoint_url": "https://example-project.openai.azure.com/openai/deployments/mistral-large/chat/completions?api-version=2024-08-01-preview", "api_key": "your-azure-api-key", "model_id": "mistral-large" }, { "model_slug": "openai/gpt-4o", "endpoint_url": "https://example-project.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview", "api_key": "your-azure-api-key", "model_id": "gpt-4o" } ] ``` Make sure to replace the url with your own project url. Also the url should end with /chat/completions with the api version that you would like to use. # Crypto API > Learn how to purchase OpenRouter credits using cryptocurrency. Complete guide to Coinbase integration, supported chains, and automated credit purchases. You can purchase credits using cryptocurrency through our Coinbase integration. This can either happen through the UI, on your [credits page](https://openrouter.ai/credits), or through our API as described below. While other forms of payment are possible, this guide specifically shows how to pay with the chain's native token. Headless credit purchases involve three steps: 1. Getting the calldata for a new credit purchase 2. Sending a transaction on-chain using that data 3. Detecting low account balance, and purchasing more ## Getting Credit Purchase Calldata Make a POST request to `/api/v1/credits/coinbase` to create a new charge. You'll include the amount of credits you want to purchase (in USD, up to \${cryptoMaxDollarPurchase}), the address you'll be sending the transaction from, and the EVM chain ID of the network you'll be sending on. Currently, we only support the following chains (mainnet only): * Ethereum ({SupportedChainIDs.Ethereum}) * Polygon ({SupportedChainIDs.Polygon}) * Base ({SupportedChainIDs.Base}) ***recommended*** ```typescript const response = await fetch('https://openrouter.ai/api/v1/credits/coinbase', { method: 'POST', headers: { Authorization: 'Bearer ', 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: 10, // Target credit amount in USD sender: '0x9a85CB3bfd494Ea3a8C9E50aA6a3c1a7E8BACE11', chain_id: 8453, }), }); const responseJSON = await response.json(); ``` The response includes the charge details and transaction data needed to execute the on-chain payment: ```json { "data": { "id": "...", "created_at": "2024-01-01T00:00:00Z", "expires_at": "2024-01-01T01:00:00Z", "web3_data": { "transfer_intent": { "metadata": { "chain_id": 8453, "contract_address": "0x03059433bcdb6144624cc2443159d9445c32b7a8", "sender": "0x9a85CB3bfd494Ea3a8C9E50aA6a3c1a7E8BACE11" }, "call_data": { "recipient_amount": "...", "deadline": "...", "recipient": "...", "recipient_currency": "...", "refund_destination": "...", "fee_amount": "...", "id": "...", "operator": "...", "signature": "...", "prefix": "..." } } } } } ``` ## Sending the Transaction You can use [viem](https://viem.sh) (or another similar evm client) to execute the transaction on-chain. In this example, we'll be fulfilling the charge using the [swapAndTransferUniswapV3Native()](https://github.com/coinbase/commerce-onchain-payment-protocol/blob/d891289bd1f41bb95f749af537f2b6a36b17f889/contracts/interfaces/ITransfers.sol#L168-L171) function. Other methods of swapping are also available, and you can learn more by checking out Coinbase's [onchain payment protocol here](https://github.com/coinbase/commerce-onchain-payment-protocol/tree/master). Note, if you are trying to pay in a less common ERC-20, there is added complexity in needing to make sure that there is sufficient liquidity in the pool to swap the tokens. ```typescript import { createPublicClient, createWalletClient, http, parseEther } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { base } from 'viem/chains'; // The ABI for Coinbase's onchain payment protocol const abi = [ { inputs: [ { internalType: 'contract IUniversalRouter', name: '_uniswap', type: 'address', }, { internalType: 'contract Permit2', name: '_permit2', type: 'address' }, { internalType: 'address', name: '_initialOperator', type: 'address' }, { internalType: 'address', name: '_initialFeeDestination', type: 'address', }, { internalType: 'contract IWrappedNativeCurrency', name: '_wrappedNativeCurrency', type: 'address', }, ], stateMutability: 'nonpayable', type: 'constructor', }, { inputs: [], name: 'AlreadyProcessed', type: 'error' }, { inputs: [], name: 'ExpiredIntent', type: 'error' }, { inputs: [ { internalType: 'address', name: 'attemptedCurrency', type: 'address' }, ], name: 'IncorrectCurrency', type: 'error', }, { inputs: [], name: 'InexactTransfer', type: 'error' }, { inputs: [{ internalType: 'uint256', name: 'difference', type: 'uint256' }], name: 'InsufficientAllowance', type: 'error', }, { inputs: [{ internalType: 'uint256', name: 'difference', type: 'uint256' }], name: 'InsufficientBalance', type: 'error', }, { inputs: [{ internalType: 'int256', name: 'difference', type: 'int256' }], name: 'InvalidNativeAmount', type: 'error', }, { inputs: [], name: 'InvalidSignature', type: 'error' }, { inputs: [], name: 'InvalidTransferDetails', type: 'error' }, { inputs: [ { internalType: 'address', name: 'recipient', type: 'address' }, { internalType: 'uint256', name: 'amount', type: 'uint256' }, { internalType: 'bool', name: 'isRefund', type: 'bool' }, { internalType: 'bytes', name: 'data', type: 'bytes' }, ], name: 'NativeTransferFailed', type: 'error', }, { inputs: [], name: 'NullRecipient', type: 'error' }, { inputs: [], name: 'OperatorNotRegistered', type: 'error' }, { inputs: [], name: 'PermitCallFailed', type: 'error' }, { inputs: [{ internalType: 'bytes', name: 'reason', type: 'bytes' }], name: 'SwapFailedBytes', type: 'error', }, { inputs: [{ internalType: 'string', name: 'reason', type: 'string' }], name: 'SwapFailedString', type: 'error', }, { anonymous: false, inputs: [ { indexed: false, internalType: 'address', name: 'operator', type: 'address', }, { indexed: false, internalType: 'address', name: 'feeDestination', type: 'address', }, ], name: 'OperatorRegistered', type: 'event', }, { anonymous: false, inputs: [ { indexed: false, internalType: 'address', name: 'operator', type: 'address', }, ], name: 'OperatorUnregistered', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, internalType: 'address', name: 'previousOwner', type: 'address', }, { indexed: true, internalType: 'address', name: 'newOwner', type: 'address', }, ], name: 'OwnershipTransferred', type: 'event', }, { anonymous: false, inputs: [ { indexed: false, internalType: 'address', name: 'account', type: 'address', }, ], name: 'Paused', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, internalType: 'address', name: 'operator', type: 'address', }, { indexed: false, internalType: 'bytes16', name: 'id', type: 'bytes16' }, { indexed: false, internalType: 'address', name: 'recipient', type: 'address', }, { indexed: false, internalType: 'address', name: 'sender', type: 'address', }, { indexed: false, internalType: 'uint256', name: 'spentAmount', type: 'uint256', }, { indexed: false, internalType: 'address', name: 'spentCurrency', type: 'address', }, ], name: 'Transferred', type: 'event', }, { anonymous: false, inputs: [ { indexed: false, internalType: 'address', name: 'account', type: 'address', }, ], name: 'Unpaused', type: 'event', }, { inputs: [], name: 'owner', outputs: [{ internalType: 'address', name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'pause', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'paused', outputs: [{ internalType: 'bool', name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'permit2', outputs: [{ internalType: 'contract Permit2', name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'registerOperator', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { internalType: 'address', name: '_feeDestination', type: 'address' }, ], name: 'registerOperatorWithFeeDestination', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'renounceOwnership', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ internalType: 'address', name: 'newSweeper', type: 'address' }], name: 'setSweeper', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, { components: [ { internalType: 'address', name: 'owner', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, ], internalType: 'struct EIP2612SignatureTransferData', name: '_signatureTransferData', type: 'tuple', }, ], name: 'subsidizedTransferToken', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, { internalType: 'uint24', name: 'poolFeesTier', type: 'uint24' }, ], name: 'swapAndTransferUniswapV3Native', outputs: [], stateMutability: 'payable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, { components: [ { components: [ { components: [ { internalType: 'address', name: 'token', type: 'address' }, { internalType: 'uint256', name: 'amount', type: 'uint256' }, ], internalType: 'struct ISignatureTransfer.TokenPermissions', name: 'permitted', type: 'tuple', }, { internalType: 'uint256', name: 'nonce', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, ], internalType: 'struct ISignatureTransfer.PermitTransferFrom', name: 'permit', type: 'tuple', }, { components: [ { internalType: 'address', name: 'to', type: 'address' }, { internalType: 'uint256', name: 'requestedAmount', type: 'uint256', }, ], internalType: 'struct ISignatureTransfer.SignatureTransferDetails', name: 'transferDetails', type: 'tuple', }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, ], internalType: 'struct Permit2SignatureTransferData', name: '_signatureTransferData', type: 'tuple', }, { internalType: 'uint24', name: 'poolFeesTier', type: 'uint24' }, ], name: 'swapAndTransferUniswapV3Token', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, { internalType: 'address', name: '_tokenIn', type: 'address' }, { internalType: 'uint256', name: 'maxWillingToPay', type: 'uint256' }, { internalType: 'uint24', name: 'poolFeesTier', type: 'uint24' }, ], name: 'swapAndTransferUniswapV3TokenPreApproved', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { internalType: 'address payable', name: 'destination', type: 'address' }, ], name: 'sweepETH', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { internalType: 'address payable', name: 'destination', type: 'address' }, { internalType: 'uint256', name: 'amount', type: 'uint256' }, ], name: 'sweepETHAmount', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { internalType: 'address', name: '_token', type: 'address' }, { internalType: 'address', name: 'destination', type: 'address' }, ], name: 'sweepToken', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { internalType: 'address', name: '_token', type: 'address' }, { internalType: 'address', name: 'destination', type: 'address' }, { internalType: 'uint256', name: 'amount', type: 'uint256' }, ], name: 'sweepTokenAmount', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'sweeper', outputs: [{ internalType: 'address', name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, ], name: 'transferNative', outputs: [], stateMutability: 'payable', type: 'function', }, { inputs: [{ internalType: 'address', name: 'newOwner', type: 'address' }], name: 'transferOwnership', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, { components: [ { components: [ { components: [ { internalType: 'address', name: 'token', type: 'address' }, { internalType: 'uint256', name: 'amount', type: 'uint256' }, ], internalType: 'struct ISignatureTransfer.TokenPermissions', name: 'permitted', type: 'tuple', }, { internalType: 'uint256', name: 'nonce', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, ], internalType: 'struct ISignatureTransfer.PermitTransferFrom', name: 'permit', type: 'tuple', }, { components: [ { internalType: 'address', name: 'to', type: 'address' }, { internalType: 'uint256', name: 'requestedAmount', type: 'uint256', }, ], internalType: 'struct ISignatureTransfer.SignatureTransferDetails', name: 'transferDetails', type: 'tuple', }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, ], internalType: 'struct Permit2SignatureTransferData', name: '_signatureTransferData', type: 'tuple', }, ], name: 'transferToken', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, ], name: 'transferTokenPreApproved', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'unpause', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'unregisterOperator', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, { components: [ { components: [ { components: [ { internalType: 'address', name: 'token', type: 'address' }, { internalType: 'uint256', name: 'amount', type: 'uint256' }, ], internalType: 'struct ISignatureTransfer.TokenPermissions', name: 'permitted', type: 'tuple', }, { internalType: 'uint256', name: 'nonce', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, ], internalType: 'struct ISignatureTransfer.PermitTransferFrom', name: 'permit', type: 'tuple', }, { components: [ { internalType: 'address', name: 'to', type: 'address' }, { internalType: 'uint256', name: 'requestedAmount', type: 'uint256', }, ], internalType: 'struct ISignatureTransfer.SignatureTransferDetails', name: 'transferDetails', type: 'tuple', }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, ], internalType: 'struct Permit2SignatureTransferData', name: '_signatureTransferData', type: 'tuple', }, ], name: 'unwrapAndTransfer', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, ], name: 'unwrapAndTransferPreApproved', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { components: [ { internalType: 'uint256', name: 'recipientAmount', type: 'uint256' }, { internalType: 'uint256', name: 'deadline', type: 'uint256' }, { internalType: 'address payable', name: 'recipient', type: 'address', }, { internalType: 'address', name: 'recipientCurrency', type: 'address', }, { internalType: 'address', name: 'refundDestination', type: 'address', }, { internalType: 'uint256', name: 'feeAmount', type: 'uint256' }, { internalType: 'bytes16', name: 'id', type: 'bytes16' }, { internalType: 'address', name: 'operator', type: 'address' }, { internalType: 'bytes', name: 'signature', type: 'bytes' }, { internalType: 'bytes', name: 'prefix', type: 'bytes' }, ], internalType: 'struct TransferIntent', name: '_intent', type: 'tuple', }, ], name: 'wrapAndTransfer', outputs: [], stateMutability: 'payable', type: 'function', }, { stateMutability: 'payable', type: 'receive' }, ]; // Set up viem clients const publicClient = createPublicClient({ chain: base, transport: http(), }); const account = privateKeyToAccount('0x...'); const walletClient = createWalletClient({ chain: base, transport: http(), account, }); // Use the calldata included in the charge response const { contract_address } = responseJSON.data.web3_data.transfer_intent.metadata; const call_data = responseJSON.data.web3_data.transfer_intent.call_data; // When transacting in ETH, a pool fees tier of 500 (the lowest) is very // likely to be sufficient. However, if you plan to swap with a different // contract method, using less-common ERC-20 tokens, it is recommended to // call that chain's Uniswap QuoterV2 contract to check its liquidity. // Depending on the results, choose the lowest fee tier which has enough // liquidity in the pool. const poolFeesTier = 500; // Simulate the transaction first to prevent most common revert reasons const { request } = await publicClient.simulateContract({ abi, account, address: contract_address, functionName: 'swapAndTransferUniswapV3Native', args: [ { recipientAmount: BigInt(call_data.recipient_amount), deadline: BigInt( Math.floor(new Date(call_data.deadline).getTime() / 1000), ), recipient: call_data.recipient, recipientCurrency: call_data.recipient_currency, refundDestination: call_data.refund_destination, feeAmount: BigInt(call_data.fee_amount), id: call_data.id, operator: call_data.operator, signature: call_data.signature, prefix: call_data.prefix, }, poolFeesTier, ], // Transaction value in ETH. You'll want to include a little extra to // ensure the transaction & swap is successful. All excess funds return // back to your sender address afterwards. value: parseEther('0.004'), }); // Send the transaction on chain const txHash = await walletClient.writeContract(request); console.log('Transaction hash:', txHash); ``` Once the transaction succeeds on chain, we'll add credits to your account. You can track the transaction status using the returned transaction hash. Credit purchases lower than \$500 will be immediately credited once the transaction is on chain. Above \$500, there is a \~15 minute confirmation delay, ensuring the chain does not re-org your purchase. ## Detecting Low Balance While it is possible to simply run down the balance until your app starts receiving 402 error codes for insufficient credits, this gap in service while topping up might not be desirable. To avoid this, you can periodically call the `GET /api/v1/credits` endpoint to check your available credits. ```typescript const response = await fetch('https://openrouter.ai/api/v1/credits', { method: 'GET', headers: { Authorization: 'Bearer ' }, }); const { data } = await response.json(); ``` The response includes your total credits purchased and usage, where your current balance is the difference between the two: ```json { "data": { "total_credits": 50.0, "total_usage": 42.0 } } ``` Note that these values are cached, and may be up to 60 seconds stale. # OAuth PKCE > Implement secure user authentication with OpenRouter using OAuth PKCE. Complete guide to setting up and managing OAuth authentication flows. Users can connect to OpenRouter in one click using [Proof Key for Code Exchange (PKCE)](https://oauth.net/2/pkce/). Here's a step-by-step guide: ## PKCE Guide ### Step 1: Send your user to OpenRouter To start the PKCE flow, send your user to OpenRouter's `/auth` URL. ```txt title="With S256 Code Challenge (Recommended)" wordWrap https://openrouter.ai/auth?callback_url=&code_challenge=&code_challenge_method=S256 ``` ```txt title="With Plain Code Challenge" wordWrap https://openrouter.ai/auth?callback_url=&code_challenge=&code_challenge_method=plain ``` ```txt title="Without Code Challenge" wordWrap https://openrouter.ai/auth?callback_url= ``` The `code_challenge` parameter is optional but recommended. For maximum security, set `code_challenge_method` to `S256`, and set `code_challenge` to the base64 encoding of the sha256 hash of `code_verifier`. For more info, [visit Auth0's docs](https://auth0.com/docs/get-started/authentication-and-authorization-flow/call-your-api-using-the-authorization-code-flow-with-pkce#parameters). #### How to Generate a Code Challenge In JavaScript, you can use the `crypto` API to generate a code challenge for the S256 method. ```typescript title="Generate Code Challenge" async function sha256CodeChallenge(input: string) { return crypto.createHash('sha256').update(input).digest('base64url'); } const code_verifier = 'your_random_string'; const generatedCodeChallenge = await sha256CodeChallenge(code_verifier); ``` #### Localhost Apps If your app is a local-first app or otherwise doesn't have a public URL, it is recommended to test with `http://localhost:3000` as the callback and referrer URLs. When moving to production, replace the localhost/private referrer URL with a public GitHub repo or a link to your project website. ### Step 2: Exchange the code for a user-controlled API key After the user logs in with OpenRouter, they are redirected back to your site with a `code` parameter in the URL. Extract this code and make an API call to `https://openrouter.ai/api/v1/auth/keys` to exchange the code for a user-controlled API key. You can do this on the frontend or backend but backend is recommended for security. ```typescript title="Exchange Code" fetch('https://openrouter.ai/api/v1/auth/keys', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ code: '', code_verifier: '', // If code_challenge was used code_challenge_method: '', // If code_challenge was used }), }); ``` And that's it for the PKCE flow! ### Step 3: Use the API key Store the API key securely and use it to [make OpenRouter requests](/api-reference/completion). ```typescript title="Make an OpenRouter request" fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: 'Bearer ', 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'openai/gpt-4o', messages: [ { role: 'user', content: 'Hello!', }, ], }), }); ``` ## Error Codes * `400 Invalid code_challenge_method`: Make sure you're using the same code challenge method in step 1 as in step 2. * `403 Invalid code or code_verifier`: Make sure your user is logged in to OpenRouter, and that `code_verifier` and `code_challenge_method` are correct. * `405 Method Not Allowed`: Make sure you're using `POST` and `HTTPS` for your request. ## External Tools * [PKCE Tools](https://example-app.com/pkce) * [Online PKCE Generator](https://tonyxu-io.github.io/pkce-generator/) # Provider Integration > Learn how to integrate your AI models with OpenRouter. Complete guide for providers to make their models available through OpenRouter's unified API. ## For Providers If you'd like to be a model provider and sell inference on OpenRouter, [fill out our form](https://openrouter.notion.site/15a2fd57c4dc8067bc61ecd5263b31fd) to get started. To be eligible to provide inference on OpenRouter you must have the following: ### 1. List Models Endpoint You must implement an endpoint that returns all models that should be served by OpenRouter. At this endpoint, please return a list of all available models on your platform. Below is an example of the response format: ```json { "data": [ { "id": "anthropic/claude-2.0", "name": "Anthropic: Claude v2.0", "created": 1690502400, "description": "Anthropic's flagship model...", // Optional "context_length": 100000, // Required "max_completion_tokens": 4096, // Optional "pricing": { "prompt": "0.000008", // pricing per 1 token "completion": "0.000024", // pricing per 1 token "image": "0", // pricing per 1 image "request": "0" // pricing per 1 request } } ] } ``` NOTE: `pricing` fields are in string format to avoid floating point precision issues, and must be in USD. ### 2. Auto Top Up or Invoicing For OpenRouter to use the provider we must be able to pay for inference automatically. This can be done via auto top up or invoicing. # Reasoning Tokens > Learn how to use reasoning tokens to enhance AI model outputs. Implement step-by-step reasoning traces for better decision making and transparency. For models that support it (DeepSeek R1 being the best example), the OpenRouter API supports retrieving **Reasoning Tokens**. Reasoning tokens provide a transparent look into the reasoning steps taken by a model. Reasoning tokens are considered output tokens and charged accordingly. While all reasoning models generate these tokens, only some models and providers make them available in the response. To retrieve reasoning tokens when available, add `include_reasoning: true` to your API request. Reasoning tokens will appear in the `reasoning` field of each message: ```python Python import requests import json url = "https://openrouter.ai/api/v1/chat/completions" headers = { "Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json" } payload = { "model": "deepseek/deepseek-r1", "messages": [ {"role": "user", "content": "How would you build the world's tallest skyscraper?"} ], "include_reasoning": True } response = requests.post(url, headers=headers, data=json.dumps(payload)) print(response.json()['choices'][0]['message']['reasoning']) ``` This can be used in more complex workflows. Below is a toy example that injects R1's reasoning into a less advanced model to make it smarter. Note the use of the `stop` parameter, that will stop the model from generating a completion (only reasoning tokens will be returned). ```python Python import requests import json question = "Which is bigger: 9.11 or 9.9?" url = "https://openrouter.ai/api/v1/chat/completions" headers = { "Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json" } def do_req(model, content, include_reasoning=False): payload = { "model": model, "messages": [ {"role": "user", "content": content} ], "include_reasoning": include_reasoning, "stop": "" } return requests.post(url, headers=headers, data=json.dumps(payload)) # R1 will reliably return "done" for the content portion of the response content = f"{question} Please think this through, but don't output an answer" reasoning_response = do_req("deepseek/deepseek-r1", content, True) reasoning = reasoning_response.json()['choices'][0]['message']['reasoning'] # Let's test! Here's the naive response: simple_response = do_req("openai/gpt-4o-mini", question) print(simple_response.json()['choices'][0]['message']['content']) # Here's the response with the reasoning token injected: content = f"{question}. Here is some context to help you: {reasoning}" smart_response = do_req("openai/gpt-4o-mini", content) print(smart_response.json()['choices'][0]['message']['content']) ``` # Frameworks > Integrate OpenRouter using popular frameworks and SDKs. Complete guides for OpenAI SDK, LangChain, PydanticAI, and Vercel AI SDK integration. You can find a few examples of using OpenRouter with other frameworks in [this Github repository](https://github.com/OpenRouterTeam/openrouter-examples). Here are some examples: ## Using the OpenAI SDK * Using `pip install openai`: [github](https://github.com/OpenRouterTeam/openrouter-examples-python/blob/main/src/openai_test.py). * Using `npm i openai`: [github](https://github.com/OpenRouterTeam/openrouter-examples/blob/main/examples/openai/index.ts). You can also use [Grit](https://app.grit.io/studio?key=RKC0n7ikOiTGTNVkI8uRS) to automatically migrate your code. Simply run `npx @getgrit/launcher openrouter`. ```typescript title="TypeScript" import OpenAI from "openai" const openai = new OpenAI({ baseURL: "https://openrouter.ai/api/v1", apiKey: "${API_KEY_REF}", defaultHeaders: { ${getHeaderLines().join('\n ')} }, }) async function main() { const completion = await openai.chat.completions.create({ model: "${Model.GPT_4_Omni}", messages: [ { role: "user", content: "Say this is a test" } ], }) console.log(completion.choices[0].message) } main(); ``` ```python title="Python" from openai import OpenAI from os import getenv # gets API Key from environment variable OPENAI_API_KEY client = OpenAI( base_url="https://openrouter.ai/api/v1", api_key=getenv("OPENROUTER_API_KEY"), ) completion = client.chat.completions.create( model="${Model.GPT_4_Omni}", extra_headers={ "HTTP-Referer": "", # Optional. Site URL for rankings on openrouter.ai. "X-Title": "", # Optional. Site title for rankings on openrouter.ai. }, # pass extra_body to access OpenRouter-only arguments. # extra_body={ # "models": [ # "${Model.GPT_4_Omni}", # "${Model.Mixtral_8x_22B_Instruct}" # ] # }, messages=[ { "role": "user", "content": "Say this is a test", }, ], ) print(completion.choices[0].message.content) ``` ## Using LangChain * Using [LangChain for Python](https://github.com/langchain-ai/langchain): [github](https://github.com/alexanderatallah/openrouter-streamlit/blob/main/pages/2_Langchain_Quickstart.py) * Using [LangChain.js](https://github.com/langchain-ai/langchainjs): [github](https://github.com/OpenRouterTeam/openrouter-examples/blob/main/examples/langchain/index.ts) * Using [Streamlit](https://streamlit.io/): [github](https://github.com/alexanderatallah/openrouter-streamlit) ```typescript title="TypeScript" const chat = new ChatOpenAI( { modelName: '', temperature: 0.8, streaming: true, openAIApiKey: '${API_KEY_REF}', }, { basePath: 'https://openrouter.ai/api/v1', baseOptions: { headers: { 'HTTP-Referer': '', // Optional. Site URL for rankings on openrouter.ai. 'X-Title': '', // Optional. Site title for rankings on openrouter.ai. }, }, }, ); ``` ```python title="Python" from langchain.chat_models import ChatOpenAI from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from os import getenv from dotenv import load_dotenv load_dotenv() template = """Question: {question} Answer: Let's think step by step.""" prompt = PromptTemplate(template=template, input_variables=["question"]) llm = ChatOpenAI( openai_api_key=getenv("OPENROUTER_API_KEY"), openai_api_base=getenv("OPENROUTER_BASE_URL"), model_name="", model_kwargs={ "headers": { "HTTP-Referer": getenv("YOUR_SITE_URL"), "X-Title": getenv("YOUR_SITE_NAME"), } }, ) llm_chain = LLMChain(prompt=prompt, llm=llm) question = "What NFL team won the Super Bowl in the year Justin Beiber was born?" print(llm_chain.run(question)) ``` *** ## Using PydanticAI [PydanticAI](https://github.com/pydantic/pydantic-ai) provides a high-level interface for working with various LLM providers, including OpenRouter. ### Installation ```bash pip install 'pydantic-ai-slim[openai]' ``` ### Configuration You can use OpenRouter with PydanticAI through its OpenAI-compatible interface: ```python from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIModel model = OpenAIModel( "anthropic/claude-3.5-sonnet", # or any other OpenRouter model base_url="https://openrouter.ai/api/v1", api_key="sk-or-...", ) agent = Agent(model) result = await agent.run("What is the meaning of life?") print(result) ``` For more details about using PydanticAI with OpenRouter, see the [PydanticAI documentation](https://ai.pydantic.dev/models/#api_key-argument). *** ## Vercel AI SDK You can use the [Vercel AI SDK](https://www.npmjs.com/package/ai) to integrate OpenRouter with your Next.js app. To get started, install [@openrouter/ai-sdk-provider](https://github.com/OpenRouterTeam/ai-sdk-provider): ```bash npm install @openrouter/ai-sdk-provider ``` And then you can use [streamText()](https://sdk.vercel.ai/docs/reference/ai-sdk-core/stream-text) API to stream text from OpenRouter. ```typescript title="TypeScript" import { createOpenRouter } from '@openrouter/ai-sdk-provider'; import { streamText } from 'ai'; import { z } from 'zod'; export const getLasagnaRecipe = async (modelName: string) => { const openrouter = createOpenRouter({ apiKey: '${API_KEY_REF}', }); const result = await streamText({ model: openrouter(modelName), prompt: 'Write a vegetarian lasagna recipe for 4 people.', }); return result.toAIStreamResponse(); }; export const getWeather = async (modelName: string) => { const openrouter = createOpenRouter({ apiKey: '${API_KEY_REF}', }); const result = await streamText({ model: openrouter(modelName), prompt: 'What is the weather in San Francisco, CA in Fahrenheit?', tools: { getCurrentWeather: { description: 'Get the current weather in a given location', parameters: z.object({ location: z .string() .describe('The city and state, e.g. San Francisco, CA'), unit: z.enum(['celsius', 'fahrenheit']).optional(), }), execute: async ({ location, unit = 'celsius' }) => { // Mock response for the weather const weatherData = { 'Boston, MA': { celsius: '15°C', fahrenheit: '59°F', }, 'San Francisco, CA': { celsius: '18°C', fahrenheit: '64°F', }, }; const weather = weatherData[location]; if (!weather) { return `Weather data for ${location} is not available.`; } return `The current weather in ${location} is ${weather[unit]}.`; }, }, }, }); return result.toAIStreamResponse(); }; ```