メインコンテンツへ移動

Agent.generateLegacy()(Legacy)

警告

非推奨:このメソッドは非推奨で、従来の Model Adapter でのみ動作します。現在の Model Adapter では、代わりに .generate() を使用してください。

.generateLegacy() は Agent 生成 API の従来版で、従来の Model Adapter を使ってテキストまたは構造化レスポンスを生成します。メッセージと任意の生成オプションを受け取ります。

使用例
使用例への直接リンク

await agent.generateLegacy('message for agent')

Processor の再試行対応
Processor の再試行対応への直接リンク

generateLegacy() は Error Processor や maxProcessorRetries を実行せず、従来の AI SDK 生成パスを使用します。

従来の Model Adapter を使う Scorer Judge は generateLegacy() を呼び出します。Mastra の現在の生成 API を使う Scorer Judge で利用できる、調整済みの StreamErrorRetryProcessor Budget は適用されません。Error Processor の再試行が必要な場合は、現在の Model Adapter を使用してください。従来の maxRetries オプションは独立しており、デフォルトは 2 です。

パラメータ
パラメータへの直接リンク

messages:

string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]
Agent へ送るメッセージ。単一の文字列、文字列配列、またはマルチモーダルな内容(テキスト、画像など)を持つ構造化メッセージオブジェクトを指定できます。

options?:

AgentGenerateOptions
生成処理の任意設定。
AgentGenerateOptions

abortSignal?:

AbortSignal
Agent の実行を中止できる Signal オブジェクト。Signal が中止されると、進行中のすべての処理が終了します。

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 用のカスタム instructions。

outputProcessors?:

Processor[]
Agent に設定された Output Processor を上書きします。ユーザーへ返す前に、Agent からのメッセージを変更または検証できます。processOutputResultprocessOutputStream の一方または両方を実装する必要があります。

inputProcessors?:

Processor[]
Agent に設定された Input Processor を上書きします。Agent が処理する前にメッセージを変更または検証できます。processInput 関数を実装する必要があります。

experimental_output?:

Zod schema | JsonSchema7
推奨される方法は structuredOutput プロパティの使用です。テキスト生成と Tool 呼び出しに加えて、構造化出力の生成を有効にします。モデルは指定された Schema に準拠するレスポンスを生成します。

instructions?:

string
この生成に限り Agent のデフォルト instructions を上書きするカスタム instructions。新しい Agent インスタンスを作成せずに、Agent の動作を動的に変更する場合に便利です。

output?:

Zod schema | JsonSchema7
出力に期待する構造を定義します。JSON Schema オブジェクトまたは Zod Schema を指定できます。

memory?:

object
Memory の設定。Memory を管理する推奨方法です。
object

thread:

string | { id: string; metadata?: Record<string, any>, title?: string }
会話 Thread。文字列 ID、または id と任意の metadata を持つオブジェクトとして指定します。

resource:

string
Thread に関連付けるユーザーまたは Resource の識別子。

options?:

MemoryConfig
メッセージ履歴や Semantic Recall など、Memory の動作設定。以下の MemoryConfig を参照してください。

maxSteps?:

number
許可する実行 Step の最大数。

maxRetries?:

number
最大再試行回数。再試行を無効にするには 0 を設定します。

onStepFinish?:

GenerateTextOnStepFinishCallback<any> | never
各実行 Step の後に呼び出される Callback 関数。Step の詳細を 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
モデルに少なくとも1つの Tool の使用を必須とします。

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

object
モデルに名前を指定した特定 Tool の使用を必須とします。

toolsets?:

ToolsetsInput
生成中に Agent で利用できる追加 Toolset。

clientTools?:

ToolsInput
リクエストの 'client' 側で実行される Tool。これらの Tool の定義には execute 関数がありません。

hooks?:

ToolHooks
Tool 呼び出しの前後に実行される実行単位の Hook。この実行では、一致する Agent レベルの Hook を上書きします。beforeToolCall{ proceed: false, output } を返して Tool 呼び出しをスキップできます。

savePerStep?:

boolean
各生成 Step の完了後にメッセージを増分保存します(デフォルト:false)。Observational Memory が有効な場合は内部で無効化されます。

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 固有オプションの Record です。

requestContext?:

RequestContext
依存性注入とコンテキスト情報に使う Request Context。

maxTokens?:

number
生成する Token の最大数。

topP?:

number
Nucleus Sampling。0〜1 の数値です。temperature または topP のどちらか一方だけを設定することを推奨します。

topK?:

number
後続の各 Token について、上位 K 個の選択肢からのみ Sampling します。確率が低い 'long tail' のレスポンスを除外するために使います。

presencePenalty?:

number
Presence Penalty の設定。Prompt にすでに含まれる情報をモデルが繰り返す確率に影響します。-1(反復を増加)から 1(最大 Penalty、反復を減少)までの数値です。

frequencyPenalty?:

number
Frequency Penalty の設定。モデルが同じ単語やフレーズを繰り返す確率に影響します。-1(反復を増加)から 1(最大 Penalty、反復を減少)までの数値です。

stopSequences?:

string[]
Stop Sequence。設定すると、いずれかの Stop Sequence が生成された時点でモデルはテキスト生成を停止します。

seed?:

number
Random Sampling に使う Seed(整数)。設定し、モデルが対応している場合、呼び出しは決定的な結果を生成します。

headers?:

Record<string, string | undefined>
リクエストとともに送信する追加 HTTP Header。HTTP ベースの Provider にのみ適用されます。

戻り値
戻り値への直接リンク

text?:

string
生成されたテキストレスポンス。出力が 'text' の場合(Schema 未指定)に存在します。

object?:

object
生成された構造化レスポンス。outputstructuredOutputexperimental_output のいずれかで Schema を指定した場合に存在します。

toolCalls?:

Array<ToolCall>
生成処理中に行われた Tool 呼び出し。text モードと object モードの両方に存在します。
Array<ToolCall>

toolName:

string
呼び出された Tool の名前。

args:

any
Tool へ渡された引数。

新しい API への移行
新しい API への移行への直接リンク

情報

新しい .generate() メソッドは、AI SDK v5 以降との互換性、構造化出力処理の改善、ストリーミング対応の強化などの機能を提供します。詳しい移行手順は移行ガイドを参照してください。

移行の簡単な例
移行の簡単な例への直接リンク

変更前(Legacy)
変更前(Legacy)への直接リンク

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