> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/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:
      "You are a helpful assistant that translates English to French. Translate the user sentence.",
  },
  {
    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("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 工具模式，并在每次模型调用时传入。

```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: "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);
```

```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 Schema 响应格式（当模型支持时使用）
* **`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-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", // [!code highlight]
});
const response = await structuredModel.invoke(
  "Provide details about the movie Inception"
);
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: "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]);
  ```

  ```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: "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]);
  ```
</CodeGroup>

***

## 令牌使用量元数据

调用后，令牌使用量信息可在响应的 `usage_metadata` 属性上获取：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const aiMsg = await model.invoke("Tell me a joke.");
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("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 按顺序尝试每个提供商，如果一个不可用则回退到下一个：

```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="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/chat/openrouter.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
