memorysync 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ *.iml
2
+ .gradle
3
+ /local.properties
4
+ /.idea/caches
5
+ /.idea/libraries
6
+ /.idea/modules.xml
7
+ /.idea/workspace.xml
8
+ /.idea/navEditor.xml
9
+ /.idea/assetWizardSettings.xml
10
+ .DS_Store
11
+ /build
12
+ /captures
13
+ .externalNativeBuild
14
+ .cxx
15
+ local.properties
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MemorySync
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: memorysync
3
+ Version: 1.0.0
4
+ Summary: Official Python client for the MemorySync API.
5
+ Project-URL: Homepage, https://memorysync.dev
6
+ Project-URL: Documentation, https://memorysync.dev/docs
7
+ Author: MemorySync
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: client,memory,memorysync,sdk
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.9
22
+ Requires-Dist: httpx<1.0,>=0.25
23
+ Requires-Dist: typing-extensions>=4.5; python_version < '3.11'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # memorysync
27
+
28
+ Official Python client for the MemorySync API. Sync and async, no surprises.
29
+
30
+ ```bash
31
+ pip install memorysync
32
+ ```
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ from memorysync import MemorySyncClient
38
+
39
+ ms = MemorySyncClient(
40
+ api_key="...",
41
+ base_url="https://api.memorysync.dev",
42
+ project_id="proj_xxxxxxxxxxxxxxxx", # optional
43
+ end_user_id="user_42", # optional
44
+ )
45
+
46
+ ms.add("User prefers dark mode.")
47
+
48
+ result = ms.query("ui preferences", k=5)
49
+ for m in result.memories:
50
+ print(m.id, m.text)
51
+ ```
52
+
53
+ ## Async usage
54
+
55
+ ```python
56
+ import asyncio
57
+ from memorysync import AsyncMemorySyncClient
58
+
59
+ async def main():
60
+ async with AsyncMemorySyncClient(api_key="...", base_url="...") as ms:
61
+ result = await ms.query("ui preferences", k=5)
62
+ print(result.memories)
63
+
64
+ asyncio.run(main())
65
+ ```
66
+
67
+ Use `MemorySyncClient` as a context manager when you want deterministic
68
+ connection cleanup:
69
+
70
+ ```python
71
+ with MemorySyncClient(api_key="...", base_url="...") as ms:
72
+ ms.add("...")
73
+ ```
74
+
75
+ ## Configuration
76
+
77
+ | Argument | Required | Description |
78
+ | --------------- | -------- | -------------------------------------------------------------------------------------------- |
79
+ | `api_key` | yes | Sent as `X-API-Key`. Provision in your MemorySync dashboard. |
80
+ | `base_url` | yes | Deployment URL of your MemorySync instance. |
81
+ | `project_id` | no | Pin every request to a project (`X-Project-ID`). Format: `proj_` + 16 hex chars. |
82
+ | `end_user_id` | no | Identify which of *your* users this client speaks for (`X-End-User-ID`). |
83
+ | `timeout` | no | Per-request timeout in seconds. Default `30.0`. |
84
+ | `transport` | no | Inject a custom `httpx` transport (tests, retries, proxies). |
85
+
86
+ `end_user_id` can also be passed per-call on `add()` to override the client default.
87
+
88
+ ## Methods
89
+
90
+ Every method maps 1:1 to a real HTTP route. The two clients share the same
91
+ surface; only the call style differs (sync vs `await`).
92
+
93
+ | Method | Route |
94
+ | -------------------------------------------- | -------------------------------------- |
95
+ | `add(text, **opts)` | `POST /memory/add` |
96
+ | `bulk_add(items, *, deduplicate=True)` | `POST /memory/bulk-add` |
97
+ | `query(query, *, k=None, ...)` | `POST /memory/query` |
98
+ | `get(memory_id)` | `GET /memory/{id}` |
99
+ | `update(memory_id, **fields)` | `PATCH /memory/{id}` |
100
+ | `forget(memory_ids, *, reason=None)` | `DELETE /memory/forget` |
101
+ | `summarize(memory_ids, *, lossless=False)` | `POST /memory/summarize` |
102
+ | `compose(prompt_template, *, recall_k=None)` | `POST /memory/compose` |
103
+ | `export_all()` | `GET /memory/export` |
104
+ | `create_relation(from_id, **opts)` | `POST /memory/{id}/relations` |
105
+
106
+ ### `add` returns one of two shapes
107
+
108
+ `add()` runs through MemorySync's extraction pipeline, so input that carries no
109
+ high-value content is intentionally skipped. Branch on the type of the result:
110
+
111
+ ```python
112
+ from memorysync import AddSkippedResponse, Memory
113
+
114
+ result = ms.add("User prefers dark mode.")
115
+ if isinstance(result, AddSkippedResponse):
116
+ print("skipped:", result.reason)
117
+ else:
118
+ assert isinstance(result, Memory)
119
+ print(result.id, result.text)
120
+ ```
121
+
122
+ ## Errors
123
+
124
+ Every non-2xx response raises a typed subclass of `MemorySyncError`:
125
+
126
+ | Class | When |
127
+ | ----------------- | ------------------------------------------- |
128
+ | `AuthError` | `401` / `403` — bad key, missing scope. |
129
+ | `ValidationError` | `400` / `409` / `422`. |
130
+ | `NotFoundError` | `404` — record not visible to the caller. |
131
+ | `RateLimitError` | `429` — read `err.retry_after_seconds`. |
132
+ | `ServerError` | `5xx`. |
133
+ | `MemorySyncError` | Network errors, timeouts, anything else. |
134
+
135
+ Every error carries `status_code`, `response`, and the server-issued
136
+ `request_id` (when present) for support escalation.
137
+
138
+ ```python
139
+ import time
140
+ from memorysync import RateLimitError
141
+
142
+ try:
143
+ ms.add("...")
144
+ except RateLimitError as e:
145
+ time.sleep(e.retry_after_seconds)
146
+ ```
147
+
148
+ ## License
149
+
150
+ MIT
@@ -0,0 +1,125 @@
1
+ # memorysync
2
+
3
+ Official Python client for the MemorySync API. Sync and async, no surprises.
4
+
5
+ ```bash
6
+ pip install memorysync
7
+ ```
8
+
9
+ ## Quick start
10
+
11
+ ```python
12
+ from memorysync import MemorySyncClient
13
+
14
+ ms = MemorySyncClient(
15
+ api_key="...",
16
+ base_url="https://api.memorysync.dev",
17
+ project_id="proj_xxxxxxxxxxxxxxxx", # optional
18
+ end_user_id="user_42", # optional
19
+ )
20
+
21
+ ms.add("User prefers dark mode.")
22
+
23
+ result = ms.query("ui preferences", k=5)
24
+ for m in result.memories:
25
+ print(m.id, m.text)
26
+ ```
27
+
28
+ ## Async usage
29
+
30
+ ```python
31
+ import asyncio
32
+ from memorysync import AsyncMemorySyncClient
33
+
34
+ async def main():
35
+ async with AsyncMemorySyncClient(api_key="...", base_url="...") as ms:
36
+ result = await ms.query("ui preferences", k=5)
37
+ print(result.memories)
38
+
39
+ asyncio.run(main())
40
+ ```
41
+
42
+ Use `MemorySyncClient` as a context manager when you want deterministic
43
+ connection cleanup:
44
+
45
+ ```python
46
+ with MemorySyncClient(api_key="...", base_url="...") as ms:
47
+ ms.add("...")
48
+ ```
49
+
50
+ ## Configuration
51
+
52
+ | Argument | Required | Description |
53
+ | --------------- | -------- | -------------------------------------------------------------------------------------------- |
54
+ | `api_key` | yes | Sent as `X-API-Key`. Provision in your MemorySync dashboard. |
55
+ | `base_url` | yes | Deployment URL of your MemorySync instance. |
56
+ | `project_id` | no | Pin every request to a project (`X-Project-ID`). Format: `proj_` + 16 hex chars. |
57
+ | `end_user_id` | no | Identify which of *your* users this client speaks for (`X-End-User-ID`). |
58
+ | `timeout` | no | Per-request timeout in seconds. Default `30.0`. |
59
+ | `transport` | no | Inject a custom `httpx` transport (tests, retries, proxies). |
60
+
61
+ `end_user_id` can also be passed per-call on `add()` to override the client default.
62
+
63
+ ## Methods
64
+
65
+ Every method maps 1:1 to a real HTTP route. The two clients share the same
66
+ surface; only the call style differs (sync vs `await`).
67
+
68
+ | Method | Route |
69
+ | -------------------------------------------- | -------------------------------------- |
70
+ | `add(text, **opts)` | `POST /memory/add` |
71
+ | `bulk_add(items, *, deduplicate=True)` | `POST /memory/bulk-add` |
72
+ | `query(query, *, k=None, ...)` | `POST /memory/query` |
73
+ | `get(memory_id)` | `GET /memory/{id}` |
74
+ | `update(memory_id, **fields)` | `PATCH /memory/{id}` |
75
+ | `forget(memory_ids, *, reason=None)` | `DELETE /memory/forget` |
76
+ | `summarize(memory_ids, *, lossless=False)` | `POST /memory/summarize` |
77
+ | `compose(prompt_template, *, recall_k=None)` | `POST /memory/compose` |
78
+ | `export_all()` | `GET /memory/export` |
79
+ | `create_relation(from_id, **opts)` | `POST /memory/{id}/relations` |
80
+
81
+ ### `add` returns one of two shapes
82
+
83
+ `add()` runs through MemorySync's extraction pipeline, so input that carries no
84
+ high-value content is intentionally skipped. Branch on the type of the result:
85
+
86
+ ```python
87
+ from memorysync import AddSkippedResponse, Memory
88
+
89
+ result = ms.add("User prefers dark mode.")
90
+ if isinstance(result, AddSkippedResponse):
91
+ print("skipped:", result.reason)
92
+ else:
93
+ assert isinstance(result, Memory)
94
+ print(result.id, result.text)
95
+ ```
96
+
97
+ ## Errors
98
+
99
+ Every non-2xx response raises a typed subclass of `MemorySyncError`:
100
+
101
+ | Class | When |
102
+ | ----------------- | ------------------------------------------- |
103
+ | `AuthError` | `401` / `403` — bad key, missing scope. |
104
+ | `ValidationError` | `400` / `409` / `422`. |
105
+ | `NotFoundError` | `404` — record not visible to the caller. |
106
+ | `RateLimitError` | `429` — read `err.retry_after_seconds`. |
107
+ | `ServerError` | `5xx`. |
108
+ | `MemorySyncError` | Network errors, timeouts, anything else. |
109
+
110
+ Every error carries `status_code`, `response`, and the server-issued
111
+ `request_id` (when present) for support escalation.
112
+
113
+ ```python
114
+ import time
115
+ from memorysync import RateLimitError
116
+
117
+ try:
118
+ ms.add("...")
119
+ except RateLimitError as e:
120
+ time.sleep(e.retry_after_seconds)
121
+ ```
122
+
123
+ ## License
124
+
125
+ MIT
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "memorysync"
7
+ version = "1.0.0"
8
+ description = "Official Python client for the MemorySync API."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "MemorySync" }]
13
+ keywords = ["memorysync", "memory", "sdk", "client"]
14
+ classifiers = [
15
+ "Development Status :: 5 - Production/Stable",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.9",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Software Development :: Libraries :: Python Modules",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = [
27
+ "httpx>=0.25,<1.0",
28
+ "typing-extensions>=4.5; python_version < '3.11'",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://memorysync.dev"
33
+ Documentation = "https://memorysync.dev/docs"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/memorysync"]
37
+
38
+ [tool.hatch.build.targets.sdist]
39
+ include = [
40
+ "src/memorysync",
41
+ "README.md",
42
+ "LICENSE",
43
+ "pyproject.toml",
44
+ ]
@@ -0,0 +1,46 @@
1
+ """Public package surface for the MemorySync Python SDK."""
2
+
3
+ from ._version import __version__
4
+ from .errors import (
5
+ AuthError,
6
+ MemorySyncError,
7
+ NotFoundError,
8
+ RateLimitError,
9
+ ServerError,
10
+ ValidationError,
11
+ )
12
+ from .types import (
13
+ AddSkippedResponse,
14
+ BulkAddItem,
15
+ BulkAddItemResult,
16
+ BulkAddResponse,
17
+ ComposeResponse,
18
+ ExportResponse,
19
+ Memory,
20
+ QueryResponse,
21
+ Relation,
22
+ RelationshipType,
23
+ )
24
+ from .client import AsyncMemorySyncClient, MemorySyncClient
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "MemorySyncClient",
29
+ "AsyncMemorySyncClient",
30
+ "Memory",
31
+ "QueryResponse",
32
+ "BulkAddItem",
33
+ "BulkAddItemResult",
34
+ "BulkAddResponse",
35
+ "AddSkippedResponse",
36
+ "ComposeResponse",
37
+ "ExportResponse",
38
+ "Relation",
39
+ "RelationshipType",
40
+ "MemorySyncError",
41
+ "AuthError",
42
+ "ValidationError",
43
+ "NotFoundError",
44
+ "RateLimitError",
45
+ "ServerError",
46
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,752 @@
1
+ """Sync and async HTTP clients for the MemorySync API.
2
+
3
+ Both clients share an internal ``_RequestBuilder`` that constructs URLs,
4
+ headers, and bodies, and an ``_ErrorMapper`` that converts HTTP failures
5
+ into the typed exception hierarchy in ``errors.py``. Only the transport
6
+ differs (``httpx.Client`` vs ``httpx.AsyncClient``).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Union
12
+
13
+ import httpx
14
+
15
+ from ._version import __version__
16
+ from .errors import (
17
+ AuthError,
18
+ MemorySyncError,
19
+ NotFoundError,
20
+ RateLimitError,
21
+ ServerError,
22
+ ValidationError,
23
+ )
24
+ from .types import (
25
+ AddResult,
26
+ AddSkippedResponse,
27
+ BulkAddItem,
28
+ BulkAddItemResult,
29
+ BulkAddResponse,
30
+ ComposeResponse,
31
+ ExportResponse,
32
+ Memory,
33
+ QueryResponse,
34
+ Relation,
35
+ RelationshipType,
36
+ )
37
+
38
+
39
+ _USER_AGENT = f"memorysync-sdk-py/{__version__}"
40
+ _BULK_LIMIT = 50
41
+
42
+
43
+ def _strip_none(d: Dict[str, Any]) -> Dict[str, Any]:
44
+ return {k: v for k, v in d.items() if v is not None}
45
+
46
+
47
+ def _camel_to_snake_filters(filters: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
48
+ if not filters:
49
+ return None
50
+ return _strip_none(
51
+ {
52
+ "memory_type": filters.get("memory_type"),
53
+ "source": filters.get("source"),
54
+ "tags": filters.get("tags"),
55
+ "since": filters.get("since"),
56
+ "until": filters.get("until"),
57
+ "include_summaries": filters.get("include_summaries"),
58
+ "tier": filters.get("tier"),
59
+ }
60
+ )
61
+
62
+
63
+ def _extract_detail(body: Any) -> Optional[str]:
64
+ if not isinstance(body, dict):
65
+ return None
66
+ if isinstance(body.get("detail"), str):
67
+ return body["detail"]
68
+ err = body.get("error")
69
+ if isinstance(err, dict) and isinstance(err.get("message"), str):
70
+ return err["message"]
71
+ detail = body.get("detail")
72
+ if isinstance(detail, list) and detail:
73
+ first = detail[0]
74
+ if isinstance(first, dict) and isinstance(first.get("msg"), str):
75
+ return first["msg"]
76
+ return None
77
+
78
+
79
+ def _extract_retry_after(body: Any) -> float:
80
+ if not isinstance(body, dict):
81
+ return 0.0
82
+ if isinstance(body.get("retry_after"), (int, float)):
83
+ return float(body["retry_after"])
84
+ err = body.get("error")
85
+ if isinstance(err, dict) and isinstance(err.get("retry_after"), (int, float)):
86
+ return float(err["retry_after"])
87
+ return 0.0
88
+
89
+
90
+ def _raise_for_status(status: int, body: Any, request_id: Optional[str]) -> None:
91
+ detail = _extract_detail(body)
92
+ kwargs: Dict[str, Any] = {"status_code": status, "response": body, "request_id": request_id}
93
+ if status in (401, 403):
94
+ raise AuthError(detail or ("Unauthenticated" if status == 401 else "Forbidden"), **kwargs)
95
+ if status == 404:
96
+ raise NotFoundError(detail or "Not found", **kwargs)
97
+ if status in (400, 409, 422):
98
+ raise ValidationError(detail or "Validation error", **kwargs)
99
+ if status == 429:
100
+ raise RateLimitError(
101
+ detail or "Rate limited",
102
+ retry_after_seconds=_extract_retry_after(body),
103
+ **kwargs,
104
+ )
105
+ if status >= 500:
106
+ raise ServerError(detail or f"Server error ({status})", **kwargs)
107
+ raise MemorySyncError(detail or f"Unexpected status {status}", **kwargs)
108
+
109
+
110
+ # ─────────────────────────────────────────────────────────────────────
111
+ # Request shaping (shared by sync & async clients)
112
+ # ─────────────────────────────────────────────────────────────────────
113
+
114
+
115
+ class _RequestBuilder:
116
+ """Pure functions that turn high-level method args into HTTP payloads."""
117
+
118
+ @staticmethod
119
+ def add(
120
+ text: str,
121
+ *,
122
+ source: Optional[str],
123
+ tags: Optional[Sequence[str]],
124
+ importance: Optional[float],
125
+ session_id: Optional[str],
126
+ metadata: Optional[Dict[str, Any]],
127
+ end_user_id: Optional[str],
128
+ ) -> Dict[str, Any]:
129
+ return _strip_none(
130
+ {
131
+ "text": text,
132
+ "source": source,
133
+ "tags": list(tags) if tags is not None else None,
134
+ "importance": importance,
135
+ "session_id": session_id,
136
+ "metadata": metadata,
137
+ "end_user_id": end_user_id,
138
+ }
139
+ )
140
+
141
+ @staticmethod
142
+ def bulk_add(items: Sequence[BulkAddItem], deduplicate: bool) -> Dict[str, Any]:
143
+ return {
144
+ "items": [i.to_dict() for i in items],
145
+ "deduplicate": deduplicate,
146
+ }
147
+
148
+ @staticmethod
149
+ def query(
150
+ query: str,
151
+ *,
152
+ k: Optional[int],
153
+ filters: Optional[Dict[str, Any]],
154
+ session_id: Optional[str],
155
+ traversal_depth: Optional[int],
156
+ ) -> Dict[str, Any]:
157
+ return _strip_none(
158
+ {
159
+ "query": query,
160
+ "k": k,
161
+ "filters": _camel_to_snake_filters(filters),
162
+ "session_id": session_id,
163
+ "traversal_depth": traversal_depth,
164
+ }
165
+ )
166
+
167
+
168
+ # ─────────────────────────────────────────────────────────────────────
169
+ # Sync client
170
+ # ─────────────────────────────────────────────────────────────────────
171
+
172
+
173
+ class MemorySyncClient:
174
+ """Synchronous client. Use :class:`AsyncMemorySyncClient` for asyncio code."""
175
+
176
+ def __init__(
177
+ self,
178
+ api_key: str,
179
+ base_url: str,
180
+ *,
181
+ project_id: Optional[str] = None,
182
+ end_user_id: Optional[str] = None,
183
+ timeout: float = 30.0,
184
+ transport: Optional[httpx.BaseTransport] = None,
185
+ ) -> None:
186
+ if not api_key or not api_key.strip():
187
+ raise ValueError("api_key is required")
188
+ if not base_url or not base_url.strip():
189
+ raise ValueError("base_url is required")
190
+ self._api_key = api_key
191
+ self._base_url = base_url.rstrip("/")
192
+ self._project_id = project_id
193
+ self._end_user_id = end_user_id
194
+ self._http = httpx.Client(timeout=timeout, transport=transport)
195
+
196
+ def __enter__(self) -> "MemorySyncClient":
197
+ return self
198
+
199
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
200
+ self.close()
201
+
202
+ def close(self) -> None:
203
+ self._http.close()
204
+
205
+ # ── HTTP plumbing ────────────────────────────────────────────────
206
+
207
+ def _headers(self, end_user_override: Optional[str] = None) -> Dict[str, str]:
208
+ h: Dict[str, str] = {
209
+ "X-API-Key": self._api_key,
210
+ "Accept": "application/json",
211
+ "User-Agent": _USER_AGENT,
212
+ }
213
+ if self._project_id:
214
+ h["X-Project-ID"] = self._project_id
215
+ eu = end_user_override or self._end_user_id
216
+ if eu:
217
+ h["X-End-User-ID"] = eu
218
+ return h
219
+
220
+ def _request(
221
+ self,
222
+ method: str,
223
+ path: str,
224
+ *,
225
+ json: Optional[Dict[str, Any]] = None,
226
+ end_user_override: Optional[str] = None,
227
+ ) -> Any:
228
+ url = f"{self._base_url}{path}"
229
+ try:
230
+ response = self._http.request(
231
+ method,
232
+ url,
233
+ headers=self._headers(end_user_override),
234
+ json=json,
235
+ )
236
+ except httpx.TimeoutException as e:
237
+ raise MemorySyncError(f"Request timed out: {e}") from e
238
+ except httpx.HTTPError as e:
239
+ raise MemorySyncError(f"Network error: {e}") from e
240
+
241
+ request_id = response.headers.get("x-request-id")
242
+ if response.status_code == 204:
243
+ return None
244
+ try:
245
+ body: Any = response.json()
246
+ except ValueError:
247
+ body = response.text or None
248
+ if response.status_code >= 400:
249
+ _raise_for_status(response.status_code, body, request_id)
250
+ return body
251
+
252
+ # ── Memory ───────────────────────────────────────────────────────
253
+
254
+ def add(
255
+ self,
256
+ text: str,
257
+ *,
258
+ source: Optional[str] = None,
259
+ tags: Optional[Sequence[str]] = None,
260
+ importance: Optional[float] = None,
261
+ session_id: Optional[str] = None,
262
+ metadata: Optional[Dict[str, Any]] = None,
263
+ end_user_id: Optional[str] = None,
264
+ ) -> AddResult:
265
+ body = _RequestBuilder.add(
266
+ text,
267
+ source=source,
268
+ tags=tags,
269
+ importance=importance,
270
+ session_id=session_id,
271
+ metadata=metadata,
272
+ end_user_id=end_user_id,
273
+ )
274
+ raw = self._request("POST", "/memory/add", json=body, end_user_override=end_user_id)
275
+ if isinstance(raw, dict) and raw.get("status") == "skipped":
276
+ return AddSkippedResponse(
277
+ status="skipped",
278
+ reason=str(raw.get("reason", "no_high_value_content")),
279
+ memory_ids=list(raw.get("memory_ids", []) or []),
280
+ candidates_extracted=int(raw.get("candidates_extracted", 0) or 0),
281
+ candidates_stored=int(raw.get("candidates_stored", 0) or 0),
282
+ )
283
+ return Memory.from_dict(raw)
284
+
285
+ def bulk_add(
286
+ self,
287
+ items: Sequence[BulkAddItem],
288
+ *,
289
+ deduplicate: bool = True,
290
+ ) -> BulkAddResponse:
291
+ if not items:
292
+ raise ValidationError("items must contain at least one entry")
293
+ if len(items) > _BULK_LIMIT:
294
+ raise ValidationError(f"items may contain at most {_BULK_LIMIT} entries per request")
295
+ raw = self._request(
296
+ "POST",
297
+ "/memory/bulk-add",
298
+ json=_RequestBuilder.bulk_add(items, deduplicate),
299
+ )
300
+ return _parse_bulk(raw)
301
+
302
+ def query(
303
+ self,
304
+ query: str,
305
+ *,
306
+ k: Optional[int] = None,
307
+ filters: Optional[Dict[str, Any]] = None,
308
+ session_id: Optional[str] = None,
309
+ traversal_depth: Optional[int] = None,
310
+ ) -> QueryResponse:
311
+ raw = self._request(
312
+ "POST",
313
+ "/memory/query",
314
+ json=_RequestBuilder.query(
315
+ query,
316
+ k=k,
317
+ filters=filters,
318
+ session_id=session_id,
319
+ traversal_depth=traversal_depth,
320
+ ),
321
+ )
322
+ return _parse_query(raw)
323
+
324
+ def get(self, memory_id: int) -> Memory:
325
+ _validate_id(memory_id, "memory_id")
326
+ raw = self._request("GET", f"/memory/{memory_id}")
327
+ return Memory.from_dict(raw)
328
+
329
+ def update(
330
+ self,
331
+ memory_id: int,
332
+ *,
333
+ tags: Optional[Sequence[str]] = None,
334
+ importance: Optional[float] = None,
335
+ metadata: Optional[Dict[str, Any]] = None,
336
+ source: Optional[str] = None,
337
+ event_type: Optional[str] = None,
338
+ ) -> Memory:
339
+ _validate_id(memory_id, "memory_id")
340
+ body = _strip_none(
341
+ {
342
+ "tags": list(tags) if tags is not None else None,
343
+ "importance": importance,
344
+ "metadata": metadata,
345
+ "source": source,
346
+ "event_type": event_type,
347
+ }
348
+ )
349
+ if not body:
350
+ raise ValidationError("update() requires at least one editable field")
351
+ raw = self._request("PATCH", f"/memory/{memory_id}", json=body)
352
+ return Memory.from_dict(raw)
353
+
354
+ def forget(self, memory_ids: Iterable[int], *, reason: Optional[str] = None) -> List[int]:
355
+ ids = list(memory_ids)
356
+ if not ids:
357
+ raise ValidationError("memory_ids must be a non-empty iterable")
358
+ body = _strip_none({"memory_ids": ids, "reason": reason})
359
+ raw = self._request("DELETE", "/memory/forget", json=body)
360
+ return list(raw or [])
361
+
362
+ def summarize(
363
+ self,
364
+ memory_ids: Iterable[int],
365
+ *,
366
+ lossless: bool = False,
367
+ ) -> Memory:
368
+ ids = list(memory_ids)
369
+ if not ids:
370
+ raise ValidationError("summarize() requires memory_ids")
371
+ raw = self._request(
372
+ "POST",
373
+ "/memory/summarize",
374
+ json={"memory_ids": ids, "lossless": lossless},
375
+ )
376
+ return Memory.from_dict(raw)
377
+
378
+ def compose(
379
+ self,
380
+ prompt_template: str,
381
+ *,
382
+ recall_k: Optional[int] = None,
383
+ max_tokens: Optional[int] = None,
384
+ ) -> ComposeResponse:
385
+ body = _strip_none(
386
+ {
387
+ "prompt_template": prompt_template,
388
+ "recall_k": recall_k,
389
+ "max_tokens": max_tokens,
390
+ }
391
+ )
392
+ raw = self._request("POST", "/memory/compose", json=body)
393
+ return _parse_compose(raw)
394
+
395
+ def export_all(self) -> ExportResponse:
396
+ raw = self._request("GET", "/memory/export")
397
+ return _parse_export(raw)
398
+
399
+ def create_relation(
400
+ self,
401
+ from_memory_id: int,
402
+ *,
403
+ to_memory_id: int,
404
+ relationship_type: RelationshipType,
405
+ confidence: Optional[float] = None,
406
+ metadata: Optional[Dict[str, Any]] = None,
407
+ ) -> Relation:
408
+ _validate_id(from_memory_id, "from_memory_id")
409
+ _validate_id(to_memory_id, "to_memory_id")
410
+ if from_memory_id == to_memory_id:
411
+ raise ValidationError("from_memory_id must differ from to_memory_id (no self-loops)")
412
+ body = _strip_none(
413
+ {
414
+ "to_memory_id": to_memory_id,
415
+ "relationship_type": relationship_type,
416
+ "confidence": confidence,
417
+ "metadata": metadata,
418
+ }
419
+ )
420
+ raw = self._request("POST", f"/memory/{from_memory_id}/relations", json=body)
421
+ return _parse_relation(raw)
422
+
423
+
424
+ # ─────────────────────────────────────────────────────────────────────
425
+ # Async client
426
+ # ─────────────────────────────────────────────────────────────────────
427
+
428
+
429
+ class AsyncMemorySyncClient:
430
+ """Async-native client for asyncio applications."""
431
+
432
+ def __init__(
433
+ self,
434
+ api_key: str,
435
+ base_url: str,
436
+ *,
437
+ project_id: Optional[str] = None,
438
+ end_user_id: Optional[str] = None,
439
+ timeout: float = 30.0,
440
+ transport: Optional[httpx.AsyncBaseTransport] = None,
441
+ ) -> None:
442
+ if not api_key or not api_key.strip():
443
+ raise ValueError("api_key is required")
444
+ if not base_url or not base_url.strip():
445
+ raise ValueError("base_url is required")
446
+ self._api_key = api_key
447
+ self._base_url = base_url.rstrip("/")
448
+ self._project_id = project_id
449
+ self._end_user_id = end_user_id
450
+ self._http = httpx.AsyncClient(timeout=timeout, transport=transport)
451
+
452
+ async def __aenter__(self) -> "AsyncMemorySyncClient":
453
+ return self
454
+
455
+ async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
456
+ await self.aclose()
457
+
458
+ async def aclose(self) -> None:
459
+ await self._http.aclose()
460
+
461
+ def _headers(self, end_user_override: Optional[str] = None) -> Dict[str, str]:
462
+ h: Dict[str, str] = {
463
+ "X-API-Key": self._api_key,
464
+ "Accept": "application/json",
465
+ "User-Agent": _USER_AGENT,
466
+ }
467
+ if self._project_id:
468
+ h["X-Project-ID"] = self._project_id
469
+ eu = end_user_override or self._end_user_id
470
+ if eu:
471
+ h["X-End-User-ID"] = eu
472
+ return h
473
+
474
+ async def _request(
475
+ self,
476
+ method: str,
477
+ path: str,
478
+ *,
479
+ json: Optional[Dict[str, Any]] = None,
480
+ end_user_override: Optional[str] = None,
481
+ ) -> Any:
482
+ url = f"{self._base_url}{path}"
483
+ try:
484
+ response = await self._http.request(
485
+ method,
486
+ url,
487
+ headers=self._headers(end_user_override),
488
+ json=json,
489
+ )
490
+ except httpx.TimeoutException as e:
491
+ raise MemorySyncError(f"Request timed out: {e}") from e
492
+ except httpx.HTTPError as e:
493
+ raise MemorySyncError(f"Network error: {e}") from e
494
+
495
+ request_id = response.headers.get("x-request-id")
496
+ if response.status_code == 204:
497
+ return None
498
+ try:
499
+ body: Any = response.json()
500
+ except ValueError:
501
+ body = response.text or None
502
+ if response.status_code >= 400:
503
+ _raise_for_status(response.status_code, body, request_id)
504
+ return body
505
+
506
+ async def add(
507
+ self,
508
+ text: str,
509
+ *,
510
+ source: Optional[str] = None,
511
+ tags: Optional[Sequence[str]] = None,
512
+ importance: Optional[float] = None,
513
+ session_id: Optional[str] = None,
514
+ metadata: Optional[Dict[str, Any]] = None,
515
+ end_user_id: Optional[str] = None,
516
+ ) -> AddResult:
517
+ body = _RequestBuilder.add(
518
+ text,
519
+ source=source,
520
+ tags=tags,
521
+ importance=importance,
522
+ session_id=session_id,
523
+ metadata=metadata,
524
+ end_user_id=end_user_id,
525
+ )
526
+ raw = await self._request("POST", "/memory/add", json=body, end_user_override=end_user_id)
527
+ if isinstance(raw, dict) and raw.get("status") == "skipped":
528
+ return AddSkippedResponse(
529
+ status="skipped",
530
+ reason=str(raw.get("reason", "no_high_value_content")),
531
+ memory_ids=list(raw.get("memory_ids", []) or []),
532
+ candidates_extracted=int(raw.get("candidates_extracted", 0) or 0),
533
+ candidates_stored=int(raw.get("candidates_stored", 0) or 0),
534
+ )
535
+ return Memory.from_dict(raw)
536
+
537
+ async def bulk_add(
538
+ self,
539
+ items: Sequence[BulkAddItem],
540
+ *,
541
+ deduplicate: bool = True,
542
+ ) -> BulkAddResponse:
543
+ if not items:
544
+ raise ValidationError("items must contain at least one entry")
545
+ if len(items) > _BULK_LIMIT:
546
+ raise ValidationError(f"items may contain at most {_BULK_LIMIT} entries per request")
547
+ raw = await self._request(
548
+ "POST",
549
+ "/memory/bulk-add",
550
+ json=_RequestBuilder.bulk_add(items, deduplicate),
551
+ )
552
+ return _parse_bulk(raw)
553
+
554
+ async def query(
555
+ self,
556
+ query: str,
557
+ *,
558
+ k: Optional[int] = None,
559
+ filters: Optional[Dict[str, Any]] = None,
560
+ session_id: Optional[str] = None,
561
+ traversal_depth: Optional[int] = None,
562
+ ) -> QueryResponse:
563
+ raw = await self._request(
564
+ "POST",
565
+ "/memory/query",
566
+ json=_RequestBuilder.query(
567
+ query,
568
+ k=k,
569
+ filters=filters,
570
+ session_id=session_id,
571
+ traversal_depth=traversal_depth,
572
+ ),
573
+ )
574
+ return _parse_query(raw)
575
+
576
+ async def get(self, memory_id: int) -> Memory:
577
+ _validate_id(memory_id, "memory_id")
578
+ raw = await self._request("GET", f"/memory/{memory_id}")
579
+ return Memory.from_dict(raw)
580
+
581
+ async def update(
582
+ self,
583
+ memory_id: int,
584
+ *,
585
+ tags: Optional[Sequence[str]] = None,
586
+ importance: Optional[float] = None,
587
+ metadata: Optional[Dict[str, Any]] = None,
588
+ source: Optional[str] = None,
589
+ event_type: Optional[str] = None,
590
+ ) -> Memory:
591
+ _validate_id(memory_id, "memory_id")
592
+ body = _strip_none(
593
+ {
594
+ "tags": list(tags) if tags is not None else None,
595
+ "importance": importance,
596
+ "metadata": metadata,
597
+ "source": source,
598
+ "event_type": event_type,
599
+ }
600
+ )
601
+ if not body:
602
+ raise ValidationError("update() requires at least one editable field")
603
+ raw = await self._request("PATCH", f"/memory/{memory_id}", json=body)
604
+ return Memory.from_dict(raw)
605
+
606
+ async def forget(self, memory_ids: Iterable[int], *, reason: Optional[str] = None) -> List[int]:
607
+ ids = list(memory_ids)
608
+ if not ids:
609
+ raise ValidationError("memory_ids must be a non-empty iterable")
610
+ body = _strip_none({"memory_ids": ids, "reason": reason})
611
+ raw = await self._request("DELETE", "/memory/forget", json=body)
612
+ return list(raw or [])
613
+
614
+ async def summarize(
615
+ self,
616
+ memory_ids: Iterable[int],
617
+ *,
618
+ lossless: bool = False,
619
+ ) -> Memory:
620
+ ids = list(memory_ids)
621
+ if not ids:
622
+ raise ValidationError("summarize() requires memory_ids")
623
+ raw = await self._request(
624
+ "POST",
625
+ "/memory/summarize",
626
+ json={"memory_ids": ids, "lossless": lossless},
627
+ )
628
+ return Memory.from_dict(raw)
629
+
630
+ async def compose(
631
+ self,
632
+ prompt_template: str,
633
+ *,
634
+ recall_k: Optional[int] = None,
635
+ max_tokens: Optional[int] = None,
636
+ ) -> ComposeResponse:
637
+ body = _strip_none(
638
+ {
639
+ "prompt_template": prompt_template,
640
+ "recall_k": recall_k,
641
+ "max_tokens": max_tokens,
642
+ }
643
+ )
644
+ raw = await self._request("POST", "/memory/compose", json=body)
645
+ return _parse_compose(raw)
646
+
647
+ async def export_all(self) -> ExportResponse:
648
+ raw = await self._request("GET", "/memory/export")
649
+ return _parse_export(raw)
650
+
651
+ async def create_relation(
652
+ self,
653
+ from_memory_id: int,
654
+ *,
655
+ to_memory_id: int,
656
+ relationship_type: RelationshipType,
657
+ confidence: Optional[float] = None,
658
+ metadata: Optional[Dict[str, Any]] = None,
659
+ ) -> Relation:
660
+ _validate_id(from_memory_id, "from_memory_id")
661
+ _validate_id(to_memory_id, "to_memory_id")
662
+ if from_memory_id == to_memory_id:
663
+ raise ValidationError("from_memory_id must differ from to_memory_id (no self-loops)")
664
+ body = _strip_none(
665
+ {
666
+ "to_memory_id": to_memory_id,
667
+ "relationship_type": relationship_type,
668
+ "confidence": confidence,
669
+ "metadata": metadata,
670
+ }
671
+ )
672
+ raw = await self._request("POST", f"/memory/{from_memory_id}/relations", json=body)
673
+ return _parse_relation(raw)
674
+
675
+
676
+ # ─────────────────────────────────────────────────────────────────────
677
+ # Shared response parsers
678
+ # ─────────────────────────────────────────────────────────────────────
679
+
680
+
681
+ def _validate_id(value: Any, name: str) -> None:
682
+ if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
683
+ raise ValidationError(f"{name} must be a positive integer")
684
+
685
+
686
+ def _parse_query(raw: Any) -> QueryResponse:
687
+ if not isinstance(raw, dict):
688
+ raise MemorySyncError("query response was not a JSON object")
689
+ memories = [Memory.from_dict(m) for m in (raw.get("memories") or [])]
690
+ return QueryResponse(
691
+ memories=memories,
692
+ context=raw.get("context"),
693
+ latency_ms=raw.get("latency_ms"),
694
+ session_id=raw.get("session_id"),
695
+ query_intent=raw.get("query_intent"),
696
+ )
697
+
698
+
699
+ def _parse_bulk(raw: Any) -> BulkAddResponse:
700
+ if not isinstance(raw, dict):
701
+ raise MemorySyncError("bulk_add response was not a JSON object")
702
+ results = [
703
+ BulkAddItemResult(
704
+ index=int(r["index"]),
705
+ status=r["status"],
706
+ memory_ids=list(r.get("memory_ids", []) or []),
707
+ reason=r.get("reason"),
708
+ )
709
+ for r in (raw.get("results") or [])
710
+ ]
711
+ return BulkAddResponse(
712
+ total=int(raw.get("total", 0)),
713
+ created=int(raw.get("created", 0)),
714
+ skipped=int(raw.get("skipped", 0)),
715
+ rejected=int(raw.get("rejected", 0)),
716
+ results=results,
717
+ )
718
+
719
+
720
+ def _parse_compose(raw: Any) -> ComposeResponse:
721
+ if not isinstance(raw, dict):
722
+ raise MemorySyncError("compose response was not a JSON object")
723
+ return ComposeResponse(
724
+ composed_prompt=str(raw.get("composed_prompt", "")),
725
+ memories_used=int(raw.get("memories_used", 0)),
726
+ token_count=int(raw.get("token_count", 0)),
727
+ truncated=bool(raw.get("truncated", False)),
728
+ )
729
+
730
+
731
+ def _parse_export(raw: Any) -> ExportResponse:
732
+ if not isinstance(raw, dict):
733
+ raise MemorySyncError("export response was not a JSON object")
734
+ return ExportResponse(
735
+ user_id=int(raw.get("user_id", 0)),
736
+ memories=list(raw.get("memories") or []),
737
+ generated_at=str(raw.get("generated_at", "")),
738
+ )
739
+
740
+
741
+ def _parse_relation(raw: Any) -> Relation:
742
+ if not isinstance(raw, dict):
743
+ raise MemorySyncError("relation response was not a JSON object")
744
+ return Relation(
745
+ id=int(raw["id"]),
746
+ from_memory_id=int(raw["from_memory_id"]),
747
+ to_memory_id=int(raw["to_memory_id"]),
748
+ relationship_type=raw["relationship_type"],
749
+ confidence=float(raw.get("confidence", 0.0)),
750
+ metadata=raw.get("metadata"),
751
+ created_at=raw.get("created_at"),
752
+ )
@@ -0,0 +1,59 @@
1
+ """Typed exceptions raised by the MemorySync SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class MemorySyncError(Exception):
9
+ """Base class for every error raised by the SDK."""
10
+
11
+ def __init__(
12
+ self,
13
+ message: str,
14
+ *,
15
+ status_code: Optional[int] = None,
16
+ response: Any = None,
17
+ request_id: Optional[str] = None,
18
+ ) -> None:
19
+ super().__init__(message)
20
+ self.status_code = status_code
21
+ self.response = response
22
+ self.request_id = request_id
23
+
24
+
25
+ class AuthError(MemorySyncError):
26
+ """401 / 403 — bad key, missing scope."""
27
+
28
+
29
+ class ValidationError(MemorySyncError):
30
+ """400 / 409 / 422 — malformed or rejected request."""
31
+
32
+
33
+ class NotFoundError(MemorySyncError):
34
+ """404 — record not visible to the caller."""
35
+
36
+
37
+ class RateLimitError(MemorySyncError):
38
+ """429 — caller has exceeded a rate or quota limit."""
39
+
40
+ def __init__(
41
+ self,
42
+ message: str,
43
+ retry_after_seconds: float,
44
+ *,
45
+ status_code: Optional[int] = None,
46
+ response: Any = None,
47
+ request_id: Optional[str] = None,
48
+ ) -> None:
49
+ super().__init__(
50
+ message,
51
+ status_code=status_code,
52
+ response=response,
53
+ request_id=request_id,
54
+ )
55
+ self.retry_after_seconds = retry_after_seconds
56
+
57
+
58
+ class ServerError(MemorySyncError):
59
+ """5xx — server failed to handle the request."""
@@ -0,0 +1,152 @@
1
+ """Public response and request dataclasses returned by the SDK.
2
+
3
+ Every shape here mirrors a real on-the-wire payload. We use plain
4
+ ``@dataclass`` (stdlib, no extra dependency) so callers can pattern-match,
5
+ serialize, and type-check without pulling Pydantic into their app.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Dict, List, Literal, Optional, Union
12
+
13
+ RelationshipType = Literal[
14
+ "similar",
15
+ "derived_from",
16
+ "continuation",
17
+ "contradiction",
18
+ "summary_of",
19
+ "detail_of",
20
+ "caused_by",
21
+ "references",
22
+ "supports",
23
+ "extends",
24
+ ]
25
+
26
+
27
+ @dataclass
28
+ class Memory:
29
+ """A single memory record. Mirrors :class:`MemoryResponse` server-side."""
30
+
31
+ id: int
32
+ text: str
33
+ summary: Optional[str] = None
34
+ tags: Optional[List[str]] = None
35
+ source: Optional[str] = None
36
+ event_type: Optional[str] = None
37
+ importance: Optional[float] = None
38
+ metadata: Optional[Dict[str, Any]] = None
39
+ is_summary: bool = False
40
+ created_at: Optional[str] = None
41
+ updated_at: Optional[str] = None
42
+ score: Optional[float] = None
43
+
44
+ @classmethod
45
+ def from_dict(cls, data: Dict[str, Any]) -> "Memory":
46
+ return cls(
47
+ id=int(data["id"]),
48
+ text=data.get("text", ""),
49
+ summary=data.get("summary"),
50
+ tags=data.get("tags"),
51
+ source=data.get("source"),
52
+ event_type=data.get("event_type"),
53
+ importance=data.get("importance"),
54
+ metadata=data.get("metadata"),
55
+ is_summary=bool(data.get("is_summary", False)),
56
+ created_at=data.get("created_at"),
57
+ updated_at=data.get("updated_at"),
58
+ score=data.get("score"),
59
+ )
60
+
61
+
62
+ @dataclass
63
+ class AddSkippedResponse:
64
+ """Returned by :meth:`MemorySyncClient.add` when extraction kept nothing."""
65
+
66
+ status: Literal["skipped"]
67
+ reason: str
68
+ memory_ids: List[int] = field(default_factory=list)
69
+ candidates_extracted: int = 0
70
+ candidates_stored: int = 0
71
+
72
+
73
+ @dataclass
74
+ class BulkAddItem:
75
+ text: str
76
+ source: Optional[str] = None
77
+ event_type: Optional[str] = None
78
+ tags: Optional[List[str]] = None
79
+ metadata: Optional[Dict[str, Any]] = None
80
+ importance: Optional[float] = None
81
+ end_user_id: Optional[str] = None
82
+
83
+ def to_dict(self) -> Dict[str, Any]:
84
+ out: Dict[str, Any] = {"text": self.text}
85
+ if self.source is not None:
86
+ out["source"] = self.source
87
+ if self.event_type is not None:
88
+ out["event_type"] = self.event_type
89
+ if self.tags is not None:
90
+ out["tags"] = self.tags
91
+ if self.metadata is not None:
92
+ out["metadata"] = self.metadata
93
+ if self.importance is not None:
94
+ out["importance"] = self.importance
95
+ if self.end_user_id is not None:
96
+ out["end_user_id"] = self.end_user_id
97
+ return out
98
+
99
+
100
+ @dataclass
101
+ class BulkAddItemResult:
102
+ index: int
103
+ status: Literal["created", "skipped", "rejected"]
104
+ memory_ids: List[int] = field(default_factory=list)
105
+ reason: Optional[str] = None
106
+
107
+
108
+ @dataclass
109
+ class BulkAddResponse:
110
+ total: int
111
+ created: int
112
+ skipped: int
113
+ rejected: int
114
+ results: List[BulkAddItemResult]
115
+
116
+
117
+ @dataclass
118
+ class QueryResponse:
119
+ memories: List[Memory]
120
+ context: Optional[str] = None
121
+ latency_ms: Optional[float] = None
122
+ session_id: Optional[str] = None
123
+ query_intent: Optional[str] = None
124
+
125
+
126
+ @dataclass
127
+ class ComposeResponse:
128
+ composed_prompt: str
129
+ memories_used: int
130
+ token_count: int
131
+ truncated: bool
132
+
133
+
134
+ @dataclass
135
+ class ExportResponse:
136
+ user_id: int
137
+ memories: List[Dict[str, Any]]
138
+ generated_at: str
139
+
140
+
141
+ @dataclass
142
+ class Relation:
143
+ id: int
144
+ from_memory_id: int
145
+ to_memory_id: int
146
+ relationship_type: RelationshipType
147
+ confidence: float
148
+ metadata: Optional[Dict[str, Any]] = None
149
+ created_at: Optional[str] = None
150
+
151
+
152
+ AddResult = Union[Memory, AddSkippedResponse]