Skip to main content

Agent 类

🌐 Agent Class

Agent 类已更新,重新组织了语音方法,更新了属性访问模式,并简化了流式 API。

🌐 The Agent class has been updated with reorganized voice methods, updated property access patterns, and streamlined streaming APIs.

已更改
Direct link to 已更改

🌐 Changed

getAgentslistAgents
Direct link to getagents-to-listagents

🌐 getAgents to listAgents

mastra.getAgents() 方法已重命名为 mastra.listAgents()。此更改与整个 API 中的命名约定保持一致,其中复数获取方法使用 list 前缀。

🌐 The mastra.getAgents() method has been renamed to mastra.listAgents(). This change aligns with the naming convention used across the API where plural getter methods use the list prefix.

要迁移,请将所有对 mastra.getAgents() 的调用替换为 mastra.listAgents()

🌐 To migrate, replace all calls to mastra.getAgents() with mastra.listAgents().

- const agents = mastra.getAgents();
+ const agents = mastra.listAgents();
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的代码:

🌐 You can use Mastra's codemod CLI to update your code automatically:

npx @mastra/codemod@latest v1/mastra-plural-apis .

RuntimeContextRequestContext
Direct link to runtimecontext-to-requestcontext

🌐 RuntimeContext to RequestContext

RuntimeContext 类在整个代码库中已重命名为 RequestContext。此更改提供了更清晰的命名,更好地描述了其作为请求特定数据的用途,并符合 Web 框架的使用惯例。

🌐 The RuntimeContext class has been renamed to RequestContext throughout the codebase. This change provides clearer naming that better describes its purpose as request-specific data and aligns with web framework conventions.

要迁移,请将所有导入和参数名称从 RuntimeContext/runtimeContext 更新为 RequestContext/requestContext

🌐 To migrate, update all imports and parameter names from RuntimeContext/runtimeContext to RequestContext/requestContext.

- import { RuntimeContext } from '@mastra/core/runtime-context';
+ import { RequestContext } from '@mastra/core/request-context';

- const runtimeContext = new RuntimeContext();
- runtimeContext.set('userTier', 'enterprise');
+ const requestContext = new RequestContext();
+ requestContext.set('userTier', 'enterprise');

- await agent.generate(messages, { runtimeContext });
+ await agent.generate(messages, { requestContext });
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的代码:

🌐 You can use Mastra's codemod CLI to update your code automatically:

npx @mastra/codemod@latest v1/runtime-context .

直接访问属性的 getter 方法
Direct link to 直接访问属性的 getter 方法

🌐 Direct property access to getter methods

直接访问 agent.llmagent.toolsagent.instructions 属性已被弃用。这一更改提供了更好的封装性,并与更广泛的 API 设计保持一致。

🌐 Direct property access to agent.llm, agent.tools, and agent.instructions is deprecated. This change provides better encapsulation and consistency with the broader API design.

要进行迁移,请将属性访问替换为相应的 getter 方法。

🌐 To migrate, replace property access with the corresponding getter methods.

- const llm = agent.llm;
- const tools = agent.tools;
- const instructions = agent.instructions;
+ const llm = agent.getLLM();
+ const tools = agent.getTools();
+ const instructions = agent.getInstructions();
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的代码:

🌐 You can use Mastra's codemod CLI to update your code automatically:

npx @mastra/codemod@latest v1/agent-property-access .

语音方法已移动到 agent.voice 命名空间
Direct link to voice-methods-moved-to-agentvoice-namespace

🌐 Voice methods moved to agent.voice namespace

与语音相关的方法已从 Agent 类移至 agent.voice 命名空间。此更改提供了更好的组织结构和更清晰的关注点分离。

🌐 Voice-related methods have been moved from the Agent class to the agent.voice namespace. This change provides better organization and clearer separation of concerns.

要迁移,请更新语音方法调用以使用 agent.voice 命名空间。

🌐 To migrate, update voice method calls to use the agent.voice namespace.

- await agent.speak('Hello');
- await agent.listen();
- const speakers = agent.getSpeakers();
+ await agent.voice.speak('Hello');
+ await agent.voice.listen();
+ const speakers = agent.voice.getSpeakers();
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的代码:

🌐 You can use Mastra's codemod CLI to update your code automatically:

npx @mastra/codemod@latest v1/agent-voice .

agent.fetchMemory()(await agent.getMemory()).recall()
Direct link to agentfetchmemory-to-await-agentgetmemoryrecall

🌐 agent.fetchMemory() to (await agent.getMemory()).recall()

