Skip to Content
ExamplesAgentsDynamic Agents

Dynamic Agents

Dynamic agents adapt their behavior and capabilities at runtime based on contextual input. Instead of relying on fixed configurations, they adjust to users, environments, or scenarios, enabling a single agent to serve personalized, context-aware responses.

Prerequisites

This example uses the openai model. Make sure to add OPENAI_API_KEY to your .env file.

.env
OPENAI_API_KEY=<your-api-key>

Creating an agent

Create an agent that returns technical support for mastra cloud using dynamic values provided via runtimeContext.

src/mastra/agents/example-support-agent.ts
import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; export const supportAgent = new Agent({ name: "support-agent", description: "Returns technical support for mastra cloud based on runtime context", instructions: async ({ runtimeContext }) => { const userTier = runtimeContext.get("user-tier"); const language = runtimeContext.get("language"); return `You are a customer support agent for [Mastra Cloud](https://mastra.ai/en/docs/mastra-cloud/overview). The current user is on the ${userTier} tier. Support guidance: ${userTier === "free" ? "- Give basic help and link to documentation." : ""} ${userTier === "pro" ? "- Offer detailed technical support and best practices." : ""} ${userTier === "enterprise" ? "- Provide priority assistance with tailored solutions." : ""} Always respond in ${language}.`; }, model: openai("gpt-4o") });

See Agent for a full list of configuration options.

Registering an agent

To use an agent, register it in your main Mastra instance.

src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra"; import { supportAgent } from "./agents/example-support-agent"; export const mastra = new Mastra({ // ... agents: { supportAgent } });

Example usage

Set RuntimeContext using set(), then use getAgent() to retrieve a reference to the agent, then call generate() with a prompt passing in the runtimeContext.

src/test-support-agent.ts
import "dotenv/config"; import { mastra } from "./mastra"; import { RuntimeContext } from "@mastra/core/runtime-context"; type SupportRuntimeContext = { "user-tier": "free" | "pro" | "enterprise"; language: "en" | "es" | "ja"; }; const runtimeContext = new RuntimeContext<SupportRuntimeContext>(); runtimeContext.set("user-tier", "free"); runtimeContext.set("language", "ja"); const agent = mastra.getAgent("supportAgent"); const response = await agent.generate("Can Mastra Cloud handle long-running requests?", { runtimeContext }); console.log(response.text);