Prompt templates allow you to construct messages dynamically with variable substitution, formatting, and composition. LangChain.js provides powerful prompt template abstractions for building maintainable and reusable prompts.
Prompt template classes are defined in @langchain/core/prompts
The most commonly used prompt template for chat models:
import { ChatPromptTemplate } from "@langchain/core/prompts";import { ChatOpenAI } from "@langchain/openai";const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant."], ["human", "Tell me a joke about {topic}"],]);const model = new ChatOpenAI({ model: "gpt-4o" });const chain = prompt.pipe(model);const result = await chain.invoke({ topic: "programming" });console.log(result.content);
const prompt = ChatPromptTemplate.fromTemplate( "Tell me a {adjective} joke about {topic}");const formatted = await prompt.invoke({ adjective: "funny", topic: "cats",});// "Tell me a funny joke about cats"
const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a {role}."], ["human", "My name is {name}"], ["ai", "Hello {name}! How can I help you today?"], ["human", "{user_input}"],]);const result = await prompt.invoke({ role: "helpful assistant", name: "Alice", user_input: "What's the weather?",});
import { ChatPromptTemplate, SystemMessagePromptTemplate,} from "@langchain/core/prompts";const systemTemplate = SystemMessagePromptTemplate.fromTemplate( "You are a {role} that specializes in {specialty}.");const prompt = ChatPromptTemplate.fromMessages([ systemTemplate, ["human", "{input}"],]);
import { AIMessagePromptTemplate } from "@langchain/core/prompts";const aiTemplate = AIMessagePromptTemplate.fromTemplate( "I understand you want to {task}. Let me help with that.");
import { ChatPromptTemplate, MessagesPlaceholder,} from "@langchain/core/prompts";import { HumanMessage, AIMessage } from "@langchain/core/messages";const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant."], new MessagesPlaceholder("chat_history"), ["human", "{input}"],]);const result = await prompt.invoke({ chat_history: [ new HumanMessage("Hi, I'm Alice"), new AIMessage("Hello Alice! Nice to meet you."), ], input: "What's my name?",});
Optional placeholders:
const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant."], new MessagesPlaceholder({ variableName: "chat_history", optional: true }), ["human", "{input}"],]);// Works without chat_historyconst result = await prompt.invoke({ input: "Hello" });
import { PromptTemplate } from "@langchain/core/prompts";const template = PromptTemplate.fromTemplate( "Write a {length} poem about {topic}.");const formatted = await template.invoke({ length: "short", topic: "the ocean",});// "Write a short poem about the ocean."
import { PromptTemplate } from "@langchain/core/prompts";const prompt = new PromptTemplate({ template: "Hello {{name}}, you are {{age}} years old.", templateFormat: "mustache", inputVariables: ["name", "age"],});
const prompt = ChatPromptTemplate.fromTemplate( "Tell me a {adjective} joke about {topic}");const partialPrompt = await prompt.partial({ adjective: "funny",});// Only need to provide topic nowconst result = await partialPrompt.invoke({ topic: "cats" });
With functions:
const prompt = ChatPromptTemplate.fromTemplate( "The current date is {date}. {input}");const partialPrompt = await prompt.partial({ date: () => new Date().toISOString(),});const result = await partialPrompt.invoke({ input: "What's today's date?",});
import { FewShotChatMessagePromptTemplate } from "@langchain/core/prompts";const examples = [ { input: "hi", output: "Hello! How can I help you?" }, { input: "bye", output: "Goodbye! Have a great day!" },];const examplePrompt = ChatPromptTemplate.fromTemplate( "Human: {input}\nAI: {output}");const fewShotPrompt = new FewShotChatMessagePromptTemplate({ examples, examplePrompt,});const finalPrompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant."], fewShotPrompt, ["human", "{input}"],]);
import { ChatPromptTemplate } from "@langchain/core/prompts";import { StringOutputParser } from "@langchain/core/output_parsers";import { ChatOpenAI } from "@langchain/openai";const prompt = ChatPromptTemplate.fromTemplate( "Tell me a joke about {topic}");const model = new ChatOpenAI({ model: "gpt-4o" });const outputParser = new StringOutputParser();const chain = prompt.pipe(model).pipe(outputParser);const result = await chain.invoke({ topic: "bears" });// Returns string directly instead of AIMessage
import { JsonOutputParser } from "@langchain/core/output_parsers";const parser = new JsonOutputParser();const prompt = ChatPromptTemplate.fromTemplate( `Extract the person's name and age from this text: {text} {format_instructions}`);const chain = prompt.pipe(model).pipe(parser);const result = await chain.invoke({ text: "John is 30 years old", format_instructions: parser.getFormatInstructions(),});// { name: "John", age: 30 }
const supportPrompt = ChatPromptTemplate.fromMessages([ ["system", `You are a customer support agent for {company}.Guidelines:- Be polite and professional- Address the customer by name: {customer_name}- Refer to order #{order_id} when relevant- If you can't help, escalate to human support`], new MessagesPlaceholder("chat_history"), ["human", "{input}"],]);
const codeReviewPrompt = ChatPromptTemplate.fromTemplate( `Review this {language} code and provide feedback.Focus areas:- Code quality and best practices- Potential bugs- Performance issues- Security concernsCode:\`\`\`{language}{code}\`\`\`Provide your review:`);
const researchPrompt = ChatPromptTemplate.fromMessages([ ["system", "You are a research assistant specializing in {field}."], ["human", `Research question: {question}Requirements:- Cite at least {min_sources} sources- Focus on publications from {start_year}-{end_year}- {additional_requirements}`],]);
// ✓ Good - Clear and specificconst prompt = ChatPromptTemplate.fromTemplate( "Summarize this article in 3-5 bullet points, focusing on key findings: {article}");// ✗ Avoid - Vagueconst prompt = ChatPromptTemplate.fromTemplate( "Summarize: {article}");
Use System Messages
Set the model’s behavior with system messages:
const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a concise assistant. Keep responses under 100 words."], ["human", "{input}"],]);
Provide Examples
Show the model what you want with few-shot examples:
const prompt = ChatPromptTemplate.fromMessages([ ["system", "Extract names from text."], ["human", "John and Mary went to the store."], ["ai", "Names: John, Mary"], ["human", "{input}"],]);
const prompt = ChatPromptTemplate.fromTemplate( "Hello {name}, your order #{order_id} is ready.");// Check required variables before invokingif (!input.name || !input.order_id) { throw new Error("Missing required variables");}