Objectives
- Understand the difference between
PromptTemplateandChatPromptTemplate. - Construct templates using
.from_template(),.from_messages(), and direct class constructors. - Format templates with inputs and feed them to Chat Models.
Why Use Prompt Templates?
In real-world LLM applications, you rarely send hardcoded, static strings to a model. Instead, you construct dynamic prompts that combine instructions, context, and user inputs. Prompt templates abstract this formatting, allowing you to define reusable templates with placeholders that are populated at runtime. LangChain provides two core classes for building prompts:PromptTemplate: Used for plain string prompts.ChatPromptTemplate: Used for structured chat-based messages (containing system, human, or assistant roles).
Three Ways to Construct Prompts
You can access and build these templates in three primary ways:1. Using .from_template()
Create a prompt template from a single string containing placeholders.
2. Using .from_messages() (ChatPromptTemplate)
Create a structured chat prompt from a list of messages (such as system and human roles represented as tuples or message objects).
3. Direct Class Instantiation
Construct the templates directly using class constructors, manually specifying input variables and template strings.Next Steps: What We Will Build
We will implement and explore prompt templates and output parsers in the following sections:- Prompt Template: Focuses on string-based prompts using
PromptTemplate. - Chat Prompt Template: Focuses on structured message prompts using
ChatPromptTemplate. - Parsers Basics: Introduces output parsers, the need for them, and basic parsers (
StrOutputParser,CommaSeparatedListOutputParser). - Pydantic Output Parser: Focuses on deserializing outputs directly into strongly-typed Pydantic schemas.
- JSON Output Parser: Explores generating structured JSON outputs in dict formats, with or without validation schemas.
Practice & Exercises
To reinforce what you’ve learned in this section, practice with the interactive notebooks:PromptTemplate Practice
Practice string templates.💻 VS Code | 🚀 Colab
ChatPromptTemplate Practice
Practice chat templates.💻 VS Code | 🚀 Colab