The OpenRouter SDK gives access to over 300 large language models on the OpenRouter chat and completion APIs, as well as the rest of our full API. For more information about the API: OpenRouter Documentation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
npm add @openrouter/sdk
# Install optional peer dependencies if you plan to use React hooks
npm add @tanstack/react-query react react-dom
pnpm add @openrouter/sdk
# Install optional peer dependencies if you plan to use React hooks
pnpm add @tanstack/react-query react react-dom
bun add @openrouter/sdk
# Install optional peer dependencies if you plan to use React hooks
bun add @tanstack/react-query react react-dom
yarn add @openrouter/sdk
# Install optional peer dependencies if you plan to use React hooks
yarn add @tanstack/react-query react react-dom
Note
This package is published with CommonJS and ES Modules (ESM) support.
For supported JavaScript runtimes, please consult RUNTIMES.md.
import { OpenRouter } from "@openrouter/sdk";
const openRouter = new OpenRouter({
apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
});
async function run() {
const result = await openRouter.beta.responses.send({
input: [
{
type: "message",
role: "user",
content: "Hello, how are you?",
},
],
instructions: "<value>",
metadata: {
"user_id": "123",
"session_id": "abc-def-ghi",
},
tools: [
{
type: "function",
name: "get_current_weather",
description: "Get the current weather in a given location",
strict: true,
parameters: {
"type": "object",
"properties": {
"location": {
"type": "string",
},
},
},
},
],
toolChoice: "auto",
parallelToolCalls: false,
model: "anthropic/claude-4.5-sonnet-20250929",
models: [
"<value 1>",
],
text: {
format: {
type: "text",
},
verbosity: "medium",
},
reasoning: {
effort: "medium",
summary: "auto",
maxTokens: 6415.05,
enabled: true,
},
maxOutputTokens: 5270.85,
temperature: 0.7,
topP: 0.9,
topK: 5913.88,
promptCacheKey: "<value>",
previousResponseId: "<id>",
prompt: {
id: "prompt-abc123",
variables: {
"name": {
type: "input_text",
text: "John",
},
},
},
include: [
"message.input_image.image_url",
],
background: false,
safetyIdentifier: "<value>",
store: false,
serviceTier: "auto",
truncation: "auto",
stream: false,
provider: {
allowFallbacks: false,
requireParameters: true,
dataCollection: "deny",
zdr: true,
order: [
"Moonshot AI",
],
only: [
"<value>",
],
ignore: [
"<value>",
],
quantizations: [
"bf16",
],
sort: "price",
maxPrice: {
prompt: "<value>",
completion: 4351.98,
image: "https://loremflickr.com/916/1698?lock=7420998995259402",
audio: "<value>",
request: "<value>",
},
experimental: {},
},
plugins: [
{
id: "file-parser",
maxFiles: 3555.38,
pdf: {
engine: "pdf-text",
},
},
],
user: "Parker.OKeefe",
});
console.log(result);
}
run();
This SDK supports the following security scheme globally:
Name | Type | Scheme | Environment Variable |
---|---|---|---|
apiKey |
http | HTTP Bearer | OPENROUTER_API_KEY |
To authenticate with the API the apiKey
parameter must be set when initializing the SDK client instance. For example:
import { OpenRouter } from "@openrouter/sdk";
const openRouter = new OpenRouter({
apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
});
async function run() {
const result = await openRouter.beta.responses.send({
input: [
{
type: "message",
role: "user",
content: "Hello, how are you?",
},
],
instructions: "<value>",
metadata: {
"user_id": "123",
"session_id": "abc-def-ghi",
},
tools: [
{
type: "function",
name: "get_current_weather",
description: "Get the current weather in a given location",
strict: true,
parameters: {
"type": "object",
"properties": {
"location": {
"type": "string",
},
},
},
},
],
toolChoice: "auto",
parallelToolCalls: false,
model: "anthropic/claude-4.5-sonnet-20250929",
models: [
"<value 1>",
],
text: {
format: {
type: "text",
},
verbosity: "medium",
},
reasoning: {
effort: "medium",
summary: "auto",
maxTokens: 6415.05,
enabled: true,
},
maxOutputTokens: 5270.85,
temperature: 0.7,
topP: 0.9,
topK: 5913.88,
promptCacheKey: "<value>",
previousResponseId: "<id>",
prompt: {
id: "prompt-abc123",
variables: {
"name": {
type: "input_text",
text: "John",
},
},
},
include: [
"message.input_image.image_url",
],
background: false,
safetyIdentifier: "<value>",
store: false,
serviceTier: "auto",
truncation: "auto",
stream: false,
provider: {
allowFallbacks: false,
requireParameters: true,
dataCollection: "deny",
zdr: true,
order: [
"Moonshot AI",
],
only: [
"<value>",
],
ignore: [
"<value>",
],
quantizations: [
"bf16",
],
sort: "price",
maxPrice: {
prompt: "<value>",
completion: 4351.98,
image: "https://loremflickr.com/916/1698?lock=7420998995259402",
audio: "<value>",
request: "<value>",
},
experimental: {},
},
plugins: [
{
id: "file-parser",
maxFiles: 3555.38,
pdf: {
engine: "pdf-text",
},
},
],
user: "Parker.OKeefe",
});
console.log(result);
}
run();
Some operations in this SDK require the security scheme to be specified at the request level. For example:
import { OpenRouter } from "@openrouter/sdk";
const openRouter = new OpenRouter();
async function run() {
const result = await openRouter.credits.createCoinbaseCharge({
bearer: process.env["OPENROUTER_BEARER"] ?? "",
}, {
amount: 711.16,
sender: "<value>",
chainId: 1,
});
console.log(result);
}
run();
Available methods
- getUserActivity - Get user activity grouped by endpoint
- list - List API keys
- create - Create a new API key
- update - Update an API key
- delete - Delete an API key
- get - Get a single API key
- getCurrentKeyMetadata - Get current API key
- send - Create a response
- send - Create a chat completion
- generate - Create a completion
- getCredits - Get remaining credits
- createCoinbaseCharge - Create a Coinbase charge for crypto payment
- list - List all endpoints for a model
- listZdrEndpoints - Preview the impact of ZDR on the available endpoints
- getGeneration - Get request & usage metadata for a generation
- count - Get total count of available models
- list - List all models and their properties
- listForUser - List models filtered by user provider preferences
- getParameters - Get a model's supported parameters and data about which are most popular
- list - List all providers
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
Available standalone functions
analyticsGetUserActivity
- Get user activity grouped by endpointapiKeysCreate
- Create a new API keyapiKeysDelete
- Delete an API keyapiKeysGet
- Get a single API keyapiKeysGetCurrentKeyMetadata
- Get current API keyapiKeysList
- List API keysapiKeysUpdate
- Update an API keybetaResponsesSend
- Create a responsechatSend
- Create a chat completioncompletionsGenerate
- Create a completioncreditsCreateCoinbaseCharge
- Create a Coinbase charge for crypto paymentcreditsGetCredits
- Get remaining creditsendpointsList
- List all endpoints for a modelendpointsListZdrEndpoints
- Preview the impact of ZDR on the available endpointsgenerationsGetGeneration
- Get request & usage metadata for a generationmodelsCount
- Get total count of available modelsmodelsList
- List all models and their propertiesmodelsListForUser
- List models filtered by user provider preferencesparametersGetParameters
- Get a model's supported parameters and data about which are most popularprovidersList
- List all providers
React hooks built on TanStack Query are included in this SDK. These hooks and the utility functions provided alongside them can be used to build rich applications that pull data from the API using one of the most popular asynchronous state management library.
To learn about this feature and how to get started, check REACT_QUERY.md.
Warning
This feature is currently in preview and is subject to breaking changes within the current major version of the SDK as we gather user feedback on it.
Available React hooks
useAnalyticsGetUserActivity
- Get user activity grouped by endpointuseApiKeysCreateMutation
- Create a new API keyuseApiKeysDeleteMutation
- Delete an API keyuseApiKeysGet
- Get a single API keyuseApiKeysGetCurrentKeyMetadata
- Get current API keyuseApiKeysList
- List API keysuseApiKeysUpdateMutation
- Update an API keyuseBetaResponsesSendMutation
- Create a responseuseChatSendMutation
- Create a chat completionuseCompletionsGenerateMutation
- Create a completionuseCreditsCreateCoinbaseChargeMutation
- Create a Coinbase charge for crypto paymentuseCreditsGetCredits
- Get remaining creditsuseEndpointsList
- List all endpoints for a modeluseEndpointsListZdrEndpoints
- Preview the impact of ZDR on the available endpointsuseGenerationsGetGeneration
- Get request & usage metadata for a generationuseModelsCount
- Get total count of available modelsuseModelsList
- List all models and their propertiesuseModelsListForUser
- List models filtered by user provider preferencesuseParametersGetParameters
- Get a model's supported parameters and data about which are most popularuseProvidersList
- List all providers
Server-sent events are used to stream content from certain
operations. These operations will expose the stream as an async iterable that
can be consumed using a for await...of
loop. The loop will
terminate when the server no longer has any events to send and closes the
underlying connection.
import { OpenRouter } from "@openrouter/sdk";
const openRouter = new OpenRouter({
apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
});
async function run() {
const result = await openRouter.beta.responses.send({
input: [
{
type: "message",
role: "user",
content: "Hello, how are you?",
},
],
instructions: "<value>",
metadata: {
"user_id": "123",
"session_id": "abc-def-ghi",
},
tools: [
{
type: "function",
name: "get_current_weather",
description: "Get the current weather in a given location",
strict: true,
parameters: {
"type": "object",
"properties": {
"location": {
"type": "string",
},
},
},
},
],
toolChoice: "auto",
parallelToolCalls: false,
model: "anthropic/claude-4.5-sonnet-20250929",
models: [
"<value 1>",
],
text: {
format: {
type: "text",
},
verbosity: "medium",
},
reasoning: {
effort: "medium",
summary: "auto",
maxTokens: 6415.05,
enabled: true,
},
maxOutputTokens: 5270.85,
temperature: 0.7,
topP: 0.9,
topK: 5913.88,
promptCacheKey: "<value>",
previousResponseId: "<id>",
prompt: {
id: "prompt-abc123",
variables: {
"name": {
type: "input_text",
text: "John",
},
},
},
include: [
"message.input_image.image_url",
],
background: false,
safetyIdentifier: "<value>",
store: false,
serviceTier: "auto",
truncation: "auto",
stream: false,
provider: {
allowFallbacks: false,
requireParameters: true,
dataCollection: "deny",
zdr: true,
order: [
"Moonshot AI",
],
only: [
"<value>",
],
ignore: [
"<value>",
],
quantizations: [
"bf16",
],
sort: "price",
maxPrice: {
prompt: "<value>",
completion: 4351.98,
image: "https://loremflickr.com/916/1698?lock=7420998995259402",
audio: "<value>",
request: "<value>",
},
experimental: {},
},
plugins: [
{
id: "file-parser",
maxFiles: 3555.38,
pdf: {
engine: "pdf-text",
},
},
],
user: "Parker.OKeefe",
});
console.log(result);
}
run();
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { OpenRouter } from "@openrouter/sdk";
const openRouter = new OpenRouter({
apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
});
async function run() {
const result = await openRouter.beta.responses.send({
input: [
{
type: "message",
role: "user",
content: "Hello, how are you?",
},
],
instructions: "<value>",
metadata: {
"user_id": "123",
"session_id": "abc-def-ghi",
},
tools: [
{
type: "function",
name: "get_current_weather",
description: "Get the current weather in a given location",
strict: true,
parameters: {
"type": "object",
"properties": {
"location": {
"type": "string",
},
},
},
},
],
toolChoice: "auto",
parallelToolCalls: false,
model: "anthropic/claude-4.5-sonnet-20250929",
models: [
"<value 1>",
],
text: {
format: {
type: "text",
},
verbosity: "medium",
},
reasoning: {
effort: "medium",
summary: "auto",
maxTokens: 6415.05,
enabled: true,
},
maxOutputTokens: 5270.85,
temperature: 0.7,
topP: 0.9,
topK: 5913.88,
promptCacheKey: "<value>",
previousResponseId: "<id>",
prompt: {
id: "prompt-abc123",
variables: {
"name": {
type: "input_text",
text: "John",
},
},
},
include: [
"message.input_image.image_url",
],
background: false,
safetyIdentifier: "<value>",
store: false,
serviceTier: "auto",
truncation: "auto",
stream: false,
provider: {
allowFallbacks: false,
requireParameters: true,
dataCollection: "deny",
zdr: true,
order: [
"Moonshot AI",
],
only: [
"<value>",
],
ignore: [
"<value>",
],
quantizations: [
"bf16",
],
sort: "price",
maxPrice: {
prompt: "<value>",
completion: 4351.98,
image: "https://loremflickr.com/916/1698?lock=7420998995259402",
audio: "<value>",
request: "<value>",
},
experimental: {},
},
plugins: [
{
id: "file-parser",
maxFiles: 3555.38,
pdf: {
engine: "pdf-text",
},
},
],
user: "Parker.OKeefe",
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { OpenRouter } from "@openrouter/sdk";
const openRouter = new OpenRouter({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
});
async function run() {
const result = await openRouter.beta.responses.send({
input: [
{
type: "message",
role: "user",
content: "Hello, how are you?",
},
],
instructions: "<value>",
metadata: {
"user_id": "123",
"session_id": "abc-def-ghi",
},
tools: [
{
type: "function",
name: "get_current_weather",
description: "Get the current weather in a given location",
strict: true,
parameters: {
"type": "object",
"properties": {
"location": {
"type": "string",
},
},
},
},
],
toolChoice: "auto",
parallelToolCalls: false,
model: "anthropic/claude-4.5-sonnet-20250929",
models: [
"<value 1>",
],
text: {
format: {
type: "text",
},
verbosity: "medium",
},
reasoning: {
effort: "medium",
summary: "auto",
maxTokens: 6415.05,
enabled: true,
},
maxOutputTokens: 5270.85,
temperature: 0.7,
topP: 0.9,
topK: 5913.88,
promptCacheKey: "<value>",
previousResponseId: "<id>",
prompt: {
id: "prompt-abc123",
variables: {
"name": {
type: "input_text",
text: "John",
},
},
},
include: [
"message.input_image.image_url",
],
background: false,
safetyIdentifier: "<value>",
store: false,
serviceTier: "auto",
truncation: "auto",
stream: false,
provider: {
allowFallbacks: false,
requireParameters: true,
dataCollection: "deny",
zdr: true,
order: [
"Moonshot AI",
],
only: [
"<value>",
],
ignore: [
"<value>",
],
quantizations: [
"bf16",
],
sort: "price",
maxPrice: {
prompt: "<value>",
completion: 4351.98,
image: "https://loremflickr.com/916/1698?lock=7420998995259402",
audio: "<value>",
request: "<value>",
},
experimental: {},
},
plugins: [
{
id: "file-parser",
maxFiles: 3555.38,
pdf: {
engine: "pdf-text",
},
},
],
user: "Parker.OKeefe",
});
console.log(result);
}
run();
OpenRouterError
is the base class for all HTTP error responses. It has the following properties:
Property | Type | Description |
---|---|---|
error.message |
string |
Error message |
error.statusCode |
number |
HTTP response status code eg 404 |
error.headers |
Headers |
HTTP response headers |
error.body |
string |
HTTP body. Can be empty string if no body is returned. |
error.rawResponse |
Response |
Raw HTTP response |
error.data$ |
Optional. Some errors may contain structured data. See Error Classes. |
import { OpenRouter } from "@openrouter/sdk";
import * as errors from "@openrouter/sdk/models/errors";
const openRouter = new OpenRouter({
apiKey: process.env["OPENROUTER_API_KEY"] ?? "",
});
async function run() {
try {
const result = await openRouter.analytics.getUserActivity({
date: "2025-08-24",
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.OpenRouterError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.ErrorResponse) {
console.log(error.data$.error); // models.ErrorResponseError
console.log(error.data$.userId); // string
}
}
}
}
run();
Primary error:
OpenRouterError
: The base class for HTTP error responses.
Less common errors (9)
Network errors:
ConnectionError
: HTTP client was unable to make a request to a server.RequestTimeoutError
: HTTP request timed out due to an AbortSignal signal.RequestAbortedError
: HTTP request was aborted by the client.InvalidRequestError
: Any input used to create a request is invalid.UnexpectedClientError
: Unrecognised or unexpected error.
Inherit from OpenRouterError
:
ErrorResponse
: Error response. Applicable to 12 of 20 methods.*ChatError
: Bad request - invalid parameters. Applicable to 2 of 20 methods.*InternalServerError
: Internal Server Error. Status code500
. Applicable to 1 of 20 methods.*ResponseValidationError
: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValue
for the raw value anderror.pretty()
for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console
's interface as an SDK option.
Warning
Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { OpenRouter } from "@openrouter/sdk";
const sdk = new OpenRouter({ debugLogger: console });
You can also enable a default debug logger by setting an environment variable OPENROUTER_DEBUG
to true.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.