AI Agents LangGraph
Prompt Templates
Intermediate
This post explores
Prompt Templates in LangGraph and LangChain
, including static and dynamic templates, template variables, reusable prompt components, and template composition. We cover tools like
ChatPromptTemplate
,
HumanMessagePromptTemplate
,
SystemMessagePromptTemplate
, and
FewShotPromptTemplate
, along with prompt formatting strategies, common mistakes, and best practices for building clean, reusable, and maintainable prompts.
What Are Prompt Templates?
Prompt Templates are reusable, structured blueprints for creating prompts. Instead of writing raw strings every time, you define a template with placeholders (variables) that can be filled dynamically at runtime.
They are one of the most powerful tools in LangChain/LangGraph for building consistent, maintainable, and scalable AI applications.
from langchain_core.prompts import ChatPromptTemplate
template = ChatPromptTemplate.from_template(
"You are a helpful assistant. Answer the following question: {question}"
)
prompt = template.invoke({"question": "What is LangGraph?"})
Static vs Dynamic Templates
Static Templates
Fixed content with no variables.
static_prompt = SystemMessage(content="You are an expert LangGraph developer.")
Dynamic Templates (Recommended)
Use variables for flexible, reusable prompts.
dynamic_template = ChatPromptTemplate.from_template(
"""You are an expert AI assistant specialized in {domain}.
User Query: {query}
Context: {context}
Provide a detailed and accurate answer."""
)
prompt_value = dynamic_template.invoke({
"domain": "LangGraph",
"query": "How do reducers work?",
"context": "Reducers merge state updates..."
})
Template Variables
Variables are defined using curly braces {variable_name}.
from langchain_core.prompts import ChatPromptTemplate
prompt_template = ChatPromptTemplate.from_messages([
("system", "You are a {role} with expertise in {expertise}."),
("human", "{user_input}"),
("ai", "{previous_response}")
])
formatted = prompt_template.invoke({
"role": "senior technical writer",
"expertise": "LangGraph",
"user_input": "Explain state management",
"previous_response": "Sure, let's break it down..."
})
Reusable Prompt Components
You can create modular prompt pieces and combine them.
from langchain_core.prompts import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
# Reusable components
system_template = SystemMessagePromptTemplate.from_template(
"You are a world-class {role}. Always be {style}."
)
human_template = HumanMessagePromptTemplate.from_template("{input}")
# Combine them
chat_prompt = ChatPromptTemplate.from_messages([
system_template,
human_template
])
ChatPromptTemplate
The most commonly used template in LangGraph.
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful LangGraph expert."),
("human", "{input}"),
("ai", "{intermediate_answer}"), # Optional few-shot
("human", "Now answer the final question: {final_question}")
])
result = prompt.invoke({
"input": "How do I create a cycle?",
"intermediate_answer": "You use conditional edges...",
"final_question": "Can you show me a code example?"
})
HumanMessagePromptTemplate & SystemMessagePromptTemplate
from langchain_core.prompts import (
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
system = SystemMessagePromptTemplate.from_template(
"You are {persona}. Your tone should be {tone}."
)
human = HumanMessagePromptTemplate.from_template(
"Explain the following concept in simple terms: {topic}"
)
combined = ChatPromptTemplate.from_messages([system, human])
FewShotPromptTemplate
Great for teaching the model a pattern.
from langchain_core.prompts import FewShotChatMessagePromptTemplate
examples = [
{"input": "What is 2+2?", "output": "4"},
{"input": "What is 5*3?", "output": "15"}
]
few_shot = FewShotChatMessagePromptTemplate(
examples=examples,
example_prompt=ChatPromptTemplate.from_messages([
("human", "{input}"),
("ai", "{output}")
])
)
final_prompt = ChatPromptTemplate.from_messages([
("system", "You are a math tutor."),
few_shot,
("human", "{new_question}")
])
Template Composition
You can combine multiple templates elegantly.
from langchain_core.prompts import ChatPromptTemplate
base_template = ChatPromptTemplate.from_template(
"You are {role}. {instructions}"
)
task_template = ChatPromptTemplate.from_template(
"Task: {task}\nContext: {context}"
)
final_prompt = base_template + task_template
Prompt Formatting Strategies
# Strategy 1: Simple string template
simple = "Answer in {style}: {question}"
# Strategy 2: Structured with multiple messages
structured = ChatPromptTemplate.from_messages([
("system", "You are {role}"),
("human", "{question}"),
("ai", "Let me think step by step...")
])
# Strategy 3: JSON mode / Structured Output
json_prompt = ChatPromptTemplate.from_template(
"""Answer the question and return in JSON format:
Question: {question}
Answer in this exact schema: {schema}"""
)
Common Template Mistakes
- Hardcoding values instead of using variables
- Making templates too long (>2000 tokens)
- Inconsistent variable names
- Forgetting to pass all required variables
- Overusing few-shot examples (can hurt performance)
- Not testing templates with real data
Best Practices for Prompt Templates
- Keep templates concise and focused
- Use clear, consistent variable names (user_query, context, format_instructions)
- Separate system instructions from task instructions
- Version control your templates
- Test templates independently before integrating
- Use partial_variables for common defaults
- Document expected input for each template
prompt = ChatPromptTemplate.from_messages([
("system", """You are an expert LangGraph developer.
Be concise, technical, and always suggest best practices."""),
("human", """Task: {task}
Context: {context}
Requirements: {requirements}""")
])
# Partial for common values
prompt = prompt.partial(requirements="Be production-ready and include error handling.")
AI agent LangChain LangGraph Python