> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Agent.generateLegacy()(旧版) > **注意:** **已弃用**:此方法已弃用,并且仅适用于旧版 model adapter。对于当前的 model adapter,请改用 [`.generate()`](https://mastra.zisheng.pro/reference/agents/generate)。 `.generateLegacy()` 方法是 Agent 生成 API 的旧版,用于配合旧版 model adapter 生成文本或结构化响应。此方法接受消息和可选的生成选项。 ## 使用示例 ```typescript await agent.generateLegacy('message for agent') ``` ## Processor 重试支持 `generateLegacy()` 不运行错误 Processor,也不使用 `maxProcessorRetries`。它改用旧版 AI SDK 生成路径。 使用旧版 model adapter 的 Scorer judge 会调用 `generateLegacy()`。它们无法获得使用 Mastra 当前生成 API 的 Scorer judge 所具备的协调式 `StreamErrorRetryProcessor` 重试预算。需要错误 Processor 重试时,请使用当前的 model adapter。旧版 `maxRetries` 选项仍保持独立,默认值为 `2`。 ## 参数 **messages** (`string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]`): 要发送给 Agent 的消息。可以是单个字符串、字符串数组,或包含多模态内容(文本、图像等)的结构化消息对象。 **options** (`AgentGenerateOptions`): 生成过程的可选配置。 **options.abortSignal** (`AbortSignal`): 用于中止 Agent 执行的 signal 对象。中止 signal 后,所有正在进行的操作都会终止。 **options.context** (`CoreMessage[]`): 提供给 Agent 的其他上下文消息。 **options.structuredOutput** (`StructuredOutputOptions`): 启用结构化输出生成并提供更好的开发者体验。内部会自动创建并使用 StructuredOutputProcessor。 **options.structuredOutput.schema** (`z.ZodSchema`): 用于验证输出的 Zod schema。 **options.structuredOutput.model** (`MastraLanguageModel`): 内部结构化 Agent 使用的 Model。 **options.structuredOutput.errorStrategy** (`'strict' | 'warn' | 'fallback'`): 解析或验证失败时采用的策略。默认为 'strict'。 **options.structuredOutput.fallbackValue** (``): 当 errorStrategy 为 'fallback' 时使用的回退值。 **options.structuredOutput.instructions** (`string`): 结构化 Agent 的自定义 instructions。 **options.outputProcessors** (`Processor[]`): 覆盖 Agent 上设置的输出 Processor。输出 Processor 可在 Agent 消息返回给用户之前修改或验证消息。必须实现 processOutputResult 和 processOutputStream 函数中的至少一个。 **options.inputProcessors** (`Processor[]`): 覆盖 Agent 上设置的输入 Processor。输入 Processor 可在 Agent 处理消息之前修改或验证消息。必须实现 processInput 函数。 **options.experimental\_output** (`Zod schema | JsonSchema7`): 请注意,推荐使用 structuredOutput 属性。该选项可在文本生成和 Tool 调用的同时启用结构化输出生成。Model 将生成符合所提供 schema 的响应。 **options.instructions** (`string`): 为此次生成覆盖 Agent 默认 instructions 的自定义 instructions。无需创建新的 Agent 实例即可动态修改 Agent 行为。 **options.output** (`Zod schema | JsonSchema7`): 定义预期的输出结构。可以是 JSON Schema 对象或 Zod schema。 **options.memory** (`object`): Memory 配置。这是管理 Memory 的推荐方式。 **options.memory.thread** (`string | { id: string; metadata?: Record, title?: string }`): 对话 thread,可以是字符串 ID,也可以是包含 id 和可选 metadata 的对象。 **options.memory.resource** (`string`): 与 thread 关联的用户或 resource 标识符。 **options.memory.options** (`MemoryConfig`): Memory 行为配置,例如消息历史记录和语义召回。请参阅下方的 MemoryConfig。 **options.maxSteps** (`number`): 允许的最大执行步骤数。 **options.maxRetries** (`number`): 最大重试次数。设为 0 可禁用重试。 **options.onStepFinish** (`GenerateTextOnStepFinishCallback | never`): 每个执行步骤完成后调用的回调函数。以 JSON 字符串接收步骤详情。不适用于结构化输出。 **options.runId** (`string`): 此次生成运行的唯一 ID,可用于跟踪和调试。 **options.telemetry** (`TelemetrySettings`): 生成期间的 telemetry 收集设置。 **options.telemetry.isEnabled** (`boolean`): 启用或禁用 telemetry。实验阶段默认禁用。 **options.telemetry.recordInputs** (`boolean`): 启用或禁用输入记录。默认启用。为避免记录敏感信息,你可能需要禁用输入记录。 **options.telemetry.recordOutputs** (`boolean`): 启用或禁用输出记录。默认启用。为避免记录敏感信息,你可能需要禁用输出记录。 **options.telemetry.functionId** (`string`): 此函数的标识符。用于按函数对 telemetry 数据分组。 **options.temperature** (`number`): 控制 Model 输出的随机性。较高的值(例如 0.8)会使输出更随机,较低的值(例如 0.2)会使输出更集中、更具确定性。 **options.toolChoice** (`'auto' | 'none' | 'required' | { type: 'tool'; toolName: string }`): 控制 Agent 在生成期间如何使用 Tool。 **options.toolChoice.'auto'** (`string`): 让 Model 决定是否使用 Tool(默认)。 **options.toolChoice.'none'** (`string`): 不使用任何 Tool。 **options.toolChoice.'required'** (`string`): 要求 Model 至少使用一个 Tool。 **options.toolChoice.{ type: 'tool'; toolName: string }** (`object`): 要求 Model 使用指定名称的 Tool。 **options.toolsets** (`ToolsetsInput`): 生成期间向 Agent 提供的其他 Toolset。 **options.clientTools** (`ToolsInput`): 在请求的 'client' 端执行的 Tool。这些 Tool 的定义中没有 execute 函数。 **options.hooks** (`ToolHooks`): 每次执行时在 Tool 调用前后运行的 hook。覆盖此次执行中匹配的 Agent 级 hook。beforeToolCall 可返回 { proceed: false, output } 以跳过 Tool 调用。 **options.savePerStep** (`boolean`): 每个生成步骤完成后增量保存消息(默认:false)。启用 observational memory 时会在内部禁用。 **options.providerOptions** (`Record>`): 传递给底层 LLM Provider 的其他 Provider 专属选项。结构为 { providerName: { optionKey: value } }。由于 Mastra 扩展了 AI SDK,有关完整的 Provider 选项,请参阅 AI SDK 文档。 **options.providerOptions.openai** (`Record`): OpenAI 专属选项。示例:{ reasoningEffort: 'high' } **options.providerOptions.anthropic** (`Record`): Anthropic 专属选项。示例:{ maxTokens: 1000 } **options.providerOptions.google** (`Record`): Google 专属选项。示例:{ safetySettings: \[...] } **options.providerOptions.\[providerName]** (`Record`): 其他 Provider 专属选项。键为 Provider 名称,值为 Provider 专属选项的记录。 **options.requestContext** (`RequestContext`): 用于依赖注入和上下文信息的 RequestContext。 **options.maxTokens** (`number`): 要生成的最大 token 数。 **options.topP** (`number`): 核采样。取值范围为 0 到 1。建议只设置 temperature 或 topP,不要同时设置。 **options.topK** (`number`): 生成后续每个 token 时,只从概率最高的 K 个选项中采样。用于移除低概率的“长尾”响应。 **options.presencePenalty** (`number`): 存在惩罚设置。它会影响 Model 重复 prompt 中已有信息的可能性。取值范围为 -1(增加重复)到 1(最大惩罚,减少重复)。 **options.frequencyPenalty** (`number`): 频率惩罚设置。它会影响 Model 重复使用相同单词或短语的可能性。取值范围为 -1(增加重复)到 1(最大惩罚,减少重复)。 **options.stopSequences** (`string[]`): 停止序列。设置后,当生成任一停止序列时,Model 将停止生成文本。 **options.seed** (`number`): 随机采样使用的 seed(整数)。如果设置且 Model 支持,调用将生成确定性结果。 **options.headers** (`Record`): 随请求发送的其他 HTTP header。仅适用于基于 HTTP 的 Provider。 ## 返回值 **text** (`string`): 生成的文本响应。当输出为 'text'(未提供 schema)时存在。 **object** (`object`): 生成的结构化响应。通过 output、structuredOutput 或 experimental\_output 提供 schema 时存在。 **toolCalls** (`Array`): 生成过程中进行的 Tool 调用。在文本和对象模式下均存在。 **toolCalls.toolName** (`string`): 被调用 Tool 的名称。 **toolCalls.args** (`any`): 传递给 Tool 的参数。 ## 迁移到新 API > **信息:** 新的 `.generate()` 方法提供了更强的能力,包括兼容 AI SDK v5+、更完善的结构化输出处理以及改进的 streaming 支持。有关详细迁移说明,请参阅[迁移指南](https://mastra.zisheng.pro/guides/migrations/vnext-to-standard-apis)。 ### 快速迁移示例 #### 迁移前(旧版) ```typescript const result = await agent.generateLegacy('message', { temperature: 0.7, maxSteps: 3, }) ``` #### 迁移后(新 API) ```typescript const result = await agent.generate('message', { modelSettings: { temperature: 0.7, }, maxSteps: 3, }) ``` ## 扩展使用示例 ```typescript import { z } from 'zod' import { ModerationProcessor, TokenLimiterProcessor } from '@mastra/core/processors' await agent.generateLegacy( [ { role: 'user', content: 'message for agent' }, { role: 'user', content: [ { type: 'text', text: 'message for agent', }, { type: 'image', imageUrl: 'https://example.com/image.jpg', mimeType: 'image/jpeg', }, ], }, ], { temperature: 0.7, maxSteps: 3, memory: { thread: 'user-123', resource: 'test-app', }, toolChoice: 'auto', providerOptions: { openai: { reasoningEffort: 'high', }, }, // Structured output with better DX structuredOutput: { schema: z.object({ sentiment: z.enum(['positive', 'negative', 'neutral']), confidence: z.number(), }), model: 'openai/gpt-5.6-sol', errorStrategy: 'warn', }, // Output processors for response validation outputProcessors: [ new ModerationProcessor({ model: 'openai/gpt-5-mini' }), new TokenLimiterProcessor({ maxTokens: 1000 }), ], }, ) ``` ## 相关内容 - [迁移指南](https://mastra.zisheng.pro/guides/migrations/vnext-to-standard-apis) - [新的 .generate() 方法](https://mastra.zisheng.pro/reference/agents/generate) - [生成响应](https://mastra.zisheng.pro/docs/agents/overview) - [以 streaming 方式传输响应](https://mastra.zisheng.pro/docs/agents/overview)