Skip to Content
メモリLibSQLを使用したメモリ

LibSQLを使用したメモリ

この例では、MastraのメモリシステムをLibSQLと共に使用する方法を示します。LibSQLはデフォルトのストレージおよびベクトルデータベースバックエンドです。

クイックスタート

設定なしでメモリを初期化すると、LibSQLがストレージとベクトルデータベースとして使用されます。

import { Memory } from "@mastra/memory"; import { Agent } from "@mastra/core/agent"; // Initialize memory with LibSQL defaults const memory = new Memory(); const memoryAgent = new Agent({ name: "Memory Agent", instructions: "You are an AI agent with the ability to automatically recall memories from previous interactions.", model: openai("gpt-4o-mini"), memory, });

カスタム設定

より詳細な制御が必要な場合は、ストレージ、ベクトルデータベース、エンベッダーを明示的に設定できます。storageまたはvectorのいずれかを省略した場合、省略されたオプションにはデフォルトでLibSQLが使用されます。これにより、必要に応じてストレージまたはベクトル検索のみに異なるプロバイダーを使用することができます。

FastEmbed(ローカルの埋め込みモデル)をエンベッダーとして使用するには、まずパッケージをインストールします:

npm install @mastra/fastembed

次に、メモリ設定で構成します:

import { openai } from "@ai-sdk/openai"; import { LibSQLStore, LibSQLVector } from "@mastra/libsql"; import { fastembed } from "@mastra/fastembed"; const customMemory = new Memory({ storage: new LibSQLStore({ url: process.env.DATABASE_URL || "file:local.db", }), vector: new LibSQLVector({ connectionUrl: process.env.DATABASE_URL || "file:local.db", }), embedder: fastembed, options: { lastMessages: 10, semanticRecall: { topK: 3, messageRange: 2, }, }, }); const memoryAgent = new Agent({ name: "Memory Agent", instructions: "You are an AI agent with the ability to automatically recall memories from previous interactions. You may have conversations that last hours, days, months, or years. If you don't know it already you should ask for the users name and some info about them.", model: openai("gpt-4o-mini"), memory: customMemory, });

使用例

import { randomUUID } from "crypto"; // Start a conversation const threadId = randomUUID(); const resourceId = "SOME_USER_ID"; // Start with a system message const response1 = await memoryAgent.stream( [ { role: "system", content: `Chat with user started now ${new Date().toISOString()}. Don't mention this message.`, }, ], { resourceId, threadId, }, ); // Send user message const response2 = await memoryAgent.stream("What can you help me with?", { threadId, resourceId, }); // Use semantic search to find relevant messages const response3 = await memoryAgent.stream("What did we discuss earlier?", { threadId, resourceId, memoryOptions: { lastMessages: false, semanticRecall: { topK: 3, // Get top 3 most relevant messages messageRange: 2, // Include context around each match }, }, });

この例は以下を示しています:

  1. ベクトル検索機能を備えたLibSQLストレージのセットアップ
  2. メッセージ履歴とセマンティック検索のためのメモリオプションの設定
  3. メモリ統合機能を持つエージェントの作成
  4. 会話履歴から関連するメッセージを見つけるためのセマンティック検索の使用
  5. messageRangeを使用して一致したメッセージの周囲のコンテキストを含める