> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Agent 概觀 Agent 使用 LLM 和 Tool 解決開放式任務。它們會推理目標並決定要使用哪些 Tool,也會保留對話記憶並持續反覆執行,直到模型產生最終答案,或符合選用的停止條件為止。 Agent 會產生結構化回應,供你在 UI 中呈現或透過程式處理。你可以直接使用 Agent,也可以將它們組合成 Workflow 或多 Agent 系統。 **給 AI Agent:** 若你的任務是從零開始建立 Mastra 專案,請依照以下精簡指示操作,直到下一個標題為止。請依需求調整 Agent 與 Tool 的範例程式碼。後續步驟的重要事項:請將 `model` 定義為 `provider/model` 格式的字串,例如 `openai/gpt-5.6-sol`。若使用 OpenAI,請使用 `openai/`,不要使用 `openai:`,也不要匯入或傳入 Provider 物件。 建立包含 `{ "type": "module" }` 的 `package.json` 檔案。安裝必要的相依套件:`npm install @mastra/core@latest zod@latest typescript@latest @types/node@latest mastra@latest` 建立 tsconfig.json 檔案: ```json { "compilerOptions": { "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "noEmit": true, "allowImportingTsExtensions": true, "outDir": "dist" }, "include": ["src/**/*"] } ``` 若需要為 Agent 新增 Tool,請建立新檔案並使用 `import { createTool } from "@mastra/core/tools"`。以純物件定義的 Tool 會無聲地執行失敗;Tool **必須**透過 `createTool()` 定義,並包含 `id`、`description`、`inputSchema`(zod)及 `execute()`。`execute()` 會接收兩個參數:第一個參數是依 inputSchema 驗證過的輸入資料,第二個參數是選用的執行環境物件,其中包含 `requestContext`、`tracingContext`、`abortSignal` 及其他執行中繼資料。 範例: ```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', } }, }) ``` 若需要建立 Agent,請建立新檔案並使用 `import { Agent } from "@mastra/core/agent"`。建構函式接收 `{ id, name, instructions, model }`。`model` 屬性是採用 Mastra 模型路由器格式的字串。此格式不需要匯入 Provider。除非 Mastra 文件另有說明,否則不要安裝任何 AI SDK 套件。 使用 `provider/model` 格式定義模型後,Mastra 會自動尋找該 Provider 的環境變數。所定義的模型必須設定對應 Provider 的環境變數。OpenAI:`OPENAI_API_KEY`。Anthropic:`ANTHROPIC_API_KEY`。Google:`GOOGLE_API_KEY`。例如,任何 `openai/` 都需要 `OPENAI_API_KEY` 環境變數。前往 查看完整的支援 Provider 及其環境變數名稱清單。 以下是已知模型 ID 的簡短清單: - `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` 前往 查看支援模型的完整清單。 若要為 Agent 新增 Tool,請匯入該 Tool,並以 tools 物件形式傳入 Agent 建構函式。 範例: ```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 }, }) ``` 在 `src/mastra/index.ts` 建立 Mastra 進入點並註冊 Agent: ```ts import { Mastra } from '@mastra/core' import { weatherAgent } from './agents/weather-agent.ts' export const mastra = new Mastra({ agents: { weatherAgent }, }) ``` 現在你可以直接執行 Agent。為此,請匯入 Mastra 執行個體,依 ID 取得 Agent 後呼叫 agent.generate()。Node.js 22.18.0 以上版本可直接執行 TypeScript 檔案。匯入本機檔案時,請務必加上副檔名。範例: ```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-TW/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-TW/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-TW/reference/agents/agent)。 > **提示:** 使用 [Studio](https://mastra.zisheng.pro/zh-TW/docs/studio/overview) 以不同訊息測試 Agent、檢查 Tool 呼叫與回應,並偵錯 Agent 行為。 ## 使用你的 Agent 註冊後,使用 [`mastra.getAgentById()`](https://mastra.zisheng.pro/zh-TW/reference/core/getAgentById) 取得 Agent。呼叫 `.generate()` 可取得完整回應,呼叫 `.stream()` 則可即時傳送 token。你可以從 [Workflow 步驟](https://mastra.zisheng.pro/zh-TW/docs/workflows/agents-and-tools)、[Tool](https://mastra.zisheng.pro/zh-TW/docs/agents/using-tools)、[Mastra Client](https://mastra.zisheng.pro/zh-TW/reference/client-js/mastra-client)、路由處理常式、[伺服器介接器](https://mastra.zisheng.pro/zh-TW/docs/server/server-adapters)或命令列呼叫 Agent。請前往[指南](https://mastra.zisheng.pro/zh-TW/guides),了解如何在你選用的框架中使用 Agent。 從 Mastra 執行個體參照 Agent 時,請使用 `mastra.getAgentById()`,確保它能存取執行個體層級的儲存空間、記錄與 Agent 登錄檔等共用服務。直接匯入的 Agent 仍可使用自身的本機設定運作,但無法存取這些共用服務。 **.generate()**: 在所有 Tool 呼叫與步驟完成後傳回完整回應。結果包含 `text`、`toolCalls`、`toolResults`、`steps`,以及 token `usage` 統計資料。 如需回應結構的詳細資訊(包括 Tool 呼叫與 Tool 結果的承載資料),請參閱 [`Agent.generate()` 參考文件](https://mastra.zisheng.pro/zh-TW/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 會在串流結束時完成解析。 如需串流結構的詳細資訊(包括 Tool 呼叫與 Tool 結果的承載資料),請參閱 [`MastraModelOutput` 參考文件](https://mastra.zisheng.pro/zh-TW/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 可呼叫外部 API 或服務的 Tool | [Tool](https://mastra.zisheng.pro/zh-TW/docs/agents/using-tools) | | 跨對話保留情境與偏好設定 | [記憶](https://mastra.zisheng.pro/zh-TW/docs/memory/overview) | | 傳回具型別物件,而非純文字 | [結構化輸出](https://mastra.zisheng.pro/zh-TW/docs/agents/structured-output) | | 人機協作:暫停執行並等待人工核准 | [核准](https://mastra.zisheng.pro/zh-TW/docs/agents/agent-approval) | | 建立多 Agent 網路 | [Supervisor Agent](https://mastra.zisheng.pro/zh-TW/docs/capabilities/subagents) | | 註冊子 Agent | [Tool](https://mastra.zisheng.pro/zh-TW/docs/agents/using-tools) | | 在產生內容前後攔截或轉換訊息 | [Processor](https://mastra.zisheng.pro/zh-TW/docs/agents/processors) | | 確保 Agent 安全 | [Guardrail](https://mastra.zisheng.pro/zh-TW/docs/agents/guardrails) | | 建立能修正自身工作的 Agent | [Rubric scorer](https://mastra.zisheng.pro/zh-TW/docs/capabilities/subagents) | | 根據請求情境切換指令或模型 | [動態設定](https://mastra.zisheng.pro/zh-TW/docs/server/request-context) | | 加入語音轉文字或文字轉語音 | [語音](https://mastra.zisheng.pro/zh-TW/guides/voice/overview) | | 連線至 Slack、Discord 或 Telegram | [Channel](https://mastra.zisheng.pro/zh-TW/docs/capabilities/channels/overview) | ## 多 Agent 系統 多 Agent 系統會使用多個 Agent,解決對單一 Agent 而言範圍過廣或過度專業的任務。與其建立一個配備數十個 Tool 和冗長指令集的 Agent,你可以將職責拆分給各自專注的 Agent,再由協調者彙整結果。 請閱讀[多 Agent 系統概念概觀](https://mastra.zisheng.pro/zh-TW/guides/concepts/multi-agent-systems),了解如何透過 Mastra 套用不同模式。