langchain.js
    Preparing search index...

    Function dynamicSystemPromptMiddleware

    • 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.

      Type Parameters

      • TContextSchema = unknown

        The shape of the runtime context available at invocation time. If your agent defines a contextSchema, pass the inferred type here to get full type-safety for runtime.context.

      Parameters

      Returns AgentMiddleware<undefined, undefined, any>

      A middleware instance that sets systemPrompt for the next model call.

      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-3-5-sonnet",
      contextSchema,
      middleware: [middleware],
      });

      await agent.invoke({ messages }, { context: { region: "EU" } });