# SDK

Install and configure the TypeScript and Python clients, and learn what they handle for you: Space selection, streaming answers, errors, retries, and pagination.

## Install the SDK

| Language | Package | Version | Requires |
| --- | --- | --- | --- |
| TypeScript | `@mirabase/sdk` | 0.3.0-rc.1 | Node.js 20.3 or newer, ES modules only, no dependencies |
| Python | `mirabase` | 0.3.0rc1 | Python 3.11 or newer, no dependencies |

TypeScript:

```bash
npm install https://mirabase.io/sdk/mirabase-sdk-0.3.0-rc.1.tgz
```

Python:

```bash
pip install https://mirabase.io/sdk/mirabase-0.3.0rc1-py3-none-any.whl
```

> **Note:** 0.3.0-rc.1 (0.3.0rc1 in Python) is a release candidate for 0.3.0. Methods and response fields may still change before the final release.

> **Note:** This site serves the packages at versioned URLs. To upgrade, install from the new version's URL. Older URLs keep working, and their content never changes. `https://mirabase.io/sdk/SHA256SUMS` lists the SHA-256 checksum of every file.

> **Warning:** In 0.2.0, a client pinned to a Space (via the `space` option or `space(id)`) did not restrict `search`, `context`, and `answer` to that Space, reading every Space the key can read instead. Upgrade to 0.3.0-rc.1 (0.3.0rc1 in Python).

## Create a client

TypeScript:

```ts
import { Mirabase } from "@mirabase/sdk/developer";

// Reads MIRABASE_API_KEY when apiKey is omitted.
const mirabase = new Mirabase();

await mirabase.files.write("/notes/plan.md", "We ship on Friday.\n");
const hits = await mirabase.search("when do we ship?");
```

Python:

```python
from mirabase import Mirabase

# Reads MIRABASE_API_KEY when api_key is omitted.
mb = Mirabase()

mb.files.write("/notes/plan.md", "We ship on Friday.\n")
hits = mb.search("when do we ship?")
```

| TypeScript | Python | Default | Meaning |
| --- | --- | --- | --- |
| `apiKey` | `api_key` | The `MIRABASE_API_KEY` environment variable | The API key |
| `baseUrl` | `base_url` | `https://api.mirabase.dev` | The service address |
| `space` | `space` | Not pinned | Pins the client to one Space, as described below |
| `timeoutMs` | `timeout` | 60 seconds | Timeout of each attempt |
| `maxRetries` | `max_retries` | 3 | How many times to retry |
| `maxRetryAfterMs` | `max_retry_after` | 60 seconds | When the service asks for a longer wait than this, the client returns the error to you without waiting |

Python also has `AsyncMirabase` with the same methods for `asyncio`, with `async with` and `aclose()`. Every request carries `User-Agent: mirabase-node/<version>` (`mirabase-python/<version>` in Python); the version is also in `SDK_VERSION` (TypeScript) and `mirabase.__version__` (Python).

## Choose the Space a call uses

| Client | Files, ingest, conversations, and the like | `search`, `context`, `answer` |
| --- | --- | --- |
| Not pinned | The default Space | Every Space the key can read |
| Pinned with the `space` option or `space(id)` | The pinned Space | The pinned Space only |

