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

# Prompt Templates Demo

> Guide to building and using LangChain chat prompt templates, populating them at runtime, and invoking ChatOpenAI to generate assistant responses, with examples and best practices.

This lesson demonstrates how to convert message patterns into reusable prompt templates and then create concrete prompts to send to a chat model using LangChain. The example below walks through the essential steps in order: imports, defining message templates, building a chat prompt template, populating it at runtime, invoking a chat model, and reading the model response.

<Callout icon="lightbulb" color="#1CB2FE">
  Before running the examples, ensure your OpenAI API key is set in the environment, for example:
  `export OPENAI_API_KEY="sk-..."`. See [Introduction to OpenAI](https://learn.kodekloud.com/user/courses/introduction-to-openai) for details and safe handling of secrets.
</Callout>

## Overview

* Build modular message templates (system/human).
* Combine them into a `ChatPromptTemplate`.
* Populate templates at runtime using `format_messages`.
* Send the formatted messages to a chat model (e.g., `ChatOpenAI`) and extract the assistant response.
* Optionally extend with few-shot examples, output parsing, or post-processing steps.

## Quick reference: core classes

| Class / helper                | Purpose                                                   | Example                                               |
| ----------------------------- | --------------------------------------------------------- | ----------------------------------------------------- |
| `ChatOpenAI`                  | Chat model wrapper — handles calling the model            | `model = ChatOpenAI()`                                |
| `ChatPromptTemplate`          | Holds a sequence of message templates and input variables | `ChatPromptTemplate.from_messages([...])`             |
| `SystemMessagePromptTemplate` | Template for system-level instructions (e.g., role)       | `SystemMessagePromptTemplate.from_template(sys_msg)`  |
| `HumanMessagePromptTemplate`  | Template for user/human messages                          | `HumanMessagePromptTemplate.from_template(human_msg)` |

## 1. Imports

Import the LangChain chat model and prompt template helpers:

```python theme={null}
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
import os
```

## 2. Define message templates

Define your system and human message templates with placeholders for runtime variables. These templates describe the pattern of messages but do not include concrete values yet.

```python theme={null}
sys_msg = "You are a {subject} teacher"
human_msg = "Tell me about {concept}"
```

These define two reusable patterns:

* System template: instructs the assistant's role and behavior.
* Human template: expresses the user query with a placeholder.

## 3. Create a ChatPromptTemplate from message templates

Combine the message templates into a structured prompt template using `ChatPromptTemplate.from_messages`. Create message template objects from the raw templates, then pass them to `from_messages`:

```python theme={null}
prompt_template = ChatPromptTemplate.from_messages(
    [
        SystemMessagePromptTemplate.from_template(sys_msg),
        HumanMessagePromptTemplate.from_template(human_msg),
    ]
)
```

If you inspect `prompt_template`, it describes its input variables and the underlying message templates. Example representation (console output):

```text theme={null}
# ChatPromptTemplate(input_variables=['subject', 'concept'],
#                    messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['subject'], template='You are a {subject} teacher')),
#                              HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['concept'], template='Tell me about {concept}'))])
```

## 4. Populate the template to create a concrete prompt

Format the template with actual values for `subject` and `concept`. `format_messages` returns a list of message objects that you can send directly to a chat model:

```python theme={null}
prompt_messages = prompt_template.format_messages(subject="Chemistry", concept="Periodic Table")
```

After formatting, `prompt_messages` contains two message objects:

* System message: "You are a Chemistry teacher"
* Human message: "Tell me about the Periodic Table"

These message objects are ready to pass to the model.

## 5. Invoke the chat model and read the response

Create a `ChatOpenAI` instance and call it with the formatted messages. The `generate_messages` API returns a `ChatResult` containing the generated assistant messages.

```python theme={null}
model = ChatOpenAI()  # set parameters like temperature or model name as needed
response = model.generate_messages([prompt_messages])  # note: pass a list of message lists

# Extract the assistant-generated message content
assistant_content = response.generations[0][0].message.content
print(assistant_content)
```

Example output you might receive:

```text theme={null}
The Periodic Table is a tabular arrangement of the chemical elements, organized based on their atomic number, electron configuration, and recurring chemical properties. The table is divided into rows called periods and columns called groups. Elements in the same group have similar chemical properties due to their similar electron configurations.

The Periodic Table was first created by Dmitri Mendeleev in 1869, who organized the elements based on their atomic mass and predicted the properties of missing elements. The modern Periodic Table is based on atomic number, which is the number of protons in an atom's nucleus. The table is a vital tool in chemistry for predicting element behavior and compound formation, and it continues to evolve as new elements are discovered.
```

## 6. How this fits into a chain

Conceptually, this is a simple chain consisting of:

* A prompt: built from templates and populated at runtime.
* A model: the chat model that consumes the prompt and returns a response.

You can extend this chain with:

* Output parsers (to structure model output).
* Post-processing steps (validation, formatting).
* Storage layers (logs, databases).

## 7. Few-shot prompting (brief)

Few-shot prompting supplies examples to demonstrate desired output style or format. In LangChain, include example message turns in your prompt template so the model sees them along with the instruction and the current query. This helps steer tone, structure, and level of detail.

Example approaches:

* Add one or more example conversation turns using `HumanMessagePromptTemplate` and `AIMessagePromptTemplate` (if available).
* Provide formatted output examples illustrating how the model should structure its response.

## Troubleshooting & tips

* If the model response seems off-topic, enrich the system message with clearer constraints or add few-shot examples demonstrating the desired format.
* Use `temperature` and `max_tokens` settings on `ChatOpenAI` to control randomness and length.
* Avoid committing API keys to source control; use environment variables or secrets management.

<Callout icon="warning" color="#FF6B6B">
  Never commit your OpenAI API key to version control. Use environment variables or secret managers to keep keys safe. Monitor usage to avoid unexpected costs.
</Callout>

## Links and references

* [LangChain course on KodeKloud](https://learn.kodekloud.com/user/courses/langchain)
* [Introduction to OpenAI on KodeKloud](https://learn.kodekloud.com/user/courses/introduction-to-openai)
* Official LangChain docs: [https://langchain.readthedocs.io](https://langchain.readthedocs.io)
* OpenAI API docs: [https://platform.openai.com/docs](https://platform.openai.com/docs)

***

This concise walkthrough covers building prompt templates, populating them at runtime, and invoking a chat model with LangChain. You can expand this pattern into pipelines for parsing, validation, or integrating with downstream applications.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/langchain/module/ae260750-791b-496c-991f-0d0333f61e40/lesson/857f3912-4a8e-4594-bb30-479d5f303cc8" />

  <Card title="Practice Lab" icon="flask-conical" cta="Learn more" href="https://learn.kodekloud.com/user/courses/langchain/module/ae260750-791b-496c-991f-0d0333f61e40/lesson/0c1c660e-6569-4b29-b3da-790d279553ff" />
</CardGroup>
