Postgresによるメモリ
この例では、PostgreSQLをストレージバックエンドとして使用するMastraのメモリシステムの使用方法を示しています。
セットアップ
まず、PostgreSQLストレージとベクトル機能を使用してメモリシステムをセットアップします:
import { Memory } from "@mastra/memory";
import { PostgresStore, PgVector } from "@mastra/pg";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
// PostgreSQL接続の詳細
const host = "localhost";
const port = 5432;
const user = "postgres";
const database = "postgres";
const password = "postgres";
const connectionString = `postgresql://${user}:${password}@${host}:${port}`;
// PostgreSQLストレージとベクトル検索でメモリを初期化
const memory = new Memory({
storage: new PostgresStore({
host,
port,
user,
database,
password,
}),
vector: new PgVector({ connectionString }),
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2,
},
},
});
// メモリ機能を持つエージェントを作成
const chefAgent = new Agent({
name: "chefAgent",
instructions:
"あなたはミシェルです。実用的で経験豊富な家庭料理人で、人々が手持ちの食材で素晴らしい料理を作るのを手伝います。",
model: openai("gpt-4o-mini"),
memory,
});
使用例
import { randomUUID } from "crypto";
// Start a conversation
const threadId = randomUUID();
const resourceId = "SOME_USER_ID";
// Ask about ingredients
const response1 = await chefAgent.stream(
"In my kitchen I have: pasta, canned tomatoes, garlic, olive oil, and some dried herbs (basil and oregano). What can I make?",
{
threadId,
resourceId,
},
);
// Ask about different ingredients
const response2 = await chefAgent.stream(
"Now I'm over at my friend's house, and they have: chicken thighs, coconut milk, sweet potatoes, and curry powder.",
{
threadId,
resourceId,
},
);
// Use memory to recall previous conversation
const response3 = await chefAgent.stream(
"What did we cook before I went to my friends house?",
{
threadId,
resourceId,
memoryOptions: {
lastMessages: 3, // Get last 3 messages for context
},
},
);
この例は以下を示しています:
- ベクトル検索機能を備えたPostgreSQLストレージのセットアップ
- メッセージ履歴とセマンティック検索のためのメモリオプションの設定
- メモリ統合機能を持つエージェントの作成
- 複数のやり取りにわたって会話のコンテキストを維持するためのエージェントの使用