mirabase 0.4.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.
Files changed (36) hide show
  1. mirabase-0.4.0/CHANGELOG.md +66 -0
  2. mirabase-0.4.0/LICENSE +202 -0
  3. mirabase-0.4.0/MANIFEST.in +1 -0
  4. mirabase-0.4.0/NOTICE +10 -0
  5. mirabase-0.4.0/PKG-INFO +353 -0
  6. mirabase-0.4.0/README.md +328 -0
  7. mirabase-0.4.0/pyproject.toml +42 -0
  8. mirabase-0.4.0/setup.cfg +4 -0
  9. mirabase-0.4.0/src/mirabase/__init__.py +89 -0
  10. mirabase-0.4.0/src/mirabase/_async.py +153 -0
  11. mirabase-0.4.0/src/mirabase/_changes.py +123 -0
  12. mirabase-0.4.0/src/mirabase/_client.py +186 -0
  13. mirabase-0.4.0/src/mirabase/_errors.py +242 -0
  14. mirabase-0.4.0/src/mirabase/_files.py +536 -0
  15. mirabase-0.4.0/src/mirabase/_generated/__init__.py +0 -0
  16. mirabase-0.4.0/src/mirabase/_generated/operations.py +1428 -0
  17. mirabase-0.4.0/src/mirabase/_generated/types.py +2923 -0
  18. mirabase-0.4.0/src/mirabase/_http.py +726 -0
  19. mirabase-0.4.0/src/mirabase/_instants.py +73 -0
  20. mirabase-0.4.0/src/mirabase/_knowledge.py +585 -0
  21. mirabase-0.4.0/src/mirabase/_llm.py +780 -0
  22. mirabase-0.4.0/src/mirabase/_llm_providers.py +171 -0
  23. mirabase-0.4.0/src/mirabase/_llm_proxy.py +218 -0
  24. mirabase-0.4.0/src/mirabase/_llm_threads.py +74 -0
  25. mirabase-0.4.0/src/mirabase/_meta.py +188 -0
  26. mirabase-0.4.0/src/mirabase/_processing.py +379 -0
  27. mirabase-0.4.0/src/mirabase/_resource.py +49 -0
  28. mirabase-0.4.0/src/mirabase/_resources.py +1247 -0
  29. mirabase-0.4.0/src/mirabase/_stream.py +201 -0
  30. mirabase-0.4.0/src/mirabase/_version.py +2 -0
  31. mirabase-0.4.0/src/mirabase/_webhooks.py +119 -0
  32. mirabase-0.4.0/src/mirabase/py.typed +0 -0
  33. mirabase-0.4.0/src/mirabase.egg-info/PKG-INFO +353 -0
  34. mirabase-0.4.0/src/mirabase.egg-info/SOURCES.txt +34 -0
  35. mirabase-0.4.0/src/mirabase.egg-info/dependency_links.txt +1 -0
  36. mirabase-0.4.0/src/mirabase.egg-info/top_level.txt +1 -0
