forked from QuixiAI/Hexis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_tools.py
More file actions
1264 lines (1109 loc) · 47.4 KB
/
Copy pathmemory_tools.py
File metadata and controls
1264 lines (1109 loc) · 47.4 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
AGI Memory MCP Tools
Provides MCP-compatible tools for an LLM to query its memory system during conversation.
These are the function definitions and handlers that allow the model to actively
recall, search, and explore its memories.
"""
import json
import re
from datetime import datetime, timezone
from dataclasses import dataclass, asdict
from typing import Optional, Any
from enum import Enum
try:
import psycopg2
from psycopg2.extras import RealDictCursor
HAS_PSYCOPG2 = True
except Exception: # pragma: no cover
psycopg2 = None # type: ignore[assignment]
RealDictCursor = None # type: ignore[assignment]
HAS_PSYCOPG2 = False
from cognitive_memory_api import (
CognitiveMemorySync,
GoalPriority as ApiGoalPriority,
GoalSource as ApiGoalSource,
MemoryType as ApiMemoryType,
)
# ============================================================================
# TOOL DEFINITIONS (OpenAI Function Calling Format)
# ============================================================================
MEMORY_TOOLS = [
{
"type": "function",
"function": {
"name": "recall",
"description": "Search memories by semantic similarity. Use this to find memories related to a topic, concept, or question. Returns the most relevant memories based on meaning, not just keyword matching.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Natural language query describing what you want to remember. Be specific and descriptive for better results."
},
"limit": {
"type": "integer",
"description": "Maximum number of memories to return (default: 5, max: 20)",
"default": 5
},
"memory_types": {
"type": "array",
"items": {
"type": "string",
"enum": ["episodic", "semantic", "procedural", "strategic"]
},
"description": "Filter by memory types. Omit to search all types."
},
"min_importance": {
"type": "number",
"description": "Minimum importance score (0.0-1.0). Use to filter for significant memories.",
"default": 0.0
}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "recall_recent",
"description": "Retrieve the most recently accessed or created memories. Useful for continuing recent conversations or recalling what was just discussed.",
"parameters": {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Number of recent memories to return (default: 5, max: 20)",
"default": 5
},
"memory_types": {
"type": "array",
"items": {
"type": "string",
"enum": ["episodic", "semantic", "procedural", "strategic"]
},
"description": "Filter by memory types. Omit to include all types."
},
"by_access": {
"type": "boolean",
"description": "If true, sort by last accessed time. If false, sort by creation time.",
"default": True
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "recall_episode",
"description": "Retrieve all memories from a specific episode (a coherent sequence of related memories, like a conversation or work session). Use when you need the full context of a past interaction.",
"parameters": {
"type": "object",
"properties": {
"episode_id": {
"type": "string",
"description": "UUID of the episode to retrieve"
}
},
"required": ["episode_id"]
}
}
},
{
"type": "function",
"function": {
"name": "explore_concept",
"description": "Explore memories connected to a specific concept. Shows how different memories relate to an idea and what other concepts are connected.",
"parameters": {
"type": "object",
"properties": {
"concept": {
"type": "string",
"description": "The concept to explore (e.g., 'machine learning', 'user preferences', 'project goals')"
},
"include_related": {
"type": "boolean",
"description": "If true, also return memories linked to related concepts",
"default": True
},
"limit": {
"type": "integer",
"description": "Maximum memories to return per concept",
"default": 5
}
},
"required": ["concept"]
}
}
},
{
"type": "function",
"function": {
"name": "explore_cluster",
"description": "Explore a thematic cluster of memories. Clusters are automatically formed groups of related memories. Use to understand patterns and themes.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Find clusters related to this topic"
},
"limit": {
"type": "integer",
"description": "Maximum clusters to return",
"default": 3
}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "get_procedures",
"description": "Retrieve procedural memories (how-to knowledge) for a specific task. Returns step-by-step instructions and prerequisites.",
"parameters": {
"type": "object",
"properties": {
"task": {
"type": "string",
"description": "The task you want to know how to do"
},
"limit": {
"type": "integer",
"description": "Maximum procedures to return",
"default": 3
}
},
"required": ["task"]
}
}
},
{
"type": "function",
"function": {
"name": "get_strategies",
"description": "Retrieve strategic memories (patterns, heuristics, lessons learned) applicable to a situation. These are meta-level insights about what works.",
"parameters": {
"type": "object",
"properties": {
"situation": {
"type": "string",
"description": "The situation or context you need strategic guidance for"
},
"limit": {
"type": "integer",
"description": "Maximum strategies to return",
"default": 3
}
},
"required": ["situation"]
}
}
},
{
"type": "function",
"function": {
"name": "list_recent_episodes",
"description": "List recent episodes (conversation sessions, work sessions, etc.) to understand what interactions have happened.",
"parameters": {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Number of episodes to return",
"default": 5
}
},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "create_goal",
"description": "Create a new goal (queued task) for the agent to pursue later. Use this for reminders, TODOs, or longer-term objectives.",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string", "description": "Short goal title"},
"description": {"type": ["string", "null"], "description": "Optional longer description"},
"priority": {
"type": "string",
"enum": ["active", "queued", "backburner"],
"default": "queued",
"description": "Desired priority (DB may demote if at limits)"
},
"source": {
"type": "string",
"enum": ["curiosity", "user_request", "identity", "derived", "external"],
"default": "user_request",
"description": "Why this goal exists"
},
"due_at": {
"type": ["string", "null"],
"description": "Optional due timestamp in ISO8601 (e.g. 2025-01-01T12:00:00Z)"
}
},
"required": ["title"],
"additionalProperties": False
}
}
},
{
"type": "function",
"function": {
"name": "queue_user_message",
"description": "Queue a message to the user in the outbox for delivery by an external integration (worker/webhook).",
"parameters": {
"type": "object",
"properties": {
"message": {"type": "string", "description": "Message body for the user"},
"intent": {"type": ["string", "null"], "description": "Optional intent/category (e.g. 'reminder', 'status', 'question')"},
"context": {"type": ["object", "null"], "description": "Optional JSON context payload"}
},
"required": ["message"],
"additionalProperties": False
}
}
}
]
_API_TOOL_NAMES = {"recall", "recall_recent", "explore_concept", "get_procedures", "get_strategies", "create_goal", "queue_user_message"}
# ============================================================================
# TOOL HANDLERS
# ============================================================================
class MemoryToolHandler:
"""Handles execution of memory tools."""
def __init__(self, db_config: dict):
self.db_config = db_config
self.conn = None
def connect(self):
"""Establish database connection."""
if not HAS_PSYCOPG2:
raise RuntimeError("psycopg2 is required for legacy MemoryToolHandler; use CognitiveMemory API instead.")
if not self.conn or self.conn.closed:
self.conn = psycopg2.connect(
host=self.db_config.get('host', 'localhost'),
port=self.db_config.get('port', 5432),
dbname=self.db_config.get('dbname', 'agi_memory'),
user=self.db_config.get('user', 'postgres'),
password=self.db_config.get('password', 'password')
)
def close(self):
"""Close database connection."""
if self.conn:
self.conn.close()
def execute_tool(self, tool_name: str, arguments: dict) -> dict:
"""Execute a tool and return the result."""
self.connect()
handlers = {
'recall': self._handle_recall,
'recall_recent': self._handle_recall_recent,
'recall_episode': self._handle_recall_episode,
'explore_concept': self._handle_explore_concept,
'explore_cluster': self._handle_explore_cluster,
'get_procedures': self._handle_get_procedures,
'get_strategies': self._handle_get_strategies,
'list_recent_episodes': self._handle_list_episodes,
}
handler = handlers.get(tool_name)
if not handler:
return {"error": f"Unknown tool: {tool_name}"}
try:
return handler(arguments)
except Exception as e:
return {"error": str(e)}
def _handle_recall(self, args: dict) -> dict:
"""Handle the recall tool - semantic memory search."""
query = args.get('query', '')
limit = min(args.get('limit', 5), 20)
memory_types = args.get('memory_types')
min_importance = args.get('min_importance', 0.0)
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
# Use the fast_recall function
cur.execute("""
SELECT
memory_id,
content,
memory_type,
score,
source
FROM fast_recall(%s, %s)
""", (query, limit * 2)) # Get more, then filter
results = cur.fetchall()
# Filter by type and importance if specified
if memory_types or min_importance > 0:
cur.execute("""
SELECT id, importance FROM memories
WHERE id = ANY(%s)
""", ([r['memory_id'] for r in results],))
importance_map = {str(row['id']): row['importance'] for row in cur.fetchall()}
filtered = []
for r in results:
mid = str(r['memory_id'])
if memory_types and r['memory_type'] not in memory_types:
continue
if importance_map.get(mid, 0) < min_importance:
continue
r['importance'] = importance_map.get(mid, 0)
filtered.append(r)
results = filtered[:limit]
# Update access counts
if results:
cur.execute("""
UPDATE memories
SET access_count = access_count + 1, last_accessed = CURRENT_TIMESTAMP
WHERE id = ANY(%s)
""", ([r['memory_id'] for r in results],))
self.conn.commit()
return {
"memories": [dict(r) for r in results],
"count": len(results),
"query": query
}
def _handle_recall_recent(self, args: dict) -> dict:
"""Handle recall_recent - get recently accessed/created memories."""
limit = min(args.get('limit', 5), 20)
memory_types = args.get('memory_types')
by_access = args.get('by_access', True)
order_col = 'last_accessed' if by_access else 'created_at'
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
type_filter = ""
params = [limit]
if memory_types:
type_filter = "AND type = ANY(%s)"
params.insert(0, memory_types)
cur.execute(f"""
SELECT
id as memory_id,
content,
type as memory_type,
importance,
created_at,
last_accessed
FROM memories
WHERE status = 'active' {type_filter}
ORDER BY {order_col} DESC NULLS LAST
LIMIT %s
""", params)
results = cur.fetchall()
return {
"memories": [dict(r) for r in results],
"count": len(results),
"sorted_by": order_col
}
def _handle_recall_episode(self, args: dict) -> dict:
"""Handle recall_episode - get all memories from an episode."""
episode_id = args.get('episode_id')
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
# Get episode info
cur.execute("""
SELECT id, started_at, ended_at, episode_type, summary
FROM episodes
WHERE id = %s
""", (episode_id,))
episode = cur.fetchone()
if not episode:
return {"error": f"Episode not found: {episode_id}"}
# Get memories in episode
cur.execute("""
SELECT
m.id as memory_id,
m.content,
m.type as memory_type,
m.importance,
m.created_at,
em.sequence_order
FROM episode_memories em
JOIN memories m ON em.memory_id = m.id
WHERE em.episode_id = %s
ORDER BY em.sequence_order
""", (episode_id,))
memories = cur.fetchall()
return {
"episode": dict(episode),
"memories": [dict(m) for m in memories],
"count": len(memories)
}
def _handle_explore_concept(self, args: dict) -> dict:
"""Handle explore_concept - find memories linked to a concept."""
concept = args.get('concept', '').lower().strip()
include_related = args.get('include_related', True)
limit = min(args.get('limit', 5), 20)
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
# Find the concept
cur.execute("""
SELECT id, name, description, path_text
FROM concepts
WHERE name ILIKE %s
LIMIT 1
""", (f'%{concept}%',))
concept_row = cur.fetchone()
if not concept_row:
# No exact concept found, fall back to semantic search
return self._handle_recall({'query': concept, 'limit': limit})
concept_id = concept_row['id']
# Get memories linked to this concept
cur.execute("""
SELECT
m.id as memory_id,
m.content,
m.type as memory_type,
m.importance,
mc.strength as concept_strength
FROM memory_concepts mc
JOIN memories m ON mc.memory_id = m.id
WHERE mc.concept_id = %s
AND m.status = 'active'
ORDER BY mc.strength DESC, m.importance DESC
LIMIT %s
""", (concept_id, limit))
memories = cur.fetchall()
# Get related concepts
related_concepts = []
if include_related:
cur.execute("""
SELECT DISTINCT c2.name, COUNT(*) as shared_memories
FROM memory_concepts mc1
JOIN memory_concepts mc2 ON mc1.memory_id = mc2.memory_id
JOIN concepts c2 ON mc2.concept_id = c2.id
WHERE mc1.concept_id = %s
AND mc2.concept_id != %s
GROUP BY c2.name
ORDER BY shared_memories DESC
LIMIT 10
""", (concept_id, concept_id))
related_concepts = [dict(r) for r in cur.fetchall()]
return {
"concept": dict(concept_row),
"memories": [dict(m) for m in memories],
"related_concepts": related_concepts,
"count": len(memories)
}
def _handle_explore_cluster(self, args: dict) -> dict:
"""Handle explore_cluster - find and explore thematic clusters."""
query = args.get('query', '')
limit = min(args.get('limit', 3), 10)
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
# Search clusters by embedding similarity
cur.execute("""
WITH query_embedding AS (
SELECT get_embedding(%s) as emb
)
SELECT
mc.id,
mc.name,
mc.description,
mc.cluster_type,
mc.importance_score,
mc.keywords,
1 - (mc.centroid_embedding <=> (SELECT emb FROM query_embedding)) as similarity
FROM memory_clusters mc
WHERE mc.centroid_embedding IS NOT NULL
ORDER BY mc.centroid_embedding <=> (SELECT emb FROM query_embedding)
LIMIT %s
""", (query, limit))
clusters = cur.fetchall()
# For each cluster, get sample memories
result_clusters = []
for cluster in clusters:
cur.execute("""
SELECT
m.id as memory_id,
m.content,
m.type as memory_type,
mcm.membership_strength
FROM memory_cluster_members mcm
JOIN memories m ON mcm.memory_id = m.id
WHERE mcm.cluster_id = %s
AND m.status = 'active'
ORDER BY mcm.membership_strength DESC
LIMIT 3
""", (cluster['id'],))
sample_memories = cur.fetchall()
result_clusters.append({
**dict(cluster),
"sample_memories": [dict(m) for m in sample_memories]
})
return {
"clusters": result_clusters,
"count": len(result_clusters),
"query": query
}
def _handle_get_procedures(self, args: dict) -> dict:
"""Handle get_procedures - find procedural knowledge."""
task = args.get('task', '')
limit = min(args.get('limit', 3), 10)
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
# Search procedural memories
cur.execute("""
WITH query_embedding AS (
SELECT get_embedding(%s) as emb
)
SELECT
m.id as memory_id,
m.content,
pm.steps,
pm.prerequisites,
pm.success_rate,
pm.average_duration,
1 - (m.embedding <=> (SELECT emb FROM query_embedding)) as similarity
FROM memories m
JOIN procedural_memories pm ON m.id = pm.memory_id
WHERE m.status = 'active'
AND m.type = 'procedural'
ORDER BY m.embedding <=> (SELECT emb FROM query_embedding)
LIMIT %s
""", (task, limit))
procedures = cur.fetchall()
return {
"procedures": [dict(p) for p in procedures],
"count": len(procedures),
"task": task
}
def _handle_get_strategies(self, args: dict) -> dict:
"""Handle get_strategies - find strategic knowledge."""
situation = args.get('situation', '')
limit = min(args.get('limit', 3), 10)
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("""
WITH query_embedding AS (
SELECT get_embedding(%s) as emb
)
SELECT
m.id as memory_id,
m.content,
sm.pattern_description,
sm.confidence_score,
sm.context_applicability,
sm.success_metrics,
1 - (m.embedding <=> (SELECT emb FROM query_embedding)) as similarity
FROM memories m
JOIN strategic_memories sm ON m.id = sm.memory_id
WHERE m.status = 'active'
AND m.type = 'strategic'
ORDER BY m.embedding <=> (SELECT emb FROM query_embedding)
LIMIT %s
""", (situation, limit))
strategies = cur.fetchall()
return {
"strategies": [dict(s) for s in strategies],
"count": len(strategies),
"situation": situation
}
def _handle_list_episodes(self, args: dict) -> dict:
"""Handle list_recent_episodes - list recent episodes."""
limit = min(args.get('limit', 5), 20)
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("""
SELECT
e.id,
e.started_at,
e.ended_at,
e.episode_type,
e.summary,
COUNT(em.memory_id) as memory_count
FROM episodes e
LEFT JOIN episode_memories em ON e.id = em.episode_id
GROUP BY e.id
ORDER BY e.started_at DESC
LIMIT %s
""", (limit,))
episodes = cur.fetchall()
return {
"episodes": [dict(e) for e in episodes],
"count": len(episodes)
}
class ApiMemoryToolHandler:
"""Tool handler backed by CognitiveMemorySync (asyncpg)."""
def __init__(self, db_config: dict):
self.db_config = db_config
self.client: CognitiveMemorySync | None = None
def connect(self) -> None:
if self.client is not None:
return
dsn = (
f"postgresql://{self.db_config.get('user', 'postgres')}:{self.db_config.get('password', 'password')}"
f"@{self.db_config.get('host', 'localhost')}:{int(self.db_config.get('port', 5432))}"
f"/{self.db_config.get('dbname', 'agi_memory')}"
)
self.client = CognitiveMemorySync.connect(dsn, min_size=1, max_size=5)
def close(self) -> None:
if self.client is not None:
self.client.close()
self.client = None
def execute_tool(self, tool_name: str, arguments: dict) -> dict:
self.connect()
assert self.client is not None
handlers = {
"recall": self._handle_recall,
"recall_recent": self._handle_recall_recent,
"explore_concept": self._handle_explore_concept,
"get_procedures": self._handle_get_procedures,
"get_strategies": self._handle_get_strategies,
"create_goal": self._handle_create_goal,
"queue_user_message": self._handle_queue_user_message,
}
handler = handlers.get(tool_name)
if not handler:
return {"error": f"Unknown tool: {tool_name}"}
try:
return handler(arguments or {})
except Exception as e:
return {"error": str(e)}
def _handle_recall(self, args: dict) -> dict:
query = args.get("query", "")
limit = min(int(args.get("limit", 5)), 20)
memory_types = args.get("memory_types")
min_importance = float(args.get("min_importance", 0.0) or 0.0)
parsed_types = None
if isinstance(memory_types, list) and memory_types:
parsed_types = [ApiMemoryType(str(t)) for t in memory_types]
result = self.client.recall(query, limit=limit, memory_types=parsed_types, min_importance=min_importance, include_partial=False)
self.client.touch_memories([m.id for m in result.memories])
memories = [
{
"memory_id": str(m.id),
"content": m.content,
"memory_type": m.type.value,
"score": m.similarity,
"source": m.source,
"importance": m.importance,
"trust_level": m.trust_level,
"source_attribution": m.source_attribution,
}
for m in result.memories
]
return {"memories": memories, "count": len(memories), "query": query}
def _handle_recall_recent(self, args: dict) -> dict:
limit = min(int(args.get("limit", 5)), 20)
memory_types = args.get("memory_types")
by_access = bool(args.get("by_access", True))
# API exposes recent by created_at; "by_access" isn't supported, so we approximate by created_at.
# If a type filter is provided, use the first type.
mt = None
if isinstance(memory_types, list) and memory_types:
mt = ApiMemoryType(str(memory_types[0]))
rows = self.client.recall_recent(limit=limit, memory_type=mt)
if by_access:
# Touch to keep access_count semantics similar.
self.client.touch_memories([m.id for m in rows])
results = [
{
"memory_id": str(m.id),
"content": m.content,
"memory_type": m.type.value,
"importance": m.importance,
"created_at": m.created_at.isoformat() if m.created_at else None,
"last_accessed": None,
"trust_level": m.trust_level,
"source_attribution": m.source_attribution,
}
for m in rows
]
return {"memories": results, "count": len(results)}
def _handle_explore_concept(self, args: dict) -> dict:
concept = str(args.get("concept", "")).strip()
include_related = bool(args.get("include_related", True))
limit = min(int(args.get("limit", 5)), 20)
if not concept:
return {"error": "Missing concept"}
direct = self.client.find_by_concept(concept, limit=limit)
combined: dict[str, dict] = {
str(m.id): {
"memory_id": str(m.id),
"content": m.content,
"memory_type": m.type.value,
"importance": m.importance,
"trust_level": m.trust_level,
"source_attribution": m.source_attribution,
"source": "concept",
"score": None,
}
for m in direct
}
if include_related:
rr = self.client.recall(concept, limit=limit, include_partial=False)
for m in rr.memories:
combined.setdefault(
str(m.id),
{
"memory_id": str(m.id),
"content": m.content,
"memory_type": m.type.value,
"importance": m.importance,
"trust_level": m.trust_level,
"source_attribution": m.source_attribution,
"source": m.source,
"score": m.similarity,
},
)
out = list(combined.values())[:limit]
return {"concept": concept, "memories": out, "count": len(out)}
def _handle_get_procedures(self, args: dict) -> dict:
task = str(args.get("task", "")).strip()
limit = min(int(args.get("limit", 3)), 10)
if not task:
return {"procedures": [], "count": 0, "task": task}
res = self.client.recall(task, limit=limit, memory_types=[ApiMemoryType.PROCEDURAL], include_partial=False)
return {"procedures": [{"memory_id": str(m.id), "content": m.content, "score": m.similarity} for m in res.memories], "count": len(res.memories), "task": task}
def _handle_get_strategies(self, args: dict) -> dict:
situation = str(args.get("situation", "")).strip()
limit = min(int(args.get("limit", 3)), 10)
if not situation:
return {"strategies": [], "count": 0, "situation": situation}
res = self.client.recall(situation, limit=limit, memory_types=[ApiMemoryType.STRATEGIC], include_partial=False)
return {"strategies": [{"memory_id": str(m.id), "content": m.content, "score": m.similarity} for m in res.memories], "count": len(res.memories), "situation": situation}
def _handle_create_goal(self, args: dict) -> dict:
title = str(args.get("title", "")).strip()
if not title:
return {"error": "Missing title"}
description = args.get("description")
priority = str(args.get("priority") or ApiGoalPriority.QUEUED.value)
source = str(args.get("source") or ApiGoalSource.USER_REQUEST.value)
due_at_raw = args.get("due_at")
due_at = None
if isinstance(due_at_raw, str) and due_at_raw.strip():
txt = due_at_raw.strip()
if txt.endswith("Z"):
txt = txt[:-1] + "+00:00"
try:
due_at = datetime.fromisoformat(txt)
except Exception:
due_at = None
goal_id = self.client.create_goal(
title,
description=str(description) if isinstance(description, str) else None,
source=source,
priority=priority,
due_at=due_at,
)
return {"goal_id": str(goal_id), "title": title, "priority": priority, "source": source, "due_at": due_at_raw}
def _handle_queue_user_message(self, args: dict) -> dict:
message = str(args.get("message", "")).strip()
if not message:
return {"error": "Missing message"}
intent = args.get("intent")
context = args.get("context")
outbox_id = self.client.queue_user_message(
message,
intent=str(intent) if isinstance(intent, str) else None,
context=context if isinstance(context, dict) else None,
)
return {"outbox_id": str(outbox_id), "queued": True}
# ============================================================================
# CONTEXT ENRICHMENT
# ============================================================================
class ContextEnricher:
"""
Automatically enriches user prompts with relevant memories before
sending to the LLM.
"""
def __init__(self, db_config: dict, top_k: int = 5):
self.db_config = db_config
self.top_k = top_k
self.client: CognitiveMemorySync | None = None
def connect(self):
"""Establish DB connection via CognitiveMemorySync."""
if self.client is not None:
return
dsn = (
f"postgresql://{self.db_config.get('user', 'postgres')}:{self.db_config.get('password', 'password')}"
f"@{self.db_config.get('host', 'localhost')}:{int(self.db_config.get('port', 5432))}"
f"/{self.db_config.get('dbname', 'agi_memory')}"
)
self.client = CognitiveMemorySync.connect(dsn, min_size=1, max_size=5)
def enrich(self, user_message: str) -> dict:
"""
Enrich a user message with relevant memories.
Returns:
{
"original_message": str,
"relevant_memories": list,
"enriched_context": str
}
"""
self.connect()
assert self.client is not None
result = self.client.recall(user_message, limit=self.top_k, include_partial=False)
memories = [
{
"memory_id": str(m.id),
"content": m.content,
"memory_type": m.type.value,
"score": m.similarity,
"source": m.source,
"importance": m.importance,
"trust_level": m.trust_level,
"source_attribution": m.source_attribution,
}
for m in result.memories
]
self.client.touch_memories([m.id for m in result.memories])
# Format memories into context
if memories:
memory_context = self._format_memories(memories)
else:
memory_context = None
return {
"original_message": user_message,
"relevant_memories": [dict(m) for m in memories],
"enriched_context": memory_context
}
def _format_memories(self, memories: list) -> str:
"""Format memories into a context string for the LLM."""
lines = ["[RELEVANT MEMORIES]"]
for i, mem in enumerate(memories, 1):
mem_type = mem['memory_type'].upper()
content = mem['content']
score = mem['score']
lines.append(f"\n({i}) [{mem_type}] (relevance: {score:.2f})")
lines.append(f" {content}")
lines.append("\n[END MEMORIES]")
return "\n".join(lines)
def close(self):
"""Close database connection."""
if self.client is not None:
self.client.close()
self.client = None
# ============================================================================
# MEMORY FORMATION (Post-conversation)
# ============================================================================
class MemoryFormation:
"""
Handles forming new memories from conversations.
Called after each exchange to potentially store new information.
"""
def __init__(self, db_config: dict, llm_client=None):
self.db_config = db_config
self.llm_client = llm_client
self.client: CognitiveMemorySync | None = None
def connect(self):
"""Establish DB connection via CognitiveMemorySync."""