- Any call can name one Space with `space`. `search`, `context`, and `answer` also take `spaces`: a list of Space ids, or `"all"` for every Space the key can read. `spaces` takes precedence over `space`, and both take precedence over the pinned Space.
- Wherever a call takes a Space id, you can also pass `default` or `ext:<external_id>`.
- The client looks up the default Space once with [`GET /v2/spaces/default`](https://mirabase.io/developers/api/spaces.md#spaces-read) and caches it.

With one Space per end user, `spaceFor` (`space_for` in Python) takes your own user id and returns a client pinned to that user's Space, creating the Space when there is none. `spaces.ensure` returns the Space itself. Both send one [`PUT /v2/spaces/ext:<external_id>`](https://mirabase.io/developers/api/spaces.md#spaces-ensure) and are safe to call again. See [One Space per end user](https://mirabase.io/developers/concepts.md#space-per-user).

TypeScript:

```ts
const user = await mirabase.spaceFor("user-42", { name: "User 42" });
await user.conversations.add(messages, { sessionId: "chat-1" });
const reply = await user.answer("What does this user prefer?"); // reads this Space only

const space = await mirabase.spaces.ensure("user-42"); // the Space itself
```

Python:

```python
user = mb.space_for("user-42", name="User 42")
user.conversations.add(messages, session_id="chat-1")
reply = user.answer("What does this user prefer?")  # reads this Space only

space = mb.spaces.ensure("user-42")  # the Space itself
```

## Stream an answer

`answer.stream` takes the same arguments as `answer` and yields `start`, `delta`, `replace`, and `final` events as the answer is written; see [Stream an answer](https://mirabase.io/developers/retrieval.md#answer-stream) for what each event means. `stream.text` is the text so far, and the `answer` of `final` is what `answer()` returns.

TypeScript:

```ts
const stream = mirabase.answer.stream("When do releases go out?");
for await (const event of stream) {
  if (event.type === "start") console.log("evidence items:", event.evidence_count);
  if (event.type === "delta") process.stdout.write(event.text);
  if (event.type === "replace") console.log("\n(the text so far is replaced by the final answer)");
}

// final is authoritative: the same object mirabase.answer returns.
const reply = await stream.finalAnswer();
console.log(reply.status, reply.answer, reply.citations);
```

Python:

```python
with mb.answer.stream("When do releases go out?") as stream:
    for event in stream:
        if event["type"] == "start":
            print("evidence items:", event["evidence_count"])
        elif event["type"] == "delta":
            print(event["text"], end="", flush=True)
        elif event["type"] == "replace":
            print("\n(the text so far is replaced by the final answer)")
    # final is authoritative: the same object mb.answer returns.
    reply = stream.final_answer()

print(reply["status"], reply["answer"], reply["citations"])
```

- The SDK throws `MirabaseError` for an `error` event, a stream cut off midway, or unparseable data, never a raw parse error. It does not retry a stream after it starts.
- Leaving the loop early, calling `close()`, or aborting the `signal` closes the connection, and the service cancels the answer. In Python use `with` and `for`, and `async with` and `async for` with `AsyncMirabase`.
- `answer` itself does not stream: passing `stream: true` (`stream=True` in Python) throws `MirabaseConfigError` with code `stream_not_supported` and sends no request.

## Handle errors

A failed request throws `MirabaseError` or one of its subclasses. The subclass follows the HTTP status, so `instanceof` (`except` in Python) can handle one class of error. Branch on `code` and `action` for the specific case: they are stable. `message` is for human readers.

| Class | HTTP status |
| --- | --- |
| `MirabaseValidationError` | 400, 422 |
| `MirabaseAuthenticationError` | 401 |
| `MirabasePermissionError` | 403 |
| `MirabaseNotFoundError` | 404, 410 |
| `MirabaseConflictError` | 409, 412 |
| `MirabaseRateLimitError` | 429 |
| `MirabaseServerError` | 500 and above |
| `MirabaseConnectionError` | No response arrived: a network failure or a timeout. The message names the address, the request, and the cause |
| `MirabaseConfigError` | A mistake in the call, caught before sending the request. The API key is checked when the client is created: white space at its ends is dropped, and a line break, space, control character, or non-ASCII character inside it gives the code `invalid_api_key`, with a message that never contains the key |

All of them extend `MirabaseError`; any other status throws `MirabaseError` itself.

| TypeScript | Python | Meaning |
| --- | --- | --- |
| `status` | `status` | HTTP status |
| `code` | `code` | The error code; see [Error codes](https://mirabase.io/developers/errors.md#codes) |
| `type` | `type` | The broad class of the error, such as `not_found` or `rate_limit` |
| `action` | `action` | The next step, when the service names one |
| `retryable` | `retryable` | Whether a retry can help |
| `requestId` | `request_id` | The request id. Include it when contacting support |
| `field` | `field` | First offending field on a 422 |
| `errors` | `errors` | On a 422, every problem in the request body, each as `{field, code, message}` |
| `limit` | `limit` | On a 429, the limit that was hit: `request_rate` or `concurrency` |
| `retryAfterSeconds` | `retry_after_seconds` | Seconds the service asked you to wait |
| `currentVersionId` | `current_version_id` | The file's current version on a 412 |
| `body` | `body` | The response body |

TypeScript:

```ts
import { MirabaseConflictError, MirabaseRateLimitError } from "@mirabase/sdk/developer";

const { etag } = await mirabase.files.stat("/notes/plan.md");
try {
  await mirabase.files.write("/notes/plan.md", "v2\n", { ifMatch: etag });
} catch (error) {
  if (error instanceof MirabaseConflictError && error.code === "precondition_failed") {
    // Someone else wrote first: read again, then retry on error.currentVersionId.
  } else if (error instanceof MirabaseRateLimitError) {
    console.log(error.limit, error.retryAfterSeconds);
  } else {
    throw error;
  }
}
```

Python:

```python
from mirabase import MirabaseConflictError, MirabaseRateLimitError

etag = mb.files.stat("/notes/plan.md").etag
try:
    mb.files.write("/notes/plan.md", "v2\n", if_match=etag)
except MirabaseConflictError as error:
    if error.code != "precondition_failed":
        raise
    ...  # Someone else wrote first: read again, then retry on error.current_version_id.
except MirabaseRateLimitError as error:
    print(error.limit, error.retry_after_seconds)
```

## Retries and idempotency

- The SDK retries a 429 automatically after the `Retry-After` wait. When `Retry-After` is longer than `maxRetryAfterMs` (`max_retry_after` in Python), it does not wait and throws `MirabaseRateLimitError`.
- The SDK retries network errors and 5xx responses only when repeating is safe: reads, and writes that carry an idempotency key.
- For every call that takes `Idempotency-Key`, the SDK generates a key and reuses it on a retry, so a retry never writes twice. See [API conventions](https://mirabase.io/developers/conventions.md#idempotency) for the rules.
- The SDK does not retry an error with `retryable` set to `false`.

## Iterate a list

A list method returns an object you can iterate, and it fetches pages as needed. `limit` is the page size, not a total. Use `take` when you want only the first few.

TypeScript:

```ts
for await (const entry of mirabase.entries.list()) {
  console.log(entry.id);
}

const firstTen = await mirabase.entries.list().take(10);
```

Python:

```python
for entry in mb.entries.list():
    print(entry["id"])

first_ten = mb.entries.list().take(10)
```

`search` returns the array of hits, which also carries `traceId` and `partial` (`trace_id` and `partial` in Python). When `partial` is `true`, the results may be incomplete.

## Upload a large file

`files.write` picks the route itself: one `PUT` up to 16 MiB, and a multipart upload above that. The call is the same either way.

## Call an endpoint directly

Every endpoint in the [API reference](https://mirabase.io/developers/api.md) has a method of its own on `raw` (`mirabase.raw` in TypeScript, `mb.raw` in Python). Reach for it when a resource method does not fit. Authentication, retries, and errors work the same.

## Next steps

- [Core concepts](https://mirabase.io/developers/concepts.md): learn what Spaces, Entries, versions, and memory are.
- [Files and versions](https://mirabase.io/developers/files.md): write, read, and edit files.
- [Memory](https://mirabase.io/developers/memory.md#conversation): store a conversation with `conversations.add` and wait for the service to distill memories.
- [API conventions](https://mirabase.io/developers/conventions.md): see the rules behind the pagination, idempotency, and retries the SDK handles for you.
