Skip to content
Developer docs
Docs menu

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

LanguagePackageVersionRequires
TypeScript@mirabase/sdk0.3.0-rc.1Node.js 20.3 or newer, ES modules only, no dependencies
Pythonmirabase0.3.0rc1Python 3.11 or newer, no dependencies
TypeScript
npm install https://mirabase.io/sdk/mirabase-sdk-0.3.0-rc.1.tgz
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.
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.
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
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?");
TypeScriptPythonDefaultMeaning
apiKeyapi_keyThe MIRABASE_API_KEY environment variableThe API key
baseUrlbase_urlhttps://api.mirabase.devThe service address
spacespaceNot pinnedPins the client to one Space, as described below
timeoutMstimeout60 secondsTimeout of each attempt
maxRetriesmax_retries3How many times to retry
maxRetryAfterMsmax_retry_after60 secondsWhen 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

ClientFiles, ingest, conversations, and the likesearch, context, answer
Not pinnedThe default SpaceEvery Space the key can read
Pinned with the space option or space(id)The pinned SpaceThe 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 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> and are safe to call again. See One Space per end user.

TypeScript
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

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 for what each event means. stream.text is the text so far, and the answer of final is what answer() returns.

TypeScript
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 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.

ClassHTTP status
MirabaseValidationError400, 422
MirabaseAuthenticationError401
MirabasePermissionError403
MirabaseNotFoundError404, 410
MirabaseConflictError409, 412
MirabaseRateLimitError429
MirabaseServerError500 and above
MirabaseConnectionErrorNo response arrived: a network failure or a timeout. The message names the address, the request, and the cause
MirabaseConfigErrorA 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.

TypeScriptPythonMeaning
statusstatusHTTP status
codecodeThe error code; see Error codes
typetypeThe broad class of the error, such as not_found or rate_limit
actionactionThe next step, when the service names one
retryableretryableWhether a retry can help
requestIdrequest_idThe request id. Include it when contacting support
fieldfieldFirst offending field on a 422
errorserrorsOn a 422, every problem in the request body, each as {field, code, message}
limitlimitOn a 429, the limit that was hit: request_rate or concurrency
retryAfterSecondsretry_after_secondsSeconds the service asked you to wait
currentVersionIdcurrent_version_idThe file's current version on a 412
bodybodyThe response body
TypeScript
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-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 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
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.add and wait for the service to distill memories.
  • API conventions: see the rules behind the pagination, idempotency, and retries the SDK handles for you.