Module 3 Lesson 2: PromptTemplate (String Abstraction)
·LangChain

Module 3 Lesson 2: PromptTemplate (String Abstraction)

From Static to Dynamic. Using PromptTemplate to create reusable instructions with variables.

PromptTemplate: Reusable Logic

In Python, we use functions with parameters to avoid repeating code. In LangChain, we use PromptTemplate to avoid repeating prompt text. A template is a string with "Holes" (variables) that you fill in later.

1. Creating Your First Template

from langchain.prompts import PromptTemplate

# 1. Define the blueprint
template = "Tell me a brief joke about {topic}."

# 2. Initialize the object
prompt_template = PromptTemplate.from_template(template)

# 3. Format with actual data
formatted_prompt = prompt_template.format(topic="artificial intelligence")

print(formatted_prompt)
# Output: "Tell me a brief joke about artificial intelligence."

2. Why Use .from_template?

You can also initialize it with an explicit list of input_variables. This is more formal and safer for complex integrations.

prompt = PromptTemplate(
    input_variables=["adjective", "content"],
    template="Tell me a {adjective} story about {content}."
)

3. Saving and Loading Prompts

You don't have to keep your prompts inside your .py files. LangChain allows you to save templates to JSON or YAML files.

  • prompt.save("my_prompt.json")
  • This allows non-developers (like product managers) to edit the prompt without touching the code.

4. Visualizing Template Injection

graph LR
    User[Topic: 'Pizza'] --> Template[Joke Template: {topic}]
    Template --> Formatter[Formatter Engine]
    Formatter --> Final[Tell me a joke about Pizza]
    Final --> LLM[Model]

5. Engineering Tip: Default Values

Sometimes a variable should be optional. While PromptTemplate usually requires all variables, you can use partial to fill in some variables early.

partial_prompt = prompt_template.partial(topic="default stuff")

Key Takeaways

  • PromptTemplate separates the logic (instruction) from the data (variables).
  • Templates use f-string style syntax ({variable}).
  • Saving prompts to JSON/YAML is a best practice for enterprise teams.
  • Validation: LangChain checks if you provide the wrong variables, helping prevent crashes.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn