AI AgentsLangChain
How do you inject dynamic prompts with middleware?
Question 320 of 324 · Updated
On this page
Direct answer#
Use LangChain's @dynamic_prompt middleware to build the system prompt at runtime instead of defining one fixed prompt for every model call. The decorated function receives a ModelRequest, allowing it to read the agent's current state and trusted runtime context before returning the appropriate system instructions.
This is useful when the same agent must adapt to different users, task stages or application modes without creating a separate agent for each combination.
1. Practical example: an adaptive support assistant#
Imagine a technical support agent used by beginners and experienced developers. It also needs to behave differently before and after a case has been verified.
| Situation | Dynamic instruction |
|---|---|
| Beginner | Use plain language |
| Experienced developer | Use precise technical terms |
| Collecting case details | Ask for missing information |
| Verified observation available | Explain the verified observation |
| Unknown task phase | Do not assume verification; clarify the task |
The agent's core instruction remains unchanged: provide read-only support and never invent case evidence.
Unlike a static system_prompt, the dynamic prompt is evaluated at the model-call boundary. If a tool updates the task phase between model calls, the next prompt can reflect that change.
2. Build the prompt#
Keep prompt construction in a small, independently testable function. Map known values to approved instructions rather than inserting arbitrary text into the system prompt.
PYTHONBASE = 'You are a read-only support assistant. Never invent case evidence.' def build_prompt(audience, phase): style = { 'beginner': 'Use plain language.', 'expert': 'Use precise technical terms.' }.get(audience, 'Use clear language.') task = { 'collecting': 'Ask for missing case details.', 'verified': 'Explain the verified observation.' }.get(phase, 'Do not assume verification; clarify the task.') return ' '.join((BASE, style, task))
For a beginner whose case details are still being collected, this produces:
> You are a read-only support assistant. Never invent case evidence. Use plain language. Ask for missing case details.
The helper uses predefined instruction fragments, with conservative defaults for unknown values. It assumes the application has validated the input types as strings or None.
3. Register dynamic_prompt middleware#
Connect the helper to a modern LangChain agent:
PYTHONfrom dataclasses import dataclass from typing import NotRequired from langchain.agents import AgentState, create_agent from langchain.agents.middleware import dynamic_prompt, ModelRequest @dataclass(frozen=True) class UserContext: audience: str class SupportState(AgentState): phase: NotRequired[str] @dynamic_prompt def support_prompt(request: ModelRequest) -> str: return build_prompt( request.runtime.context.audience, request.state.get("phase"), ) agent = create_agent( model="openai:gpt-4o-mini", tools=[], context_schema=UserContext, state_schema=SupportState, middleware=[support_prompt], ) result = agent.invoke( { "messages": [{"role": "user", "content": "My Wi-Fi keeps disconnecting."}], "phase": "collecting", }, context=UserContext(audience="beginner"), )
The example shows three distinct responsibilities:
- context_schema: describes invocation context, supplied by the host.
- state_schema: defines working fields that can change during the agent's execution.
- dynamic_prompt: reads both and returns the effective system prompt.
The host sets the initial phase. In a tool-enabled version, trusted application logic could update it after validating actual evidence. Merely defining a phase field does not perform verification.
A dynamic prompt replaces the effective system prompt at its middleware boundary; do not assume it appends to a separately configured static prompt. Include essential base instructions in the generated prompt and test composition if multiple components modify it.
Testing: The prompt-building helper was actually executed on Python 3.13.5 and passed eight checks covering both audiences, phase changes, unknown values, instruction-like input and preservation of the base instructions. LangChain and LangGraph were absent locally, so the SDK example and live model behavior were not executed. The example uses the modern API pattern under the authorized offline research exception.
4. When should you use dynamic prompts?#
| Requirement | Recommended mechanism |
|---|---|
| Same instructions for every request | Static system_prompt |
| Different explanation styles by user preference | dynamic_prompt using runtime context |
| Different guidance as the task progresses | dynamic_prompt using agent state |
| Change the actual model or available tools | Appropriate model-call middleware |
| Save a new task phase | Supported state update, not prompt generation |
Dynamic prompts are particularly useful for tutoring, customer support and multi-stage workflows. A tutoring agent can switch between introductory explanations and advanced examples; a support agent can move from collecting information to explaining verified results.
5. Common mistakes#
- Dropping base instructions: Always preserve the essential behavior and safety constraints when building the effective prompt.
- Injecting arbitrary user text as instructions: Select approved fragments from validated values. Treat retrieved documents and conversation text as data.
- Confusing guidance with permission: A prompt saying that an action is allowed does not authorize it. Enforce permissions in tools and domain services.
- Expecting state changes: Returning a dynamic prompt changes the model-facing instructions, not the persisted AgentState.
- Adding unnecessary context: Keep the resulting prompt small and relevant. More instructions do not automatically improve the answer.
Test the actual model-facing prompt in the pinned SDK, including subsequent model iterations, unknown context values, middleware ordering and separate concurrent users.
Key takeaway#
Use @dynamic_prompt when the agent's instructions need to adapt at runtime. Build them from a stable base plus validated context and current state, rather than rewriting or duplicating the entire agent.
References
- 1.LangChain agentsdocs.langchain.com
- 2.LangChain custom middlewaredocs.langchain.com
- 3.LangChain runtimedocs.langchain.com
- 4.LangChain API referencereference.langchain.com
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps