LangChain BasicsLesson 5

Prompt Templates

So far you typed full questions into each script. LangChain gives you two template classes: ChatPromptTemplate for system + human roles, and PromptTemplate for a single string you wrap in HumanMessage. This lesson also covers few-shot examples (solved Q/A pairs baked into the template) and chain-of-thought wording (short steps, then a final Answer: line). Same HTML topic as architecture_demo.py from Architecture Overview.

Why templates

Hard-coding strings works for one-off scripts. When you ask many questions with the same system line, copy-pasting it into every call gets messy. A template keeps the fixed parts in one place and leaves variables for the parts that change.

One template, many questions:

system (fixed)

Keep each reply to one short sentence.

human (placeholder)

{question}

↓ format_messages(question=…)
fill → What does the HTML <a> tag do?
fill → What does the <title> tag do?
The system line stays the same. Only {question} changes each time you call format_messages.

ChatPromptTemplate

LangChain's ChatPromptTemplate builds on the message roles you already know. Pass tuples of role and text — ("system", …) and ("human", …) — with curly-brace placeholders where values will go.

  • from_messages([…]) — define the template.
  • format_messages(question=q) — fill placeholders and get a message list for llm.invoke.
  • Placeholder names must match — {question} in the template pairs with question=q in the call.

PromptTemplate

PromptTemplate from langchain_core.prompts builds one string with placeholders. Call .format() to fill the slots, then pass the result inside a HumanMessage — handy when you do not need separate system and human roles in the template itself.

  • from_template("…{question}…") — define the string once.
  • .format(question=q) — returns plain text, not a message list.
  • Put fixed instructions and the question in the same template string, or keep using SystemMessage separately if you prefer two layers.
from langchain_core.prompts import PromptTemplate
from langchain_core.messages import HumanMessage

text_prompt = PromptTemplate.from_template(
    "Keep each reply to one short sentence.\n\nQuestion: {question}"
)

text = text_prompt.format(question=q)
reply = llm.invoke([HumanMessage(content=text)])

Few-shot prompting

Few-shot means you paste one or two solved examples into the template before the real question. In ChatPromptTemplate, alternate ("human", …) and ("ai", …) tuples with the answers you want the script to copy. The last human tuple keeps {question}.

Fixed examples, then your new question:

systemAnswer in one short sentence.
humanWhat does the <p> tag do?
aiThe <p> tag marks a paragraph of text.
humanWhat does the <h1> tag do?
aiThe <h1> tag marks the main heading on a page.
human{question}
The first two Q/A pairs never change. Only the last human line uses your placeholder.
few_shot_prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer in one short sentence."),
    ("human", "What does the <p> tag do?"),
    ("ai", "The <p> tag marks a paragraph of text."),
    ("human", "What does the <h1> tag do?"),
    ("ai", "The <h1> tag marks the main heading on a page."),
    ("human", "{question}"),
])

messages = few_shot_prompt.format_messages(question=q)
reply = llm.invoke(messages)

Chain-of-thought prompting

Chain-of-thought here is simple: ask the script to print two short steps, then a final answer on its own line. Useful when you want students to see the reasoning path, or when you plan to split steps and answer in your own code later.

Printed shape

Step 1: The <a> element wraps the clickable link text.
Step 2: The href attribute holds the destination URL.
Answer: The <a> tag marks a hyperlink to another page or file.
Chain-of-thought here means asking for brief steps first, then one final Answer: line you can parse or show as-is.
cot_prompt = ChatPromptTemplate.from_messages([
    ("system", (
        "For each HTML question: write Step 1 and Step 2, "
        "then print Answer: on its own line."
    )),
    ("human", "{question}"),
])

messages = cot_prompt.format_messages(question=q)
reply = llm.invoke(messages)

The demo script

prompt_templates_demo.py runs four blocks in order: ChatPromptTemplate, PromptTemplate, few-shot, and chain-of-thought — each looping over the same two HTML questions.

prompt_templates_demo.py
"""prompt_templates_demo.py — templates, few-shot, chain-of-thought"""
… imports, load_dotenv(), llm = ChatOpenAI(…) …
# ChatPromptTemplate — roles in one template
chat_prompt = ChatPromptTemplate.from_messages([…])
messages = chat_prompt.format_messages(question=q)
# PromptTemplate — one string, wrap in HumanMessage
text_prompt = PromptTemplate.from_template("…{question}")
llm.invoke([HumanMessage(content=text_prompt.format(question=q))])
# Few-shot — ("human", …), ("ai", …) examples, then {question}
# Chain-of-thought — system asks for Step 1, Step 2, then Answer:
Save as prompt_templates_demo.py — included in the starter ZIP from Project Setup.

Download the code

Prefer not to type the full script? Download prompt_templates_demo.py and place it next to your other lesson files.

prompt_templates_demo.py

Ready to drop into your project folder

Download .py

Inside the file

  • ChatPromptTemplate loop
  • PromptTemplate + HumanMessage
  • Few-shot human/ai examples
  • Chain-of-thought Step 1 / Step 2 / Answer:
Save into your langchain-course folder from Project Setup. Needs a working .env and active venv. The full starter ZIP includes this file too.

Run it

python prompt_templates_demo.py
PowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> python prompt_templates_demo.py
=== ChatPromptTemplate ===
Q: What does the HTML <a> tag do?
A: The <a> tag marks a hyperlink to another page or file.
Q: What does the <title> tag do?
A: The <title> tag sets the text shown in the browser tab.
=== PromptTemplate ===
Q: What does the HTML <a> tag do?
A: The <a> tag marks a hyperlink to another page or file.
… PromptTemplate and Few-shot sections follow …
=== Chain-of-thought ===
Q: What does the HTML <a> tag do?
Step 1: The <a> element wraps the link text.
Step 2: href points to the destination page.
Answer: The <a> tag marks a hyperlink to another page or file.
Four printed sections in the script. Wording may differ slightly between runs.

Templates vs raw messages

ApproachWhen to use
SystemMessage + HumanMessageOne-off calls, quick tests
ChatPromptTemplateSystem + human roles, many different inputs
PromptTemplateOne formatted string → HumanMessage, many inputs
Few-shot ChatPromptTemplateFixed human/ai examples, then a new question
Chain-of-thought templateSteps first, then an Answer: line to read or parse

Docs: Prompt templates.

What's Next

Templates, few-shot, and chain-of-thought are in place. Next: tighten wording in your system and human lines.