Skip to content

OpenRouterTeam/typescript-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

98 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenRouter SDK (Beta)

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

Table of Contents

SDK Installation

The SDK can be installed with either npm, pnpm, bun or yarn package managers.

NPM

npm add @openrouter/sdk
# Install optional peer dependencies if you plan to use React hooks
npm add @tanstack/react-query react react-dom

PNPM

pnpm add @openrouter/sdk
# Install optional peer dependencies if you plan to use React hooks
pnpm add @tanstack/react-query react react-dom

Bun

bun add @openrouter/sdk
# Install optional peer dependencies if you plan to use React hooks
bun add @tanstack/react-query react react-dom

Yarn

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.

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

SDK Example Usage

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();

Authentication

Per-Client Security Schemes

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();

Per-Operation Security Schemes

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 Resources and Operations

Available methods
  • send - Create a response
  • send - Create a chat completion
  • list - List all endpoints for a model
  • listZdrEndpoints - Preview the impact of ZDR on the available endpoints
  • 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

Standalone functions

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

React hooks with TanStack Query

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

Server-sent event streaming

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();

Retries

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();

Error Handling

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.

Example

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();

Error Classes

Primary error:

Less common errors (9)

Network errors:

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 code 500. Applicable to 1 of 20 methods.*
  • ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. See error.rawValue for the raw value and error.pretty() for a nicely formatted multi-line string.

* Check the method documentation to see if the error is applicable.

Debugging

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.

Development

Maturity

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.

Contributions

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.

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Packages

No packages published

Languages