|
| 1 | +"""LangChain integration using MemForge as conversation memory backend. |
| 2 | +
|
| 3 | +Demonstrates: |
| 4 | + - Wrapping ConversationMemory as a LangChain BaseChatMemory subclass |
| 5 | + - Injecting MemForge context into the LangChain chain via load_memory_variables |
| 6 | + - Storing LangChain exchanges back to MemForge via save_context |
| 7 | + - Drop-in replacement for ConversationBufferMemory |
| 8 | +
|
| 9 | +Run: |
| 10 | + pip install memforge langchain langchain-openai |
| 11 | + OPENAI_API_KEY=... python examples/langchain_memory.py |
| 12 | +""" |
| 13 | + |
| 14 | +import asyncio |
| 15 | +import os |
| 16 | +import sys |
| 17 | +from typing import Any |
| 18 | + |
| 19 | +AGENT_ID = "langchain-demo" |
| 20 | + |
| 21 | + |
| 22 | +def build_memforge_memory(agent_id: str) -> "MemForgeMemory": |
| 23 | + """Create a LangChain-compatible memory backed by MemForge.""" |
| 24 | + try: |
| 25 | + from langchain.memory.chat_memory import BaseChatMemory |
| 26 | + from langchain.schema import BaseMessage, HumanMessage, AIMessage |
| 27 | + except ImportError: |
| 28 | + print("Install langchain: pip install langchain", file=sys.stderr) |
| 29 | + sys.exit(1) |
| 30 | + |
| 31 | + from memforge import ConversationMemory |
| 32 | + |
| 33 | + class MemForgeMemory(BaseChatMemory): |
| 34 | + """LangChain memory adapter backed by MemForge persistent storage. |
| 35 | +
|
| 36 | + Implements the minimal BaseChatMemory interface so it can be passed |
| 37 | + directly to any LangChain chain that accepts a ``memory`` parameter. |
| 38 | + """ |
| 39 | + |
| 40 | + memory_key: str = "history" |
| 41 | + agent_id: str = "langchain-agent" |
| 42 | + _memforge: Any = None # ConversationMemory, set via model_post_init |
| 43 | + |
| 44 | + class Config: |
| 45 | + arbitrary_types_allowed = True |
| 46 | + |
| 47 | + def __init__(self, agent_id: str = "langchain-agent", **kwargs: Any) -> None: |
| 48 | + super().__init__(**kwargs) |
| 49 | + object.__setattr__(self, "agent_id", agent_id) |
| 50 | + object.__setattr__(self, "_memforge", ConversationMemory(agent_id=agent_id)) |
| 51 | + |
| 52 | + @property |
| 53 | + def memory_variables(self) -> list[str]: |
| 54 | + return [self.memory_key] |
| 55 | + |
| 56 | + def load_memory_variables(self, inputs: dict[str, Any]) -> dict[str, str]: |
| 57 | + """Retrieve relevant MemForge context synchronously for LangChain.""" |
| 58 | + human_input = inputs.get("input", inputs.get("human_input", "")) |
| 59 | + context = asyncio.get_event_loop().run_until_complete( |
| 60 | + self._memforge.get_context(human_input, max_tokens=1500) |
| 61 | + ) |
| 62 | + return {self.memory_key: context} |
| 63 | + |
| 64 | + def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None: |
| 65 | + """Persist the latest exchange to MemForge.""" |
| 66 | + human = inputs.get("input", inputs.get("human_input", "")) |
| 67 | + ai = outputs.get("output", outputs.get("response", "")) |
| 68 | + loop = asyncio.get_event_loop() |
| 69 | + if human: |
| 70 | + loop.run_until_complete(self._memforge.add_turn("user", human)) |
| 71 | + if ai: |
| 72 | + loop.run_until_complete(self._memforge.add_turn("assistant", ai)) |
| 73 | + |
| 74 | + def clear(self) -> None: |
| 75 | + """No-op: MemForge persists across sessions by design.""" |
| 76 | + |
| 77 | + return MemForgeMemory(agent_id=agent_id) # type: ignore[return-value] |
| 78 | + |
| 79 | + |
| 80 | +async def main() -> None: |
| 81 | + try: |
| 82 | + from langchain_openai import ChatOpenAI |
| 83 | + from langchain.chains import ConversationChain |
| 84 | + from langchain.prompts import PromptTemplate |
| 85 | + except ImportError: |
| 86 | + print("Install: pip install langchain langchain-openai", file=sys.stderr) |
| 87 | + sys.exit(1) |
| 88 | + |
| 89 | + if not os.environ.get("OPENAI_API_KEY"): |
| 90 | + print("Set OPENAI_API_KEY environment variable", file=sys.stderr) |
| 91 | + sys.exit(1) |
| 92 | + |
| 93 | + memory = build_memforge_memory(AGENT_ID) |
| 94 | + |
| 95 | + chain = ConversationChain( |
| 96 | + llm=ChatOpenAI(model="gpt-4o-mini"), |
| 97 | + memory=memory, |
| 98 | + prompt=PromptTemplate( |
| 99 | + input_variables=["history", "input"], |
| 100 | + template=( |
| 101 | + "You are a helpful assistant. Past context:\n{history}\n\n" |
| 102 | + "Human: {input}\nAssistant:" |
| 103 | + ), |
| 104 | + ), |
| 105 | + verbose=False, |
| 106 | + ) |
| 107 | + |
| 108 | + exchanges = [ |
| 109 | + "My name is Alex and I prefer concise answers.", |
| 110 | + "What's a good way to structure a Python project?", |
| 111 | + "Do you remember my preference from earlier?", |
| 112 | + ] |
| 113 | + |
| 114 | + for user_msg in exchanges: |
| 115 | + print(f"Human: {user_msg}") |
| 116 | + response = chain.predict(input=user_msg) |
| 117 | + print(f"Assistant: {response}\n") |
| 118 | + |
| 119 | + print("[Memory] Consolidating session...") |
| 120 | + await memory._memforge.end_session() |
| 121 | + await memory._memforge.close() |
| 122 | + print("[Memory] Done.") |
| 123 | + |
| 124 | + |
| 125 | +if __name__ == "__main__": |
| 126 | + asyncio.run(main()) |
0 commit comments