mirabase 0.4.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.
- mirabase/__init__.py +89 -0
- mirabase/_async.py +153 -0
- mirabase/_changes.py +123 -0
- mirabase/_client.py +186 -0
- mirabase/_errors.py +242 -0
- mirabase/_files.py +536 -0
- mirabase/_generated/__init__.py +0 -0
- mirabase/_generated/operations.py +1428 -0
- mirabase/_generated/types.py +2923 -0
- mirabase/_http.py +726 -0
- mirabase/_instants.py +73 -0
- mirabase/_knowledge.py +585 -0
- mirabase/_llm.py +780 -0
- mirabase/_llm_providers.py +171 -0
- mirabase/_llm_proxy.py +218 -0
- mirabase/_llm_threads.py +74 -0
- mirabase/_meta.py +188 -0
- mirabase/_processing.py +379 -0
- mirabase/_resource.py +49 -0
- mirabase/_resources.py +1247 -0
- mirabase/_stream.py +201 -0
- mirabase/_version.py +2 -0
- mirabase/_webhooks.py +119 -0
- mirabase/py.typed +0 -0
- mirabase-0.4.0.dist-info/METADATA +353 -0
- mirabase-0.4.0.dist-info/RECORD +30 -0
- mirabase-0.4.0.dist-info/WHEEL +5 -0
- mirabase-0.4.0.dist-info/licenses/LICENSE +202 -0
- mirabase-0.4.0.dist-info/licenses/NOTICE +10 -0
- mirabase-0.4.0.dist-info/top_level.txt +1 -0
mirabase/__init__.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Python SDK for the Mirabase Developer API (``/v2``).
|
|
2
|
+
|
|
3
|
+
from mirabase import Mirabase
|
|
4
|
+
|
|
5
|
+
mb = Mirabase() # MIRABASE_API_KEY
|
|
6
|
+
mb.files.write("/notes/plan.md", "# Plan")
|
|
7
|
+
for node in mb.tree("/notes"):
|
|
8
|
+
print(node["path"])
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._async import AsyncAnswerStream, AsyncMirabase
|
|
12
|
+
from ._changes import ChangeStream
|
|
13
|
+
from ._client import Mirabase
|
|
14
|
+
from ._errors import (
|
|
15
|
+
MirabaseAuthenticationError,
|
|
16
|
+
MirabaseConfigError,
|
|
17
|
+
MirabaseConflictError,
|
|
18
|
+
MirabaseConnectionError,
|
|
19
|
+
MirabaseError,
|
|
20
|
+
MirabaseGoneError,
|
|
21
|
+
MirabaseNotFoundError,
|
|
22
|
+
MirabasePaymentRequiredError,
|
|
23
|
+
MirabasePermissionError,
|
|
24
|
+
MirabasePreconditionFailedError,
|
|
25
|
+
MirabaseRateLimitError,
|
|
26
|
+
MirabaseServerError,
|
|
27
|
+
MirabaseValidationError,
|
|
28
|
+
PAYMENT_REQUIRED_CODES,
|
|
29
|
+
ProcessingError,
|
|
30
|
+
ProcessingTimeout,
|
|
31
|
+
)
|
|
32
|
+
from ._files import MAX_PUT_BYTES, FileContent, FileStat
|
|
33
|
+
from ._generated import types
|
|
34
|
+
from ._http import DEFAULT_BASE_URL, Paginator, RawResponse, RequestOptions
|
|
35
|
+
from ._knowledge import SearchHits
|
|
36
|
+
from ._processing import AsyncProcessing, Processing
|
|
37
|
+
from ._llm import MemoryCall, MemoryHandle, wrap_anthropic, wrap_openai
|
|
38
|
+
from ._meta import RateLimitInfo, ResponseMeta, TokenUsage, response_meta
|
|
39
|
+
from ._stream import AnswerStream
|
|
40
|
+
from ._version import __version__
|
|
41
|
+
from ._webhooks import parse_billing_alert, parse_webhook, verify_standard_webhook, verify_webhook_signature
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"DEFAULT_BASE_URL",
|
|
45
|
+
"MAX_PUT_BYTES",
|
|
46
|
+
"AnswerStream",
|
|
47
|
+
"AsyncAnswerStream",
|
|
48
|
+
"AsyncMirabase",
|
|
49
|
+
"AsyncProcessing",
|
|
50
|
+
"ChangeStream",
|
|
51
|
+
"FileContent",
|
|
52
|
+
"FileStat",
|
|
53
|
+
"MemoryCall",
|
|
54
|
+
"MemoryHandle",
|
|
55
|
+
"Mirabase",
|
|
56
|
+
"MirabaseAuthenticationError",
|
|
57
|
+
"MirabaseConfigError",
|
|
58
|
+
"MirabaseConflictError",
|
|
59
|
+
"MirabaseConnectionError",
|
|
60
|
+
"MirabaseError",
|
|
61
|
+
"MirabaseGoneError",
|
|
62
|
+
"MirabaseNotFoundError",
|
|
63
|
+
"MirabasePaymentRequiredError",
|
|
64
|
+
"MirabasePermissionError",
|
|
65
|
+
"MirabasePreconditionFailedError",
|
|
66
|
+
"MirabaseRateLimitError",
|
|
67
|
+
"MirabaseServerError",
|
|
68
|
+
"MirabaseValidationError",
|
|
69
|
+
"PAYMENT_REQUIRED_CODES",
|
|
70
|
+
"Paginator",
|
|
71
|
+
"Processing",
|
|
72
|
+
"ProcessingError",
|
|
73
|
+
"ProcessingTimeout",
|
|
74
|
+
"RateLimitInfo",
|
|
75
|
+
"RawResponse",
|
|
76
|
+
"RequestOptions",
|
|
77
|
+
"ResponseMeta",
|
|
78
|
+
"TokenUsage",
|
|
79
|
+
"SearchHits",
|
|
80
|
+
"__version__",
|
|
81
|
+
"parse_webhook",
|
|
82
|
+
"response_meta",
|
|
83
|
+
"types",
|
|
84
|
+
"verify_webhook_signature",
|
|
85
|
+
"verify_standard_webhook",
|
|
86
|
+
"parse_billing_alert",
|
|
87
|
+
"wrap_anthropic",
|
|
88
|
+
"wrap_openai",
|
|
89
|
+
]
|
mirabase/_async.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any, Callable
|
|
5
|
+
|
|
6
|
+
from ._client import Mirabase
|
|
7
|
+
from ._processing import AsyncProcessing
|
|
8
|
+
from ._resource import Resource
|
|
9
|
+
from ._stream import AnswerStream
|
|
10
|
+
|
|
11
|
+
_END = object()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _AsyncIterator:
|
|
15
|
+
"""``async for`` over a sync iterator; each step runs on a worker thread."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, target: Any) -> None:
|
|
18
|
+
self._target = target
|
|
19
|
+
self._iterator: Any = None
|
|
20
|
+
|
|
21
|
+
def __aiter__(self) -> "_AsyncIterator":
|
|
22
|
+
return self
|
|
23
|
+
|
|
24
|
+
async def __anext__(self) -> Any:
|
|
25
|
+
if self._iterator is None:
|
|
26
|
+
self._iterator = iter(self._target)
|
|
27
|
+
item = await asyncio.to_thread(next, self._iterator, _END)
|
|
28
|
+
if item is _END:
|
|
29
|
+
raise StopAsyncIteration
|
|
30
|
+
return item
|
|
31
|
+
|
|
32
|
+
def __getattr__(self, name: str) -> Any:
|
|
33
|
+
value = getattr(self._target, name)
|
|
34
|
+
if not callable(value):
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
async def call(*args: Any, **kwargs: Any) -> Any:
|
|
38
|
+
return await asyncio.to_thread(value, *args, **kwargs)
|
|
39
|
+
|
|
40
|
+
return call
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AsyncAnswerStream:
|
|
44
|
+
"""``AnswerStream`` for ``asyncio``: ``async with`` and ``async for``; each read runs on a worker thread."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, target: AnswerStream) -> None:
|
|
47
|
+
self._target = target
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def text(self) -> str:
|
|
51
|
+
"""The answer text so far. A ``replace`` event empties it and the final event sets it."""
|
|
52
|
+
return self._target.text
|
|
53
|
+
|
|
54
|
+
async def final_answer(self) -> Any:
|
|
55
|
+
"""Read the rest of the stream and return the answer."""
|
|
56
|
+
return await asyncio.to_thread(self._target.final_answer)
|
|
57
|
+
|
|
58
|
+
async def aclose(self) -> None:
|
|
59
|
+
"""Stop reading and close the connection."""
|
|
60
|
+
self._target.close()
|
|
61
|
+
|
|
62
|
+
close = aclose
|
|
63
|
+
|
|
64
|
+
async def __aenter__(self) -> "AsyncAnswerStream":
|
|
65
|
+
await asyncio.to_thread(self._target.__enter__)
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
async def __aexit__(self, *_: object) -> None:
|
|
69
|
+
await self.aclose()
|
|
70
|
+
|
|
71
|
+
def __aiter__(self) -> "AsyncAnswerStream":
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
async def __anext__(self) -> Any:
|
|
75
|
+
try:
|
|
76
|
+
event = await asyncio.to_thread(next, self._target, _END)
|
|
77
|
+
except asyncio.CancelledError:
|
|
78
|
+
self._target.close()
|
|
79
|
+
raise
|
|
80
|
+
if event is _END:
|
|
81
|
+
raise StopAsyncIteration
|
|
82
|
+
return event
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _lazy_result(value: Any) -> Any:
|
|
86
|
+
return AsyncAnswerStream(value) if isinstance(value, AnswerStream) else _AsyncIterator(value)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _wrap_callable(function: Callable[..., Any]) -> Callable[..., Any]:
|
|
90
|
+
if getattr(function, "__mirabase_lazy__", False):
|
|
91
|
+
return lambda *args, **kwargs: _lazy_result(function(*args, **kwargs))
|
|
92
|
+
|
|
93
|
+
async def call(*args: Any, **kwargs: Any) -> Any:
|
|
94
|
+
return await asyncio.to_thread(function, *args, **kwargs)
|
|
95
|
+
|
|
96
|
+
return call
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class _AsyncResource:
|
|
100
|
+
def __init__(self, target: Resource) -> None:
|
|
101
|
+
self._target = target
|
|
102
|
+
|
|
103
|
+
def __getattr__(self, name: str) -> Any:
|
|
104
|
+
value = getattr(self._target, name)
|
|
105
|
+
if isinstance(value, Resource):
|
|
106
|
+
return _AsyncResource(value)
|
|
107
|
+
return _wrap_callable(value) if callable(value) else value
|
|
108
|
+
|
|
109
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
110
|
+
return _wrap_callable(type(self._target).__call__.__get__(self._target))(*args, **kwargs)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class AsyncMirabase:
|
|
114
|
+
"""``Mirabase`` for ``asyncio``, with the same resources and arguments.
|
|
115
|
+
|
|
116
|
+
Every method is awaited, except lists, ``changes.watch`` and ``answer.stream``, which are read with
|
|
117
|
+
``async for``.
|
|
118
|
+
Requests run on worker threads, so cancelling a task stops waiting but not the request in flight.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
def __init__(self, *, _client: Mirabase | None = None, **options: Any) -> None:
|
|
122
|
+
self._client = _client if _client is not None else Mirabase(**options)
|
|
123
|
+
|
|
124
|
+
def __getattr__(self, name: str) -> Any:
|
|
125
|
+
value = getattr(self._client, name)
|
|
126
|
+
return _AsyncResource(value) if isinstance(value, Resource) else value
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def processing(self) -> AsyncProcessing:
|
|
130
|
+
"""``processing`` with waits that sleep on the event loop, so cancelling the task stops the wait."""
|
|
131
|
+
return AsyncProcessing(self._client.processing)
|
|
132
|
+
|
|
133
|
+
def space(self, space_id: str) -> "AsyncMirabase":
|
|
134
|
+
return AsyncMirabase(_client=self._client.space(space_id))
|
|
135
|
+
|
|
136
|
+
async def space_for(
|
|
137
|
+
self, external_id: str, *, name: str | None = None, description: str | None = None
|
|
138
|
+
) -> "AsyncMirabase":
|
|
139
|
+
client = await asyncio.to_thread(self._client.space_for, external_id, name=name, description=description)
|
|
140
|
+
return AsyncMirabase(_client=client)
|
|
141
|
+
|
|
142
|
+
async def aclose(self) -> None:
|
|
143
|
+
"""Close the idle connections the client keeps open between calls."""
|
|
144
|
+
self._client.close()
|
|
145
|
+
|
|
146
|
+
async def __aenter__(self) -> "AsyncMirabase":
|
|
147
|
+
return self
|
|
148
|
+
|
|
149
|
+
async def __aexit__(self, *_: object) -> None:
|
|
150
|
+
await self.aclose()
|
|
151
|
+
|
|
152
|
+
async def whoami(self, **kwargs: Any) -> Any:
|
|
153
|
+
return await asyncio.to_thread(self._client.whoami, **kwargs)
|
mirabase/_changes.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
from typing import Iterator
|
|
5
|
+
|
|
6
|
+
from ._errors import MirabaseError
|
|
7
|
+
from ._generated import types
|
|
8
|
+
from ._http import RequestOptions, backoff
|
|
9
|
+
from ._resource import Resource, lazy
|
|
10
|
+
|
|
11
|
+
LONG_POLL_SECONDS = 30
|
|
12
|
+
LONG_POLL_MARGIN = 15.0
|
|
13
|
+
MAX_RECONNECT_ATTEMPT = 6
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _should_reconnect(error: MirabaseError) -> bool:
|
|
17
|
+
"""A dropped connection, a 5xx or a 429 only delays the stream."""
|
|
18
|
+
if error.retryable is False:
|
|
19
|
+
return False
|
|
20
|
+
return error.status == 0 or error.status == 429 or error.status >= 500
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ChangeStream(Iterator[types.Change | types.BranchChange]):
|
|
24
|
+
"""An unbroken stream of changes; ``cursor`` is where to resume in another process.
|
|
25
|
+
|
|
26
|
+
``cursor`` moves when a page ends, so a resume may repeat events from the unfinished page: apply
|
|
27
|
+
them by ``entry_id``, or skip a ``seq`` already seen. On a branch ``seq`` is per ``source``, and
|
|
28
|
+
``source: branch`` events are compacted, so treat them as paths to re-read.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self, changes: "Changes", space: str | None, cursor: str | None, wait_seconds: int, branch: str | None = None
|
|
33
|
+
) -> None:
|
|
34
|
+
self._changes = changes
|
|
35
|
+
self._space = space
|
|
36
|
+
self._branch = branch
|
|
37
|
+
self.cursor = cursor
|
|
38
|
+
self._wait = wait_seconds
|
|
39
|
+
self._stop = threading.Event()
|
|
40
|
+
self._events = self._follow()
|
|
41
|
+
|
|
42
|
+
def __iter__(self) -> "ChangeStream":
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def __next__(self) -> types.Change | types.BranchChange:
|
|
46
|
+
return next(self._events)
|
|
47
|
+
|
|
48
|
+
def close(self) -> None:
|
|
49
|
+
"""Ends the stream after the poll in progress."""
|
|
50
|
+
self._stop.set()
|
|
51
|
+
|
|
52
|
+
def _follow(self) -> Iterator[types.Change | types.BranchChange]:
|
|
53
|
+
last_seq: dict[str, int] = {}
|
|
54
|
+
failures = 0
|
|
55
|
+
options = RequestOptions(max_retries=0, timeout=self._wait + LONG_POLL_MARGIN)
|
|
56
|
+
space = self._changes._space(self._space)
|
|
57
|
+
while not self._stop.is_set():
|
|
58
|
+
try:
|
|
59
|
+
page = self._changes.list(
|
|
60
|
+
cursor=self.cursor, wait_seconds=self._wait, branch=self._branch, space=space, options=options
|
|
61
|
+
)
|
|
62
|
+
failures = 0
|
|
63
|
+
except MirabaseError as error:
|
|
64
|
+
if not _should_reconnect(error):
|
|
65
|
+
raise
|
|
66
|
+
retry_after = error.retry_after_seconds
|
|
67
|
+
delay = backoff(min(failures, MAX_RECONNECT_ATTEMPT)) if retry_after is None else retry_after
|
|
68
|
+
failures += 1
|
|
69
|
+
self._changes._http.sleep(delay)
|
|
70
|
+
continue
|
|
71
|
+
for change in page["data"]:
|
|
72
|
+
source = change.get("source", "main")
|
|
73
|
+
if change["seq"] <= last_seq.get(source, -1):
|
|
74
|
+
continue
|
|
75
|
+
last_seq[source] = change["seq"]
|
|
76
|
+
yield change
|
|
77
|
+
self.cursor = page["cursor"]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Changes(Resource):
|
|
81
|
+
def list(
|
|
82
|
+
self,
|
|
83
|
+
*,
|
|
84
|
+
cursor: str | None = None,
|
|
85
|
+
wait_seconds: int | None = None,
|
|
86
|
+
limit: int | None = None,
|
|
87
|
+
branch: str | None = None,
|
|
88
|
+
space: str | None = None,
|
|
89
|
+
options: RequestOptions | None = None,
|
|
90
|
+
) -> types.ChangeFeed | types.BranchChangeFeed:
|
|
91
|
+
"""One page of the feed. An expired cursor is 410 ``cursor_expired``: resync from ``mb.tree``.
|
|
92
|
+
|
|
93
|
+
``branch`` takes that branch's own cursors, from ``mb.tree.snapshot`` with the same ``branch``.
|
|
94
|
+
"""
|
|
95
|
+
return self._ops.changes_list(
|
|
96
|
+
space_id=self._space(space), branch=branch, cursor=cursor, wait=wait_seconds, limit=limit, options=options
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
def activity(
|
|
100
|
+
self, *, days: int | None = None, space: str | None = None, options: RequestOptions | None = None
|
|
101
|
+
) -> types.SpaceActivity:
|
|
102
|
+
"""Who changed what lately: the feed of the last ``days`` (7 by default, at most 30), per principal.
|
|
103
|
+
|
|
104
|
+
Read it before planning work in a Space others also write to.
|
|
105
|
+
"""
|
|
106
|
+
return self._ops.changes_activity(space_id=self._space(space), days=days, options=options)
|
|
107
|
+
|
|
108
|
+
@lazy
|
|
109
|
+
def watch(
|
|
110
|
+
self,
|
|
111
|
+
*,
|
|
112
|
+
cursor: str | None = None,
|
|
113
|
+
wait_seconds: int = LONG_POLL_SECONDS,
|
|
114
|
+
branch: str | None = None,
|
|
115
|
+
space: str | None = None,
|
|
116
|
+
) -> ChangeStream:
|
|
117
|
+
"""Follow the feed, reconnecting from the last cursor after any failure a retry can fix.
|
|
118
|
+
|
|
119
|
+
Omit ``cursor`` to start from now, or take one from ``mb.tree.snapshot`` for a full sync. Raises
|
|
120
|
+
on an expired cursor (410) or lost access (401, 403).
|
|
121
|
+
"""
|
|
122
|
+
return ChangeStream(self, space, cursor, wait_seconds, branch)
|
|
123
|
+
|
mirabase/_client.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import threading
|
|
5
|
+
from typing import Callable
|
|
6
|
+
|
|
7
|
+
from ._changes import Changes
|
|
8
|
+
from ._errors import MirabaseError
|
|
9
|
+
from ._files import Files
|
|
10
|
+
from ._generated import types
|
|
11
|
+
from ._generated.operations import DeveloperOperations
|
|
12
|
+
from ._http import DEFAULT_BASE_URL, HttpClient, RequestOptions, usable_api_key
|
|
13
|
+
from ._meta import ResponseMeta
|
|
14
|
+
from ._knowledge import Answer, Branches, Context, Memories, Search
|
|
15
|
+
from ._processing import Processing
|
|
16
|
+
from ._resources import (
|
|
17
|
+
Audit,
|
|
18
|
+
Conversations,
|
|
19
|
+
Entries,
|
|
20
|
+
Jobs,
|
|
21
|
+
Keys,
|
|
22
|
+
Memory,
|
|
23
|
+
Principals,
|
|
24
|
+
Proposals,
|
|
25
|
+
RequestLogs,
|
|
26
|
+
Billing,
|
|
27
|
+
Snapshots,
|
|
28
|
+
Transfers,
|
|
29
|
+
Spaces,
|
|
30
|
+
Tree,
|
|
31
|
+
Usage,
|
|
32
|
+
Versions,
|
|
33
|
+
Webhooks,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _DefaultSpace:
|
|
38
|
+
"""Looked up once and remembered; a failed lookup is not remembered."""
|
|
39
|
+
|
|
40
|
+
def __init__(self) -> None:
|
|
41
|
+
self._lock = threading.Lock()
|
|
42
|
+
self._space_id: str | None = None
|
|
43
|
+
|
|
44
|
+
def resolve(self, spaces: Spaces) -> str:
|
|
45
|
+
with self._lock:
|
|
46
|
+
if self._space_id is None:
|
|
47
|
+
self._space_id = self._find(spaces)
|
|
48
|
+
return self._space_id
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def _find(spaces: Spaces) -> str:
|
|
52
|
+
try:
|
|
53
|
+
return spaces.get("default")["id"]
|
|
54
|
+
except MirabaseError as error:
|
|
55
|
+
if error.status != 404:
|
|
56
|
+
raise
|
|
57
|
+
raise MirabaseError(
|
|
58
|
+
status=0,
|
|
59
|
+
code="space_required",
|
|
60
|
+
message="This key has no default Space. Name one with space= or mb.space(id).",
|
|
61
|
+
action="pass_space",
|
|
62
|
+
retryable=False,
|
|
63
|
+
) from error
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def resolve_base_url(base_url: str | None) -> str:
|
|
67
|
+
"""The argument, else ``MIRABASE_API_URL`` (as the CLI and ``pnpm dev:stack`` use it; empty counts as unset),
|
|
68
|
+
else ``https://api.mirabase.io``."""
|
|
69
|
+
if base_url:
|
|
70
|
+
return base_url
|
|
71
|
+
from_environment = (os.environ.get("MIRABASE_API_URL") or "").strip()
|
|
72
|
+
return from_environment or DEFAULT_BASE_URL
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Mirabase:
|
|
76
|
+
"""The Developer API.
|
|
77
|
+
|
|
78
|
+
``api_key`` defaults to ``MIRABASE_API_KEY`` and ``base_url`` to ``MIRABASE_API_URL``, then to
|
|
79
|
+
``https://api.mirabase.io``. Calls that need a Space use ``space``, or else the default Space, so most code
|
|
80
|
+
never mentions one. With ``space``, the calls that filter by Space (``search``, ``context``, ``answer``,
|
|
81
|
+
``entries.list``, ``memories.list``, ``audit.events``) read only that Space unless a call names ``space``, or
|
|
82
|
+
``spaces="all"``.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
*,
|
|
88
|
+
api_key: str | None = None,
|
|
89
|
+
base_url: str | None = None,
|
|
90
|
+
space: str | None = None,
|
|
91
|
+
timeout: float | None = None,
|
|
92
|
+
max_retries: int | None = None,
|
|
93
|
+
max_retry_after: float | None = None,
|
|
94
|
+
sleep: Callable[[float], None] | None = None,
|
|
95
|
+
on_response: Callable[[ResponseMeta], None] | None = None,
|
|
96
|
+
allow_insecure_http: bool = False,
|
|
97
|
+
_shared: tuple[HttpClient, _DefaultSpace] | None = None,
|
|
98
|
+
) -> None:
|
|
99
|
+
"""``on_response`` is called with the headers of every HTTP response, retried attempts included: request id,
|
|
100
|
+
``RateLimit-*`` state and, on deployments that sell prepaid tokens, ``Mirabase-Tokens-*`` usage; keep it fast,
|
|
101
|
+
an exception from it is logged once and ignored. ``mirabase.response_meta(result)`` gives the same for one
|
|
102
|
+
result. ``http://`` is accepted on loopback, private addresses and one-label service names;
|
|
103
|
+
``allow_insecure_http=True`` lets it reach a public host name, which sends the key unencrypted."""
|
|
104
|
+
if _shared is None:
|
|
105
|
+
# Refused here, before anything is sent, when there is no key or it could not go into a header.
|
|
106
|
+
http = HttpClient(
|
|
107
|
+
api_key=usable_api_key(api_key or os.environ.get("MIRABASE_API_KEY")),
|
|
108
|
+
base_url=resolve_base_url(base_url),
|
|
109
|
+
timeout=timeout,
|
|
110
|
+
max_retries=max_retries,
|
|
111
|
+
max_retry_after=max_retry_after,
|
|
112
|
+
sleep=sleep,
|
|
113
|
+
on_response=on_response,
|
|
114
|
+
allow_insecure_http=allow_insecure_http,
|
|
115
|
+
)
|
|
116
|
+
default_space = _DefaultSpace()
|
|
117
|
+
else:
|
|
118
|
+
http, default_space = _shared
|
|
119
|
+
self.http = http
|
|
120
|
+
self._default_space = default_space
|
|
121
|
+
self._pinned_space = space
|
|
122
|
+
self.ops = DeveloperOperations(http.send)
|
|
123
|
+
# Generated, one method per operation, for when a resource method does not fit.
|
|
124
|
+
self.raw = self.ops
|
|
125
|
+
self.files = Files(self)
|
|
126
|
+
self.tree = Tree(self)
|
|
127
|
+
self.entries = Entries(self)
|
|
128
|
+
self.conversations = Conversations(self)
|
|
129
|
+
self.versions = Versions(self)
|
|
130
|
+
self.changes = Changes(self)
|
|
131
|
+
self.search = Search(self)
|
|
132
|
+
self.context = Context(self)
|
|
133
|
+
self.answer = Answer(self)
|
|
134
|
+
self.memories = Memories(self)
|
|
135
|
+
self.memory = Memory(self)
|
|
136
|
+
self.spaces = Spaces(self)
|
|
137
|
+
self.keys = Keys(self)
|
|
138
|
+
self.principals = Principals(self)
|
|
139
|
+
self.usage = Usage(self)
|
|
140
|
+
self.audit = Audit(self)
|
|
141
|
+
self.request_logs = RequestLogs(self)
|
|
142
|
+
self.billing = Billing(self)
|
|
143
|
+
self.jobs = Jobs(self)
|
|
144
|
+
# What became of a write: ``processing.wait(receipt)``, ``wait_all``, ``status``, ``batch_status``.
|
|
145
|
+
self.processing = Processing(self)
|
|
146
|
+
self.branches = Branches(self)
|
|
147
|
+
self.proposals = Proposals(self)
|
|
148
|
+
self.snapshots = Snapshots(self)
|
|
149
|
+
self.webhooks = Webhooks(self)
|
|
150
|
+
self.transfers = Transfers(self)
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
"""Close the idle connections the client keeps open between calls. Optional: they are closed
|
|
154
|
+
when the client is garbage collected, and a closed client opens new ones if it is used again."""
|
|
155
|
+
self.http.close()
|
|
156
|
+
|
|
157
|
+
def __enter__(self) -> "Mirabase":
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
def __exit__(self, *_: object) -> None:
|
|
161
|
+
self.close()
|
|
162
|
+
|
|
163
|
+
def space_id(self, override: str | None) -> str:
|
|
164
|
+
"""The explicit Space, else the client's, else the account's default."""
|
|
165
|
+
return override or self._pinned_space or self._default_space.resolve(self.spaces)
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def pinned_space(self) -> str | None:
|
|
169
|
+
"""The Space this client is pinned to, by ``mb.space(id)`` or ``space=``. Never the default Space."""
|
|
170
|
+
return self._pinned_space
|
|
171
|
+
|
|
172
|
+
def space(self, space_id: str) -> "Mirabase":
|
|
173
|
+
"""A client pinned to one Space, sharing this client's connection settings. Its ``search``,
|
|
174
|
+
``context``, ``answer``, ``entries.list``, ``memories.list`` and ``audit.events`` read that Space only,
|
|
175
|
+
unless a call names ``space``, or ``spaces="all"`` for every Space the key can read."""
|
|
176
|
+
return Mirabase(space=space_id, _shared=(self.http, self._default_space))
|
|
177
|
+
|
|
178
|
+
def space_for(
|
|
179
|
+
self, external_id: str, *, name: str | None = None, description: str | None = None
|
|
180
|
+
) -> "Mirabase":
|
|
181
|
+
"""A client pinned to the Space that carries your own id for it, such as your user id. The Space is
|
|
182
|
+
created when there is none (``mb.spaces.ensure``), so this is all a new end user needs."""
|
|
183
|
+
return self.space(self.spaces.ensure(external_id, name=name, description=description)["id"])
|
|
184
|
+
|
|
185
|
+
def whoami(self, *, options: RequestOptions | None = None) -> types.Whoami:
|
|
186
|
+
return self.ops.identity_whoami(options=options)
|