memsy 0.3.0__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.
- memsy/__init__.py +160 -0
- memsy/_http.py +204 -0
- memsy/async_client.py +200 -0
- memsy/async_control.py +119 -0
- memsy/client.py +200 -0
- memsy/control.py +125 -0
- memsy/control_resources/__init__.py +18 -0
- memsy/control_resources/billing.py +55 -0
- memsy/control_resources/events.py +89 -0
- memsy/control_resources/interest.py +89 -0
- memsy/control_resources/keys.py +103 -0
- memsy/control_resources/usage.py +93 -0
- memsy/exceptions.py +190 -0
- memsy/models.py +802 -0
- memsy/py.typed +0 -0
- memsy/resources/__init__.py +15 -0
- memsy/resources/memories.py +113 -0
- memsy/resources/orgs.py +123 -0
- memsy/resources/roles.py +137 -0
- memsy/resources/teams.py +137 -0
- memsy-0.3.0.dist-info/METADATA +551 -0
- memsy-0.3.0.dist-info/RECORD +23 -0
- memsy-0.3.0.dist-info/WHEEL +4 -0
memsy/__init__.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Memsy Python SDK — official client for the Memsy memory service.
|
|
3
|
+
|
|
4
|
+
Quick start (hot-path memory)::
|
|
5
|
+
|
|
6
|
+
from memsy import MemsyClient, EventPayload
|
|
7
|
+
|
|
8
|
+
client = MemsyClient(base_url="https://your-memsy-core-url", api_key="msy_...")
|
|
9
|
+
health = client.health()
|
|
10
|
+
|
|
11
|
+
# Ingest events
|
|
12
|
+
result = client.ingest([
|
|
13
|
+
EventPayload(actor_id="user_1", session_id="sess_1",
|
|
14
|
+
kind="user_message", content="I prefer dark mode",
|
|
15
|
+
role_id="role_eng", team_id="team_platform")
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
# Search memories
|
|
19
|
+
results = client.search("user preferences", include_source_events=True)
|
|
20
|
+
|
|
21
|
+
# Onboarding / hierarchy
|
|
22
|
+
client.orgs.create(org_id="my-org", name="My Org", focus="...")
|
|
23
|
+
client.roles.list(org_id="my-org")
|
|
24
|
+
client.memories.stats()
|
|
25
|
+
|
|
26
|
+
Control-plane (billing, keys, usage, events)::
|
|
27
|
+
|
|
28
|
+
from memsy import MemsyControlClient
|
|
29
|
+
|
|
30
|
+
control = MemsyControlClient(base_url="https://your-api-url", api_key="msy_...")
|
|
31
|
+
me = control.me()
|
|
32
|
+
events = control.events.list(limit=20)
|
|
33
|
+
|
|
34
|
+
Async usage::
|
|
35
|
+
|
|
36
|
+
from memsy import AsyncMemsyClient, AsyncMemsyControlClient, EventPayload
|
|
37
|
+
|
|
38
|
+
async with AsyncMemsyClient(base_url="...", api_key="msy_...") as client:
|
|
39
|
+
health = await client.health()
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from memsy.async_client import AsyncMemsyClient
|
|
43
|
+
from memsy.async_control import AsyncMemsyControlClient
|
|
44
|
+
from memsy.client import MemsyClient
|
|
45
|
+
from memsy.control import MemsyControlClient
|
|
46
|
+
from memsy.exceptions import (
|
|
47
|
+
AuthenticationError,
|
|
48
|
+
AuthorizationError,
|
|
49
|
+
BillingNotEnabledError,
|
|
50
|
+
FeatureNotAvailable,
|
|
51
|
+
KeyLimitReachedError,
|
|
52
|
+
MemsyAPIError,
|
|
53
|
+
MemsyConnectionError,
|
|
54
|
+
MemsyError,
|
|
55
|
+
OrgIdNotAllowedError,
|
|
56
|
+
OrgLimitReachedError,
|
|
57
|
+
RateLimitExceeded,
|
|
58
|
+
SeatLimitReachedError,
|
|
59
|
+
SeatRequiredError,
|
|
60
|
+
UsageLimitExceeded,
|
|
61
|
+
)
|
|
62
|
+
from memsy.models import (
|
|
63
|
+
# Control-plane models
|
|
64
|
+
ApiKeyInfo,
|
|
65
|
+
ApiKeyListResponse,
|
|
66
|
+
BillingSummary,
|
|
67
|
+
ClearResponse,
|
|
68
|
+
CreateKeyResponse,
|
|
69
|
+
DimensionUsage,
|
|
70
|
+
EventItemResponse,
|
|
71
|
+
EventListResponse,
|
|
72
|
+
# Core models
|
|
73
|
+
EventPayload,
|
|
74
|
+
HealthResponse,
|
|
75
|
+
IngestResponse,
|
|
76
|
+
Invoice,
|
|
77
|
+
# Console memory models
|
|
78
|
+
MemoryItemResource,
|
|
79
|
+
MemoryListResponse,
|
|
80
|
+
MemoryScopeInfo,
|
|
81
|
+
MemoryStatsResponse,
|
|
82
|
+
MeResponse,
|
|
83
|
+
# Onboarding models
|
|
84
|
+
OrgResource,
|
|
85
|
+
PaymentMethod,
|
|
86
|
+
ProInterestResponse,
|
|
87
|
+
RateLimitInfo,
|
|
88
|
+
RoleResource,
|
|
89
|
+
SearchResponse,
|
|
90
|
+
SearchResult,
|
|
91
|
+
SourceEvent,
|
|
92
|
+
StatusResponse,
|
|
93
|
+
TeamResource,
|
|
94
|
+
TimeseriesPoint,
|
|
95
|
+
UpcomingInvoice,
|
|
96
|
+
UsageInfo,
|
|
97
|
+
UsageSummaryResponse,
|
|
98
|
+
UsageTimeseriesResponse,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
__all__ = [
|
|
102
|
+
# Clients
|
|
103
|
+
"MemsyClient",
|
|
104
|
+
"AsyncMemsyClient",
|
|
105
|
+
"MemsyControlClient",
|
|
106
|
+
"AsyncMemsyControlClient",
|
|
107
|
+
# Core request models
|
|
108
|
+
"EventPayload",
|
|
109
|
+
"SourceEvent",
|
|
110
|
+
# Core response models
|
|
111
|
+
"IngestResponse",
|
|
112
|
+
"SearchResponse",
|
|
113
|
+
"SearchResult",
|
|
114
|
+
"StatusResponse",
|
|
115
|
+
"HealthResponse",
|
|
116
|
+
"ClearResponse",
|
|
117
|
+
# Onboarding models
|
|
118
|
+
"OrgResource",
|
|
119
|
+
"RoleResource",
|
|
120
|
+
"TeamResource",
|
|
121
|
+
# Console memory models
|
|
122
|
+
"MemoryScopeInfo",
|
|
123
|
+
"MemoryItemResource",
|
|
124
|
+
"MemoryListResponse",
|
|
125
|
+
"MemoryStatsResponse",
|
|
126
|
+
# Control-plane models
|
|
127
|
+
"MeResponse",
|
|
128
|
+
"DimensionUsage",
|
|
129
|
+
"UsageSummaryResponse",
|
|
130
|
+
"TimeseriesPoint",
|
|
131
|
+
"UsageTimeseriesResponse",
|
|
132
|
+
"PaymentMethod",
|
|
133
|
+
"UpcomingInvoice",
|
|
134
|
+
"BillingSummary",
|
|
135
|
+
"Invoice",
|
|
136
|
+
"ApiKeyInfo",
|
|
137
|
+
"ApiKeyListResponse",
|
|
138
|
+
"CreateKeyResponse",
|
|
139
|
+
"EventItemResponse",
|
|
140
|
+
"EventListResponse",
|
|
141
|
+
"ProInterestResponse",
|
|
142
|
+
# Usage & Rate Limit
|
|
143
|
+
"UsageInfo",
|
|
144
|
+
"RateLimitInfo",
|
|
145
|
+
# Exceptions
|
|
146
|
+
"MemsyError",
|
|
147
|
+
"MemsyConnectionError",
|
|
148
|
+
"MemsyAPIError",
|
|
149
|
+
"AuthenticationError",
|
|
150
|
+
"AuthorizationError",
|
|
151
|
+
"FeatureNotAvailable",
|
|
152
|
+
"OrgIdNotAllowedError",
|
|
153
|
+
"SeatRequiredError",
|
|
154
|
+
"OrgLimitReachedError",
|
|
155
|
+
"KeyLimitReachedError",
|
|
156
|
+
"BillingNotEnabledError",
|
|
157
|
+
"SeatLimitReachedError",
|
|
158
|
+
"RateLimitExceeded",
|
|
159
|
+
"UsageLimitExceeded",
|
|
160
|
+
]
|
memsy/_http.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from memsy.exceptions import (
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
AuthorizationError,
|
|
10
|
+
BillingNotEnabledError,
|
|
11
|
+
FeatureNotAvailable,
|
|
12
|
+
KeyLimitReachedError,
|
|
13
|
+
MemsyAPIError,
|
|
14
|
+
OrgIdNotAllowedError,
|
|
15
|
+
OrgLimitReachedError,
|
|
16
|
+
RateLimitExceeded,
|
|
17
|
+
SeatLimitReachedError,
|
|
18
|
+
SeatRequiredError,
|
|
19
|
+
UsageLimitExceeded,
|
|
20
|
+
)
|
|
21
|
+
from memsy.models import RateLimitInfo, UsageInfo
|
|
22
|
+
|
|
23
|
+
DEFAULT_MAX_RETRIES = 3
|
|
24
|
+
DEFAULT_RETRY_BACKOFF = 1.0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _detail_from_body(body: dict[str, Any], fallback: str = "") -> str:
|
|
28
|
+
"""Extract a human-readable detail string from a parsed error body."""
|
|
29
|
+
detail = body.get("detail")
|
|
30
|
+
if isinstance(detail, dict):
|
|
31
|
+
return detail.get("message", "") or detail.get("error", "")
|
|
32
|
+
if isinstance(detail, str) and detail:
|
|
33
|
+
return detail
|
|
34
|
+
return body.get("message", "") or body.get("error", "") or fallback
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _get_error_body(response: httpx.Response) -> tuple[dict[str, Any], str | None]:
|
|
38
|
+
"""Return (effective_body_dict, error_code) from a non-2xx response.
|
|
39
|
+
|
|
40
|
+
Unwraps FastAPI's {"detail": {...}} envelope when the detail value is a dict.
|
|
41
|
+
"""
|
|
42
|
+
try:
|
|
43
|
+
body = response.json()
|
|
44
|
+
except Exception:
|
|
45
|
+
return {}, None
|
|
46
|
+
|
|
47
|
+
detail = body.get("detail")
|
|
48
|
+
effective: dict[str, Any] = {**body, **detail} if isinstance(detail, dict) else body
|
|
49
|
+
return effective, effective.get("error")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class HttpCoreMixin:
|
|
53
|
+
"""Shared HTTP helpers for MemsyClient and MemsyControlClient.
|
|
54
|
+
|
|
55
|
+
Provides header parsing and error classification. The _request method
|
|
56
|
+
is not shared because sync vs async implementations differ.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def _parse_response_headers(
|
|
60
|
+
self, response: httpx.Response
|
|
61
|
+
) -> tuple[UsageInfo | None, RateLimitInfo | None]:
|
|
62
|
+
# Pass response.headers directly — it's case-insensitive so header names resolve
|
|
63
|
+
# correctly. Converting to dict() would lowercase keys and break lookups.
|
|
64
|
+
usage = UsageInfo.from_headers(response.headers)
|
|
65
|
+
rate_limit = RateLimitInfo.from_headers(response.headers)
|
|
66
|
+
usage = usage if any(v is not None for v in vars(usage).values()) else None
|
|
67
|
+
rate_limit = (
|
|
68
|
+
rate_limit if rate_limit.limit is not None or rate_limit.remaining is not None else None
|
|
69
|
+
)
|
|
70
|
+
return usage, rate_limit
|
|
71
|
+
|
|
72
|
+
def _classify_error(self, response: httpx.Response) -> MemsyAPIError:
|
|
73
|
+
status_code = response.status_code
|
|
74
|
+
# Single JSON parse covers both error-code dispatch and detail extraction.
|
|
75
|
+
body, error_code = _get_error_body(response)
|
|
76
|
+
detail = _detail_from_body(body, response.text)
|
|
77
|
+
|
|
78
|
+
if status_code == 400 and error_code == "org_id_not_allowed":
|
|
79
|
+
return OrgIdNotAllowedError(
|
|
80
|
+
f"org_id not allowed on this tier: {detail}",
|
|
81
|
+
status_code=status_code,
|
|
82
|
+
detail=detail,
|
|
83
|
+
error_code=error_code,
|
|
84
|
+
response=response,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
if status_code == 401:
|
|
88
|
+
return AuthenticationError(
|
|
89
|
+
f"Authentication failed: {detail}",
|
|
90
|
+
status_code=status_code,
|
|
91
|
+
detail=detail,
|
|
92
|
+
error_code=error_code,
|
|
93
|
+
response=response,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
if status_code == 403:
|
|
97
|
+
if error_code == "feature_not_available":
|
|
98
|
+
return FeatureNotAvailable(
|
|
99
|
+
f"Feature not available: {detail}",
|
|
100
|
+
status_code=status_code,
|
|
101
|
+
detail=detail,
|
|
102
|
+
error_code=error_code,
|
|
103
|
+
response=response,
|
|
104
|
+
feature=body.get("feature"),
|
|
105
|
+
current_tier=body.get("current_tier"),
|
|
106
|
+
upgrade_url=body.get("upgrade_url"),
|
|
107
|
+
)
|
|
108
|
+
if error_code == "seat_required":
|
|
109
|
+
return SeatRequiredError(
|
|
110
|
+
f"Seat required: {detail}",
|
|
111
|
+
status_code=status_code,
|
|
112
|
+
detail=detail,
|
|
113
|
+
error_code=error_code,
|
|
114
|
+
response=response,
|
|
115
|
+
)
|
|
116
|
+
if error_code == "org_limit_reached":
|
|
117
|
+
return OrgLimitReachedError(
|
|
118
|
+
f"Org limit reached: {detail}",
|
|
119
|
+
status_code=status_code,
|
|
120
|
+
detail=detail,
|
|
121
|
+
error_code=error_code,
|
|
122
|
+
response=response,
|
|
123
|
+
limit=body.get("limit"),
|
|
124
|
+
current=body.get("current"),
|
|
125
|
+
)
|
|
126
|
+
if error_code == "key_limit_reached":
|
|
127
|
+
return KeyLimitReachedError(
|
|
128
|
+
f"API key limit reached: {detail}",
|
|
129
|
+
status_code=status_code,
|
|
130
|
+
detail=detail,
|
|
131
|
+
error_code=error_code,
|
|
132
|
+
response=response,
|
|
133
|
+
limit=body.get("limit"),
|
|
134
|
+
current=body.get("current"),
|
|
135
|
+
)
|
|
136
|
+
if error_code == "billing_not_enabled":
|
|
137
|
+
return BillingNotEnabledError(
|
|
138
|
+
f"Billing not enabled: {detail}",
|
|
139
|
+
status_code=status_code,
|
|
140
|
+
detail=detail,
|
|
141
|
+
error_code=error_code,
|
|
142
|
+
response=response,
|
|
143
|
+
interest_path=body.get("interest_path"),
|
|
144
|
+
)
|
|
145
|
+
if error_code in ("wrong_scope", "insufficient_scope") or "scope" in detail.lower():
|
|
146
|
+
return AuthorizationError(
|
|
147
|
+
f"Authorization failed: {detail}",
|
|
148
|
+
status_code=status_code,
|
|
149
|
+
detail=detail,
|
|
150
|
+
error_code=error_code,
|
|
151
|
+
response=response,
|
|
152
|
+
required_scope=body.get("required_scope") or body.get("scope"),
|
|
153
|
+
)
|
|
154
|
+
return AuthorizationError(
|
|
155
|
+
f"Authorization failed: {detail}",
|
|
156
|
+
status_code=status_code,
|
|
157
|
+
detail=detail,
|
|
158
|
+
error_code=error_code,
|
|
159
|
+
response=response,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
if status_code == 409 and error_code == "seat_limit_reached":
|
|
163
|
+
return SeatLimitReachedError(
|
|
164
|
+
f"Seat limit reached: {detail}",
|
|
165
|
+
status_code=status_code,
|
|
166
|
+
detail=detail,
|
|
167
|
+
error_code=error_code,
|
|
168
|
+
response=response,
|
|
169
|
+
purchased_seats=body.get("purchased_seats"),
|
|
170
|
+
assigned_seats=body.get("assigned_seats"),
|
|
171
|
+
pending_invites=body.get("pending_invites"),
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
if status_code == 429:
|
|
175
|
+
retry_after = response.headers.get("Retry-After")
|
|
176
|
+
retry_after_float = float(retry_after) if retry_after else None
|
|
177
|
+
if error_code == "usage_limit_exceeded" or "quota" in detail.lower():
|
|
178
|
+
return UsageLimitExceeded(
|
|
179
|
+
f"Usage limit exceeded: {detail}",
|
|
180
|
+
status_code=status_code,
|
|
181
|
+
detail=detail,
|
|
182
|
+
error_code=error_code,
|
|
183
|
+
response=response,
|
|
184
|
+
dimension=body.get("dimension"),
|
|
185
|
+
current=body.get("current"),
|
|
186
|
+
limit=body.get("limit"),
|
|
187
|
+
upgrade_url=body.get("upgrade_url"),
|
|
188
|
+
)
|
|
189
|
+
return RateLimitExceeded(
|
|
190
|
+
f"Rate limit exceeded: {detail}",
|
|
191
|
+
status_code=status_code,
|
|
192
|
+
detail=detail,
|
|
193
|
+
error_code=error_code,
|
|
194
|
+
response=response,
|
|
195
|
+
retry_after=retry_after_float,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
return MemsyAPIError(
|
|
199
|
+
f"Memsy API error {status_code}: {detail}",
|
|
200
|
+
status_code=status_code,
|
|
201
|
+
detail=detail,
|
|
202
|
+
error_code=error_code,
|
|
203
|
+
response=response,
|
|
204
|
+
)
|
memsy/async_client.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from memsy._http import DEFAULT_MAX_RETRIES, DEFAULT_RETRY_BACKOFF, HttpCoreMixin
|
|
9
|
+
from memsy.exceptions import MemsyAPIError, MemsyConnectionError
|
|
10
|
+
from memsy.models import (
|
|
11
|
+
ClearResponse,
|
|
12
|
+
EventPayload,
|
|
13
|
+
HealthResponse,
|
|
14
|
+
IngestResponse,
|
|
15
|
+
RateLimitInfo,
|
|
16
|
+
SearchResponse,
|
|
17
|
+
StatusResponse,
|
|
18
|
+
UsageInfo,
|
|
19
|
+
)
|
|
20
|
+
from memsy.resources.memories import AsyncMemoriesResource
|
|
21
|
+
from memsy.resources.orgs import AsyncOrgsResource
|
|
22
|
+
from memsy.resources.roles import AsyncRolesResource
|
|
23
|
+
from memsy.resources.teams import AsyncTeamsResource
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AsyncMemsyClient(HttpCoreMixin):
|
|
27
|
+
"""
|
|
28
|
+
Asynchronous Memsy SDK client for the hot-path memory engine (memsy-core).
|
|
29
|
+
|
|
30
|
+
Usage::
|
|
31
|
+
|
|
32
|
+
async with AsyncMemsyClient(base_url="https://your-api-gateway-url", api_key="***") as c:
|
|
33
|
+
health = await client.health()
|
|
34
|
+
|
|
35
|
+
# or manage lifecycle manually
|
|
36
|
+
client = AsyncMemsyClient(base_url="...", api_key="***")
|
|
37
|
+
try:
|
|
38
|
+
results = await client.search("what does the user prefer?")
|
|
39
|
+
finally:
|
|
40
|
+
await client.close()
|
|
41
|
+
|
|
42
|
+
Sub-resource accessors::
|
|
43
|
+
|
|
44
|
+
await client.orgs.create(org_id="my-org", name="My Org", focus="...")
|
|
45
|
+
await client.roles.list(org_id="my-org")
|
|
46
|
+
await client.memories.stats()
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
base_url: str,
|
|
52
|
+
api_key: str,
|
|
53
|
+
timeout: float = 30.0,
|
|
54
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
55
|
+
retry_backoff: float = DEFAULT_RETRY_BACKOFF,
|
|
56
|
+
) -> None:
|
|
57
|
+
self._base_url = base_url.rstrip("/")
|
|
58
|
+
self._api_key = api_key
|
|
59
|
+
self._max_retries = max_retries
|
|
60
|
+
self._retry_backoff = retry_backoff
|
|
61
|
+
self._client = httpx.AsyncClient(
|
|
62
|
+
base_url=self._base_url,
|
|
63
|
+
timeout=timeout,
|
|
64
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
65
|
+
)
|
|
66
|
+
self.orgs = AsyncOrgsResource(self)
|
|
67
|
+
self.roles = AsyncRolesResource(self)
|
|
68
|
+
self.teams = AsyncTeamsResource(self)
|
|
69
|
+
self.memories = AsyncMemoriesResource(self)
|
|
70
|
+
|
|
71
|
+
async def __aenter__(self) -> AsyncMemsyClient:
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
75
|
+
await self.close()
|
|
76
|
+
|
|
77
|
+
async def close(self) -> None:
|
|
78
|
+
"""Close the underlying HTTP connection pool."""
|
|
79
|
+
await self._client.aclose()
|
|
80
|
+
|
|
81
|
+
async def _request(
|
|
82
|
+
self, method: str, path: str, **kwargs: Any
|
|
83
|
+
) -> tuple[Any, UsageInfo | None, RateLimitInfo | None]:
|
|
84
|
+
"""Make HTTP request with retry logic for 429s."""
|
|
85
|
+
for attempt in range(self._max_retries + 1):
|
|
86
|
+
try:
|
|
87
|
+
response = await self._client.request(method, path, **kwargs)
|
|
88
|
+
except httpx.ConnectError as e:
|
|
89
|
+
raise MemsyConnectionError(
|
|
90
|
+
f"Could not connect to Memsy at {self._base_url}: {e}"
|
|
91
|
+
) from e
|
|
92
|
+
except httpx.TimeoutException as e:
|
|
93
|
+
raise MemsyConnectionError(f"Request to Memsy timed out: {e}") from e
|
|
94
|
+
|
|
95
|
+
if response.status_code == 429 and attempt < self._max_retries:
|
|
96
|
+
retry_after = response.headers.get("Retry-After")
|
|
97
|
+
wait_time = (
|
|
98
|
+
float(retry_after) if retry_after else self._retry_backoff * (2**attempt)
|
|
99
|
+
)
|
|
100
|
+
await asyncio.sleep(wait_time)
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
usage, rate_limit = self._parse_response_headers(response)
|
|
104
|
+
|
|
105
|
+
if not response.is_success:
|
|
106
|
+
raise self._classify_error(response)
|
|
107
|
+
|
|
108
|
+
if response.status_code == 204 or not response.content:
|
|
109
|
+
return None, usage, rate_limit
|
|
110
|
+
|
|
111
|
+
return response.json(), usage, rate_limit
|
|
112
|
+
|
|
113
|
+
raise MemsyAPIError("Max retries exceeded", status_code=429, detail="")
|
|
114
|
+
|
|
115
|
+
async def ingest(self, events: list[EventPayload]) -> IngestResponse:
|
|
116
|
+
"""
|
|
117
|
+
Ingest a batch of events.
|
|
118
|
+
|
|
119
|
+
:param events: List of EventPayload objects to ingest.
|
|
120
|
+
:returns: IngestResponse with the generated event IDs.
|
|
121
|
+
"""
|
|
122
|
+
body = {"events": [e.to_dict() for e in events]}
|
|
123
|
+
data, usage, rate_limit = await self._request("POST", "/ingest", json=body)
|
|
124
|
+
response = IngestResponse.from_dict(data)
|
|
125
|
+
response.usage = usage
|
|
126
|
+
response.rate_limit = rate_limit
|
|
127
|
+
return response
|
|
128
|
+
|
|
129
|
+
async def search(
|
|
130
|
+
self,
|
|
131
|
+
query: str,
|
|
132
|
+
*,
|
|
133
|
+
actor_id: str | None = None,
|
|
134
|
+
limit: int = 10,
|
|
135
|
+
threshold: float = 0.3,
|
|
136
|
+
include_source_events: bool = False,
|
|
137
|
+
) -> SearchResponse:
|
|
138
|
+
"""
|
|
139
|
+
Search memories.
|
|
140
|
+
|
|
141
|
+
:param query: Natural language query string.
|
|
142
|
+
:param actor_id: Optional actor/user ID to further scope the search.
|
|
143
|
+
:param limit: Maximum number of results to return (default 10).
|
|
144
|
+
:param threshold: Minimum relevance score threshold (default 0.3).
|
|
145
|
+
:param include_source_events: Include source events in result metadata.
|
|
146
|
+
:returns: SearchResponse containing ranked memory results.
|
|
147
|
+
"""
|
|
148
|
+
body: dict[str, Any] = {
|
|
149
|
+
"query": query,
|
|
150
|
+
"limit": limit,
|
|
151
|
+
"threshold": threshold,
|
|
152
|
+
"include_source_events": include_source_events,
|
|
153
|
+
}
|
|
154
|
+
if actor_id is not None:
|
|
155
|
+
body["actor_id"] = actor_id
|
|
156
|
+
data, usage, rate_limit = await self._request("POST", "/search", json=body)
|
|
157
|
+
response = SearchResponse.from_dict(data)
|
|
158
|
+
response.usage = usage
|
|
159
|
+
response.rate_limit = rate_limit
|
|
160
|
+
return response
|
|
161
|
+
|
|
162
|
+
async def status(self, event_ids: list[str]) -> StatusResponse:
|
|
163
|
+
"""
|
|
164
|
+
Check processing status for a set of ingested event IDs.
|
|
165
|
+
|
|
166
|
+
:param event_ids: List of event IDs returned by a previous ingest call.
|
|
167
|
+
:returns: StatusResponse with completed, failed, and pending ID lists.
|
|
168
|
+
"""
|
|
169
|
+
data, usage, rate_limit = await self._request(
|
|
170
|
+
"POST", "/status", json={"event_ids": event_ids}
|
|
171
|
+
)
|
|
172
|
+
response = StatusResponse.from_dict(data)
|
|
173
|
+
response.usage = usage
|
|
174
|
+
response.rate_limit = rate_limit
|
|
175
|
+
return response
|
|
176
|
+
|
|
177
|
+
async def health(self) -> HealthResponse:
|
|
178
|
+
"""
|
|
179
|
+
Check if the Memsy service is healthy.
|
|
180
|
+
|
|
181
|
+
:returns: HealthResponse with status, version, and component health.
|
|
182
|
+
"""
|
|
183
|
+
data, usage, rate_limit = await self._request("GET", "/health")
|
|
184
|
+
response = HealthResponse.from_dict(data)
|
|
185
|
+
response.usage = usage
|
|
186
|
+
response.rate_limit = rate_limit
|
|
187
|
+
return response
|
|
188
|
+
|
|
189
|
+
async def clear(self, container_tag: str) -> ClearResponse:
|
|
190
|
+
"""
|
|
191
|
+
Clear tracking state for a container/conversation tag.
|
|
192
|
+
|
|
193
|
+
:param container_tag: The container tag to clear.
|
|
194
|
+
:returns: ClearResponse with count of deleted items.
|
|
195
|
+
"""
|
|
196
|
+
data, usage, rate_limit = await self._request("DELETE", f"/clear/{container_tag}")
|
|
197
|
+
response = ClearResponse.from_dict(data)
|
|
198
|
+
response.usage = usage
|
|
199
|
+
response.rate_limit = rate_limit
|
|
200
|
+
return response
|
memsy/async_control.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from memsy._http import DEFAULT_MAX_RETRIES, DEFAULT_RETRY_BACKOFF, HttpCoreMixin
|
|
9
|
+
from memsy.control_resources.billing import AsyncBillingResource
|
|
10
|
+
from memsy.control_resources.events import AsyncEventsResource
|
|
11
|
+
from memsy.control_resources.interest import AsyncInterestResource
|
|
12
|
+
from memsy.control_resources.keys import AsyncKeysResource
|
|
13
|
+
from memsy.control_resources.usage import AsyncUsageResource
|
|
14
|
+
from memsy.exceptions import MemsyAPIError, MemsyConnectionError
|
|
15
|
+
from memsy.models import HealthResponse, MeResponse, RateLimitInfo, UsageInfo
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AsyncMemsyControlClient(HttpCoreMixin):
|
|
19
|
+
"""
|
|
20
|
+
Asynchronous client for the Memsy control-plane API (api/).
|
|
21
|
+
|
|
22
|
+
Handles account management, billing, API key lifecycle, usage reporting,
|
|
23
|
+
and event browsing. Separate from ``AsyncMemsyClient`` because the control-plane
|
|
24
|
+
is a distinct service with its own base URL.
|
|
25
|
+
|
|
26
|
+
Usage::
|
|
27
|
+
|
|
28
|
+
async with AsyncMemsyControlClient(
|
|
29
|
+
base_url="https://api.memsy.io/api",
|
|
30
|
+
api_key="msy_...",
|
|
31
|
+
) as control:
|
|
32
|
+
me = await control.me()
|
|
33
|
+
events = await control.events.list(limit=20)
|
|
34
|
+
|
|
35
|
+
Sub-resource accessors::
|
|
36
|
+
|
|
37
|
+
control.usage — AsyncUsageResource
|
|
38
|
+
control.billing — AsyncBillingResource
|
|
39
|
+
control.keys — AsyncKeysResource
|
|
40
|
+
control.events — AsyncEventsResource
|
|
41
|
+
control.interest — AsyncInterestResource
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
base_url: str,
|
|
47
|
+
api_key: str,
|
|
48
|
+
timeout: float = 30.0,
|
|
49
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
50
|
+
retry_backoff: float = DEFAULT_RETRY_BACKOFF,
|
|
51
|
+
) -> None:
|
|
52
|
+
self._base_url = base_url.rstrip("/")
|
|
53
|
+
self._api_key = api_key
|
|
54
|
+
self._max_retries = max_retries
|
|
55
|
+
self._retry_backoff = retry_backoff
|
|
56
|
+
self._client = httpx.AsyncClient(
|
|
57
|
+
base_url=self._base_url,
|
|
58
|
+
timeout=timeout,
|
|
59
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
60
|
+
)
|
|
61
|
+
self.usage = AsyncUsageResource(self)
|
|
62
|
+
self.billing = AsyncBillingResource(self)
|
|
63
|
+
self.keys = AsyncKeysResource(self)
|
|
64
|
+
self.events = AsyncEventsResource(self)
|
|
65
|
+
self.interest = AsyncInterestResource(self)
|
|
66
|
+
|
|
67
|
+
async def __aenter__(self) -> AsyncMemsyControlClient:
|
|
68
|
+
return self
|
|
69
|
+
|
|
70
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
71
|
+
await self.close()
|
|
72
|
+
|
|
73
|
+
async def close(self) -> None:
|
|
74
|
+
"""Close the underlying HTTP connection pool."""
|
|
75
|
+
await self._client.aclose()
|
|
76
|
+
|
|
77
|
+
async def _request(
|
|
78
|
+
self, method: str, path: str, **kwargs: Any
|
|
79
|
+
) -> tuple[Any, UsageInfo | None, RateLimitInfo | None]:
|
|
80
|
+
"""Make HTTP request with retry logic for 429s."""
|
|
81
|
+
for attempt in range(self._max_retries + 1):
|
|
82
|
+
try:
|
|
83
|
+
response = await self._client.request(method, path, **kwargs)
|
|
84
|
+
except httpx.ConnectError as e:
|
|
85
|
+
raise MemsyConnectionError(
|
|
86
|
+
f"Could not connect to Memsy control-plane at {self._base_url}: {e}"
|
|
87
|
+
) from e
|
|
88
|
+
except httpx.TimeoutException as e:
|
|
89
|
+
raise MemsyConnectionError(f"Request to Memsy control-plane timed out: {e}") from e
|
|
90
|
+
|
|
91
|
+
if response.status_code == 429 and attempt < self._max_retries:
|
|
92
|
+
retry_after = response.headers.get("Retry-After")
|
|
93
|
+
wait_time = (
|
|
94
|
+
float(retry_after) if retry_after else self._retry_backoff * (2**attempt)
|
|
95
|
+
)
|
|
96
|
+
await asyncio.sleep(wait_time)
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
usage, rate_limit = self._parse_response_headers(response)
|
|
100
|
+
|
|
101
|
+
if not response.is_success:
|
|
102
|
+
raise self._classify_error(response)
|
|
103
|
+
|
|
104
|
+
if response.status_code == 204 or not response.content:
|
|
105
|
+
return None, usage, rate_limit
|
|
106
|
+
|
|
107
|
+
return response.json(), usage, rate_limit
|
|
108
|
+
|
|
109
|
+
raise MemsyAPIError("Max retries exceeded", status_code=429, detail="")
|
|
110
|
+
|
|
111
|
+
async def me(self) -> MeResponse:
|
|
112
|
+
"""Return identity information for the authenticated caller."""
|
|
113
|
+
data, _, _ = await self._request("GET", "/me")
|
|
114
|
+
return MeResponse.from_dict(data)
|
|
115
|
+
|
|
116
|
+
async def health(self) -> HealthResponse:
|
|
117
|
+
"""Check if the Memsy control-plane is healthy."""
|
|
118
|
+
data, _, _ = await self._request("GET", "/health")
|
|
119
|
+
return HealthResponse.from_dict(data)
|