# 检索与上下文

由调用方选择来源的 search、由服务选择来源并分配预算的 context，以及带引用的 answer。

三个接口都需要 `knowledge:read`，`answer` 另外需要 `knowledge:answer`。不传 `space_ids` 时使用调用方能读的全部 Space，不只是默认 Space。请求只涉及一个最终用户或一个项目时，请在 `space_ids` 里指定它的 Space。

| 接口 | 来源选择方 | 适用场景 |
| --- | --- | --- |
| [`POST /v2/retrieval/search`](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-search) | 调用方 | 你知道要找什么，想自己排序和展示 |
| [`POST /v2/retrieval/context`](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-buildcontext) | 服务 | 给 Agent 的一个任务组装上下文，要控制 token 预算 |
| [`POST /v2/retrieval/answer`](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-answer) | 服务，并由模型作答 | 你没有自己的模型，想直接获得带引用的回答 |

## 检索

写入后的下一个请求就能通过词法检索到，处理完成后再加上向量检索和重排。

curl:

```bash
curl -X POST https://api.mirabase.dev/v2/retrieval/search \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "where do files and memory live"}'
```

TypeScript:

```ts
const hits = await mirabase.search("where do files and memory live");
```

Python:

```python
hits = mb.search("where do files and memory live")
```

读取结果时注意以下字段：

