memoryo-sdk 0.1.1__py3-none-any.whl
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.
- memoryo_sdk-0.1.1.dist-info/METADATA +410 -0
- memoryo_sdk-0.1.1.dist-info/RECORD +11 -0
- memoryo_sdk-0.1.1.dist-info/WHEEL +5 -0
- memoryo_sdk-0.1.1.dist-info/licenses/LICENSE +21 -0
- memoryo_sdk-0.1.1.dist-info/top_level.txt +1 -0
- memoryos/__init__.py +18 -0
- memoryos/async_client.py +455 -0
- memoryos/client.py +454 -0
- memoryos/errors.py +59 -0
- memoryos/types.py +515 -0
- memoryos/universal.py +249 -0
memoryos/async_client.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import time
|
|
5
|
+
import warnings
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Any, Self
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from memoryos.errors import MemoryOSError, map_sdk_error
|
|
13
|
+
from memoryos.types import (
|
|
14
|
+
AddEnvelope,
|
|
15
|
+
AddRequest,
|
|
16
|
+
AddResult,
|
|
17
|
+
ConversationMessage,
|
|
18
|
+
DeleteEnvelope,
|
|
19
|
+
EdTechMemoryProfile,
|
|
20
|
+
EdTechProfileEnvelope,
|
|
21
|
+
ExportEnvelope,
|
|
22
|
+
MemoryExport,
|
|
23
|
+
MemoryClarificationAnswerEnvelope,
|
|
24
|
+
MemoryClarificationAnswerResult,
|
|
25
|
+
MemoryJobStatus,
|
|
26
|
+
MemoryJobStatusEnvelope,
|
|
27
|
+
MemoryListEnvelope,
|
|
28
|
+
MemoryPage,
|
|
29
|
+
MemorySource,
|
|
30
|
+
MemorySourceReviewAnswerEnvelope,
|
|
31
|
+
MemorySourceReviewAnswerResult,
|
|
32
|
+
QuotaMode,
|
|
33
|
+
RetrievalFeedbackEnvelope,
|
|
34
|
+
RetrievalFeedbackRequest,
|
|
35
|
+
RetrievalFeedbackResult,
|
|
36
|
+
RetrieveEnvelope,
|
|
37
|
+
RetrieveResult,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class AsyncMemory:
|
|
42
|
+
DEFAULT_BASE_URL = "https://api.memoryo.dev"
|
|
43
|
+
DEFAULT_TIMEOUT = 30.0
|
|
44
|
+
MAX_RETRIES = 3
|
|
45
|
+
|
|
46
|
+
def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = DEFAULT_TIMEOUT) -> None:
|
|
47
|
+
if not api_key.strip():
|
|
48
|
+
raise ValueError("api_key must not be empty.")
|
|
49
|
+
self.api_key = api_key
|
|
50
|
+
self.base_url = base_url.rstrip("/")
|
|
51
|
+
self.timeout = float(timeout)
|
|
52
|
+
self._client = httpx.AsyncClient(
|
|
53
|
+
base_url=self.base_url,
|
|
54
|
+
timeout=self.timeout,
|
|
55
|
+
headers={
|
|
56
|
+
"Authorization": f"ApiKey {self.api_key}",
|
|
57
|
+
"Accept": "application/json",
|
|
58
|
+
"Content-Type": "application/json",
|
|
59
|
+
"User-Agent": "memoryos-python/0.1.0",
|
|
60
|
+
},
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
async def __aenter__(self) -> Self:
|
|
64
|
+
return self
|
|
65
|
+
|
|
66
|
+
async def __aexit__(self, _exc_type, _exc, _tb) -> None:
|
|
67
|
+
await self.close()
|
|
68
|
+
|
|
69
|
+
async def close(self) -> None:
|
|
70
|
+
await self._client.aclose()
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def _resolve_external_user_id(
|
|
74
|
+
external_user_id: str | None,
|
|
75
|
+
kwargs: dict[str, Any],
|
|
76
|
+
) -> str:
|
|
77
|
+
deprecated_user_id = kwargs.pop("user_id", None)
|
|
78
|
+
if deprecated_user_id is not None:
|
|
79
|
+
warnings.warn(
|
|
80
|
+
"user_id is deprecated, use external_user_id",
|
|
81
|
+
DeprecationWarning,
|
|
82
|
+
stacklevel=2,
|
|
83
|
+
)
|
|
84
|
+
if external_user_id is None:
|
|
85
|
+
external_user_id = str(deprecated_user_id)
|
|
86
|
+
if kwargs:
|
|
87
|
+
unexpected = ", ".join(sorted(kwargs))
|
|
88
|
+
raise TypeError(f"Unexpected keyword argument(s): {unexpected}")
|
|
89
|
+
if external_user_id is None:
|
|
90
|
+
raise TypeError("external_user_id is required")
|
|
91
|
+
return external_user_id
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def source(
|
|
95
|
+
service: str,
|
|
96
|
+
*,
|
|
97
|
+
event_id: str | None = None,
|
|
98
|
+
observed_at: Any | None = None,
|
|
99
|
+
scope: dict[str, Any] | None = None,
|
|
100
|
+
evidence: list[Any] | None = None,
|
|
101
|
+
) -> MemorySource:
|
|
102
|
+
"""Create source metadata for multi-service memory writes.
|
|
103
|
+
|
|
104
|
+
Most apps can omit source in add(). Use this helper when Billing,
|
|
105
|
+
Support, CRM, or another service needs explicit provenance.
|
|
106
|
+
"""
|
|
107
|
+
return MemorySource.for_service(
|
|
108
|
+
service,
|
|
109
|
+
event_id=event_id,
|
|
110
|
+
observed_at=observed_at,
|
|
111
|
+
scope=scope,
|
|
112
|
+
evidence=evidence,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
async def add(
|
|
116
|
+
self,
|
|
117
|
+
messages: list[ConversationMessage | dict[str, Any]],
|
|
118
|
+
external_user_id: str,
|
|
119
|
+
agent_id: str | None = None,
|
|
120
|
+
metadata: dict[str, Any] | None = None,
|
|
121
|
+
idempotency_key: str | None = None,
|
|
122
|
+
source: MemorySource | dict[str, Any] | None = None,
|
|
123
|
+
conversation_id: str | None = None,
|
|
124
|
+
) -> AddResult:
|
|
125
|
+
payload = AddRequest(
|
|
126
|
+
external_user_id=external_user_id,
|
|
127
|
+
agent_id=agent_id,
|
|
128
|
+
messages=[item if isinstance(item, ConversationMessage) else ConversationMessage.model_validate(item) for item in messages],
|
|
129
|
+
metadata=metadata or {},
|
|
130
|
+
conversation_id=conversation_id,
|
|
131
|
+
source=(
|
|
132
|
+
source
|
|
133
|
+
if isinstance(source, MemorySource)
|
|
134
|
+
else MemorySource.model_validate(source)
|
|
135
|
+
if source is not None
|
|
136
|
+
else None
|
|
137
|
+
),
|
|
138
|
+
)
|
|
139
|
+
response = await self._request_response(
|
|
140
|
+
"POST",
|
|
141
|
+
"/v1/memories/add",
|
|
142
|
+
json=payload.model_dump(mode="json", exclude_none=True, exclude_defaults=True),
|
|
143
|
+
headers={"Idempotency-Key": idempotency_key} if idempotency_key else None,
|
|
144
|
+
)
|
|
145
|
+
parsed = AddEnvelope.model_validate(self._parse_json(response))
|
|
146
|
+
return AddResult(
|
|
147
|
+
job_id=parsed.job_id,
|
|
148
|
+
status=parsed.status,
|
|
149
|
+
blocked_reason=parsed.blocked_reason,
|
|
150
|
+
retry_after_seconds=parsed.retry_after_seconds,
|
|
151
|
+
budget_remaining_pct=parsed.budget_remaining_pct,
|
|
152
|
+
quota_mode=self._quota_mode_from_response(response),
|
|
153
|
+
processing_eta_seconds=parsed.processing_eta_seconds,
|
|
154
|
+
processing_status=self._processing_status_from_response(response, parsed.processing_status),
|
|
155
|
+
circuit_status=self._circuit_status_from_response(response),
|
|
156
|
+
nothing_to_extract=parsed.nothing_to_extract,
|
|
157
|
+
proposal_ids=parsed.proposal_ids,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
async def get(
|
|
161
|
+
self,
|
|
162
|
+
query: str,
|
|
163
|
+
external_user_id: str,
|
|
164
|
+
limit: int = 10,
|
|
165
|
+
categories: list[str] | None = None,
|
|
166
|
+
agent_id: str | None = None,
|
|
167
|
+
time_filter_days: int | None = None,
|
|
168
|
+
format: str = "bullets",
|
|
169
|
+
context_max_tokens: int = 500,
|
|
170
|
+
as_of: datetime | None = None,
|
|
171
|
+
) -> RetrieveResult:
|
|
172
|
+
body: dict[str, Any] = {
|
|
173
|
+
"query": query,
|
|
174
|
+
"external_user_id": external_user_id,
|
|
175
|
+
"limit": limit,
|
|
176
|
+
"categories": categories or [],
|
|
177
|
+
"format": format,
|
|
178
|
+
"context_max_tokens": context_max_tokens,
|
|
179
|
+
}
|
|
180
|
+
if agent_id is not None:
|
|
181
|
+
body["agent_id"] = agent_id
|
|
182
|
+
if time_filter_days is not None:
|
|
183
|
+
body["time_filter_days"] = time_filter_days
|
|
184
|
+
if as_of is not None:
|
|
185
|
+
if as_of.tzinfo is None:
|
|
186
|
+
raise ValueError("as_of must include a timezone")
|
|
187
|
+
body["as_of"] = as_of.isoformat()
|
|
188
|
+
response = await self._request_response(
|
|
189
|
+
"POST",
|
|
190
|
+
"/v1/memories/retrieve",
|
|
191
|
+
json=body,
|
|
192
|
+
)
|
|
193
|
+
parsed = RetrieveEnvelope.model_validate(self._parse_json(response))
|
|
194
|
+
quota_mode = parsed.quota_mode or self._quota_mode_from_response(response)
|
|
195
|
+
return RetrieveResult(
|
|
196
|
+
retrieval_id=parsed.retrieval_id,
|
|
197
|
+
items=parsed.data,
|
|
198
|
+
cached=parsed.cached,
|
|
199
|
+
system_prompt_addition=parsed.system_prompt_addition,
|
|
200
|
+
context_token_count=parsed.context_token_count,
|
|
201
|
+
memories_from_hot_tier=parsed.memories_from_hot_tier,
|
|
202
|
+
quota_mode=quota_mode,
|
|
203
|
+
is_passthrough=quota_mode == "PASSTHROUGH",
|
|
204
|
+
is_degraded=quota_mode == "DEGRADED_RETRIEVE",
|
|
205
|
+
circuit_status=self._circuit_status_from_response(response),
|
|
206
|
+
clarification_question=parsed.clarification_question,
|
|
207
|
+
clarification=parsed.clarification,
|
|
208
|
+
source_reviews=parsed.source_reviews,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
async def get_job_status(self, job_id: str) -> MemoryJobStatus:
|
|
212
|
+
"""Return the current state of an asynchronous extraction job."""
|
|
213
|
+
if not str(job_id or "").strip():
|
|
214
|
+
raise ValueError("job_id must not be empty")
|
|
215
|
+
response = await self._request("GET", f"/v1/memories/jobs/{quote(job_id, safe='')}")
|
|
216
|
+
return MemoryJobStatusEnvelope.model_validate(response).data
|
|
217
|
+
|
|
218
|
+
async def wait_for_job(
|
|
219
|
+
self,
|
|
220
|
+
job_id: str,
|
|
221
|
+
*,
|
|
222
|
+
timeout: float = 120.0,
|
|
223
|
+
poll_interval: float = 1.0,
|
|
224
|
+
) -> MemoryJobStatus:
|
|
225
|
+
"""Poll until extraction reaches a terminal state, raising on timeout.
|
|
226
|
+
|
|
227
|
+
``failed`` is intentionally non-terminal: the backend persists that
|
|
228
|
+
state while an automatic retry is waiting to run. Exhausted jobs end
|
|
229
|
+
in ``dead``.
|
|
230
|
+
"""
|
|
231
|
+
if timeout <= 0:
|
|
232
|
+
raise ValueError("timeout must be greater than zero")
|
|
233
|
+
if poll_interval <= 0:
|
|
234
|
+
raise ValueError("poll_interval must be greater than zero")
|
|
235
|
+
deadline = time.monotonic() + timeout
|
|
236
|
+
while True:
|
|
237
|
+
job = await self.get_job_status(job_id)
|
|
238
|
+
if job.status in {"completed", "dead", "dead_letter", "dead_lettered", "cancelled"}:
|
|
239
|
+
return job
|
|
240
|
+
if time.monotonic() >= deadline:
|
|
241
|
+
raise TimeoutError(f"MemoryOS job {job_id} did not finish within {timeout:g} seconds")
|
|
242
|
+
await asyncio.sleep(min(poll_interval, max(0.0, deadline - time.monotonic())))
|
|
243
|
+
|
|
244
|
+
async def feedback(
|
|
245
|
+
self,
|
|
246
|
+
retrieval_id: str,
|
|
247
|
+
outcome: str,
|
|
248
|
+
used_memory_ids: list[str] | None = None,
|
|
249
|
+
correction: str | None = None,
|
|
250
|
+
agent_confidence: float | None = None,
|
|
251
|
+
metadata: dict[str, Any] | None = None,
|
|
252
|
+
) -> RetrievalFeedbackResult:
|
|
253
|
+
payload = RetrievalFeedbackRequest(
|
|
254
|
+
retrieval_id=retrieval_id,
|
|
255
|
+
outcome=outcome, # type: ignore[arg-type]
|
|
256
|
+
used_memory_ids=used_memory_ids or [],
|
|
257
|
+
correction=correction,
|
|
258
|
+
agent_confidence=agent_confidence,
|
|
259
|
+
metadata=metadata or {},
|
|
260
|
+
)
|
|
261
|
+
response = await self._request_response(
|
|
262
|
+
"POST",
|
|
263
|
+
"/v1/memories/retrieval-feedback",
|
|
264
|
+
json=payload.model_dump(mode="json", exclude_none=True),
|
|
265
|
+
)
|
|
266
|
+
parsed = RetrievalFeedbackEnvelope.model_validate(self._parse_json(response))
|
|
267
|
+
return parsed.data
|
|
268
|
+
|
|
269
|
+
async def answer_source_review(
|
|
270
|
+
self, review_id: str, *, external_user_id: str, version: str, action: str,
|
|
271
|
+
) -> MemorySourceReviewAnswerResult:
|
|
272
|
+
"""Non-activating review response. Restate requires a normal add() call."""
|
|
273
|
+
if action not in {"keep_current", "restate", "dismiss"}:
|
|
274
|
+
raise ValueError("action must be one of: keep_current, restate, dismiss")
|
|
275
|
+
response = await self._request_response(
|
|
276
|
+
"POST", f"/v1/memories/source-reviews/{quote(review_id, safe='')}/answer",
|
|
277
|
+
json={"external_user_id": external_user_id, "version": version, "action": action},
|
|
278
|
+
)
|
|
279
|
+
return MemorySourceReviewAnswerEnvelope.model_validate(self._parse_json(response)).data
|
|
280
|
+
|
|
281
|
+
async def answer_clarification(
|
|
282
|
+
self,
|
|
283
|
+
clarification_id: str,
|
|
284
|
+
*,
|
|
285
|
+
external_user_id: str,
|
|
286
|
+
answer: str,
|
|
287
|
+
free_text: str | None = None,
|
|
288
|
+
) -> MemoryClarificationAnswerResult:
|
|
289
|
+
"""Resolve a surfaced clarification after the user answers in the customer chat."""
|
|
290
|
+
if answer not in {"A", "B", "both", "neither"}:
|
|
291
|
+
raise ValueError("answer must be one of: A, B, both, neither")
|
|
292
|
+
response = await self._request_response(
|
|
293
|
+
"POST",
|
|
294
|
+
f"/v1/memories/clarifications/{quote(clarification_id, safe='')}/answer",
|
|
295
|
+
json={
|
|
296
|
+
"external_user_id": external_user_id,
|
|
297
|
+
"answer": answer,
|
|
298
|
+
"free_text": free_text,
|
|
299
|
+
},
|
|
300
|
+
)
|
|
301
|
+
return MemoryClarificationAnswerEnvelope.model_validate(
|
|
302
|
+
self._parse_json(response)
|
|
303
|
+
).data
|
|
304
|
+
|
|
305
|
+
async def delete(
|
|
306
|
+
self,
|
|
307
|
+
memory_id: str,
|
|
308
|
+
external_user_id: str | None = None,
|
|
309
|
+
hard_delete: bool = False,
|
|
310
|
+
**kwargs: Any,
|
|
311
|
+
) -> bool:
|
|
312
|
+
# Deletion is tenant-scoped by memory_id. external_user_id/user_id is
|
|
313
|
+
# retained only for compatibility with older SDK call sites.
|
|
314
|
+
_ = external_user_id
|
|
315
|
+
_ = kwargs.pop("user_id", None)
|
|
316
|
+
if kwargs:
|
|
317
|
+
raise TypeError(f"Unexpected keyword arguments: {', '.join(sorted(kwargs))}")
|
|
318
|
+
response = await self._request(
|
|
319
|
+
"DELETE",
|
|
320
|
+
f"/v1/memories/{memory_id}",
|
|
321
|
+
params={"hard_delete": str(hard_delete).lower()},
|
|
322
|
+
)
|
|
323
|
+
return DeleteEnvelope.model_validate(response).data.deleted
|
|
324
|
+
|
|
325
|
+
async def list(
|
|
326
|
+
self,
|
|
327
|
+
external_user_id: str | None = None,
|
|
328
|
+
page_cursor: str | None = None,
|
|
329
|
+
limit: int = 50,
|
|
330
|
+
**kwargs: Any,
|
|
331
|
+
) -> MemoryPage:
|
|
332
|
+
resolved_external_user_id = self._resolve_external_user_id(external_user_id, kwargs)
|
|
333
|
+
params: dict[str, Any] = {
|
|
334
|
+
"external_user_id": resolved_external_user_id,
|
|
335
|
+
"limit": limit,
|
|
336
|
+
}
|
|
337
|
+
if page_cursor:
|
|
338
|
+
params["cursor"] = page_cursor
|
|
339
|
+
response = await self._request("GET", "/v1/memories", params=params)
|
|
340
|
+
parsed = MemoryListEnvelope.model_validate(response)
|
|
341
|
+
return MemoryPage(
|
|
342
|
+
items=parsed.data,
|
|
343
|
+
next_cursor=parsed.pagination.next_cursor,
|
|
344
|
+
limit=parsed.pagination.limit,
|
|
345
|
+
total=parsed.pagination.total,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
async def export(self, external_user_id: str | None = None, **kwargs: Any) -> MemoryExport:
|
|
349
|
+
resolved_external_user_id = self._resolve_external_user_id(external_user_id, kwargs)
|
|
350
|
+
response = await self._request(
|
|
351
|
+
"GET",
|
|
352
|
+
f"/v1/users/{quote(resolved_external_user_id, safe='')}/export",
|
|
353
|
+
)
|
|
354
|
+
return ExportEnvelope.model_validate(response).data
|
|
355
|
+
|
|
356
|
+
async def get_edtech_profile(self, external_user_id: str) -> EdTechMemoryProfile | None:
|
|
357
|
+
"""Return the structured EdTech profile for a user, if enabled."""
|
|
358
|
+
|
|
359
|
+
response = await self._request(
|
|
360
|
+
"GET",
|
|
361
|
+
"/v1/memories/edtech-profile",
|
|
362
|
+
params={"external_user_id": external_user_id},
|
|
363
|
+
)
|
|
364
|
+
return EdTechProfileEnvelope.model_validate(response).data
|
|
365
|
+
|
|
366
|
+
async def _request(
|
|
367
|
+
self,
|
|
368
|
+
method: str,
|
|
369
|
+
path: str,
|
|
370
|
+
*,
|
|
371
|
+
json: dict[str, Any] | None = None,
|
|
372
|
+
params: dict[str, Any] | None = None,
|
|
373
|
+
headers: dict[str, str] | None = None,
|
|
374
|
+
) -> dict[str, Any]:
|
|
375
|
+
response = await self._request_response(method, path, json=json, params=params, headers=headers)
|
|
376
|
+
return self._parse_json(response)
|
|
377
|
+
|
|
378
|
+
async def _request_response(
|
|
379
|
+
self,
|
|
380
|
+
method: str,
|
|
381
|
+
path: str,
|
|
382
|
+
*,
|
|
383
|
+
json: dict[str, Any] | None = None,
|
|
384
|
+
params: dict[str, Any] | None = None,
|
|
385
|
+
headers: dict[str, str] | None = None,
|
|
386
|
+
) -> httpx.Response:
|
|
387
|
+
last_error: MemoryOSError | None = None
|
|
388
|
+
|
|
389
|
+
for attempt in range(self.MAX_RETRIES + 1):
|
|
390
|
+
try:
|
|
391
|
+
response = await self._client.request(method, path, json=json, params=params, headers=headers)
|
|
392
|
+
except httpx.HTTPError as exc:
|
|
393
|
+
raise MemoryOSError(f"MemoryOS request failed: {exc}") from exc
|
|
394
|
+
|
|
395
|
+
if response.status_code < 400:
|
|
396
|
+
return response
|
|
397
|
+
|
|
398
|
+
error = self._error_from_response(response)
|
|
399
|
+
if response.status_code in {429, 500, 502, 503, 504} and attempt < self.MAX_RETRIES:
|
|
400
|
+
last_error = error
|
|
401
|
+
await asyncio.sleep(2**attempt)
|
|
402
|
+
continue
|
|
403
|
+
raise error
|
|
404
|
+
|
|
405
|
+
raise last_error or MemoryOSError("Request failed after retries.")
|
|
406
|
+
|
|
407
|
+
@staticmethod
|
|
408
|
+
def _parse_json(response: httpx.Response) -> dict[str, Any]:
|
|
409
|
+
try:
|
|
410
|
+
payload = response.json()
|
|
411
|
+
except ValueError as exc:
|
|
412
|
+
raise MemoryOSError("MemoryOS returned a non-JSON response.", status_code=response.status_code) from exc
|
|
413
|
+
if not isinstance(payload, dict):
|
|
414
|
+
raise MemoryOSError("MemoryOS returned an unexpected response payload.", status_code=response.status_code)
|
|
415
|
+
return payload
|
|
416
|
+
|
|
417
|
+
def _error_from_response(self, response: httpx.Response) -> MemoryOSError:
|
|
418
|
+
try:
|
|
419
|
+
payload = self._parse_json(response)
|
|
420
|
+
except MemoryOSError:
|
|
421
|
+
return map_sdk_error(
|
|
422
|
+
status_code=response.status_code,
|
|
423
|
+
message=f"MemoryOS request failed with status {response.status_code}.",
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
error_payload = payload.get("error", "request_failed")
|
|
427
|
+
message = str(error_payload).replace("_", " ")
|
|
428
|
+
return map_sdk_error(
|
|
429
|
+
status_code=response.status_code,
|
|
430
|
+
message=message,
|
|
431
|
+
code=str(payload.get("code")) if payload.get("code") else None,
|
|
432
|
+
request_id=str(payload.get("request_id")) if payload.get("request_id") else None,
|
|
433
|
+
details=payload.get("details"),
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
@staticmethod
|
|
437
|
+
def _quota_mode_from_response(response: httpx.Response) -> QuotaMode:
|
|
438
|
+
raw_mode = response.headers.get("X-MemoryOS-Quota-Mode", "FULL").upper()
|
|
439
|
+
if raw_mode in {"FULL", "PASSTHROUGH", "DEGRADED_RETRIEVE", "BLOCKED"}:
|
|
440
|
+
return raw_mode # type: ignore[return-value]
|
|
441
|
+
return "FULL"
|
|
442
|
+
|
|
443
|
+
@staticmethod
|
|
444
|
+
def _circuit_status_from_response(response: httpx.Response) -> str:
|
|
445
|
+
raw_status = response.headers.get("X-MemoryOS-Circuit-Status", "HEALTHY").upper()
|
|
446
|
+
if raw_status in {"HEALTHY", "DEGRADED", "CRITICAL"}:
|
|
447
|
+
return raw_status
|
|
448
|
+
return "HEALTHY"
|
|
449
|
+
|
|
450
|
+
@staticmethod
|
|
451
|
+
def _processing_status_from_response(response: httpx.Response, fallback: str = "normal") -> str:
|
|
452
|
+
raw_status = response.headers.get("X-MemoryOS-Processing", fallback).lower()
|
|
453
|
+
if raw_status in {"normal", "delayed"}:
|
|
454
|
+
return raw_status
|
|
455
|
+
return "normal"
|