Chuyển đến nội dung

Bài 6 · Models, Prompts and Parsers

Prompt Templates

Build reusable prompts with LangChain PromptTemplate and ChatPromptTemplate: variables, system and human messages, partial variables, validation and a runnable template engine stand-in.

A prompt is text with holes. A prompt template is a reusable recipe with named placeholders, filled in at run time. Templates keep instructions separate from data, make prompts testable and versionable, and are Runnables, so they slot straight into a chain. LangChain has two main kinds: PromptTemplate for a single string and ChatPromptTemplate for a list of messages. For chat models you almost always want the second.

PromptTemplate: one string

Python
from langchain_core.prompts import PromptTemplate

template = PromptTemplate.from_template(
    "Write a {tone} product description for {product}."
)
print(template.input_variables)            # ['product', 'tone']
value = template.invoke({"product": "a steel water bottle", "tone": "playful"})
print(value.to_string())
# Write a playful product description for a steel water bottle.

from_template finds the itself. invoke takes a dictionary and returns a PromptValue, which can be rendered as a plain string (to_string()) or as chat messages (to_messages()), whichever the next step needs.

ChatPromptTemplate: a list of messages

Python
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a {role}. Answer in {language}."),
    ("human", "{question}"),
])

messages = prompt.invoke({
    "role": "patient math tutor",
    "language": "English",
    "question": "Why is 0.1 + 0.2 not exactly 0.3?",
}).to_messages()

Each tuple is (role, template text). Roles are "system", "human" and "ai"; you can also pass message objects or message template classes. The result is a list of SystemMessage and HumanMessage ready for a chat model. Because the template is a Runnable, prompt | model just works.

How filling really works

Templates use Python's str.format syntax by default (f-string style), so literal braces must be doubled: {{ and }}. This is the classic trap when a prompt contains JSON:

Python
ChatPromptTemplate.from_messages([
    ("system", 'Reply as JSON like {{"answer": "..."}}. Topic: {topic}'),
])

LangChain also supports template_format="jinja2" for loops and conditions, but only use it with prompt text you wrote yourself; templates from untrusted sources are a risk with the more powerful engines.

A mini template engine (runnable)

The mechanics are simple enough to rebuild. This stand-in does what PromptTemplate does at its core: discover variables, check you supplied them all, and fill them.

Python Stand-in: a tiny prompt template

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The real class raises a similar error, so missing variables fail loudly at the prompt, instead of sending half-empty text to a paid API.

A chat template stand-in (runnable)

Now the chat version: a list of (role, text) pairs, each filled from the same dictionary.

Python Stand-in: a chat prompt template

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Partial variables

Sometimes a value is known early, such as today's date or the app name. Fix it with .partial() so callers only supply the rest.

Python
from datetime import date

prompt = ChatPromptTemplate.from_messages([
    ("system", "Today is {today}. You help with {topic}."),
    ("human", "{question}"),
]).partial(today=date.today().isoformat())

prompt.invoke({"topic": "travel", "question": "Best month for Lisbon?"})

A partial can also be a function, evaluated each time the prompt is used, which is handy for timestamps. Plain Python can do the same with functools.partial-like thinking.

Python Stand-in: partial variables, including a function

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Writing good templates

  • Put rules in the system message and data in the human message. Models treat them differently, and it keeps untrusted user text away from your instructions.
  • Be explicit about format. "Answer in at most two sentences" works better than "be brief".
  • Name variables for what they hold: beats .
  • Keep templates in one place (a prompts.py module or files), not scattered through code, so you can review and test them.
  • Treat user input as data. A user can type "ignore previous instructions". Templates do not stop prompt injection; see the evaluation chapter for defenses.
flowchart LR
    V["Variables dict"] --> T["ChatPromptTemplate"]
    T --> M["List of messages"]
    M --> L["Chat model"]

A template turns a dictionary into the exact messages the model sees.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does prompt.invoke({'topic': 'tides'}) return for a ChatPromptTemplate?

    Templates only format text; they do not call a model. The PromptValue becomes messages for the next step.
  2. 2. How do you write a literal curly brace in a default (f-string style) template?

    Single braces mark variables, so literal braces, for example in JSON examples, are doubled.
  3. 3. What is .partial(today=...) used for?

    A partial pre-fills variables; a callable value is evaluated each time the prompt is used.
  4. 4. Which belongs in the system message?

    System messages carry developer-controlled instructions; user data goes in human messages.

Summary

  • PromptTemplate formats one string; ChatPromptTemplate builds a list of role-tagged messages.
  • Templates are Runnables: dict in, PromptValue out, ready for | model.
  • Double the braces for literal {}; missing variables raise errors.
  • .partial() pre-fills values, including functions evaluated at run time.
  • Keep rules in the system message and treat user input as data.

Next: Few-Shot Prompts and Message Placeholders

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.