langchain / / 2025. 11. 8. 21:20

[LangChain v1.0] Long-term memory

출처: https://docs.langchain.com/oss/python/langchain/long-term-memory

개요

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

메모리 저장

LangGraph는 장기 메모리를 store에 JSON 문서로 저장합니다.

각 메모리는 사용자 정의 namespace(폴더와 유사)와 고유한 key(파일 이름과 유사)를 사용합니다. Namespace는 종종 사용자 또는 조직 ID 또는 정보를 더 쉽게 구성할 수 있도록 하는 기타 레이블을 포함합니다.

코드 예제 - 메모리 저장

from langgraph.store.memory import InMemoryStore

def embed(texts: list[str]) -> list[list[float]]:
    return [[1.0, 2.0] * len(texts)]

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",
    },
)
item = store.get(namespace, "a-memory")
items = store.search(
    namespace, filter={"my-key": "my-value"}, query="language preferences"
)

도구에서 장기 메모리 읽기

도구는 ToolRuntime을 통해 저장된 정보에 액세스할 수 있으며, 이를 통해 에이전트가 문맥적으로 사용자 데이터를 검색할 수 있습니다.

코드 예제 - 사용자 조회를 위한 도구

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

store = InMemoryStore()
store.put(
    ("users",),
    "user_123",
    {
        "name": "John Smith",
        "language": "English",
    }
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    store = runtime.store
    user_id = runtime.context.user_id
    user_info = store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent = create_agent(
    model="claude-sonnet-4-5-20250929",
    tools=[get_user_info],
    store=store,
    context_schema=Context
)

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

도구에서 장기 메모리 쓰기

에이전트가 새로운 정보 또는 업데이트된 정보를 store에 다시 유지할 수 있는 방법을 보여줍니다.

코드 예제 - 사용자 정보 업데이트를 위한 도구

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

store = InMemoryStore()

@dataclass
class Context:
    user_id: str

class UserInfo(TypedDict):
    name: str

@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    store = runtime.store
    user_id = runtime.context.user_id
    store.put(("users",), user_id, user_info)
    return "Successfully saved user info."

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

agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    context=Context(user_id="user_123")
)

store.get(("users",), "user_123").value

Langchain v1.0

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유