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.
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 dataclassfrom langchain.agents import create_agentfrom langchain.agents.middleware import dynamic_prompt@dataclassclass Customer: tier: str@dynamic_promptdef 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.
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.