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

# ChatOpenRouter 集成

> 使用 LangChain JavaScript 集成 ChatOpenRouter 对话模型。

这将帮助您开始使用 OpenRouter [对话模型](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md)。OpenRouter 是一个统一的 API，通过单个端点提供对来自多个提供者（OpenAI、Anthropic、Google、Meta 等）的模型的访问。

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

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

## 概述

### 集成详情

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

### 模型功能

| [工具调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) | [结构化输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output.md) | [图像输入](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态) | 音频输入 | 视频输入 | [Token 级流式输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/streaming.md) | [Token 使用情况](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#token-使用) | [Logprobs](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#对数概率) |
| :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |

## 设置

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

### 凭证

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

```bash theme={null}
export OPENROUTER_API_KEY="your-api-key"
```

要启用模型调用的自动跟踪，请设置您的 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```bash theme={null}
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
```

### 安装

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

```bash npm theme={null}
npm install @langchain/openrouter @langchain/core
```

```bash yarn theme={null}
yarn add @langchain/openrouter @langchain/core
```

```bash pnpm theme={null}
pnpm add @langchain/openrouter @langchain/core
```

## 实例化

现在您可以实例化模型：

```typescript theme={null}
import { ChatOpenRouter } from "@langchain/openrouter";

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

***

## 调用

```typescript theme={null}
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={null}
J'adore la programmation.
```

***

## 流式输出

```typescript theme={null}
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={null}
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={null}
[
  {
    name: 'get_weather',
    args: { location: 'San Francisco, CA' },
    id: 'call_abc123',
    type: 'tool_call'
  }
]
```

### 严格模式

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

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

有关绑定工具和工具调用输出的更多信息，请访问 [工具调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) 文档。

***

## 结构化输出

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

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

> [!NOTE]
>
> 当多模型路由处于活动状态（`models` 列表或 `route: "fallback"`），该方法始终回退到 `functionCalling`，因为实际后端模型的功能在请求时未知。

```typescript theme={null}
import { ChatOpenRouter } from "@langchain/openrouter";
import { z } from "zod";

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

```text theme={null}
{
  title: 'Inception',
  year: 2010,
  director: 'Christopher Nolan',
  rating: 8.8
}
```

您可以使用 `strict: true` 与 `jsonSchema` 和 `functionCalling` 方法传递，以强制执行精确的模式遵循：

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

***

## 多模态输入

OpenRouter 支持对接受它们的模型进行 [多模态输入](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态)。可用的模态取决于您选择的模型—请查看 [OpenRouter 模型页面](https://openrouter.ai/models) 获取详细信息。

> [!NOTE]
>
> 并非所有模型都支持所有模态。请查看 [OpenRouter 模型页面](https://openrouter.ai/models) 获取模型特定的支持信息。

### 图像输入

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

```typescript URL theme={null}
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 encoded theme={null}
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]);
```

***

## Token 使用元数据

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

```typescript theme={null}
const aiMsg = await model.invoke("Tell me a joke.");
console.log(aiMsg.usage_metadata);
```

```text theme={null}
{
  input_tokens: 12,
  output_tokens: 25,
  total_tokens: 37
}
```

当底层提供者在响应中包含详细的 token 细分时，它们将自动显示：

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

流式输出时，从最终块聚合 token 使用情况：

```typescript theme={null}
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={null}
const model = new ChatOpenRouter({
  model: "anthropic/claude-sonnet-4.5",
  provider: {
    order: ["Anthropic", "Google"],
    allow_fallbacks: true,
  },
});
```

要仅限制对特定提供者的请求，请使用 `only`。要排除某些提供者，请使用 `ignore`：

```typescript theme={null}
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={null}
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={null}
const model = new ChatOpenRouter({
  model: "anthropic/claude-sonnet-4.5",
  provider: { data_collection: "deny" },
});
```

### 按量化过滤

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

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

### 组合选项

提供者选项可以组合在一起：

```typescript theme={null}
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={null}
const model = new ChatOpenRouter({
  model: "openai/gpt-4o",
  models: ["openai/gpt-4o", "anthropic/claude-sonnet-4.5"],
  route: "fallback",
});
```

***

## 插件

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

```typescript theme={null}
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={null}
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)。

***

> 官方原文：[src/oss/javascript/integrations/chat/openrouter.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/chat/openrouter.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.