Skip to main content

Agents Overview

Agents are the core building blocks of Mastra. They provide a high-level abstraction for AI interactions, managing language models, tools, memory, and workflows in a cohesive way.

What is an Agent?

An agent in Mastra is an AI entity that can:
  • Respond to user messages with text or structured data
  • Use tools to perform actions and access external systems
  • Delegate tasks to other agents or workflows
  • Remember conversations across sessions using memory
  • Work with files through workspace integration
  • Execute workflows for complex multi-step operations

Core Capabilities

Language Model Integration

Agents wrap language models (LLMs) from various providers:
import { Agent } from '@mastra/core/agent';

const agent = new Agent({
  id: 'my-agent',
  name: 'My Agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-4o', // Simple string format
});

Tool Usage

Agents can use tools to extend their capabilities:
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

const weatherTool = createTool({
  id: 'get-weather',
  description: 'Get weather for a location',
  inputSchema: z.object({
    location: z.string(),
  }),
  execute: async ({ location }) => {
    return { temp: 72, condition: 'sunny' };
  },
});

const agent = new Agent({
  id: 'weather-agent',
  name: 'Weather Agent',
  instructions: 'Help users with weather information',
  model: 'openai/gpt-4o',
  tools: {
    weatherTool,
  },
});

Memory & Conversations

Agents can persist conversations and recall context:
import { Memory } from '@mastra/memory';

const agent = new Agent({
  id: 'support-agent',
  name: 'Support Agent',
  instructions: 'You are a customer support assistant',
  model: 'openai/gpt-4o',
  memory: new Memory(),
});

// Generate with memory
await agent.generate('What were we talking about?', {
  memory: {
    resource: 'user-123',
    thread: { id: 'thread-456' },
  },
});

Multi-Agent Collaboration

Agents can delegate work to specialized sub-agents:
const researchAgent = new Agent({
  id: 'research-agent',
  name: 'Research Agent',
  instructions: 'You perform detailed research',
  model: 'openai/gpt-4o',
});

const supervisorAgent = new Agent({
  id: 'supervisor',
  name: 'Supervisor',
  instructions: 'Coordinate research and analysis tasks',
  model: 'openai/gpt-4o',
  agents: {
    researchAgent,
  },
});

Agent Execution Methods

Generate (Non-Streaming)

Get a complete response in one call:
const result = await agent.generate('Hello!');
console.log(result.text); // Full response text
console.log(result.toolCalls); // Tools that were called

Stream (Real-time)

Stream responses token-by-token for better UX:
const stream = await agent.stream('Tell me a story');

for await (const chunk of stream.textStream) {
  process.stdout.write(chunk);
}

Network (Multi-Primitive)

Orchestrate complex workflows with agents, tools, and workflows:
const stream = await agent.network('Build a feature and test it', {
  maxSteps: 20,
  completion: {
    scorers: [testScorer],
    strategy: 'all',
  },
});

Agent Configuration Options

OptionTypeDescription
idstringUnique identifier for the agent
namestringHuman-readable name
instructionsstring | object | functionSystem prompt defining behavior
modelstring | object | arrayLanguage model configuration
toolsobject | functionTools the agent can use
agentsobject | functionSub-agents for delegation
workflowsobject | functionWorkflows the agent can execute
memoryMemory | functionMemory for conversation persistence
workspaceWorkspace | functionFile system and code execution
inputProcessorsarrayPre-process messages before LLM
outputProcessorsarrayPost-process messages after LLM
maxRetriesnumberRetry attempts for failed calls

Dynamic Configuration

Many agent options support dynamic resolution using functions:
import { RequestContext } from '@mastra/core/request-context';

const agent = new Agent({
  id: 'dynamic-agent',
  name: 'Dynamic Agent',
  // Dynamic instructions based on context
  instructions: ({ requestContext }) => {
    const userRole = requestContext.get('userRole');
    return userRole === 'admin'
      ? 'You have admin privileges'
      : 'You have standard privileges';
  },
  // Dynamic tools based on context
  tools: ({ requestContext }) => {
    const tier = requestContext.get('tier');
    return tier === 'premium'
      ? { ...basicTools, ...premiumTools }
      : basicTools;
  },
  model: 'openai/gpt-4o',
});

Next Steps

Creating Agents

Learn how to create and configure agents

Tools

Add tools to extend agent capabilities

Streaming

Stream responses in real-time

Structured Output

Get typed, validated responses

Build docs developers (and LLMs) love