Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

MongoDB Atlas 로 LangGraph.js 에이전트에 장기 메모리 추가하기

MongoDB LangGraph.js와 통합하여 MongoDB LangGraph 체크포인트에서 얻는 단기 메모리 외에도 에이전트에 장기 메모리를 추가할 수 있습니다.

이 페이지는 다음 튜토리얼의 개념을 기반으로 합니다.

이 페이지에서 다음 방법을 학습 .

  • LangGraph에서 장기 기억과 대조되는 단기를 이해합니다.

  • LangGraph.js에 대한 MongoDB 지원 장기 메모리 저장 구성합니다.

  • 스레드와 세션 전반에서 사용자별 데이터를 유지하고 조회 .

  • 장기 기억을 MongoDB Vector Search와 결합하고,Voyage AI 임베딩과 AutoEmbedding을 결합하여 시맨틱 호출을 수행합니다.

참고

이 페이지의 예제에서는 TypeScript 스타일 구문을 사용합니다. 유형 주석을 제거하여 일반 JavaScript 에 맞게 조정할 수 있습니다.

LangGraph는 두 가지 보완적인 메모리 메커니즘을 제공합니다.

체크포인터 를 사용하여 요청 전반에 걸쳐 단일 스레드(대화)의 상태 유지합니다. 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 임베딩을 지원하는 저장된 데이터에 대해 시맨틱 검색 및 메타데이터 필터링을 수행합니다.

시작하기 전에 다음 항목이 준비되어 있는지 확인하세요.

다음 사항을 숙지하고 완료하는 것이 좋습니다.

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 스토어가 모두 포함되어 있습니다.

LangGraph Stores는 BaseStore getputdelete search 계층적 네임스페이스 아래의 JSON 문서에 대해,,, 등의 연산을 사용하여 인터페이스를 구현 .

기존 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 를 내보내는 모듈을 만듭니다.

// 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 또는 시스템 프롬프트에 ).

  • 에이전트 학습한 내용을 기반으로 각 상호 작용 후 장기 기억을 업데이트합니다.

장기 기억을 의미별로 검색할 수 있도록 하려면 다음을 수행할 수 있습니다.

  1. 각 메모리를 다음을 포함하는 문서 로 저장합니다.

    • 텍스트 요약 또는 설명입니다.

    • 구조화된 메타데이터 ( 예시: userId, type, tags).

    • 시맨틱 검색 위한 임베딩 벡터입니다.

  2. 메모리 컬렉션 의 embedding 필드 에 MongoDB Vector Search 인덱스 구성합니다.

  3. Atlas Embedding and Reranking API 통해Voyage AI 임베딩 또는Voyage AutoEmbeddings를 사용하여 삽입하기 전에 각 메모리 문서 에 대한 임베딩을 생성합니다.

  4. MongoDBStore에 내장 search 메서드를 사용하고, 메모리 컬렉션 에서 $vectorSearch 를 호출하며, 선택적으로 userIdtype와 같은 메타데이터 필터와 결합합니다.

다음 코드는 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 통합 모두에서 MongoDBSaver 의 지원을 받습니다.

장기 기억(저장소)

시간이 지나도 유지되어야 하는 스레드 간 정보에 사용합니다.

사용자 프로필, 정책 및 제약 조건, 수명이 긴 팩트, 의미론적 회상 등에 적합합니다. LangGraph.js에서 BaseStore 의 MongoDB 스토어 구현 으로 지원됩니다.

많은 실제 애플리케이션에서 다음을 수행할 수 있습니다.

  • 단기 기억을 사용하여 현재 대화의 일관성을 유지하세요.

  • 장기 기억을 사용하여 사용자와 과거 대화의 중요한 사실을 기억합니다.

  • 자동 임베딩과 함께 MongoDB Vector Search 및 Voyage AI 임베딩을 사용하여 응답을 생성할 때 의미적으로 메모리를 검색 .

MongoDB는 다음과 같은 개발자 리소스도 제공합니다.

돌아가기

AI 에이전트 빌드