-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathclient.py
More file actions
3539 lines (3081 loc) · 135 KB
/
client.py
File metadata and controls
3539 lines (3081 loc) · 135 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 logging # noqa: F401
import re
import warnings
from collections.abc import AsyncIterator, Sequence
from typing import TYPE_CHECKING, Any, Literal, NoReturn, TypedDict
if TYPE_CHECKING:
from typing_extensions import Self
import httpx
from pydantic import BaseModel
from ulid import ULID
from .exceptions import (
MemoryClientError,
MemoryNotFoundError,
MemoryServerError,
MemoryValidationError,
)
from .filters import (
CreatedAt,
Entities,
LastAccessed,
MemoryType,
Namespace,
SessionId,
Topics,
UserId,
)
from .models import (
AckResponse,
ClientMemoryRecord,
CreateSummaryViewRequest,
ForgetPolicy,
ForgetResponse,
HealthCheckResponse,
MemoryMessage,
MemoryRecord,
MemoryRecordResults,
MemoryStrategyConfig,
MemoryTypeEnum,
ModelNameLiteral,
RecencyConfig,
SearchModeEnum,
SessionListResponse,
SummaryView,
SummaryViewPartitionResult,
Task,
WorkingMemory,
WorkingMemoryResponse,
)
from .tool_schema import ToolSchema, ToolSchemaCollection
# === Tool Name Constants ===
# Current tool names
TOOL_SEARCH_MEMORY = "search_memory"
TOOL_GET_OR_CREATE_WORKING_MEMORY = "get_or_create_working_memory"
TOOL_LAZILY_CREATE_LONG_TERM_MEMORY = "lazily_create_long_term_memory"
TOOL_UPDATE_WORKING_MEMORY_DATA = "update_working_memory_data"
TOOL_GET_LONG_TERM_MEMORY = "get_long_term_memory"
TOOL_EAGERLY_CREATE_LONG_TERM_MEMORY = "eagerly_create_long_term_memory"
TOOL_EDIT_LONG_TERM_MEMORY = "edit_long_term_memory"
TOOL_DELETE_LONG_TERM_MEMORIES = "delete_long_term_memories"
TOOL_GET_CURRENT_DATETIME = "get_current_datetime"
# Deprecated tool names (aliases for backwards compatibility)
TOOL_ADD_MEMORY_TO_WORKING_MEMORY = "add_memory_to_working_memory" # Deprecated
TOOL_CREATE_LONG_TERM_MEMORY = "create_long_term_memory" # Deprecated
# === 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
"""
from . import __version__
self.config = config
self._client = httpx.AsyncClient(
base_url=config.base_url,
timeout=config.timeout,
headers={
"User-Agent": f"agent-memory-client/{__version__}",
"X-Client-Version": __version__,
},
)
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) -> NoReturn:
"""Handle HTTP errors and convert to appropriate exceptions.
This method always raises an exception and never returns normally.
"""
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)
# This should never be reached, but mypy needs to know this never returns
raise MemoryServerError(
f"Unexpected status code: {response.status_code}", 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)
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)
async def get_working_memory(
self,
session_id: str,
user_id: str | None = None,
namespace: str | None = None,
model_name: ModelNameLiteral | None = None,
context_window_max: int | None = None,
) -> WorkingMemoryResponse:
"""
Get working memory for a session, including messages and context.
.. deprecated:: next_version
This method is deprecated because it doesn't inform you whether
a session was created or found existing. Use `get_or_create_working_memory`
instead, which returns a tuple of (memory, created) for better session management.
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
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
"""
import warnings
warnings.warn(
"get_working_memory is deprecated and will be removed in a future version. "
"Use get_or_create_working_memory instead, which returns both the memory and "
"whether the session was created or found existing.",
DeprecationWarning,
stacklevel=2,
)
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
# 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)
async def get_or_create_working_memory(
self,
session_id: str,
user_id: str | None = None,
namespace: str | None = None,
model_name: ModelNameLiteral | None = None,
context_window_max: int | None = None,
long_term_memory_strategy: MemoryStrategyConfig | None = None,
) -> tuple[bool, WorkingMemory]:
"""
Get working memory for a session, creating it if it doesn't exist.
This method returns a tuple with the creation status and the working memory.
This is important for applications that need to know if they're working with
a new session or an existing one.
Args:
session_id: The session ID to retrieve or create working memory for
user_id: The user ID to retrieve working memory for
namespace: Optional namespace for the session
model_name: Optional model name to determine context window size
context_window_max: Optional direct specification of context window tokens
long_term_memory_strategy: Optional strategy configuration for memory extraction
when promoting to long-term memory
Returns:
Tuple of (created: bool, memory: WorkingMemory)
- created: True if the session was created, False if it already existed
- memory: The WorkingMemory object
Example:
```python
# Get or create session memory
created, memory = await client.get_or_create_working_memory(
session_id="chat_session_123",
user_id="user_456"
)
if created:
logging.info("Created new session")
else:
logging.info("Found existing session")
logging.info(f"Session has {len(memory.messages)} messages")
# With memory extraction strategy options
created, memory = await client.get_or_create_working_memory(
session_id="chat_session_456",
user_id="user_789",
long_term_memory_strategy=MemoryStrategyConfig(
strategy="summary",
config={"max_summary_length": 500}
)
)
```
"""
try:
# Try to get existing working memory first
existing_memory = await self.get_working_memory(
session_id=session_id,
user_id=user_id,
namespace=namespace,
model_name=model_name,
context_window_max=context_window_max,
)
# Check if this is an unsaved session (deprecated behavior for old clients)
if getattr(existing_memory, "unsaved", None) is True:
# This is an unsaved session - we need to create it properly
empty_memory = WorkingMemory(
session_id=session_id,
namespace=namespace or self.config.default_namespace,
messages=[],
memories=[],
data={},
user_id=user_id,
)
created_memory = await self.put_working_memory(
session_id=session_id,
memory=empty_memory,
user_id=user_id,
model_name=model_name,
context_window_max=context_window_max,
)
return (True, created_memory)
return (False, existing_memory)
except (httpx.HTTPStatusError, MemoryNotFoundError) as e:
# Handle both HTTPStatusError and MemoryNotFoundError for 404s
is_404 = False
if isinstance(e, httpx.HTTPStatusError):
is_404 = e.response.status_code == 404
elif isinstance(e, MemoryNotFoundError):
is_404 = True
if is_404:
# Session doesn't exist, create it
empty_memory = WorkingMemory(
session_id=session_id,
namespace=namespace or self.config.default_namespace,
messages=[],
memories=[],
data={},
user_id=user_id,
long_term_memory_strategy=long_term_memory_strategy
or MemoryStrategyConfig(),
)
created_memory = await self.put_working_memory(
session_id=session_id,
memory=empty_memory,
user_id=user_id,
model_name=model_name,
context_window_max=context_window_max,
)
return (True, created_memory)
else:
# Re-raise other HTTP errors
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)
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)
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:
try:
created, existing_memory = await self.get_or_create_working_memory(
session_id=session_id,
namespace=namespace,
)
except Exception:
existing_memory = None
# 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: Sequence[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
created, existing_memory = await self.get_or_create_working_memory(
session_id=session_id,
namespace=namespace,
)
# Determine final memories list
if replace or not existing_memory:
final_memories = list(memories)
else:
final_memories = existing_memory.memories + list(memories)
# Auto-generate IDs for memories that don't have them
for memory in final_memories:
if not memory.id:
memory.id = str(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: Sequence[ClientMemoryRecord | MemoryRecord],
deduplicate: bool = True,
) -> AckResponse:
"""
Create long-term memories for later retrieval.
Args:
memories: List of MemoryRecord objects to store
deduplicate: Whether to deduplicate memories before indexing (default: True)
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)
logging.info(f"Stored memories: {response.status}")
```
"""
# Apply default namespace and ensure IDs are present
if self.config.default_namespace is not None:
for memory in memories:
if memory.namespace is None:
memory.namespace = self.config.default_namespace
# Ensure all memories have IDs
for memory in memories:
if not memory.id:
memory.id = str(ULID())
payload = {
"memories": [
m.model_dump(exclude_none=True, mode="json") for m in memories
],
"deduplicate": deduplicate,
}
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)
async def delete_long_term_memories(self, memory_ids: Sequence[str]) -> AckResponse:
"""
Delete long-term memories.
Args:
memory_ids: List of memory IDs to delete
Returns:
AckResponse indicating success
"""
params = {"memory_ids": list(memory_ids)}
try:
response = await self._client.delete(
"/v1/long-term-memory",
params=params,
)
response.raise_for_status()
return AckResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
async def get_long_term_memory(self, memory_id: str) -> MemoryRecord:
"""
Get a specific long-term memory by its ID.
Args:
memory_id: The unique ID of the memory to retrieve
Returns:
MemoryRecord object containing the memory details
Raises:
MemoryClientException: If memory not found or request fails
"""
try:
response = await self._client.get(f"/v1/long-term-memory/{memory_id}")
response.raise_for_status()
return MemoryRecord(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
async def edit_long_term_memory(
self, memory_id: str, updates: dict[str, Any]
) -> MemoryRecord:
"""
Edit an existing long-term memory by its ID.
Args:
memory_id: The unique ID of the memory to edit
updates: Dictionary of fields to update (text, topics, entities, memory_type, etc.)
Returns:
MemoryRecord object containing the updated memory
Raises:
MemoryClientException: If memory not found or update fails
"""
try:
response = await self._client.patch(
f"/v1/long-term-memory/{memory_id}",
json=updates,
)
response.raise_for_status()
return MemoryRecord(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
# ==================== Forget ====================
async def forget_long_term_memories(
self,
policy: ForgetPolicy,
namespace: str | None = None,
user_id: str | None = None,
session_id: str | None = None,
limit: int | None = None,
dry_run: bool = False,
pinned_ids: list[str] | None = None,
) -> ForgetResponse:
"""
Run a forgetting pass with the provided policy.
Args:
policy: The forget policy defining what to forget
namespace: Optional namespace filter
user_id: Optional user ID filter
session_id: Optional session ID filter
limit: Optional limit on number of memories to process
dry_run: If True, don't actually delete, just return what would be deleted
pinned_ids: Optional list of memory IDs to exclude from forgetting
Returns:
ForgetResponse with scanned count, deleted count, and deleted IDs
"""
params = {}
if namespace is not None:
params["namespace"] = namespace
if user_id is not None:
params["user_id"] = user_id
if session_id is not None:
params["session_id"] = session_id
if limit is not None:
params["limit"] = limit
if dry_run:
params["dry_run"] = dry_run
body = {"policy": policy.model_dump(exclude_none=True)}
if pinned_ids:
body["pinned_ids"] = pinned_ids
try:
response = await self._client.post(
"/v1/long-term-memory/forget",
params=params,
json=body,
)
response.raise_for_status()
return ForgetResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
# ==================== Summary Views ====================
async def list_summary_views(self) -> list[SummaryView]:
"""
List all summary views.
Returns:
List of SummaryView objects
"""
try:
response = await self._client.get("/v1/summary-views")
response.raise_for_status()
return [SummaryView(**v) for v in response.json()]
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
async def create_summary_view(
self, request: CreateSummaryViewRequest
) -> SummaryView:
"""
Create a new summary view.
Args:
request: The summary view configuration
Returns:
The created SummaryView object
"""
try:
response = await self._client.post(
"/v1/summary-views",
json=request.model_dump(exclude_none=True),
)
response.raise_for_status()
return SummaryView(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
async def get_summary_view(self, view_id: str) -> SummaryView | None:
"""
Get a summary view by ID.
Args:
view_id: The unique view ID
Returns:
SummaryView object or None if not found
"""
try:
response = await self._client.get(f"/v1/summary-views/{view_id}")
response.raise_for_status()
return SummaryView(**response.json())
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
return None
self._handle_http_error(e.response)
async def delete_summary_view(self, view_id: str) -> AckResponse:
"""
Delete a summary view.
Args:
view_id: The unique view ID
Returns:
AckResponse indicating success
"""
try:
response = await self._client.delete(f"/v1/summary-views/{view_id}")
response.raise_for_status()
return AckResponse(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
async def run_summary_view_partition(
self, view_id: str, group: dict[str, str]
) -> SummaryViewPartitionResult:
"""
Run a single summary view partition.
Args:
view_id: The unique view ID
group: Concrete values for the view's group_by fields
Returns:
SummaryViewPartitionResult with the computed summary
"""
try:
response = await self._client.post(
f"/v1/summary-views/{view_id}/partitions/run",
json={"group": group},
)
response.raise_for_status()
return SummaryViewPartitionResult(**response.json())
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
async def list_summary_view_partitions(
self,
view_id: str,
namespace: str | None = None,
user_id: str | None = None,
session_id: str | None = None,
memory_type: str | None = None,
) -> list[SummaryViewPartitionResult]:
"""
List summary view partitions.
Args:
view_id: The unique view ID
namespace: Optional namespace filter
user_id: Optional user ID filter
session_id: Optional session ID filter
memory_type: Optional memory type filter
Returns:
List of SummaryViewPartitionResult objects
"""
params = {}
if namespace is not None:
params["namespace"] = namespace
if user_id is not None:
params["user_id"] = user_id
if session_id is not None:
params["session_id"] = session_id
if memory_type is not None:
params["memory_type"] = memory_type
try:
response = await self._client.get(
f"/v1/summary-views/{view_id}/partitions",
params=params,
)
response.raise_for_status()
return [SummaryViewPartitionResult(**p) for p in response.json()]
except httpx.HTTPStatusError as e:
self._handle_http_error(e.response)
async def run_summary_view(self, view_id: str, force: bool = False) -> Task:
"""
Run a full summary view (async task).
Args:
view_id: The unique view ID
force: Force recomputation even if cached
Returns: