Skip to main content
In this section, you will learn how to construct, format, and invoke plain string-based prompt templates using PromptTemplate.

The Prompt Template Workflow

Before looking at code, here are the main steps in the standard prompt interaction pipeline:
  1. Creating the Template: Write a text prompt containing placeholder variables in curly braces {}.
    • API: PromptTemplate.from_template() or PromptTemplate(input_variables=..., template=...)
    • Ex:
  2. Formatting the Template: Inject actual runtime user inputs into the template’s placeholder variables.
    • API:
      • .format(**kwargs) - returns str
      • .invoke(dict) - returns PromptValue
    • Ex:
  3. Passing to the LLM: Send the formatted prompt output to the Chat Model.
    • API: model.invoke(prompt_value)
  4. Processing the Result: Retrieve the generated response and extract the text content.
    • API: result.content

Objectives

  1. Define a string prompt template using the helper classmethod .from_template().
  2. Construct a string prompt template using the direct class constructor PromptTemplate(...).
  3. Format templates using .format() and .invoke().
  4. 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 the PromptTemplate 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 constructor PromptTemplate to 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