Skip to main content

💻 Practice Notebook

Master the concepts from this page with hands-on practice: 💻 VS Code | 🚀 Colab | 📥 Download Notebook When building LLM applications, managing prompts dynamically is essential. LangChain provides powerful abstractions like PromptTemplate and ChatPromptTemplate to build reusable prompts, manage conversation messages, and parse variables.

1. PromptTemplate (String-Based Prompts)

PromptTemplate is used to create simple, string-based prompts. It is ideal for non-conversational LLMs or basic text generation pipelines.

1.1 Code Examples

Example 1: Concept Explanation

Output:

Example 2: Automated Code Reviewer

Create a prompt template that takes language and code variables and instructs the model to review the code.
Output:

1.2 Exercises for PromptTemplate

Exercise 1: Recipe Generator

Define a PromptTemplate that takes an ingredients list (e.g., “tomato, cheese, basil”) and a cuisine type (e.g., “Italian”), and prompts the model to generate a recipe.

Exercise 2: Technical Definition Writer

Define a PromptTemplate that takes a term and an audience_level (e.g., “5-year-old” or “PhD student”) and generates a customized definition.

2. Message Types & Chat Structures

Chat models communicate using lists of structured messages rather than a single block of text. This helps maintain role-based boundaries and conversational context. LangChain provides three main message classes in langchain_core.messages:
  • SystemMessage: Sets the behavior, persona, rules, or constraints for the assistant. This message is usually sent first.
  • HumanMessage: Represents input sent by the user.
  • AIMessage: Represents responses generated by the model.

2.1 Why Message Objects are Important

Message objects allow API providers (like Google Gemini, OpenAI, or Anthropic) to handle conversations structure-selectively. They let the backend know exactly who said what, which prevents the LLM from confusing system guardrails with user input.

2.2 Invoking ChatModels with Message Objects

You can pass a list of message objects directly to a Chat Model to initiate or continue a multi-turn conversation.

3. ChatPromptTemplate (Message-Based Prompts)

ChatPromptTemplate structures conversation flows for Chat Models using lists of system, human, and AI instructions.

3.1 Code Examples

Example 1: Customer Service Ticket Auto-Classifier

Categorize customer support tickets into Hardware, Software, or Billing issues.

Example 2: Geography Expert (Few-Shot Chat)

Simulate flag color retrieval with few-shot examples embedded inside a chat dialogue.

3.2 Exercises for ChatPromptTemplate

Exercise 1: History Guide Roleplay

Create a ChatPromptTemplate simulating a historical dialogue.
  • System message: "You are \{historical_figure\}, a historical figure. Answer in their character."
  • Human: "What was your greatest achievement?"
  • AI: "My greatest achievement was \{achievement\}."
  • Human: "Why was \{achievement\} important?"
Invoke this template with historical_figure="Julius Caesar" and achievement="crossing the Rubicon". Print the generated list of messages.

Exercise 2: Code Translator

Create a ChatPromptTemplate representing a code translation engine.
  • System message: "You are an expert software engineer that translates source code from \{source_lang\} to \{target_lang\}."
  • Human: "Translate this code:\n\n\{code\}"
Invoke this template with source_lang="Python", target_lang="JavaScript", and code="print('Hello World')" and print the messages.

4. Variable Passing Mechanisms

When invoking templates or chains, you pass variables depending on the count of placeholders:
  • Single-Variable Shortcut: If the template has exactly one placeholder (e.g., \{variable\}), you can pass a raw string. LangChain maps it automatically.
  • Multi-Variable Dictionary: If the template has multiple placeholders, you must pass a dictionary of key-value pairs.

5. Extracting Responses: .content vs .text vs Direct Output

Depending on the component you invoke, the returned value has different structures. It is crucial to know how to extract the raw text response:

5.1 Use .content (For ChatModels)

When you invoke a Chat Model (e.g., initialized using init_chat_model for Groq or Gemini), the return value is an AIMessage object. To access the generated text, you must use .content.

5.2 Use .text (For Few-Shot / Legacy formatting and outputs)

When formatting older or specific templates (like FewShotPromptTemplate), the formatted result is a PromptValue object. In these cases, you access the raw string representation using .text. Additionally, some legacy LLM completion model classes (as opposed to modern ChatModel classes) or generation results return response structures where the generated text output itself is accessed via .text.

5.3 Direct Output

If you are invoking a local pipeline (e.g., HuggingFacePipeline) or a chain containing a StrOutputParser, the return value is already a plain Python string (str), so you can print or use it directly.