Course contentsShow
← AI Engineering
Lesson 502 of 1,88613. LLM Orchestration FrameworksFree lesson

Prompt Templates Basics

Creating reusable prompt templates with variables and understanding the PromptTemplate class for dynamic prompts.

Prompt Templates Basics

What you'll learn: How to create reusable, dynamic prompts using variables instead of hardcoding text every time.

Why Templates Matter

Imagine writing the same email format dozens of times, changing only the name and subject. Tedious, right? Prompt templates work the same way—they let you define a prompt structure once with placeholders, then fill in different values as needed.

In LangChain, instead of manually crafting strings like f"Tell me about {topic}" every time, you create a PromptTemplate that handles variable substitution cleanly and consistently.

The PromptTemplate Class

LangChain's PromptTemplate class is your tool for building dynamic prompts. You define a template string with placeholders (usually in curly braces), specify which variables it expects, and then generate specific prompts by passing values.

Basic pattern:

from langchain.prompts import PromptTemplate

template = PromptTemplate(
    input_variables=["topic"],
    template="Explain {topic} in simple terms."
)

prompt = template.format(topic="quantum computing")
# Result: "Explain quantum computing in simple terms."

Multiple Variables

Templates can have several placeholders:

template = PromptTemplate(
    input_variables=["role", "task"],
    template="You are a {role}. Your task: {task}"
)

prompt = template.format(role="historian", task="summarize World War II")

Why Use Templates?

  • Reusability: Define once, use everywhere
  • Consistency: Same structure across your application
  • Maintainability: Update the template in one place
  • Integration: Works seamlessly with LangChain chains and pipelines

Key Takeaway: Prompt templates transform hardcoded strings into reusable, variable-driven components, making your AI applications cleaner and more maintainable through the PromptTemplate class.