---
layout: default
---

# dynamicSystemPromptMiddleware

<div class="mt-4 text-xs">

<v-click>

```typescript
import * as z from "zod";
import { createAgent, dynamicSystemPromptMiddleware } from "langchain";

const contextSchema = z.object({
  userRole: z.enum(["expert", "beginner"]),
});

const agent = createAgent({
  model: "mistral:mistral-large-latest",
  tools: [searchTool],
  contextSchema,
  middleware: [
    dynamicSystemPromptMiddleware<z.infer<typeof contextSchema>>((state, runtime) => {
      const userRole = runtime.context.userRole;
      let prompt = "Eres un asistente útil.";

      if (userRole === "expert") {
        prompt += " Proporciona respuestas técnicas detalladas.";
      } else {
        prompt += " Explica conceptos de forma simple, sin jerga técnica.";
      }
      return prompt;
    }),
  ],
});

await agent.invoke(
  { messages: [{ role: "user", content: "Explica machine learning" }] },
  { context: { userRole: "beginner" } }
);
```

</v-click>

</div>
