OpenRouter 發布 LangChain 專用套件與 ChatOpenRouter 設定指南
Using OpenRouter With LangChain: ChatOpenRouter Setup Guide
OpenRouter 正式推出 LangChain 專用套件 langchain-openrouter(Python)與 @langchain/openrouter(TypeScript),提供原生整合與自動跨供應商故障轉移能力。
原文詳述 LangChain 整合 OpenRouter 的專用套件設定方式與路由設定,開發者可據此評估如何直接呼叫多模型並啟用自動容錯。
譯文尚未完整,完整內容請切換至原文。
你想在不重建任何東西的情況下,將 OpenRouter 超過 400 個模型加入你現有的 LangChain 應用。整合現在有專用套件:langchain-openrouter 在 PyPI,@langchain/openrouter 在 npm,但許多舊指南仍教ChatOpenAI 加上 base_url 覆寫。這份指南涵蓋目前的路徑。
當你將 LangChain 鏈指向 ChatOpenRouter 時,我們的路由層會自動處理供應商負載平衡、斷線避免以及跨供應商失敗轉移。你的鏈程式碼永遠不會看到重試,且未完成的請求不會產生任何費用。LangChain 的檔案說明引數;本指南也涵蓋其背後的路由行為。

快速入門:5 分鐘內在 LangChain 應用中使用 OpenRouter
三步驟完成可用模型呼叫:安裝、驗證、呼叫。
OpenRouter 是一個模型路由器,背後僅有一個 OpenAI 相容 API:一個端點、超過 400 個模型、70+ 供應商。ChatOpenRouter 可像其他 LangChain 聊天模型一樣插入任何鏈或代理。模型字串是唯一的 OpenRouter 專屬專案。
步驟 1:安裝與驗證
安裝 langchain-openrouter 並將你的金鑰放入環境變數。於 openrouter.ai/settings/keys 產生金鑰。
pip install -U langchain-openrouter
export OPENROUTER_API_KEY="sk-or-..."使用 -U 旗標。該套件為測試版且更新迅速;請始終拉取最新。ChatOpenRouter 會自動從環境讀取 OPENROUTER_API_KEY。若你以不同方式管理機密,也可明確傳遞為 api_key。
步驟 2:例項化並呼叫
from langchain_openrouter import ChatOpenRouter
model = ChatOpenRouter(
model="anthropic/claude-sonnet-4.5",
temperature=0,
max_tokens=1024,
max_retries=2,
)
response = model.invoke("Summarize this support ticket in one sentence.")
print(response.content)temperature、max_tokens 與 max_retries 的行為與任何 LangChain 聊天模型完全相同。model 引數是我們在 provider/model 格式的 slug。
若你想在連線 LangChain 前確認金鑰是否有效,端點會直接使用 OpenAI 聊天格式:
curl https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.5",
"messages": [{"role": "user", "content": "Summarize this support ticket in one sentence."}]
}'相同金鑰、相同模型字串、相同回應結構。ChatOpenRouter 是該端點的型別化 LangChain 包裝器。
步驟 3:TypeScript
TypeScript 路徑與 @langchain/openrouter 的形狀相同:
import { ChatOpenRouter } from '@langchain/openrouter';
const model = new ChatOpenRouter('anthropic/claude-sonnet-4.5', {
temperature: 0.8,
});
const response = await model.invoke('Summarize this support ticket in one sentence.');
console.log(response.content);使用 npm install @langchain/openrouter 安裝。當前版本可於 npm 找到。
完整設定細節請參見 OpenRouter 的 LangChain 整合頁面 與 LangChain 的 ChatOpenRouter 參考。
選擇模型:供應商/模型字串
model 引數是 OpenRouter 的 slug,格式為 provider/model,切換模型只需改一個字串。鏈中其餘部分不變:提示、工具定義與輸出保持不變。
今天設定 model="anthropic/claude-sonnet-4.5",明天改為 openai/gpt-5-mini 或 deepseek/deepseek-r1,你的鏈仍保持不變。
從 openrouter.ai/models 抓取目前的 provider/model 字串。該頁面顯示可用模型、提供者及每個模型每標記的費用。此指南中的 slug 為示意,實際目錄為真實來源。
對於 LangChain 代理,存在一個簡寫,完全跳過建構子:
from langchain.agents import create_agent
agent = create_agent(model="openrouter:anthropic/claude-sonnet-4.5")openrouter:provider/model 字首告訴 create_agent 通過 ChatOpenRouter 解析。相同一字串切換,升一層。
串流回應
使用 stream_events 以在模型產生時即取得 token。非同步變體 astream_events 亦可於非同步鏈中執行相同功能。
串流的每標記費率與非串流呼叫相同。你串流是為了使用者體驗,而非計費。
for event in model.stream_events(
"Explain provider routing in three sentences.",
version="v3"
):
if event["event"] == "on_chat_model_stream":
print(event["data"]["chunk"].text, end="", flush=True)傳遞 version="v3" 以取得目前事件結構。非同步形式與 astream_events 及 async for 相同:
async for event in model.astream_events(
"Explain provider routing in three sentences.",
version="v3"
):
if event["event"] == "on_chat_model_stream":
print(event["data"]["chunk"].text, end="", flush=True)usage_metadata 可於最終聚合訊息中取得,因此你可在不發起第二次呼叫的情況下讀取 token 數量。
工具呼叫與結構化輸出
使用 bind_tools 進行工具呼叫,使用 with_structured_output 進行型別化回應。兩者皆接受 strict=True 以強制遵守 schema。strict 只與 function_calling 與 json_schema 方法配合,無法與 json_mode。
以 Pydantic schema 繫結工具
from pydantic import BaseModel, Field
class GetWeather(BaseModel):
"""Get the current weather for a city."""
city: str = Field(description="City name, e.g. 'Lisbon'")
model_with_tools = model.bind_tools([GetWeather], strict=True)
result = model_with_tools.invoke("What's the weather in Lisbon?")
print(result.tool_calls)strict=True 使模型遵循工具 schema,而非即興產生引數。
取得結構化輸出
with_structured_output 為整個回應繫結 schema:
class TicketSummary(BaseModel):
sentiment: str
priority: int
summary: str
structured = model.with_structured_output(TicketSummary, method="json_schema")
summary = structured.invoke("Customer is furious the export button is broken again.")
print(summary.priority, summary.summary)The default method is function_calling. Passing method="json_schema" uses native JSON-schema enforcement where the model supports it.
Not every model supports every method; check the model catalog for per-model capabilities. Setting require_parameters: true in the provider object (covered next) keeps requests on providers that honor the parameters you sent.
Provider routing and fallbacks
ChatOpenRouter exposes our routing layer through openrouter_provider and route, so a single chain can survive a provider going down with no extra resilience code in your app.
Here’s what happens by default when you make a call. We price-load-balance across the providers serving your chosen model and route away from any provider that had an outage in the last 30 seconds, using the rest as live fallbacks. Your chain code never sees the retry. A request that ultimately can’t be completed isn’t billed.
Steer providers with openrouter_provider
model = ChatOpenRouter(
model="anthropic/claude-sonnet-4.5",
openrouter_provider={
"order": ["Anthropic", "Google"],
"allow_fallbacks": True,
"data_collection": "deny",
"sort": "throughput",
},
)order sets your provider preference. allow_fallbacks: True lets us fall back past your preferred providers if they’re unavailable. sort accepts "throughput" or "latency" when speed matters more than price. data_collection: "deny" routes away from providers that train on your prompts. only and ignore allow or exclude specific providers. require_parameters: True keeps requests on providers that support the exact parameters you’re sending.
The full provider object reference is at openrouter.ai/docs/guides/routing/provider-selection.
Fail over across models, not just providers
Provider failover is on by default; route="fallback" states it explicitly. To also fail over to different models, pass a models array through model_kwargs and we try each model in sequence:
model = ChatOpenRouter(
model="anthropic/claude-sonnet-4.5",
route="fallback",
model_kwargs={
"models": [
"anthropic/claude-sonnet-4.5",
"openai/gpt-5-mini",
"google/gemini-3-flash-preview",
],
},
)models isn’t a named constructor argument, so it rides in model_kwargs, which forwards extra parameters to the API unchanged. If the primary can’t serve the request, we try the next provider, then the next model in the array. Pair the array with sort: {by, partition: "none"} in openrouter_provider to rank endpoints globally across all listed models rather than per-model.

