DocsStation
LangChain

Prompts in LangChain

By csestudy247 Updated December 2, 2026 6 min read
6 min read
LangChain Tutorial

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.

Important: You do not need to use Ollama specifically. You can use the LLM provider you already have access to. The main difference is usually the model initialization and the required integration package/API key. The prompt code can remain largely the same.

Common LangChain Model Providers

The prompt can stay the same while the model object changes. For example, this tutorial uses Ollama:

Python – Ollama
from langchain_ollama import ChatOllama

llm = ChatOllama(model="gemma3:1b")

You could instead use OpenAI:

Python – OpenAI
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="your-openai-model")

Or Google Gemini:

Python – Google Gemini
from langchain_google_genai import ChatGoogleGenerativeAI

llm = ChatGoogleGenerativeAI(
    model="your-gemini-model"
)

Or Anthropic Claude:

Python – Anthropic
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:

Python
prompt = PromptTemplate.from_template(
    "Explain {topic} in simple words."
)

chain = prompt | llm

response = chain.invoke({
    "topic": "Machine Learning"
})

print(response.content)
Remember: The prompt is the main focus of this tutorial. The model provider is interchangeable; only the model setup, package installation, credentials, and model name may differ.

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.

Python
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.

Python
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.

Python
response = (prompt | llm).invoke({
    "topic": "Machine Learning"
})

print(response.content)
Important: Prompt variables are normally passed as a dictionary.

2. Dynamic Prompts

A dynamic prompt allows values to be supplied at runtime. The template remains the same while the input can change.

Python
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:

Enter topic: LangChain

The final prompt becomes:

Explain LangChain in simple words and keep it short.

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.

Python
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} → beginner

4. ChatPromptTemplate

ChatPromptTemplate is useful when working with chat models and structured messages.

Python
from langchain_core.prompts import ChatPromptTemplate

llm = ChatOllama(model="gemma3:1b")

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.

Python
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.

Python
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.

Python
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:

Python
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.

Python
chain = prompt | llm
Input ↓ Prompt ↓ LLM ↓ Response

You can also add an output parser:

Python
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.

Python
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

  • PromptTemplate creates reusable prompts.
  • {topic} represents a prompt variable.
  • Runtime values are usually passed as a dictionary.
  • ChatPromptTemplate is useful for structured chat messages.
  • MessagesPlaceholder is useful for conversation history.
  • Few-shot prompting provides examples to guide the model.
  • prompt | llm connects 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.

Learn More

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

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.

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.

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.

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

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.

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.

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.

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.

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.

Scroll to Top