Skip to Content
ExamplesAgentsChanging the System Prompt

Changing the System Prompt

When creating an agent, the instructions define the general rules for its behavior. They establish the agent’s role, personality, and overall approach, and remain consistent across all interactions. A system prompt can be passed to .generate() to influence how the agent responds in a specific request, without modifying the original instructions.

In this example, the system prompt is used to change the agent’s voice between different Harry Potter characters, demonstrating how the same agent can adapt its style while keeping its core setup unchanged.

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

Define the agent and provide instructions, which set its default behavior and describe how it should respond when no system prompt is supplied at runtime.

src/mastra/agents/example-harry-potter-agent.ts
import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; export const harryPotterAgent = new Agent({ name: "harry-potter-agent", description: "Provides character-style responses from the Harry Potter universe.", instructions: `You are a character-voice assistant for the Harry Potter universe. Reply in the speaking style of the requested character (e.g., Harry, Hermione, Ron, Dumbledore, Snape, Hagrid). If no character is specified, default to Harry Potter.`, 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 { harryPotterAgent } from "./agents/example-harry-potter-agent"; export const mastra = new Mastra({ // ... agents: { harryPotterAgent } });

Default character response

Use getAgent() to retrieve the agent and call generate() with a prompt. As defined in the instructions, this agent defaults to Harry Potter’s voice when no character is specified.

src/test-harry-potter-agent.ts
import "dotenv/config"; import { mastra } from "./mastra"; const agent = mastra.getAgent("harryPotterAgent"); const response = await agent.generate("What is your favorite room in Hogwarts?"); console.log(response.text);

Changing the character voice

By providing a different system prompt at runtime, the agent’s voice can be switched to another character. This changes how the agent responds for that request without altering its original instructions.

src/test-harry-potter-agent.ts
import "dotenv/config"; import { mastra } from "./mastra"; const agent = mastra.getAgent("harryPotterAgent"); const response = await agent.generate([ { role: "system", content: "You are Draco Malfoy." }, { role: "user", content: "What is your favorite room in Hogwarts?" } ]); console.log(response.text);
View Example on GitHub (outdated)