Skip to main content

Creating Agents

This guide walks you through creating agents in Mastra, from basic setup to advanced configuration.

Basic Agent Setup

1

Install Dependencies

First, install the required packages:
npm install @mastra/core
2

Import the Agent Class

Import the Agent class from @mastra/core/agent:
import { Agent } from '@mastra/core/agent';
3

Create Your First Agent

Create an agent with minimal configuration:
const agent = new Agent({
  id: 'my-first-agent',
  name: 'My First Agent',
  instructions: 'You are a helpful AI assistant',
  model: 'openai/gpt-4o',
});
4

Use the Agent

Generate a response:
const result = await agent.generate('Hello! Can you help me?');
console.log(result.text);

Configuration Options

Required Fields

Every agent requires these fields:
id
string
required
Unique identifier for the agent. Used for registration and lookups.
name
string
required
Human-readable name for the agent.
instructions
string | SystemMessage | function
required
System prompt that defines the agent’s behavior and personality.
model
string | ModelConfig | ModelConfig[]
required
Language model(s) to use. See Model Configuration for details.

Optional Fields

description
string
Description of the agent’s purpose and capabilities.
tools
object | function
Tools the agent can use. Can be static or dynamically resolved.
agents
object | function
Sub-agents this agent can delegate to.
workflows
object | function
Workflows the agent can execute.
memory
Memory | function
Memory instance for conversation persistence.
workspace
Workspace | function
Workspace for file operations and code execution.
inputProcessors
array
Processors to run before LLM calls.
outputProcessors
array
Processors to run after LLM calls.
maxRetries
number
default:"0"
Maximum retry attempts for failed model calls.
maxProcessorRetries
number
Maximum retries triggered by processors.

Model Configuration

Simple String Format

