---
title: Prompts in LangChain
description: "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…"
url: "https://csestudy247.com/docs/prompts-in-langchain/"
updated: "2026-09-18"
category: LangChain
---

# Prompts in LangChain

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 →](https://reference.langchain.com/python/langchain-core/prompts)

Q.1 If specific input is provided, which value should the temperature parameter be set to?

- 1.0
- 2.0
- 0
- 1.5

    Setting temperature to 0 makes the model deterministic and focused, returning the most probable tokens.    [Discuss it](#)

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.

    Consider how sensitive LLMs are to slight changes in phrasing and who should control the style and behavior of the response.    [Discuss it](#)

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.

    Look for a parameter that verifies the structural integrity of the dynamic inputs.    [Discuss it](#)

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.

    Think about the benefits of object-oriented design, specifically regarding reusability and safety checks.    [Discuss it](#)

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

    This message usually appears at the very beginning of the chat history to establish rules.    [Discuss it](#)

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.

    Think about how a model knows what you were talking about two minutes ago.    [Discuss it](#)

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.

    Consider how you would insert an unknown number of past messages into a fixed template structure.    [Discuss it](#)

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.

    Think about a data structure that pairs two items: a label and a value.    [Discuss it](#)

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.

    Think about software engineering best practices such as reusability, readability, and maintainability.    [Discuss it](#)

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.

    Think about the different senses or types of media an AI can perceive.    [Discuss it](#)

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.
