MongoDB LangGraph.js와 통합하여 MongoDB LangGraph 체크포인터에서 얻는 단기 메모리 외에도 에이전트에 장기 메모리를 추가할 수 있습니다.
이 페이지는 다음 튜토리얼의 개념을 기반으로 합니다.
이 페이지에서 다음 방법을 학습 .
LangGraph에서 장기 기억과 대조되는 단기를 이해합니다.
LangGraph.js에 대한 MongoDB 지원 장기 메모리 저장 구성합니다.
스레드와 세션 전반에서 사용자별 데이터를 유지하고 조회 .
장기 기억을 MongoDB Vector Search와 결합하고,Voyage AI 임베딩과 AutoEmbedding을 결합하여 시맨틱 호출을 수행합니다.
참고
이 페이지의 예제에서는 TypeScript 스타일 구문을 사용합니다. 유형 주석을 제거하여 일반 JavaScript 에 맞게 조정할 수 있습니다.
LangGraph의 MongoDB 메모리 메커니즘 개요
LangGraph는 두 가지 보완적인 메모리 메커니즘을 제공합니다.
단기 기억(체크포인트)
Uses a 체크포인터 를 사용하여 요청 전반에 걸쳐 단일 스레드(대화)의 상태 유지합니다. MongoDB 통합에서 이는 MongoDB LangGraph 체크포인터(MongoDBSaver)에 의해 처리됩니다. 이를 통해 특정 대화에 대해 시간 여행, 휴먼 인 루프(Human-in-Loop) 검토, 내결함성과 같은 기능을 사용할 수 있습니다.
장기 기억(저장)
저장 추상화를 사용하여 단일 대화 내에서만이 아닌 스레드 간에 데이터를 유지합니다. 세션 간과 에이전트 간에 모두 유지되어야 하는 데이터를 저장하는 데 적합합니다.
LangGraph.js용 MongoDB 스토어를 사용하면 다음을 수행할 수 있습니다.
MongoDB 백엔드 로 사용하여 JavaScript /TypeScript에서
BaseStore인터페이스를 구현합니다.LangGraph의 표준 스토어 API (
get,put,delete,search)를 사용합니다.JSON 문서를 계층적 네임스페이스 아래에 저장합니다( 예시:
[userId, "memories"]).자동 임베딩을 통해 MongoDB Vector Search 및 Voyage AI 임베딩을 지원하는 저장된 데이터에 대해 시맨틱 검색 및 메타데이터 필터링을 수행합니다.
전제 조건
시작하기 전에 다음 항목이 준비되어 있는지 확인하세요.
다음 MongoDB cluster 유형 중 하나입니다.
MongoDB 6.0.11 버전, 이상을 실행 Atlas cluster7.0.2. 사용자의 IP 주소 가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.
Atlas CLI 사용하여 생성된 로컬 Atlas 배포서버 입니다. 자세히 학습 로컬 Atlas 배포 만들기를 참조하세요.
검색 및 벡터 검색이 설치된 MongoDB Community 또는 Enterprise 클러스터.
npm 및 Node.js 가 설치되어 있어야 합니다.
Voyage AI API 키입니다. API 키를 만들려면 모델 API 키를 참조하세요.
OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 OpenAI 계정이 있어야 합니다. OpenAI 계정 등록에 대해 자세히 학습하려면 OpenAI API 웹사이트를 참조하세요.
시맨틱 검색 사용하려는 경우, MongoDB 벡터 검색용으로 구성된 MongoDB 데이터베이스 및 컬렉션. To learn more, see 자세히 학습 Atlas Vector Search 인덱스 만들기를 참조하세요.
다음 사항을 숙지하고 완료하는 것이 좋습니다.
MongoDB LangGraph.js와 통합합니다 (개요, 체크포인터 및 검색 도구).
LangGraph.js와 MongoDB Atlas (엔드 투 엔드 에이전트, 벡터 검색 , 단기 기억)를 사용하여 AI 에이전트를 빌드하세요.
설치 종속성
AI 에이전트 빌드 튜토리얼에 사용된 핵심 종속성과 LangGraph.js용 MongoDB 저장 모듈을 설치합니다.
npm init -y # Core LangChain / LangGraph / MongoDB dependencies npm i --legacy-peer-deps \ langchain \ @langchain/langgraph \ @langchain/mongodb \ @langchain/community \ @langchain/langgraph-checkpoint-mongodb \ dotenv \ express \ mongodb \ zod
@langchain/langgraph-checkpoint-mongodb 패키지 장기 기억을 위한 체크포인터와 MongoDB 저장 모두 포함되어 있습니다.
MongoDB 저장 구성
LangGraph Stores는 계층적 네임스페이스 아래의 JSON 문서에 대해 get, put, delete, search 등의 연산을 사용하여 BaseStore 인터페이스를 구현.
MongoDB 클라이언트 초기화
기존 LangGraph.js 에이전트 서버 의 MongoDB 클라이언트 구성을 재사용합니다.
// mongodb-client.ts import { MongoClient } from "mongodb"; import "dotenv/config"; export const client = new MongoClient(process.env.MONGODB_URI as string); export async function connectClient() { await client.connect(); await client.db("admin").command({ ping: 1 }); console.log("Pinged your deployment. You successfully connected to MongoDB!"); }
MongoDBStore 인스턴스 생성
장기 기억을 위해 구성된 MongoDBStore 를 내보내는 모듈을 만듭니다.
// long-term-store.ts import type { MongoClient } from "mongodb"; import { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; const DB_NAME = "hr_database"; const COLLECTION_NAME = "long_term_memory"; export function createMongoDBStore(client: MongoClient) { const store = new MongoDBStore({ client, dbName: DB_NAME, collectionName: COLLECTION_NAME, }); return store; }
이 저장 [userId, "memories"] 또는 [userId, "preferences"]와(과) 같은 계층적 네임스페이스로 입력되는 스레드와 세션 전반에 걸쳐 데이터를 유지합니다.
장기 기억 스키마 설계
장기 기억은 사용자 또는 도메인에 대한 안정적인 사실을 모델링할 때 가장 잘 작동합니다.
일반적인 패턴은 다음과 같습니다.
사용자 프로필 - 역할, 연공서열, 팀, 위치. 지속적인 기본 설정( 예시: 어조, 언어, 제품 계층).
제약 조건 및 정책 - 알러지, 컴플라이언스 제한, 예산 한도.
상호 작용 기록 요약 - 과거 세션에 대한 높은 수준의 요약입니다. 이월해야 하는 결정( 예시: '사용자는 자체 관리형보다 MongoDB Atlas 선호합니다')입니다.
이를 간단한 JSON 문서로 저장하거나 시맨틱 검색 위한 임베딩이 있는 문서로 저장 수 있습니다.
사용자 메모리 유지
MongoDB 스토어 API 다음 작업을 지원합니다.
put- 값을 저장 하거나 업데이트 .get- 네임스페이스 및 키로 값을 조회 .delete- 값을 제거 .search- 벡터 유사성 및/또는 메타데이터 필터를 기준으로 값을 조회 .
정확한 TypeScript 유형은 다를 수 있지만, 다음 코드는 LangGraph.js의 일반적인 사용 패턴 보여줍니다.
// memory-api.ts import type { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; type MemoryValue = { type: "profile" | "preference" | "fact"; data: Record<string, unknown>; updatedAt: string; }; export async function putUserMemory( store: MongoDBStore, userId: string, key: string, value: MemoryValue ) { await store.put( [userId, "memories"], key, value ); } export async function getUserMemories( store: MongoDBStore, userId: string, key: string ) { const result = await store.get( [userId, "memories"], key ); return result; }
에이전트 워크플로에 장기 메모리 추가
이 섹션에서는 다음을 포함하여 LangGraph.js 및 MongoDB Atlas 사용하여 AI 에이전트 빌드에 설명된 것과 유사한 에이전트 워크플로가 이미 있다고 가정합니다.
messages필드 가 있는GraphState주석입니다.Voyage AI 의 임베딩을 사용하여 MongoDB Vector Search를 호출하는 도구 노드 .
도구를 호출할지, 아니면 직접 응답할지를 결정하는 채팅 모델 노드 .
단기 기억을 위한
MongoDBSaver체크포인터입니다.
에이전트 함수에 저장 삽입
MongoDB 클라이언트 와 함께 store 를 허용하도록 callAgent 함수를 업데이트합니다.
// agent-with-long-term-memory.ts import { ChatOpenAI } from "@langchain/openai"; import { AIMessage, BaseMessage, HumanMessage, } from "@langchain/core/messages"; import { ChatPromptTemplate, MessagesPlaceholder, } from "@langchain/core/prompts"; import { StateGraph, Annotation } from "@langchain/langgraph"; import { tool } from "@langchain/core/tools"; import { ToolNode } from "@langchain/langgraph/prebuilt"; import { MongoDBSaver } from "@langchain/langgraph-checkpoint-mongodb"; import type { MongoClient } from "mongodb"; import type { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; import { putUserMemory, getUserMemories } from "./memory-api"; export async function callAgent( client: MongoClient, store: MongoDBStore, query: string, threadId: string, userId: string, ) { const dbName = "hr_database"; const db = client.db(dbName); const collection = db.collection("employees"); // 1. Retrieve long-term memories for the user const existingMemories = await getUserMemories(store, userId, "last_response"); // 2. Define graph state const GraphState = Annotation.Root({ messages: Annotation<BaseMessage[]>({ reducer: (x, y) => x.concat(y), }), userId: Annotation<string>(), memories: Annotation<unknown | null>(), }); // 3. Define tools (for example, MongoDB Vector Search retriever) const employeeLookupTool = tool(/* ...reuse from Build an AI Agent tutorial... */); const tools = [employeeLookupTool]; const toolNode = new ToolNode<typeof GraphState.State>(tools); // 4. Configure the chat model const model = new ChatOpenAI({ model: "gpt-5.4-mini", }).bindTools(tools); // 5. Define the model node async function callModel(state: typeof GraphState.State) { const prompt = ChatPromptTemplate.fromMessages([ "system", `You are a helpful HR chatbot agent. Use the provided tools and long-term memories to answer questions. Long-term memories (if any) are in the "memories" field.`, new MessagesPlaceholder("messages"), ]); const formatted = await prompt.formatMessages({ messages: state.messages, }); const result = await model.invoke(formatted); return { messages: [result] }; } // 6. Define routing logic function shouldContinue(state: typeof GraphState.State) { const messages = state.messages; const lastMessage = messages[messages.length - 1] as AIMessage; if (lastMessage.tool_calls?.length) { return "tools"; } return "__end__"; } // 7. Build the workflow const workflow = new StateGraph(GraphState) .addNode("agent", callModel) .addNode("tools", toolNode) .addEdge("__start__", "agent") .addConditionalEdges("agent", shouldContinue) .addEdge("tools", "agent"); // 8. Configure short-term memory (checkpointer) const checkpointer = new MongoDBSaver({ client, dbName }); const app = workflow.compile({ checkpointer, store, }); // 9. Invoke the graph with both short-term and long-term memory const finalState = await app.invoke( { messages: [new HumanMessage(query)], userId, memories: existingMemories, }, { recursionLimit: 15, configurable: { thread_id: threadId }, }, ); const last = finalState.messages[finalState.messages.length - 1]; const content = last.content; // 10. Optionally, update long-term memory with new facts await putUserMemory(store, userId, "last_response", { type: "fact", data: { content }, updatedAt: new Date().toISOString(), }); return content; }
이 패턴 사용하면 다음을 수행할 수 있습니다.
각 상호 작용이 시작될 때 장기 기억을 읽습니다.
해당 메모리를 상태 에 삽입합니다( 예시:
memories또는 시스템 프롬프트에 ).에이전트 학습한 내용을 기반으로 각 상호 작용 후 장기 기억을 업데이트합니다.
장기 기억을 위한 시맨틱 검색 및 자동 임베딩 사용
장기 기억을 의미별로 검색할 수 있도록 하려면 다음을 수행할 수 있습니다.
각 메모리를 다음을 포함하는 문서 로 저장합니다.
텍스트 요약 또는 설명입니다.
구조화된 메타데이터 ( 예시:
userId,type,tags).시맨틱 검색 위한 임베딩 벡터입니다.
메모리 컬렉션 의
embedding필드 에 MongoDB 벡터 검색 인덱스 구성합니다.Atlas Embedding and Reranking API 통해 Voyage AI 임베딩 또는 Voyage AutoEmbeddings를 사용하여 삽입하기 전에 각 메모리 문서에 대한 임베딩을 생성합니다.
MongoDBStore에 내장search메서드를 사용하고, 메모리 컬렉션 에서$vectorSearch를 호출하며, 선택적으로userId및type와 같은 메타데이터 필터와 결합합니다.
다음 코드는 MongoDBStore 에 내장 search 메서드를 사용하여 의미론적 유사성 및 메타데이터 필터로 메모리를 찾는 방법을 보여 줍니다.
// semantic-memory.ts import type { MongoDBStore } from "@langchain/langgraph-checkpoint-mongodb"; export async function searchUserMemories( store: MongoDBStore, userId: string, queryText: string, limit = 5, ) { const results = await store.search( [userId, "memories"], { query: queryText, filter: { type: "fact" }, limit, }, ); return results; }
search 메서드는 다음 필드가 있는 네임스페이스 접두사 및 옵션 객체 허용합니다.
query- 시맨틱 검색 위한 텍스트 문자열입니다. 저장 MongoDB Vector Search를 사용하여 쿼리 와 의미론적으로 유사한 메모리를 찾습니다.filter- 결과 범위를 좁힐 수 있는 메타데이터 필터 객체 ( 예시:{ type: "fact" }).limit- 반환할 최대 결과 수입니다(기본값:10).offset- 페이지 매김을 위해 건너뛸 결과의 수입니다(기본값:0).
참고
Voyage AutoEmbeddings를 사용하면 임베딩 생성을 Atlas Embedding and Reranking API 로 오프로드하고 MongoDB Vector Search를 저장 백엔드로 사용할 수 있습니다. LangGraph.js 장기 기억 저장소는 이러한 환경과 함께 작동하여 자동 임베딩 생성을 LangGraph 저장 및 벡터 검색과 결합하여 통합된 장기 기억 계층을 생성할 수 있도록 설계되었습니다.
단기 기억과 장기 기억을 사용해야 하는 경우
다음 지침을 사용하여 애플리케이션 의 각 부분에 적합한 메모리 메커니즘을 선택하세요.
메커니즘 | 사용 시기 | 세부 정보 |
|---|---|---|
단기 기억(체크포인터) | 대화 내에서만 중요한 스레드별 컨텍스트에 사용합니다. | 단계별 추론, 도구 호출 결과 및 중간 상태 에 적합합니다. Python 및 JavaScript 통합 모두에서 |
장기 기억(저장) | 시간이 지나도 유지되어야 하는 스레드 간 정보에 사용합니다. | 사용자 프로필, 정책 및 제약 조건, 수명이 긴 팩트, 의미론적 회상 등에 적합합니다. LangGraph.js에서 |
많은 실제 애플리케이션에서 다음을 수행할 수 있습니다.
단기 기억을 사용하여 현재 대화의 일관성을 유지하세요.
장기 기억을 사용하여 사용자와 과거 대화의 중요한 사실을 기억합니다.
자동 임베딩과 함께 MongoDB 벡터 검색 및 Voyage AI 임베딩을 사용하여 응답을 생성할 때 의미적으로 메모리를 검색 .
다음 단계
LangGraph.js 및 MongoDB Atlas 사용하여 AI 에이전트 빌드의 엔드 투 엔드 튜토리얼을 따르세요.
이 페이지를 기존 에이전트 위에 장기 기억 및 시맨틱 검색 계층화하기 위한 참고 자료로 사용하세요.
임베딩 및 자동 임베딩 워크플로에 대한 자세한 내용은 Voyage AI Docs 및 Atlas Embedding and Reranking API (Atlas Embedding and Reranking API)를 참조하세요.
MongoDB는 다음과 같은 개발자 리소스도 제공합니다.