> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Agent 概览 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/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` 使用 Mastra 的[模型路由器](https://mastra.zisheng.pro/models),以 `'provider/model-name'` 格式指定。 要让整个应用都能使用该 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/reference/agents/agent)。 > **提示:** 使用 [Studio](https://mastra.zisheng.pro/docs/studio/overview) 通过不同消息测试 Agent,检查 Tool 调用和响应,并调试 Agent 行为。 ## 使用 Agent 注册后,使用 [`mastra.getAgentById()`](https://mastra.zisheng.pro/reference/core/getAgentById) 获取 Agent。调用 `.generate()` 获得完整响应,或调用 `.stream()` 实时传输 token。你可以从 [Workflow 步骤](https://mastra.zisheng.pro/docs/workflows/agents-and-tools)、[Tool](https://mastra.zisheng.pro/docs/agents/using-tools)、[Mastra Client](https://mastra.zisheng.pro/reference/client-js/mastra-client)、路由处理程序、[服务器适配器](https://mastra.zisheng.pro/docs/server/server-adapters)或命令行调用 Agent。请参阅[指南](https://mastra.zisheng.pro/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/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,它们会在流结束时解析。 有关流结构(包括 Tool 调用和 Tool 结果的 payload),请参阅 [`MastraModelOutput` 参考](https://mastra.zisheng.pro/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/docs/agents/using-tools) | | 跨对话保留上下文和偏好 | [Memory](https://mastra.zisheng.pro/docs/memory/overview) | | 返回类型化对象,而不是纯文本 | [结构化输出](https://mastra.zisheng.pro/docs/agents/structured-output) | | 人机协同:暂停执行并等待人工批准 | [批准](https://mastra.zisheng.pro/docs/agents/agent-approval) | | 构建多 Agent 网络 | [Supervisor Agent](https://mastra.zisheng.pro/docs/capabilities/subagents) | | 注册子 Agent | [Tool](https://mastra.zisheng.pro/docs/agents/using-tools) | | 在生成前后拦截或转换消息 | [Processor](https://mastra.zisheng.pro/docs/agents/processors) | | 保障 Agent 安全 | [Guardrail](https://mastra.zisheng.pro/docs/agents/guardrails) | | 构建能够纠正自身工作的 Agent | [Rubric scorer](https://mastra.zisheng.pro/docs/capabilities/subagents) | | 根据请求上下文切换指令或模型 | [动态配置](https://mastra.zisheng.pro/docs/server/request-context) | | 添加语音转文本或文本转语音 | [语音](https://mastra.zisheng.pro/guides/voice/overview) | | 连接 Slack、Discord 或 Telegram | [Channel](https://mastra.zisheng.pro/docs/capabilities/channels/overview) | ## 多 Agent 系统 多 Agent 系统使用多个 Agent 解决对单个 Agent 而言过于宽泛或专业化的任务。你无需构建一个包含数十个 Tool 和冗长指令集的 Agent,而是可以将职责拆分给各个专用 Agent,再由协调者汇总结果。 阅读[多 Agent 系统概念概览](https://mastra.zisheng.pro/guides/concepts/multi-agent-systems),了解如何在 Mastra 中应用不同模式。