跳至主要內容

Agent.generateLegacy()(舊版)

注意

已棄用:此方法已棄用,並只適用於舊版模型轉接器。若使用目前的模型轉接器,請改用 .generate()

.generateLegacy() 方法是 Agent 生成 API 的舊版,配合舊版模型轉接器使用,以產生文字或結構化回應。此方法接受訊息及可選的生成選項。

使用範例
使用範例 的直接連結

await agent.generateLegacy('message for agent')

Processor 重試支援
Processor 重試支援 的直接連結

generateLegacy() 不會執行錯誤 Processor 或 maxProcessorRetries,而是使用舊版 AI SDK 生成路徑。

使用舊版模型轉接器的評分器判定會呼叫 generateLegacy()。它們不會獲得使用 Mastra 目前生成 API 的評分器判定可用的協調式 StreamErrorRetryProcessor 重試額度。如需錯誤 Processor 重試,請使用目前的模型轉接器。舊版 maxRetries 選項仍然獨立,預設為 2

參數
參數 的直接連結

messages:

string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]
要傳送給 Agent 的訊息。可以是單一字串、字串陣列,或包含多模態內容(文字、圖像等)的結構化訊息物件。

options?:

AgentGenerateOptions
生成程序的可選設定。
AgentGenerateOptions

abortSignal?:

AbortSignal
讓你中止 Agent 執行的訊號物件。訊號中止時,所有進行中的操作都會終止。

context?:

CoreMessage[]
提供給 Agent 的額外上下文訊息。

structuredOutput?:

StructuredOutputOptions<S extends ZodTypeAny = ZodTypeAny>
啟用結構化輸出生成,提供更佳的開發者體驗。內部會自動建立並使用 StructuredOutputProcessor。
StructuredOutputOptions<S extends ZodTypeAny = ZodTypeAny>

schema:

z.ZodSchema<S>
用於驗證輸出的 Zod schema。

model:

MastraLanguageModel
內部結構化 Agent 使用的模型。

errorStrategy?:

'strict' | 'warn' | 'fallback'
剖析或驗證失敗時採用的策略。預設為 'strict'。

fallbackValue?:

<S extends ZodTypeAny>
當 errorStrategy 為 'fallback' 時使用的後備值。

instructions?:

string
結構化 Agent 的自訂指示。

outputProcessors?:

Processor[]
覆寫 Agent 上設定的輸出 Processor。輸出 Processor 可在 Agent 的訊息傳回給使用者前修改或驗證訊息,必須實作 processOutputResultprocessOutputStream 函式(亦可兩者皆實作)。

inputProcessors?:

Processor[]
覆寫 Agent 上設定的輸入 Processor。輸入 Processor 可在訊息由 Agent 處理前修改或驗證訊息,必須實作 processInput 函式。

experimental_output?:

Zod schema | JsonSchema7
請注意,建議使用 structuredOutput 屬性。這會在文字生成和 Tool 呼叫之外啟用結構化輸出生成。模型會產生符合所提供 schema 的回應。

instructions?:

string
針對這次生成覆寫 Agent 預設指示的自訂指示。適合在不建立新 Agent 實例的情況下動態修改 Agent 行為。

output?:

Zod schema | JsonSchema7
定義預期的輸出結構。可以是 JSON Schema 物件或 Zod schema。

memory?:

object
記憶體設定。這是建議的記憶體管理方式。
object

thread:

string | { id: string; metadata?: Record<string, any>, title?: string }
對話執行緒,可以是字串 ID,或包含 id 及可選 metadata 的物件。

resource:

string
與執行緒相關聯的使用者或資源識別碼。

options?:

MemoryConfig
記憶體行為設定,例如訊息記錄及語意回憶。請參閱下方的 MemoryConfig

maxSteps?:

number
允許的最大執行步驟數目。

maxRetries?:

number
最大重試次數。設為 0 可停用重試。

onStepFinish?:

GenerateTextOnStepFinishCallback<any> | never
每個執行步驟後呼叫的回呼函式。以 JSON 字串接收步驟詳情。不適用於結構化輸出。

runId?:

string
這次生成執行的唯一 ID,適合用於追蹤及除錯。

telemetry?:

TelemetrySettings
生成期間收集遙測資料的設定。
TelemetrySettings

isEnabled?:

boolean
啟用或停用遙測。實驗階段預設停用。

recordInputs?:

boolean
啟用或停用輸入記錄。預設啟用。你可能需要停用輸入記錄,以免記錄敏感資料。

recordOutputs?:

boolean
啟用或停用輸出記錄。預設啟用。你可能需要停用輸出記錄,以免記錄敏感資料。

