Mastra의 에이전트는 강력한 메모리 시스템을 활용하여 대화 기록을 저장하고, 관련 정보를 불러오며, 지속적인 맥락을 유지할 수 있습니다. 이를 통해 에이전트가 보다 자연스럽고 상태를 가진 대화를 나눌 수 있게 됩니다.
에이전트에 메모리 활성화하기
메모리를 활성화하려면, 단순히 Memory 클래스를 인스턴스화한 후 에이전트 설정에 전달하면 됩니다. 이때 메모리 패키지와 저장소 어댑터(storage adapter)를 함께 설치해야 합니다.
npm install @mastra/memory@latest @mastra/libsql@latest
import { Agent } from "@mastra/core/agent";
import { Memory } from "@mastra/memory";
import { LibSQLStore } from "@mastra/libsql";
import { openai } from "@ai-sdk/openai";
const memory = new Memory({
storage: new LibSQLStore({
url: "file:../../memory.db",
}),
});
const agent = new Agent({
name: "MyMemoryAgent",
instructions: "You are a helpful assistant with memory.",
model: openai("gpt-4o"),
memory, // Attach the memory instance
});
이 기본 설정은 기본값을 사용합니다. 더 다양한 설정 방법은 메모리 문서를 참고하세요.
동적 메모리 구성
동적 지침, 모델, 도구를 설정하는 것과 마찬가지로, 실행 시점 컨텍스트를 활용해 메모리를 동적으로 구성할 수도 있습니다. 이를 통해 다음과 같은 기능을 구현할 수 있습니다.
-
사용자 등급이나 선호도에 따라 다른 메모리 시스템 사용
-
서로 다른 환경별로 메모리 구성 전환
-
기능 플래그에 따라 메모리 기능 활성화 또는 비활성화
-
사용자 컨텍스트에 맞춘 메모리 동작 맞춤화
예제: 사용자 등급 기반 메모리 구성
import { Agent } from "@mastra/core/agent";
import { Memory } from "@mastra/memory";
import { LibSQLStore } from "@mastra/libsql";
import { PostgresStore } from "@mastra/pg";
import { openai } from "@ai-sdk/openai";
// 사용자 등급별로 서로 다른 메모리 인스턴스 생성
const premiumMemory = new Memory({
storage: new LibSQLStore({ url: "file:premium.db" }),
options: {
semanticRecall: { topK: 10, messageRange: 5 }, // 프리미엄 사용자에게 더 많은 컨텍스트 제공
workingMemory: { enabled: true },
},
});
const standardMemory = new Memory({
storage: new LibSQLStore({ url: "file:standard.db" }),
options: {
semanticRecall: { topK: 3, messageRange: 2 }, // 일반 사용자에게 기본 수준의 회상 제공
workingMemory: { enabled: false },
},
});
const agent = new Agent({
name: "TieredMemoryAgent",
instructions: "사용자 등급별 메모리 기능을 갖춘 도움을 주는 어시스턴트입니다.",
model: openai("gpt-4o"),
memory: ({ runtimeContext }) => {
const userTier = runtimeContext.get("userTier");
return userTier === "premium" ? premiumMemory : standardMemory;
},
});
예제: 환경 기반 메모리
const agent = new Agent({
name: "EnvironmentAwareAgent",
instructions: "You are a helpful assistant.",
model: openai("gpt-4o"),
memory: ({ runtimeContext }) => {
const environment = runtimeContext.get("environment");
if (environment === "test") {
// 테스트용 로컬 스토리지 사용
return new Memory({
storage: new LibSQLStore({ url: ":memory:" }),
options: {
workingMemory: { enabled: true },
},
});
} else if (environment === "production") {
// 프로덕션 데이터베이스 사용
return new Memory({
storage: new PostgresStore({ connectionString: process.env.PRODUCTION_DB_URL }),
options: {
workingMemory: { enabled: true },
},
});
}
// 개발 환경
return new Memory({
storage: new LibSQLStore({ url: "file:dev.db" }),
});
},
});
예제: 비동기 메모리 구성
const agent = new Agent({
name: "AsyncMemoryAgent",
instructions: "You are a helpful assistant.",
model: openai("gpt-4o"),
memory: async ({ runtimeContext }) => {
const userId = runtimeContext.get("userId");
// 비동기 메모리 설정 시뮬레이션 (예: 데이터베이스 조회)
await new Promise(resolve => setTimeout(resolve, 10));
return new Memory({
storage: new LibSQLStore({
url: `file:user_${userId}.db`
}),
});
},
});
동적 메모리 사용하기
동적 메모리를 사용할 때는 에이전트 호출 시 런타임 컨텍스트를 전달하세요:
import { RuntimeContext } from "@mastra/core/runtime-context";
// 사용자 정보가 포함된 런타임 컨텍스트 생성
const runtimeContext = new RuntimeContext();
runtimeContext.set("userTier", "premium");
runtimeContext.set("environment", "production");
// 런타임 컨텍스트와 함께 에이전트 사용
const response = await agent.generate("내가 좋아하는 색깔은 파란색이라는 걸 기억해줘.", {
memory: {
resource: "user_alice",
thread: { id: "preferences_thread" },
},
runtimeContext, // 런타임 컨텍스트 전달
});
에이전트 호출에서 메모리 사용하기
상호작용 중에 메모리를 활용하려면 에이전트의 stream() 또는 generate() 메소드를 호출할 때 반드시 resourceId와 threadId를 제공해야 합니다.
-
resourceId: 일반적으로 사용자나 엔티티를 식별합니다 (예:user_123). -
threadId: 특정 대화 스레드를 식별합니다 (예:support_chat_456).
// 메모리를 사용하는 에이전트 호출 예제
await agent.stream("내가 좋아하는 색깔은 파란색이라는 걸 기억해줘.", {
resourceId: "user_alice",
threadId: "preferences_thread",
});
// 같은 스레드에서 나중에...
const response = await agent.stream("내가 좋아하는 색깔이 뭐야?", {
resourceId: "user_alice",
threadId: "preferences_thread",
});
// 에이전트는 메모리를 사용하여 좋아하는 색깔을 기억할 것입니다.
이러한 ID들은 대화 기록과 컨텍스트가 적절한 사용자와 대화에 대해 올바르게 저장되고 검색되도록 보장합니다.
다음 단계
스레드, 대화 기록, 의미적 회상, 작업 메모리와 같은 Mastra의 메모리 기능을 계속 탐색해보세요.
2025년 7월 26일 기준 번역
by dongne.lab@gmail.com