fetchMemory() 方法已被更明确的 API 替代。此更改更清楚地说明了内存访问的异步特性。

🌐 The fetchMemory() method has been replaced with a more explicit API. This change provides better clarity about the asynchronous nature of memory access.

要迁移,请将 fetchMemory() 调用替换为新 API。

🌐 To migrate, replace fetchMemory() calls with the new API.

- const messages = await agent.fetchMemory({ threadId: 'thread-123' });
+ const memory = await agent.getMemory();
+ const result = await memory.recall({ threadId: 'thread-123' });
+ const messages = result.messages;

get*list* 的处理器方法名称
Direct link to processor-method-names-from-get-to-list

🌐 Processor method names from get* to list*

代理处理器方法已从 get* 重命名为 list* 模式,以与更广泛的 API 保持一致。此更改符合 list* 方法返回集合的惯例。

🌐 Agent processor methods have been renamed from get* to list* pattern for consistency with the broader API. This change aligns with the convention that list* methods return collections.

要迁移,请更新处理器方法名称。

🌐 To migrate, update processor method names.

- const inputProcessors = await agent.getInputProcessors(runtimeContext);
- const outputProcessors = await agent.getOutputProcessors(runtimeContext);
+ const inputProcessors = await agent.listInputProcessors(requestContext);
+ const outputProcessors = await agent.listOutputProcessors(requestContext);
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的代码:

🌐 You can use Mastra's codemod CLI to update your code automatically:

npx @mastra/codemod@latest v1/agent-processor-methods .

默认选项方法为 AI SDK 版本重命名
Direct link to 默认选项方法为 AI SDK 版本重命名

🌐 Default options method renames for AI SDK versions

默认选项方法已被重命名,以明确区分旧版(AI SDK v4)和新版(AI SDK v5+)API。此更改有助于开发者了解他们正在针对的是哪个版本的AI SDK。

🌐 Default options methods have been renamed to clarify legacy (AI SDK v4) vs new (AI SDK v5+) APIs. This change helps developers understand which AI SDK version they're targeting.

要进行迁移,请根据你使用的 AI SDK 版本更新方法名称。

🌐 To migrate, update method names based on which AI SDK version you're using.

  // For legacy AI SDK v4
- const options = await agent.getDefaultGenerateOptions();
- const streamOptions = await agent.getDefaultStreamOptions();
+ const options = await agent.getDefaultGenerateOptionsLegacy();
+ const streamOptions = await agent.getDefaultStreamOptionsLegacy();

// For new AI SDK v5+ (default)
const streamOptions = await agent.getDefaultStreamOptions();

modelSettings.abortSignal 到顶层 abortSignal
Direct link to modelsettingsabortsignal-to-top-level-abortsignal

🌐 modelSettings.abortSignal to top-level abortSignal

abortSignal 选项已从 modelSettings 移动到 stream/generate 选项的顶层。此更改更清晰地区分了模型特定设置与执行控制。

🌐 The abortSignal option has been moved from modelSettings to the top level of stream/generate options. This change provides a clearer separation between model-specific settings and execution control.

要迁移,请将 abortSignalmodelSettings 移动到顶层。

🌐 To migrate, move abortSignal from modelSettings to the top level.

  agent.stream('Hello', {
- modelSettings: {
- abortSignal: abortController.signal,
- },
+ abortSignal: abortController.signal,
});
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的代码:

🌐 You can use Mastra's codemod CLI to update your code automatically:

npx @mastra/codemod@latest v1/agent-abort-signal .

outputstructuredOutput.schema
Direct link to output-to-structuredoutputschema

🌐 output to structuredOutput.schema

已弃用的 outputexperimental_output 选项已被移除。此更改统一使用单一、稳定的结构化输出 API。

🌐 The deprecated output and experimental_output options have been removed. This change consolidates on a single, stable API for structured output.

要迁移,请将 outputexperimental_output 更新到 structuredOutput.schema

🌐 To migrate, update from output or experimental_output to structuredOutput.schema.

  agent.stream('Hello', {
- output: z.object({ result: z.string() }),
+ structuredOutput: {
+ schema: z.object({ result: z.string() }),
+ },
});

代理 id 字段现在是必填项
Direct link to agent-id-field-is-now-required

🌐 Agent id field is now required

在创建代理时,现在必须填写 id 字段。之前可以在没有明确 ID 的情况下创建代理,但现在不再支持此操作。

🌐 The id field is now required when creating an Agent. Previously, agents could be created without an explicit ID, but this is no longer supported.

要进行迁移,请在所有代理配置中添加一个 id 字段。

