memlib-ai 0.1.0__py3-none-any.whl

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.
memlib/__init__.py ADDED
File without changes
memlib/extractor.py ADDED
@@ -0,0 +1,103 @@
1
+ import json
2
+ from collections.abc import Sequence
3
+ from typing import Any
4
+
5
+ from memlib.llm import LLMClient
6
+ from memlib.types import CandidateMemory, Message
7
+ from memlib.prompts import EXTRACTION_SYSTEM_PROMPT
8
+
9
+
10
+ class MemoryExtractor:
11
+
12
+ def __init__(self, llm: LLMClient) -> None:
13
+ self.llm = llm
14
+
15
+ def extract(self, messages: Sequence[Message]) -> list[CandidateMemory]:
16
+
17
+ pair = self._latest_pair(messages)
18
+
19
+ if not pair:
20
+ return []
21
+
22
+ response = self.llm.complete(
23
+ system_prompt=EXTRACTION_SYSTEM_PROMPT,
24
+ user_prompt=self._format_input(pair),
25
+ )
26
+
27
+ return self._parse_response(response)
28
+
29
+ @staticmethod
30
+ def _latest_pair(messages: Sequence[Message]) -> list[Message]:
31
+
32
+ if len(messages) < 2:
33
+ return []
34
+
35
+ return list(messages[-2:])
36
+
37
+ @staticmethod
38
+ def _format_input(messages: Sequence[Message]) -> str:
39
+
40
+ return json.dumps(
41
+ {
42
+ "user_message": messages[0].content,
43
+ "assistant_response": messages[1].content,
44
+ },
45
+ ensure_ascii=True,
46
+ )
47
+
48
+ @staticmethod
49
+ def _parse_response(response: str) -> list[CandidateMemory]:
50
+ data = MemoryExtractor._load_json(response)
51
+
52
+ if not isinstance(data, dict):
53
+ return []
54
+
55
+ raw_memories = data.get("memories", [])
56
+
57
+ if not isinstance(raw_memories, list):
58
+ return []
59
+
60
+ candidates: list[CandidateMemory] = []
61
+
62
+ for raw_memory in raw_memories:
63
+ if not isinstance(raw_memory, dict):
64
+ continue
65
+
66
+ content = str(raw_memory.get("content", "")).strip()
67
+ memory_type = str(raw_memory.get("type", "fact")).strip() or "fact"
68
+
69
+ if not content:
70
+ continue
71
+
72
+ metadata = {
73
+ key: value
74
+ for key, value in raw_memory.items()
75
+ if key != "content" and isinstance(key, str)
76
+ }
77
+
78
+ candidates.append(
79
+ CandidateMemory(
80
+ content=content,
81
+ memory_type=memory_type,
82
+ metadata=metadata,
83
+ )
84
+ )
85
+
86
+ return candidates
87
+
88
+ @staticmethod
89
+ def _load_json(response: str) -> Any:
90
+ stripped = response.strip()
91
+
92
+ if stripped.startswith("```"):
93
+ stripped = (
94
+ stripped.removeprefix("```json")
95
+ .removeprefix("```")
96
+ .removesuffix("```")
97
+ .strip()
98
+ )
99
+
100
+ try:
101
+ return json.loads(stripped)
102
+ except json.JSONDecodeError:
103
+ return {}
@@ -0,0 +1,81 @@
1
+ from langchain_core.language_models.chat_models import BaseChatModel
2
+ from pydantic import BaseModel, Field
3
+
4
+ from memlib.prompts import GRAPH_EXTRACTOR_PROMPT
5
+ from memlib.types import GraphFact, MemoryItem
6
+
7
+
8
+ class _ExtractedRelationship(BaseModel):
9
+ """A single relationship extracted by the LLM."""
10
+
11
+ subject: str = Field(
12
+ description="Source entity of the relationship."
13
+ )
14
+
15
+ relation: str = Field(
16
+ description="Concise uppercase relationship name."
17
+ )
18
+
19
+ object: str = Field(
20
+ description="Target entity of the relationship."
21
+ )
22
+
23
+
24
+ class _GraphExtractionOutput(BaseModel):
25
+ """Structured output returned by the graph extraction LLM."""
26
+
27
+ relationships: list[_ExtractedRelationship] = Field(
28
+ default_factory=list,
29
+ description="Relationships explicitly supported by the memory.",
30
+ )
31
+
32
+
33
+ class GraphExtractor:
34
+ def __init__(self, llm: BaseChatModel) -> None:
35
+ self.llm = llm
36
+
37
+ self.structured_llm = llm.with_structured_output(
38
+ _GraphExtractionOutput
39
+ )
40
+
41
+ def extract(
42
+ self,
43
+ memory: MemoryItem,
44
+ user_id: str,
45
+ ) -> list[GraphFact]:
46
+ if not memory.content.strip():
47
+ return []
48
+
49
+ prompt = f"""
50
+ {GRAPH_EXTRACTOR_PROMPT}
51
+
52
+ CANONICAL MEMORY:
53
+ {memory.content}
54
+ """
55
+
56
+ result = self.structured_llm.invoke(prompt)
57
+
58
+ facts: list[GraphFact] = []
59
+
60
+ for relationship in result.relationships:
61
+ subject = relationship.subject.strip()
62
+ relation = relationship.relation.strip().upper()
63
+ object_ = relationship.object.strip()
64
+
65
+ if not subject or not relation or not object_:
66
+ continue
67
+
68
+ facts.append(
69
+ GraphFact(
70
+ subject=subject,
71
+ relation=relation,
72
+ object=object_,
73
+ memory_id=memory.id,
74
+ user_id=user_id,
75
+ metadata={
76
+ "source": "global_memory",
77
+ },
78
+ )
79
+ )
80
+
81
+ return facts
memlib/graph_store.py ADDED
@@ -0,0 +1,274 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any
3
+ import json
4
+ import re
5
+
6
+ from neo4j import GraphDatabase
7
+
8
+ from memlib.types import GraphFact
9
+
10
+
11
+ class GraphStore(ABC):
12
+
13
+ @abstractmethod
14
+ def add_fact(self, fact: GraphFact) -> None:
15
+ raise NotImplementedError
16
+
17
+ @abstractmethod
18
+ def delete_memory(self, memory_id: str) -> None:
19
+ raise NotImplementedError
20
+
21
+ @abstractmethod
22
+ def search(
23
+ self,
24
+ query: str,
25
+ user_id: str,
26
+ *,
27
+ limit: int = 10,
28
+ ) -> list[dict[str, Any]]:
29
+ raise NotImplementedError
30
+
31
+ @abstractmethod
32
+ def clear_user(self, user_id: str) -> None:
33
+ raise NotImplementedError
34
+
35
+ @abstractmethod
36
+ def close(self) -> None:
37
+ raise NotImplementedError
38
+
39
+
40
+ class Neo4jGraphStore(GraphStore):
41
+
42
+ def __init__(
43
+ self,
44
+ uri: str,
45
+ username: str,
46
+ password: str,
47
+ *,
48
+ database: str | None = None,
49
+ ) -> None:
50
+ self.driver = GraphDatabase.driver(
51
+ uri,
52
+ auth=(username, password),
53
+ )
54
+
55
+ self.database = database
56
+
57
+ def add_fact(self, fact: GraphFact) -> None:
58
+ cypher = """
59
+ MERGE (subject:Entity {
60
+ user_id: $user_id,
61
+ name: $subject
62
+ })
63
+
64
+ MERGE (object:Entity {
65
+ user_id: $user_id,
66
+ name: $object
67
+ })
68
+
69
+ MERGE (subject)-[relationship:RELATES {
70
+ memory_id: $memory_id,
71
+ relation: $relation,
72
+ user_id: $user_id
73
+ }]->(object)
74
+
75
+ SET relationship.metadata = $metadata
76
+ """
77
+
78
+ parameters = {
79
+ "user_id": fact.user_id,
80
+ "subject": fact.subject,
81
+ "relation": fact.relation,
82
+ "object": fact.object,
83
+ "memory_id": fact.memory_id,
84
+ "metadata": json.dumps(fact.metadata or {}),
85
+ }
86
+
87
+ with self.driver.session(
88
+ database=self.database
89
+ ) as session:
90
+ session.run(
91
+ cypher,
92
+ parameters,
93
+ )
94
+
95
+ def delete_memory(
96
+ self,
97
+ memory_id: str,
98
+ ) -> None:
99
+ cypher = """
100
+ MATCH ()-[relationship:RELATES {
101
+ memory_id: $memory_id
102
+ }]->()
103
+
104
+ DELETE relationship
105
+ """
106
+
107
+ parameters = {
108
+ "memory_id": memory_id,
109
+ }
110
+
111
+ with self.driver.session(
112
+ database=self.database
113
+ ) as session:
114
+ session.run(
115
+ cypher,
116
+ parameters,
117
+ )
118
+
119
+ def search(
120
+ self,
121
+ query: str,
122
+ user_id: str,
123
+ *,
124
+ limit: int = 10,
125
+ ) -> list[dict[str, Any]]:
126
+ if not query.strip():
127
+ return []
128
+
129
+ search_terms = self._search_terms(query)
130
+
131
+ if not search_terms:
132
+ return []
133
+
134
+ cypher = """
135
+ MATCH (subject:Entity)-[relationship:RELATES]->(object:Entity)
136
+
137
+ WHERE relationship.user_id = $user_id
138
+
139
+ AND any(
140
+ term IN $search_terms
141
+ WHERE
142
+ toLower(subject.name) CONTAINS term
143
+ OR
144
+ toLower(object.name) CONTAINS term
145
+ OR
146
+ toLower(relationship.relation) CONTAINS term
147
+ )
148
+
149
+ RETURN
150
+ subject.name AS subject,
151
+ relationship.relation AS relation,
152
+ object.name AS object,
153
+ relationship.memory_id AS memory_id,
154
+ relationship.metadata AS metadata
155
+
156
+ LIMIT $limit
157
+ """
158
+
159
+ parameters = {
160
+ "user_id": user_id,
161
+ "search_terms": search_terms,
162
+ "limit": limit,
163
+ }
164
+
165
+ with self.driver.session(
166
+ database=self.database
167
+ ) as session:
168
+ result = session.run(
169
+ cypher,
170
+ parameters,
171
+ )
172
+
173
+ return [
174
+ {
175
+ "subject": record["subject"],
176
+ "relation": record["relation"],
177
+ "object": record["object"],
178
+ "memory_id": record["memory_id"],
179
+ "metadata": self._decode_metadata(
180
+ record["metadata"]
181
+ ),
182
+ }
183
+ for record in result
184
+ ]
185
+
186
+ def clear_user(
187
+ self,
188
+ user_id: str,
189
+ ) -> None:
190
+ cypher = """
191
+ MATCH (entity:Entity {
192
+ user_id: $user_id
193
+ })
194
+
195
+ DETACH DELETE entity
196
+ """
197
+
198
+ parameters = {
199
+ "user_id": user_id,
200
+ }
201
+
202
+ with self.driver.session(
203
+ database=self.database
204
+ ) as session:
205
+ session.run(
206
+ cypher,
207
+ parameters,
208
+ )
209
+
210
+ def close(self) -> None:
211
+ """Close the Neo4j driver."""
212
+ self.driver.close()
213
+
214
+ @staticmethod
215
+ def _decode_metadata(
216
+ metadata: Any,
217
+ ) -> dict[str, Any]:
218
+ if metadata is None:
219
+ return {}
220
+
221
+ if isinstance(metadata, dict):
222
+ return metadata
223
+
224
+ if isinstance(metadata, str):
225
+ try:
226
+ value = json.loads(metadata)
227
+
228
+ if isinstance(value, dict):
229
+ return value
230
+
231
+ except json.JSONDecodeError:
232
+ pass
233
+
234
+ return {}
235
+
236
+ @staticmethod
237
+ def _search_terms(
238
+ query: str,
239
+ ) -> list[str]:
240
+ words = re.findall(
241
+ r"[a-zA-Z0-9_-]+",
242
+ query.lower(),
243
+ )
244
+
245
+ stopwords = {
246
+ "a",
247
+ "an",
248
+ "and",
249
+ "are",
250
+ "do",
251
+ "does",
252
+ "for",
253
+ "i",
254
+ "in",
255
+ "is",
256
+ "it",
257
+ "me",
258
+ "my",
259
+ "of",
260
+ "on",
261
+ "or",
262
+ "the",
263
+ "to",
264
+ "what",
265
+ "which",
266
+ "who",
267
+ }
268
+
269
+ return [
270
+ word
271
+ for word in words
272
+ if word not in stopwords
273
+ and len(word) > 1
274
+ ]
memlib/llm.py ADDED
@@ -0,0 +1,52 @@
1
+ from typing import Any
2
+
3
+ from langchain_core.language_models import BaseChatModel
4
+ from langchain_core.messages import HumanMessage, SystemMessage
5
+
6
+
7
+ class LLMClient:
8
+ def __init__(self, llm: BaseChatModel):
9
+ self.llm = llm
10
+
11
+ def complete(
12
+ self,
13
+ system_prompt: str,
14
+ user_prompt: str,
15
+ ) -> str:
16
+ """
17
+ Execute a simple LLM completion.
18
+
19
+ Used by:
20
+ - memory extraction
21
+ - memory update resolver
22
+ - summary generation
23
+ """
24
+
25
+ response = self.llm.invoke(
26
+ [
27
+ SystemMessage(content=system_prompt),
28
+ HumanMessage(content=user_prompt),
29
+ ]
30
+ )
31
+
32
+ return self._extract_content(response)
33
+
34
+ def invoke(self, messages: list[Any]) -> str:
35
+ """
36
+ Generic invoke wrapper for advanced usage.
37
+ """
38
+
39
+ response = self.llm.invoke(messages)
40
+
41
+ return self._extract_content(response)
42
+
43
+ @staticmethod
44
+ def _extract_content(response: Any) -> str:
45
+ """
46
+ Normalize LangChain response output.
47
+ """
48
+
49
+ if hasattr(response, "content"):
50
+ return str(response.content)
51
+
52
+ return str(response)