Your LangChain chain points at one ChatOpenRouter, we spread the request across providers, and you’re billed only for the run that succeeds.
Reasoning, multimodal, caching, and observability
Each of these is one constructor or request parameter.
Reasoning
Set a reasoning budget with the reasoning parameter:
model = ChatOpenRouter(
model="anthropic/claude-sonnet-4.5",
reasoning={"effort": "high", "summary": "auto"},
)effort runs from xhigh down through high, medium, low, minimal, to none. Reasoning token counts appear in usage_metadata.output_token_details.reasoning, so you can see exactly what the thinking cost.
Multimodal inputs
Image, audio, video, and PDF inputs pass through HumanMessage content blocks, just as LangChain handles multimodal models. Which modalities are supported depends on the model; check the catalog for per-model capabilities.
Prompt caching
Drop a cache_control: {"type": "ephemeral"} breakpoint on a message content block to enable caching. Cache reads surface in usage_metadata.input_token_details.cache_read, so you can see the savings per call. The prompt caching guide covers the cost side.
Observability
Pass a session_id (up to 256 characters) to group related requests, and a trace object for per-request metadata. We forward both to your configured Broadcast destinations, so traces land in your existing stack without extra instrumentation.
None of these require changes to your chain structure; they’re constructor or request parameters that layer on top of whatever you’ve already built.
Common problems and how to fix them
Four problems come up often, and each has a fix.
Version compatibility on a beta package
langchain-openrouter 為近期版本並處於測試階段,因此需要使用最新版的 LangChain。它不向下相容舊版 LangChain。請鎖定 PyPI 上的版本,並同步升級 LangChain,避免從舊教程複製版本鎖定。
ChatOpenAI + base_url 模式
若使用的 LangChain 版本早於專用套件的發布,將 ChatOpenAI 的 base_url 指向 https://openrouter.ai/api/v1 並使用您的 OpenRouter 金鑰仍然有效。若無法升級,請使用此方法。使用最新版 LangChain 時,專用的 ChatOpenRouter 套件能更乾淨地存取提供者路由、推理與結構化輸出,但若目前設定運作正常,並非急需遷移。
模型每次回傳相同答案
若模型持續回傳相同回覆,通常是溫度或快取行為所致,而非缺陷。請設定非零溫度,並檢查提示快取是否啟用。
每個模型的引數支援
並非所有模型都支援所有可傳遞的引數。若不確定,請在 openrouter_provider 中設定 require_parameters: true,以便只路由至接受您引數的供應者,或先檢查目錄中的模型頁面。
統一使用 ChatOpenRouter 套件,從 PyPI 或 npm 鎖定其版本,並從 openrouter.ai/models 取得最新模型字串。設定 openrouter_provider 後,鏈中的每一次呼叫皆會自動繼承跨供應者失效轉移,只對成功執行的跑次計費。
常見問題
OpenRouter 與 LangChain 相同嗎?
不是。它們是協作而非競爭。OpenRouter 是一個模型供應商與路由器,位於單一 OpenAI 相容 API 之後,提供 400+ 模型來自 70+ 供應商。LangChain 是您構建鏈與代理的協調框架。您可透過 ChatOpenRouter 在 LangChain 中使用 OpenRouter 作為模型。
如何在 LangChain 中使用 OpenRouter?
安裝 langchain-openrouter,設定 OPENROUTER_API_KEY,並例項化 ChatOpenRouter(model="provider/model")。接著像任何 LangChain 聊天模型一樣呼叫 .invoke(...)、.stream_events(...)、.bind_tools(...) 或 .with_structured_output(...)。該套件仍為測試版;請從 PyPI 或 npm 鎖定版本。TypeScript 路徑使用 @langchain/openrouter,其結構相同。
LangChain 是否支援 OpenRouter 工具呼叫與結構化輸出?
是的。使用 model.bind_tools([...]) 進行工具呼叫,使用 model.with_structured_output(Schema, method="json_schema") 進行型別化回覆,兩者皆搭配 strict=True 以強制執行 schema。這些是目前 ChatOpenRouter 套件的首屈一指方法,取代舊版 JSON-schema 變通方案在遺留 ChatOpenAI 路徑上的做法。
我能否在 LangChain 中設定供應者路由或備援?
可以。傳遞 openrouter_provider={...} 以引導供應者,並傳遞 model_kwargs={"models": [...]} 以在模型間失效轉移。供應者失效轉移預設為啟用:OpenRouter 會依價格負載平衡,並在過去 30 秒內發生停機的供應者上路由。失敗的請求不計費;您只需為成功執行的跑次付費。
我還需要 ChatOpenAI + base_url 模式嗎?
在目前的 LangChain 中不需要。專用的 ChatOpenRouter 套件是目前的路徑,提供更乾淨的供應者路由、推理與結構化輸出存取。ChatOpenAI 的覆寫,將 base_url 指向 https://openrouter.ai/api/v1 並使用您的 OpenRouter 金鑰,仍可作為舊版 LangChain(早於套件發布)的備援方案。
我可以使用哪些模型?
目錄中 400+ 模型皆可使用,透過 provider/model slug。請檢視 openrouter.ai/models 以取得最新字串、各模型功能與價格。可用模型與每 token 的費率會變動,請以目錄為真實資料來源。
來源:openrouter blog · openrouter.ai