PostgreSQL を用いたメモリ
この例では、Mastra のメモリシステムをストレージのバックエンドとして PostgreSQL と組み合わせて使用する方法を示します。
前提条件
この例では openai
モデルを使用し、pgvector
拡張機能を有効にした PostgreSQL データベースが必要です。.env
ファイルに次を追加してください:
.env
OPENAI_API_KEY=<your-api-key>
DATABASE_URL=<your-connection-string>
また、次のパッケージをインストールしてください:
npm install @mastra/pg
エージェントにメモリを追加する
エージェントに PostgreSQL のメモリ機能を追加するには、Memory
クラスを使用し、PostgresStore
を用いて新たに storage
キーを作成します。connectionString
にはリモートの接続先またはローカルのデータベース接続を指定できます。
src/mastra/agents/example-pg-agent.ts
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { PostgresStore } from "@mastra/pg";
export const pgAgent = new Agent({
name: "pg-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 PostgresStore({
connectionString: process.env.DATABASE_URL!
}),
options: {
threads: {
generateTitle: true
}
}
})
});
fastembed を使ったローカル埋め込み
埋め込みは、メモリの semanticRecall
が意味ベース(キーワードではなく)で関連するメッセージを検索するために用いる数値ベクトルです。このセットアップでは、ベクトル埋め込みの生成に @mastra/fastembed
を使用します。
まずは fastembed
をインストールします:
npm install @mastra/fastembed
次のコードをエージェントに追加します:
src/mastra/agents/example-pg-agent.ts
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { PostgresStore, PgVector } from "@mastra/pg";
import { fastembed } from "@mastra/fastembed";
export const pgAgent = new Agent({
name: "pg-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 PostgresStore({
connectionString: process.env.DATABASE_URL!
}),
vector: new PgVector({
connectionString: process.env.DATABASE_URL!
}),
embedder: fastembed,
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2
}
}
})
});
使用例
このリクエストのリコール範囲を絞るには memoryOptions
を使用します。lastMessages: 5
を設定して直近メッセージに基づく想起を制限し、semanticRecall
を使って、各一致の前後文脈として messageRange: 2
件の隣接メッセージを含めつつ、最も関連性の高い topK: 3
件のメッセージを取得します。
src/test-pg-agent.ts
import "dotenv/config";
import { mastra } from "./mastra";
const threadId = "123";
const resourceId = "user-456";
const agent = mastra.getAgent("pgAgent");
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);
}