-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathclient.py
More file actions
2333 lines (2005 loc) · 83.4 KB
/
client.py
File metadata and controls
2333 lines (2005 loc) · 83.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
"""
Agent Memory Server API Client
This module provides a standalone client for the REST API of the Agent Memory Server.
"""
import asyncio
import re
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING, Any, Literal, TypedDict
if TYPE_CHECKING:
from typing_extensions import Self
import httpx
import ulid
from pydantic import BaseModel
from .exceptions import MemoryClientError, MemoryServerError, MemoryValidationError
from .filters import (
CreatedAt,
Entities,
LastAccessed,
MemoryType,
Namespace,
SessionId,
Topics,
UserId,
)
from .models import (
AckResponse,
ClientMemoryRecord,
HealthCheckResponse,
MemoryRecord,
MemoryRecordResults,
MemoryTypeEnum,
ModelNameLiteral,
SessionListResponse,
WorkingMemory,
WorkingMemoryResponse,
)
# === Tool Call Type Definitions ===
class OpenAIFunctionCall(TypedDict):
"""OpenAI function call format (legacy)."""
name: str
arguments: str
class OpenAIToolCall(TypedDict):
"""OpenAI tool call format (current)."""
id: str
type: Literal["function"]
function: OpenAIFunctionCall
class AnthropicToolUse(TypedDict):
"""Anthropic tool use format."""
type: Literal["tool_use"]
id: str
name: str
input: dict[str, Any]
class UnifiedToolCall(TypedDict):
"""Unified tool call format for internal use."""
id: str | None
name: str
arguments: dict[str, Any]
provider: Literal["openai", "anthropic", "generic"]
class ToolCallResolutionResult(TypedDict):
"""Result of resolving a tool call."""
success: bool
function_name: str
result: Any | None
error: str | None
formatted_response: str
# === Client Configuration ===
class MemoryClientConfig(BaseModel):
"""Configuration for the Memory API Client"""
base_url: str
timeout: float = 30.0
default_namespace: str | None = None
default_model_name: str | None = None
default_context_window_max: int | None = None
class MemoryAPIClient:
"""
Client for the Agent Memory Server REST API.
This client provides methods to interact with all server endpoints:
- Health check
- Session management (list, get, put, delete)
- Long-term memory (create, search)
- Enhanced functionality (lifecycle, batch, pagination, validation)
"""
def __init__(self, config: MemoryClientConfig):
"""
Initialize the Memory API Client.
Args:
config: MemoryClientConfig instance with server connection details
"""
self.config = config
self._client = httpx.AsyncClient(
base_url=config.base_url,
timeout=config.timeout,
)
async def close(self) -> None:
"""Close the underlying HTTP client."""
await self._client.aclose()
async def __aenter__(self) -> "Self":
"""Support using the client as an async context manager."""
return self
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
"""Close the client when exiting the context manager."""
await self.close()
def _handle_http_error(self, response: httpx.Response) -> None:
"""Handle HTTP errors and convert to appropriate exceptions."""
if response.status_code == 404:
from .exceptions import MemoryNotFoundError
raise MemoryNotFoundError(f"Resource not found: {response.url}")
elif response.status_code >= 400:
try:
error_data = response.json()
message = error_data.get("detail", f"HTTP {response.status_code}")
except Exception:
message = f"HTTP {response.status_code}: {response.text}"
raise MemoryServerError(message, response.status_code)
async def health_check(self) -> HealthCheckResponse:
"""
Check the health of the memory server.
Returns:
HealthCheckResponse with current server timestamp
"""
try:
response = await self._client.get("/v1/health")
response.raise_for_status()
return HealthCheckResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
raise
async def list_sessions(
self,
limit: int = 20,
offset: int = 0,
namespace: str | None = None,
user_id: str | None = None,
) -> SessionListResponse:
"""
List available sessions with optional pagination and namespace filtering.
Args:
limit: Maximum number of sessions to return (default: 20)
offset: Offset for pagination (default: 0)
namespace: Optional namespace filter
user_id: Optional user ID filter
Returns:
SessionListResponse containing session IDs and total count
"""
params = {
"limit": str(limit),
"offset": str(offset),
}
if namespace is not None:
params["namespace"] = namespace
elif self.config.default_namespace is not None:
params["namespace"] = self.config.default_namespace
if user_id is not None:
params["user_id"] = user_id
try:
response = await self._client.get("/v1/working-memory/", params=params)
response.raise_for_status()
return SessionListResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
raise
async def get_working_memory(
self,
session_id: str,
user_id: str | None = None,
namespace: str | None = None,
window_size: int | None = None,
model_name: ModelNameLiteral | None = None,
context_window_max: int | None = None,
) -> WorkingMemoryResponse:
"""
Get working memory for a session, including messages and context.
Args:
session_id: The session ID to retrieve working memory for
user_id: The user ID to retrieve working memory for
namespace: Optional namespace for the session
window_size: Optional number of messages to include
model_name: Optional model name to determine context window size
context_window_max: Optional direct specification of context window tokens
Returns:
WorkingMemoryResponse containing messages, context and metadata
Raises:
MemoryNotFoundError: If the session is not found
MemoryServerError: For other server errors
"""
params = {}
if user_id is not None:
params["user_id"] = user_id
if namespace is not None:
params["namespace"] = namespace
elif self.config.default_namespace is not None:
params["namespace"] = self.config.default_namespace
if window_size is not None:
params["window_size"] = str(window_size)
# Use provided model_name or fall back to config default
effective_model_name = model_name or self.config.default_model_name
if effective_model_name is not None:
params["model_name"] = effective_model_name
# Use provided context_window_max or fall back to config default
effective_context_window_max = (
context_window_max or self.config.default_context_window_max
)
if effective_context_window_max is not None:
params["context_window_max"] = str(effective_context_window_max)
try:
response = await self._client.get(
f"/v1/working-memory/{session_id}", params=params
)
response.raise_for_status()
# Get the raw JSON response
response_data = response.json()
# Messages from JSON parsing are already in the correct dict format
return WorkingMemoryResponse(**response_data)
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
raise
async def put_working_memory(
self,
session_id: str,
memory: WorkingMemory,
user_id: str | None = None,
model_name: str | None = None,
context_window_max: int | None = None,
) -> WorkingMemoryResponse:
"""
Store session memory. Replaces existing session memory if it exists.
Args:
session_id: The session ID to store memory for
memory: WorkingMemory object with messages and optional context
user_id: Optional user ID for the session (overrides user_id in memory object)
model_name: Optional model name for context window management
context_window_max: Optional direct specification of context window max tokens
Returns:
WorkingMemoryResponse with the updated memory (potentially summarized if token limit exceeded)
"""
# If namespace not specified in memory but set in config, use config's namespace
if memory.namespace is None and self.config.default_namespace is not None:
memory.namespace = self.config.default_namespace
# Build query parameters for model-aware summarization
params = {}
if user_id is not None:
params["user_id"] = user_id
# Use provided model_name or fall back to config default
effective_model_name = model_name or self.config.default_model_name
if effective_model_name is not None:
params["model_name"] = effective_model_name
# Use provided context_window_max or fall back to config default
effective_context_window_max = (
context_window_max or self.config.default_context_window_max
)
if effective_context_window_max is not None:
params["context_window_max"] = str(effective_context_window_max)
try:
response = await self._client.put(
f"/v1/working-memory/{session_id}",
json=memory.model_dump(exclude_none=True, mode="json"),
params=params,
)
response.raise_for_status()
return WorkingMemoryResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
raise
async def delete_working_memory(
self, session_id: str, namespace: str | None = None, user_id: str | None = None
) -> AckResponse:
"""
Delete working memory for a session.
Args:
session_id: The session ID to delete memory for
namespace: Optional namespace for the session
user_id: Optional user ID for the session
Returns:
AckResponse indicating success
"""
params = {}
if namespace is not None:
params["namespace"] = namespace
elif self.config.default_namespace is not None:
params["namespace"] = self.config.default_namespace
if user_id is not None:
params["user_id"] = user_id
try:
response = await self._client.delete(
f"/v1/working-memory/{session_id}", params=params
)
response.raise_for_status()
return AckResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
raise
async def set_working_memory_data(
self,
session_id: str,
data: dict[str, Any],
namespace: str | None = None,
preserve_existing: bool = True,
) -> WorkingMemoryResponse:
"""
Convenience method to set JSON data in working memory.
This method allows you to easily store arbitrary JSON data in working memory
without having to construct a full WorkingMemory object.
Args:
session_id: The session ID to set data for
data: Dictionary of JSON data to store
namespace: Optional namespace for the session
preserve_existing: If True, preserve existing messages and memories (default: True)
Returns:
WorkingMemoryResponse with the updated memory
Example:
```python
# Store user preferences
await client.set_working_memory_data(
session_id="session123",
data={
"user_settings": {"theme": "dark", "language": "en"},
"preferences": {"notifications": True}
}
)
```
"""
# Get existing memory if preserving
existing_memory = None
if preserve_existing:
existing_memory = await self.get_working_memory(
session_id=session_id,
namespace=namespace,
)
# Create new working memory with the data
working_memory = WorkingMemory(
session_id=session_id,
namespace=namespace or self.config.default_namespace,
messages=existing_memory.messages if existing_memory else [],
memories=existing_memory.memories if existing_memory else [],
data=data,
context=existing_memory.context if existing_memory else None,
user_id=existing_memory.user_id if existing_memory else None,
)
return await self.put_working_memory(session_id, working_memory)
async def add_memories_to_working_memory(
self,
session_id: str,
memories: list[ClientMemoryRecord | MemoryRecord],
namespace: str | None = None,
replace: bool = False,
) -> WorkingMemoryResponse:
"""
Convenience method to add structured memories to working memory.
This method allows you to easily add MemoryRecord objects to working memory
without having to manually construct and manage the full WorkingMemory object.
Args:
session_id: The session ID to add memories to
memories: List of MemoryRecord objects to add
namespace: Optional namespace for the session
replace: If True, replace all existing memories; if False, append to existing (default: False)
Returns:
WorkingMemoryResponse with the updated memory
Example:
```python
# Add a semantic memory
await client.add_memories_to_working_memory(
session_id="session123",
memories=[
MemoryRecord(
text="User prefers dark mode",
memory_type="semantic",
topics=["preferences", "ui"],
id="pref_dark_mode"
)
]
)
```
"""
# Get existing memory
existing_memory = await self.get_working_memory(
session_id=session_id,
namespace=namespace,
)
# Determine final memories list
if replace or not existing_memory:
final_memories = memories
else:
final_memories = existing_memory.memories + memories
# Auto-generate IDs for memories that don't have them
for memory in final_memories:
if not memory.id:
memory.id = str(ulid.ULID())
# Create new working memory with the memories
working_memory = WorkingMemory(
session_id=session_id,
namespace=namespace or self.config.default_namespace,
messages=existing_memory.messages if existing_memory else [],
memories=final_memories,
data=existing_memory.data if existing_memory else {},
context=existing_memory.context if existing_memory else None,
user_id=existing_memory.user_id if existing_memory else None,
)
return await self.put_working_memory(session_id, working_memory)
async def create_long_term_memory(
self, memories: list[ClientMemoryRecord | MemoryRecord]
) -> AckResponse:
"""
Create long-term memories for later retrieval.
Args:
memories: List of MemoryRecord objects to store
Returns:
AckResponse indicating success
Raises:
MemoryServerError: If long-term memory is disabled or other errors
Example:
```python
from .models import ClientMemoryRecord
# Store user preferences as semantic memory
memories = [
ClientMemoryRecord(
text="User prefers dark mode interface",
memory_type="semantic",
topics=["preferences", "ui"],
entities=["dark_mode", "interface"]
),
ClientMemoryRecord(
text="User mentioned they work late nights frequently",
memory_type="episodic",
topics=["work_habits", "schedule"],
entities=["work", "schedule"]
)
]
response = await client.create_long_term_memory(memories)
print(f"Stored memories: {response.status}")
```
"""
# Apply default namespace if needed
if self.config.default_namespace is not None:
for memory in memories:
if memory.namespace is None:
memory.namespace = self.config.default_namespace
payload = {
"memories": [m.model_dump(exclude_none=True, mode="json") for m in memories]
}
try:
response = await self._client.post(
"/v1/long-term-memory/",
json=payload,
)
response.raise_for_status()
return AckResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
raise
async def search_long_term_memory(
self,
text: str,
session_id: SessionId | dict[str, Any] | None = None,
namespace: Namespace | dict[str, Any] | None = None,
topics: Topics | dict[str, Any] | None = None,
entities: Entities | dict[str, Any] | None = None,
created_at: CreatedAt | dict[str, Any] | None = None,
last_accessed: LastAccessed | dict[str, Any] | None = None,
user_id: UserId | dict[str, Any] | None = None,
distance_threshold: float | None = None,
memory_type: MemoryType | dict[str, Any] | None = None,
limit: int = 10,
offset: int = 0,
) -> MemoryRecordResults:
"""
Search long-term memories using semantic search and filters.
Args:
text: Search query text for semantic similarity
session_id: Optional session ID filter
namespace: Optional namespace filter
topics: Optional topics filter
entities: Optional entities filter
created_at: Optional creation date filter
last_accessed: Optional last accessed date filter
user_id: Optional user ID filter
distance_threshold: Optional distance threshold for search results
memory_type: Optional memory type filter
limit: Maximum number of results to return (default: 10)
offset: Offset for pagination (default: 0)
Returns:
MemoryRecordResults with matching memories and metadata
Raises:
MemoryServerError: If long-term memory is disabled or other errors
Example:
```python
# Search with topic and entity filters
from .filters import Topics, Entities
results = await client.search_long_term_memory(
text="meeting notes about project alpha",
topics=Topics(all=["meetings", "projects"]),
entities=Entities(any=["project_alpha", "team_meeting"]),
limit=10,
distance_threshold=0.3
)
print(f"Found {results.total} memories")
for memory in results.memories:
print(f"- {memory.text[:100]}... (distance: {memory.dist})")
```
"""
# Convert dictionary filters to their proper filter objects if needed
if isinstance(session_id, dict):
session_id = SessionId(**session_id)
if isinstance(namespace, dict):
namespace = Namespace(**namespace)
if isinstance(topics, dict):
topics = Topics(**topics)
if isinstance(entities, dict):
entities = Entities(**entities)
if isinstance(created_at, dict):
created_at = CreatedAt(**created_at)
if isinstance(last_accessed, dict):
last_accessed = LastAccessed(**last_accessed)
if isinstance(memory_type, dict):
memory_type = MemoryType(**memory_type)
# Apply default namespace if needed and no namespace filter specified
if namespace is None and self.config.default_namespace is not None:
namespace = Namespace(eq=self.config.default_namespace)
payload = {
"text": text,
"limit": limit,
"offset": offset,
}
# Add filters if provided
if session_id:
payload["session_id"] = session_id.model_dump(exclude_none=True)
if namespace:
payload["namespace"] = namespace.model_dump(exclude_none=True)
if topics:
payload["topics"] = topics.model_dump(exclude_none=True)
if entities:
payload["entities"] = entities.model_dump(exclude_none=True)
if created_at:
payload["created_at"] = created_at.model_dump(
exclude_none=True, mode="json"
)
if last_accessed:
payload["last_accessed"] = last_accessed.model_dump(
exclude_none=True, mode="json"
)
if user_id:
if isinstance(user_id, dict):
payload["user_id"] = user_id
else:
payload["user_id"] = user_id.model_dump(exclude_none=True)
if memory_type:
payload["memory_type"] = memory_type.model_dump(exclude_none=True)
if distance_threshold is not None:
payload["distance_threshold"] = distance_threshold
try:
response = await self._client.post(
"/v1/memory/search",
json=payload,
)
response.raise_for_status()
return MemoryRecordResults(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
raise
# === LLM Tool Integration ===
async def search_memory_tool(
self,
query: str,
topics: list[str] | None = None,
entities: list[str] | None = None,
memory_type: str | None = None,
max_results: int = 5,
min_relevance: float | None = None,
user_id: str | None = None,
) -> dict[str, Any]:
"""
Simplified long-term memory search designed for LLM tool use.
This method provides a streamlined interface for LLMs to search
long-term memory with common parameters and user-friendly output.
Perfect for exposing as a tool to LLM frameworks. Note: This only
searches long-term memory, not working memory.
Args:
query: The search query text
topics: Optional list of topic strings to filter by
entities: Optional list of entity strings to filter by
memory_type: Optional memory type ("episodic", "semantic", "message")
max_results: Maximum results to return (default: 5)
min_relevance: Optional minimum relevance score (0.0-1.0)
user_id: Optional user ID to filter memories by
Returns:
Dict with 'memories' list and 'summary' for LLM consumption
Example:
```python
# Simple search for LLM tool use
result = await client.search_memory_tool(
query="user preferences about UI themes",
topics=["preferences", "ui"],
max_results=3,
min_relevance=0.7
)
print(result["summary"]) # "Found 2 relevant memories for: user preferences about UI themes"
for memory in result["memories"]:
print(f"- {memory['text']} (score: {memory['relevance_score']})")
```
LLM Framework Integration:
```python
# Register as OpenAI tool
tools = [MemoryAPIClient.get_memory_search_tool_schema()]
# Handle tool calls
if tool_call.function.name == "search_memory":
args = json.loads(tool_call.function.arguments)
result = await client.search_memory_tool(**args)
```
"""
from .filters import Entities, MemoryType, Topics
# Convert simple parameters to filter objects
topics_filter = Topics(any=topics) if topics else None
entities_filter = Entities(any=entities) if entities else None
memory_type_filter = MemoryType(eq=memory_type) if memory_type else None
user_id_filter = UserId(eq=user_id) if user_id else None
# Convert min_relevance to distance_threshold (assuming 0-1 relevance maps to 1-0 distance)
distance_threshold = (
(1.0 - min_relevance) if min_relevance is not None else None
)
results = await self.search_long_term_memory(
text=query,
topics=topics_filter,
entities=entities_filter,
memory_type=memory_type_filter,
distance_threshold=distance_threshold,
limit=max_results,
user_id=user_id_filter,
)
# Format for LLM consumption
formatted_memories = []
for memory in results.memories:
formatted_memories.append(
{
"text": memory.text,
"memory_type": memory.memory_type,
"topics": memory.topics or [],
"entities": memory.entities or [],
"created_at": memory.created_at.isoformat()
if memory.created_at
else None,
"relevance_score": 1.0 - memory.dist
if hasattr(memory, "dist") and memory.dist is not None
else None,
}
)
return {
"memories": formatted_memories,
"total_found": results.total,
"query": query,
"summary": f"Found {len(formatted_memories)} relevant memories for: {query}",
}
@classmethod
def get_memory_search_tool_schema(cls) -> dict[str, Any]:
"""
Get OpenAI-compatible tool schema for memory search.
Returns tool definition that can be passed to LLM frameworks
like OpenAI, Anthropic Claude, etc. Use this to register
memory search as a tool that LLMs can call.
Returns:
Tool schema dictionary compatible with OpenAI tool calling format
Example:
```python
# Register with OpenAI
import openai
tools = [MemoryAPIClient.get_memory_search_tool_schema()]
response = await openai.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "What did I say about my preferences?"}],
tools=tools,
tool_choice="auto"
)
```
Tool Handler Example:
```python
async def handle_tool_calls(client, tool_calls):
for tool_call in tool_calls:
if tool_call.function.name == "search_memory":
args = json.loads(tool_call.function.arguments)
result = await client.search_memory_tool(**args)
# Process result and send back to LLM
yield result
```
"""
return {
"type": "function",
"function": {
"name": "search_memory",
"description": "Search long-term memory for relevant information based on a query. Use this when you need to recall past conversations, user preferences, or previously stored information. Note: This searches only long-term memory, not current working memory.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query describing what information you're looking for",
},
"topics": {
"type": "array",
"items": {"type": "string"},
"description": "Optional list of topics to filter by (e.g., ['preferences', 'work', 'personal'])",
},
"entities": {
"type": "array",
"items": {"type": "string"},
"description": "Optional list of entities to filter by (e.g., ['John', 'project_alpha', 'meetings'])",
},
"memory_type": {
"type": "string",
"enum": ["episodic", "semantic", "message"],
"description": "Optional filter by memory type: 'episodic' (events/experiences), 'semantic' (facts/knowledge), 'message' (conversation history)",
},
"max_results": {
"type": "integer",
"minimum": 1,
"maximum": 20,
"default": 5,
"description": "Maximum number of results to return",
},
"min_relevance": {
"type": "number",
"minimum": 0.0,
"maximum": 1.0,
"description": "Optional minimum relevance score (0.0-1.0, higher = more relevant)",
},
"user_id": {
"type": "string",
"description": "Optional user ID to filter memories by (e.g., 'user123')",
},
},
"required": ["query"],
},
},
}
# === Working Memory Tool Integration ===
async def get_working_memory_tool(
self,
session_id: str,
namespace: str | None = None,
user_id: str | None = None,
) -> dict[str, Any]:
"""
Get current working memory state formatted for LLM consumption.
This method provides a summary of the current working memory state
that's easy for LLMs to understand and work with.
Args:
session_id: The session ID to get memory for
namespace: Optional namespace for the session
user_id: Optional user ID for the session
Returns:
Dict with formatted working memory information
Example:
```python
# Get working memory state for LLM
memory_state = await client.get_working_memory_tool(
session_id="current_session"
)
print(memory_state["summary"]) # Human-readable summary
print(f"Messages: {memory_state['message_count']}")
print(f"Memories: {len(memory_state['memories'])}")
```
"""
try:
result = await self.get_working_memory(
session_id=session_id,
namespace=namespace or self.config.default_namespace,
user_id=user_id,
)
# Format for LLM consumption
message_count = len(result.messages) if result.messages else 0
memory_count = len(result.memories) if result.memories else 0
data_keys = list(result.data.keys()) if result.data else []
# Create formatted memories list
formatted_memories = []
if result.memories:
for memory in result.memories:
formatted_memories.append(
{
"text": memory.text,
"memory_type": memory.memory_type,
"topics": memory.topics or [],
"entities": memory.entities or [],
"created_at": memory.created_at.isoformat()
if memory.created_at
else None,
}
)
return {
"session_id": session_id,
"message_count": message_count,
"memory_count": memory_count,
"memories": formatted_memories,
"data_keys": data_keys,
"data": result.data or {},
"context": result.context,
"summary": f"Session has {message_count} messages, {memory_count} stored memories, and {len(data_keys)} data entries",
}
except Exception as e:
return {
"session_id": session_id,
"error": str(e),
"summary": f"Error retrieving working memory: {str(e)}",
}
async def add_memory_tool(
self,
session_id: str,
text: str,
memory_type: str,
topics: list[str] | None = None,
entities: list[str] | None = None,
namespace: str | None = None,
user_id: str | None = None,
) -> dict[str, Any]:
"""
Add a structured memory to working memory with LLM-friendly response.
This method allows LLMs to store important information as structured
memories that will be automatically managed by the memory server.
Args:
session_id: The session ID to add memory to
text: The memory content to store
memory_type: Type of memory ("episodic", "semantic", "message")
topics: Optional topics for categorization
entities: Optional entities mentioned
namespace: Optional namespace for the session
user_id: Optional user ID for the session
Returns:
Dict with success/failure information
Example:
```python
# Store user preference as semantic memory
result = await client.add_memory_tool(
session_id="current_session",
text="User prefers vegetarian restaurants",
memory_type="semantic",
topics=["preferences", "dining"],
entities=["vegetarian", "restaurants"]
)
print(result["summary"]) # "Successfully stored semantic memory"
```
"""
try:
# Create memory record
memory = ClientMemoryRecord(
text=text,
memory_type=MemoryTypeEnum(memory_type),
topics=topics,
entities=entities,
namespace=namespace or self.config.default_namespace,
user_id=user_id,
)
# Add to working memory
await self.add_memories_to_working_memory(
session_id=session_id,
memories=[memory],
namespace=namespace or self.config.default_namespace,
replace=False,
)
return {
"success": True,