Skip to main content

개요

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

메모리 저장

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

const embed = (texts: string[]): number[][] => {
    // 실제 임베딩 함수 또는 LangChain 임베딩 객체로 교체하세요
    return texts.map(() => [1.0, 2.0]);
};

// InMemoryStore는 데이터를 인메모리 딕셔너리에 저장합니다. 프로덕션에서는 DB 기반 store를 사용하세요.
const store = new InMemoryStore({ index: { embed, dims: 2 } }); 
const userId = "my-user";
const applicationContext = "chitchat";
const namespace = [userId, applicationContext]; 

await store.put( 
    namespace,
    "a-memory",
    {
        rules: [
            "User likes short, direct language",
            "User only speaks English & TypeScript",
        ],
        "my-key": "my-value",
    }
);

// ID로 "메모리"를 가져옵니다
const item = await store.get(namespace, "a-memory"); 

// 이 네임스페이스 내에서 "메모리"를 검색하고, 콘텐츠 동등성으로 필터링하며, 벡터 유사도로 정렬합니다
const items = await 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
import * as z from "zod";
import { createAgent, tool } from "langchain";
import { InMemoryStore, type Runtime } from "@langchain/langgraph";

// InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production.
const store = new InMemoryStore(); 
const contextSchema = z.object({
    userId: z.string(),
});

// Write sample data to the store using the put method
await 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
);

const getUserInfo = tool(
  // Look up user info.
  async (_, runtime: Runtime<z.infer<typeof contextSchema>>) => {
    // Access the store - same as that provided to `createAgent`
    const userId = runtime.context?.userId;
    if (!userId) {
      throw new Error("userId is required");
    }
    // Retrieve data from store - returns StoreValue object with value and metadata
    const userInfo = await runtime.store.get(["users"], userId);
    return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
  },
  {
    name: "getUserInfo",
    description: "Look up user info by userId from the store.",
    schema: z.object({}),
  }
);

const agent = createAgent({
    model: "openai:gpt-4o-mini",
    tools: [getUserInfo],
    contextSchema,
    // Pass store to agent - enables agent to access store when running tools
    store, 
});

// Run the agent
const result = await agent.invoke(
    { messages: [{ role: "user", content: "look up user information" }] },
    { context: { userId: "user_123" } } 
);

console.log(result.messages.at(-1)?.content);
/**
 * Outputs:
 * User Information:
 * - Name: John Smith
 * - Language: English
 */

Write long-term memory from tools

Example of a tool that updates user information
import * as z from "zod";
import { tool, createAgent, type AgentRuntime } from "langchain";
import { InMemoryStore, type Runtime } from "@langchain/langgraph";

// InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production.
const store = new InMemoryStore(); 

const contextSchema = z.object({
    userId: z.string(),
});

// Schema defines the structure of user information for the LLM
const UserInfo = z.object({
    name: z.string(),
});

// Tool that allows agent to update user information (useful for chat applications)
const saveUserInfo = tool(
  async (userInfo: z.infer<typeof UserInfo>, runtime: Runtime<z.infer<typeof contextSchema>>) => {
    const userId = runtime.context?.userId;
    if (!userId) {
      throw new Error("userId is required");
    }
    // Store data in the store (namespace, key, data)
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    schema: UserInfo,
  }
);

const agent = createAgent({
    model: "openai:gpt-4o-mini",
    tools: [saveUserInfo],
    contextSchema,
    store, 
});

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

// You can access the store directly to get the value
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }

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