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({
// Optional storage configuration - libsql will be used by default
storage: new LibSQLStore({
url: "file:./memory.db",
}),
// Optional vector database for semantic search
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クラスは専用のツール呼び出しを使用してワーキングメモリの更新を自動的に管理します。
設定例:
const memory = new Memory({
options: {
workingMemory: {
enabled: true,
template: "# User\n- **First Name**:\n- **Last Name**:",
},
},
});
テンプレートが提供されない場合、Memoryクラスはユーザーの詳細、設定、目標、およびその他のコンテキスト情報をMarkdown形式で含むデフォルトのテンプレートを使用します。詳細な使用例とベストプラクティスについては、ワーキングメモリガイドを参照してください。
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はVercel AI SDK を通じて、OpenAI、Google、Mistral、Cohereなどのオプションを含む多くの埋め込みモデルをサポートしています。