langchain-memoryrouter 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.3
2
+ Name: langchain-memoryrouter
3
+ Version: 0.1.0
4
+ Summary: MemoryRouter integration for LangChain and LangGraph
5
+ Author: MemoryRouter
6
+ License: MIT
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Dist: httpx>=0.25
18
+ Requires-Dist: langchain-core>=0.3.0
19
+ Requires-Dist: langgraph>=0.2.0
20
+ Requires-Dist: pytest>=8 ; extra == 'test'
21
+ Requires-Dist: pytest-asyncio>=0.23 ; extra == 'test'
22
+ Requires-Dist: respx>=0.21 ; extra == 'test'
23
+ Requires-Dist: ruff>=0.8 ; extra == 'test'
24
+ Requires-Dist: mypy>=1.10 ; extra == 'test'
25
+ Requires-Python: >=3.9
26
+ Project-URL: Documentation, https://memoryrouter.ai/docs
27
+ Project-URL: Homepage, https://memoryrouter.ai
28
+ Project-URL: Repository, https://github.com/johnrood/MemoryRouter
29
+ Provides-Extra: test
30
+ Description-Content-Type: text/markdown
31
+
32
+ # langchain-memoryrouter
33
+
34
+ MemoryRouter memory for LangChain and LangGraph.
35
+
36
+ MemoryRouter gives every user in your AI product a private memory vault. This package lets LangChain developers use that memory layer through tools, graph nodes, or a LangChain `BaseStore`.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install langchain-memoryrouter
42
+ ```
43
+
44
+ Get a Memory Key at [memoryrouter.ai](https://memoryrouter.ai). In multi-user products, map each app user to their own Memory Key.
45
+
46
+ ## Storage hygiene
47
+
48
+ Every write path sanitizes messages before ingest. MemoryRouter stores conversation text only:
49
+
50
+ - Keeps `HumanMessage` text as `user`
51
+ - Keeps `AIMessage` text as `assistant`
52
+ - Drops `ToolMessage` entirely
53
+ - Drops AI tool calls and function-call args
54
+ - Drops AI messages that are only tool calls with no text
55
+
56
+ This is enforced in tools, nodes, and store writes. It is not a config option.
57
+
58
+ ## Pattern 1: tools
59
+
60
+ Works with LangChain `bind_tools()` and LangGraph `create_react_agent()`.
61
+
62
+ ```python
63
+ from langchain_memoryrouter import create_memory_tools
64
+
65
+ tools = create_memory_tools(memory_key="mk_user_123")
66
+ model_with_tools = model.bind_tools(list(tools))
67
+ ```
68
+
69
+ The package exposes two primitives only:
70
+
71
+ - `memoryrouter_retain` stores sanitized conversation text with `/v1/memory/ingest`
72
+ - `memoryrouter_recall` searches memory with `/v1/memory/search`
73
+
74
+ No `reflect` tool. MemoryRouter is retain and recall.
75
+
76
+ ## Pattern 2: LangGraph nodes
77
+
78
+ Use nodes when you want memory to run automatically in the graph.
79
+
80
+ ```python
81
+ from langchain_memoryrouter import create_recall_node, create_retain_node
82
+
83
+ recall_node = create_recall_node(memory_key_config_key="memory_key")
84
+ retain_node = create_retain_node(memory_key_config_key="memory_key")
85
+
86
+ result = graph.invoke(
87
+ {"messages": messages},
88
+ config={"configurable": {"memory_key": "mk_user_123", "thread_id": "chat_abc"}},
89
+ )
90
+ ```
91
+
92
+ `create_recall_node` calls `/v1/memory/prepare` and returns a ready-to-inject memory context block. `create_retain_node` sanitizes and calls `/v1/memory/ingest`.
93
+
94
+ ## Pattern 3: BaseStore
95
+
96
+ Use `MemoryRouterStore` as a semantic long-term store for LangGraph.
97
+
98
+ ```python
99
+ from langchain_memoryrouter import MemoryRouterStore
100
+
101
+ store = MemoryRouterStore(memory_key="mk_user_123")
102
+ graph = builder.compile(store=store)
103
+ ```
104
+
105
+ MemoryRouter is semantic memory, not a literal KV database. `mset` retains text into the user's vault. `mget` searches by key and returns the best matching memory content.
106
+
107
+ ## API targeted
108
+
109
+ Base URL: `https://api.memoryrouter.ai`
110
+
111
+ Auth: `Authorization: Bearer mk_xxx`
112
+
113
+ Retain:
114
+
115
+ ```http
116
+ POST /v1/memory/ingest
117
+ {
118
+ "messages": [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}],
119
+ "session_id": "optional",
120
+ "model": "optional",
121
+ "embeddings": "optional"
122
+ }
123
+ ```
124
+
125
+ Recall:
126
+
127
+ ```http
128
+ POST /v1/memory/search
129
+ {"query": "what does the user prefer", "limit": 10}
130
+ ```
131
+
132
+ Graph recall context:
133
+
134
+ ```http
135
+ POST /v1/memory/prepare
136
+ {
137
+ "messages": [{"role": "user", "content": "..."}],
138
+ "session_id": "optional",
139
+ "density": "default",
140
+ "context_limit": 10
141
+ }
142
+ ```
@@ -0,0 +1,111 @@
1
+ # langchain-memoryrouter
2
+
3
+ MemoryRouter memory for LangChain and LangGraph.
4
+
5
+ MemoryRouter gives every user in your AI product a private memory vault. This package lets LangChain developers use that memory layer through tools, graph nodes, or a LangChain `BaseStore`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install langchain-memoryrouter
11
+ ```
12
+
13
+ Get a Memory Key at [memoryrouter.ai](https://memoryrouter.ai). In multi-user products, map each app user to their own Memory Key.
14
+
15
+ ## Storage hygiene
16
+
17
+ Every write path sanitizes messages before ingest. MemoryRouter stores conversation text only:
18
+
19
+ - Keeps `HumanMessage` text as `user`
20
+ - Keeps `AIMessage` text as `assistant`
21
+ - Drops `ToolMessage` entirely
22
+ - Drops AI tool calls and function-call args
23
+ - Drops AI messages that are only tool calls with no text
24
+
25
+ This is enforced in tools, nodes, and store writes. It is not a config option.
26
+
27
+ ## Pattern 1: tools
28
+
29
+ Works with LangChain `bind_tools()` and LangGraph `create_react_agent()`.
30
+
31
+ ```python
32
+ from langchain_memoryrouter import create_memory_tools
33
+
34
+ tools = create_memory_tools(memory_key="mk_user_123")
35
+ model_with_tools = model.bind_tools(list(tools))
36
+ ```
37
+
38
+ The package exposes two primitives only:
39
+
40
+ - `memoryrouter_retain` stores sanitized conversation text with `/v1/memory/ingest`
41
+ - `memoryrouter_recall` searches memory with `/v1/memory/search`
42
+
43
+ No `reflect` tool. MemoryRouter is retain and recall.
44
+
45
+ ## Pattern 2: LangGraph nodes
46
+
47
+ Use nodes when you want memory to run automatically in the graph.
48
+
49
+ ```python
50
+ from langchain_memoryrouter import create_recall_node, create_retain_node
51
+
52
+ recall_node = create_recall_node(memory_key_config_key="memory_key")
53
+ retain_node = create_retain_node(memory_key_config_key="memory_key")
54
+
55
+ result = graph.invoke(
56
+ {"messages": messages},
57
+ config={"configurable": {"memory_key": "mk_user_123", "thread_id": "chat_abc"}},
58
+ )
59
+ ```
60
+
61
+ `create_recall_node` calls `/v1/memory/prepare` and returns a ready-to-inject memory context block. `create_retain_node` sanitizes and calls `/v1/memory/ingest`.
62
+
63
+ ## Pattern 3: BaseStore
64
+
65
+ Use `MemoryRouterStore` as a semantic long-term store for LangGraph.
66
+
67
+ ```python
68
+ from langchain_memoryrouter import MemoryRouterStore
69
+
70
+ store = MemoryRouterStore(memory_key="mk_user_123")
71
+ graph = builder.compile(store=store)
72
+ ```
73
+
74
+ MemoryRouter is semantic memory, not a literal KV database. `mset` retains text into the user's vault. `mget` searches by key and returns the best matching memory content.
75
+
76
+ ## API targeted
77
+
78
+ Base URL: `https://api.memoryrouter.ai`
79
+
80
+ Auth: `Authorization: Bearer mk_xxx`
81
+
82
+ Retain:
83
+
84
+ ```http
85
+ POST /v1/memory/ingest
86
+ {
87
+ "messages": [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}],
88
+ "session_id": "optional",
89
+ "model": "optional",
90
+ "embeddings": "optional"
91
+ }
92
+ ```
93
+
94
+ Recall:
95
+
96
+ ```http
97
+ POST /v1/memory/search
98
+ {"query": "what does the user prefer", "limit": 10}
99
+ ```
100
+
101
+ Graph recall context:
102
+
103
+ ```http
104
+ POST /v1/memory/prepare
105
+ {
106
+ "messages": [{"role": "user", "content": "..."}],
107
+ "session_id": "optional",
108
+ "density": "default",
109
+ "context_limit": 10
110
+ }
111
+ ```
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "langchain-memoryrouter"
3
+ version = "0.1.0"
4
+ description = "MemoryRouter integration for LangChain and LangGraph"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = { text = "MIT" }
8
+ authors = [{ name = "MemoryRouter" }]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Intended Audience :: Developers",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.9",
15
+ "Programming Language :: Python :: 3.10",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ ]
21
+ dependencies = [
22
+ "httpx>=0.25",
23
+ "langchain-core>=0.3.0",
24
+ "langgraph>=0.2.0",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ test = ["pytest>=8", "pytest-asyncio>=0.23", "respx>=0.21", "ruff>=0.8", "mypy>=1.10"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://memoryrouter.ai"
32
+ Documentation = "https://memoryrouter.ai/docs"
33
+ Repository = "https://github.com/johnrood/MemoryRouter"
34
+
35
+ [build-system]
36
+ requires = ["uv_build>=0.8.0,<0.9.0"]
37
+ build-backend = "uv_build"
38
+
39
+ [tool.ruff]
40
+ line-length = 100
41
+
42
+ [tool.mypy]
43
+ python_version = "3.10"
44
+ warn_unused_ignores = true
45
+ ignore_missing_imports = true
@@ -0,0 +1,15 @@
1
+ """MemoryRouter integrations for LangChain and LangGraph."""
2
+
3
+ from langchain_memoryrouter.client import AsyncMemoryRouterClient, MemoryRouterClient
4
+ from langchain_memoryrouter.nodes import create_recall_node, create_retain_node
5
+ from langchain_memoryrouter.store import MemoryRouterStore
6
+ from langchain_memoryrouter.tools import create_memory_tools
7
+
8
+ __all__ = [
9
+ "AsyncMemoryRouterClient",
10
+ "MemoryRouterClient",
11
+ "MemoryRouterStore",
12
+ "create_memory_tools",
13
+ "create_recall_node",
14
+ "create_retain_node",
15
+ ]
@@ -0,0 +1,61 @@
1
+ """Hard storage hygiene for MemoryRouter retain paths."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Iterable, List, Optional
6
+
7
+ try:
8
+ from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
9
+ except Exception: # pragma: no cover
10
+ AIMessage = HumanMessage = BaseMessage = object # type: ignore
11
+
12
+
13
+ def _text_content(content: Any) -> str:
14
+ if isinstance(content, str):
15
+ return content.strip()
16
+ if isinstance(content, list):
17
+ parts: List[str] = []
18
+ for item in content:
19
+ if isinstance(item, str):
20
+ parts.append(item)
21
+ elif isinstance(item, dict) and item.get("type") == "text":
22
+ text = item.get("text")
23
+ if isinstance(text, str):
24
+ parts.append(text)
25
+ return "\n".join(part.strip() for part in parts if part and part.strip()).strip()
26
+ return ""
27
+
28
+
29
+ def sanitize_messages(messages: Iterable[Any]) -> List[Dict[str, str]]:
30
+ """Return only human/assistant text messages.
31
+
32
+ Tool messages, system messages, tool call metadata, function call args, and any
33
+ non-text content are dropped. An AI message that is only a tool call with no
34
+ text content is dropped.
35
+ """
36
+
37
+ sanitized: List[Dict[str, str]] = []
38
+ for message in messages:
39
+ role: Optional[str] = None
40
+ content: Any = None
41
+
42
+ if isinstance(message, dict):
43
+ raw_role = message.get("role") or message.get("type")
44
+ if raw_role in {"user", "human"}:
45
+ role = "user"
46
+ elif raw_role in {"assistant", "ai"}:
47
+ role = "assistant"
48
+ content = message.get("content")
49
+ elif isinstance(message, HumanMessage):
50
+ role = "user"
51
+ content = getattr(message, "content", None)
52
+ elif isinstance(message, AIMessage):
53
+ role = "assistant"
54
+ content = getattr(message, "content", None)
55
+ else:
56
+ continue
57
+
58
+ text = _text_content(content)
59
+ if role and text:
60
+ sanitized.append({"role": role, "content": text})
61
+ return sanitized
@@ -0,0 +1,154 @@
1
+ """Thin MemoryRouter HTTP clients.
2
+
3
+ Targets the real public API:
4
+ - POST /v1/memory/ingest with {messages, session_id?, model?, embeddings?}
5
+ - POST /v1/memory/search with {query, limit}
6
+ - POST /v1/memory/prepare with {messages, session_id?, density?, context_limit?, embeddings?}
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ import httpx
14
+
15
+ MessageDict = Dict[str, str]
16
+
17
+
18
+ class MemoryRouterClient:
19
+ """Synchronous client for MemoryRouter memory endpoints."""
20
+
21
+ def __init__(
22
+ self,
23
+ memory_key: Optional[str] = None,
24
+ *,
25
+ base_url: str = "https://api.memoryrouter.ai",
26
+ timeout: float = 30.0,
27
+ headers: Optional[Dict[str, str]] = None,
28
+ ) -> None:
29
+ self.memory_key = memory_key
30
+ self.base_url = base_url.rstrip("/")
31
+ self.timeout = timeout
32
+ self.headers = headers or {}
33
+
34
+ def _headers(self, memory_key: Optional[str], session_id: Optional[str] = None) -> Dict[str, str]:
35
+ key = memory_key or self.memory_key
36
+ if not key:
37
+ raise ValueError("memory_key is required")
38
+ headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
39
+ headers.update(self.headers)
40
+ if session_id:
41
+ headers["X-Session-ID"] = session_id
42
+ return headers
43
+
44
+ def ingest(
45
+ self,
46
+ messages: List[MessageDict],
47
+ *,
48
+ memory_key: Optional[str] = None,
49
+ session_id: Optional[str] = None,
50
+ model: Optional[str] = None,
51
+ embeddings: Optional[str] = None,
52
+ ) -> Dict[str, Any]:
53
+ body: Dict[str, Any] = {"messages": messages}
54
+ if session_id:
55
+ body["session_id"] = session_id
56
+ if model:
57
+ body["model"] = model
58
+ if embeddings:
59
+ body["embeddings"] = embeddings
60
+ with httpx.Client(timeout=self.timeout) as client:
61
+ resp = client.post(
62
+ f"{self.base_url}/v1/memory/ingest",
63
+ headers=self._headers(memory_key, session_id),
64
+ json=body,
65
+ )
66
+ resp.raise_for_status()
67
+ return resp.json()
68
+
69
+ def search(
70
+ self,
71
+ query: str,
72
+ *,
73
+ limit: int = 10,
74
+ memory_key: Optional[str] = None,
75
+ session_id: Optional[str] = None,
76
+ ) -> Dict[str, Any]:
77
+ with httpx.Client(timeout=self.timeout) as client:
78
+ resp = client.post(
79
+ f"{self.base_url}/v1/memory/search",
80
+ headers=self._headers(memory_key, session_id),
81
+ json={"query": query, "limit": limit},
82
+ )
83
+ resp.raise_for_status()
84
+ return resp.json()
85
+
86
+ def prepare(
87
+ self,
88
+ messages: List[MessageDict],
89
+ *,
90
+ memory_key: Optional[str] = None,
91
+ session_id: Optional[str] = None,
92
+ density: Optional[str] = None,
93
+ context_limit: Optional[int] = None,
94
+ embeddings: Optional[str] = None,
95
+ ) -> Dict[str, Any]:
96
+ body: Dict[str, Any] = {"messages": messages}
97
+ if session_id:
98
+ body["session_id"] = session_id
99
+ if density:
100
+ body["density"] = density
101
+ if context_limit is not None:
102
+ body["context_limit"] = context_limit
103
+ if embeddings:
104
+ body["embeddings"] = embeddings
105
+ with httpx.Client(timeout=self.timeout) as client:
106
+ resp = client.post(
107
+ f"{self.base_url}/v1/memory/prepare",
108
+ headers=self._headers(memory_key, session_id),
109
+ json=body,
110
+ )
111
+ resp.raise_for_status()
112
+ return resp.json()
113
+
114
+
115
+ class AsyncMemoryRouterClient(MemoryRouterClient):
116
+ """Async client for MemoryRouter memory endpoints."""
117
+
118
+ async def aingest(self, messages: List[MessageDict], **kwargs: Any) -> Dict[str, Any]:
119
+ body: Dict[str, Any] = {"messages": messages}
120
+ for key in ("session_id", "model", "embeddings"):
121
+ if kwargs.get(key):
122
+ body[key] = kwargs[key]
123
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
124
+ resp = await client.post(
125
+ f"{self.base_url}/v1/memory/ingest",
126
+ headers=self._headers(kwargs.get("memory_key"), kwargs.get("session_id")),
127
+ json=body,
128
+ )
129
+ resp.raise_for_status()
130
+ return resp.json()
131
+
132
+ async def asearch(self, query: str, *, limit: int = 10, **kwargs: Any) -> Dict[str, Any]:
133
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
134
+ resp = await client.post(
135
+ f"{self.base_url}/v1/memory/search",
136
+ headers=self._headers(kwargs.get("memory_key"), kwargs.get("session_id")),
137
+ json={"query": query, "limit": limit},
138
+ )
139
+ resp.raise_for_status()
140
+ return resp.json()
141
+
142
+ async def aprepare(self, messages: List[MessageDict], **kwargs: Any) -> Dict[str, Any]:
143
+ body: Dict[str, Any] = {"messages": messages}
144
+ for key in ("session_id", "density", "context_limit", "embeddings"):
145
+ if kwargs.get(key) is not None:
146
+ body[key] = kwargs[key]
147
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
148
+ resp = await client.post(
149
+ f"{self.base_url}/v1/memory/prepare",
150
+ headers=self._headers(kwargs.get("memory_key"), kwargs.get("session_id")),
151
+ json=body,
152
+ )
153
+ resp.raise_for_status()
154
+ return resp.json()
@@ -0,0 +1,77 @@
1
+ """LangGraph node factories for automatic recall and retain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Dict, Optional
6
+
7
+ from langchain_core.runnables import RunnableConfig
8
+
9
+ from langchain_memoryrouter._sanitize import sanitize_messages
10
+ from langchain_memoryrouter.client import MemoryRouterClient
11
+
12
+
13
+ def _config_value(config: Optional[RunnableConfig], key: str) -> Optional[str]:
14
+ if not config:
15
+ return None
16
+ configurable = config.get("configurable", {}) if isinstance(config, dict) else {}
17
+ value = configurable.get(key) or config.get(key)
18
+ return str(value) if value else None
19
+
20
+
21
+ def create_recall_node(
22
+ *,
23
+ client: Optional[MemoryRouterClient] = None,
24
+ base_url: str = "https://api.memoryrouter.ai",
25
+ memory_key_config_key: str = "memory_key",
26
+ fallback_user_config_key: str = "user_id",
27
+ messages_key: str = "messages",
28
+ output_key: str = "memory_context",
29
+ density: str = "default",
30
+ context_limit: Optional[int] = None,
31
+ ) -> Callable[[Dict[str, Any], Optional[RunnableConfig]], Dict[str, Any]]:
32
+ """Create a LangGraph node that recalls MemoryRouter context for state messages."""
33
+
34
+ mr = client or MemoryRouterClient(base_url=base_url)
35
+
36
+ def node(state: Dict[str, Any], config: Optional[RunnableConfig] = None) -> Dict[str, Any]:
37
+ memory_key = _config_value(config, memory_key_config_key) or _config_value(
38
+ config, fallback_user_config_key
39
+ )
40
+ clean = sanitize_messages(state.get(messages_key, []))
41
+ if not memory_key or not clean:
42
+ return {output_key: None}
43
+ result = mr.prepare(
44
+ clean,
45
+ memory_key=memory_key,
46
+ session_id=_config_value(config, "thread_id"),
47
+ density=density,
48
+ context_limit=context_limit,
49
+ )
50
+ return {output_key: result.get("context")}
51
+
52
+ return node
53
+
54
+
55
+ def create_retain_node(
56
+ *,
57
+ client: Optional[MemoryRouterClient] = None,
58
+ base_url: str = "https://api.memoryrouter.ai",
59
+ memory_key_config_key: str = "memory_key",
60
+ fallback_user_config_key: str = "user_id",
61
+ messages_key: str = "messages",
62
+ model: Optional[str] = None,
63
+ ) -> Callable[[Dict[str, Any], Optional[RunnableConfig]], Dict[str, Any]]:
64
+ """Create a LangGraph node that retains sanitized conversation text."""
65
+
66
+ mr = client or MemoryRouterClient(base_url=base_url)
67
+
68
+ def node(state: Dict[str, Any], config: Optional[RunnableConfig] = None) -> Dict[str, Any]:
69
+ memory_key = _config_value(config, memory_key_config_key) or _config_value(
70
+ config, fallback_user_config_key
71
+ )
72
+ clean = sanitize_messages(state.get(messages_key, []))
73
+ if memory_key and clean:
74
+ mr.ingest(clean, memory_key=memory_key, session_id=_config_value(config, "thread_id"), model=model)
75
+ return {}
76
+
77
+ return node
@@ -0,0 +1,88 @@
1
+ """LangChain BaseStore backed by MemoryRouter.
2
+
3
+ MemoryRouter is semantic memory, not a literal KV database. `mset` retains text
4
+ values into the vault. `mget` searches by key and returns best matching content.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any, Iterator, Optional, Sequence, Tuple
11
+
12
+ from langchain_core.stores import BaseStore
13
+
14
+ from langchain_memoryrouter._sanitize import sanitize_messages
15
+ from langchain_memoryrouter.client import AsyncMemoryRouterClient, MemoryRouterClient
16
+
17
+
18
+ class MemoryRouterStore(BaseStore[str, Any]):
19
+ """BaseStore implementation for LangGraph compile(store=...)."""
20
+
21
+ def __init__(
22
+ self,
23
+ memory_key: str,
24
+ *,
25
+ base_url: str = "https://api.memoryrouter.ai",
26
+ session_id: Optional[str] = None,
27
+ model: str = "langchain-memoryrouter",
28
+ ) -> None:
29
+ self.memory_key = memory_key
30
+ self.session_id = session_id
31
+ self.model = model
32
+ self.client = MemoryRouterClient(memory_key=memory_key, base_url=base_url)
33
+ self.async_client = AsyncMemoryRouterClient(memory_key=memory_key, base_url=base_url)
34
+
35
+ def _value_to_messages(self, key: str, value: Any) -> list[dict[str, str]]:
36
+ if isinstance(value, (list, tuple)):
37
+ clean = sanitize_messages(value)
38
+ if clean:
39
+ return clean
40
+ if isinstance(value, str):
41
+ text = value.strip()
42
+ else:
43
+ text = json.dumps(value, ensure_ascii=False, default=str)
44
+ if not text:
45
+ return []
46
+ return [{"role": "user", "content": f"{key}: {text}"}]
47
+
48
+ def mget(self, keys: Sequence[str]) -> list[Any | None]:
49
+ values: list[Any | None] = []
50
+ for key in keys:
51
+ result = self.client.search(key, limit=1, session_id=self.session_id)
52
+ memories = result.get("memories", [])
53
+ values.append(memories[0].get("content") if memories else None)
54
+ return values
55
+
56
+ def mset(self, key_value_pairs: Sequence[Tuple[str, Any]]) -> None:
57
+ messages: list[dict[str, str]] = []
58
+ for key, value in key_value_pairs:
59
+ messages.extend(self._value_to_messages(key, value))
60
+ if messages:
61
+ self.client.ingest(messages, session_id=self.session_id, model=self.model)
62
+
63
+ def mdelete(self, keys: Sequence[str]) -> None:
64
+ # The public MemoryRouter API exposes full vault delete but not per-memory-key
65
+ # delete by arbitrary LangChain store key. Treat as a no-op for compatibility.
66
+ return None
67
+
68
+ def yield_keys(self, *, prefix: str | None = None) -> Iterator[str]:
69
+ # MemoryRouter search is semantic, not key-indexed. There is no public key list.
70
+ return iter(())
71
+
72
+ def search(self, query: str, *, limit: int = 10) -> list[dict[str, Any]]:
73
+ return self.client.search(query, limit=limit, session_id=self.session_id).get("memories", [])
74
+
75
+ async def amget(self, keys: Sequence[str]) -> list[Any | None]:
76
+ values: list[Any | None] = []
77
+ for key in keys:
78
+ result = await self.async_client.asearch(key, limit=1, session_id=self.session_id)
79
+ memories = result.get("memories", [])
80
+ values.append(memories[0].get("content") if memories else None)
81
+ return values
82
+
83
+ async def amset(self, key_value_pairs: Sequence[Tuple[str, Any]]) -> None:
84
+ messages: list[dict[str, str]] = []
85
+ for key, value in key_value_pairs:
86
+ messages.extend(self._value_to_messages(key, value))
87
+ if messages:
88
+ await self.async_client.aingest(messages, session_id=self.session_id, model=self.model)
@@ -0,0 +1,44 @@
1
+ """LangChain tool factories for MemoryRouter retain and recall."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional, Sequence, Tuple
6
+
7
+ from langchain_core.messages import BaseMessage
8
+ from langchain_core.tools import StructuredTool
9
+
10
+ from langchain_memoryrouter._sanitize import sanitize_messages
11
+ from langchain_memoryrouter.client import MemoryRouterClient
12
+
13
+
14
+ def create_memory_tools(
15
+ memory_key: str,
16
+ *,
17
+ client: Optional[MemoryRouterClient] = None,
18
+ base_url: str = "https://api.memoryrouter.ai",
19
+ default_limit: int = 10,
20
+ ) -> Tuple[StructuredTool, StructuredTool]:
21
+ """Create standard LangChain tools: memoryrouter_retain and memoryrouter_recall."""
22
+
23
+ mr = client or MemoryRouterClient(memory_key=memory_key, base_url=base_url)
24
+
25
+ def memoryrouter_retain(messages: Sequence[BaseMessage], session_id: Optional[str] = None) -> str:
26
+ """Store human and assistant conversation text in MemoryRouter."""
27
+ clean = sanitize_messages(messages)
28
+ if not clean:
29
+ return "No conversation text to retain."
30
+ mr.ingest(clean, session_id=session_id)
31
+ return f"Retained {len(clean)} conversation message(s)."
32
+
33
+ def memoryrouter_recall(query: str, limit: int = default_limit, session_id: Optional[str] = None) -> str:
34
+ """Search MemoryRouter for relevant prior conversation memory."""
35
+ result = mr.search(query, limit=limit, session_id=session_id)
36
+ memories = result.get("memories", [])
37
+ if not memories:
38
+ return "No relevant memories found."
39
+ return "\n".join(m.get("content", "") for m in memories if m.get("content"))
40
+
41
+ return (
42
+ StructuredTool.from_function(memoryrouter_retain, name="memoryrouter_retain"),
43
+ StructuredTool.from_function(memoryrouter_recall, name="memoryrouter_recall"),
44
+ )