以编程方式使用文档

这将帮助你开始使用 OpenRouter 聊天模型。OpenRouter 是一个统一 API,通过单一端点提供对多个提供商模型(OpenAI、Anthropic、Google、Meta 等)的访问。

有关可用模型的完整列表,请访问 OpenRouter 模型页面.

概述

集成详情

可序列化PY 支持下载量版本
ChatOpenRouter@langchain/openrouter!NPM - 下载量!NPM - 版本

模型特性

工具调用结构化输出图像输入音频输入视频输入Token 级流式输出Token 使用量对数概率

设置

要通过 OpenRouter 访问模型,你需要创建一个 OpenRouter 账户、获取一个 API 密钥,并安装 @langchain/openrouter 集成包。

凭证

访问 OpenRouter 密钥页面 注册并生成 API 密钥。完成此操作后,设置 OPENROUTER_API_KEY 环境变量:

要启用模型调用的自动追踪,请设置你的 LangSmith API 密钥:

# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

安装

LangChain OpenRouter 集成位于 @langchain/openrouter package:

npm install @langchain/openrouter @langchain/core
yarn add @langchain/openrouter @langchain/core
pnpm add @langchain/openrouter @langchain/core

实例化

现在你可以实例化模型:

const model = new ChatOpenRouter({
  model: "anthropic/claude-sonnet-4.5",
  temperature: 0,
  maxTokens: 1024,
  // other params...
});

调用

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 schema、LangChain 工具或原始函数定义作为工具传递给模型。在底层,这些会被转换为 OpenAI 工具 schema 并在每次模型调用时传入。

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 Schema 完全匹配:

const modelWithStrictTools = new ChatOpenRouter({
  model: "openai/gpt-4o",
}).bindTools([getWeather], { strict: true });

关于绑定工具和工具调用输出的更多信息,请前往 工具调用 docs.

结构化输出

ChatOpenRouter 支持通过以下方式实现结构化输出 .withStructuredOutput() 方法。提取策略会根据模型能力自动选择:

  • - **jsonSchema**—原生 JSON Schema 响应格式(当模型支持时使用)
  • - **functionCalling**—将模式包装为工具调用(默认回退)
  • - **jsonMode**—要求模型以 JSON 格式响应,但不做严格的模式约束
const model = new ChatOpenRouter({ model: "openai/gpt-5.5" });

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", // [!code highlight]
});
const response = await structuredModel.invoke(
  "Provide details about the movie Inception"
);
console.log(response);
{
  title: 'Inception',
  year: 2010,
  director: 'Christopher Nolan',
  rating: 8.8
}

您可以传递 strict: truejsonSchemafunctionCalling 方法配合使用,以强制精确的模式遵循:

const strictModel = model.withStructuredOutput(movieSchema, {
  name: "movie",
  method: "jsonSchema",
  strict: true,
});

多模态输入

OpenRouter 支持 多模态输入 对于支持它们的模型。可用的模态取决于您选择的模型——请查看 OpenRouter 模型页面 了解详情。

图像输入

使用列表内容格式提供图像输入以及文本。

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]);
const model = new ChatOpenRouter({ model: "openai/gpt-4o" });

const imageData = fs.readFileSync("/path/to/image.jpg").toString("base64");

const message = new HumanMessage({
  content: [
    { type: "text", text: "Describe this image." },
    {
      type: "image_url", // [!code highlight]
      image_url: { // [!code highlight]
        url: `data:image/jpeg;base64,${imageData}`, // [!code highlight]
      }, // [!code highlight]
    },
  ],
});
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—从提示缓存中服务的输入令牌

流式传输时,从最后一个数据块中汇总令牌使用情况:

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 to "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"] },
});

组合选项

Provider 选项可以组合在一起:

const model = new ChatOpenRouter({
  model: "openai/gpt-4o",
  provider: {
    order: ["OpenAI", "Azure"],
    allow_fallbacks: false,
    require_parameters: true,
    data_collection: "deny",
  },
});

请参阅 OpenRouter Provider 路由文档 获取完整的选项列表。

多模型路由

OpenRouter 支持跨多个模型路由请求。传递一个 models 数组和一个可选的 route strategy:

const model = new ChatOpenRouter({
  model: "openai/gpt-4o",
  models: ["openai/gpt-4o", "anthropic/claude-sonnet-4.5"],
  route: "fallback",
});

插件

OpenRouter 支持 插件 可扩展模型能力。通过 plugins parameter:

const model = new ChatOpenRouter({
  model: "openai/gpt-4o",
  plugins: [
    { id: "web", max_results: 5 },
  ],
});

可用的插件包括 web (网络搜索), file-parser (PDF 解析), moderation, auto-routerresponse-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 文档.