Skip to Content

Agent.getMemory()

getMemory() メソッドは、エージェントに関連付けられたメモリシステムを取得します。このメソッドは、会話間で情報を保存および取得するためのエージェントのメモリ機能にアクセスするために使用されます。

構文

getMemory(): MastraMemory | undefined

パラメータ

このメソッドはパラメータを取りません。

戻り値

エージェントにメモリシステムが設定されている場合はMastraMemoryインスタンスを返し、メモリシステムが設定されていない場合はundefinedを返します。

説明

getMemory()メソッドは、エージェントに関連付けられたメモリシステムにアクセスするために使用されます。メモリシステムによりエージェントは以下のことが可能になります:

  • 複数のインタラクションにわたって情報を保存および取得する
  • 会話履歴を維持する
  • ユーザーの設定や文脈を記憶する
  • 過去のインタラクションに基づいてパーソナライズされた応答を提供する

このメソッドは、メモリシステムを使用する前にエージェントがメモリシステムを持っているかどうかを確認するために、hasOwnMemory()と組み合わせて使用されることがよくあります。

基本的な使い方

import { Agent } from "@mastra/core/agent"; import { Memory } from "@mastra/memory"; import { openai } from "@ai-sdk/openai"; // Create a memory system const memory = new Memory(); // Create an agent with memory const agent = new Agent({ name: "memory-assistant", instructions: "You are a helpful assistant that remembers previous conversations.", model: openai("gpt-4o"), memory, }); // Get the memory system const agentMemory = agent.getMemory(); if (agentMemory) { // Use the memory system to retrieve thread messages const thread = await agentMemory.getThreadById({ resourceId: "user-123", threadId: "conversation-1", }); console.log("Retrieved thread:", thread); }

使用前にメモリを確認する

import { Agent } from "@mastra/core/agent"; import { openai } from "@ai-sdk/openai"; // Create an agent without memory const agent = new Agent({ name: "stateless-assistant", instructions: "You are a helpful assistant.", model: openai("gpt-4o"), }); // Check if the agent has memory before using it if (agent.hasOwnMemory()) { const memory = agent.getMemory(); // Use memory... } else { console.log("This agent does not have a memory system."); }

会話でメモリを使う

import { Agent } from "@mastra/core/agent"; import { Memory } from "@mastra/memory"; import { openai } from "@ai-sdk/openai"; // Create a memory system const memory = new Memory(); // Create an agent with memory const agent = new Agent({ name: "memory-assistant", instructions: "You are a helpful assistant that remembers previous conversations.", model: openai("gpt-4o"), memory, }); // First interaction - store information await agent.generate("My name is Alice.", { resourceId: "user-123", threadId: "conversation-1", }); // Later interaction - retrieve information const result = await agent.generate("What's my name?", { resourceId: "user-123", threadId: "conversation-1", }); console.log(result.text); // Should mention "Alice" // Access the memory system directly const agentMemory = agent.getMemory(); if (agentMemory) { // Retrieve messages from the thread const { messages } = await agentMemory.query({ resourceId: "user-123", threadId: "conversation-1", selectBy: { last: 10, // Get the last 10 messages }, }); console.log("Retrieved messages:", messages); }