Learn prompts, PromptTemplate, dynamic prompts, ChatPromptTemplate, message history and few-shot prompting with practical Python examples.
Before You Start: Which LLM Can You Use? #
The prompting concepts explained in this tutorial are not limited to Ollama. LangChain provides integrations for many LLM providers, including OpenAI, Google Gemini, Anthropic Claude, Ollama, and others.
In this tutorial, Ollama is used in the examples
because it allows you to run supported models locally. However,
the main concepts such as PromptTemplate,
ChatPromptTemplate, dynamic variables,
message history, and few-shot prompting work with supported
LangChain chat models from different providers.
Common LangChain Model Providers #
The prompt can stay the same while the model object changes. For example, this tutorial uses Ollama:
from langchain_ollama import ChatOllama
llm = ChatOllama(model="gemma3:1b")
You could instead use OpenAI:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="your-openai-model")
Or Google Gemini:
from langchain_google_genai import ChatGoogleGenerativeAI
llm = ChatGoogleGenerativeAI(
model="your-gemini-model"
)
Or Anthropic Claude:
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
model="your-claude-model"
)
After creating the model, the same LangChain prompt concepts can be composed with the model:
prompt = PromptTemplate.from_template(
"Explain {topic} in simple words."
)
chain = prompt | llm
response = chain.invoke({
"topic": "Machine Learning"
})
print(response.content)
What is a Prompt? #
A prompt is an instruction or input given to an LLM. In LangChain, prompts can be simple text or reusable templates containing dynamic variables.
from langchain_ollama import ChatOllama
llm = ChatOllama(model="gemma3:1b")
response = llm.invoke(
"Explain machine learning in simple words."
)
print(response.content)
1. PromptTemplate #
PromptTemplate is used to create reusable
prompts with variables.
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template(
"Explain {topic} in simple words."
)
Here {topic} is a prompt variable.
Its value can be provided at runtime.
response = (prompt | llm).invoke({
"topic": "Machine Learning"
})
print(response.content)
2. Dynamic Prompts #
A dynamic prompt allows values to be supplied at runtime. The template remains the same while the input can change.
from langchain_ollama import ChatOllama
from langchain_core.prompts import PromptTemplate
llm = ChatOllama(model="gemma3:1b")
prompt = PromptTemplate.from_template(
"Explain {topic} in simple words and keep it short."
)
chain = prompt | llm
topic = input("Enter topic: ")
response = chain.invoke({
"topic": topic
})
print(response.content)
If the user enters:
The final prompt becomes:
The same template can be reused for Python, RAG, Machine Learning, Deep Learning, LangChain, and other topics.
3. Multiple Prompt Variables #
A prompt can contain multiple variables.
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template(
"Explain {topic} for a {level} student."
)
response = (prompt | llm).invoke({
"topic": "Machine Learning",
"level": "beginner"
})
print(response.content)
The variables are mapped to their values:
{topic} → Machine Learning{level} → beginner4. ChatPromptTemplate #
ChatPromptTemplate is useful when working
with chat models and structured messages.
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
(
"system",
"You are a helpful programming teacher."
),
(
"human",
"Explain {topic} in simple words."
)
])
chain = prompt | llm
response = chain.invoke({
"topic": "Python"
})
print(response.content)
The two important message roles here are:
- System: Defines the AI’s behavior and instructions.
- Human: Contains the user’s request.
5. System and Human Messages #
System messages can define how the model should respond.
prompt = ChatPromptTemplate.from_messages([
(
"system",
"""You are an expert Python teacher.
Explain concepts for beginners.
Use simple examples."""
),
(
"human",
"Explain {topic}."
)
])
6. MessagesPlaceholder #
MessagesPlaceholder is useful when you want
to insert conversation history into a chat prompt.
from langchain_core.prompts import (
ChatPromptTemplate,
MessagesPlaceholder
)
prompt = ChatPromptTemplate.from_messages([
(
"system",
"You are a helpful assistant."
),
MessagesPlaceholder("history"),
(
"human",
"{question}"
)
])
Conversation history can then be supplied at runtime.
from langchain_core.messages import (
HumanMessage,
AIMessage
)
history = [
HumanMessage(content="What is Python?"),
AIMessage(content="Python is a programming language.")
]
response = (prompt | llm).invoke({
"history": history,
"question": "What can I build with Python?"
})
print(response.content)
7. Few-Shot Prompting #
Few-shot prompting means providing examples to the model before asking it to perform the actual task.
For example, sentiment classification:
from langchain_core.prompts import (
PromptTemplate,
FewShotPromptTemplate
)
examples = [
{
"input": "I love this product.",
"output": "Positive"
},
{
"input": "This product is terrible.",
"output": "Negative"
}
]
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Input: {input}\nOutput: {output}"
)
prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="Classify the sentiment:",
suffix="Input: {input}\nOutput:",
input_variables=["input"]
)
print(prompt.format(
input="This product is excellent."
))
8. Prompt | LLM #
LangChain uses the pipe operator | to connect
components together.
chain = prompt | llm
You can also add an output parser:
from langchain_core.output_parsers import StrOutputParser
chain = prompt | llm | StrOutputParser()
response = chain.invoke({
"topic": "Machine Learning"
})
print(response)
9. Complete Dynamic Prompt Example #
The following example combines a chat prompt, runtime input, Ollama and an output parser.
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
llm = ChatOllama(model="gemma3:1b")
prompt = ChatPromptTemplate.from_messages([
(
"system",
"You are an expert computer science teacher. "
"Explain topics for beginners."
),
(
"human",
"Explain {topic} in simple words and give one example."
)
])
chain = prompt | llm | StrOutputParser()
topic = input("Enter topic: ")
response = chain.invoke({
"topic": topic
})
print(response)
Key Points #
PromptTemplatecreates reusable prompts.{topic}represents a prompt variable.- Runtime values are usually passed as a dictionary.
ChatPromptTemplateis useful for structured chat messages.MessagesPlaceholderis useful for conversation history.- Few-shot prompting provides examples to guide the model.
prompt | llmconnects the prompt to the LLM.
Conclusion #
LangChain prompts provide a structured way to create
reusable and dynamic instructions for LLM applications.
Beginners should first understand
PromptTemplate and
ChatPromptTemplate, then move to message history,
few-shot prompting, RAG and agents.
LangChain APIs change over time. For the latest syntax, integrations and examples, always check the official LangChain documentation.
Visit Official LangChain Documentation →Q.1 If specific input is provided, which value should the temperature parameter be set to?
1.0
2.0
0
1.5
Explanation
A temperature of 0 reduces randomness to absolute zero, which is ideal for tasks requiring high precision and consistency.
Q.2 What is the primary risk of allowing users to provide the entire string as a 'static prompt' in a production LLM application?
It leads to inconsistent user experiences and potential hallucinations.
The LangChain framework will automatically block the request.
The API costs will increase exponentially.
The model will lose its ability to process multi-modal inputs.
Explanation
Allowing users to control the entire static prompt can cause inconsistent outputs, unpredictable behavior, and prompt injection risks. In production systems, developers should control the system prompt while users provide only the necessary input.
Q.3 Which specific LangChain feature allows developers to catch errors if a required variable is missing from a prompt before the code is executed in production?
The save() function.
The load_prompt function.
The validate_template parameter.
Python f-strings.
Explanation
The validate_template parameter checks whether all required input variables are present in a prompt template. It helps detect missing variables during development, preventing runtime errors when the application is executed in production.
Q.4 Why is it advantageous to use the PromptTemplate class instead of standard Python f-strings for complex applications?
It supports serialization, validation, and integration with LangChain's ecosystem.
It allows the model to bypass the temperature settings.
It automatically reduces the number of tokens used in a request.
It is the only way to send messages to the OpenAI API.
Explanation
PromptTemplate provides features such as template validation, serialization, reusability, and seamless integration with LangChain components. These capabilities make it more suitable than standard Python f-strings for building scalable and maintainable LLM applications.
Q.5 Which message type in LangChain is best suited for providing the LLM with a 'persona,' such as 'You are a knowledgeable doctor'?
AIMessage
SystemMessage
HumanMessage
TemplateMessage
Explanation
The SystemMessage is used to define the AI’s role, behavior, or persona before the conversation begins. It provides high-level instructions that guide how the LLM should respond throughout the interaction, such as ‘You are a knowledgeable doctor.
Q.6 In a chatbot application, why is it necessary to append the LLM's response (AIMessage) back into the chat history list?
To provide the model with context for future user queries.
To reduce the computational load on the local machine.
To convert the text into a multi-modal format.
To prevent the API key from expiring.
Explanation
Appending the AIMessage to the chat history preserves the conversation context. When the user asks a follow-up question, the LLM can reference both the user’s previous messages and its own earlier responses, enabling coherent, context-aware conversations.
Q.7 What is the specific purpose of the MessagesPlaceholder class in a ChatPromptTemplate?
To serve as a default response when the LLM fails.
To mask sensitive user information like passwords.
To translate prompts into multiple languages.
To hold a spot for a dynamic list of historical messages.
Explanation
The MessagesPlaceholder class reserves a location in a ChatPromptTemplate where a dynamic list of messages, such as conversation history, can be inserted. This allows the prompt to include previous interactions while keeping the template reusable and flexible.
Q.8 When creating a ChatPromptTemplate in recent versions of LangChain, what is the recommended way to define the messages within the list?
Using tuples containing the role and the content, such as ('system', 'template string').
Using a single long string with special delimiters.
Defining each message in a separate external JSON file.
Passing raw Python dictionaries only.
Explanation
In recent versions of LangChain, the recommended way to define messages in a ChatPromptTemplate is by using tuples that pair the message role with its content, such as (‘system’, ‘You are a helpful assistant’) or (‘human’, ‘{input}’). This approach is concise, readable, and integrates seamlessly with LangChain’s prompt templating system.
Q.9 What is the primary advantage of using a ChatPromptTemplate instead of manually concatenating strings to build prompts?
It provides a structured, reusable, and maintainable way to compose prompts.
It automatically increases the model's context window.
It eliminates the need for an LLM API key.
It guarantees that the LLM will always return the correct answer.
Explanation
ChatPromptTemplate helps developers create structured prompts by separating message roles and dynamic variables. This makes prompts easier to reuse, maintain, validate, and integrate with other LangChain components compared to manually concatenating strings.
Q.10 Which of the following describes a 'multi-modal' prompt?
A prompt that is split into several smaller chunks.
A prompt that is translated into three or more languages.
A prompt that uses multiple LLMs simultaneously.
A prompt that includes different types of data like images, audio, or video.
Explanation
A multi-modal prompt combines multiple types of input data, such as text, images, audio, or video, allowing the AI model to process and reason across different modalities. For example, an LLM may analyze an image together with a text question to generate a response.