UNPKG

@openrouter/ai-sdk-provider

Version:

The [OpenRouter](https://openrouter.ai/) provider for the [Vercel AI SDK](https://sdk.vercel.ai/docs) gives access to over 300 large language models on the OpenRouter chat and completion APIs.

373 lines (356 loc) 13.4 kB
import { LanguageModelV2, LanguageModelV2CallOptions, LanguageModelV2Content, LanguageModelV2FinishReason, LanguageModelV2Usage, LanguageModelV2CallWarning, LanguageModelV2ResponseMetadata, SharedV2Headers, LanguageModelV2StreamPart } from '@ai-sdk/provider'; export { LanguageModelV2, LanguageModelV2Prompt } from '@ai-sdk/provider'; type OpenRouterChatModelId = string; type OpenRouterChatSettings = { /** Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. As an example, you can pass {"50256": -100} to prevent the <|endoftext|> token from being generated. */ logitBias?: Record<number, number>; /** Return the log probabilities of the tokens. Including logprobs will increase the response size and can slow down response times. However, it can be useful to understand better how the model is behaving. Setting to true will return the log probabilities of the tokens that were generated. Setting to a number will return the log probabilities of the top n tokens that were generated. */ logprobs?: boolean | number; /** Whether to enable parallel function calling during tool use. Default to true. */ parallelToolCalls?: boolean; /** A unique identifier representing your end-user, which can help OpenRouter to monitor and detect abuse. Learn more. */ user?: string; /** * Web search plugin configuration for enabling web search capabilities */ plugins?: Array<{ id: 'web'; /** * Maximum number of search results to include (default: 5) */ max_results?: number; /** * Custom search prompt to guide the search query */ search_prompt?: string; }>; /** * Built-in web search options for models that support native web search */ web_search_options?: { /** * Maximum number of search results to include */ max_results?: number; /** * Custom search prompt to guide the search query */ search_prompt?: string; }; /** * Provider routing preferences to control request routing behavior */ provider?: { /** * List of provider slugs to try in order (e.g. ["anthropic", "openai"]) */ order?: string[]; /** * Whether to allow backup providers when primary is unavailable (default: true) */ allow_fallbacks?: boolean; /** * Only use providers that support all parameters in your request (default: false) */ require_parameters?: boolean; /** * Control whether to use providers that may store data */ data_collection?: 'allow' | 'deny'; /** * List of provider slugs to allow for this request */ only?: string[]; /** * List of provider slugs to skip for this request */ ignore?: string[]; /** * List of quantization levels to filter by (e.g. ["int4", "int8"]) */ quantizations?: Array<'int4' | 'int8' | 'fp4' | 'fp6' | 'fp8' | 'fp16' | 'bf16' | 'fp32' | 'unknown'>; /** * Sort providers by price, throughput, or latency */ sort?: 'price' | 'throughput' | 'latency'; /** * Maximum pricing you want to pay for this request */ max_price?: { prompt?: number | string; completion?: number | string; image?: number | string; audio?: number | string; request?: number | string; }; }; } & OpenRouterSharedSettings; type OpenRouterProviderOptions = { models?: string[]; /** * https://openrouter.ai/docs/use-cases/reasoning-tokens * One of `max_tokens` or `effort` is required. * If `exclude` is true, reasoning will be removed from the response. Default is false. */ reasoning?: { enabled?: boolean; exclude?: boolean; } & ({ max_tokens: number; } | { effort: 'high' | 'medium' | 'low'; }); /** * A unique identifier representing your end-user, which can * help OpenRouter to monitor and detect abuse. */ user?: string; }; type OpenRouterSharedSettings = OpenRouterProviderOptions & { /** * @deprecated use `reasoning` instead */ includeReasoning?: boolean; extraBody?: Record<string, unknown>; /** * Enable usage accounting to get detailed token usage information. * https://openrouter.ai/docs/use-cases/usage-accounting */ usage?: { /** * When true, includes token usage information in the response. */ include: boolean; }; }; /** * Usage accounting response * @see https://openrouter.ai/docs/use-cases/usage-accounting */ type OpenRouterUsageAccounting = { promptTokens: number; promptTokensDetails?: { cachedTokens: number; }; completionTokens: number; completionTokensDetails?: { reasoningTokens: number; }; totalTokens: number; cost?: number; costDetails: { upstreamInferenceCost: number; }; }; type OpenRouterCompletionModelId = string; type OpenRouterCompletionSettings = { /** Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. As an example, you can pass {"50256": -100} to prevent the <|endoftext|> token from being generated. */ logitBias?: Record<number, number>; /** Return the log probabilities of the tokens. Including logprobs will increase the response size and can slow down response times. However, it can be useful to better understand how the model is behaving. Setting to true will return the log probabilities of the tokens that were generated. Setting to a number will return the log probabilities of the top n tokens that were generated. */ logprobs?: boolean | number; /** The suffix that comes after a completion of inserted text. */ suffix?: string; } & OpenRouterSharedSettings; type OpenRouterChatConfig = { provider: string; compatibility: 'strict' | 'compatible'; headers: () => Record<string, string | undefined>; url: (options: { modelId: string; path: string; }) => string; fetch?: typeof fetch; extraBody?: Record<string, unknown>; }; declare class OpenRouterChatLanguageModel implements LanguageModelV2 { readonly specificationVersion: "v2"; readonly provider = "openrouter"; readonly defaultObjectGenerationMode: "tool"; readonly modelId: OpenRouterChatModelId; readonly supportedUrls: Record<string, RegExp[]>; readonly settings: OpenRouterChatSettings; private readonly config; constructor(modelId: OpenRouterChatModelId, settings: OpenRouterChatSettings, config: OpenRouterChatConfig); private getArgs; doGenerate(options: LanguageModelV2CallOptions): Promise<{ content: Array<LanguageModelV2Content>; finishReason: LanguageModelV2FinishReason; usage: LanguageModelV2Usage; warnings: Array<LanguageModelV2CallWarning>; providerMetadata?: { openrouter: { provider: string; usage: OpenRouterUsageAccounting; }; }; request?: { body?: unknown; }; response?: LanguageModelV2ResponseMetadata & { headers?: SharedV2Headers; body?: unknown; }; }>; doStream(options: LanguageModelV2CallOptions): Promise<{ stream: ReadableStream<LanguageModelV2StreamPart>; warnings: Array<LanguageModelV2CallWarning>; request?: { body?: unknown; }; response?: LanguageModelV2ResponseMetadata & { headers?: SharedV2Headers; body?: unknown; }; }>; } type OpenRouterCompletionConfig = { provider: string; compatibility: 'strict' | 'compatible'; headers: () => Record<string, string | undefined>; url: (options: { modelId: string; path: string; }) => string; fetch?: typeof fetch; extraBody?: Record<string, unknown>; }; declare class OpenRouterCompletionLanguageModel implements LanguageModelV2 { readonly specificationVersion: "v2"; readonly provider = "openrouter"; readonly modelId: OpenRouterCompletionModelId; readonly supportedUrls: Record<string, RegExp[]>; readonly defaultObjectGenerationMode: undefined; readonly settings: OpenRouterCompletionSettings; private readonly config; constructor(modelId: OpenRouterCompletionModelId, settings: OpenRouterCompletionSettings, config: OpenRouterCompletionConfig); private getArgs; doGenerate(options: LanguageModelV2CallOptions): Promise<Awaited<ReturnType<LanguageModelV2['doGenerate']>>>; doStream(options: LanguageModelV2CallOptions): Promise<Awaited<ReturnType<LanguageModelV2['doStream']>>>; } interface OpenRouterProvider extends LanguageModelV2 { (modelId: OpenRouterChatModelId, settings?: OpenRouterCompletionSettings): OpenRouterCompletionLanguageModel; (modelId: OpenRouterChatModelId, settings?: OpenRouterChatSettings): OpenRouterChatLanguageModel; languageModel(modelId: OpenRouterChatModelId, settings?: OpenRouterCompletionSettings): OpenRouterCompletionLanguageModel; languageModel(modelId: OpenRouterChatModelId, settings?: OpenRouterChatSettings): OpenRouterChatLanguageModel; /** Creates an OpenRouter chat model for text generation. */ chat(modelId: OpenRouterChatModelId, settings?: OpenRouterChatSettings): OpenRouterChatLanguageModel; /** Creates an OpenRouter completion model for text generation. */ completion(modelId: OpenRouterCompletionModelId, settings?: OpenRouterCompletionSettings): OpenRouterCompletionLanguageModel; } interface OpenRouterProviderSettings { /** Base URL for the OpenRouter API calls. */ baseURL?: string; /** @deprecated Use `baseURL` instead. */ baseUrl?: string; /** API key for authenticating requests. */ apiKey?: string; /** Custom headers to include in the requests. */ headers?: Record<string, string>; /** OpenRouter compatibility mode. Should be set to `strict` when using the OpenRouter API, and `compatible` when using 3rd party providers. In `compatible` mode, newer information such as streamOptions are not being sent. Defaults to 'compatible'. */ compatibility?: 'strict' | 'compatible'; /** Custom fetch implementation. You can use it as a middleware to intercept requests, or to provide a custom fetch implementation for e.g. testing. */ fetch?: typeof fetch; /** A JSON object to send as the request body to access OpenRouter features & upstream provider features. */ extraBody?: Record<string, unknown>; } /** Create an OpenRouter provider instance. */ declare function createOpenRouter(options?: OpenRouterProviderSettings): OpenRouterProvider; /** Default OpenRouter provider instance. It uses 'strict' compatibility mode. */ declare const openrouter: OpenRouterProvider; /** @deprecated Use `createOpenRouter` instead. */ declare class OpenRouter { /** Use a different URL prefix for API calls, e.g. to use proxy servers. The default prefix is `https://openrouter.ai/api/v1`. */ readonly baseURL: string; /** API key that is being sent using the `Authorization` header. It defaults to the `OPENROUTER_API_KEY` environment variable. */ readonly apiKey?: string; /** Custom headers to include in the requests. */ readonly headers?: Record<string, string>; /** * Creates a new OpenRouter provider instance. */ constructor(options?: OpenRouterProviderSettings); private get baseConfig(); chat(modelId: OpenRouterChatModelId, settings?: OpenRouterChatSettings): OpenRouterChatLanguageModel; completion(modelId: OpenRouterCompletionModelId, settings?: OpenRouterCompletionSettings): OpenRouterCompletionLanguageModel; } export { OpenRouter, type OpenRouterCompletionSettings, type OpenRouterProvider, type OpenRouterProviderOptions, type OpenRouterProviderSettings, type OpenRouterSharedSettings, type OpenRouterUsageAccounting, createOpenRouter, openrouter };