Memory クラスリファレンス
Memory
クラスは、Mastra における会話履歴とスレッドベースのメッセージストレージを管理するための堅牢なシステムを提供します。これにより、会話の永続的な保存、セマンティック検索機能、および効率的なメッセージの取得が可能になります。デフォルトでは、LibSQL をストレージとベクトル検索に使用し、FastEmbed を埋め込みに使用します。
基本的な使用法
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({
// Optional storage configuration - libsql will be used by default
storage: new LibSQLStore({
url: "file:./memory.db",
}),
// Optional vector database for semantic search - libsql will be used by default
vector: new LibSQLVector({
url: "file:./vector.db",
}),
// Memory configuration options
options: {
// Number of recent messages to include
lastMessages: 20,
// Semantic search configuration
semanticRecall: {
topK: 3, // Number of similar messages to retrieve
messageRange: {
// Messages to include around each result
before: 2,
after: 1,
},
},
// Working memory configuration
workingMemory: {
enabled: true,
template: `
# User
- First Name:
- Last Name:
`,
},
},
});
const agent = new Agent({
memory,
...otherOptions,
});
ワーキングメモリ
ワーキングメモリ機能により、エージェントは会話間で永続的な情報を維持することができます。有効にすると、Memoryクラスはテキストストリームタグまたはツールコールを通じて、ワーキングメモリの更新を自動的に管理します。
ワーキングメモリの更新を処理するには、次の2つのモードがあります:
-
text-stream(デフォルト):エージェントはMarkdownを含むXMLタグ(
<working_memory># User \n ## Preferences...</working_memory>
)を使用して、応答に直接ワーキングメモリの更新を含めます。これらのタグは自動的に処理され、表示される出力からは削除されます。 -
tool-call:エージェントはワーキングメモリを更新するための専用ツールを使用します。このモードは、text-streamモードがデータストリーミングと互換性がないため、
toDataStream()
を使用する場合に使用すべきです。さらに、このモードはメモリ更新に対するより明示的な制御を提供し、テキストタグの管理よりもツールの使用が得意なエージェントと連携する場合に好まれることがあります。
設定例:
const memory = new Memory({
options: {
workingMemory: {
enabled: true,
template: "# User\n- **First Name**:\n- **Last Name**:",
use: "tool-call", // または 'text-stream'
},
},
});
テンプレートが提供されない場合、Memoryクラスはユーザーの詳細、設定、目標、およびその他の文脈情報をMarkdown形式で含むデフォルトのテンプレートを使用します。詳細な使用例とベストプラクティスについては、ワーキングメモリガイドを参照してください。
embedder
デフォルトでは、Memoryはbge-small-en-v1.5
モデルを使用したFastEmbedを使用し、パフォーマンスとモデルサイズ(約130MB)のバランスが良好です。異なるモデルやプロバイダーを使用したい場合にのみ、embedderを指定する必要があります。
ローカルエンベディングがサポートされていない環境では、APIベースのエンベッダーを使用できます:
import { Memory } from "@mastra/memory";
import { openai } from "@ai-sdk/openai";
const agent = new Agent({
memory: new Memory({
embedder: openai.embedding("text-embedding-3-small"), // ネットワークリクエストを追加
}),
});
MastraはOpenAI、Google、Mistral、Cohereなどのオプションを含むVercel AI SDK を通じて多くのエンベディングモデルをサポートしています。