mirror of
https://github.com/hwchase17/langchain.git
synced 2026-02-21 14:43:07 +00:00
Adding a `dynamic_prompt` decorator to support smoother devx for dynamic
system prompts
```py
from langchain.agents.middleware.types import dynamic_prompt, ModelRequest, AgentState
from langchain.agents.middleware_agent import create_agent
from langgraph.runtime import Runtime
from dataclasses import dataclass
from langchain_core.messages import HumanMessage
@dataclass
class Context:
user_name: str
@dynamic_prompt
def my_prompt(request: ModelRequest, state: AgentState, runtime: Runtime[Context]) -> str:
user_name = runtime.context.user_name
return (
f"You are a helpful assistant helping {user_name}. Please refer to the user as {user_name}."
)
agent = create_agent(model="openai:gpt-4o", middleware=[my_prompt]).compile()
result = agent.invoke({"messages": [HumanMessage("Hello")]}, context=Context(user_name="Sydney"))
for msg in result["messages"]:
msg.pretty_print()
"""
================================ Human Message =================================
Hello
================================== Ai Message ==================================
Hello Sydney! How can I assist you today?
"""
```