LibSQL を用いたメモリー
この例では、Mastra のメモリーシステムで LibSQL をストレージバックエンドとして利用する方法を示します。
前提条件
この例では openai
モデルを使用します。OPENAI_API_KEY
を .env
ファイルに追加してください。
.env
OPENAI_API_KEY=<your-api-key>
また、次のパッケージをインストールしてください:
npm install @mastra/libsql
エージェントにメモリを追加する
エージェントに LibSQL のメモリ機能を追加するには、Memory
クラスを使用し、LibSQLStore
で新しい storage
キーを作成します。url
にはリモートの場所かローカルのファイルシステム上のリソースを指定できます。
src/mastra/agents/example-libsql-agent.ts
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { LibSQLStore } from "@mastra/libsql";
export const libsqlAgent = new Agent({
name: "libsql-agent",
instructions: "You are an AI agent with the ability to automatically recall memories from previous interactions.",
model: openai("gpt-4o"),
memory: new Memory({
storage: new LibSQLStore({
url: "file:libsql-agent.db"
}),
options: {
threads: {
generateTitle: true
}
}
})
});
fastembed を使ったローカル埋め込み
埋め込みは、memory の semanticRecall
が(キーワードではなく)意味に基づいて関連メッセージを検索するために用いる数値ベクトルです。このセットアップでは、@mastra/fastembed
を使ってベクトル埋め込みを生成します。
はじめに fastembed
をインストールします:
npm install @mastra/fastembed
次をエージェントに追加します:
src/mastra/agents/example-libsql-agent.ts
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
import { fastembed } from "@mastra/fastembed";
export const libsqlAgent = new Agent({
name: "libsql-agent",
instructions: "You are an AI agent with the ability to automatically recall memories from previous interactions.",
model: openai("gpt-4o"),
memory: new Memory({
storage: new LibSQLStore({
url: "file:libsql-agent.db"
}),
vector: new LibSQLVector({
connectionUrl: "file:libsql-agent.db"
}),
embedder: fastembed,
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2
},
threads: {
generateTitle: true
}
}
})
});
使用例
このリクエストでのリコール範囲には memoryOptions
を使用します。lastMessages: 5
を設定して直近メッセージに基づくリコールを制限し、semanticRecall
を使って、各一致の前後文脈として messageRange: 2
の隣接メッセージを含めつつ、関連性の高いメッセージを topK: 3
件取得します。
src/test-libsql-agent.ts
import "dotenv/config";
import { mastra } from "./mastra";
const threadId = "123";
const resourceId = "user-456";
const agent = mastra.getAgent("libsqlAgent");
const message = await agent.stream("My name is Mastra", {
memory: {
thread: threadId,
resource: resourceId
}
});
await message.textStream.pipeTo(new WritableStream());
const stream = await agent.stream("What's my name?", {
memory: {
thread: threadId,
resource: resourceId
},
memoryOptions: {
lastMessages: 5,
semanticRecall: {
topK: 3,
messageRange: 2
}
}
});
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}