ChatPromptTemplate and send them to Chat Models.
Objectives
- Construct a structured prompt template using the helper classmethod
.from_messages()with Tuples. - Construct a prompt template using the direct class constructor
ChatPromptTemplate(...). - Format templates into messages, invoke models, and display responses.
- Understand when to use
.from_messages()versus the direct constructor, and string templates versus chat templates.
Code Implementation
Each step of the implementation is preceded by extensive comments explaining the code logic.Method 1: Construction via .from_messages() with Tuples
This is the most common method. You pass a list of ("role", "template_string") tuples, and LangChain automatically parses roles and placeholder values.
Method 2: Construction via Direct Class Constructor
You can initializeChatPromptTemplate directly by passing a list of message objects or message template objects using the messages parameter in the constructor.
Caveat: Mixing Message Objects and Placeholders
When defining templates, you must format variables dynamically using tuples. If you pass an instantiated Message class (likeHumanMessage) with placeholder variables in its string content, LangChain’s formatter will fail to detect and inject the variables.
1. Instantiating a Message without dynamic placeholders (Works)
2. Placing placeholders inside Message classes (Fails)
[!WARNING]
Always use the tuple format ("role", "template string") when you want placeholders to be dynamically populated at runtime inside a chat prompt template.
When to Use What
1. .from_messages() vs. Direct Constructor
.from_messages(): Best when you want to quickly build a dynamic sequence of messages (such as system instructions combined with user input) using the simplified("role", "template")tuple structure.- Direct Class Constructor (
ChatPromptTemplate(messages=[...])): Best when you already have pre-constructed message templates or message objects (e.g., loading them from a database or memory log) and need to pass them directly.
2. PromptTemplate vs. ChatPromptTemplate
PromptTemplate: Use when working with completion-style language models that accept a single plain string as input.ChatPromptTemplate: Use when building applications for Chat Models (like ChatGPT, Claude, or Gemini) which expect structured lists of conversation messages representing different participant roles.
3. ChatPromptTemplate.from_template() vs ChatPromptTemplate.from_messages()
ChatPromptTemplate.from_template() is a convenient shortcut for creating a chat prompt with a single human message, while ChatPromptTemplate.from_messages() is used when you need multiple messages or different message roles such as system, human, and ai.
Practice & Exercises
To practice feeding prompt templates into chat models, open the interactive notebook:Practice & Exercises
Practice formatting dynamic chat messages, using message list wrappers, and invoking models.💻 VS Code | 🚀 Colab | 📥 Download