Memory クラス
Memory
クラスは、Mastra における会話履歴とスレッド型メッセージ保存を管理するための堅牢なシステムを提供します。これにより、会話の永続保存、セマンティック検索、効率的なメッセージ取得が可能になります。会話履歴にはストレージプロバイダーの設定が必要で、セマンティックリコールを有効にする場合は、ベクターストアとエンベッダーの用意も必要です。
使用例
src/mastra/agents/test-agent.ts
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
export const agent = new Agent({
name: "test-agent",
instructions: "You are an agent with memory.",
model: openai("gpt-4o"),
memory: new Memory({
options: {
workingMemory: {
enabled: true
}
}
})
});
エージェントで
workingMemory
を有効化するには、メインの Mastra インスタンスにストレージプロバイダーを設定する必要があります。詳しくは Mastra class を参照してください。
コンストラクターのパラメーター
storage?:
MastraStorage
メモリデータを永続化するためのストレージ実装。指定しない場合は `new DefaultStorage({ config: { url: "file:memory.db" } })` が既定になります。
vector?:
MastraVector | false
セマンティック検索向けのベクターストア。ベクター機能を無効化するには `false` を指定します。
embedder?:
EmbeddingModel<string> | EmbeddingModelV2<string>
ベクトル埋め込み用のエンベッダーインスタンス。セマンティックリコールが有効な場合は必須です。
options?:
MemoryConfig
メモリの設定オプション。
processors?:
MemoryProcessor[]
LLM に送信する前にメッセージをフィルタリングまたは変換できるメモリプロセッサの配列。
オプションパラメータ
lastMessages?:
number | false
= 10
取得する最新メッセージの数。無効にする場合は false を指定します。
semanticRecall?:
boolean | { topK: number; messageRange: number | { before: number; after: number }; scope?: 'thread' | 'resource' }
= false
メッセージ履歴に対するセマンティック検索を有効化します。boolean か、設定オプションを持つオブジェクトを指定できます。有効化するには、ベクトルストアとエンベッダーの両方の設定が必要です。
workingMemory?:
WorkingMemory
= { enabled: false, template: '# User Information\n- **First Name**:\n- **Last Name**:\n...' }
ワーキングメモリ機能の設定。`{ enabled: boolean; template?: string; schema?: ZodObject<any> | JSONSchema7; scope?: 'thread' | 'resource' }` または `{ enabled: boolean }`(無効化)を指定できます。
threads?:
{ generateTitle?: boolean | { model: DynamicArgument<MastraLanguageModel>; instructions?: DynamicArgument<string> } }
= { generateTitle: false }
メモリスレッドの作成に関する設定。`generateTitle` は、ユーザーの最初のメッセージからスレッドタイトルを自動生成するかどうかを制御します。boolean か、カスタムの model と instructions を含むオブジェクトを指定できます。
戻り値
memory:
Memory
指定された構成の新しい Memory インスタンス。
拡張的な使用例
src/mastra/agents/test-agent.ts
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
export const agent = new Agent({
name: "test-agent",
instructions: "You are an agent with memory.",
model: openai("gpt-4o"),
memory: new Memory({
storage: new LibSQLStore({
url: "file:./working-memory.db"
}),
vector: new LibSQLVector({
connectionUrl: "file:./vector-memory.db"
}),
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2,
scope: 'resource'
},
workingMemory: {
enabled: true
},
threads: {
generateTitle: true
}
}
})
});