AI Hints
Home›LangChain Tutorial›Context and Errors
LangChain · Lesson 52 of 120

Dynamic Prompts

Changing per request.

⏱ 2 min read▶ Video at 57:54🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

A fixed system prompt treats every customer the same. But a loyalty member might get a warmer greeting, and a child's account needs simpler words. A dynamic prompt builds the system prompt fresh, for every request.

Dynamic Prompts
From the video: Dynamic Prompts
  • Fixed prompts treat all alike
  • Members, children, staff
  • Build the prompt per request

A prompt per customer type

The dynamic prompt decorator turns a function into middleware. It receives the request, and returns the system prompt to use. Here it reads the customer's tier from the runtime context, which we'll look at more closely soon. Run it. The same question gets a different style of answer for a child, and for a member.

dynamic_prompt.pypython
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.agents.middleware import dynamic_prompt

@dataclass
class Customer:
    tier: str

@dynamic_prompt
def by_tier(request):
    if request.runtime.context.tier == "child":
        return "You help children. Use very simple words. One sentence."
    return "You help loyalty members. Thank them warmly. One sentence."

agent = create_agent("google_genai:gemini-flash-lite-latest",
                     middleware=[by_tier], context_schema=Customer)
q = {"messages": [{"role": "user", "content": "What is a novel?"}]}
for tier in ["child", "member"]:
    print(tier, "->", agent.invoke(q, context=Customer(tier))["messages"][-1].text)
Output
child -> A novel is a long story in a book that is made up.
member -> Thank you so much for being a valued loyalty member! A novel is a long,
fictional narrative written in prose that typically explores complex characters,
settings, and plots over the course of a book.

Ideas for dynamic prompts

Dynamic prompts are handy whenever instructions depend on the situation. The user's role or language. The time of day, or a sale that's running. How long the conversation has been going. Or which tools are currently allowed.

keyvalue
Userrole, language, tier
Shopsales, opening hours
Conversationlength, topic
Permissionswhat's allowed

Summary

A dynamic prompt builds the system prompt per request, from context. Use the dynamic prompt decorator. Next, what happens when a tool fails.

Key takeaways
  • @dynamic_prompt
  • Reads the context
  • Different instructions
Next up: Tool Errors — failing gracefully