ains-brain 0.1.0b1__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.
Files changed (73) hide show
  1. ains_brain-0.1.0b1/PKG-INFO +23 -0
  2. ains_brain-0.1.0b1/README.md +4 -0
  3. ains_brain-0.1.0b1/ains_brain/__init__.py +394 -0
  4. ains_brain-0.1.0b1/ains_brain/py.typed +0 -0
  5. ains_brain-0.1.0b1/ains_brain.egg-info/PKG-INFO +23 -0
  6. ains_brain-0.1.0b1/ains_brain.egg-info/SOURCES.txt +71 -0
  7. ains_brain-0.1.0b1/ains_brain.egg-info/dependency_links.txt +1 -0
  8. ains_brain-0.1.0b1/ains_brain.egg-info/requires.txt +2 -0
  9. ains_brain-0.1.0b1/ains_brain.egg-info/top_level.txt +2 -0
  10. ains_brain-0.1.0b1/ains_brain_api/__init__.py +8 -0
  11. ains_brain-0.1.0b1/ains_brain_api/api/__init__.py +1 -0
  12. ains_brain-0.1.0b1/ains_brain_api/api/default/__init__.py +1 -0
  13. ains_brain-0.1.0b1/ains_brain_api/api/default/correct.py +253 -0
  14. ains_brain-0.1.0b1/ains_brain_api/api/default/create_grant.py +253 -0
  15. ains_brain-0.1.0b1/ains_brain_api/api/default/delete_user.py +235 -0
  16. ains_brain-0.1.0b1/ains_brain_api/api/default/export_user.py +230 -0
  17. ains_brain-0.1.0b1/ains_brain_api/api/default/health.py +128 -0
  18. ains_brain-0.1.0b1/ains_brain_api/api/default/history.py +255 -0
  19. ains_brain-0.1.0b1/ains_brain_api/api/default/list_access.py +250 -0
  20. ains_brain-0.1.0b1/ains_brain_api/api/default/list_facts.py +289 -0
  21. ains_brain-0.1.0b1/ains_brain_api/api/default/list_grants.py +230 -0
  22. ains_brain-0.1.0b1/ains_brain_api/api/default/openapi.py +128 -0
  23. ains_brain-0.1.0b1/ains_brain_api/api/default/recall.py +237 -0
  24. ains_brain-0.1.0b1/ains_brain_api/api/default/request_status.py +195 -0
  25. ains_brain-0.1.0b1/ains_brain_api/api/default/retain.py +253 -0
  26. ains_brain-0.1.0b1/ains_brain_api/api/default/revoke_grant.py +249 -0
  27. ains_brain-0.1.0b1/ains_brain_api/api/default/status.py +128 -0
  28. ains_brain-0.1.0b1/ains_brain_api/client.py +280 -0
  29. ains_brain-0.1.0b1/ains_brain_api/errors.py +16 -0
  30. ains_brain-0.1.0b1/ains_brain_api/models/__init__.py +87 -0
  31. ains_brain-0.1.0b1/ains_brain_api/models/access_info.py +88 -0
  32. ains_brain-0.1.0b1/ains_brain_api/models/access_info_op.py +12 -0
  33. ains_brain-0.1.0b1/ains_brain_api/models/access_response.py +83 -0
  34. ains_brain-0.1.0b1/ains_brain_api/models/change.py +137 -0
  35. ains_brain-0.1.0b1/ains_brain_api/models/change_kind.py +13 -0
  36. ains_brain-0.1.0b1/ains_brain_api/models/correction_request.py +82 -0
  37. ains_brain-0.1.0b1/ains_brain_api/models/correction_request_kind.py +9 -0
  38. ains_brain-0.1.0b1/ains_brain_api/models/correction_response.py +116 -0
  39. ains_brain-0.1.0b1/ains_brain_api/models/delete_response.py +94 -0
  40. ains_brain-0.1.0b1/ains_brain_api/models/error_body.py +90 -0
  41. ains_brain-0.1.0b1/ains_brain_api/models/error_body_code.py +23 -0
  42. ains_brain-0.1.0b1/ains_brain_api/models/error_response.py +67 -0
  43. ains_brain-0.1.0b1/ains_brain_api/models/export_response.py +84 -0
  44. ains_brain-0.1.0b1/ains_brain_api/models/export_response_sections.py +82 -0
  45. ains_brain-0.1.0b1/ains_brain_api/models/export_response_sections_additional_property_item.py +47 -0
  46. ains_brain-0.1.0b1/ains_brain_api/models/fact.py +120 -0
  47. ains_brain-0.1.0b1/ains_brain_api/models/fact_ref.py +83 -0
  48. ains_brain-0.1.0b1/ains_brain_api/models/facts_response.py +114 -0
  49. ains_brain-0.1.0b1/ains_brain_api/models/grant_info.py +157 -0
  50. ains_brain-0.1.0b1/ains_brain_api/models/grant_info_scope.py +9 -0
  51. ains_brain-0.1.0b1/ains_brain_api/models/grant_request.py +84 -0
  52. ains_brain-0.1.0b1/ains_brain_api/models/grant_request_scope.py +9 -0
  53. ains_brain-0.1.0b1/ains_brain_api/models/grants_response.py +83 -0
  54. ains_brain-0.1.0b1/ains_brain_api/models/health_response.py +61 -0
  55. ains_brain-0.1.0b1/ains_brain_api/models/history_response.py +93 -0
  56. ains_brain-0.1.0b1/ains_brain_api/models/openapi_response_200.py +45 -0
  57. ains_brain-0.1.0b1/ains_brain_api/models/pending_response.py +88 -0
  58. ains_brain-0.1.0b1/ains_brain_api/models/pending_response_status.py +8 -0
  59. ains_brain-0.1.0b1/ains_brain_api/models/recall_request.py +103 -0
  60. ains_brain-0.1.0b1/ains_brain_api/models/recall_response.py +91 -0
  61. ains_brain-0.1.0b1/ains_brain_api/models/recalled_fact.py +185 -0
  62. ains_brain-0.1.0b1/ains_brain_api/models/recalled_fact_status.py +10 -0
  63. ains_brain-0.1.0b1/ains_brain_api/models/request_status_response.py +98 -0
  64. ains_brain-0.1.0b1/ains_brain_api/models/request_status_response_op.py +9 -0
  65. ains_brain-0.1.0b1/ains_brain_api/models/request_status_response_status.py +11 -0
  66. ains_brain-0.1.0b1/ains_brain_api/models/retain_request.py +83 -0
  67. ains_brain-0.1.0b1/ains_brain_api/models/retain_response.py +118 -0
  68. ains_brain-0.1.0b1/ains_brain_api/models/status_response.py +72 -0
  69. ains_brain-0.1.0b1/ains_brain_api/models/status_response_status.py +9 -0
  70. ains_brain-0.1.0b1/ains_brain_api/models/superseded_fact.py +77 -0
  71. ains_brain-0.1.0b1/ains_brain_api/types.py +54 -0
  72. ains_brain-0.1.0b1/pyproject.toml +34 -0
  73. ains_brain-0.1.0b1/setup.cfg +4 -0
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: ains-brain
3
+ Version: 0.1.0b1
4
+ Summary: Official Python client for the AINS Brain API: dated long-term memory for AI agents.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://brain.ai-no-te.io
7
+ Project-URL: Repository, https://github.com/union-mate/ains-brain-sdk
8
+ Keywords: ains,ains-brain,ai-memory,agent-memory,long-term-memory
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: httpx2<3,>=2.13.1
18
+ Requires-Dist: attrs>=22.2.0
19
+
20
+ # ains-brain (Python)
21
+
22
+ Client for the AINS Brain API. `from ains_brain import AinsBrain`. See ../README.md for how the client is
23
+ generated and tested.
@@ -0,0 +1,4 @@
1
+ # ains-brain (Python)
2
+
3
+ Client for the AINS Brain API. `from ains_brain import AinsBrain`. See ../README.md for how the client is
4
+ generated and tested.
@@ -0,0 +1,394 @@
1
+ """AINS Brain: the Python client (Python 3.11+).
2
+
3
+ Requests are built by ains_brain_api, which is generated from the gateway's OpenAPI document
4
+ (``./generate.sh``); this module is the thin layer on top: retries, idempotency keys and typed errors.
5
+
6
+ Every call made with the key (except get_request) carries an Idempotency-Key that stays the same across retries, so
7
+ a retried call is stored and charged once, even when the first answer was lost on the way back. Errors are typed: catch
8
+ BalanceEmptyError to tell your user to top up, AinsBrainError for all.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import datetime as _dt
14
+ import email.utils
15
+ import random
16
+ import re
17
+ import time
18
+ import uuid
19
+ from collections.abc import Callable, Iterator
20
+ from typing import Any
21
+
22
+ import httpx2
23
+
24
+ from ains_brain_api import Client as _Client
25
+ from ains_brain_api.api.default import correct as _correct
26
+ from ains_brain_api.api.default import create_grant as _create_grant
27
+ from ains_brain_api.api.default import delete_user as _delete_user
28
+ from ains_brain_api.api.default import export_user as _export_user
29
+ from ains_brain_api.api.default import health as _health
30
+ from ains_brain_api.api.default import history as _history
31
+ from ains_brain_api.api.default import list_access as _list_access
32
+ from ains_brain_api.api.default import list_facts as _list_facts
33
+ from ains_brain_api.api.default import list_grants as _list_grants
34
+ from ains_brain_api.api.default import recall as _recall
35
+ from ains_brain_api.api.default import request_status as _request_status
36
+ from ains_brain_api.api.default import retain as _retain
37
+ from ains_brain_api.api.default import revoke_grant as _revoke_grant
38
+ from ains_brain_api.api.default import status as _status
39
+ from ains_brain_api.models import (CorrectionRequest, CorrectionRequestKind, GrantRequest, GrantRequestScope, RecallRequest,
40
+ RetainRequest)
41
+ from ains_brain_api.types import UNSET
42
+
43
+ __all__ = [
44
+ "AinsBrain", "AinsBrainError", "InvalidRequestError", "AuthenticationError", "BalanceEmptyError",
45
+ "ReadOnlyKeyError", "NotFoundError", "ConflictError", "IdempotencyConflictError", "IdempotencyInProgressError", "UnderReviewError", "TooLargeError", "RateLimitError", "UnavailableError", "TemporarilyUnavailableError", "AtCapacityError", "ConnectionError",
46
+ "InvalidResponseError", "NotStoredError", "is_pending", "DEFAULT_BASE_URL", "DEFAULT_WAIT_SECONDS",
47
+ ]
48
+ __version__ = "1.0.0"
49
+
50
+ Time = str | _dt.datetime # RFC 3339, e.g. "2026-06-01T09:00:00Z", or an aware datetime
51
+
52
+ # wait_for_request's default, in seconds: the gateway settles a 202 about pending.settled_after_seconds (300 s) after the call,
53
+ # on a sweep every pending.sweep_every_seconds (60 s) (its limits.json, copied to site/truth/gateway_limits.json; a test keeps
54
+ # this at least their sum), plus a minute's margin.
55
+ DEFAULT_WAIT_SECONDS = 420.0
56
+ _now = time.monotonic # wait_for_request's clock (tests replace it)
57
+
58
+
59
+ class AinsBrainError(Exception):
60
+ """status: the HTTP status (0 when no answer came); code: the API's error code; request_id: the
61
+ gateway's id for the request (X-Request-Id or error.request_id), when the answer had one; idempotency_key: the
62
+ Idempotency-Key the call was sent with. After a connection error or a timeout a write may have been stored:
63
+ resend it only with this same key (a new key could store it twice)."""
64
+
65
+ def __init__(self, message: str, status: int, code: str, request_id: str | None = None):
66
+ super().__init__(message)
67
+ self.status, self.code, self.request_id = status, code, request_id
68
+ self.retry_after: float | None = None
69
+ self.idempotency_key: str | None = None
70
+
71
+ def __repr__(self):
72
+ return f"{type(self).__name__}(status={self.status}, code={self.code!r}, request_id={self.request_id!r}, message={str(self)!r})"
73
+
74
+
75
+ class InvalidRequestError(AinsBrainError): pass
76
+ class AuthenticationError(AinsBrainError): pass
77
+ class BalanceEmptyError(AinsBrainError): pass
78
+ class ReadOnlyKeyError(AinsBrainError):
79
+ """403 read_only_key: the key can only read."""
80
+ class NotFoundError(AinsBrainError): pass
81
+ class ConflictError(AinsBrainError): pass
82
+ class IdempotencyConflictError(ConflictError):
83
+ """409 idempotency_conflict: the Idempotency-Key was used with a different request, or (IdempotencyInProgressError)
84
+ its first request is still running."""
85
+ class IdempotencyInProgressError(IdempotencyConflictError):
86
+ """409 idempotency_conflict because the first request with this key is still running (not a different request).
87
+ Retried with backoff and the same key; raised when it is still running after the retries."""
88
+ class UnderReviewError(ConflictError):
89
+ """409 under_review (retain only): the first retain with this Idempotency-Key went to review (its outcome could not be told; a
90
+ person settles it). Not retried. status_url is the first request's status URL, as the API sends it; first_request_id is its id
91
+ for get_request / wait_for_request. Send new work with a new key."""
92
+ status_url: str | None = None
93
+ first_request_id: str | None = None
94
+ class TooLargeError(AinsBrainError): pass
95
+ class RateLimitError(AinsBrainError): pass
96
+ class UnavailableError(AinsBrainError): pass
97
+ class TemporarilyUnavailableError(UnavailableError):
98
+ """503 temporarily_unavailable: the balance cannot be checked right now (retried)."""
99
+ class AtCapacityError(UnavailableError):
100
+ """503 at_capacity: no room for new end users right now (not retried: it does not clear in seconds)."""
101
+ class ConnectionError(AinsBrainError): pass # noqa: A001 (shadows the builtin inside this module only)
102
+ class InvalidResponseError(AinsBrainError):
103
+ """A success status whose body is not the JSON the API promises."""
104
+ class NotStoredError(UnavailableError):
105
+ """502 not_stored: the memory could not be written; nothing was stored or charged. Retried with the same key."""
106
+
107
+
108
+ _BY_STATUS = {400: InvalidRequestError, 401: AuthenticationError, 402: BalanceEmptyError, 403: ReadOnlyKeyError, 404: NotFoundError,
109
+ 409: ConflictError, 413: TooLargeError, 429: RateLimitError}
110
+
111
+
112
+ _BY_CODE = {"idempotency_conflict": IdempotencyConflictError, "temporarily_unavailable": TemporarilyUnavailableError,
113
+ "at_capacity": AtCapacityError, "not_stored": NotStoredError, "under_review": UnderReviewError}
114
+
115
+
116
+ # The API's public address (config/hosts.json "api"; a test keeps them equal).
117
+ DEFAULT_BASE_URL = "https://api-brain.ai-no-te.io"
118
+
119
+
120
+ def is_pending(answer: Any) -> bool:
121
+ """True for a write answered 202: its outcome is not known yet. Read it with get_request or wait_for_request before
122
+ sending it again; answer["idempotency_key"] (added by the SDK) is the key to resend with if it says not_stored."""
123
+ return isinstance(answer, dict) and answer.get("status") == "pending" and isinstance(answer.get("request_id"), str)
124
+
125
+
126
+ # the gateway's two 409 idempotency_conflict answers share a code; only the words tell "still running" apart
127
+ _STILL_RUNNING = re.compile(r"still running|is being created", re.I)
128
+
129
+
130
+ def _retryable(e: AinsBrainError) -> bool:
131
+ return ((e.status == 429 or e.status >= 500) and e.code != "at_capacity") or isinstance(e, IdempotencyInProgressError)
132
+
133
+
134
+ class AinsBrain:
135
+ def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, max_retries: int = 2,
136
+ timeout: float = 30.0, max_retry_delay: float = 60.0, sleep: Callable[[float], Any] = time.sleep,
137
+ write_timeout: float = 300.0):
138
+ """max_retries: retries after the first try, for network errors, 429 and 5xx. timeout: seconds per try for reads.
139
+ write_timeout: seconds per try for writes (retain, correct, delete_user), default 300: the gateway may hold a
140
+ write up to 240 s before it answers 202 (pending). max_retry_delay: the longest wait between tries in seconds,
141
+ Retry-After included."""
142
+ if not api_key:
143
+ raise ValueError("api_key is required: create one in the console.")
144
+ self._key = api_key
145
+ self._base = base_url.rstrip("/")
146
+ self._retries = max_retries
147
+ self._timeout = timeout
148
+ self._write_timeout = write_timeout
149
+ self._max_delay = max_retry_delay
150
+ self._sleep = sleep
151
+ self._api = _Client(base_url=self._base, timeout=httpx2.Timeout(timeout),
152
+ headers={"accept": "application/json", "user-agent": f"ains-brain-python/{__version__}"})
153
+
154
+ def __repr__(self):
155
+ return f"AinsBrain(base_url={self._base!r})"
156
+
157
+ def close(self) -> None:
158
+ """Close the connection pool (also done by ``with AinsBrain(...) as brain:``)."""
159
+ self._api.get_httpx_client().close()
160
+
161
+ def __enter__(self):
162
+ return self
163
+
164
+ def __exit__(self, *exc):
165
+ self.close()
166
+
167
+ # --- the API. as_user_id: another of your end users acting on user_id's memory under a live grant (sent as the
168
+ # AINS-As-User header). Every call with the key carries an Idempotency-Key, the same on every retry.
169
+ def retain(self, user_id: str, text: str, occurred_at: Time | None = None, idempotency_key: str | None = None, *,
170
+ as_user_id: str | None = None) -> dict:
171
+ """Store what an end user said. as_user_id needs a read_write grant. A 202 answer (outcome not known yet) is
172
+ returned as a pending dict: see is_pending and wait_for_request."""
173
+ body = RetainRequest(user_id=user_id, text=text, occurred_at=_time("occurred_at", occurred_at))
174
+ return self._send(_retain._get_kwargs(body=body, ains_as_user=_opt(as_user_id), idempotency_key=_key(idempotency_key)), write=True)
175
+
176
+ def recall(self, user_id: str, query: str, as_of: Time | None = None, limit: int | None = None,
177
+ idempotency_key: str | None = None, *, as_user_id: str | None = None) -> dict:
178
+ """The facts that answer the query, best first, each with its source text and why. as_of: as things stood then."""
179
+ body = RecallRequest(user_id=user_id, query=query, as_of=_time("as_of", as_of), limit=_opt(limit))
180
+ return self._send(_recall._get_kwargs(body=body, ains_as_user=_opt(as_user_id), idempotency_key=_key(idempotency_key)))
181
+
182
+ def correct(self, user_id: str, fact_id: str, kind: str, note: str | None = None, idempotency_key: str | None = None, *,
183
+ as_user_id: str | None = None) -> dict:
184
+ """kind="update": was true, no longer is (as_user_id needs a read_write grant). kind="never_true": never right
185
+ (only on the end user's own correction, never as another user). A 202 answer is returned as a pending dict."""
186
+ body = CorrectionRequest(user_id=user_id, fact_id=fact_id, kind=CorrectionRequestKind(kind), note=_opt(note))
187
+ return self._send(_correct._get_kwargs(body=body, ains_as_user=_opt(as_user_id), idempotency_key=_key(idempotency_key)), write=True)
188
+
189
+ def list_facts(self, user_id: str, as_of: Time | None = None, limit: int | None = None, cursor: str | None = None,
190
+ idempotency_key: str | None = None, *, as_user_id: str | None = None) -> dict:
191
+ """One page of the end user's current facts (as of as_of, default now)."""
192
+ return self._send(_list_facts._get_kwargs(user_id, as_of=_when("as_of", as_of), limit=_opt(limit), cursor=_opt(cursor),
193
+ ains_as_user=_opt(as_user_id), idempotency_key=_key(idempotency_key)))
194
+
195
+ def iter_facts(self, user_id: str, as_of: Time | None = None, limit: int | None = None, *,
196
+ as_user_id: str | None = None) -> Iterator[dict]:
197
+ """Every fact, following pages. All pages are read as of the first page's as_of, so a set that changes
198
+ while you page is never skipped or repeated."""
199
+ cursor = None
200
+ while True:
201
+ page = self.list_facts(user_id, as_of=as_of, limit=limit, cursor=cursor, as_user_id=as_user_id)
202
+ if as_of is None:
203
+ as_of = page["as_of"]
204
+ yield from page["facts"]
205
+ cursor = page.get("next_cursor")
206
+ if not cursor:
207
+ return
208
+
209
+ def history(self, user_id: str, fact_id: str, idempotency_key: str | None = None, *, as_user_id: str | None = None) -> dict:
210
+ """The change records of one fact, oldest first."""
211
+ return self._send(_history._get_kwargs(user_id, fact_id=fact_id, ains_as_user=_opt(as_user_id), idempotency_key=_key(idempotency_key)))
212
+
213
+ def get_request(self, request_id: str) -> dict:
214
+ """What became of a write answered 202: status pending, stored or not_stored (final), or review (a person settles
215
+ it; never charged twice); and whether it was charged. Sent with no Idempotency-Key: the gateway keeps the first
216
+ answer to a key for 24 h, so a keyed status read would keep answering its first "pending". A NotFoundError
217
+ may be temporary just after the 202 (the outcome is still being recorded): read again, as wait_for_request does;
218
+ never resend the write with a new key."""
219
+ return self._send(_request_status._get_kwargs(request_id)) # no Idempotency-Key: the API ignores one here (every read is current)
220
+
221
+ def wait_for_request(self, pending: dict | str, interval: float = 1.0, timeout: float = DEFAULT_WAIT_SECONDS) -> dict:
222
+ """Reads the write's status until it is no longer pending, or until timeout seconds (default 420: the gateway
223
+ settles a 202 in about 5 to 6 minutes); answers the last status read (still "pending" after the timeout). A
224
+ NotFoundError is read again until the timeout (just after a 202 the outcome may not be recorded yet), then raised.
225
+ If it says not_stored, send the write again with pending["idempotency_key"]."""
226
+ request_id = pending if isinstance(pending, str) else pending["request_id"]
227
+ until = _now() + timeout
228
+ while True:
229
+ st = None
230
+ try:
231
+ st = self.get_request(request_id)
232
+ except NotFoundError:
233
+ if _now() >= until:
234
+ raise
235
+ if (st is not None and st["status"] != "pending") or _now() >= until:
236
+ return st
237
+ self._sleep(min(interval, max(0.0, until - _now())))
238
+
239
+ def delete_user(self, user_id: str, idempotency_key: str | None = None) -> dict:
240
+ """Delete everything stored for this end user. Free; never refused for balance. Keep the receipt. Owner only."""
241
+ return self._send(_delete_user._get_kwargs(user_id, idempotency_key=_key(idempotency_key)), write=True)
242
+
243
+ def export_user(self, user_id: str, idempotency_key: str | None = None) -> dict:
244
+ """Everything stored for this end user, grants and access record included. Never refused for balance. Owner only."""
245
+ return self._send(_export_user._get_kwargs(user_id, idempotency_key=_key(idempotency_key)))
246
+
247
+ def create_grant(self, user_id: str, to_user_id: str, scope: str, expires_at: Time | None = None,
248
+ idempotency_key: str | None = None) -> dict:
249
+ """Let to_user_id use user_id's memory: scope "read", or "read_write" (read, retain, update corrections). Owner only. Free."""
250
+ body = GrantRequest(to_user_id=to_user_id, scope=GrantRequestScope(scope), expires_at=_time("expires_at", expires_at))
251
+ return self._send(_create_grant._get_kwargs(user_id, body=body, idempotency_key=_key(idempotency_key)))
252
+
253
+ def list_grants(self, user_id: str, idempotency_key: str | None = None) -> dict:
254
+ """The grants user_id has made, live or not. Free."""
255
+ return self._send(_list_grants._get_kwargs(user_id, idempotency_key=_key(idempotency_key)))
256
+
257
+ def revoke_grant(self, user_id: str, grant_id: str, idempotency_key: str | None = None) -> dict:
258
+ """Revoke a grant; it stops at once. Free."""
259
+ return self._send(_revoke_grant._get_kwargs(user_id, grant_id, idempotency_key=_key(idempotency_key)))
260
+
261
+ def list_access(self, user_id: str, limit: int | None = None, idempotency_key: str | None = None) -> dict:
262
+ """Every call other users made under user_id's grants, newest first. Free."""
263
+ return self._send(_list_access._get_kwargs(user_id, limit=_opt(limit), idempotency_key=_key(idempotency_key)))
264
+
265
+ def status(self) -> dict:
266
+ """Whether the service can serve memory now: "ok" or "degraded". No key needed."""
267
+ return self._send(_status._get_kwargs(), auth=False)
268
+
269
+ def health(self) -> dict:
270
+ return self._send(_health._get_kwargs(), auth=False)
271
+
272
+ # --- transport: the same request (and Idempotency-Key) on every try
273
+ def _send(self, kwargs: dict, auth: bool = True, write: bool = False) -> dict:
274
+ # a valid id ([A-Za-z0-9._:-]) never needs encoding and the gateway refuses an encoded one: the generated
275
+ # builder quotes ':' as %3A, so it is put back (nothing else in a valid id is ever quoted)
276
+ kwargs["url"] = kwargs["url"].replace("%3A", ":")
277
+ if auth:
278
+ kwargs.setdefault("headers", {})["authorization"] = "Bearer " + self._key
279
+ client = self._api.get_httpx_client()
280
+ per_try = self._write_timeout if write else self._timeout
281
+ kwargs["timeout"] = httpx2.Timeout(per_try)
282
+ key = kwargs.get("headers", {}).get("Idempotency-Key")
283
+
284
+ def with_key(e: AinsBrainError) -> AinsBrainError:
285
+ e.idempotency_key = key
286
+ return e
287
+
288
+ last: AinsBrainError | None = None
289
+ for attempt in range(self._retries + 1):
290
+ if attempt:
291
+ self._sleep(self._delay(attempt, last))
292
+ try:
293
+ r = client.request(**kwargs)
294
+ except httpx2.TimeoutException:
295
+ last = with_key(ConnectionError(f"No answer within {per_try} s.", 0, "timeout"))
296
+ continue
297
+ except httpx2.TransportError as e:
298
+ last = with_key(ConnectionError(f"Could not reach the API: {type(e).__name__}.", 0, "connection_error"))
299
+ continue
300
+ rid = r.headers.get("x-request-id")
301
+ if 200 <= r.status_code < 300:
302
+ try:
303
+ out = r.json()
304
+ if r.status_code == 202 and is_pending(out):
305
+ out["idempotency_key"] = kwargs.get("headers", {}).get("Idempotency-Key")
306
+ return out
307
+ except ValueError:
308
+ raise with_key(InvalidResponseError(f"The API answered {r.status_code} with a body that is not JSON.",
309
+ r.status_code, "invalid_response", rid)) from None
310
+ last = with_key(_error(r, rid))
311
+ if not _retryable(last):
312
+ raise last
313
+ raise last
314
+
315
+ def _delay(self, attempt: int, last: AinsBrainError | None) -> float:
316
+ ra = getattr(last, "retry_after", None)
317
+ if ra is not None:
318
+ return min(ra, self._max_delay)
319
+ return min(self._max_delay, 8.0, 0.5 * 2 ** (attempt - 1)) + random.random() * 0.1
320
+
321
+
322
+ def _error(r: httpx2.Response, rid: str | None) -> AinsBrainError:
323
+ try:
324
+ err = r.json().get("error") or {}
325
+ if not isinstance(err, dict):
326
+ err = {}
327
+ except (ValueError, AttributeError):
328
+ err = {}
329
+ in_progress = err.get("code") == "idempotency_conflict" and bool(_STILL_RUNNING.search(_s(err.get("message")) or ""))
330
+ cls = (IdempotencyInProgressError if in_progress else _BY_CODE.get(err.get("code")) or _BY_STATUS.get(r.status_code)) or (
331
+ UnavailableError if r.status_code >= 500 else AinsBrainError)
332
+ out = cls(_s(err.get("message")) or f"HTTP {r.status_code}", r.status_code, _s(err.get("code")) or f"http_{r.status_code}",
333
+ rid or _s(err.get("request_id")))
334
+ out.retry_after = _retry_after(r.headers.get("retry-after"))
335
+ if isinstance(out, UnderReviewError) and _s(err.get("status_url")):
336
+ out.status_url = err["status_url"]
337
+ m = re.search(r"/v1/requests/([^/?#]+)$", out.status_url)
338
+ out.first_request_id = m.group(1) if m else None
339
+ return out
340
+
341
+
342
+ def _retry_after(h: str | None) -> float | None:
343
+ """Retry-After as seconds or an HTTP date, in seconds."""
344
+ if not h:
345
+ return None
346
+ try:
347
+ return max(0.0, float(h))
348
+ except ValueError:
349
+ pass
350
+ try:
351
+ at = email.utils.parsedate_to_datetime(h)
352
+ except (TypeError, ValueError):
353
+ return None
354
+ return max(0.0, (at - _dt.datetime.now(_dt.timezone.utc)).total_seconds())
355
+
356
+
357
+ def _s(v: Any) -> str | None:
358
+ return v if isinstance(v, str) else None
359
+
360
+
361
+ def _key(k: str | None) -> str:
362
+ return k or "sdk_" + str(uuid.uuid4())
363
+
364
+
365
+ def _opt(v: Any) -> Any:
366
+ return UNSET if v is None else v
367
+
368
+
369
+ def _aware(name: str, t: Time) -> _dt.datetime:
370
+ """t as an aware datetime; a time without a zone is refused here, before any request (the gateway answers 400 to it)."""
371
+ try:
372
+ d = t if isinstance(t, _dt.datetime) else _dt.datetime.fromisoformat(t)
373
+ except (TypeError, ValueError):
374
+ raise ValueError(f"{name} must be an RFC 3339 time with a time zone, for example 2026-06-01T09:00:00Z "
375
+ f"(got {t!r}).") from None
376
+ if d.tzinfo is None or d.utcoffset() is None:
377
+ raise ValueError(f"{name} has no time zone: pass an aware datetime (tzinfo set) or a string ending in Z or +hh:mm, "
378
+ f"for example 2026-06-01T09:00:00Z (got {t!r}).")
379
+ return d
380
+
381
+
382
+ def _time(name: str, t: Time | None) -> Any:
383
+ """A time for a request body: checked for a zone; a string is sent as given."""
384
+ if t is None:
385
+ return UNSET
386
+ d = _aware(name, t)
387
+ return t if isinstance(t, str) else d
388
+
389
+
390
+ def _when(name: str, t: Time | None) -> Any:
391
+ """A time for a query parameter (the generated client sends datetime.isoformat())."""
392
+ if t is None:
393
+ return UNSET
394
+ return _aware(name, t)
File without changes
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: ains-brain
3
+ Version: 0.1.0b1
4
+ Summary: Official Python client for the AINS Brain API: dated long-term memory for AI agents.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://brain.ai-no-te.io
7
+ Project-URL: Repository, https://github.com/union-mate/ains-brain-sdk
8
+ Keywords: ains,ains-brain,ai-memory,agent-memory,long-term-memory
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: httpx2<3,>=2.13.1
18
+ Requires-Dist: attrs>=22.2.0
19
+
20
+ # ains-brain (Python)
21
+
22
+ Client for the AINS Brain API. `from ains_brain import AinsBrain`. See ../README.md for how the client is
23
+ generated and tested.
@@ -0,0 +1,71 @@
1
+ README.md
2
+ pyproject.toml
3
+ ains_brain/__init__.py
4
+ ains_brain/py.typed
5
+ ains_brain.egg-info/PKG-INFO
6
+ ains_brain.egg-info/SOURCES.txt
7
+ ains_brain.egg-info/dependency_links.txt
8
+ ains_brain.egg-info/requires.txt
9
+ ains_brain.egg-info/top_level.txt
10
+ ains_brain_api/__init__.py
11
+ ains_brain_api/client.py
12
+ ains_brain_api/errors.py
13
+ ains_brain_api/types.py
14
+ ains_brain_api/api/__init__.py
15
+ ains_brain_api/api/default/__init__.py
16
+ ains_brain_api/api/default/correct.py
17
+ ains_brain_api/api/default/create_grant.py
18
+ ains_brain_api/api/default/delete_user.py
19
+ ains_brain_api/api/default/export_user.py
20
+ ains_brain_api/api/default/health.py
21
+ ains_brain_api/api/default/history.py
22
+ ains_brain_api/api/default/list_access.py
23
+ ains_brain_api/api/default/list_facts.py
24
+ ains_brain_api/api/default/list_grants.py
25
+ ains_brain_api/api/default/openapi.py
26
+ ains_brain_api/api/default/recall.py
27
+ ains_brain_api/api/default/request_status.py
28
+ ains_brain_api/api/default/retain.py
29
+ ains_brain_api/api/default/revoke_grant.py
30
+ ains_brain_api/api/default/status.py
31
+ ains_brain_api/models/__init__.py
32
+ ains_brain_api/models/access_info.py
33
+ ains_brain_api/models/access_info_op.py
34
+ ains_brain_api/models/access_response.py
35
+ ains_brain_api/models/change.py
36
+ ains_brain_api/models/change_kind.py
37
+ ains_brain_api/models/correction_request.py
38
+ ains_brain_api/models/correction_request_kind.py
39
+ ains_brain_api/models/correction_response.py
40
+ ains_brain_api/models/delete_response.py
41
+ ains_brain_api/models/error_body.py
42
+ ains_brain_api/models/error_body_code.py
43
+ ains_brain_api/models/error_response.py
44
+ ains_brain_api/models/export_response.py
45
+ ains_brain_api/models/export_response_sections.py
46
+ ains_brain_api/models/export_response_sections_additional_property_item.py
47
+ ains_brain_api/models/fact.py
48
+ ains_brain_api/models/fact_ref.py
49
+ ains_brain_api/models/facts_response.py
50
+ ains_brain_api/models/grant_info.py
51
+ ains_brain_api/models/grant_info_scope.py
52
+ ains_brain_api/models/grant_request.py
53
+ ains_brain_api/models/grant_request_scope.py
54
+ ains_brain_api/models/grants_response.py
55
+ ains_brain_api/models/health_response.py
56
+ ains_brain_api/models/history_response.py
57
+ ains_brain_api/models/openapi_response_200.py
58
+ ains_brain_api/models/pending_response.py
59
+ ains_brain_api/models/pending_response_status.py
60
+ ains_brain_api/models/recall_request.py
61
+ ains_brain_api/models/recall_response.py
62
+ ains_brain_api/models/recalled_fact.py
63
+ ains_brain_api/models/recalled_fact_status.py
64
+ ains_brain_api/models/request_status_response.py
65
+ ains_brain_api/models/request_status_response_op.py
66
+ ains_brain_api/models/request_status_response_status.py
67
+ ains_brain_api/models/retain_request.py
68
+ ains_brain_api/models/retain_response.py
69
+ ains_brain_api/models/status_response.py
70
+ ains_brain_api/models/status_response_status.py
71
+ ains_brain_api/models/superseded_fact.py
@@ -0,0 +1,2 @@
1
+ httpx2<3,>=2.13.1
2
+ attrs>=22.2.0
@@ -0,0 +1,2 @@
1
+ ains_brain
2
+ ains_brain_api
@@ -0,0 +1,8 @@
1
+ """A client library for accessing AINS Brain API"""
2
+
3
+ from .client import AuthenticatedClient, Client
4
+
5
+ __all__ = (
6
+ "AuthenticatedClient",
7
+ "Client",
8
+ )
@@ -0,0 +1 @@
1
+ """Contains methods for accessing the API"""
@@ -0,0 +1 @@
1
+ """Contains endpoint functions for accessing the API"""