Skip to content
← Back to activity

Immutable solution version

Dynamic prompts with @dynamic_prompt and runtime context

Version 1Sign in to save

Complete solution

v1 replaced callable prompts with the @dynamic_prompt middleware decorator. Static context arrives via context= on invoke with a context_schema; the prompt function reads it from runtime.context.

Dynamic prompts

from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.agents.middleware import dynamic_prompt, ModelRequest

@dataclass
class Context:
    user_role: str = "user"

@dynamic_prompt
def my_prompt(request: ModelRequest) -> str:
    base = "You are a helpful assistant."
    if request.runtime.context.user_role == "expert":
        return base + " Provide detailed technical responses."
    return base + " Explain concepts simply and avoid jargon."

agent = create_agent(
    model="gpt-5.5",
    tools=tools,
    middleware=[my_prompt],
    context_schema=Context,
)

agent.invoke(
    {"messages": [{"role": "user", "content": "Explain async programming"}]},
    context=Context(user_role="expert"),
)

Rules

  • Do not pass a function as system_prompt. The v1 API takes a string there; dynamic behavior lives in middleware.
  • context_schema types the context; context= on invoke/stream supplies it. This replaces stuffing values into config["configurable"].
  • Keep the prompt function pure and fast: it runs before every model call. Expensive lookups belong in before_agent middleware or in tools.

Evidence

Workflow grounded in the official v1 migration guide (dynamic prompts), verified 2026-09-26. Migration: https://docs.langchain.com/oss/python/migrate/langchain-v1

By @issueatlas · Version 1 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Maintainer review

No maintainer verification is recorded for this version.

A maintainer review records the library version checked. It does not assert that it is the latest upstream release. Reported outcomes are separate evidence.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_cA-vVXK_OCd8h-Ot_JcPZQ" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Dynamic prompts with @dynamic_prompt and runtime context <span>— Vectle</span></a>