Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Theme
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Create API Key
Add Docs
OpenRouter SDK
https://github.com/openrouterteam/typescript-sdk
Admin
The OpenRouter SDK is a TypeScript toolkit for building AI-powered features and solutions in any JS
...
Tokens:
139,032
Snippets:
860
Trust Score:
8.8
Update:
4 days ago
Context
Skills
Chat
Benchmark
94
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# OpenRouter TypeScript SDK (`@openrouter/sdk`) The OpenRouter TypeScript SDK is a type-safe toolkit for building AI-powered applications with access to 300+ language models through a single, unified API. Auto-generated from OpenRouter's OpenAPI specification and kept in sync with every API change, it provides full TypeScript types for all parameters and responses, catching invalid configurations at compile time rather than in production. The SDK supports all major JavaScript runtimes (Node.js, Deno, Bun, browsers, and edge functions) and is distributed as an ESM-only package. The SDK exposes the following resource namespaces: `chat`, `embeddings`, `models`, `generations`, `analytics`, `apiKeys`, `credits`, `guardrails`, `endpoints`, `providers`, `oAuth`, and `beta.responses`. Every method is also available as a tree-shakeable standalone function via `@openrouter/sdk/funcs/*`, making it suitable for bundle-size-sensitive browser and serverless environments. Standalone functions return `Result<Value, Error>` types instead of throwing, enabling explicit, type-safe error handling. --- ## Installation ```bash npm add @openrouter/sdk # or: pnpm add @openrouter/sdk | bun add @openrouter/sdk | yarn add @openrouter/sdk ``` --- ## Client Initialization Initialize the `OpenRouter` client with your API key and optional app metadata headers. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", httpReferer: "https://myapp.com", // optional: your site URL appTitle: "My AI App", // optional: app name shown on openrouter.ai appCategories: "productivity", // optional: app category debugLogger: process.env.DEBUG ? console : undefined, // enable debug logs locally only }); ``` --- ## `chat.send` — Create a Chat Completion Sends a message to any supported model and returns a completion response. Supports both streaming and non-streaming modes, system prompts, provider routing preferences, temperature, max tokens, and more. ```typescript import { OpenRouter } from "@openrouter/sdk"; import * as errors from "@openrouter/sdk/models/errors"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", httpReferer: "https://myapp.com", appTitle: "My AI App", }); // Non-streaming: single response object async function chatNonStreaming() { try { const result = await openRouter.chat.send({ chatRequest: { model: "openai/gpt-4", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "What is the capital of France?" }, ], temperature: 0.7, maxTokens: 150, }, }); console.log(result.choices[0].message.content); // => "The capital of France is Paris." } catch (err) { if (err instanceof errors.UnauthorizedResponseError) { console.error("Invalid API key"); } else if (err instanceof errors.PaymentRequiredResponseError) { console.error("Insufficient credits"); } else if (err instanceof errors.TooManyRequestsResponseError) { console.error("Rate limited – back off and retry"); } else { throw err; } } } // Streaming: async iterable of delta chunks async function chatStreaming() { const stream = await openRouter.chat.send({ chatRequest: { model: "openai/gpt-4", messages: [{ role: "user", content: "Write a short haiku about the ocean." }], stream: true, provider: { sort: "price", zdr: true }, // prefer cheapest provider with zero-data-retention }, }); for await (const chunk of stream) { const delta = chunk.choices[0]?.delta?.content; if (delta) process.stdout.write(delta); } // => "Waves crash on shore...\nSalt mist fills the morning air...\nSea calls me home now." } chatNonStreaming(); chatStreaming(); ``` --- ## `chat.send` standalone function — Tree-shakeable Chat Use `chatSend` from the standalone functions entry-point for optimal bundle size in browser/edge environments. ```typescript import { OpenRouterCore } from "@openrouter/sdk/core.js"; import { chatSend } from "@openrouter/sdk/funcs/chatSend.js"; const openRouter = new OpenRouterCore({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", httpReferer: "https://myapp.com", appTitle: "My AI App", }); async function run() { const res = await chatSend(openRouter, { chatRequest: { model: "openai/gpt-4", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "What is the capital of France?" }, ], maxTokens: 150, temperature: 0.7, }, }); if (res.ok) { console.log(res.value.choices[0].message.content); // => "The capital of France is Paris." } else { // res.error is fully typed — no unknown catch needed console.error("Chat failed:", res.error.message); } } run(); ``` --- ## `beta.responses.send` — OpenAI Responses API Format Creates a streaming or non-streaming response using the OpenResponses API format (`/responses` endpoint), an alternative to the chat completions format. ```typescript 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({ xOpenRouterExperimentalMetadata: "enabled", responsesRequest: { model: "openai/gpt-4o", input: "Tell me a short joke.", }, }); console.log(result); } run(); ``` --- ## `embeddings.generate` — Generate Text Embeddings Submits text to an embeddings model and returns a vector representation. Accepts a string or array of strings. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.embeddings.generate({ requestBody: { input: "The quick brown fox jumps over the lazy dog", model: "openai/text-embedding-3-small", }, }); console.log(result.data[0].embedding.slice(0, 5)); // => [-0.0023064255, -0.009327292, 0.015797101, -0.007895398, 0.05773878] console.log("Embedding dimensions:", result.data[0].embedding.length); // => Embedding dimensions: 1536 } run(); ``` --- ## `embeddings.listModels` — List Available Embedding Models Returns a list of all embedding models available on OpenRouter along with their properties (context length, pricing, etc.). ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.embeddings.listModels(); for (const model of result.data ?? []) { console.log(`${model.id}: context=${model.contextLength}, prompt=$${model.pricing?.prompt}/token`); } // => openai/text-embedding-3-small: context=8191, prompt=$0.00000002/token // => openai/text-embedding-3-large: context=8191, prompt=$0.00000013/token } run(); ``` --- ## `models.list` — List All Available Models Returns all models available on OpenRouter including their architecture, context length, pricing, and provider information. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.models.list(); for (const model of result.data ?? []) { console.log(`${model.id}: context=${model.contextLength}`); } // => openai/gpt-4: context=8192 // => anthropic/claude-3-5-sonnet: context=200000 // => google/gemini-2.0-flash-001: context=1048576 // => (300+ more models) } run(); ``` --- ## `models.count` — Get Total Model Count Returns the total count of available models without fetching full model data. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.models.count(); console.log("Total models available:", result.count); // => Total models available: 342 } run(); ``` --- ## `models.listForUser` — List Models Filtered by User Preferences Returns models filtered by the authenticated user's provider preferences, privacy settings, and assigned guardrails. Requires a bearer token. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ httpReferer: "https://myapp.com", appTitle: "My AI App", }); async function run() { const result = await openRouter.models.listForUser({ bearer: process.env["OPENROUTER_BEARER"] ?? "", }); console.log("Models available to this user:", result.data?.length); for (const model of result.data ?? []) { console.log(model.id); } } run(); ``` --- ## `generations.getGeneration` — Get Generation Metadata Retrieves request and usage metadata for a specific generation (token counts, cost, model, latency, etc.) using its generation ID. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.generations.getGeneration({ id: "gen-1234567890abcdef", }); console.log("Model used:", result.data?.model); console.log("Prompt tokens:", result.data?.usage?.promptTokens); console.log("Completion tokens:", result.data?.usage?.completionTokens); console.log("Total cost (USD):", result.data?.totalCost); // => Model used: openai/gpt-4 // => Prompt tokens: 42 // => Completion tokens: 87 // => Total cost (USD): 0.00039 } run(); ``` --- ## `generations.listGenerationContent` — Get Stored Prompt & Completion Retrieves the stored prompt and completion content for a generation. Requires content logging to be enabled in your account settings. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.generations.listGenerationContent({ id: "gen-1234567890abcdef", }); console.log("Prompt:", result.data?.prompt); console.log("Completion:", result.data?.completion); } run(); ``` --- ## `analytics.getUserActivity` — Get User Activity Data Returns user activity data grouped by endpoint for the last 30 completed UTC days. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", // must be a management key }); async function run() { const result = await openRouter.analytics.getUserActivity(); for (const item of result.data ?? []) { console.log(`${item.date}: ${item.requestCount} requests, $${item.totalCost} spent`); } // => 2026-05-01: 1240 requests, $2.34 spent // => 2026-05-02: 980 requests, $1.87 spent } run(); ``` --- ## `credits.getCredits` — Get Credit Balance Returns the total credits purchased and total credits used for the authenticated account. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.credits.getCredits(); console.log("Total purchased (USD):", result.data?.totalGranted); console.log("Total used (USD):", result.data?.totalUsed); console.log("Remaining (USD):", (result.data?.totalGranted ?? 0) - (result.data?.totalUsed ?? 0)); // => Total purchased (USD): 50 // => Total used (USD): 12.43 // => Remaining (USD): 37.57 } run(); ``` --- ## `apiKeys.getCurrentKeyMetadata` — Inspect the Current API Key Returns metadata about the API key being used in the current request (name, usage limits, remaining budget, etc.). ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.apiKeys.getCurrentKeyMetadata(); console.log("Key name:", result.data?.name); console.log("Usage limit (USD):", result.data?.limit); console.log("Usage so far (USD):", result.data?.usage); // => Key name: Production Key // => Usage limit (USD): 100 // => Usage so far (USD): 23.41 } run(); ``` --- ## `apiKeys.list` — List All API Keys Lists all API keys for the authenticated user. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.apiKeys.list(); for (const key of result.data ?? []) { console.log(`[${key.hash.slice(0, 8)}...] ${key.name} — disabled: ${key.disabled}`); } // => [f01d5260...] Production Key — disabled: false // => [a3c89f12...] Dev Key — disabled: false } run(); ``` --- ## `apiKeys.create` — Create a New API Key Creates a new API key with optional name, spending limit, limit reset interval, and expiry date. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.apiKeys.create({ requestBody: { name: "My New API Key", limit: 50, // $50 USD spending cap limitReset: "monthly", // reset usage counter monthly expiresAt: new Date("2027-12-31T23:59:59Z"), includeByokInLimit: true, }, }); console.log("Created key hash:", result.data?.hash); console.log("Key value (store securely):", result.data?.key); } run(); ``` --- ## `apiKeys.delete` — Delete an API Key Permanently deletes an API key by its hash. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.apiKeys.delete({ hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", }); console.log("Deleted:", result.data?.deleted); // => Deleted: true } run(); ``` --- ## `apiKeys.get` — Get a Single API Key Retrieves a single API key by its hash including usage, limits, and status. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.apiKeys.get({ hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", }); console.log("Name:", result.data?.name); console.log("Limit:", result.data?.limit); console.log("Usage:", result.data?.usage); console.log("Disabled:", result.data?.disabled); } run(); ``` --- ## `apiKeys.update` — Update an API Key Updates an existing API key's name, spending limit, reset interval, or disabled status. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.apiKeys.update({ hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", requestBody: { name: "Updated API Key Name", limit: 75, limitReset: "daily", disabled: false, includeByokInLimit: true, }, }); console.log("Updated key name:", result.data?.name); } run(); ``` --- ## `guardrails.list` — List Guardrails (Paginated) Lists all guardrails for the authenticated user. Supports pagination via `for await`. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.list(); for await (const page of result) { for (const guardrail of page.data ?? []) { console.log(`[${guardrail.id}] ${guardrail.name}: $${guardrail.limitUsd} limit`); } } // => [550e8400-...] My Guardrail: $50 limit } run(); ``` --- ## `guardrails.create` — Create a Guardrail Creates a new guardrail with spending limits, allowed/ignored providers/models, and a reset interval. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.create({ createGuardrailRequest: { name: "Production Guardrail", description: "Limits production keys to OpenAI and Anthropic only", allowedProviders: ["openai", "anthropic"], allowedModels: null, ignoredModels: null, ignoredProviders: null, limitUsd: 50, resetInterval: "monthly", enforceZdr: false, }, }); console.log("Created guardrail ID:", result.data?.id); console.log("Name:", result.data?.name); } run(); ``` --- ## `guardrails.get` — Get a Guardrail Retrieves a single guardrail by its UUID. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.get({ id: "550e8400-e29b-41d4-a716-446655440000", }); console.log("Guardrail:", result.data?.name); console.log("Spend limit:", result.data?.limitUsd); console.log("Allowed providers:", result.data?.allowedProviders); } run(); ``` --- ## `guardrails.update` — Update a Guardrail Updates an existing guardrail's name, description, spending limit, or reset interval. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.update({ id: "550e8400-e29b-41d4-a716-446655440000", updateGuardrailRequest: { name: "Updated Guardrail Name", description: "Updated description", limitUsd: 75, resetInterval: "weekly", }, }); console.log("Updated:", result.data?.name); } run(); ``` --- ## `guardrails.delete` — Delete a Guardrail Permanently deletes a guardrail by its UUID. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.delete({ id: "550e8400-e29b-41d4-a716-446655440000", }); console.log("Deleted:", result.data?.deleted); } run(); ``` --- ## `guardrails.bulkAssignKeys` — Assign API Keys to a Guardrail Assigns multiple API keys to a guardrail by their hashes, applying the guardrail's constraints to all assigned keys. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.bulkAssignKeys({ id: "550e8400-e29b-41d4-a716-446655440000", bulkAssignKeysRequest: { keyHashes: [ "c56454edb818d6b14bc0d61c46025f1450b0f4012d12304ab40aacb519fcbc93", "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", ], }, }); console.log("Assigned count:", result.data?.assignedCount); } run(); ``` --- ## `guardrails.bulkUnassignKeys` — Unassign API Keys from a Guardrail Removes multiple API keys from a guardrail by their hashes. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.bulkUnassignKeys({ id: "550e8400-e29b-41d4-a716-446655440000", bulkUnassignKeysRequest: { keyHashes: [ "c56454edb818d6b14bc0d61c46025f1450b0f4012d12304ab40aacb519fcbc93", ], }, }); console.log("Unassigned count:", result.data?.unassignedCount); } run(); ``` --- ## `guardrails.bulkAssignMembers` — Assign Members to a Guardrail Assigns multiple organization members to a guardrail by their user IDs. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.bulkAssignMembers({ id: "550e8400-e29b-41d4-a716-446655440000", bulkAssignMembersRequest: { memberUserIds: ["user_abc123", "user_def456"], }, }); console.log("Assigned members:", result.data?.assignedCount); } run(); ``` --- ## `guardrails.bulkUnassignMembers` — Unassign Members from a Guardrail Removes multiple organization members from a guardrail. Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.bulkUnassignMembers({ id: "550e8400-e29b-41d4-a716-446655440000", bulkUnassignMembersRequest: { memberUserIds: ["user_abc123"], }, }); console.log("Unassigned:", result.data?.unassignedCount); } run(); ``` --- ## `guardrails.listGuardrailKeyAssignments` — List Key Assignments for a Guardrail Lists all API keys currently assigned to a specific guardrail (paginated). Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.listGuardrailKeyAssignments({ id: "550e8400-e29b-41d4-a716-446655440000", }); for await (const page of result) { for (const assignment of page.data ?? []) { console.log("Assigned key hash:", assignment.keyHash); } } } run(); ``` --- ## `guardrails.listGuardrailMemberAssignments` — List Member Assignments for a Guardrail Lists all organization members assigned to a specific guardrail (paginated). Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.listGuardrailMemberAssignments({ id: "550e8400-e29b-41d4-a716-446655440000", }); for await (const page of result) { for (const assignment of page.data ?? []) { console.log("Member user ID:", assignment.userId); } } } run(); ``` --- ## `guardrails.listKeyAssignments` — List All Key Assignments Lists all API key-to-guardrail assignments for the authenticated user (paginated). Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.listKeyAssignments(); for await (const page of result) { for (const assignment of page.data ?? []) { console.log(`Key ${assignment.keyHash} → Guardrail ${assignment.guardrailId}`); } } } run(); ``` --- ## `guardrails.listMemberAssignments` — List All Member Assignments Lists all organization member-to-guardrail assignments for the authenticated user (paginated). Requires a management API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.listMemberAssignments(); for await (const page of result) { for (const assignment of page.data ?? []) { console.log(`Member ${assignment.userId} → Guardrail ${assignment.guardrailId}`); } } } run(); ``` --- ## `endpoints.list` — List Endpoints for a Model Returns all available provider endpoints for a given model (identified by author and slug), including quantization, pricing, and status. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.endpoints.list({ author: "openai", slug: "gpt-4", }); for (const endpoint of result.data ?? []) { console.log(`Provider: ${endpoint.name}, status: ${endpoint.status}`); } // => Provider: openai, status: active } run(); ``` --- ## `endpoints.listZdrEndpoints` — Preview ZDR Impact on Endpoints Returns a preview of which provider endpoints remain available after applying Zero Data Retention (ZDR) filtering. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.endpoints.listZdrEndpoints(); console.log("ZDR-compatible endpoints:", result); } run(); ``` --- ## `providers.list` — List All Providers Returns all AI providers available through OpenRouter with their names, status, and supported features. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.providers.list(); for (const provider of result.data ?? []) { console.log(provider.name); } // => openai // => anthropic // => google // => deepseek // => (many more) } run(); ``` --- ## `oAuth.createAuthCode` — Create PKCE Authorization Code Creates an authorization code for the PKCE OAuth flow to generate user-controlled API keys. Used when integrating OpenRouter sign-in into your app. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.oAuth.createAuthCode({ requestBody: { callbackUrl: "https://myapp.com/auth/callback", codeChallenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", codeChallengeMethod: "S256", limit: 100, // $100 USD spending cap for the user key }, }); console.log("Authorization URL:", result.data?.authUrl); // Redirect user to result.data.authUrl to authorize } run(); ``` --- ## `oAuth.exchangeAuthCodeForAPIKey` — Exchange Auth Code for API Key Exchanges the authorization code received in the PKCE callback for a user-controlled OpenRouter API key. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { // Called after the user is redirected back to your callbackUrl const result = await openRouter.oAuth.exchangeAuthCodeForAPIKey({ requestBody: { code: "auth_code_abc123def456", // from the ?code= query param in callback codeVerifier: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", // original PKCE verifier codeChallengeMethod: "S256", }, }); console.log("User API key:", result.data?.apiKey); // Store this key securely and use it on behalf of the user } run(); ``` --- ## Retry Configuration All SDK methods accept a `retries` option with exponential backoff configuration for automatic retries on transient errors. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.chat.send( { chatRequest: { model: "openai/gpt-4", messages: [{ role: "user", content: "Hello!" }], }, }, { retries: { strategy: "backoff", retryConnectionErrors: true, backoff: { initialInterval: 500, // start with 500ms wait maxInterval: 60000, // cap at 60s between retries exponent: 1.5, // multiply wait by 1.5x each attempt maxElapsedTime: 300000, // give up after 5 minutes total }, }, } ); console.log(result.choices[0].message.content); } run(); ``` --- ## Pagination Endpoints that return paginated data (such as `guardrails.list`, `guardrails.listGuardrailKeyAssignments`, and `guardrails.listKeyAssignments`) return async iterables that can be consumed with `for await...of`. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.guardrails.list(); // Automatically fetches additional pages as needed for await (const page of result) { for (const guardrail of page.data ?? []) { console.log(guardrail.name); } } } run(); ``` --- ## Summary The OpenRouter TypeScript SDK is primarily used for two categories of tasks: **AI inference** and **account/infrastructure management**. For AI inference, `chat.send` is the core method — it routes requests to 300+ models from a single API call with full type safety, supports both streaming and non-streaming modes, and allows per-request provider preferences (price sorting, ZDR enforcement, provider allowlists). The `embeddings.generate` method provides vector embedding generation using any supported embedding model. The `beta.responses.send` method supports the newer OpenAI Responses API format as an alternative completion interface. For account and infrastructure management, the SDK provides comprehensive coverage of the OpenRouter management APIs: `apiKeys.*` methods handle key creation, rotation, and budget enforcement programmatically; `guardrails.*` methods allow organizations to create spending limits and provider restrictions and attach them in bulk to keys or members; `credits.getCredits` and `analytics.getUserActivity` support cost monitoring and usage dashboards; and `oAuth.*` methods implement the PKCE flow for building apps where end users log in with their own OpenRouter accounts. The standalone function API (`OpenRouterCore` + `@openrouter/sdk/funcs/*`) is the recommended integration pattern for frontend or edge deployments where bundle size matters, while the class-based API is ergonomically preferred for Node.js backends and server-side rendering frameworks.