这将帮助您开始使用 OpenRouter 聊天模型 。OpenRouter 是一个统一的 API,通过单一端点提供对来自多个提供商(OpenAI、Anthropic、Google、Meta 等)模型的访问。
要获取可用模型的完整列表,请访问 OpenRouter 模型页面 。
集成详情
模型功能
要通过 OpenRouter 访问模型,您需要创建一个 OpenRouter 帐户 ,获取 API 密钥,并安装 @langchain/openrouter 集成包。
前往 OpenRouter 密钥页面 注册并生成 API 密钥。完成此操作后,设置 OPENROUTER_API_KEY 环境变量:
export OPENROUTER_API_KEY = "your-api-key"
要启用模型调用的自动跟踪,请设置您的 LangSmith API 密钥:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
LangChain OpenRouter 集成位于 @langchain/openrouter 包中:
npm install @langchain/openrouter @langchain/core
实例化
现在我们可以实例化模型对象并生成聊天补全:
import { ChatOpenRouter } from "@langchain/openrouter" ;
const model = new ChatOpenRouter ( {
model : "anthropic/claude-sonnet-4.5" ,
temperature : 0 ,
maxTokens : 1024 ,
// 其他参数...
} ) ;
const aiMsg = await model . invoke ([
{
role : "system" ,
content :
"You are a helpful assistant that translates English to French. Translate the user sentence." ,
},
{
role : "user" ,
content : "I love programming." ,
},
]) ;
console . log (aiMsg . content) ;
J'adore la programmation.
流式传输
const stream = await model . stream ( "Write a short poem about the sea." ) ;
for await ( const chunk of stream) {
process . stdout . write ( typeof chunk . content === "string" ? chunk . content : "" ) ;
}
工具调用
OpenRouter 使用与 OpenAI 兼容的工具调用格式。您可以描述工具及其参数,并让模型返回一个 JSON 对象,其中包含要调用的工具以及该工具的输入。
绑定工具
通过 ChatOpenRouter.bindTools,您可以将 Zod 模式、LangChain 工具或原始函数定义作为工具传递给模型。在底层,这些会被转换为 OpenAI 工具模式,并在每次模型调用时传入。
import { ChatOpenRouter } from "@langchain/openrouter" ;
import { tool } from "@langchain/core/tools" ;
import { z } from "zod" ;
const getWeather = tool ( async ({ location }) => `Sunny in ${ location } ` , {
name : "get_weather" ,
description : "Get the current weather in a given location" ,
schema : z . object ( {
location : z
. string ()
. describe ( "The city and state, e.g. San Francisco, CA" ) ,
} ) ,
} ) ;
const modelWithTools = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
} ) . bindTools ([getWeather]) ;
const aiMsg = await modelWithTools . invoke (
"What is the weather like in San Francisco?"
) ;
console . log (aiMsg . tool_calls) ;
[
{
name: 'get_weather',
args: { location: 'San Francisco, CA' },
id: 'call_abc123',
type: 'tool_call'
}
]
严格模式
传递 strict: true 以保证模型输出与工具定义中提供的 JSON 模式完全匹配:
const modelWithStrictTools = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
} ) . bindTools ([getWeather] , { strict : true } ) ;
有关绑定工具和工具调用输出的更多信息,请访问 工具调用 文档。
结构化输出
ChatOpenRouter 通过 .withStructuredOutput() 方法支持结构化输出。提取策略会根据模型能力自动选择:
jsonSchema — 原生 JSON Schema 响应格式(当模型支持时使用)
functionCalling — 将模式包装为工具调用(默认回退方案)
jsonMode — 要求模型以 JSON 格式响应,无严格模式约束
当启用多模型路由(models 列表或 route: "fallback")时,该方法始终回退到 functionCalling,因为在请求时无法确定实际后端模型的能力。
import { ChatOpenRouter } from "@langchain/openrouter" ;
import { z } from "zod" ;
const model = new ChatOpenRouter ( { model : "openai/gpt-5.4" } ) ;
const movieSchema = z . object ( {
title : z . string () . describe ( "The title of the movie" ) ,
year : z . number () . describe ( "The year the movie was released" ) ,
director : z . string () . describe ( "The director of the movie" ) ,
rating : z . number () . describe ( "The movie's rating out of 10" ) ,
} ) ;
const structuredModel = model . withStructuredOutput (movieSchema , {
name : "movie" ,
method : "jsonSchema" ,
} ) ;
const response = await structuredModel . invoke (
"Provide details about the movie Inception"
) ;
console . log (response) ;
{
title: 'Inception',
year: 2010,
director: 'Christopher Nolan',
rating: 8.8
}
您可以使用 jsonSchema 和 functionCalling 方法传递 strict: true 以强制严格遵循模式:
const strictModel = model . withStructuredOutput (movieSchema , {
name : "movie" ,
method : "jsonSchema" ,
strict : true ,
} ) ;
多模态输入
OpenRouter 支持接受多模态输入的模型的 多模态输入 。可用的模态取决于您选择的模型——详情请查看 OpenRouter 模型页面 。
图像输入
使用列表内容格式提供图像输入和文本。
import { ChatOpenRouter } from "@langchain/openrouter" ;
import { HumanMessage } from "@langchain/core/messages" ;
const model = new ChatOpenRouter ( { model : "openai/gpt-4o" } ) ;
const message = new HumanMessage ( {
content : [
{ type : "text" , text : "Describe this image." },
{
type : "image_url" ,
image_url : {
url : "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" ,
},
},
] ,
} ) ;
const response = await model . invoke ([message]) ;
令牌使用量元数据
调用后,令牌使用量信息可在响应的 usage_metadata 属性上获取:
const aiMsg = await model . invoke ( "Tell me a joke." ) ;
console . log (aiMsg . usage_metadata) ;
{
input_tokens: 12,
output_tokens: 25,
total_tokens: 37
}
当底层提供商在其响应中包含详细的令牌细分时,它们会自动显示:
output_token_details.reasoning — 用于内部思维链推理的令牌
input_token_details.cache_read — 从提示缓存提供的输入令牌
流式传输时,从最后一个块聚合令牌使用量:
import { AIMessageChunk } from "@langchain/core/messages" ;
import { concat } from "@langchain/core/utils/stream" ;
const stream = await model . stream ( "Tell me a joke." ) ;
let finalMsg : AIMessageChunk | undefined ;
for await ( const chunk of stream) {
finalMsg = finalMsg ? concat (finalMsg , chunk) : chunk ;
}
console . log (finalMsg ?. usage_metadata) ;
提供商路由
OpenRouter 上的许多模型由多个提供商提供服务。provider 参数让您控制哪些提供商处理您的请求以及如何选择它们。
排序和过滤提供商
使用 order 设置首选提供商顺序。OpenRouter 按顺序尝试每个提供商,如果一个不可用则回退到下一个:
const model = new ChatOpenRouter ( {
model : "anthropic/claude-sonnet-4.5" ,
provider : {
order : [ "Anthropic" , "Google" ] ,
allow_fallbacks : true ,
},
} ) ;
要将请求限制为仅特定提供商,请使用 only。要排除某些提供商,请使用 ignore:
const onlyModel = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
provider : { only : [ "OpenAI" , "Azure" ] },
} ) ;
const ignoreModel = new ChatOpenRouter ( {
model : "meta-llama/llama-4-maverick" ,
provider : { ignore : [ "DeepInfra" ] },
} ) ;
按成本、速度或延迟排序
默认情况下,OpenRouter 在提供商之间进行负载平衡,优先选择成本较低的。使用 sort 更改优先级:
const fastModel = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
provider : { sort : "throughput" },
} ) ;
const lowLatencyModel = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
provider : { sort : "latency" },
} ) ;
数据收集策略
如果您的用例要求提供商不存储或训练您的数据,请将 data_collection 设置为 "deny":
const model = new ChatOpenRouter ( {
model : "anthropic/claude-sonnet-4.5" ,
provider : { data_collection : "deny" },
} ) ;
按量化过滤
对于开放权重模型,您可以将路由限制为特定精度级别:
const model = new ChatOpenRouter ( {
model : "meta-llama/llama-4-maverick" ,
provider : { quantizations : [ "fp16" , "bf16" ] },
} ) ;
组合选项
提供商选项可以组合在一起:
const model = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
provider : {
order : [ "OpenAI" , "Azure" ] ,
allow_fallbacks : false ,
require_parameters : true ,
data_collection : "deny" ,
},
} ) ;
有关选项的完整列表,请参阅 OpenRouter 提供商路由文档 。
多模型路由
OpenRouter 支持跨多个模型路由请求。传递一个 models 数组和一个可选的 route 策略:
const model = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
models : [ "openai/gpt-4o" , "anthropic/claude-sonnet-4.5" ] ,
route : "fallback" ,
} ) ;
OpenRouter 支持扩展模型能力的 插件 。通过 plugins 参数传递插件配置:
const model = new ChatOpenRouter ( {
model : "openai/gpt-4o" ,
plugins : [
{ id : "web" , max_results : 5 },
] ,
} ) ;
可用的插件包括 web(网络搜索)、file-parser(PDF 解析)、moderation、auto-router 和 response-healing。
应用归因
OpenRouter 通过 HTTP 头支持应用归因。通过构造函数参数设置这些:
const model = new ChatOpenRouter ( {
model : "anthropic/claude-sonnet-4.5" ,
siteUrl : "https://myapp.com" ,
siteName : "My App" ,
} ) ;
API 参考
有关所有 ChatOpenRouter 功能和配置的详细文档,请访问 ChatOpenRouter API 参考 。
有关 OpenRouter 平台、模型和功能的更多信息,请参阅 OpenRouter 文档 。
将这些文档连接 到 Claude、VSCode 等,通过 MCP 获取实时答案。