🌐 To migrate, add an id field to all Agent configurations.

  const agent = new Agent({
+ id: 'my-agent',
name: 'My Agent',
instructions: 'You are a helpful assistant',
model: 'openai/gpt-4',
});

id 可以与 name 相同,也可以使用不同的标识符。该 ID 会在调用 mastra.getAgentById() 时使用,并且在你的 Mastra 实例中必须是唯一的。

🌐 The id can be the same as the name, or you can use a different identifier. The ID will be used when calling mastra.getAgentById() and must be unique within your Mastra instance.

// Register agent with Mastra
const mastra = new Mastra({
agents: {
myAgent: agent, // key can differ from id
},
});

// Retrieve by ID
const agent = mastra.getAgentById('my-agent');

流 API 响应现在会编辑敏感数据
Direct link to 流 API 响应现在会编辑敏感数据

🌐 Stream API responses now redact sensitive data

Mastra 服务器现在会自动从代理流响应中编辑敏感信息。这可以防止在 step-startstep-finishfinish 流片段中意外泄露系统提示、工具定义和 API 密钥。

🌐 The Mastra server now automatically redacts sensitive information from agent stream responses. This prevents accidental exposure of system prompts, tool definitions, and API keys in step-start, step-finish, and finish stream chunks.

已编辑内容:

  • request.body 包含 LLM 请求负载(系统提示、工具架构)
  • metadata.request 在步骤结果中
  • output.steps[].request 在嵌套步骤数据中

此行为默认启用。如果你需要访问完整的请求数据(例如,用于调试或内部服务),可以在直接使用服务器适配器时禁用屏蔽(例如,@mastra/hono@mastra/express)。

🌐 This behavior is enabled by default. If you need access to the full request data (e.g., for debugging or internal services), you can disable redaction when using server adapters directly (e.g., @mastra/hono or @mastra/express).

已移除
Direct link to 已移除

🌐 Removed

generateVNextstreamVNext 方法
Direct link to generatevnext-and-streamvnext-methods

🌐 generateVNext and streamVNext methods

已弃用的 generateVNext()streamVNext() 方法已被删除。这些方法以前用于 AI SDK v5+ 的兼容性,但现在已成为标准实现。

🌐 The deprecated generateVNext() and streamVNext() methods have been removed. These methods were previously used for AI SDK v5+ compatibility but are now the standard implementation.

要迁移,请使用标准的 generate()stream() 方法。

🌐 To migrate, use the standard generate() and stream() methods.

- const result = await agent.generateVNext('Hello');
- const stream = await agent.streamVNext('Hello');
+ const result = await agent.generate('Hello');
+ const stream = await agent.stream('Hello');
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的代码:

🌐 You can use Mastra's codemod CLI to update your code automatically:

npx @mastra/codemod@latest v1/agent-generate-stream-v-next .

format 参数来自 stream()generate()
Direct link to format-parameter-from-stream-and-generate

🌐 format parameter from stream() and generate()

format 参数已从 agent.stream()agent.generate() 方法中移除。AI SDK 流转换现在由 @mastra/ai-sdk 包处理。此更改通过将 AI SDK 特定代码移到专用包中来提高树摇优化效果。

🌐 The format parameter has been removed from agent.stream() and agent.generate() methods. AI SDK stream transformations are now handled by the @mastra/ai-sdk package. This change improves tree-shaking by moving AI SDK-specific code to a dedicated package.

要进行迁移,请使用 @mastra/ai-sdk 中的 toAISdkStream() 函数进行 AI SDK 格式转换。

🌐 To migrate, use the toAISdkStream() function from @mastra/ai-sdk for AI SDK format conversion.

- const stream = await agent.stream(messages, {
- format: 'aisdk',
- });

+ import { toAISdkStream } from '@mastra/ai-sdk';
+
+ const stream = await agent.stream(messages);
+ const aiSdkStream = toAISdkStream(stream, { from: 'agent' });

agent.toStep() 方法
Direct link to agenttostep-method

🌐 agent.toStep() method

toStep() 方法已从 Agent 类中移除。现在,代理可以直接添加到工作流步骤中,无需显式转换。

🌐 The toStep() method has been removed from the Agent class. Agents can now be added directly to workflow steps without explicit conversion.

要进行迁移,请将代理直接添加到工作流步骤中。工作流会自动处理转换。

🌐 To migrate, add agents directly to workflow steps. Workflows handle the transformation automatically.

- const step = agent.toStep();
- const workflow = new Workflow({
- steps: [step],
- });

+ const workflow = new Workflow({
+ steps: [agent],
+ });