The easiest way to specify a model:
const agent = new Agent({
  id: 'simple-agent',
  name: 'Simple Agent',
  instructions: 'You are helpful',
  model: 'openai/gpt-4o-mini', // provider/model-name
});
Supported providers:
  • openai/* - OpenAI models (GPT-4, GPT-3.5, etc.)
  • anthropic/* - Anthropic Claude models
  • google/* - Google Gemini models
  • groq/* - Groq models
  • And many more!

Model Object Format

For more control, use an object:
import { openai } from '@ai-sdk/openai';

const agent = new Agent({
  id: 'custom-agent',
  name: 'Custom Agent',
  instructions: 'You are helpful',
  model: openai('gpt-4o', {
    structuredOutputs: true,
  }),
});

Model Fallbacks

Define fallback models for reliability:
const agent = new Agent({
  id: 'reliable-agent',
  name: 'Reliable Agent',
  instructions: 'You are helpful',
  model: [
    { model: 'openai/gpt-4o', maxRetries: 2 },
    { model: 'anthropic/claude-3-5-sonnet-20241022', maxRetries: 2 },
    { model: 'openai/gpt-4o-mini', maxRetries: 1 },
  ],
});
The agent will try each model in order until one succeeds.

Instructions

String Instructions

Simple string format:
const agent = new Agent({
  id: 'chef',
  name: 'Chef Agent',
  instructions: 'You are a professional chef who helps users with recipes and cooking techniques.',
  model: 'openai/gpt-4o',
});

System Message Object

Use the structured format for better control:
const agent = new Agent({
  id: 'chef',
  name: 'Chef Agent',
  instructions: {
    role: 'system',
    content: `You are Michel, a practical and experienced home chef.
    Help users cook great meals with whatever ingredients they have available.
    Explain steps clearly and offer substitutions when needed.`,
  },
  model: 'openai/gpt-4o',
});

Dynamic Instructions

Change instructions based on context:
import { RequestContext } from '@mastra/core/request-context';

const agent = new Agent({
  id: 'support-agent',
  name: 'Support Agent',
  instructions: ({ requestContext }) => {
    const userTier = requestContext.get('userTier');
    const language = requestContext.get('language') || 'en';
    
    if (userTier === 'premium') {
      return `You are a premium support agent. Provide priority assistance in ${language}.`;
    }
    return `You are a support agent. Provide helpful assistance in ${language}.`;
  },
  model: 'openai/gpt-4o',
});

// Use with context
const ctx = new RequestContext();
ctx.set('userTier', 'premium');
ctx.set('language', 'es');

const result = await agent.generate('Necesito ayuda', {
  requestContext: ctx,
});

Real-World Examples

Customer Support Agent

packages/core/src/agent/agent.ts
import { Agent } from '@mastra/core/agent';
import { Memory } from '@mastra/memory';
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

const ticketTool = createTool({
  id: 'create-ticket',
  description: 'Create a support ticket',
  inputSchema: z.object({
    subject: z.string(),
    description: z.string(),
    priority: z.enum(['low', 'medium', 'high']),
  }),
  execute: async ({ subject, description, priority }) => {
    // Create ticket in your system
    return { ticketId: '12345', status: 'created' };
  },
});

const supportAgent = new Agent({
  id: 'support-agent',
  name: 'Support Agent',
  description: 'Handles customer support inquiries',
  instructions: `You are a customer support agent.
    Be helpful, empathetic, and professional.
    Create tickets for issues that require follow-up.`,
  model: 'openai/gpt-4o',
  tools: {
    ticketTool,
  },
  memory: new Memory(),
});

Research Agent with Workspace

import { Agent } from '@mastra/core/agent';
import { Workspace, LocalFilesystem } from '@mastra/core/workspace';

const workspace = new Workspace({
  filesystem: new LocalFilesystem({
    basePath: './research-data',
  }),
});

const researchAgent = new Agent({
  id: 'research-agent',
  name: 'Research Agent',
  description: 'Conducts research and saves findings',
  instructions: `You are a research agent.
    When researching topics:
    1. Gather comprehensive information
    2. Save your findings to files
    3. Cite sources
    4. Provide summaries`,
  model: 'openai/gpt-4o',
  workspace,
});

// Agent can now use workspace tools automatically:
// - write_file
// - read_file
// - list_files
// - delete_file

Multi-Agent Supervisor

From: examples/agent/src/mastra/agents/model-v2-agent.ts
import { Agent } from '@mastra/core/agent';
import { Memory } from '@mastra/memory';
import { createScorer } from '@mastra/core/evals';

const researchAgent = new Agent({
  id: 'research-agent',
  name: 'Research Agent',
  instructions: 'You perform detailed research on topics',
  model: 'openai/gpt-4o-mini',
});

const analysisAgent = new Agent({
  id: 'analysis-agent',
  name: 'Analysis Agent',
  instructions: 'You analyze data and provide insights',
  model: 'openai/gpt-4o-mini',
});

const supervisorAgent = new Agent({
  id: 'supervisor',
  name: 'Research Supervisor',
  description: 'Coordinates research and analysis',
  instructions: `You coordinate complex research tasks.
    Workflow:
    1. Break down the request into tasks
    2. Delegate to research-agent for information
    3. Delegate to analysis-agent for insights
    4. Synthesize results`,
  model: 'openai/gpt-4o',
  agents: {
    researchAgent,
    analysisAgent,
  },
  memory: new Memory(),
  defaultOptions: {
    maxSteps: 10,
    delegation: {
      onDelegationStart: async ({ primitiveId, prompt }) => {
        console.log(`Delegating to ${primitiveId}`);
        return { proceed: true };
      },
      onDelegationComplete: async ({ primitiveId, result }) => {
        console.log(`${primitiveId} completed`);
      },
    },
  },
});

Validation & Type Safety

Request Context Schema

Validate request context values:
import { z } from 'zod';

const agent = new Agent({
  id: 'typed-agent',
  name: 'Typed Agent',
  instructions: 'You are helpful',
  model: 'openai/gpt-4o',
  requestContextSchema: z.object({
    userId: z.string(),
    tenantId: z.string(),
    roles: z.array(z.string()),
  }),
});

// This will validate context before execution
const ctx = new RequestContext();
ctx.set('userId', '123');
ctx.set('tenantId', 'acme');
ctx.set('roles', ['admin']);

await agent.generate('Hello', { requestContext: ctx });

Best Practices

Choose IDs that are URL-safe and names that clearly describe the agent’s purpose:
// Good
id: 'customer-support-agent'
name: 'Customer Support Agent'

// Avoid
id: 'agent1'
name: 'Agent'
Be explicit about the agent’s role, constraints, and behavior:
instructions: `You are a technical support specialist for SaaS products.
- Always ask for error messages and screenshots
- Provide step-by-step troubleshooting
- Escalate to engineering if issue persists after 3 attempts
- Be patient and encouraging`
Configure fallbacks to handle API outages:
model: [
  { model: 'openai/gpt-4o', maxRetries: 2 },
  { model: 'anthropic/claude-3-5-sonnet-20241022', maxRetries: 1 },
]
Use functions for context-dependent behavior:
tools: ({ requestContext }) => {
  // Return different tools based on user permissions
  const permissions = requestContext.get('permissions');
  return filterToolsByPermissions(allTools, permissions);
}

Next Steps

Tools

Learn how to add tools to your agents

Streaming

Implement real-time streaming responses

Structured Output

Get typed, validated output from agents

Memory

Add conversation persistence with memory

Build docs developers (and LLMs) love