Prompt Templates
Relevant source files
The following files were used as context for generating this wiki page: - [libs/core/langchain_core/prompts/base.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/prompts/base.py) - [libs/core/langchain_core/prompts/prompt.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/prompts/prompt.py) - [libs/core/langchain_core/prompts/chat.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/prompts/chat.py) - [libs/core/langchain_core/prompts/few_shot.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/prompts/few_shot.py) - [libs/core/langchain_core/prompts/__init__.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/prompts/__init__.py) - [libs/langchain/langchain/chains/sql_database/prompt.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/langchain/langchain/chains/sql_database/prompt.py) - [libs/langchain/langchain/chains/query_constructor/prompt.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/langchain/langchain/chains/query_constructor/prompt.py) - [libs/core/tests/unit_tests/prompts/test_prompt.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/tests/unit_tests/prompts/test_prompt.py)Prompt templates are a core abstraction in LangChain, designed to facilitate the creation of dynamic and reusable prompts for language models. They allow developers to define a template with placeholders (input variables) that can be filled in at runtime. This system supports various prompt structures, from simple string formatting to complex, multi-message chat conversations and few-shot examples.
The primary goal of prompt templates is to separate the logic of prompt construction from the application code, making prompts easier to manage, version, and reuse across different parts of a system. The framework provides a hierarchy of template classes, starting with BasePromptTemplate, to handle different use cases and model types.
Core Concepts and Architecture
The foundation of the prompt system is the BasePromptTemplate abstract class. It defines the common interface for all prompt templates and is a RunnableSerializable component, making it a standard part of LangChain Expression Language (LCEL) chains.
Sources: libs/core/langchain_core/prompts/base.py:32-37
BasePromptTemplate
This abstract base class defines the essential properties and methods for all prompt templates.
Key Attributes:
| Attribute | Type | Description |
|---|---|---|
input_variables | list[str] | A list of variable names required as input for the prompt. |
optional_variables | list[str] | A list of optional variable names. |
output_parser | Optional[BaseOutputParser] | An optional parser to structure the output from the language model. |
partial_variables | Mapping[str, Any] | A dictionary of variables to pre-populate in the template. These are applied before user-provided variables. |
metadata | Optional[dict[str, Any]] | Metadata for tracing and logging. |
tags | Optional[list[str]] | Tags for tracing and logging. |
Sources: libs/core/langchain_core/prompts/base.py:35-55
The following diagram illustrates the class hierarchy for major prompt template implementations.
This diagram shows the inheritance structure of the main prompt template classes.
Sources: libs/core/langchain_core/prompts/init.py:10-25
Invocation Flow
When a prompt template is invoked, it follows a standard sequence of operations to produce a PromptValue.
This flowchart shows the internal process when invoke is called on a BasePromptTemplate.
Sources: libs/core/langchain_core/prompts/base.py:151-178, libs/core/langchain_core/prompts/base.py:231-237
String-based Prompts
PromptTemplate
The PromptTemplate is the most common implementation, used for creating prompts from a single template string. It supports multiple templating formats.
Key Attributes:
| Attribute | Type | Description |
|---|---|---|
template | str | The template string. |
template_format | PromptTemplateFormat | The templating engine to use. Can be f-string (default), jinja2, or mustache. |
validate_template | bool | Whether to validate the template against the input variables during initialization. |
Sources: libs/core/langchain_core/prompts/prompt.py:22-41
Instantiation
PromptTemplate can be created directly or using class methods for convenience.
-
from_template(template, **kwargs): This is the most common way to create aPromptTemplate. It automatically infersinput_variablesfrom the template string.# Example of creating a PromptTemplate from langchain_core.prompts import PromptTemplate template = "What is the capital of {country}?" prompt = PromptTemplate.from_template(template) # prompt.input_variables will be ['country']Sources: libs/core/langchain_core/prompts/prompt.py:101-104, libs/core/tests/unit_tests/prompts/test_prompt.py:32-36
-
from_file(template_file, **kwargs): Loads the template from a file.# Example of loading from a file prompt = PromptTemplate.from_file("path/to/prompt.txt")Sources: libs/core/langchain_core/prompts/prompt.py:121-123, libs/core/tests/unit_tests/prompts/test_prompt.py:202-205
Chat-based Prompts
ChatPromptTemplate
For chat models, prompts are typically a sequence of messages, each with a specific role (e.g., System, Human, AI). ChatPromptTemplate is designed to construct these message lists.
It is composed of one or more BaseMessagePromptTemplate objects. Common message prompt templates include:
SystemMessagePromptTemplate: For system-level instructions.HumanMessagePromptTemplate: For user input.AIMessagePromptTemplate: For previous AI responses.MessagesPlaceholder: A placeholder for a variable number of messages, often used for chat history.
Sources: libs/core/langchain_core/prompts/chat.py:16-24, libs/core/langchain_core/prompts/chat.py:223-228
Instantiation and Formatting
A ChatPromptTemplate is usually created from a list of message templates.
This sequence diagram illustrates how a ChatPromptTemplate formats a list of messages from its constituent templates.
Sources: libs/core/langchain_core/prompts/chat.py:223-241
Here is a code example demonstrating its creation:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
chat_template = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant that translates {input_language} to {output_language}."),
MessagesPlaceholder(variable_name="chat_history"),
("human", "{text}"),
]
)
Sources: libs/core/langchain_core/prompts/chat.py:230-241
Few-Shot Prompts
FewShotPromptTemplate
FewShotPromptTemplate is used to construct prompts that include a set of examples to guide the model's response. This is a powerful technique for improving performance on specific tasks.
Key Attributes:
| Attribute | Type | Description |
|---|---|---|
examples | Optional[list[dict]] | A list of example dictionaries to format into the prompt. |
example_selector | Any | An optional component to dynamically select examples based on the input. |
example_prompt | PromptTemplate | A PromptTemplate used to format each individual example. |
prefix | str | A string to prepend to the formatted examples. |
suffix | str | A string to append after the formatted examples. It must contain the input variables for the final prompt. |
example_separator | str | The string used to join the prefix, examples, and suffix. |
Sources: libs/core/langchain_core/prompts/few_shot.py:20-44
The construction of a few-shot prompt is illustrated below.
This flowchart shows how FewShotPromptTemplate assembles a prompt from its components.
Sources: libs/core/langchain_core/prompts/few_shot.py:112-140
Practical Applications
Prompt templates are used extensively throughout the langchain library to build chains for specific tasks.
SQL Database Chains
For interacting with SQL databases, different PromptTemplate instances are defined for various SQL dialects (e.g., PostgreSQL, MySQL, SQLite). These templates instruct the model on how to generate syntactically correct queries for the target database.
# Example for PostgreSQL
_postgres_prompt = """You are a PostgreSQL expert. Given an input question, first create a syntactically correct PostgreSQL query to run...
Only use the following tables:
{table_info}
Question: {input}"""
POSTGRES_PROMPT = PromptTemplate(
input_variables=["input", "table_info", "top_k"],
template=_postgres_prompt,
)
Sources: libs/langchain/langchain/chains/sql_database/prompt.py:193-207
Query Constructor Chains
More complex prompts are used to translate natural language queries into structured requests. These often use few-shot examples to teach the model the desired output format (e.g., a JSON object with "query" and "filter" fields).
# An example used in a few-shot prompt for query construction
EXAMPLE_PROMPT_TEMPLATE = """\
<< Example {i}. >>
Data Source:
{data_source}
User Query:
{user_query}
Structured Request:
{structured_request}
"""
EXAMPLE_PROMPT = PromptTemplate.from_template(EXAMPLE_PROMPT_TEMPLATE)
Sources: libs/langchain/langchain/chains/query_constructor/prompt.py:49-59
Conclusion
Prompt Templates are a fundamental and versatile feature in LangChain. They provide a structured, reusable, and powerful way to manage and generate prompts for language models. By separating prompt logic from application code and offering specialized classes like ChatPromptTemplate and FewShotPromptTemplate, they enable developers to build sophisticated and reliable LLM-powered applications. Their integration with the LangChain Expression Language (LCEL) makes them a seamless part of any data processing or generation pipeline.