Dynamic System Prompt Middleware
Allows setting the system prompt dynamically right before each model invocation. Useful when the prompt depends on the current agent state or per-invocation context.
dynamicSystemPromptMiddleware<
TContextSchema = unknown
>(
fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>
): AgentMiddleware<undefined, undefined, unknown, readonly ClientTool | ServerTool[]>| Name | Type | Description |
|---|---|---|
fn* | DynamicSystemPromptMiddlewareConfig<TContextSchema> | Function that receives the current agent |
import { z } from "zod";
import { dynamicSystemPrompt } from "langchain";
import { createAgent, SystemMessage } from "langchain";
const contextSchema = z.object({ region: z.string().optional() });
const middleware = dynamicSystemPrompt<z.infer<typeof contextSchema>>(
(_state, runtime) => `You are a helpful assistant. Region: ${runtime.context.region ?? "n/a"}`
);
const agent = createAgent({
model: "anthropic:claude-sonnet-4-5",
contextSchema,
middleware: [middleware],
});
await agent.invoke({ messages }, { context: { region: "EU" } });