Agent 使用 LLM 和 Tool 解决开放式任务。它们会推理目标,并决定使用哪些 Tool。它们会保留对话记忆并持续迭代,直到模型给出最终答案或满足可选的停止条件。
Agent 会生成结构化响应,你可以在 UI 中渲染这些响应或以编程方式处理。你可以直接使用 Agent,也可以将其组合到 Workflow 或多 Agent 系统中。
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.6-sol. 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 @mastra/core@latest zod@latest typescript@latest @types/node@latest mastra@latest
Create a tsconfig.json file:
{
"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:
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({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: '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. No provider import is needed for this format. Don't install any AI SDK package unless Mastra's documentation says otherwise.
By defining the model using provider/model format Mastra automatically looks for environment variables for the 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.6-sol, 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.
Add a tool an agent by importing the tool and passing it to the agent constructor as a tools object.
Example:
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.
`,
model: 'openai/gpt-5.6-sol',
tools: { weatherTool },
})
Create a Mastra entry point at src/mastra/index.ts and register the agent:
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:
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)
当任务是开放式的,且无法预先确定具体步骤时,请使用 Agent。Agent 会决定调用哪些 Tool、循环多少次以及何时停止。你只需提供目标和约束,无需定义每个步骤。对于控制流明确、预先确定的多步骤流程,请改用 Workflow。
观看 Mastra Agent 快速入门,快速了解如何创建和测试 Mastra Agent。
从 @mastra/core 实例化 Agent 类并提供必填属性,以创建 Agent:
src/mastra/agents/test-agent.ts
import { Agent } from '@mastra/core/agent'
export const testAgent = new Agent({
id: 'test-agent',
name: 'Test Agent',
instructions: 'You are a helpful assistant.',
model: 'openai/gpt-5.6-sol',
})
instructions 定义 Agent 的行为、个性和能力。它们是系统级提示词,用于确立 Agent 的核心身份和专长。model 使用 Mastra 的模型路由器,以 'provider/model-name' 格式指定。
要让整个应用都能使用该 Agent,请将其注册到 Mastra 实例(通常位于 src/mastra/index.ts)中:
src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { testAgent } from './agents/test-agent'
export const mastra = new Mastra({
agents: { testAgent },
})
注册后,可以从 Workflow、Tool 或其他 Agent 调用它,并可访问内存、日志和可观测性功能等共享资源。
有关可用属性和配置的更多信息,请参阅 Agent 参考。
使用 Studio 通过不同消息测试 Agent,检查 Tool 调用和响应,并调试 Agent 行为。
注册后,使用 mastra.getAgentById() 获取 Agent。调用 .generate() 获得完整响应,或调用 .stream() 实时传输 token。你可以从 Workflow 步骤、Tool、Mastra Client、路由处理程序、服务器适配器或命令行调用 Agent。请参阅指南,了解如何在所选框架中使用 Agent。
从 Mastra 实例引用 Agent 时,请使用 mastra.getAgentById(),以确保它能访问实例级存储、日志和 Agent 注册表等共享服务。直接导入的 Agent 仍可使用自己的本地配置运行,但无法访问这些共享服务。
在所有 Tool 调用和步骤完成后返回完整响应。结果包括 text、toolCalls、toolResults、steps 和 token usage 统计信息。
有关响应结构(包括 Tool 调用和 Tool 结果的 payload),请参阅 Agent.generate() 参考。
const agent = mastra.getAgentById('test-agent')
const response = await agent.generate('Help me organize my day')
console.log(response.text)
返回一个可在 token 到达时使用的流。结果公开 textStream 用于增量输出,还公开 toolCalls、toolResults、steps 和 token usage 的 Promise,它们会在流结束时解析。
有关流结构(包括 Tool 调用和 Tool 结果的 payload),请参阅 MastraModelOutput 参考。
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)
}
Agent 运行后,可使用下表找到接下来要执行的操作所对应的页面:
多 Agent 系统使用多个 Agent 解决对单个 Agent 而言过于宽泛或专业化的任务。你无需构建一个包含数十个 Tool 和冗长指令集的 Agent,而是可以将职责拆分给各个专用 Agent,再由协调者汇总结果。
阅读多 Agent 系统概念概览,了解如何在 Mastra 中应用不同模式。