跳至主要內容

Agent.generateLegacy()(舊版)

警告

已棄用:此方法已棄用,且僅適用於舊版模型 adapter。若使用目前的模型 adapter,請改用 .generate()

.generateLegacy() 方法是 Agent 生成 API 的舊版,搭配舊版模型 adapter 產生文字或結構化回應。此方法接受訊息與選用的生成選項。

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

await agent.generateLegacy('message for agent')

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

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

使用舊版模型 adapter 的 Scorer judge 會呼叫 generateLegacy()。它們不會取得使用 Mastra 目前生成 API 之 Scorer judge 可用的協調式 StreamErrorRetryProcessor 額度。若需要錯誤 Processor 重試,請使用目前的模型 adapter。舊版 maxRetries 選項仍會分開計算,預設為 2

參數
「參數」的直接連結

messages:

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

options?:

AgentGenerateOptions
生成流程的選用設定。
AgentGenerateOptions

abortSignal?:

AbortSignal
可讓您中止 Agent 執行的 signal 物件。signal 中止時,所有進行中的作業都會終止。

context?:

CoreMessage[]
要提供給 Agent 的其他 context 訊息。

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' 時的 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 }
對話 thread,可以是字串 ID,或包含 id 與選用 metadata 的物件。

resource:

string
與 thread 關聯之使用者或 resource 的識別碼。

options?:

MemoryConfig
記憶體行為設定,例如訊息歷程與語意回想。請參閱下方的 MemoryConfig

maxSteps?:

number
允許的執行步驟數上限。

maxRetries?:

number
重試次數上限。設為 0 可停用重試。

onStepFinish?:

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

runId?:

string
此次生成 run 的唯一 ID,適合用於追蹤與偵錯。

telemetry?:

TelemetrySettings
生成期間的 telemetry 收集設定。
TelemetrySettings

isEnabled?:

boolean
啟用或停用 telemetry。此功能仍為實驗性質,因此預設停用。

recordInputs?:

boolean
啟用或停用輸入記錄。預設為啟用。若要避免記錄敏感資訊,您可以停用輸入記錄。

recordOutputs?:

boolean
啟用或停用輸出記錄。預設為啟用。若要避免記錄敏感資訊,您可以停用輸出記錄。

functionId?:

string
此函式的識別碼,用來依函式將 telemetry 資料分組。

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 的 toolset。

clientTools?:

ToolsInput
在 request 的 'client' 端執行的 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 專屬選項。key 是 Provider 名稱,value 是 Provider 專屬選項的記錄。

requestContext?:

RequestContext
用於相依性注入與情境資訊的 Request Context。

maxTokens?:

number
要生成的 token 數量上限。

topP?:

number
核心取樣。此數值介於 0 與 1 之間。建議設定 temperaturetopP,但不要同時設定兩者。

topK?:

number
每個後續 token 只從機率最高的 K 個選項取樣,用來排除「長尾」低機率回應。

presencePenalty?:

number
存在懲罰設定。會影響模型重複 prompt 中既有資訊的機率。數值介於 -1(增加重複)與 1(最大懲罰,減少重複)之間。

frequencyPenalty?:

number
頻率懲罰設定。會影響模型重複使用相同字詞或片語的機率。數值介於 -1(增加重複)與 1(最大懲罰,減少重複)之間。

stopSequences?:

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

seed?:

number
隨機取樣使用的 seed(整數)。設定此值且模型支援時,呼叫會生成確定性結果。

headers?:

Record<string, string | undefined>
要與 request 一併傳送的其他 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 }),
],
},
)