Skip to main content

개요

LangChain 에이전트는 LangGraph 영속성을 사용하여 장기 메모리를 활성화합니다. 이는 고급 주제이며 사용하려면 LangGraph에 대한 지식이 필요합니다.

메모리 저장

LangGraph는 장기 메모리를 store에 JSON 문서로 저장합니다. 각 메모리는 사용자 정의 namespace(폴더와 유사)와 고유한 key(파일 이름과 유사) 아래에 구성됩니다. 네임스페이스에는 정보를 더 쉽게 구성할 수 있도록 사용자 또는 조직 ID나 기타 레이블이 포함되는 경우가 많습니다. 이러한 구조는 메모리의 계층적 구성을 가능하게 합니다. 네임스페이스 간 검색은 콘텐츠 필터를 통해 지원됩니다.
from langgraph.store.memory import InMemoryStore


def embed(texts: list[str]) -> list[list[float]]:
    # 실제 임베딩 함수 또는 LangChain 임베딩 객체로 교체하세요
    return [[1.0, 2.0] * len(texts)]


# InMemoryStore는 데이터를 인메모리 딕셔너리에 저장합니다. 프로덕션에서는 DB 기반 store를 사용하세요.
store = InMemoryStore(index={"embed": embed, "dims": 2}) 
user_id = "my-user"
application_context = "chitchat"
namespace = (user_id, application_context) 
store.put( 
    namespace,
    "a-memory",
    {
        "rules": [
            "User likes short, direct language",
            "User only speaks English & python",
        ],
        "my-key": "my-value",
    },
)
# ID로 "메모리"를 가져옵니다
item = store.get(namespace, "a-memory") 
# 이 네임스페이스 내에서 "메모리"를 검색하고, 콘텐츠 동등성으로 필터링하며, 벡터 유사도로 정렬합니다
items = store.search( 
    namespace, filter={"my-key": "my-value"}, query="language preferences"
)
For more information about the memory store, see the Persistence guide.

Read long-term memory in tools

A tool the agent can use to look up user information
from dataclasses import dataclass

from langchain_core.runnables import RunnableConfig
from langchain.agents import create_agent
from langchain.tools import tool, ToolRuntime
from langgraph.store.memory import InMemoryStore


@dataclass
class Context:
    user_id: str

# InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production.
store = InMemoryStore() 

# Write sample data to the store using the put method
store.put( 
    ("users",),  # Namespace to group related data together (users namespace for user data)
    "user_123",  # Key within the namespace (user ID as key)
    {
        "name": "John Smith",
        "language": "English",
    }  # Data to store for the given user
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # Access the store - same as that provided to `create_agent`
    store = runtime.store 
    user_id = runtime.context.user_id
    # Retrieve data from store - returns StoreValue object with value and metadata
    user_info = store.get(("users",), user_id) 
    return str(user_info.value) if user_info else "Unknown user"

agent = create_agent(
    model="anthropic:claude-sonnet-4-5",
    tools=[get_user_info],
    # Pass store to agent - enables agent to access store when running tools
    store=store, 
    context_schema=Context
)

# Run the agent
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123") 
)

Write long-term memory from tools

Example of a tool that updates user information
from dataclasses import dataclass
from typing_extensions import TypedDict

from langchain.agents import create_agent
from langchain.tools import tool, ToolRuntime
from langgraph.store.memory import InMemoryStore


# InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production.
store = InMemoryStore() 

@dataclass
class Context:
    user_id: str

# TypedDict defines the structure of user information for the LLM
class UserInfo(TypedDict):
    name: str

# Tool that allows agent to update user information (useful for chat applications)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # Access the store - same as that provided to `create_agent`
    store = runtime.store 
    user_id = runtime.context.user_id 
    # Store data in the store (namespace, key, data)
    store.put(("users",), user_id, user_info) 
    return "Successfully saved user info."

agent = create_agent(
    model="anthropic:claude-sonnet-4-5",
    tools=[save_user_info],
    store=store, 
    context_schema=Context
)

# Run the agent
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # user_id passed in context to identify whose information is being updated
    context=Context(user_id="user_123") 
)

# You can access the store directly to get the value
store.get(("users",), "user_123").value

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I