ChatPromptTemplate, SystemMessagePromptTemplate, and HumanMessagePromptTemplate.
Prerequisites and Setup
Ensure you have the required packages installed:Never commit your API key to version control. Use environment variables or a secrets manager.
Choosing the Right Prompt Classes
LangChain provides several classes to structure your chat prompts. Use the table below as a quick reference:| Class | Purpose | Example |
|---|---|---|
| ChatPromptTemplate | Combine system & human messages | ChatPromptTemplate.from_messages([...]) |
| SystemMessagePromptTemplate | Define system-level instructions | SystemMessagePromptTemplate(prompt=...) |
| HumanMessagePromptTemplate | Template for user-level messages | HumanMessagePromptTemplate(prompt=...) |
1. Defining Reusable Message Templates
Start by creating message strings with placeholders:2. Building a ChatPromptTemplate
UseChatPromptTemplate.from_messages to stitch together your system and human templates:
prompt_template holds the structure but lacks the actual subject and concept values.
3. Populating and Formatting the Prompt
Fill in the placeholders at runtime:filled_messages contains two messages:
- System: “You are a Chemistry teacher”
- Human: “Tell me about Periodic Table”
4. Invoking the Chat Model
Send the formatted messages to the OpenAI chat model:The Periodic Table is a tabular arrangement of the chemical elements, organized by atomic number, electron configuration, and recurring chemical properties. Rows are called periods, columns are groups, and elements in the same group share similar chemical behaviors.
5. Extending with Few-Shot Prompting
You can embed few-shot examples or custom tones by explicitly composing templates:Few-shot prompting can increase token usage—and cost—so monitor your token counts and model billing.