Metadata-Version: 2.4
Name: mirabase
Version: 0.4.0
Summary: Python SDK for the Mirabase Developer API: files, knowledge and memory for agents
Author: Mirabase
License-Expression: Apache-2.0
Project-URL: Homepage, https://mirabase.io/developers
Project-URL: Documentation, https://mirabase.io/developers/sdks
Keywords: mirabase,agent,memory,knowledge,rag,llm,context,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Dynamic: license-file

# Mirabase SDK for Python

One API for files, knowledge and memory. This package is the client for the Mirabase Developer API
(`https://api.mirabase.io`, `/v2`).

- Docs: https://mirabase.io/developers
- API reference: https://mirabase.io/developers/api
- For agents and models: https://api.mirabase.io/llms.txt

## Install

```sh
pip install mirabase        # or: uv add mirabase, poetry add mirabase
```

Every release is also a file on mirabase.io, with its checksum in https://mirabase.io/sdk/SHA256SUMS:
`pip install https://mirabase.io/sdk/mirabase-0.4.0-py3-none-any.whl`. A version is released when the API that
matches it is.

Python 3.11 or newer. The package has no dependencies (HTTP is the standard library's, with a connection pool) and
ships type information (`py.typed`).

## Use

Create a key in the console (https://console.mirabase.io), then:

```python
from mirabase import Mirabase

mb = Mirabase()  # reads MIRABASE_API_KEY and MIRABASE_API_URL, or pass api_key=... and base_url=...

# Write a file. It is found by words on the next request; wait_seconds holds the response (up to 10 s) until it is
# indexed for meaning too, so the answer below can use it.
mb.files.write("/notes/plan.md", "# Plan\n\nWe ship on Friday. Tina owns the launch.\n", wait_seconds=10)

# Search by meaning. The result is a list; hits.partial is true when it may be incomplete.
hits = mb.search("when do we ship?")

# A token-budgeted context pack for your own model.
pack = mb.context("when do we ship, and who owns it?", budget_tokens=2000)

# Or an answer with citations. It abstains when the evidence is not enough.
answer = mb.answer("When do we ship?")
print(answer["status"], answer["answer"], answer["citations"])

# One Space only: a client pinned with mb.space(id) searches, builds context, answers and lists Entries,
# memories and audit events in that Space. Name another per call with space=..., others with spaces=[...]
# where a call takes several, or spaces="all" for every Space the key can read.
mine = mb.space("spc_123").search("when do we ship?")
```

`AsyncMirabase` has the same methods for `asyncio`. Every operation of the API is also available as
a method on `mb.raw`, which is not pinned: it sends what you pass.

`base_url` defaults to the `MIRABASE_API_URL` environment variable (an empty value counts as unset), then to
`https://api.mirabase.io`. The previous address, `https://api.mirabase.dev`, serves the same API and keeps working.

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
with a line break, a space or any other character that cannot be sent in a header inside it is refused when the client
is made (`MirabaseConfigError`, code `invalid_api_key`); the message says what kind of character and where, never the
key. `repr()` of the client and its parts never shows the key.

The base URL is checked when the client is made (`MirabaseConfigError`, code `invalid_base_url`): `https://`
anywhere; `http://` only on loopback, private addresses, `.localhost`, `.local`, `.internal` and one-label service
names such as `http://mirabase:4379`, unless you pass `allow_insecure_http=True`; no user name, password, query or
fragment; never a link-local address such as a cloud metadata service. A redirect to another origin does not carry
the key.

The client keeps a few idle connections open; `with Mirabase() as mb:` (or `mb.close()`) closes them, and
`async with AsyncMirabase() as mb:` (or `await mb.aclose()`) does the same for the async client.

`AsyncMirabase` runs each request on a worker thread (`asyncio.to_thread`), so the package needs no HTTP library;
cancelling a task stops waiting, not the request in flight.

## Lists

List methods return a `Paginator`: a `for` loop walks every page on demand (`async for` on `AsyncMirabase`),
`.take(n)` stops early, and `.pages()` yields whole pages with their cursors.

```python
for node in mb.tree("/notes"):
    print(node["path"])
recent = mb.entries.list(limit=20).take(20)
```

## Retries, timeouts and idempotency

- **Retries.** Up to `max_retries` (default 3) on connection failures, 5xx and 429, with full-jitter exponential
  backoff (0.5 s base, 8 s cap). A `Retry-After` from the service is honoured; one longer than `max_retry_after`
  (default 60 s) is raised as the error instead of waited out.
- **Only what is safe to repeat.** Reads, and calls that carry an `Idempotency-Key`, are retried. The SDK creates
  the key once per call and sends the same one on every retry: a retried write replays the first result instead of
  writing twice, and a retried `search`, `context` or `answer` is not charged again (the service remembers a key,
  with the API key, operation and body, for 24 hours). Pass `RequestOptions(idempotency_key=...)` to reuse one across
  processes. A streamed answer is retried only while it opens, and is charged when it completes. A call that is not
  safe to repeat (a `DELETE`) is retried on 429 only, which the service sends before doing anything. 402 is never
  retried.
- **Timeouts.** `timeout` (seconds, default 60) applies to each attempt.

```python
from mirabase import Mirabase, RequestOptions

mb = Mirabase(max_retries=5, timeout=20)
mb.files.write("/a.md", "x", options=RequestOptions(idempotency_key=job_id, timeout=5))
mb.answer("When do we ship?", options=RequestOptions(idempotency_key=f"{job_id}:answer"))  # not charged twice
```

**Date-times** go out as full RFC 3339 with seconds: an aware `datetime` is sent as `isoformat()` (a naive one is
refused), and a string such as `2026-11-22T10:00Z` in a date-time field (`occurred_at`, `reference_time`,
`filter["occurred_from"]`, ...) is sent as `2026-11-22T10:00:00Z`. Values inside `metadata` are yours and are sent as
given.

## Usage, cost and rate limits

Each response says how much it cost and how much of your rate limit is left. `response_meta(result)` reads it for a
result the API returned as a JSON object (most calls), and `on_response=` sees every response, retried attempts and
failures included. `tokens` is set on deployments that sell prepaid tokens, for operations that charge.

```python
from mirabase import Mirabase, response_meta

mb = Mirabase(on_response=lambda meta: metrics.observe(meta.operation, (meta.tokens and meta.tokens.charged) or 0))
answer = mb.answer("When do we ship?")
meta = response_meta(answer)
# ResponseMeta(operation='Retrieval_answer', method='POST', status=200, request_id='req_…',
#              rate_limit=RateLimitInfo(limit=120, remaining=119, reset_seconds=1),
#              tokens=TokenUsage(charged=812, reserved=0, remaining=999188))
```

A result that carries metadata is still the `dict` (or `list`) the API returned: equal to it, and `json.dumps`
writes the API's body. A hook that raises is logged once on the `mirabase` logger and does not fail the call.

Coming from 0.2.0: there, a client pinned with `space=` or `mb.space(id)` did not limit `search`, `context` and
`answer` to that Space, and its `entries.list`, `memories.list` and `audit.events` listed every Space the key can
read. From 0.3.0rc1 on, a pinned client limits all six to its Space.

## Streaming an answer

`mb.answer.stream` takes what `mb.answer` takes and yields the answer as it is written.

```python
with mb.answer.stream("When do we ship?") as stream:
    for event in stream:
        if event["type"] in ("delta", "replace"):
            render(stream.text)  # a draft: `replace` withdraws what was shown so far
    answer = stream.final_answer()  # the same object mb.answer returns
render(answer["answer"])  # the final text is the one to keep
print(answer["citations"])
```

Events are dicts with a `type`: `start` (once, when retrieval is done), `delta`, `replace` and `final`
(`event["answer"]`). `stream.text` is the draft so far; a `replace` empties it, so show drafts in a place you can
redraw, and keep the final answer, not the deltas. A failure during the stream raises `MirabaseError`, and a stream
that has started is not retried.

With `AsyncMirabase`:

```python
async with mb.answer.stream("When do we ship?") as stream:
    async for event in stream:
        if event["type"] in ("delta", "replace"):
            render(stream.text)
    answer = await stream.final_answer()
```

Cancelling the task closes the connection, which cancels the answer.

## A Space for each of your users

Name a Space by your own id for it, such as your user id. `mb.space_for` returns a client pinned to that
Space and creates the Space when there is none, so one call is all a new user needs.

```python
mine = mb.space_for("user-42", name="User 42")
mine.files.write("/notes/plan.md", "# Plan")
mine.search("plan")  # reads that Space only
for entry in mine.entries.list():  # that Space's Entries only
    print(entry["id"])

space = mb.spaces.ensure("user-42")  # the Space itself; safe to call again
```

Anywhere a Space id goes, `ext:user-42` names the same Space.

## Conversations

```python
receipt = mb.conversations.add(
    [
        {"role": "user", "content": "We ship on Friday."},
        {"role": "assistant", "content": "Noted."},
    ],
    session_id="chat-42",
)
status = mb.processing.wait(receipt)  # until distillation has ended too
print(status["enrichments"]["memory"])  # "succeeded"; "skipped" when the server has no LLM
for memory in mb.memories.list(entry=receipt["entry_id"]):
    print(memory["text"])
```

One call stores the batch as one Entry, and memories are distilled from it afterwards. It is
`mb.entries.ingest({"kind": "conversation", ...})` under another name.

Distillation runs in the background once the conversation is searchable, and starts about half a minute later so
that a burst of writes costs one model call; with the model's time, memories usually exist 30 to 60 seconds after the
call. `mb.processing.wait(receipt)` returns when they do. `mb.jobs.wait(receipt["job_id"])` returns earlier, as soon
as the conversation is searchable, before any memory exists. A server you run yourself sets the delays with
`MIRABASE_AUTO_*_DELAY_SECONDS`; without them it waits about two minutes.

## Waiting for processing

A write returns as soon as the content is stored; indexing and the later steps run afterwards. Each write receipt
carries `version_id` and, when the service includes it, `status`. `mb.processing.wait` waits until that version is
processed and returns its status.

```python
from mirabase import ProcessingError, ProcessingTimeout

receipt = mb.files.write("/notes/plan.md", "# Plan")
mb.processing.wait(receipt, until="searchable")  # search finds it
status = mb.processing.wait(receipt)  # every step has ended
print(status["state"], status["degraded"])

results = mb.files.batch(operations)
mb.processing.wait_all([result["write"] for result in results if "write" in result])
```

- **Arguments.** `wait` takes a receipt (`files.write`, `files.batch` items' `write`, `entries.ingest`,
  `conversations.add`, `entries.reprocess`) or a version id. Keyword arguments: `until` (`"processed"`, the
  default, or `"searchable"`), `timeout` in seconds (default 120), and `allow_no_content`.
- **Requests.** When the receipt's `status` already satisfies `until`, no request is sent. Otherwise `wait` polls
  `GET /v2/versions/{version_id}/status` after 0.5, 1, 2 and 4 seconds, then every 5 seconds, each delay varied
  by up to 20 percent. A 429 or 503 response waits for its `Retry-After` instead. `wait_all` polls
  `POST /v2/versions/batch-status` with the versions still pending, 100 per request, and returns the statuses in
  the order given.
- **Errors.** A version that ends `failed`, `discarded` or `superseded` raises `ProcessingError`; so does
  `no_content` unless `allow_no_content=True`. `error.last_status` is the status that ended the wait, and from
  `wait_all`, `error.statuses` holds the last status known for each write. A version that does not exist, or that
  the key cannot read, raises `MirabaseNotFoundError`. When `timeout` runs out, `ProcessingTimeout` (code
  `wait_timeout`) is raised with `error.last_status`; processing continues on the service.
- **asyncio.** On `AsyncMirabase`, `await mb.processing.wait(...)` sleeps on the event loop, so cancelling the task
  stops the wait.

`mb.processing.status(version_id)` and `mb.processing.batch_status(version_ids)` read the status without waiting.

## Memory for your LLM client

Wrap the OpenAI or Anthropic client you already have. Each chat call then gets the relevant context from
Mirabase added to its prompt, and the turn (the user message and the reply text) is stored afterwards.

```python
from mirabase import Mirabase, wrap_openai

openai = wrap_openai(OpenAI(), Mirabase(), session_id="chat-42")
reply = openai.chat.completions.create(model=model, messages=messages)  # streaming works the same way
# One call can use another session or Space, or skip either half:
openai.chat.completions.create(model=model, messages=messages, mirabase={"space": user_space, "session_id": "chat-43"})
```

`wrap_anthropic(Anthropic(), Mirabase())` does the same for `messages.create`, and both accept the async
clients.

- **One Space.** Turns are stored in `space`, or in the Mirabase client's Space (the one it is pinned to, else
  your default Space), and context is read from that same Space. Give each end user a Space and nothing of
  one reaches another. `recall_spaces` reads from other Spaces instead, or from `"all"` the key can read.
- **It never fails or delays your model call.** Context is skipped after `recall_timeout` (3 seconds), and
  after three failed reads in a row for 30 seconds. Turns are stored on worker threads; the interpreter
  waits for them at exit, and `openai.mirabase.flush()` waits earlier (`background=False` stores before
  `create` returns). Errors go to `on_error(error, stage)`; without it, the first of each kind is a
  `RuntimeWarning`.
- **Citation marks.** The context asks the model to cite sources as `[c1]`. The reply you get keeps them; the
  stored copy does not.
- **What has memory.** `chat.completions.create` and `messages.create`, streaming included, also on the
  clients `with_options()` and `copy()` return. These run **without memory**, and say so once through
  `on_error` (stage `"unsupported"`): OpenAI's `responses.*`, `chat.completions.parse()` and `.stream()`;
  Anthropic's `messages.stream()`, `messages.parse()`, `beta.messages.*`; `with_raw_response` and
  `with_streaming_response` on either.

## Errors

A failed request raises `MirabaseError`. `error.code` is stable, `error.action` names what to do next
when the service gives one, and `error.request_id` identifies the request when you report a problem.
`error.type` is the broad class of the failure, `error.errors` lists every invalid field of a 422,
`error.limit` says which limit a 429 hit, and `error.body` is the response body.

The class follows the HTTP status, so `except` can pick one kind of failure:

| Class | Status |
| --- | --- |
| `MirabaseValidationError` | 400, 422 |
| `MirabaseAuthenticationError` | 401 |
| `MirabasePaymentRequiredError` | 402 (`balance_insufficient`, `key_token_limit_reached`, `budget_exceeded`) |
| `MirabasePermissionError` | 403 |
| `MirabaseNotFoundError` | 404; `MirabaseGoneError` (a subclass) for 410, such as an expired change cursor |
| `MirabaseConflictError` | 409; `MirabasePreconditionFailedError` (a subclass) for 412, such as a failed `If-Match` |
| `MirabaseRateLimitError` | 429 |
| `MirabaseServerError` | 500 and above |

All are subclasses of `MirabaseError`, and any other status is a plain `MirabaseError`.
`MirabaseConnectionError` means no response arrived (network failure or timeout), and
`MirabaseConfigError` a mistake in the call that was caught before anything was sent.

On deployments that sell prepaid tokens, a write, model call or answer the account cannot pay for raises
`MirabasePaymentRequiredError`; reads of existing data keep working. `error.code` says which limit
(`PAYMENT_REQUIRED_CODES` lists them) and `error.action` what to do: `top_up_balance` or `raise_budget` in the
console. A 429 `quota_exceeded` names the used-up quota in `error.quota`.

```python
from mirabase import MirabaseNotFoundError, MirabasePaymentRequiredError, MirabaseRateLimitError

try:
    entry = mb.entries.get(entry_id)
except MirabaseNotFoundError:
    entry = None
except MirabaseRateLimitError as error:
    print(error.limit, error.retry_after_seconds)
except MirabasePaymentRequiredError as error:
    print(error.code, error.action)  # top up or raise the budget in the console, then retry
```

## Versioning

`0.x`: a minor release may change the API, and says how in `CHANGELOG.md`; a patch release does not. The TypeScript,
Python and Go SDKs and the CLI release together under one number.

## Licence

Apache-2.0. See `LICENSE` and `NOTICE`.
