LangChain

Using OpenRouter with LangChain

Using LangChain

1import { ChatOpenAI } from "@langchain/openai";
2import { HumanMessage, SystemMessage } from "@langchain/core/messages";
3
4const chat = new ChatOpenAI(
5 {
6 model: '<model_name>',
7 temperature: 0.8,
8 streaming: true,
9 apiKey: '${API_KEY_REF}',
10 },
11 {
12 baseURL: 'https://openrouter.ai/api/v1',
13 defaultHeaders: {
14 'HTTP-Referer': '<YOUR_SITE_URL>', // Optional. Site URL for rankings on openrouter.ai.
15 'X-Title': '<YOUR_SITE_NAME>', // Optional. Site title for rankings on openrouter.ai.
16 },
17 },
18);
19
20// Example usage
21const response = await chat.invoke([
22 new SystemMessage("You are a helpful assistant."),
23 new HumanMessage("Hello, how are you?"),
24]);