> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# 1. Prompt Template

> Define string-based prompt templates using from_template and the class constructor

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**:
     ```python theme={null}
     prompt_template = PromptTemplate.from_template("Tell me a joke about {topic}.")
     ```
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**:
     ```python theme={null}
     prompt_value = prompt_template.invoke({"topic": "cats"})
     ```
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.

```python theme={null}
# Import environmental loader from dotenv
from dotenv import load_dotenv

# Import prompt templates and model initialization helpers
from langchain.prompts import PromptTemplate
from langchain.chat_models import init_chat_model

# Load keys and environment settings from local .env
load_dotenv()

# Initialize the Groq model using core abstractions
model = init_chat_model("llama-3.3-70b-versatile", model_provider="groq")

# Define a simple prompt template string with a placeholder '{topic}'
template_str = "Tell me a joke about {topic}."

# Construct the template object using the helper classmethod
prompt_template = PromptTemplate.from_template(template_str)

print("----- Method 1: .from_template() -----")

# Format the template into a plain string using keyword arguments
formatted_str = prompt_template.format(topic="cats")
print("Formatted string:")
print(formatted_str)

# Invoke the template to get a PromptValue wrapper object
prompt_value = prompt_template.invoke({"topic": "cats"})

# Feed the formatted PromptValue directly to the Chat Model
result = model.invoke(prompt_value)

# Print the textual content returned by the LLM
print("\nModel Response:")
print(result.content)
```

***

### 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`.

```python theme={null}
# Import environmental loader from dotenv
from dotenv import load_dotenv

# Import prompt templates and model initialization helpers
from langchain.prompts import PromptTemplate
from langchain.chat_models import init_chat_model

# Load keys and environment settings from local .env
load_dotenv()

# Initialize the Groq model using core abstractions
model = init_chat_model("llama-3.3-70b-versatile", model_provider="groq")

# Construct the template directly by invoking the constructor class
# and specifying the input variable list explicitly
prompt_template_direct = PromptTemplate(
    input_variables=["adjective", "animal"],
    template="Tell me a {adjective} story about a {animal}."
)

print("\n----- Method 2: Direct Class Instantiation -----")

# Invoke the directly instantiated template with the values for its placeholders
prompt_value = prompt_template_direct.invoke({"adjective": "funny", "animal": "panda"})

# Feed the formatted prompt directly to the Chat Model
result = model.invoke(prompt_value)

# Print the textual content returned by the LLM
print("Model Response:")
print(result.content)
```

***

## 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:

<CardGroup cols={1}>
  <Card title="Practice & Exercises" icon="laptop-code">
    Practice formatting plain string prompt templates, adding placeholders, and feeding inputs to models.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/GenAI%20With%20Python/public/notebooks/langchain/1_prompt_template.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/genai-course/blob/master/public/notebooks/langchain/1_prompt_template.ipynb) | <a href="/public/notebooks/langchain/1_prompt_template.ipynb" download>📥 Download</a>
  </Card>
</CardGroup>
