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形式で含むデフォルトテンプレートを使用します。詳細な使用例とベストプラクティスについては、ワーキングメモリガイドを参照してください。
スレッドタイトル生成
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ベースのエンベッダーを使用することができます(この問題はありません):
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はOpenAI、Google、Mistral、Cohereなどのオプションを含む、Vercel AI SDK を通じて多くの埋め込みモデルをサポートしています。