### Copy environment file for local development Source: https://github.com/openrouterteam/typescript-sdk/blob/main/README.md Copies the example environment file to `.env` for local development setup. ```bash cp .env.example .env ``` -------------------------------- ### Install Dependencies Source: https://github.com/openrouterteam/typescript-sdk/blob/main/tests/e2e/README.md Run this command to install project dependencies. ```bash npm install ``` -------------------------------- ### Quick Start: Send Chat Message and Log Response (TypeScript) Source: https://github.com/openrouterteam/typescript-sdk/blob/main/OVERVIEW.md A concise example showing the essential steps to initialize the client, send a simple chat message, and log the content of the response. ```typescript import OpenRouter from '@openrouter/sdk'; const client = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY }); const response = await client.chat.send({ model: "minimax/minimax-m2", messages: [ { role: "user", content: "Hello!" } ] }); console.log(response.choices[0].message.content); ``` -------------------------------- ### Install OpenRouter SDK with Bun Source: https://github.com/openrouterteam/typescript-sdk/blob/main/README.md Install the OpenRouter SDK using the bun package manager. ```bash bun add @openrouter/sdk ``` -------------------------------- ### Install OpenRouter TypeScript SDK Source: https://context7.com/openrouterteam/typescript-sdk/llms.txt Install the SDK using npm, pnpm, bun, or yarn. ```bash npm add @openrouter/sdk # or: pnpm add @openrouter/sdk | bun add @openrouter/sdk | yarn add @openrouter/sdk ``` -------------------------------- ### Build and Run TypeScript Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/examples/README.md Execute this command to build the project and run a TypeScript example file using tsx. ```bash npm run build && npx tsx example.ts ``` -------------------------------- ### Install OpenRouter SDK with Yarn Source: https://github.com/openrouterteam/typescript-sdk/blob/main/README.md Install the OpenRouter SDK using the yarn package manager. ```bash yarn add @openrouter/sdk ``` -------------------------------- ### CreateKeysData Model Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createkeysdata.md Example of how to instantiate the CreateKeysData model with various properties. Ensure all required fields are populated. ```typescript import { CreateKeysData } from "@openrouter/sdk/models/operations"; let value: CreateKeysData = { byokUsage: 17.38, byokUsageDaily: 17.38, byokUsageMonthly: 17.38, byokUsageWeekly: 17.38, createdAt: "2025-08-24T10:30:00Z", creatorUserId: "user_2dHFtVWx2n56w6HkM0000000000", disabled: false, hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", includeByokInLimit: false, label: "sk-or-v1-0e6...1c96", limit: 100, limitRemaining: 74.5, limitReset: "monthly", name: "My Production Key", updatedAt: "2025-08-24T15:45:00Z", usage: 25.5, usageDaily: 25.5, usageMonthly: 25.5, usageWeekly: 25.5, workspaceId: "0df9e665-d932-5740-b2c7-b52af166bc11", }; ``` -------------------------------- ### Install OpenRouter SDK with NPM Source: https://github.com/openrouterteam/typescript-sdk/blob/main/README.md Install the OpenRouter SDK using the npm package manager. ```bash npm add @openrouter/sdk ``` -------------------------------- ### Running Examples with TypeScript Source: https://github.com/openrouterteam/typescript-sdk/blob/main/AGENTS.md Execute example scripts using Node.js with the `ts-node` loader. Ensure your API key is set in the `.env` file before running. ```bash cd examples # Set your API key in .env first node --loader ts-node/esm call-model.example.ts ``` -------------------------------- ### Install OpenRouter SDK with PNPM Source: https://github.com/openrouterteam/typescript-sdk/blob/main/README.md Install the OpenRouter SDK using the pnpm package manager. ```bash pnpm add @openrouter/sdk ``` -------------------------------- ### PublicEndpoint Example Usage Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/publicendpoint.md Demonstrates how to import and use the PublicEndpoint type to define a model endpoint object. Ensure the @openrouter/sdk/models package is installed. ```typescript import { PublicEndpoint } from "@openrouter/sdk/models"; let value: PublicEndpoint = { contextLength: 8192, latencyLast30m: { p50: 0.25, p75: 0.35, p90: 0.48, p99: 0.85, }, maxCompletionTokens: 4096, maxPromptTokens: 8192, modelId: "openai/gpt-4", modelName: "GPT-4", name: "OpenAI: GPT-4", pricing: { completion: "0.00006", prompt: "0.00003", }, providerName: "OpenAI", quantization: "fp16", supportedParameters: [ "temperature", "top_p", "max_tokens", ], supportsImplicitCaching: true, tag: "openai", throughputLast30m: { p50: 45.2, p75: 38.5, p90: 28.3, p99: 15.1, }, uptimeLast1d: 99.8, uptimeLast30m: 99.5, uptimeLast5m: 100, }; ``` -------------------------------- ### CreateGuardrailRequest Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createguardrailrequest.md This example demonstrates the structure of a `CreateGuardrailRequest` object. It includes settings for allowed providers, content filters, usage limits, and naming the guardrail. ```json { "allowed_models": null, "allowed_providers": [ "openai", "anthropic", "deepseek" ], "content_filter_builtins": [ { "action": "block", "slug": "regex-prompt-injection" } ], "content_filters": null, "description": "A guardrail for limiting API usage", "enforce_zdr": false, "ignored_models": null, "ignored_providers": null, "limit_usd": 50, "name": "My New Guardrail", "reset_interval": "monthly" } ``` -------------------------------- ### Instantiate OutputTokensDetails Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/outputtokensdetails.md Example of how to import and instantiate the OutputTokensDetails model with reasoning token counts. ```typescript import { OutputTokensDetails } from "@openrouter/sdk/models"; let value: OutputTokensDetails = { reasoningTokens: 478527, }; ``` -------------------------------- ### Initialize GetUserActivityRequest Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/getuseractivityrequest.md Demonstrates how to import and initialize an empty GetUserActivityRequest object. This is useful for starting a request to get user activity. ```typescript import { GetUserActivityRequest } from "@openrouter/sdk/models/operations"; let value: GetUserActivityRequest = {}; ``` -------------------------------- ### Instantiate ListProvidersData Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listprovidersdata.md Example of how to instantiate the ListProvidersData model with required fields. ```typescript import { ListProvidersData } from "@openrouter/sdk/models/operations"; let value: ListProvidersData = { name: "OpenAI", privacyPolicyUrl: "https://openai.com/privacy", slug: "openai", }; ``` -------------------------------- ### CreateAuthKeysCodeResponse Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createauthkeyscoderesponse.md Example of how to use the CreateAuthKeysCodeResponse model in TypeScript. Ensure the necessary import is included. ```typescript import { CreateAuthKeysCodeResponse } from "@openrouter/sdk/models/operations"; let value: CreateAuthKeysCodeResponse = { data: { appId: 12345, createdAt: "2025-08-24T10:30:00Z", id: "auth_code_xyz789", }, }; ``` -------------------------------- ### Instantiate ListKeyAssignmentsResponse Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listkeyassignmentsresponse.md Example of how to instantiate the ListKeyAssignmentsResponse object with sample data. Ensure correct types for all fields. ```typescript import { ListKeyAssignmentsResponse } from "@openrouter/sdk/models/operations"; let value: ListKeyAssignmentsResponse = { result: { data: [ { assignedBy: "user_abc123", createdAt: "2025-08-24T10:30:00Z", guardrailId: "550e8400-e29b-41d4-a716-446655440001", id: "550e8400-e29b-41d4-a716-446655440000", keyHash: "c56454edb818d6b14bc0d61c46025f1450b0f4012d12304ab40aacb519fcbc93", keyLabel: "prod-key", keyName: "Production Key", }, ], totalCount: 1, }, }; ``` -------------------------------- ### Instantiate ListProvidersResponse Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listprovidersresponse.md Example of how to create an instance of ListProvidersResponse with provider data. Ensure the correct import statement is used. ```typescript import { ListProvidersResponse } from "@openrouter/sdk/models/operations"; let value: ListProvidersResponse = { data: [ { name: "OpenAI", privacyPolicyUrl: "https://openai.com/privacy", slug: "openai", }, ], }; ``` -------------------------------- ### Install OpenRouter SDK (Bash) Source: https://github.com/openrouterteam/typescript-sdk/blob/main/OVERVIEW.md Command to install the OpenRouter SDK using npm. This is the first step to integrating the SDK into a TypeScript project. ```bash npm install @openrouter/sdk ``` -------------------------------- ### Instantiate FilePath Model Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/filepath.md Example of how to create an instance of the FilePath model. Ensure the 'FilePath' type is imported from '@openrouter/sdk/models'. ```typescript import { FilePath } from "@openrouter/sdk/models"; let value: FilePath = { fileId: "file-abc123", index: 0, type: "file_path", }; ``` -------------------------------- ### Instantiate UpdateKeysData Model Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/updatekeysdata.md Example of how to create an instance of the UpdateKeysData model with all its properties. Ensure all required fields are populated. ```typescript import { UpdateKeysData } from "@openrouter/sdk/models/operations"; let value: UpdateKeysData = { byokUsage: 17.38, byokUsageDaily: 17.38, byokUsageMonthly: 17.38, byokUsageWeekly: 17.38, createdAt: "2025-08-24T10:30:00Z", creatorUserId: "user_2dHFtVWx2n56w6HkM0000000000", disabled: false, hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", includeByokInLimit: false, label: "sk-or-v1-0e6...1c96", limit: 100, limitRemaining: 74.5, limitReset: "monthly", name: "My Production Key", updatedAt: "2025-08-24T15:45:00Z", usage: 25.5, usageDaily: 25.5, usageMonthly: 25.5, usageWeekly: 25.5, workspaceId: "0df9e665-d932-5740-b2c7-b52af166bc11", }; ``` -------------------------------- ### Example Usage of Quantization Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/quantization.md Demonstrates how to import and use the Quantization type. Unrecognized values are captured as Unrecognized. ```typescript import { Quantization } from "@openrouter/sdk/models"; let value: Quantization = "fp16"; // Open enum: unrecognized values are captured as Unrecognized ``` -------------------------------- ### Instantiate ReasoningDetailText Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/reasoningdetailtext.md Example of how to import and create an instance of ReasoningDetailText. The 'type' field is required. ```typescript import { ReasoningDetailText } from "@openrouter/sdk/models"; let value: ReasoningDetailText = { type: "reasoning.text", }; ``` -------------------------------- ### Instantiate OpenAIResponsesRefusalContent Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/openairesponsesrefusalcontent.md Example of how to create an instance of OpenAIResponsesRefusalContent. Ensure the 'refusal' and 'type' fields are correctly populated. ```typescript import { OpenAIResponsesRefusalContent } from "@openrouter/sdk/models"; let value: OpenAIResponsesRefusalContent = { refusal: "I'm sorry, I cannot assist with that request", type: "refusal", }; ``` -------------------------------- ### Instantiate ReasoningDetailSummary Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/reasoningdetailsummary.md Example of how to create an instance of the ReasoningDetailSummary model in TypeScript. Ensure the 'summary' and 'type' fields are provided. ```typescript import { ReasoningDetailSummary } from "@openrouter/sdk/models"; let value: ReasoningDetailSummary = { summary: "The model analyzed the problem by first identifying key constraints, then evaluating possible solutions…", type: "reasoning.summary", }; ``` -------------------------------- ### Instantiate GetCurrentKeyResponse Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/getcurrentkeyresponse.md Example of how to create an instance of the GetCurrentKeyResponse model in TypeScript. Ensure the necessary import is included. ```typescript import { GetCurrentKeyResponse } from "@openrouter/sdk/models/operations"; let value: GetCurrentKeyResponse = { data: { byokUsage: 17.38, byokUsageDaily: 17.38, byokUsageMonthly: 17.38, byokUsageWeekly: 17.38, creatorUserId: "user_2dHFtVWx2n56w6HkM0000000000", includeByokInLimit: false, isFreeTier: false, isManagementKey: false, isProvisioningKey: false, label: "sk-or-v1-au7...890", limit: 100, limitRemaining: 74.5, limitReset: "monthly", rateLimit: { interval: "1h", note: "This field is deprecated and safe to ignore.", requests: 1000, }, usage: 25.5, usageDaily: 25.5, usageMonthly: 25.5, usageWeekly: 25.5, }, }; ``` -------------------------------- ### CreateAuthKeysCodeRequest Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createauthkeyscoderequest.md Instantiate CreateAuthKeysCodeRequest with a callback URL. Ensure the callback URL is correctly formatted. ```typescript import { CreateAuthKeysCodeRequest } from "@openrouter/sdk/models/operations"; let value: CreateAuthKeysCodeRequest = { requestBody: { callbackUrl: "https://myapp.com/auth/callback", }, }; ``` -------------------------------- ### Example Usage in TypeScript Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listguardrailsglobals.md Demonstrates how to import and use the ListGuardrailsGlobals model in a TypeScript project. ```typescript import { ListGuardrailsGlobals } from "@openrouter/sdk/models/operations"; let value: ListGuardrailsGlobals = {}; // Example of assigning values: value = { httpReferer: "https://example.com", appTitle: "Example App", appCategories: "example-category" }; console.log(value); ``` -------------------------------- ### Initialize ListProvidersRequest Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listprovidersrequest.md Import and initialize an empty ListProvidersRequest object. This is useful for starting with default or no parameters. ```typescript import { ListProvidersRequest } from "@openrouter/sdk/models/operations"; let value: ListProvidersRequest = {}; ``` -------------------------------- ### Instantiate BulkAssignKeysToGuardrailRequest Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/bulkassignkeystoguardrailrequest.md Example of how to create an instance of the BulkAssignKeysToGuardrailRequest model. Ensure the 'id' and 'bulkAssignKeysRequest' fields are correctly populated. ```typescript import { BulkAssignKeysToGuardrailRequest } from "@openrouter/sdk/models/operations"; let value: BulkAssignKeysToGuardrailRequest = { id: "550e8400-e29b-41d4-a716-446655440000", bulkAssignKeysRequest: { keyHashes: [ "c56454edb818d6b14bc0d61c46025f1450b0f4012d12304ab40aacb519fcbc93", ], }, }; ``` -------------------------------- ### CreateGuardrailRequest Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createguardrailrequest.md Instantiate a CreateGuardrailRequest object with a name for the new guardrail. Ensure the SDK is imported. ```typescript import { CreateGuardrailRequest } from "@openrouter/sdk/models/operations"; let value: CreateGuardrailRequest = { createGuardrailRequest: { name: "My New Guardrail", }, }; ``` -------------------------------- ### Constructing a SendChatCompletionRequestRequest Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/sendchatcompletionrequestrequest.md Example of how to create a SendChatCompletionRequestRequest object with system and user messages. ```typescript import { SendChatCompletionRequestRequest } from "@openrouter/sdk/models/operations"; let value: SendChatCompletionRequestRequest = { chatRequest: { messages: [ { content: "You are a helpful assistant.", role: "system", }, { content: "What is the capital of France?", role: "user", }, ], }, }; ``` -------------------------------- ### Instantiate ListEndpointsZdrResponse Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listendpointszdrresponse.md Example of how to create and populate a ListEndpointsZdrResponse object in TypeScript. Ensure the necessary model is imported. ```typescript import { ListEndpointsZdrResponse } from "@openrouter/sdk/models/operations"; let value: ListEndpointsZdrResponse = { data: [ { contextLength: 8192, latencyLast30m: { p50: 0.25, p75: 0.35, p90: 0.48, p99: 0.85, }, maxCompletionTokens: 4096, maxPromptTokens: 8192, modelId: "openai/gpt-4", modelName: "GPT-4", name: "OpenAI: GPT-4", pricing: { completion: "0.00006", prompt: "0.00003", }, providerName: "OpenAI", quantization: "fp16", supportedParameters: [ "temperature", "top_p", "max_tokens", ], supportsImplicitCaching: true, tag: "openai", throughputLast30m: { p50: 45.2, p75: 38.5, p90: 28.3, p99: 15.1, }, uptimeLast1d: 99.8, uptimeLast30m: 99.5, uptimeLast5m: 100, }, ], }; ``` -------------------------------- ### Instantiate ListGuardrailMemberAssignmentsResponse Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listguardrailmemberassignmentsresponse.md Example of how to create an instance of ListGuardrailMemberAssignmentsResponse with sample data. Ensure the correct import path is used. ```typescript import { ListGuardrailMemberAssignmentsResponse } from "@openrouter/sdk/models/operations"; let value: ListGuardrailMemberAssignmentsResponse = { result: { data: [ { assignedBy: "user_abc123", createdAt: "2025-08-24T10:30:00Z", guardrailId: "550e8400-e29b-41d4-a716-446655440001", id: "550e8400-e29b-41d4-a716-446655440000", organizationId: "org_xyz789", userId: "user_abc123", }, ], totalCount: 1, }, }; ``` -------------------------------- ### Create URLCitation Object Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/openairesponsesannotation.md Example of creating a `models.URLCitation` object. This type represents a citation to a URL, including start and end indices, title, and the URL itself. ```typescript const value: models.URLCitation = { endIndex: 582752, startIndex: 114325, title: "", type: "url_citation", url: "https://dim-jet.biz/", }; ``` -------------------------------- ### Create ResponseOutputText Object Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/responseoutputtext.md Example of how to create a ResponseOutputText object. Ensure the 'text' and 'type' fields are correctly populated. ```typescript import { ResponseOutputText } from "@openrouter/sdk/models"; let value: ResponseOutputText = { text: "The capital of France is Paris.", type: "output_text", }; ``` -------------------------------- ### Prepare for Publishing Source: https://github.com/openrouterteam/typescript-sdk/blob/main/AGENTS.md Runs the build process automatically before publishing the package. ```bash pnpm run prepublishOnly ``` -------------------------------- ### GET /models/count Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/models/README.md Get the total count of available models. ```APIDOC ## GET /models/count ### Description Get total count of available models ### Method GET ### Endpoint /models/count ### Parameters #### Query Parameters - **request** (operations.GetModelsRequest) - Required - The request object to use for the request. - **options** (RequestOptions) - Optional - Used to set various options for making HTTP requests. - **options.fetchOptions** (RequestInit) - Optional - Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. - **options.retries** (RetryConfig) - Optional - Enables retrying HTTP requests under certain failure conditions. ### Response #### Success Response (200) - **count** (number) - The total number of available models. #### Response Example { "count": 150 } ### Errors - **errors.BadRequestResponseError** (400) - application/json - **errors.InternalServerResponseError** (500) - application/json - **errors.OpenRouterDefaultError** (4XX, 5XX) - */* ``` -------------------------------- ### Initialize GetKeyResponse Object Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/getkeyresponse.md Demonstrates how to initialize a GetKeyResponse object with sample data. Ensure the imported type matches your SDK version. ```typescript import { GetKeyResponse } from "@openrouter/sdk/models/operations"; let value: GetKeyResponse = { data: { byokUsage: 17.38, byokUsageDaily: 17.38, byokUsageMonthly: 17.38, byokUsageWeekly: 17.38, createdAt: "2025-08-24T10:30:00Z", creatorUserId: "user_2dHFtVWx2n56w6HkM0000000000", disabled: false, hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", includeByokInLimit: false, label: "Production API Key", limit: 100, limitRemaining: 74.5, limitReset: "monthly", name: "My Production Key", updatedAt: "2025-08-24T15:45:00Z", usage: 25.5, usageDaily: 25.5, usageMonthly: 25.5, usageWeekly: 25.5, workspaceId: "0df9e665-d932-5740-b2c7-b52af166bc11", }, }; ``` -------------------------------- ### Get Key API Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/apikeys/README.md This section details the parameters and response for the Get Key API endpoint. ```APIDOC ## GET /get-key ### Description Retrieves a key based on the provided request parameters. ### Method GET ### Endpoint /get-key ### Parameters #### Query Parameters - **request** (operations.GetKeyRequest) - Required - The request object to use for the request. - **options** (RequestOptions) - Optional - Used to set various options for making HTTP requests. - **options.fetchOptions** (RequestInit) - Optional - Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. - **options.retries** (RetryConfig) - Optional - Enables retrying HTTP requests under certain failure conditions. ### Response #### Success Response (200) - **Promise** (operations.GetKeyResponse) - The response from the Get Key API call. ``` -------------------------------- ### String Type Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createembeddingsresponse.md Example of using a string type, typically for a placeholder or simple value. ```typescript const value: string = ""; ``` -------------------------------- ### Initialize PDFParserOptions Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/pdfparseroptions.md Demonstrates how to import and initialize PDFParserOptions with default values. No specific setup is required beyond the import. ```typescript import { PDFParserOptions } from "@openrouter/sdk/models"; let value: PDFParserOptions = {}; ``` -------------------------------- ### CreateEmbeddingsRequestBody Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createembeddingsrequest.md Example of the request body for creating embeddings, including input text, model, and optional dimensions. ```json { "dimensions": 1536, "input": "The quick brown fox jumps over the lazy dog", "model": "openai/text-embedding-3-small" } ``` -------------------------------- ### Initialize PromptTokensDetails Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/prompttokensdetails.md Demonstrates how to import and initialize an empty PromptTokensDetails object. This can be used as a starting point for tracking token usage. ```typescript import { PromptTokensDetails } from "@openrouter/sdk/models"; let value: PromptTokensDetails = {}; ``` -------------------------------- ### Initialize and Use OpenRouter SDK Source: https://github.com/openrouterteam/typescript-sdk/blob/main/USAGE.md Instantiate the OpenRouter client with your API key and application details. Then, make a call to retrieve user activity analytics. Ensure your OPENROUTER_API_KEY is set in the environment variables. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ httpReferer: "", appTitle: "", appCategories: "", apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.analytics.getUserActivity(); console.log(result); } run(); ``` -------------------------------- ### Create Embeddings Response Body Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createembeddingsresponse.md Example of how to structure the CreateEmbeddingsResponseBody, including embedding data, model, and object type. ```typescript const value: operations.CreateEmbeddingsResponseBody = { data: [ { embedding: [ 0.0023064255, -0.009327292, 0.015797347, ], object: "embedding", }, ], model: "openai/text-embedding-3-small", object: "list", }; ``` -------------------------------- ### GET /key - Get Current API Key Metadata Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/apikeys/README.md Retrieves metadata for the API key associated with the current authentication session. ```APIDOC ## GET /key ### Description Get information on the API key associated with the current authentication session. ### Method GET ### Endpoint /key ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the API key. - **name** (string) - The name of the API key. - **created** (string) - The timestamp when the API key was created. - **last_used** (string) - The timestamp when the API key was last used. - **expires** (string) - The timestamp when the API key will expire. #### Response Example ```json { "id": "key_abc123", "name": "My Test Key", "created": "2023-10-27T10:00:00Z", "last_used": "2023-10-27T12:30:00Z", "expires": "2024-10-27T10:00:00Z" } ``` ``` -------------------------------- ### CreateKeysRequestBody Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createkeysrequest.md Example of a CreateKeysRequestBody object, showing optional fields like expiration, limits, and name. This object is part of the CreateKeysRequest. ```json { "expires_at": "2027-12-31T23:59:59Z", "include_byok_in_limit": true, "limit": 50, "limit_reset": "monthly", "name": "My New API Key" } ``` -------------------------------- ### CreateKeysResponse Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createkeysresponse.md Demonstrates how to use the CreateKeysResponse type to represent a newly created API key. Ensure the '@openrouter/sdk/models/operations' is imported. ```typescript import { CreateKeysResponse } from "@openrouter/sdk/models/operations"; let value: CreateKeysResponse = { data: { byokUsage: 0, byokUsageDaily: 0, byokUsageMonthly: 0, byokUsageWeekly: 0, createdAt: "2025-08-24T10:30:00Z", creatorUserId: "user_2dHFtVWx2n56w6HkM0000000000", disabled: false, hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", includeByokInLimit: true, label: "My New API Key", limit: 50, limitRemaining: 50, limitReset: "monthly", name: "My New API Key", updatedAt: null, usage: 0, usageDaily: 0, usageMonthly: 0, usageWeekly: 0, workspaceId: "0df9e665-d932-5740-b2c7-b52af166bc11", }, key: "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", }; ``` -------------------------------- ### GET /credits - Get Remaining Credits Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/credits/README.md Retrieves the total credits purchased and used for the authenticated user. Requires a Management API key. ```APIDOC ## GET /credits ### Description Get total credits purchased and used for the authenticated user. ### Method GET ### Endpoint /credits ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed for this endpoint." } ``` ### Response #### Success Response (200) - **value** (object) - An object containing credit information. - **total_purchased** (number) - Total credits purchased. - **total_used** (number) - Total credits used. - **total_available** (number) - Total credits available. #### Response Example ```json { "value": { "total_purchased": 10000, "total_used": 500, "total_available": 9500 } } ``` ``` -------------------------------- ### Instantiate ListGuardrailKeyAssignmentsResponse Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listguardrailkeyassignmentsresponse.md Demonstrates how to create an instance of ListGuardrailKeyAssignmentsResponse with sample data. Ensure the correct import path is used. ```typescript import { ListGuardrailKeyAssignmentsResponse } from "@openrouter/sdk/models/operations"; let value: ListGuardrailKeyAssignmentsResponse = { result: { data: [ { assignedBy: "user_abc123", createdAt: "2025-08-24T10:30:00Z", guardrailId: "550e8400-e29b-41d4-a716-446655440001", id: "550e8400-e29b-41d4-a716-446655440000", keyHash: "c56454edb818d6b14bc0d61c46025f1450b0f4012d12304ab40aacb519fcbc93", keyLabel: "prod-key", keyName: "Production Key", }, ], totalCount: 1, }, }; ``` -------------------------------- ### models.OpenResponsesResult Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createresponsesresponse.md An example of the `models.OpenResponsesResult` type, which represents a completed response from the API. It includes details like completion time, model used, and the output content. ```typescript const value: models.OpenResponsesResult = { completedAt: 728667, createdAt: 1704067200, error: null, frequencyPenalty: 9990.37, id: "resp-abc123", incompleteDetails: null, instructions: null, metadata: null, model: "gpt-4", object: "response", output: [ { content: [ { text: "Hello! How can I help you today?", type: "output_text", }, ], id: "msg-abc123", role: "assistant", type: "message", }, ], parallelToolCalls: true, presencePenalty: null, status: "completed", temperature: null, toolChoice: "auto", tools: [], topP: null, }; ``` -------------------------------- ### Run SDK Tests Source: https://github.com/openrouterteam/typescript-sdk/blob/main/CLAUDE.md Executes tests using Vitest. Requires an OpenRouter API key set in the .env file. Tests are organized into e2e, unit, and funcs directories. ```bash npx vitest ``` ```bash npx vitest tests/e2e/call-model.test.ts ``` ```bash npx vitest --watch ``` -------------------------------- ### Initialize ListKeyAssignmentsRequest Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listkeyassignmentsrequest.md Demonstrates how to import and initialize an empty ListKeyAssignmentsRequest object. ```typescript import { ListKeyAssignmentsRequest } from "@openrouter/sdk/models/operations"; let value: ListKeyAssignmentsRequest = {}; ``` -------------------------------- ### GET /activity - Get User Activity Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/analytics/README.md Retrieves user activity data grouped by endpoint for the last 30 completed UTC days. Requires a Management API key. ```APIDOC ## GET /activity ### Description Returns user activity data grouped by endpoint for the last 30 (completed) UTC days. [Management key](/docs/guides/overview/auth/management-api-keys) required. ### Method GET ### Endpoint /activity ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of results to return. - **offset** (integer) - Optional - The number of results to skip. ### Request Example ```json { "example": "No request body for GET request" } ``` ### Response #### Success Response (200) - **data** (array) - An array of activity objects, each containing endpoint usage details. - **total** (integer) - The total number of activity records available. #### Response Example ```json { "example": "{\"data\": [{\"endpoint\": \"/v1/chat/completions\", \"total_requests\": 150, \"total_tokens\": 30000, \"total_cost\": 0.0015}], \"total\": 1}" } ``` ``` -------------------------------- ### ExchangeAuthCodeForAPIKeyRequestBody Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/exchangeauthcodeforapikeyrequest.md Provides an example of the request body for exchanging an authorization code for an API key, including optional fields like code challenge method and code verifier. ```json { "code": "auth_code_abc123def456", "code_challenge_method": "S256", "code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" } ``` -------------------------------- ### Create Embeddings Response Body Example Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/createembeddingsresponsebody.md Example of how to structure a CreateEmbeddingsResponseBody object in TypeScript. Ensure the 'data' field is an array of embedding objects, and 'model' and 'object' fields are correctly populated. ```typescript import { CreateEmbeddingsResponseBody } from "@openrouter/sdk/models/operations"; let value: CreateEmbeddingsResponseBody = { data: [ { embedding: [ 0.0023064255, -0.009327292, 0.015797347, ], object: "embedding", }, ], model: "openai/text-embedding-3-small", object: "list", }; ``` -------------------------------- ### Instantiate ListMemberAssignmentsResponse Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/listmemberassignmentsresponse.md Demonstrates how to create an instance of ListMemberAssignmentsResponse with sample data. Ensure the import statement is included. ```typescript import { ListMemberAssignmentsResponse } from "@openrouter/sdk/models/operations"; let value: ListMemberAssignmentsResponse = { result: { data: [ { assignedBy: "user_abc123", createdAt: "2025-08-24T10:30:00Z", guardrailId: "550e8400-e29b-41d4-a716-446655440001", id: "550e8400-e29b-41d4-a716-446655440000", organizationId: "org_xyz789", userId: "user_abc123", }, ], totalCount: 1, }, }; ``` -------------------------------- ### Get Generation Content using Standalone Function Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/generations/README.md This standalone function provides an alternative way to get generation content, optimized for tree-shaking. It requires an initialized OpenRouterCore instance and handles success and error responses explicitly. ```typescript import { OpenRouterCore } from "@openrouter/sdk/core.js"; import { generationsListGenerationContent } from "@openrouter/sdk/funcs/generationsListGenerationContent.js"; // Use `OpenRouterCore` for best tree-shaking performance. // You can create one instance of it to use across an application. const openRouter = new OpenRouterCore({ httpReferer: "", appTitle: "", appCategories: "", apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const res = await generationsListGenerationContent(openRouter, { id: "gen-1234567890", }); if (res.ok) { const { value: result } = res; console.log(result); } else { console.log("generationsListGenerationContent failed:", res.error); } } run(); ``` -------------------------------- ### Instantiate FileCitation Model Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/filecitation.md Import and create a FileCitation object. Ensure all required fields are provided. ```typescript import { FileCitation } from "@openrouter/sdk/models"; let value: FileCitation = { fileId: "file-abc123", filename: "research_paper.pdf", index: 0, type: "file_citation", }; ``` -------------------------------- ### Initialize UpdateKeysResponse Object Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/updatekeysresponse.md Demonstrates how to initialize an UpdateKeysResponse object with sample data. Ensure the correct import statement is used. ```typescript import { UpdateKeysResponse } from "@openrouter/sdk/models/operations"; let value: UpdateKeysResponse = { data: { byokUsage: 17.38, byokUsageDaily: 17.38, byokUsageMonthly: 17.38, byokUsageWeekly: 17.38, createdAt: "2025-08-24T10:30:00Z", creatorUserId: "user_2dHFtVWx2n56w6HkM0000000000", disabled: false, hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", includeByokInLimit: true, label: "Updated API Key Name", limit: 75, limitRemaining: 49.5, limitReset: "daily", name: "Updated API Key Name", updatedAt: "2025-08-24T16:00:00Z", usage: 25.5, usageDaily: 25.5, usageMonthly: 25.5, usageWeekly: 25.5, workspaceId: "0df9e665-d932-5740-b2c7-b52af166bc11", }, }; ``` -------------------------------- ### Get Remaining Credits with Standalone Function Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/credits/README.md This standalone function provides an alternative way to get credit information, optimized for tree-shaking. It returns a result object with 'ok' and 'error' properties. Ensure OPENROUTER_API_KEY is set in your environment. ```typescript import { OpenRouterCore } from "@openrouter/sdk/core.js"; import { creditsGetCredits } from "@openrouter/sdk/funcs/creditsGetCredits.js"; // Use `OpenRouterCore` for best tree-shaking performance. // You can create one instance of it to use across an application. const openRouter = new OpenRouterCore({ httpReferer: "", appTitle: "", appCategories: "", apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const res = await creditsGetCredits(openRouter); if (res.ok) { const { value: result } = res; console.log(result); } else { console.log("creditsGetCredits failed:", res.error); } } run(); ``` -------------------------------- ### Get API Key using Standalone Function Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/apikeys/README.md This standalone function provides an alternative way to get a single API key by hash, optimized for tree-shaking. It requires an instance of `OpenRouterCore` and handles success and error responses explicitly. ```typescript import { OpenRouterCore } from "@openrouter/sdk/core.js"; import { apiKeysGet } from "@openrouter/sdk/funcs/apiKeysGet.js"; // Use `OpenRouterCore` for best tree-shaking performance. // You can create one instance of it to use across an application. const openRouter = new OpenRouterCore({ httpReferer: "", appTitle: "", appCategories: "", apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const res = await apiKeysGet(openRouter, { hash: "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943", }); if (res.ok) { const { value: result } = res; console.log(result); } else { console.log("apiKeysGet failed:", res.error); } } run(); ``` -------------------------------- ### TopProviderInfo Example Usage Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/topproviderinfo.md Demonstrates how to import and use the TopProviderInfo type in TypeScript. This is useful for initializing or type-checking provider information. ```typescript import { TopProviderInfo } from "@openrouter/sdk/models"; let value: TopProviderInfo = { isModerated: true, }; ``` -------------------------------- ### Actionable Error Messages Example (TypeScript) Source: https://github.com/openrouterteam/typescript-sdk/blob/main/OVERVIEW.md Provides an example of the specific and actionable error messages the SDK provides, helping developers quickly resolve issues instead of dealing with generic errors. ```typescript // Instead of generic errors, get specific guidance: // "Model 'openai/o1-preview' requires at least 2 messages. // You provided 1 message. Add a system or user message." ``` -------------------------------- ### List Providers using SDK Instance Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/providers/README.md Use this method to list all available providers via the OpenRouter SDK. Ensure you have initialized the OpenRouter client with your API key and referer information. ```typescript import { OpenRouter } from "@openrouter/sdk"; const openRouter = new OpenRouter({ httpReferer: "", appTitle: "", appCategories: "", apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const result = await openRouter.providers.list(); console.log(result); } run(); ``` -------------------------------- ### Initialize ResponseOutputTextTopLogprob Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/responseoutputtexttoplogprob.md Demonstrates how to create an instance of the ResponseOutputTextTopLogprob model. Ensure the model is imported from '@openrouter/sdk/models'. ```typescript import { ResponseOutputTextTopLogprob } from "@openrouter/sdk/models"; let value: ResponseOutputTextTopLogprob = { bytes: [ 303617, 34414, ], logprob: 1976.4, token: "", }; ``` -------------------------------- ### Get Current API Key Metadata (Standalone Function) Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/apikeys/README.md This standalone function provides an alternative way to get current API key metadata, optimized for tree-shaking. It requires an instance of `OpenRouterCore` and handles success and error responses explicitly. ```typescript import { OpenRouterCore } from "@openrouter/sdk/core.js"; import { apiKeysGetCurrentKeyMetadata } from "@openrouter/sdk/funcs/apiKeysGetCurrentKeyMetadata.js"; // Use `OpenRouterCore` for best tree-shaking performance. // You can create one instance of it to use across an application. const openRouter = new OpenRouterCore({ httpReferer: "", appTitle: "", appCategories: "", apiKey: process.env["OPENROUTER_API_KEY"] ?? "", }); async function run() { const res = await apiKeysGetCurrentKeyMetadata(openRouter); if (res.ok) { const { value: result } = res; console.log(result); } else { console.log("apiKeysGetCurrentKeyMetadata failed:", res.error); } } run(); ``` -------------------------------- ### Get Guardrail Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/sdks/guardrails/README.md Retrieves a specific guardrail by its ID. ```APIDOC ## GET /guardrails/{guardrailId} ### Description Retrieves a specific guardrail by its ID. ### Method GET ### Endpoint /guardrails/{guardrailId} ### Parameters #### Path Parameters - **guardrailId** (string) - Required - The ID of the guardrail to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the guardrail. - **name** (string) - The name of the guardrail. - **description** (string) - A description of the guardrail. - **createdAt** (string) - The timestamp when the guardrail was created. - **updatedAt** (string) - The timestamp when the guardrail was last updated. #### Response Example ```json { "id": "grd_12345", "name": "Profanity Filter", "description": "Filters out profane language.", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Initialize Reasoning Configuration Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/reasoning.md Import and initialize an empty reasoning configuration object. This serves as a starting point for setting specific reasoning constraints. ```typescript import { Reasoning } from "@openrouter/sdk/models"; let value: Reasoning = {}; ``` -------------------------------- ### Example Usage of ExchangeAuthCodeForAPIKeyResponse in TypeScript Source: https://github.com/openrouterteam/typescript-sdk/blob/main/docs/models/operations/exchangeauthcodeforapikeyresponse.md Demonstrates how to import and use the ExchangeAuthCodeForAPIKeyResponse model in a TypeScript application. This example shows the structure of a successful API key exchange response, including the API key and associated user ID. ```typescript import { ExchangeAuthCodeForAPIKeyResponse } from "@openrouter/sdk/models/operations"; let value: ExchangeAuthCodeForAPIKeyResponse = { key: "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", userId: "user_2yOPcMpKoQhcd4bVgSMlELRaIah", }; ```