TMetrics 来自 Agent 的通用参数
Direct link to tmetrics-generic-parameter-from-agent

🌐 TMetrics generic parameter from Agent

AgentConfigAgent 构造函数中的 TMetrics 泛型参数已被移除。现在,指标/评分器使用评分器 API 配置,而不再是 Agent 类型系统的一部分。

🌐 The TMetrics generic parameter has been removed from AgentConfig and the Agent constructor. Metrics/scorers are now configured using the scorers API instead of being part of the Agent type system.

要迁移,请移除 TMetrics 泛型参数,并使用新的 API 配置评分器。

🌐 To migrate, remove the TMetrics generic parameter and configure scorers using the new API.

- const agent = new Agent<AgentId, Tools, Metrics>({
+ const agent = new Agent<AgentId, Tools>({
// ...
});

Tripwire 响应格式已更改
Direct link to Tripwire 响应格式已更改

🌐 Tripwire response format changed

触发器响应格式已从单独的 tripwiretripwireReason 字段更改为包含所有相关数据的单个 tripwire 对象。

🌐 The tripwire response format has changed from separate tripwire and tripwireReason fields to a single tripwire object containing all related data.

要迁移,请更新你的代码以从新的对象结构中访问tripwire数据。

🌐 To migrate, update your code to access tripwire data from the new object structure.

  const result = await agent.generate('Hello');

- if (result.tripwire) {
- console.log(result.tripwireReason);
- }
+ if (result.tripwire) {
+ console.log(result.tripwire.reason);
+ // New fields available:
+ // result.tripwire.retry - whether this step should be retried
+ // result.tripwire.metadata - additional metadata from the processor
+ // result.tripwire.processorId - which processor triggered the tripwire
+ }

用于流式响应:

🌐 For streaming responses:

  for await (const chunk of stream.fullStream) {
if (chunk.type === 'tripwire') {
- console.log(chunk.payload.tripwireReason);
+ console.log(chunk.payload.reason);
+ // New fields available:
+ // chunk.payload.retry
+ // chunk.payload.metadata
+ // chunk.payload.processorId
}
}

步骤结果现在还包括触发器信息:

🌐 The step results now also include tripwire information:

  const result = await agent.generate('Hello');

for (const step of result.steps) {
- // No tripwire info on steps
+ if (step.tripwire) {
+ console.log('Step was blocked:', step.tripwire.reason);
+ }
}

prepareStep 消息格式
Direct link to preparestep-messages-format

🌐 prepareStep messages format

prepareStep 回调现在接收 MastraDBMessage 格式的消息,而不是 AI SDK v5+ 模型消息格式。此更改将 prepareStep 与新的 processInputStep 处理方法统一,该方法在每个自主循环的步骤中运行。

🌐 The prepareStep callback now receives messages in MastraDBMessage format instead of AI SDK v5+ model message format. This change unifies prepareStep with the new processInputStep processor method, which runs at each step of the agentic loop.

如果你需要旧的 AI SDK v5+ 格式,请使用 messageList.get.all.aiV5.model()

🌐 If you need the old AI SDK v5+ format, use messageList.get.all.aiV5.model():

  agent.generate('Hello', {
prepareStep: async ({ messages, messageList }) => {
- // messages was AI SDK v5+ ModelMessage format
- console.log(messages[0].content);
+ // messages is now MastraDBMessage format
+ // Use messageList to get AI SDK v5+ format if needed:
+ const aiSdkMessages = messageList.get.all.aiV5.model();

return { toolChoice: 'auto' };
},
});

threadIdresourceIdmemory 选项
Direct link to threadid-and-resourceid-to-memory-option

🌐 threadId and resourceId to memory option

threadIdresourceId 选项已从 agent.stream()agent.generate() 中移除。请改用 memory 选项,它提供了更清晰的内存配置 API。

🌐 The threadId and resourceId options have been removed from agent.stream() and agent.generate(). Use the memory option instead, which provides a cleaner API for memory configuration.

要迁移,请将 threadIdresourceId 移动到 memory 选项中:

🌐 To migrate, move threadId and resourceId into the memory option:

  await agent.stream('Hello', {
- threadId: 'thread-123',
- resourceId: 'user-456',
+ memory: {
+ thread: 'thread-123',
+ resource: 'user-456',
+ },
});

memory 选项在创建新线程时也支持传递线程元数据:

🌐 The memory option also supports passing thread metadata when creating new threads:

await agent.stream('Hello', {
memory: {
thread: {
id: 'thread-123',
title: 'Support conversation',
metadata: { category: 'billing' },
},
resource: 'user-456',
},
});