SDK
MarkdownInstall 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 |
npm install https://mirabase.io/sdk/mirabase-sdk-0.3.0-rc.1.tgzhttps://mirabase.io/sdk/SHA256SUMS lists the SHA-256 checksum of every file.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
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?");| 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, andansweralso takespaces: a list of Space ids, or"all"for every Space the key can read.spacestakes precedence overspace, and both take precedence over the pinned Space. - Wherever a call takes a Space id, you can also pass
defaultorext:<external_id>. - The client looks up the default Space once with
GET /v2/spaces/defaultand 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> and are safe to call again. See One Space per end user.
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 itselfStream 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 for what each event means. stream.text is the text so far, and the answer of final is what answer() returns.
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);- The SDK throws
MirabaseErrorfor anerrorevent, 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 thesignalcloses the connection, and the service cancels the answer. In Python usewithandfor, andasync withandasync forwithAsyncMirabase. answeritself does not stream: passingstream: true(stream=Truein Python) throwsMirabaseConfigErrorwith codestream_not_supportedand 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 |
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 |
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;
}
}Retries and idempotency
- The SDK retries a 429 automatically after the
Retry-Afterwait. WhenRetry-Afteris longer thanmaxRetryAfterMs(max_retry_afterin Python), it does not wait and throwsMirabaseRateLimitError. - 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 for the rules. - The SDK does not retry an error with
retryableset tofalse.
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.
for await (const entry of mirabase.entries.list()) {
console.log(entry.id);
}
const firstTen = await mirabase.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 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: learn what Spaces, Entries, versions, and memory are.
- Files and versions: write, read, and edit files.
- Memory: store a conversation with
conversations.addand wait for the service to distill memories. - API conventions: see the rules behind the pagination, idempotency, and retries the SDK handles for you.