@@ -0,0 +1,66 @@
1
+ # Changelog
2
+
3
+ All notable changes to `mirabase` on PyPI. The Python, TypeScript (`@mirabase/sdk`) and Go SDKs and the CLI release
4
+ together under one number. While the version is `0.x`, a minor release may change the API and says how here.
5
+
6
+ ## 0.4.0
7
+
8
+ ### Added
9
+
10
+ - `MirabasePaymentRequiredError` for 402, on deployments that sell prepaid tokens: `balance_insufficient`,
11
+ `key_token_limit_reached` and `budget_exceeded` (all three in `PAYMENT_REQUIRED_CODES`). Never retried.
12
+ - `error.quota` on 429 `quota_exceeded`: `writes`, `storage_bytes`, `model_tokens` or `model_spend_micro_usd`.
13
+ - Response metadata: `response_meta(result)` and `on_response=` (on the client, and per call through
14
+ `RequestOptions(on_response=...)`) give the request id, the `RateLimit-*` state and, where tokens are sold,
15
+ `Mirabase-Tokens-Charged`, `-Reserved` and `-Remaining` (`ResponseMeta`, `RateLimitInfo`, `TokenUsage`).
16
+ - `allow_insecure_http=` option.
17
+ - `MirabasePreconditionFailedError` (412) and `MirabaseGoneError` (410), subclasses of the conflict and not-found
18
+ errors, so `If-Match` failures and expired cursors can be told from a 409 or a 404.
19
+ - `CHANGELOG.md` in the source distribution.
20
+ - Processing status of a write: `mb.processing.wait(receipt, until=...)` and `wait_all(writes)` wait until a version is
21
+ searchable or every step has ended (`ProcessingError`, `ProcessingTimeout`; `AsyncProcessing` for asyncio);
22
+ `status(version_id)` and `batch_status(version_ids)` read it once.
23
+
24
+ ### Changed
25
+
26
+ - `search`, `context` and `answer` send an `Idempotency-Key`: one per call, the same on every retry, or yours via
27
+ `RequestOptions(idempotency_key=...)`. The service does not charge a repeated billable read with the same key (with the API key,
28
+ operation and body) within 24 hours, so an answer is now retried on a 5xx or a lost connection like a read; a
29
+ streamed answer only while it opens.
30
+ - Date-times always go out as full RFC 3339 with seconds: a string such as `2026-11-22T10:00Z` in a date-time field
31
+ (the service now refuses it with 422) is sent as `2026-11-22T10:00:00Z`; `metadata` is left as given.
32
+
33
+ - **The base URL is checked when the client is made** (`MirabaseConfigError`, `invalid_base_url`). `http://` is
34
+ accepted on loopback, private addresses, `.localhost`, `.local`, `.internal` and one-label service names; a public
35
+ host name over `http://` now needs `allow_insecure_http=True`. A user name or password, a query or fragment, and
36
+ link-local addresses (cloud metadata services, also written as a number such as `http://2852039166`) are refused.
37
+ - Results the API returns as a JSON object or array are a `dict` or `list` subclass that carries the response's
38
+ metadata. They compare equal to the plain value and serialise the same; only `type(result) is dict` changes.
39
+ - A 402 raises `MirabasePaymentRequiredError` instead of a plain `MirabaseError`; `except MirabaseError` still catches
40
+ it.
41
+ - The version moves from `0.3.0rc1` to `0.4.0`, the same number as the TypeScript and Go SDKs and the CLI.
42
+
43
+ ### Security
44
+
45
+ - The API key no longer follows a redirect to another origin. Requests sent through a proxy, or redirected, go through
46
+ `urllib`, whose redirect handler copied the `Authorization` header to whatever host the redirect named; the key is
47
+ now sent as an unredirected header and put back only for a redirect to the same scheme, host and port.
48
+
49
+ ### Migrating from 0.3.0rc1
50
+
51
+ - If you send to a public host over `http://`, switch to `https://` or pass `allow_insecure_http=True`.
52
+ - Replace `type(result) is dict` with `isinstance(result, dict)`.
53
+
54
+ ## 0.3.0rc1
55
+
56
+ - A client pinned with `space=` or `mb.space(id)` limits `search`, `context`, `answer`, `entries.list`,
57
+ `memories.list` and `audit.events` to its Space.
58
+ - `MIRABASE_API_URL` is read from the environment.
59
+ - Conditional and ranged reads: `files.read_if_changed`, `files.read_range`.
60
+ - `str(error)` carries the code, HTTP status, field and request id after the service's sentence.
61
+ - The transport keeps a connection pool.
62
+ - Apache-2.0.
63
+
64
+ ## 0.2.0
65
+
66
+ - First release, distributed as a file from mirabase.dev.
mirabase-0.4.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ include CHANGELOG.md
mirabase-0.4.0/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ Mirabase SDK for Python
2
+ Copyright 2026 Mirabase
3
+
4
+ This product includes software developed at Mirabase (https://mirabase.io).
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this software except in
7
+ compliance with the License. You may obtain a copy of the License in the LICENSE file or at
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ This package contains no third-party code and has no runtime dependencies.
@@ -0,0 +1,353 @@
1
+ Metadata-Version: 2.4
2
+ Name: mirabase
3
+ Version: 0.4.0
4
+ Summary: Python SDK for the Mirabase Developer API: files, knowledge and memory for agents
5
+ Author: Mirabase
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://mirabase.io/developers
8
+ Project-URL: Documentation, https://mirabase.io/developers/sdks
9
+ Keywords: mirabase,agent,memory,knowledge,rag,llm,context,sdk
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ License-File: NOTICE
24
+ Dynamic: license-file
25
+
26
+ # Mirabase SDK for Python
27
+
28
+ One API for files, knowledge and memory. This package is the client for the Mirabase Developer API
29
+ (`https://api.mirabase.io`, `/v2`).
30
+
31
+ - Docs: https://mirabase.io/developers
32
+ - API reference: https://mirabase.io/developers/api
33
+ - For agents and models: https://api.mirabase.io/llms.txt
34
+
35
+ ## Install
36
+
37
+ ```sh
38
+ pip install mirabase # or: uv add mirabase, poetry add mirabase
39
+ ```
40
+
41
+ Every release is also a file on mirabase.io, with its checksum in https://mirabase.io/sdk/SHA256SUMS:
42
+ `pip install https://mirabase.io/sdk/mirabase-0.4.0-py3-none-any.whl`. A version is released when the API that
43
+ matches it is.
44
+
45
+ Python 3.11 or newer. The package has no dependencies (HTTP is the standard library's, with a connection pool) and
46
+ ships type information (`py.typed`).
47
+
48
+ ## Use
49
+
50
+ Create a key in the console (https://console.mirabase.io), then:
51
+
52
+ ```python
53
+ from mirabase import Mirabase
54
+
55
+ mb = Mirabase() # reads MIRABASE_API_KEY and MIRABASE_API_URL, or pass api_key=... and base_url=...
56
+
57
+ # Write a file. It is found by words on the next request; wait_seconds holds the response (up to 10 s) until it is
58
+ # indexed for meaning too, so the answer below can use it.
59
+ mb.files.write("/notes/plan.md", "# Plan\n\nWe ship on Friday. Tina owns the launch.\n", wait_seconds=10)
60
+
61
+ # Search by meaning. The result is a list; hits.partial is true when it may be incomplete.
62
+ hits = mb.search("when do we ship?")
63
+
64
+ # A token-budgeted context pack for your own model.
65
+ pack = mb.context("when do we ship, and who owns it?", budget_tokens=2000)
66
+
67
+ # Or an answer with citations. It abstains when the evidence is not enough.
68
+ answer = mb.answer("When do we ship?")
69
+ print(answer["status"], answer["answer"], answer["citations"])
70
+
71
+ # One Space only: a client pinned with mb.space(id) searches, builds context, answers and lists Entries,
72
+ # memories and audit events in that Space. Name another per call with space=..., others with spaces=[...]
73
+ # where a call takes several, or spaces="all" for every Space the key can read.
74
+ mine = mb.space("spc_123").search("when do we ship?")
75
+ ```
76
+
77
+ `AsyncMirabase` has the same methods for `asyncio`. Every operation of the API is also available as
78
+ a method on `mb.raw`, which is not pinned: it sends what you pass.
79
+
80
+ `base_url` defaults to the `MIRABASE_API_URL` environment variable (an empty value counts as unset), then to
81
+ `https://api.mirabase.io`. The previous address, `https://api.mirabase.dev`, serves the same API and keeps working.
82
+
83
+ White space around the key is ignored, so a key read from a file or a secret that ends with a line break works. A key
84
+ with a line break, a space or any other character that cannot be sent in a header inside it is refused when the client
85
+ is made (`MirabaseConfigError`, code `invalid_api_key`); the message says what kind of character and where, never the
86
+ key. `repr()` of the client and its parts never shows the key.
87
+
88
+ The base URL is checked when the client is made (`MirabaseConfigError`, code `invalid_base_url`): `https://`
89
+ anywhere; `http://` only on loopback, private addresses, `.localhost`, `.local`, `.internal` and one-label service
90
+ names such as `http://mirabase:4379`, unless you pass `allow_insecure_http=True`; no user name, password, query or
91
+ fragment; never a link-local address such as a cloud metadata service. A redirect to another origin does not carry
92
+ the key.
93
+
94
+ The client keeps a few idle connections open; `with Mirabase() as mb:` (or `mb.close()`) closes them, and
95
+ `async with AsyncMirabase() as mb:` (or `await mb.aclose()`) does the same for the async client.
96
+
97
+ `AsyncMirabase` runs each request on a worker thread (`asyncio.to_thread`), so the package needs no HTTP library;
98
+ cancelling a task stops waiting, not the request in flight.
99
+
100
+ ## Lists
101
+
102
+ List methods return a `Paginator`: a `for` loop walks every page on demand (`async for` on `AsyncMirabase`),
103
+ `.take(n)` stops early, and `.pages()` yields whole pages with their cursors.
104
+
105
+ ```python
106
+ for node in mb.tree("/notes"):
107
+ print(node["path"])
108
+ recent = mb.entries.list(limit=20).take(20)
109
+ ```
110
+
111
+ ## Retries, timeouts and idempotency
112
+
113
+ - **Retries.** Up to `max_retries` (default 3) on connection failures, 5xx and 429, with full-jitter exponential
114
+ backoff (0.5 s base, 8 s cap). A `Retry-After` from the service is honoured; one longer than `max_retry_after`
115
+ (default 60 s) is raised as the error instead of waited out.
116
+ - **Only what is safe to repeat.** Reads, and calls that carry an `Idempotency-Key`, are retried. The SDK creates
117
+ the key once per call and sends the same one on every retry: a retried write replays the first result instead of
118
+ writing twice, and a retried `search`, `context` or `answer` is not charged again (the service remembers a key,
119
+ with the API key, operation and body, for 24 hours). Pass `RequestOptions(idempotency_key=...)` to reuse one across
120
+ processes. A streamed answer is retried only while it opens, and is charged when it completes. A call that is not
121
+ safe to repeat (a `DELETE`) is retried on 429 only, which the service sends before doing anything. 402 is never
122
+ retried.
123
+ - **Timeouts.** `timeout` (seconds, default 60) applies to each attempt.
124
+
125
+ ```python
126
+ from mirabase import Mirabase, RequestOptions
127
+
128
+ mb = Mirabase(max_retries=5, timeout=20)
129
+ mb.files.write("/a.md", "x", options=RequestOptions(idempotency_key=job_id, timeout=5))
130
+ mb.answer("When do we ship?", options=RequestOptions(idempotency_key=f"{job_id}:answer")) # not charged twice
131
+ ```
132
+
133
+ **Date-times** go out as full RFC 3339 with seconds: an aware `datetime` is sent as `isoformat()` (a naive one is
134
+ refused), and a string such as `2026-11-22T10:00Z` in a date-time field (`occurred_at`, `reference_time`,
135
+ `filter["occurred_from"]`, ...) is sent as `2026-11-22T10:00:00Z`. Values inside `metadata` are yours and are sent as
136
+ given.
137
+
138
+ ## Usage, cost and rate limits
139
+
140
+ Each response says how much it cost and how much of your rate limit is left. `response_meta(result)` reads it for a
141
+ result the API returned as a JSON object (most calls), and `on_response=` sees every response, retried attempts and
142
+ failures included. `tokens` is set on deployments that sell prepaid tokens, for operations that charge.
143
+
144
+ ```python
145
+ from mirabase import Mirabase, response_meta
146
+
147
+ mb = Mirabase(on_response=lambda meta: metrics.observe(meta.operation, (meta.tokens and meta.tokens.charged) or 0))
148
+ answer = mb.answer("When do we ship?")
149
+ meta = response_meta(answer)
150
+ # ResponseMeta(operation='Retrieval_answer', method='POST', status=200, request_id='req_…',
151
+ # rate_limit=RateLimitInfo(limit=120, remaining=119, reset_seconds=1),
152
+ # tokens=TokenUsage(charged=812, reserved=0, remaining=999188))
153
+ ```
154
+
155
+ A result that carries metadata is still the `dict` (or `list`) the API returned: equal to it, and `json.dumps`
156
+ writes the API's body. A hook that raises is logged once on the `mirabase` logger and does not fail the call.
157
+
158
+ Coming from 0.2.0: there, a client pinned with `space=` or `mb.space(id)` did not limit `search`, `context` and
159
+ `answer` to that Space, and its `entries.list`, `memories.list` and `audit.events` listed every Space the key can
160
+ read. From 0.3.0rc1 on, a pinned client limits all six to its Space.
161
+
162
+ ## Streaming an answer
163
+
164
+ `mb.answer.stream` takes what `mb.answer` takes and yields the answer as it is written.
165
+
166
+ ```python
167
+ with mb.answer.stream("When do we ship?") as stream:
168
+ for event in stream:
169
+ if event["type"] in ("delta", "replace"):
170
+ render(stream.text) # a draft: `replace` withdraws what was shown so far
171
+ answer = stream.final_answer() # the same object mb.answer returns
172
+ render(answer["answer"]) # the final text is the one to keep
173
+ print(answer["citations"])
174
+ ```
175
+
176
+ Events are dicts with a `type`: `start` (once, when retrieval is done), `delta`, `replace` and `final`
177
+ (`event["answer"]`). `stream.text` is the draft so far; a `replace` empties it, so show drafts in a place you can
178
+ redraw, and keep the final answer, not the deltas. A failure during the stream raises `MirabaseError`, and a stream
179
+ that has started is not retried.
180
+
181
+ With `AsyncMirabase`:
182
+
183
+ ```python
184
+ async with mb.answer.stream("When do we ship?") as stream:
185
+ async for event in stream:
186
+ if event["type"] in ("delta", "replace"):
187
+ render(stream.text)
188
+ answer = await stream.final_answer()
189
+ ```
190
+
191
+ Cancelling the task closes the connection, which cancels the answer.
192
+
193
+ ## A Space for each of your users
194
+
195
+ Name a Space by your own id for it, such as your user id. `mb.space_for` returns a client pinned to that
196
+ Space and creates the Space when there is none, so one call is all a new user needs.
197
+
198
+ ```python
199
+ mine = mb.space_for("user-42", name="User 42")
200
+ mine.files.write("/notes/plan.md", "# Plan")
201
+ mine.search("plan") # reads that Space only
202
+ for entry in mine.entries.list(): # that Space's Entries only
203
+ print(entry["id"])
204
+
205
+ space = mb.spaces.ensure("user-42") # the Space itself; safe to call again
206
+ ```
207
+
208
+ Anywhere a Space id goes, `ext:user-42` names the same Space.
209
+
210
+ ## Conversations
211
+
212
+ ```python
213
+ receipt = mb.conversations.add(
214
+ [
215
+ {"role": "user", "content": "We ship on Friday."},
216
+ {"role": "assistant", "content": "Noted."},
217
+ ],
218
+ session_id="chat-42",
219
+ )
220
+ status = mb.processing.wait(receipt) # until distillation has ended too
221
+ print(status["enrichments"]["memory"]) # "succeeded"; "skipped" when the server has no LLM
222
+ for memory in mb.memories.list(entry=receipt["entry_id"]):
223
+ print(memory["text"])
224
+ ```
225
+
226
+ One call stores the batch as one Entry, and memories are distilled from it afterwards. It is
227
+ `mb.entries.ingest({"kind": "conversation", ...})` under another name.
228
+
229
+ Distillation runs in the background once the conversation is searchable, and starts about half a minute later so
230
+ that a burst of writes costs one model call; with the model's time, memories usually exist 30 to 60 seconds after the
231
+ call. `mb.processing.wait(receipt)` returns when they do. `mb.jobs.wait(receipt["job_id"])` returns earlier, as soon
232
+ as the conversation is searchable, before any memory exists. A server you run yourself sets the delays with
233
+ `MIRABASE_AUTO_*_DELAY_SECONDS`; without them it waits about two minutes.
234
+
235
+ ## Waiting for processing
236
+
237
+ A write returns as soon as the content is stored; indexing and the later steps run afterwards. Each write receipt
238
+ carries `version_id` and, when the service includes it, `status`. `mb.processing.wait` waits until that version is
239
+ processed and returns its status.
240
+
241
+ ```python
242
+ from mirabase import ProcessingError, ProcessingTimeout
243
+
244
+ receipt = mb.files.write("/notes/plan.md", "# Plan")
245
+ mb.processing.wait(receipt, until="searchable") # search finds it
246
+ status = mb.processing.wait(receipt) # every step has ended
247
+ print(status["state"], status["degraded"])
248
+
249
+ results = mb.files.batch(operations)
250
+ mb.processing.wait_all([result["write"] for result in results if "write" in result])
251
+ ```
252
+
253
+ - **Arguments.** `wait` takes a receipt (`files.write`, `files.batch` items' `write`, `entries.ingest`,
254
+ `conversations.add`, `entries.reprocess`) or a version id. Keyword arguments: `until` (`"processed"`, the
255
+ default, or `"searchable"`), `timeout` in seconds (default 120), and `allow_no_content`.
256
+ - **Requests.** When the receipt's `status` already satisfies `until`, no request is sent. Otherwise `wait` polls
257
+ `GET /v2/versions/{version_id}/status` after 0.5, 1, 2 and 4 seconds, then every 5 seconds, each delay varied
258
+ by up to 20 percent. A 429 or 503 response waits for its `Retry-After` instead. `wait_all` polls
259
+ `POST /v2/versions/batch-status` with the versions still pending, 100 per request, and returns the statuses in
260
+ the order given.
261
+ - **Errors.** A version that ends `failed`, `discarded` or `superseded` raises `ProcessingError`; so does
262
+ `no_content` unless `allow_no_content=True`. `error.last_status` is the status that ended the wait, and from
263
+ `wait_all`, `error.statuses` holds the last status known for each write. A version that does not exist, or that
264
+ the key cannot read, raises `MirabaseNotFoundError`. When `timeout` runs out, `ProcessingTimeout` (code
265
+ `wait_timeout`) is raised with `error.last_status`; processing continues on the service.
266
+ - **asyncio.** On `AsyncMirabase`, `await mb.processing.wait(...)` sleeps on the event loop, so cancelling the task
267
+ stops the wait.
268
+
269
+ `mb.processing.status(version_id)` and `mb.processing.batch_status(version_ids)` read the status without waiting.
270
+
271
+ ## Memory for your LLM client
272
+
273
+ Wrap the OpenAI or Anthropic client you already have. Each chat call then gets the relevant context from
274
+ Mirabase added to its prompt, and the turn (the user message and the reply text) is stored afterwards.
275
+
276
+ ```python
277
+ from mirabase import Mirabase, wrap_openai
278
+
279
+ openai = wrap_openai(OpenAI(), Mirabase(), session_id="chat-42")
280
+ reply = openai.chat.completions.create(model=model, messages=messages) # streaming works the same way
281
+ # One call can use another session or Space, or skip either half:
282
+ openai.chat.completions.create(model=model, messages=messages, mirabase={"space": user_space, "session_id": "chat-43"})
283
+ ```
284
+
285
+ `wrap_anthropic(Anthropic(), Mirabase())` does the same for `messages.create`, and both accept the async
286
+ clients.
287
+
288
+ - **One Space.** Turns are stored in `space`, or in the Mirabase client's Space (the one it is pinned to, else
289
+ your default Space), and context is read from that same Space. Give each end user a Space and nothing of
290
+ one reaches another. `recall_spaces` reads from other Spaces instead, or from `"all"` the key can read.
291
+ - **It never fails or delays your model call.** Context is skipped after `recall_timeout` (3 seconds), and
292
+ after three failed reads in a row for 30 seconds. Turns are stored on worker threads; the interpreter
293
+ waits for them at exit, and `openai.mirabase.flush()` waits earlier (`background=False` stores before
294
+ `create` returns). Errors go to `on_error(error, stage)`; without it, the first of each kind is a
295
+ `RuntimeWarning`.
296
+ - **Citation marks.** The context asks the model to cite sources as `[c1]`. The reply you get keeps them; the
297
+ stored copy does not.
298
+ - **What has memory.** `chat.completions.create` and `messages.create`, streaming included, also on the
299
+ clients `with_options()` and `copy()` return. These run **without memory**, and say so once through
300
+ `on_error` (stage `"unsupported"`): OpenAI's `responses.*`, `chat.completions.parse()` and `.stream()`;
301
+ Anthropic's `messages.stream()`, `messages.parse()`, `beta.messages.*`; `with_raw_response` and
302
+ `with_streaming_response` on either.
303
+
304
+ ## Errors
305
+
306
+ A failed request raises `MirabaseError`. `error.code` is stable, `error.action` names what to do next
307
+ when the service gives one, and `error.request_id` identifies the request when you report a problem.
308
+ `error.type` is the broad class of the failure, `error.errors` lists every invalid field of a 422,
309
+ `error.limit` says which limit a 429 hit, and `error.body` is the response body.
310
+
311
+ The class follows the HTTP status, so `except` can pick one kind of failure:
312
+
313
+ | Class | Status |
314
+ | --- | --- |
315
+ | `MirabaseValidationError` | 400, 422 |
316
+ | `MirabaseAuthenticationError` | 401 |
317
+ | `MirabasePaymentRequiredError` | 402 (`balance_insufficient`, `key_token_limit_reached`, `budget_exceeded`) |
318
+ | `MirabasePermissionError` | 403 |
319
+ | `MirabaseNotFoundError` | 404; `MirabaseGoneError` (a subclass) for 410, such as an expired change cursor |
320
+ | `MirabaseConflictError` | 409; `MirabasePreconditionFailedError` (a subclass) for 412, such as a failed `If-Match` |
321
+ | `MirabaseRateLimitError` | 429 |
322
+ | `MirabaseServerError` | 500 and above |
323
+
324
+ All are subclasses of `MirabaseError`, and any other status is a plain `MirabaseError`.
325
+ `MirabaseConnectionError` means no response arrived (network failure or timeout), and
326
+ `MirabaseConfigError` a mistake in the call that was caught before anything was sent.
327
+
328
+ On deployments that sell prepaid tokens, a write, model call or answer the account cannot pay for raises
329
+ `MirabasePaymentRequiredError`; reads of existing data keep working. `error.code` says which limit
330
+ (`PAYMENT_REQUIRED_CODES` lists them) and `error.action` what to do: `top_up_balance` or `raise_budget` in the
331
+ console. A 429 `quota_exceeded` names the used-up quota in `error.quota`.
332
+
333
+ ```python
334
+ from mirabase import MirabaseNotFoundError, MirabasePaymentRequiredError, MirabaseRateLimitError
335
+
336
+ try:
337
+ entry = mb.entries.get(entry_id)
338
+ except MirabaseNotFoundError:
339
+ entry = None
340
+ except MirabaseRateLimitError as error:
341
+ print(error.limit, error.retry_after_seconds)
342
+ except MirabasePaymentRequiredError as error:
343
+ print(error.code, error.action) # top up or raise the budget in the console, then retry
344
+ ```
345
+
346
+ ## Versioning
347
+
348
+ `0.x`: a minor release may change the API, and says how in `CHANGELOG.md`; a patch release does not. The TypeScript,
349
+ Python and Go SDKs and the CLI release together under one number.
350
+
351
+ ## Licence
352
+
353
+ Apache-2.0. See `LICENSE` and `NOTICE`.