In the previous article, we learned how to create reusable prompts using PromptTemplate.
That approach works well for simple tasks like:
- Explaining a topic
- Translating text
- Generating interview questions
However, modern AI applications such as ChatGPT and Gemini are conversation-based rather than simple text prompts.
Instead of sending a single prompt, they exchange a sequence of messages.
This is where ChatPromptTemplate comes in.
It allows you to create structured conversations using different message roles.
In this article, you'll learn:
- What ChatPromptTemplate is
- Why it is useful
- PromptTemplate vs ChatPromptTemplate
- HumanMessage
- AIMessage
- SystemMessage
- Variables
- Multiple Variables
fromMessages()pipe()- OpenAI examples
- Gemini examples
Let's get started.
What is ChatPromptTemplate?
ChatPromptTemplate is used to create structured conversations for chat models.
Instead of one prompt string, it builds a sequence of messages.
System
↓
Human
↓
AI
↓
Human
↓
AI
Each message has a specific role.
Why Do We Need ChatPromptTemplate?
Suppose you write:
await model.invoke(
"Explain Node.js."
);
Now imagine you want the AI to behave like a senior backend engineer.
You would need to include additional instructions in every prompt.
With ChatPromptTemplate:
System:
You are a senior backend engineer.
Human:
Explain Node.js.
The conversation is structured, making prompts cleaner and easier to maintain.
PromptTemplate vs ChatPromptTemplate
PromptTemplate | ChatPromptTemplate
Single prompt | Multiple messages
Best for text generation | Best for conversations
No message roles | Supports message roles
Limited context | Designed for chat models
Import Required Modules
import "dotenv/config";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import {
HumanMessage,
AIMessage,
SystemMessage,
} from "@langchain/core/messages";
import { ChatOpenAI } from "@langchain/openai";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
Initialize OpenAI
const openAIModel = new ChatOpenAI({
model: "gpt-4.1-mini",
});
Initialize Gemini
const geminiModel =
new ChatGoogleGenerativeAI({
model: "gemini-2.5-flash",
});
Creating Your First ChatPromptTemplate
const prompt =
ChatPromptTemplate.fromMessages([
[
"human",
"Explain Node.js.",
],
]);
Format the messages:
const messages =
await prompt.formatMessages();
Invoke the model:
const response =
await openAIModel.invoke(messages);
console.log(response.content);
HumanMessage
A HumanMessage represents input from the user.
const message =
new HumanMessage(
"Explain React."
);
Equivalent conversation:
User:
Explain React.
Using HumanMessage
const response =
await geminiModel.invoke([
new HumanMessage(
"What is Express.js?"
),
]);
console.log(response.content);
AIMessage
An AIMessage represents a previous response from the AI.
const message =
new AIMessage(
"React is a JavaScript library."
);
This is useful when constructing or replaying conversations.
Using AIMessage
const response =
await openAIModel.invoke([
new HumanMessage(
"What is React?"
),
new AIMessage(
"React is a JavaScript library."
),
new HumanMessage(
"Who created it?"
),
]);
console.log(response.content);
The model understands that "it" refers to React.
SystemMessage
SystemMessage defines the AI's behavior.
new SystemMessage(
"You are a Node.js instructor."
)
Now every answer is generated from the perspective of a Node.js teacher.
AI Teacher Example
const response =
await openAIModel.invoke([
new SystemMessage(
"You are a Node.js instructor."
),
new HumanMessage(
"Explain Streams."
),
]);
console.log(response.content);
AI Interviewer Example
const response =
await geminiModel.invoke([
new SystemMessage(
"You are a senior frontend interviewer."
),
new HumanMessage(
"Ask me React interview questions."
),
]);
console.log(response.content);
Variables in ChatPromptTemplate
Variables work the same way as in PromptTemplate.
const prompt =
ChatPromptTemplate.fromMessages([
[
"system",
"You are a {role}.",
],
[
"human",
"Explain {topic}.",
],
]);
Invoke:
const messages =
await prompt.formatMessages({
role: "Backend Architect",
topic: "Node.js",
});
const response =
await openAIModel.invoke(messages);
console.log(response.content);
Multiple Variables
const prompt =
ChatPromptTemplate.fromMessages([
[
"system",
"You are a {role}.",
],
[
"human",
"Explain {topic} for a {level} developer.",
],
]);
Invoke:
const response =
await prompt
.pipe(openAIModel)
.invoke({
role: "Programming Teacher",
topic: "React",
level: "Beginner",
});
console.log(response.content);
Using pipe()
Without pipe():
const messages =
await prompt.formatMessages({
role: "Teacher",
topic: "Node.js",
});
const response =
await openAIModel.invoke(messages);
With pipe():
const chain =
prompt.pipe(openAIModel);
const response =
await chain.invoke({
role: "Teacher",
topic: "Node.js",
});
console.log(response.content);
The prompt is formatted automatically.
Real-World Example: AI Teacher
const prompt =
ChatPromptTemplate.fromMessages([
[
"system",
"You are a programming instructor.",
],
[
"human",
"{question}",
],
]);
const chain =
prompt.pipe(openAIModel);
const response =
await chain.invoke({
question:
"Explain the Event Loop.",
});
console.log(response.content);
Real-World Example: Customer Support Bot
const prompt =
ChatPromptTemplate.fromMessages([
[
"system",
"You are a customer support executive.",
],
[
"human",
"{question}",
],
]);
const chain =
prompt.pipe(geminiModel);
const response =
await chain.invoke({
question:
"I forgot my password.",
});
console.log(response.content);
Best Practices
- Use
SystemMessageto define the assistant's role. - Keep system instructions concise and focused.
- Use variables to make prompts reusable.
- Prefer
pipe()for cleaner composition. - Reuse templates instead of recreating them.
Common Beginner Mistakes
- Using
PromptTemplatefor chat applications. - Omitting the
SystemMessagewhen consistent behavior is required. - Hardcoding values instead of using variables.
- Recreating templates unnecessarily.
Final Thoughts
ChatPromptTemplate is the foundation of conversational AI in LangChain.js. By organizing prompts into structured messages with clear roles, you can build assistants that are easier to maintain, extend, and reuse.
Combined with variables and pipe(), it enables clean, flexible prompt design that works seamlessly with both OpenAI and Google Gemini.
Happy Coding! 🚀