LangChain

Interacting with LLMs

Prompt Templates

In this lesson, we’ll dive into prompt templates—parameterized messages that make your LangChain interactions more flexible, consistent, and reusable. Instead of hard-coding each system, human, or AI message, you define templates with placeholders that are filled in at runtime.

What Are Prompt Templates?

A prompt template is a blueprint for your LLM interactions. You can:

  • Define system, human, or AI messages with named placeholders
  • Populate placeholders at runtime, generating dynamic prompts
  • Chain multiple templates together, passing data from one step to the next
  • Standardize messaging across your team for a consistent LLM experience

Note

Always verify that all placeholders match the input keys you supply at runtime to avoid template rendering errors.

Benefits of Using Prompt Templates

BenefitDescriptionExample
ReusabilityCreate once, reuse across multiple chainsgreeting = "Hello, {user_name}!"
ConsistencyEnforce a standard messaging formatSystem prompts that always start with company branding
FlexibilityQuickly swap out placeholders or default valuesChanging {user_name} to {customer_name} globally
MaintainabilityEasier updates when requirements evolveUpdate tone or style in one template file

Core Components

  1. System Message Template
    Typically sets the overall behavior of the LLM.

    from langchain.prompts import SystemMessagePromptTemplate
    
    system_template = SystemMessagePromptTemplate.from_template(
        "You are a helpful assistant for {company_name} support."
    )
    
  2. Human Message Template
    Captures user input or queries.

    from langchain.prompts import HumanMessagePromptTemplate
    
    human_template = HumanMessagePromptTemplate.from_template(
        "Hi, my order #{order_id} is delayed. Can you help?"
    )
    
  3. AI Message Template
    Formats or parses the LLM’s response.

    from langchain.prompts import AIMessagePromptTemplate
    
    ai_template = AIMessagePromptTemplate.from_template(
        "The estimated delivery date for order {order_id} is {delivery_date}."
    )
    

The image is a diagram illustrating the flow of an AI message between an application and a chat model, using a prompt template.

Demo Scenarios

In the following demos, we’ll cover:

  1. Creating prompt templates with placeholders
  2. Generating parameterized prompts
  3. Building reusable, organization-wide templates

Let’s jump into the hands-on examples and see these prompt templates in action!


Watch Video

Watch video content

Previous
Messages in ChatModel Demo