functionId?:

string
此函式的識別碼,用於按函式將遙測資料分組。

temperature?:

number
控制模型輸出的隨機程度。較高的值(例如 0.8)會令輸出更隨機,較低的值(例如 0.2)則令輸出更集中且具確定性。

toolChoice?:

'auto' | 'none' | 'required' | { type: 'tool'; toolName: string }
控制 Agent 在生成期間使用 Tool 的方式。
'auto' | 'none' | 'required' | { type: 'tool'; toolName: string }

'auto':

string
讓模型決定是否使用 Tool(預設)。

'none':

string
不要使用任何 Tool。

'required':

string
要求模型使用至少一個 Tool。

{ type: 'tool'; toolName: string }:

object
要求模型使用指定名稱的 Tool。

toolsets?:

ToolsetsInput
生成期間可供 Agent 使用的額外 Tool 集合。

clientTools?:

ToolsInput
在請求的「客戶端」執行的 Tool。這些 Tool 的定義中沒有 execute 函式。

hooks?:

ToolHooks
每次執行時在 Tool 呼叫前後運行的 hook。這次執行會覆寫相符的 Agent 層級 hook。beforeToolCall 可傳回 { proceed: false, output } 以略過 Tool 呼叫。

savePerStep?:

boolean
每個生成步驟完成後逐步儲存訊息(預設:false)。啟用觀察式記憶體時,內部會停用此功能。

providerOptions?:

Record<string, Record<string, JSONValue>>
傳遞至底層 LLM Provider 的額外 Provider 特定選項。結構為 { providerName: { optionKey: value } }。由於 Mastra 擴充 AI SDK,完整的 Provider 選項請參閱 AI SDK 文件
Record<string, Record<string, JSONValue>>

openai?:

Record<string, JSONValue>
OpenAI 特定選項。範例:{ reasoningEffort: 'high' }

anthropic?:

Record<string, JSONValue>
Anthropic 特定選項。範例:{ maxTokens: 1000 }

google?:

Record<string, JSONValue>
Google 特定選項。範例:{ safetySettings: [...] }

[providerName]?:

Record<string, JSONValue>
其他 Provider 特定選項。鍵是 Provider 名稱,值是 Provider 特定選項的記錄。

requestContext?:

RequestContext
用於依賴注入及上下文資料的 Request Context。

maxTokens?:

number
要生成的最大 token 數目。

topP?:

number
核心採樣。數值介乎 0 至 1。建議設定 temperaturetopP 其中一項,不要同時設定兩者。

topK?:

number
每個後續 token 只從最高的 K 個選項中採樣,用於移除「長尾」低概率回應。

presencePenalty?:

number
存在懲罰設定。這會影響模型重複提示中已有資料的可能性。數值介乎 -1(增加重複)至 1(最大懲罰,減少重複)。

frequencyPenalty?:

number
頻率懲罰設定。這會影響模型重複使用相同字詞或短語的可能性。數值介乎 -1(增加重複)至 1(最大懲罰,減少重複)。

stopSequences?:

string[]
停止序列。設定後,模型生成其中一個停止序列時便會停止生成文字。

seed?:

number
隨機採樣使用的種子(整數)。如已設定且模型支援,呼叫會生成確定性結果。

headers?:

Record<string, string | undefined>
隨請求傳送的額外 HTTP header。只適用於以 HTTP 為基礎的 Provider。

傳回值
傳回值 的直接連結

text?:

string
生成的文字回應。當輸出為 'text'(未提供 schema)時存在。

object?:

object
生成的結構化回應。透過 outputstructuredOutputexperimental_output 提供 schema 時存在。

toolCalls?:

Array<ToolCall>
生成程序期間作出的 Tool 呼叫。在文字及物件模式中均存在。
Array<ToolCall>

toolName:

string
被呼叫 Tool 的名稱。

args:

any
傳遞給 Tool 的引數。

遷移至新 API
遷移至新 API 的直接連結

資訊

新的 .generate() 方法提供更強的功能,包括 AI SDK v5+ 相容性、更佳的結構化輸出處理,以及改良的串流支援。詳細遷移指示請參閱遷移指南

快速遷移範例
快速遷移範例 的直接連結

遷移前(舊版)
遷移前(舊版) 的直接連結

const result = await agent.generateLegacy('message', {
temperature: 0.7,
maxSteps: 3,
})

遷移後(新 API)
遷移後(新 API) 的直接連結

const result = await agent.generate('message', {
modelSettings: {
temperature: 0.7,
},
maxSteps: 3,
})

進階使用範例
進階使用範例 的直接連結

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 }),
],
},
)