# SDK

安装和配置 TypeScript 与 Python 客户端，并了解它们替你处理的 Space 选择、流式回答、错误、重试和分页。

## 安装 SDK

| 语言 | 包 | 版本 | 运行要求 |
| --- | --- | --- | --- |
| TypeScript | `@mirabase/sdk` | 0.3.0-rc.1 | Node.js 20.3 及以上，仅提供 ES 模块，无依赖 |
| Python | `mirabase` | 0.3.0rc1 | Python 3.11 及以上，无依赖 |

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
```

> **说明：** 0.3.0-rc.1（Python 为 0.3.0rc1）是 0.3.0 的候选版本。正式版发布前，方法和返回字段仍可能调整。

> **说明：** 安装包由本站点直接提供，地址中包含版本号。升级时请使用新版本的地址；旧版本地址长期有效，且内容保持不变。每个文件的 SHA-256 列于 `https://mirabase.io/sdk/SHA256SUMS`。

> **注意：** 在 0.2.0 中，固定到某个 Space 的客户端（通过 `space` 选项或 `space(id)`）在调用 `search`、`context` 和 `answer` 时未限定到该 Space，而是会读取该 Key 可读的所有 Space。请升级到 0.3.0-rc.1（Python 为 0.3.0rc1）。

## 创建客户端

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 | 默认值 | 含义 |
| --- | --- | --- | --- |
| `apiKey` | `api_key` | 环境变量 `MIRABASE_API_KEY` | API Key |
| `baseUrl` | `base_url` | `https://api.mirabase.dev` | 服务地址 |
| `space` | `space` | 不固定 | 把客户端固定到一个 Space，见下文 |
| `timeoutMs` | `timeout` | 60 秒 | 每次尝试的超时 |
| `maxRetries` | `max_retries` | 3 | 最多重试几次 |
| `maxRetryAfterMs` | `max_retry_after` | 60 秒 | 服务要求等待的时间超过该值时不等待，直接返回错误 |

Python 另有 `AsyncMirabase`，方法相同，用于 `asyncio`，支持 `async with` 和 `aclose()`。每个请求都带 `User-Agent: mirabase-node/<版本>`（Python 是 `mirabase-python/<版本>`）；版本号也可以从 `SDK_VERSION`（TypeScript）和 `mirabase.__version__`（Python）读到。

## 选择调用的 Space

| 客户端 | 文件、导入、对话等 | `search`、`context`、`answer` |
| --- | --- | --- |
| 不固定 | 默认 Space | 这个 Key 能读的全部 Space |
| 用 `space` 选项或 `space(id)` 固定 | 固定的 Space | 只读固定的 Space |

