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 使用 'provider/model-name' 格式,並透過 Mastra 的模型路由器指定。
如要讓整個應用程式都可以使用 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;這些 Promise 會在串流結束時 resolve。
有關串流結構,包括 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 匯集結果。
請閱讀多 Agent 系統的概念概覽,了解如何運用 Mastra 實施不同模式。