PromptTemplate.
The Prompt Template Workflow
Before looking at code, here are the main steps in the standard prompt interaction pipeline:- Creating the Template: Write a text prompt containing placeholder variables in curly braces
{}.- API:
PromptTemplate.from_template()orPromptTemplate(input_variables=..., template=...) - Ex:
- API:
- Formatting the Template: Inject actual runtime user inputs into the template’s placeholder variables.
- API:
.format(**kwargs)- returnsstr.invoke(dict)- returnsPromptValue
- Ex:
- API:
- Passing to the LLM: Send the formatted prompt output to the Chat Model.
- API:
model.invoke(prompt_value)
- API:
- Processing the Result: Retrieve the generated response and extract the text content.
- API:
result.content
- API:
Objectives
- Define a string prompt template using the helper classmethod
.from_template(). - Construct a string prompt template using the direct class constructor
PromptTemplate(...). - Format templates using
.format()and.invoke(). - Send formatted prompt inputs to Chat Models and display results.
Code Implementation
Each step of the implementation is preceded by extensive comments explaining the code logic.Method 1: Construction via .from_template()
This helper classmethod automatically infers the input variables from your template string based on curly braces {}. We then format it, send it to the model, and print the output.
Method 2: Construction via Direct Class Constructor
You can also construct a template directly using thePromptTemplate class constructor. This requires you to explicitly specify the list of input_variables.
When to Use What
Using .from_template()
- Usage:
PromptTemplate.from_template("text {var}") - Best For: Fast prototyping, interactive shells, and simpler templates.
- Pros: Concise syntax; automatically parses and registers variable placeholders.
- Cons: Offers less control; cannot pre-define or customize variable properties explicitly.
Using the Direct Class Constructor
- Usage:
PromptTemplate(input_variables=["var"], template="text {var}") - Best For: Production codebases and complex prompt workflows.
- Pros: Explicit declaration of inputs; enables validation of variables at startup time.
- Cons: Requires more lines of setup.
[!TIP] Use.from_template()for quick scripts and interactive testing. For stable, production-grade applications, use the direct class constructorPromptTemplateto explicitly declare variable requirements and enforce strict verification.
Practice & Exercises
To practice configuring and running basic string templates, open the interactive notebook:Practice & Exercises
Practice formatting plain string prompt templates, adding placeholders, and feeding inputs to models.💻 VS Code | 🚀 Colab | 📥 Download