Agents
Create AI agents with tools, memory, and multi-agent coordination
Agents
Agents use LLMs and tools to solve open-ended tasks. They reason about goals, decide which tools to use, retain conversation memory, and iterate internally until the model emits a final answer or an optional stop condition is met.
Topics
- Overview - Introduction to agents
- Tools - Equip agents with tools to take actions
- Structured Output - Generate typed responses
- Supervisor Agents - Coordinate multiple agents
- Processors - Transform agent inputs and outputs
- Guardrails - Safety and content filtering
- Agent Approval - Require human approval for actions
- Voice - Add voice capabilities to agents
- Channels - Connect agents to different platforms
- Networks - Connect multiple agents together
Agent Overview
Agents are the core building blocks of Mastra applications. They combine LLMs with tools, memory, and other capabilities to perform tasks.
Creating an Agent
import { Mastra } from '@mastra/core';
export const mastra = new Mastra({
agents: {
myAgent: {
name: 'My Agent',
instructions: 'You are a helpful assistant',
model: 'gpt-4',
},
},
});
Key Concepts
- Instructions - System prompts that define agent behavior
- Tools - Functions the agent can call to take actions
- Memory - Conversation history and context retention
- Model - The LLM that powers the agent
Agent Lifecycle
- User sends a message
- Agent retrieves relevant context from memory
- Agent reasons and decides on tool calls
- Agent executes tools and receives results
- Agent generates a final response
- Interaction is stored in memory
Agent Tools
Tools extend agent capabilities by allowing them to interact with external systems and perform actions.
Creating Tools
import { createTool } from '@mastra/tools';
const weatherTool = createTool({
name: 'getWeather',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string().describe('The city name'),
}),
execute: async ({ location }) => {
// Call weather API
return { temp: 72, conditions: 'sunny' };
},
});
Tool Types
- Data tools - Fetch information
- Action tools - Perform actions
- Transformation tools - Process and transform data
Assigning Tools to Agents
export const mastra = new Mastra({
agents: {
myAgent: {
name: 'My Agent',
instructions: 'You are a helpful weather assistant',
tools: [weatherTool],
},
},
});
Structured Output
Generate type-safe, structured responses from agents using Zod schemas.
Defining Output Schema
import { z } from 'zod';
const weatherResponseSchema = z.object({
location: z.string(),
temperature: z.number(),
conditions: z.string(),
recommendation: z.string().optional(),
});
Using Structured Output
const agent = mastra.getAgent('weatherAgent');
const response = await agent.generate(
'What is the weather in San Francisco?',
{
outputSchema: weatherResponseSchema,
}
);
const data = response.object; // Typed as weatherResponseSchema
Benefits
- Type-safe responses
- Consistent output format
- Easy integration with downstream systems
Supervisor Agents
Supervisor agents coordinate multiple specialized agents to handle complex tasks.
Architecture
A supervisor agent:
- Breaks down complex tasks
- Delegates to specialized sub-agents
- Synthesizes results from multiple agents
- Ensures quality and consistency
Example
const supervisor = mastra.getAgent('supervisorAgent');
// The supervisor automatically routes tasks to specialized agents
const result = await supervisor.generate(
'Research and summarize the latest AI developments'
);
When to Use Supervisor Agents
- Complex multi-step workflows
- Tasks requiring different expertise areas
- Systems that need to balance multiple priorities
Agent Processors
Processors transform agent inputs and outputs, enabling custom preprocessing and postprocessing.
Built-in Processors
- MessageHistory - Manage conversation history
- ModerationProcessor - Content moderation
- PIIDetector - PII detection and handling
- TokenLimiterProcessor - Control token usage
- SemanticRecall - Retrieve semantically similar memories
Creating Custom Processors
import { Processor } from '@mastra/core';
const myProcessor = new Processor({
name: 'myProcessor',
process: async (input, context) => {
// Transform input or output
return transformedInput;
},
});
Applying Processors
export const mastra = new Mastra({
agents: {
myAgent: {
name: 'My Agent',
processors: [myProcessor],
},
},
});
Guardrails
Guardrails ensure agents operate within defined safety boundaries.
Types of Guardrails
- Input validation - Sanitize user inputs
- Output filtering - Filter potentially harmful outputs
- Tool restrictions - Limit which tools can be called
- Rate limiting - Prevent abuse
Configuring Guardrails
export const mastra = new Mastra({
agents: {
myAgent: {
name: 'My Agent',
guardrails: {
inputFilter: myInputFilter,
outputFilter: myOutputFilter,
allowedTools: ['search', 'calculator'],
},
},
},
});
Agent Approval
Require human approval before agents execute certain actions.
When to Use Approvals
- Destructive actions (delete, cancel)
- Financial transactions
- External API calls with side effects
- Actions exceeding certain thresholds
Configuration
export const mastra = new Mastra({
agents: {
myAgent: {
name: 'My Agent',
approvalRules: {
requireApprovalFor: ['delete*', 'sendEmail', 'processPayment'],
approvers: ['admin@example.com'],
},
},
},
});
Approval Flow
- Agent determines an action requires approval
- Agent pauses and sends approval request
- Human reviews and approves/rejects
- Agent continues or aborts based on decision
Voice
Add voice capabilities to agents for conversational interactions.
Voice Providers
- OpenAI
- ElevenLabs
- Azure
- Deepgram
- And more...
Configuration
export const mastra = new Mastra({
agents: {
myAgent: {
name: 'Voice Agent',
voice: {
provider: 'openai',
voice: 'alloy',
},
},
},
});
Features
- Text-to-speech responses
- Speech-to-text input
- Real-time voice conversations
- Voice activity detection
Channels
Channels connect agents to different platforms and communication channels.
Supported Channels
- Webhook - HTTP endpoints
- Slack - Slack integrations
- Discord - Discord bots
- WhatsApp - WhatsApp Business
- Custom - Build your own channel adapter
Creating a Channel
import { WebhookChannel } from '@mastra/channels';
const channel = new WebhookChannel({
agent: myAgent,
path: '/webhook',
});
Channel Events
Channels handle:
- Incoming messages
- Outgoing responses
- Error handling
- Rate limiting
Agent Networks
Connect multiple agents together to form collaborative networks.
Network Types
- Supervisor networks - One agent coordinates others
- Peer networks - Agents collaborate as equals
- Hierarchical networks - Multiple levels of specialization
Creating a Network
export const mastra = new Mastra({
agents: {
coordinator: {
name: 'Coordinator',
network: {
type: 'supervisor',
agents: ['researcher', 'writer', 'editor'],
},
},
},
});
Communication Patterns
- Request-response - One agent asks, another answers
- Broadcast - One agent sends to multiple agents
- Aggregation - Multiple agents contribute to a single result