> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 메시지 기록 메시지 기록은 가장 기본적이고 중요한 기억의 형태입니다. 이는 LLM에게 컨텍스트 창에서 최근 메시지 보기를 제공하여 Agent가 이전 교환을 참조하고 일관되게 응답할 수 있도록 합니다. 메시지 기록을 검색하여 UI에 과거 대화를 표시할 수도 있습니다. > **정보:** 각 메시지는 스레드(대화)와 리소스(연결된 사용자 또는 엔터티)에 속합니다. 자세한 내용은 [스레드와 리소스](#threads-and-resources)를 참조하세요. > **경고:** 클라이언트 애플리케이션에서 Memory를 사용할 때는 전체 대화 기록이 아니라 클라이언트의 **새 메시지만** 전달하세요. Mastra가 저장소에서 메시지를 로드하기 때문에 전체 기록을 보내는 것은 중복되며 클라이언트 측 타임스탬프가 저장된 타임스탬프와 충돌할 때 메시지 순서 버그가 발생할 수 있습니다. > > AI SDK 예시는 [Mastra Memory 사용하기](https://mastra.zisheng.pro/ko/guides/build-your-ui/ai-sdk-ui)를 참조하세요. ## 스레드 및 리소스 Mastra는 두 가지 식별자를 사용하여 대화를 구성합니다. - **실**: 일련의 메시지가 포함된 대화 세션입니다. - **의지**: 사용자, 조직, 프로젝트 또는 애플리케이션의 다른 도메인 엔터티와 같이 스레드를 소유하는 엔터티입니다. Studio는 스레드 및 리소스 ID를 자동으로 생성합니다. 직접 `stream()` 또는 `generate()`를 호출할 때는 이러한 식별자를 명시적으로 제공하세요. ## 시작하기 데이터베이스용 [스토리지 어댑터](https://mastra.zisheng.pro/ko/docs/storage/overview)와 함께 Mastra Memory 모듈을 설치하세요. 아래 예시에서는 데이터를 로컬 `mastra.db` 파일에 저장하는 `@mastra/libsql`을 사용합니다. **npm**: ```bash npm install @mastra/memory@latest @mastra/libsql@latest ``` **pnpm**: ```bash pnpm add @mastra/memory@latest @mastra/libsql@latest ``` **Yarn**: ```bash yarn add @mastra/memory@latest @mastra/libsql@latest ``` **Bun**: ```bash bun add @mastra/memory@latest @mastra/libsql@latest ``` 메시지 기록에는 대화를 유지하기 위한 스토리지 어댑터가 필요합니다. 아직 구성하지 않은 경우 Mastra 인스턴스에 스토리지를 구성합니다. ```typescript import { Mastra } from '@mastra/core' import { LibSQLStore } from '@mastra/libsql' export const mastra = new Mastra({ storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db', }), }) ``` Agent에서 [`Memory`](https://mastra.zisheng.pro/ko/reference/memory/memory-class) 인스턴스를 생성하세요. ```typescript import { Memory } from '@mastra/memory' import { Agent } from '@mastra/core/agent' export const agent = new Agent({ id: 'test-agent', memory: new Memory({ options: { lastMessages: 10, }, }), }) ``` Agent를 호출하면 메시지가 데이터베이스에 자동으로 저장됩니다. `threadId`, `resourceId` 및 선택적 `metadata`를 지정할 수 있습니다. **.generate()**: ```typescript await agent.generate('Hello', { memory: { thread: { id: 'thread-123', title: 'Support conversation', metadata: { category: 'billing' }, }, resource: 'user-456', }, }) ``` **.stream()**: ```typescript await agent.stream('Hello', { memory: { thread: { id: 'thread-123', title: 'Support conversation', metadata: { category: 'billing' }, }, resource: 'user-456', }, }) ``` > **정보:** `agent.generate()` 또는 `agent.stream()`을 호출하면 스레드와 메시지가 자동으로 생성되지만, [`createThread()`](https://mastra.zisheng.pro/ko/reference/memory/createThread) 및 [`saveMessages()`](https://mastra.zisheng.pro/ko/reference/memory/memory-class)를 사용하여 직접 생성할 수도 있습니다. 이 기록은 두 가지 방법으로 사용할 수 있습니다. - **자동 포함**: Mastra는 최근 메시지를 자동으로 가져와 컨텍스트 창에 포함합니다. 기본적으로 최근 메시지 10개가 포함되어 Agent가 대화를 이어갈 수 있습니다. 이 수는 `lastMessages`로 조정할 수 있지만 대부분의 경우 신경 쓰지 않아도 됩니다. - [**수동 쿼리**](#querying): 더 세밀하게 제어하려면 `recall()` 함수를 사용하여 스레드와 메시지를 직접 쿼리하세요. 컨텍스트 창에 포함할 Memory를 정확히 선택하거나 UI에 대화 기록을 렌더링할 메시지를 가져올 수 있습니다. > **팁:** Memory가 활성화되면 [Studio](https://mastra.zisheng.pro/ko/docs/studio/overview)는 메시지 기록을 사용하여 채팅 사이드바에 이전 대화를 표시합니다. ## 스레드 제목 생성 `generateTitle`을 활성화하면 Mastra가 대화 내용에서 설명적인 스레드 제목을 자동으로 생성할 수 있습니다. 스레드 목록이나 사이드바에 대화 제목을 표시하는 채팅 인터페이스를 만들 때 이 옵션을 사용하세요. ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' export const supportAgent = new Agent({ id: 'support-agent', name: 'Support agent', instructions: 'Answer customer support questions.', model: 'openai/gpt-5.6-sol', memory: new Memory({ options: { generateTitle: true, }, }), }) ``` 제목 생성은 Agent가 응답한 후 비동기적으로 실행되며 응답 시간에는 영향을 주지 않습니다. 비용이나 동작을 최적화하려면 더 작은 [`model`](https://mastra.zisheng.pro/ko/models)과 사용자 지정 `instructions`를 제공하세요. ```typescript import { Agent } from '@mastra/core/agent' import { Memory } from '@mastra/memory' export const supportAgent = new Agent({ id: 'support-agent', name: 'Support agent', instructions: 'Answer customer support questions.', model: 'openai/gpt-5.6-sol', memory: new Memory({ options: { generateTitle: { model: 'openai/gpt-5-mini', instructions: 'Generate a one-word title.', }, }, }), }) ``` ## Memory 액세스 스레드와 메시지를 쿼리, 복제 또는 삭제하는 Memory 기능에 접근하려면 Agent에서 `getMemory()`를 호출하세요. ```typescript const agent = mastra.getAgentById('test-agent') const memory = await agent.getMemory() ``` `Memory` 인스턴스를 통해 스레드 목록 조회, 메시지 회상, 대화 복제 등의 함수에 접근할 수 있습니다. ## 쿼리 중 UI에 대화 기록을 표시하거나 사용자 지정 Memory 검색 논리를 위해 스레드와 메시지를 가져오려면 이러한 메서드를 사용하세요. > **경고:** Memory 시스템은 액세스 제어를 시행하지 않습니다. 쿼리를 실행하기 전에 애플리케이션 로직에서 현재 사용자에게 액세스 권한이 있는지 확인하세요.`resourceId` being queried. ### 스레드 리소스의 스레드를 가져오려면 [`listThreads()`](https://mastra.zisheng.pro/ko/reference/memory/listThreads)를 사용하세요. ```typescript const result = await memory.listThreads({ filter: { resourceId: 'user-123' }, perPage: false, }) ``` 스레드를 통해 페이지를 매깁니다. ```typescript const result = await memory.listThreads({ filter: { resourceId: 'user-123' }, page: 0, perPage: 10, }) console.log(result.threads) // thread objects console.log(result.hasMore) // more pages available? ``` 메타데이터로 필터링하고 정렬 순서를 제어할 수도 있습니다. ```typescript const result = await memory.listThreads({ filter: { resourceId: 'user-123', metadata: { status: 'active' }, }, orderBy: { field: 'createdAt', direction: 'DESC' }, }) ``` ID로 단일 스레드를 가져오려면 다음을 사용하세요.[`getThreadById()`](https://mastra.zisheng.pro/ko/reference/memory/getThreadById): ```typescript const thread = await memory.getThreadById({ threadId: 'thread-123' }) ``` ### 메시지 스레드가 있으면 [`recall()`](https://mastra.zisheng.pro/ko/reference/memory/recall)을 사용하여 메시지를 가져오세요. 페이지네이션, 날짜 필터링 및 [의미 검색](https://mastra.zisheng.pro/ko/docs/memory/semantic-recall)을 지원합니다. 기본 회수는 스레드의 모든 메시지를 반환합니다. ```typescript const { messages } = await memory.recall({ threadId: 'thread-123', perPage: false, }) ``` 메시지 페이지 매기기: ```typescript const { messages } = await memory.recall({ threadId: 'thread-123', page: 0, perPage: 50, }) ``` 날짜 범위별로 필터링: ```typescript const { messages } = await memory.recall({ threadId: 'thread-123', filter: { dateRange: { start: new Date('2025-01-01'), end: new Date('2025-06-01'), }, }, }) ``` 얕은 메시지 메타데이터로 필터링: ```typescript const { messages } = await memory.recall({ threadId: 'thread-123', filter: { metadata: { category: 'billing', escalated: true, priority: 2, archivedAt: null, }, }, }) ``` 메타데이터 필터는 `string`, 유한한 `number`, `boolean`, `null`과 같은 얕은 스칼라 값만 일치시킵니다. 지정된 모든 메타데이터 키에는 AND 의미 체계가 적용됩니다. `null` 필터는 명시적인 `null` 값에만 일치합니다. 존재하지 않는 메타데이터 키는 일치하지 않습니다. 메타데이터 키는 문자나 밑줄로 시작해야 하며 영숫자와 밑줄만 포함할 수 있습니다. 길이는 128자 이하여야 하며 `__proto__`, `constructor`, `prototype` 같은 예약된 프로토타입 키는 사용할 수 없습니다. 성능은 스토리지 백엔드에 따라 다릅니다. 일부 백엔드는 필터의 일부를 데이터베이스로 푸시할 수 있지만, 다른 백엔드는 스레드, 리소스, 날짜 제약 조건을 적용한 후 페이지 매김 전에 후보 메시지를 검색합니다. ID로 단일 메시지를 가져옵니다. ```typescript const { messages } = await memory.recall({ threadId: 'thread-123', include: [{ id: 'msg-123' }], }) ``` 주변 컨텍스트와 함께 ID별로 여러 메시지를 가져옵니다. ```typescript const { messages } = await memory.recall({ threadId: 'thread-123', include: [ { id: 'msg-123' }, { id: 'msg-456', withPreviousMessages: 3, withNextMessages: 1, }, ], }) ``` 의미 검색을 사용하는 경우(설정 방법은 [의미 회상](https://mastra.zisheng.pro/ko/docs/memory/semantic-recall) 참조): ```typescript const { messages } = await memory.recall({ threadId: 'thread-123', vectorSearchString: 'project deadline discussion', threadConfig: { semanticRecall: true, }, }) ``` ### UI 형식 메시지 쿼리는 `MastraDBMessage[]` 형식을 반환합니다. 프런트엔드에 메시지를 표시하려면 UI 라이브러리가 요구하는 형식으로 변환해야 할 수 있습니다. 예를 들어 [`toAISdkV5Messages`](https://mastra.zisheng.pro/ko/reference/ai-sdk/to-ai-sdk-v5-messages)는 메시지를 AI SDK UI 형식으로 변환합니다. ## 스레드 복제 스레드 복제는 해당 메시지와 함께 기존 스레드의 복사본을 만듭니다. 이는 잠재적으로 파괴적인 작업 전에 대화를 분기하거나 체크포인트를 생성하거나 대화의 변형을 테스트하는 데 유용합니다. ```typescript const { thread, clonedMessages } = await memory.cloneThread({ sourceThreadId: 'thread-123', title: 'Branched conversation', }) ``` 복제되는 메시지를 필터링(개수 또는 날짜 범위 기준)하고, 사용자 정의 스레드 ID를 지정하고, 유틸리티 방법을 사용하여 복제 관계를 검사할 수 있습니다. 전체 API는 [`cloneThread()`](https://mastra.zisheng.pro/ko/reference/memory/cloneThread) 및 [복제 유틸리티](https://mastra.zisheng.pro/ko/reference/memory/clone-utilities)를 참조하세요. ## 메시지 삭제 스레드에서 메시지를 제거하려면 [`deleteMessages()`](https://mastra.zisheng.pro/ko/reference/memory/deleteMessages)를 사용하세요. 메시지 ID로 삭제하거나 스레드의 모든 메시지를 지울 수 있습니다.