- `score` 只在同一个响应内可比较。
- `freshness: pending_index` 表示命中来自新鲜缓冲：仅完成词法匹配，该版本尚未处理完成。
- `partial` 为 `true` 时，某路检索发生降级，或分数未经相关度校准。
- `modified_at` 是该版本的写入时间；`occurred_at` 是来源自身的时间，例如对话中某条消息产生的时间。若写入时已知内容发生的时间，请传入 `occurred_at`。
- 段落注明截至日期时，命中结果带有 `stated_date` 和 `stated_date_from`。多个文件同时上传且 `modified_at` 相同时，可用它区分新旧记录。判定规则见 [stated_date](https://mirabase.io/zh/developers/api/schemas.md#DevSearchHit.stated_date)。
- 针对历史消息发起检索时，传入 `reference_time` 和 `timezone`，查询中的“昨天”“上周”即按该消息的时间换算。`context` 和 `answer` 同样接受这两个参数。
- 分支里的内容在合并之前检索不到。

## 构建上下文

`context` 接收一个任务描述，由服务挑选来源、分配预算并打包，同时在 `route` 里解释它的选择。路由用确定性规则，不调用模型，所以同样的输入可以重放和解释。

curl:

```bash
curl -X POST https://api.mirabase.dev/v2/retrieval/context \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"task": "Fix the failing upload test", "purpose": "coding", "tier": "standard", "budget_tokens": 4000}'
```

TypeScript:

```ts
const pack = await mirabase.context("Fix the failing upload test", {
  purpose: "coding",
  tier: "standard",
  budget_tokens: 4000,
});
```

Python:

```python
pack = mb.context(
    "Fix the failing upload test",
    purpose="coding",
    tier="standard",
    budget_tokens=4000,
)
```

来源有 `memory`、`agent_profile`、`skills`、`files`、`changes` 和 `knowledge`。`route.sources` 逐个列出已启用来源的预算、用量、选中和省略的数量，以及 `why` 中的稳定代码；已禁用的来源记录在 [rules_fired](https://mirabase.io/zh/developers/api/schemas.md#DevContextRoute.rules_fired) 中。未用完的预算留空，记在 `route.unused_tokens` 中，不会填入不相关的内容。

- `budget_tokens` 覆盖整个响应，不只是 `items`；`tokens_used` 不会超过它。
- `memory_view` 是确定性的记忆视图：相同的记忆生成相同的字节，与任务无关。把 `memory_view_etag` 作为 `have_memory_etag` 传回，视图未变更时不再重复返回，适合作为 prompt 缓存前缀。
- 技能来自 `/.mirabase/skills/<name>/SKILL.md`。`skills` 条目的 `text` 是一行描述，正文按 `path` 读取。
- 条目可能带 `flags`：`stale`、`superseded`、`conflict` 或 `agent_written`。
- 打包期间证据变化时，服务会自动重新打包一次；仍然变化才返回 409 `evidence_changed`，此时再发一次同样的请求。

### 表格计算

任务要对表格求和、计数、求平均或取最大值、最小值时，服务会在整张表上计算，不调用模型；何时计算、不计算的原因和上限见 [API 参考](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-buildcontext)。计算结果是单独的一个条目，正文写明运算、所用的列、筛选条件、参与计算的行数和结果。

### 以文本形式获取上下文

若无需自行拼接提示词，可在请求中传入 `render: "text"`，响应将增加 `rendered` 字段：`rendered.text` 是将该上下文包排版后的文本，可直接放入提示词。首行声明内容为参考材料而非指令；随后是记忆视图；之后在各自的 `[cN]` 编号下列出各来源内容。同一上下文包渲染出的文本完全相同。

## 获取带引用的回答

[`POST /v2/retrieval/answer`](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-answer) 用 `context` 会选的证据回答 `question`，在正文里用 `[cN]` 标注引用。它接受与 `context` 相同的选择参数，另有 `history`、`output_language`、`include` 和 `stream`。自己有模型时，通常用 `context` 更合适。

curl:

```bash
curl -X POST https://api.mirabase.dev/v2/retrieval/answer \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"question": "When do releases go out?", "output_language": "en"}'
```

TypeScript:

```ts
const reply = await mirabase.answer("When do releases go out?", { output_language: "en" });
if (reply.status === "answered") console.log(reply.answer, reply.citations);
else console.log("abstained:", reply.reason);

// Report what you used, the same as for a context pack.
await mirabase.context.feedback(reply.pack_id, reply.citations.map((citation) => citation.citation_id));
```

Python:

```python
reply = mb.answer("When do releases go out?", output_language="en")
if reply["status"] == "answered":
    print(reply["answer"], reply["citations"])
else:
    print("abstained:", reply.get("reason"))

# Report what you used, the same as for a context pack.
mb.context.feedback(reply["pack_id"], [citation["citation_id"] for citation in reply["citations"]])
```

- 先看 `status`：`answered` 或 `abstained`。放弃时 `answer` 为空，`reason` 说明原因，取值见 [DevAnswerAbstainReason](https://mirabase.io/zh/developers/api/schemas.md#DevAnswerAbstainReason)。找不到相关证据时不调用模型，直接返回 `no_evidence`。
- `citations` 只列回答里引用了的证据，按首次引用的顺序；`evidence_count` 是交给模型的条目数。`pack_id` 和上下文包一样可以接收反馈。
- 模型会得知每条证据的写入时间和内容对应的日期。问题问的是当前状态（如“现在”“目前”）时，关于同一事物的证据按从新到旧排列。同一事物指同一个 Entry、多次保存的同一个网页，或 `metadata.subject_key` 取值相同的几个 Entry；路径或标题相似不算。要让一组文件（如每周的状态报告）按新旧排列，请给它们设置相同的 `subject_key`。
- 回答默认不使用 `changes` 和 `skills` 两个来源；要使用它们，请传 [weights](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-answer.body.weights)。
- 同时运行的回答数有上限，超出时返回 429 `rate_limited`，见 [限流与限额](https://mirabase.io/zh/developers/conventions.md#rate-limits)。502 `model_failed` 和 503 `answer_unavailable` 可以稍后重试。SDK 只在 429 时自动重试回答；502 和 503 不重试，因为每次尝试都是一次模型调用。

### 查看模型读过的证据

请求带 `include: ["evidence"]` 时，响应增加 `evidence`，按模型读取的顺序列出它读过的每一条证据，不带正文。回答给出旧值时，用它核对模型读了哪几条，以及每一条的日期。

### 流式获取回答

请求带 `stream: true` 时，响应是 `text/event-stream`，而不是单个 JSON 响应体。认证、校验和等待空闲名额都在流打开之前完成，因此这些错误仍是普通的 HTTP 响应。流打开后状态码是 200，之后的错误作为 `error` 事件返回。两个 SDK 都提供 `answer.stream`，替你解析事件。各事件的 `data` 结构见 [获取带引用的回答](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-answer)。

curl:

```bash
# -N turns off curl's output buffering, so each event prints as it arrives.
curl -N -X POST https://api.mirabase.dev/v2/retrieval/answer \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"question": "When do releases go out?", "stream": true}'
```

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

```text
: stream open

id: 1
event: start
data: {"request_id":"req_5d1e","pack_id":"pck_7c19","evidence_count":6,"partial":false}

id: 2
event: delta
data: {"text":"Releases go out "}

: ping

id: 3
event: delta
data: {"text":"on Thursdays [c1]."}

id: 4
event: final
data: {"status":"answered","answer":"Releases go out on Thursdays [c1].","citations":[{"citation_id":"c1","entry_id":"ent_9a41","version_id":"ver_4d02","title":"release-notes.md","source":"files","path":"/notes/release-notes.md","text":"From November on, releases go out on Thursdays."}],"evidence_count":6,"pack_id":"pck_7c19","partial":false,"route":{"purpose":"task","tier":"standard","rules_fired":["source:off:changes:answer_default","source:off:skills:answer_default"],"sources":[],"unused_tokens":1200}}
```

- 按顺序拼接 `delta` 的文本。收到 `replace` 时丢弃已显示的文本，改为显示 `final` 的 `answer`；有的回答只有 `final`，没有 `delta`。
- 以 `:` 开头的行是保持连接的注释，忽略它们，也忽略不认识的事件名。
- `final` 和 `error` 只发送其中一个，发送后流结束。收到 `error` 时丢弃已显示的文本。未收到这两者即结束的流说明连接已中断：请按请求失败处理并重新提问。流不支持续传。
- 流式回答在流结束之前占用一个回答名额。断开连接会取消回答并释放名额；在 SDK 里提前跳出循环、调用 `close()` 或取消 `signal` 都会断开连接。
- SDK 的 `answer.stream` 把 `error` 事件、中途断流和无法解析的数据都作为 `MirabaseError` 抛出，已经开始的流不会自动重试。`mirabase.answer(question, { stream: true })` 不会流式返回：它抛出 `MirabaseConfigError`，代码为 `stream_not_supported`，请改用 `answer.stream`。

## 发送反馈

[`POST /v2/retrieval/context/{pack_id}/feedback`](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-contextfeedback) 传实际用到的 `used_citation_ids`，只传引用，不传内容。报告会累加，重复或分几次报告都安全。

curl:

```bash
curl -X POST "https://api.mirabase.dev/v2/retrieval/context/$PACK_ID/feedback" \
  -H "Authorization: Bearer $MIRABASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"used_citation_ids": ["c1"]}'
```

TypeScript:

```ts
await mirabase.context.feedback(pack.pack_id, ["c1"]);
```

Python:

```python
mb.context.feedback(pack["pack_id"], ["c1"])
```

## 授权

- 服务在规划之前先解析允许访问的 Space；对于不可见或不存在的 Space，服务均返回 404 `not_found`。
- 所有结果都经过同一道最终检查，`route` 和省略计数在授权之后生成。
- `scope_used.space_ids` 是这次实际用到的 Space。
- `agent_profile` 仅对 Agent 的 Key 启用。

> **说明：** MCP 客户端可以用同一个 API Key 连接 `/mcp`。工具 `mira.search`、`mira.context`、`mira.answer` 和 `mira.context.feedback` 各对应一次上面的请求，见 [连接 Agent（MCP）](https://mirabase.io/zh/developers/agents.md)。

## 查看检索过程

将请求中的 [explain](https://mirabase.io/zh/developers/api/retrieval.md#retrieval-search.body.explain) 设为 `true` 时，`search`、`context` 和 `answer` 的每条结果以及响应本身都会包含 `explain`：说明结果由哪几路检索召回、重排前后的位置、匹配的查询词，以及调整了其位置的规则。检索结果及其顺序不会因此改变。

- 控制台的“检索测试台”以你的登录身份或你提供的 API Key 运行搜索、上下文和回答，并显示每条结果的召回原因。
- 控制台的“请求日志”列出账户最近的 API 请求（仅含元数据），可按状态、路由、API Key、客户端和错误码筛选；对于检索请求，可以查看其轨迹，或在检索测试台中重新打开。仅团队所有者和管理员可查看。
- 同样的数据也可以通过 API 读取：[`GET /v2/request-logs`](https://mirabase.io/zh/developers/api/request-logs.md#requestlogs-list) 和 [`GET /v2/retrieval/traces/{trace_id}`](https://mirabase.io/zh/developers/api/request-logs.md#requestlogs-trace)。所需权限和保留期见 [API 参考](https://mirabase.io/zh/developers/api/request-logs.md)。

## 下一步

- [记忆](https://mirabase.io/zh/developers/memory.md)：让上下文里带上提炼出的事实。
- [连接 Agent](https://mirabase.io/zh/developers/agents.md)：让 Agent 通过 MCP 使用同样的检索。
- [API 约定](https://mirabase.io/zh/developers/conventions.md#rate-limits)：检索的并发和速率限制。
