Mem0 を使ったメモリ
この例では、カスタムツールを通じて Mem0 をメモリバックエンドとして用い、Mastra のエージェントシステムを活用する方法を示します。
前提条件
この例では openai
モデルを使用し、Mem0 の API キーが必要です。.env
ファイルに次の内容を追加してください:
.env
OPENAI_API_KEY=<your-api-key>
MEM0_API_KEY=<your-mem0-api-key>
次のパッケージをインストールしてください:
npm install @mastra/mem0
Mem0 の API キーは、app.mem0.ai にサインアップし、新しいプロジェクトを作成すると取得できます。
エージェントにメモリを追加する
エージェントに Mem0 のメモリ機能を追加するには、Mem0Integration
を用いたカスタムツールを作成し、それらをエージェントのツールに追加します。これにより、エージェントは Mem0 を使ってメモリ操作を自在に行えるようになります。
src/mastra/agents/example-mem0-agent.ts
import { createTool } from "@mastra/core/tools";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { Mem0Integration } from "@mastra/mem0";
import { z } from "zod";
const mem0 = new Mem0Integration({
config: {
apiKey: process.env.MEM0_API_KEY!,
user_id: "mem0-agent"
}
});
export const mem0Agent = new Agent({
name: "mem0-agent",
instructions: `
You are a helpful assistant that has the ability to memorize and remember facts using Mem0.
Use the Mem0-memorize tool to save important information that might be useful later.
Use the Mem0-remember tool to recall previously saved information when answering questions.
`,
model: openai("gpt-4o"),
tools: {
mem0Memorize: createTool({
id: "Mem0-memorize",
description: "Save information to Mem0",
inputSchema: z.object({
statement: z.string()
}),
execute: async ({ context }) => {
const { statement } = context;
await mem0.createMemory(statement);
console.log(`memory "${statement}" saved.\n`);
return { success: true };
}
}),
mem0Remember: createTool({
id: "Mem0-remember",
description: "Recall agent memories",
inputSchema: z.object({
question: z.string()
}),
outputSchema: z.object({
answer: z.string()
}),
execute: async ({ context }) => {
const { question } = context;
const memory = await mem0.searchMemory(question);
return { answer: memory };
}
})
}
});
使用例
エージェントが適切な Mem0 ツールを呼び出すように、system メッセージを使用します。記憶の保存には、エージェントに情報を保存するよう指示する system メッセージを使います。想起には、回答する前に記憶を検索するようエージェントに指示する system メッセージを使います。
src/test-mem0-agent.ts
import "dotenv/config";
import { mastra } from "./mastra";
const threadId = "123";
const resourceId = "user-456";
const agent = mastra.getAgent("mem0Agent");
const message = await agent.stream(
[
{ role: "system", content: "Use the mem0Memorize tool to save any personal information shared by the user." },
{ role: "user", content: "My name is Mastra" }
],
{
memory: { thread: threadId, resource: resourceId }
}
);
await message.textStream.pipeTo(new WritableStream());
const stream = await agent.stream(
[
{ role: "system", content: "Use the mem0Remember tool to search for any relevant memories before answering questions about the user." },
{ role: "user", content: "What's my name?" }
],
{
memory: {
thread: threadId,
resource: resourceId
}
}
);
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}