> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # Memory Memory를 사용하면 Agent가 상호 작용 전반에 걸쳐 사용자 메시지와 Agent 응답, Tool 결과를 기억하여 일관성을 유지하고 대화 흐름을 유지하며 시간이 지남에 따라 더 나은 답변을 생성하는 데 필요한 컨텍스트를 제공할 수 있습니다. Mastra Agent는 다음을 저장하도록 구성될 수 있습니다.[message history](https://mastra.zisheng.pro/ko/docs/memory/message-history). Additionally, you can enable: - [관찰 기억](https://mastra.zisheng.pro/ko/docs/memory/observational-memory)(권장): 백그라운드 Agent를 사용하여 증가하는 원시 메시지 기록을 대체하는 조밀한 관찰 로그를 유지합니다. 이렇게 하면 장기 Memory를 보존하면서 컨텍스트 창을 작게 유지합니다. - [작업기억](https://mastra.zisheng.pro/ko/docs/memory/working-memory): 이름, 선호도, 목표 등 지속적이고 구조화된 사용자 데이터를 저장합니다. - [의미적 회상](https://mastra.zisheng.pro/ko/docs/memory/semantic-recall): 정확한 키워드가 아닌 의미론적 의미를 기반으로 관련 과거 메시지를 검색합니다. - [다중 사용자 스레드](https://mastra.zisheng.pro/ko/docs/memory/multi-user-threads): 여러 사용자가 하나의 스레드를 공유합니다. 결합된 Memory가 Model의 컨텍스트 제한을 초과하는 경우[memory processors](https://mastra.zisheng.pro/ko/docs/memory/memory-processors) 은 가장 관련성 높은 정보가 보존되도록 콘텐츠를 필터링하거나 잘라내거나 우선순위를 지정할 수 있습니다. Memory 결과는 구성된 하나 이상의 저장소에 저장됩니다.[storage providers](https://mastra.zisheng.pro/ko/docs/storage/overview). :::tip\[📹 보기] 보다[Mastra memory concepts](https://www.youtube.com/watch?v=18iIHQtIPmc) 에서 Agent가 사용할 수 있는 Memory 계층의 개념적 개요를 확인하세요. ::: ## Memory를 사용해야 하는 경우 Agent가 이전 교환을 참조하거나 세션 초기의 사용자 기본 설정이나 사실을 회상하는 다단계 대화를 유지해야 하거나 대화 스레드 내에서 시간이 지남에 따라 컨텍스트를 구축해야 할 때 Memory를 사용하십시오. 각 상호작용이 독립적인 단일 회전 요청의 경우 Memory를 건너뜁니다. ## 빠른 시작 1. 설치하다`@mastra/memory` package. **npm**: ```bash npm install @mastra/memory@latest ``` **pnpm**: ```bash pnpm add @mastra/memory@latest ``` **Yarn**: ```bash yarn add @mastra/memory@latest ``` **Bun**: ```bash bun add @mastra/memory@latest ``` 2. Memory**requires** 메시지 기록(사용자 메시지와 Agent 응답 포함)을 영구 저장할 스토리지 Provider를 설정하세요. 이 빠른 시작의 목적에 따라 다음을 사용합니다.`@mastra/libsql`. **npm**: ```bash npm install @mastra/libsql@latest ``` **pnpm**: ```bash pnpm add @mastra/libsql@latest ``` **Yarn**: ```bash yarn add @mastra/libsql@latest ``` **Bun**: ```bash bun add @mastra/libsql@latest ``` 사용 가능한 Provider 및 Mastra의 저장 공간 작동 방식에 대한 자세한 내용을 보려면 다음을 방문하세요.[storage](https://mastra.zisheng.pro/ko/docs/storage/overview) documentation. 3. 구성된 모든 Agent에서 Memory를 활성화하려면 기본 Mastra 인스턴스에 스토리지 공급자를 추가하세요. **AI Agent의 경우:**중요: 추가`id` to `LibSQLStore`. ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: ':memory:', }), }) ``` 4. 만들기`Memory` instance and pass it to the agent's `memory` option. ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' export const memoryAgent = new Agent({ id: 'memory-agent', name: 'Memory Agent', memory: new Memory({ options: { lastMessages: 20, }, }), }) ``` 방문하다[Memory Class](https://mastra.zisheng.pro/ko/reference/memory/memory-class) for a full list of configuration options. 5. 예를 들어 대리인에게 전화하십시오.[Studio](https://mastra.zisheng.pro/ko/docs/studio/overview). Studio에서 Agent와 새 채팅을 시작하고 오른쪽 사이드바를 확인하세요. 이제 다양한 Memory 관련 정보가 표시됩니다. ## 메시지 기록 통과`memory` object with `resource` and `thread` to track message history. - `resource`: 사용자 또는 엔터티에 대한 안정적인 식별자입니다. - `thread`: 특정 대화나 세션을 분리하는 ID입니다. ```typescript const response = await memoryAgent.generate('Remember my favorite color is blue.', { memory: { resource: 'user-123', thread: 'conversation-123', }, }) ``` Memory에 저장된 정보를 불러오려면 해당 Agent를 호출하세요.`resource` and `thread` values used in the original conversation. ```typescript const response = await memoryAgent.generate("What's my favorite color?", { memory: { resource: 'user-123', thread: 'conversation-123', }, }) // Response: "Your favorite color is blue." ``` > **경고:** 각 스레드에는 소유자(`resourceId`)이며 생성 후에는 변경할 수 없습니다. 소유자가 다른 스레드에 동일한 스레드 ID를 재사용하면 쿼리할 때 오류가 발생하므로 피하세요. 리소스에 대한 모든 스레드를 나열하거나 특정 스레드를 검색하려면,[use the memory API directly](https://mastra.zisheng.pro/ko/docs/memory/message-history). ## 관찰 기억 장시간 실행되는 대화의 경우 원시 메시지 기록이 컨텍스트 창을 채울 때까지 늘어나 Agent 성능이 저하됩니다.[Observational Memory](https://mastra.zisheng.pro/ko/docs/memory/observational-memory) 은 오래된 메시지를 밀도 높은 관찰로 압축하는 백그라운드 Agent를 실행하여 이 문제를 해결합니다. 장기 Memory를 보존하면서 컨텍스트 창을 작게 유지합니다. **AI Agent의 경우:**관찰 Memory를 사용하려면 스토리지 공급자가 필요합니다! Mastra 인스턴스에서 설정해야 합니다.`src/mastra/index.ts` or pass it to the Agent constructor. ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' export const memoryAgent = new Agent({ id: 'memory-agent', name: 'Memory Agent', memory: new Memory({ options: { observationalMemory: true, }, }), }) ``` 보다[Observational Memory](https://mastra.zisheng.pro/ko/docs/memory/observational-memory) 에서 관찰과 리플렉션의 작동 방식에 대한 자세한 내용을 확인하고, [the reference](https://mastra.zisheng.pro/ko/reference/memory/observational-memory) for all configuration options. ## Model이 보는 것 각 Memory 기능은 Model에 전송된 요청의 시스템 메시지 또는 대화 메시지에 추가됩니다. 레이어는 활성화한 기능에 따라 달라집니다. 작업 Memory와 의미 회상은 구성된 경우에만 나타납니다. 관찰 Memory에도 동일하게 적용되며 메시지 기록은 기본적으로 켜져 있습니다. 다이어그램은 활성화된 각 레이어가 요청에 배치되는 위치를 보여줍니다. 아래 목록은 각 레이어의 역할을 설명합니다. ![Diagram showing how Mastra assembles the model context: system messages containing agent instructions, call-time system messages, working memory, cross-thread semantic recall, and Observational Memory, followed by conversation messages where message history and same-thread semantic recall interleave by timestamp, then call-time context messages, and finally the new user message](/img/memory/memory-context-window-light.svg) - [작업기억](https://mastra.zisheng.pro/ko/docs/memory/working-memory)템플릿과 저장된 데이터가 포함된 시스템 메시지로 삽입됩니다. 와 함께`useStateSignals`, it's delivered as a state signal instead. - [의미적 회상](https://mastra.zisheng.pro/ko/docs/memory/semantic-recall)현재 스레드의 일치 항목은 일반 메시지로 삽입되고 타임스탬프별로 메시지 기록과 인터리브됩니다. 대신 다른 스레드의 일치 항목은 시스템 메시지 형식으로 지정됩니다. - [메시지 기록](https://mastra.zisheng.pro/ko/docs/memory/message-history)마지막 N개 메시지를 시간순으로 추가합니다. 새 메시지는 항상 마지막에 옵니다. - [관찰 기억](https://mastra.zisheng.pro/ko/docs/memory/observational-memory)오래된 원시 기록을 대체합니다. 반영 및 관찰은 시스템 메시지에 존재하며 아직 관찰되지 않은 메시지만 대화에 남아 있습니다. 짧은 연속 알림은 대화 메시지 시작 부분에 배치됩니다. - 컨텍스트 메시지는 선택사항입니다.`context` array passed on a call, for example `agent.generate(msg, { context: [...] })`. 앱 상태나 자체 RAG 결과처럼 일회성 배경 정보에 사용하세요. 해당 요청에서만 일반 대화 메시지로 표시되며 Memory에는 절대 저장되지 않습니다. 대화 메시지는 타임스탬프별로 정렬되고 메시지 ID별로 중복 제거되므로 회수된 오래된 메시지가 최근 기록 앞에 표시됩니다. 통화 시 전달된 컨텍스트 메시지에는 현재 시간이 찍혀 기록 및 회수 다음, 새 메시지 앞에 배치됩니다. 실제 요청에 대한 정확한 컨텍스트를 검사하려면 다음을 사용하세요.[Tracing](https://mastra.zisheng.pro/ko/docs/observability/tracing/overview) and open the LLM call spans, see [Observability](#observability) below. ## 다중 Agent 시스템의 Memory 언제[supervisor agent](https://mastra.zisheng.pro/ko/docs/capabilities/subagents) 가 하위 Agent에 위임하면 Mastra는 하위 Agent의 Memory를 자동으로 격리합니다. 모든 위임에서 자동으로 이루어지므로 이를 활성화하는 플래그는 없습니다. 이 범위 지정 방식을 이해하면 비공개로 유지할 항목과 의도적으로 공유할 항목을 결정할 수 있습니다. ### 위임이 Memory 범위를 지정하는 방법 각 대표단은 새로운`threadId` and a deterministic `resourceId` for the subagent: - **스레드 ID**: 위임별로 고유합니다. 하위 Agent는 호출될 때마다 깨끗한 메시지 기록으로 시작됩니다. - **리소스 ID**: 다음과 같이 파생됨`{parentResourceId}-{agentName}`. 리소스 ID는 위임 전반에 걸쳐 일정하므로 리소스 범위 Memory는 호출 간에 유지됩니다. 하위 Agent는 동일한 사용자의 이전 위임에서 얻은 사실을 기억합니다. - **Memory 인스턴스**: 자체 Memory가 없는 하위 Agent는 감독자의 Memory를 상속받습니다.`Memory` 인스턴스와 구성된 모든 옵션을 상속합니다. 하위 Agent가 자체 인스턴스를 정의하면 그것이 우선합니다. > **노트:** 타이틀 생성(`generateTitle`) is a top-level thread concern and **isn't** 은 상속된 하위 Agent 스레드에 적용되지 않습니다. 각 위임은 누구에게도 표시되지 않는 임시 스레드를 생성하므로 여기에 제목 생성을 실행하면 위임마다 LLM 호출 하나가 낭비됩니다. 하위 Agent 자체 스레드의 제목을 생성하려면 해당 하위 Agent에 자체 Memory 구성을 제공하세요. 감독자는 작업을 완료하는 데 충분한 배경 ​​지식을 갖도록 대화 컨텍스트를 하위 Agent에 전달합니다. 위임 Prompt와 하위 Agent의 응답만 저장되며 전체 상위 대화는 저장되지 않습니다. 다음을 사용하여 하위 Agent에 도달하는 메시지를 제어할 수 있습니다.[`messageFilter`](https://mastra.zisheng.pro/ko/docs/capabilities/subagents) callback. > **노트:** 하위 Agent 리소스 ID에는 항상 Agent 이름(`{parentResourceId}-{agentName}`). 동일한 상위 Agent 아래의 서로 다른 하위 Agent는 위임을 통해 리소스 ID를 공유하지 않습니다. 이 기본 격리를 뛰어넘기 위해 Agent를 직접 호출할 때 일치하는 식별자를 전달하여 Agent 간에 Memory를 공유할 수 있습니다. ### Agent 간 Memory 공유 위임 흐름 외부에서 Agent를 직접 호출하는 경우 Memory 공유는 두 가지 식별자에 의해 제어됩니다.`resourceId` and `threadId`. 같은 값을 사용하는 Agent는 동일한 데이터를 읽고 씁니다. 이는 Agent들이 공유 컨텍스트에서 협업할 때 유용합니다. 예를 들어 연구 Agent가 메모를 저장하고 작성 Agent가 이를 읽을 수 있습니다. **리소스 범위 공유**가장 일반적인 패턴이다.[Working memory](https://mastra.zisheng.pro/ko/docs/memory/working-memory) and [semantic recall](https://mastra.zisheng.pro/ko/docs/memory/semantic-recall) default to `scope: 'resource'`. If two agents share a `resourceId`, 서로 다른 스레드에서도 관찰, 작업 Memory 및 임베딩을 공유합니다. ```typescript // Both agents share the same resource-scoped memory await researcher.generate('Find information about quantum computing.', { memory: { resource: 'project-42', thread: 'research-session' }, }) await writer.generate('Write a summary from the research notes.', { memory: { resource: 'project-42', thread: 'writing-session' }, }) ``` 두 호출 모두 사용하기 때문에`resource: 'project-42'`, 작성 Agent는 연구 Agent의 관찰과 작업 Memory에 접근할 수 있습니다. 의미 임베딩도 리소스를 통해 공유됩니다. 각 Agent는 여전히 자체 스레드를 사용하므로 메시지 기록은 분리된 상태로 유지됩니다. **스레드 범위 공유**더 단단한 결합을 제공합니다.[Observational Memory](https://mastra.zisheng.pro/ko/docs/memory/observational-memory) uses `scope: 'thread'` by default. If two agents use the same `resource` and `thread`, 전체 메시지 기록을 공유합니다. 각 Agent는 다른 Agent가 작성한 모든 메시지를 볼 수 있습니다. 이는 Agent들이 서로의 정확한 출력을 기반으로 작업해야 할 때 유용합니다. ## Observability 할 수 있게 하다[Tracing](https://mastra.zisheng.pro/ko/docs/observability/tracing/overview) 를 사용하여 실제로 작동하는 Memory를 모니터링하고 디버깅하세요. Trace에는 Agent가 각 요청의 컨텍스트에 포함한 메시지와 관찰이 정확히 표시되므로 Agent의 동작을 이해하고 Memory 검색이 예상대로 작동하는지 확인할 수 있습니다. 열려 있는[Studio](https://mastra.zisheng.pro/ko/docs/studio/overview) and select the **Observability** 사이드바의 탭을 여세요. 최근 Agent 요청의 Trace를 열고 LLM 호출 스팬을 찾으세요. ## 요청당 Memory 전환 사용[`RequestContext`](https://mastra.zisheng.pro/ko/docs/server/request-context) 을 사용하여 요청별 값에 접근하세요. 이를 통해 요청 컨텍스트에 따라 서로 다른 Memory 또는 스토리지 구성을 조건부로 선택할 수 있습니다. ```typescript export type UserTier = { 'user-tier': 'enterprise' | 'pro' } const premiumMemory = new Memory() const standardMemory = new Memory() export const memoryAgent = new Agent({ id: 'memory-agent', name: 'Memory Agent', memory: ({ requestContext }) => { const userTier = requestContext.get('user-tier') as UserTier['user-tier'] return userTier === 'enterprise' ? premiumMemory : standardMemory }, }) ``` 방문하다[Request Context](https://mastra.zisheng.pro/ko/docs/server/request-context) for more information. ## 관련된 - [`Memory`참조](https://mastra.zisheng.pro/ko/reference/memory/memory-class) - [트레이싱](https://mastra.zisheng.pro/ko/docs/observability/tracing/overview) - [요청 컨텍스트](https://mastra.zisheng.pro/ko/docs/server/request-context) - [마스트라 코드](https://code.mastra.ai/): 마스트라의 Memory 시스템을 이용한 코딩 Agent