> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Agents 概覽 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/`, not `openai:`, 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: ```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({ 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/` requires the `OPENAI_API_KEY` environment variable. Go to 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 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: ```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.6-sol', tools: { weatherTool }, }) ``` 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) ``` ## 何時使用 Agent 當任務屬於開放式,而且無法預先確定執行步驟時,便適合使用 Agent。Agent 會決定要調用哪些 Tool、循環多少次,以及何時停止。你只需提供目標和限制條件,毋須逐一定義每個步驟。對於已有明確控制流程、預先設定的多步驟程序,應改用 [Workflow](https://mastra.zisheng.pro/zh-HK/docs/workflows/overview)。 > **📹 觀看影片:** 觀看 [Mastra Agent 快速入門](https://www.youtube.com/watch?v=G8tXjcseNjg),透過簡短示範了解如何建立和測試 Mastra Agent。 ## 快速入門 從 `@mastra/core` 實例化 `Agent` 類別並提供必要屬性,即可建立 Agent: ```typescript 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 的[模型路由器](https://mastra.zisheng.pro/zh-HK/models)指定。 如要讓整個應用程式都可以使用 Agent,請在 Mastra 實例中註冊它(通常位於 `src/mastra/index.ts`): ```typescript import { Mastra } from '@mastra/core' import { testAgent } from './agents/test-agent' export const mastra = new Mastra({ agents: { testAgent }, }) ``` 註冊後,Workflow、Tool 或其他 Agent 都可以調用它,而它亦可存取記憶、日誌記錄和可觀察性功能等共享資源。 有關可用屬性和設定的詳細資訊,請參閱 [Agent 參考資料](https://mastra.zisheng.pro/zh-HK/reference/agents/agent)。 > **提示:** 使用 [Studio](https://mastra.zisheng.pro/zh-HK/docs/studio/overview) 以不同訊息測試 Agent、檢視 Tool 調用和回應,以及除錯 Agent 行為。 ## 使用你的 Agent 註冊後,透過 [`mastra.getAgentById()`](https://mastra.zisheng.pro/zh-HK/reference/core/getAgentById) 取得 Agent。調用 `.generate()` 以取得完整回應,或調用 `.stream()` 即時傳送 token。你可以從 [Workflow 步驟](https://mastra.zisheng.pro/zh-HK/docs/workflows/agents-and-tools)、[Tool](https://mastra.zisheng.pro/zh-HK/docs/agents/using-tools)、[Mastra Client](https://mastra.zisheng.pro/zh-HK/reference/client-js/mastra-client)、路由處理程式、[伺服器適配器](https://mastra.zisheng.pro/zh-HK/docs/server/server-adapters)或命令列調用 Agent。請參閱[指南部分](https://mastra.zisheng.pro/zh-HK/guides),了解如何在你選用的框架中使用 Agent。 從 Mastra 實例引用 Agent 時,請使用 `mastra.getAgentById()`,確保它可以存取實例層級儲存空間、日誌記錄和 Agent 註冊表等共享服務。直接匯入的 Agent 仍可配合本身的本地設定運作,但無法存取這些共享服務。 **.generate()**: 在所有 Tool 調用和步驟完成後傳回完整回應。結果包括 `text`、`toolCalls`、`toolResults`、`steps` 和 token `usage` 統計資料。 有關回應結構,包括 Tool 調用和 Tool 結果的 payload,請參閱 [`Agent.generate()` 參考資料](https://mastra.zisheng.pro/zh-HK/reference/agents/generate)。 ```ts const agent = mastra.getAgentById('test-agent') const response = await agent.generate('Help me organize my day') console.log(response.text) ``` **.stream()**: 傳回可在 token 到達時取用的串流。結果提供 `textStream` 以進行增量輸出,並提供 `toolCalls`、`toolResults`、`steps` 和 token `usage` 的 Promise;這些 Promise 會在串流結束時 resolve。 有關串流結構,包括 Tool 調用和 Tool 結果的 payload,請參閱 [`MastraModelOutput` 參考資料](https://mastra.zisheng.pro/zh-HK/reference/streaming/agents/MastraModelOutput)。 ```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) } ``` ## 擴展你的 Agent Agent 開始運作後,可透過下表找到適合的頁面,了解下一步如何完成所需操作: | 目標 | 從這裏開始 | | ----------------------------- | -------------------------------------------------------------------------------- | | 為 Agent 提供 Tool,以調用外部 API 或服務 | [Tool](https://mastra.zisheng.pro/zh-HK/docs/agents/using-tools) | | 跨對話保留上下文和偏好設定 | [記憶](https://mastra.zisheng.pro/zh-HK/docs/memory/overview) | | 傳回類型化物件,而非純文字 | [結構化輸出](https://mastra.zisheng.pro/zh-HK/docs/agents/structured-output) | | Human-in-the-loop:暫停執行並等候人工批准 | [批准](https://mastra.zisheng.pro/zh-HK/docs/agents/agent-approval) | | 建立多 Agent 網絡 | [Supervisor Agent](https://mastra.zisheng.pro/zh-HK/docs/capabilities/subagents) | | 註冊子 Agent | [Tool](https://mastra.zisheng.pro/zh-HK/docs/agents/using-tools) | | 在生成前後攔截或轉換訊息 | [Processor](https://mastra.zisheng.pro/zh-HK/docs/agents/processors) | | 確保 Agent 安全 | [Guardrail](https://mastra.zisheng.pro/zh-HK/docs/agents/guardrails) | | 建立能修正自身工作的 Agent | [Rubric scorer](https://mastra.zisheng.pro/zh-HK/docs/capabilities/subagents) | | 根據請求上下文切換指令或模型 | [動態設定](https://mastra.zisheng.pro/zh-HK/docs/server/request-context) | | 加入語音轉文字或文字轉語音 | [語音](https://mastra.zisheng.pro/zh-HK/guides/voice/overview) | | 連接 Slack、Discord 或 Telegram | [Channel](https://mastra.zisheng.pro/zh-HK/docs/capabilities/channels/overview) | ## 多 Agent 系統 多 Agent 系統會使用多個 Agent,解決對單一 Agent 而言範圍過廣或過於專門的任務。與其建立一個配備數十個 Tool 和冗長指令集的 Agent,你可以將職責分配給各個專注於特定工作的 Agent,再由協調 Agent 匯集結果。 請閱讀[多 Agent 系統的概念概覽](https://mastra.zisheng.pro/zh-HK/guides/concepts/multi-agent-systems),了解如何運用 Mastra 實施不同模式。