> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# ChatOpenRouter 集成

> 使用 LangChain JavaScript 集成 ChatOpenRouter 聊天模型。

本文将帮助您开始使用 OpenRouter [聊天模型](/oss/javascript/langchain/models)。OpenRouter 是一个统一的 API，通过单一端点提供对多个提供商（OpenAI、Anthropic、Google、Meta 等）模型的访问。

<Tip>
  **API 参考**

  有关所有功能和配置选项的详细文档，请访问 [ChatOpenRouter API 参考](https://reference.langchain.com/javascript/langchain-openrouter/ChatOpenRouter)。
</Tip>

有关可用模型的完整列表，请访问 [OpenRouter 模型页面](https://openrouter.ai/models)。

## 概述

### 集成详情

| 类                                                                                                  | 包                                                                              | 可序列化 | [Python 支持](/oss/javascript/integrations/chat/openrouter) |                                                  下载量                                                  |                                                 版本                                                 |
| :------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- | :--: | :-------------------------------------------------------: | :---------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------: |
| [`ChatOpenRouter`](https://reference.langchain.com/javascript/langchain-openrouter/ChatOpenRouter) | [`@langchain/openrouter`](https://www.npmjs.com/package/@langchain/openrouter) |   ✅  |                             ✅                             | ![NPM - Downloads](https://img.shields.io/npm/dm/@langchain/openrouter?style=flat-square\&label=%20&) | ![NPM - Version](https://img.shields.io/npm/v/@langchain/openrouter?style=flat-square\&label=%20&) |

### 模型特性

| [工具调用](/oss/javascript/langchain/tools) | [结构化输出](/oss/javascript/langchain/structured-output) | [图像输入](/oss/javascript/langchain/messages#multimodal) | 音频输入 | 视频输入 | [令牌级流式传输](/oss/javascript/langchain/streaming/) | [令牌使用量](/oss/javascript/langchain/models#token-usage) | [对数概率](/oss/javascript/langchain/models#log-probabilities) |
| :-------------------------------------: | :--------------------------------------------------: | :---------------------------------------------------: | :--: | :--: | :---------------------------------------------: | :---------------------------------------------------: | :--------------------------------------------------------: |
|                    ✅                    |                           ✅                          |                           ✅                           |   ✅  |   ✅  |                        ✅                        |                           ✅                           |                              ✅                             |

## 设置

要通过 OpenRouter 访问模型，您需要创建一个 [OpenRouter 账户](https://openrouter.ai/)，获取 API 密钥，并安装 `@langchain/openrouter` 集成包。

### 凭证

前往 [OpenRouter 密钥页面](https://openrouter.ai/settings/keys) 注册并生成 API 密钥。完成后，设置 `OPENROUTER_API_KEY` 环境变量：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export OPENROUTER_API_KEY="your-api-key"
```

要启用模型调用的自动追踪，请设置您的 [LangSmith](/langsmith/home) API 密钥：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
```

### 安装

LangChain OpenRouter 集成位于 `@langchain/openrouter` 包中：

<CodeGroup>
  ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  npm install @langchain/openrouter @langchain/core
  ```

  ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add @langchain/openrouter @langchain/core
  ```

  ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pnpm add @langchain/openrouter @langchain/core
  ```
</CodeGroup>

## 实例化

现在我们可以实例化模型对象并生成聊天补全：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ChatOpenRouter } from "@langchain/openrouter";

const model = new ChatOpenRouter({
  model: "anthropic/claude-sonnet-4.5",
  temperature: 0,
  maxTokens: 1024,
  // 其他参数...
});
```

***

## 调用

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const aiMsg = await model.invoke([
  {
    role: "system",
    content:
      "你是一个将英语翻译成法语的助手。翻译用户的句子。",
  },
  {
    role: "user",
    content: "I love programming.",
  },
]);
console.log(aiMsg.content);
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
J'adore la programmation.
```

***

## 流式传输

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const stream = await model.stream("写一首关于大海的短诗。");
for await (const chunk of stream) {
  process.stdout.write(typeof chunk.content === "string" ? chunk.content : "");
}
```

***

## 工具调用

OpenRouter 使用与 OpenAI 兼容的工具调用格式。您可以描述工具及其参数，让模型返回一个包含要调用的工具及其输入参数的 JSON 对象。

### 绑定工具

使用 `ChatOpenRouter.bindTools`，您可以将 Zod 模式、LangChain 工具或原始函数定义作为工具传递给模型。在底层，这些会被转换为 OpenAI 工具模式，并在每次模型调用时传入。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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: "获取指定地点的当前天气",
  schema: z.object({
    location: z
      .string()
      .describe("城市和州，例如：San Francisco, CA"),
  }),
});

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

const aiMsg = await modelWithTools.invoke(
  "旧金山的天气怎么样？"
);
console.log(aiMsg.tool_calls);
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[
  {
    name: 'get_weather',
    args: { location: 'San Francisco, CA' },
    id: 'call_abc123',
    type: 'tool_call'
  }
]
```

### 严格模式

传递 `strict: true` 以确保模型输出与工具定义中提供的 JSON 模式完全匹配：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const modelWithStrictTools = new ChatOpenRouter({
  model: "openai/gpt-4o",
}).bindTools([getWeather], { strict: true });
```

有关绑定工具和工具调用输出的更多信息，请参阅 [工具调用](/oss/javascript/langchain/tools) 文档。

***

## 结构化输出

`ChatOpenRouter` 通过 `.withStructuredOutput()` 方法支持结构化输出。提取策略根据模型能力自动选择：

* **`jsonSchema`** — 原生 JSON 模式响应格式（当模型支持时使用）
* **`functionCalling`** — 将模式包装为工具调用（默认回退）
* **`jsonMode`** — 要求模型以 JSON 格式响应，没有严格的模式约束

<Note>
  当多模型路由激活时（`models` 列表或 `route: "fallback"`），该方法总是回退到 `functionCalling`，因为实际后端模型的能力在请求时是未知的。
</Note>

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { ChatOpenRouter } from "@langchain/openrouter";
import { z } from "zod";

const model = new ChatOpenRouter({ model: "openai/gpt-4.1" });

const movieSchema = z.object({
  title: z.string().describe("电影标题"),
  year: z.number().describe("电影上映年份"),
  director: z.string().describe("电影导演"),
  rating: z.number().describe("电影的评分（满分10分）"),
});

const structuredModel = model.withStructuredOutput(movieSchema, {
  name: "movie",
  method: "jsonSchema", // [!code highlight]
});
const response = await structuredModel.invoke(
  "提供电影《盗梦空间》的详细信息"
);
console.log(response);
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  title: 'Inception',
  year: 2010,
  director: 'Christopher Nolan',
  rating: 8.8
}
```

您可以在 `jsonSchema` 和 `functionCalling` 方法中传递 `strict: true` 以强制完全遵循模式：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const strictModel = model.withStructuredOutput(movieSchema, {
  name: "movie",
  method: "jsonSchema",
  strict: true,
});
```

***

## 多模态输入

OpenRouter 支持接受多模态输入的模型进行 [多模态输入](/oss/javascript/langchain/messages#multimodal)。可用的模态取决于您选择的模型 — 请查看 [OpenRouter 模型页面](https://openrouter.ai/models) 了解详情。

<Note>
  并非所有模型都支持所有模态。请查看 [OpenRouter 模型页面](https://openrouter.ai/models) 了解特定模型的支持情况。
</Note>

### 图像输入

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

<CodeGroup>
  ```typescript URL theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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: "描述这张图片。" },
      {
        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]);
  ```

  ```typescript Base64 编码 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import { ChatOpenRouter } from "@langchain/openrouter";
  import { HumanMessage } from "@langchain/core/messages";
  import * as fs from "node:fs";

  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: "描述这张图片。" },
      {
        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]);
  ```
</CodeGroup>

***

## 令牌使用量元数据

调用后，令牌使用量信息可在响应的 `usage_metadata` 属性中找到：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const aiMsg = await model.invoke("讲个笑话。");
console.log(aiMsg.usage_metadata);
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  input_tokens: 12,
  output_tokens: 25,
  total_tokens: 37
}
```

当底层提供商在其响应中包含详细的令牌细分时，它们会自动显示：

* `output_token_details.reasoning` — 用于内部思维链推理的令牌
* `input_token_details.cache_read` — 从提示缓存中提供的输入令牌

流式传输时，从最终块中聚合令牌使用量：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { AIMessageChunk } from "@langchain/core/messages";
import { concat } from "@langchain/core/utils/stream";

const stream = await model.stream("讲个笑话。");
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 按顺序尝试每个提供商，如果某个提供商不可用，则回退到下一个：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const model = new ChatOpenRouter({
  model: "anthropic/claude-sonnet-4.5",
  provider: {
    order: ["Anthropic", "Google"],
    allow_fallbacks: true,
  },
});
```

要仅将请求限制在特定提供商，请使用 `only`。要排除某些提供商，请使用 `ignore`：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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` 更改优先级：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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"`：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const model = new ChatOpenRouter({
  model: "anthropic/claude-sonnet-4.5",
  provider: { data_collection: "deny" },
});
```

### 按量化筛选

对于开放权重模型，您可以限制路由到特定的精度级别：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const model = new ChatOpenRouter({
  model: "meta-llama/llama-4-maverick",
  provider: { quantizations: ["fp16", "bf16"] },
});
```

### 组合选项

提供商选项可以组合使用：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const model = new ChatOpenRouter({
  model: "openai/gpt-4o",
  provider: {
    order: ["OpenAI", "Azure"],
    allow_fallbacks: false,
    require_parameters: true,
    data_collection: "deny",
  },
});
```

有关完整选项列表，请参阅 [OpenRouter 提供商路由文档](https://openrouter.ai/docs/guides/routing/provider-selection)。

***

## 多模型路由

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

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const model = new ChatOpenRouter({
  model: "openai/gpt-4o",
  models: ["openai/gpt-4o", "anthropic/claude-sonnet-4.5"],
  route: "fallback",
});
```

***

## 插件

OpenRouter 支持扩展模型功能的 [插件](https://openrouter.ai/docs/features/plugins)。通过 `plugins` 参数传递插件配置：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 标头支持应用归属。通过构造函数参数设置这些：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const model = new ChatOpenRouter({
  model: "anthropic/claude-sonnet-4.5",
  siteUrl: "https://myapp.com",
  siteName: "My App",
});
```

***

## API 参考

有关 `ChatOpenRouter` 所有功能和配置的详细文档，请访问 [ChatOpenRouter API 参考](https://reference.langchain.com/javascript/langchain-openrouter/ChatOpenRouter)。

有关 OpenRouter 平台、模型和功能的更多信息，请参阅 [OpenRouter 文档](https://openrouter.ai/docs)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\javascript\integrations\chat\openrouter.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
