Introduction
In the previous article, we learned how to set up LangChain.js and build our first AI application.
We initialized both OpenAI and Google Gemini models and generated our first AI response.
However, we only scratched the surface.
To build production-ready AI applications, you need to understand Chat Models in detail.
In this article, you'll learn:
- What Chat Models are
- How Chat Models work
- Model configuration
- Temperature
- Max Tokens
- Timeout
- Retries
- invoke()
- batch()
- stream()
- OpenAI examples
- Gemini examples
- Best practices
Let's get started.
What is a Chat Model?
A Chat Model is a language model optimized for conversations.
Instead of generating plain text from a single prompt, it processes a sequence of messages and produces an AI response.
Examples include:
- OpenAI GPT
- Google Gemini
- Anthropic Claude
In LangChain, every chat model follows the same interface.
User Message
↓
Chat Model
↓
AI Response
This consistency is one of LangChain's biggest strengths.
Why Use Chat Models?
Imagine you're building:
- AI Chatbot
- AI Teacher
- Customer Support Assistant
- Coding Assistant
These applications involve conversations, not isolated prompts.
Chat models understand conversational context and message roles, making them ideal for these use cases.
Project Setup
Install the required packages:
npm install langchain @langchain/openai @langchain/google-genai dotenv
Project structure:
langchain-chat-models/
│
├── index.js
├── .env
└── package.json
Configure Environment Variables
OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key
Initialize OpenAI
import "dotenv/config";
import { ChatOpenAI } from "@langchain/openai";
const openAIModel = new ChatOpenAI({
model: "gpt-4.1-mini",
temperature: 0.7,
});
Initialize Gemini
import "dotenv/config";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
const geminiModel = new ChatGoogleGenerativeAI({
model: "gemini-2.5-flash",
temperature: 0.7,
});
Understanding Model Configuration
A chat model accepts several configuration options.
const model = new ChatOpenAI({
model: "gpt-4.1-mini",
temperature: 0.7,
});
Let's understand each one.
model
model: "gpt-4.1-mini"
This specifies which AI model to use.
Different models vary in:
- Speed
- Cost
- Context window
- Reasoning ability
Choose the model that best matches your application's needs.
temperature
Temperature controls randomness.
temperature: 0
Produces consistent and deterministic responses.
Good for:
- Coding
- Documentation
- Question answering
temperature: 1
Produces more creative and varied responses.
Good for:
- Story writing
- Marketing copy
- Brainstorming
timeout
You can specify how long the request should wait.
const model = new ChatOpenAI({
model: "gpt-4.1-mini",
timeout: 30000,
});
This waits up to 30 seconds before timing out.
maxRetries
Network requests may occasionally fail.
const model = new ChatOpenAI({
model: "gpt-4.1-mini",
maxRetries: 2,
});
LangChain automatically retries failed requests.
Your First Request (invoke)
The invoke() method sends a single request to the model.
OpenAI:
const response = await openAIModel.invoke(
"What is Node.js?"
);
console.log(response.content);
Gemini:
const response = await geminiModel.invoke(
"What is Node.js?"
);
console.log(response.content);
invoke() is the most commonly used method when working with chat models.
Processing Multiple Requests (batch)
Suppose you need to generate multiple responses.
Instead of calling invoke() repeatedly:
await model.invoke("React");
await model.invoke("Node");
await model.invoke("Express");
Use batch():
const responses = await openAIModel.batch([
"What is React?",
"What is Node.js?",
"What is Express.js?",
]);
responses.forEach((response) => {
console.log(response.content);
});
Gemini works the same way:
const responses = await geminiModel.batch([
"What is JavaScript?",
"What is TypeScript?",
]);
responses.forEach((response) => {
console.log(response.content);
});
Use batch() when processing multiple independent prompts.
Streaming Responses (stream)
Normally, invoke() waits for the complete response.
Streaming returns chunks as they are generated.
Thinking...
↓
Hello
↓
Hello World
OpenAI:
const stream = await openAIModel.stream(
"Explain JavaScript."
);
for await (const chunk of stream) {
process.stdout.write(chunk.content);
}
Gemini:
const stream = await geminiModel.stream(
"Explain Node.js."
);
for await (const chunk of stream) {
process.stdout.write(chunk.content);
}
Streaming is ideal for chat interfaces where users expect responses to appear progressively.
Real-World Example
Imagine you're building an AI coding assistant.
- Use
invoke()when the user asks one programming question. - Use
batch()to generate explanations for several concepts at once. - Use
stream()to display code suggestions progressively in the editor.
Choosing the right method improves both performance and user experience.
Best Practices
- Reuse model instances instead of creating a new one for every request.
- Store API keys in environment variables.
- Choose an appropriate temperature for your use case.
- Use
stream()for conversational interfaces. - Wrap API calls in
try...catchto handle errors gracefully.
Common Beginner Mistakes
- Creating a new model instance for every request.
- Setting a very high temperature when deterministic answers are needed.
- Using
invoke()repeatedly instead ofbatch()for bulk tasks. - Forgetting to consume streams with
for await...of. - Hardcoding API keys.
Final Thoughts
Chat Models are the core of every LangChain application. They provide a unified interface for interacting with different AI providers while supporting powerful features like configuration, batching, and streaming.
In this article, you learned:
- What Chat Models are
- How to configure OpenAI and Gemini
- How to use
invoke() - How to use
batch() - How to use
stream() - Best practices for production applications
With these fundamentals in place, you're ready to move on to Prompt Templates and start building reusable AI workflows.
Happy Coding! 🚀