-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsemantic.py
More file actions
428 lines (356 loc) · 12.2 KB
/
Copy pathsemantic.py
File metadata and controls
428 lines (356 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
"""
Semantic Memory Implementation
Semantic memory stores facts, preferences, and structured knowledge that persist
across conversation threads. This is ideal for:
- User preferences (language, style, interests)
- Factual knowledge (user's name, location, occupation)
- Structured information (product catalog, FAQ)
Examples:
>>> from langgraph.store.memory import InMemoryStore
>>> store = InMemoryStore()
>>> memory = SemanticMemory(store, user_id="alice")
>>> memory.store_fact("name", "Alice Smith")
>>> memory.store_preference("cuisine", "Italian")
>>> facts = memory.recall_all()
"""
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass
from datetime import datetime
from langgraph.store.base import BaseStore
@dataclass
class Fact:
"""A single fact stored in semantic memory."""
key: str
value: Any
category: str
source: str = "conversation"
confidence: float = 1.0
created_at: str = None
updated_at: str = None
def __post_init__(self):
if self.created_at is None:
self.created_at = datetime.now().isoformat()
if self.updated_at is None:
self.updated_at = self.created_at
def to_dict(self) -> Dict:
"""Convert fact to dictionary for storage."""
return {
"value": self.value,
"category": self.category,
"source": self.source,
"confidence": self.confidence,
"created_at": self.created_at,
"updated_at": self.updated_at
}
@classmethod
def from_dict(cls, key: str, data: Dict) -> "Fact":
"""Create fact from stored dictionary."""
return cls(
key=key,
value=data["value"],
category=data["category"],
source=data.get("source", "conversation"),
confidence=data.get("confidence", 1.0),
created_at=data.get("created_at"),
updated_at=data.get("updated_at")
)
class SemanticMemory:
"""
Semantic memory manager for long-term fact storage.
Stores and retrieves facts, preferences, and structured knowledge using
LangGraph's Store interface.
Args:
store: LangGraph BaseStore instance (e.g., InMemoryStore, PostgresStore)
user_id: Unique identifier for the user
namespace_prefix: Optional prefix for memory namespace
Examples:
>>> memory = SemanticMemory(store, user_id="user_123")
>>> memory.store_fact("email", "alice@example.com", category="contact")
>>> email = memory.recall("email")
"""
def __init__(
self,
store: BaseStore,
user_id: str,
namespace_prefix: str = "semantic"
):
self.store = store
self.user_id = user_id
self.namespace = (namespace_prefix, user_id)
def store_fact(
self,
key: str,
value: Any,
category: str = "general",
source: str = "conversation",
confidence: float = 1.0
) -> None:
"""
Store a fact in semantic memory.
Args:
key: Unique identifier for the fact
value: The fact's value (can be any JSON-serializable type)
category: Category for organizing facts (e.g., "preference", "contact")
source: Source of the fact (e.g., "conversation", "profile", "inference")
confidence: Confidence level (0.0 to 1.0)
Examples:
>>> memory.store_fact("name", "Alice")
>>> memory.store_fact("age", 30, category="demographics")
>>> memory.store_fact("likes_coffee", True, category="preference", confidence=0.8)
"""
fact = Fact(
key=key,
value=value,
category=category,
source=source,
confidence=confidence
)
self.store.put(
namespace=self.namespace,
key=key,
value=fact.to_dict()
)
def store_preference(
self,
preference_type: str,
value: Any,
confidence: float = 1.0
) -> None:
"""
Store a user preference (convenience method).
Args:
preference_type: Type of preference (e.g., "cuisine", "language", "theme")
value: Preference value
confidence: Confidence level
Examples:
>>> memory.store_preference("language", "Python")
>>> memory.store_preference("theme", "dark_mode")
"""
self.store_fact(
key=f"pref_{preference_type}",
value=value,
category="preference",
confidence=confidence
)
def recall(self, key: str) -> Optional[Any]:
"""
Recall a specific fact by key.
Args:
key: Fact identifier
Returns:
The fact's value, or None if not found
Examples:
>>> name = memory.recall("name")
>>> if name:
... print(f"User's name is {name}")
"""
try:
result = self.store.get(namespace=self.namespace, key=key)
if result:
return result.value.get("value")
except Exception:
pass
return None
def recall_with_metadata(self, key: str) -> Optional[Fact]:
"""
Recall a fact with full metadata.
Args:
key: Fact identifier
Returns:
Fact object with metadata, or None if not found
Examples:
>>> fact = memory.recall_with_metadata("name")
>>> print(f"Confidence: {fact.confidence}, Source: {fact.source}")
"""
try:
result = self.store.get(namespace=self.namespace, key=key)
if result:
return Fact.from_dict(key, result.value)
except Exception:
pass
return None
def recall_by_category(self, category: str) -> Dict[str, Any]:
"""
Recall all facts in a category.
Args:
category: Category name
Returns:
Dictionary of {key: value} for facts in the category
Examples:
>>> preferences = memory.recall_by_category("preference")
>>> for key, value in preferences.items():
... print(f"{key}: {value}")
"""
all_facts = self.recall_all()
return {
key: fact.value
for key, fact in all_facts.items()
if fact.category == category
}
def recall_all(self) -> Dict[str, Fact]:
"""
Recall all facts from semantic memory.
Returns:
Dictionary of {key: Fact} for all stored facts
Examples:
>>> all_facts = memory.recall_all()
>>> for key, fact in all_facts.items():
... print(f"{key}: {fact.value} ({fact.category})")
"""
try:
results = self.store.search(namespace=self.namespace)
return {
item.key: Fact.from_dict(item.key, item.value)
for item in results
}
except Exception:
return {}
def search(self, query: str, limit: int = 5) -> List[Tuple[str, Any, float]]:
"""
Search semantic memory using similarity search.
Note: Requires store to be configured with embeddings for semantic search.
Args:
query: Search query
limit: Maximum number of results
Returns:
List of (key, value, similarity_score) tuples
Examples:
>>> results = memory.search("What food does the user like?")
>>> for key, value, score in results:
... print(f"{key}: {value} (similarity: {score:.2f})")
"""
try:
results = self.store.search(
namespace=self.namespace,
query=query,
limit=limit
)
return [
(item.key, item.value.get("value"), getattr(item, "score", 1.0))
for item in results
]
except Exception:
return []
def update_fact(
self,
key: str,
value: Any = None,
confidence: float = None
) -> bool:
"""
Update an existing fact.
Args:
key: Fact identifier
value: New value (if None, keeps existing)
confidence: New confidence (if None, keeps existing)
Returns:
True if fact was updated, False if not found
Examples:
>>> memory.update_fact("name", "Alice Johnson")
>>> memory.update_fact("age", confidence=0.9)
"""
fact = self.recall_with_metadata(key)
if not fact:
return False
if value is not None:
fact.value = value
if confidence is not None:
fact.confidence = confidence
fact.updated_at = datetime.now().isoformat()
self.store.put(
namespace=self.namespace,
key=key,
value=fact.to_dict()
)
return True
def delete_fact(self, key: str) -> bool:
"""
Delete a fact from semantic memory.
Args:
key: Fact identifier
Returns:
True if deleted, False if not found
Examples:
>>> memory.delete_fact("old_preference")
"""
try:
self.store.delete(namespace=self.namespace, key=key)
return True
except Exception:
return False
def clear_category(self, category: str) -> int:
"""
Delete all facts in a category.
Args:
category: Category to clear
Returns:
Number of facts deleted
Examples:
>>> count = memory.clear_category("temporary")
>>> print(f"Deleted {count} temporary facts")
"""
facts = self.recall_all()
count = 0
for key, fact in facts.items():
if fact.category == category:
self.delete_fact(key)
count += 1
return count
def get_context_string(self, categories: Optional[List[str]] = None) -> str:
"""
Get a formatted string of facts for use in LLM context.
Args:
categories: Optional list of categories to include. If None, includes all.
Returns:
Formatted string describing stored facts
Examples:
>>> context = memory.get_context_string(categories=["preference"])
>>> print(context)
# Output:
# User Preferences:
# - cuisine: Italian
# - theme: dark_mode
"""
all_facts = self.recall_all()
if categories:
facts = {k: v for k, v in all_facts.items() if v.category in categories}
else:
facts = all_facts
if not facts:
return "No stored information available."
# Group by category
by_category: Dict[str, List[Tuple[str, Any]]] = {}
for key, fact in facts.items():
if fact.category not in by_category:
by_category[fact.category] = []
by_category[fact.category].append((key, fact.value))
# Format output
lines = []
for category, items in sorted(by_category.items()):
lines.append(f"{category.title()}:")
for key, value in items:
lines.append(f" - {key}: {value}")
return "\n".join(lines)
# Example usage
if __name__ == "__main__":
from langgraph.store.memory import InMemoryStore
# Create store and memory
store = InMemoryStore()
memory = SemanticMemory(store, user_id="alice")
# Store facts
print("Storing facts...")
memory.store_fact("name", "Alice Smith")
memory.store_fact("email", "alice@example.com", category="contact")
memory.store_preference("cuisine", "Italian")
memory.store_preference("language", "Python")
# Recall
print(f"\nName: {memory.recall('name')}")
print(f"Email: {memory.recall('email')}")
# Recall by category
print("\nPreferences:")
prefs = memory.recall_by_category("preference")
for key, value in prefs.items():
print(f" {key}: {value}")
# Get context
print("\nContext string:")
print(memory.get_context_string())