Memory クラス リファレンス
Memory
クラスは、Mastra における会話履歴とスレッドベースのメッセージ保存を管理するための堅牢なシステムを提供します。これにより、会話の永続化、セマンティック検索、効率的なメッセージ取得が可能になります。会話履歴を利用するにはストレージプロバイダーの設定が必須で、セマンティックリコールを有効にする場合は、ベクトルストアとエンベッダーの用意も必要です。
基本的な使い方
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
const agent = new Agent({
memory: new Memory(),
...otherOptions,
});
カスタム設定
import { Memory } from "@mastra/memory";
import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
import { Agent } from "@mastra/core/agent";
const memory = new Memory({
// 省略可能なストレージ設定(デフォルトは libsql)
storage: new LibSQLStore({
url: "file:./memory.db",
}),
// セマンティック検索用の任意のベクターデータベース
vector: new LibSQLVector({
url: "file:./vector.db",
}),
// メモリ設定オプション
options: {
// 直近のメッセージの含める数
lastMessages: 20,
// セマンティック検索の設定
semanticRecall: {
topK: 3, // 取得する類似メッセージの数
messageRange: {
// 各結果の前後に含めるメッセージ
before: 2,
after: 1,
},
},
// ワーキングメモリの設定
workingMemory: {
enabled: true,
template: `
# User
- First Name:
- Last Name:
`,
},
// スレッドの設定
threads: {
generateTitle: true, // エージェントのモデルでタイトルを生成
// あるいはタイトル生成に別のモデルを使用
// generateTitle: {
// model: openai("gpt-4.1-nano"), // タイトルには低コストなモデルを使用
// instructions: "Generate a concise title based on the initial user message.", // タイトル用のカスタム指示
// },
},
},
});
const agent = new Agent({
memory,
...otherOptions,
});
ワーキングメモリ
ワーキングメモリ機能により、エージェントは会話をまたいで情報を持続的に保持できます。有効化すると、Memory クラスが専用のツール呼び出しを使ってワーキングメモリの更新を自動管理します。
設定例:
const memory = new Memory({
options: {
workingMemory: {
enabled: true,
template: "# User\n- **First Name**:\n- **Last Name**:",
},
},
});
テンプレートが指定されていない場合、Memory クラスは既定のテンプレートを使用し、ユーザー情報、嗜好、目標、その他のコンテキスト情報の項目を Markdown 形式で含みます。詳しい使用例やベストプラクティスは、Working Memory guide を参照してください。
スレッドタイトルの生成
generateTitle
機能は、ユーザーの最初のメッセージに基づいて会話スレッドに意味のあるタイトルを自動生成します。これにより、アプリ内で会話を整理・識別しやすくなります。
基本的な使い方
const memory = new Memory({
options: {
threads: {
generateTitle: true, // エージェントのモデルでタイトルを生成
},
},
});
カスタムモデルと指示によるコスト最適化
メインの会話には高品質なモデルを使いつつ、タイトル生成には別の(一般的に低コストな)モデルとカスタム指示を指定できます:
import { openai } from "@ai-sdk/openai";
const memory = new Memory({
options: {
threads: {
generateTitle: {
model: openai("gpt-4.1-nano"), // タイトル用の低コストモデル
instructions: "Generate a concise, friendly title based on the initial user message.", // タイトル用のカスタム指示
},
},
},
});
const agent = new Agent({
model: openai("gpt-4o"), // メイン会話用の高品質モデル
memory,
});
モデル選択と指示の動的化
実行時のコンテキストに基づいて、モデルと指示を動的に決定する関数を使用することもできます:
const memory = new Memory({
options: {
threads: {
generateTitle: {
model: (ctx: RuntimeContext) => {
// コンテキストに応じてモデルを切り替え
const userTier = ctx.get("userTier");
return userTier === "premium"
? openai("gpt-4.1")
: openai("gpt-4.1-nano");
},
instructions: (ctx: RuntimeContext) => {
const language = ctx.get("userLanguage") || "English";
return `Generate a concise, engaging title in ${language} based on the user's first message.`;
},
},
},
},
});
embedder
semanticRecall
が有効な場合は、埋め込みモデルが必要です。
選択肢の一つとして @mastra/fastembed
を利用できます。これは FastEmbed を用いたデバイス上/ローカル実行の埋め込みモデルを提供します。このモデルはローカルで動作し、API キーやネットワークリクエストは不要です。
使用するには、まずパッケージをインストールします:
npm install @mastra/fastembed
次に、Memory
インスタンスで設定します。
import { Memory } from "@mastra/memory";
import { fastembed } from "@mastra/fastembed";
import { Agent } from "@mastra/core/agent";
const agent = new Agent({
memory: new Memory({
embedder: fastembed,
// ... other memory config
}),
});
なお、プロジェクトのデプロイ先によっては、FastEmbed の内部依存関係が大きいため、プロジェクトをデプロイできない場合があります。
代わりに、この問題のない OpenAI のような API ベースの埋め込み器(embedder)を使用できます。
import { Memory } from "@mastra/memory";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
const agent = new Agent({
memory: new Memory({
embedder: openai.embedding("text-embedding-3-small"),
}),
});
Mastra は Vercel AI SDK を通じて、OpenAI、Google、Mistral、Cohere など、数多くの埋め込みモデルをサポートしています。