- 每次调用都可以用 `space` 指定一个 Space。`search`、`context` 和 `answer` 还接受 `spaces`：一组 Space id，或 `"all"`（这个 Key 能读的全部 Space）。`spaces` 优先于 `space`，两者都优先于客户端固定的 Space。
- 需要 Space id 的地方都可以写 `default` 或 `ext:<external_id>`。
- 默认 Space 只查一次并缓存，用的是一次 [`GET /v2/spaces/default`](https://mirabase.io/zh/developers/api/spaces.md#spaces-read)。

每个最终用户一个 Space 时，用 `spaceFor`（Python 是 `space_for`）按你自己的用户 id 取得一个固定在这个用户 Space 上的客户端；Space 不存在时会创建。只需获取 Space 本身时使用 `spaces.ensure`。两者都只发一次 [`PUT /v2/spaces/ext:<external_id>`](https://mirabase.io/zh/developers/api/spaces.md#spaces-ensure)，重复调用是安全的。见 [一个最终用户一个 Space](https://mirabase.io/zh/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
```

## 流式获取回答

`answer.stream` 接受与 `answer` 相同的参数，边生成边返回 `start`、`delta`、`replace` 和 `final` 事件，事件的含义见 [流式获取回答](https://mirabase.io/zh/developers/retrieval.md#answer-stream)。`stream.text` 是到目前为止的文本，`final` 的 `answer` 与 `answer()` 的返回值相同。

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"])
```

- `error` 事件、中途断流和无法解析的数据都作为 `MirabaseError` 抛出，不会抛出原始的解析错误。已经开始的流不会自动重试。
- 提前跳出循环、调用 `close()` 或取消 `signal` 都会关闭连接，服务随之取消回答。Python 用 `with` 和 `for`，`AsyncMirabase` 用 `async with` 和 `async for`。
- `answer` 本身不流式返回：传 `stream: true`（Python 是 `stream=True`）会抛出 `MirabaseConfigError`，代码为 `stream_not_supported`，不发出请求。

## 处理错误

请求失败时抛出 `MirabaseError` 或它的子类。子类由 HTTP 状态码决定，可以用 `instanceof`（Python 用 `except`）只处理一类错误。具体情况按 `code` 和 `action` 分支，二者保持稳定；`message` 供人阅读。

| 类 | HTTP 状态码 |
| --- | --- |
| `MirabaseValidationError` | 400、422 |
| `MirabaseAuthenticationError` | 401 |
| `MirabasePermissionError` | 403 |
| `MirabaseNotFoundError` | 404、410 |
| `MirabaseConflictError` | 409、412 |
| `MirabaseRateLimitError` | 429 |
| `MirabaseServerError` | 500 及以上 |
| `MirabaseConnectionError` | 没有收到响应：网络故障或超时。错误信息写明地址、请求和原因 |
| `MirabaseConfigError` | 调用本身有误，在发出请求前检出。创建客户端时即校验 API Key：首尾的空白字符会被去除，Key 中含有换行、空格、控制字符或非 ASCII 字符时，代码为 `invalid_api_key`，错误信息不包含 Key |

这些类都继承 `MirabaseError`；其他状态码抛出的是 `MirabaseError` 本身。

| TypeScript | Python | 含义 |
| --- | --- | --- |
| `status` | `status` | HTTP 状态码 |
| `code` | `code` | 错误码，见 [错误码](https://mirabase.io/zh/developers/errors.md#codes) |
| `type` | `type` | 错误的大类，如 `not_found`、`rate_limit` |
| `action` | `action` | 下一步操作，仅在服务返回时提供 |
| `retryable` | `retryable` | 重试是否有意义 |
| `requestId` | `request_id` | 请求 id，联系支持时请提供 |
| `field` | `field` | 422 时第一个出错的字段 |
| `errors` | `errors` | 422 时请求体里的全部问题，每项是 `{field, code, message}` |
| `limit` | `limit` | 429 时触发的限制：`request_rate` 或 `concurrency` |
| `retryAfterSeconds` | `retry_after_seconds` | 服务要求等待的秒数 |
| `currentVersionId` | `current_version_id` | 412 时文件的当前版本 |
| `body` | `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)
```

## 重试和幂等

- 429 会自动重试，按 `Retry-After` 等待。`Retry-After` 超过 `maxRetryAfterMs`（Python 为 `max_retry_after`）时不等待，直接抛出 `MirabaseRateLimitError`。
- 网络错误和 5xx 只在重发安全时重试：读请求，以及带幂等键的写请求。
- 对接受 `Idempotency-Key` 的调用，SDK 会自动生成幂等键并在重试时复用，避免重复写入。规则见 [API 约定](https://mirabase.io/zh/developers/conventions.md#idempotency)。
- `retryable` 为 `false` 的错误不重试。

## 遍历列表

列表方法返回可直接遍历的对象，并按需自动翻页。`limit` 是每页条数，不是总数；只需前几条时使用 `take`。

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` 返回命中的数组，数组上另有 `traceId` 和 `partial`（Python 是 `trace_id` 和 `partial`）。`partial` 为 `true` 时结果可能不完整。

## 上传大文件

`files.write` 自动选择上传方式：16 MiB 以内使用单次 `PUT`，超过 16 MiB 使用分片上传。调用方式不变。

## 直接调用接口

[API 参考](https://mirabase.io/zh/developers/api.md) 中的每个接口在 `raw` 上都有对应的方法（TypeScript 为 `mirabase.raw`，Python 为 `mb.raw`）。资源方法不适用时可调用它，认证、重试和错误处理方式相同。

## 下一步

- [核心概念](https://mirabase.io/zh/developers/concepts.md)：了解 Space、Entry、版本和记忆。
- [文件与版本](https://mirabase.io/zh/developers/files.md)：写入、读取和修改文件。
- [记忆](https://mirabase.io/zh/developers/memory.md#conversation)：用 `conversations.add` 写入对话，并等待服务提炼记忆。
- [API 约定](https://mirabase.io/zh/developers/conventions.md)：了解 SDK 自动处理的分页、幂等和重试规则。
