@mastra/core
Version:
214 lines (155 loc) • 12 kB
Markdown
> Discover all available pages from the documentation index: https://mastra.ai/llms.txt
# Agents overview
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. Agents produce structured responses you can render in your UI or process programmatically. Use agents directly or compose them into workflows or multi-agent systems.
**For AI agents:** If you're tasked to build a Mastra project from scratch, follow the condensed instructions until the next heading. Adjust the example code for the agent & tool to your needs. Important for later: Define `model` as a string in `provider/model` format, for example `openai/gpt-5.5`. For OpenAI, use `openai/<model>`, not `openai:<model>`, and don't import or pass a provider object.
Create a `package.json` file with `{ "type": "module" }`. Install the required dependencies: `npm install /core@latest zod@latest typescript@latest @types/node mastra`
Create a tsconfig.json file:
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"outDir": "dist"
},
"include": ["src/**/*"]
}
```
If you need to add a tool to the agent, create a new file and use `import { createTool } from "@mastra/core/tools"`. Plain object tool definitions silently fail to execute; tools MUST be defined via `createTool()` with `id`, `description`, `inputSchema` (zod), `execute()`. `execute()` receives two parameters: the validated input data based on inputSchema (first parameter) and an optional execution context object (second parameter) containing `requestContext`, `tracingContext`, `abortSignal`, and other execution metadata.
Example:
```ts
// src/mastra/tools/weather-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'get-weather',
description: 'Get current weather for a location',
inputSchema: z.object({
location: z.string().describe('City name'),
}),
outputSchema: z.object({
output: z.string(),
}),
execute: async ({ location }) => {
return {
output: `The weather in ${location} is sunny`,
}
},
})
```
If you need to create an agent, create a new file and use `import { Agent } from "@mastra/core/agent"`. The constructor takes `{ id, name, instructions, model }`. The `model` property is a string in Mastra's model router format: `provider/model`, for example `openai/gpt-5.5`. For OpenAI models, use `openai/<model>`, not `openai:<model>`, and don't pass a provider object. No provider import is needed for this format. Do not install any AI SDK package unless Mastra's documentation says otherwise.
Add a tool an agent by importing the tool and passing it to the agent constructor as a tools object.
Example:
```ts
// src/mastra/agents/weather-agent.ts
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool.ts'
export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: `
You are a helpful weather assistant that provides accurate weather information.
Your primary function is to help users get weather details for specific locations. When responding:
- Include relevant details like humidity, wind conditions, and precipitation
- Keep responses concise but informative
Use the weatherTool to fetch current weather data.
`,
// Use a string in provider/model format, not provider:model or a provider object.
model: 'openai/gpt-5.5',
tools: { weatherTool },
})
```
By defining the model using `provider/model` format Mastra automatically looks for environment variables for the given provider. The defined model requires an environment variable to be set for the provider. OpenAI: `OPENAI_API_KEY`. Anthropic: `ANTHROPIC_API_KEY`. Google: `GOOGLE_API_KEY`. Example: Any `openai/<model>` requires the `OPENAI_API_KEY` environment variable. Go to <https://mastra.ai/models/environment-variables> for a full list of supported providers and their environment variable names.
Short list of known model IDs are:
- `openai/gpt-5.5`, `openai/gpt-5-mini`
- `anthropic/claude-sonnet-4-6`, `anthropic/claude-opus-4-7`, `anthropic/claude-haiku-4-5`
- `google/gemini-2.5-flash`
Go to <https://mastra.ai/models> for a full list of supported models.
Create a Mastra entry point at `src/mastra/index.ts` and register the agent:
```ts
import { Mastra } from '@mastra/core'
import { weatherAgent } from './agents/weather-agent.ts'
export const mastra = new Mastra({
agents: { weatherAgent },
})
```
You're now able to run the agent directly. For this, import the Mastra instance and call the agent.generate() after retrieving the agent by its id. Node.js 22.18.0 and later are able to run TypeScript files directly. Make sure to add file extensions when importing local files. Example:
```ts
// run.mjs
import { mastra } from './src/mastra/index.ts'
const agent = mastra.getAgentById('weather-agent')
const response = await agent.generate('Weather in SF')
console.log(response.text)
```
## When to use agents
Use agents when the task is open-ended and the steps aren't known in advance. An agent decides which tools to call, how many times to loop, and when to stop. You provide the goal and constraints instead of defining each step. For predetermined, multi-step processes with explicit control flow, use [workflows](https://mastra.ai/docs/workflows/overview) instead.
> **Tip:** Watch an introduction to agents, and how they compare to workflows on [YouTube (7 minutes)](https://youtu.be/0jg2g3sNvgw).
## Quickstart
Create an agent by instantiating the `Agent` class from `/core` and provide the required properties:
```typescript
import { Agent } from '/core/agent'
export const testAgent = new Agent({
id: 'test-agent',
name: 'Test Agent',
instructions: 'You are a helpful assistant.',
model: 'openai/gpt-5.5',
})
```
The `instructions` define the agent's behavior, personality, and capabilities. They're system-level prompts that establish the agent's core identity and expertise. The `model` is specified as `'provider/model-name'` using Mastra's [model router](https://mastra.ai/models).
To make the agent available throughout your application, register it in your Mastra instance (typically located in `src/mastra/index.ts`):
```typescript
import { Mastra } from '/core'
import { testAgent } from './agents/test-agent'
export const mastra = new Mastra({
agents: { testAgent },
})
```
Once registered, it can be called from workflows, tools, or other agents, and has access to shared resources such as memory, logging, and observability features.
> **Tip:** Use [Studio](https://mastra.ai/docs/studio/overview) to test your agent with different messages, inspect tool calls and responses, and debug agent behavior.
> **Note:** Visit the [agent reference](https://mastra.ai/reference/agents/agent) for more information on available properties and configurations.
## Use your agent
After registration, retrieve your agent with [`mastra.getAgentById()`](https://mastra.ai/reference/core/getAgentById). Call `.generate()` for a complete response or `.stream()` to deliver tokens in real time. You can call agents from [workflow steps](https://mastra.ai/docs/workflows/agents-and-tools), [tools](https://mastra.ai/docs/agents/using-tools), the [Mastra Client](https://mastra.ai/reference/client-js/mastra-client), route handlers, [server adapters](https://mastra.ai/docs/server/server-adapters), or the command line. Visit the [guides section](https://mastra.ai/guides) to learn how to use agents in your framework of choice.
When referencing an agent from your Mastra instance, use `mastra.getAgentById()` to ensure it has access to shared services such as instance-level storage, logging, and agent registry. A directly imported agent can still work with its own local configuration, but it won't have access to those shared services.
**.generate()**:
Returns the full response after all tool calls and steps complete. The result includes `text`, `toolCalls`, `toolResults`, `steps`, and token `usage` statistics.
See the [`Agent.generate()` reference](https://mastra.ai/reference/agents/generate) for the response shape, including tool call and tool result payloads.
```ts
const agent = mastra.getAgentById('test-agent')
const response = await agent.generate('Help me organize my day')
console.log(response.text)
```
**.stream()**:
Returns a stream you can consume as tokens arrive. The result exposes `textStream` for incremental output and promises for `toolCalls`, `toolResults`, `steps`, and token `usage` that resolve when the stream finishes.
See the [`MastraModelOutput` reference](https://mastra.ai/reference/streaming/agents/MastraModelOutput) for the stream shape, including tool call and tool result payloads.
```ts
const agent = mastra.getAgentById('test-agent')
const stream = await agent.stream('Help me organize my day')
for await (const chunk of stream.textStream) {
process.stdout.write(chunk)
}
```
## Expand your agent
Once your agent is running, use this table to find the right page for what you want to do next:
| Goal | Start here |
| -------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Give your agent tools to call external APIs or services | [Tools](https://mastra.ai/docs/agents/using-tools) |
| Keep context and preferences across conversations | [Memory](https://mastra.ai/docs/memory/overview) |
| Get typed objects back instead of plain text | [Structured output](https://mastra.ai/docs/agents/structured-output) |
| Human-in-the-loop: Pause execution and wait for human approval | [Approval](https://mastra.ai/docs/agents/agent-approval) |
| Build a multi-agent network | [Supervisor agents](https://mastra.ai/docs/agents/supervisor-agents) |
| Register subagents | [Tools](https://mastra.ai/docs/agents/using-tools) |
| Intercept or transform messages before and after generation | [Processors](https://mastra.ai/docs/agents/processors) |
| Keep your agent safe | [Guardrails](https://mastra.ai/docs/agents/guardrails) |
| Build agents that correct their work | [Rubric scorer](https://mastra.ai/docs/agents/supervisor-agents) |
| Swap instructions or models based on request context | [Dynamic configuration](https://mastra.ai/docs/server/request-context) |
| Add speech-to-text or text-to-speech | [Voice](https://mastra.ai/docs/voice/overview) |
| Connect to Slack, Discord, or Telegram | [Channels](https://mastra.ai/docs/agents/channels) |
## Multi-agent systems
A multi-agent system uses multiple agents to solve a task that's too broad or too specialized for a single agent. Instead of building one agent with dozens of tools and a long instruction set, you split responsibilities across focused agents and let a coordinator bring results together.
Read the [conceptual overview of multi-agent systems](https://mastra.ai/guides/concepts/multi-agent-systems) to learn how you can apply different patterns with Mastra.