ChatOpenRouter 통합
ChatOpenRouter 통합
LangChain JavaScript로 ChatOpenRouter 채팅 모델과 통합하는 방법을 안내할게요.
출처: 문서
본문
이 문서는 OpenRouter 채팅 모델을 시작하는 데 도움을 줘요. OpenRouter는 여러 제공자(OpenAI, Anthropic, Google, Meta 등)의 모델에 단일 엔드포인트로 접근할 수 있게 하는 통합 API예요.
For detailed documentation of all features and configuration options, head to the ChatOpenRouter API reference.
사용 가능한 모델의 전체 목록은 OpenRouter 모델 페이지를 참고하세요.
개요
통합 세부 정보
| 클래스 | 패키지 | Serializable | PY 지원 | Downloads | Version |
|---|---|---|---|---|---|
ChatOpenRouter |
@langchain/openrouter |
✅ | ✅ |
모델 기능
| Tool calling | Structured output | Image input | Audio input | Video input | Token-level streaming | Token usage | Logprobs |
|---|---|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
설정
OpenRouter를 통해 모델에 접근하려면 OpenRouter 계정을 만들고 API 키를 받은 뒤 @langchain/openrouter 통합 패키지를 설치해야 해요.
자격 증명
OpenRouter 키 페이지로 이동해 가입하고 API 키를 생성하세요. 완료되면 OPENROUTER_API_KEY 환경 변수를 설정하세요:
export OPENROUTER_API_KEY="your-api-key"
선택적으로 다음 환경 변수를 설정해 LangSmith로 모델 호출 추적(tracing)을 활성화할 수 있어요:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
설치
LangChain OpenRouter 통합은 @langchain/openrouter 패키지에 있어요:
yarn add @langchain/openrouter @langchain/core
pnpm add @langchain/openrouter @langchain/core
인스턴스 생성
이제 모델을 인스턴스화할 수 있어요:
import { ChatOpenRouter } from "@langchain/openrouter";
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 : "");
}
Tool calling
OpenRouter는 OpenAI 호환 tool calling 형식을 사용해요. 도구와 그 인자를 설명하면, 모델이 호출할 도구와 해당 도구의 입력을 담은 JSON 객체를 반환하게 할 수 있어요.
도구 바인딩
ChatOpenRouter.bindTools와 함께 Zod 스키마, LangChain 도구, 또는 원시 함수 정의를 도구로 모델에 전달할 수 있어요. 내부적으로 이들은 OpenAI 도구 스키마로 변환되어 모든 모델 호출에 전달돼요.
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);
[
{
name: 'get_weather',
args: { location: 'San Francisco, CA' },
id: 'call_abc123',
type: 'tool_call'
}
]
엄격 모드 (Strict mode)
도구 정의에 제공된 JSON Schema와 모델 출력이 정확히 일치하도록 보장하려면 strict: true를 전달하세요:
const modelWithStrictTools = new ChatOpenRouter({
model: "openai/gpt-4o",
}).bindTools([getWeather], { strict: true });
도구 바인딩 및 tool call 출력에 대한 자세한 내용은 tool calling 문서를 참고하세요.
구조화된 출력 (Structured output)
ChatOpenRouter는 .withStructuredOutput() 메서드를 통해 구조화된 출력을 지원해요. 추출 전략은 모델 기능에 따라 자동으로 선택돼요:
jsonSchema— 네이티브 JSON Schema 응답 형식 (모델이 지원할 때 사용)functionCalling— 스키마를 tool call로 감싸기 (기본 대체)jsonMode— 엄격한 스키마 제약 없이 JSON으로 응답하도록 모델에 요청
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);
{
title: 'Inception',
year: 2010,
director: 'Christopher Nolan',
rating: 8.8
}
jsonSchema 및 functionCalling 메서드와 함께 strict: true를 전달해 정확한 스키마 준수를 강제할 수 있어요:
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]);
```typescript Base64 encoded 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]);
토큰 사용량 메타데이터
호출 후 토큰 사용량 정보는 응답의 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— 내부 chain-of-thought 추론에 사용된 토큰input_token_details.cache_read— 프롬프트 캐시에서 제공된 입력 토큰
스트리밍 시 마지막 청크에서 집계된 토큰 사용량을 얻으세요:
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는 순서대로 각 제공자를 시도하고, 하나가 사용 불가하면 다음으로 폴백해요:
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을 "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"] },
});
옵션 결합
제공자 옵션은 함께 구성할 수 있어요:
const model = new ChatOpenRouter({
model: "openai/gpt-4o",
provider: {
order: ["OpenAI", "Azure"],
allow_fallbacks: false,
require_parameters: true,
data_collection: "deny",
},
});
전체 옵션 목록은 OpenRouter 제공자 라우팅 문서를 참고하세요.
멀티 모델 라우팅
OpenRouter는 여러 모델에 걸친 요청 라우팅을 지원해요. models 배열과 선택적 route 전략을 전달하세요:
const model = new ChatOpenRouter({
model: "openai/gpt-4o",
models: ["openai/gpt-4o", "anthropic/claude-sonnet-4.5"],
route: "fallback",
});
플러그인
OpenRouter는 모델 기능을 확장하는 플러그인을 지원해요. plugins 매개변수로 플러그인 구성을 전달하세요:
const model = new ChatOpenRouter({
model: "openai/gpt-4o",
plugins: [
{ id: "web", max_results: 5 },
],
});
사용 가능한 플러그인에는 web(웹 검색), file-parser(PDF 파싱), moderation, auto-router, response-healing이 있어요.
앱 귀속 (App attribution)
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 문서를 참고하세요.
더 알아보기
- 이 문서를 MCP로 연결하면 Claude, VSCode 등에서 실시간 답변을 받을 수 있어요.
- GitHub에서 이 페이지 편집하기 또는 이슈 제출하기.