<!-- api/audio -->
---
title: 音訊
description: OpenAI 風格的語音轉文字、翻譯與文字轉語音端點，以及本機自訂語音，由 mlx-audio 模型提供。
---

音訊路由遵循 OpenAI 的 `/v1/audio/*` 規格。轉錄與翻譯接收 multipart 上傳，回傳 JSON 或字幕文字；語音合成接收 JSON，回傳編碼後的音訊，或是以 Server-Sent Events 串流傳送的原始 PCM 區塊。Yunshu 另外提供本機自訂語音（同意錄音加語音登錄）。

音訊模型來自選用的 `audio` extra（`pip install "yunshu[audio]"`，底層為 `mlx-audio`）。你指定的模型必須是已載入、且類型正確的音訊模型（轉錄用 ASR，語音合成用 TTS），否則伺服器回傳 `404`，訊息會指出模態不符。

<Endpoint method="POST" path="/v1/audio/transcriptions" />
<Endpoint method="POST" path="/v1/audio/translations" />
<Endpoint method="POST" path="/v1/audio/speech" />
<Endpoint method="POST" path="/v1/audio/speech/stream" />
<Endpoint method="GET" path="/v1/audio/voices" />
<Endpoint method="POST" path="/v1/audio/voices" />
<Endpoint method="POST" path="/v1/audio/voice_consents" />

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。設定後請送出 `Authorization: Bearer <token>`（或 `x-api-key`）。未設定 token 時，這類推論路由對綁定的位址是開放的。
</Callout>

## 模型選擇

- 單模型模式（`yunshu serve` 只載入一個模型）會使用所服務的模型，`model` 欄位僅供參考。
- 多模型模式下，模型必須已經載入，否則請求會得到 `503`，訊息提示使用 `POST /v1/models/load`。設定 `YUNSHU_ALLOW_AUTO_LOAD=1` 後，音訊請求可以按需載入模型。
- 載入多個音訊引擎時，會使用 id 與 `model` 相符（不分大小寫）的引擎。

被辨識為 ASR 的模型系列有 `whisper`、`qwen3_asr`、`parakeet`、`qwen2_audio`；TTS 系列有 `qwen3_tts`、`kokoro`、`chatterbox`（以及名稱含 `tts` 者）。個別 checkpoint 能否運作取決於安裝的 `mlx-audio`，請參考[模型](/docs/getting-started/models)。

## 轉錄

`POST /v1/audio/transcriptions` 使用 `multipart/form-data`。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `file` | file | 是 | 音訊或影片上傳，最大 25 MB。音訊：`.wav .mp3 .ogg .flac .m4a .webm .aac`。影片：`.mp4 .mkv .avi .mov .wmv .ts .mts`（以 `ffmpeg` 擷取音軌）。 | 支援 |
| `model` | string | 是 | ASR 模型 id。空字串會回傳 `400`。 | 支援 |
| `language` | string | 否 | 傳給模型的語言提示。 | 支援 |
| `response_format` | string | 否 | `json`（預設）、`text`、`srt`、`vtt`、`verbose_json`。其他值回傳 `400`。 | 支援 |
| `prompt` | string | 否 | 傳給模型的提示文字。 | 支援 |
| `temperature` | number | 否 | 0 到 1。省略時由模型使用自己的預設值。 | 支援 |
| `timestamp_granularities` | list of string | 否 | 傳入 `word` 可要求逐字時間戳。同時接受 `timestamp_granularities` 與 SDK 使用的 `timestamp_granularities[]`。 | 支援 |

### 回應格式

| `response_format` | Content-Type | 內容 |
| --- | --- | --- |
| `json` | `application/json` | `{"text", "language"}`；模型有產生時另含 `segments` 與 `duration` |
| `verbose_json` | `application/json` | `text`、`language`、`task: "transcribe"`、`duration`、`segments`（欄位會補齊成 OpenAI 的 segment 結構，模型沒給的欄位用中性預設值），可用時另含 `words` |
| `text` | `text/plain` | 純文字逐字稿 |
| `srt` | `text/plain` | 由 segments 產生的 SubRip 字幕 |
| `vtt` | `text/vtt` | 由 segments 產生的 WebVTT 字幕 |

`srt` 與 `vtt` 需要 segment 時間戳。模型若沒有回傳 segments，字幕內容會是空的。

## 翻譯

`POST /v1/audio/translations` 把語音解碼成英文文字。接受 `file`、`model`、`response_format`（同樣五種值）、`prompt` 與 `temperature`，沒有 `language` 欄位。

翻譯是 Whisper 的能力。若已載入的模型路徑與請求的 id 都不含 `whisper`，伺服器回傳 `501`：

```json
{
  "error": {
    "message": "The loaded ASR model does not support translation (Whisper-only). Load a Whisper model for /v1/audio/translations, or use /v1/audio/transcriptions followed by an LLM translation step.",
    "type": "server_error",
    "param": null,
    "code": null
  }
}
```

`json` 回傳 `{"text": ...}`。`verbose_json` 另含 `task: "translate"`、`language: "english"`、`duration` 與 `segments`。`text`、`srt`、`vtt` 回傳純文字內容（這裡三者都是 `text/plain`）。

## 語音合成

`POST /v1/audio/speech` 接受 JSON 本文（或欄位名稱相同的 `multipart/form-data`），回傳音訊位元組，並帶有 `Content-Disposition: attachment; filename=speech.<ext>` 標頭。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | TTS 模型 id。 | 支援 |
| `input` | string | 是 | 要朗讀的文字。不可為空，最多 32768 個字元。 | 支援 |
| `voice` | string 或 object | 否 | 語音名稱（預設 `alloy`），或以 `POST /v1/audio/voices` 登錄的自訂語音 `{"id": "voice_..."}`。內建名稱以 `GET /v1/audio/voices` 為準；備用清單為 `alloy`、`chelsie`、`ethan`、`aiden`。 | 支援 |
| `response_format` | string | 否 | `mp3`、`opus`、`aac`、`flac`、`wav`、`pcm`。伺服器預設為 `wav`；官方 OpenAI SDK 除非你覆寫，否則會送出 `mp3`。可用 `format` 作為別名。 | 支援 |
| `speed` | number | 否 | 0.25 到 4.0，預設 1.0。 | 支援 |
| `temperature` | number | 否 | 0 到 2。 | 支援 |
| `instruct` | string | 否 | 給 VoiceDesign 類模型的自由描述。省略時會依語音名稱產生簡短描述。 | 擴充 |
| `top_k` | integer | 否 | 預設 50。 | 擴充 |
| `top_p` | number | 否 | 0 到 1，預設 0.95。 | 擴充 |
| `repetition_penalty` | number | 否 | 0 到 2，預設 1.0。 | 擴充 |
| `max_tokens` | integer | 否 | 1 到 32768，預設 4096。 | 擴充 |
| `ref_audio` | string | 否 | 聲音複製用的本機參考錄音路徑。URI scheme 與 `..` 片段會被拒絕；絕對路徑需要 `YUNSHU_ALLOW_LOCAL_FILES=1`。不能與自訂 `voice` 同時使用。 | 擴充 |
| `ref_text` | string | 否 | 參考錄音的逐字稿。 | 擴充 |
| `language` | string | 否 | 多語系模型使用的語言代碼。 | 擴充 |
| `seed` | integer | 否 | 隨機種子。 | 擴充 |
| `segment_size` | integer | 否 | 50 到 2000，預設 300。只用於串流路由。 | 擴充 |
| `instructions`、`stream_format` | | 否 | 不在結構內的 OpenAI 欄位，會被忽略。 | 接受但忽略 |

### 輸出格式與 ffmpeg 後備

引擎產生的是 WAV，其他格式由 `ffmpeg` 轉碼：

| `response_format` | Content-Type | 備註 |
| --- | --- | --- |
| `wav` | `audio/wav` | 不轉碼。 |
| `pcm` | `audio/L16; rate=<取樣率>; channels=<n>` | 去掉 WAV 標頭的原始 16-bit little-endian 取樣，由 Python 處理，不需要 `ffmpeg`。 |
| `mp3` | `audio/mpeg` | 需要 `ffmpeg`。 |
| `opus` | `audio/ogg` | Ogg 封裝的 Opus；需要含 `libopus` 的 `ffmpeg`。 |
| `aac` | `audio/aac` | ADTS 串流；需要 `ffmpeg`。 |
| `flac` | `audio/flac` | 需要 `ffmpeg`。 |

若 `PATH` 中沒有 `ffmpeg`（或轉碼失敗），伺服器不會替位元組貼上錯誤的標籤，而是回傳 `audio/wav` 的 WAV 音訊，並加上回應標頭 `X-Yunshu-Audio-Format-Fallback: wav`，檔名為 `.wav`。若你依賴壓縮格式，請檢查這個標頭。安裝 `ffmpeg`（例如 `brew install ffmpeg`）即可避免後備。影片轉錄同樣依賴 `ffmpeg`，沒有時請求會失敗並回傳 `415`。

## 語音串流

`POST /v1/audio/speech/stream` 使用相同的 JSON 本文，回應為 `text/event-stream`。回應標頭包含 `X-Audio-Format: pcm-s16le` 與 `X-Sample-Rate: <取樣率>`。串流時沒有壓縮格式：區塊一律是原始 16-bit PCM，`response_format` 只會被驗證，不會有其他作用。

過長的輸入會依 `segment_size` 個字元切成多段，依序合成。事件順序如下：

| 事件 `type` | 欄位 | 時機 |
| --- | --- | --- |
| `header` | `wav_header`（base64）、`sample_rate` | 第一個事件。WAV 標頭宣告長度未知。 |
| `audio` | `audio`（base64 PCM16）、`text`、`segment` | 每個音訊區塊一筆。 |
| `done` | 無 | 最後一段之後。 |
| `cancelled` | 無 | 請求被取消，例如透過 `POST /v1/cancel`。 |
| `error` | `error.message`、`error.type` | 合成中途失敗。 |

`done` 或 `error` 之後，串流以 `data: [DONE]` 結束。`cancelled` 事件會直接結束串流，不會再送 `[DONE]`。

## 自訂語音

自訂語音只存在本機。錄音存放在有上限的 Files 儲存區，因此 Files 的配額與到期規則同樣適用，請見[檔案](/docs/api/files)。登錄流程會保存一份同意錄音，但不會驗證說話者身分。

1. `POST /v1/audio/voice_consents` 建立同意記錄。
2. `POST /v1/audio/voices` 建立引用該同意記錄的語音。
3. 在語音合成請求中使用 `"voice": {"id": "voice_..."}`。

`POST /v1/audio/voice_consents` 使用 `multipart/form-data`：

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `name` | string | 是 | 1 到 256 個字元。 |
| `language` | string | 是 | 最多 64 個字元。 |
| `recording` | file | 是 | 音訊，最大 10 MiB，解碼後最長 60 秒。MIME 類型須為 `audio/mpeg`、`audio/wav`、`audio/x-wav`、`audio/ogg`、`audio/aac`、`audio/flac`、`audio/webm`、`audio/mp4` 之一。 |

回傳 `{"object": "audio.voice_consent", "id": "cons_...", "name", "language", "created_at"}`。

`POST /v1/audio/voices` 使用 `multipart/form-data`：

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `name` | string | 是 | 1 到 256 個字元。 |
| `consent` | string | 是 | 上一步取得的 `cons_...` id。 |
| `audio_sample` | file | 是 | 限制與上面的 `recording` 相同。 |
| `type` | string | 否 | 只支援 `audio_sample`，其他值回傳 `400`（不支援以提示詞設計的語音）。 |
| `ref_text` | string | 否 | 樣本的逐字稿，最多 32768 個字元。 |

回傳 `{"object": "audio.voice", "id": "voice_...", "name", "type": "audio_sample", "created_at"}`。登錄時會用 `soundfile`（包含在 audio extra 中）解碼樣本；無法解碼的樣本回傳 `400`，缺少相依套件則回傳 `503`。

使用自訂語音需要支援參考音訊的 TTS 模型，否則語音合成請求會回傳 `400`。Qwen3-TTS 必須是 Base 模型，且需要逐字稿（登錄時的 `ref_text` 或語音合成請求中的 `ref_text`）；CustomVoice 與 VoiceDesign 變體會被拒絕。

`GET /v1/audio/voices` 回傳 `{"object": "list", "data": [{"id": "alloy", "object": "voice"}, ...]}`，先列出已載入 TTS 模型的內建名稱，再接上已登錄的自訂語音（完整語音物件）。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
# Transcribe
curl http://localhost:8000/v1/audio/transcriptions \
  -F file=@meeting.wav \
  -F model=local \
  -F response_format=verbose_json \
  -F "timestamp_granularities[]=word"

# Speak (WAV, no ffmpeg needed)
curl http://localhost:8000/v1/audio/speech \
  -H "Content-Type: application/json" \
  -d '{"model": "local", "input": "Hello from Yunshu.", "voice": "alloy", "response_format": "wav"}' \
  -o hello.wav
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

with open("meeting.wav", "rb") as f:
    result = client.audio.transcriptions.create(
        model="local", file=f, response_format="verbose_json"
    )
print(result.text)

speech = client.audio.speech.create(
    model="local", voice="alloy", input="Hello from Yunshu.", response_format="wav"
)
speech.write_to_file("hello.wav")
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";
import fs from "node:fs";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "not-needed" });

const result = await client.audio.transcriptions.create({
  model: "local",
  file: fs.createReadStream("meeting.wav"),
});
console.log(result.text);

const speech = await client.audio.speech.create({
  model: "local",
  voice: "alloy",
  input: "Hello from Yunshu.",
  response_format: "wav",
});
fs.writeFileSync("hello.wav", Buffer.from(await speech.arrayBuffer()));
```

</Tab>
</Tabs>

## 錯誤

錯誤使用 OpenAI 的格式 `{"error": {"message", "type", "param", "code"}}`。

| 狀態碼 | 情況 |
| --- | --- |
| `400` | `response_format` 不合法、`model` 或 `input` 為空、數值超出範圍、`voice` 物件不合法、上傳內容不是可解碼的音訊、自訂語音或同意記錄有誤。 |
| `404` | 找不到符合 `model` 且模態正確的已載入模型。 |
| `413` | 上傳超過 25 MB（轉錄、翻譯），或錄音超過 10 MiB（語音登錄）。 |
| `415` | 上傳了影片，但缺少 `ffmpeg` 或無法擷取音軌。 |
| `501` | 在非 Whisper 的 ASR 模型上要求翻譯。 |
| `503` | 多模型模式下模型未載入，或語音登錄缺少 `soundfile`。 |
| `507` | GPU 記憶體不足。 |
| `500` | 轉錄、翻譯或合成失敗。 |

回應開始後才發生的串流失敗，會以 `error` 事件送出，而不是 HTTP 狀態碼。

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 轉錄，`json` / `text` / `srt` / `vtt` / `verbose_json` | <Support status="supported">支援</Support> |
| 逐字時間戳 | <Support status="partial">ASR 模型有產生時才有</Support> |
| 翻譯成英文 | <Support status="partial">僅 Whisper 模型；其他回傳 501</Support> |
| 語音合成 `wav` 與 `pcm` | <Support status="supported">支援</Support> |
| 語音合成 `mp3`、`opus`、`aac`、`flac` | <Support status="partial">需要 ffmpeg，否則回傳帶後備標頭的 WAV</Support> |
| 串流時的壓縮音訊 | <Support status="unsupported">僅原始 PCM16</Support> |
| 自訂語音 | <Support status="partial">需要支援參考音訊的 TTS 模型</Support> |
| 提示詞設計語音（`type` 非 `audio_sample`） | <Support status="unsupported">回傳 400</Support> |
| `diarized_json`、`gpt-4o-transcribe` 串流事件 | <Support status="unsupported">尚未支援</Support> |

## 相關頁面

- [Realtime](/docs/api/realtime)：透過 WebSocket 進行語音對話。
- [擴充](/docs/api/extensions)：`POST /v1/omni/speech/stream`，原生語音對語音。
- [檔案](/docs/api/files)：存放已登錄語音的儲存區。
- [模型](/docs/getting-started/models)：選擇與載入音訊模型。


---

<!-- api/batches -->
---
title: 批次
description: OpenAI Batch API，由單一的 loopback 背景工作程序把每一行 JSONL 重播到本伺服器，重新啟動後可繼續執行。
---

`/v1/batches` 遵循 OpenAI Batch API。流程是：先透過[檔案 API](/docs/api/files) 上傳 `purpose=batch` 的 JSONL 請求檔，建立指向該檔案的批次，輪詢到批次結束，再下載輸出檔。Anthropic 的訊息批次使用同一套機制，文件寫在 [Messages](/docs/api/messages) 頁面。

<Endpoint method="POST" path="/v1/batches" />
<Endpoint method="GET" path="/v1/batches" />
<Endpoint method="GET" path="/v1/batches/{batch_id}" />
<Endpoint method="POST" path="/v1/batches/{batch_id}/cancel" />

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。背景工作程序呼叫伺服器時會沿用該 token，所以批次的驗證、模型路由、前綴快取與工具行為都和一般請求相同。
</Callout>

## 批次如何執行

- 單一背景工作程序依建立時間由舊到新處理排隊的批次，批次內的請求也是一次執行一筆。
- 每一行都會當作一般的 HTTP `POST`，送到本伺服器上該批次指定的端點（使用建立批次時的同一個主機與連接埠）。一般的即時流量會與之交錯，GPU 工作由引擎序列化。
- 每一行的 `stream` 都會被強制設為 `false`。
- 批次狀態存放在檔案儲存區（預設 `~/.yunshu/files`，可用 `YUNSHU_FILES_DIR` 變更）。重新啟動後，工作程序會接手未完成的批次，並跳過已經有結果的行，因此批次會從中斷處繼續。
- 完成期限固定為建立後 24 小時。超過期限仍未跑完時，批次以 `expired` 結束，剩下的行不會執行。

## 建立批次

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `input_file_id` | string | 是 | 以 `purpose=batch` 上傳的檔案。 | 支援 |
| `endpoint` | string | 是 | `/v1/chat/completions`、`/v1/completions`、`/v1/embeddings`、`/v1/responses` 之一。 | 支援 |
| `completion_window` | string | 是 | 必須是 `24h`。 | 支援 |
| `metadata` | object | 否 | 最多 16 個鍵，值只能是字串。 | 支援 |
| `output_expires_after` | object | 否 | OpenAI 用來設定輸出檔到期的欄位。 | 接受但忽略 |

### 輸入檔格式

每行一個 JSON 物件（空白行會略過）：

```json
{"custom_id": "req-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "local", "messages": [{"role": "user", "content": "Say hi"}], "max_tokens": 16}}
{"custom_id": "req-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "local", "messages": [{"role": "user", "content": "Say bye"}], "max_tokens": 16}}
```

建立批次時會檢查：

- `custom_id` 必填、為字串，且在檔案內唯一。
- `method` 必須是 `POST`。
- `url` 必須等於批次的 `endpoint`。
- `body` 必須是 JSON 物件，且不可設定 `stream: true`。
- 最多 50,000 筆請求。
- 檔案不可為空。

只要有任何一行驗證失敗，批次仍會建立，但 `status` 是 `"failed"`，並附上 `errors` 清單（最多 20 筆，含 `code`、`message`、`param`、`line`），不會執行任何請求。

## 批次物件

```json
{
  "id": "batch_0a1b2c3d4e5f60718293a4b5",
  "object": "batch",
  "endpoint": "/v1/chat/completions",
  "errors": null,
  "input_file_id": "file_9f8e7d6c5b4a39281716f5e4",
  "completion_window": "24h",
  "status": "in_progress",
  "output_file_id": null,
  "error_file_id": null,
  "created_at": 1767225600,
  "in_progress_at": 1767225601,
  "expires_at": 1767312000,
  "finalizing_at": null,
  "completed_at": null,
  "failed_at": null,
  "expired_at": null,
  "cancelling_at": null,
  "cancelled_at": null,
  "request_counts": { "total": 2, "completed": 1, "failed": 0 },
  "metadata": null
}
```

狀態有：`validating`、`failed`、`in_progress`、`finalizing`、`completed`、`expired`、`cancelling`、`cancelled`。輸入驗證通過的批次在工作程序接手前會維持 `validating`。id 也接受 `batch-...` 的寫法，並對應到 `batch_...`。

## 結果

批次結束時，成功的行寫入輸出檔，非 2xx 的行寫入錯誤檔。兩者都是儲存區裡的一般檔案（purpose 分別為 `batch_output` 與 `batch_error`），而且只有在有內容時才會建立。用 `output_file_id` 與 `error_file_id` 搭配 `GET /v1/files/{file_id}/content` 取得。

每一行結果：

```json
{"id": "batch_req_3c1f...", "custom_id": "req-1", "response": {"status_code": 200, "request_id": "req_...", "body": {"id": "chatcmpl-...", "object": "chat.completion"}}, "error": null}
```

如果請求根本送不出去（傳輸失敗），該行會是 `response: null`，並帶 `error: {"code": "request_failed", "message": ...}`，計為失敗。

## 列表與取消

`GET /v1/batches` 接受 `limit`（1 到 100，預設 20）與 `after`（批次 id），回傳 `{"object": "list", "data", "first_id", "last_id", "has_more"}`，由新到舊。

`POST /v1/batches/{batch_id}/cancel` 會把 `validating` 或 `in_progress` 的批次改成 `cancelling`；工作程序會在下一行之前停止，批次以 `cancelled` 結束。對已在 `cancelling` 的批次再次取消會原樣回傳。其他狀態回傳 `409`，code 為 `invalid_state`。已經完成的行會保留結果。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/files -F purpose=batch -F file=@requests.jsonl

curl http://localhost:8000/v1/batches \
  -H "Content-Type: application/json" \
  -d '{"input_file_id": "file_9f8e7d6c5b4a39281716f5e4", "endpoint": "/v1/chat/completions", "completion_window": "24h"}'

curl http://localhost:8000/v1/batches/batch_0a1b2c3d4e5f60718293a4b5
curl http://localhost:8000/v1/files/file_1122334455667788990011aa/content
```

</Tab>
<Tab value="Python">

```python
import time
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

up = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")
batch = client.batches.create(
    input_file_id=up.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)

while batch.status in ("validating", "in_progress", "finalizing", "cancelling"):
    time.sleep(2)
    batch = client.batches.retrieve(batch.id)

if batch.output_file_id:
    print(client.files.content(batch.output_file_id).text)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";
import fs from "node:fs";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "not-needed" });

const up = await client.files.create({
  file: fs.createReadStream("requests.jsonl"),
  purpose: "batch",
});
let batch = await client.batches.create({
  input_file_id: up.id,
  endpoint: "/v1/chat/completions",
  completion_window: "24h",
});
while (["validating", "in_progress", "finalizing", "cancelling"].includes(batch.status)) {
  await new Promise((r) => setTimeout(r, 2000));
  batch = await client.batches.retrieve(batch.id);
}
```

</Tab>
</Tabs>

## 錯誤

OpenAI 格式：`{"error": {"message", "type", "param", "code"}}`。

| 狀態碼 | Code | 情況 |
| --- | --- | --- |
| `400` | `missing_required_parameter` | 缺少 `input_file_id`。 |
| `400` | `invalid_value` | `endpoint` 不合法、`completion_window` 不是 `24h`、`metadata` 不合法、輸入檔的 purpose 不是 `batch`、輸入檔不存在。 |
| `404` | `batch_not_found` | 批次 id 不存在。 |
| `409` | `invalid_state` | 取消已結束的批次。 |

## Anthropic 訊息批次

Anthropic Message Batches 路由（`POST /v1/messages/batches` 等）共用同一個工作程序、儲存區與 24 小時期限，說明在 [Messages](/docs/api/messages) 頁面。差異在於：請求直接內嵌在 `requests` 陣列（含 `custom_id` 與 `params`），每批最多 100,000 筆，結果以 JSONL 從 `GET /v1/messages/batches/{batch_id}/results` 串流取得，已結束的批次可用 `DELETE /v1/messages/batches/{batch_id}` 刪除。

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 建立、取得、列出、取消 | <Support status="supported">支援</Support> |
| 端點 `/v1/chat/completions`、`/v1/completions`、`/v1/embeddings`、`/v1/responses` | <Support status="supported">支援</Support> |
| 重新啟動後繼續 | <Support status="supported">未完成的批次會接續執行</Support> |
| 行與行之間平行執行 | <Support status="unsupported">一次執行一行</Support> |
| 串流的行 | <Support status="unsupported">建立時即拒絕</Support> |
| `24h` 以外的完成期限 | <Support status="unsupported">被拒絕</Support> |
| 其他端點（例如 `/v1/images/generations`） | <Support status="unsupported">被拒絕</Support> |
| 刪除 OpenAI 批次 | <Support status="unsupported">沒有刪除路由</Support> |

## 相關頁面

- [檔案](/docs/api/files)：上傳輸入與下載輸出。
- [Messages](/docs/api/messages)：Anthropic 批次路由。
- [Chat Completions](/docs/api/chat-completions)、[Responses](/docs/api/responses) 與 [Embeddings](/docs/api/embeddings)：請求本文格式。


---

<!-- api/chat-completions -->
---
title: Chat completions
description: OpenAI Chat Completions 端點，支援 tools、結構化輸出、logprobs、推理、圖片／音訊／影片輸入與串流，並附上舊版文字補全端點。
---

`POST /v1/chat/completions` 遵循 OpenAI Chat Completions 格式，因此官方 `openai` SDK、LangChain、LiteLLM 與多數 agent 工具只要改 base URL 就能使用。純文字的 `mlx-lm` 模型與視覺語言的 `mlx-vlm` 模型由同一個路由提供；請求中只要含有圖片、音訊或影片區塊，就會被導向 VLM。`POST /v1/completions` 是舊版的「給提示詞、回傳文字」端點，說明放在本頁最後。

<Endpoint method="POST" path="/v1/chat/completions" />
<Endpoint method="POST" path="/v1/completions" />

<Callout type="info">
只有在設定 `YUNSHU_AUTH_TOKEN` 時才會強制驗證，請見 [API 總覽](/docs/api/overview)。單模型模式下 `model` 的值僅供參考；多模型模式下它用來選擇模型。
</Callout>

## 請求

未知的頂層欄位會被忽略，所以用戶端可以繼續送出 Yunshu 用不到的 OpenAI 欄位（`service_tier`、`modalities`、`prediction`、`web_search_options`、`safety_identifier` 等）。任何選用欄位若為 JSON `null`，視為「未設定」並套用預設值。負的 `top_k`（vLLM 表示「停用」的寫法）會變成 `0`。

### 核心欄位

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | 模型 id。單模型模式下僅供參考。 | 支援 |
| `messages` | array | 是 | 對話內容。至少要有一則內容不為空的 `user` 訊息。見[訊息](#訊息)。 | 支援 |
| `stream` | boolean | 否 | 使用 Server-Sent Events。預設 `false`。 | 支援 |
| `stream_options` | object | 否 | 僅能搭配 `stream: true`。`include_usage` 會在最後加一個 usage 區塊；`continuous_usage_stats`（vLLM 擴充）會在每個區塊都附上累計的 `usage`。 | 支援 |
| `max_tokens` | integer | 否 | 生成長度上限，`0` 至 `1048576`。省略時為模型的輸出上限（262144，Qwen3.8 模型卡的思考模式數值；OpenAI 規格為「直到模型上限」），只能由營運者上限 `YUNSHU_DEFAULT_MAX_TOKENS` 調低。上下文視窗仍會限縮；`x_yunshu.budget` 回報實際值與來源（`max_tokens_source`：`request`、`model_limit`、`operator_cap`）。 | 支援 |
| `max_completion_tokens` | integer | 否 | OpenAI 較新的名稱。兩者同時設定時以它為準。 | 支援 |
| `n` | integer | 否 | 回傳的選項數，`1` 至 `128`。搭配 `stream: true` 時，每個區塊都帶有所屬選項的 `index`；各選項依序串流（文字路徑一次處理一個請求，視覺語言模型則並行），`seed` 與非串流相同，會衍生出每個選項的種子（`seed + index`）。最後一個 usage 區塊是提示詞計一次、所有補全加總。 | 支援 |
| `stop` | string 或 array | 否 | 最多 16 個停止序列。空字串會被丟棄。 | 支援 |
| `user` | string | 否 | 只會連同請求 ID 寫入日誌，沒有其他作用。 | 接受但忽略 |
| `store` | boolean | 否 | 保留完成的 completion 供日後查詢。見[儲存的 completions](/docs/api/stored-completions)。 | 支援 |
| `metadata` | object | 否 | 最多 16 組字串鍵值；`store` 為 true 時會連同 completion 一起儲存。 | 支援 |
| `keep_alive` | string 或 number | 否 | Ollama 風格的常駐提示（`"5m"`、`300`、`-1`、`0`）。在多模型模式下生效。 | 擴充 |
| `timeout` | number | 否 | 秒數，`1` 至 `600`。時間到時結束生成，回傳部分結果與 `finish_reason: "length"`。 | 擴充 |

### 取樣

| 參數 | 型別 | 預設 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `temperature` | number | `0.7` | `0` 至 `2`。注意預設值與 OpenAI 的 `1.0` 不同。 | 支援 |
| `top_p` | number | `1.0` | `0` 至 `1`。 | 支援 |
| `top_k` | integer | `0` | `0` 表示停用。 | 支援 |
| `min_p` | number | `0.0` | `0` 至 `1`。 | 支援 |
| `repetition_penalty` | number | `1.0` | `0` 至 `2`。非 OpenAI 欄位：沿用 mlx-lm，只看最近 20 個提示詞與生成的 token。 | 支援 |
| `frequency_penalty` | number | `0.0` | `-2` 至 `2`。與 OpenAI 相同：計入每個已生成的 token（不含提示詞）。 | 支援 |
| `presence_penalty` | number | `0.0` | `-2` 至 `2`。與 OpenAI 相同：token 一旦生成過就套用。 | 支援 |
| `logit_bias` | object | 無 | token id 對偏移量的對照，每個值介於 `-100` 至 `100`。鍵為字串形式的 token id。 | 支援 |
| `seed` | integer | 無 | 64 位元有號整數。讓取樣可重現。 | 支援 |
| `top_n_sigma` | number | `0.0` | `0` 至 `10`。只保留 logit 落在最大值 n 個標準差內的 token；`0` 為關閉。 | 擴充 |
| `xtc_probability`、`xtc_threshold` | number | `0.0` | XTC 取樣器。機率 `0` 至 `1`，門檻 `0` 至 `0.5`。 | 擴充 |
| `min_tokens` | integer | `0` | 在累積到這麼多 token 之前，遮蔽結束符號。 | 擴充 |
| `ignore_eos` | boolean | `false` | 越過結束符號繼續生成，直到 `max_tokens`。 | 擴充 |
| `suppress_tokens` | array of integer | 無 | 永遠不會被產生的 token id。 | 擴充 |
| `stop_token_ids` | array of integer | 無 | 最多 16 個會結束生成的 token id。 | 擴充 |
| `spec_decode` | boolean | `false` | 要求此請求使用推測解碼。只有在模型與路徑具備 drafter 時才生效，否則忽略。 | 部分支援 |
| `priority` | integer | `0` | `0` 至 `100`。以請求優先順序的形式轉交給引擎。 | 部分支援 |
| `lora_adapter` | string | 無 | 此請求使用的 LoRA adapter id。僅限文字模型；VLM 會回應 `400`。 | 部分支援 |
| `logits_processors` | array | 無 | 自訂 logits processor。VLM 會回應 `400`。 | 部分支援 |

### 訊息

每則訊息的 `role` 為 `system`、`developer`、`user`、`assistant`、`tool` 或 `function`，其他角色都是 `400`。

| 欄位 | 型別 | 說明 | 狀態 |
| --- | --- | --- | --- |
| `content` | string、array 或 null | 文字，或內容區塊的陣列。`system`、`developer` 與 `user` 訊息不接受僅含空白的文字與空陣列。 | 支援 |
| `tool_calls` | array | 用於 `assistant` 訊息：模型先前發出的呼叫，含 `id`、`type` 與 `function.name` / `function.arguments`。 | 支援 |
| `tool_call_id` | string | `tool` 訊息必填。 | 支援 |
| `name` | string | `tool` 訊息上的函式名稱。 | 支援 |
| `reasoning_content` 或 `reasoning` | string | `assistant` 訊息中先前的推理內容，會交給聊天模板。 | 擴充 |

內容區塊：

| 區塊 `type` | 結構 | 說明 |
| --- | --- | --- |
| `text` | `{"type": "text", "text": "..."}` | 可帶 `prompt_cache_breakpoint` 物件，見[提示詞快取](/docs/guides/prompt-caching)。 |
| `image_url` | `{"type": "image_url", "image_url": {"url": "..."}}` | 支援 `http`、`https` 與 `data:` URL。`file://` URL 以及指向 loopback、私有或 link-local 主機的 URL 會被以 `400` 拒絕。`detail` 會被接受但僅供參考，像素預算由模型的 processor 決定。`image` 與 `image_data` 區塊會被正規化成這個結構。 |
| `input_audio` | `{"type": "input_audio", "input_audio": {"data": "<base64>", "format": "wav"}}` | 導向接受音訊輸入的模型。 |
| `audio_url` | `{"type": "audio_url", "audio_url": {"url": "..."}}` | 同上。 |
| `video_url`、`video_file` | OpenAI 風格的影片區塊 | 導向接受影片輸入的模型。 |

模型若不接受某個區塊的模態，會回應 `400` 並指出該區塊，例如 `messages.content[type=image_url]: this model accepts text input, not image`。帶有媒體的請求若指向不是視覺語言模型的模型，同樣回應 `400`。

### Tools

| 參數 | 型別 | 說明 | 狀態 |
| --- | --- | --- | --- |
| `tools` | array | 函式工具：`{"type": "function", "function": {"name", "description", "parameters"}}`。 | 支援 |
| `tool_choice` | string 或 object | `auto`、`none`、`required`，或 `{"type": "function", "function": {"name": "..."}}`。`required` 與指定函式都需要非空的 `tools`，且名稱必須在 `tools` 內。`allowed_tools` 形式會被摺疊成 `tools` 加上模式。 | 支援 |
| `parallel_tool_calls` | boolean | 預設 `true`。設為 `false` 時最多回傳一個呼叫。 | 支援 |

模型的聊天模板若原生支援 tools，Yunshu 會把 tools 交給模板；否則會注入一段工具提示並從輸出解析呼叫。模型卡上的 `yunshu.contract.tools.mode` 會告訴你是哪一種（`template` 或 `prompt`）。呼叫會出現在 `message.tool_calls`，並帶 `finish_reason: "tool_calls"`。生成之後，伺服器會強制執行 `tool_choice: "none"`（不回傳任何呼叫）、指定函式（丟棄其他函式的呼叫）以及 `parallel_tool_calls: false`（只保留第一個呼叫）。模型沒有發出的呼叫不會被憑空捏造。字串型態的引數值會依你 `parameters` 結構描述中的型別轉換。在 VLM 上，tools 不能與 `response_format` 或 `grammar` 並用，否則回應 `400`。

### 結構化輸出

| 參數 | 說明 | 狀態 |
| --- | --- | --- |
| `response_format` | `{"type": "text"}`、`{"type": "json_object"}` 或 `{"type": "json_schema", "json_schema": {"name", "schema", "strict"}}`。`json_schema` 必須提供 `json_schema` 物件。`strict: true` 時，物件結構會加上 `additionalProperties: false`。其他 `type` 一律 `400`。 | 支援 |
| `grammar` | 原生約束：`{"type": "json", "schema": {...}}`、`{"type": "regex", "pattern": "..."}`、`{"type": "choice", "choices": [...]}` 或 `{"type": "cfg", "grammar": "..."}`。優先於 `response_format`。 | 擴充 |
| `guided_json`、`guided_regex`、`guided_choice`、`guided_grammar` | 同樣約束的 vLLM 寫法。`guided_regex` 上限 2048 字元，`guided_grammar` 上限 32768。 | 擴充 |
| `structured_outputs` | vLLM 物件，恰好帶 `json`、`regex`、`choice`、`grammar`、`json_object` 其中一個。不支援 `structural_tag`。 | 擴充 |

約束式解碼會遮蔽 logits，因此從第一個 token 起就能產生符合結構的輸出。引擎無法編譯的 schema 或 pattern 會回應 `400`。見[結構化輸出](/docs/guides/structured-output)。

### 推理

| 參數 | 說明 | 狀態 |
| --- | --- | --- |
| `enable_thinking` | 開啟或關閉模型的思考模式。也會讀取 `chat_template_kwargs.enable_thinking`。 | 支援 |
| `reasoning_effort` | 推理強度。也會讀取 `chat_template_kwargs.reasoning_effort`。超出模板自身清單的值會被對應（在使用 `xhigh` 的模板上，`high` 會變成 `xhigh`）。`none` 與 `minimal` 會關閉思考（等同 `enable_thinking: false`）。其他值會原樣傳給模型的聊天範本，作為範本自己的 `reasoning_effort` 變數（Qwen3.8：`low`、`medium`、`xhigh`）；範本沒列出的值會對應到它自己的層級（`high` 與 `max` 變成 `xhigh`）。它不會被換算成思考 token 上限；要設上限請用 `thinking_budget`。範本沒有這個變數、或模型沒有推理模式時，會被忽略。 | 支援 |
| `thinking_budget` | 思考 token 上限，`1` 至 `262144`（模型的思考上限）。 | 擴充 |
| `chat_template_kwargs` | 傳給聊天模板的額外變數。 | 支援 |

推理文字會放在 `message.reasoning_content`，與 `content` 分開。推理 token 也算在 `completion_tokens` 內，`usage.completion_tokens_details.reasoning_tokens` 則說明其中有多少。

### Logprobs

| 參數 | 型別 | 說明 | 狀態 |
| --- | --- | --- | --- |
| `logprobs` | boolean | 在 `choices[].logprobs.content` 回傳每個 token 的對數機率。 | 支援 |
| `top_logprobs` | integer | 每個 token 的候選數，`0` 至 `20`。需要 `logprobs: true`。 | 支援 |
| `prompt_logprobs` | integer | 提示詞各 token 的 logprobs，回傳在 `choices[].prompt_logprobs`。 | 擴充 |

### 快取

| 參數 | 說明 | 狀態 |
| --- | --- | --- |
| `prompt_cache_key`、`prompt_cache_retention`、`prompt_cache_options` | OpenAI 的提示詞快取提示。在視覺語言路徑上使用；純文字模型會接受但忽略，因為它們的前綴快取是自動的。 | 部分支援 |

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-local" \
  -d '{
    "model": "local",
    "messages": [
      {"role": "system", "content": "You are concise."},
      {"role": "user", "content": "Name three prime numbers."}
    ],
    "max_tokens": 64
  }'
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

resp = client.chat.completions.create(
    model="local",
    messages=[
        {"role": "system", "content": "You are concise."},
        {"role": "user", "content": "Name three prime numbers."},
    ],
    max_tokens=64,
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "sk-local" });

const resp = await client.chat.completions.create({
  model: "local",
  messages: [
    { role: "system", content: "You are concise." },
    { role: "user", content: "Name three prime numbers." },
  ],
  max_tokens: 64,
});
console.log(resp.choices[0].message.content);
```

</Tab>
</Tabs>

### 串流

<Tabs items={["curl", "Python"]}>
<Tab value="curl">

```bash
curl -N http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "local",
    "stream": true,
    "stream_options": {"include_usage": true},
    "messages": [{"role": "user", "content": "Write a haiku about autumn."}]
  }'
```

</Tab>
<Tab value="Python">

```python
stream = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Write a haiku about autumn."}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices:
        delta = chunk.choices[0].delta
        print(delta.content or "", end="", flush=True)
    elif chunk.usage:
        print("\n", chunk.usage.total_tokens, "tokens")
```

</Tab>
</Tabs>

### 工具呼叫

```python
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "What is the weather in Taipei?"}]
first = client.chat.completions.create(model="local", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)

messages.append(first.choices[0].message.model_dump(exclude_none=True))
messages.append({"role": "tool", "tool_call_id": call.id, "content": '{"temp_c": 24}'})
final = client.chat.completions.create(model="local", messages=messages, tools=tools)
print(final.choices[0].message.content)
```

### JSON schema 輸出

```python
resp = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Extract: Ada Lovelace, born 1815."}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {"name": {"type": "string"}, "born": {"type": "integer"}},
                "required": ["name", "born"],
            },
        },
    },
)
print(resp.choices[0].message.content)
```

### 圖片輸入

請使用視覺語言模型，例如 Qwen3.5 VLM 檢查點。

```python
resp = client.chat.completions.create(
    model="local",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What is in this picture?"},
            {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo..."}},
        ],
    }],
)
```

### 推理

```python
resp = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Is 391 prime?"}],
    extra_body={"enable_thinking": True},
)
msg = resp.choices[0].message
print(getattr(msg, "reasoning_content", None))
print(msg.content)
print(resp.usage.completion_tokens_details.reasoning_tokens)
```

## 回應

```json
{
  "id": "chatcmpl-9f2c4e1ab07d4c3e8a51b2c6",
  "object": "chat.completion",
  "created": 1760000000,
  "model": "local",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "2, 3 and 5.",
        "reasoning_content": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 9,
    "total_tokens": 33,
    "completion_tokens_details": { "reasoning_tokens": 0 },
    "prompt_tokens_details": { "cached_tokens": 0 }
  },
  "x_yunshu": { "request_id": "req_0f3a9c2d4b7e41a6b8c1d2e3", "ttft_ms": 84.2, "decode_tps": 61.3 }
}
```

- `reasoning_content` 只在模型產生了推理時才會出現。模型呼叫工具時，`tool_calls` 會取代或伴隨 `content`；每個呼叫都有 `id`（`call_...`）、`type: "function"` 與 `function.name` / `function.arguments`（JSON 字串）。
- `finish_reason` 為 `stop`、`length` 或 `tool_calls`。內部原因會被對應：取消或錯誤對應為 `stop`，逾時或記憶體上限對應為 `length`。
- `usage.completion_tokens` 已經包含推理 token；`reasoning_tokens` 與 `cached_tokens` 是各自總數內的細項，不會另外加總。`cached_tokens` 是由前綴快取提供的提示詞前綴長度。
- `choices[].logprobs.content[]` 的每一項為 `{token, logprob, bytes, top_logprobs: [{token, logprob, bytes}]}`。
- `x_yunshu` 是 [API 總覽](/docs/api/overview)中說明的 Yunshu 擴充。當回傳的工具呼叫對應到已設定的 MCP 用戶端的工具，並由閘道代為執行時，會出現 `mcp_tool_results`。
- `max_tokens` 與 `max_completion_tokens` 小於 1 會回 `400`，與 OpenAI 相同（只有 `/v1/completions` 接受 0，用於 echo 評分）。要計算提示詞長度，請把相同的 `messages` POST 到 `/tokenize`：`count` 就是生成實際會跑的提示詞長度。
- 若 VLM 的結構化輸出結果仍未通過驗證，會回應 `422` 並附上 `x_yunshu.validation`。

## 串流

設定 `stream: true` 後，回應為 `text/event-stream`。每個事件是 `data: <json>` 加一個空行。

1. 第一個區塊帶 `delta: {"role": "assistant", "content": null}`。
2. 內容區塊帶 `delta.content`。推理會先以 `delta.reasoning_content` 送出，接著才是回答。
3. 工具呼叫以 `delta.tool_calls` 串流：先是一個帶 `index`、`id`、`type` 與 `function.name` 的區塊，再來是同一個 `index` 的 `function.arguments` 片段。
4. 帶有 `finish_reason` 與空 delta 的區塊結束該選項。
5. 有 `stream_options.include_usage` 時，之後還有一個 `choices: []` 的區塊，內含 `usage` 物件與 `x_yunshu` 統計。
6. `data: [DONE]` 結束串流。

區塊的 `object` 為 `chat.completion.chunk`。區塊之間伺服器可能送出 SSE 註解行（`: keep-alive`，以及長提示詞 prefill 期間的 `: yunshu-progress {...}`），SSE 解析器會忽略註解。如果串流開始後生成失敗，串流會送出單一的 `data: {"error": {...}}` 事件，然後是 `[DONE]`。

## 錯誤

| 狀態碼 | 時機 |
| --- | --- |
| 400 | 結構或數值驗證失敗（`code: validation_error`，`param` 指出欄位）、模型不支援的功能、無效的圖片 URL、提示詞超出上下文視窗、格式錯誤的 `response_format` 或 `grammar`。 |
| 401 | 已設定 token，但缺少或不正確。 |
| 404 | 多模型模式下未知的模型。 |
| 429 | 佇列已滿，帶 `Retry-After`。 |
| 500 | 引擎失敗（`server_error`）。 |
| 503 | 沒有載入任何模型、模型仍在載入，或有其他請求執行時記憶體吃緊。 |
| 504 | 超過 `X-Yunshu-Deadline-Ms` 的期限。 |
| 507 | GPU 記憶體不足（`type: memory_error`）。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 文字、system、developer、tool 訊息 | <Support status="supported">支援</Support> |
| 圖片輸入 | <Support status="supported">視覺語言模型</Support> |
| 音訊與影片輸入區塊 | <Support status="partial">接受它們的模型</Support> |
| 串流、`stream_options.include_usage` | <Support status="supported">支援</Support> |
| `n` 大於 1 | <Support status="supported">串流與非串流皆可，區塊帶有 `index`</Support> |
| Function tools、`tool_choice`、`parallel_tool_calls` | <Support status="supported">支援</Support> |
| `response_format` 的 `json_object` 與 `json_schema` | <Support status="supported">約束式解碼</Support> |
| `logprobs`、`top_logprobs` | <Support status="supported">最多 20 個候選</Support> |
| `reasoning_effort`、`enable_thinking`、`reasoning_content` | <Support status="supported">具推理模式的模型</Support> |
| `store`、`metadata` | <Support status="supported">見儲存的 completions</Support> |
| `user`、`service_tier`、`modalities`、`prediction` | <Support status="unsupported">接受但忽略</Support> |
| 音訊輸出（`audio` 請求欄位） | <Support status="unsupported">尚未支援；請使用音訊路由</Support> |
| VLM 上的 LoRA 與自訂 logits processor | <Support status="unsupported">400</Support> |

## 舊版文字補全

`POST /v1/completions` 接受原始提示詞並回傳文字，不套用聊天模板。它支援與 chat 路由相同的取樣參數，以及 `stream`、`stream_options`、`stop`、`seed`、`logit_bias`、`response_format`、`grammar` / `guided_*` 約束、`logprobs`、`n`、`echo` 與 `best_of`。這裡沒有推理與工具相關參數。

| 參數 | 型別 | 說明 | 狀態 |
| --- | --- | --- | --- |
| `model` | string | 模型 id。 | 支援 |
| `prompt` | string、字串陣列、token id 陣列，或 token id 陣列的陣列 | 必填。字串陣列或 token id 陣列的陣列會依序為每個提示詞產生選項。有多個提示詞時不可使用 `stream: true`。 | 支援 |
| `max_tokens` | integer | 預設 `16`（OpenAI completions 規格），上限 `1048576`。也接受 `max_completion_tokens`。 | 支援 |
| `echo` | boolean | 把提示詞放在回傳文字之前。搭配 `logprobs` 時，提示詞 token 也會有 logprobs（限單一字串提示詞）。 | 支援 |
| `logprobs` | integer | `0` 至 `5`。回應使用舊版的 `tokens`、`token_logprobs`、`top_logprobs`、`text_offset` 陣列。 | 支援 |
| `best_of` | integer | 為每個提示詞產生這麼多候選，回傳平均 logprob 最佳的 `n` 個。必須不小於 `n`；不可搭配串流或多個提示詞。所有候選都計入 `usage`。 | 支援 |
| `n` | integer | `1` 至 `128`。搭配 `stream: true` 時，區塊帶有 `choices[].index`，與 chat 路由相同。 | 支援 |
| `suffix` | string | 會被接受。這裡沒有 fill-in-the-middle 模板，所以不會被使用，也不會附加到文字後面。 | 接受但忽略 |
| `stop`、`seed`、`temperature`、`top_p`、`top_k`、`min_p`、各種 penalty、`logit_bias`、`stream_options` | | 與 chat 路由相同。 | 支援 |

```bash
curl http://localhost:8000/v1/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "local", "prompt": "The capital of France is", "max_tokens": 8, "temperature": 0}'
```

```json
{
  "id": "cmpl-3b7d1c0e5a9f4d2e8c61a0b7",
  "object": "text_completion",
  "created": 1760000000,
  "model": "local",
  "choices": [{ "index": 0, "text": " Paris.", "finish_reason": "stop" }],
  "usage": { "prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8 }
}
```

串流使用 `object: "text_completion"` 的區塊與 `choices[].text`，之後是選用的 usage 區塊與 `[DONE]`。錯誤格式與 chat 路由相同。這裡也會強制執行模型的能力契約（對不生成文字的模型使用 `response_format`、`grammar` 與 `logprobs` 會回應 `400`）。

## 相關頁面

- [儲存的 completions](/docs/api/stored-completions)
- [Responses](/docs/api/responses)
- [結構化輸出](/docs/guides/structured-output)
- [提示詞快取](/docs/guides/prompt-caching)
- [模型與能力契約](/docs/api/models)
- [擴充功能](/docs/api/extensions)


---

<!-- api/decisions -->
---
title: Decisions
description: 由決策頭模型在單次前向傳遞中回答型別化問題（是非、單選、有序評分），回傳機率而不產生任何文字。
---

決策模型針對輸入回答結構化問題，而且不寫出任何文字。你送出一段輸入與一組型別化的問題，模型只讀一次輸入與問題結構，就為每個答案回傳機率。這和聊天補全以及 JSON schema 約束解碼都不同：因為沒有生成，輸出 token 永遠是零，延遲就是一次 prefill。

適合用在路由、分類、護欄檢查與評分，也就是你想要校準過的機率，而不是取樣出來的答案。

<Endpoint method="POST" path="/v1/decisions" />

`POST /v1/systemone` 是同一個引擎的另一種傳輸格式，說明在[擴充](/docs/api/extensions)。

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。此路由無狀態，也不支援串流。
</Callout>

## 決策模型

此路由需要決策 checkpoint，也就是骨幹模型加上訓練好的決策頭。Yunshu 載入 MLX 格式的 Cloudflare Clef 聯合 schema 頭，包含 Clef-flash。checkpoint 會依檔案內容自動偵測；載入後它會被歸類為決策模型，而不是聊天模型。

```bash
yunshu pull abenzerps/Clef-MLX
yunshu serve -m abenzerps/Clef-MLX
```

其他決策頭系列尚未支援，頭部不明的 checkpoint 會載入失敗。對聊天模型要求決策會回傳 `400`。圖片需要支援視覺的 checkpoint（`vision` extra）；在純文字 checkpoint 上送圖片會回傳 `400`。

## 請求

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | 決策模型 id（單模型模式：所服務的模型）。 | 支援 |
| `input` | string 或 array | 是 | 文字，或使用者訊息，見下文。 | 支援 |
| `questions` | array | 是 | 1 到 128 個問題。答案會依相同順序回傳。 | 支援 |
| `safety_identifier` | string | 否 | 最多 64 個字元。 | 接受但忽略 |

未知的頂層欄位會被忽略，所以 SDK 的 `extra_body` 不會讓呼叫失敗。問題物件則是嚴格的：問題或訊息內出現未知欄位會以 `400` 拒絕。

### 輸入

可以是字串，或訊息陣列 `{"role": "user", "content": ...}`，其中 `content` 是字串或 part 清單：

| Part | 欄位 | 備註 |
| --- | --- | --- |
| `input_text` | `text` | 多段文字以換行串接。 |
| `input_image` | `image_url`，選填 `detail` | 必須是內嵌的 `data:image/...;base64,...` URL。外部 URL 與檔案 id 會被拒絕。最多 128 張圖片。 |

文字最多 1,000,000 個字元，且輸入加上問題結構的總長度必須在 16,384 個 token 以內。超過會被拒絕，不會被截斷。只允許 `user` 角色。

### 問題

| `type` | 欄位 | 答案 |
| --- | --- | --- |
| `predicate` | `instructions`，選填 `name` | 是非機率。 |
| `choice` | `instructions`、`choices`（2 到 64 個 `{"value", "description"?}`），選填 `name` | 最可能的 `value`、其信心值，以及所有選項的機率。`value` 為字串或布林值，且不可重複（布林 `true` 與字串 `"true"` 會衝突）。 |
| `score` | `instructions`、`levels`（2 到 64 個 `{"label", "description"?}`），選填 `name` | 期望的從零開始等級索引、信心值與各等級機率。決策頭讀取的是等級的 `description`（沒有時用 `label`），且 label 不可重複。 |

若有指定 `name`，必須唯一。

## 回應

```json
{
  "answers": [
    {
      "type": "choice",
      "name": "route",
      "choice": "support",
      "confidence": 0.93,
      "probabilities": [
        { "value": "support", "probability": 0.93 },
        { "value": "sales", "probability": 0.07 }
      ]
    },
    { "type": "predicate", "name": "urgent", "probability": 0.81 },
    {
      "type": "score",
      "name": "sentiment",
      "score": 0.22,
      "confidence": 0.78,
      "probabilities": [
        { "label": "negative", "value": 0, "probability": 0.78 },
        { "label": "positive", "value": 1, "probability": 0.22 }
      ]
    }
  ],
  "model": "abenzerps/Clef-MLX",
  "usage": {
    "input_tokens": 142,
    "input_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 0 },
    "output_tokens": 0,
    "output_tokens_details": { "reasoning_tokens": 0 },
    "total_tokens": 142
  }
}
```

如果決策頭對某個問題回傳非有限值，該答案會是 `{"type": "refusal", "name": ...}`，不會編造機率。`usage.input_tokens` 是 prefill 長度，`cached_tokens` 一律為 0。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/decisions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "abenzerps/Clef-MLX",
    "input": "The customer asks for a refund after a broken delivery.",
    "questions": [
      {"type": "choice", "name": "route", "instructions": "Choose the support team.",
       "choices": [{"value": "support"}, {"value": "sales"}]},
      {"type": "predicate", "name": "urgent", "instructions": "Is this urgent?"}
    ]
  }'
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

decision = client.decisions.create(
    model="abenzerps/Clef-MLX",
    input="The customer asks for a refund after a broken delivery.",
    questions=[
        {
            "type": "choice",
            "name": "route",
            "instructions": "Choose the support team.",
            "choices": [{"value": "support"}, {"value": "sales"}],
        }
    ],
)
print(decision.answers)
```

`decisions` 資源需要較新的 `openai` SDK。若 SDK 較舊，請用 `httpx` 或 `requests` 送出相同的 JSON 本文。

</Tab>
<Tab value="JavaScript">

```ts
const res = await fetch("http://localhost:8000/v1/decisions", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "abenzerps/Clef-MLX",
    input: "The customer asks for a refund after a broken delivery.",
    questions: [
      {
        type: "choice",
        name: "route",
        instructions: "Choose the support team.",
        choices: [{ value: "support" }, { value: "sales" }],
      },
    ],
  }),
});
console.log((await res.json()).answers);
```

</Tab>
</Tabs>

## 錯誤

錯誤使用 OpenAI 的格式 `{"error": {"message", "type", "param", "code"}}`。

| 狀態碼 | 情況 |
| --- | --- |
| `400` | JSON 或結構不合法、輸入為空、名稱或選項重複、choices 或 levels 少於 2 個、外部圖片 URL、在純文字 checkpoint 上送圖片、該模型不是決策模型、輸入超過 16,384 個 token。 |
| `404` | 找不到模型或模型未載入。 |
| `507` | GPU 記憶體不足。 |
| `500` | 決策執行失敗。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| predicate、choice、score 問題 | <Support status="supported">支援</Support> |
| 圖片輸入（內嵌 base64） | <Support status="partial">僅支援視覺的 checkpoint</Support> |
| MLX 格式的 Cloudflare Clef checkpoint | <Support status="supported">支援</Support> |
| 其他決策頭系列 | <Support status="unsupported">載入失敗</Support> |
| 串流、提示快取、儲存狀態 | <Support status="unsupported">無狀態，單次前向傳遞</Support> |
| `safety_identifier` | <Support status="unsupported">接受但忽略</Support> |

## 相關頁面

- [擴充](/docs/api/extensions)：`POST /v1/systemone` 上的 System One 傳輸格式。
- [結構化輸出](/docs/guides/structured-output)：需要依 JSON schema 生成文字時的做法。
- [模型](/docs/getting-started/models)：載入 checkpoint。


---

<!-- api/embeddings -->
---
title: Embeddings
description: OpenAI embeddings 端點，支援文字與多模態 embedding 模型，另有回傳原始池化向量的 vLLM 風格 pooling 端點。
---

`POST /v1/embeddings` 遵循 OpenAI embeddings 格式：送入文字（或 token id），每個輸入得到一個向量。搭配多模態 embedding 檢查點時，同一個路由也能嵌入圖片、音訊與影片。`POST /v1/pooling` 是 vLLM 風格的搭配端點，回傳未正規化的池化隱藏狀態。

Embedding 模型與聊天模型是不同的檢查點。多模型模式下在 `model` 填入 embedder 的名稱；單模型模式下，載入的模型本身就必須是 embedder。`GET /v1/models` 會顯示 `yunshu.kind: "embedding"`，向量維度則在 `yunshu.embeddings` 底下。

<Endpoint method="POST" path="/v1/embeddings" />
<Endpoint method="POST" path="/v1/pooling" />

<Callout type="info">
只有在設定 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。見 [API 總覽](/docs/api/overview)。
</Callout>

## 請求

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | Embedding 模型 id。 | 支援 |
| `input` | string、字串陣列、整數陣列、整數陣列的陣列，或物件陣列 | 是（或用 `messages`） | 要嵌入的文字。字串陣列會逐一嵌入。整數陣列是以 token id 表示的一段文字；整數陣列的陣列則是多段文字。物件（`{"text": ..., "image": ...}`）用於多模態 embedder。 | 支援 |
| `messages` | array | 否 | vLLM 風格的聊天訊息，內含文字、`image_url`、`input_audio`、`audio_url` 或 `video` 區塊，會被轉成單一個多模態項目。請用它取代 `input`，不可同時使用。 | 擴充 |
| `encoding_format` | string | 否 | `float`（預設）或 `base64`（little-endian float32 打包後再做 base64）。 | 支援 |
| `dimensions` | integer | 否 | `1` 至 `8192`。把向量截成前面這麼多個值並重新正規化（Matryoshka 風格）。要求的維度超過模型原生維度會回應 `400`。 | 支援 |
| `pooling_type` | string | 否 | `MEAN`、`CLS` 或 `LAST`（不分大小寫）。覆寫模型自身的池化方式。適用於可池化的文字模型；結果會做 L2 正規化。 | 擴充 |
| `instruction` | string | 否 | 文字模型：以 `instruction`、換行、再接文字的形式加在每個輸入前面。多模態模型：作為 embedder 的指示傳入。 | 擴充 |
| `task` | string | 否 | 僅限多模態 embedder：embedder 的任務名稱。未知的任務會回應 `400`。 | 擴充 |
| `user` | string | 否 | 為了相容而接受。 | 接受但忽略 |

限制：每個請求最多 2048 個輸入，每段文字最多 65536 字元。清單必須同質（全是字串、全是 token id，或全是 token id 清單）。空字串與僅含空白的輸入會被拒絕。

除非模型另有回傳，向量會做 L2 正規化；非有限值會被換成 `0`。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-local" \
  -d '{
    "model": "Qwen/Qwen3-Embedding-0.6B",
    "input": ["How do I reset my password?", "Password reset steps"],
    "dimensions": 256
  }'
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

resp = client.embeddings.create(
    model="Qwen/Qwen3-Embedding-0.6B",
    input=["How do I reset my password?", "Password reset steps"],
    dimensions=256,
)
a, b = (d.embedding for d in resp.data)
print(len(a), sum(x * y for x, y in zip(a, b)))  # cosine, since vectors are unit length
print(resp.usage.total_tokens)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "sk-local" });

const resp = await client.embeddings.create({
  model: "Qwen/Qwen3-Embedding-0.6B",
  input: ["How do I reset my password?", "Password reset steps"],
  dimensions: 256,
});
console.log(resp.data[0].embedding.length);
```

</Tab>
</Tabs>

### 多模態輸入

使用多模態 embedding 模型時，每個 `input` 項目是字串，或是帶有 `text`、`image`、`audio`、`video` 鍵的物件（至少要有一個）。圖片可以是 URL 或 data URI。

```bash
curl http://localhost:8000/v1/embeddings \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen3-VL-Embedding",
    "input": [
      {"text": "a red bicycle"},
      {"image": "data:image/png;base64,iVBORw0KGgo..."},
      {"text": "a red bicycle", "image": "https://example.com/bike.jpg"}
    ]
  }'
```

聊天訊息的寫法則是把媒體依序放進同一個項目：

```json
{
  "model": "Qwen3-VL-Embedding",
  "messages": [
    {"role": "user", "content": [
      {"type": "text", "text": "a red bicycle"},
      {"type": "image_url", "image_url": {"url": "https://example.com/bike.jpg"}}
    ]}
  ]
}
```

純文字的 embedding 模型收到物件項目與 `messages` 時，會回應 `400`。

## 回應

```json
{
  "object": "list",
  "data": [
    { "object": "embedding", "index": 0, "embedding": [0.0123, -0.0456, 0.0789] },
    { "object": "embedding", "index": 1, "embedding": [0.0101, -0.0399, 0.0812] }
  ],
  "model": "Qwen/Qwen3-Embedding-0.6B",
  "usage": { "prompt_tokens": 11, "total_tokens": 11 }
}
```

上面的向量已縮短；實際向量長度是模型的完整維度（或 `dimensions`）。設定 `encoding_format: "base64"` 時，`embedding` 是 base64 字串而不是陣列。文字模型的 `usage` 計算輸入 token 數，不含特殊 token。多模態模型則是 embedder 回報的 token 數，沒有回報時為項目數。

## Pooling

`POST /v1/pooling` 回傳每個輸入的池化隱藏狀態，不做正規化，供需要自行後處理的工具使用。

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `model` | string | 是 | Embedding 模型 id。 |
| `input` | string 或字串陣列 | 是 | 最多 2048 段文字，每段最多 8192 字元。 |
| `pooling_type` | string | 否 | `CLS`（預設）、`MEAN` 或 `LAST`。 |
| `encoding_format` | string | 否 | `float`（預設）或 `base64`。 |

```bash
curl http://localhost:8000/v1/pooling \
  -H "Content-Type: application/json" \
  -d '{"model": "Qwen/Qwen3-Embedding-0.6B", "input": "hello", "pooling_type": "LAST"}'
```

```json
{
  "object": "list",
  "data": [{ "object": "pooling", "index": 0, "data": [0.52, -1.31, 0.07] }],
  "model": "Qwen/Qwen3-Embedding-0.6B",
  "usage": { "prompt_tokens": 2, "total_tokens": 2 }
}
```

多模態 embedding 模型不由 `POST /v1/pooling` 提供（`400`），請改用 `POST /v1/embeddings`。無法產生 embedding 的模型（例如混合架構的聊天模型）會回應 `400`，並在訊息中說明。

## 錯誤

| 狀態碼 | 時機 |
| --- | --- |
| 400 | 驗證失敗（空輸入、清單型別混用、`encoding_format` 或 `pooling_type` 超出範圍、輸入過多、`dimensions` 超過原生維度）；對純文字 embedder 送入媒體；不正確的 `task`。 |
| 401 | 已設定 token，但缺少或不正確。 |
| 404 | 找不到該 embedding 模型。 |
| 422 | 清單中有空項目，或 token id 清單含有非整數。 |
| 507 | GPU 記憶體不足。 |
| 500 | Embedding 生成失敗（`server_error`）。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 字串、字串陣列與 token id 輸入 | <Support status="supported">支援</Support> |
| `encoding_format` 的 `float` 與 `base64` | <Support status="supported">支援</Support> |
| `dimensions`（截斷並重新正規化） | <Support status="supported">支援</Support> |
| 多模態輸入（圖片、音訊、影片） | <Support status="partial">僅限多模態 embedding 模型</Support> |
| `pooling_type`、`instruction`、`task`、`messages` | <Support status="extension">擴充</Support> |
| 把聊天模型當 embedder 使用 | <Support status="partial">會退回使用平均池化的隱藏狀態，這並非為檢索訓練；請改載入 embedding 檢查點</Support> |
| `user` | <Support status="unsupported">接受但忽略</Support> |
| 在 Neural Engine 上計算 embedding | <Support status="partial">以 `YUNSHU_ANE_EMBEDDINGS` 選擇啟用，僅適用於設定的 embedding 模型；見[設定](/docs/guides/configuration)</Support> |

## 相關頁面

- [Rerank 與評分](/docs/api/rerank)
- [模型](/docs/api/models)
- [模型支援](/docs/guides/model-support)
- [Ollama 相容層](/docs/api/ollama)


---

<!-- api/evals -->
---
title: 評測
description: 以本機儲存實作的 OpenAI Evals API：定義評分器、對 JSONL 或已儲存的 completion 執行評測，並讀取逐筆結果。
---

`/v1/evals` 路由遵循 OpenAI Evals API。一個 eval 描述資料結構與一組評分器（`testing_criteria`）；run 則把每一筆資料交給這些評分器，必要時先讓模型取樣，並為每筆資料記錄一個 output item，以及通過 / 失敗的統計。所有內容都以 JSON 存放在 `~/.yunshu/evals`（可用 `YUNSHU_EVALS_DIR` 變更）。

run 在伺服器行程內於背景執行。取樣與以模型評分的評分器，會在行程內呼叫本伺服器自己的 Chat Completions 路由，因此使用的模型、驗證與取樣行為都和一般請求相同。

<Endpoint method="POST" path="/v1/evals" />
<Endpoint method="GET" path="/v1/evals" />
<Endpoint method="GET" path="/v1/evals/{eval_id}" />
<Endpoint method="POST" path="/v1/evals/{eval_id}" />
<Endpoint method="DELETE" path="/v1/evals/{eval_id}" />
<Endpoint method="POST" path="/v1/evals/{eval_id}/runs" />
<Endpoint method="GET" path="/v1/evals/{eval_id}/runs" />
<Endpoint method="GET" path="/v1/evals/{eval_id}/runs/{run_id}" />
<Endpoint method="POST" path="/v1/evals/{eval_id}/runs/{run_id}/cancel" />
<Endpoint method="DELETE" path="/v1/evals/{eval_id}/runs/{run_id}" />
<Endpoint method="GET" path="/v1/evals/{eval_id}/runs/{run_id}/output_items" />
<Endpoint method="GET" path="/v1/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}" />

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。run 會把建立它的請求中的 `Authorization` 或 `x-api-key` 標頭只保留在記憶體裡（不會寫入磁碟），供內部呼叫使用。
</Callout>

## 建立 eval

`POST /v1/evals` 接收 JSON 本文，同時必須通過 OpenAI SDK `EvalCreateParams` 型別的檢查。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `name` | string | 否 | 顯示名稱。 | 支援 |
| `metadata` | object | 否 | 最多 16 組字串鍵值。 | 支援 |
| `data_source_config` | object | 是 | `{"type": "custom", "item_schema": {...}, "include_sample_schema": bool}`。`type` 也可以是 `stored_completions` 或 `logs`。 | 部分支援 |
| `testing_criteria` | array | 是 | 非空的評分器清單，`name` 不可為空且不可重複。 | 支援 |

`custom` 需要 `item_schema`，且必須是有效的 JSON Schema（Draft 2020-12）；建立 run 時，每一筆資料的 `item` 都會依它驗證。儲存後回傳的 `data_source_config` 形式為 `{"type", "schema"}`，其中 `schema` 會把你的 `item_schema` 包在 `item` 之下（`include_sample_schema` 為 true 時另加 `sample.output_text` 屬性）。

### 評分器

| 評分器 `type` | 欄位 | 作用 |
| --- | --- | --- |
| `string_check` | `name`、`input`、`reference`、`operation`（`eq`、`ne`、`like`、`ilike`） | 比較兩個樣板字串。`like` 表示 `reference` 是 `input` 的子字串；`ilike` 不分大小寫。分數為 1 或 0。 |
| `text_similarity` | `name`、`input`、`reference`、`evaluation_metric`、`pass_threshold` | 在本機計算、不使用模型的字面相似度。指標：`cosine`、`fuzzy_match`、`bleu`、`gleu`、`meteor`、`rouge_1` 到 `rouge_5`、`rouge_l`。分數達到 `pass_threshold` 即通過。 |
| `score_model` | `name`、`model`、`input`（訊息）、選填 `range`（預設 `[0, 1]`）、`pass_threshold`、`sampling_params` | 由模型回傳 `range` 內的數字；分數達到 `pass_threshold`（預設 1）即通過。 |
| `label_model` | `name`、`model`、`input`（訊息）、`labels`、`passing_labels`、`sampling_params` | 由模型回傳 `labels` 之一；標籤在 `passing_labels` 內即通過。 |

評分器欄位是樣板：`{{item.field}}` 與 `{{sample.output_text}}` 這類佔位符會以該筆資料的內容取代（巢狀路徑與清單索引以點號表示）。引用了不存在的欄位，該筆資料會以錯誤結束。字面相似度指標是 Yunshu 自己的實作：cosine 使用詞頻，METEOR 使用完全相同詞元的對齊且沒有同義詞語料，BLEU 是未經平滑的句子層級 BLEU，所以分數可能與其他實作略有差異。

以模型評分的評分器會透過本機的 `response_format` JSON Schema 路徑要求結構化輸出（一個 `score` 數字或一個 `label` 字串），再驗證結果。

其他評分器類型（例如 `python`、`endpoint`）會回傳 `400`。

## 更新、列出、刪除 eval

- `POST /v1/evals/{eval_id}` 可更新 `name` 與 `metadata`。
- `GET /v1/evals` 接受 `limit`（1 到 100，預設 20）、`order`（`asc` 或 `desc`，預設 `desc`）、`after` 與 `order_by`（`created_at` 或 `updated_at`）。
- `DELETE /v1/evals/{eval_id}` 會刪除 eval、取消並移除它所有的 run，並回傳 `{"object": "eval.deleted", "deleted": true, "eval_id": ...}`。

列表回傳 `{"object": "list", "data", "has_more", "first_id", "last_id"}`。`after` 游標不存在時回傳 `400`。

## 建立 run

`POST /v1/evals/{eval_id}/runs` 的本文會依 SDK 的 `RunCreateParams` 驗證：

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `name`、`metadata` | | 否 | 顯示名稱與最多 16 組字串鍵值。 | 支援 |
| `data_source.type` | string | 是 | `jsonl`（直接評分給定的資料）或 `completions`（先讓模型取樣）。其他類型回傳 `400`。 | 部分支援 |
| `data_source.source` | object | 是 | 資料來源，見下表。 | 支援 |
| `data_source.model` | string | 否 | 搭配 `type: "completions"`，指定要取樣的模型。省略時評分資料本身的 `sample`。 | 支援 |
| `data_source.input_messages` | object | 有 `model` 時必填 | `{"type": "template", "template": [messages]}` 或 `{"type": "item_reference", "item_reference": "item.input"}`。 | 支援 |
| `data_source.sampling_params` | object | 否 | 傳給 Chat Completions（`temperature`、`top_p`、`seed`、`max_completion_tokens` 等）。 | 支援 |

資料來源（`data_source.source.type`）：

| 來源 | 欄位 | 備註 |
| --- | --- | --- |
| `file_content` | `content`：`{"item": {...}, "sample": {...}}` 的陣列 | 內嵌資料。 |
| `file_id` | [檔案](/docs/api/files)儲存區中檔案的 `id` | JSONL 檔，一行一筆，格式同上。 |
| `stored_completions` | 選填 `model`、`metadata`、`created_after`、`created_before`、`limit` | 由本伺服器儲存的 Chat Completions 組成（見[已儲存的 Completions](/docs/api/stored-completions)）。`limit` 為 1 到 10000。 |

資料最多 10,000 筆，每筆 `item` 都必須符合 eval 的 `item_schema`。資料來源有問題時，建立請求會在任何事情執行前以 `400` 失敗。

建立請求會立刻回傳 `status: "queued"` 的 run，實際工作在背景進行。

```json
{
  "id": "evalrun_0a1b2c3d4e5f60718293a4b5",
  "object": "eval.run",
  "created_at": 1767225600,
  "eval_id": "eval_9f8e7d6c5b4a39281716f5e4",
  "name": "",
  "model": "local",
  "status": "queued",
  "error": null,
  "report_url": "",
  "metadata": null,
  "per_model_usage": [],
  "per_testing_criteria_results": [
    { "testing_criteria": "exact", "passed": 0, "failed": 0 }
  ],
  "result_counts": { "total": 0, "passed": 0, "failed": 0, "errored": 0 },
  "data_source": { "type": "completions", "model": "local" }
}
```

run 的 `status` 有：`queued`、`in_progress`、`completed`、`canceled`、`failed`。資料逐筆依序處理。伺服器重新啟動時，排隊中或執行中的 run 會被標為失敗（`error.code` 為 `interrupted`），請建立新的 run 重試。`report_url` 一律為空字串。

## Run 與 output item

- `GET /v1/evals/{eval_id}/runs` 接受 `status`、`limit`、`order`（預設 `asc`）與 `after`。
- `GET /v1/evals/{eval_id}/runs/{run_id}` 回傳 run，含目前的計數與各模型的 token 用量。
- `POST /v1/evals/{eval_id}/runs/{run_id}/cancel` 取消排隊中或執行中的 run（狀態變為 `canceled`）；已結束的 run 原樣回傳。
- `DELETE /v1/evals/{eval_id}/runs/{run_id}` 取消並刪除，回傳 `{"object": "eval.run.deleted", "deleted": true, "run_id": ...}`。
- `GET .../output_items` 列出項目，`status` 可篩選 `pass` 或 `fail`。`GET .../output_items/{output_item_id}` 取得單一項目。

output item 範例：

```json
{
  "id": "evalitem_0a1b2c3d4e5f60718293a4b5",
  "object": "eval.run.output_item",
  "created_at": 1767225610,
  "eval_id": "eval_9f8e7d6c5b4a39281716f5e4",
  "run_id": "evalrun_0a1b2c3d4e5f60718293a4b5",
  "datasource_item_id": 0,
  "datasource_item": { "question": "2+2?", "answer": "4" },
  "sample": {
    "model": "local",
    "input": [{ "role": "user", "content": "2+2?" }],
    "output": [{ "role": "assistant", "content": "4" }],
    "finish_reason": "stop",
    "usage": { "prompt_tokens": 14, "completion_tokens": 2, "total_tokens": 16, "cached_tokens": 0 },
    "error": null
  },
  "results": [
    { "name": "exact", "type": "string_check", "score": 1.0, "passed": true }
  ],
  "status": "pass"
}
```

所有評分器都通過時 `status` 為 `pass`，至少一個未通過為 `fail`，該筆資料本身出錯（例如樣板引用的欄位不存在，或模型呼叫失敗）則為 `error`，錯誤訊息在 `sample.error`。`error` 項目會計入 `result_counts.errored`，且不會出現在 `pass` / `fail` 的篩選結果中。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/evals \
  -H "Content-Type: application/json" \
  -d '{
    "name": "arith",
    "data_source_config": {
      "type": "custom",
      "item_schema": {"type": "object", "properties": {"question": {"type": "string"}, "answer": {"type": "string"}}, "required": ["question", "answer"]},
      "include_sample_schema": true
    },
    "testing_criteria": [
      {"type": "string_check", "name": "exact", "input": "{{sample.output_text}}", "operation": "eq", "reference": "{{item.answer}}"}
    ]
  }'

curl http://localhost:8000/v1/evals/eval_9f8e7d6c5b4a39281716f5e4/runs \
  -H "Content-Type: application/json" \
  -d '{
    "name": "run-1",
    "data_source": {
      "type": "completions",
      "model": "local",
      "input_messages": {"type": "template", "template": [{"role": "user", "content": "{{item.question}} Answer with just the number."}]},
      "source": {"type": "file_content", "content": [{"item": {"question": "2+2?", "answer": "4"}}]}
    }
  }'
```

</Tab>
<Tab value="Python">

```python
import time
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

ev = client.evals.create(
    name="arith",
    data_source_config={
        "type": "custom",
        "item_schema": {
            "type": "object",
            "properties": {"question": {"type": "string"}, "answer": {"type": "string"}},
            "required": ["question", "answer"],
        },
        "include_sample_schema": True,
    },
    testing_criteria=[
        {
            "type": "string_check",
            "name": "exact",
            "input": "{{sample.output_text}}",
            "operation": "eq",
            "reference": "{{item.answer}}",
        }
    ],
)

run = client.evals.runs.create(
    ev.id,
    name="run-1",
    data_source={
        "type": "completions",
        "model": "local",
        "input_messages": {
            "type": "template",
            "template": [{"role": "user", "content": "{{item.question}} Answer with just the number."}],
        },
        "source": {"type": "file_content", "content": [{"item": {"question": "2+2?", "answer": "4"}}]},
    },
)

while run.status in ("queued", "in_progress"):
    time.sleep(1)
    run = client.evals.runs.retrieve(run.id, eval_id=ev.id)
print(run.result_counts)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "not-needed" });

const ev = await client.evals.create({
  name: "arith",
  data_source_config: {
    type: "custom",
    item_schema: {
      type: "object",
      properties: { question: { type: "string" }, answer: { type: "string" } },
      required: ["question", "answer"],
    },
    include_sample_schema: true,
  },
  testing_criteria: [
    {
      type: "string_check",
      name: "exact",
      input: "{{sample.output_text}}",
      operation: "eq",
      reference: "{{item.answer}}",
    },
  ],
});

let run = await client.evals.runs.create(ev.id, {
  data_source: {
    type: "completions",
    model: "local",
    input_messages: {
      type: "template",
      template: [{ role: "user", content: "{{item.question}} Answer with just the number." }],
    },
    source: { type: "file_content", content: [{ item: { question: "2+2?", answer: "4" } }] },
  },
});
```

</Tab>
</Tabs>

## 錯誤

錯誤使用 OpenAI 的格式，code 例如 `invalid_value`、`invalid_type`、`not_found`、`unsupported_value`。

| 狀態碼 | 情況 |
| --- | --- |
| `400` | 本文不符合 SDK 型別、`data_source_config`、評分器或資料來源類型不支援、JSON Schema 無效、樣板有誤、超過 10,000 筆資料、某筆資料違反 `item_schema`、分頁或篩選值不合法。 |
| `404` | eval、run、output item 或檔案不存在。 |

run 執行期間發生的失敗不會改變 HTTP 狀態碼，而是以 `error` 狀態的 output item 呈現，或讓 run 變成 `status: "failed"` 並帶有 `error`。

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| eval CRUD、run、output item、取消 | <Support status="supported">支援</Support> |
| 評分器 `string_check`、`text_similarity`、`score_model`、`label_model` | <Support status="supported">支援</Support> |
| 評分器 `python`、`endpoint`、`multi` | <Support status="unsupported">回傳 400</Support> |
| run 資料來源 `jsonl` 與 `completions` | <Support status="supported">支援</Support> |
| run 資料來源 `responses`、`logs` 等 | <Support status="unsupported">回傳 400</Support> |
| `data_source_config.type: "logs"` | <Support status="partial">可建立 eval，但沒有任何 run 來源會讀取 logs</Support> |
| 資料平行處理 | <Support status="unsupported">一次處理一筆</Support> |
| 重新啟動後繼續 run | <Support status="unsupported">被中斷的 run 會標為失敗</Support> |
| `report_url` | <Support status="unsupported">一律為空</Support> |

## 相關頁面

- [檔案](/docs/api/files)：以 `purpose=evals` 上傳 JSONL 資料。
- [已儲存的 Completions](/docs/api/stored-completions)：`stored_completions` 來源所讀取的內容。
- [Chat Completions](/docs/api/chat-completions)：run 使用的取樣路徑。


---

<!-- api/extensions -->
---
title: 擴充
description: Yunshu 在 OpenAI、Anthropic 與 Ollama API 之上額外提供的功能：狀態、預熱、取消、逐筆回應統計、多工 WebSocket、原生語音與 System One。
---

Yunshu 的擴充一律是附加且有命名空間的，所以官方 SDK 不需修改就能繼續使用。它們出現在三個地方：

- JSON：回應頂層的 `x_yunshu` 物件（Messages 與 Responses 則放在 `usage` 內），以及錯誤中的 `error.x_yunshu`。OpenAI SDK 會把未知欄位保留在 `model_extra`；Anthropic 與 Ollama SDK 則會忽略。
- SSE：以註解行呈現，例如 `: yunshu-progress {...}`。所有 SSE 解析器都會略過註解。
- 標頭：`X-Request-Id` 與 `X-Yunshu-*`。

驗證規則和其他路由相同：只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。

<Endpoint method="GET" path="/v1/yunshu/status" />
<Endpoint method="POST" path="/v1/yunshu/warmup" />
<Endpoint method="POST" path="/v1/cancel" />
<Endpoint method="GET" path="/v1/active-generations" />
<Endpoint method="WS" path="/v1/stream" />
<Endpoint method="POST" path="/v1/omni/speech/stream" />
<Endpoint method="POST" path="/v1/systemone" />

檢視請求用的路由 `GET /v1/requests`、`GET /v1/requests/{request_id}` 與 `DELETE /v1/requests/{request_id}`，說明在[維運](/docs/api/operations)。

## 請求 id

每個請求都有 id：若你的 `X-Request-Id` 標頭是 1 到 128 個 `A-Za-z0-9._:-` 字元就使用它，否則產生 `req_...` 形式的值。它會回傳在每個回應上（包含錯誤）、寫入伺服器日誌，並放入 `x_yunshu.request_id` 與 `error.x_yunshu.request_id`。同一個 id 也是查詢狀態與取消的把手：

```bash
curl http://localhost:8000/v1/chat/completions -H "X-Request-Id: job-7" -H "Content-Type: application/json" \
  -d '{"model": "local", "stream": true, "messages": [{"role": "user", "content": "Write a long story."}]}'

curl http://localhost:8000/v1/requests/job-7                       # where is it?
curl -X DELETE http://localhost:8000/v1/requests/job-7             # cancel it
```

如果取消指令在請求抵達引擎之前就到了（例如還在分詞或解碼圖片），伺服器會記住它，並在開始生成的瞬間套用。

## 逐筆回應統計：`x_yunshu`

`x_yunshu` 出現在非串流 Chat 與 Completions 回應的 JSON 本文、串流的最後一個 usage 區塊中，而在用戶端沒有要求 usage 時，則放在 `[DONE]` 之前的 `: yunshu-stats {...}` 註解裡。Messages 與 Responses 則把同一個物件放在 `usage` 之內。Ollama 路由會把它對應到 Ollama 自己的奈秒欄位。

```json
"x_yunshu": {
  "request_id": "job-7",
  "queue_wait_ms": 0.4, "ttft_ms": 309.5,
  "prompt_tokens": 58, "cached_tokens": 0, "prefill_ms": 287.5, "prefill_tps": 201.7,
  "completion_tokens": 24, "decode_ms": 541.3, "decode_tps": 42.5, "total_ms": 857.3,
  "speculative": { "mode": "mtp", "drafted": 20, "accepted": 15, "acceptance_rate": 0.75 },
  "timings": { "cache_n": 0, "prompt_n": 58, "prompt_ms": 287.5, "prompt_per_second": 201.7,
               "predicted_n": 24, "predicted_ms": 541.3, "predicted_per_second": 42.5 }
}
```

| 欄位 | 意義 |
| --- | --- |
| `queue_wait_ms` | 從抵達引擎到開始 prefill 之間的時間。 |
| `ttft_ms` | 從請求抵達到第一個生成 token 的時間。 |
| `prefill_tps` | 未快取的提示 token 數除以 prefill 時間。 |
| `decode_tps` | (completion token 數 - 1) 除以第一個與最後一個 token 之間的時間。 |
| `cached_tokens` | 由前綴快取提供的提示 token 數。 |
| `speculative` | 有草稿器（`mtp` 或 `dflash`）服務該請求時才有；沒有草稿時為 `null`。 |
| `timings` | 同樣的量測值，使用 llama.cpp 風格的鍵名。 |
| `cancelled` | 回答被取消或逾時截斷時為 `true`。 |
| `context_policy` | 提示為了放進視窗而被縮短時才有：策略、前後的 token 與訊息數，以及被移除的內容。 |
| `budget` | `max_tokens` 因提示佔去上下文視窗而被調降、或請求未帶上限時才有：`max_tokens_requested`、`max_tokens_granted`、`max_tokens_source`（`request`、`model_limit`、`operator_cap`、`api_spec_default`），被調降時另有 `clamped_by`。 |
| `server_tools` | Messages 與 Responses 上的伺服器端工具迴圈報告：`rounds`、`round_usage[]`、`tools[]`。 |

路徑無法量測的欄位為 `null`。非串流回應另外帶有精簡標頭 `X-Yunshu-Queue-Wait-Ms`、`X-Yunshu-TTFT-Ms`、`X-Yunshu-Prefill-Tps`、`X-Yunshu-Decode-Tps`、`X-Yunshu-Cached-Tokens`、`X-Yunshu-Cache-Tier`、`X-Yunshu-Cache-Reload-Ms`、`X-Yunshu-Total-Ms`、`X-Yunshu-Spec`、`X-Yunshu-Spec-Acceptance`、`X-Yunshu-Cancelled`、`X-Yunshu-Context-Policy`，給只記錄標頭、不解析本文的用戶端。

放不下的提示不會被默默截斷：最新的使用者回合與系統訊息一律不會被移除，如果光是它們就超過視窗，請求會以 `400` 與 code `context_length_exceeded` 失敗。

## 佇列、進度與過載

生成回應帶有 `X-Yunshu-Queue-Position`（比你早到、仍在處理中的請求數；0 表示立即服務）與 `X-Yunshu-Queue-Est-Wait-Ms`（依你前面尚待 prefill 的量估算的下限）。

串流的 Chat 或 Completions 請求在排隊或 prefill 期間，伺服器每隔 `YUNSHU_PROGRESS_INTERVAL_S` 秒（預設 2，`0` 關閉）寫出一行 SSE 註解，直到第一個 token：

```text
: yunshu-progress {"request_id":"job-8","elapsed_s":8.12,"phase":"prefill","prompt_tokens":93268,"cached_tokens":0,"processed_tokens":92160,"percent":98.8,"tokens_per_second":8125.3,"eta_s":0.1}
: yunshu-progress {"request_id":"job-9","elapsed_s":3.0,"phase":"queued","queue_position":1,"queue_est_wait_ms":41200.0}
```

`percent` 只計算實際運算的 token；前綴快取命中的部分以 `cached_tokens` 回報。非串流請求無法在處理途中回報進度，請用你送出的 id 輪詢 `GET /v1/requests/{request_id}`。

過載時會直接拒絕，而不是無上限地排隊。當處理中的請求已達 `YUNSHU_QUEUE_LIMIT`（預設 64，`0` 表示不限）時，新抵達的 Chat、Completions、Messages、Responses 請求會得到 `429`，帶有 `Retry-After`，以及 `error.x_yunshu` 內容 `{"reason": "queue_full", "queue_depth", "queue_limit", "retry_after_s"}`。當 MLX 記憶體超過 `YUNSHU_MEMORY_PRESSURE_REJECT`（預設為 Metal 工作集的 0.95）且仍有其他請求在執行時，新的生成請求會得到 `503`，reason 為 `memory_pressure`。閒置的伺服器不會因為記憶體而拒絕請求。

`X-Yunshu-Deadline-Ms: N`（1 到 86,400,000）是你願意等待的牆鐘時間，從抵達起算，含排隊時間。超過後生成會被取消，用戶端收到 `504` 與 code `deadline_exceeded`（Messages 為 `timeout_error`）；若串流已開始，則以一個終止錯誤事件結束。這和請求本文的 `timeout` 欄位不同，後者是讓生成以部分答案結束。

## `keep_alive` 與狀態

`POST /v1/chat/completions` 與 `POST /v1/completions` 上的 `keep_alive` 遵循 Ollama 的語法：秒數、像 `"5m"` 的時間字串、負值表示「保持載入」、`0` 表示閒置後立即釋放模型。它在多模型模式下才有作用：閒置模型會在 keep-alive 到期後卸載，若請求沒有設定，則依 `YUNSHU_MODEL_TTL_SECONDS`。單模型伺服器永遠不會釋放模型，所以會接受這個欄位但不做任何事。

`GET /v1/yunshu/status` 回傳一個物件，包含營運者在送出大請求前想知道的一切：

```json
{
  "object": "yunshu.status",
  "version": "0.1.5",
  "state": "running",
  "uptime_s": 17.3,
  "load_error": null,
  "models": [{ "id": "Qwen3.8-27B-oQ4e-mtp", "type": "VLMEngine", "loaded": true, "loading": false, "pinned": true }],
  "memory": { "active_gb": 16.2, "active_bytes": 17394617344, "cache_gb": 0.28, "peak_gb": 16.9, "total_gb": 128.0, "pressure": 0.127 },
  "requests": { "active": 1, "queued": 0, "prefill": 0, "decode": 1, "items": [{ "request_id": "job-7", "phase": "decode", "completion_tokens": 112 }] },
  "last": null,
  "gpu": {},
  "throughput": { "window_s": 60, "requests": 3, "prompt_tokens": 11765, "completion_tokens": 64,
                  "live_decode_tps": 41.8, "mean_prefill_tps": 502.9, "mean_decode_tps": 51.7 }
}
```

`state` 為 `running`、`shutdown_requested` 或 `shutting_down`。名稱為 `*_gb` 的記憶體欄位使用二進位 GiB（1 GiB 為 1024^3 位元組），且各有精確的 `*_bytes` 對應欄位。多模型模式下，每個模型另有 `size_gb`、`size_bytes`、`idle_s`、`keep_alive_s`、`expires_in_s`。`gpu` 內是有追蹤 GPU 忙碌時間的各引擎累計秒數。

## 預熱

`POST /v1/yunshu/warmup` 會在需要時載入模型，沿著正常路徑執行一次小型生成（編譯 kernel、預熱配置器），並把指定的提示留在前綴快取中，讓第一個真正的請求就是熱的。

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `model` | string | 否 | 預設為所服務的模型。多模型模式下指定未知模型回傳 `404`。 |
| `prompt` | string | 否 | 要留在快取中的系統提示或前綴，預設 `"Hello"`。 |
| `messages` | array | 否 | 以聊天訊息取代 `prompt` 進行預熱。 |
| `keep_alive` | string、number | 否 | 設定該模型的 keep-alive（多模型模式）。值不合法回傳 `400`。 |
| `max_tokens` | integer | 否 | 預設 1。 |

回應：

```json
{
  "object": "yunshu.warmup",
  "model": "Qwen3.8-27B-oQ4e-mtp",
  "loaded_now": false,
  "load_ms": 0.0,
  "keep_alive_s": 1800,
  "generated": true,
  "x_yunshu": { "ttft_ms": 309.5 },
  "warmup_ms": 412.7
}
```

對無法生成文字的模型類型（ASR、TTS、embedding 等），`generated` 為 `false`。若預熱用的生成本身失敗，呼叫仍然成功，回應會帶 `warning` 字串，而不是 `x_yunshu`。

## 取消

`POST /v1/cancel` 接收 `{"request_id": "job-7"}` 或 `{"cancel_all": true}`，回傳 `{"status": "cancelled", "request_id": ...}` 或 `{"status": "cancelled", "count": N}`。id 不存在回傳 `404`，本文兩個欄位都沒有則回傳 `400`。`GET /v1/active-generations` 回傳處理中生成的 `{"object": "list", "data": [...], "active": [...], "count": N}`。它們與 `DELETE /v1/requests/{request_id}` 接受相同的 id。

## `WS /v1/stream`

一條 WebSocket 可承載許多並行請求。伺服器事件就是 SSE 串流所帶的同一批物件，外面包上你的請求 id。握手使用與 HTTP 相同的驗證（`Authorization: Bearer`、`x-api-key` 或 `?token=`），並在升級連線前檢查；檢查失敗時握手會被拒絕。伺服器送出的第一則訊息是 `session.created`。

用戶端訊息（JSON 文字訊框）：

| 訊息 | 意義 |
| --- | --- |
| `{"type": "request", "id": "a", "api": "chat.completions", "body": {...}, "stream_id": "s"}` | 開始一個請求。`api` 為 `chat.completions`、`completions`、`responses` 或 `messages`；`body` 是一般的 HTTP 本文（`stream` 會被強制開啟；chat 的 `stream_options.include_usage` 預設開啟）。`stream_id` 為選填。 |
| `{"type": "cancel", "id": "a"}` | 中止，以 `done` 結束，reason 為 `cancelled`。 |
| `{"type": "stop", "id": "a"}` | 依需求停止，reason 為 `stopped`。 |
| `{"type": "update", "id": "a", "max_tokens": N}` | 限制串流 delta 的總數；回應 `updated`，以 reason `max_tokens` 結束。 |
| `{"type": "ping", "t": ...}` | 存活檢查，回應 `pong`。 |

伺服器訊息：

| 訊息 | 意義 |
| --- | --- |
| `session.created` | `{"protocol": "yunshu.stream", "apis": [...], "limits": {"max_inflight", "max_stream_ids", "send_queue", "ping_interval_s"}}` |
| `event` | `{"id", "event": "<SSE 事件名稱或 null>", "data": {...}}`，一個 SSE 事件。 |
| `progress`、`stats` | 欄位與 `yunshu-progress`、`yunshu-stats` 註解相同。 |
| `done` | 每個請求的終止訊息：`reason`（`completed`、`cancelled`、`stopped`、`max_tokens`、`error`）、`request_id`、`stats`（`ttft_ms`、`duration_ms`、`events`、`deltas`）。 |
| `error` | `{"id"?, "status", "error": {"message", "type", ...}}`，帶有 `id` 時屬於該請求。 |
| `ping` | 每隔 `YUNSHU_WS_PING_INTERVAL` 秒的心跳（預設 15，`0` 關閉）。 |

限制：每條連線最多 `YUNSHU_WS_MAX_INFLIGHT`（預設 16）個並行請求（超過回傳 `429`，code 為 `too_many_requests`），重複使用仍在進行中的 `id` 為 `409`，不同的 `stream_id` 最多 32 個。相同 `stream_id` 的請求依序執行，不同 id 則並行。送出的事件最多緩衝 `YUNSHU_WS_SEND_QUEUE`（預設 256）個，超過後生成會暫停，直到讀取端跟上。關閉 socket 會取消所有進行中的請求。當你的 `id` 是 1 到 128 個 `A-Za-z0-9._:-` 字元時，它同時也是 HTTP 的 `X-Request-Id`。

`WS /v1/responses` 在同一個傳輸層上提供 OpenAI 的 Responses WebSocket 模式，請見 [Responses](/docs/api/responses)。

## 原生語音：`POST /v1/omni/speech/stream`

對帶有 Talker 的模型（Qwen3-Omni），這個路由從同一個模型串流文字與語音，不需要 ASR 到 LLM 再到 TTS 的串接。若所服務的模型能發聲就直接重用；否則可用 `YUNSHU_OMNI_MODEL` 指向另一個 omni 模型。沒有可發聲的模型時，路由回傳 `503`。

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `text` | string | 是 | 1 到 8000 個字元。 |
| `speaker` | string | 否 | 模型的說話者或別名。未知的說話者回傳 `400` 並列出有效名稱。 |
| `thinker_max_new_tokens` | integer | 否 | 0 到 512。 |
| `image_path` | string | 否 | 圖片輸入：伺服器上的檔案路徑、`data:` URI（base64）或 http(s) URL。 |
| `audio_path` | string | 否 | 音訊輸入，形式同上。 |

內嵌與下載的媒體上限為 64 MiB（`413`）。回應為 `text/event-stream`：

| 事件 | 內容 |
| --- | --- |
| `{"type": "text", "delta": "..."}` | 一段 Thinker 文字。 |
| `{"type": "audio", "delta": "<base64 PCM16>", "sr": 24000}` | 一個語音區塊，單聲道 16-bit little-endian。 |
| `{"type": "done", ...}` | 最終統計，之後接 `data: [DONE]`。 |
| `{"type": "error", "message": ...}` | 串流開始後的失敗。 |

```bash
curl -N http://localhost:8000/v1/omni/speech/stream \
  -H "Content-Type: application/json" \
  -d '{"text": "Say hello in one short sentence."}'
```

## System One：`POST /v1/systemone`

這是[決策](/docs/api/decisions)引擎的另一種傳輸格式：問題是以名稱為鍵的 map，答案也用相同的名稱回傳。它需要相同的決策 checkpoint。

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `model` | string | 是 | 決策模型 id。 |
| `state` | any | 是 | 輸入，文字或任何 JSON 值。 |
| `questions` | object | 是 | 名稱對應 `{"type", "instructions"?, "criteria"?}` 的 map，1 到 128 個問題。 |
| `images` | array of string | 否 | base64 圖片或 `data:image/...;base64,...` URL，最多 128 張。 |

問題類型：`noul`（布林；選填的 `criteria` map 可含 `true` 與 `false` 的描述）、`choice`（`criteria` 為選項對應描述的 map，至少 2 個）與 `score`（`criteria` 為等級描述的清單，至少 2 個）。

```json
{
  "model": "abenzerps/Clef-MLX",
  "answers": {
    "urgent": { "type": "noul", "noul": 0.81 },
    "route": { "type": "choice", "choice": "support", "confidence": 0.93, "probabilities": { "support": 0.93, "sales": 0.07 } },
    "tone": { "type": "score", "score": 0.22, "confidence": 0.78, "legend": { "0": "calm", "1": "angry" }, "probabilities": { "0": 0.78, "1": 0.22 } }
  },
  "usage": { "input_tokens": 142, "output_tokens": 0 }
}
```

此路由的驗證錯誤回傳 `422`（decisions 路由則是 `400`）；非決策模型、找不到模型或引擎錯誤，則與 `POST /v1/decisions` 相同，回傳 `400` 或 `404`。決策頭無法回答的問題會回傳 `{"type": "refusal"}`。

## 會告訴你該怎麼做的錯誤

OpenAI 格式的錯誤（包含中介層產生的）會把修正方式放兩次：附加在 `error.message` 後面，以及結構化地放在 `error.x_yunshu`（`hint`、`request_id`，過載時還有佇列欄位）。提示涵蓋的情況有：上下文太長、記憶體不足、驗證、未知模型、本文過大、速率限制、模型載入中或關閉中、驗證失敗與內部錯誤。Anthropic 格式的錯誤則完全維持 Anthropic 規格的樣子。

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| `x_yunshu` 統計、`X-Yunshu-*` 標頭、進度註解 | <Support status="extension">Yunshu 擴充</Support> |
| 請求 id、依 id 取消、deadline 標頭 | <Support status="extension">Yunshu 擴充</Support> |
| `keep_alive` | <Support status="partial">僅在多模型模式下有作用</Support> |
| 狀態與預熱 | <Support status="extension">Yunshu 擴充</Support> |
| `WS /v1/stream` | <Support status="extension">Yunshu 協定</Support> |
| 非串流請求的進度 | <Support status="unsupported">請改為輪詢 `GET /v1/requests/{request_id}`</Support> |
| 原生語音 | <Support status="partial">需要帶有 Talker 的模型</Support> |

## 相關頁面

- [維運](/docs/api/operations)：健康檢查、指標與請求檢視。
- [Realtime](/docs/api/realtime)：OpenAI Realtime WebSocket。
- [Decisions](/docs/api/decisions)：`POST /v1/decisions`。
- [Chat Completions](/docs/api/chat-completions)：帶有這些欄位的路由。


---

<!-- api/files -->
---
title: 檔案
description: 本機檔案儲存區，在同一組 /v1/files 路徑上同時支援 OpenAI Files API 與 Anthropic Files API。
---

Yunshu 把上傳的檔案存放在同一個本機儲存區（預設 `~/.yunshu/files`）。同一組路由會以兩種格式回應，由請求決定：只要請求帶有 `anthropic-version` 標頭（所有 Anthropic SDK 都會送出）就使用 Anthropic 格式，否則使用 OpenAI 格式。OpenAI SDK 不會送這個標頭。

儲存的檔案會用在其他地方：批次的輸入與輸出檔（[批次](/docs/api/batches)）、評測資料（[評測](/docs/api/evals)）、登錄的自訂語音（[音訊](/docs/api/audio)），以及 [Responses](/docs/api/responses) 與 [Messages](/docs/api/messages) 請求中的檔案引用。

<Endpoint method="POST" path="/v1/files" />
<Endpoint method="GET" path="/v1/files" />
<Endpoint method="GET" path="/v1/files/{file_id}" />
<Endpoint method="GET" path="/v1/files/{file_id}/content" />
<Endpoint method="DELETE" path="/v1/files/{file_id}" />

<Callout type="info">
設定靜態 token 或 API 金鑰後會強制驗證。這裡只有單一擁有者：出示 token 的人（未設定 token 時則是任何人）看得到所有檔案。
</Callout>

## 限制與儲存

| 設定 | 預設值 | 作用 |
| --- | --- | --- |
| `YUNSHU_FILES_DIR` | `~/.yunshu/files` | 儲存區目錄。 |
| `YUNSHU_FILES_MAX_BYTES` | 536870912（512 MB） | 單一上傳檔的大小上限；超過會以 `413` `file_too_large` 失敗。 |
| `YUNSHU_FILES_MAX_TOTAL_BYTES` | 0（不限） | 儲存區總大小；上傳後會超過時以 `413` `storage_quota_exceeded` 失敗（會先清除已過期的檔案）。 |
| `YUNSHU_FILES_TTL_DAYS` | 未設定 | 上傳後經過這麼多天就刪除。未設定則保留到手動刪除。 |

其他行為：

- id 的形式是 `file_` 加 24 個十六進位字元。凡是需要 id 的地方，也接受 OpenAI 的寫法 `file-...`，並對應到 `file_...`。
- 中繼資料與內容都以原子方式寫入；過期檔案會在存取時以及儲存區啟動時被清除。
- 磁碟已滿時，上傳回傳 `507`，code 為 `insufficient_storage`。

## 上傳

`POST /v1/files` 使用 `multipart/form-data`。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `file` | file | 是 | 檔案部分。 | 支援 |
| `purpose` | string | OpenAI：是 | `assistants`、`batch`、`fine-tune`、`vision`、`user_data`、`evals` 之一，其他值回傳 `400`。Anthropic 請求會忽略（以 `user_data` 儲存）。 | 支援 |
| `expires_after` | object | 否 | 僅 OpenAI。`{"anchor": "created_at", "seconds": 3600..2592000}`，可用 `expires_after[anchor]` 與 `expires_after[seconds]` 表單欄位，或單一 JSON 字串送出。 | 支援 |

OpenAI 上傳不可為空檔案。所有 `purpose` 值都會被接受，但只有 Yunshu 會用到的值才有實際作用：`batch` 對應[批次](/docs/api/batches)，`evals` 對應[評測](/docs/api/evals)。這裡不會執行任何微調。

OpenAI 回應：

```json
{
  "id": "file_0a1b2c3d4e5f60718293a4b5",
  "object": "file",
  "bytes": 1204,
  "created_at": 1767225600,
  "expires_at": null,
  "filename": "requests.jsonl",
  "purpose": "batch",
  "status": "processed",
  "status_details": null
}
```

Anthropic 回應：

```json
{
  "id": "file_0a1b2c3d4e5f60718293a4b5",
  "type": "file",
  "filename": "report.pdf",
  "mime_type": "application/pdf",
  "size_bytes": 48210,
  "created_at": "2026-01-01T00:00:00Z",
  "downloadable": false
}
```

儲存的 `mime_type` 優先採用上傳時宣告且夠具體的 content type，否則從內容判斷（PDF、PNG、JPEG、GIF、WebP），再依檔名推測。

## 列出、取得、刪除

| 路由 | OpenAI 格式 | Anthropic 格式 |
| --- | --- | --- |
| `GET /v1/files` | 查詢參數：`purpose`、`limit`（1 到 10000，預設 10000）、`order`（`asc` 或 `desc`，預設 `desc`）、`after`（檔案 id）。回傳 `{"object": "list", "data", "has_more", "first_id", "last_id"}`。 | 查詢參數：`limit`（1 到 1000，預設 20）、`after_id`、`before_id`。回傳 `{"data", "first_id", "last_id", "has_more"}`。不依 `purpose` 篩選。 |
| `GET /v1/files/{file_id}` | 檔案物件。 | 檔案物件。 |
| `DELETE /v1/files/{file_id}` | `{"id", "object": "file", "deleted": true}` | `{"id", "type": "file_deleted"}` |

列表依建立時間由新到舊。

## 下載內容

`GET /v1/files/{file_id}/content` 以附件形式回傳儲存的位元組，並帶有儲存的 content type 與檔名。

在 Anthropic 格式下，遵循 Anthropic 的規則：只有工具產生的檔案可以下載，使用者上傳的不行。Yunshu 把所有上傳檔案標為 `downloadable: false`，因此 Anthropic 風格的請求（帶 `anthropic-version` 標頭）會得到 `403`。要讀回檔案，請使用 OpenAI 格式（不帶 `anthropic-version` 標頭）。

## 在請求中使用儲存的檔案

請求中以 id 引用時，儲存的檔案會被內嵌到模型請求中：

| 位置 | 引用方式 |
| --- | --- |
| [Messages](/docs/api/messages) | `{"type": "image"}` 或 `{"type": "document"}` 區塊，搭配 `"source": {"type": "file", "file_id": "file_..."}`。文字文件會變成文字來源，其他轉成 base64。 |
| [Responses](/docs/api/responses) | 帶 `file_id` 的 `input_file` 或 `input_image` 項目。 |

id 不存在時回傳 `404` `file_not_found`。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
# Upload (OpenAI dialect)
curl http://localhost:8000/v1/files \
  -F purpose=user_data \
  -F file=@notes.txt

# List and download
curl "http://localhost:8000/v1/files?limit=5"
curl http://localhost:8000/v1/files/file_0a1b2c3d4e5f60718293a4b5/content -o notes.txt

# Upload with the Anthropic dialect: the header selects it
curl http://localhost:8000/v1/files \
  -H "anthropic-version: 2023-06-01" \
  -F file=@report.pdf
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

f = client.files.create(file=open("notes.txt", "rb"), purpose="user_data")
print(f.id, f.bytes)

for item in client.files.list(limit=5):
    print(item.id, item.filename)

print(client.files.content(f.id).text)
client.files.delete(f.id)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";
import fs from "node:fs";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "not-needed" });

const f = await client.files.create({
  file: fs.createReadStream("notes.txt"),
  purpose: "user_data",
});
console.log(f.id, f.bytes);
await client.files.del(f.id);
```

</Tab>
</Tabs>

## 錯誤

OpenAI 格式的錯誤使用 `{"error": {"message", "type", "param", "code"}}`；Anthropic 格式的錯誤使用 `{"type": "error", "error": {"type", "message"}}`。

| 狀態碼 | Code | 情況 |
| --- | --- | --- |
| `400` | `invalid_value` | `purpose`、`expires_after`、`limit` 或 `order` 不合法。 |
| `400` | | 不是 multipart 本文、缺少 `file`、檔案為空（OpenAI）。 |
| `404` | `file_not_found` | id 不存在、格式錯誤或已過期。 |
| `403` | | 以 Anthropic 格式下載上傳的檔案內容。 |
| `413` | `file_too_large`、`storage_quota_exceeded` | 超過單檔或總量上限。 |
| `507` | `insufficient_storage` | 磁碟已滿。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| OpenAI Files：上傳、列出、取得、刪除、內容 | <Support status="supported">支援</Support> |
| 依 `anthropic-version` 選擇的 Anthropic Files 格式 | <Support status="supported">支援</Support> |
| `expires_after` | <Support status="supported">1 小時到 30 天，只支援 `created_at` 錨點</Support> |
| Anthropic 格式下載上傳的檔案 | <Support status="unsupported">403，與 Anthropic API 相同</Support> |
| 分段 / 可續傳的 `uploads` API | <Support status="unsupported">未提供</Support> |
| `purpose` 背後的微調、assistants、vision 流程 | <Support status="unsupported">purpose 值只會被接受並儲存</Support> |

## 相關頁面

- [批次](/docs/api/batches)：輸入與輸出 JSONL 檔。
- [評測](/docs/api/evals)：以 `purpose=evals` 上傳的資料集。
- [音訊](/docs/api/audio)：存放在此儲存區的自訂語音。
- [Messages](/docs/api/messages) 與 [Responses](/docs/api/responses)：檔案引用。


---

<!-- api/images -->
---
title: 圖像與 OCR
description: OpenAI 風格的本機圖像生成、編輯與變體端點，以及用來從圖片擷取文字的 Yunshu OCR 端點。
---

本頁涵蓋兩組路由。圖像路由遵循 OpenAI 的 `/v1/images/*` 規格，執行本機的 Z-Image 類擴散管線。`POST /v1/ocr` 是 Yunshu 自己的路由（不屬於 OpenAI API），會用 OCR 模型或任何已載入的視覺語言模型把上傳的圖片轉成文字。

<Endpoint method="POST" path="/v1/images/generations" />
<Endpoint method="POST" path="/v1/images/generations/stream" />
<Endpoint method="POST" path="/v1/images/edits" />
<Endpoint method="POST" path="/v1/images/variations" />
<Endpoint method="POST" path="/v1/ocr" />

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。圖像生成需要先載入圖像模型（見[模型](/docs/getting-started/models)）；選用的 `generation` extra 會提供額外的相依套件。
</Callout>

## 圖像生成

`POST /v1/images/generations` 接收 JSON 本文。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `prompt` | string | 是 | 提示詞，不可為空白。 | 支援 |
| `model` | string | 否 | 圖像模型 id，預設 `Z-Image-Turbo-MLX-4bit`。若與已載入的圖像模型都不相符、但剛好只載入了一個圖像模型，就使用那一個。 | 支援 |
| `n` | integer | 否 | 1 到 10，預設 1。圖片依序逐張生成。 | 支援 |
| `size` | string | 否 | `WIDTHxHEIGHT`，預設 `1024x1024`。兩邊都必須介於 64 到 2048，且為 64 的倍數。 | 支援 |
| `response_format` | string | 否 | `b64_json`（預設）或 `url`。 | 支援 |
| `num_inference_steps` | integer | 否 | 1 到 100，預設 4（針對 Turbo 模型調整）。 | 擴充 |
| `seed` | integer | 否 | 第 `i` 張使用 `seed + i`。未提供 seed 時，每張圖各自使用新的隨機 seed。 | 擴充 |
| `control_image` | string | 否 | 作為控制訊號的 base64 圖片（可帶 `data:` URL 前綴）。 | 擴充 |
| `control_scale` | number | 否 | 0 到 2，預設 0.8。僅在有 `control_image` 時使用。 | 擴充 |
| `preview_interval` | integer | 否 | 僅串流路由：每 N 步輸出一張解碼後的預覽（0 表示關閉）。 | 擴充 |
| `quality`、`style`、`background`、`output_format`、`moderation` | | 否 | 不在結構內的 OpenAI 欄位，會被忽略。 | 接受但忽略 |

回應一律是 PNG 資料：

```json
{
  "created": 1767225600,
  "data": [
    { "b64_json": "iVBORw0KGgo..." }
  ]
}
```

使用 `response_format: "url"` 時，每個項目的 `url` 是 `data:image/png;base64,...` URI（同時帶有 `b64_json`）。Yunshu 不代管生成的檔案，所以 `url` 不會是 http 連結。

### 串流生成

`POST /v1/images/generations/stream` 使用相同的本文，回傳 `text/event-stream`。每個事件是一行帶 JSON 物件的 `data:`，沒有 `event:` 名稱：

| 事件形式 | 意義 |
| --- | --- |
| `{"step", "total_steps", "progress", "is_final": false}` | 去噪進度。 |
| `{"step", "total_steps", "progress", "image", "is_final": false, "is_preview": true}` | 附帶 base64 PNG 預覽的進度（僅當 `preview_interval` 大於 0）。 |
| `{"step", "progress": 1.0, "image", "is_final": true}` | base64 PNG 的最終圖片，之後接 `data: [DONE]`。 |
| `{"type": "cancelled"}` | 請求被取消（例如透過 `POST /v1/cancel`），之後接 `[DONE]`。 |
| `{"error": {"message", "type"}}` | 串流開始後發生失敗，之後接 `[DONE]`。 |

串流路由只生成一張圖片，不使用 `n` 與 `control_image`。

## 編輯與變體

`POST /v1/images/edits` 與 `POST /v1/images/variations` 可以接收 `multipart/form-data`（OpenAI SDK 的送法：`image` 檔案加文字欄位），也可以接收含 base64 `image` 的 JSON。只會讀取第一個 `image` 檔案；`mask` 與其他檔案會被忽略。圖片超過 25 MB 會回傳 `413`。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `image` | file 或 base64 string | 是 | 來源圖片。 | 支援 |
| `prompt` | string | 編輯：是 | 編輯指示。變體沒有 `prompt` 欄位（傳了也會被忽略）。 | 支援 |
| `model` | string | 否 | 同圖像生成。 | 支援 |
| `n` | integer | 否 | 1 到 10，預設 1。 | 支援 |
| `size` | string | 否 | 同圖像生成。 | 支援 |
| `response_format` | string | 否 | `b64_json`（預設）或 `url`（data URI，不含 `b64_json`）。 | 支援 |
| `num_inference_steps`、`seed` | | 否 | 同圖像生成。 | 擴充 |
| `denoise_strength` | number | 否 | 0 到 1。決定結果可偏離來源圖多遠：編輯預設 0.8，變體預設 0.45。 | 擴充 |
| `mask` | file | 否 | 局部重繪遮罩。 | 接受但忽略 |

編輯是圖生圖：以來源圖片為起點，由 `denoise_strength` 決定結果可以偏離來源多少。這兩個路由沒有以遮罩為基礎的局部重繪。

## OCR

`POST /v1/ocr` 使用 `multipart/form-data`。

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `file` | file | 是 | 圖片，最大 10 MB。可讀取 PNG、JPEG、WebP、TIFF、BMP；檔案會以 Pillow 驗證，不是圖片時回傳 `400`。 |
| `model` | string | 否 | OCR 或 VLM 模型 id。留空表示使用第一個已載入的 OCR 引擎。 |
| `task` | string | 否 | `text`（預設）、`formula` 或 `table`。 |
| `language` | string | 否 | 引導輸出語言的提示。不會做語言偵測。 |

引擎選擇：優先使用已載入的 OCR 類模型（例如 GLM-OCR checkpoint）。沒有的話，會退而使用已載入的視覺語言模型，搭配文字辨識提示詞。兩者都沒有時，伺服器回傳 `503`。

```json
{
  "text": "Invoice 2026-001\nTotal: 120.00",
  "model": "mlx-community/GLM-OCR-bf16",
  "confidence": null,
  "language": null,
  "task": "text",
  "prompt_tokens": 312,
  "completion_tokens": 18,
  "usage": {
    "prompt_tokens": 312,
    "completion_tokens": 18,
    "total_tokens": 330,
    "image_tokens": 290
  }
}
```

`confidence` 一律為 `null`：兩條路徑都不產生信心分數。走 VLM 後備時 `language` 會原樣回傳你給的提示，走 OCR 引擎時為 `null`。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/images/generations \
  -H "Content-Type: application/json" \
  -d '{"model": "Z-Image-Turbo-MLX-4bit", "prompt": "a red bicycle in the rain", "size": "1024x1024", "seed": 7}' \
  | python3 -c "import sys,json,base64; open('out.png','wb').write(base64.b64decode(json.load(sys.stdin)['data'][0]['b64_json']))"

curl http://localhost:8000/v1/images/edits \
  -F image=@out.png \
  -F prompt="make it night" \
  -F denoise_strength=0.6

curl http://localhost:8000/v1/ocr -F file=@receipt.png -F task=text
```

</Tab>
<Tab value="Python">

```python
import base64
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

img = client.images.generate(
    model="Z-Image-Turbo-MLX-4bit",
    prompt="a red bicycle in the rain",
    size="1024x1024",
    response_format="b64_json",
)
with open("out.png", "wb") as f:
    f.write(base64.b64decode(img.data[0].b64_json))

with open("out.png", "rb") as f:
    edited = client.images.edit(
        model="Z-Image-Turbo-MLX-4bit",
        image=f,
        prompt="make it night",
        response_format="b64_json",
    )
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";
import fs from "node:fs";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "not-needed" });

const img = await client.images.generate({
  model: "Z-Image-Turbo-MLX-4bit",
  prompt: "a red bicycle in the rain",
  size: "1024x1024",
  response_format: "b64_json",
});
fs.writeFileSync("out.png", Buffer.from(img.data[0].b64_json!, "base64"));
```

</Tab>
</Tabs>

## 錯誤

錯誤使用 OpenAI 的格式 `{"error": {"message", "type", "param", "code"}}`。

| 狀態碼 | 情況 |
| --- | --- |
| `400` | `prompt` 或 `image` 為空白、`size` 無法解析或不是介於 64 到 2048 的 64 倍數、`response_format` 不合法、base64 無效、OCR 上傳的不是圖片。 |
| `404` | 沒有符合 `model` 的圖像生成模型，或該模型屬於其他模態。 |
| `413` | 圖片上傳超過 25 MB（OCR：超過 10 MB）。 |
| `501` | 僅圖像生成：已載入的圖像模型使用管線無法執行的佈局（扁平的 Lance/Wan 類 checkpoint）。編輯與變體遇到同樣情況會回傳 `500`。 |
| `503` | OCR：沒有載入 OCR 或視覺語言模型。 |
| `507` | GPU 記憶體不足。 |
| `500` | 生成、編輯、變體或 OCR 失敗。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 文生圖，`b64_json` 與 data URI 形式的 `url` | <Support status="supported">支援</Support> |
| 串流進度與預覽 | <Support status="extension">Yunshu 擴充</Support> |
| 圖像編輯與變體（圖生圖） | <Support status="partial">沒有遮罩局部重繪</Support> |
| 代管的 `url` 連結 | <Support status="unsupported">僅提供 data URI</Support> |
| 控制圖引導 | <Support status="extension">Yunshu 擴充</Support> |
| `gpt-image-1` 選項（`quality`、`background`、`output_format`） | <Support status="unsupported">被忽略</Support> |
| Lance/Wan 類圖像 checkpoint | <Support status="unsupported">501</Support> |
| 使用 OCR 模型或 VLM 後備的 OCR | <Support status="supported">支援</Support> |

## 相關頁面

- [模型](/docs/getting-started/models)：載入圖像與 OCR 模型。
- [Chat Completions](/docs/api/chat-completions)：改把圖片送給視覺語言模型。
- [擴充](/docs/api/extensions)：取消執行中的請求。


---

<!-- api/mcp -->
---
title: MCP
description: Yunshu 作為 MCP 伺服器（透過 HTTP 的 JSON-RPC），提供產生、語音與圖片工具，以及回報 MCP 用戶端連線池的路由。
---

Yunshu 在兩個方向上支援 Model Context Protocol。

- 作為 **MCP 伺服器**，`POST /v1/mcp` 接受 JSON-RPC 2.0 請求，並把本機模型以工具的形式提供出來：文字產生、語音合成與圖片生成。任何支援 MCP 的代理程式都能這樣使用你的本機模型。
- 作為 **MCP 用戶端**，Yunshu 可以在啟動時連到你設定的 MCP 工具伺服器，並透過兩個唯讀路由回報找到的內容。

在 Messages 或 Responses 請求中呼叫遠端 MCP 伺服器（`mcp_servers` 與 `mcp` 工具功能）是另一項功能，見[伺服器端工具](/docs/api/server-tools)。

<Endpoint method="POST" path="/v1/mcp" />
<Endpoint method="GET" path="/v1/mcp/sse" />
<Endpoint method="GET" path="/v1/mcp/tools" />
<Endpoint method="GET" path="/v1/mcp/client/status" />
<Endpoint method="GET" path="/v1/mcp/client/tools" />

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證；請送出 `Authorization: Bearer <token>` 或 `x-api-key`。`POST /v1/mcp` 上的驗證或權限失敗，會以 JSON-RPC 錯誤物件（code `-32600`）加上 HTTP 狀態碼回傳，讓 MCP 用戶端能解析。限定只能使用特定模型的金鑰，在使用 `generate`、`synthesize_speech` 與 `generate_image` 工具時也會被檢查。
</Callout>

## MCP 伺服器

### 實作的協定

- 傳輸：每個 `POST /v1/mcp` 帶一則 JSON-RPC 2.0 訊息，以單一 `application/json` 回應作答。不支援批次陣列（會回傳錯誤物件）。伺服器是無狀態的：不發放 session id，也不保留每個用戶端的狀態。
- 沒有 `id` 的訊息是通知，回應 `204 No Content`。明確寫成 `id: null` 的視為請求。
- `initialize` 回報 `protocolVersion` 為 `2024-11-05`、`serverInfo` 為 `{"name": "yunshu", "version": ...}`，以及 `tools`、`resources`、`prompts` 能力（都沒有 `listChanged` 或 `subscribe`）。
- 由伺服器主動發起的訊息（sampling、roots、logging、進度通知、資源訂閱）尚未實作。

方法：

| 方法 | 行為 |
| --- | --- |
| `initialize` | 回傳上述能力。 |
| `notifications/initialized` | 接受。 |
| `ping` | 回傳 `{}`。 |
| `tools/list` | 列出下列工具，以及嵌入程式碼在行程內註冊的任何工具。 |
| `tools/call` | 執行工具。未知的工具：錯誤 `-32601`。 |
| `resources/list` | 每個已註冊的模型一筆資源，`yunshu://models/<model id>`，MIME 為 `application/json`。單模型模式下為空。 |
| `resources/read` | 讀取上述 URI（以 JSON 文字回傳模型資訊）。未知的 URI：錯誤 `-32602`。 |
| `prompts/list`、`prompts/get` | 四個內建提示範本：`summarize`（`text`）、`translate`（`text`、`target_language`）、`code_review`（`code`、`language`）與 `explain`（`concept`）。缺少必要引數：錯誤 `-32602`。 |

其他方法回傳錯誤 `-32601`（找不到方法）。JSON 無效是 `-32700`，封包格式錯誤是 `-32600`，參數錯誤是 `-32602`，非預期的失敗是 `-32603`，訊息固定為 `Internal error`。

### 工具

| 工具 | 引數 | 結果 |
| --- | --- | --- |
| `generate` | `model`（schema 中為必填；省略時使用預設模型）、`messages`（`{role, content}` 陣列，必填）、`max_tokens`（512）、`temperature`（0.7）、`top_p`、`top_k`、`min_p`、`repetition_penalty`、`frequency_penalty`、`presence_penalty`、`enable_thinking`、`seed`、`stop` | 一個 `text` 內容項目，內容為產生的文字。 |
| `synthesize_speech` | `text`（必填）、`voice`（預設 `alloy`） | 一個 `text` 項目與一個 `audio` 項目（base64 WAV，`audio/wav`）。需要多模型模式並已載入 TTS 模型。 |
| `generate_image` | `prompt`（必填）、`width`、`height`（預設 512）、`num_inference_steps`（預設 4）、`seed` | 一個 `image` 項目（base64 PNG，`image/png`）與一個 `text` 項目。需要多模型模式並已載入圖片模型。 |

結果採標準格式 `{"content": [...], "isError": false}`。工具執行時失敗（模型未載入、引擎錯誤）是一般結果，帶有 `isError: true`，訊息在 `text` 項目中；缺少必要引數則是 JSON-RPC 錯誤 `-32602`。文字與 base64 內容會在約 1 MB 處截斷。

`generate` 的引數比 Chat Completions 少：沒有工具、沒有串流，也沒有結構化輸出。需要這些功能請用 [Chat Completions](/docs/api/chat-completions)。

### 範例

<Tabs items={["curl", "Python"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
       "params": {"name": "generate",
                  "arguments": {"model": "local", "max_tokens": 64,
                                "messages": [{"role": "user", "content": "Say hello."}]}}}'
```

</Tab>
<Tab value="Python">

```python
import httpx

def rpc(method, params=None, id=1):
    r = httpx.post(
        "http://localhost:8000/v1/mcp",
        headers={"Authorization": "Bearer sk-local"},
        json={"jsonrpc": "2.0", "id": id, "method": method, "params": params or {}},
        timeout=120,
    )
    return r.json()

print(rpc("initialize")["result"]["serverInfo"])
print([t["name"] for t in rpc("tools/list")["result"]["tools"]])
out = rpc("tools/call", {"name": "generate", "arguments": {"messages": [{"role": "user", "content": "Hi"}]}})
print(out["result"]["content"][0]["text"])
```

</Tab>
</Tabs>

`tools/call` 的回應：

```json
{ "jsonrpc": "2.0", "id": 1, "result": { "content": [{ "type": "text", "text": "Hello!" }], "isError": false } }
```

### REST 探索

`GET /v1/mcp/tools` 回傳與 `tools/list` 相同的工具清單，但沒有 JSON-RPC 外層：`{"tools": [{name, description, inputSchema}]}`。

`GET /v1/mcp/sse` 開啟一條 Server-Sent Events 串流，先送出一次 `event: endpoint`，內容為 `data: /v1/mcp`，之後大約每 15 秒送出一次 `event: ping`，直到用戶端中斷連線。它只負責宣告該往哪裡 POST：回應仍然在每個 `POST /v1/mcp` 的本文中，而不是這條串流。因此期待在事件串流上收到回覆的舊式 HTTP+SSE 用戶端會收不到；請使用接受 POST 回傳純 JSON 回應的用戶端。

### 連接用戶端

支援 HTTP 伺服器、且接受每次 POST 以 JSON 回覆的 MCP 用戶端，可以把 `http://localhost:8000/v1/mcp` 當成伺服器 URL；開啟驗證時，以 `Authorization` 標頭帶上 bearer token。Claude Code 的作法是 `claude mcp add` 的 HTTP 傳輸；Codex 與其他代理程式在各自的 MCP 設定中有對應的選項。由於伺服器實作的是協定版本 `2024-11-05` 與上述工具，預期的用途是「把我的本機模型當成工具來呼叫」，而不是取代代理程式自己的工具。以 Yunshu 作為模型端點的程式開發代理程式（見[代理程式](/docs/guides/agents)）並不需要這個伺服器：它們自己連到自己的 MCP 伺服器，工具會以一般函式工具的形式交給模型。

## MCP 用戶端連線池

Yunshu 可以在啟動時連到 MCP 工具伺服器，來源可以是檔案（`YUNSHU_MCP_CONFIG`），也可以是 `YUNSHU_MCP_SERVERS` 中的 JSON 陣列。檔案內容是 `{"mcpServers": {"<id>": {...}}}` 或 `{"servers": [...]}`。每個項目：

| 鍵 | 說明 |
| --- | --- |
| `id`／`name` | 伺服器 id（`mcpServers` 為物件時，就是鍵名）。 |
| `transport` | `stdio`（預設）、`sse` 或 `streamable_http`。 |
| `command`、`args` | `stdio` 要啟動的行程。 |
| `url`、`headers` | `sse` 與 `streamable_http` 的端點與標頭。 |
| `enabled` | 預設為 `true`。 |

伺服器只在啟動時連線一次（修改設定後需要重新啟動），連線失敗的伺服器會被略過。非串流的 Chat Completions 回應中，若有工具呼叫的名稱符合連線池中的工具，Yunshu 會執行它，並把輸出以 `mcp_tool_results`（`{tool_call_id, output}` 清單）加到回應本文；結果不會自動回饋給模型，而且只有請求自己宣告了某個工具，模型才會看到它。不符合任何連線池工具的工具呼叫，照常回傳給你的用戶端。

### 狀態與工具

`GET /v1/mcp/client/status`：

```json
{
  "enabled": true,
  "connected_servers": 1,
  "total_tools": 3,
  "servers": { "files": { "connected": true, "tools": 3 } }
}
```

沒有設定連線池時回傳 `{"enabled": false, "connected_servers": 0, "total_tools": 0}`。

`GET /v1/mcp/client/tools` 回傳 `{"tools": [{name, description, server_id, input_schema}], "openai_format": [{type: "function", function: {name, description, parameters}}]}`；沒有連線池時兩個清單都是空的。`openai_format` 清單可以直接當作 Chat Completions 請求的 `tools` 使用。

## 錯誤

| 情況 | 結果 |
| --- | --- |
| JSON 無效 | HTTP 200，JSON-RPC 錯誤 `-32700`。 |
| 不是 JSON 物件、封包格式錯誤、`jsonrpc` 不對 | JSON-RPC 錯誤 `-32600`。 |
| 未知的方法或工具 | JSON-RPC 錯誤 `-32601`。 |
| 缺少或無效的參數 | JSON-RPC 錯誤 `-32602`。 |
| 非預期的失敗 | JSON-RPC 錯誤 `-32603`，訊息 `Internal error`。 |
| 驗證或權限失敗 | JSON-RPC 錯誤 `-32600`，HTTP `401` 或 `403`。 |
| 工具執行了但失敗 | `isError: true` 的結果。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| `POST /v1/mcp` 的 `initialize`、工具、資源、提示、`ping` | <Support status="supported">支援</Support> |
| `generate`、`synthesize_speech`、`generate_image` 工具 | <Support status="supported">支援（後兩者需要已載入的 TTS 或圖片模型）</Support> |
| Session、JSON-RPC 批次、伺服器對用戶端的請求、進度、訂閱 | <Support status="unsupported">尚未支援</Support> |
| 在舊式 SSE 串流上回覆 | <Support status="unsupported">尚未支援（回覆在 POST 本文中）</Support> |
| MCP 用戶端連線池（stdio、SSE、streamable HTTP）、狀態路由 | <Support status="partial">啟動時設定；結果只回報，不回饋給模型</Support> |

## 相關頁面

- [伺服器端工具](/docs/api/server-tools)
- [代理程式](/docs/guides/agents)
- [Chat Completions](/docs/api/chat-completions)
- [設定](/docs/guides/configuration)


---

<!-- api/messages -->
---
title: Messages
description: Anthropic Messages API，支援工具、思考、圖片、含引用的文件、token 計數與訊息批次。
---

Yunshu 在 `POST /v1/messages`（也可用 `POST /messages`）提供 Anthropic Messages API，在 `POST /v1/messages/count_tokens` 提供 token 計數，並在 `/v1/messages/batches` 提供 Message Batches。官方 `anthropic` Python 與 TypeScript SDK 只要把 `base_url` 指向伺服器根路徑（不加 `/v1`）即可使用。Claude Code 等使用 Anthropic 規格的代理程式也是以同樣方式連線（見[代理程式](/docs/guides/agents)）。

請求會被轉換成與 [Chat Completions](/docs/api/chat-completions) 相同的引擎路徑，因此本機模型、前綴快取與受限解碼都是共用的。伺服器端工具（`web_search_20250305`、`web_fetch_20250910`、MCP 連接器）請見[伺服器端工具](/docs/api/server-tools)。

<Endpoint method="POST" path="/v1/messages" />
<Endpoint method="POST" path="/messages" />
<Endpoint method="POST" path="/v1/messages/count_tokens" />
<Endpoint method="POST" path="/messages/count_tokens" />
<Endpoint method="POST" path="/v1/messages/batches" />
<Endpoint method="GET" path="/v1/messages/batches" />
<Endpoint method="GET" path="/v1/messages/batches/{batch_id}" />
<Endpoint method="POST" path="/v1/messages/batches/{batch_id}/cancel" />
<Endpoint method="DELETE" path="/v1/messages/batches/{batch_id}" />
<Endpoint method="GET" path="/v1/messages/batches/{batch_id}/results" />

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。Anthropic SDK 以 `x-api-key` 送出金鑰，伺服器接受它來取代 `Authorization: Bearer`。單模型模式下 `model` 欄位僅供參考：已載入的模型會回應任何名稱（例如 `claude-sonnet-4-5`），回應中會原樣帶回你送出的名稱。多模型模式下，可用 `YUNSHU_MODEL_ALIASES` 把這類名稱對應到實際提供的模型。
</Callout>

## 標頭

| 標頭 | 行為 |
| --- | --- |
| `x-api-key` | 設定了 `YUNSHU_AUTH_TOKEN` 時，視為 bearer token。 |
| `Authorization: Bearer ...` | 同樣接受。 |
| `anthropic-version` | 任何用戶端都接受；不驗證其值，也不會改變行為。 |
| `anthropic-beta` | 接受，但不必要。MCP 連接器、結構化輸出、Files API 等 beta 功能由請求本文驅動，而不是這個標頭。 |

## 請求

### 核心欄位

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | 模型 id；單模型模式下僅供參考。 | 支援 |
| `messages` | array | 是 | 非空的 `{role, content}` 清單。`content` 是字串或區塊清單。位於開頭或對話中的 `system` 角色項目會被提升到系統提示。 | 支援 |
| `max_tokens` | integer | 否 | 1 到 1048576。與 Anthropic API 相同為必填：省略會回 `400` `invalid_request_error`（`max_tokens: Field required`）。 | 支援 |
| `system` | string 或文字區塊陣列 | 否 | 系統提示。區塊可帶 `cache_control`。 | 支援 |
| `temperature` | number | 否 | 0 到 2。省略時預設 0.7。 | 支援 |
| `top_p`、`top_k` | number、integer | 否 | `top_p` 為 0 到 1（預設 1.0）；`top_k` 為 0 表示停用。 | 支援 |
| `stop_sequences` | array of string | 否 | 最多 16 個非空字串。命中時回合結束，`stop_reason` 為 `"stop_sequence"`，命中的字串放在 `stop_sequence`。 | 支援 |
| `stream` | boolean | 否 | Server-Sent Events。 | 支援 |
| `metadata` | object | 否 | 接受。 | 接受但忽略 |
| `service_tier`、`container` | string、object | 否 | 接受，讓 SDK 的請求能通過驗證。 | 接受但忽略 |
| `context_management` | object | 否 | 上下文編輯：`{"edits": [...]}`，支援 `clear_tool_uses_20250919`（`trigger` 以輸入 token 或工具使用次數觸發，另有 `keep`、`clear_at_least`、`exclude_tools`、`clear_tool_inputs`）與 `clear_thinking_20251015`（`keep`，只能是第一個 edit）。被清除的工具結果會變成 `[cleared]`。回應帶有 `context_management.applied_edits`（串流時在 `message_delta`）；`count_tokens` 回傳 `context_management.original_input_tokens`。`compact_20260112`（伺服器端壓縮）：輸入超過 `trigger`（預設 `150000`、最小 `50000` 輸入 token）時，由所服務的模型以和 Responses 壓縮相同的機制摘要較早的輪次（`YUNSHU_COMPACT_MAX_TOKENS` 限制摘要長度）；回覆以 `compaction` 區塊開頭（串流為 `compaction_delta`，`usage.iterations` 列出壓縮與訊息兩段），`instructions` 可引導摘要。`pause_after_compaction` 只回傳該區塊，`stop_reason` 為 `compaction`。把區塊送回後，其前的內容全部捨棄；`content` 為 null 的區塊視為不做事。`count_tokens` 不會壓縮。未知的 edit 類型回應 `400`。 | 支援 |

### 思考

| 參數 | 說明 | 狀態 |
| --- | --- | --- |
| `thinking: {"type": "enabled", "budget_tokens": N}` | 開啟思考並設定預算。`budget_tokens` 必須是小於 `max_tokens` 的正整數，否則 `400`。推理內容以 `thinking` 內容區塊回傳。 | 支援 |
| `thinking: {"type": "disabled"}` | 關閉思考。 | 支援 |
| `thinking: {"type": "adaptive"}` | 沿用模型範本的預設。 | 支援 |
| 沒有 `thinking` 欄位 | 思考關閉，與 Anthropic API 相同（思考需主動開啟）。 | 支援 |
| `output_config.effort` | 對應到範本的推理強度。`reasoning_effort` 是 Yunshu 的寫法。 | 支援 |

思考能力取決於載入的模型。對於聊天範本本身不會思考的模型，`enabled` 會加入一段要求用 `<think>` 標籤包住推理的指示，並限制回覆開頭照做，因此仍會回傳 `thinking` 區塊。強制的 `tool_choice`（`any` 或 `tool`）會關閉思考，因為 Anthropic 也不允許兩者並用。思考區塊的 `signature` 為空字串；沒有 redacted thinking 區塊。

### 工具

| 參數 | 型別 | 說明 | 狀態 |
| --- | --- | --- | --- |
| `tools` | array | 自訂工具 `{name, description, input_schema}`。 | 支援 |
| `tool_choice` | object 或 string | `{"type": "auto"}`、`{"type": "any"}`、`{"type": "tool", "name": "..."}`、`{"type": "none"}`。`disable_parallel_tool_use: true` 會把回覆限制為一次呼叫。強制選擇透過受限解碼落實；呼叫了非指定工具的結果會被丟棄。 | 支援 |
| `tools[].cache_control` | object | 參與快取計算（見下）。 | 支援 |
| `bash_*`、`text_editor_*`、`memory_*`、`computer_*` 等型別工具 | object | 只以 `type` 與 `name` 宣告。Yunshu 會補上文件記載的 `input_schema`，讓本機模型能產生有效的 `tool_use`；由你的用戶端執行工具並送回 `tool_result`。`computer_*` 支援 `display_width_px`、`display_height_px`、`display_number` 與 `enable_zoom`。較新的 `computer_toolset_20260801` 協定尚未實作。 | 部分支援 |
| `web_search_*`、`web_fetch_*`、`mcp_toolset` 與頂層 `mcp_servers` | array | 由伺服器執行。見[伺服器端工具](/docs/api/server-tools)。 | 支援 |
| `code_execution_*` 與其他託管工具 | | 無法使用。 | 尚未支援 |

用戶端工具的結果與官方 API 一樣，以使用者訊息中的 `tool_result` 區塊送回。`tool_result` 可包含文字與圖片區塊。

### 內容區塊

| 區塊 | 說明 | 狀態 |
| --- | --- | --- |
| `text` | 純文字，可帶 `cache_control`。 | 支援 |
| `image` | `source` 類型為 `base64`（png、jpeg、gif、webp）、`url`（會依 SSRF 規則檢查；私有位址與非 HTTP(S) 的 URL 是 `400`）或 `file`（[檔案](/docs/api/files) id）。需要視覺語言模型；純文字模型會回 `400`。 | 支援 |
| `document` | `source` 類型為 `text`（`text/plain`）、`content`（文字與圖片區塊）、`base64` PDF（最大 32 MiB、100 頁、不得加密）、`url`（PDF；會擋掉私有位址）或 `file`。支援 `title`、`context` 與 `citations: {"enabled": true}`。會讀取文字層；視覺模型還會收到頁面影像，只有影像的 PDF 需要視覺模型。擷取出的文字上限為 200 萬字元。 | 支援 |
| `tool_use`、`tool_result` | 用戶端工具往返。 | 支援 |
| `thinking` | 推理模型會回傳；也接受放回助理回合。 | 支援 |
| `server_tool_use`、`web_search_tool_result`、`web_fetch_tool_result`、`mcp_tool_use`、`mcp_tool_result` | 由伺服器端工具回傳；也接受放回歷史。 | 支援 |
| `search_result`、`container_upload`、`redacted_thinking` | 不會解讀。 | 尚未支援 |

#### 引用

`document` 區塊設了 `citations: {"enabled": true}` 時，模型會看到附有精確字元位移的文件，並被要求標記來源。標記會對照真實文件驗證，再轉成公開格式：`char_location`（文字）、`page_location`（PDF）或 `content_block_location`（content 文件），各自帶 `cited_text`、`document_index` 與 `document_title`。標記超出文件範圍，或引用了未啟用引用的文件時，請求會以 `502` 失敗（串流時為 SSE `error` 事件），而不是回傳捏造的引用。串流中，引用以 `citations_delta` 事件送達。引用品質取決於本機模型是否遵循標記指示。

### 結構化輸出與引擎控制

| 參數 | 說明 | 狀態 |
| --- | --- | --- |
| `output_config.format` / `output_format` | `{"type": "json_schema", "schema": {...}}` 把解碼限制在該 schema。 | 支援 |
| `cache_control`（頂層、區塊層級） | 標記前綴快取斷點（見下）。 | 支援 |
| `json_schema`、`response_format`、`grammar` | Yunshu 的受限解碼擴充（`json_object`、`json_schema`；`regex`、`choice`、`cfg` 文法）。 | 擴充 |
| `min_p`、`repetition_penalty`、`frequency_penalty`、`presence_penalty`、`logit_bias`、`seed`、`stop_token_ids`、`min_tokens`、`ignore_eos`、`suppress_tokens`、`xtc_probability`、`xtc_threshold`、`logprobs`、`top_logprobs`、`lora_adapter`、`spec_decode`、`priority`、`timeout` | 與其他路由共用的引擎控制。 | 擴充 |

### 提示快取

在系統區塊、訊息、工具定義或文件上加 `cache_control: {"type": "ephemeral"}`，可標記快取斷點。Yunshu 的前綴快取是自動的；這些提示告訴它持久斷點在哪裡。用量會回報拆分：`cache_read_input_tokens` 是重用的前綴，`cache_creation_input_tokens` 是這個回合寫入的可快取前綴（到最後一個斷點為止），`input_tokens` 是其餘部分，三者相加等於提示長度。見[提示快取](/docs/guides/prompt-caching)。

## 範例

<Tabs items={["curl", "Python", "TypeScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: sk-local" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "local",
    "max_tokens": 256,
    "system": "You are concise.",
    "messages": [{"role": "user", "content": "Name three primary colors."}]
  }'
```

</Tab>
<Tab value="Python">

```python
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:8000", api_key="sk-local")

message = client.messages.create(
    model="local",
    max_tokens=256,
    messages=[{"role": "user", "content": "Name three primary colors."}],
)
print(message.content[0].text)
print(message.usage.input_tokens, message.usage.output_tokens)
```

</Tab>
<Tab value="TypeScript">

```ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({ baseURL: "http://localhost:8000", apiKey: "sk-local" });

const stream = client.messages.stream({
  model: "local",
  max_tokens: 256,
  messages: [{ role: "user", content: "Write a haiku about rain." }],
});
stream.on("text", (t) => process.stdout.write(t));
const final = await stream.finalMessage();
console.log(final.stop_reason);
```

</Tab>
</Tabs>

### 工具使用

```python
tools = [{
    "name": "get_weather",
    "description": "Current weather for a city",
    "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}]
msgs = [{"role": "user", "content": "Weather in Taipei?"}]
r1 = client.messages.create(model="local", max_tokens=512, tools=tools, messages=msgs)
use = next(b for b in r1.content if b.type == "tool_use")
msgs += [
    {"role": "assistant", "content": r1.content},
    {"role": "user", "content": [{"type": "tool_result", "tool_use_id": use.id, "content": "24 C, clear"}]},
]
r2 = client.messages.create(model="local", max_tokens=512, tools=tools, messages=msgs)
print(r2.content[0].text)
```

### 圖片

```python
import base64

data = base64.b64encode(open("photo.png", "rb").read()).decode()
r = client.messages.create(
    model="local",
    max_tokens=200,
    messages=[{
        "role": "user",
        "content": [
            {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": data}},
            {"type": "text", "text": "What is in this picture?"},
        ],
    }],
)
```

### 含引用的文件

```python
r = client.messages.create(
    model="local",
    max_tokens=300,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "document",
                "source": {"type": "text", "media_type": "text/plain", "data": "The moon orbits Earth every 27.3 days."},
                "title": "Moon facts",
                "citations": {"enabled": True},
            },
            {"type": "text", "text": "How long is the moon's orbit?"},
        ],
    }],
)
for block in r.content:
    print(block.text, getattr(block, "citations", None))
```

### 思考

```python
r = client.messages.create(
    model="local",
    max_tokens=2048,
    thinking={"type": "enabled", "budget_tokens": 1024},
    messages=[{"role": "user", "content": "Is 91 prime?"}],
)
for block in r.content:
    print(block.type)  # thinking, then text
```

### 計算 token

```python
n = client.messages.count_tokens(
    model="local",
    messages=[{"role": "user", "content": "Hello"}],
)
print(n.input_tokens)
```

## 回應

```json
{
  "id": "msg_4f1c2a7e9b3d4c5a6e7f8091",
  "type": "message",
  "role": "assistant",
  "model": "local",
  "content": [
    { "type": "text", "text": "Red, yellow and blue." }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 21,
    "output_tokens": 8,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  }
}
```

`stop_reason` 為 `end_turn`、`max_tokens`（產生因逾時或記憶體保護而中斷時也用這個值）、`stop_sequence`、`tool_use`，或 `pause_turn`（伺服器端工具迴圈達到迭代上限；見[伺服器端工具](/docs/api/server-tools)）。模型有推理時，會有 `usage.output_tokens_details.reasoning_tokens`。伺服器端工具請求另有 `usage.server_tool_use`。

### 計算 token

`POST /v1/messages/count_tokens` 接受與 `POST /v1/messages` 相同的本文，回傳 `{"input_tokens": N}`。它的提示轉譯方式與產生時相同（系統提示含被提升的 `system` 訊息、工具、思考指示、文件、檔案），並透過聊天範本計算，因此數字會與實際呼叫的 `input_tokens` 一致。每張圖片以固定估計值 576 個 token 計算。

### 訊息批次

批次由背景工作程序執行，該程序透過 loopback 呼叫本伺服器，並在重新啟動後恢復。`POST /v1/messages/batches` 接受 `{"requests": [{"custom_id", "params"}]}`，其中 `params` 是一般的 Messages 本文（`model`、`max_tokens`、`messages` 必填）；`custom_id` 必須符合 `^[a-zA-Z0-9_-]{1,64}$` 且不得重複，最多 100000 個請求。批次物件的 `type` 為 `message_batch`，並有 `processing_status`（`in_progress`、`canceling`、`ended`）、`request_counts`、時間戳與 `results_url`。列表可用 `limit`（1-1000）、`after_id`、`before_id`。結果（`GET .../results`）為 JSONL，批次結束後才能取得（之前是 `409`）。取消已結束的批次，或刪除仍在處理的批次，都是 `400`。OpenAI 風格的批次 API 見[批次](/docs/api/batches)。

## 串流

`stream: true` 時，伺服器依 Anthropic 的順序送出 Server-Sent Events：

1. `message_start`（`content` 為空的訊息，以及提示的 `usage`）
2. 每個區塊：`content_block_start`、一個以上的 `content_block_delta`、`content_block_stop`。delta 類型有 `thinking_delta`（思考區塊先出現）、`text_delta`、`input_json_delta`（工具引數，以部分 JSON 串流）與 `citations_delta`（含引用的文件、伺服器端工具結果）。
3. `message_delta`，含 `delta.stop_reason`、`delta.stop_sequence` 與累計的 `usage`
4. `message_stop`

長提示預填期間會送出 `: keep-alive` 註解行，讓讀取逾時較短的用戶端保持連線。串流開始後的失敗是單一的 `event: error`，內容為 `{"type": "error", "error": {"type", "message"}}`，之後不會再有 `message_delta` 或 `message_stop`。中斷連線會取消產生。

## 錯誤

錯誤使用 Anthropic 的格式；這些路徑上由驗證與限流層產生的拒絕也是如此：

```json
{ "type": "error", "error": { "type": "invalid_request_error", "message": "messages: field is required and cannot be empty" } }
```

| 狀態 | `error.type` | 原因 |
| --- | --- | --- |
| `400` | `invalid_request_error` | 本文無效（`messages` 為空、`thinking.budget_tokens` 不小於 `max_tokens`、`stop_sequences` 超過 16 個）、提示超出上下文視窗、把圖片送給純文字模型、被擋掉的 URL、無法讀取的文件、模型不支援所要求的功能。 |
| `401` | `authentication_error` | 設定了 `YUNSHU_AUTH_TOKEN` 時，金鑰缺少或錯誤。 |
| `403` | `permission_error` | 金鑰沒有該模型的權限。 |
| `404` | `not_found_error` | 多模型模式下未知的模型，或未知的檔案 id、批次 id。 |
| `413` | `request_too_large` | 提示太大無法預填，或文件過大。 |
| `429` | `rate_limit_error` | 觸發了已設定的限制。 |
| `500` | `api_error` | 內部錯誤。 |
| `502` | `api_error` | 模型產生的文件引用未通過驗證。 |
| `503` / `529` | `overloaded_error` | 沒有載入模型，或伺服器已滿載。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| Messages，串流與非串流 | <Support status="supported">支援</Support> |
| `count_tokens` | <Support status="supported">支援</Support> |
| 訊息批次 | <Support status="supported">支援</Support> |
| 工具、`tool_choice`、平行工具呼叫控制 | <Support status="supported">支援</Support> |
| `bash`、`text_editor`、`memory`、`computer` 用戶端工具 | <Support status="partial">提供 schema；由用戶端執行</Support> |
| `thinking` enabled、disabled、adaptive | <Support status="supported">支援</Support> |
| 圖片（base64、url、file） | <Support status="supported">支援（需視覺模型）</Support> |
| 文件與引用 | <Support status="supported">支援</Support> |
| 伺服器端工具：網路搜尋、網頁擷取、MCP 連接器 | <Support status="supported">支援</Support> |
| `cache_control` | <Support status="partial">提示與計算；快取本身是自動的</Support> |
| `metadata`、`service_tier`、`container` | <Support status="partial">接受但忽略</Support> |
| `context_management`（`clear_tool_uses`、`clear_thinking`） | <Support status="supported">已套用並回報 `applied_edits`</Support> |
| 程式碼執行、託管的記憶工具、`search_result` 區塊、簽名或 redacted thinking | <Support status="unsupported">尚未支援</Support> |

## 相關頁面

- [伺服器端工具](/docs/api/server-tools)
- [Chat Completions](/docs/api/chat-completions)
- [檔案](/docs/api/files)
- [批次](/docs/api/batches)
- [代理程式](/docs/guides/agents)
- [提示快取](/docs/guides/prompt-caching)


---

<!-- api/models -->
---
title: 模型
description: 列出並查詢提供服務的模型，模型卡同時涵蓋 OpenAI、Anthropic、OpenRouter、vLLM 與 LM Studio 方言；並說明多模型模式下的載入與卸載。
---

`GET /v1/models` 回傳這台伺服器可提供的模型。每個項目都是依磁碟上的檢查點檔案（設定檔、聊天模板、safetensors 標頭）推導出的模型卡，所以回答的是載入的權重實際能做什麼，而不是名稱讓人猜測的功能。同一個項目同時帶有多個生態系的欄位名稱，OpenAI、Anthropic、OpenRouter、vLLM 與 LM Studio 的用戶端都能找到自己要的欄位。Yunshu 自己的詳細資訊都放在單一的 `yunshu` 鍵底下。

<Endpoint method="GET" path="/v1/models" />
<Endpoint method="GET" path="/v1/models/{model_id}" />
<Endpoint method="POST" path="/v1/models/load" />
<Endpoint method="POST" path="/v1/models/unload/{model_id}" />

<Callout type="info">
只有在設定 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。列出與查詢模型在沒有 token 時是開放的。載入與卸載屬於操作性路由：需要已設定的 token（或 `YUNSHU_AUTH_DISABLED=true`），見[載入與卸載](#載入與卸載)。
</Callout>

## 列出模型

`GET /v1/models` 沒有參數。回應是同時符合 OpenAI 與 Anthropic SDK 清單型別的 list 物件。

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/models -H "Authorization: Bearer sk-local"
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")
for m in client.models.list():
    print(m.id)

import anthropic

a = anthropic.Anthropic(base_url="http://localhost:8000", api_key="sk-local")
for m in a.models.list():
    print(m.id, m.display_name, m.max_input_tokens)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "sk-local" });
const models = await client.models.list();
for (const m of models.data) console.log(m.id);
```

</Tab>
</Tabs>

節錄的一個項目：

```json
{
  "object": "list",
  "data": [
    {
      "id": "mlx-community/Qwen3.5-0.8B-MLX-bf16",
      "object": "model",
      "created": 1760000000,
      "owned_by": "yunshu",
      "type": "model",
      "display_name": "Qwen3.5-0.8B-MLX-bf16",
      "created_at": "2025-10-09T08:53:20Z",
      "max_input_tokens": 262144,
      "max_tokens": 131072,
      "capabilities": {
        "thinking": { "supported": true, "types": { "adaptive": { "supported": false }, "enabled": { "supported": true } } },
        "image_input": { "supported": true },
        "structured_outputs": { "supported": true },
        "vision": true,
        "tools": true
      },
      "context_length": 262144,
      "max_model_len": 262144,
      "task": "generate",
      "state": "loaded",
      "compatibility_type": "mlx",
      "yunshu": {
        "kind": "vlm",
        "family": "qwen3_5",
        "input_modalities": ["text", "image"],
        "output_modalities": ["text"],
        "contract": { "unsupported_fields": "400" }
      }
    }
  ],
  "has_more": false,
  "first_id": "mlx-community/Qwen3.5-0.8B-MLX-bf16",
  "last_id": "mlx-community/Qwen3.5-0.8B-MLX-bf16"
}
```

數值僅為示意，也省略了許多欄位；真實的項目帶有下表列出的所有欄位。多模型模式下，清單包含所有已註冊的模型，不論是否已載入；單模型模式下只有載入的那一個模型。沒有分頁：`has_more` 永遠是 `false`。

### 項目內容

| 方言 | 欄位 |
| --- | --- |
| OpenAI | `id`、`object`（`"model"`）、`created`、`owned_by`（`"yunshu"`） |
| Anthropic | `type`（`"model"`）、`display_name`、`created_at`、`max_input_tokens`、`max_tokens`、`capabilities` |
| OpenRouter | `name`、`canonical_slug`、`description`、`context_length`、`architecture`（`modality`、`input_modalities`、`output_modalities`、`tokenizer`）、`pricing`（全是 `"0"`）、`top_provider`、`supported_parameters`、`default_parameters` |
| vLLM | `root`、`parent`、`max_model_len`、`task`（`generate`、`embed`、`score`、`transcription`、`speech`、`image_generation`、`ocr`） |
| LM Studio | `arch`、`quantization`、`state`（`loaded` 或 `not-loaded`）、`max_context_length`、`publisher`、`compatibility_type`（`"mlx"`）、`model_type` |
| Yunshu | `yunshu`：完整的模型卡，說明如下 |

Anthropic 的 `capabilities` 物件包含 Anthropic SDK 模型要求的所有鍵（`batch`、`citations`、`code_execution`、`context_management`、`effort`、`image_input`、`pdf_input`、`structured_outputs`、`thinking`），其 `supported` 旗標來自模型卡。LM Studio 與 vLLM 用戶端使用的扁平布林值（`vision`、`trained_for_tool_use`、`tools`、`function_calling`、`reasoning`、`embedding`）也放在同一個物件內。

### `yunshu` 模型卡

| 欄位 | 意義 |
| --- | --- |
| `kind` | `chat`、`vlm`、`omni`、`embedding`、`reranker`、`classifier`、`decision`、`asr`、`tts`、`sts`、`image`、`ocr` 或 `video`。 |
| `family`、`architecture`、`parameters` | 從檢查點讀出的模型家族、架構類別與參數量。 |
| `quantization` | 位元寬度、群組大小與模式；混合精度的檢查點還有逐層分組。 |
| `input_modalities`、`output_modalities` | `text`、`image`、`video`、`audio`、`embedding`、`score`、`decision` 的子集。 |
| `context` | `length` 與其推導方式。`max_output_tokens` 是對外宣告的輸出上限。 |
| `reasoning` | 模型是否有思考模式、切換開關、預設狀態、強度等級與別名。 |
| `tools`、`structured_output`、`logprobs` | 工具呼叫的支援與模式、支援的約束類型、最大的 `top_logprobs`。 |
| `embeddings` | Embedding 模型的向量維度、池化方式與是否正規化。 |
| `audio`、`image` | 語音與圖像模型的模態專屬細節。 |
| `speculative` | 模型具備的推測解碼方法（例如 `mtp`）以及是否無損。 |
| `prefix_cache` | 前綴快取是否服務此模型，以及類型。 |
| `state`、`memory` | 已載入、載入中、固定、錯誤；權重位元組數與預估記憶體。 |
| `api` | 哪些路由與線上格式可服務此模型。 |
| `supported_parameters` | chat 路由對此模型接受的請求欄位。 |
| `generation_defaults` | 來自檢查點 `generation_config.json` 的取樣預設值。 |
| `contract` | 能力契約，見下文。 |
| `capability_tags` | 扁平標籤，例如 `chat`、`tools`、`vision`、`thinking`。 |
| `server_tools` | 文字類模型專用：閘道執行的工具（網頁搜尋提供者、MCP 連接器）設定了哪些。 |

匿名呼叫者看不到檔案系統路徑，也看不到常駐狀態。出示已設定的 `YUNSHU_AUTH_TOKEN` 的請求，每個項目還會有 `loaded`、`size_gb`、`size_bytes` 與 `stats`，以及 `yunshu.path` 和帶有模型管理器計數器的頂層 `registry` 物件。沒有設定 token 時，所有人都是匿名。

## 查詢單一模型

`GET /v1/models/{model_id}` 以相同結構回傳單一項目。id 可以含斜線（`mlx-community/Qwen3.5-0.8B-MLX-bf16`），解析方式與推論相同：精確 id、別名、不分大小寫比對。未知的 id 回應 `404`：

```json
{
  "error": {
    "message": "Model 'nope' not found",
    "type": "invalid_request_error",
    "param": null,
    "code": "model_not_found"
  }
}
```

即使在生成路由接受任何名稱的單模型模式下，這個路由對伺服器沒有列出的 id 仍會回應 `404`。

## 能力契約

每張模型卡都有 `yunshu.contract` 物件，每個生成路由也都強制執行同一個物件，所以清單能精確告訴你請求可以用到什麼。

| 鍵 | 內容 |
| --- | --- |
| `tools` | `supported`；`mode`（聊天模板能轉換 tools 時為 `template`，由 Yunshu 注入工具提示時為 `prompt`）；`parallel`；接受的 `tool_choice` 值。 |
| `structured_output` | `json_object`；`json_schema` 與其引擎（`in-house`，超出內建子集的 schema 另有 `llguidance`）；`regex`；`choice`；`grammar`（Lark 語法，透過 `llguidance`）。 |
| `logprobs`、`reasoning` | 支援與否、最大的 `top_logprobs`、強度等級。 |
| `media` | 文字以外的輸入與輸出模態。 |
| `speculative` | `mode`（`mtp`、`dflash2` 或 `none`）與 `lossless`。 |
| `cache_tiers` | `ram`，啟用 SSD 層時還有 `ssd`。 |
| `context` | 視窗長度與最大輸出 token 數。 |
| `unsupported_fields` | 永遠是 `"400"`。 |

請求若用到契約排除的功能，會回應 `400` 並指出欄位，格式採用該方言的錯誤格式：

- 對不接受該輸入的模型送出 `image`、`audio` 或 `video` 內容區塊；
- 對不生成文字的模型（embedding、reranker、語音、圖像模型）使用 `tools`、`tool_choice`、`response_format`、`grammar`、`guided_*` 欄位或 `logprobs`。

對沒有推理模式的模型使用 `reasoning_effort` 與 `thinking_budget` 會被刻意接受但沒有作用，因為程式設計 agent 每個請求都會帶推理強度。設定檔無法讀取的檢查點沒有契約，也不受限制。

## 載入與卸載

<Callout type="warn">
這些路由會改變記憶體中的內容，因此需要驗證：沒有設定 `YUNSHU_AUTH_TOKEN`（且 `YUNSHU_AUTH_DISABLED` 不是 true）時會回應 `401`，訊息為 `No authentication configured. Set YUNSHU_AUTH_TOKEN or YUNSHU_AUTH_DISABLED=true.` 設定 token 後，與其他路由一樣送出它即可。
</Callout>

### 載入模型

`POST /v1/models/load` 載入模型並啟動它的引擎。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | 在模型管理器中註冊的模型 id。接受 `model_id` 作為別名；兩者都送時以 `model` 為準。 | 支援 |
| `pin` | boolean | 否 | 預設 `false`。 | 接受但忽略 |

```bash
curl -X POST http://localhost:8000/v1/models/load \
  -H "Authorization: Bearer $YUNSHU_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"model": "mlx-community/Qwen3.5-0.8B-MLX-bf16"}'
```

```json
{ "status": "loaded", "model": "mlx-community/Qwen3.5-0.8B-MLX-bf16" }
```

多模型模式下，模型必須已註冊（位於 `YUNSHU_MODELS_DIR` 下），否則回應 `404`。沒有模型管理器時，這個路由會把指定的路徑載入唯一的引擎；批次引擎則會拒絕（`400`）。

### 卸載模型

`POST /v1/models/unload/{model_id}` 釋放模型佔用的記憶體。僅限多模型模式（其他情況回應 `400`）。id 的解析方式（別名與大小寫）與推論相同。

```bash
curl -X POST http://localhost:8000/v1/models/unload/mlx-community/Qwen3.5-0.8B-MLX-bf16 \
  -H "Authorization: Bearer $YUNSHU_AUTH_TOKEN"
```

```json
{ "status": "unloaded", "model": "mlx-community/Qwen3.5-0.8B-MLX-bf16" }
```

仍有請求在處理中的模型不會被卸載（`409`），因此執行中的生成不會被硬生生中斷。

### 錯誤

| 狀態碼 | 時機 |
| --- | --- |
| 400 | `model` 為空；載入失敗且有特定原因（訊息會說明）；在批次引擎上做單一引擎載入；在多模型模式之外卸載。 |
| 401 | 沒有設定 token，或 token 缺少或不正確。 |
| 404 | 未知的模型（`GET`、卸載），或尚未註冊的模型（載入）。 |
| 409 | 同一個模型正在載入或卸載中；卸載時仍有作用中的請求，或模型在卸載期間變成使用中。 |
| 500 | 載入因未預期的原因失敗（`Model loading failed`）。 |
| 503 | 引擎尚未初始化。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 以 OpenAI 與 Anthropic 清單格式提供 `GET /v1/models` | <Support status="supported">支援</Support> |
| 每個項目都帶 OpenRouter、vLLM、LM Studio 中繼資料 | <Support status="supported">支援</Support> |
| 分頁參數（`limit`、`after`） | <Support status="unsupported">尚未支援；一律回傳完整清單</Support> |
| 在生成路由強制執行能力契約 | <Support status="supported">支援</Support> |
| 模型載入與卸載 | <Support status="supported">需驗證；卸載僅限多模型模式</Support> |
| 載入時的 `pin` | <Support status="unsupported">接受但忽略</Support> |
| 透過 API 從磁碟刪除模型 | <Support status="unsupported">這些路由不提供；請見 Ollama 相容層或 CLI</Support> |

## 相關頁面

- [API 總覽](/docs/api/overview)
- [Chat completions](/docs/api/chat-completions)
- [模型支援](/docs/guides/model-support)
- [模型入門](/docs/getting-started/models)
- [Ollama 相容層](/docs/api/ollama)


---

<!-- api/ocr -->
---
title: OCR
description: POST /v1/ocr 會用 OCR 模型把上傳的圖片轉成文字；沒有載入 OCR 模型時，改用任何已載入的視覺語言模型。
---

`POST /v1/ocr` 是 Yunshu 自己的路由，不屬於 OpenAI API。它接收一張上傳的圖片，回傳從中讀出的文字。`yunshu ocr` 與主控台的「圖片辨識」對話框使用的是同一條路由。

<Endpoint method="POST" path="/v1/ocr" />

<Callout type="info">
只有設定了 `YUNSHU_AUTH_TOKEN` 才會強制驗證。使用 API 金鑰時，該金鑰需要推論權限，並且能存取最後實際服務此請求的模型。
</Callout>

## 請求

`multipart/form-data`。

| 欄位 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `file` | file | 是 | 圖片，最大 10 MB。上傳內容會以 Pillow 驗證，不是圖片時回傳 `400`。可讀取 PNG、JPEG、WebP、TIFF、BMP。 |
| `model` | string | 否 | OCR 模型或視覺語言模型的 id。留空表示使用第一個已載入的 OCR 模型。 |
| `task` | string | 否 | `text`（預設）、`formula` 或 `table`，決定辨識提示詞（`Text Recognition:`、`Formula Recognition:`、`Table Recognition:`）；未知的值視同 `text`。 |
| `language` | string | 否 | 引導輸出語言的提示（「Respond in ...」）。不會做語言偵測。 |

## 如何選擇模型

1. 優先使用已載入的 OCR 類模型：`model` 指定的那一個，`model` 留空時用第一個已載入的。若 `model` 指向已註冊但尚未載入的 OCR 模型，模型管理器會嘗試載入它。
2. 否則退而使用已載入的視覺語言模型：`model` 若是已載入的 VLM 就用它，不然用任何一個已載入的 VLM。圖片會搭配任務提示詞與「Extract all text from this image verbatim」送出，採貪婪解碼（`temperature` 為 0），最多產生 2048 個新 token。OCR 引擎路徑上限為 4096。
3. 兩者都沒有時，伺服器回傳 `503`。

金鑰的模型範圍會針對實際解析出的模型再檢查一次，所以受模型範圍限制的金鑰不能靠留空 `model` 繞到其他模型。

## 回應

```json
{
  "text": "Invoice 2026-001\nTotal: 120.00",
  "model": "mlx-community/GLM-OCR-bf16",
  "confidence": null,
  "language": null,
  "task": "text",
  "prompt_tokens": 312,
  "completion_tokens": 18,
  "usage": {
    "prompt_tokens": 312,
    "completion_tokens": 18,
    "total_tokens": 330,
    "image_tokens": 290
  }
}
```

| 欄位 | 說明 |
| --- | --- |
| `text` | 擷取出的文字。模型什麼都沒讀到時可能是空字串。 |
| `model` | 實際服務此請求的模型 id。 |
| `confidence` | 一律為 `null`：兩條路徑都不產生信心分數，Yunshu 也不會捏造。 |
| `language` | 走 VLM 後備時是你給的 `language` 提示；走 OCR 引擎路徑時為 `null`。不做偵測。 |
| `task` | 原樣回傳請求的 `task`。 |
| `prompt_tokens`、`completion_tokens`、`usage` | token 數量。`usage.image_tokens` 是圖片佔的部分；走 VLM 後備且引擎未回報時，會依圖片尺寸與視覺設定估算。 |

回應不含文字框或位置，只有文字。

## 範例

<Tabs items={["curl", "Python", "CLI"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/ocr \
  -F file=@receipt.png \
  -F task=text \
  -F language="English"
```

</Tab>
<Tab value="Python">

```python
import requests

with open("receipt.png", "rb") as f:
    r = requests.post(
        "http://localhost:8000/v1/ocr",
        files={"file": ("receipt.png", f, "image/png")},
        data={"model": "", "task": "text"},
        timeout=180,
    )
r.raise_for_status()
print(r.json()["text"])
```

</Tab>
<Tab value="CLI">

```bash
yunshu ocr page.png
```

</Tab>
</Tabs>

## 取消

請求會註冊到請求追蹤器，用戶端斷線或呼叫 `POST /v1/cancel`（見[擴充](/docs/api/extensions)）時會被取消。在 OCR 引擎路徑上，生成呼叫本身會跑到 token 上限；處理常式會立即返回，結果則被丟棄。在 VLM 後備路徑上，生成會在解碼步驟之間停止。

## 錯誤

| 狀態碼 | 情況 |
| --- | --- |
| `400` | 上傳的檔案不是伺服器能讀取的圖片。 |
| `401`、`403` | 缺少或無效的憑證，或該金鑰不可推論、不可使用實際解析出的模型。 |
| `413` | 圖片超過 10 MB。 |
| `503` | 沒有載入 OCR 模型，也沒有載入視覺語言模型。 |
| `507` | GPU 記憶體不足。 |
| `500` | 擷取失敗；原因在伺服器日誌中。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 文字、公式與表格任務 | <Support status="extension">Yunshu 擴充</Support> |
| 視覺語言模型後備 | <Support status="supported">支援</Support> |
| 信心分數 | <Support status="unsupported">一律為 null</Support> |
| 文字位置或文字框 | <Support status="unsupported">僅提供文字</Support> |
| PDF 輸入 | <Support status="unsupported">僅限圖片</Support> |

## 相關頁面

- [Images](/docs/api/images)：圖像生成、編輯與變體。
- [多模態](/docs/guides/multimodal)：哪些路由處理哪種輸入。
- [主控台](/docs/getting-started/console)：「圖片辨識」對話框。


---

<!-- api/ollama -->
---
title: Ollama
description: 與 Ollama 相容的 /api 路由，讓 Ollama 用戶端與 SDK 能直接連到 Yunshu，並精確列出哪些是真實支援、哪些不是。
---

Yunshu 在 `/api` 下提供 Ollama 原生 API，因此為 Ollama 寫的工具（官方 `ollama` Python 與 JavaScript 函式庫、Open WebUI、Continue 等）不必修改就能指向這個伺服器。這些路由是一層很薄的轉換：每個 `/api/chat`、`/api/generate`、`/api/embed` 或 `/api/embeddings` 請求都會轉成對應的 OpenAI 請求，再送回同一個伺服器，所以模型路由、驗證、前綴快取、工具呼叫與受限解碼的行為，與 OpenAI 路由完全一樣。

<Endpoint method="POST" path="/api/chat" />
<Endpoint method="POST" path="/api/generate" />
<Endpoint method="POST" path="/api/embed" />
<Endpoint method="POST" path="/api/embeddings" />
<Endpoint method="GET" path="/api/tags" />
<Endpoint method="POST" path="/api/show" />
<Endpoint method="GET" path="/api/ps" />
<Endpoint method="GET" path="/api/version" />
<Endpoint method="POST" path="/api/pull" />
<Endpoint method="POST" path="/api/create" />
<Endpoint method="POST" path="/api/copy" />
<Endpoint method="DELETE" path="/api/delete" />
<Endpoint method="POST" path="/api/push" />

<Callout type="info">
預設連接埠是 8000，不是 Ollama 的 11434，所以請明確設定主機（例如 `http://localhost:8000`）。只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證；`Authorization` 標頭會轉送到內部請求。錯誤使用 Ollama 的格式 `{"error": "message"}`，HTTP 狀態碼為底層失敗的狀態碼。模型名稱以 Yunshu 的名稱為準：`:latest` 後綴會被接受並忽略，回應會原樣帶回你送出的名稱。
</Callout>

## 哪些是真實的

| 路由 | 狀態 | 行為 |
| --- | --- | --- |
| `POST /api/chat` | <Support status="supported">真實支援</Support> | 以 `messages`、`tools`、`format`、`options`、`think`、圖片進行聊天。預設以 NDJSON 串流。 |
| `POST /api/generate` | <Support status="supported">真實支援</Support> | 單一提示，可帶 `system` 與 `images`。空提示會回傳 `{"done": true, "done_reason": "load"}`，不會產生內容。 |
| `POST /api/embed` | <Support status="supported">真實支援</Support> | `input` 為字串或清單；可帶 `dimensions`。 |
| `POST /api/embeddings` | <Support status="supported">真實支援</Support> | 舊版的單一提示寫法。 |
| `GET /api/tags` | <Support status="supported">真實支援</Support> | 列出 Yunshu 提供的模型。 |
| `POST /api/show` | <Support status="supported">真實支援</Support> | 以 Ollama 格式回傳模型資訊卡。 |
| `GET /api/ps` | <Support status="supported">真實支援</Support> | 目前已載入的模型。 |
| `GET /api/version` | <Support status="supported">真實支援</Support> | Yunshu 的版本。 |
| `POST /api/pull` | <Support status="partial">僅限 Hugging Face 儲存庫，需多模型模式</Support> | 下載原生 MLX 儲存庫。 |
| `POST /api/create` | <Support status="partial">只能為現有模型命名</Support> | `from` 加上名稱；不支援 Modelfile 功能。 |
| `POST /api/copy` | <Support status="partial">別名，不複製權重</Support> | 建立指向同一份權重的符號連結名稱。 |
| `DELETE /api/delete` | <Support status="partial">需多模型模式，僅限模型目錄內</Support> | 移除別名，或移除模型目錄內的檢查點。 |
| `POST /api/push` | <Support status="unsupported">尚未支援</Support> | 一律回傳 `501`。 |

Ollama 的 blob 上傳與存在檢查路由完全不提供。Ollama 的 OpenAI 相容 `/v1` 路由就是 Yunshu 自己的 OpenAI 路由，見 [Chat Completions](/docs/api/chat-completions)。

## 聊天與產生

兩個路由都接受下列欄位。

| 欄位 | 路由 | 狀態 | 行為 |
| --- | --- | --- | --- |
| `model` | 兩者 | 支援 | 必填。單模型模式會以任何名稱提供已載入的模型。 |
| `messages` | chat | 支援 | 必填，`{role, content, images, tool_calls, tool_name}` 陣列。 |
| `prompt`、`system`、`images` | generate | 支援 | `system` 會變成系統訊息；`images` 為 base64 字串。 |
| `stream` | 兩者 | 支援 | 預設 `true`（NDJSON，`application/x-ndjson`）。`false` 則回傳單一 JSON 物件。 |
| `format` | 兩者 | 支援 | `"json"` 或 JSON schema 物件；以受限解碼落實。 |
| `tools` | 兩者 | 支援 | Ollama／OpenAI 格式的函式工具。呼叫會出現在 `message.tool_calls`，`arguments` 為物件。 |
| `think` | 兩者 | 支援 | `true`／`false` 切換思考；`"low"`、`"medium"`、`"high"` 設定推理強度。推理內容放在 `message.thinking`（chat）或 `thinking`（generate）。 |
| `options.temperature`、`top_p`、`top_k`、`min_p`、`seed`、`presence_penalty`、`frequency_penalty` | 兩者 | 支援 | 傳給引擎。 |
| `options.repeat_penalty` | 兩者 | 支援 | 對應到 `repetition_penalty`。 |
| `options.num_predict` | 兩者 | 支援 | 正數即為 token 上限。`-1`、`-2` 或省略時使用 8192。 |
| `options.stop` | 兩者 | 支援 | 字串或清單。 |
| `options.num_ctx`、`num_batch`、`num_gpu`、`mirostat*`、`typical_p`、`penalize_newline`、`use_mmap` 與其他執行器選項 | 兩者 | 接受但忽略 | 上下文大小是已載入模型本身的屬性。 |
| `keep_alive` | 兩者 | 接受但忽略 | 模型的存續由 Yunshu 管理，不是依個別請求。 |
| `template`、`raw`、`context`、`suffix`、`truncate` | generate／chat | 接受但忽略 | 提示範本一律使用模型自己的聊天範本。 |

訊息中的 `images` 是 base64 字串（資料會包成 PNG data URL），需要視覺語言模型。

## 範例

<Tabs items={["curl", "Python"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/api/chat -d '{
  "model": "local",
  "messages": [{"role": "user", "content": "Why is the sky blue?"}],
  "stream": false
}'
```

</Tab>
<Tab value="Python">

```python
from ollama import Client

client = Client(host="http://localhost:8000")

reply = client.chat(
    model="local",
    messages=[{"role": "user", "content": "Why is the sky blue?"}],
)
print(reply["message"]["content"])

for part in client.generate(model="local", prompt="Write a haiku.", stream=True):
    print(part["response"], end="")

print(client.embed(model="local-embedding", input=["hello", "world"])["embeddings"][0][:4])
```

</Tab>
</Tabs>

### 結構化輸出

```bash
curl http://localhost:8000/api/chat -d '{
  "model": "local",
  "stream": false,
  "messages": [{"role": "user", "content": "Ada Lovelace was born in 1815."}],
  "format": {"type": "object", "properties": {"name": {"type": "string"}, "born": {"type": "integer"}}, "required": ["name", "born"]}
}'
```

## 回應

非串流的 `/api/chat`：

```json
{
  "model": "local",
  "created_at": "2026-01-01T12:00:00.000000Z",
  "message": { "role": "assistant", "content": "Sunlight scatters off air molecules." },
  "done": true,
  "done_reason": "stop",
  "total_duration": 812000000,
  "load_duration": 0,
  "prompt_eval_count": 24,
  "prompt_eval_duration": 120000000,
  "eval_count": 8,
  "eval_duration": 690000000
}
```

`/api/generate` 回傳 `response` 而不是 `message`。`done_reason` 為 `stop` 或 `length`（工具呼叫以 `stop` 結束）。時間單位為奈秒；引擎回報自己的計時時就用它，否則由閘道量測。除非引擎回報載入時間，否則 `load_duration` 為 0。

## 串流

`stream` 為 true（預設）時，回應是 NDJSON，每行一個 JSON 物件：重複的 `done: false` 區塊帶有 `message.content`（或 `response`），模型有推理時還有 `message.thinking`，最後是一個 `done: true` 的物件，含 `done_reason`、計時欄位與任何 `message.tool_calls`。工具呼叫在最後一個物件一次送達，不會逐段送出。串流開始後的失敗，是單獨一行 `{"error": "..."}`，之後不會有 `done: true` 那一行。

## 模型與嵌入

- `GET /api/tags` 回傳 `{"models": [{name, model, modified_at, size, digest, details}]}`。`size` 在已知時取自模型資訊卡的權重大小。`digest` 是模型 id 的雜湊，不是檔案內容的雜湊。
- `POST /api/show` 接受 `model`（或 `name`），以 Ollama 格式回傳模型資訊卡（`details`、`model_info`、`capabilities`、`modelfile`、`parameters`、`template`、`modified_at`）。未知的模型是 `404`。
- `GET /api/ps` 回傳已載入的模型，`expires_at` 一律是 `0001-01-01T00:00:00Z`（不會到期）。
- `POST /api/embed` 回傳 `{"model", "embeddings": [[...]], "total_duration", "load_duration", "prompt_eval_count"}`；`POST /api/embeddings` 回傳 `{"embedding": [...]}`。兩者都需要嵌入模型，且與[嵌入](/docs/api/embeddings)使用同一個引擎。

## 模型管理

這些路由只在多模型模式（`yunshu serve --models-dir`）下運作，並需要與載入、卸載模型相同的權限；單模型模式下會回應 `400`。

- `POST /api/pull` 搭配 `{"model": "org/name"}`，會下載內含原生 safetensors 權重的 Hugging Face 儲存庫並註冊。已註冊的名稱會立即回傳成功。Ollama 登錄庫的名稱（`library/llama3:8b`）與 GGUF 儲存庫會被拒絕（`400`）。回覆是單獨一行 `{"status": "success"}`（`"stream": false` 時為 JSON）；沒有進度事件。
- `POST /api/create` 只接受 `{"model": "new-name", "from": "existing-model"}`，建立持久的別名。`files`、`adapters`、`quantize`、`parameters`、`template`、`system`、`messages` 欄位會被拒絕（`400`）。
- `POST /api/copy` 搭配 `source` 與 `destination`，建立指向同一份權重的符號連結別名。目的地已存在是 `409`。
- `DELETE /api/delete` 搭配 `model`，會卸載並移除別名，或刪除模型目錄內的檢查點目錄。模型目錄外的檢查點會被拒絕（`400`），仍有別名指向的檢查點是 `409`，使用中的模型是 `409`。
- `POST /api/push` 一律回傳 `501`，訊息說明不支援登錄庫上傳。

## 錯誤

`{"error": "message"}`，附上失敗的狀態碼：本文錯誤或缺少 `model`、`messages` 為 `400`，驗證與權限為 `401`／`403`，未知模型為 `404`，模型管理衝突為 `409`，`/api/push` 為 `501`，產生錯誤則沿用上游狀態（例如提示超出上下文視窗為 `400`）。

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 聊天、產生、NDJSON 串流 | <Support status="supported">支援</Support> |
| 工具、結構化 `format`、`think`、圖片 | <Support status="supported">支援</Support> |
| 嵌入（`/api/embed`、`/api/embeddings`） | <Support status="supported">支援</Support> |
| Tags、show、ps、version | <Support status="supported">支援</Support> |
| Pull、create、copy、delete | <Support status="partial">僅限原生 MLX 儲存庫與別名</Support> |
| `num_ctx`、`keep_alive`、Modelfile `template` 等執行器選項 | <Support status="partial">接受但忽略</Support> |
| 登錄庫上傳（`/api/push`）、GGUF 匯入、blobs | <Support status="unsupported">尚未支援</Support> |

## 相關頁面

- [Chat Completions](/docs/api/chat-completions)
- [嵌入](/docs/api/embeddings)
- [模型](/docs/api/models)
- [模型支援](/docs/guides/model-support)


---

<!-- api/operations -->
---
title: 維運
description: 健康檢查探針、Prometheus 指標、即時請求檢視與取消、伺服器屬性、互動式文件、速率限制與日誌。
---

這些路由是為了把 Yunshu 當作服務執行而準備的：給服務管理員或負載平衡器用的探針、Prometheus 端點、進行中請求的即時檢視，以及 OpenAPI 文件。更完整的狀態物件請見[擴充](/docs/api/extensions)中的 `GET /v1/yunshu/status`。

<Endpoint method="GET" path="/health" />
<Endpoint method="GET" path="/health/live" />
<Endpoint method="GET" path="/health/ready" />
<Endpoint method="GET" path="/metrics" />
<Endpoint method="GET" path="/v1/requests" />
<Endpoint method="GET" path="/v1/requests/{request_id}" />
<Endpoint method="DELETE" path="/v1/requests/{request_id}" />
<Endpoint method="GET" path="/props" />
<Endpoint method="GET" path="/v1/props" />
<Endpoint method="GET" path="/version" />
<Endpoint method="GET" path="/docs" />
<Endpoint method="GET" path="/openapi.json" />

## 哪些路由需要 token

只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。設定後，下列路徑仍然公開，讓探針與文件可以繼續運作：`/health`、`/health/live`、`/health/ready`、`/version`、`/docs`、`/redoc`、`/openapi.json`、`/` 與主控台的靜態資源。其餘一切，包含 `/metrics`、`/props` 與請求相關路由，都需要 `Authorization: Bearer <token>` 或 `x-api-key`。

## 健康檢查探針

| 路由 | 用途 | 回應 |
| --- | --- | --- |
| `GET /health` | 精簡的存活摘要。行程能回應時一律 `200`。 | `{"status": "ok", "engine": {"loaded": bool}, "server_state": "running", "uptime_seconds": 12.3}` |
| `GET /health/live` | 存活探針。 | `{"alive": true, "state": "running"}` |
| `GET /health/ready` | 就緒探針。就緒時 `200`，未就緒時 `503`。 | `{"ready": bool, "checks": {...}}` |

`server_state` 與 `state` 的值為 `running`、`shutdown_requested` 或 `shutting_down`。這些端點是公開的，所以刻意不回傳模型名稱、佇列深度或記憶體數字。

符合下列任一情況時，`GET /health/ready` 回傳 `503`：

- 伺服器正在為關閉而排空請求（`checks.not_shutting_down` 為 `false`），
- 沒有載入任何模型，也無法按需載入（`checks.model_loaded` 為 `false`），
- Metal 記憶體用量達到或超過系統記憶體的 95%（`checks.gpu_memory_ok` 為 `false`）。

多模型模式下，已註冊但尚未載入的模型視為就緒，因為請求會按需載入它們；`checks.models_registered` 會回報註冊的數量。如果沒有載入模型是因為載入失敗，回應本文會帶有含載入錯誤的 `reason`。

```json
{ "ready": true, "checks": { "not_shutting_down": true, "model_loaded": true, "gpu_memory_ok": true } }
```

存活檢查請用 `GET /health/live`，就緒檢查請用 `GET /health/ready`。

## Prometheus 指標

`GET /metrics` 回傳 Prometheus 文字格式。它永遠掛載，若設定了 bearer token 就需要驗證，所以請在 Prometheus 的抓取工作中設定 bearer 驗證。指標使用 `yunshu_` 前綴：

| 指標家族 | 內容 |
| --- | --- |
| `yunshu_request_total`、`yunshu_request_duration_seconds` | 依 method、status 與端點分組的 HTTP 請求數；請求延遲直方圖。 |
| `yunshu_gateway_active_requests` | 目前進行中的推論請求數。 |
| `yunshu_tokens_generated_total`、`yunshu_ttft_seconds`、`yunshu_itl_seconds`、`yunshu_inference_duration_seconds`、`yunshu_prefill_duration_seconds` | 生成 token 數、首 token 延遲、token 間延遲，以及推論與 prefill 時間直方圖。 |
| `yunshu_itl_p50_ms`、`yunshu_itl_p99_ms`、`yunshu_step_duration_ms`、`yunshu_compute_utilization_pct` | 延遲百分位數與步驟耗時的 gauge。 |
| `yunshu_kv_cache_*`、`yunshu_kv_prefix_cache_*`、`yunshu_radix_*` | KV 區塊使用量、前綴快取項目數、命中、未命中與逐出。 |
| `yunshu_apc_*` | VLM runner 的自動前綴快取：RAM 與 SSD 層、各層查詢、命中的 token 數、逐出、WARM 層位元組數與壓縮比。 |
| `yunshu_spec_*`、`yunshu_mtp_*` | 推測解碼：草稿與被接受的 token 數、接受率、MTP 週期、n-gram 提案。帶有 `model_id` 標籤。 |
| `yunshu_gpu_busy_seconds_total`、`yunshu_round_driver_busy_seconds_total` | 累計的 GPU 忙碌秒數；一段時間內的閒置比例等於 1 減去第一個指標的變化率。 |
| `yunshu_scheduler_*`、`yunshu_chunked_prefill_*`、`yunshu_attention_eviction_*` | batched 引擎的排程器與 prefill gauge。 |
| `yunshu_model_warmup_*`、`yunshu_lora_*`、`yunshu_response_cache_*` | 預熱次數、LoRA adapter 記帳、回應快取的命中與未命中。 |

哪些家族有資料取決於所用的引擎與功能；沒用到的家族會維持零。指標中的記憶體數字單位為位元組。

## 檢視與取消請求

每個請求都有 id（你的 `X-Request-Id` 或產生的值，見[擴充](/docs/api/extensions)）。以下路由以該 id 運作。

`GET /v1/requests` 列出進行中的請求：

```json
{
  "object": "list",
  "count": 1,
  "data": [
    {
      "request_id": "job-8",
      "elapsed_s": 8.12,
      "phase": "prefill",
      "prompt_tokens": 93268,
      "cached_tokens": 0,
      "processed_tokens": 92160,
      "percent": 98.8,
      "tokens_per_second": 8125.3,
      "eta_s": 0.1,
      "path": "/v1/chat/completions",
      "stream": true,
      "model": "local",
      "engine_request_id": "chatcmpl-...",
      "cancelled": false
    }
  ]
}
```

`phase` 為 `starting`、`queued`、`prefill` 或 `decode`。排隊中的請求會顯示 `queue_position` 與 `queue_est_wait_ms`；解碼中的請求會顯示 `completion_tokens`。沒有經過受追蹤的 HTTP 路徑的生成（例如批次工作）會以 phase `running` 出現。

`GET /v1/requests/{request_id}` 以 `{"object": "yunshu.request", ...}` 回傳單一請求，欄位相同；id 不存在或已完成則回傳 `404`。要追蹤長時間的非串流 prefill，請輪詢這個路由。

`DELETE /v1/requests/{request_id}` 依用戶端請求 id 或 completion id 取消。回傳 `{"object": "yunshu.request", "id": ..., "status": "cancelled"}`；若請求已受理但尚未交給引擎，則為 `"cancelling"`（一註冊就會被取消）。未知的 id 回傳 `404`。`POST /v1/cancel` 以本文做同樣的事，見[擴充](/docs/api/extensions)。

## 伺服器屬性

`GET /props` 與 `GET /v1/props`（同一個處理函式）回傳 llama.cpp 風格的所服務模型屬性，給會探測這些屬性的工具：

```json
{
  "default_generation_settings": { "n_ctx": 32768 },
  "model_path": "mlx-community/Qwen3.5-0.8B-MLX-bf16",
  "chat_template": "{% ... %}",
  "total_slots": 1
}
```

它只回報單一所服務的模型；沒有載入模型，或在多模型模式下沒有單一所服務的引擎時，回傳 `503`。要取得各模型的詳細資訊，請用 `GET /v1/models`，見[模型](/docs/api/models)。

`GET /version` 回傳 `{"version", "service": "yunshu", "description"}`。

## 互動式文件

`GET /docs` 提供 Swagger UI，`GET /redoc` 提供 ReDoc，`GET /openapi.json` 提供所有已註冊路由的 OpenAPI 文件。即使設定了 token，這三者也都是公開的。

## 管理端點

`/v1/yunshu/*` 下 Yunshu 專屬路由（另見[驗證與金鑰](/docs/guides/auth-and-keys)與[遙測](/docs/guides/telemetry)）。每條路由的細節與測試狀態見 `docs/guides/API_SURFACE.md`。標示 admin 的需要管理員 token。

| 路由 | 回傳或作用 |
|---|---|
| `GET /v1/yunshu/memory` | 統一記憶體帳本：各持有者（權重、前綴快取 RAM 與 warm 層、MLX 快取、即時 KV）、工作集、主機壓力 |
| `GET /v1/yunshu/cache, /cache/tiers` | 前綴快取條目與各層用量、命中、SSD 讀取速率（只有雜湊標籤，不含 token） |
| `POST /v1/yunshu/cache/clear, /cache/tiers/clear` | 清除常駐 APC 或單一層（admin；全域清除時引擎未閒置會回 409） |
| `POST /v1/yunshu/downloads`, `GET /v1/yunshu/downloads`, `DELETE /v1/yunshu/downloads/{id}` | 佇列、列出與取消 Hugging Face 下載到模型目錄；磁碟放不下時回 507 |
| `GET /v1/yunshu/models/local` | 磁碟上所有模型（無論是否已註冊） |
| `POST /v1/yunshu/models/register`, `DELETE /v1/yunshu/models/register/{model_id}` | 註冊或取消註冊本機 checkpoint，不載入（多模型模式） |
| `POST /v1/yunshu/models/{id}/reload`, `GET /v1/yunshu/models/{id}/fit`, `GET /v1/yunshu/models/impact`, `POST /v1/yunshu/models/cancel` | 重新載入以套用設定、記憶體 fit 試算、驅逐影響、取消載入或下載 |
| `GET /v1/yunshu/logs, /logs/stream` | 已遮蔽的記憶體內伺服器日誌環（admin），一般或 SSE |
| `GET /v1/yunshu/spec-decode` | MTP / DFlash 各草稿深度的 drafted 與 accepted token 數 |
| `GET /v1/yunshu/requests/recent, /requests/history` | 已完成請求環與輪替的 serve log 中繼資料（只有數字，無提示詞） |
| `GET /v1/yunshu/bundle, /bundle/manifest` | 本機診斷檔與其內容清單；不會上傳 |

## 相容 Tavily 的路由

在 `/tavily` 之下，Yunshu 以自己的搜尋與擷取層提供 Tavily REST API 的本機實作：`POST /tavily/search`、`POST /tavily/extract`、`POST /tavily/crawl`、`POST /tavily/map`、`POST /tavily/research`、`GET /tavily/research/{request_id}`、`POST /tavily/feedback`、`POST /tavily/logs`、`GET /tavily/usage`、`GET /tavily/providers`，以及 MCP 端點 `POST /tavily/mcp`。這些路徑沒有 `/v1`，錯誤格式為 `{"detail": {"error": "..."}}`。設定了 token 時，Tavily 用戶端可以用 bearer token，或在請求本文中以 `api_key` 傳入。這裡不計費：`GET /tavily/usage` 回報的 credits 一律為零。供應商與設定請見[網頁搜尋指南](/docs/guides/web-search)。

## 速率限制與受理控制

- **依 IP 的速率限制。** 預設關閉。把 `YUNSHU_RATE_LIMIT_RPM` 設為正數，就會對每個用戶端 IP 啟用 token bucket（每分鐘請求數，突發量等於上限）。超過時回傳 `429` 與 `Retry-After`，格式符合該路由的錯誤格式。健康檢查、文件與 `/metrics` 不受限，CORS preflight 也不受限。只有列在 `YUNSHU_TRUSTED_PROXIES` 的代理才會採信 `X-Forwarded-For`。
- **受理控制。** 對生成路由一律啟用。`YUNSHU_QUEUE_LIMIT`（預設 64）限制進行中的請求數，超過時回傳 `429`；記憶體壓力過高且仍有其他請求在執行時回傳 `503`。兩者都帶有 `Retry-After`。見[擴充](/docs/api/extensions)。
- **Deadline。** 請求標頭 `X-Yunshu-Deadline-Ms` 限制一個請求能等待與執行的時間。

## 日誌

每個請求都會記錄其請求 id、method、路徑、狀態碼與延遲，並在 `X-Request-ID` 回應標頭中回傳該 id。成功的請求以 debug 層級記錄，`4xx` 為 warning，`5xx` 為 error，所以預設的 `INFO` 層級只會顯示有問題的請求；設定 `YUNSHU_LOG_LEVEL=DEBUG` 可看到每一個請求。耗時超過 `YUNSHU_SLOW_REQUEST_THRESHOLD` 秒（預設 30）的請求會記錄 `SLOW_REQUEST` 警告，統一記憶體用量超過 85% 時會記錄 `MEMORY_PRESSURE` 警告。健康檢查、文件與 `/metrics` 的請求不會被記錄。以 launchd 服務執行時，服務日誌會輪替並壓縮，且會遮蔽機密，見[服務](/docs/getting-started/service)。

`/debug` 之下另有額外的檢視路由，但只有在 `YUNSHU_DEBUG_ROUTES=1` 時才會掛載，且需要 token 或 `YUNSHU_AUTH_DISABLED`。它們是診斷輔助，不是穩定的 API。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl -i http://localhost:8000/health/ready
curl -s http://localhost:8000/metrics | head
curl -s http://localhost:8000/v1/requests
curl -X DELETE http://localhost:8000/v1/requests/job-8
```

</Tab>
<Tab value="Python">

```python
import httpx

base = "http://localhost:8000"
ready = httpx.get(f"{base}/health/ready")
print(ready.status_code, ready.json())

for r in httpx.get(f"{base}/v1/requests").json()["data"]:
    print(r["request_id"], r["phase"], r.get("percent"))
```

</Tab>
<Tab value="JavaScript">

```ts
const base = "http://localhost:8000";
const ready = await fetch(`${base}/health/ready`);
console.log(ready.status, await ready.json());

const { data } = await (await fetch(`${base}/v1/requests`)).json();
for (const r of data) console.log(r.request_id, r.phase, r.percent);
```

</Tab>
</Tabs>

## 錯誤

| 狀態碼 | 情況 |
| --- | --- |
| `401` | 已設定 token，路由不是公開的，而請求沒有有效的 token。 |
| `404` | 請求 id 不存在。 |
| `429` | 速率限制（啟用時）或佇列上限。 |
| `503` | 就緒檢查失敗、因記憶體壓力而拒絕，或沒有單一模型載入時呼叫 `GET /props`。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 存活、就緒與精簡健康檢查 | <Support status="supported">支援</Support> |
| Prometheus `/metrics` | <Support status="supported">支援</Support> |
| 請求列表、輪詢與取消 | <Support status="extension">Yunshu 擴充</Support> |
| `/props` | <Support status="partial">精簡的 llama.cpp 風格子集，單一模型</Support> |
| 依 IP 的速率限制 | <Support status="partial">除非設定 `YUNSHU_RATE_LIMIT_RPM`，否則關閉</Support> |
| slot 管理路由（`/slots`） | <Support status="unsupported">未提供</Support> |
| Tavily credits 計費 | <Support status="unsupported">本機實作，不計費</Support> |

## 相關頁面

- [擴充](/docs/api/extensions)：`GET /v1/yunshu/status`、預熱與請求 id。
- [服務](/docs/getting-started/service)：以 launchd 執行。
- [疑難排解](/docs/guides/troubleshooting)：探針失敗時該檢查什麼。
- [網頁搜尋指南](/docs/guides/web-search)：相容 Tavily 的路由。


---

<!-- api/overview -->
---
title: API 總覽
description: 基礎 URL、Yunshu 提供的各種 API 方言、驗證方式、model 欄位的解析規則、錯誤格式、請求 ID，以及整份 API 的路由對照表。
---

同一個 Yunshu 行程會同時提供多種線上格式：OpenAI API、Anthropic Messages API、相容 Ollama 的層、JSON-RPC 的 MCP 端點，以及一組 vLLM 風格的工具路由（tokenize、score、rerank）。它們都是同一個引擎之上的薄薄一層。本頁說明所有路由共通的部分，各路由的細節請看[路由總覽](#路由總覽)中連結的頁面。

## 基礎 URL

伺服器預設監聽 `8000` 埠。

| 用戶端 | 基礎 URL | 說明 |
| --- | --- | --- |
| OpenAI SDK 與任何相容 OpenAI 的工具 | `http://localhost:8000/v1` | SDK 會自行接上 `/chat/completions`、`/embeddings` 等路徑。 |
| Anthropic SDK | `http://localhost:8000` | SDK 會自行接上 `/v1/messages`，請不要自己加 `/v1`。 |
| Ollama 用戶端 | `http://localhost:8000` | 路由位於 `/api/*` 底下。 |
| vLLM 風格工具（tokenize） | `http://localhost:8000` | `/tokenize` 與 `/detokenize` 也提供不帶 `/v1` 前綴的版本。 |

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")
```

```python
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:8000", api_key="not-needed")
```

## 驗證

驗證支援靜態管理 token，以及有權限範圍、期限與滾動配額的具名 API 金鑰。

- 未設定 `YUNSHU_AUTH_TOKEN` 且沒有 API 金鑰（預設）：推論路由（chat、completions、embeddings、tokenize 等）不需驗證。`POST /v1/models/load` 這類操作性路由因為無從授權，會回應 `401`。
- 設定了 `YUNSHU_AUTH_TOKEN`：除了一份很短的公開清單之外，所有請求都需要有效的 token 或 API 金鑰。公開路徑為 `/health`、`/health/live`、`/health/ready`、`/version`、`/docs`、`/openapi.json`、`/redoc`、`/`、`/console` 與靜態資源前綴。
- `YUNSHU_AUTH_DISABLED=true` 會完全關閉驗證，連操作性路由也不例外。僅限本機開發使用。

兩種送法都可以，伺服器在所有路由、所有方言上都接受：

```bash
curl http://localhost:8000/v1/models -H "Authorization: Bearer $YUNSHU_AUTH_TOKEN"
curl http://localhost:8000/v1/models -H "x-api-key: $YUNSHU_AUTH_TOKEN"
```

兩個標頭都存在時，採用 `Authorization: Bearer` 的值。比對採用常數時間。缺少 token 時回應 `401`，訊息為 `Missing or invalid Authorization header`；token 錯誤時回應 `401`，訊息為 `Invalid or missing API key`。兩者都會帶 `WWW-Authenticate: Bearer` 標頭。

具名 API 金鑰使用相同標頭；`infer` 與 `admin` 限制存取範圍，過期或撤銷的金鑰無效，超出配額回應 `429`。金鑰共用這台伺服器的資料，但 Files 與 Conversations 除外：infer 金鑰只看得到自己的。

<Callout type="info">
沒有設定 token 與 API 金鑰時，SDK 送出的金鑰會被忽略，所以 `not-needed` 或 `sk-local` 之類的任何佔位字串都可以。要讓伺服器對外網路開放之前，請維持預設的 localhost 綁定，或先設定 token。
</Callout>

## `model` 欄位

`model` 的意義取決於伺服器的啟動方式。

| 模式 | 啟動方式 | `model` 的意義 |
| --- | --- | --- |
| 單模型 | 設定 `YUNSHU_MODEL`，或在 `yunshu serve` 指定一個模型 | 僅供參考。不論你送什麼名稱，所有生成路由都使用唯一載入的模型，名稱會原樣出現在回應中。`GET /v1/models/{id}` 對伺服器沒有列出的 id 仍會回應 `404`。 |
| 多模型 | `YUNSHU_MULTI_MODEL=1`，模型放在 `YUNSHU_MODELS_DIR` 底下 | 作為選擇器。名稱會依註冊表解析（別名、不分大小寫比對，以及最後一個 `/` 之後的部分），模型在第一次使用時載入，未知的名稱回應 `404`。 |

`GET /v1/models` 會列出可用的 id，詳見[模型](/docs/api/models)。embedding、rerank 與 scoring 模型是獨立的檢查點：多模型模式下在 `model` 填入它們的名稱；單模型模式下，載入的那個模型本身就必須是 embedder 或 reranker。

每個生成路由在執行前，還會檢查模型的能力契約（capability contract）。請求若用到模型沒有的功能（對純文字模型送圖片區塊、對 embedding 模型使用 tools、對不生成文字的模型要求 `logprobs`），會回應 `400` 並指出欄位名稱。契約內容見[模型](/docs/api/models)。

## 錯誤

錯誤內容的格式跟隨出錯路由所屬的方言，包含在路由執行前就被驗證、限流或請求驗證擋下的錯誤。

OpenAI 格式的路由（Anthropic、Ollama、MCP、Tavily 以外的所有路由）：

```json
{
  "error": {
    "message": "Model 'foo' not found (hint: GET /v1/models lists the model ids this server can serve; pull one with `yunshu pull <repo>`)",
    "type": "invalid_request_error",
    "param": null,
    "code": "model_not_found",
    "x_yunshu": {
      "hint": "GET /v1/models lists the model ids this server can serve; pull one with `yunshu pull <repo>`",
      "request_id": "req_0f3a9c2d4b7e41a6b8c1d2e3"
    }
  }
}
```

Anthropic 路由（`/v1/messages`、`/messages` 與 `count_tokens` 路由）：

```json
{
  "type": "error",
  "error": { "type": "invalid_request_error", "message": "max_tokens: Field required" }
}
```

| 狀態碼 | OpenAI 的 `type` / `code` | Anthropic 的 `error.type` |
| --- | --- | --- |
| 400 | `invalid_request_error` / 結構驗證失敗為 `validation_error`，其他為 `bad_request` | `invalid_request_error` |
| 401 | `authentication_error` / `invalid_api_key` | `authentication_error` |
| 404 | `invalid_request_error` / `model_not_found`（未知路由為 `not_found`） | `not_found_error` |
| 409 | `invalid_request_error` / `conflict` | `invalid_request_error` |
| 413 | `invalid_request_error` / `request_too_large` | `request_too_large` |
| 429 | `rate_limit_error` / `rate_limit_exceeded`，帶 `Retry-After` | `rate_limit_error` |
| 500 | `server_error` / `internal_error` | `api_error` |
| 503 | `server_error` / `service_unavailable`，帶 `Retry-After` | `overloaded_error` |

其他方言：Ollama 路由回應 `{"error": "message"}`，MCP 端點回應 JSON-RPC 2.0 錯誤物件，Tavily 路由回應 `{"detail": {"error": "message"}}`。

幾件值得知道的事：

- 在所有方言上，請求本文驗證失敗都是 `400`，而不是 `422`。`error.param` 會指出出問題的欄位。
- 提示詞超出模型的上下文視窗時，回應 `400` 與 `code: "context_length_exceeded"`。
- `x_yunshu.hint` 是針對常見錯誤的一行修正建議；同樣的文字也會以 `(hint: ...)` 附加在 `message` 後面，因為許多 SDK 只會顯示 message。
- 伺服器滿載（`YUNSHU_QUEUE_LIMIT`）時回應 `429` 並帶 `Retry-After`；記憶體不足時回應 `503`。OpenAI 與 Anthropic SDK 都會重試這兩種狀態。
- 串流開始之後發生的錯誤無法再改變 HTTP 狀態碼，串流會送出最後一個 `data: {"error": ...}` 事件，接著是 `data: [DONE]`。

## 請求 ID 與標頭

每個請求都有一個 ID。送出 `X-Request-Id`（1 至 128 個 `A-Z a-z 0-9 . _ : -` 字元）可自行指定，否則伺服器會產生 `req_...`。這個 ID 會原樣出現在 `X-Request-Id` 回應標頭（錯誤回應也一樣）、`error.x_yunshu.request_id` 與 `x_yunshu.request_id` 中，並用來在伺服器日誌裡識別該請求。

生成路由會讀取或回傳的其他標頭：

| 標頭 | 方向 | 說明 |
| --- | --- | --- |
| `X-Request-Id` | 雙向 | 上述的請求 ID。 |
| `X-Yunshu-Deadline-Ms` | 請求 | 從請求抵達起算的牆鐘時間預算，含排隊等待。超過後生成會被取消，回應 `504`（串流則送出一個終止錯誤事件）。 |
| `X-Yunshu-Queue-Position`、`X-Yunshu-Queue-Est-Wait-Ms` | 回應 | 請求抵達時伺服器的忙碌程度。 |
| `X-Yunshu-TTFT-Ms`、`X-Yunshu-Prefill-Tps`、`X-Yunshu-Decode-Tps`、`X-Yunshu-Cached-Tokens`、`X-Yunshu-Cache-Tier`、`X-Yunshu-Total-Ms` | 回應（非串流） | `x_yunshu` 內數值的精簡複本。值未知時該標頭會省略。 |
| `X-Yunshu-Cancelled` | 回應 | 回答因取消或逾時而中斷時為 `true`。 |
| `X-Yunshu-Spec`、`X-Yunshu-Spec-Acceptance` | 回應 | 若有執行推測解碼，表示其模式與接受率。 |
| `Retry-After` | 回應 | `429` 與 `503` 時建議等待的秒數。 |

進行中的生成可用請求 ID 取消，詳見[營運](/docs/api/operations)。

## Yunshu 擴充欄位

Yunshu 新增的內容都放在專屬的命名空間下，官方 SDK 因此完全不受影響。

- `x_yunshu`：位於非串流的 chat、completions、Responses 或 Messages 回應 JSON 中，包含排隊等待、首 token 延遲、prefill 與 decode 速度、快取 token 數與快取層級、推測解碼計數，以及適用時的 `cancelled`、`budget` 或 `context_policy`。串流回應則把同一個物件放在最後的 usage 區塊（OpenAI）或 `usage` 內（Messages、Responses）。
- OpenAI 格式錯誤中的 `error.x_yunshu`：`hint`、`request_id`，過載錯誤時還有原因與佇列深度。
- 請求等待或 prefill 期間送出的 SSE 註解行，例如 `: yunshu-progress {...}`。SSE 解析器會忽略註解。
- `GET /v1/models` 回傳的每個模型物件內的 `yunshu`。
- 生成路由上的額外請求欄位（例如 `top_n_sigma`、`spec_decode`、`thinking_budget`、`keep_alive`、`grammar`）。

欄位清單與意義見[擴充功能](/docs/api/extensions)。

## 路由總覽

| 路由 | 頁面 |
| --- | --- |
| `POST /v1/chat/completions`、`POST /v1/completions` | [Chat completions](/docs/api/chat-completions) |
| `GET /v1/chat/completions`、`GET /v1/chat/completions/{id}`、`POST /v1/chat/completions/{id}`、`DELETE /v1/chat/completions/{id}`、`GET /v1/chat/completions/{id}/messages` | [儲存的 completions](/docs/api/stored-completions) |
| `POST /v1/responses`、`GET /v1/responses/{id}`、`DELETE /v1/responses/{id}`、`POST /v1/responses/{id}/cancel`、`POST /v1/responses/input_tokens`、`POST /v1/responses/compact`、`WS /v1/responses` | [Responses](/docs/api/responses) |
| `POST /v1/messages`、`POST /v1/messages/count_tokens`（也提供不帶 `/v1` 的版本） | [Messages](/docs/api/messages) |
| 伺服器端的網頁搜尋、網頁擷取與 MCP 連接器工具 | [伺服器工具](/docs/api/server-tools) |
| `POST /v1/embeddings`、`POST /v1/pooling` | [Embeddings](/docs/api/embeddings) |
| `POST /v1/rerank`、`POST /v1/score`、`POST /v1/classify` | [Rerank 與評分](/docs/api/rerank) |
| `POST /v1/tokenize`、`POST /v1/detokenize`、`POST /v1/apply-template`（也提供不帶 `/v1` 的版本） | [Tokenization](/docs/api/tokenization) |
| `POST /v1/audio/transcriptions`、`POST /v1/audio/translations`、`POST /v1/audio/speech`、`POST /v1/audio/speech/stream`、`GET /v1/audio/voices` | [音訊](/docs/api/audio) |
| `POST /v1/images/generations`、`POST /v1/images/edits`、`POST /v1/images/variations` | [圖像](/docs/api/images) |
| `GET /v1/models`、`GET /v1/models/{id}`、`POST /v1/models/load`、`POST /v1/models/unload/{id}` | [模型](/docs/api/models) |
| `POST /v1/files`、`GET /v1/files`、`GET /v1/files/{id}`、`GET /v1/files/{id}/content`、`DELETE /v1/files/{id}` | [檔案](/docs/api/files) |
| `POST /v1/batches`、`GET /v1/batches`、`POST /v1/messages/batches` 及相關路由 | [批次](/docs/api/batches) |
| `POST /v1/evals` 及相關路由 | [Evals](/docs/api/evals) |
| `WS /v1/realtime`、`POST /v1/realtime/client_secrets`、`POST /v1/realtime/calls` | [Realtime](/docs/api/realtime) |
| `POST /api/chat`、`POST /api/generate`、`POST /api/embed`、`GET /api/tags` 及相關路由 | [Ollama](/docs/api/ollama) |
| `POST /v1/mcp`、`GET /v1/mcp/sse` | [MCP](/docs/api/mcp) |
| `POST /v1/decisions`、`POST /v1/systemone` | [Decisions](/docs/api/decisions) |
| `GET /v1/requests`、`DELETE /v1/requests/{id}`、`POST /v1/cancel`、`GET /v1/yunshu/status`、`GET /health`、`GET /metrics` | [營運](/docs/api/operations) |

## 尚未提供的 OpenAI 與 Anthropic 功能

Yunshu 是本機推論引擎，專為執行託管服務而存在的 API 沒有對應物。對這些路由發出請求會得到 `404`。

<NotServed>

| 未提供 | API | 原因 |
| --- | --- | --- |
| `/v1/fine_tuning/jobs` | OpenAI | 此伺服器不做訓練。可用 `mlx-lm` 工具產生 LoRA adapter，並在引擎支援時以 `lora_adapter` 載入。 |
| `/v1/moderations` | OpenAI | 沒有託管的內容審核模型。 |
| `/v1/assistants`、`/v1/threads`、`/v1/threads/{id}/runs` | OpenAI（舊版） | 已由 Yunshu 提供的 Responses API 取代。 |
| `/v1/vector_stores`、file search | OpenAI | 沒有託管的檢索儲存庫。請搭配 `POST /v1/embeddings` 與自己的索引。 |
| `/v1/uploads` | OpenAI | 未實作分段的 multipart 上傳。`POST /v1/files` 接受單次上傳。 |
| `/v1/containers`、code interpreter | OpenAI | 沒有託管的沙箱。 |
| `/v1/videos`（Sora） | OpenAI | 沒有影片生成端點。 |
| `/v1/organizations/*`、`/v1/skills` | Anthropic | 帳號與託管技能的管理在本機不存在。 |
| 程式碼執行、computer use 與 memory 工具 | Anthropic 與 OpenAI | 託管工具，在本機沒有意義。用戶端的 function tools 可正常使用。 |

</NotServed>

Yunshu 在生成迴圈內自行執行的工具（網頁搜尋、網頁擷取、MCP 連接器）請見[伺服器工具](/docs/api/server-tools)。

## 相關頁面

- [Chat completions](/docs/api/chat-completions)
- [模型](/docs/api/models)
- [擴充功能](/docs/api/extensions)
- [設定](/docs/guides/configuration)


---

<!-- api/realtime -->
---
title: Realtime
description: 透過 WebSocket（GA 與 beta 結構）和 WebRTC 提供的 OpenAI Realtime 協定，支援暫時性用戶端金鑰、文字與語音回合，以及工具呼叫。
---

Yunshu 提供 OpenAI Realtime 協定：一條長連線的 WebSocket（或 WebRTC data channel），雙向傳送 JSON 事件。你設定 session、加入對話項目或串流麥克風音訊，伺服器則串流回傳文字、音訊與工具呼叫事件。官方 `openai` SDK 的 `client.realtime.connect()` 可以直接使用。

<Endpoint method="WS" path="/v1/realtime" />
<Endpoint method="WS" path="/realtime" />
<Endpoint method="POST" path="/v1/realtime/client_secrets" />
<Endpoint method="POST" path="/v1/realtime/sessions" />
<Endpoint method="POST" path="/v1/realtime/transcription_sessions" />
<Endpoint method="POST" path="/v1/realtime/calls" />

## 連線

連到 `ws://localhost:8000/v1/realtime?model=local`。`model` 查詢參數指定這個 session 使用的模型（單模型模式下任何名稱都會對應到所服務的模型；多模型模式下指定未知模型時，會收到 code 為 `model_not_found` 的 `error` 事件，並關閉連線）。

| 格式 | 如何選擇 | 備註 |
| --- | --- | --- |
| GA（預設） | `WS /v1/realtime`，不帶 beta 標頭 | `client.realtime.connect()` 使用的格式：巢狀的 `audio.input` / `audio.output` session，事件名稱如 `response.output_text.delta`。 |
| Beta | 在 `WS /v1/realtime` 帶 `OpenAI-Beta: realtime=v1`，或直接使用 `WS /realtime` | 扁平的 session（`modalities`、`voice`、`input_audio_format` 等），事件名稱如 `response.text.delta`，另外會送出 `conversation.created`。 |

只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。設定後，連線需要下列其中一種：

- `Authorization: Bearer <token>` 標頭，
- 瀏覽器用的子協定 `openai-insecure-api-key.<token>`（同時帶上 `realtime` 作為第二個子協定），
- `?token=` 查詢參數，
- 暫時性用戶端金鑰（`ek_...`），可放在上述任一位置，見下文。

若帶有 `Origin` 標頭，必須被 `YUNSHU_CORS_ORIGINS` 允許（該設定為 `*` 時除外）。檢查失敗時會在升級連線之前就關閉，用戶端看到的是握手失敗。

伺服器送出的第一則訊息是 `session.created`。GA 格式之後會保持安靜直到你開口；beta 格式還會送出 `conversation.created`。若沒有載入任何模型，伺服器會立刻送出一個 `error` 事件。

## Session 設定

送出帶有 `session` 物件的 `session.update`。下表用 GA 結構，括號內是 beta 名稱。

| 欄位 | 說明 | 狀態 |
| --- | --- | --- |
| `output_modalities`（`modalities`） | `["text"]`（預設）或 `["audio"]`。beta 形式也接受 `["text", "audio"]`。 | 支援 |
| `instructions` | 回應使用的系統提示。 | 支援 |
| `audio.output.voice`（`voice`） | `alloy`、`echo`、`shimmer`、`ash`、`ballad`、`coral`、`sage`、`verse` 之一，或 omni 模型的原生說話者。無效的語音會被忽略。 | 支援 |
| `audio.input.format`、`audio.output.format`（`input_audio_format`、`output_audio_format`） | GA：`audio/pcm`（24 kHz 單聲道 16-bit）、`audio/pcmu`、`audio/pcma`。Beta：`pcm16`、`g711_ulaw`、`g711_alaw`。 | 支援 |
| `audio.input.turn_detection`（`turn_detection`） | `null`（手動 commit）或 `{"type": "server_vad", "threshold", "prefix_padding_ms", "silence_duration_ms", "idle_timeout_ms"}`。 | 支援 |
| `audio.input.noise_reduction`（`input_audio_noise_reduction`） | `{"type": "near_field"}`、`far_field` 或 `null`。 | 支援 |
| `tools`、`tool_choice` | 函式工具；`tool_choice` 為 `auto`、`none`、`required` 或指定函式。 | 支援 |
| `max_output_tokens`（`max_response_output_tokens`） | 整數。 | 支援 |
| `temperature` | 取樣溫度，預設 0.7。 | 支援 |
| `audio.input.transcription` | 使用哪個 ASR 模型取決於目前載入的 ASR 引擎，這個欄位不會用來挑選。 | 接受但忽略 |
| `top_p`、`top_k`、`min_p`、`repetition_penalty`、`frequency_penalty`、`presence_penalty`、`logit_bias`、`seed`、`enable_thinking` | Yunshu 的取樣擴充，會直接傳遞。 | 擴充 |
| `tracing`、`include`、`type` | 忽略。 | 接受但忽略 |

server VAD 的預設值為 `threshold` 0.5、`prefix_padding_ms` 300、`silence_duration_ms` 500，以及 120 ms 持續說話才算插話的門檻（`barge_in_min_ms`，GA session 中不會顯示）。可用 `YUNSHU_REALTIME_VAD_THRESHOLD`、`YUNSHU_REALTIME_PREFIX_PADDING_MS`、`YUNSHU_REALTIME_SILENCE_MS`、`YUNSHU_REALTIME_BARGE_IN_MS` 在伺服器端統一調整。`YUNSHU_REALTIME_VAD=silero` 會把預設的能量式偵測改為 Silero VAD（模型由 `YUNSHU_REALTIME_VAD_MODEL` 指定）。`turn_detection.type` 為 `semantic_vad` 時會以 `server_vad` 處理；`eagerness`、`create_response`、`interrupt_response` 會被忽略（偵測到回合結束後一律建立回應，說話會打斷正在播放的回應）。

某個欄位的值不合法（例如不認得的音訊格式）時會被默默略過並保留原值；`session.updated` 事件會顯示實際生效的 session。

## 用戶端事件

| 事件 | 行為 |
| --- | --- |
| `session.update` | 變更 session，回應 `session.updated`。 |
| `conversation.item.create` | 新增項目（訊息、函式呼叫、函式呼叫輸出）。回應 `conversation.item.added` 與 `conversation.item.done`（GA）或 `conversation.item.created`（beta）。id 重複或項目過大時以 `error` 拒絕。 |
| `conversation.item.delete` | 移除項目，回應 `conversation.item.deleted`。 |
| `conversation.item.truncate` | 記錄使用者實際聽到助理音訊項目的多少，回應 `conversation.item.truncated`。 |
| `input_audio_buffer.append` | 附加 base64 音訊。 |
| `input_audio_buffer.commit` | 轉錄緩衝區，並作為使用者訊息加入對話。 |
| `input_audio_buffer.clear` | 丟棄緩衝區。 |
| `response.create` | 開始一個回應。`response` 可帶 `output_modalities`、`instructions`、`tools`、`tool_choice`、`temperature`、`max_output_tokens`、`input`（作為這個回應完整上下文的項目；`[]` 表示清空）以及 `conversation: "none"`（不寫入歷史）。 |
| `response.cancel` | 取消執行中的回應。 |
| `output_audio_buffer.clear` | 中斷正在說話的回應。 |

每個 session 同時只會有一個回應。已有回應執行中又送 `response.create` 會得到 `error`。未知的事件類型會得到 `type: "invalid_request_error"` 的 `error`。

## 伺服器事件

文字回合的順序：`response.created`、`rate_limits.updated`、`response.output_item.added`、`response.content_part.added`、重複的 `response.output_text.delta`、`response.output_text.done`、`response.content_part.done`、`response.output_item.done`、`response.done`。beta 格式的名稱是 `response.text.delta` 與 `response.text.done`。

包含工具呼叫的回合會輸出 `function_call` 項目，以及 `response.function_call_arguments.delta` 與 `response.function_call_arguments.done`。把結果以 `function_call_output` 類型的 `conversation.item.create` 送回，再送一次 `response.create`。

`response.done` 帶有 `status`（`completed`、`cancelled` 或 `failed`）、輸出項目，以及 `usage`（`input_tokens`、`output_tokens`、`total_tokens`）。

語音回合的事件：

| 事件 | 時機 |
| --- | --- |
| `input_audio_buffer.speech_started`、`input_audio_buffer.speech_stopped` | server VAD 偵測到開始與結束說話。 |
| `input_audio_buffer.committed` | 緩衝區已 commit，由 VAD 或你的 `commit` 觸發。 |
| `conversation.item.added` / `.done` | 帶有逐字稿的使用者項目。 |
| `conversation.item.input_audio_transcription.completed` | 使用者回合的 ASR 逐字稿。 |
| `response.output_audio.delta`、`response.output_audio.done` | 以 session 輸出格式編碼的 base64 音訊區塊（beta 為 `response.audio.delta`）。 |
| `response.output_audio_transcript.delta`、`.done` | 語音回覆的文字。 |
| `output_audio_buffer.started`、`.stopped`、`.cleared` | 僅 GA 格式：標示一個回應音訊的起訖；被取消或插話中斷時為 `cleared`。 |
| `input_audio_buffer.timeout_triggered` | 經過 `idle_timeout_ms` 都沒有說話；會 commit 一個空的使用者回合並回應。 |
| `error` | 任何失敗。內容為 `{"type": "error", "event_id", "error": {"message", "type", "code"?}}`。 |

## 文字回合與語音回合

文字回合只需要載入聊天模型：建立使用者訊息項目，送出 `response.create`，讀取 `output_text` 事件。

語音回合有兩種實作：

- **串接（預設）。** 輸入音訊由已載入的 ASR 模型轉錄，文字送給聊天模型，回覆再由已載入的 TTS 模型合成。這需要多模型設定，在聊天模型旁同時載入 ASR 模型，以及（要輸出音訊時）TTS 模型。沒有 ASR 模型時，commit 會得到 code 為 `no_asr_engine` 的 `error`；沒有 TTS 模型時，音訊回應會結束但沒有任何音訊區塊。
- **原生語音對語音。** 當所服務的模型帶有 Talker（Qwen3-Omni）時，原始音訊直接送進模型，語音直接回來。`YUNSHU_REALTIME_OMNI` 預設為 `auto`（有可發聲的模型時使用原生），`on` 強制使用，`off` 強制使用串接。

音訊限制：輸入緩衝區上限為 `YUNSHU_REALTIME_MAX_INPUT_AUDIO_BYTES`（10 MiB），超過會清空緩衝區並送出 `input_audio_buffer_overflow` 錯誤。一個 session 最多保留 `YUNSHU_REALTIME_MAX_CONVERSATION_ITEMS`（1000）個項目，最舊的會被丟棄。

## 暫時性用戶端金鑰

給瀏覽器使用時，請在你的後端產生一把短效金鑰再交給網頁。`ek_...` 的值可用在靜態 token 能用的地方，包含 `WS /v1/realtime` 與 `POST /v1/realtime/calls`。

`POST /v1/realtime/client_secrets`（GA）接收 `{"expires_after": {"anchor": "created_at", "seconds": 10..7200}, "session": {...}}`（預設 600 秒；`session.type` 為 `realtime` 或 `transcription`），回傳 `{"value": "ek_...", "expires_at", "session": {...}}`。你傳入的 session 會套用在使用該金鑰的連線上，該連線之後無法覆寫。`POST /v1/realtime/sessions` 與 `POST /v1/realtime/transcription_sessions` 是 beta 形式，回傳的 session 帶有 `client_secret` 物件。金鑰只存在記憶體（最多同時 1000 把），所以重新啟動後會失效。轉錄金鑰可以做轉錄，但不能建立回應。

## WebRTC

`POST /v1/realtime/calls` 用來協商 WebRTC 通話：以 `application/sdp` 送出 SDP offer（或 multipart 的 `sdp` 加 JSON `session`），得到狀態 `201` 的 SDP answer。音訊走媒體軌道（內部重新取樣為 24 kHz 單聲道 PCM），相同的 JSON 事件則走標籤為 `oai-events` 的 data channel，使用 GA 格式。

需求與限制：

- 需安裝選用的 extra：`pip install "yunshu[webrtc]"`。沒有安裝時，此路由回傳 `503`，並建議改用 WebSocket。
- 沒有設定 STUN 或 TURN 伺服器，所以對等端必須能直接連線（同一台機器或區域網路）。
- 同時最多 16 通有效通話（超過回傳 `429`）。大於 128 KiB 的 offer 回傳 `413`。
- 通話會在對等端失敗或關閉、伺服器關閉、開啟後滿一小時，或 offer 之後 60 秒內 data channel 都沒有開啟時結束。
- 回應帶有一個指出通話的 `Location` 標頭，但沒有可查詢或掛斷通話的路由，請直接關閉 peer connection。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
# Mint an ephemeral key for a browser
curl http://localhost:8000/v1/realtime/client_secrets \
  -H "Content-Type: application/json" \
  -d '{"expires_after": {"anchor": "created_at", "seconds": 600},
       "session": {"type": "realtime", "model": "local", "output_modalities": ["text"], "instructions": "Be brief."}}'
```

</Tab>
<Tab value="Python">

```python
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

async def main():
    async with client.realtime.connect(model="local") as conn:
        await conn.session.update(session={"type": "realtime", "output_modalities": ["text"]})
        await conn.conversation.item.create(
            item={"type": "message", "role": "user",
                  "content": [{"type": "input_text", "text": "Say hello in five words."}]}
        )
        await conn.response.create()
        async for event in conn:
            if event.type == "response.output_text.delta":
                print(event.delta, end="", flush=True)
            elif event.type == "response.done":
                break

asyncio.run(main())
```

</Tab>
<Tab value="JavaScript">

```ts
import WebSocket from "ws";

const ws = new WebSocket("ws://localhost:8000/v1/realtime?model=local", {
  headers: { Authorization: "Bearer not-needed" },
});

ws.on("open", () => {
  ws.send(JSON.stringify({ type: "session.update", session: { type: "realtime", output_modalities: ["text"] } }));
  ws.send(JSON.stringify({
    type: "conversation.item.create",
    item: { type: "message", role: "user", content: [{ type: "input_text", text: "Say hello in five words." }] },
  }));
  ws.send(JSON.stringify({ type: "response.create" }));
});

ws.on("message", (raw) => {
  const event = JSON.parse(raw.toString());
  if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
  if (event.type === "response.done") ws.close();
});
```

</Tab>
</Tabs>

## 與官方託管 API 的差異

- `semantic_vad` 以 `server_vad` 提供。
- `rate_limits.updated` 會跟在 `response.created` 之後，但並沒有配額：`requests` 回報 `YUNSHU_RATE_LIMIT_RPM`（為 0 時是 32 位元整數的最大值），`tokens` 回報模型的上下文視窗。
- `audio.input.noise_reduction` 是在 CPU 上執行的輕量因果高通濾波加底噪展開器，不是神經網路降噪。
- `output_audio_buffer.started`、`.stopped`、`.cleared` 在 WebSocket 上也會送出（OpenAI 只在 WebRTC 與 SIP 送出）。
- 不支援的 session 欄位會被默默接受，而不是被拒絕。
- 音訊輸入需要另外的 ASR 模型或原生語音模型，沒有內建的語音辨識器。
- 不提供 SIP 通話與監控用的 sideband WebSocket。

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| WebSocket，GA 與 beta 結構 | <Support status="supported">支援</Support> |
| 文字回合、工具呼叫、truncate、取消 | <Support status="supported">支援</Support> |
| 經由 ASR、LLM、TTS 的語音回合 | <Support status="partial">需要載入 ASR 與 TTS 模型</Support> |
| 原生語音對語音 | <Support status="partial">需要帶有 Talker 的模型（Qwen3-Omni）</Support> |
| server VAD | <Support status="supported">能量式，可選 Silero</Support> |
| `semantic_vad` | <Support status="partial">以 `server_vad` 提供</Support> |
| 暫時性用戶端金鑰 | <Support status="supported">僅存在記憶體</Support> |
| WebRTC | <Support status="partial">選用的 `webrtc` extra，沒有 STUN/TURN</Support> |
| SIP、sideband 連線 | <Support status="unsupported">未提供</Support> |

## 相關頁面

- [音訊](/docs/api/audio)：HTTP 的語音合成與轉錄端點。
- [擴充](/docs/api/extensions)：`WS /v1/stream` 與 `POST /v1/omni/speech/stream`。
- [Chat Completions](/docs/api/chat-completions)：Realtime 沿用的文字取樣行為。


---

<!-- api/rerank -->
---
title: Rerank 與評分
description: 以 embedding 模型、cross-encoder reranker 與序列分類檢查點對文件重新排序、為文字配對評分並分類文字。
---

三個 vLLM 風格的路由負責檢索後處理：`POST /v1/rerank` 依與查詢的相關度為文件排序，`POST /v1/score` 為文字配對評分，`POST /v1/classify` 為文字指派標籤。它們會在你指定的、具備評分能力的模型上執行：

- 訓練過的 cross-encoder reranker（文字，或像 Qwen3-VL-Reranker 這樣的多模態 reranker）會把每組查詢／文件配對一起評分。這是準確度最好的選擇。
- 序列分類檢查點（帶有訓練過的分類頭的模型）由 `POST /v1/classify` 使用，標籤取自檢查點本身。
- Embedding 模型可作為備援：比較分別計算出的向量之間的相似度。成本較低，但不如 cross-encoder 精準；`rerank` 會把餘弦相似度對應到 `0` 至 `1` 的範圍。

聊天模型不能用於這些路由；它們會回應 `400`，並說明該模型無法產生 embedding。

<Endpoint method="POST" path="/v1/rerank" />
<Endpoint method="POST" path="/v1/score" />
<Endpoint method="POST" path="/v1/classify" />

<Callout type="info">
只有在設定 `YUNSHU_AUTH_TOKEN` 時才會強制驗證，見 [API 總覽](/docs/api/overview)。多模型模式下 `model` 用來選擇評分模型；單模型模式下，載入的模型本身就必須是評分模型。
</Callout>

## Rerank

### 請求

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | Reranker 或 embedding 模型 id。 | 支援 |
| `query` | string 或 object | 是 | 查詢。物件 `{"text": ..., "image": ...}` 需要多模態 cross-encoder。 | 支援 |
| `documents` | array | 是 | 最多 2048 項，每項是字串或 `{"text": ..., "image": ...}` 物件。超過 8192 字元的字串會被截斷。 | 支援 |
| `top_n` | integer | 否 | 只回傳最好的 `n` 個，`1` 至 `2048`。 | 支援 |
| `return_documents` | boolean | 否 | 預設 `true`：每筆結果都帶著它的 `document`。 | 支援 |
| `instruction` | string | 否 | 給支援指示的 cross-encoder 的任務指示，最多 8192 字元。 | 支援 |
| `use_activation` | boolean | 否 | 僅限文字 cross-encoder：套用分數的 activation（預設開啟）。其他模型會回應 `400`。 | 擴充 |

### 範例

<Tabs items={["curl", "Python"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/rerank \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen/Qwen3-Reranker-0.6B",
    "query": "How do I reset my password?",
    "documents": [
      "Our office is closed on public holidays.",
      "To reset your password, open Settings and choose Security.",
      "Shipping usually takes three to five days."
    ],
    "top_n": 2
  }'
```

</Tab>
<Tab value="Python">

```python
import requests

r = requests.post(
    "http://localhost:8000/v1/rerank",
    json={
        "model": "Qwen/Qwen3-Reranker-0.6B",
        "query": "How do I reset my password?",
        "documents": [
            "Our office is closed on public holidays.",
            "To reset your password, open Settings and choose Security.",
            "Shipping usually takes three to five days.",
        ],
        "top_n": 2,
    },
)
for item in r.json()["results"]:
    print(item["index"], item["relevance_score"], item["document"]["text"])
```

</Tab>
</Tabs>

### 回應

```json
{
  "id": "rerank-1760000000",
  "object": "list",
  "model": "Qwen/Qwen3-Reranker-0.6B",
  "results": [
    { "index": 1, "relevance_score": 0.982114, "document": { "text": "To reset your password, open Settings and choose Security." } },
    { "index": 2, "relevance_score": 0.114203, "document": { "text": "Shipping usually takes three to five days." } }
  ],
  "usage": { "prompt_tokens": 63, "total_tokens": 63 }
}
```

結果依 `relevance_score` 由高到低排序；`index` 是該文件在請求 `documents` 中的位置。`relevance_score` 四捨五入到小數點後六位。cross-encoder 的分數就是模型給的分數；embedding 模型則是 `(cosine + 1) / 2`。

## Score

`POST /v1/score` 為文字配對評分，每組配對回傳一個數字。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | 模型 id。 | 支援 |
| `text_1` | string 或 array | 是 | 第一組文字。別名：`queries`、`data_1`。 | 支援 |
| `text_2` | string 或 array | 是 | 第二組文字。別名：`documents`、`items`、`data_2`。 | 支援 |
| `scoring_type` | string | 否 | `cosine`（預設）、`dot` 或 `euclidean`（負的距離）。只有 embedding 模型可設定；cross-encoder 除了 `cosine` 都回應 `400`。 | 支援 |
| `use_activation` | boolean | 否 | 僅限文字 cross-encoder。 | 擴充 |
| `instruction` | string | 否 | 給 cross-encoder 的任務指示。也可以放在 `chat_template_kwargs.instruction`；`chat_template_kwargs` 的其他鍵會回應 `400`。 | 支援 |

兩邊的文字會逐項配對。如果某一邊只有一項，會與另一邊的每一項廣播配對；否則兩邊長度必須相同。每邊最多 2048 項，每段文字最多 8192 字元。

```bash
curl http://localhost:8000/v1/score \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen/Qwen3-Reranker-0.6B",
    "text_1": "What is the capital of France?",
    "text_2": ["Paris is the capital of France.", "Bananas are yellow."]
  }'
```

```json
{
  "object": "list",
  "id": "score-0f1e2d3c4b5a69788796a5b4c3d2e1f0",
  "created": 1760000000,
  "model": "Qwen/Qwen3-Reranker-0.6B",
  "data": [
    { "object": "score", "index": 0, "score": 0.9731 },
    { "object": "score", "index": 1, "score": 0.0124 }
  ],
  "usage": { "prompt_tokens": 38, "total_tokens": 38 }
}
```

## Classify

`POST /v1/classify` 有兩種模式，由模型決定。

**訓練過的分類器。** 如果模型是序列分類檢查點，`input` 是字串或字串陣列，且不可傳 `labels`（會使用檢查點自帶的標籤；傳了 `labels` 會回應 `400`）。

```json
{
  "object": "list",
  "model": "my-classifier",
  "data": [
    { "object": "classification", "index": 0, "probs": [0.91, 0.06, 0.03] }
  ],
  "labels": ["positive", "neutral", "negative"],
  "usage": { "prompt_tokens": 9, "total_tokens": 9 },
  "results": [
    { "label": "positive", "score": 0.91, "index": 0 },
    { "label": "neutral", "score": 0.06, "index": 1 },
    { "label": "negative", "score": 0.03, "index": 2 }
  ]
}
```

當 `input` 是單一字串時，會多出 `results`（依分數排序的標籤）。

**以 embedding 模型做零樣本分類。** `input` 是單一字串，`labels` 至少兩項（也接受別名 `candidate_labels`）。輸入與每個標籤都會被嵌入，餘弦相似度除以 `temperature`（預設 `0.07`，範圍大於 `0` 至 `10`）後再做 softmax。

```bash
curl http://localhost:8000/v1/classify \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen/Qwen3-Embedding-0.6B",
    "input": "The battery died after two hours.",
    "labels": ["battery", "screen", "shipping"]
  }'
```

```json
{
  "model": "Qwen/Qwen3-Embedding-0.6B",
  "results": [
    { "label": "battery", "score": 0.874, "index": 0 },
    { "label": "screen", "score": 0.082, "index": 2 },
    { "label": "shipping", "score": 0.044, "index": 1 }
  ],
  "usage": { "prompt_tokens": 16, "total_tokens": 16 }
}
```

`index` 是標籤在請求中的位置；`results` 依 `score` 排序。分數總和為一。

## 錯誤

| 狀態碼 | 時機 |
| --- | --- |
| 400 | 驗證失敗（空文字、無法廣播的長度不一致、未知的 `scoring_type`、標籤少於兩個、文字超過 8192 字元、對訓練過的分類器傳了 `labels`）；把多模態的查詢或文件送給不是 cross-encoder reranker 的模型；對不是文字 cross-encoder 的模型使用 `use_activation`；無法產生 embedding 的聊天模型。 |
| 401 | 已設定 token，但缺少或不正確。 |
| 404 | 找不到該模型。 |
| 507 | GPU 記憶體不足。 |
| 500 | 評分失敗（`server_error`）。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 文字 cross-encoder 重新排序 | <Support status="supported">支援</Support> |
| 多模態重新排序（圖片查詢或文件） | <Support status="partial">僅限多模態 cross-encoder 模型</Support> |
| 以 embedding 模型作為 rerank、score、classify 的備援 | <Support status="supported">支援</Support> |
| 訓練過的序列分類頭 | <Support status="supported">支援</Support> |
| `dot` 與 `euclidean` 評分 | <Support status="partial">僅限 embedding 模型</Support> |
| Cohere 或 Jina 專屬欄位（`max_chunks_per_doc`、`rank_fields`） | <Support status="unsupported">尚未支援；未知欄位會被忽略</Support> |

## 相關頁面

- [Embeddings](/docs/api/embeddings)
- [模型](/docs/api/models)
- [模型支援](/docs/guides/model-support)


---

<!-- api/responses -->
---
title: Responses
description: OpenAI Responses API，支援儲存回應、背景模式、對話、壓縮、用戶端工具與 WebSocket 模式。
---

Yunshu 在 `POST /v1/responses` 提供 OpenAI Responses API，以及周邊路由：取回、刪除、取消、列出輸入項目、計算輸入 token、壓縮對話，還有 Conversations API。同一個路徑也提供 WebSocket 模式。官方 `openai` SDK 不需修改即可使用（`client.responses.create`、`.retrieve`、`.delete`、`.cancel`、`.input_items.list`、`.compact`、`.input_tokens.count`、`.connect`、`client.conversations.*`）。

每個請求都會轉換成與 [Chat Completions](/docs/api/chat-completions) 相同的引擎路徑，因此取樣、受限解碼、前綴快取、視覺輸入與工具呼叫的行為一致。網路搜尋與 `mcp` 工具由伺服器執行，詳見[伺服器端工具](/docs/api/server-tools)。

<Endpoint method="POST" path="/v1/responses" />
<Endpoint method="GET" path="/v1/responses/{response_id}" />
<Endpoint method="DELETE" path="/v1/responses/{response_id}" />
<Endpoint method="POST" path="/v1/responses/{response_id}/cancel" />
<Endpoint method="GET" path="/v1/responses/{response_id}/input_items" />
<Endpoint method="POST" path="/v1/responses/input_tokens" />
<Endpoint method="POST" path="/v1/responses/compact" />
<Endpoint method="WS" path="/v1/responses" />
<Endpoint method="POST" path="/v1/conversations" />
<Endpoint method="GET" path="/v1/conversations/{conversation_id}" />
<Endpoint method="POST" path="/v1/conversations/{conversation_id}" />
<Endpoint method="DELETE" path="/v1/conversations/{conversation_id}" />
<Endpoint method="POST" path="/v1/conversations/{conversation_id}/items" />
<Endpoint method="GET" path="/v1/conversations/{conversation_id}/items" />
<Endpoint method="GET" path="/v1/conversations/{conversation_id}/items/{item_id}" />
<Endpoint method="DELETE" path="/v1/conversations/{conversation_id}/items/{item_id}" />

<Callout type="info">
只有在設定了 `YUNSHU_AUTH_TOKEN` 時才會強制驗證。單模型模式下 `model` 欄位僅供參考：已載入的模型會回應任何名稱，回應中會原樣帶回你送出的名稱。多模型模式下，未知的模型會得到 `404`。
</Callout>

## 請求

`POST /v1/responses` 接收 JSON 本文。

### 輸入與狀態

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | 模型 id。空字串會被拒絕。 | 支援 |
| `input` | string 或項目陣列 | 是 | 純字串，或下列項目：`message`（角色 `user`、`assistant`、`system`、`developer`；`developer` 視同 `system`）、`function_call`、`function_call_output`、`reasoning`、`custom_tool_call`、`custom_tool_call_output`、`local_shell_call`、`local_shell_call_output`、`tool_search_call`、`tool_search_output`、`computer_call`、`computer_call_output`、`web_search_call`、`mcp_call`、`mcp_list_tools`、`mcp_approval_request`、`mcp_approval_response`、`compaction`、`item_reference`。內容部分：`input_text`、`input_image`、`input_file`、`input_audio`。空字串與空陣列會被拒絕（`generate: false` 除外）。 | 支援 |
| `instructions` | string | 否 | 這次請求的系統提示。不會透過 `previous_response_id` 延續。 | 支援 |
| `previous_response_id` | string | 否 | 從已儲存的回應繼續。先前的回合會重播進提示中，最多往回追 16 層。未知、未儲存或不屬於你的 id 不會報錯：串接就在該處停止，請求會在沒有那段歷史的情況下執行。 | 支援 |
| `conversation` | string 或 object | 否 | 對話 id（或 `{"id": ...}`）。對話項目會加在 `input` 前面，回應結束時這一回合會附加到對話中。不可與 `previous_response_id` 同時使用（`400`）。 | 支援 |
| `context_management` | array | 否 | `[{"type": "compaction", "compact_threshold": N}]`：輸入超過 N 個 token 時先壓縮。 | 支援 |
| `store` | boolean | 否 | 預設 `true`，與官方 API 相同。已儲存的回應可以取回、刪除、取消、串接與列出。 | 支援 |
| `background` | boolean | 否 | 在背景產生。未設 `stream` 時立即回傳 `queued` 回應；`stream: true` 時事件即時串流並被保留，連線中斷後可用 `GET /v1/responses/{id}?stream=true&starting_after=N` 接續。可與 `web_search`、`mcp` 工具並用。 | 支援 |
| `truncation` | `auto` 或 `disabled` | 否 | `auto`：提示超過上下文視窗時丟棄最舊的非系統訊息，並在 `x_yunshu.context_policy` 回報移除了什麼。`disabled`（預設）則回傳 `400`。 | 支援 |
| `generate` | boolean | 否 | `false` 只把提示前綴預先填入快取，回傳回應 id 但不產生輸出（Codex 使用的 WebSocket 預熱）。 | 支援 |
| `metadata` | object | 否 | 最多 16 組；會在回應中原樣帶回。 | 支援 |
| `include` | array of string | 否 | `reasoning.encrypted_content` 會在推理項目加上不透明的 `encrypted_content`；`web_search_call.action.sources` 會列出搜尋來源。其他值會被接受但沒有作用。 | 部分支援 |
| `max_tool_calls` | integer | 否 | 限制單一回應的伺服器端工具呼叫次數（網路搜尋與 `mcp`）。 | 支援 |
| `prompt_cache_key`、`prompt_cache_retention`、`prompt_cache_options`、`safety_identifier`、`service_tier`、`client_metadata`、`user` | 各種 | 否 | 接受，並在 Response 物件有對應欄位時帶回。不會改變行為；前綴快取是自動的。 | 接受但忽略 |

### 產生

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `max_output_tokens` | integer | 否 | 1 到 1048576。省略時（Codex 不送）為模型的輸出上限（含推理 token，262144），並受上下文視窗限縮；營運者上限 `YUNSHU_DEFAULT_MAX_TOKENS` 可調低。`x_yunshu.budget.max_tokens_source` 說明採用哪一個。也接受別名 `max_completion_tokens`。 | 支援 |
| `temperature` | number | 否 | 0 到 2，預設 1.0。 | 支援 |
| `top_p` | number | 否 | 0 到 1，預設 1.0。 | 支援 |
| `top_k`、`min_p`、`top_n_sigma`、`repetition_penalty`、`frequency_penalty`、`presence_penalty`、`xtc_probability`、`xtc_threshold` | number | 否 | 額外的取樣控制，範圍與 Chat Completions 相同。 | 擴充 |
| `seed` | integer | 否 | 決定性取樣的種子。 | 支援 |
| `stop`、`stop_token_ids` | array | 否 | 最多 16 個非空停止字串（可傳單一字串）。 | 擴充 |
| `min_tokens`、`ignore_eos`、`suppress_tokens`、`logit_bias`、`logprobs`、`top_logprobs`、`n` | 各種 | 否 | 傳給引擎。`logit_bias` 的值必須是有限數且介於 -100 到 100。`stream: true` 時不接受大於 1 的 `n`。 | 擴充 |
| `reasoning` | object | 否 | `{"effort": "low\|medium\|high"}` 對應到範本的推理強度。不會讀取 `summary`。 | 部分支援 |
| `reasoning_effort`、`enable_thinking`、`thinking_budget` | 各種 | 否 | `reasoning` 的扁平等效欄位。 | 擴充 |
| `text` | object | 否 | `text.format` 為 `json_schema` 或 `json_object` 時會變成受限解碼；預設為 `text`。 | 支援 |
| `response_format`、`grammar` | object | 否 | Chat 風格的結構化輸出與文法限制（`json`、`regex`、`choice`、`cfg`）。 | 擴充 |
| `stream` | boolean | 否 | Server-Sent Events。 | 支援 |
| `stream_options` | object | 否 | 接受。用量一律出現在最後的事件中。 | 接受但忽略 |
| `timeout`、`priority`、`lora_adapter`、`spec_decode` | 各種 | 否 | 與其他路由共用的引擎控制。視覺語言模型會拒絕 `lora_adapter` 與自訂 `logits_processors`。 | 擴充 |

### 工具

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `tools` | array | 否 | 見下方的工具類型。 | 部分支援 |
| `tool_choice` | string 或 object | 否 | `auto`、`none`、`required`、指定函式（`{"type": "function", "name": "..."}`），或 `allowed_tools` 物件（會併入工具清單）。強制選擇會在串流開始前檢查。 | 支援 |
| `parallel_tool_calls` | boolean | 否 | 預設 `true`。 | 支援 |

支援的工具類型：

| `type` | 由誰執行 | 狀態 |
| --- | --- | --- |
| `function` | 你的用戶端。模型的呼叫以 `function_call` 項目回傳。 | 支援 |
| `namespace` | 你的用戶端。子工具會攤平給模型，回傳的呼叫保留 namespace。跨 namespace 的重複名稱是 `400`。 | 支援 |
| `custom` | 你的用戶端。以 `custom_tool_call` 回傳，`input` 為純文字。支援 text 格式，以及 `syntax` 為 `regex` 或 `lark` 的 `grammar` 格式（受限解碼）。 | 支援 |
| `local_shell` | 你的用戶端。以 `local_shell_call` 回傳。 | 支援 |
| `tool_search` | 你的用戶端，且只接受 `execution: "client"`。`defer_loading` 的工具會一直隱藏，直到 `tool_search_output` 載入它們。託管式的 tool search 是 `400`。 | 部分支援 |
| `computer` | 你的用戶端。見下方說明。 | 部分支援 |
| `web_search`、`web_search_preview` | 伺服器。見[伺服器端工具](/docs/api/server-tools)。 | 支援 |
| `mcp` | 伺服器連線到你指定的 MCP 伺服器。見[伺服器端工具](/docs/api/server-tools)。 | 部分支援 |
| `code_interpreter`、託管 `shell` | 由伺服器在本機沙盒中執行，需手動開啟。見[伺服器端工具](/docs/api/server-tools)。 | 部分支援 |
| `file_search`、`image_generation` 等託管工具 | 無法使用。 | 尚未支援 |

用戶端工具（`custom`、`local_shell`、`tool_search`、`computer`）可以與 `web_search`、`mcp` 在同一個請求中並用：伺服器在迴圈內執行自己的工具，用戶端工具呼叫則交還給你，並像一般用戶端工具呼叫一樣結束該回應。

#### computer 工具

`tools: [{"type": "computer"}]` 支援作為由用戶端執行的工具。閘道會把它轉成一個函式，引數是有順序的 `actions` 陣列，並回傳含 `actions` 的 `computer_call` 項目（每個動作為 `click`、`double_click`、`drag`、`move`、`scroll`、`keypress`、`type`、`wait`、`screenshot` 之一）。`pending_safety_checks` 一律為空。

Yunshu 不會執行任何電腦動作。由你的用戶端執行動作、截圖，再以 `computer_call_output` 項目送回，其 `output` 為 `{"type": "computer_screenshot", "image_url": "..."}` 或 `{"file_id": "..."}`；模型需要具備視覺輸入才能讀懂截圖。沒有 `computer_screenshot` 的 `computer_call_output` 是 `400`。這是本機模型，並未像託管的電腦操作模型那樣專門訓練過，動作品質取決於你載入的模型。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-local" \
  -d '{
    "model": "local",
    "instructions": "Answer in one sentence.",
    "input": "Why is the sky blue?",
    "max_output_tokens": 200
  }'
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

first = client.responses.create(
    model="local",
    input="My name is Mei. Remember it.",
)
second = client.responses.create(
    model="local",
    previous_response_id=first.id,
    input="What is my name?",
)
print(second.output_text)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "sk-local" });

const stream = await client.responses.create({
  model: "local",
  input: "Write a haiku about autumn.",
  stream: true,
});
for await (const event of stream) {
  if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
}
```

</Tab>
</Tabs>

### 結構化輸出

```python
resp = client.responses.create(
    model="local",
    input="Extract: Ada Lovelace, born 1815.",
    text={
        "format": {
            "type": "json_schema",
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {"name": {"type": "string"}, "born": {"type": "integer"}},
                "required": ["name", "born"],
                "additionalProperties": False,
            },
        }
    },
)
print(resp.output_text)
```

### 函式工具迴圈

```python
tools = [{
    "type": "function",
    "name": "get_weather",
    "description": "Current weather for a city",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}]
r1 = client.responses.create(model="local", input="Weather in Taipei?", tools=tools)
call = next(i for i in r1.output if i.type == "function_call")
r2 = client.responses.create(
    model="local",
    previous_response_id=r1.id,
    tools=tools,
    input=[{"type": "function_call_output", "call_id": call.call_id, "output": '{"temp_c": 24}'}],
)
print(r2.output_text)
```

### 背景模式

```python
job = client.responses.create(model="local", input="Write a long story.", background=True)
print(job.status)  # queued
done = client.responses.retrieve(job.id)       # 輪詢，直到狀態不再是 queued / in_progress
client.responses.cancel(job.id)                # 或取消

# 背景 + 串流：讀取事件，並可從任一 sequence number 重新連線
stream = client.responses.create(model="local", input="Write a long story.", background=True, stream=True)
for ev in client.responses.retrieve(job_id, stream=True, starting_after=12):
    ...
```

回應仍在 `queued` 時送來的取消，會在開始產生之前就被處理。背景產生失敗時，儲存的狀態會變成 `failed`，`error.code` 為 `internal_error`。

## 回應

```json
{
  "id": "resp-3f2a9c1d5b7e4a60c8d19e22",
  "object": "response",
  "created_at": 1760000000,
  "completed_at": 1760000002,
  "status": "completed",
  "model": "local",
  "output": [
    {
      "type": "message",
      "id": "msg-0d4c7e9a1b2f3c4d5e6f7a8b",
      "role": "assistant",
      "status": "completed",
      "content": [
        { "type": "output_text", "text": "Sunlight scatters off air molecules, and blue scatters most.", "annotations": [] }
      ]
    }
  ],
  "usage": {
    "input_tokens": 28,
    "output_tokens": 14,
    "total_tokens": 42,
    "input_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 0 },
    "output_tokens_details": { "reasoning_tokens": 0 }
  },
  "instructions": "Answer in one sentence.",
  "tool_choice": "auto",
  "parallel_tool_calls": true,
  "store": true,
  "background": false,
  "truncation": "disabled",
  "previous_response_id": null,
  "metadata": null
}
```

物件中也會帶回請求設定（`temperature`、`top_p`、`max_output_tokens`、`tools`、`text`、`reasoning`、`service_tier` 等）。模型有推理時，`output` 最前面會有一個 `reasoning` 項目，其 `summary` 的類型為 `summary_text`。工具呼叫以 `function_call` 項目呈現，含 `call_id`、`name` 與 `arguments`。因 token 上限被截斷的回應，`status` 為 `incomplete`，並有 `incomplete_details.reason`。Yunshu 另外加上 `x_yunshu` 物件（計時、快取與推測解碼統計；有回合被丟棄時還有 `context_policy`），詳見[擴充功能](/docs/api/extensions)。

### 取回、刪除、取消

- `GET /v1/responses/{response_id}` 回傳已儲存的回應，找不到則回傳 `404`，code 為 `response_not_found`。
- `DELETE /v1/responses/{response_id}` 回傳 `{"id": "...", "object": "response.deleted", "deleted": true}`。
- `POST /v1/responses/{response_id}/cancel` 停止進行中的產生。對於已儲存且為 `queued` 或 `in_progress` 的回應，會儲存並回傳 `status: "cancelled"`；對已完成的回應則原樣回傳；未知的 id 回傳 `404`。

已儲存的回應存放在伺服器行程的記憶體中（保留最近 1024 筆），重新啟動後會消失。回應只對建立它的呼叫者可見。

### 列出輸入項目

`GET /v1/responses/{response_id}/input_items` 以 Responses 項目回傳該請求自己的輸入（含 `input_text` 或 `input_image` 部分的 `message`、`function_call`、`function_call_output`）。`instructions` 與系統、開發者訊息不會列出，透過 `previous_response_id` 取得的歷史屬於先前的回應。

| 查詢參數 | 說明 |
| --- | --- |
| `limit` | 1 到 100，預設 20。 |
| `order` | `desc`（預設）或 `asc`。 |
| `after`、`before` | 以項目 id 作為游標。未知的游標是 `404`，code 為 `item_not_found`。 |

結果為 `{"object": "list", "data": [...], "first_id", "last_id", "has_more"}`。

### 計算輸入 token

`POST /v1/responses/input_tokens` 接受與 `POST /v1/responses` 相同的本文（`model` 仍為必填），回傳：

```json
{ "object": "response.input_tokens", "input_tokens": 28 }
```

提示的建立方式與產生時相同（指示、項目、對話、壓縮項目、`previous_response_id` 串接、工具），並透過聊天範本轉譯，因此數字會等於同一請求的 `usage.input_tokens`。不計入伺服器端工具定義（`web_search`、`mcp`），也不會執行自動壓縮。

### 壓縮

`POST /v1/responses/compact` 壓縮一段對話。它接受 `model`，以及 `input`（字串或項目）和（或）`previous_response_id`，另有選用的 `instructions` 與 `tools`。所有使用者與開發者訊息都原文保留；其餘部分由一個不透明的 `compaction` 項目取代，裡面包著模型寫的摘要（最多 `YUNSHU_COMPACT_MAX_TOKENS` 個 token，預設 2048）。歷史太長、放不進上下文視窗時，會分多次摘要。

```json
{
  "id": "resp_9a8b7c6d5e4f3a2b1c0d9e8f",
  "object": "response.compaction",
  "created_at": 1760000000,
  "output": [
    { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": "..." }] },
    { "type": "compaction", "id": "cmp_0123456789abcdef01234567", "encrypted_content": "..." }
  ],
  "usage": { "input_tokens": 1200, "output_tokens": 180, "total_tokens": 1380 }
}
```

下一個請求把 `output` 當作 `input` 傳回去即可。`encrypted_content` 是摘要的 base64 封裝，並非加密；它只是讓用戶端把該項目當成不透明資料處理。

## 對話

Conversations API 把項目存放在伺服器端，讓你用 `conversation` 重複使用，而不必每次重送歷史。每個對話是 `YUNSHU_CONVERSATIONS_DIR`（預設 `~/.yunshu/conversations`）下的一個 JSON 檔，因此對話在重新啟動後仍會保留。

| 路由 | 說明 |
| --- | --- |
| `POST /v1/conversations` | 本文 `{"items": [...], "metadata": {...}}`，兩者皆可省略。每次呼叫最多 20 個項目、16 個 metadata 鍵。回傳 `{"id": "conv_...", "object": "conversation", "created_at", "metadata"}`。 |
| `GET /v1/conversations/{conversation_id}` | 取回。 |
| `POST /v1/conversations/{conversation_id}` | 取代 `metadata`（本文必填）。 |
| `DELETE /v1/conversations/{conversation_id}` | 回傳 `{"id", "object": "conversation.deleted", "deleted": true}`。 |
| `POST /v1/conversations/{conversation_id}/items` | 本文 `{"items": [...]}`（必填），每次最多 20 個。回傳清單。 |
| `GET /v1/conversations/{conversation_id}/items` | `limit` 1-100（預設 20）、`order` 為 `desc`（預設）或 `asc`、`after` 游標。 |
| `GET /v1/conversations/{conversation_id}/items/{item_id}` | 取回單一項目。 |
| `DELETE /v1/conversations/{conversation_id}/items/{item_id}` | 移除單一項目。 |

```python
conv = client.conversations.create()
client.responses.create(model="local", conversation=conv.id, input="I like green tea.")
r = client.responses.create(model="local", conversation=conv.id, input="What do I like?")
print(r.output_text)
```

錯誤使用 OpenAI 格式，code 包含 `conversation_not_found`、`item_not_found`、`invalid_json`、`missing_required_parameter` 與 `insufficient_storage`（`507`，磁碟已滿）。

## 串流

`stream: true` 時，回應為 Server-Sent Events：每則訊息的 `event:` 行等於其 JSON `data:` 的 `type`，並帶有遞增的 `sequence_number`。串流以 `data: [DONE]` 結束。長提示在預填階段時可能出現註解行（`: keep-alive`）。

一般產生依序送出：

1. `response.created`、`response.in_progress`
2. 有推理時：`response.output_item.added`（`reasoning` 項目）、`response.reasoning_summary_part.added`、`response.reasoning_summary_text.delta`、`response.reasoning_summary_text.done`、`response.reasoning_summary_part.done`、`response.output_item.done`
3. 訊息：`response.output_item.added`、`response.content_part.added`、重複的 `response.output_text.delta`、`response.output_text.done`、`response.content_part.done`、`response.output_item.done`
4. 每個函式呼叫：`response.output_item.added`（已帶有 `call_id`、`name`、`arguments`）、`response.function_call_arguments.done`、`response.output_item.done`。函式呼叫是整個一次送出，不會以引數 delta 分段。
5. 結尾事件：`response.completed`、`response.incomplete`（token 上限、逾時或取消）或 `response.failed`

視請求而定的其他事件：

| 事件 | 時機 |
| --- | --- |
| `response.custom_tool_call_input.delta`、`response.custom_tool_call_input.done` | `custom` 工具呼叫。 |
| `response.output_text.annotation.added` | 網路搜尋的 URL 引用。 |
| `response.web_search_call.in_progress`、`.searching`、`.completed` | 伺服器端網路搜尋。 |
| `response.mcp_list_tools.in_progress`、`.completed` | `mcp` 工具列出了某個伺服器的工具。 |
| `response.mcp_call.in_progress`、`response.mcp_call_arguments.delta`、`response.mcp_call_arguments.done`、`response.mcp_call.completed`、`response.mcp_call.failed` | 伺服器端的 `mcp` 呼叫。 |

串流開始後發生的錯誤，會是同一條串流上的結尾 `response.failed` 事件（不會再送出第二個 HTTP 回應）；`stream: true` 時遇到未知模型，也是以 code 為 `model_not_found` 的 `response.failed` 回報。

## WebSocket 模式

`WS /v1/responses` 使用 OpenAI 的 Responses WebSocket 模式（SDK 中的 `client.responses.connect()`）。來源（Origin）與 token 檢查在升級之前進行；設定了 `YUNSHU_AUTH_TOKEN` 時，請以 `Authorization: Bearer ...`、`x-api-key` 或 `token` 查詢參數送出 token。

用戶端訊息（JSON 文字訊框）：

| 訊息 | 說明 |
| --- | --- |
| `{"type": "response.create", ...body}` | 本文欄位與 `POST /v1/responses` 相同；`stream` 會被強制開啟。選用的 `stream_id` 會把請求放進同一條通道（通道內先進先出，不同通道並行；最多 32 條），選用的 `client_request_id` 為請求命名。 |
| `{"type": "response.cancel", "id": "..."}` | 依 `client_request_id` 或 `stream_id` 取消。沒有 id 時會取消此連線上所有進行中的請求。未知的 id 會回傳 `404` 錯誤訊息。 |
| `{"type": "ping"}` | 以 `{"type": "pong"}` 回應。 |

伺服器送出與 SSE 串流相同的 `response.*` 事件，每個訊框一個 JSON 物件。不屬於某個回應的失敗，以 `{"type": "error", "status": 400, "error": {"message", "type"}}` 送達：JSON 無效、未知的訊息類型、重複的進行中請求 id（`409`），或同時請求過多（`429`，每個連線預設 16 個，設定為 `YUNSHU_WS_MAX_INFLIGHT`）。對外事件依連線緩衝（`YUNSHU_WS_SEND_QUEUE`）；讀取過慢的用戶端會讓產生暫停，而不是讓緩衝區無限增長。關閉連線會取消其進行中的請求。

```python
with client.responses.connect() as conn:
    conn.response.create(model="local", input="Say hi.")
    for event in conn:
        if event.type == "response.output_text.delta":
            print(event.delta, end="")
        if event.type in ("response.completed", "response.failed"):
            break
```

## 錯誤

錯誤使用 OpenAI 格式 `{"error": {"message", "type", "param", "code"}}`。

| 狀態 | 原因 |
| --- | --- |
| `400` | 本文或欄位無效（`input` 為空、`stop` 超過 16 個、`logit_bias` 超出範圍、`metadata` 超過 16 組）、`truncation` 為 disabled 時提示超出上下文視窗（`context_length_exceeded`）、模型不支援所要求的功能、`conversation` 與 `previous_response_id` 並用、不支援的工具組合、格式錯誤的 `computer_call_output`。 |
| `401` / `403` | 缺少或錯誤的 token；金鑰沒有該模型的權限。 |
| `404` | 未知的模型（多模型模式）、未知的回應（`response_not_found`）或檔案參照。 |
| `413` | 提示太大，記憶體無法預填。 |
| `424` | 無法連線到 `mcp` 工具伺服器（`external_connector_error`）。 |
| `502` | 模型為用戶端工具產生了格式錯誤的引數，例如無效的 `computer` 動作。 |
| `503` | 沒有載入任何模型。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| `POST /v1/responses`，串流與非串流 | <Support status="supported">支援</Support> |
| 取回、刪除、取消、輸入項目、輸入 token、壓縮 | <Support status="supported">支援</Support> |
| `previous_response_id` 串接、`store` | <Support status="supported">支援（存於記憶體，重新啟動後消失）</Support> |
| 背景模式 | <Support status="supported">支援，可搭配 `stream` 與伺服器端工具</Support> |
| Conversations API | <Support status="supported">支援（持久化）</Support> |
| `text.format` json_schema 與 json_object | <Support status="supported">支援</Support> |
| function、namespace、custom、local_shell、用戶端 tool_search | <Support status="supported">支援</Support> |
| `computer` 工具 | <Support status="partial">由用戶端執行；伺服器從不執行動作</Support> |
| `web_search`、`mcp` | <Support status="supported">支援，由伺服器執行</Support> |
| `code_interpreter`、託管 `shell` | <Support status="partial">由伺服器於 srt 內執行，需手動開啟（`YUNSHU_CODE_EXECUTION`）</Support> |
| `reasoning.summary` 產生、託管式 `tool_search`、`file_search`、`image_generation` | <Support status="unsupported">尚未支援</Support> |
| 恢復背景串流（`starting_after`） | <Support status="supported">支援（事件保存在記憶體，重新啟動後消失）</Support> |
| WebSocket 模式 | <Support status="supported">支援</Support> |

## 相關頁面

- [Chat Completions](/docs/api/chat-completions)
- [伺服器端工具](/docs/api/server-tools)
- [結構化輸出](/docs/guides/structured-output)
- [提示快取](/docs/guides/prompt-caching)
- [擴充功能](/docs/api/extensions)


---

<!-- api/server-tools -->
---
title: 伺服器端工具
description: 網路搜尋、網頁擷取與 MCP 連接器，由 Yunshu 在產生迴圈內為 Anthropic Messages 與 OpenAI Responses 請求執行。
---

Anthropic 與 OpenAI 的 API 中，有些工具是由伺服器執行，而不是由你的用戶端執行。Yunshu 支援其中三種：網路搜尋、網頁擷取（僅 Anthropic），以及呼叫遠端 MCP 伺服器的連接器。請求宣告了其中之一時，Yunshu 會在單一請求內跑一個迴圈：模型產生內容、呼叫伺服器端工具、Yunshu 執行它（非同步、在模型執行緒之外、有逾時限制）、附加結果，再繼續產生，直到模型不再呼叫伺服器端工具為止。你拿到的是一個回應，其內容會交錯排列工具區塊與最終文字。每一輪都會重送相同的對話加上新的回合，所以前綴快取會提供共用的前綴，續接時只需要預填新增的 token。

| 工具 | Anthropic Messages | OpenAI Responses |
| --- | --- | --- |
| 網路搜尋 | `web_search_20250305` | `web_search`、`web_search_preview` |
| 網頁擷取 | `web_fetch_20250910` | API 中沒有 |
| MCP 連接器 | `mcp_servers` + `mcp_toolset` | `{"type": "mcp"}` |

路由是 [`POST /v1/messages`](/docs/api/messages) 與 [`POST /v1/responses`](/docs/api/responses)，沒有獨立的端點。

<Callout type="warn">
使用預設提供者的網路搜尋，會把你的查詢文字（以及你的 IP 位址）送到第三方搜尋服務。只有在請求宣告了網路搜尋工具、而且模型呼叫它時才會送出。設定 `YUNSHU_WEB_SEARCH_PROVIDER=none` 可完全停用搜尋。見[網路搜尋](/docs/guides/web-search)。
</Callout>

## 設定

伺服器端工具由伺服器的設定控制（見[設定](/docs/guides/configuration)）；請求只負責宣告工具。

| 設定 | 預設 | 意義 |
| --- | --- | --- |
| `YUNSHU_WEB_SEARCH_PROVIDER` | `auto` | 搜尋後端：`auto`、`none`、`searxng`、`brave`、`tavily`、`exa`、`serper`、`perplexity`、`ddg_html`、`wikipedia`、`mwmbl`、`mojeek`、`marginalia`。`auto` 會並行查詢多個輕量與已設定的提供者並合併結果；`none` 停用搜尋。 |
| `YUNSHU_WEB_KEYLESS` | 開啟 | 在 `auto` 模式下允許免金鑰的 DuckDuckGo（盡力而為，可能被封鎖）與 Wikipedia。 |
| `YUNSHU_SEARXNG_URL` | 未設定 | 自行架設的 SearXNG 基底 URL（需啟用 JSON 輸出）。選用。 |
| `YUNSHU_BRAVE_API_KEY`、`YUNSHU_TAVILY_API_KEY`、`YUNSHU_EXA_API_KEY`、`YUNSHU_SERPER_API_KEY`、`YUNSHU_PERPLEXITY_API_KEY`、`YUNSHU_MOJEEK_API_KEY`、`YUNSHU_MARGINALIA_API_KEY` | 未設定 | 需要金鑰的提供者所用的金鑰。設定後會加入 `auto`。 |
| `YUNSHU_WEB_SEARCH_RESULTS` | 5 | 每次搜尋呼叫回傳的結果數。 |
| `YUNSHU_WEB_SEARCH_PROVIDER_TIMEOUT` | 1.0 秒 | `auto` 模式下每個提供者的期限。 |
| `YUNSHU_WEB_RESEARCH` | 關閉 | 用來源頁面的摘錄豐富化搜尋摘要（被擷取的 URL 會離開本機）。 |
| `YUNSHU_WEB_FETCH` | 開啟 | 提供 `web_fetch`。關閉時，網頁擷取請求會得到 `unavailable` 錯誤。 |
| `YUNSHU_WEB_FETCH_ALLOW_PRIVATE` | 關閉 | 讓 `web_fetch` 可以連到私有、loopback 與 link-local 位址。 |
| `YUNSHU_WEB_FETCH_MAX_BYTES` | 2000000 | 下載本文大小上限。 |
| `YUNSHU_WEB_FETCH_TIMEOUT` | 20 秒 | 每個頁面的期限。 |
| `YUNSHU_WEB_FETCH_MAX_TEXT_CHARS` | 40000 | 交給模型的擷取文字會截到此長度。 |
| `YUNSHU_MCP_CONNECTOR` | 開啟 | 提供 MCP 連接器。 |
| `YUNSHU_MCP_CONNECTOR_ALLOW_PRIVATE` | 開啟 | 讓連接器可以連到私有與 loopback 的 MCP 伺服器（本機工具伺服器是常見情境）。關閉後只允許公開位址。 |
| `YUNSHU_MCP_CONNECTOR_TIMEOUT` | 30 秒 | 每次呼叫（initialize、`tools/list`、`tools/call`）。 |
| `YUNSHU_MCP_CONNECTOR_MAX_BYTES` | 8 MiB | MCP 伺服器單一回覆的大小上限。 |
| `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` | 8 | 單一請求中「產生、執行、繼續」的最大輪數。 |

沒有可用的搜尋提供者時，搜尋請求不會讓整個呼叫失敗：工具結果會帶 `unavailable` 錯誤，回應的 `x_yunshu.server_tools` 物件會附上設定提示。`GET /v1/models` 會在 `yunshu.server_tools` 下顯示各工具目前的狀態（`web_search.available` 與提供者、`web_fetch.available`、`mcp_connector.available`）。

## Anthropic Messages

### 網路搜尋

在 `tools` 中宣告：

```json
{ "type": "web_search_20250305", "name": "web_search", "max_uses": 3, "allowed_domains": ["docs.python.org"], "user_location": {"type": "approximate", "country": "TW"} }
```

| 欄位 | 狀態 | 說明 |
| --- | --- | --- |
| `max_uses` | 支援 | 單一請求中達到此呼叫次數後，後續呼叫會得到 `max_uses_exceeded` 錯誤結果。 |
| `allowed_domains`、`blocked_domains` | 支援 | 依網域過濾結果（網域也會比對其子網域）。 |
| `user_location` | 支援 | 作為位置提示傳給搜尋提供者。 |
| `cache_control`、`allowed_callers`、`defer_loading` | 接受但忽略 | |

回應內容會交錯出現下列區塊：

```json
[
  { "type": "server_tool_use", "id": "srvtoolu_...", "name": "web_search", "input": { "query": "python 3.13 release date" } },
  {
    "type": "web_search_tool_result",
    "tool_use_id": "srvtoolu_...",
    "content": [
      { "type": "web_search_result", "url": "https://...", "title": "...", "encrypted_content": "...", "page_age": null }
    ]
  },
  {
    "type": "text",
    "text": "Python 3.13 was released in October 2024 [1].",
    "citations": [
      { "type": "web_search_result_location", "url": "https://...", "title": "...", "encrypted_index": "...", "cited_text": "..." }
    ]
  }
]
```

搜尋失敗時回傳 `content: {"type": "web_search_tool_result_error", "error_code": "..."}`，錯誤碼有 `unavailable`、`max_uses_exceeded`、`too_many_requests`、`invalid_input`、`query_too_long`（查詢超過 400 個字元）。`usage.server_tool_use.web_search_requests` 記錄呼叫次數。

### 網頁擷取

```json
{ "type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5, "allowed_domains": ["example.com"], "max_content_tokens": 20000 }
```

支援 `max_uses`、`allowed_domains`、`blocked_domains` 與 `max_content_tokens`（把文字上限降到約每個 token 四個字元）。結果區塊：

```json
{
  "type": "web_fetch_tool_result",
  "tool_use_id": "srvtoolu_...",
  "content": {
    "type": "web_fetch_result",
    "url": "https://example.com/",
    "retrieved_at": "2026-01-01T00:00:00Z",
    "content": {
      "type": "document",
      "title": "Example Domain",
      "citations": { "enabled": false },
      "source": { "type": "text", "media_type": "text/markdown", "data": "..." }
    }
  }
}
```

HTML 會轉成 Markdown；text、JSON 與 XML 類型以文字回傳。其他內容類型（包含 PDF 與圖片）會以 `unsupported_content_type` 失敗。錯誤以 `web_fetch_tool_result_error` 回傳，`error_code` 為 `url_not_allowed`、`url_not_accessible`、`unsupported_content_type`、`url_too_long`（URL 超過 250 個字元）、`invalid_tool_input`、`too_many_requests`、`max_uses_exceeded` 或 `unavailable`。`usage.server_tool_use.web_fetch_requests` 記錄呼叫次數。擷取的內容不可被引用：結果文件的 `citations.enabled` 為 false。

### 引用

文字區塊上的引用，是根據模型在它所用結果旁邊寫的 `[n]` 標記建立的。每一筆是 `web_search_result_location`，帶有該結果的 `url` 與 `title`、取自最相符段落或摘要的最多 150 字元 `cited_text`，以及 `encrypted_index`。`encrypted_content` 與 `encrypted_index` 是不透明的封裝，讓後續請求可以重放這些結果；本機伺服器沒有需要對自己的用戶端隱藏的東西，所以它們並未加密。`page_age` 取決於提供者回傳什麼，常常是 `null`。模型是否會寫 `[n]` 標記取決於模型，小模型可能根據搜尋結果回答，卻沒有產生引用。文件引用是另一項功能，見 [Messages](/docs/api/messages)。

### pause_turn

迴圈達到 `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` 輪、模型仍在呼叫伺服器端工具時，訊息會以 `stop_reason: "pause_turn"` 結束。把回應內容當作助理回合送回去，就能繼續。

### 程式碼執行

`code_execution_20250522`、`_20250825`、`_20260120` 與 `_20260521` 在本機的 Anthropic sandbox-runtime 內執行。預設關閉：設 `YUNSHU_CODE_EXECUTION=1` 並安裝 `@anthropic-ai/sandbox-runtime`（Node 22.12 以上）。關閉時宣告此工具的請求回 `400`；開啟但沒有 runtime 時回 `503`；指令絕不會在沙盒外執行。回應含 `*_tool_result` 區塊與可回傳的 `container`。沙盒只能寫入自己的容器、讀不到你的家目錄，除非用 `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW` 列出主機，否則沒有網路。

| 版本 | 子工具 | Python 直譯器 |
| --- | --- | --- |
| `20250522` | `code_execution`（Python） | 每次呼叫全新行程 |
| `20250825` | `bash_code_execution`、`text_editor_code_execution`（若有客戶端工具列出 code execution 呼叫者，再加 `code_execution`） | 每次呼叫全新行程 |
| `20260120`、`20260521` | 三者皆有 | 每個容器一個行程：變數在呼叫之間保留（REPL 狀態） |

bash 寫入 `$OUTPUT_DIR` 的檔案與 Python cell 產生的檔案，都以 Files API id 回傳。**程式化工具呼叫：** 工具若設 `"allowed_callers": ["code_execution_20260120"]`，就成為直譯器中的 `async` Python 函式。程式碼 await 它時，該回合以 `stop_reason: "tool_use"` 結束，每個呼叫一個帶 `caller: {type, tool_id}` 的 `tool_use` 區塊；帶著 `container` 把工具結果送回，回應就接著給出 `code_execution_tool_result`。模型自己的歷史只有那次程式碼呼叫與最終結果。暫停的 cell 最多等候 270 秒。詳見[指南](https://github.com/yuhuanowo/Yunshu/blob/main/docs/guides/CODE_EXECUTION.md)。

### OpenAI code interpreter、shell 與容器

同一個設定下，OpenAI Responses 請求可宣告 `{"type": "code_interpreter", "container": {"type": "auto"}}`（或容器 id）與託管的 `{"type": "shell", "environment": {"type": "container_auto"}}`（或 `container_reference`）。回應有 `code_interpreter_call` 項目（`code`、`container_id`，加上 `include: ["code_interpreter_call.outputs"]` 才有 `outputs`）、`shell_call` / `shell_call_output` 項目、串流事件 `response.code_interpreter_call.*`、`response.code_interpreter_call_code.*`、`response.shell_call_command.*`、`response.shell_call_output_content.*`，以及程式碼產生的檔案的 `container_file_citation` 註解。Python 狀態保留在容器內；`previous_response_id` 會重用它。`environment` 為 `local` 的 `shell` 工具由你的客戶端執行。

這些背後的容器有 OpenAI containers API。`expires_after` 是閒置壽命（上限為 `YUNSHU_CODE_EXECUTION_TTL_MIN`），`memory_limit` 是 `YUNSHU_CODE_EXECUTION_MEMORY_MB` 之下的上限，`network_policy` 只能縮小 `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW`。檔案位於 `/mnt/data/<name>`。

<Endpoint method="POST" path="/v1/containers" />
<Endpoint method="GET" path="/v1/containers" />
<Endpoint method="GET" path="/v1/containers/{container_id}" />
<Endpoint method="DELETE" path="/v1/containers/{container_id}" />
<Endpoint method="POST" path="/v1/containers/{container_id}/files" />
<Endpoint method="GET" path="/v1/containers/{container_id}/files" />
<Endpoint method="GET" path="/v1/containers/{container_id}/files/{file_id}" />
<Endpoint method="GET" path="/v1/containers/{container_id}/files/{file_id}/content" />
<Endpoint method="DELETE" path="/v1/containers/{container_id}/files/{file_id}" />

### MCP 連接器

在頂層 `mcp_servers` 宣告遠端 MCP 伺服器，並可在 `tools` 中為每個伺服器加一筆 `mcp_toolset`：

```json
{
  "mcp_servers": [
    { "type": "url", "name": "docs", "url": "https://mcp.example.com/mcp", "authorization_token": "secret" }
  ],
  "tools": [
    { "type": "mcp_toolset", "mcp_server_name": "docs", "default_config": { "enabled": true }, "configs": { "dangerous_tool": { "enabled": false } } }
  ]
}
```

| 欄位 | 狀態 | 說明 |
| --- | --- | --- |
| `mcp_servers[].name`、`url` | 支援 | 兩者皆必填。 |
| `mcp_servers[].authorization_token` | 支援 | 以 bearer token 送出。 |
| `mcp_servers[].headers` | 擴充 | 額外的請求標頭。 |
| `mcp_servers[].tool_configuration` | 支援 | 較早的 beta 寫法：`enabled` 與 `allowed_tools`。 |
| `mcp_toolset.default_config.enabled`、`configs.{tool}.enabled` | 支援 | 啟用或停用個別工具。 |
| toolset 中的 `defer_loading`、`cache_control` | 接受但忽略 | |

閘道在請求開始時連線（Streamable HTTP，失敗時退回較舊的 HTTP+SSE 傳輸），列出工具，並把啟用的工具以 `<server>__<tool>` 的名稱呈現給模型。工具呼叫會產生 `mcp_tool_use`（含 `server_name`）與 `mcp_tool_result`（含 `is_error` 與文字 `content`）。工具結果會截到 100000 個字元。同一回合中的呼叫並行執行。沒有核准步驟。無法連線的伺服器會得到 `400 invalid_request_error`。

## OpenAI Responses

### 網路搜尋

```json
{ "type": "web_search", "filters": { "allowed_domains": ["docs.python.org"] }, "user_location": {"type": "approximate", "country": "TW"}, "search_context_size": "medium" }
```

支援 `filters.allowed_domains` 與 `user_location`；`search_context_size` 會被接受，但沒有作用。模型也可以開啟頁面並在其中搜尋（`open_page` 與 `find_in_page` 動作）。輸出包含一個 `web_search_call` 項目（`action` 含 `type`、`query`；`status` 為 `completed` 或 `failed`），接著是一個 `message`，其 `output_text` 帶有 `url_citation` 註解（`start_index`、`end_index`、`url`、`title`），由模型的 `[n]` 標記建立。加上 `include: ["web_search_call.action.sources"]` 可在 `action.sources` 列出結果 URL。`max_tool_calls` 限制搜尋次數；超過上限的呼叫會失敗，並把訊息交給模型。

### mcp 工具

```json
{
  "type": "mcp",
  "server_label": "docs",
  "server_url": "https://mcp.example.com/mcp",
  "authorization": "secret",
  "allowed_tools": ["search"],
  "require_approval": "never"
}
```

| 欄位 | 狀態 | 說明 |
| --- | --- | --- |
| `server_label`、`server_url` | 支援 | 兩者皆必填（否則 `400`）。 |
| `authorization`、`headers` | 支援 | MCP 伺服器的憑證；不會在回應的 `tools` 中回顯。 |
| `allowed_tools` | 支援 | 名稱清單，或 `{"tool_names": [...]}`。 |
| `require_approval` | 支援 | `"never"` 會立即執行工具。預設值（`"always"`），或列出 `never.tool_names` 的物件，會讓模型的呼叫停在 `mcp_approval_request` 項目；在下一個請求（搭配 `previous_response_id`）送出 `mcp_approval_response` 項目（`approval_request_id`、`approve`、`reason`）來執行或拒絕。 |
| `connector_id` | 尚未支援 | OpenAI 託管的連接器會得到 `400`（`unsupported_connector`）；請改傳伺服器 URL。 |

某個伺服器的第一個回應會包含 `mcp_list_tools` 項目；之後帶有該項目的請求（或含有它的已儲存回應）會略過列出步驟。呼叫以 `mcp_call` 項目呈現，含 `arguments`、`output`、`error` 與 `approval_request_id`。無法連線的伺服器會得到 `424`，code 為 `external_connector_error`。

## 網路安全

- `web_fetch` 會自行解析主機名稱，在連線前以及每一次重新導向時（最多 5 次，每次都重新驗證）拒絕私有、loopback 與 link-local 位址，包含雲端中繼資料位址。連線會固定在驗證過的位址，因此檢查與請求之間 DNS 回答不會改變。不會送出 cookie。`YUNSHU_WEB_FETCH_ALLOW_PRIVATE=1` 可解除限制。
- Messages 上的圖片與 PDF `url` 來源以相同方式檢查。
- MCP 連接器預設是例外：它可以連到私有與 loopback 伺服器（`YUNSHU_MCP_CONNECTOR_ALLOW_PRIVATE`），因為本機工具伺服器是正常情境。如果不受信任的用戶端能連到你的伺服器，請關閉它。
- 搜尋查詢與擷取的頁面都是由模型控制的輸入。擷取的文字會以工具輸出的形式進入模型，所以頁面可能試圖左右模型；請把伺服器端工具當作任何會讀取開放網路的工具來對待。

## 限制與尚未支援的部分

- 託管的記憶工具、檔案搜尋、圖片生成與 OpenAI 託管連接器皆無法使用。程式碼執行（Anthropic `code_execution_*`、OpenAI `code_interpreter` 與託管 `shell`）需手動開啟（見上）；OpenAI 的 `programmatic_tool_calling` 與容器 skills 尚未實作。
- `web_fetch` 不讀取 PDF 或圖片，也無法執行 JavaScript。
- 網路搜尋品質取決於你設定的提供者；免金鑰的預設值是盡力而為。
- Responses API 沒有網頁擷取工具；請使用 `mcp` 的 fetch 伺服器，或改走 Anthropic 路由。
- 同一個 Responses 請求中，伺服器端工具不能與 `custom`、`local_shell`、`tool_search` 或 `computer` 工具混用（`400`）。一般的函式工具可以與伺服器端工具並用；函式呼叫會回傳給你的用戶端。
- Responses 請求中，`background: true` 不能與 `web_search` 或 `mcp` 並用（`400`）。

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| Anthropic `web_search_20250305` | <Support status="supported">支援</Support> |
| Anthropic `web_fetch_20250910` | <Support status="supported">支援（文字、HTML）</Support> |
| Anthropic `mcp_servers` + `mcp_toolset` | <Support status="supported">支援</Support> |
| Responses `web_search` / `web_search_preview` | <Support status="supported">支援</Support> |
| Responses `mcp` 工具、核准 | <Support status="supported">支援</Support> |
| Responses `connector_id` 連接器 | <Support status="unsupported">尚未支援</Support> |
| 長迴圈的 `pause_turn` | <Support status="supported">僅 Anthropic</Support> |
| 網頁擷取的引用、PDF 擷取 | <Support status="unsupported">尚未支援</Support> |

## 相關頁面

- [Messages](/docs/api/messages)
- [Responses](/docs/api/responses)
- [網路搜尋指南](/docs/guides/web-search)
- [設定](/docs/guides/configuration)
- [代理程式](/docs/guides/agents)


---

<!-- api/stored-completions -->
---
title: 儲存的 completions
description: 以 store true 把 chat completion 保存在本機磁碟，再用 OpenAI 的 stored-completions 路由列出、查詢、加標籤與刪除。
---

在 chat completion 請求上設定 `store: true`，Yunshu 就會把完成的 completion 連同你送出的訊息一起保存。下列路由可以列出、查詢、重新標記與刪除這些紀錄，遵循 OpenAI 的 stored-completions API。所有資料都在你的磁碟上，不會送到任何地方。

<Endpoint method="POST" path="/v1/chat/completions" />
<Endpoint method="GET" path="/v1/chat/completions" />
<Endpoint method="GET" path="/v1/chat/completions/{completion_id}" />
<Endpoint method="POST" path="/v1/chat/completions/{completion_id}" />
<Endpoint method="DELETE" path="/v1/chat/completions/{completion_id}" />
<Endpoint method="GET" path="/v1/chat/completions/{completion_id}/messages" />

<Callout type="info">
只有在設定 `YUNSHU_AUTH_TOKEN` 時才會強制驗證；設定後，這些路由和其他推論路由一樣需要 token。見 [API 總覽](/docs/api/overview)。
</Callout>

## 儲存的運作方式

- 在 `POST /v1/chat/completions` 上送出 `store: true`（可再加 `metadata`）。沒有 `store` 就不會寫入任何東西。
- 非串流的 completion 在回應為 `200` 時儲存。串流的 completion 則在串流以 `data: [DONE]` 正常結束時儲存：各區塊會被重新組合成單一個 `chat.completion` 物件（內容、`reasoning_content`、工具呼叫、logprobs、usage）。中途斷線或以錯誤結束的串流不會被儲存。
- 每筆紀錄包含 completion 物件與輸入訊息。`n` 大於 1 時，所有選項都會儲存。
- 紀錄是 JSON 檔案，每個 completion 一個，放在 `~/.yunshu/chat_completions`（可用 `YUNSHU_CHAT_COMPLETIONS_DIR` 變更）。紀錄數超過 `YUNSHU_CHAT_COMPLETIONS_MAX`（預設 5000）時，最舊的會被刪除。
- 儲存失敗不會讓請求失敗：只會記入日誌，回應照常回傳。
- 檔案是純 JSON。你訊息中的圖片 data URL 會照原樣儲存，所以單筆紀錄可能很大。

### Metadata

`metadata` 是最多 16 組字串鍵值的物件；鍵最長 64 字元，值最長 512 字元。超出限制或不是字串，會回應 `400` 並帶 `param: "metadata"`。它會隨儲存的 completion 一併回傳，也可作為列表的過濾條件。

## 列出儲存的 completions

`GET /v1/chat/completions` 回傳一頁儲存的 completions。

| 查詢參數 | 型別 | 說明 |
| --- | --- | --- |
| `limit` | integer | `1` 至 `100`。預設 `20`。 |
| `order` | string | `asc`（最舊在前，預設）或 `desc`。 |
| `after` | string | 從哪個 completion id 之後繼續。未知的 id 會回應 `400`。 |
| `model` | string | 只列出 `model` 等於此值的 completions。 |
| `metadata[key]` | string | 只列出 metadata 中該鍵恰好等於此值的 completions。可重複指定多個鍵，必須全部符合。 |

```bash
curl -G http://localhost:8000/v1/chat/completions \
  --data-urlencode "limit=10" \
  --data-urlencode "order=desc" \
  --data-urlencode "metadata[session]=demo"
```

```json
{
  "object": "list",
  "data": [
    {
      "id": "chatcmpl-9f2c4e1ab07d4c3e8a51b2c6",
      "object": "chat.completion",
      "created": 1760000000,
      "model": "local",
      "choices": [{ "index": 0, "message": { "role": "assistant", "content": "Hello!" }, "finish_reason": "stop" }],
      "usage": { "prompt_tokens": 12, "completion_tokens": 3, "total_tokens": 15 },
      "metadata": { "session": "demo" }
    }
  ],
  "first_id": "chatcmpl-9f2c4e1ab07d4c3e8a51b2c6",
  "last_id": "chatcmpl-9f2c4e1ab07d4c3e8a51b2c6",
  "has_more": false
}
```

## 查詢、更新與刪除

| 路由 | 行為 |
| --- | --- |
| `GET /v1/chat/completions/{completion_id}` | 回傳儲存的 `chat.completion` 物件，含 `metadata`。 |
| `POST /v1/chat/completions/{completion_id}` | 本文為 `{"metadata": {...}}`。整個 metadata 物件會被取代（傳 `{}` 即清空），並回傳更新後的 completion。`metadata` 為必填。 |
| `DELETE /v1/chat/completions/{completion_id}` | 刪除紀錄，回傳 `{"id": "...", "object": "chat.completion.deleted", "deleted": true}`。 |
| `GET /v1/chat/completions/{completion_id}/messages` | 列出該 completion 的輸入訊息。與列表路由一樣接受 `limit`、`order` 與 `after`。 |

訊息列表中的每一則是你送出的訊息，外加產生的 `id`（`msg_...`）。原本 `content` 是陣列時，`content` 會變成串接後的文字，而 `content_parts` 保留 `text` 與 `image_url` 區塊；否則 `content_parts` 為 `null`。

## 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
# Store a completion
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "local",
    "store": true,
    "metadata": {"session": "demo"},
    "messages": [{"role": "user", "content": "Say hello."}]
  }'

# Fetch, relabel and delete it
curl http://localhost:8000/v1/chat/completions/chatcmpl-9f2c4e1ab07d4c3e8a51b2c6
curl -X POST http://localhost:8000/v1/chat/completions/chatcmpl-9f2c4e1ab07d4c3e8a51b2c6 \
  -H "Content-Type: application/json" -d '{"metadata": {"session": "demo", "reviewed": "yes"}}'
curl http://localhost:8000/v1/chat/completions/chatcmpl-9f2c4e1ab07d4c3e8a51b2c6/messages
curl -X DELETE http://localhost:8000/v1/chat/completions/chatcmpl-9f2c4e1ab07d4c3e8a51b2c6
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

created = client.chat.completions.create(
    model="local",
    store=True,
    metadata={"session": "demo"},
    messages=[{"role": "user", "content": "Say hello."}],
)

stored = client.chat.completions.retrieve(created.id)
client.chat.completions.update(created.id, metadata={"session": "demo", "reviewed": "yes"})

for c in client.chat.completions.list(metadata={"session": "demo"}, order="desc", limit=10):
    print(c.id, c.metadata)

for m in client.chat.completions.messages.list(created.id):
    print(m.role, m.content)

client.chat.completions.delete(created.id)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "sk-local" });

const created = await client.chat.completions.create({
  model: "local",
  store: true,
  metadata: { session: "demo" },
  messages: [{ role: "user", content: "Say hello." }],
});

const stored = await client.chat.completions.retrieve(created.id);
await client.chat.completions.update(created.id, { metadata: { reviewed: "yes" } });
for await (const c of client.chat.completions.list({ order: "desc", limit: 10 })) {
  console.log(c.id);
}
await client.chat.completions.delete(created.id);
```

</Tab>
</Tabs>

## 錯誤

錯誤採用 OpenAI 格式 `{"error": {"message", "type": "invalid_request_error", "param", "code"}}`。

| 狀態碼 | `code` | 時機 |
| --- | --- | --- |
| 400 | `invalid_type`、`invalid_value` | `limit` 不是整數或不在 `1` 至 `100`；`order` 不是 `asc` 或 `desc`；`after` 不在列表中（`param` 會指出欄位）。 |
| 400 | `invalid_json` | 更新請求的本文不是 JSON。 |
| 400 | `missing_required_parameter` | 更新請求的本文沒有 `metadata`。 |
| 400 | `invalid_type`、`metadata_too_large` | Metadata 不是字串物件、超過 16 組鍵值，或鍵或值太長。 |
| 401 | | 已設定 token，但缺少或不正確。 |
| 404 | `not_found` | 沒有符合該 id 的儲存 completion。看起來不像 `chatcmpl-...` 的 id 同樣是 `404`。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 非串流與串流 chat completion 上的 `store: true` | <Support status="supported">支援</Support> |
| 以 `limit`、`order`、`after`、`model`、`metadata[...]` 過濾列表 | <Support status="supported">支援</Support> |
| 查詢、更新 metadata、刪除、列出訊息 | <Support status="supported">支援</Support> |
| 在這裡儲存 Responses API 物件 | <Support status="unsupported">不適用；見 Responses</Support> |
| 本機磁碟以外的儲存、單筆紀錄到期 | <Support status="unsupported">尚未支援；只有數量上限會淘汰舊紀錄</Support> |

## 相關頁面

- [Chat completions](/docs/api/chat-completions)
- [Responses](/docs/api/responses)
- [API 總覽](/docs/api/overview)
- [設定](/docs/guides/configuration)


---

<!-- api/tokenization -->
---
title: Tokenization
description: 以 vLLM 風格的 tokenize、detokenize 與 apply-template 路由計算並檢視 token，另有 llama.cpp 風格的 props 路由。
---

這些路由開放已載入模型的 tokenizer 與聊天模板。你可以在送出長提示詞前先計算 token 數、檢查對話如何被轉成模板文字，或把 token id 還原成文字。請求與回應結構遵循 vLLM 的 `/tokenize` 與 `/detokenize`。每個路由都同時提供帶 `/v1` 前綴與不帶前綴的版本。

<Endpoint method="POST" path="/v1/tokenize" />
<Endpoint method="POST" path="/v1/detokenize" />
<Endpoint method="POST" path="/v1/apply-template" />
<Endpoint method="POST" path="/tokenize" />
<Endpoint method="POST" path="/detokenize" />
<Endpoint method="POST" path="/apply-template" />
<Endpoint method="GET" path="/v1/props" />

<Callout type="info">
只有在設定 `YUNSHU_AUTH_TOKEN` 時才會強制驗證，見 [API 總覽](/docs/api/overview)。若要用 Anthropic 風格計算 token，請使用 `POST /v1/messages/count_tokens`，說明在 [Messages](/docs/api/messages) 頁面。
</Callout>

## 選擇 tokenizer

三個路由的 `model` 都是選填。tokenizer 來自已載入的模型：

- 單模型模式下，一律使用載入模型的 tokenizer，`model` 僅供參考。
- 多模型模式下，模型必須已經載入。名稱會先精確比對，再不分大小寫比對，最後比對最後一個 `/` 之後的部分。未載入或未知的模型會回應 `404`，訊息為 `No tokenizer available for model '...'`。伺服器絕不會拿別的模型的詞彙表來回答。

## Tokenize

### 請求

`prompt` 與 `messages` 必須恰好送一個；兩個都送或都不送會回應 `400`。

| 參數 | 型別 | 必填 | 說明 | 狀態 |
| --- | --- | --- | --- | --- |
| `model` | string | 否 | 見上文。 | 支援 |
| `prompt` | string 或字串陣列 | 二選一 | 原始文字。陣列會逐一 tokenize。別名：`text`、`input`。 | 支援 |
| `messages` | array | 二選一 | 聊天訊息，tokenize 前會先以模型的聊天模板轉換。陣列形式的 `content` 只保留其中的 `text` 區塊；圖片與其他媒體不計入。 | 支援 |
| `add_special_tokens` | boolean | 否 | 搭配 `prompt`：預設 `true`。搭配 `messages`：預設 `false`，因為模板本身已包含特殊 token。 | 支援 |
| `add_generation_prompt` | boolean | 否 | 僅限 `messages`。預設 `true`：結尾加上 assistant 回合的開頭。 | 支援 |
| `continue_final_message` | boolean | 否 | 僅限 `messages`。接續最後一則訊息，而不是開啟新回合；會關閉 `add_generation_prompt`。 | 支援 |
| `tools` | array | 否 | 僅限 `messages`。交給模板轉換的工具定義。 | 支援 |
| `chat_template_kwargs` | object | 否 | 僅限 `messages`。額外的模板變數，例如 `enable_thinking`。 | 支援 |
| `return_token_strs` | boolean | 否 | 同時回傳每個 token 解碼後的文字。預設 `false`。 | 支援 |

### 回應

```json
{
  "count": 7,
  "max_model_len": 262144,
  "tokens": [9707, 11, 1879, 0],
  "token_strs": ["Hello", ",", " world", "!"]
}
```

- `count` 是所有輸入的 token 總數。
- `max_model_len` 是模型的上下文視窗；無法判定時為 `null`。
- 單一 `prompt` 字串或 `messages` 時，`tokens` 是一維清單；`prompt` 為陣列時是清單的清單。
- `token_strs` 只在 `return_token_strs` 時出現，巢狀結構與 `tokens` 相同。

### 範例

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
# Raw text
curl http://localhost:8000/v1/tokenize \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello, world!", "return_token_strs": true}'

# A conversation as the chat route would render it
curl http://localhost:8000/v1/tokenize \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "system", "content": "You are concise."},
      {"role": "user", "content": "Hi"}
    ]
  }'
```

</Tab>
<Tab value="Python">

```python
import requests

base = "http://localhost:8000"
r = requests.post(f"{base}/v1/tokenize", json={"prompt": "Hello, world!"})
ids = r.json()["tokens"]

back = requests.post(f"{base}/v1/detokenize", json={"tokens": ids})
print(back.json()["prompt"])  # Hello, world!

chat = requests.post(
    f"{base}/v1/tokenize",
    json={"messages": [{"role": "user", "content": "Hi"}], "chat_template_kwargs": {"enable_thinking": False}},
)
print(chat.json()["count"], "of", chat.json()["max_model_len"])
```

</Tab>
<Tab value="JavaScript">

```ts
const base = "http://localhost:8000";
const res = await fetch(`${base}/v1/tokenize`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ prompt: "Hello, world!" }),
});
const { count, tokens } = await res.json();
console.log(count, tokens);
```

</Tab>
</Tabs>

## Detokenize

`POST /v1/detokenize` 把 token id 轉回文字。

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `model` | string | 否 | 見上文。 |
| `tokens` | 整數陣列 | 是 | Token id。 |
| `skip_special_tokens` | boolean | 否 | 預設 `true`：文字中不含特殊 token。 |

```bash
curl http://localhost:8000/v1/detokenize \
  -H "Content-Type: application/json" \
  -d '{"tokens": [9707, 11, 1879, 0]}'
```

```json
{ "prompt": "Hello, world!" }
```

超出詞彙表範圍的 token id 會回應 `422`。

## Apply template

`POST /v1/apply-template` 以模型的聊天模板轉換訊息，回傳最終的提示詞字串，不做 tokenize。

| 參數 | 型別 | 必填 | 說明 |
| --- | --- | --- | --- |
| `model` | string | 否 | 見上文。 |
| `messages` | array | 是 | 聊天訊息。 |
| `tools` | array | 否 | 交給模板的工具定義。 |
| `add_generation_prompt` | boolean | 否 | 預設 `true`。 |
| `chat_template_kwargs` | object | 否 | 額外的模板變數。 |

```bash
curl http://localhost:8000/v1/apply-template \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "Hi"}]}'
```

```json
{ "prompt": "<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n" }
```

實際文字取決於模型的模板。模板丟出錯誤（例如訊息順序不被允許）時，會回應 `400`，訊息為 `chat template failed: ...`。

## 伺服器屬性

`GET /v1/props`（也可用 `GET /props`）是一份簡短的 llama.cpp 風格已載入模型描述，供會去查詢它的工具使用。

```json
{
  "default_generation_settings": { "n_ctx": 262144 },
  "model_path": "mlx-community/Qwen3.5-0.8B-MLX-bf16",
  "chat_template": "{% for message in messages %}...",
  "total_slots": 1
}
```

沒有載入任何模型時回應 `503`。完整的模型描述請用 [`GET /v1/models`](/docs/api/models)。

## 錯誤

| 狀態碼 | 時機 |
| --- | --- |
| 400 | `prompt` 與 `messages` 兩個都送或都不送；聊天模板錯誤；格式錯誤的 JSON。 |
| 401 | 已設定 token，但缺少或不正確。 |
| 404 | 找不到指定模型可用的 tokenizer。 |
| 422 | `tokens` 中有無效的 token id。 |
| 503 | 沒有載入任何模型時呼叫 `GET /v1/props`。 |

## 支援狀況

| 功能 | 狀態 |
| --- | --- |
| 對文字與聊天訊息做 tokenize | <Support status="supported">支援</Support> |
| Detokenize、apply-template | <Support status="supported">支援</Support> |
| 不帶前綴的路由（`/tokenize`、`/detokenize`、`/apply-template`） | <Support status="supported">支援</Support> |
| `messages` 中的圖片、音訊或影片 token | <Support status="unsupported">不計入；只會 tokenize 文字區塊</Support> |
| Anthropic 格式中工具、圖片與 system 區塊的 token 計算 | <Support status="supported">請使用 `POST /v1/messages/count_tokens`</Support> |

## 相關頁面

- [Chat completions](/docs/api/chat-completions)
- [Messages](/docs/api/messages)
- [模型](/docs/api/models)


---

<!-- developers/accuracy -->
---
title: 準確度對齊
description: Yunshu 如何以三個層級（logit 分歧、貪婪分歧、成對任務評測）證明其服務路徑在同一檢查點上算出與原生 MLX 和 mlx-vlm 相同的結果。
---

一次 300 題的基準測試帶有約 13 題的 95% 雜訊，因此看不出細微的數值漂移。Yunshu 因此用三個層級檢查準確度，由最便宜、最敏感的開始。本頁寫給修改 kernel、快取版面配置或排程器的維護者。日常的候選檢查見[驗證](/docs/developers/verification)；各層級如何作為發版關卡見[發版關卡](/docs/developers/release-gate)。

## 它做什麼

| 層級 | 比較對象 | 腳本 |
|---|---|---|
| 1 | 固定文字上的下一個 token 分布（teacher forcing）：KL 散度、top-1 一致率、困惑度（perplexity） | `scripts/research/accuracy/kld.py` |
| 2 | 50 個固定提示詞的貪婪續寫，最多 256 個 token：完全相符與第一個不同位置 | `scripts/research/accuracy/greedy_div.py` |
| 3 | 透過使用者實際使用的 HTTP 端點，做成對的下游評測：GSM8K、IFEval、MMLU-Pro、BFCL（工具呼叫）、needle 檢索 | `scripts/research/accuracy/paired_eval.py` |

基準永遠是同一檢查點上的原生 `mlx-vlm`，且不匯入任何 Yunshu 的 kernel（沒有 batch-invariant、ragged KV、lane 或 oMLX kernel）；執行時會斷言這一點。候選則是 `VLMEngine._build_batch_runner` 安裝的內容。

### 層級 1：teacher forcing 的 logit 對齊

這是 llama.cpp `perplexity --kl-divergence` 與 vLLM logprob 接近度測試背後的方法。

- **語料。** `common.build_corpus` 建立固定的 token 語料（散文、程式碼、中文與數學的 2048 token 視窗，另有 8K 與 32K 的長文件）。token id 只私下保存。
- **基準檔。** 每個位置的 top-64 對數機率，加上固定隨機子集位置的完整詞表 log-softmax，因此之後的比較不必重跑基準。子集之外的位置使用 top-64 加一個合併的尾部桶，這是真實分歧的下界。
- **部分**（`kld.py` 中的 `PARTS` 表）：`prefill`、`dec1`（每步一個 token，早期為推測 lane）、`dec6`（6 個 token 的驗證區塊）、`decb` 與 `decb8`（在 ragged bf16 或 int8 KV 快取上的雙列共用批次）、`stockb2`（原生雙列批次，作為雜訊底線）。
- **指標。** KL 散度（基準對候選）的平均、中位數、第 99 百分位與最大值；top-1 一致率；top-1 機率的平均變化；兩者的困惑度，整體以及依語料類型與位置區間分組。

### 層級 2：貪婪分歧

50 個固定的對話提示詞（英文、程式碼、數學、中文與長文摘要），貪婪解碼，最多 256 個 token（`greedy_div.py` 中的 `N_PROMPTS, MAX_TOKENS = 50, 256`）。每一對執行以整段續寫是否完全相同，以及第一個不同位置評分。`engine` 設定會讓每個提示詞各以關閉與開啟推測（`allow_draft`）執行；

### 層級 3：成對下游評測

`paired_eval.py` 把相同的題目經由同一個聊天端點，以貪婪解碼送給基準伺服器（原生 `mlx_vlm.server`）與 Yunshu。題目以 id 配對；只有兩邊都沒有傳輸錯誤而完成的題目才進入配對。每個基準都會回報成對差異與 95% 區間、不一致計數 `b`（基準對、Yunshu 錯）與 `c`（相反），以及精確的 McNemar p 值（`mcnemar_exact`、`loss_p`）。不使用獨立的準確率區間，因為它們比成對區間寬兩到三倍。失敗的嘗試、截斷與完成長度都會回報，不會隱藏。

## 為什麼這樣設計

- 在可負擔的樣本數下，基準分數分不出數值上合法的實作與正在漂移的實作；對固定文字做分布層級的檢查就分得出來。
- 候選必須對照原生 MLX 對自身的表現來判斷。重跑是逐位元相同的，所以任何非零差異都是真正的路徑差異。光是改變批次大小或預填區塊大小，就會讓原生輸出產生小而可測量的偏移；這個散布（`stockb2` 部分與區塊大小比較）就是門檻所依據的雜訊底線。
- 層級 3 用來抓住分布指標漏掉的問題：格式損壞、工具呼叫與長上下文檢索。

## 保證

層級 1 的通過條件，依語料類型與位置的每個切片：

- 平均 KL 散度不超過原生對原生底線的兩倍，中位數與第 99 百分位同樣如此；
- top-1 一致率至少 98.4%；
- 困惑度的絕對變化不超過 0.5%；
- 硬性關卡：Yunshu 的 `prefill`，以及 `dec6` 對 `dec1`，必須逐位元相同（分歧恰為 0）。這讓推測解碼經過 verify kernel 後，輸出與關閉推測解碼完全相同。

層級 2 的通過條件：

- 開啟與關閉推測的輸出，50 題全部相同（硬性關卡）；
- 對基準的完全相符數與第一個分歧位置的中位數，不得低於同一檢查點已記錄的基線；
- 原生重跑 50 題全部相同（測試框架的健全性檢查）。

層級 3 的通過條件：每一組都沒有顯著退步（對 `b` 大於 `c` 的 McNemar p 至少為 0.05）。顯著的進步視為相同準確度附近的雜訊，不算改善。部分執行會標示為部分，不會當作基準分數引用。

有損的選項（int8 KV、權重量化）以其自身公布的差距來判斷，不套用上述無損限制。

<Callout type="info">
實測的分數表刻意不放在本頁：它們會隨每次 kernel 變更而過時。有日期的數字記錄在基準日誌（`docs/reports/PERF_TREND.md`）與[基準測試](/docs/guides/benchmarks)。
</Callout>

## 設定

| 設定或選項 | 預設 | 效果 |
|---|---|---|
| `YUNSHU_KV_PRECISION` | `bf16` | `decb8` 以 int8 KV 編碼執行；這是有損選項，以其自身差距判斷 |
| `paired_eval.py report --bench B --ref ref --cand default` | n/a | 由可續跑的各 arm 檔案重新計算某個基準的結果列 |
| `kld.py run --config stock\|serve --part ...` | n/a | 選擇要執行哪個 arm 與哪些部分 |

## 限制

- 層級 1 與 2 的可信度取決於固定的語料與提示詞；更換檢查點需要重建基準（不帶 `--ref` 執行 `kld.py run --config stock`）。
- 基準伺服器實際上是循序處理的（沒有批次），所以長工作中它的請求可能逾時，而 Yunshu 的請求能完成；這些嘗試會計入報告。
- MMLU-Pro 執行使用固定種子的隨機抽樣，而非分層抽樣，且部分執行的區間很寬。
- 單一檢查點與單一機器的結果無法外推：請在目標檢查點上重跑。

## 如何驗證

```bash
# Tier 1
python scripts/research/accuracy/kld.py corpus
python scripts/research/accuracy/kld.py run --config stock --part prefill
python scripts/research/accuracy/kld.py run --config serve --part dec6
python scripts/research/accuracy/kld.py report

# Tier 2
python scripts/research/accuracy/greedy_div.py build
python scripts/research/accuracy/greedy_div.py run
python scripts/research/accuracy/greedy_div.py compare

# Tier 3 (per benchmark)
python scripts/research/accuracy/paired_eval.py report --bench B --ref ref --cand default
```

GPU 工作經由 `scripts/dev/gpuq` 執行。每次修改 kernel、快取版面配置或排程器，都要在 Qwen3.8-27B 上跑層級 1 與層級 2，任一條件失敗就阻擋合併；基準檔每個檢查點與語料版本只保存一次，所以一次檢查只需付出候選那一側的成本。層級 3 在每次發版前以及任何有損選項變更後執行。`yv` 工具的 `quality` 階段是層級 3 的低成本版本，每次變更都可以跑；見[驗證](/docs/developers/verification)。

## 相關頁面

- [驗證](/docs/developers/verification)
- [發版關卡](/docs/developers/release-gate)
- [基準測試](/docs/guides/benchmarks)


---

<!-- developers/agent-compat -->
---
title: Agent 相容性
description: Claude Code、Codex CLI 與 opencode 實際會呼叫什麼、Yunshu 如何處理每個請求，以及用最新 CLI 重新驗證這些主張的腳本。
---

對程式開發 agent，目標是盡可能貼近原生行為：Claude Code、Codex CLI、opencode 與官方 SDK 用到的每個端點、標頭、beta、工具類型與伺服器端工具，都應該像真正的 Anthropic 與 OpenAI API 一樣運作，而不只是生成正確。本頁記錄每個 agent 呼叫什麼（來自對真實 CLI 的普查）、Yunshu 如何處理，以及這些主張如何被驗證。面向使用者的設定見 [Agents](/docs/guides/agents)。

## 它做什麼

普查工具會讓真實的 CLI 連到一個記錄用的模擬伺服器，因此 agent 發出哪些請求的清單來自觀察，而非文件。工具位於 `scripts/research/agent_compat/`。

| 元件 | 做什麼 |
|---|---|
| `census_server.py` | 有腳本、會記錄的模擬模型伺服器。記錄每個請求（方法、路徑、查詢、標頭、本文），以一連串工具呼叫的腳本回應，讓 agent 走完一個工作階段，對未知路徑回傳 404，並以符合規格的伺服器工具區塊回答 `web_search_*` 請求。不需 GPU |
| `census.py` | 讓固定版本的 CLI 跑過腳本化的工作階段：一般對話、bash 與編輯、子 agent、網頁搜尋與擷取、MCP、圖片、思考、`/context`、`/cost`、`/compact`、狀態列、模型探索、Codex 推理、壓縮、websocket 與目錄，以及 opencode。隔離：清理過的環境、獨立的 `HOME`、`CLAUDE_CONFIG_DIR` 與 `CODEX_HOME`，並以 `sandbox-exec` 拒絕除 loopback 外的一切 |
| `census_tui.py` | 在 pty 中驅動 agent 的互動式 TUI（`/status`、`/model`） |
| `replay.py`、`replay_report.py` | 把每個記錄下來的請求重播到真正的 Yunshu，並比較狀態與串流有效性 |
| `e2e_agents.py`、`e2e_sdk.py`、`capture_proxy.py`、`fake_searxng.py`、`tiny_mcp.py` | 用真實 agent 與官方 SDK 搭配真實模型做端到端執行，附帶假的 SearXNG（有可檢查事實的固定語料）、一個小型 MCP 伺服器與完整擷取代理 |
| `stream_check.py`、`synthetic_requests.py` | 串流驗證，以及重播階段使用的 SDK 形狀合成請求 |

原始普查資料為私有（本機依日期命名的 `agent-census` 目錄，已被忽略）。

## 各 agent 呼叫什麼

### Claude Code

| 請求 | 時機 | Yunshu |
|---|---|---|
| `POST /v1/messages?beta=true`，`stream: true` | 每一回合。多個 `anthropic-beta` 值、以多個區塊表示並帶 `cache_control` 的 `system`、對話中途的 `role: "system"` 項目、許多用戶端工具、`thinking: {type: "adaptive"}`、`output_config`、`context_management`、`metadata.user_id` | 已支援。beta 絕不被拒絕。接受 `adaptive` 思考與 `output_config` |
| `POST /v1/messages/count_tokens?beta=true` | `/context` | 已支援（計算 system、messages、tools） |
| `GET /v1/models?limit=1000` | 只在 `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` 時；用來填入 `/model` | 已支援，附 `max_input_tokens`、`max_tokens` 與 `capabilities` |
| 帶有 `web_search_20250305` 工具的 `POST /v1/messages` | 它的 WebSearch 工具：搜尋在伺服器端執行，用戶端負責顯示 `web_search_tool_result` 區塊 | 以伺服器工具實作，見下文 |
| 小模型呼叫 | 標題、摘要、WebFetch 的頁面摘要 | 已支援 |
| MCP 伺服器 | 用戶端：工具以 `mcp__server__tool` 函式工具的形式交給模型 | 無需處理；需要一般的工具呼叫 |
| WebFetch | 用戶端擷取，再以小模型呼叫做摘要 | 無需處理 |
| 子 agent、`/compact` | 一般的 `/v1/messages` 呼叫 | 已支援 |

封鎖通往 Anthropic 的流量後，沒有觀察到其他請求：沒有遙測、OAuth 或更新呼叫。CLI 無法從自訂伺服器得知兩件事：上下文視窗（對未知的模型 id 它假設為 200K，這就是 `CLAUDE_CODE_MAX_CONTEXT_TOKENS` 存在的原因）與價格（對未知模型它印出自己的算式；這無法從伺服器端修正）。

### Codex CLI

| 請求 | 時機 | Yunshu |
|---|---|---|
| `POST /v1/responses`，`stream: true`，`store: false` | 每一回合。`instructions`、`input` 項目（`developer` 與 `user` 訊息、`function_call`、`function_call_output`、`reasoning`）、類型為 `function`、`namespace`（含巢狀 `tools`）與 `web_search` 的 `tools`、`parallel_tool_calls`、`reasoning`、`include: ["reasoning.encrypted_content"]`、`prompt_cache_key` | 已支援，包括 `namespace` 與 `web_search` 工具 |
| 帶 `Upgrade: websocket` 的 `/v1/responses` | 只在供應商設定 `supports_websockets = true` 時；嘗試三次，然後改用 POST | `WS /v1/responses` 已存在；見[傳輸方式](/docs/guides/transports) |
| 壓縮 | 本地：以 `tools: []` 的一般 `POST /v1/responses`；自訂供應商沒有 `/responses/compact` | 已支援 |
| 模型中繼資料 | 絕不從自訂供應商取得；沒有目錄時 Codex 會印出「Model metadata not found」、不送推理強度，且只提供內建模型 | `yunshu launch codex` 會寫入 `model_catalog_json` |
| `web_search = "live"` | 加入 `{type: "web_search"}` 工具，並預期 `web_search_call` 項目 | 已實作 |
| MCP 伺服器 | 用戶端函式工具 | 無需處理 |

### opencode

| 請求 | 時機 | Yunshu |
|---|---|---|
| `POST /v1/chat/completions`，`stream_options: {include_usage: true}` | 每一回合；產生標題時先送一個 `reasoning_effort: "low"` 的請求；標頭 `x-session-id`、`x-session-affinity` | 已支援 |
| `/models` | 不會取得；限制來自 `provider.*.models.*.limit` | `yunshu launch opencode` 會寫入這些值 |

## 保證

下方的功能矩陣使用以下標籤：**可用**（已驗證，並列出證據）、**部分**、**缺少**、**n/a**（agent 從不要求）。證據：「E2E」是真實的固定版本 agent 搭配真實 Yunshu、啟動輔助工具的設定與擷取代理；「SDK」是官方 SDK 搭配真實伺服器；「unit」是以假物件（fake）取代真實元件的 `tests/unit`。

| 功能 | Claude Code | Codex | opencode | SDK 使用者 | 證據 |
|---|---|---|---|---|---|
| 串流生成、工具呼叫 | 可用 | 可用 | 可用 | 可用 | 三者的 E2E 編輯與 bash 任務、unit |
| 對話中途的 system 訊息 | 可用（文字與圖片回合） | 可用（`developer` 項目） | n/a | 可用 | unit |
| 以原生形狀表示的思考與推理 | 可用（`thinking` 區塊） | 可用（`reasoning` 項目、`encrypted_content` 往返） | 可用（`reasoning_content`） | 可用 | unit、SDK |
| 強度控制 | 可用（`output_config.effort`） | 可用（透過目錄層級的 `reasoning.effort`） | 可用（`reasoning_effort`） | 可用 | unit、launch |
| 網頁搜尋，伺服器端 | 可用 | 可用 | n/a（用戶端工具） | 可用（Messages 與 Responses，串流與非串流） | E2E、SDK |
| 網頁擷取 | CLI 內用戶端 | n/a | n/a | 可用（伺服器端，有 SSRF 防護） | SDK |
| MCP | 用戶端，可用 | 用戶端，可用 | n/a | 伺服器端連接器可用 | E2E、SDK |
| 圖片（工具結果或輸入） | 可用 | exec 中 n/a | n/a | 可用 | E2E |
| 模型探索與選擇器 | 可用 | 可用（目錄） | n/a | 可用 | TUI 擷取、普查 |
| 上下文視窗與自動壓縮點 | 可用 | 可用（目錄） | 可用（`limit.context`） | 可用 | E2E `/context`、launch |
| 費用顯示 | 顯示零；每回合費用是 CLI 自己的算式 | n/a | n/a | n/a | TUI 擷取 |
| 速率限制標頭 | n/a：沒有 agent 需要它們；Yunshu 沒有配額，也不憑空捏造 | n/a | n/a | n/a | 普查 |
| `count_tokens` | 可用 | n/a | n/a | 可用 | 普查重播 |
| 用量欄位 | 可用（包括快取讀取與思考 token） | 可用 | 可用（`include_usage`） | 可用 | E2E 擷取 |
| 請求途中引擎失敗 | 可用：帶引擎訊息的 SSE `error` 事件 | 可用：`response.failed` | 可用：錯誤 chunk | 可用 | unit |
| Websocket 傳輸 | n/a | 可用（`WS /v1/responses`） | n/a | n/a | E2E |
| agent 介面中的即時引擎狀態 | 可用：`yunshu launch claude` 會安裝 `yunshu statusline`，除非你有自己的 | 不提供 | 不提供 | `x_yunshu` 欄位、`: yunshu-progress` SSE 註解 | unit |
| agent 流量上的前綴快取重用 | 可用：每個請求的 `x_yunshu.cache` 與 `X-Yunshu-Cache-*` | 可用 | 可用 | 可用 | 基準日誌中的快取稽核 |

### 從真實用戶端學到的請求形狀規則

這些是在真實 SDK 與用戶端上失敗過、已修正並由測試涵蓋的行為：

| 用戶端行為 | Yunshu 的做法 |
|---|---|
| 聊天範本丟棄的明確 `cache_control` 標記 | 請求不帶明確檢查點照常處理，日誌會指出該標記；標記只是提示，絕不造成失敗 |
| `"temperature": null`、`"max_tokens": null`、`"stream": null`（LangChain、LiteLLM、Vercel AI SDK、Zed） | 在所有生成路由上，明確的 null 視為未設定（`schemas/nulls.py`） |
| `top_k: -1` | 負的 `top_k` 表示停用 |
| 省略 `max_tokens` | 由 `YUNSHU_DEFAULT_MAX_TOKENS` 決定（預設 32768）；上下文預算仍會對它設限 |
| 聊天的 `tool_choice: {"type": "allowed_tools"}` 與 Responses 的形式 | 兩條路由都折疊為 `tools` 加上一個模式 |
| Responses 的 `usage.input_tokens_details` | 包含 `cache_write_tokens`，如目前 `openai` 的 `Response` 型別所要求（真實寫入量在 `x_yunshu` 中） |
| 串流開始後發生範本或引擎錯誤 | 在 Messages、聊天與 Responses 上送出 `error` 事件，絕不回傳空的成功回覆 |
| 圖片 `Read` 之後的 Claude Code 回合 | 視覺路徑會執行模型家族的訊息轉接器，因此每回合的 system 備註不會破壞 Qwen 的範本 |

已知缺口（每一項都在 `tests/unit/test_spec_field_inventory.py` 中附理由列出）：聊天的 `functions` 與 `function_call`（已棄用）、聊天中的自訂工具、Responses 的 `prompt` 範本、沒有 `user` 回合的訊息、省略 `input` 的 Responses。Yunshu 以 `data: [DONE]` 結束 Responses 串流（真實 API 不會）；每個 SDK 與 Codex 都會在此停止。

### 取樣式推測解碼

取樣請求（溫度大於零，也就是程式開發 agent 送出的類型）透過 MTP lane 起草，並使用以位置為鍵的 Gumbel 取樣（`keyed_sampling.py`）。雜訊使用 23 個隨機位元（24 位元在 float32 中會四捨五入為 1.0，產生無限大的 Gumbel 值），而被過濾的 logits 會在加入雜訊之後才遮罩，因此被過濾的 token 永遠不可能勝出。貪婪請求從未受影響。檢查項目是：lane 與依鍵逐一抽樣的 token 完全相同、抽樣符合過濾後的 softmax，以及 agent E2E 任務通過且輸出乾淨。

## 伺服器端工具

網頁搜尋、網頁擷取與 MCP 連接器都在 Yunshu 內部執行，所以 Claude Code、Codex 與 SDK 看到的是原生的伺服器工具區塊。使用者指南是[網頁搜尋](/docs/guides/web-search)；已註冊的設定與其預設值如下：

| 設定 | 預設 | 效果 |
|---|---|---|
| `YUNSHU_WEB_SEARCH_PROVIDER` | `auto` | 搜尋後端；`none` 停用搜尋 |
| `YUNSHU_WEB_KEYLESS` | on | 允許免金鑰的 DuckDuckGo 與 Wikipedia（盡力而為）；設為 `0` 可停用免金鑰後備 |
| `YUNSHU_WEB_RESEARCH` | off | 選擇性啟用的來源擷取、抽取與本地排序；在成對品質評測完成前維持關閉 |
| `YUNSHU_WEB_RESEARCH_MODEL` | unset | 指定一個已載入的本地嵌入模型；Yunshu 絕不自行載入，也不會退回使用生成模型 |
| `YUNSHU_WEB_FETCH` | on | 提供伺服器端 `web_fetch` 工具；私有、loopback 與 link-local 位址會被封鎖 |
| `YUNSHU_WEB_FETCH_MAX_BYTES`、`YUNSHU_WEB_FETCH_TIMEOUT` | 2000000, 20.0 | 每個頁面的最大本文與等待時間 |
| `YUNSHU_MCP_CONNECTOR` | on | 為 Anthropic `mcp_servers` 與 OpenAI Responses `{type: mcp}` 提供 MCP 連接器 |
| `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` | 8 | 每個請求的生成、執行與繼續輪數 |

<Callout type="warn">
搜尋查詢會離開這台機器。模型生成的查詢文字可能包含對話上下文，搜尋供應商會看到該查詢與你的 IP；來源頁面會看到擷取的 URL。對話歷史與用戶端憑證不會被轉送。擷取到的頁面摘錄是不受信任的資料，而過濾器不保證能抵抗提示詞注入。
</Callout>

## 啟動 agent

`yunshu launch claude|codex|opencode` 會從 `/v1/models` 讀取模型卡，並把 agent 否則會猜錯的內容傳給它；`--dry-run` 會印出這些內容。

| Agent | 設定了什麼 |
|---|---|
| Claude Code | `ANTHROPIC_BASE_URL`、`ANTHROPIC_AUTH_TOKEN`、每個模型別名都指向所服務的模型、`CLAUDE_CODE_MAX_CONTEXT_TOKENS`（真實的視窗）、`CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY`、選用的 `CLAUDE_CODE_EFFORT_LEVEL`（`--effort`），以及執行 `yunshu statusline` 的 `--settings` 狀態列（若你已有自己的 `statusLine` 則略過，以 `--no-statusline` 關閉）。只用環境變數與旗標：不會寫入 `~/.claude` |
| Codex | `~/.codex/config.toml`（`model_provider`、`model_context_window`、`model_auto_compact_token_limit`，設定供應商時加上 `web_search = "live"`）與 `~/.codex/yunshu-models.json`（`model_catalog_json`） |
| opencode | `opencode.json` 中的 `provider.yunshu`，含 `limit.context`、`limit.output`、`reasoning`、`tool_call`、`modalities` |

## 設定

| 設定或選項 | 預設 | 效果 |
|---|---|---|
| `YUNSHU_DEFAULT_MAX_TOKENS` | 32768 | 請求省略 `max_tokens` 時的完成長度 |
| `scripts/dev/agentcompat --stages` | `census,m3` | 執行哪些驗證階段 |
| `scripts/dev/agentcompat --model` | `Qwen3.5-9B-MLX-4bit` | M3 階段所服務的模型 |

## 限制

- Claude Code 的 `/model` 仍會列出它的內建列，且預設列帶有 `[1m]` 標籤：兩者都來自用戶端自己的目錄。它實際使用的視窗是真實的視窗（`/context`）。
- 非串流 Responses 的 `web_search` SDK 檢查與模型有關：小模型有時會不呼叫工具就直接回答。
- Codex `/status` 需要先完成一個回合，才會印出 token 用量。
- Cline、Continue 與 Open WebUI 是設定指引，而非每個版本的端到端主張。

## 如何驗證

文件會過時，所以上述主張用一個指令、一個結論重新驗證（只有在有正面證據時才以 0 結束，並將 `verdict.json` 寫入本機依日期命名、已被忽略的 `agentcompat-<commit>` 目錄）：

```bash
scripts/dev/agentcompat                      # census,m3
scripts/dev/agentcompat --stages install,census,m3
```

| 階段 | 證明什麼 |
|---|---|
| `install` | 在 `/Volumes/P5Plus/yunshu-build/agentic-clis-latest` 下安裝最新的 Claude Code、Codex 與 opencode（絕不全域安裝；使用帶 `*_V=latest` 的 `install_agents.sh`） |
| `census` | 用這些 CLI 對記錄用模擬伺服器跑腳本化工作階段；與固定版本的普查做差異比對（路徑、查詢鍵、標頭、beta 值、本文欄位、工具與區塊類型）。每個新項目都必須寫進本頁 |
| `m3` | 在 M3 筆電上的兩個有時間上限的 gpuq 工作（`m3_serve.py`、小型 Qwen3.5 模型，僅 loopback，位於 `ssh -L` 轉發之後）。工作 1 重播每個普查工作階段的第一個與最後一個請求，加上 SDK 形狀的合成請求（狀態 2xx、SSE 事件順序與欄位、以官方 `anthropic` 與 `openai` 模型驗證的本文）。工作 2 用最新的 CLI 執行腳本化的 agent 任務（編輯、bash、MCP、圖片、`/context`）。通道中斷或工作未乾淨結束都會使該次執行失敗，並將該通道隔離，等人來檢查 |

`python/` 中的規格漂移由 `tests/unit/test_spec_field_inventory.py` 涵蓋：已安裝的 `openai` 與 `anthropic` SDK 請求型別的每個參數，要嘛是請求模型的欄位，要嘛附理由列出，因此新的 SDK 版本新增欄位時會讓 CI 失敗，而不是被默默丟棄。Agent 相容性是 `scripts/dev/release_check` 的阻擋檢查之一；見[發版就緒](/docs/developers/release-readiness)。

## 相關頁面

- [Agents](/docs/guides/agents)
- [Agentic 程式開發基準](/docs/developers/agentic-bench)
- [發版關卡](/docs/developers/release-gate)


---

<!-- developers/agentic-bench -->
---
title: Agentic 程式開發基準
description: 如何在真實的程式開發 agent 迴圈（Claude Code、Codex CLI、opencode）與隱藏測試下量測 Yunshu，以及如何執行、重複與擴充這套基準。
---

單一請求的數字無法呈現引擎在人們實際使用情境下的表現：上下文持續增長的多輪程式開發 agent 迴圈、大量工具呼叫、回合之間的前綴複用，以及長時間的工作階段。`scripts/research/agentic/` 會驅動真實的程式開發 agent 去連接本機伺服器，並由隱藏測試決定它們寫出的程式是否可用。

## 它做什麼

每一次（agent、引擎、任務、重複）的執行都會記錄：

- agent 看不到的測試的通過或失敗、牆鐘時間、agent 結束狀態與逾時；
- 模型請求數；提示詞、完成與快取 token 總數；快取命中率；最大提示詞；
- 每個請求的 TTFT 與解碼 tok/s，由記錄代理（`proxy.py`）在線路層量測，因此每個引擎都以相同方式量測；
- API 錯誤（4xx、5xx、不完整或錯誤的串流；僅記錄中繼資料）、格式錯誤的工具呼叫參數，以及洩漏到文字中的工具呼叫標記；
- 伺服器在執行期間的實體記憶體佔用峰值。

agent 是由 `scripts/research/agentic/install_agents.sh` 安裝在 `/Volumes/P5Plus/yunshu-test-envs/agentic-clis` 下的固定版本副本，絕不使用你 `PATH` 上的那些：**opencode**（Chat Completions）、**Claude Code**（Messages）與 **Codex CLI**（Responses）。每次執行都有全新的 `HOME`、XDG 目錄、`TMPDIR`、`CLAUDE_CONFIG_DIR` 與 `CODEX_HOME`、清理過的環境與假金鑰，並在 `sandbox-exec` 下執行：除 loopback 外封鎖所有網路、隱藏真實的 `~/.claude`、`~/.codex`、`~/.config`、鑰匙圈與 shell rc 檔，且只允許寫入該次執行的目錄。取樣參數採用各 agent 預設送出的值。

共有 20 個任務：12 個來自 Aider polyglot 基準的 Exercism Python 練習（下載到 `/Volumes/P5Plus/datasets/agentic`，commit 記錄在 meta 列，絕不提交進儲存庫），以及 8 個自訂的多檔案任務（修 bug、CLI 旗標加測試、三檔案重構、標準函式庫 HTTP JSON API、依規格寫解析器、在約 2,100 行的套件中定位並修改的長上下文任務、在雜亂資料上來回處理的 shell 任務、失敗測試集的分診）。

## 為什麼這樣設計

- agent 流量才是真實的工作負載：長上下文、重複的前綴與大量簡短的工具回合。在這裡，前綴快取複用與 TTFT 比峰值解碼速度更重要。
- 隱藏測試讓結果成為任務成敗，而非風格評判。
- 在記錄代理處量測，消除了各引擎自身計時的偏差。
- 失敗的執行留在分母中；逾時算作失敗。

## 保證

- 可重複執行的結論遵循失敗即關閉原則：API 錯誤、格式錯誤的工具呼叫、標記洩漏與缺失的執行都會使其失敗。
- 輸出檔以一列 `meta`（引擎、檢查點、git SHA、agent 版本、旗標）開頭。執行可續跑：`--output` 中已存在的任務與重複會被略過。
- 只公布有日期的彙總結果，並附上快照 SHA、分母、逾時與不確定性；原始執行中繼資料、agent 產物與 JSONL 保持私有，放在被忽略的本機目錄。

## 設定

| 選項 | 預設 | 效果 |
|---|---|---|
| `run_agentic.py run --serve yunshu` | n/a | 為該工作啟動伺服器（Yunshu 預設或 TensorFold），結束時終止它 |
| `--engine-url URL --engine-label X` | n/a | 使用你自己啟動的伺服器 |
| `--agent`、`--tasks`、`--repeat` | n/a | 選擇 agent、任務（`all` 或清單）與重複次數 |
| `--shard-i`、`--shard-n` | n/a | 把執行清單分給多個工作 |
| `--budget-min` | n/a | 停止啟動新的執行，讓工作在其佇列逾時內結束 |
| `scripts/dev/agentbench --priority` | -1 | 矩陣各格的 gpuq 優先權（每夜獨立執行） |

## 執行方式

```bash
# one server per job; --serve starts it and kills it at the end
python scripts/research/agentic/run_agentic.py run --serve yunshu --checkpoint $M \
    --engine-label yunshu-default --agent opencode --tasks all --repeat 3 \
    --output docs/research/runs/DATE-agentic/yunshu-default-opencode.jsonl

# against a server you started yourself
python scripts/research/agentic/run_agentic.py run --engine-url http://127.0.0.1:18990 --engine-label X ...

python scripts/research/agentic/run_agentic.py summarize docs/research/runs/DATE-agentic/*.jsonl
python scripts/research/agentic/run_agentic.py check-tasks   # reference solutions pass, starting repos fail
```

GPU 工作經由 `scripts/dev/gpuq` 執行。

### 整個矩陣：`scripts/dev/agentbench`

`scripts/dev/agentbench` 會針對某個 ref（`--ref`，預設 `main`）上的預設 27B 伺服器，用 Claude Code、Codex 與 opencode 跑全部 20 個任務：每一格提交一個低優先權的 gpuq 工作，結論採失敗即關閉，並與先前記錄的執行比較。`--dry-run` 預覽，`--no-wait` 在提交後返回，`--collect` 收集已提交的執行。`scripts/dev/release_check` 會以優先權 -3 為候選發行版提交它，並印出之後的 collect 指令。Agentbench 僅供參考：發版關卡、M3 全面測試與 agent 相容性會阻擋發版，agentbench 不會。無論如何，仍要收集並記錄每一個已提交的結果。

## 新增任務

建立 `scripts/research/agentic/tasks/<id>/`，內含：

- `task.json`：`id`、`title`、`prompt`、`test`（argv），選用的 `protected` 檔案（評分前會還原），以及選用的 `generate` 腳本（把額外檔案寫入工作目錄）；
- `repo/`：起始檔案；
- `hidden/`：測試檔案，只在評分時才複製到 `_hidden_tests/`（已設定 `AGENTIC_TASK_DIR` 與 `AGENTIC_TASK_SRC`）；
- `reference/`：能解出該任務的覆蓋層，或 `apply.py`。

`check-tasks` 必須回報起始儲存庫失敗、參考解答通過。任務要保持確定性且可離線執行。Polyglot 練習列在 `tasks.py` 中，並由資料集展開。

## 已記錄的結果

只公布一項有日期的結果，取自 `docs/reports/PERF_TREND.md`（2026-10-02，部分矩陣；Qwen3.8-27B oQ4e-mtp、M5 Max、Yunshu 預設設定、20 個任務；兩個快照的程式碼與執行組成不同，因此不合併）：

| 快照（git SHA、日期） | agent | 執行數 | 通過 | 通過率（Wilson 95%） | 牆鐘中位數 / p90（秒） | 快取命中 | 逾時 |
|---|---|---:|---:|---|---|---:|---:|
| prod (c4e2b244+, 09-30) | opencode | 41 | 34 | 83% (69-91%) | 337 / 1200 | 83.6% | 5 |
| prod4 (d225f16c, 10-02) | claude | 15 | 14 | 93% (70-99%) | 93 / 309 | 89.2% | 0 |
| prod4 (d225f16c, 10-02) | opencode | 10 | 9 | 90% (60-98%) | 112 / 137 | 84.2% | 0 |

在 n 為 10 到 15 時區間很寬，快照之間的變化只是一個方向，而非量測到的加速。Codex 與 TensorFold 的格子沒有公布結果。

## 限制

- 矩陣並不完整；沒有任何一格涵蓋全部 20 個任務的三次重複。
- agent 為了可重複性而固定版本；與最新 CLI 的相容性是另一項檢查，見 [Agent 相容性](/docs/developers/agent-compat)。
- 只有在工作沒有被服務流量暫停、也沒有受外部 CPU 負載污染時，計時才有意義；見[邊服務邊開發](/docs/developers/serve-and-develop)。

## 如何驗證

`check-tasks` 證明任務集是健全的。`scripts/dev/agentbench --dry-run` 預覽矩陣，`run_agentic.py summarize` 為一組 JSONL 檔案印出彙總。面向使用者的 agent 設定見 [Agents](/docs/guides/agents)。

## 相關頁面

- [Agent 相容性](/docs/developers/agent-compat)
- [發版關卡](/docs/developers/release-gate)
- [基準測試](/docs/guides/benchmarks)


---

<!-- developers/api-parity -->
---
title: API 一致性矩陣
description: 我們提供的 OpenAI 與 Anthropic API，每個請求或回應功能一列、每個路由與串流模式一欄；可執行的 probe 讓每個 engaged 格子都有證據，每個缺口都有計數。
---

API 層是四個 router，用不同的方言服務同一個引擎：chat completions、Responses、Messages 與舊版 completions。一項功能（tools、`seed`、`logprobs`、結構化輸出、background、伺服器端工具……）必須在規格有該功能的每個路由上都能運作，不論串流與否。**API 一致性矩陣**（`python/yunshu_gateway/api_matrix.json`）列出這些功能，以及每個路由如何處理它們，並由 `tests/unit/test_api_parity.py` 與 `tests/unit/test_api_parity_wire.py` 強制執行。它是引擎路徑矩陣（`python/yunshu_engine/path_matrix.json`，見[架構](/docs/developers/architecture)）在 API 層的對應物。

## 結構

- **列**（61）：取樣欄位、`max_tokens`、`stop`、`n`、`logprobs`、tools / `tool_choice` / 平行呼叫 / 工具結果、結構化輸出與文法、推理與思考控制、usage 與快取 token、background、store / retrieve / delete、`previous_response_id` 與 conversation、取消與客戶端斷線、context 管理與溢位、伺服器端工具（web search、web fetch、MCP、程式碼執行、shell）、prompt 快取欄位與 `cache_control`、圖片 / 音訊 / 影片 / 檔案輸入、metadata、`service_tier`、`include`、引擎開關、`x_yunshu` 與請求 id、錯誤格式、token 計數與批次。
- **欄**（9）：`chat`、`responses`、`messages`、`completions`，各分串流與非串流，另加 `responses/background`。
- **格子**：`engaged`（程式碼證據，加上確實跑過該格子的 probe 或具名測試）、`na`（規格明說不適用，附理由）、`partial` 或 `missing`（缺口，附 `kind`：`unimplemented`、`divergent` 或 `untested`，以及影響與負責人）。

## Probe

格子只有在有測試實際執行它時才算 `engaged`。`test_api_parity_wire.py` 用腳本化引擎接在真實 router 後面，執行 434 個 probe：請求經過實際路由（原始 HTTP 或官方 OpenAI 與 Anthropic SDK），串流、非串流與 background 都跑，並檢查抵達引擎的內容（轉發 probe：每個取樣與約束欄位），或回傳的內容（行為 probe：usage、快取 token、推理拆分、工具呼叫、結構化輸出、儲存物件、previous-response 串接、取消、客戶端斷線、context 溢位、錯誤格式）。`partial` 格子的 probe 若開始通過，測試就會失敗，直到把格子改成 `engaged`，所以缺口不可能被悄悄補上。

## 目前狀態

| 欄 | engaged | na | partial / missing |
|---|---|---|---|
| `chat/nonstream` | 34 | 15 | 12 |
| `chat/stream` | 35 | 15 | 11 |
| `responses/nonstream` | 48 | 9 | 4 |
| `responses/stream` | 45 | 11 | 5 |
| `responses/background` | 37 | 11 | 13 |
| `messages/nonstream` | 39 | 16 | 6 |
| `messages/stream` | 35 | 18 | 8 |
| `completions/nonstream` | 27 | 32 | 2 |
| `completions/stream` | 28 | 32 | 1 |

328 格 engaged、159 格不適用、62 個缺口。矩陣中的 `gap_budget` 就是最後這個數字，只能往下降。

## 防護

- 四個請求模型任何一個新增欄位、新增伺服器端工具種類（`ServerToolDef.kind`）或新增 `server_tools` 模組，在有對應的列之前測試都會失敗。
- 證據（程式碼片段、測試函式）移動或消失，測試會失敗。
- `duplicates` 列出 14 項在多個 router 重複實作的功能（工具呼叫串流、usage 組裝、取樣解析、伺服器端工具迴圈、錯誤對應、斷線處理、stop 與 finish 對應、推理拆分、`response_format` 解析、`tool_choice` 強制、訊息轉換、`n > 1`、文字與 VLM 分支、儲存物件），每項附檔案路徑與一行合併建議。

## 新增或修改功能

1. 在 router 加上請求欄位，再於 `api_matrix.json` 加一列（或把欄位加到既有列）。
2. 填滿九個格子。優先在 `test_api_parity_wire.py` 寫 probe；否則以檔案與函式名稱引用 route 層級的測試。
3. 若補上了缺口，在同一個 commit 把格子改成 engaged 並降低 `gap_budget`。

執行 `uv run pytest tests/unit/test_api_parity.py tests/unit/test_api_parity_wire.py -q`。另見[請求生命週期](/docs/internals/request-lifecycle)與[代理程式相容性](/docs/developers/agent-compat)。


---

<!-- developers/architecture -->
---
title: 架構
description: 請求如何流經 gateway 與引擎、兩條服務路徑、前綴快取、推測解碼、batch-invariant kernel 與無損保證，以及受限解碼。
---

Yunshu 是針對 Apple Silicon 的單節點推論引擎。單一行程同時執行 FastAPI gateway 與以 MLX 為基礎的引擎，並提供 OpenAI、Anthropic 與 Ollama 風格的 API。本頁說明各部分如何組合，對象是會閱讀或修改程式碼的人。這裡只陳述程式碼實際做的事；可調整的行為請見[設定](/docs/guides/configuration)。

## 套件結構

儲存庫是扁平的 monorepo，Python 套件都在 `python/` 底下。

| 套件 | 職責 |
|---|---|
| `yunshu_gateway` | FastAPI 應用程式。`routers/` 實作 OpenAI、Anthropic、Ollama、MCP、Realtime 與 Tavily 相容介面；`schemas/` 放共用的請求正規化；`server_tools/` 執行伺服器端的網路搜尋、擷取與 MCP connector；`middleware/` 有驗證、指標、請求日誌、速率限制、斷線處理與 `x_yunshu` 擴充 |
| `yunshu_engine` | 所有實際執行模型的部分：模態分派（LLM、VLM、OCR、ASR、TTS、圖像、embeddings）、兩條文字服務路徑、取樣與限制、推測解碼、前綴快取、Metal kernel（`kernels/`）以及設定註冊表（`settings.py`） |
| `yunshu_kv` | KV 快取的建構元件：block pool 與雜湊、序列化、壓縮、SSD 儲存與 warm 層。引擎的前綴快取就是由這些元件組成 |
| `yunshu_cli` | `yunshu` 指令：`serve`、`chat`、`launch`、`service`、`config`、`doctor`、`cache` 等 |
| `yunshu_control` | 少量共用輔助：稽核日誌與 token 計數 |

## 從請求到 token

```text
client ── HTTP ──> middleware ──> router ──> engine dispatch
                                              │
                    ┌─────────────────────────┴───────────────────────┐
                    │ VLM batch runner                                │ text fast path
                    │ (every mlx-vlm model)                           │ (text-only mlx-lm models)
                    └─────────────────────────┬───────────────────────┘
                                              ▼
                              one MLX thread, one Metal stream
```

1. **Middleware** 驗證請求（只有設定了 `YUNSHU_AUTH_TOKEN` 才需要 token）、指派 `X-Request-Id`、記錄指標，並監看用戶端斷線；斷線會取消該次生成。
2. **Router** 依方言的 schema 驗證請求本文，並加以正規化（null 欄位視為未設定，`guided_*` 與 `structured_outputs` 折疊成同一種限制形式，驗證 tool choice），再轉成一個內部的生成請求。
3. **引擎分派** 查找模型（`ModelManager` 延遲載入模型、在記憶體壓力下以 LRU 淘汰，也可以釘選模型），並把請求交給該類型的引擎。
4. 引擎回傳 token；gateway 再把它們轉成方言的回應或串流，包括 usage、工具呼叫區塊、推理內容拆分與附加的 `x_yunshu` 欄位。

## 兩條服務路徑

所有 GPU 工作都在**單一 MLX 執行緒**上進行：一個全域的單 worker executor 擁有執行緒本地的 Metal stream，每個引擎都把工作提交到那裡。多模型服務因此是安全的，也是程式碼從不在 event loop 上直接操作 MLX 陣列的原因。

### VLM batch runner

所有經由 `mlx-vlm` 服務的模型（`VLMEngine`）都跑在 VLM batch runner 上，由 `VLMEngine._build_batch_runner` 建構，runner 承載 round driver，round driver 以三種模型層服務每個 row：packed Qwen3.5（dense 與 MoE）、packed Flash-Next（Qwen4），以及 generic 層（模型自己的 upstream forward，逐 row 執行）供其他所有家族使用。這也包含送到 Qwen3.5 這類 VLM 檢查點的純文字請求。

- **連續批次處理**，每個請求有自己的取樣參數與種子（`RowSampler`）。預填一次只接納一個請求，並與其他列的解碼交錯進行。
- **前綴快取（APC）** 適用於所有沒有滑動視窗快取的模型家族：混合模型使用精確檢查點，媒體以圖像像素與音訊特徵為鍵，另有選用的 SSD 層。見[提示詞快取](/docs/guides/prompt-caching)。
- **圖像、音訊與影片輸入**由 runner 的媒體準備步驟處理。
- **推測解碼** 僅限 Qwen3.5 家族（見下）。
- VLM 不接受 LoRA 轉接器與自訂 logits processor。

Runner 只產出 token id。解碼成文字、stop 字串、思考狀態與交給 HTTP 層的傳遞都留在 `VLMEngine`，所以每條文字路徑回報結果的方式一致。

### 純文字快速路徑

純文字 `mlx-lm` 模型走 `_generate_fast`，直接呼叫 mlx-lm 的 `generate_step`，一次處理一個請求；對這類模型的並行請求會被序列化。這條路徑有自己的前綴快取（`KVPrefixCache`）、KV 量化、n-gram 與 jump-forward 選項，以及受限解碼的取樣器。

### 每個請求的狀態

- **取樣器**：溫度、top-p、top-k、min-p、懲罰項、logit bias 與種子都是逐請求套用。使用推測解碼的取樣請求會抽取以位置為鍵的雜訊，讓結果不依賴哪些 token 被草擬。
- **Stop 與推理狀態**：stop 字串、結束 token 與推理邊界由每個請求自己的狀態機追蹤（建立在 Aho-Corasick trie 上），所以即使 stop 序列橫跨 token 邊界也能被找到。
- **Detokenizer**：每個請求有自己的串流 detokenizer。Detokenizer 從不放進池中重複使用，因為 reset 可能洩漏位元組緩衝區。

## 前綴快取

兩條路徑都會重用先前提示詞中與新提示詞共享前綴的 KV 快取。VLM runner 的 APC 儲存精確檢查點（某個 token 位置的注意力 KV 加循環狀態），為每一組不同的「system prompt 加工具」保留一個開頭檢查點，以較新的檢查點取代同一段對話較舊的檢查點，並把被淘汰的檢查點寫入可跨重啟保留的 SSD 層。精確視窗還原依模型而定；Gemma 4 已有配對驗證，但不代表所有滑動視窗模型皆支援。無損與有損的選項，以及 usage 中會看到什麼，見[提示詞快取](/docs/guides/prompt-caching)。

## 推測解碼

對 VLM runner 上的 Qwen3.5 家族（model type 為 `qwen3_5`、`qwen3_6` 與 `qwen3_5_moe`），解碼可以先草擬數個 token，再用一次前向傳遞驗證：

- **MTP**：使用檢查點自帶的 multi-token-prediction head 草擬。這是預設（`YUNSHU_MTP`），預設區塊大小為 6 個 token（`YUNSHU_MTP_BLOCK_SIZE`）。
- **DFlash**：使用外部的 block-diffusion 草擬器。`YUNSHU_VLM_DRAFT` 可指向草擬器目錄、強制使用 `mtp`，或設為 `off` 關閉草擬；未設定時，會使用在模型目錄或 Hugging Face 快取中找到的相符草擬器。

推測解碼在 round driver 的封裝 row 上執行，因此並行請求也會起草。其他模型家族使用 generic 層，不做推測。

### Batch-invariant kernel 與無損保證

Yunshu 做出的保證是：**開啟推測解碼時，貪婪（greedy）輸出與同一個引擎關閉推測解碼時 token 完全相同。** 為此，目標模型在解碼（一列）與驗證（數列）時的每個矩陣乘法，都通過同一個 kernel，其每一列的結果不依賴有幾列共用這次呼叫；注意力與 GatedDeltaNet 的驗證路徑相對於單列解碼是位元精確的。只有引擎標記為目標的模組會被改道，草擬模型保留原本的 kernel；預填區塊也維持原本的 kernel。

這個保證沒有說的是：輸出不需要與原生 MLX 的單列解碼位元相同。不同的歸約順序會讓 logits 產生捨入等級的差異，這種漂移是預期內的。Kernel 是在執行期編譯的 Metal kernel（`mx.fast.metal_kernel`），放在 `python/yunshu_engine/kernels/`；其中一部分是從其他專案 vendor 或衍生而來，記錄在[上游追蹤](/docs/developers/upstream-tracking)。只有在同一個檢查點的端到端比較顯示確實有收益、且輸出相同（或在容差內）時，才會採用自訂 kernel；見[驗證](/docs/developers/verification)。

## 受限解碼

`response_format`、`grammar`、`guided_*` 與強制的 `tool_choice` 會轉成一個限制物件。每一步取樣器都會遮蔽限制不接受的 token。JSON schema 與 `json_object` 預設使用 `llguidance` matcher，或內建的狀態機（`YUNSHU_JSON_SCHEMA_ENGINE`）；正規表示式與 choice 由內建引擎編譯；上下文無關文法使用 `llguidance`。預設的遮蔽方式是 allowlist 取樣器，另有選用的 xgrammar 風格 bitmask 引擎（`YUNSHU_GRAMMAR_BITMASK`）與 jump-forward 解碼（`YUNSHU_JUMP_FORWARD`）。無效的限制會在生成前以 `400` 拒絕。見[結構化輸出](/docs/guides/structured-output)。

## 設定

每個 `YUNSHU_*` 設定都登錄在 `python/yunshu_engine/settings.py`，有型別、預設值、說明與分組，並透過 `settings.get(...)` 讀取；程式碼從不用 `os.environ` 讀取它們（由單元測試強制）。值的來源依優先順序為：命令列（`--set`）、環境變數、`~/.yunshu/config.toml`、登錄的預設值；`yunshu config` 會顯示生效的值與其來源。新增設定的規則見[貢獻指南](/docs/developers/contributing)。

## 相關頁面

- [提示詞快取](/docs/guides/prompt-caching)
- [結構化輸出](/docs/guides/structured-output)
- [貢獻指南](/docs/developers/contributing)
- [驗證](/docs/developers/verification)


---

<!-- developers/auxiliary-scheduling -->
---
title: 輔助請求排程
description: 已擷取的用戶端附帶請求（opencode 標題生成）如何讓位給互動式 agent 回合、prefill 工作如何排序，以及輸出為什麼保持相同。
---

Agent 用戶端在使用者的一次操作中，可能送出不只一個請求。例如 opencode 會在主要 agent 回合旁同時啟動標題生成請求。在單一 GPU 上，標題請求可能卡在使用者正在等待的長 prefill 前面。Yunshu 精確辨識已擷取的輔助請求，讓互動式回合先執行，並保持每個輸出與一般排程逐 token 相同。本頁是維護者的設計參考；用戶端行為請見 [Agent 用戶端](/docs/guides/agents)。

## 它做什麼

一個策略在 VLM batch runner 上運作，且只有在已載入的後端實際啟用合格的 batch-invariant kernel（`_prefix_invariant_dispatch`，即 27B 等調校過的 Qwen3.5 系列）時才預設開啟：

- **輔助請求讓位**（`YUNSHU_AUXILIARY_SCHEDULING`）。`python/yunshu_gateway/admission.py` 的 `auxiliary_kind` 對已驗證的 Chat Completions 請求本體分類。只有符合已擷取的 opencode 標題指紋的請求，才算輔助請求：沒有 tools 或 functions、已擷取的用戶端模型名稱、`max_tokens` 為 32000、恰好三則純文字訊息且角色為 `system,user,user`，且 system 訊息的 SHA-256 等於已擷取的值。其他請求，包括 Claude Code 與 Codex，維持優先權 0，因為這兩者沒有擷取到輔助請求，也不憑空編造指紋。結果是請求記錄上的 `scheduling_priority = -1`；它不會進入 prompt 或取樣參數。
- **Prefill 順序**由 round driver 自行決定：每個請求都是一個 row，其 prefill 依剩餘量最短優先排序。早先的未快取工作排序設定（`YUNSHU_UNCACHED_SCHEDULING`）已隨 stock runner 一併移除。

下方的時序圖顯示一個標題請求與一個 agent 回合同時到達的情形。

```mermaid
sequenceDiagram
  participant C as client
  participant G as gateway admission
  participant R as VLM batch runner
  C->>G: title request (auxiliary)
  C->>G: agent turn (interactive)
  G->>G: auxiliary waits 500 ms for its companion turn
  G->>R: agent turn runs first
  Note over G,R: auxiliary waits for interactive requests to drain or 10 s aging
  G->>R: auxiliary admitted, APC off
  R->>R: auxiliary rows pause between GPU slices while a primary exists
```

### Gateway 行為

被辨識為輔助的請求先等待 500 ms（`defer_auxiliary`），讓隨行的 agent 回合到達，然後等到沒有互動式請求進行中，或自己已等待 10 秒（`AGING_S`），才進入引擎。一般請求不會多等。這個延後也讓輔助工作在有主要請求時，不會進入序列化的文字快速路徑。

### Runner 行為

- VLM runner 在有主要工作時保留待處理的輔助 row，把兩種優先權放在不同 batch，並在有主要請求時暫停進行中的輔助 batch。[round driver](/docs/developers/round-driver) 有獨立的輔助 driver，使用相同的模型、chunk 與取樣路徑。
- 自上次服務起已等待 10 秒的輔助 row 會得到一次服務機會。這不是完成期限：進行中的 atom、較舊的工作、用戶端取消與期限仍然適用。
- 互動式 prefill 在被一個 atom 超越後獲得持續的 FIFO 保護，所以之後到達的短請求，不能一再插到長的冷請求前面。被選中的請求會先完成最後 2048 token 的視窗並送出第一個 token，才償還解碼負債。
- prefill atom 之後欠解碼中 row 的解碼時間至少 75 ms（`DECODE_QUANTUM_S`），上限為 `DECODE_QUANTUM_MAX_S`，仍在前幾個 token 的 row 獲得較大的份額。簡短的主要請求完成交接（`PRIMARY_HANDOFF_S`，100 ms）讓即將完成的主要請求排在輔助請求進入之前，並使用只在 CPU 上的計時器，使 MLX 工作留在單一 executor 執行緒。

## 為什麼

證據來自儲存的用戶端流量，而不是用戶端名稱或小模型的啟發式判斷。`scripts/research/agentic/characterize_auxiliary.py` 會盤點已擷取的請求本體。在擷取的資料中，opencode 會在 agent 回合旁送出標題請求（prompt 很短、輸出上限很大），而 Claude Code 與 Codex 沒有擷取到輔助請求。更廣泛的啟發式可能讓真正的使用者工作被降低優先權。範圍收窄的代價是，未知的附帶請求仍維持互動式。

## 保證

- **輸出相同。** 輔助排程只改變順序，不改變 token 區段、取樣或 grammar 狀態。在 27B checkpoint 上的擷取重播，會在策略開啟與關閉下比較完整的內容、推理、tool-call 與 finish-reason 摘要，涵蓋主要與輔助回應；閘門要求每項比較都相符。
- **不取消輔助工作。** 輔助輸出不會被取消、丟棄、重啟或截斷；暫停的 row 帶著狀態繼續。已取消的暫停 row 在下一個 slice 被清理。
- **快取隔離。** 輔助請求不讀寫前綴快取（APC），不能取代或驅逐主要請求的 RAM 或磁碟 checkpoint，也不更新 prefill 成本模型。它們仍執行相同的標準 checkpoint 運算，使數值與一般排程相同。文字快速路徑同樣對它們略過前綴與 prompt 快取。
- **不合格的後端維持一般排程**（FIFO 準入與一般 APC），除非明確啟用該設定。
- **不可搶佔的 kernel。** 已提交的 GPU 運算無法中斷。在輔助 prefill 開始後才到達的主要請求，等的是目前的 slice，而不是整個輔助生成。純文字 `mlx-lm` 快速路徑仍會讓已開始的請求跑完；那裡只套用 gateway 延後與快取保護。
- **context 防護使用精確 token 數。** 合格的 VLM 後端為成功的文字 token 計數保留以 tokenizer 為範圍的 LRU（128 個字串、估計 2 MiB 文字），讓重複的 prompt 不必在 gateway 的 context 與 prefill 防護中重新分詞。角色與工具的額外開銷與媒體成本仍逐次計算，失敗的編碼不會被快取。這只節省主機端工作。

## 設定

| 設定 | 預設 | 效果 |
|---|---|---|
| `YUNSHU_AUXILIARY_SCHEDULING` | 僅合格後端為 `true` | `0` 關閉，`1` 也讓不合格的後端啟用。穩定的部署覆寫項 |

預設值由 `settings.scheduling_enabled` 解析：當值來自預設來源時，由已載入後端的資格決定；明確設定的值永遠優先。

## 限制

- 只辨識已擷取的 opencode 標題指紋。模型名稱、輸出上限或 system 文字不同的請求都是互動式。
- 量測結果只涵蓋 27B VLM runner。證據來自一次擷取的 session，在交錯的全新伺服器配對中重播；這是排程取捨，不是通用的速度提升。開啟策略後，擷取資料的首 token 時間中位數略差，而尾部、六回合完成時間與長 prefill 混合負載有改善（見下）。
- 輔助請求的延遲是刻意犧牲的：重播中，開啟策略後標題的平均首 token 時間較高。
- round driver 維持嚴格的輔助優先權且沒有老化，所以持續不斷的主要 driver 流量可能無限期延後輔助服務。
- 未擷取的用戶端與 API（Responses、Messages）不會被分類。

## 如何驗證

- 單元測試：`tests/unit/test_auxiliary_inventory.py`、`tests/unit/test_auxiliary_scheduling.py`、`tests/unit/test_priority_scheduling.py` 與 `tests/unit/test_priority_queue.py` 涵蓋指紋近似但不符、關閉、跨 executor 執行緒的優先權傳遞、待處理與進行中的優先權反轉、保留狀態的恢復、獨立的推測與 driver lane，以及排除 APC。
- GPU 重播：`scripts/research/agentic/i8_summarize.py` 會拒絕不完整的執行，並比較主要與輔助請求的完整回應摘要；僅用 CPU 的排序由 `scripts/research/agentic/i8_admission_sim.py` 模擬。這些透過 GPU 佇列執行；見[驗證](/docs/developers/verification)。
- 量測結果（Qwen3.8-27B，2026-10-03，`docs/reports/PERF_TREND.md`）：擷取的主要請求首 token 時間 p50 0.7515 s 至 0.7570 s，p90 8.5990 s 至 7.6239 s，六回合完成時間總和 40.226 s 至 33.504 s；長 prefill 混合負載 p50 23.098 s 至 8.6795 s。所有配對的摘要皆相符。


---

<!-- developers/contributing -->
---
title: 貢獻指南
description: 建立開發環境、執行 lint 與測試、遵守設定註冊表規則，並送出 pull request。
---

Yunshu 的原始碼在 [github.com/YuhuanStudio/Yunshu](https://github.com/YuhuanStudio/Yunshu)，採用 Apache 2.0 授權。你提交的貢獻即表示同意以相同方式授權。本頁說明日常的工作流程；儲存庫中的 `CONTRIBUTING.md` 與 `AGENTS.md` 是同樣規則的精簡版。

## 前置需求

- 搭載 Apple Silicon 的 Mac，以及原生 arm64 的 Python。Yunshu 需要 macOS。
- Python 3.13 或更新版本。
- [uv](https://github.com/astral-sh/uv)，這是本專案唯一使用的 Python 套件管理器。
- [just](https://github.com/casey/just) 作為指令執行器（`brew install just`）。

## 建立環境

```bash
git clone https://github.com/YuhuanStudio/Yunshu.git
cd Yunshu
just setup
```

`just setup` 會執行 `uv sync --all-extras --dev`。若想要較輕量的環境，只安裝需要的 extra：

```bash
uv sync --extra vision        # mlx-vlm：VLM、OCR、Qwen3.5 家族
uv sync --extra audio         # mlx-audio：ASR、TTS 與 Realtime 語音串接
uv sync --extra omni          # mlx-vlm + torch：原生 Qwen3-Omni 語音對語音
uv sync --extra generation    # 圖像生成
uv sync --extra embeddings    # /v1/embeddings 與 /v1/rerank
```

以本機 MLX 模型啟動開發伺服器：

```bash
YUNSHU_MODEL=/path/to/mlx-model just dev    # 在 127.0.0.1:8000 啟動 uvicorn
just dev-multi                              # 多模型模式，模型放在 ./models
```

## 開發迴圈

| 指令 | 作用 |
|---|---|
| `just lint` | 對 `python/` 與 `tests/` 執行 `ruff check`，並執行 mypy 基準檢查 |
| `just format` | 對 `python/` 與 `tests/` 執行 `ruff format` |
| `just test-unit` | 單元測試（`tests/`，排除整合測試）；不需要任何模型 |
| `just test` | 目前與上面相同，執行單元測試 |
| `just test-integration` | 整合測試，需要真實模型或執行中的服務（需主動執行） |
| `just test-single tests/unit/test_foo.py` | 只跑一個檔案 |

單一測試也可以用 `uv run pytest tests/unit/test_foo.py -q` 執行。pytest 設定在 `pyproject.toml`：嚴格的 `xfail`、asyncio auto 模式，以及 `gpu`、`integration`、`slow` 三個標記。

程式風格：Python 3.13，以 ruff 格式化，行寬 88，lint 規則為 `E, F, W, I, N, UP, B, SIM`，以 `just lint` 為準。註解應說明「為什麼」（隱藏的限制、細微的不變式、變通辦法），而不是重述程式碼。

## 儲存庫結構

| 路徑 | 內容 |
|---|---|
| `python/yunshu_gateway/` | FastAPI gateway：路由、schema、middleware、伺服器端工具 |
| `python/yunshu_engine/` | 推論引擎：服務路徑、取樣、推測解碼、前綴快取、kernel、設定註冊表 |
| `python/yunshu_kv/` | KV 快取建構元件 |
| `python/yunshu_cli/` | `yunshu` CLI |
| `python/yunshu_control/` | 稽核日誌與 token 計數 |
| `tests/` | `unit/`、`integration/` 與 `e2e/` 測試 |
| `scripts/` | 工具：`gen_config_docs.py`、`dev/`（驗證與發版輔助）、`vendor/`、`release/` |
| `docs/` | 參考指南 |
| `frontend/` | Web 控制台，也包含這份文件（`frontend/docs/`，三種語言的 MDX） |

各套件如何組合見[架構](/docs/developers/architecture)。Metal kernel 在執行期編譯（`mx.fast.metal_kernel`），所以沒有獨立的 kernel 建置步驟。

## 設定註冊表規則

每個 `YUNSHU_*` 設定都登錄在 `python/yunshu_engine/settings.py`，並以 `settings.get(...)` 或其型別化的 getter 讀取。程式碼絕不對 `YUNSHU_*` 名稱使用 `os.environ` 或 `getenv`；單元測試會強制檢查這一點。

新增設定的步驟：

1. 在 `settings.py` 加一行 `_add(...)`，包含名稱、型別、預設值、一行說明與分類。
2. 在使用的地方以 `settings.get("YUNSHU_NAME")` 讀取。
3. 重新產生參考文件並一併提交：

   ```bash
   uv run python scripts/gen_config_docs.py
   uv run python scripts/gen_config_docs.py --check    # 檢查文件是否為最新（CI 風格）
   ```

4. 若該設定改變了預設值、API 或 CLI 行為，請記在 `CHANGELOG.md` 的 Unreleased 區段，使用者需要動作時附上遷移步驟。

值的解析優先順序由高到低為：`yunshu serve --set KEY=VALUE` 與具型別的 `serve` 旗標、行程環境變數、設定檔（`~/.yunshu/config.toml`，由 `yunshu config set` 寫入），最後是登錄的預設值。`yunshu config` 會印出生效的值與其來源。

### 實驗性旗標是暫時的

設定可以標記為 `stability="experimental"`。每一個都必須寫明將用哪項量測來決定它（`decide=`）與加入時間（`added=`），而且同時最多只能有八個。量測完成後，勝出的做法成為預設，旗標與落敗的程式路徑一併刪除。只有**無損**的最佳化（版面配置、kernel、排程器，也就是不改變輸出的改動）可以這樣取代預設；若選擇退出的開關確有價值，可以保留。**有損**的選項（KV int8、權重量化，以及任何改變輸出品質的做法）是預設為無損的穩定使用者選項，單靠基準測試不會讓它們成為預設。

## 熱路徑的改動

效能工作以端到端結果判斷。單獨更快的 kernel 並不足夠：改動熱路徑時，需要同一個檢查點上的輸出比較（token 完全相同，或在明確說明的容差內），以及對首 token 延遲、解碼速度或前綴重用的實測影響。工具說明見[驗證](/docs/developers/verification)。

## Commit 與 pull request

Commit 訊息遵循 [Conventional Commits](https://www.conventionalcommits.org/)：

```text
feat(cli): add `yunshu pull` subcommand
fix(gateway): correct streaming SSE keepalive interval
docs(readme): clarify non-goals
```

對 `main` 開 pull request，說明改了什麼與原因，並附上 `just test-unit` 的輸出。只有改動觸及熱路徑時才需要附基準比較。審查的期望：

- 讓改動保持聚焦，並描述使用者可見的前後差異。
- 修 bug 需要一個沒有修正就會失敗的回歸測試。
- 記錄你執行了什麼，以及哪些沒有驗證。純文件的改動不需要模型基準。
- 揭露是否使用 AI 協助，並自行檢視結果，包括來源與授權聲明。
- 大型架構變更請先走簡短的 RFC。

## 公開文件檢查

改動已記載的行為時，下列檢查能讓文件與程式碼保持一致：

```bash
uv run pytest tests/unit/test_public_docs.py tests/unit/test_doc_source_consistency.py -q
uv run python scripts/gen_config_docs.py --check
uv run python scripts/dev/api_coverage.py
```

`scripts/dev/ci-local <commit-sha>` 會在乾淨的 Python 3.13 checkout 中重現發版的建置檢查，不使用任何模型：lint、格式、mypy、單元測試、套件建置、`twine` 驗證與 wheel 安裝冒煙測試。

## 範圍

Yunshu 是單節點推論引擎。分散式或多節點服務，以及多租戶控制平面，不在範圍內。單節點的解碼與最佳化工作（推測解碼、受限解碼、量化、快取、kernel）在範圍內且歡迎參與，讓真實用戶端的行為與對照廠商 API 時一致的相容性工作也是。

## 相關頁面

- [架構](/docs/developers/architecture)
- [驗證](/docs/developers/verification)
- [發版關卡](/docs/developers/release-gate)
- [上游追蹤](/docs/developers/upstream-tracking)
- [設定](/docs/guides/configuration)


---

<!-- developers/hardware-validation -->
---
title: 硬體驗證
description: Yunshu 跨 Apple Silicon 世代的驗證計畫，以及 M5 Max 硬體地圖：各單元量測到什麼、Yunshu 用到哪些，以及哪些想法通過了 roofline 檢驗。
---

本頁分成兩個部分。第一部分是 Apple Silicon 支援的驗證計畫，它是產品目標，並不代表每種晶片與 macOS 的組合都已測試過。第二部分是一台 M5 Max 機器的硬體地圖，用來決定最佳化該投入哪裡。

## 硬體驗證計畫

託管的 `macos-14` CI 作業不能證明特定的 M 系列 GPU 世代，也不能證明真實的 Metal 可用。目前的工作流程是 `.github/workflows/ci.yml` 與 `release.yml`；沒有為硬體覆蓋額外配置 runner。

### 它做什麼

| 層級 | 觸發 | 檢查 | 需保留的證據 |
|---|---|---|---|
| 快速 | 每次變更 | Linux 上的 lint 與建置；在依賴允許的情況下，執行不需模型的公開契約與 CLI 測試 | 原始碼 SHA、依賴鎖定檔與測試數量 |
| 正確性 | 受信任的 PR 或發布前 | Apple Silicon 單元測試；微型模型的 API、快取與約束冒煙測試 | 晶片、記憶體、macOS、Python 與 MLX 版本、檢查點修訂版，以及通過、失敗與略過的數量 |
| 硬體覆蓋 | 排程或發布前 | M1 到 M5；最舊的支援 macOS 與目前的 macOS，使用可取得的主機 | 明確標示已測試與未測試的格子；輸出、快取與 logprob 一致性 |
| 效能 | 受控的排程執行 | 同一檢查點的解碼，以及冷、暖與第二回合的 TTFT；三次交錯重複 | 原始收據、實際啟用的模式、輸出長度、摘要、中位數與退步 |

### 保證

- 某個版本無法取得的硬體會列為未測試，絕不標示為通過。
- 絕不從 runner 名稱推斷 GPU 覆蓋。
- 不受信任的 PR 程式碼不會在個人模型主機上執行。
- 正確性失敗與效能雜訊、基礎設施失敗分開處理。失敗的案例會保留，不會被默默重試而從報告中消失。
- 只有在穩定的雜訊基線建立之後，基準測試門檻才會變成關卡。

### 限制

維護者必須先盤點可用主機與支援的最低 macOS 版本，這個計畫才會成為必要的 CI。目前 M5 Max 是計時用機器，36 GB 的 M3 筆電只提供正確性與可攜性證據：M3 的結果絕不會核准 M5 熱路徑的預設值，M3 上的失敗必須在 M5 重現後，才能否決 M5 的最佳化。此通道記載於[邊服務邊開發](/docs/developers/serve-and-develop)。

### 如何驗證

正確性層級是 `scripts/dev/ci-local <sha>` 加上發版關卡的 `install` 階段；見[發版關卡](/docs/developers/release-gate)。M3 通道是 `scripts/dev/m3sweep` 與 `gpuq submit --device m3`。基準測試方法見[基準測試](/docs/guides/benchmarks)，準確度證據見[準確度對齊](/docs/developers/accuracy)。

## M5 Max 硬體地圖

本節是單一機器（M5 Max、40 核 GPU、128 GB）的歷史探測紀錄，並不代表目前的依賴版本或發版效能；要看有日期的數字，請用[基準測試](/docs/guides/benchmarks)。探測腳本位於 `scripts/research/hw/`，每個都會寫出 JSONL，數字都在裡面（本頁不收錄，因為它們只代表同一台機器在某一時間點的結果）。每個 GPU、ANE 與重度 CPU 探測都在共用的 GPU 鎖下執行，因為這些單元共用同一個記憶體系統，一個執行會干擾另一個。

### 各單元的用途

| 單元 | 探測腳本 | Yunshu 用到它的什麼 |
|---|---|---|
| 記憶體頻寬 | `bw_unified_memory.py`、`decode_proxy_step.py`、`decode_step_model.py`、`decode_step_engine.py` | 解碼每一步都要讀取一次完整的模型權重，所以受頻寬限制 |
| GPU 張量單元（NAX） | `gpu_compute.py`、`tensor_unit_peak.py` | prefill 使用 MLX 中的 NAX 量化矩陣乘法；解碼與驗證使用 NAX 封裝的 4 位元 kernel |
| GPU 啟動與同步 | `launch_overhead.py` | 啟動成本透過 `async_eval` 藏在 GPU 工作之後 |
| ANE | `ane_probe.py`、`pick_best_ane.py`、`bg_gpu_concurrency.py`、`session_ane_prefill.sh` | 僅作為嵌入協同處理器（`ane_embedding.py`） |
| CPU | `cpu_probe.py` | 把 token 轉回文字（detokenization）、文法與取樣的銜接工作 |
| 解碼旁的 prefill | `gpu_stream_overlap.py`、`bench_prefill_interleave.py` | 以 prefill 區塊大小作為策略（`ROUND_PREFILL_CHUNK`） |

### 發現

- **解碼受權重頻寬限制。** 一步不可能低於以最佳實測讀取頻寬讀完權重的時間，而原生解碼已經很接近這條線。只有每個 token 讀取更少位元組（每次讀權重接受更多 token、更低位元數），或讓多列共用讀取，才能推進。小型投影（K/V、GDN gate）遠低於頻寬線，是融合 kernel 啟動可能有幫助的地方。
- **寬驗證幾乎免費。** 量化矩陣乘法在數列以內仍受權重頻寬限制，運算要超過數十列才會成為瓶頸，所以一次權重讀取可以服務多列驗證。這就是推測解碼與多列解碼划得來的原因。
- **啟動開銷不是瓶頸。** CPU 在 GPU 執行前一步時建立下一步的計算圖。對解碼層使用 `mx.compile`、`MLX_MAX_OPS_PER_BUFFER` 與 `MLX_METAL_FAST_SYNCH` 都沒有可測量的變化，而且 MLX 沒有可利用的圖重播。
- **ANE 不是免費的頻寬。** GPU 解碼時它幾乎保有自己全部的速率，但每次 ANE 呼叫都從同一個 DRAM 串流權重，會拖慢 GPU 解碼。單獨使用時它的 prefill 約為閒置 GPU 速率的三分之一，所以最多只適用於「另一個請求正在串流輸出時才到達」的提示詞，而且它的數值與 MLX 的 4 位元權重不同（屬於有損選項，不是預設）。
- **CPU 幫不上解碼。** 對單列而言，在大詞彙表上取樣很便宜（argmax 藏在下一步之後），但多列的 top-k 或排序就不是了，所以取樣留在 GPU 上。CPU 的記憶體流量也會拖慢 GPU，因此用 CPU 產生草稿並不實際。
- **Wired 記憶體與電源。** `mx.set_wired_limit` 與快取上限的調整，在 128 GB 的機器上沒有增益；持續解碼迴圈中看不到降頻。
- **Prefill 與解碼互相競爭。** 兩個 GPU 命令佇列不會讓 prefill 與解碼重疊，而且解碼沒有優先權。在單一佇列上，較小的 prefill 區段能讓執行中的請求解碼快很多，代價是新抵達的提示詞首個 token 的時間變長。兩種區塊大小下，提示詞的 token 都與單獨執行時相同。`ROUND_PREFILL_CHUNK` 設定區段大小。

### 提案與結果

| 想法 | 結果 |
|---|---|
| 以 prefill 區塊作為策略 | 完成：`ROUND_PREFILL_CHUNK`，預設 512；依解碼列數自適應調整尚未完成 |
| 讓解碼 kernel 維持在頻寬線上（融合小型投影） | 未完成 |
| 更寬的驗證與多列解碼 | 透過 round driver 進行中；見 [Round driver](/docs/developers/round-driver) |
| 張量單元上的 int8 activation prefill | 有損，所以只能是使用者選項；未採用 |
| round driver 中的批次序列混合器 | 未完成，預期增益小 |
| 在 GPU 解碼旁進行 ANE prefill | 有損選項，投入極高；排在最後 |
| 在 CPU 上取樣 | 否決：留在 GPU 上 |
| ANE 上的草稿器與 GPU 驗證重疊 | 放棄：草稿取決於上一輪接受的 token，而且 ANE 會佔用 GPU 頻寬 |
| 解碼層的 `mx.compile`、wired 記憶體調校、高效能模式、prefill 專用的第二個命令佇列 | 放棄：沒有可測量的效果，或反而更差 |

### 設定

| 設定 | 預設值 | 效果 |
|---|---|---|

### 如何驗證

在 GPU 佇列下執行探測，以免干擾共用的單元，例如：

```bash
scripts/dev/gpuq submit --label hw-decode-proxy --mem-gb 30 -- \
  python scripts/research/hw/decode_proxy_step.py
```

開始最佳化之前先算出 roofline：理論上限與其依賴。要在執行環境中比較，而不是用孤立的微基準測試，因為每次呼叫都會 eval 的元件會高估小型 kernel 的成本。

## 相關頁面

- [發版就緒](/docs/developers/release-readiness)
- [驗證](/docs/developers/verification)
- [基準測試](/docs/guides/benchmarks)


---

<!-- developers/prior-art-formats -->
---
title: 檢索與既有格式
description: Yunshu 載入哪些已發布的 embedding、reranker 與分類器 checkpoint 格式、各自使用哪個 loader，以及如何對照上游實作檢查這些 loader。
---

對於檢索模型，Yunshu 直接載入實際發布的格式，而不要求私有轉換。撰寫 loader 之前，會先尋找既有的 MLX 移植、checkpoint 格式或執行環境，並載入該格式。本頁列出涵蓋的範圍、刻意不支援的項目，以及一致性檢查的做法。這是維護者參考；端點請見 [Embeddings](/docs/api/embeddings) 與 [Rerank](/docs/api/rerank)，衍生檔案的來源請見[上游追蹤](/docs/developers/upstream-tracking)。

## 它做什麼

| 系列 | Loader | 備註 |
|---|---|---|
| EmbeddingGemma 2（bf16、affine 4-bit 與其他已發布的量化） | `python/yunshu_engine/embedding_gemma2_loader.py` 的 `load_published_model`：已安裝 `mlx_vlm.models.embedding_gemma2` 時使用維護中的 `mlx_vlm.embedding_loader.load_embedding_model`（strict）；否則使用衍生 loader | 衍生的後備方案使用依 Hugging Face `embedding_gemma2` 架構撰寫、vendored 的 MIT 文字塔，以及 mlx-vlm 的 Gemma 4 視覺與音訊塔。量化模組依 checkpoint 的 scale 建構；視覺與音訊塔可保留浮點權重；打包的整數張量絕不轉成浮點。未量化的 checkpoint 沿用原本的浮點 loader。來源記錄在 `vendor.json` |
| BERT、RoBERTa、XLM-RoBERTa 編碼器與序列分類器 | mlx-vlm 維護中的 encoder loader 搭配 `SequenceClassificationModel` | 涵蓋使用不帶前綴的 backbone 名稱的已發布 BGE 轉換、單標籤與多標籤 head，以及帶浮點或量化 head 的量化編碼層。缺少 backbone 或 head 張量會是載入錯誤 |
| Qwen3 yes/no reranker | 在 mlx-lm 量化 loader 上使用官方的 instruction、prefix 與 suffix 配方 | 與轉換後 checkpoint 自帶的 `query` 與 `document` 角色模板一致 |
| Qwen3-VL 檢索 | 已安裝的 `mlx-embeddings` `model.process` API | 沒有任何 GPL 原始碼被複製進 Yunshu |

空的 embedding 輸入會回傳空清單，加入預設 instruction 時不會修改呼叫端的輸入字典。

## 為什麼

使用者會直接使用 Hugging Face 上發布的原樣 checkpoint。若 loader 悄悄換成不同的 head 或模板，會回傳看似合理但錯誤的向量與分數，因此每種格式要嘛和上游一樣正確載入，要嘛以可操作的錯誤訊息失敗。

## 保證

- checkpoint 缺少 head 或 backbone 時是載入錯誤，絕不悄悄替換。
- `JinaForRanking`（Jina v3）是另一種架構，仍不支援：它訓練好的排序 head 不能用 Qwen 的 yes/no logits 取代。
- Qwen3 reranker 的模板很重要：已發布的 0.6B 4-bit chat 模板預期 `query` 與 `document` 角色。若服務改傳 `user`，該模板會丟掉 query 與 document，導致不同的配對產生相同的 token id 與 logits。Yunshu 使用與轉換後角色模板相符的官方配方。

## 限制

- 2026-10-08 的 Hugging Face 盤點顯示，Google EmbeddingGemma 2 與所檢查的每個 mlx-community 轉換版本都只有單一 `model.safetensors`，因此這些已發布快照不會觸發多分片載入的缺陷。重新打包或私有的多分片 checkpoint 可能會遇到。這是有日期的盤點，不是對未來上傳的承諾。
- 與 `mflux` 的擴散模型比較屬於稽核，不是服務路徑。經檢視的 `mflux` 對應表會丟掉沒有 `mflux` safetensors metadata 的 affine 4-bit diffusers checkpoint 的 scale 與 bias，所以探測先解碼權重，並把結果標示為含格式橋接的浮點參考。它不是原生量化載入，也不改變任何服務端預設值。

## 如何驗證

- CPU 單元測試：`tests/unit/test_prior_art_check.py`、`tests/unit/test_priorfix_capabilities.py`、`tests/unit/test_priorfix_probes.py` 與 `tests/unit/test_priorfix_mflux_reference.py`。
- `scripts/dev/yv ab --base <sha> --cand <sha> --suite embedding --label <name>` 會載入 bf16、4-bit，以及重新打包成兩個分片的真實 bf16 checkpoint，在 Mac 上比較 Yunshu 的封裝與直接呼叫上游模型的結果，並對 bf16 向量套用 0.99985 的 fp32 cosine 下限。量化精度另行回報。
- `--suite priorart` 執行範圍受限的檢索、Omni 預處理輸入與固定種子的擴散比較；`--env PRIORART_KINDS=capabilities` 在一次 GPU 准入內，以獨立的子行程執行 Gemma 各格式、檢索、分類器、擴散稽核與 Omni 預處理，每個項目保留一份證據檔與回傳碼，並拒絕缺漏、過期或裝置錯誤的證據。`PRIORART_KINDS=diffusion-timing` 以 256 px、2 步、種子 7 執行三組交錯配對，並附上確切的工作負載與中位數。

這些是針對特定模態的稽核，不納入一般 LLM 套件。擴散比較的計時結果不用來決定效能或預設值。以上全都使用 GPU 佇列；見[驗證](/docs/developers/verification)。


---

<!-- developers/release-gate -->
---
title: 發版關卡
description: Yunshu 版本發布前必須通過的檢查、關卡如何測試已安裝的建置版本，以及新使用者第一個小時的就緒清單。
---

只有在確切要發布的 commit 上通過發版關卡，版本才會發布。關卡以使用者取得 Yunshu 的方式來測試：建置成 wheel，用 `uv tool install` 安裝到乾淨的環境，再用官方的 OpenAI 與 Anthropic SDK 透過 HTTP 驅動。每項檢查都會印出 `PASS`、`FAIL` 或 `SKIP`，結束時輸出總表，只要有任何失敗就以非零結束碼退出。已記載的功能若失敗就是 `FAIL`；某個模型家族的檢查點路徑沒有設定時，會以 `SKIP` 並附上原因回報。

關卡會把所有安裝與寫入的內容放在自己的根目錄底下：自己的 `HOME`、工具目錄與快取。它絕不會動到你的 `~/.yunshu` 或 `~/.local`。

## 階段

| 階段 | 必須成立的條件 |
|---|---|
| `install` | `uv build` 成功。`yunshu[vision]` 與 `yunshu[all]` 都能從 wheel 安裝。`--version` 與 `pyproject.toml` 一致。`yunshu doctor` 沒有失敗的檢查。`model list` 找得到模型目錄。對已在磁碟上的模型執行 `pull` 會拒絕下載。`config set models_dir` 能往返。`service install --dry-run` 會印出 launchd agent 且不寫入任何東西 |
| `serve-27b` | 旗艦模型 Qwen3.8-27B 在已安裝的執行檔上運作。功能矩陣全數通過。OpenAI SDK 通過 chat、串流、工具（auto、強制、串流 delta）、JSON schema、stop、logprobs、推理內容拆分與圖像輸入；Anthropic SDK 通過 messages、串流、工具使用與 thinking。生成中途中斷串流後，下一個請求仍能正確回答。32K token 的提示詞能找回其中的 needle。八個並行請求都能回答。伺服器的解碼速度與引擎在行程內的速度相當（同樣的貪婪提示詞各走一次，要求文字相同，並有吞吐量比值的門檻）。伺服器日誌沒有 traceback |
| `families` | 每個支援的模型家族都能啟動、通過冒煙檢查，並在結束時沒有 traceback：VLM runner 上的 Qwen3.5 家族、純文字 `mlx-lm` 模型（快速路徑、工具與 schema）、Gemma-4（工具與圖像）、OCR、ASR、TTS、Qwen3-Omni 與圖像生成 |
| `soak` | 27B 模型在八個請求同時進行下完成成對的 MMLU-Pro，零錯誤，且準確度沒有明顯低於已記錄的基線；接著進行貼近真實的混合浸泡測試，零錯誤且正確率高。每一部分結束後，行程的記憶體占用必須回到起點附近數 GiB 之內 |
| `agent-sessions` | 長時間代理流量會做的事，每項檢查都在各自乾淨啟動的伺服器上執行。約 50K token、Claude Code 風格的 `POST /v1/messages` 迴圈，每一輪都必須產生有效的工具呼叫、找回所有 needle，並且每輪都從快取重用前一個提示詞的絕大部分。長文件、短問題、工具呼叫與 JSON schema 答案分別單獨與同時執行，同時執行的每個輸出都必須等於它單獨執行的輸出。閒置一段時間（釋放記憶體）後，以及在同一個 SSD 快取層上重新啟動後，相同請求會回傳相同文字，且提示詞的大部分來自快取。伺服器的貪婪文字等於同一檢查點上的原生 `mlx-lm` 或 `mlx-vlm` |
| `long` | 在 32K、64K 與 128K 執行[驗證](/docs/developers/verification)的 `long` suite，並以前一個版本為參考：token 相同（包含長回覆的草擬開啟與關閉）、前綴快取相等、速度、記憶體、相對於原生的 needle 檢索，以及並行長請求。結論必須存在且每個規劃的階段都要通過；缺少格子、階段沒有執行、基礎設施錯誤，或超過門檻的退步都會讓關卡失敗 |
| `service` | 預設關閉，因為它會載入真實的 launchd agent。啟用後，`service install` 必須能提供模型服務，`service uninstall` 必須釋放連接埠 |

需要模型的階段透過 `scripts/dev/yv gate` 執行，它把各階段當作獨立的工作執行，並記住哪些階段已在該 commit 上通過，所以較晚的失敗之後重跑時會略過已通過的階段（`--fresh` 重跑全部；`--stages` 選擇部分階段）。請不要直接呼叫底層腳本：保存成功階段證據的是 `yv`。

```bash
scripts/dev/yv gate                                   # 所有階段
scripts/dev/yv gate --stages install,serve-27b        # 指定階段
```

檢查本身位於 `scripts/release/gate_checks.py`。模型路徑來自環境變數（`scripts/release/local.env.example` 列出變數名稱）。當基線合理地改變時，例如新的預設 kernel 讓某個準確度分數改變，腳本中的基線常數會連同支持這項改變的量測一起更新。

## 發布一個版本

版本號放在 `pyproject.toml`，每次發布都需要一筆標有日期的 `CHANGELOG.md` 條目。所有驗證都針對最終的那個 commit；之後再有任何改動，就需要重新檢查。

1. 用 `scripts/dev/ci-local <sha>` 在本機執行等同 CI 的檢查：lint、格式、mypy、前端檢查、單元測試、套件建置、`twine` 驗證與 wheel 安裝冒煙測試。
2. 在同一個 commit 上執行完整關卡與其他發版檢查。需要模型的代理基準測試另外收集，僅供參考，不會阻擋發版。
3. 為 commit 打上 tag（`v<version>`）並推送。發版工作流程會檢查 tag 與 `pyproject.toml` 及 changelog 一致，在 Apple Silicon runner 上執行 lint、型別檢查、控制台建置與單元測試，建置 sdist 與 wheel，執行 `twine check`，把 wheel 安裝到乾淨環境，等待維護者在 `pypi` environment 核准，以 trusted publishing 發布到 PyPI（不儲存任何 token），並開啟一個草稿 GitHub release 供審閱。

如果在發布步驟之前失敗，就沒有發布任何東西：刪除 tag、修正問題後重新打 tag。版本號以小步前進；patch 帶來修正與改進，minor 代表真正的能力躍進。完整流程見儲存庫中的 `RELEASING.md`。

## 發版就緒清單

就緒清單涵蓋新使用者在第一個 token 之前會遇到的事。它是能力清單，而不是測試結果：它說明有哪些東西存在，而證明某個 commit 的是上面的關卡。

| 範圍 | 使用者可以期待什麼 | 狀態 |
|---|---|---|
| 安裝 | 從 PyPI、wheel 或 git 執行 `uv tool install "yunshu[vision]"`；以 `uv sync` 從原始碼安裝 | <Support status="supported">支援</Support> |
| 安裝 | 透過共用的 `YuhuanStudio/homebrew-tap` formula 使用 Homebrew | <Support status="partial">在每次 PyPI 發布之後才加入</Support> |
| 安裝 | macOS 應用程式、選單列程式、DMG | <Support status="unsupported">不在規劃中：以 CLI 加 launchd 服務為主</Support> |
| 首次執行 | `yunshu doctor` 檢查平台、Rosetta、macOS、Python、MLX 與 Metal、`mlx-lm` 與 `mlx-vlm`、記憶體、設定、模型目錄與磁碟、模型是否放得下、連接埠與服務，並為每個問題提供修正方式 | <Support status="supported">支援</Support> |
| 首次執行 | `yunshu pull org/name` 下載到 `~/.yunshu/models`，可續傳中斷的下載，並拒絕重新下載已在磁碟上的模型（模型目錄或 Hugging Face 快取） | <Support status="supported">支援</Support> |
| 首次執行 | 依可用 RAM 的精選模型選擇器 | <Support status="planned">規劃中：目前使用者需要自己知道儲存庫 id</Support> |
| 服務 | `yunshu serve -m <model>` 或 `--models-dir`；預設安全綁定 `127.0.0.1`，網路綁定但沒有 token 時會警告 | <Support status="supported">支援</Support> |
| 服務 | 預檢通過後模型載入失敗時，伺服器保持運作，`GET /health/ready` 回傳 503 並寫出 fatal 日誌 | <Support status="supported">刻意如此，讓背景服務能回報狀態</Support> |
| 服務 | 背景服務：`yunshu service install`、`start`、`stop`、`restart`、`status`、`logs`、`rotate-logs`（launchd、當機自動重啟、依大小與時間輪替日誌） | <Support status="supported">支援</Support> |
| 維運 | `GET /health`、`GET /health/ready`、`GET /health/live`、`GET /version`、`GET /metrics` 與 `yunshu status` | <Support status="supported">支援</Support> |
| 設定 | 單一入口：註冊表、`~/.yunshu/config.toml`、`--set` 與 `yunshu config`，以及自動產生的參考文件 | <Support status="supported">支援</Support> |
| 用戶端 | OpenAI SDK、curl 與 Anthropic SDK；以 `yunshu launch` 支援 Claude Code、Codex、opencode 與 Pi | <Support status="supported">支援</Support> |
| 用戶端 | Cline、Continue、Open WebUI | <Support status="partial">設定指引；並非每個版本都測試</Support> |
| 升級 | `uv tool upgrade yunshu`；執行中的服務需要 `yunshu service restart` | <Support status="supported">支援</Support> |
| 遙測 | 不蒐集任何資料。只有在使用者操作時才會對外連線：模型下載、你設定的 MCP 伺服器、已設定的網路搜尋來源，以及請求指定 URL 的 `web_fetch` | <Support status="supported">刻意如此</Support> |
| CI | 每次 push 執行 lint 與建置；macOS 單元測試套件在發版或手動觸發時執行 | <Support status="partial">並非每次 push 都跑完整單元測試</Support> |

這些項目面向使用者的部分，請見[程式代理與 SDK](/docs/guides/agents)、[網路搜尋與擷取](/docs/guides/web-search) 與[背景服務指南](/docs/getting-started/service)。

## 相關頁面

- [驗證](/docs/developers/verification)
- [貢獻指南](/docs/developers/contributing)
- [上游追蹤](/docs/developers/upstream-tracking)
- [安裝](/docs/getting-started/install)


---

<!-- developers/release-readiness -->
---
title: 發版就緒
description: 發版的對外檢查清單、哪些是證據而哪些只是能力清單，以及整理自 RELEASING.md 的維護者流程。
---

本頁寫給維護者。它涵蓋新使用者在第一個 token 之前會遇到的事（安裝、首次執行、服務、用戶端、升級、解除安裝）、每一項有什麼證據，以及發版流程的順序。清單表格本身與各項的支援狀態在[發版關卡](/docs/developers/release-gate)，本頁不重複。

## 它做什麼

就緒清單是能力清單，不是測試結果。它說明有哪些東西存在。證明某個 commit 的是發版關卡（`scripts/dev/yv gate`），證明打包沒問題的是 `scripts/dev/ci-local`。引擎的速度與準確度另外記錄在[基準測試](/docs/guides/benchmarks)與[準確度對齊](/docs/developers/accuracy)。

| 範圍 | 證據來源 |
|---|---|
| 從 wheel 安裝、`doctor`、`pull`、`model list`、`config set models_dir`、`service install --dry-run` | 關卡階段 `install` |
| 服務、SDK 用戶端、旗艦模型 | 關卡階段 `serve-27b` |
| 支援的模型家族 | 關卡階段 `families` |
| 記憶體回收與無錯誤的浸泡測試 | 關卡階段 `soak` |
| 長時間的 agent 流量、閒置釋放、SSD 快取層上的重新啟動 | 關卡階段 `agent-sessions` |
| 長上下文一致性、快取內容一致、速度、記憶體 | 關卡階段 `long` |
| 真實的 launchd 服務 | 關卡階段 `service`（預設關閉） |
| 套件建置、lint、型別、單元測試、乾淨安裝 | `scripts/dev/ci-local`，接著是發版工作流程 |
| Claude Code、Codex、opencode 的行為 | `scripts/dev/agentcompat`，見[Agent 相容性](/docs/developers/agent-compat) |
| M3 可攜性 | `scripts/dev/m3sweep` |

## 為什麼這樣設計

- 版本號以小步前進：patch 帶來修正與改進，minor 代表真正的能力躍進。
- 儲存庫是公開的，安裝路徑是 CLI 加上 launchd 服務。不規劃 macOS 應用程式。Homebrew 走共用的 tap `YuhuanStudio/homebrew-tap`。
- 模型預設放在 `~/.yunshu/models`；Hugging Face 快取中的模型可直接使用，位置可用 `yunshu config set models_dir` 變更。
- 預檢通過後模型載入失敗時，伺服器保持運作但處於未就緒狀態（`GET /health/ready` 回傳 503 並寫出 fatal 日誌），這對背景服務是正確的。
- 不收集任何遙測。只有在使用者操作時才會對外連線。
- 除了由維護者執行下列步驟之外，不會發布任何東西。

## 保證

- 所有驗證都針對最終的發版 commit；之後再有改動，就需要重新檢查。
- 已經上到 PyPI 的版本不能重新上傳；以下一個 patch 版本向前修正。如果在發布步驟之前失敗，就沒有發布任何東西：刪除 tag、修正後重新打 tag。
- 1.0 之前也不代表可以悄悄破壞相容性。使用者可見的移除，或 API、預設值的變更，需要升級說明，指出替代方案與影響；穩定的設定與 CLI 選項應先給警告，並至少保留一個已發布版本的重疊期，除非安全或正確性要求立即移除。Python 內部介面不是穩定的嵌入 API。
- 發版說明依固定順序：一段說明使用者獲得什麼，接著是 `Highlights`、`Upgrade notes / breaking changes`、`Performance`（機器、檢查點、工作負載、前後對照、來源連結），然後是 `Added`、`Changed`、`Fixed`、`Security`，以及比較頁尾。每個量測數字都連到有日期的基準測試。

## 流程

<Steps>
<Step>

### 一次性設定

在 pypi.org 為專案 `yunshu` 新增 trusted publisher（owner `YuhuanStudio`、repository `Yunshu`、workflow `release.yml`、environment `pypi`）；不儲存任何 API token。在儲存庫設定中建立 GitHub environment `pypi` 並指定必要的審核者，讓每次發布都要等待核准。

</Step>
<Step>

### 準備 commit

兩次發版之間，`main` 以 PEP 440 開發版本號（例如 `0.1.6.dev0`）承載下一個版本。在 `pyproject.toml` 中去掉 `.devN` 後綴，加入標有日期的 `CHANGELOG.md` 條目後提交。打完 tag 之後，把 `main` 設為下一個 `.dev0`。

</Step>
<Step>

### 驗證確切的 commit

```bash
nice -n 15 scripts/dev/ci-local main
scripts/dev/yv gate --priority -1 --stages install,serve-27b,families,agent-sessions
# final release: CI, gate, M3 sweep, agent compatibility and agentbench together
scripts/dev/release_check main --label-prefix <prefix>
scripts/dev/release_check main --dry-run     # preview only: no CI, no GPU jobs
```

`release_check` 把以 SHA 為鍵的證據保存在 `/Volumes/P5Plus/yunshu-build/release-check/`，固定使用乾淨的工作樹，並印出 agentbench 的收集指令。CI、關卡、M3 sweep 與代理相容性會阻擋發版；agentbench 以優先權 -3 執行，僅供參考，但其結果仍必須收集並記錄。絕不要直接執行 `gate.sh`：`yv gate` 透過 GPU 佇列提交並保存成功階段的證據，所以重跑會略過已通過的部分。請檢查每個已完成工作的結束狀態與最終的證據紀錄。

</Step>
<Step>

### 打 tag 並推送

```bash
git tag -a v<version> -m "Yunshu <version>"
git push origin main v<version>
```

發版工作流程會檢查 tag 與 `pyproject.toml` 及 changelog 一致，在 Apple Silicon runner 上執行 ruff、mypy、控制台檢查與單元測試，建置 sdist 與 wheel，執行 `twine check`，把 wheel 安裝到乾淨的工具環境，等待 `pypi` environment 的核准，發布到 PyPI，並開啟一個以 changelog 段落作為說明的草稿 GitHub release。請審閱並發布這份草稿。

</Step>
<Step>

### 發版之後

檢查乾淨安裝（`uv tool install "yunshu[vision]"`，然後 `yunshu doctor`）。更新共用 tap 中的 Homebrew formula：填入 PyPI 目前提供的 sdist 的 `sha256`，再把 `packaging/homebrew/yunshu.rb` 複製到 `Formula/yunshu.rb`。

接著從目前的上游開始下一個週期：`uv lock --upgrade`，然後執行測試與 lint；在 27B 上重新確認推測解碼的輸出與一般解碼相同、成對的準確度測試集差異在一題以內，以及解碼與 TTFT 沒有退步（把前後數字記錄在 `docs/reports/PERF_TREND.md`）；執行 `just vendor-check`，並審閱每一個上游已有變動的 vendored kernel、移植檔案或 monkeypatch（見[上游追蹤](/docs/developers/upstream-tracking)）；閱讀上游的發版說明，找出修正與想法。把這次同步作為獨立的合併，之後出現退步時才能用二分法定位到它。

</Step>
</Steps>

## 設定

| 選項 | 預設值 | 效果 |
|---|---|---|
| `yv gate --stages` | 所有階段 | 執行選定的關卡階段；`--fresh` 重跑全部 |
| `yv gate --priority` | 依指令而定 | 關卡工作的 GPU 佇列優先權 |
| `release_check --label-prefix` | `releng015-release` | 為提交的工作加上標籤 |
| `release_check --dry-run` | off | 預覽，不執行 CI 或 GPU 工作 |

## 限制

- push 時的 CI 在 Linux 上執行 lint 與建置；macOS 單元測試在發版或手動執行時才跑，所以清單不宣稱有一次最新的 CI 執行。
- 依可用 RAM 的精選模型選擇器尚未存在；使用者需要自己知道儲存庫 id。
- Cline、Continue 與 Open WebUI 是設定指引，並非每個版本都測試。
- 僅用 CPU 的文件候選版本可以使用 `yv ab --suite preflight`；它不會認證引擎的輸出或效能。

## 如何驗證

預覽發版時會發布的說明，並檢查公開文件：

```bash
uv run pytest tests/unit/test_public_docs.py tests/unit/test_release_notes.py -q
uv run python scripts/release/notes.py <version> --output /path/to/review-notes.md
```

`scripts/release/notes.py` 會加入固定版本的 pip 與 uv 指令、附有 tap 延遲說明的 Homebrew 指示，以及與前一版的比較。打 tag 之前，審閱 `git log <previous-tag>..main`，把數字與 `docs/reports/PERF_TREND.md` 核對，註明機器、檢查點、模式與重複次數，納入工作負載的退步，並解決每一個 TODO。

## 相關頁面

- [發版關卡](/docs/developers/release-gate)
- [驗證](/docs/developers/verification)
- [Agent 相容性](/docs/developers/agent-compat)
- [安裝](/docs/getting-started/install)


---

<!-- developers/roadmap -->
---
title: 路線圖與提案
description: Yunshu 的優先事項、不在範圍內的項目，以及重大變更使用的輕量 RFC 流程。
---

Yunshu 優先處理 Apple Silicon 上快速的本機 LLM 與 VLM 推論：解碼速度、冷啟動與命中快取時的首 token 延遲、前綴重用，以及完整的用戶端行為。Qwen3.8-27B 是第一個調校完成的模型。本頁記錄的是方向，不含日期，也不代表相關工作已經上線。已發行的行為屬於 changelog；實測結果屬於[效能基準](/docs/guides/benchmarks)。

## 優先事項

| 優先權 | 工作 | 完成證據 |
|---|---|---|
| 現在 | 縮小 27B 與 Flash-Next 已實測到的長 context 差距 | 在 32K、64K 與 128K 分別比較冷、暖與後續請求的首 token 時間及解碼；目前的差距見[效能基準](/docs/guides/benchmarks) |
| 下一步 | Apple Silicon 可攜性證據 | 記錄 M1 到 M5 與 macOS 的檢查，區分通過、失敗與未測試的組合 |
| 下一步 | 模型與用戶端能力證據 | 針對特定 checkpoint 與用戶端版本的結果；不支援的功能會回傳可操作的錯誤訊息 |
| 下一步 | 可重現的效能數據發布 | 同一 checkpoint 的冷、暖與第二回合執行，附正確性檢查與原始收據連結 |
| 之後 | 更廣泛的模型調校 | 在不降低輸出正確性的前提下，取得實測的端到端收益 |

音訊、語音、圖像與影片生成，以及 embeddings 仍是支援的能力。共用路徑上的退步，以及明確列為優先的工作，會優先處理。分散式服務與多租戶基礎設施不在範圍內。

## 輕量 RFC 流程

例行修正走一般的貢獻與審查流程（見[貢獻指南](/docs/developers/contributing)）。對於公開 API、設定、快取格式、支援硬體或架構的重大變更，實作前請先記錄提案，內容包含：

- 使用者的問題與具體提議的行為；
- 範圍、替代方案與選擇的理由；
- 相容性、遷移、隱私與失敗時的行為；
- 正確性檢查、決定成敗的量測方式，以及回滾計畫；
- 負責人、狀態（proposed、accepted、implemented 或 superseded）與決定的理由。

可使用既有的討論，或可供審查的 Markdown 提案；小修正不需要另開 issue。維護者在審查提案的地方記錄決定。Accepted 不代表已上線：請附上實作與驗證的連結，再關閉提案。涉及安全漏洞的細節請依 `SECURITY.md` 私下回報，不要寫在公開提案中。

## 決策與維護

貢獻者要對自己變更的品質與說明負責。維護者審查範圍、相容性與證據；儲存庫管理員控制合併、發行與存取權限。審查者應指出尚未解決的異議，並記錄最後選擇的取捨。治理方面的變更需要明確的維護者審查；本頁不授予儲存庫權限，也不建立新的角色。


---

<!-- developers/round-driver -->
---
title: Round driver
description: "服務所有 mlx-vlm 模型的 packed-row 引擎：每一步對所有解碼中的 row 做一次 forward、row 不變的運算，以及同時為多個 row 做成本感知的 MTP 或 DFlash 草稿。"
---

Round driver（`python/yunshu_engine/round_driver/`）是所有經由 `mlx-vlm` 載入的模型的服務路徑。每個請求都是一個 row，driver 透過三種模型層服務這些 row：packed Qwen3.5 層（dense 與 MoE 的 Qwen3.5 系列模型）、packed Flash-Next 層（Qwen4），以及 generic 層（每個 row 直接使用模型自己的 upstream forward，預設不做草稿），供其他所有模型家族與 Apple Paravirtual Metal 使用。推測解碼跑在 packed 層上：並行請求也能做草稿（MTP 鏈，或共用公平 32 節點驗證預算的 DFlash2 草稿）。設定 `YUNSHU_VLM_DRAFT=off` 時，driver 仍服務所有請求，只是不做草稿；推測開啟與關閉的輸出逐 token 相同。本頁是維護者參考；其他服務路徑請見[架構](/docs/developers/architecture)。

## 它做什麼

每個請求都是一個 **row**。row 先在自己的單 row 快取上 prefill（每個 attention 層一個 `KVCache`、每個 GatedDeltaNet 層一個 `ArraysCache`、MTP head 一個 `KVCache`）。prompt 處理完後加入解碼 batch（`round_driver/batch.py` 的 `DecodeBatch`），所有解碼中的 row 共用 slot 緩衝區：

- 每個 attention 層的 K/V 放在 slot 緩衝區，每個 row 擁有一個 slot，容量以 512 個 key 為單位增長；
- GDN 狀態與 conv 視窗是每層的 batch 陣列（加入時串接，結束時取出）；
- MTP head 的 KV 放在同類的 slot 緩衝區。

`RoundDriver`（`driver.py`）以**步（step）**推進各 row，每一步是一種 forward：

- **解碼步**：每個解碼中 row 的視窗（待處理 token 加上 `d >= 0` 個草稿），右側補齊到最長視窗。norm、投影與 MLP 在 packed 的 row 上執行；attention 用一次 scatter 寫入所有 row 的 key，再用一次 ragged-attention launch 讀取（`kernels/ragged_attention.py`）；GDN 的 conv 與遞迴各是一次 batch launch（`kernels/gdn_rows.py`）。
- **Prefill 步**：等待中 prompt 的固定大小 **atom**（`vlm_engine.py` 中的 `ROUND_PREFILL_CHUNK`，512 token；Flash-Next 為 2048），從 prompt 起點對齊網格，在 prompt 的 checkpoint 與結尾處切開。有 row 在解碼時一次一個 atom；沒有 row 解碼時可把連續的完整 atom 一起執行。

當有 row 在解碼且有 prompt 在等待時，prefill 步與解碼步一對一交替。每一步只做一種工作：在 Qwen3.8-27B 上，把解碼 row 併入 prefill forward，並不比相同 chunk 大小下的交替執行更好（2026-09-29）。

圖說：一個 row 從進入到結束的流程；解碼步與其他 row 的 prefill 步交替進行。

```mermaid
flowchart LR
  A["request becomes a row"] --> B["prefill atoms on its own caches"]
  B --> C["join decode batch"]
  C --> D["decode step: packed windows"]
  D --> E["host walks acceptance, commits kept tokens"]
  E --> F["MTP head draft with cost-aware depth"]
  F --> D
  D --> G["row finishes and leaves the batch"]
```

### 路由

`VLMEngine._build_batch_runner` 在模型載入時選擇模型層：

- **Apple Paravirtual Metal**：generic 層，不使用 APC，也不做推測。
- **Qwen3.5 系列或 Qwen4 模型**（`_SPEC_MODEL_TYPES`），且 packed 層支援其語言模型（`_round_driver_wanted`）：使用 packed Qwen3.5 層，Qwen4 則使用 Flash-Next 層。量化的 Qwen3.5 checkpoint 若 lane 運算自我測試失敗，則改用 generic 層。
- **其他所有模型**：generic 層，每個 row 一次 upstream 呼叫，一般解碼。只有請求帶 `spec_decode: true`，或設定 `YUNSHU_NGRAM_DEFAULT=1` 開啟 n-gram，generic row 才會做草稿。設定了草稿 LM（`YUNSHU_DRAFT_MODEL`）或 Gemma-4 assistant（`YUNSHU_GEMMA4_ASSISTANT`）時使用它們，否則使用 n-gram。

草稿另外選擇（`spec_select.choose`）。`YUNSHU_VLM_DRAFT=off` 不做草稿；指定 DFlash 草稿模型目錄或 `mtp` 則選用該路徑；未設定時，若找到相符的 DFlash2 草稿模型就使用它，否則使用 checkpoint 的 MTP head。`YUNSHU_MTP=0` 會關閉 MTP head。

所有請求（文字或多媒體）都是同一個 driver 的 row。多媒體 prompt 攜帶自己的 prompt features（packed 層為 `VLMBatchRunner._media_request`，generic 層為 `_generic_request`）。row 只有在其 processor 允許時才會做草稿（見下文）。

## 為什麼

Upstream `mlx-vlm` 的 `BatchGenerator` 一次只跑一個 prompt batch，推測 batch 不能接受新加入的 row，且 MTP drafter 狀態只對應一個 batch。在 27B（M5 Max）上的量測：

- MMLU-Pro 300 b8（長推理，8 個並行）：Yunshu 139 tok/s（只在請求獨自執行時做草稿）、TensorFold MTP parallel-8 159、Splash 223。
- 8 個並行 1K prompt：最後一個的 TTFT 約 10 秒（prefill 一次只處理一個請求）。

這些數字來自先前的原始共用 batch 路徑，保留作為 driver 的設計動機。

Driver 是 Yunshu 自己的迴圈（參考 TensorFold 的 lane engine，MIT；見[上游追蹤](/docs/developers/upstream-tracking)），讓多個 row 能共用一次 forward、在任何一步加入，並仍產生與單獨執行時相同的 token。早期原型量測顯示，先前的原始路徑在並行長推理負載下落後競爭對手；這個 driver 的最新跨引擎比較（Yunshu 0.1.7.dev0，2026-11-04 至 2026-11-08）見[效能基準](/docs/guides/benchmarks)，上文數字來自先前的原始路徑。

## 保證

row 的運算不取決於哪些 row 共用該步、其他 row 驗證多少草稿，或它自己是否做草稿。

- **投影**（所有目標線性層與 LM head）使用 lane matmul（`kernels/tensorfold/lane_qmm.py`，MIT）：1 到 128 個 row 時，每個 row 的位元只取決於權重形狀而非 row 數；更寬的呼叫會切成 128-row 的片段（`kernels/lane_linear.py`）。
- **解碼與驗證 attention**（`T <= 8` 個 token）使用 ragged token-tile kernel：每個 token 的位元不取決於 `T` 或其他 row。
- **GDN** 以一次 launch 處理所有 row 的狀態；只保留視窗一部分的 row 會從保存的中間狀態繼續（`DecodeBatch.commit`）。
- **Prefill** 遵循只由 prompt 決定的 atom 計畫，因此重複的 prompt，或從網格上 checkpoint 還原的 row，會用與冷執行相同的 atom 做 prefill：APC 命中與未命中逐 token 相同。
- **貪婪 row**：開啟與關閉推測的結果相同，單獨執行的 row 與在任何 batch 或加入順序下的同一個 row 結果也相同。**取樣 row** 使用 `keyed_sampling.KeyedSampler`（種子與生成索引），所以索引 `g` 的 token 是該 row 的 logits、種子與 `g` 的純函式。
- **generic 層**：每個解碼中的 row 每輪對 upstream 做一次自己的呼叫，使用自己的快取，所以一個 row 的輸出不取決於其他 row：單獨執行與並行執行相同，貪婪與 seeded 皆然。

在 packed 層上，草稿使用 checkpoint 的 MTP head（或選定時的 DFlash2 草稿模型），對每個可做草稿的 row 都適用。head 的 KV 每一步都會更新，所以任何 row 在任何一步都能開始做草稿。每個 row 的草稿深度來自 `round_driver/allocate.py`（TensorFold 的分配規則，MIT）：以 EMA 追蹤每個深度的接受率，依邊際期望 token 數貪婪地分配草稿，並選擇每毫秒期望提交 token 數最大的分配，forward 成本是在執行中線上量測的。不使用以 row 數為準的門檻。

每個模型都使用 `APCManager` 前綴快取，透過 `APCCoordinator`（checkpoint 策略），適用於所有沒有 sliding-window 快取的模型家族。項目以模型與 processor 的身分做鹽值（`VLMBatchRunner._driver_extra_hash`），因此在一種身分下快取的前綴，對另一種身分來說是冷的。

## 設定

| 設定 | 預設 | 效果 |
|---|---|---|
| `YUNSHU_KV_PRECISION` | `bf16` | `int8` 作用於 packed Qwen3.5 層的 row；Flash-Next 與 generic 層維持 bf16 |
| `YUNSHU_MTP` | `true` | 使用 checkpoint 的 MTP head 做草稿；`false` 會關閉該草稿 |
| `YUNSHU_VLM_DRAFT` | 未設定 | `off` 關閉草稿；指定草稿模型目錄或 `mtp` 則選用該草稿（見路由） |

## 限制

- XTC 取樣的 row 從不做草稿。含有可視窗化集合之外的 logits processor 的 row（純 token mask 與 logit bias、repetition penalty、至多一個 frequency 或 presence penalty）每輪只解碼一個 token。logprobs 的 row，以及受 invariant 工具呼叫或 response-format guide 約束的 row 會做草稿；其他約束的 row 每輪只解碼一個 token，且從不做草稿。
- packed 層無法攜帶的 prompt feature 會在加入時拋出錯誤（`VLMBatchRunner._media_request`）。
- 待辦：每個 row 每輪約 25 ms 的成本（草稿、驗證、抽樣）使四 row 的 seeded 解碼僅與先前的共用 batch 持平。

## 如何驗證

- `tests/unit/test_round_driver.py`（隨機小型 Qwen3.5 上的貪婪不變性）、`tests/unit/test_round_driver_apc.py`（命中等於未命中）、`tests/unit/test_round_driver_routing.py`（模型層與草稿路由），以及 `tests/unit/test_round_driver_generic.py`（generic 層）。
- `scripts/research/sweep_round_driver.py` 在真實 checkpoint 上（單獨、batch、錯開加入與自迴歸的一致性），以及 `scripts/research/probe_span_bits.py`（不同 prefill 區段大小下隱藏狀態與快取相同）。這些需要 GPU 佇列；見[驗證](/docs/developers/verification)。


---

<!-- developers/serve-and-develop -->
---
title: 在同一台機器上服務與開發
description: GPU 佇列如何讓正式的 Yunshu 伺服器與開發用 GPU 工作共用同一台 Mac，包含閒置閘門、搶佔、記憶體與 CPU 准入，以及量測完整性規則。
---

GPU 佇列（`scripts/dev/gpuq`）支援在同一台機器上，一邊為真實使用者運行正式的 Yunshu 伺服器，一邊讓開發用的 GPU 工作（基準測試、評測）使用它。佇列能感知正式伺服器：開發工作只在伺服器閒置時執行，使用者流量一到就立刻凍結。本頁寫給維護者；它說明佇列，以及佇列所依賴的引擎端掛鉤。

## 它做什麼

工作是提交給佇列常駐程式的獨立行程。每個工作會經過常駐程式在 `gpuq status` 中回報的各個狀態：

說明：一個受閘門控制的工作從等待伺服器閒置到完成的過程，以及使用者流量到達時走的暫停路徑。

```mermaid
stateDiagram-v2
    [*] --> pending
    pending --> wait_idle: serving not idle yet
    pending --> wait_mem: memory not admitted
    pending --> wait_cpu: quiet CPU needed
    wait_idle --> running: idle for idle_start_s
    wait_mem --> running
    wait_cpu --> running
    running --> paused: request arrives (SIGSTOP)
    paused --> running: idle for idle_resume_s (SIGCONT)
    running --> done
    running --> failed
```

| 元件 | 行為 |
|---|---|
| 輪詢器 | 常駐程式每隔 `poll_s` 對每個已設定伺服器的 `/v1/yunshu/status` 發出 GET，只讀取 `requests.active` 與 `requests.queued`。不含提示詞，也不含請求項目 |
| 啟動閘門 | 只有在每個伺服器都已閒置（沒有執行中、沒有排隊）達 `idle_start_s` 之後，工作才會啟動 |
| 搶佔 | 請求出現時，`SIGSTOP` 只送給該工作自己的行程群組（佇列讓每個工作在自己的 session 中啟動；絕不對其他東西發送訊號，更不會發給伺服器） |
| 恢復 | 伺服器閒置達 `idle_resume_s` 之後送出 `SIGCONT` |
| 暫停紀錄 | 每段區間都存在工作 JSON 中（`pauses: [[t0, t1], ...]`，牆上時鐘），也寫入 `$GPUQ_PAUSE_FILE` 指定的檔案 |
| 逾時 | `--timeout` 與 `--stall` 只計算活動時間；暫停的時間不算 |
| 記憶體准入 | 工作宣告 `--mem-gb`（搭配 `--serving-ok` 時為 0）。只有可用記憶體減去 `mem_gb` 後仍保留 `reserve_gb`，才會啟動 |
| 繞過 | `--serving-ok` 略過閒置閘門與服務暫停（用於僅 CPU 的工作）。優先權搶佔仍然適用 |
| 優先權搶佔 | 優先權 0 或更高的待處理工作，在記憶體容得下兩個常駐工作時，可以對執行中、優先權 -1 或更低的工作送出 `SIGSTOP`；不會為了回收記憶體而殺掉任何工作 |
| 狀態 | `gpuq status` 顯示 `wait-idle`、`wait-mem`、`wait-cpu`、`paused` 與 `pauses=N` 計數；`idle:` 一行說明為什麼待處理工作沒有任何執行中的工作 |

## 為什麼這樣設計

- 正式伺服器絕不能被基準測試拖慢，基準測試也絕不能悄悄量到使用者流量。因此佇列暫停的是工作而不是伺服器，並記錄這次暫停。
- 輪詢只讀計數器，所以任何使用者內容都不會到達佇列。
- 它以失敗關閉為原則：無法連線的伺服器（連線被拒）視為閒置，但逾時、5xx 或無法解析的回應視為忙碌。

## 保證

- 沒有設定伺服器 URL 或明確的保留量時，就沒有服務閘門，記憶體准入為循序，也沒有服務暫停。
- 優先權搶佔仍會檢查記憶體：實測可用記憶體減去新工作的 `mem_gb` 後，必須保留 `reserve_gb`。記憶體未知就不能搶佔，被擋住的高優先權工作會顯示為 `wait-mem`。
- 作用中的標籤（待處理、執行中或已暫停）是獨佔的；同一個標籤不能同時提交兩次。提交絕不會刪除先前的日誌、暫停紀錄、回傳碼或輸出檔案。

### 量測完整性

包含暫停時間的基準測試數字，量到的是使用者的流量，不是引擎，所以測試工具絕不能回報這樣的樣本。

- `scripts/dev/gpuq_pause.py`（僅用標準函式庫）提供 `was_paused(t0, t1)`、`timed(fn)` 與 `pause_intervals()`。`timed` 會丟棄並重跑與暫停重疊的樣本，重複重疊後拋出 `PausedSampleError`。它以失敗關閉為原則：無法讀取的 `$GPUQ_PAUSE_FILE` 視為已暫停；在 gpuq 之外，該變數未設定，也絕不會暫停。
- 已接入 `scripts/research/agentic/replay_traffic.py`、`scripts/research/bench_engine_matrix.py`，以及發版關卡的 `cancel_then_next` 牆鐘時間檢查。離線即時 A/B 重播（`scripts/servedev/replay.py` 的 `ab()`）同樣會從兩個 arm 中丟棄時間視窗與暫停重疊的配對，回報 `paused_pairs_dropped`，並且在沒有乾淨配對剩下時以失敗關閉的方式結束。新的基準測試腳本必須把每個計時樣本包在 `timed(...)` 中。準確度評測不需要：暫停只會讓它們變慢。
- 搶佔會在第一個請求之後的一個輪詢間隔內生效，所以樣本可能在停止之前短暫與請求共用 GPU。請讓 `poll_s` 保持很小。關閉這個空窗的握手機制見下文。

### 外部 CPU 與記憶體污染

每個已啟動的工作都會在開始時、定期，以及結束時記錄 `cpu_samples`（`load_1m`、`load_5m`、`foreign_cpu_pct` 與最大的外部行程）。外部 CPU 包含除了該工作自己的行程樹，以及 `nice` 為 10 或以上的背景行程之外的所有行程。達到門檻或取樣失敗時，工作會被標記為 `contended`。

- 以 `--quiet` 提交的工作會在啟動前等待 CPU 安靜（`--quiet-window`、`--quiet-max-wait`；環境變數預設值 `GPUQ_CPU_THRESHOLD`、`GPUQ_QUIET_WINDOW_S`、`GPUQ_QUIET_MAX_WAIT_S`、`GPUQ_CPU_SAMPLE_S`）。等待時間以該工作的最長等待與 `GPUQ_QUIET_HOLD_MAX_S`（常駐程式環境變數，預設 300 秒）中較小者為限；到期時工作會啟動並標記為 `quiet_timeout` 與 `contended`。服務與記憶體准入仍然適用，`--serving-ok` 不會繞過 CPU 閘門。
- 記憶體污染規則會在以下情況拒絕工作：其行程樹的壓縮或交換記憶體太多（`GPUQ_SWAP_MB`）、工作期間主機的 swap-in 太大（`GPUQ_HOST_SWAP_MB`），或主機的空閒加非活躍記憶體低於下限（`GPUQ_MEMORY_FLOOR_MB`）。無法讀取的證據以失敗關閉處理。工作 JSON 會記錄 `host_swap_mb`、`job_swap_mb`、`available_min_mb`、`memory_processes` 與 `memory_policy_version`。
- 對於其他方面成功、但受污染的效能或安靜工作，`gpuq wait` 回傳 3。`scripts/dev/gpuq_contention.py:was_contended()` 讓測試工具讀取該旗標；發版關卡在有限的安靜等待之後，會把受污染的伺服器路徑比較重試一次，兩次都受污染就回報為 contended（關卡結束碼 3），而文字或推測解碼的輸出不一致仍然算失敗。
- 僅 CPU 的測試套件與建置在 `nice -n 15` 下執行，所以不計入外部 CPU 監控。請不要在單元測試加入 `taskpolicy -b`：效率核心排程可能破壞對時間敏感的檢查。

## 設定

服務閘門的設定存在於常駐程式環境變數，或 `$GPUQ_DIR/serving.json`；後者每個迴圈都會重新讀取，所以可以即時編輯：

```json
{"urls": ["http://127.0.0.1:8000"], "idle_start_s": 120, "idle_resume_s": 30,
 "poll_s": 1, "reserve_gb": 16, "api_key": "optional bearer if the server needs one"}
```

| 設定 | 預設值 | 效果 |
|---|---|---|
| `GPUQ_SERVING_URLS`（`urls`） | none | 要輪詢的伺服器，以逗號分隔；沒有設定表示沒有服務閘門 |
| `GPUQ_IDLE_START_S`（`idle_start_s`） | 120 | 工作可以啟動之前所需的閒置時間 |
| `GPUQ_IDLE_RESUME_S`（`idle_resume_s`） | 30 | 已暫停的工作恢復之前所需的閒置時間 |
| `GPUQ_SERVING_POLL_S`（`poll_s`） | 1 | 輪詢間隔（秒） |
| `GPUQ_RESERVE_GB`（`reserve_gb`） | 16 | 准入工作後保持空閒的記憶體 |
| `GPUQ_SERVING_KEY`（`api_key`） | none | 伺服器需要時使用的 Bearer token |
| `GPUQ_SHORT_MIN`、`GPUQ_SHORT_WAIT_S`、`GPUQ_SHORT_SHARE` | 10 min、5 min、0.15 | 短工作通道的限制 |
| `GPUQ_FILLER_WAIT_S`、`GPUQ_FILLER_MAX_MIN` | 30 s、30 min | 佇列頭部被 CPU 安靜條件擋住時，填補工作的限制 |
| `YUNSHU_SERVE_LOG` | off | 僅含數字的事件日誌（時間、token 數、快取層、推測解碼接受率、並行度、arm、build）；絕不含提示詞、輸出或 token id。`YUNSHU_SERVE_LOG_DIR`、`YUNSHU_SERVE_LOG_MAX_MB` 與 `YUNSHU_SERVE_LOG_KEEP` 控制位置與輪替 |
| `YUNSHU_RESEARCH_ACTIVITY_FILE` | unset | 本機暫停握手檔案；也要在 `serving.json` 中將它設為 `activity_files` |
| `YUNSHU_RESEARCH_PAUSE_TIMEOUT_S` | 2.0 | 准入前等待 gpuq 確認的最長時間；逾時回傳 503 |
| `YUNSHU_ARM` | unset | 在日誌中標記手動選擇的設定，不改變行為 |

伺服器在 `/v1/yunshu/status` 中回報累計的 GPU 忙碌秒數，在 `/metrics` 中回報 `yunshu_gpu_busy_seconds_total`。這些是忙碌時間計數器，不是硬體使用率的取樣。

### 共同服務握手

設定 `YUNSHU_RESEARCH_ACTIVITY_FILE` 後，伺服器會寫出一個僅含數字的活動檔案，並在推論之前，最多等待 `YUNSHU_RESEARCH_PAUSE_TIMEOUT_S`，等 gpuq 給出新的確認，表示每個研究行程都已被觀察到停止。這關閉了輪詢間隔造成的空窗，否則第一個請求可能與計時樣本共用 GPU。

### 提交工作

```bash
scripts/dev/gpuq submit --label eval --mem-gb 30 -- python bench.py      # gated, preemptible
scripts/dev/gpuq submit --label lint --serving-ok -- python cpu_job.py   # bypasses the gate
scripts/dev/gpuq submit --label x-smoke --timeout 5 -- python smoke.py   # short lane
scripts/dev/gpuq submit --quiet --priority -1 --quiet-window 20 \
  --quiet-max-wait 300 --label cpu-quiet-unique -- python bench.py
scripts/dev/gpuq submit --label eval-unique --out results/a.jsonl --expect-complete -- python sweep.py
scripts/dev/gpuq wait --max-seconds 45 JOB_ID OTHER_JOB_ID
scripts/dev/gpuq digest --label-prefix eval- --since 6h
```

- 佇列層級的 `--out` 參數放在 `--` 分隔符之前。`--expect-complete` 要求每個輸出都是非空檔案，且其中有一行是字面值 `complete`。
- `wait` 對整個 id 清單使用同一個期限，並且每個工作印出一行。結束碼 0：每個工作都已完成且 rc 為 0，輸出經過驗證。結束碼 1：有工作失敗、被取消、不存在，或輸出無效。結束碼 2：期限到時仍有工作處於待處理或執行中（優先於已結束同伴的失敗）。結束碼 3：成功但受污染的效能或安靜工作。
- `gpuq digest`（`scripts/dev/gpuq_digest.py`）列出自上次摘要以來結束的工作，依標籤家族分組；只要有任何工作以 `failed`、`lost`、`stalled`、`timeout` 或 `cancelled` 結束、rc 缺失或不為零，或輸出缺失或為空，就以 1 結束。`--peek` 不動標記（`$GPUQ_DIR/.digest_marker`），`--since` 絕不移動它，帶標籤篩選的摘要也絕不移動全域標記。協調者在每次檢查時執行它，並處理每一行被標示的項目。
- 短工作通道：`--timeout` 不超過 10 分鐘，或以 `--short` 提交的工作，在等待 5 分鐘之後，可以排在長工作之前執行，但受長工作時間滾動佔比的限制，且不會連續兩次。超過逾時的短工作會被殺掉並標記為 `timeout`。
- 開發工作的優先權為非正數；`--gate` 讓一個關卡排在同優先權待辦事項之前。計時格需要安靜准入；正確性格不需要。

### 重新載入常駐程式

常駐程式在啟動時載入它的 Python 程式碼。佇列變更合併之後，請暫停接受新的提交，並在工作邊界重新啟動常駐程式；執行中與已暫停的工作會在重啟時被接管。只終止持有 `daemon.lock` 的行程（以 PID，絕不用行程群組），並用 `/usr/bin/python3` 啟動替代者：

```bash
export GPUQ_DIR=/Volumes/P5Plus/yunshu-gpuq
scripts/dev/gpuq status
GPUQ_DAEMON_PID="$(lsof -t "$GPUQ_DIR/daemon.lock")"
ps -p "$GPUQ_DAEMON_PID" -o pid=,command=   # must be gpuq.py _daemon
kill -TERM "$GPUQ_DAEMON_PID"
while kill -0 "$GPUQ_DAEMON_PID" 2>/dev/null; do sleep 1; done
nohup /usr/bin/python3 scripts/dev/gpuq.py _daemon >> "$GPUQ_DIR/daemon.log" 2>&1 < /dev/null &
scripts/dev/gpuq status
```

只有佇列擁有者做這件事；worker 絕不在量測期間重新啟動正在運作的常駐程式。

### 選用的 M3 正確性通道

`gpuq submit --device m5|m3|any` 預設為 `m5`。一個常駐程式同時執行本機 M5 槽位與遠端 M3 槽位；`any` 由先准入它的槽位保留一次。本機服務、安靜准入與優先權搶佔都適用於 M5 槽位，而 `--quiet` 與 `m3`、`any` 並用時會被拒絕，因為計時屬於 M5。`M3_HOST`、`M3_KEY` 與 `M3_REPO` 的設定方式與 `scripts/dev/m3run` 相同；所有 worktree、輸出、模型、快取與暫存檔都留在那個 checkout 內，因為 M3 是一台個人筆電。筆電只會在固定上限內准入宣告的記憶體，該上限為使用者保留了容量，所以請宣告實際的峰值。

遠端快照是 HEAD 加上已追蹤的修改，位於一個 detached worktree。即使命令失敗，宣告的輸出也會回到原本的路徑。SSH 或傳輸失敗就是失敗的工作，絕不是成功的收據；如果無法確認遠端清理，`m3-quarantine.json` 會阻擋後續的 M3 派送，直到有人檢查。M3 摘要條目標示為可攜性證據（不是 M5），混合裝置的準確度或一致性 arm 與 M3 效能結論，會被研究分析輔助工具拒絕。M3 上的失敗必須在 M5 重現後，才能否決 M5 的最佳化；M3 通過絕不會核准 M5 熱路徑的預設值。

## 限制

上述的引擎端元件都已實作。`scripts/servedev/` 中的離線腳本有 `replay.py`（僅形狀的重播 A/B，token 相同否則失敗）、`bandit.py`（對已註冊的無損調整項目進行 UCB1 bandit，帶有可逆的帳本）以及 `loop.py`（有閘門的候選迴圈）；沒有任何一個會根據即時流量選擇 arm。離線的 switchback、CUPED 與 mSPRT 輔助工具，以及執行歷史的變異數剖析都已存在；沒有啟用任何線上 arm 選擇。

已規劃但尚未實作：

- 在即時流量上進行線上無損 A/B，只記錄指標（不含提示詞）；
- 依據這些指標，對無損調整項目進行 bandit 自動調校；
- 有閘門的自主改進迴圈，只透過現有的關卡來提出、量測並落地變更。

要在開發的同時常駐提供 27B 服務，仍須先在長上下文上追平：冷、暖與後續 TTFT、解碼、並行與記憶體都要達標。佇列機制已經實作；這並不表示效能關卡已通過。定時抽樣無法觀察到兩次輪詢之間所有短命的行程，佇列也不暗示任何每秒 token 數或 TTFT 的提升。

## 如何驗證

```bash
scripts/dev/gpuq status          # states, pauses, idle explanation
scripts/dev/gpuq digest --peek   # finished jobs, flagged failures
```

佇列行為由 `tests/unit` 下的 gpuq 測試涵蓋；在正式常駐程式重新啟動之前，請先在隔離的佇列中跨優先權測試佇列變更。基準測試腳本只有在把每個計時樣本包進 `scripts/dev/gpuq_pause.py` 的 `timed(...)` 時才正確。另見[驗證](/docs/developers/verification)、[發版就緒](/docs/developers/release-readiness)與[Agentic 程式開發基準](/docs/developers/agentic-bench)。

## 相關頁面

- [驗證](/docs/developers/verification)
- [硬體驗證](/docs/developers/hardware-validation)
- [遙測](/docs/guides/telemetry)


---

<!-- developers/upstream-tracking -->
---
title: 上游追蹤
description: Yunshu 如何在 vendor.json 記錄取自其他專案的程式碼、四種上游依賴類型，以及 just vendor-check 如何回報上游的變動。
---

Yunshu 建立在 MLX、`mlx-lm`、`mlx-vlm` 與其他數個開源專案的想法之上。每一處複製、改寫、重新實作或 monkeypatch 上游程式碼的地方，都記錄在 `vendor.json` 中，讓上游的變動與修正可以被追蹤，授權也得到遵守。`THIRD_PARTY_NOTICES.md` 附有對應的授權全文，並隨 wheel 與 sdist 一起發布。

## 四種類型

每個項目都列出上游的 `repo`、`clone`（`reference/` 底下的 checkout，該目錄不納入 git）、`commit`（本地程式碼所依據的上游 commit 或發行 tag）、`license`，以及本地的 `path`。

| 類型 | 意義 | 如何同步 |
|---|---|---|
| `vendored` | 從上游複製的檔案。`local_changes` 列出刻意做的修改 | 重新複製該檔案，再套用 `local_changes` |
| `derived` | 依據特定上游檔案（`upstream_paths`）改寫 | 閱讀上游差異，移植重要的部分 |
| `inspired` | 相同的演算法或設計，但是獨立撰寫的程式碼 | 閱讀上游差異，尋找想法或錯誤修正 |
| `patches` | 對上游符號的 monkeypatch，以 `module`、`symbol`、`signature` 與 `source_sha256` 描述 | 對照新的上游原始碼，重新檢查我們的替代實作 |

屬於這些類型的每個原始碼檔案，開頭都有一行 `# Upstream (kind): repo (license) paths @ commit` 註解（patch 使用 `# Patches upstream ...`）。下面說明的自我檢查，會在有這種標頭卻沒有對應清單項目時失敗。

清單中除了這四種類型之外，還有其他區段：

- `watch`：為了想法或修正而追蹤的參考 clone，附上重要的檔案 glob 與已審閱到的 commit。
- `watch_excluded`：`reference/` 底下所有其他 clone，並說明為何不追蹤。
- `packages`：在 `pyproject.toml` 宣告之外額外的套件版本。
- `prior_art` 與其他 `*_prior_art` 清單：僅供探索的候選項目，各有自己的授權與版本。它們是關於其他地方有什麼的筆記，不是已採用的程式碼、合格的載入器，也不代表通過了對照檢驗。

## 執行檢查

```bash
just vendor-check                                          # 先抓取 clone，再回報
uv run python scripts/vendor/check_upstream.py --no-fetch  # 離線：依已有的 clone 回報
```

報告包含這些區段：被 patch 的符號、vendored 檔案、derived 項目、inspired 項目、被監看的路徑、套件，以及自我檢查。

| 結束碼 | 意義 |
|---|---|
| `0` | 一切正常 |
| `1` | 有項目落後上游（被追蹤的路徑有新 commit，或套件有新版） |
| `2` | 被 patch 的符號已改變或不存在，或自我檢查失敗 |

### 監看的內容

- **被 patch 的符號**會從已安裝的套件計算雜湊（正規化後的 AST 原始碼）。出現 `UPSTREAM SOURCE CHANGED` 表示我們替代實作所包裝或複製的程式碼已改變。請閱讀新的原始碼，修改 `python/yunshu_engine/` 中的替代實作，執行測試與對照檢查，然後記錄新的雜湊：

  ```bash
  uv run python scripts/vendor/check_upstream.py --update-hashes
  ```

- **被監看的儲存庫**會列出自上次審閱的 commit 起，動到設定 glob 的上游 commit，以及上游新增且符合 glob 的檔案。固定到已安裝套件的儲存庫，會與該發行版的 tag 比較。讀完報告後，請把 `commit` 往前移。
- **套件**從 `pyproject.toml` 讀取（基本相依、每個 extra 與每個 dependency group）。報告顯示已安裝的版本、PyPI 上的最新版本與宣告的版本限制，因此新的相依不會被漏掉。
- **自我檢查**：`python/` 底下的檔案，若開頭幾行寫著 `# Upstream`，或「ported from」「adapted from」「studied from」「Inspired by」，就必須出現在 `vendor.json` 中。`reference/` 底下既不在 `watch`、也不在 `watch_excluded` 的 clone 同樣會失敗，所以新的 clone 不可能沒被分類。

## 同步 derived 或 inspired 項目

1. `just vendor-check` 會列出自該項目上次審閱的 commit（第一次審閱前則為 `commit`）以來，其路徑上的上游 commit。
2. 閱讀它們，例如用 `git -C reference/<clone> show <sha>`，並移植適用的部分。
3. 重新複製檔案時，把 `commit` 設為新的上游來源。若刻意保留本地實作，請保持 `commit` 作為其來源紀錄，並加上 `reviewed_commit`、`reviewed_date` 與 `review_reason`，說明哪些上游變動已經涵蓋、不適用，或需要自己的正確性與效能關卡。下一次檢查仍會回報該次審閱之後的變動，而本地的差異永遠與最初複製的來源比較。

涉及 kernel 或解碼路徑的移植，遵循一貫的證據規則：在同一個檢查點上比較輸出（完全相同或在容差內），並量測端到端的效果，見[驗證](/docs/developers/verification)。

## 新增一筆

1. 把項目加進 `vendor.json` 中正確的清單。若是 patch，執行 `--update-hashes` 來記錄雜湊。
2. 讓原始碼檔案以 `# Upstream (kind): repo (license) paths @ commit` 註解開頭。
3. 把上游的授權加進 `THIRD_PARTY_NOTICES.md`。
4. 若缺少 clone，請把儲存庫 clone 到 `reference/<name>`（`reference/` 不納入 git）。

## 第三方聲明

`THIRD_PARTY_NOTICES.md` 摘要列出每個上游、其授權，以及 Yunshu 如何使用它（vendored kernel、derived 模組、inspired 程式碼、patch），接著附上各授權全文。上游包括 `mlx`、`mlx-lm` 與 `mlx-vlm`（MIT）、oMLX、vLLM、sglang 等 Apache-2.0 專案，以及 llama.cpp（MIT）。當你加入對他人程式碼的依賴時，聲明檔案是同一次改動的一部分，而不是之後再補。

## 相關頁面

- [架構](/docs/developers/architecture)
- [驗證](/docs/developers/verification)
- [貢獻指南](/docs/developers/contributing)


---

<!-- developers/verification -->
---
title: 驗證
description: Yunshu 如何用 yv 驗證工具確認一項最佳化是無損且沒有變慢，以及如何與原生 MLX 比較準確度。
---

Yunshu 只接受有證據的最佳化：輸出必須相同（或在明確說明的容差內）、新路徑必須確實有執行，而且量測到的效果必須是真的。本頁說明產生這些證據的工具與其採用的規則，對象是修改解碼、預填、快取或排程路徑的貢獻者。

## 必須成立的條件

| 要求 | 意義 |
|---|---|
| **Token 完全相同** | 無損的改動不會改變貪婪輸出：在同一個檢查點上，候選版本產生的 token 與基準 commit 相同。對推測解碼而言，開啟草擬的輸出必須等於關閉草擬的輸出 |
| **確實啟用** | 新路徑必須被證明有在執行（計數器、日誌或回應欄位），不能只是假設。兩次其實都走舊路徑的比較什麼也證明不了 |
| **快取精確** | 由前綴快取服務的請求必須等於同一請求冷啟動的結果，並且要回報 `cached_tokens > 0` |
| **無退步** | 解碼速度、首 token 延遲與記憶體不得在量測雜訊之外變差 |
| **失敗即關閉（fail closed）** | 沒有證據就不算通過。不完整的執行、遺失的結果或提早結束的工作都是失敗，絕不當作略過 |

有損的選項（KV int8、權重量化，以及任何改變輸出品質的做法）是預設為無損的使用者設定，不會因為基準測試而被採用。見[貢獻指南](/docs/developers/contributing)。

## `yv` 工具

`scripts/dev/yv` 會對候選改動執行標準驗證並回傳單一結論。請用它，不要自己寫一次性的量測腳本。它會為兩個比較對象各建一棵固定版本的樹、依序執行各階段、在第一個失敗處停止、記住已完成的部分，並寫出 `verdict.json` 與 `verdict.md`。

```bash
scripts/dev/yv ab --base <base-sha> --cand <candidate-sha> --suite decode --label my-change
scripts/dev/yv ab --base <base-sha> --cand <candidate-sha> --suite prefill \
  --cand-env YUNSHU_VLM_DRAFT=mtp --label my-change-mtp --detach
scripts/dev/yv status <run>      # 查看某次執行的狀態
scripts/dev/yv wait <run>        # 阻塞直到有結論
scripts/dev/yv suites            # 列出 suite
scripts/dev/yv gate              # 發版關卡，逐階段保存結果
```

結束碼 `0` 表示所有階段通過，`1` 表示有階段失敗，`2` 表示基礎設施錯誤（工具、git 或參數不一致）。`yv ab` 會阻塞到完成；`--detach` 則立即返回。

### 比較對象（arm）

為了得到可審查的結論，請把兩邊都提交，並傳入完整的 commit SHA，讓基準與候選是兩個明確、有名稱的狀態。`--base` 與 `--cand` 也接受 checkout 目錄；未提交的改動會被雜湊進 arm 的鍵，所以重新續跑時不會把同一棵樹的兩種狀態混在一起。兩邊使用同一個直譯器。`--env K=V` 同時套用於兩邊，`--cand-env` 只套用於候選，`--base-env` 只套用於基準。`--model` 指定檢查點。

### 階段

階段依下列順序執行，並在第一個失敗處停止（除非該 suite 被標記為繼續執行）。

| 階段 | 做什麼 | 通過條件 |
|---|---|---|
| `preflight` | 僅用 CPU。兩棵樹都能 import，並執行與差異相關的單元測試 | import 成功、測試通過 |
| `smoke` | 兩邊都能啟動服務並回答。`--engaged SPEC` 證明候選路徑有執行：`log:REGEX`（候選伺服器日誌）、`field:KEY=REGEX`（`x_yunshu` 回應欄位）或 `spec:MODE`（使用中的推測模式） | 能回答，且每個 `--engaged` 都符合 |
| `identity` | 在每個 suite 的 context 長度下，對固定的程式碼與散文提示詞做貪婪解碼（冷啟動、暖快取、後續回合）；對文字、推理內容、工具呼叫、結束原因與 token 數計算摘要。加上 `--spec-off` 時，關閉草擬的候選也必須等於開啟草擬的候選 | 每個格子都相等 |
| `apc` | 暖請求（由前綴快取服務）必須等於冷請求，並回報 `cached_tokens > 0`。沒有前綴快取的路徑使用 `--no-apc-hit-required` | 命中等於未命中 |
| `quality` | 200 題成對的 MMLU-Pro，基準與候選交錯執行 | 兩邊所有題目都有評分，且答對題數的差距在一題以內 |
| `speed` | 解碼 tok/s、冷啟動 TTFT 與後續 TTFT，多次重複，依基準、候選、基準、候選交錯。回報中位數、成對差異與雜訊估計 | 沒有任何中位數的惡化超過 2% 與實測雜訊兩者中較大者（`--speed-tol`）；受干擾的重複會重跑一次 |
| `memory` | 峰值記憶體、閒置後的記憶體，以及短暫後續請求後仍保留的記憶體 | 沒有任何指標比基準多出超過 3% 加 0.25 GiB |
| `longqa` | 在 32K、64K 與 128K 提示詞中放入確定性的 key-value needle，各問一個貪婪問題 | 答對數與基準相差在一以內 |
| `conc` | 兩個並行請求，每個都是暖的 32K 前綴加新文字 | TTFT 與每個請求的解碼速度在基準的 10% 以內 |

`--spec-modes default,mtp,dflash` 會對每種推測方法各重複一次 identity 階段。

### Suite

| Suite | 階段與 context |
|---|---|
| `decode` | preflight、smoke、identity、apc、speed，1K 與 8K |
| `prefill` | 再加上 quality，最長到 32K |
| `scheduler` | preflight、smoke、identity、apc、quality、speed，1K 與 8K |
| `memory` | preflight、smoke、identity、memory |
| `quick` | 快速迭代用的階梯；合併前請執行 `full` |
| `full` | 所有階段，1K、8K 與 32K |
| `long` | 32K、64K 與 128K 的格子，回覆 2048 token：identity（含草擬開啟與關閉）、apc、speed、memory、longqa 與 conc；即使有階段失敗，每個階段仍會執行 |
| `longtrend` | 主要長格子各跑一次，用於比較不同版本 |
| `tiny` | 在小模型上執行所有階段，用來試跑工具本身 |

像 `--suite smoke,identity,speed` 這樣的臨時階梯會保持標準的階段順序。可覆寫的選項：`--ctx`、`--reps`、`--mmlu-n`、`--mem-sizes`、`--mem-reps`、`--speed-tol` 與 `--spec-off`。

### 續跑與結論

每個階段在進行時就會寫下證據。只有當某個格子的工作乾淨結束，且紀錄以 `complete: true` 結尾時，證據才算數；提早結束的工作不留下證據，該階段就失敗。重新執行同一個指令即可續跑：已完成的格子會被重用（結論中會標示），失敗只會損失進行中的那個格子。在既有的 label 下更改基準、候選、環境、suite 或模型會被拒絕，請改用新的 label。

`verdict.json` 包含 label、兩邊的 commit、環境、suite、模型、整體結果、失敗的階段，以及各階段的狀態、原因與數字。`verdict.md` 是給人閱讀的摘要。

## 與原生 MLX 比較準確度

與同一檢查點上的原生 MLX 或 `mlx-vlm` 是否等價，分三個層級檢查，由最便宜、最敏感的開始。300 題的基準測試約有 13 題的 95% 雜訊，單靠它看不出細微的數值漂移。

| 層級 | 比較對象 | 敏感於 |
|---|---|---|
| 1 | 固定文字上的下一個 token 分布（teacher forcing）：KL divergence 與 top-1 一致率 | 非常小的數值漂移 |
| 2 | 50 個固定提示詞、最多 256 token 的貪婪續寫 | 第一個不同的 token |
| 3 | 成對的下游評測（GSM8K、IFEval、MMLU-Pro、needle 檢索、工具呼叫），逐題配對，使用 McNemar 檢定與信賴區間 | 任務層級的差異 |

參考基準永遠是同一檢查點上、未載入任何 Yunshu kernel 的原生 `mlx-vlm`，而且執行時會斷言這一點。候選版本是與「原生 MLX 對自己」的差異相比：重複執行是位元精確的，所以任何非零差異都是真實的路徑差異；但只要更改批次大小或預填區塊大小，平均 KL divergence 就已經會移動約 1e-3 到 3e-3，top-1 一致率降到約 98.8%。這就是數值上合理實作的尺度。

第 1 層的通過條件：

- 平均 KL divergence 不超過原生對原生基準線的兩倍，中位數與第 99 百分位數也一樣；
- top-1 一致率至少 98.4%；
- perplexity 變化不超過 0.5%；
- 硬性條件：使用推測解碼時，多 token 的驗證區塊必須與單 token 解碼位元相同，因此草擬開啟等於草擬關閉。

第 2 層：草擬開啟與關閉時，50 個提示詞必須完全相同，且與參考基準的吻合數不得低於同一檢查點已記錄的基線。

第 3 層以帶區間的成對差異回報，等價的路徑在約 200 到 300 題的成對集合上必須在一題以內一致。不會為每次改動都重跑完整基準測試。

## 驗證代理與 API 行為

用戶端依賴的行為是以官方工具驗證，而不是假設：

- 單元測試（`tests/unit`）涵蓋請求與回應的形狀，其中一個測試會把已安裝的 `openai` 與 `anthropic` SDK 型別的每個請求參數與請求模型比對，所以新的 SDK 欄位若既不支援也沒有列為忽略，CI 就會失敗。
- 路由覆蓋測試：當應用程式註冊了某個路由，卻沒有任何檢查或經審查的豁免提到它時就會失敗。
- 發版關卡會用官方 SDK 透過 HTTP 驅動已安裝的建置版本；見[發版關卡](/docs/developers/release-gate)。

## 相關頁面

- [發版關卡](/docs/developers/release-gate)
- [貢獻指南](/docs/developers/contributing)
- [架構](/docs/developers/architecture)


---

<!-- getting-started/console -->
---
title: 主控台
description: Yunshu 服務內建的網頁主控台：觀察引擎、管理模型與金鑰、閱讀日誌、試用 API，並閱讀這份文件。
---

主控台是由它自己的輕量程序（`yunshu console`，連接埠 8100）提供的網頁應用，與引擎分開執行。這個程序提供主控台與這份文件、把主控台的 API 呼叫轉送給引擎，並記錄歷史，所以引擎重新啟動或當機時，主控台仍可使用、仍持續記錄。它是觀察單一引擎的視窗：即時狀態、請求、模型、快取、日誌、API 金鑰、設定與這份文件。它不負責啟動引擎，也不是聊天產品。

<Callout type="info">
主控台支援繁體中文、簡體中文與英文，預設跟隨瀏覽器語言，選擇會保存在瀏覽器；可從上方列的語言按鈕切換。這份文件也跟隨同一個選擇。
</Callout>

## 開啟主控台

照常啟動服務：`yunshu serve` 會在引擎旁邊啟動主控台程序。在瀏覽器開啟主控台連接埠的 `/console/`，預設是 `http://127.0.0.1:8100/console/`（引擎維持 8000）。`--no-console` 可略過、`--console-port` 可更換連接埠，`yunshu console --engine http://host:8000` 可單獨執行，例如監看另一台機器上的引擎。`yunshu service install` 會把它安裝成獨立的 launchd job，引擎重新啟動期間它仍持續服務與記錄。舊的 `http://127.0.0.1:8000/console/` 在一個版本內仍可使用，會導向主控台程序。

靜態頁面是公開的，這樣你才能在瀏覽器輸入權杖。主控台發出的每個 API 呼叫仍遵守一般驗證規則：預設的本機服務不需要權杖就能讀取狀態、歷史、請求、模型與快取檢視；管理頁面（API 金鑰、日誌、服務、CORS）需要管理員權杖，缺少時會顯示提示並連到設定。請在「設定」輸入 `YUNSHU_AUTH_TOKEN` 或管理員金鑰；預設只保存在頁面記憶體，重新整理後即清除。

若 `/console/` 回應 404 並顯示「Yunshu Console is not built」，表示已安裝的套件不含主控台建置，API 不受影響。從原始碼執行時，以 Node.js 22.18 以上與 pnpm 建置：

```bash
cd frontend
pnpm install --frozen-lockfile
pnpm build
```

建置結果寫入 `python/yunshu_gateway/console_static`，由主控台程序提供。

## 頁面

側邊欄有六區：總覽、請求、診斷、模型、推理測試與設定。日誌在診斷分頁；下載與快取在模型分頁；金鑰與 API 存取在設定分頁。文件從頂端列開啟，原有分頁網址仍有效。

| 頁面 | 功能 |
|---|---|
| 引擎總覽 | 即時引擎狀態：階段（排隊、預填、解碼）、吞吐量、記憶體、快取與進行中請求。請求執行時每秒更新約四次，閒置時放慢。 |
| 請求與效能 | 進行中與已結束的請求，含各階段時間軸、token 與快取細節、篩選、CSV 匯出與單筆取消。 |
| 日誌 | 伺服器日誌環，可依等級與文字篩選並即時追尾。 |
| 引擎診斷 | 健康檢查、主機讀數、支援包預覽與原始診斷資料。 |
| 模型庫 | 已載入與可用的模型及記憶體數字；載入、卸載、預熱、容量檢查與閒置保留。 |
| 下載 | 從 Hugging Face 下載模型，附進度、磁碟空間檢查與取消。 |
| 快取 | 前綴快取各層（記憶體、暖層、SSD）的項目、生命週期事件與清除操作。 |
| 推理測試 | 串流對話，含生成設定、工具、圖片、token 信心與產生程式碼片段。 |
| API 接入 | 你的服務連線片段，以及它註冊的路由目錄。 |
| 文件 | 這些頁面，可從命令面板搜尋。 |
| 金鑰 | 具名 API 金鑰：權限範圍、到期時間、滾動日配額與各金鑰用量。 |
| 設定 | 服務位址與權杖、主題與語言、每個引擎設定及其來源、CORS 與服務重新啟動。 |

## 歷史，以及引擎離線時

主控台程序每秒讀取一次引擎，把歷史保存在 `~/.yunshu/console-history.sqlite`：最近一小時 1 秒解析度、24 小時 10 秒、30 天 1 分鐘，另有已結束請求的紀錄（只有數字，從不保存提示詞或輸出）。開啟時，圖表（15 分鐘到 30 天）與請求列表會先從這裡回補，再接上即時資料。引擎連不上的期間不會記錄，所以那一段會顯示為缺口與事件（「引擎無法連線」「引擎恢復連線」「引擎重新啟動」「模型載入失敗」），絕不會畫一條線穿過去。

引擎沒有回應時，主控台會顯示「引擎自 18:02:11 離線，4 秒後重試」並持續重試（退避到約十秒，回到分頁或網路恢復時立即重試）。顯示引擎資料的頁面保留最後的資料，變暗並標示為過期；文件與設定不受影響。引擎在線但模型載入失敗時，頁面顯示錯誤，「載入模型」仍可使用。單一頁面出錯不會讓整個主控台當機。

## 狀態與狀態列

桌面頁面底部獨立的浮動狀態膠囊顯示引擎狀態、已載入模型與記憶體。點它（手機上是精簡膠囊）會展開狀態島：即時階段、吞吐量、各擁有者的記憶體與主機資訊。伺服器沒有回報的值顯示為無法取得，而不是 0。

更新失敗時，主控台保留上一次的數字並註明；連不上引擎時會顯示離線橫幅，附「重試」與「連線設定」。

## 命令面板

按 `⌘K`（其他系統為 `Ctrl K`）開啟命令面板：可跳到頁面、執行載入模型或清除快取等動作、切換語言，也能搜尋這份文件，輸入兩個字以上，符合的頁面與段落會列在「文件」之下。按 `?` 可看鍵盤快速鍵。

## 連線設定

預設情況下，主控台連到提供它的同一個來源。你可以在「設定」改指向另一台 Yunshu 服務；該服務必須透過 CORS 設定（`YUNSHU_CORS_ORIGINS`，有管理員權杖時可在設定頁編輯）允許主控台的來源。瀏覽器只保存服務位址、主題與語言；權杖只有在你要求時才保存。

## 通知

上方列的鈴鐺會開啟通知中心（通知）。它依時間由新到舊列出主控台在監看期間發生的變化，最多 50 筆；徽章顯示未讀數量，打開面板即標為已讀，「清除全部」會清空。每一列都連到能說明該事件的頁面。

| 事件 | 觸發時機 | 前往 |
|---|---|---|
| 模型已載入／模型載入失敗 | 兩次狀態讀取之間，模型的已載入或錯誤狀態改變 | 模型 |
| 下載完成／下載失敗 | 排隊中或進行中的下載結束 | 下載 |
| 引擎無法連線／引擎已恢復連線 | 引擎停止或恢復回應 | 診斷／總覽 |
| 引擎已重新啟動 | 回報的運作時間倒退 | 診斷 |
| 記憶體壓力偏高 | Metal 使用中記憶體達統一記憶體的 80%；回落 5 個百分點後解除 | 模型 |
| 伺服器錯誤增加 | 一分鐘內出現 3 個以上 5xx 回應；每 5 分鐘最多一次 | 請求 |

只有警告與錯誤會另外跳出提示訊息，其餘靜靜留在通知中心。開啟頁面後的第一次讀取不會產生任何通知，開啟前已完成的下載也不會被通知。

<Callout type="info">
這些事件是瀏覽器根據主控台本來就在讀的狀態、請求與下載資料推算出來的。它們依伺服器位址存放在 `sessionStorage`，重新整理分頁後仍在，但開新分頁就不會，也不會傳給伺服器。這與主控台程序記錄的歷史及其引擎事件是兩回事。
</Callout>

## 記憶體帳本

記憶體帳本回答「統一記憶體被誰佔用」。資料來自引擎的 `/v1/yunshu/memory`（需要推論權限），頁面可見時主控台每隔數秒重新讀取。它出現在三個地方：

- **模型**：某個模型的詳細資料中的「記憶體持有者」。
- **狀態島**：Metal 記憶體區塊（連同 Swap、記憶體壓力與保留池）。
- **快取**：前綴快取的佔用量會標示「來自記憶體帳本」。

表格（持有者、大小、可回收）列出模型權重、前綴快取（記憶體）、前綴快取（暖層）、進行中請求的 KV、記憶體保留池與其他，並以一條對照 Metal 記憶體的長條呈現。標記線顯示自伺服器啟動以來的峰值、Metal 建議上限與 wired 上限。

- 伺服器沒有計數器的大小會顯示「未知」，而不是 0；估算值會標示「估算」。
- 各持有者加總超過 Metal 使用中記憶體時，「其他」顯示 0，並說明超出的量。
- 沒有此路由的引擎會顯示「此引擎版本沒有提供記憶體持有者明細」，並停止輪詢。

各持有者如何計算，請見[記憶體管理](/docs/internals/memory)。

## 推測解碼與階段延遲

兩個面板都在「請求」頁，讀取引擎的已完成請求紀錄（`/v1/yunshu/requests/recent`）。

**推測解碼**位於請求列表下方。它先說明最近已完成的請求中有多少回報了推測解碼，再依「模式」分組，顯示請求數、接受率（已接受 token 總數除以草稿 token 總數，只計入兩個計數器都有回報的請求）、接受／草稿 token 與輪數；複製草稿（copy-draft）回合會另外標出。沒有推測解碼紀錄的請求視為一般解碼，有模式但沒有計數器的請求則不納入比率。引擎目前只回報每個請求的總數，所以沒有逐深度圖表。第二個區塊「引擎累計計數器」（模型、MTP 週期、接受、拒絕、自適應草稿）讀自 `/debug/spec-decode`，涵蓋引擎啟動以來的全部；若 `/debug` 關閉，會說明引擎未提供。

**階段延遲**是請求瀑布圖，顯示在單一請求的詳細資料中。階段有模型租用、閘道准入、引擎排隊、模板與分詞、前綴快取還原、預填、首個解碼與首次送出，時間零點是閘道收到請求的時刻。

<Callout type="warn">
引擎沒有觀測到的階段會列在「未回報」，絕不畫成 0。預填結束是主機端回呼的邊界，不是 GPU 剖析；模板與分詞包含媒體前處理；首次送出是伺服器送完資料，不代表用戶端已收到。由頁面根據狀態輪詢組出、沒有引擎紀錄的列沒有瀑布圖，較舊的引擎則會顯示「這個引擎還沒有提供階段延遲」。引擎有主機遙測時，詳細資料還會顯示預填與解碼區間的能耗估算，其中包含其他行程與閒置功耗。
</Callout>

## Realtime 連線健康

在「診斷」頁，「Realtime 連線」卡片（測試連線）檢查從這個瀏覽器到引擎 Realtime WebSocket（`/v1/realtime`，依頁面使用 `ws` 或 `wss`）的路徑。它只開啟一次連線並等待第一個事件，然後顯示建立連線、第一個事件、伺服器延遲與緩衝深度，並標明各項來自瀏覽器或伺服器。它不傳送音訊、不使用 GPU，所以證明的是連得到，而不是語音品質；引擎沒有回報的數值會省略，不會顯示成 0。請見 [Realtime API](/docs/api/realtime)。

## 工具測試與圖片辨識

兩者都從 Playground 工具列開啟，並使用該處選定的模型。

### 工具測試

「工具測試」開啟工具呼叫與結構化輸出測試。在「工具呼叫」分頁貼上 JSON 格式的工具定義（輸入時即時檢查：名稱為 1 到 64 個字母、數字、底線或連字號，`parameters` 為 object schema），輸入提示詞後按「送出第一輪」。每一輪都會顯示引擎是否呼叫了工具，以及引數是否為合法 JSON、是否指向你定義的工具、是否符合 schema。填入結果並按「送回結果並繼續」進入下一輪，直到輪數上限；「重新開始」會重置。在「結構化輸出」分頁提供 JSON schema 後送出，回覆會檢查是否為 JSON 並是否符合 schema。頁面只檢查 JSON Schema 的一個子集，並列出略過的關鍵字；回應也不會說明引擎是否用受限解碼強制執行 schema，這裡只檢查結果。請求會送到 `/v1/chat/completions`。請見[結構化輸出](/docs/guides/structured-output)。

### 圖片辨識

「圖片辨識」對話框接受 10 MB 以內的 PNG、JPG、WEBP、TIFF 或 BMP，送到 `/v1/ocr`，顯示辨識出的文字、模型與 token 用量。沒有任何已載入模型能回應時，按鈕停用並提示「沒有載入 OCR 或視覺模型，無法使用圖片辨識」；優先使用 OCR 類模型，否則用第一個已載入的視覺模型。圖片只送給引擎，不會被保留。引擎只回傳文字，所以不會在圖片上標出位置，也沒有信心數值。請見 [OCR API](/docs/api/ocr)。

## 引擎固定、自動探索與量測暫停

這些功能屬於主控台程序（`yunshu console`），請見[主控台程序](/docs/internals/console-process)。

- **自動探索。**`yunshu console --engine auto`（或 `YUNSHU_CONSOLE_ENGINE=auto`）讓同一個主控台在引擎重新啟動與換連接埠時保持開啟。每隔 `YUNSHU_CONSOLE_DISCOVER_S` 秒（預設 2）以 `/health` 探測候選連接埠；`YUNSHU_CONSOLE_DISCOVER_PORTS=all`（預設）會取這台 Mac 上所有正在監聽的 TCP 連接埠，也可以指定清單，例如 `8000,18990-18999`。只有回應方式像 Yunshu 引擎的連接埠才算數。它會留在目前跟隨的引擎上，連續兩次探測失敗後才改跟最近啟動的存活引擎。
- **固定。**狀態島會列出存活的引擎（引擎：連接埠、模型、運作時間）。「使用」會固定其中一個，只要它還活著就優先；「改為跟隨最新」則取消固定。也可透過主控台程序的 engines 路由操作（`/console/api/engines`，也可從 `/v1/yunshu/console/engines` 存取）。
- **等待。**沒有存活的引擎時，狀態島顯示「等待引擎啟動」，引擎一啟動主控台就會連上；短暫的中斷會以重新啟動的平靜樣式呈現，而不是當成故障。
- **量測暫停。**`YUNSHU_CONSOLE_PAUSE_FILE` 指定的檔案內容為 `{"pause": true, "until": ..., "reason": "..."}` 期間，主控台不輪詢也不探測任何引擎，監控就不會干擾計時實驗，狀態島會顯示「因量測暫停：原因」。你自己發出的請求仍會通過。暫停在 `until` 到期、`until` 為 null 時於檔案最後寫入兩小時後，或檔案被移除時結束。

<Callout type="info">
請求歷史會連同每個請求記下引擎 URL 與啟動時間，所以切換引擎會呈現為獨立的工作階段，並以 `engine_switched` 事件標示。
</Callout>

## 網路與 CORS

「設定」有一個「網路與 CORS」分頁，修改需要管理員權杖。

- **網路**是唯讀的：顯示主控台連線的位址，以及可連線範圍（僅本機或區域網路可連線）。它會顯示切換用的 `yunshu service install --force --host 127.0.0.1` 或 `--host 0.0.0.0` 指令，因為監聽位址要重新安裝服務才能變更。開放區域網路之前，請先設定 `YUNSHU_AUTH_TOKEN` 或建立 API 金鑰，並只允許你需要的來源。
- **CORS 來源**編輯哪些網站可以從瀏覽器呼叫這個伺服器。新增來源時寫成 `http://` 或 `https://` 加主機、不含路徑，或單獨一個 `*`；`*` 不能與其他來源並用，且需要明確確認，因為它會讓任何網站呼叫伺服器（不帶憑證）。頁面會說明這個主控台自己的來源是否被允許。儲存立即生效；「還原預設」會還原預設。
- 如果清單由 `YUNSHU_CORS_ORIGINS` 或命令列旗標設定，會優先於設定檔：編輯器會提示這點，編輯會被儲存，但不會改變正在執行的值。

完整的 CORS 規則請見[驗證、API 金鑰與 CORS](/docs/guides/auth-and-keys)。

## 主控台不做的事

- 它不是多使用者控制平面：金鑰的權限範圍與配額只針對這一台本機服務。
- 它不保存長期的對話歷史；推理測試的資料庫只存在你的瀏覽器。
- 請求檢視從不保存提示詞與回應，只有中繼資料。

## 相關頁面

- [快速開始](/docs/getting-started/quickstart)
- [設定](/docs/guides/configuration)
- [維運 API](/docs/api/operations)
- [模型 API](/docs/api/models)


---

<!-- getting-started/install -->
---
title: 安裝
description: 以 uv、pip 或 Homebrew 從 PyPI 安裝 Yunshu，並用 yunshu doctor 檢查安裝狀態。
---

## 系統需求

| 需求 | 說明 |
|---|---|
| 硬體 | 搭載 Apple Silicon（arm64）的 Mac。MLX 無法在 Intel Mac 或透過 Rosetta 執行的 Python 上運作。 |
| macOS | 14（Sonoma）或更新版本。版本較舊時 `yunshu doctor` 會判定為失敗。 |
| Python | 3.13 或更新版本。`uv tool install` 可以替你取得由 uv 管理的 3.13。 |
| 記憶體 | 統一記憶體需容納模型權重與 KV 快取。模型放不下時，`yunshu doctor -m <model>` 會發出警告。 |

## 以 uv 安裝（建議）

先安裝 [uv](https://docs.astral.sh/uv/getting-started/installation/)，再從 [PyPI](https://pypi.org/project/yunshu) 安裝套件：

```bash
uv tool install "yunshu[vision]" --python 3.13
yunshu --version
```

`vision` 額外套件會安裝 `mlx-vlm`。Qwen3.5 / 3.6 / 3.8 系列與所有視覺語言模型都需要它；這些模型的純文字請求也由它處理。不帶額外套件的基本安裝只能服務純文字的 `mlx-lm` 模型。

之後要升級：

```bash
uv tool upgrade yunshu
```

## 以 pip 安裝

```bash
python3.13 -m venv ~/yunshu-env
source ~/yunshu-env/bin/activate
pip install "yunshu[vision]"
```

## 以 Homebrew 安裝

Yunshu 發佈在共用的 tap `YuhuanStudio/homebrew-tap`：

```bash
brew install yuhuanstudio/tap/yunshu
```

這份 formula 會建立 Python 3.13 虛擬環境，並安裝帶有 `vision` 額外套件的 Yunshu。它需要 Apple Silicon 與 macOS Sonoma 或更新版本。formula 沒有定義 Homebrew service；若要在背景執行，請使用 [`yunshu service`](/docs/getting-started/service)，所有安裝方式都是同一套做法。

## 選用的額外套件

額外套件以名稱安裝，例如 `uv tool install "yunshu[vision,audio]" --python 3.13`。

| 額外套件 | 新增內容 | 用途 |
|---|---|---|
| `vision` | `mlx-vlm`、Pillow | Qwen3.5 / 3.6 / 3.8 與其他視覺語言模型、圖片與影片輸入 |
| `audio` | `mlx-audio` | 語音轉文字、文字轉語音，以及 Realtime 語音 WebSocket |
| `omni` | `mlx-vlm`、torch、torchvision、Pillow | 使用 Qwen3-Omni 的原生語音對語音 |
| `embeddings` | `mlx-embeddings` | `POST /v1/embeddings` |
| `generation` | diffusers、torch、torchvision、Pillow | 影像生成。未安裝時 `POST /v1/images/generations` 會回傳 503。 |
| `compression` | zstandard、lz4 | 前綴快取 SSD 層的選用壓縮編碼 |
| `webrtc` | aiortc | 以 WebRTC 使用 Realtime（`POST /v1/realtime/calls`） |
| `web-render` | playwright | 網頁擷取的瀏覽器渲染（需另外安裝瀏覽器） |
| `all` | `vision`、`audio`、`omni`、`embeddings`、`generation`、`compression` | 以上所有模態 |

## 檢查安裝

```bash
yunshu doctor
```

`yunshu doctor` 會檢查平台（Apple Silicon、macOS 版本、是否透過 Rosetta）、Python、MLX 與 Metal、記憶體、已安裝的套件版本與額外套件、你的設定、模型目錄與未完成的下載、可用磁碟空間、快取完整性、你打算使用的連接埠，以及是否已安裝登入服務。每個問題都會附上建議的修復方式。有問題導致無法啟動時，指令會以狀態碼 1 結束。

加上 `-m <model>` 可一併檢查模型（路徑或 Hugging Face repo id）是否存在、是否完整、記憶體是否放得下；對 Qwen3.5 系列模型，還會顯示將使用哪一種推測式解碼路徑。`--no-metal` 會略過匯入 MLX；這項檢查無法證明 Metal 或檢查點確實可用。

```bash
yunshu doctor -m mlx-community/Qwen3.5-0.8B-MLX-bf16
yunshu --json doctor --no-metal
```

## 解除安裝

```bash
yunshu service uninstall      # 僅在你安裝過登入服務時需要
uv tool uninstall yunshu      # 或：brew uninstall yunshu、pip uninstall yunshu
```

下載的模型位於 `~/.yunshu/models`，不會被移除。完整的清理清單請見[服務](/docs/getting-started/service)。

## 下一步

繼續閱讀[快速開始](/docs/getting-started/quickstart)。若安裝失敗，請見[疑難排解](/docs/guides/troubleshooting)。


---

<!-- getting-started/models -->
---
title: 模型
description: Yunshu 在哪裡存放與尋找模型、如何下載、列出與移除模型，以及如何從同一個目錄服務多個模型。
---

Yunshu 載入 MLX 格式的檢查點。一個模型就是含有 `config.json` 與 `*.safetensors` 權重的資料夾（或含有 `model_index.json` 的 diffusers pipeline）。

## 模型存放位置

Yunshu 會在兩個地方尋找模型。

| 位置 | 預設值 | 說明 |
|---|---|---|
| 模型目錄 | `~/.yunshu/models` | `yunshu pull` 寫入的位置。模型以 `<org>/<name>` 存放，例如 `~/.yunshu/models/mlx-community/Qwen3.5-0.8B-MLX-bf16`。掃描時也會讀取直接放在目錄下的資料夾。 |
| Hugging Face 快取 | Hugging Face 自己的快取位置（`HF_HOME`、`HF_HUB_CACHE`） | 含有設定檔與權重的快照會被發現並就地重用，不會複製。 |

把模型參照傳給 `yunshu serve -m` 時，Yunshu 在考慮下載之前會依序解析：既有的路徑、模型目錄下的名稱（`name` 或 `org/name`），再來是已在 Hugging Face 快取中的 repo id。都找不到時，載入器會把該參照當作 Hugging Face repo id。

### 變更模型目錄

用 `yunshu config set` 設定 `models_dir`（即設定項 `YUNSHU_MODELS_DIR`）：

```bash
yunshu config set models_dir /path/to/models
yunshu config path          # 顯示寫入的檔案：~/.yunshu/config.toml
```

這會改變之後 `yunshu pull` 的下載位置，以及多模型模式下伺服器的掃描位置；不會搬移你已下載的模型。鍵名可以加或不加 `YUNSHU_` 前綴，路徑值會以絕對路徑儲存。同名的環境變數優先於設定檔，此時 `yunshu config set` 會印出提示。用 `yunshu config unset models_dir` 可移除該設定。`yunshu config` 會顯示每個設定的有效值與來源，請見[設定](/docs/guides/configuration)。

## 列出模型

```bash
yunshu model list                     # 模型目錄 + Hugging Face 快取
yunshu model list --no-hf-cache       # 只看模型目錄
yunshu model list --dir /path/to/dir  # 掃描其他目錄
yunshu model list --url http://localhost:8000   # 改為詢問執行中的伺服器
yunshu --json model list
```

對於磁碟上的每個模型，表格會顯示名稱、偵測到的類型、大小，以及位於模型目錄還是 Hugging Face 快取。使用 `--url` 時，指令會呼叫伺服器的 `GET /v1/models`，並列出伺服器回報的內容。`yunshu models` 是 `yunshu model` 的別名。

## 下載模型

```bash
yunshu pull mlx-community/Qwen3.5-9B-MLX-4bit
yunshu pull mlx-community/Qwen3.5-9B-MLX-4bit --revision main
yunshu pull mlx-community/Qwen3.5-9B-MLX-4bit --dir /path/to/models
```

| 選項 | 說明 |
|---|---|
| `--dir`、`-d` | 下載到此目錄，而非預設的模型目錄。 |
| `--revision`、`-r` | 要解析的分支、標籤或 commit。即使模型已存在也會解析。 |
| `--force` | 即使模型已在磁碟上也下載。只會取得缺少或已變更的檔案，不會刪除任何東西。 |

參數必須是 `org/name` 格式的 Hugging Face repo id。若模型目錄或 Hugging Face 快取中已有完整副本，`yunshu pull` 會告知並且不再下載。中斷的下載只要再執行同一個指令就會續傳。`yunshu model pull` 是同一個指令。此指令不會替你挑選模型。

可用 `yunshu doctor -m <model>` 檢查下載結果，它會回報缺少的權重分片，以及模型是否放得進記憶體。

## 檢視與移除

```bash
yunshu model info mlx-community/Qwen3.5-9B-MLX-4bit   # 別名：model show
yunshu model rm mlx-community/Qwen3.5-9B-MLX-4bit --yes
```

`model info` 會顯示模型的類型、大小、檔案數量，以及 `config.json` 中的主要架構與量化欄位。`model rm` 依完整名稱從模型目錄移除模型；未加 `--yes` 時會要求確認，而在 `--json` 模式下一定要加 `--yes`。位於 Hugging Face 快取的模型、符號連結的模型，以及模型目錄之外的模型都不會被移除，請在來源處管理。移除檔案前，請先從執行中的伺服器卸載該模型。

## 服務單一或多個模型

**單一模型模式。** 指定 `--model`（或把模型當作第一個參數）。不論請求送出的 `model` 名稱為何，所有請求都對應到該模型。

```bash
yunshu serve -m mlx-community/Qwen3.5-9B-MLX-4bit
yunshu serve ~/.yunshu/models/mlx-community/Qwen3.5-9B-MLX-4bit
```

**多模型模式。** 指定 `--models-dir`（或 `-d`），服務目錄中找到的模型。模型在啟動時登錄，並在請求指名時才依需求載入。`GET /v1/models` 會列出可用的 id。

```bash
yunshu serve --models-dir ~/.yunshu/models
yunshu model list --url http://localhost:8000
```

已登錄模型但尚未載入任何模型的伺服器，`GET /health/ready` 仍會回報就緒。請求的 `model` 欄位必須是列出的 id 之一。

### 在執行中的伺服器載入與卸載

```bash
yunshu model load mlx-community/Qwen3.5-9B-MLX-4bit
yunshu model unload mlx-community/Qwen3.5-9B-MLX-4bit
```

這些指令會呼叫 `POST /v1/models/load` 與 `POST /v1/models/unload/{model_id}`。它們屬於操作性端點：未設定 `YUNSHU_AUTH_TOKEN` 時會被拒絕，因此請在伺服器設定 token，並在執行 CLI 的 shell 中匯出相同的值。請見[模型 API](/docs/api/models)。

## 相關頁面

- [快速開始](/docs/getting-started/quickstart)
- [模型支援](/docs/guides/model-support)：支援哪些模型系列與類型。
- [CLI 參考](/docs/guides/cli)


---

<!-- getting-started/quickstart -->
---
title: 快速開始
description: 下載模型、啟動伺服器、確認就緒，並以 curl、OpenAI SDK 或 yunshu chat 送出第一個請求。
---

本頁帶你從已安裝的 `yunshu` 指令走到第一個回答。如果 `yunshu --version` 還無法執行，請先看[安裝](/docs/getting-started/install)。

<Steps>
<Step>

### 下載模型

先看看磁碟上已有哪些模型，再拉取一個小模型作為第一次測試：

```bash
yunshu model list
yunshu pull mlx-community/Qwen3.5-0.8B-MLX-bf16
```

`yunshu pull` 會下載到 `~/.yunshu/models`（請見[模型](/docs/getting-started/models)）。中斷的下載可以續傳，若模型目錄或 Hugging Face 快取中已有完整的副本，則會直接重用。0.8B 模型只適合做冒煙測試；實際使用請選較大的 MLX 檢查點。

</Step>
<Step>

### 檢查模型並啟動伺服器

```bash
yunshu doctor -m mlx-community/Qwen3.5-0.8B-MLX-bf16
yunshu serve -m mlx-community/Qwen3.5-0.8B-MLX-bf16
```

模型也可以當作第一個參數傳入（`yunshu serve mlx-community/Qwen3.5-0.8B-MLX-bf16`），或指定本機目錄。伺服器預設監聽 `127.0.0.1:8000`。請保持這個終端機開啟；按 Ctrl-C 即可停止伺服器。

如果在互動式終端機中執行 `yunshu serve` 但沒有設定任何模型，它會請你從磁碟上的模型選一個，或輸入 Hugging Face 儲存庫。它不會自行下載模型。在沒有終端機的環境中，它會以錯誤結束並提示下一步。

</Step>
<Step>

### 等待就緒

開啟第二個終端機：

```bash
curl --fail http://127.0.0.1:8000/health/ready
curl --fail http://127.0.0.1:8000/v1/models
```

模型載入中或載入失敗時，`GET /health/ready` 會回傳 HTTP 503；伺服器可以接受請求後才回傳 200。連接埠開著並不代表模型已就緒。載入失敗時，503 的內容會帶有 `reason`。

</Step>
<Step>

### 送出請求

在單一模型模式下，`model` 欄位只是參考用途：任何名稱都會對應到你啟動的那個模型。預設不需要 API 金鑰；只有設定了 `YUNSHU_AUTH_TOKEN` 才會強制驗證。

<Tabs items={["curl", "Python", "JavaScript"]}>
<Tab value="curl">

```bash
curl --fail http://localhost:8000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "local",
    "messages": [{"role": "user", "content": "Say hello in one sentence."}],
    "max_tokens": 64,
    "temperature": 0
  }'
```

</Tab>
<Tab value="Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")
reply = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Say hello in one sentence."}],
    max_tokens=64,
)
print(reply.choices[0].message.content)
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "not-needed" });
const reply = await client.chat.completions.create({
  model: "local",
  messages: [{ role: "user", content: "Say hello in one sentence." }],
  max_tokens: 64,
});
console.log(reply.choices[0].message.content);
```

</Tab>
</Tabs>

</Step>
</Steps>

OpenAI 用戶端使用 base URL `http://localhost:8000/v1`。Anthropic 用戶端使用不含 `/v1` 的 `http://localhost:8000`，並呼叫 `POST /v1/messages`。請見 [API 總覽](/docs/api/overview)。

## 在終端機中對話

`yunshu chat` 是連到已執行伺服器的互動式用戶端。它不會下載模型，也不會啟動伺服器。

```bash
yunshu chat
yunshu chat --system "Answer briefly." --temperature 0.2 --thinking
```

對話中，`/clear` 重設對話，`/thinking` 切換思考模式，`/model <name>` 切換模型，`/help` 列出指令，`/quit`（或 Ctrl-C）離開。選項請見 [CLI 參考](/docs/guides/cli)。

若只需要一次非互動式請求，請使用 `yunshu complete`：

```bash
yunshu complete "Say hello in one sentence." --max-tokens 64
yunshu --json complete "Say hello in one sentence."
```

## 8000 埠被佔用時

`yunshu serve` 會在載入模型之前先確認能否綁定位址，無法綁定就會以錯誤結束。請改用其他連接埠，並在所有地方使用同一個埠：

```bash
yunshu serve -m mlx-community/Qwen3.5-0.8B-MLX-bf16 --port 8001
yunshu chat --url http://127.0.0.1:8001
```

在檢查與實際綁定之間，仍可能有其他行程佔用該埠；以最終的綁定錯誤為準。伺服器只監聽 `127.0.0.1`。若要接受其他機器的連線，請使用 `--host 0.0.0.0`，並同時設定 `--auth-token`；綁定非本機位址卻沒有 token 時，`yunshu serve` 會發出警告。

## 搭配程式碼代理使用

`yunshu launch` 會為程式碼工具寫入設定，並讓它連到你的伺服器。請先預覽：

```bash
yunshu launch claude --dry-run
yunshu launch codex --dry-run
yunshu launch opencode --dry-run
```

確認後再去掉 `--dry-run` 執行同一個指令。支援的工具有 `claude`、`codex`、`opencode` 與 `pi`；`yunshu launch list` 會顯示哪些已安裝。啟動器會從伺服器讀取所服務模型的上下文視窗、輸出上限、推理強度等級與視覺支援，並交給該工具。請見[代理程式](/docs/guides/agents)。

## 下一步

- [模型](/docs/getting-started/models)：模型存放的位置與管理方式。
- [服務](/docs/getting-started/service)：登入時自動啟動 Yunshu。
- [主控台](/docs/getting-started/console)：以網頁檢視執行中的引擎。


---

<!-- getting-started/service -->
---
title: 服務
description: 以 yunshu service 管理的使用者層級 launchd 代理程式，讓 Yunshu 在登入時於背景執行。
---

`yunshu service` 在 macOS 上管理使用者層級的 launchd 代理程式（agent）。該 agent 會在你登入時啟動 Yunshu，當程序當機時重新啟動（正常停止則不會），並把輸出寫入會自動輪替的記錄檔。它以你的身分執行，不需要 root 權限，也不會動到下列兩個路徑以外的任何位置。

| 項目 | 位置 |
|---|---|
| launchd agent | `~/Library/LaunchAgents/com.yuhuanstudio.yunshu.plist` |
| 記錄檔 | `~/Library/Logs/Yunshu/yunshu.log` |

此指令僅限 macOS。不論以 uv、pip 或 Homebrew 安裝，用法都相同；Homebrew formula 沒有另外定義 service。

## 安裝

可以先檢查模型，再安裝：

```bash
yunshu doctor -m mlx-community/Qwen3.5-9B-MLX-4bit
yunshu service install -m mlx-community/Qwen3.5-9B-MLX-4bit
```

`install` 接受決定要服務什麼、在哪裡服務的選項：

| 選項 | 說明 |
|---|---|
| `--model`、`-m` | 模型資料夾或 Hugging Face repo id。已存在的路徑會以絕對路徑儲存。 |
| `--models-dir`、`-d` | 服務此目錄中的所有模型（多模型模式）。 |
| `--host` | 綁定的主機。預設 `127.0.0.1`。 |
| `--port`、`-p` | 綁定的連接埠。預設 `8000`。 |
| `--config`、`-c` | 服務每次啟動時都會讀取的 TOML 設定檔，檔案必須存在。 |
| `--set KEY=VALUE` | 在安裝時固定的設定，可重複使用。 |
| `--dry-run` | 以 property list 格式印出 launchd agent，不做任何變更。 |
| `--no-start` | 寫入 agent 但不立即啟動。 |
| `--force` | 取代已安裝的 agent。 |

你必須指明要服務什麼：傳入 `--model` 或 `--models-dir`，或已設定 `YUNSHU_MODEL`。`install` 會拒絕未通過 `yunshu doctor -m` 同一套模型檢查的模型（例如路徑不存在或下載不完整）。若已安裝 agent，除非加上 `--force`，否則 `install` 會報錯停止。

`install` 會寫入兩個 agent：引擎，以及獨立 job 的主控台程序（`com.yuhuanstudio.yunshu.console`，停止時一律重新啟動），所以引擎重新啟動或當機時，主控台仍持續服務與記錄。`--no-console` 只安裝引擎、`--console-port` 更換主控台連接埠（預設 8100），`yunshu service logs --console` 讀取它的記錄檔，`yunshu service restart` 只重新啟動引擎。引擎 agent 使用執行 `install` 的那個安裝環境所用的 Python 來執行 `python -m yunshu_cli serve --no-console ...`。在同一個環境升級 Yunshu 之後，請執行 `yunshu service restart`。若換到不同的環境，請重新執行 `yunshu service install --force ...`。

```bash
yunshu service install -m mlx-community/Qwen3.5-9B-MLX-4bit --dry-run   # 先檢視
```

### 服務使用的設定

你在 shell 中 `export` 的設定不會被複製到服務。請把它們寫進以 `--config` 傳入的設定檔，或用 `--set` 固定。環境變數 `HF_HOME`、`HF_HUB_CACHE`、`HF_ENDPOINT` 與 `HF_HUB_OFFLINE` 是例外：它們會被複製，讓服務找到同一個 Hugging Face 快取。未指定 `--config` 時，服務仍會讀取 `yunshu config set` 寫入的使用者層級檔案 `~/.yunshu/config.toml`。服務的 `PATH` 固定為 `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`。

設定檔是扁平的 `KEY = value` TOML：

```toml
# ~/.yunshu/yunshu.toml
YUNSHU_AUTH_TOKEN = "change-me"
YUNSHU_LOG_KEEP = 14
```

```bash
yunshu service install -m mlx-community/Qwen3.5-9B-MLX-4bit -c ~/.yunshu/yunshu.toml
```

若綁定非本機的 `--host`，請同時設定驗證 token。所有設定請見[設定](/docs/guides/configuration)。

## 日常指令

```bash
yunshu service status        # 已安裝 / 執行中（pid）/ 是否健康，以及路徑
yunshu service logs -n 100   # 最後 100 行（預設 50）
yunshu service logs -f       # 持續追蹤記錄
yunshu service restart       # 例如編輯設定檔之後
yunshu service stop          # 停止，直到下次登入或執行 `service start`
yunshu service start
yunshu service uninstall     # 停止並移除 agent；模型與記錄會保留
```

| 指令 | 行為 |
|---|---|
| `status` | 回報 agent 是否已安裝與載入、pid 與上次結束代碼、安裝時使用的 URL，以及 `GET /health` 是否有回應。`--json` 回傳相同的資訊。 |
| `logs` | 顯示最後 `--lines`/`-n` 行。`--follow`/`-f` 持續輸出，且不能與 `--json` 併用。尚無記錄檔時會失敗。 |
| `start` | 啟動已安裝的 agent。尚未安裝時會失敗。 |
| `stop` | 卸載 agent。直到下次登入或執行 `start` 之前都會保持停止。 |
| `restart` | 重新啟動執行中的 agent。服務未執行時會失敗，此時請改用 `start`。 |
| `uninstall` | 停止 agent 並刪除 plist。模型與記錄會保留。 |

agent 被設定為當機後重新啟動、正常結束則不重啟，且 launchd 兩次重啟之間至少間隔 10 秒。若模型無法載入，伺服器仍會保持運作，`GET /health/ready` 會回傳 503 並附上原因，而不是讓程序反覆結束重啟。

## 記錄輪替

服務在執行期間會自行輪替記錄。輪替依大小與時間進行；被輪替的檔案是已去除 token 與 API 金鑰的 gzip 壓縮檔。下列設定控制輪替：

| 設定 | 預設值 | 說明 |
|---|---|---|
| `YUNSHU_LOG_MAX_MB` | 50 | 達到此大小（MiB）時輪替。0 表示關閉依大小輪替。 |
| `YUNSHU_LOG_ROTATE_HOURS` | 24 | 經過此小時數也會輪替。0 表示關閉依時間輪替。 |
| `YUNSHU_LOG_KEEP` | 7 | 保留的已輪替檔案數量。 |
| `YUNSHU_LOG_RETENTION_DAYS` | 14 | 刪除超過此天數的已輪替檔案。0 表示保留，直到被 `YUNSHU_LOG_KEEP` 清除。 |

`yunshu service rotate-logs` 會立即輪替記錄，適合在服務已停止時使用。

## 完整解除安裝

```bash
yunshu service uninstall
uv tool uninstall yunshu               # 或：brew uninstall yunshu、pip uninstall yunshu
rm -rf ~/Library/Logs/Yunshu
rm -rf ~/.yunshu                       # 下載的模型與設定：刪除前請確認
```

前綴快取的 SSD 層位於 `~/.yunshu/cache/apc`，除非 `YUNSHU_VLM_APC_DISK_DIR` 指向其他位置；若你設定過，也請一併刪除該目錄。

## 相關頁面

- [安裝](/docs/getting-started/install)
- [疑難排解](/docs/guides/troubleshooting)
- [CLI 參考](/docs/guides/cli)


---

<!-- guides/agents -->
---
title: 程式代理與 SDK
description: 以啟動器或手動設定，讓 Claude Code、Codex、opencode、Pi 與官方 OpenAI、Anthropic SDK 連到本機的 Yunshu 伺服器。
---

Yunshu 在 `/v1` 下提供 OpenAI API，並在 `/v1/messages` 提供 Anthropic Messages API，因此任何能設定 base URL 的程式代理或 SDK 都可以直接使用。對 Claude Code、Codex、opencode 與 Pi，`yunshu launch` 還多做一步：它會從伺服器讀取模型卡，把代理原本只能猜的數值（context window、輸出上限、推理等級、是否支援視覺）直接交給代理。

| | 值 |
|---|---|
| OpenAI base URL | `http://localhost:8000/v1` |
| Anthropic base URL | `http://localhost:8000`（SDK 會自行加上 `/v1/messages`） |
| API key | 任意佔位字串。只有伺服器以 `YUNSHU_AUTH_TOKEN`（或 `--auth-token`）啟動時才會檢查 |
| 模型名稱 | 單模型模式下名稱僅供參考，`local` 即可。多模型模式請使用 `GET /v1/models` 回傳的 id |

設定 token 後，伺服器接受 `Authorization: Bearer <token>`（OpenAI 用戶端）或 `x-api-key: <token>`（Anthropic 用戶端）。

## 以 launch 啟動代理

先啟動伺服器（`yunshu serve -m <model>`，見[快速開始](/docs/getting-started/quickstart)），然後：

```bash
yunshu launch list                      # 列出已安裝的工具
yunshu launch claude                    # Claude Code
yunshu launch codex                     # Codex CLI
yunshu launch opencode                  # opencode
yunshu launch pi                        # Pi
yunshu launch codex --dry-run           # 只印出設定，不寫入任何檔案
```

| 選項 | 說明 |
|---|---|
| `--model`, `-m` | 要使用的模型 id。預設：`GET /v1/models` 中第一個看起來像已知聊天模型家族的模型，否則取列表第一個 |
| `--url`, `-u` | 伺服器網址。預設 `http://localhost:8000`，或環境變數 `YUNSHU_GATEWAY_URL` |
| `--api-key`, `-k` | 交給工具的 API key |
| `--effort` | 僅 Claude Code：設定 `CLAUDE_CODE_EFFORT_LEVEL` |
| `--statusline` / `--no-statusline` | 僅 Claude Code：加入（預設）或略過 Yunshu 狀態列 |
| `--dry-run` | 印出將寫入或匯出的內容後結束 |

啟動器會先檢查 `GET /health`，沒有伺服器回應時會給出提示並結束。工具未安裝時也會失敗（`--dry-run` 不檢查這點）。

### 各工具會設定什麼

<Tabs items={["Claude Code", "Codex", "opencode", "Pi"]}>
<Tab value="Claude Code">

只使用環境變數，不會寫入 `~/.claude` 下的任何檔案。

| 變數 | 值 |
|---|---|
| `ANTHROPIC_BASE_URL` | 伺服器網址，不含 `/v1` |
| `ANTHROPIC_AUTH_TOKEN` | API key；未指定時為 `yunshu`（使用 bearer token，而不是 `ANTHROPIC_API_KEY`） |
| `ANTHROPIC_MODEL`、`ANTHROPIC_SMALL_FAST_MODEL`、`ANTHROPIC_DEFAULT_OPUS_MODEL`、`ANTHROPIC_DEFAULT_SONNET_MODEL`、`ANTHROPIC_DEFAULT_HAIKU_MODEL`、`CLAUDE_CODE_SUBAGENT_MODEL` | 所服務的模型 id，讓所有別名與子代理都對應到它 |
| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | 模型真實的 context window（Claude Code 對不認識的模型 id 會假設 200K） |
| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | 模型的輸出上限，最多 32000 |
| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | `1`：`/model` 會列出 `GET /v1/models` 的模型 |
| `DISABLE_TELEMETRY`、`DISABLE_ERROR_REPORTING`、`DISABLE_AUTOUPDATER` | `1` |
| `CLAUDE_CODE_EFFORT_LEVEL` | 僅在使用 `--effort` 時設定 |

啟動前，啟動器會從環境中移除 `ANTHROPIC_API_KEY`、`CLAUDE_CODE_USE_BEDROCK` 與 `CLAUDE_CODE_USE_VERTEX`，避免殘留的設定把請求送到別處。

它也會以 `--settings` 傳入一個執行 `yunshu statusline` 的狀態列（預填進度、解碼速度、最近一次快取命中、context 使用量）。如果你自己的 Claude Code `settings.json` 已經定義了 `statusLine`，或使用 `--no-statusline`，就不會加入。

</Tab>
<Tab value="Codex">

寫入兩個檔案；既有的 `config.toml` 會先備份成同目錄下帶時間戳記的 `.<timestamp>.bak`。

- `~/.codex/config.toml`：設定 `model`、`model_provider = "yunshu"`、`model_catalog_json`、`model_context_window`、`model_auto_compact_token_limit`（視窗的 85%）、`web_search`，推理模型另有 `model_reasoning_summary = "auto"`。並加入 `[model_providers.yunshu]` 表，內含 `base_url = "<server>/v1"`、`env_key = "YUNSHU_API_KEY"` 與 `wire_api = "responses"`。檔案中的其他設定與表會保留。
- `~/.codex/yunshu-models.json`：模型目錄項目，包含真實的 context window、聊天模板接受的推理等級、輸入模態，以及精簡的 `base_instructions`。Codex 不會向自訂供應商取得模型中繼資料；沒有目錄時會印出「Model metadata not found」，也不會送出推理強度。

模型卡回報可使用伺服器端網路搜尋時，`web_search` 為 `"live"`，否則為 `"disabled"`。啟動器會匯出 `YUNSHU_API_KEY`（API key，或 `yunshu`），再執行 `codex -m <model>`。

</Tab>
<Tab value="opencode">

更新 `~/.config/opencode/opencode.json`（會保留一份帶時間戳記的 `.bak`），加入 `provider.yunshu` 項目與 `"model": "yunshu/<id>"`。供應商使用 `@ai-sdk/openai-compatible`，`baseURL` 為 `<server>/v1`，模型項目帶有 `tool_call`、`reasoning`、`limit.context`、`limit.output` 與 `modalities`。opencode 不會向自訂供應商取得 `/models`，所以 context 百分比與壓縮時機就由這些上限決定。

</Tab>
<Tab value="Pi">

更新 `~/.pi/agent/models.json`（供應商 `yunshu`、`api: "openai-completions"`、`baseUrl` 為 `<server>/v1`）與 `~/.pi/agent/settings.json`（`defaultProvider`、`defaultModel`），然後執行 `pi --model yunshu/<model>`。與其他三者不同，Pi 的項目不會帶入模型卡的 context 與輸出上限。

</Tab>
</Tabs>

## 手動設定

不想讓啟動器改動你的設定時，可以自行設定。

<Tabs items={["Claude Code", "Codex", "opencode"]}>
<Tab value="Claude Code">

```bash
export ANTHROPIC_BASE_URL=http://localhost:8000
export ANTHROPIC_AUTH_TOKEN=sk-local
export ANTHROPIC_MODEL=local
export ANTHROPIC_SMALL_FAST_MODEL=local
export CLAUDE_CODE_MAX_CONTEXT_TOKENS=131072   # 你的模型真實視窗
claude
```

</Tab>
<Tab value="Codex">

```toml
# ~/.codex/config.toml
model = "local"
model_provider = "yunshu"
model_context_window = 131072

[model_providers.yunshu]
name = "Yunshu"
base_url = "http://localhost:8000/v1"
env_key = "YUNSHU_API_KEY"
wire_api = "responses"
```

```bash
export YUNSHU_API_KEY=sk-local
codex
```

沒有 `model_catalog_json` 時 Codex 不認識這個模型：會出現「Model metadata not found」，也沒有推理強度可選。

</Tab>
<Tab value="opencode">

```json
{
  "provider": {
    "yunshu": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Yunshu",
      "options": { "baseURL": "http://localhost:8000/v1", "apiKey": "sk-local" },
      "models": {
        "local": {
          "name": "local",
          "tool_call": true,
          "reasoning": false,
          "limit": { "context": 131072, "output": 32768 },
          "modalities": { "input": ["text"], "output": ["text"] }
        }
      }
    }
  },
  "model": "yunshu/local"
}
```

</Tab>
</Tabs>

其他相容 OpenAI 的工具只要有 base URL 與 key 就能使用：Cline 與 Roo Code（供應商選「OpenAI Compatible」，base URL 為 `http://localhost:8000/v1`）、Continue（`provider: openai`、`apiBase: http://localhost:8000/v1`）以及 Open WebUI（Settings、Connections、OpenAI API）。這些只是設定指引，並不像上述三個代理一樣每個版本都做測試。

## 各代理使用哪些端點

下表是代理對自訂供應商發出的呼叫，以及 Yunshu 如何回應。

| 代理 | 請求 | Yunshu |
|---|---|---|
| Claude Code | 每一輪 `POST /v1/messages`，`stream: true`，帶有 `anthropic-beta` 標頭、system 區塊上的 `cache_control`、`thinking` 與 `output_config.effort` | 支援。beta 標頭一律不會被拒絕 |
| Claude Code | `POST /v1/messages/count_tokens`（`/context`） | 支援：計算 system、messages 與 tools |
| Claude Code | `GET /v1/models`（開啟 discovery 後用來填 `/model`） | 支援，回傳 `max_input_tokens`、`max_tokens` 與 `capabilities` |
| Claude Code | 帶有 `web_search_20250305` 工具的 `POST /v1/messages` | 由伺服器端執行，見[網路搜尋與擷取](/docs/guides/web-search) |
| Claude Code | 小模型呼叫（標題、摘要）與子代理 | 一般的 `POST /v1/messages` 呼叫 |
| Codex | `POST /v1/responses`，`stream: true`、`store: false`，帶有 function、namespace 與 `web_search` 工具、`reasoning`、`include` | 支援 |
| Codex | `WS /v1/responses`（只在供應商設定 `supports_websockets` 時使用；啟動器不會設定） | 支援 |
| Codex | 壓縮（compaction） | 不帶工具的一般 `POST /v1/responses` 呼叫 |
| opencode | `POST /v1/chat/completions`，帶 `stream_options.include_usage`、較大的 `max_tokens`、function 工具；產生標題時使用 `reasoning_effort: "low"` | 支援 |

在代理中設定的 MCP 伺服器屬於用戶端：代理自己連線，並把它們的工具當作一般 function tool 傳給模型，因此 Yunshu 只需要能正常運作的工具呼叫。Claude Code 的 WebFetch 同樣在用戶端執行。伺服器端的 MCP connector（Messages 的 `mcp_servers`、Responses 的 `{type: mcp}` 工具）是另一項功能，見[伺服器工具](/docs/api/server-tools)。

## 哪些可用、哪些不可用

| 功能 | Claude Code | Codex | opencode | 狀態 |
|---|---|---|---|---|
| 串流、工具呼叫 | 是 | 是 | 是 | <Support status="supported">支援</Support> |
| 對話中途的 system 或 developer 備註 | 是 | 是（`developer` items） | 未使用 | <Support status="supported">支援</Support> |
| 推理強度控制 | `output_config.effort` 對應到聊天模板的 `reasoning_effort` | 透過目錄中的等級送出 `reasoning.effort` | `reasoning_effort` | <Support status="supported">支援</Support> |
| 網路搜尋 | 伺服器端 `web_search` | 伺服器端 `web_search` | 未使用（用戶端工具） | 有可用搜尋來源時<Support status="supported">支援</Support> |
| 網頁擷取 | CLI 在用戶端執行 | 未使用 | 未使用 | SDK 使用者可用伺服器端 `web_fetch` 工具 |
| MCP | 用戶端 | 用戶端 | 用戶端 | 以一般工具呼叫的形式<Support status="supported">支援</Support> |
| 圖片輸入 | 是（`Read` 一張 PNG） | `exec` 模式未使用 | 未使用 | <Support status="partial">需要視覺模型</Support> |
| 模型選單與 context window | 來自 `/v1/models` 與啟動環境 | 來自模型目錄 | 來自 `limit` | 使用 `yunshu launch` 時<Support status="supported">支援</Support> |
| 在 UI 顯示引擎即時狀態 | `yunshu statusline` | 無 | 無 | <Support status="extension">僅 Claude Code</Support> |
| 費用顯示 | 對不認識的模型會顯示自行估算的數字；實際上不會計費 | 不適用 | 不適用 | <Support status="unsupported">無法由伺服器端修正</Support> |
| 速率限制標頭 | 不送出：Yunshu 沒有配額 | 不送出 | 不送出 | <Support status="unsupported">未提供</Support> |

其他需要知道的事：

- 串流開始後發生的失敗，會以串流內的錯誤回報（Messages 為 SSE `error` 事件，Responses 為 `response.failed`，chat 為錯誤 chunk），而不是一個空的成功回應。
- 明確的 `cache_control` 標記只是提示。如果聊天模板丟掉了標記（Qwen 模板會移除先前回合的推理內容），請求會在沒有明確檢查點的情況下照常處理，而不會失敗。見[提示詞快取](/docs/guides/prompt-caching)。
- `temperature`、`max_tokens`、`stream` 等欄位的 JSON `null` 視為「未設定」並被接受，因為有數個 SDK 會送出 `null`。
- Responses 串流會以 `data: [DONE]` 結尾，這一點與真正的 API 不同。官方 SDK 與 Codex 遇到它都會正常停止。
- 請求模型已知的缺口：已棄用的 chat `functions` / `function_call` 欄位、chat 中的 custom tools、Responses 的 `prompt` 範本，以及沒有 `input` 的 Responses 請求。
- Claude Code 的 `/model` 仍會列出它內建的模型列，那是用戶端自己的目錄。它實際使用的 context window 是真實值（可用 `/context` 確認）。
- 代理每一輪都會送出大量重複的長提示。Yunshu 的前綴快取會重用共同的部分，所以第一輪之後只需預填新增的 token。

## SDK 設定

以下四段範例都使用佔位 key。若同時服務多個模型，請把 `local` 換成模型 id。

<Tabs items={["OpenAI Python", "OpenAI JavaScript", "Anthropic Python", "Anthropic JavaScript"]}>
<Tab value="OpenAI Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

resp = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Explain MLX in one sentence."}],
    extra_body={"reasoning_effort": "medium"},  # 交給支援它的模板
)
print(resp.choices[0].message.content)
```

</Tab>
<Tab value="OpenAI JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "sk-local" });

const resp = await client.chat.completions.create({
  model: "local",
  messages: [{ role: "user", content: "Hello" }],
});
console.log(resp.choices[0].message.content);
```

</Tab>
<Tab value="Anthropic Python">

```python
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:8000", api_key="sk-local")

msg = client.messages.create(
    model="local",
    max_tokens=512,
    messages=[{"role": "user", "content": "Hello"}],
)
print(msg.content[-1].text)
```

</Tab>
<Tab value="Anthropic JavaScript">

```ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({ baseURL: "http://localhost:8000", apiKey: "sk-local" });

const msg = await client.messages.create({
  model: "local",
  max_tokens: 512,
  messages: [{ role: "user", content: "Hello" }],
});
console.log(msg.content);
```

</Tab>
</Tabs>

OpenAI SDK 的 base URL 以 `/v1` 結尾；Anthropic SDK 的則不含 `/v1`。串流（`stream=True`）、工具、`response_format`、`stop`、`logprobs` 與 `seed` 都可透過官方 SDK 使用。推理模型的思考內容會與答案分開串流（chat 為 `delta.reasoning_content`）。

若要從其他機器或容器連線，請以 `--host 0.0.0.0 --auth-token <secret>` 啟動伺服器，並把該密碼當作 key。預設綁定位址是 `127.0.0.1`。

## 相關頁面

- [Chat Completions](/docs/api/chat-completions)、[Responses](/docs/api/responses) 與 [Messages](/docs/api/messages)
- [網路搜尋與擷取](/docs/guides/web-search)
- [提示詞快取](/docs/guides/prompt-caching)
- [CLI 參考](/docs/guides/cli)
- [疑難排解](/docs/guides/troubleshooting)


---

<!-- guides/auth-and-keys -->
---
title: 驗證、API 金鑰與 CORS
description: 如何用 token 或逐金鑰配額保護 Yunshu 伺服器、從 API 寫入設定、編輯 CORS 來源，以及內建防護的作用。
---

Yunshu 是單節點、單一操作者的伺服器。存取控制分為三層，全部在本機：靜態 token、附配額的選用 API 金鑰，以及 CORS 來源。

## 靜態 token

設定 `YUNSHU_AUTH_TOKEN`（或以 `--auth-token` 啟動）。之後除了 health、version 與文件之外，每個請求都需要 `Authorization: Bearer <token>` 或 `x-api-key`。文字 WebSocket 端點也接受 `?token=`。

| 狀態 | 推論路由 | 維運路由（載入／卸載模型、設定、金鑰、日誌、診斷） |
|---|---|---|
| 已設定 token | 需要 token | 需要 token |
| 沒有 token 且沒有儲存的 API 金鑰 | 開放 | 拒絕 |
| `YUNSHU_AUTH_DISABLED=1` | 開放 | 開放 |

<Callout type="warn">
token 是管理員憑證。`YUNSHU_AUTH_DISABLED=1` 會開放一切，只適用於本機開發。`YUNSHU_HOST` 預設為 `127.0.0.1`；綁定 `0.0.0.0` 之前請先設定 token。
</Callout>

## 附配額的 API 金鑰

除了靜態 token，操作者可以建立多把金鑰。每把金鑰有範圍（`infer`、`admin`）、選用的到期時間，以及配額（`requests_per_day`、`tokens_per_day`、`max_concurrent`）。可在主控台的 Keys 頁面管理，或使用具 admin 範圍的 API。

<Steps>
<Step>

建立金鑰。`secret` 只會在回應中出現一次；`~/.yunshu/keys.json`（權限 0600）中只儲存雜湊。

```bash
curl -s -X POST localhost:8000/v1/yunshu/keys \
  -H "Authorization: Bearer $YUNSHU_AUTH_TOKEN" \
  -H 'content-type: application/json' \
  -d '{"name":"laptop","scopes":["infer"],"quotas":{"requests_per_day":1000,"max_concurrent":2}}'
```

</Step>
<Step>

把 secret 交給用戶端，作為它的 API 金鑰。

</Step>
<Step>

查看每把金鑰的每日用量（請求、提示詞、完成與快取 token、錯誤）：

```bash
curl -s localhost:8000/v1/yunshu/usage -H "Authorization: Bearer $YUNSHU_AUTH_TOKEN"
```

</Step>
</Steps>

對金鑰使用 `PATCH` 與 `DELETE` 可編輯與移除，`POST /v1/yunshu/keys/{id}/rotate` 會重新簽發。超過配額時，會以該路由自己的錯誤格式回傳 `429` 並附 `Retry-After`。這些路由列於 [Yunshu 擴充](/docs/api/extensions)與[維運](/docs/api/operations)。

金鑰不是租戶。infer 金鑰只看得到自己建立的 Files 與 Conversations（其他金鑰的物件回 404）；靜態 token、關閉驗證模式與 admin 金鑰看得到全部。已儲存的 completions 與 Evals 資料仍共用，沒有 RBAC。Realtime WebSocket 接受金鑰，但不計算配額。

## 寫入設定

`GET /v1/yunshu/config` 會列出每個設定的值、預設值、來源，以及變更何時生效（`live`、`reload` 或 `restart`）。`PATCH /v1/yunshu/config` 會驗證並以原子方式保存變更（全部成功或全部不變，檔案權限 0600）。環境變數或 CLI 的值仍然優先，並標示為 `overridden`。`dry_run` 可預覽變更。

需要重新啟動的設定會被標記，讓主控台提示你。只有在伺服器由 launchd 執行時，`POST /v1/yunshu/service/restart` 才會重新啟動伺服器。主控台的設定頁面提供相同功能，並有搜尋框與逐項控制。所有設定請見[設定](/docs/guides/configuration)。

## CORS

`GET` 與 `PATCH /v1/yunshu/cors`，以及主控台設定頁面，都可即時編輯允許的來源。`YUNSHU_CORS_ORIGINS` 預設為 `http://localhost:3000,http://localhost:8000`。

- 來源格式為 `scheme://host[:port]`，最多 50 個。
- 萬用字元（`*`）需要明確確認，不能與其他來源並用，且會停用 credentials。會傳送 cookie 或 authorization 標頭的瀏覽器必須使用明確的來源。
- 同一份清單也用來檢查 Realtime 與文字 WebSocket 的 `Origin` 標頭。
- 綁定位址與區域網路暴露在此 API 中為唯讀。

## Host 與 Origin 檢查

綁定在 loopback 位址的伺服器會檢查 `Host` 標頭，網頁因此無法經 DNS rebinding 連到它。接受 `localhost`（含 `localhost.` 與 `*.localhost`）、任何 `127.0.0.0/8` 寫法（`127.0.0.1`、`127.1`）、`[::1]` 與未指定位址（`0.0.0.0`、`[::]`），任何埠號。其他一律回 `403`，訊息會指出該標頭值與對應設定。綁定 `0.0.0.0` 的伺服器在未設定 `YUNSHU_ALLOWED_HOSTS` 時不做檢查。

- 反向代理、`tailscale serve`、cloudflared 通道或 `ssh -L` 若把對外名稱當作 `Host` 轉給 loopback 伺服器，必須把該名稱加入 `YUNSHU_ALLOWED_HOSTS`（以逗號分隔；`*` 關閉檢查）。
- loopback 綁定不接受 `host.docker.internal`：容器要連到主機 loopback，伺服器必須監聽 loopback 以外（`YUNSHU_HOST=0.0.0.0`），此時檢查本來就關閉。
- 帶有 `Origin` 且不帶憑證的狀態變更請求，必須來自 loopback、請求自身的 origin 或 `YUNSHU_CORS_ORIGINS`。自訂協定請列 `scheme://*`（例如 `vscode-webview://*`）或完整 origin（`app://.`）。`Origin: null` 一律拒絕。帶 `Authorization` 或 `x-api-key` 的請求不受影響。

## 登入失敗

非 loopback 的用戶端位址在 60 秒內送出 20 次錯誤憑證後，後續錯誤憑證會得到 `429` 與 `Retry-After`。正確的 token 或金鑰一律通過並清除該用戶端的計數；完全沒有憑證的請求回 `401`，不計次。`YUNSHU_TRUSTED_PROXIES` 列出連線的代理時，以 `X-Forwarded-For` 的最後一項為用戶端位址，否則用連線對端位址。

## 其他防護

- 模型下載重新導向到其他來源時，會丟棄 Authorization、API 金鑰與 cookie 標頭。
- Realtime 暫時性 secret（`ek_...`）與日誌行中的憑證會被遮蔽。轉錄用的 secret 無法建立模型回應。
- `web_fetch` 會封鎖私有、loopback 與 link-local 位址（包含重新導向之後），除非設定 `YUNSHU_WEB_FETCH_ALLOW_PRIVATE=1`。含路徑穿越的儲存庫 ID 會在存取磁碟前被拒絕。
- `YUNSHU_RATE_LIMIT_RPM`（預設 `0`，關閉）限制每個用戶端每分鐘的請求數；當伺服器暴露給其他機器時請設定。
- 不會傳送任何使用分析資料。本機會取樣什麼，請見[主機遙測](/docs/guides/telemetry)。


---

<!-- guides/benchmarks -->
---
title: 效能實測
description: 2026-11-04 至 2026-11-08 的 27B 完整比較，Apple M5 Max，審計研究 gaps_full_1109。數字與 docs/BENCHMARKS.md 一致。
---

Apple M5 Max，128 GB 統一記憶體，Qwen3.8-27B 4-bit。雲樞 0.1.7.dev0（main，round driver）
及其 Phase B 建置（`yunshu-pb2`）。完整比較執行於 2026-11-04 至 2026-11-08。下列每個數字都來自經審計的研究
`gaps_full_1109`（2026-11-09；私有研究筆記，不在本倉庫中），該研究由原始列資料產生。競爭對手：TensorFold 1.1.8 與 1.2.1、
Splash 1.5.0、llama.cpp b12061、oMLX 0.7.3 與 0.7.3rc1、mlx-lm-server 0.32.2、mlx-vlm-server 0.7.11 與 mlx-serve 26.11.1。
Kapitsa 0.2.26 與 LM Studio 已排除（見下文）。

2026-10-19 的 27B 快照已被本次執行取代，此處不再重複。它作為帶日期的報告保留：[RELEASE_016 快照 2026-10-19](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_016_BENCHMARKS_2026-10-19.md)。
[0.1.5 快照](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_015_BENCHMARKS.md) 作為歷史保持不變。

## 如何閱讀這些數字

- 每個數值是 2 或 3 次重複的中位數。許多雲樞單元格另外進行了一次未計畫的第三次重複。
- 研究有兩種口徑。STRICT 只有在雙方都通過每項審計檢查時才計入一列，因此只剩 18 個可比列，全部來自批次 B1。REF 還忽略兩項記帳性失敗：B2 中混用了兩個 harness 提交，以及一個未計畫的額外重複檔案。下列每個數字都是 REF 數字。在 REF 下，每個數字所用的雲樞一側只帶有 REF 豁免的檢查，重啟列除外（見其他單元格）。
- 已排除：所有 Kapitsa 單元格（啟動的二進位雜湊與固定的不一致，因此不使用其 RAW 勝出結果）；tool-chat 解碼 tok/s（27 token 的回覆使計時視窗過短；tool-chat TTFT 保留）；128K 混合負載的逐列中位數（角色不同；採用彙總值）；重啟解碼 tok/s（不同引擎之間不可比）；LM Studio（從未執行）。
- 百分比遵循研究口徑。正值表示雲樞更好。百分比取雲樞 main 與雲樞 pb2 中較好的一個，而顯示的雲樞數值為 main 欄（與 README 中數值相同）。當 pb2 更快時，顯示的比值可能與百分比不同。
- 範圍：32K、64K 與 128K 的程式碼和散文提示詞，以及下文列出的並行、混合與重啟單元格。該研究不能確立一般品質或一般排名。

## 雲樞的定位

在完整矩陣中，REF 共有 114 個可比列。雲樞贏 17 列，輸 97 列：輸給 Splash（37）、TensorFold 1.1.8（36）、TensorFold 1.2.1（22）、llama.cpp（1）與 mlx-serve（1）。其中四十個失敗出現在 32K 及以上。

在程式碼提示詞上，TensorFold 在每個深度都領先 27B 解碼；在散文上，TensorFold 在 32K 與 64K 領先，Splash 在 128K 散文解碼領先。冷 TTFT 在 32K 與 64K 落後於 Splash，在 128K 領先。溫 TTFT 在 32K 領先，在 64K 與 128K 落後。後續輪（turn-2）TTFT 在每個深度都落敗，其中最大差距出現在 64K（程式碼 -61.5%）。

### 程式碼提示詞

| 指標 | 32K | 64K | 128K |
|---|---|---|---|
| 解碼 tok/s，冷 | 191.2 vs 238.7（TensorFold 1.1.8）：-19.6% | 107.5 vs 122.7（TensorFold 1.1.8）：-12.4% | 80.9 vs 96.5（TensorFold 1.1.8）：-15.9% |
| 解碼 tok/s，溫 | 198.6 vs 238.1（TensorFold 1.1.8）：-16.6% | 111.1 vs 122.8（TensorFold 1.1.8）：-9.5% | 84.9 vs 96.5（TensorFold 1.1.8）：-11.1% |
| 冷 TTFT s | 32.846 vs 30.570（Splash）：-6.9% | 74.667 vs 73.051（Splash）：-2.2% | 186.818 vs 197.221（Splash）：+5.6% |
| 溫 TTFT s | 0.044 vs 0.086（Splash）：+94.4% | 0.140 vs 0.108（Splash）：-22.5% | 0.273 vs 0.148（Splash）：-45.0% |
| 後續輪 TTFT s | 1.022 vs 0.433（llama.cpp b12061）：-57.7% | 0.473 vs 0.182（TensorFold 1.1.8）：-61.5% | 0.583 vs 0.318（TensorFold 1.1.8）：-35.0% |

### 散文提示詞

| 指標 | 32K | 64K | 128K |
|---|---|---|---|
| 解碼 tok/s，冷 | 66.1 vs 78.0（TensorFold 1.1.8）：-15.3% | 50.8 vs 60.8（TensorFold 1.2.1）：-16.4% | 42.0 vs 49.9（Splash）：-15.3% |
| 解碼 tok/s，溫 | 67.2 vs 78.5（TensorFold 1.2.1）：-14.3% | 51.0 vs 61.5（TensorFold 1.2.1）：-17.0% | 43.4 vs 52.0（Splash）：-15.0% |
| 解碼 tok/s，後續輪 | 67.3 vs 99.9（TensorFold 1.2.1）：-30.3% | 51.6 vs 58.5（TensorFold 1.2.1）：-11.8% | 44.1 vs 47.9（Splash）：-7.9% |
| 冷 TTFT s | 32.825 vs 30.572（Splash）：-6.9% | 74.666 vs 73.076（Splash）：-2.1% | 187.030 vs 197.168（Splash）：+5.4% |
| 溫 TTFT s | 0.040 vs 0.082（llama.cpp b12061）：+105.0% | 0.127 vs 0.107（Splash）：-15.4% | 0.266 vs 0.150（Splash）：-41.4% |
| 後續輪 TTFT s | 0.325 vs 0.126（TensorFold 1.1.8）：-47.5% | 0.467 vs 0.181（TensorFold 1.1.8）：-51.3% | 0.567 vs 0.324（TensorFold 1.2.1）：-31.5% |

### 其他單元格

- 不同的 8K 提示詞，彙總解碼 tok/s，程式碼。雲樞 main（pb2）在 2、4 與 8 個並行請求下：
  27.3（36.8）、33.0（38.5）與 37.1（39.1）。最佳競爭對手（REF）：TensorFold 1.2.1 42.3、TensorFold 1.2.1 45.1、
  TensorFold 1.1.8 45.2。雲樞相對最佳：-13.1%、-14.7% 與 -13.5%。Kapitsa 已排除。
- 混合 128K，程式碼，8 個並行（一個 128K 長請求和 7 個短請求）。彙總 tok/s：16.1（pb2 18.1），對比 Splash 17.7，+2.0%。長請求 TTFT：222.256 s（pb2 212.084 s），對比 Splash 224.558 s，+5.9%。逐列中位數不是同口徑比較，因此不予報告。
- 近似相同快取下的 turn-2（研究中的 idle5 單元格，程式碼，32K）：TTFT 0.983 s，已快取 32704 個 token；對比 TensorFold 1.1.8 的 0.070 s，已快取 33283 個 token，-92.9%。64K 與 128K 的 turn-2 在程式碼和散文上落後 31% 至 61%。
- 程式碼 turn-2 解碼，32K：342.2 tok/s（pb2 347.0），對比 Splash 127.2，+168.9%。研究未解釋這一結果，因此不將其視為普遍結論。
- 重啟，程式碼，32K：重啟 TTFT 32.868 s，對比 mlx-serve 26.11.1 的 0.313 s，-99.0%。兩個雲樞引擎在重啟後都顯示 0 個已快取 token（審計項 `cold_cache` 失敗），因此磁碟層還原未被證明。該重啟項已重新開啟。
- 結構化輸出（json-schema，8K，冷解碼）：74.3 tok/s（pb2 24.0，未通過 engaged 模式），對比 TensorFold 1.1.8 的 163.8，-54.6%。
- Flash-Next（Qwen4）不在本次比較之中。

### 研究遺留的待辦事項

- Kapitsa 必須重新固定版本（其二進位雜湊已變化），其單元格才能計入。
- 有 50 個單元格帶有未計畫的 r2 檔案，需要做出決定，然後重新審計。
- 為整個批次固定同一個 harness 提交（B2 混用了兩個）。
- 重新執行 B1 中 pb2 在 32K 與 64K turn-2 的輪次時間異常值。
- 執行 LM Studio，或將其從清單中移除。
- 在真實解碼視窗上測量 tool-chat 解碼（27 token 的回覆使目前 tok/s 失去意義）。

## 歷史

- 2026-10-19 的 27B 快照（TensorFold 1.1.0，llama.cpp b11721）：[RELEASE_016 快照](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_016_BENCHMARKS_2026-10-19.md)。已被上述 2026-11-04 至 2026-11-08 的比較取代。
- 0.1.5 快照：[RELEASE_015 效能實測](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_015_BENCHMARKS.md)。


---

<!-- guides/cli -->
---
title: CLI 參考
description: 每個 yunshu 指令、子指令與選項，以及全域旗標、JSON 模式與結束代碼。
---

`yunshu` 指令用來啟動與管理伺服器，也可以作為執行中伺服器的用戶端。執行 `yunshu --help` 或 `yunshu <command> --help` 可看到即時的說明文字；本頁列出每個指令的功能與可接受的選項。

## 全域選項

全域選項要放在指令名稱之前。

| 選項 | 說明 |
|---|---|
| `--url`、`-u` | 與伺服器通訊的指令所用的伺服器 URL。預設 `http://localhost:8000`。也會讀取環境變數 `YUNSHU_GATEWAY_URL`。 |
| `--json` | 機器可讀的輸出。有限執行的指令會在 stdout 印出單一 JSON 結果，進度與表格送到 stderr。失敗時印出 `{"error": "..."}` 並以非零狀態碼結束。 |
| `--version`、`-V` | 印出版本後結束。 |

```bash
yunshu --json model list
yunshu --url http://localhost:8001 --json complete "Hello"
```

在 `--json` 模式下，用法錯誤（未知的選項、缺少參數）也會以 JSON 錯誤物件輸出到 stdout。結束代碼並不一致：2 用於輸入與連線錯誤，1 用於操作失敗。`yunshu doctor` 在任何檢查失敗時以 1 結束。

當 CLI 自己的環境或設定檔中設定了 `YUNSHU_AUTH_TOKEN` 時，呼叫伺服器的指令會送出 `Authorization: Bearer <token>`。

## 指令總覽

| 分組 | 指令 |
|---|---|
| 開始使用 | `setup`、`doctor`、`pull`、`serve`、`service`、`chat`、`completion` |
| 伺服器與模型 | `model`（別名 `models`）、`config`、`status`、`top`、`launch`、`cache` |
| 評估與診斷 | `statusline`、`eval`、`bench`、`diagnose` |
| 推論（呼叫執行中的伺服器） | `complete`、`embed`、`tokenize`、`detokenize`、`rerank`、`classify`、`score`、`transcribe`、`speak`、`ocr`、`image`、`image-edit`、`image-variations`、`voices`、`cancel` |

## 開始使用

### `yunshu setup`

從本機的完整模型（模型目錄與 Hugging Face 快取）中選一個，或輸入要下載的 Hugging Face MLX 儲存庫，然後印出應該執行的 `yunshu serve` 指令。它不會啟動伺服器。需要互動式終端機；在 `--json` 模式或沒有終端機時，會以錯誤結束，並列出找到的模型與下一步。

### `yunshu doctor`

檢查這台 Mac 能否執行 Yunshu，並為每個問題印出修復方式。涵蓋的項目請見[安裝](/docs/getting-started/install)。

| 選項 | 說明 |
|---|---|
| `--model`、`-m` | 一併檢查此模型（路徑或 repo id）。預設為 `YUNSHU_MODEL` 設定。 |
| `--host` | 你將要服務的主機（用於連接埠檢查）。預設 `127.0.0.1`。 |
| `--port`、`-p` | 你將要服務的連接埠。預設 `8000`。 |
| `--no-metal` | 略過匯入 MLX 與 GPU 探測。 |

任何檢查失敗時結束狀態為 1。`--json` 回傳 `{version, ok, checks}`。

### `yunshu pull REPO_ID`

把 Hugging Face 模型下載到模型目錄。也可使用 `yunshu model pull`。

| 選項 | 說明 |
|---|---|
| `--dir`、`-d` | 下載到此目錄。 |
| `--revision`、`-r` | 分支、標籤或 commit。 |
| `--force` | 即使模型已在磁碟上也下載（只取得缺少或已變更的檔案）。 |

請見[模型](/docs/getting-started/models)。

### `yunshu serve [MODEL]`

啟動推論伺服器。模型可以用位置參數或 `--model` 指定；兩者給了不同的值會報錯。若既沒有設定模型也沒有設定模型目錄，互動式終端機會提示你選擇模型；否則指令會失敗並提示下一步。若參照符合模型目錄或 Hugging Face 快取中的模型，會服務該本機副本而不是下載。

| 選項 | 說明 |
|---|---|
| `--model`、`-m` | 模型路徑或 Hugging Face id（單一模型模式）。 |
| `--models-dir`、`-d` | 要掃描模型的目錄（多模型模式）。 |
| `--host`、`-h` | 綁定的主機。預設 `127.0.0.1`。綁定非本機主機又沒有 token 時會印出警告。 |
| `--port`、`-p` | 綁定的連接埠。預設 `8000`。 |
| `--uds` | 改在此 Unix domain socket 上服務而非 TCP；`--host` 與 `--port` 會被忽略。 |
| `--workers`、`-w` | worker 行程數。預設 `1`。 |
| `--max-memory` | 模型可用的 GPU 記憶體上限，例如 `32GB`，或 `disabled`。 |
| `--auth-token` | 請求必須帶上的 bearer token（設定 `YUNSHU_AUTH_TOKEN`）。 |
| `--mcp-config` | MCP 設定檔的路徑。 |
| `--hf-endpoint` | 自訂的 Hugging Face Hub 端點。 |
| `--http-proxy`、`--https-proxy`、`--no-proxy` | 下載時使用的代理設定。 |
| `--log-level` | `trace`、`debug`、`info`、`warning` 或 `error`。預設 `info`。 |
| `--startup-timeout` | 等待模型載入的最長秒數。 |
| `--slow-request-threshold` | 請求超過此秒數時記錄警告。 |
| `--drain-timeout` | 關閉時讓進行中請求完成的秒數。 |
| `--keep-alive-timeout` | 閒置連線保持開啟的秒數（0 表示停用）。 |
| `--max-request-size` | 請求本文大小上限（位元組）。 |
| `--server-header` | 在回應中送出 `Server: Yunshu`。 |
| `--reload` | 開發用的自動重新載入。 |
| `--no-console` | 不在引擎旁邊啟動主控台程序。 |
| `--console-port` | 主控台程序的連接埠。預設 `8100`（`YUNSHU_CONSOLE_PORT`）。 |
| `--config`、`-c` | 含 `YUNSHU_*` 設定的 TOML 檔案。 |
| `--set KEY=VALUE` | 覆寫任一設定；`YUNSHU_` 前綴可省略，可重複使用。未知的名稱會報錯並列出最接近的名稱。 |

旗標與 `--set` 的優先順序最高，高於環境變數與設定檔。載入之前，`serve` 會確認位址可以綁定，並執行與 `doctor` 相同的模型檢查；無法載入的模型仍會讓伺服器啟動，由 `GET /health/ready` 回報原因。使用 `--json` 時會先印出 `starting` 事件，之後行程持續執行；就緒狀態請看 `GET /health/ready`，而不是這個事件。所有設定請見[設定](/docs/guides/configuration)。

### `yunshu console`

單獨執行主控台程序：網頁主控台與文件、轉送引擎 API 的反向代理，以及記錄下來的歷史。它不載入 MLX。`yunshu serve` 會在引擎旁邊啟動一個；要監看另一台機器上的引擎，或想手動讓它持續執行時，就用這個指令。

| 選項 | 說明 |
|---|---|
| `--engine`、`-e` | 要監看並轉送的引擎網址。預設 `http://127.0.0.1:8000`（`YUNSHU_CONSOLE_ENGINE`）。 |
| `--host`、`-h` | 綁定主機。預設 `127.0.0.1`。 |
| `--port`、`-p` | 綁定連接埠。預設 `8100`。 |
| `--engine-token` | 讀取引擎所用的 Bearer 權杖（`YUNSHU_CONSOLE_ENGINE_TOKEN`，否則 `YUNSHU_AUTH_TOKEN`）。 |
| `--config`、`-c` | `YUNSHU_*` 設定的 TOML 檔。 |
| `--no-history` | 不記錄指標歷史與請求紀錄。 |

### `yunshu service`

以 launchd 在登入時執行 Yunshu，分成兩個 job：引擎與主控台程序（引擎重新啟動時主控台仍持續記錄）。子指令：`install`、`uninstall`、`start`、`stop`、`restart`、`status`、`logs`、`rotate-logs`。完整選項請見[服務](/docs/getting-started/service)頁面。

`yunshu service logs` 支援 `--follow`/`-f` 與 `--lines`/`-n`（預設 50）。`yunshu service install` 支援 `--no-start`（寫入 agent 但不啟動）；`--instance` 與 `--state-dir`（必須一起使用）會跑隔離的開發用 launchd label（`dev-*`）。`yunshu console --static-dir DIR` 從目錄提供 console 建置（開發與測試用）。

### `yunshu chat`

與執行中伺服器的互動式終端機對話。不支援 `--json`。

| 選項 | 說明 |
|---|---|
| `--model`、`-m` | 模型名稱。預設為伺服器列出的第一個模型，優先選擇已知的對話模型系列。 |
| `--url`、`-u` | 伺服器 URL。預設 `http://localhost:8000`。 |
| `--system`、`-s` | 系統提示詞。 |
| `--temperature`、`-t` | 取樣溫度。預設 `0.7`。 |
| `--max-tokens` | 最大輸出 token 數。預設 `2048`。 |
| `--thinking` | 啟用思考模式。 |
| `--no-stream` | 停用串流。 |

對話中可用：`/clear`、`/thinking`、`/model <name>`、`/help`、`/quit`（也可用 `/exit`、`/q`）。

### `yunshu completion SHELL`

印出 `zsh`、`bash` 或 `fish` 的 shell 自動完成腳本。它不會修改你的 shell 檔案。

```bash
mkdir -p ~/.zfunc
yunshu completion zsh > ~/.zfunc/_yunshu     # 在 compinit 之前把 ~/.zfunc 加入 fpath
yunshu completion bash > ~/.yunshu-completion.bash
yunshu completion fish > ~/.config/fish/completions/yunshu.fish
```

## 伺服器與模型

### `yunshu model`（別名 `models`）

| 子指令 | 用途 |
|---|---|
| `list` | 列出磁碟上的模型，或以 `--url` 列出伺服器上的模型。選項：`--dir`/`-d`、`--hf-cache`/`--no-hf-cache`、`--url`/`-u`。 |
| `pull REPO_ID` | 與 `yunshu pull` 相同。 |
| `info MODEL`（別名 `show`） | 顯示模型名稱或路徑的類型、大小、檔案數量與 `config.json` 主要欄位。 |
| `rm MODEL` | 依完整名稱移除已下載的模型。`--yes`/`-y` 略過確認（搭配 `--json` 時必須使用）。 |
| `load MODEL` | 在執行中的伺服器載入模型（`POST /v1/models/load`）。 |
| `unload MODEL` | 從執行中的伺服器卸載模型（`POST /v1/models/unload/{model_id}`）。 |
| `benchmark MODEL` | 在本機行程內執行生成效能測試（以 mlx-lm 載入模型，因此適用於文字模型；會使用 GPU）。選項：`--prompt-tokens`（128）、`--max-tokens`（256）、`--runs`/`-n`（3）、`--warmup`（1）。 |

`load` 與 `unload` 接受 `--url`/`-u`。

### `yunshu config`

顯示每個穩定設定的有效值與來源（`cli`、`env`、`file` 或 `default`），以及警告與網路搜尋供應商的健康狀態。

| 選項 | 說明 |
|---|---|
| `--all`、`-a` | 包含實驗性與內部設定。 |
| `--json` | 印出 JSON。 |
| `--config`、`-c` | 一併讀取此 TOML 檔案。 |

子指令：

| 子指令 | 用途 |
|---|---|
| `config set KEY VALUE` | 把設定存入 `~/.yunshu/config.toml`（或以 `--config`/`-c` 指定的檔案）。鍵名可省略 `YUNSHU_`；值會經過驗證。路徑類設定以絕對路徑儲存。 |
| `config unset KEY` | 從檔案中移除設定。 |
| `config path` | 印出使用者設定檔的位置。 |

### `yunshu status`

顯示伺服器健康狀態、GPU 與記憶體使用量、請求計數，以及伺服器列出的模型。選項：`--url`/`-u`。無法連線到伺服器時會以錯誤結束。

### `yunshu top`

與 `status` 相同，但以迴圈持續更新。選項：`--url`/`-u`、`--once`（印出一次快照後結束）、`--interval`（秒，預設 `2.0`，最小 `0.5`）。搭配 `--json` 時回傳一次快照。

### `yunshu launch [TOOL]`

為外部的程式碼工具設定好你的伺服器並啟動它。`TOOL` 可為 `claude`、`codex`、`opencode`、`pi`，或 `list`（預設），後者顯示這些工具及其是否已安裝。

| 選項 | 說明 |
|---|---|
| `--model`、`-m` | 要使用的模型。預設為伺服器所服務的模型。 |
| `--url`、`-u` | 伺服器 URL。 |
| `--api-key`、`-k` | 交給工具的 API 金鑰。 |
| `--effort` | Claude Code 的推理強度（`low`、`medium`、`high` 等）。 |
| `--statusline` / `--no-statusline` | Claude Code：在狀態列顯示即時引擎狀態（預設開啟），除非你已有自己的狀態列。 |
| `--dry-run` | 只印出設定，不寫入也不啟動工具。 |

### `yunshu cache`

檢視並清理 SSD 前綴快取（僅限已啟用的快取）。

| 子指令 | 用途 |
|---|---|
| `status` | 每個快取的大小、上限與問題。不做任何變更。 |
| `gc` | 找出被截斷、損毀與舊格式的項目、孤立的暫存檔、過期的命名空間，以及超過容量上限的項目。除非加上 `--apply`，否則只回報。 |

## 評估與診斷

### `yunshu diagnose`

| 子指令 | 用途 |
|---|---|
| `gpu` | GPU 與 Metal 能力的詳細資訊（在本機使用 MLX）。 |
| `server` | 檢查執行中伺服器的健康狀態與統計。選項：`--url`/`-u`。 |
| `bundle` | 寫出本機診斷檔：版本、平台、套件版本、已遮蔽機密的設定、doctor 檢查結果、SSD 快取狀態，以及服務記錄中最近的錯誤行。不含提示詞、補全內容與模型權重，也不會上傳。選項：`--output`/`-o`（預設 `./yunshu-diagnostics-<time>.json`）、`--host`、`--port`/`-p`。 |

### `yunshu eval BENCHMARK`

對執行中的伺服器執行準確度基準測試。`BENCHMARK` 可為 `mmlu`、`gsm8k`、`hellaswag`、`truthfulqa`、`humaneval`、`arc`、`piqa`，`all` 表示全部執行，`list`（預設）則列出可用項目。

| 選項 | 說明 |
|---|---|
| `--url`、`-u` | 伺服器 URL。 |
| `--model`、`-m` | 要評估的模型。 |
| `--sample`、`-n` | 取樣數量（0 表示使用完整資料集）。 |
| `--quick`、`-q` | 以 50 筆樣本快速執行。 |

### `yunshu bench`

| 子指令 | 用途 |
|---|---|
| `roofline` | 在本機 GPU 上量測矩陣乘法 roofline。選項：`--min`（64）、`--max`（8192）、`--dtype`（`float16`）、`--steps`（8）。 |
| `memory` | 顯示 Apple Silicon 記憶體配置與 MLX 配置量。 |
| `inference` | 本機行程內的生成效能測試。選項：`--model`/`-m`（路徑）、`--prompt-len`、`--max-tokens`、`--requests`/`-n`、`--batch`/`-b`、`--warmup`。 |
| `latency` | 對執行中伺服器量測延遲。選項：`--url`/`-u`、`--model`/`-m`、`--prompt`（32 token）、`--max-tokens`（64）、`--requests`/`-n`（10）。 |
| `throughput` | 對執行中伺服器量測吞吐量。選項：`--url`/`-u`、`--model`/`-m`、`--concurrency`/`-c`（4）、`--requests`/`-n`（20）、`--max-tokens`（128）。 |

`roofline`、`memory` 與 `inference` 會在本機執行 MLX 並使用 GPU；伺服器正忙於實際工作時請勿執行。

### `yunshu statusline`

為程式碼代理的狀態列印出單行引擎狀態：進行中請求的 prefill 進度、解碼速度與前綴快取命中，資料來自 `GET /v1/yunshu/status`。以管線輸入時，會從 stdin 讀取 Claude Code 的 session JSON。伺服器無法連線時會印出簡短標記而不是失敗。選項：`--url`/`-u`、`--api-key`/`-k`（或 `YUNSHU_API_KEY`）。

## 推論指令

這些指令向執行中的伺服器送出單一請求（`--url`/`-u`，預設 `http://localhost:8000`）。它們是非互動式的，可搭配 `--json`。`--model`/`-m` 預設為 `local`，在單一模型模式下可被接受。

| 指令 | 請求 | 備註 |
|---|---|---|
| `complete PROMPT` | `POST /v1/chat/completions` | 選項：`--max-tokens`（256）、`--temperature`/`-t`（0.7）、`--system`/`-s`。 |
| `embed TEXT` | `POST /v1/embeddings` | 印出維度與前幾個值；`--json` 回傳完整向量。 |
| `tokenize TEXT` | `POST /v1/tokenize` | 印出 token 數；`--ids` 回傳 token id。 |
| `detokenize TOKEN...` | `POST /v1/detokenize` | 把 token id 轉回文字。 |
| `rerank QUERY DOC...` | `POST /v1/rerank` | `--top-n` 限制結果數量（0 表示全部）。 |
| `classify TEXT LABEL...` | `POST /v1/classify` | 針對給定標籤的零樣本分類。 |
| `score TEXT1 TEXT2` | `POST /v1/score` | `--type` 為 `cosine`（預設）、`dot` 或 `euclidean`。 |
| `transcribe FILE` | `POST /v1/audio/transcriptions` | `--language`/`-l`；`--translate` 改用 `POST /v1/audio/translations`。 |
| `speak TEXT` | `POST /v1/audio/speech` | 必須指定 `--out`/`-o`（.wav 或 .mp3）；`--voice`（預設 `ethan`）。 |
| `voices` | `GET /v1/audio/voices` | 列出 `speak` 可用的聲音。 |
| `ocr FILE` | `POST /v1/ocr` | 從圖片檔擷取文字。 |
| `image PROMPT` | `POST /v1/images/generations` | 必須指定 `--out`/`-o`；`--model`/`-m`（預設 `Z-Image-Turbo-MLX-4bit`）、`--size`（`1024x1024`）、`--steps`（4）。 |
| `image-edit FILE PROMPT` | `POST /v1/images/edits` | 必須指定 `--out`/`-o`；`--model`/`-m`、`--steps`、`--strength`（0.8）。 |
| `image-variations FILE` | `POST /v1/images/variations` | 必須指定 `--out`/`-o`；`--model`/`-m`、`--steps`。 |
| `cancel [REQUEST_ID]` | `POST /v1/cancel` | 取消單一生成，或以 `--all` 取消全部。 |

```bash
yunshu complete "Explain unified memory in one sentence." --max-tokens 80
yunshu tokenize "hello world" --ids
yunshu rerank "apple pie recipe" "How to bake a pie" "Stock prices today"
yunshu speak "Hello from Yunshu" --out hello.wav
```

請求能否成功取決於已載入的模型與已安裝的額外套件；請見[模型支援](/docs/guides/model-support)。

## 相關頁面

- [快速開始](/docs/getting-started/quickstart)
- [設定](/docs/guides/configuration)
- [疑難排解](/docs/guides/troubleshooting)


---

<!-- guides/clients -->
---
title: 連接用戶端
description: 將 OpenAI 與 Anthropic SDK、curl、Open WebUI 與程式碼代理指向本機的 Yunshu 伺服器，並確認伺服器狀態正常。
---

Yunshu 在 `/v1` 下提供 OpenAI API，並在 `/v1/messages` 提供 Anthropic Messages API。只要能設定 base URL 的工具都可以使用。

| | 值 |
|---|---|
| OpenAI base URL | `http://127.0.0.1:8000/v1` |
| Anthropic base URL | `http://127.0.0.1:8000`（SDK 會自動附加 `/v1/messages`） |
| API 金鑰 | 任意字串；若伺服器設有 token 或 API 金鑰，則使用該憑證 |
| 模型名稱 | 單模型模式（`yunshu serve -m ...`）：任何名稱都會對應到所服務的模型。多模型模式（`--models-dir`）：使用 `GET /v1/models` 回傳的 id |

使用 `--auth-token` 時，金鑰可以用 `Authorization: Bearer <token>`（OpenAI 用戶端）或 `x-api-key: <token>`（Anthropic 用戶端）傳入。請見[驗證與 API 金鑰](/docs/guides/auth-and-keys)。

<Callout type="warn">
`yunshu serve` 預設綁定 `127.0.0.1`。若要從其他機器或 Docker 容器連線，請以 `--host 0.0.0.0 --auth-token <secret>` 啟動。在非 loopback 位址上未設定 token 就提供服務時，會印出警告。
</Callout>

## 呼叫伺服器

<Tabs items={["curl", "OpenAI Python", "OpenAI JavaScript", "Anthropic Python"]}>
<Tab value="curl">

```bash
curl http://127.0.0.1:8000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{"model": "local", "messages": [{"role": "user", "content": "Hello"}]}'
```

</Tab>
<Tab value="OpenAI Python">

```python
from openai import OpenAI

client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="local")
r = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Explain MLX in one sentence."}],
    # Passed to chat templates that support it.
    extra_body={"reasoning_effort": "medium"},
)
print(r.choices[0].message.content)
```

</Tab>
<Tab value="OpenAI JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://127.0.0.1:8000/v1", apiKey: "local" });
const r = await client.chat.completions.create({
  model: "local",
  messages: [{ role: "user", content: "Hello" }],
});
console.log(r.choices[0].message.content);
```

</Tab>
<Tab value="Anthropic Python">

```python
import anthropic

client = anthropic.Anthropic(base_url="http://127.0.0.1:8000", api_key="local")
msg = client.messages.create(
    model="local",
    max_tokens=512,
    messages=[{"role": "user", "content": "Hello"}],
)
print(msg.content[-1].text)
```

</Tab>
</Tabs>

支援串流、工具、`response_format`（JSON schema）、`stop`、`logprobs` 與 `seed`；請見 [Chat Completions](/docs/api/chat-completions)、[Responses](/docs/api/responses) 與 [Messages](/docs/api/messages)。推理模型的思考輸出會與答案分開串流，位於 `delta.reasoning_content`。

## 程式碼代理

<Tabs items={["Claude Code", "Codex, OpenCode, Pi", "Cline and Roo Code", "Continue"]}>
<Tab value="Claude Code">

Claude Code 使用 Anthropic API：

```bash
ANTHROPIC_BASE_URL=http://127.0.0.1:8000 ANTHROPIC_AUTH_TOKEN=local ANTHROPIC_MODEL=local claude
```

</Tab>
<Tab value="Codex, OpenCode, Pi">

`yunshu launch <tool>` 會寫入該工具的設定，使其指向正在執行的伺服器。`yunshu launch list` 會列出已安裝的工具。

</Tab>
<Tab value="Cline and Roo Code">

選擇提供者「OpenAI Compatible」，base URL 填 `http://127.0.0.1:8000/v1`，金鑰任意，模型填 `local`。

</Tab>
<Tab value="Continue">

新增一個模型項目：`provider: openai`、`apiBase: http://127.0.0.1:8000/v1`、`model: local`。

</Tab>
</Tabs>

`yunshu launch claude` 也會設定模型的實際 context window，並在你沒有自己的狀態列時，把 `yunshu statusline`（預填進度、解碼速度、最近一次快取命中）加到 Claude Code 的狀態列。伺服器端的 `web_search` 與 `web_fetch`、MCP connector，以及各代理支援的內容，請見[程式代理與 SDK](/docs/guides/agents)與[伺服器工具](/docs/api/server-tools)。

代理會送出冗長且重複的提示詞。前綴快取會重用共同的部分，所以第一輪之後只需預填新增的 token（[提示詞快取](/docs/guides/prompt-caching)）。

## Open WebUI

<Steps>
<Step>

啟動 Yunshu，讓容器可以連到它：`yunshu serve -m <model> --host 0.0.0.0 --auth-token <secret>`。只有 Open WebUI 在 Docker 中執行時才需要這一步。

</Step>
<Step>

在 Open WebUI 開啟「設定」，再選「連線」，然後選 OpenAI API。

</Step>
<Step>

URL 填 `http://host.docker.internal:8000/v1`（Docker）或 `http://127.0.0.1:8000/v1`（原生），金鑰填你的 secret。

</Step>
</Steps>

Yunmo 是另一個使用者專案，它的 `llm_adapter` 相容 OpenAI：把 `base_url` 設為 `http://127.0.0.1:8000/v1` 即可。

## 檢查伺服器

| 端點 | 驗證 | 用途 |
|---|---|---|
| `GET /health` | 無 | 存活狀態，以及是否已載入模型 |
| `GET /health/ready` | 無 | 在已載入模型或已註冊的隨需載入模型、且使用中的 GPU 記憶體低於統一記憶體 95% 時回傳 200；否則回傳 503 |
| `GET /version` | 無 | 已安裝的 Yunshu 版本 |
| `GET /v1/models` | 有設定時需 token | 所服務的模型 |
| `GET /metrics` | 有設定時需 token | Prometheus 指標 |

`yunshu status` 會在命令列印出相同資訊。

## 相關文件

- [傳輸方式](/docs/guides/transports)：WebSocket 與 Unix socket 存取。
- [網路搜尋](/docs/guides/web-search)與 [Tavily 相容 API](/docs/guides/tavily)。
- [Decisions](/docs/api/decisions)、[Evals](/docs/api/evals) 與 [Stored completions](/docs/api/stored-completions)（搭配一般 OpenAI SDK 使用 `store=True`）。


---

<!-- guides/code-execution -->
---
title: 程式碼執行
description: 啟用 Anthropic code_execution 工具，讓模型撰寫的指令在你的 Mac 上於 sandbox-runtime 內執行，並了解其容器、檔案與限制。
---

Anthropic 的 `code_execution_20250522`、`_20250825`、`_20260120` 與 `_20260521` 工具會在這台機器上、Anthropic 的 [sandbox-runtime](https://github.com/anthropics/sandbox-runtime)（`srt`）內執行。此功能預設為關閉。沙箱如何建構，請見[程式碼執行沙箱](/docs/internals/code-execution-sandbox)。

## 啟用

<Steps>
<Step>

安裝沙箱執行環境。需要 Node 22.12 或更新版本，`srt` 是選用的相依套件。

```bash
npm install -g @anthropic-ai/sandbox-runtime
```

</Step>
<Step>

啟用程式碼執行並啟動服務：

```bash
yunshu serve -m <model> --set code_execution=1
```

</Step>
<Step>

執行 `yunshu doctor`，查看「code execution」那一列，會顯示 `srt` 版本與自我測試結果。

</Step>
</Steps>

| 設定 | 預設 | 意義 |
|---|---|---|
| `YUNSHU_CODE_EXECUTION` | `false` | 提供此工具。關閉時：宣告它的請求會得到指出此設定的 `400`。開啟但沒有 `srt` 時：回傳 `503`（`api_error`）並附安裝指令。指令絕不會在 `srt` 之外執行。 |
| `YUNSHU_CODE_EXECUTION_ROOT` | `~/.yunshu/sandbox` | 每個容器一個子目錄，權限 0700。 |
| `YUNSHU_CODE_EXECUTION_TIMEOUT` | `60.0` 秒 | 每次呼叫的牆上時間（同時是 CPU 時間上限）；逾時為 `execution_time_exceeded`。 |
| `YUNSHU_CODE_EXECUTION_MEMORY_MB` | `2048` | 該次呼叫整個行程群組的常駐記憶體，每 100 ms 取樣一次；超過就終止該呼叫。 |
| `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW` | 未設定 | 沙箱可連線的主機，以逗號分隔（`example.com`、`*.example.com`、`host:443`）。未設定：完全沒有網路，包含 loopback。 |
| `YUNSHU_CODE_EXECUTION_TTL_MIN` | `20.0` | 容器閒置多少分鐘後，連同其檔案一併刪除。 |

## 從 Messages API 使用

在 [Messages](/docs/api/messages) 請求中宣告此工具，不需要 beta 標頭：

```json
{"type": "code_execution_20250825", "name": "code_execution"}
```

模型會得到兩個子工具：`bash_code_execution` 與 `text_editor_code_execution`（`view`、`create`、`str_replace`）。回應會依 Anthropic 文件帶有 `server_tool_use` 區塊，以及 `bash_code_execution_tool_result` 或 `text_editor_code_execution_tool_result` 區塊。串流的方式相同：子工具輸入以 `input_json_delta` 傳送，每個結果區塊則整個放在一個 `content_block_start` 中。回應也帶有 `container: {id, expires_at}`（串流時位於 `message_delta.delta`）。

- **容器。** 將 `container: "<id>"`（或 `{id}`）傳回來即可保留工作目錄。未知或已過期的 id 會是 `400`。容器在閒置 TTL 後刪除，總量上限為 2 GiB（最舊的先刪）。
- **檔案。** `container_upload` 內容區塊會把 [Files API](/docs/api/files) 的檔案複製到工作目錄。每次 bash 呼叫都有全新的 `$OUTPUT_DIR`；其頂層檔案會變成 Files API 項目，以 `bash_code_execution_output {file_id}` 回傳（用 `GET /v1/files/{id}/content` 下載）。
- **輸出限制。** stdout 與 stderr 各自在 64 KiB 截斷（並標記）。stdout 與 stderr 合計超過 1 MiB 的呼叫會被終止（`output_file_too_large`）。背景行程會隨該次呼叫結束。指令看到的環境變數只有 `PATH`、`HOME`（容器）、`TMPDIR`、`OUTPUT_DIR` 與地區設定變數，絕不包含伺服器的環境。

## Python、REPL 狀態與程式化工具呼叫

`20250522` 只有一個 Python 工具（`code_execution`，每次呼叫全新行程）。`20250825` 有 bash 與文字編輯器（客戶端工具在 `allowed_callers` 列出 code execution 呼叫者時再加 Python，同樣每次全新）。`20260120` 與 `20260521` 三者皆有，且 Python 行程與容器同生命週期：變數與 import 在呼叫之間保留。逾時、記憶體超限、輸出超過 1 MiB、閒置 10 分鐘、刪除容器，或超過四個容器各持有一個行程時，行程會被殺掉並乾淨地重啟。

工具若設 `"allowed_callers": ["code_execution_20260120"]`，就成為直譯器中的 `async` Python 函式。程式碼 await 它時，該回合以 `stop_reason: "tool_use"` 結束，每個呼叫一個帶 `caller: {type, tool_id}` 的 `tool_use` 區塊。帶著 `container` 把結果送回，回應就接著給出 `code_execution_tool_result`。cell 最多等候 270 秒；單一 cell 最多 256 次呼叫。

## OpenAI Responses 與容器

同一個設定下，[Responses](/docs/api/responses) 請求可宣告 `{"type": "code_interpreter", "container": {"type": "auto"}}`（或 `cntr_` id）與託管的 `{"type": "shell", "environment": {"type": "container_auto"}}`。回應有 `code_interpreter_call`、`shell_call`、`shell_call_output` 項目、對應的串流事件，以及程式碼產生的檔案的 `container_file_citation` 註解；背景模式也可用。容器有 OpenAI containers API（`/v1/containers`，含檔案）；`expires_after`、`memory_limit`、`network_policy` 只能縮小上述設定。詳見[伺服器端工具](/docs/api/server-tools)。

## 沙箱允許什麼

- **寫入：** 僅限容器目錄。
- **讀取：** `/Users`、`/Volumes`、`/home` 與容器根目錄一律拒絕；只有該容器本身與 Python 直譯器的前綴會被重新允許。你的家目錄、金鑰、`~/.yunshu` 與其他容器都讀不到。
- **網路：** 除非列出，否則沒有。loopback 永遠無法連線，且允許的名稱無法解析到私有網段。
- **其他：** Unix socket、Apple Events 與 `open` 皆關閉。

違規事件只以中繼資料記錄（容器 id、回傳碼、位元組數）；指令、輸出與檔案內容絕不寫入日誌。

<Callout type="warn">
允許的網域清單不會檢查流量內容。允許像 `github.com` 這樣範圍廣的主機仍可能洩漏資料，所以請讓清單盡量短。
</Callout>

## 與 Anthropic 容器的差異

- 是 macOS，不是 Linux x86_64。Python 是 Yunshu 所使用的直譯器（僅標準函式庫，沒有 pandas 或 numpy）。
- 沒有 Content Credentials。
- 沒有 Content Credentials、容器 skills 與 OpenAI 的 `programmatic_tool_calling`。
- 沙箱在 macOS 的 `sandbox-exec` 下執行，Apple 已將它標為棄用；`srt` 是 0.0.x 版本（已測試：0.0.81）。


---

<!-- guides/configuration -->
---
title: 設定
description: 所有 YUNSHU_* 設定的型別與預設值，由設定登錄檔產生。
---

每個 Yunshu 設定都是登錄在 `python/yunshu_engine/settings.py` 的 `YUNSHU_*` 名稱，各有唯一的型別、預設值與解析規則。
除此之外沒有任何程式碼會讀取 `YUNSHU_*` 環境變數。

## 設定值的來源

優先順序由高到低：

1. `yunshu serve` 的旗標與 `--set KEY=VALUE`（可重複；`KEY` 可省略 `YUNSHU_` 前綴，例如 `--set mtp_block_size=4`），
2. 行程的環境變數，
3. TOML 設定檔：`yunshu serve --config yunshu.toml` 或 `YUNSHU_CONFIG=yunshu.toml`，
4. 下表列出的預設值。

設定檔是一組 `KEY = value`，可以平放，也可以放在任意表格（table）之下（表格名稱會被忽略，鍵可用短名或全名）：

```toml
model = "~/models/Qwen3.8-27B-4bit"

[server]
default_max_tokens = 1024

[voice]
YUNSHU_REALTIME_SILENCE_MS = 400
```

布林值接受 `1/true/yes/on` 與 `0/false/no/off`。無法解析的值會在啟動時當成錯誤，並列出所有有問題的設定。
未登錄的 `YUNSHU_*` 名稱會被忽略，並以警告指出最接近的已登錄設定。

`yunshu config` 會印出每個穩定設定的有效值與來源（`cli`、`env`、`file`、`default`）；`--all` 會加上實驗性與內部設定，
`--json` 輸出 JSON，`--config FILE` 會納入設定檔。

## 穩定性

- **stable**：受支援的部署設定。
- **experimental**：暫時性。每一項都註明由哪一項量測決定去留與加入時間；量測完成後，勝出者成為預設，旗標與落敗的程式路徑會被刪除。同一時間最多 8 項。
- **internal**：除錯輔助。

下表的說明直接來自設定登錄檔，所有語言都以英文呈現。

## 穩定設定

### model

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_MODEL` | path | unset | restart | Model path or Hugging Face id served in single-model mode; every requested model name maps to it. |
| `YUNSHU_MULTI_MODEL` | bool | off | restart | Multi-model mode: discover models under YUNSHU_MODELS_DIR and load them on demand. Ignored when YUNSHU_MODEL is set. |
| `YUNSHU_MODELS_DIR` | path | unset | restart | Directory of model folders for multi-model mode (each folder name is a model id). Unset: ~/.yunshu/models (also where `yunshu pull` downloads to). |
| `YUNSHU_HF_CACHE_MODELS` | bool | on | live | Multi-model mode: also offer models already in the Hugging Face cache (the models directory wins on name clashes). `yunshu serve -m org/name` uses a cached copy either way. |
| `YUNSHU_MODEL_TTL_SECONDS` | float | unset | restart | Multi-model mode: unload a model idle for this many seconds. Unset: never. |
| `YUNSHU_ALLOW_AUTO_LOAD` | bool | off | live | Multi-model mode: let audio requests load a model that is not loaded yet (otherwise they are rejected). |
| `YUNSHU_MAX_LORAS` | int | 4 | reload | Maximum LoRA adapters kept loaded (text models). |
| `YUNSHU_TRUST_REMOTE_CODE` | bool | off | reload | Allow Hugging Face tokenizers/processors that need trust_remote_code. |
| `YUNSHU_WARM_PROMPTS` | str | unset | reload | Prompts prefilled at startup to warm the prefix cache: '\|\|'-separated text or file paths. |

### server

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_CONFIG` | path | unset | restart | TOML config file with YUNSHU_* settings (lower precedence than the environment). |
| `YUNSHU_DECODE_TAIL_SHARE` | float | 0.5 | reload | Share of GPU time running decode rows are owed after each prefill atom of a newcomer, once every running row is past its first 48 tokens: a prefill atom of t seconds earns decode time share*t (0.075-4 s). The same GPU time is divided either way. Measured on the 27B with one long reply running and a cold 4K / 32K prompt arriving (3 interleaved reps): 0.25 gave the running row 5.0 tok/s and the newcomer first token after 7.0 s / 58 s; 0.5 gave 7.6 tok/s at 7.8 s / 68 s; 1.0 gave 11.2 tok/s at 9.8 s (4K). Lower favors the newcomer's first token, higher the running reply. |
| `YUNSHU_AUXILIARY_SCHEDULING` | bool | on | reload | Deprioritize captured opencode title requests: interactive VLM jobs run first; auxiliary rows pause between GPU slices and never read or write APC. Unknown fingerprints keep normal scheduling. Defaults on only with engaged qualified batch-invariant kernels; other backends require explicit opt-in. Disable to restore ordinary scheduling. In-flight GPU operations cannot be interrupted. |
| `YUNSHU_QUEUE_LIMIT` | int | 64 | live | Generation requests (chat, completions, messages, responses) in flight at once, running and waiting together. The next one is refused at once with 429, `Retry-After` and the queue depth in `error.x_yunshu` instead of waiting without bound. 0 = no limit. |
| `YUNSHU_MEMORY_PRESSURE_REJECT` | float | 0.95 | live | Share of the Metal working set (MLX active memory / recommended working set) above which, while other requests are running, a new generation request is refused with 503 and `Retry-After` (it would OOM the process). An idle server never refuses. 0 = off. |
| `YUNSHU_ORPHAN_GRACE_SECONDS` | float | 120.0 | live | Orphan adoption: when a client disconnects mid-generation (an agent timing out a long streamed reply), keep that generation running for this many seconds instead of cancelling it. An identical request (same model, messages, tools, constraints and sampling parameters, streaming or not) arriving inside the window is attached to it: the tokens already generated replay at once and the rest follow live, so the work is never repeated. Two live identical requests are never merged. A cancel request or deadline still stops at once; unadopted generations are cancelled when the window ends. Observed: Claude Code re-sends 5 s to 14 min after cutting a stream. 0 = cancel at disconnect. |
| `YUNSHU_ORPHAN_MAX` | int | 2 | live | Most orphaned generations kept at once (each still holds its decode row and KV until adopted or expired; the oldest is cancelled beyond this). |
| `YUNSHU_SAMPLING_DEFAULTS` | `model` \| `api` | model | reload | Where a request that omits a sampling parameter gets it: 'model' (the model's published per-mode recommendation, then its generation_config.json, then the API default) or 'api' (the official API default only: temperature 1.0, top_p 1.0, others off). A value in the request always wins. |
| `YUNSHU_DEFAULT_MAX_TOKENS` | int | 0 | reload | Operator cap on the output length of a chat / responses request that omits max_tokens / max_output_tokens. 0 (default) = the model's output limit (262144, Qwen3.8 card: thinking mode), which the API specs define as the default; the context window still clamps it (x_yunshu.budget reports the effective value and its source). A positive value lowers the default only; an explicit request value is never capped by it. |
| `YUNSHU_MAX_PREFILL_TOKENS` | int | 0 | live | Reject prompts longer than this many tokens (0: no limit beyond the model context). |
| `YUNSHU_STARTUP_TIMEOUT` | float | 300.0 | restart | Seconds to wait for the model to load before startup fails. |
| `YUNSHU_DRAIN_TIMEOUT` | float | 30.0 | restart | Seconds to wait for in-flight requests on shutdown. |
| `YUNSHU_KEEP_ALIVE_TIMEOUT` | int | 5 | restart | Seconds an idle HTTP connection stays open. |
| `YUNSHU_UDS` | path | unset | restart | Serve on this Unix domain socket instead of a TCP port (same app; curl --unix-socket, httpx uds=). |
| `YUNSHU_WS_MAX_INFLIGHT` | int | 16 | live | Text WebSocket (/v1/stream, wss /v1/responses): maximum concurrent requests per connection. |
| `YUNSHU_WS_PING_INTERVAL` | float | 15.0 | live | Text WebSocket: seconds between server heartbeat pings (0 disables). |
| `YUNSHU_WS_SEND_QUEUE` | int | 256 | live | Text WebSocket: outbound events buffered per connection before generation is paused (backpressure). |
| `YUNSHU_MAX_REQUEST_SIZE` | int | 33554432 (32 MiB) | restart | Maximum request body size in bytes. Default 32 MiB = the Anthropic Messages API request limit (32 MB, API errors reference), the largest agent client (Claude Code) request the engine is meant to take; longer sessions with base64 images or large tool results used to fail with 413 at the former 10 MiB. |
| `YUNSHU_PROGRESS_INTERVAL_S` | float | 2.0 | live | Streaming chat/completions: seconds between `: yunshu-progress` SSE comments (queue / prefill progress, ETA) before the first token; 0 turns them off. Strict SSE clients ignore comment lines. |
| `YUNSHU_SLOW_REQUEST_THRESHOLD` | float | 30.0 | restart | Log a warning for requests slower than this many seconds. |
| `YUNSHU_CORS_ORIGINS` | str | http://localhost:3000,http://localhost:8000 | live | Comma-separated allowed CORS origins ('*' for any). Also checked for the Realtime WebSocket Origin header. |
| `YUNSHU_RESPONSE_CACHE` | bool | off | restart | Cache identical non-streaming responses in memory. |
| `YUNSHU_BATCH_MAX_ITEMS` | int | 100000 | live | Batch API: maximum requests per batch (also capped by the protocol limits: 50,000 OpenAI, 100,000 Anthropic). |
| `YUNSHU_BATCH_TIMEOUT` | float | 0.0 | live | Batch API: timeout in seconds for each request a batch runs (0: no timeout); a request that times out is recorded as failed. |
| `YUNSHU_ALLOW_LOCAL_FILES` | bool | off | live | Allow requests to reference any local file path (default: only under YUNSHU_MEDIA_DIR). |
| `YUNSHU_MEDIA_DIR` | path | unset | live | Directory local media paths must live under. Unset: $TMPDIR/yunshu_media. |
| `YUNSHU_FILES_DIR` | path | unset | live | Directory of the local Files / Batch API store. Unset: ~/.yunshu/files. |
| `YUNSHU_FILES_MAX_BYTES` | int | 536870912 (512 MiB) | live | Files API: maximum size of one uploaded file in bytes (default 512 MB). |
| `YUNSHU_FILES_TTL_DAYS` | float | unset | live | Files API: delete uploaded files after this many days. Unset: keep forever. |
| `YUNSHU_FILES_MAX_TOTAL_BYTES` | int | 0 | live | Files API: total bytes the store may hold; an upload that would exceed it fails with 413 storage_quota_exceeded (expired files are reaped first). 0: unlimited. |
| `YUNSHU_EVALS_DIR` | path | unset | restart | Directory of the local Evals API JSON store. Unset: ~/.yunshu/evals. |
| `YUNSHU_CONVERSATIONS_DIR` | path | unset | live | Directory of the Conversations API store (JSON, one file per conversation). Unset: ~/.yunshu/conversations. |
| `YUNSHU_CHAT_COMPLETIONS_DIR` | path | unset | restart | Directory of stored chat completions (store=true; JSON, one file per completion). Unset: ~/.yunshu/chat_completions. |
| `YUNSHU_CHAT_COMPLETIONS_MAX` | int | 5000 | restart | Stored chat completions kept; the oldest are evicted past this count. |
| `YUNSHU_CONVERSATION_MAX_ITEMS` | int | 10000 | live | Conversations API: maximum number of items one conversation may hold. |
| `YUNSHU_COMPACT_MAX_TOKENS` | int | 2048 | live | Responses compaction: maximum tokens of the model-written summary. |
| `YUNSHU_GIL_SWITCH_MS` | float | 0.5 | reload | Serving process: how long (ms) a Python thread may hold the GIL before another thread that wants it gets it. CPython's 5 ms made the event loop wake up to 5 ms late while the generation thread was running Python (Qwen3.8-27B decode: loop wake-up lag p99 5.3 ms, 0.5 ms gives 2.0 ms; short-prompt TTFT -1.4 ms; tokens/s unchanged). Scheduling only, output unchanged. 0 = CPython default. |

### auth

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_HOST` | str | 127.0.0.1 | restart | Bind host of `yunshu serve` (`--host` wins). 127.0.0.1 serves this Mac only; 0.0.0.0 also serves the local network (set YUNSHU_AUTH_TOKEN then). |
| `YUNSHU_AUTH_TOKEN` | str | unset | live | Bearer token. When set, every request except health/version/docs needs it; unset: inference is open and operational endpoints are denied. |
| `YUNSHU_ADMIN_WRITE_EXEC_SETTINGS` | bool | off | live | Let `PATCH /v1/yunshu/config` (the console settings editor) change settings that run host code or touch arbitrary host paths: every path setting, YUNSHU_MCP_SERVERS (stdio commands), YUNSHU_TRUST_REMOTE_CODE, YUNSHU_CODE_EXECUTION, YUNSHU_ALLOW_LOCAL_FILES. Off (default): they are read-only over HTTP (403 `exec_setting_read_only`); edit the config file or `yunshu config set` on the host instead. Not writable over HTTP itself. |
| `YUNSHU_AUTH_DISABLED` | bool | off | live | Disable auth entirely (operational endpoints open too). Local development only. |
| `YUNSHU_ACTOR_IDENTITY` | str | owner | live | Identity recorded for authenticated requests in the audit log. |
| `YUNSHU_RATE_LIMIT_RPM` | int | 0 | restart | Per-client request rate limit in requests per minute; 0 (default) turns rate limiting off. A local single-user engine has no need for it; set it when the server is exposed to other machines. |
| `YUNSHU_TRUSTED_PROXIES` | list | unset | restart | Comma-separated proxy IPs whose X-Forwarded-For header is trusted. |
| `YUNSHU_ALLOWED_HOSTS` | list | unset | live | Comma-separated Host names this server answers, besides loopback names. Empty (default): a server bound to a loopback address answers only loopback Host headers (localhost, 127.0.0.1, [::1]; this stops DNS rebinding) and one bound to 0.0.0.0 checks nothing. Set it to turn the check on for any bind address; '*' turns it off. |

### memory

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_FOOTPRINT_SAMPLE_MS` | int | 0 | restart | Sample this process's phys_footprint every N ms on a background thread and export the peak as yunshu_process_footprint_bytes on /metrics (the memory benchmarks set 20). 0 (default) = off. |
| `YUNSHU_MAX_MEMORY_GB` | gb | unset | restart | Memory ceiling in GiB (multi-model mode, and the VLM runner's load-time budget and request admission: a request waits in the queue instead of growing past the ceiling), e.g. '48' or '48GB'; 'disabled' turns the enforcer off. Unset: 80% of unified memory. |
| `YUNSHU_MEMORY_ADMISSION` | bool | on | reload | VLM runner: hold a new request in the queue while the host has no memory headroom for its KV and prefill workspace (live macOS available memory + reclaimable MLX buffers, kernel pressure level, swap growth, and the YUNSHU_MAX_MEMORY_GB ceiling), shed APC RAM entries (to SSD where configured) when available memory falls below the reserve, and at load shrink the APC budget to fit weights + reserve + minimum KV (refusing with a clear error only when even that does not fit). The first request of an idle server is always admitted. Scheduling only: outputs are unchanged, and the held reason is reported in `x_yunshu.reasons.queue`, the console queue and `/metrics`. 0 = off. |
| `YUNSHU_MEMORY_RESERVE_GB` | float | unset | reload | Memory the admission gate keeps free for macOS (page cache, compressor, other apps) in GiB. Unset: 5% of physical RAM, at least 4 GiB (128 GiB machine: 6.4; 16 GiB: 4). Also the line below which APC RAM entries are shed. |
| `YUNSHU_PREFILL_STEP_SIZE` | int | 2048 | live | Text engine: prompt tokens per prefill forward pass; lower it to cap the prefill activation peak on small-memory machines. |
| `YUNSHU_MEM_PRESSURE_THRESHOLD` | float | 85.0 | reload | Text engine: evict prefix-cache entries above this memory use (percent, or a fraction &lt;= 1). |

### cache

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_PREFIX_MAX_ENTRIES` | int | 64 | reload | Text engine: prefix KV cache entries. |
| `YUNSHU_PREFIX_HOT_LIMIT` | int | 0 | reload | Text engine: keep only this many prefix KV entries full precision and store older ones 4-bit in RAM (lossy on reuse; memory vs quality). 0 = every entry full precision. |
| `YUNSHU_SSD_CACHE` | bool | off | reload | Text engine: persist prefix KV to SSD. |
| `YUNSHU_SSD_CACHE_DIR` | path | ~/.cache/yunshu/kv-ssd | reload | Text engine: SSD prefix-cache directory. |
| `YUNSHU_SSD_CACHE_PRECISION` | `native` \| `int8` | native | reload | Text engine: SSD prefix-cache storage precision: 'native' (KV and recurrent state stored bit-exact; lossless) or 'int8' (per-tensor int8, about half the disk bytes of bf16; lossy on reuse; memory vs quality). |
| `YUNSHU_SSD_CACHE_PREFILL_CEIL_TPS` | float | 20000.0 | reload | Text engine: skip an SSD prefix restore when the model's observed prefill speed exceeds this (tokens/s): re-prefilling is then as fast as reading the KV back. |
| `YUNSHU_SSD_CACHE_MAX_GB` | float | 10.0 | reload | Text engine: SSD prefix-cache size cap in GiB, one budget for the whole directory (all models together). |
| `YUNSHU_CACHE_RESERVE_PCT` | float | 10.0 | live | SSD prefix caches (APC and text): free space, as a percentage of the volume, that no cache write may eat into. The reserve is max(this percentage, YUNSHU_CACHE_RESERVE_GB); the effective cap of a cache root is also limited to what the reserve leaves it. |
| `YUNSHU_CACHE_RESERVE_GB` | float | 20.0 | live | SSD prefix caches (APC and text): minimum free space in GiB left on the volume (see YUNSHU_CACHE_RESERVE_PCT). A write that would leave less is dropped and spilling pauses until space is back. |
| `YUNSHU_CACHE_STALE_DAYS` | float | 7.0 | live | SSD prefix caches (APC and text): a checkpoint namespace not used for this many days, or whose checkpoint no longer exists or has changed, is removed before anything else is evicted (0 = never by age). |
| `YUNSHU_KV_QUANT_BITS` | `auto` \| `off` \| `2` \| `3` \| `4` \| `8` | off | reload | Text engine KV cache quantization (lossy; memory vs quality): 'off' (lossless, the default on every hardware tier; an explicit 'off' also beats model_settings.json), 'auto' (8-bit once the KV cache would exceed ~2 GiB), or 2/3/4/8 bits always. |

### vlm-runner

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_VLM_APC_DRAFT_WINDOW_GB` | float | 0.25 | restart | RAM budget in GiB for the DFlash drafter context windows kept beside APC checkpoints (about 0.1 GiB each at 2047 positions). On a prefix hit the drafter starts with the stored window instead of only the uncached suffix, which restores its acceptance (lossless: the target verifies every draft). 0 disables. |
| `YUNSHU_VLM_APC_MEMORY_GB` | float | unset | reload | VLM runner prefix cache (APC) RAM budget in GiB; 0 disables the prefix cache. Unset: half of the memory left after the model weights and an OS / activation reserve (a quarter of the machine, 4 to 16 GiB), at most a quarter of the machine and 32 GiB, and 0 (off) when under 1 GiB would be left (128 GB machine, 27B model: 32; 8 GB machine, 4B model: 0). A 27B checkpoint costs about 130 KiB per cached token. |
| `YUNSHU_VLM_APC_DISK` | bool | on | reload | APC SSD tier: prefix checkpoints that RAM evicts (and, at shutdown, those still resident) are written to disk and read back instead of re-prefilling (bit-exact states, lossless; a 27B checkpoint reloads about 20x faster than it prefills). Set 0 to keep the prefix cache in RAM only. |
| `YUNSHU_VLM_APC_PERSIST` | `store` \| `evict` | store | reload | When a prefix checkpoint reaches the APC SSD tier. 'store' (default): it is queued to the disk writer thread as soon as it is stored (off the request path, atomic temp file + rename, the disk cap and free-space reserve apply; a newer checkpoint of the same conversation replaces it), so a killed or crashed server restarts with its cache. 'evict': written only when RAM evicts it and at a clean shutdown (fewest SSD writes; a kill loses what was still in RAM). |
| `YUNSHU_VLM_APC_DISK_DIR` | path | unset | reload | Directory of the APC SSD tier. Unset: ~/.yunshu/cache/apc (internal disk). Put it on a fast volume to keep the internal disk clean. |
| `YUNSHU_KV_PRECISION` | `bf16` \| `int8` | bf16 | reload | KV cache precision of the Qwen3.5-family runner's decode rows: 'bf16' (lossless) or 'int8' (int8 codes + one fp16 scale per 32-dim group: ~0.53x the KV memory and read bandwidth for a small attention error; memory vs quality). With int8 every decode row's target KV is int8, a lone request and concurrent rows alike, and speculative drafting and verification read the int8 KV, so a reply never depends on whether other requests overlapped it. Prefill and the prefix cache stay bf16; a row is quantized once when it joins the decode batch. Applies to the packed Qwen3.5 layer (dense and MoE Qwen3.5-family attention); Flash-Next and generic VLM layers stay bf16. |
| `YUNSHU_VLM_APC_DISK_GB` | float | unset | reload | Size cap of the APC SSD tier in GiB, one budget for the whole directory (every checkpoint namespace together; least recently used files go first across namespaces; 0 = no configured cap, the free-space reserve still applies). Unset: a quarter of the volume, at most 64 GiB (a 128 GB disk: 32). A 27B checkpoint costs about 130 KiB per token, so 64 GiB holds about 500K tokens. |
| `YUNSHU_PREFILL_MATMUL` | `stock` \| `lane` | stock | reload | Qwen3.5-family VLM prefill matmul. On the qualified Qwen3.8-27B / M5 Max / MLX 0.32.3 path, stock selects native NAX for every prompt piece (short pieces pad input rows to 64 and crop output); narrow gates and the vocabulary head keep their row-invariant lane arithmetic. Decode and speculative verify keep their existing kernels. Other configurations retain the legacy stock dispatch above 512 rows. lane keeps lane matmul throughout. Prefill arithmetic is isolated by APC kernel_id and SSD namespace. |
| `YUNSHU_PREFILL_BUFFER_CACHE_GB` | float | unset | reload | VLM runner: GiB of MLX's freed-buffer cache kept across prefill steps. Unset: 5% of physical RAM, at most 6 GiB (128 GiB: 6; 8 GiB: 0.4), but 0.5 GiB when the resident weights leave little headroom (above 80% of YUNSHU_MAX_MEMORY_GB when set, else above 45% of RAM): lossless, it cuts the long-prefill peak of a 74 GB model by 5-10 GB. Uses MLX's cache limit to reclaim excess freed memory on the next allocation without clearing every reusable bucket; freed buffers may transiently exceed the limit until that allocation. Keeps long-prefix restore buffers warm across requests. 0 = upstream clear after every chunk. Allocator only; output unchanged. |
| `YUNSHU_PREFILL_GDN` | `chunked` \| `step` | chunked | reload | Qwen3.5-family VLM prefill recurrence. chunked uses mx.fast.gated_delta_update; the qualified split-invariant 27B path uses it for every prompt piece, padding short tails to 64 with identity updates that preserve fp32 state. Checkpoints and resumable cuts are absolute 64-token boundaries. step retains the per-token kernel and disables split-invariant mode. Decode and speculative verify retain their existing kernels. Part of the APC arithmetic namespace. |
| `YUNSHU_PREFILL_ATTENTION` | `tile` \| `stock` | tile | reload | Qwen3.5-family VLM prefill attention on the qualified M5 Max / MLX 0.32.3 pair (bf16, D=256, causal, plain KV). tile uses BQ32 NAX attention; the qualified split-invariant 27B path uses it for every query length, including unaligned short tails. Other configurations retain the 1024-row threshold. stock disables split-invariant mode. Decode and speculative verify retain their kernels. Split-invariant attention is included in the APC arithmetic namespace. |
| `YUNSHU_ANE_FFN_SPLIT` | `off` \| `splash` | off | restart | Qwen3.5-family VLM prefill (single-row prompt steps of at least the calibrated rows): `splash` splits each dense FFN layer by intermediate channel between the GPU and the Apple Neural Engine, as Splash does (Apache-2.0 port): the ANE runs a W8A8 share (int8 weights rotated by a block Hadamard transform, int8 activations) through the private AppleNeuralEngine API on IOSurface memory shared with Metal, ordered by a shared event inside the GPU command stream. LOSSY: the ANE's part differs from the GPU's by about 2.5% RMS of what it adds, so outputs and logprobs differ slightly from `off`; prefix-cache states are kept apart by the kernel id. The share and the least chunk come from a calibration on this Mac (about a minute at first start, remembered per model and device). Any ANE failure or a split that loses to the GPU alone stops it for the life of the process and the GPU reruns the step. Costs about 0.7 GiB of extra resident memory (ANE surfaces and GPU slice scales). The hidden size must be whole 2560-channel segments (other models stay on the GPU). Off by default. |
| `YUNSHU_ANE_FFN_SHARE` | float | unset | restart | With YUNSHU_ANE_FFN_SPLIT=splash: fixed fraction (0-1) of intermediate channels the ANE takes, skipping calibration (rounded to 512-channel units). Unset: calibrated. |
| `YUNSHU_ANE_FFN_TRACE` | bool | off | restart | With YUNSHU_ANE_FFN_SPLIT=splash: log, for each split prompt step, the Neural Engine's milliseconds per layer and the GPU-side gap between layers (diagnostics). |
| `YUNSHU_ANE_FFN_CACHE` | path | unset | restart | With YUNSHU_ANE_FFN_SPLIT=splash: directory of the compiled Neural Engine programs' sources and the remembered calibration. Unset: ~/.yunshu/ane_cache/ffn. |
| `YUNSHU_ANE_FFN_MIN_ROWS` | int | unset | restart | With YUNSHU_ANE_FFN_SHARE: least prompt-step rows that take the split (512-2048, steps of 128). Unset: 512. |
| `YUNSHU_VLM_APC_DISK_TIERS` | str | unset | reload | Further APC storage tiers below the SSD directory, comma-separated, each 'PATH[@GiB]' (an external SSD, an HDD, a NAS mount). Each volume is profiled at startup (sequential read / write bandwidth and latency, cached per mount for a day) and the tiers are ordered by measured read speed. Checkpoints the SSD tier evicts move down in the background instead of being deleted; a tier is used for a hit only when restoring from it beats re-prefilling (measured bandwidth against the observed prefill speed). A tier that is not mounted is skipped; when it returns its files are validated again. Each tier has its own cap (default: a quarter of its volume, at most 64 GiB) and free-space reserve. Lossless; unset: SSD only. |
| `YUNSHU_VLM_APC_DISK_ENCODING` | `auto` \| `raw` \| `zstd` | auto | reload | How the lower APC storage tiers (YUNSHU_VLM_APC_DISK_TIERS) hold a checkpoint: 'raw' (a copy of the SSD file), 'zstd' (lossless: byte-plane shuffle of bf16 tensors + zstd; decoded on restore), 'auto' (zstd only when the measured gain in effective read bandwidth, ratio against decode cost, beats raw on that device: slow disks and network shares, not fast SSDs). Never lossy. |
| `YUNSHU_VLM_APC_WARM` | `off` \| `lossless` \| `int8` \| `int4` | off | reload | APC WARM tier: what happens to a prefix checkpoint that leaves the RAM tier (HOT, ready-to-use arrays) before it goes to SSD. 'off': straight to SSD. 'lossless': kept in RAM compressed (zstd after a byte-plane shuffle; bit-exact, a WARM hit equals a HOT hit token for token; costs CPU for compression and a decode on hit). 'int8' / 'int4': attention K/V kept in RAM as affine group-quantized codes (LOSSY: a hit restores dequantized K/V, so output can differ from a cold prefill; the SSD tier keeps exact states in these modes). The WARM tier takes YUNSHU_VLM_APC_WARM_SHARE of the APC RAM budget. |
| `YUNSHU_VLM_APC_WARM_SHARE` | float | 0.4 | reload | Share of the APC RAM budget (YUNSHU_VLM_APC_MEMORY_GB) that the WARM tier takes when YUNSHU_VLM_APC_WARM is on; the HOT tier keeps the rest. One budget, split: total APC RAM does not grow. |
| `YUNSHU_VLM_MAX_IMAGE_BYTES` | int | 26214400 (25 MiB) | live | Largest image a request may reference by URL, in bytes. |
| `YUNSHU_VLM_MAX_VIDEO_BYTES` | int | 104857600 (100 MiB) | restart | Largest video a request may reference by URL, in bytes. |
| `YUNSHU_VLM_INSECURE_SSL` | bool | off | live | Retry image downloads without TLS verification when verification fails. |
| `YUNSHU_PLE_STORAGE` | `auto` \| `ssd` \| `ssd-rows` \| `memory` | auto | reload | Qwen3.8-Flash-Next (qwen4_exp): where the n-gram embedding (PLE) table lives. 'auto' (default): 'ssd-rows' when `yunshu prepare <model>` has repacked this checkpoint (one time, ~32 GB; cold TTFT -22..-26% at 1K, -5..-9% at 8K, lossless), else 'ssd'. 'ssd': rows are read from the checkpoint's own files on demand (a small manifest is built once under ~/.yunshu/cache/ple), so the ~30 GB table never enters memory; the rows are byte-identical, so output is unchanged. Measured on Flash-Next oQ2.5e (2026-10-28): peak 82.9 -&gt; 54.5 GB, macOS-compressed memory 30 GB -&gt; 0, identical text, speed unchanged (3 interleaved reps against a hand-built view: DFlash2 81.6 vs 82.4, MTP 84.3 vs 85.4 tok/s). 'ssd-rows': as 'ssd', but from a one-time repacked copy of the table with each row's weight, scales and biases in one 100-byte record (~32 GB, built by `yunshu prepare` or on first load under YUNSHU_PLE_ROWS_DIR; a mismatching or torn repack is never used), so a cold row costs one disk read instead of three; byte-identical rows. 'memory': load the table like any weight. A pack that already declares external PLE storage is used as it is. |
| `YUNSHU_PLE_ROWS_DIR` | path | unset | reload | Qwen3.8-Flash-Next with YUNSHU_PLE_STORAGE=ssd-rows: directory of the repacked one-record-per-row PLE table (~32 GB per model; one subdirectory per model). Unset: ~/.yunshu/cache/ple. |
| `YUNSHU_PLE_READ_THREADS` | int | 64 | reload | Qwen3.8-Flash-Next (qwen4_exp) with the n-gram embedding (PLE) read from SSD: threads that read a token's PLE rows in parallel. A token needs 48 random row reads (16 heads x weight/scales/biases); upstream reads them one after another (about 7 ms per token on fresh text, hidden only when a prompt repeats and hits the row cache). The rows returned are byte-identical to the serial read, so output is unchanged. Default 64 (2026-11-12, M5 Max, oQ2.5e: cold-read microbench of 24K rows 16 threads 1.43-1.64 s, 64: 0.64-0.67 s, 128: 0.56-0.59 s; yv pleon-thr64 vs 16: identity 0 mismatches, cold TTFT 8K code -4.7%, prose -11.8%, 32K within noise; 128 measured no better than 64 in pleon-thr128). 0 = upstream serial reads. |
| `YUNSHU_PLE_ROW_CACHE` | int | 200000 | reload | Qwen3.8-Flash-Next (qwen4_exp) with the n-gram embedding (PLE) read from SSD: rows an LRU keeps for decode windows. Every decode step reads 16 head rows x 3 tensors per token from SSD on the MLX thread (1.1-1.7 ms of a 14-20 ms host step); common tokens repeat, and a row's bytes depend only on its id, so a cached row is byte-identical to a read (output unchanged). Each cached row is about 0.5 KB (100 B of data plus array headers): 200000 rows (the default) is about 100 MB; the LRU belongs to the prefetcher and is dropped with it on unload. Prompt spans are not cached (their rows are mostly unique and already prefetched). Default 200000 (2026-11-13, Flash-Next oQ2.5e, yv pledec-cache: identity 18 cells 0 mismatches; decode code@8K +6.4%, prose@8K +2.9%, follow-up TTFT -5%; 32K/64K neutral). 0 = off. |
| `YUNSHU_GC_POLICY` | `default` \| `freeze` \| `defer` | defer | reload | Python cyclic-collector policy of the VLM runner (a ~110 ms generation-2 pass can land right after a long prefill and delay the first token). Default: defer (27B 32K, yv ttftfloor-gc-defer32: identity 0 mismatches, warm TTFT -2.3%, follow-up -0.6%, decode +0.4%). default: Python's own, the opt-out. freeze: after load, collect once and gc.freeze() the startup heap (vLLM and SGLang do the same). defer: freeze, a 100x higher generation-2 multiplier, and the collector is disabled from request arrival to its first token (bounded: first token, 60 s or 5M net allocations; idle servers still collect). Output is unchanged. |
| `YUNSHU_NEXT_TURN_PREFILL` | `off` \| `decode` \| `stride` \| `boundary` \| `exact` | decode | reload | VLM chats: how the next turn reuses a reply. decode (default, user 2026-11-02): the cache the reply was decoded into is stored when the reply ends, so a follow-up that repeats the conversation prefills only its new message (as TensorFold / mlx-serve do; the reused reply KV comes from decode kernels, so a hit may differ numerically from a cold recompute). stride / boundary / exact: while idle after a reply, prefill its rendered assistant text and store APC checkpoints instead (decode-time KV is never reused; hit == cold). Default stride on qualified split-invariant 27B stops at the last absolute 64-token boundary at or before assistant end; without split-invariant kernels it retains the full prefill-atom grid. A matching arriving request adopts in-flight work; other requests cancel at a preemptible boundary. off disables rehearsal. boundary/exact retain the legacy assistant-end split policy on unsupported configurations and may change their cold rounding. Costs idle GPU time and one cached prefix. |
| `YUNSHU_NEXT_TURN_DELAY_S` | float | 0.3 | live | Seconds between a finished reply and next-turn rehearsal. Default 0.3 lets an immediate follow-up (agent loops) arrive before rehearsal starts and prefill once, while a later one adopts running work; 0 starts as soon as idle, which costs an immediate follow-up about 0.15-0.25 s (rehearsal plus a short tail request). No GPU work is started while foreground requests are waiting. |

### speculative

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_MTP` | bool | on | reload | Qwen3.5-family VLMs: draft with the checkpoint's MTP head (batch-invariant, spec on == spec off). |
| `YUNSHU_VLM_DRAFT` | path | unset | reload | Qwen3.5-family VLMs: speculative draft override. A DFlash drafter directory; 'mtp' forces the checkpoint MTP head; 'off' disables drafting. Unset: a DFlash2 drafter matching the model is used automatically when it is in the models dir or the Hugging Face cache, else the MTP head (batch-invariant verify, spec on == spec off). |
| `YUNSHU_MTP_BLOCK_SIZE` | int | unset | reload | Draft block size (DFlash: the ceiling its acceptance-driven depth stays under). Unset: 2 for Flash-Next (qwen4) MTP, 6 for other MTP, the drafter's trained block for DFlash. |
| `YUNSHU_SPEC_COPY_ROWS` | int | 32 | reload | Dense and MoE Qwen3.5-family DFlash drafts on the round driver (Flash-Next DFlash rows have no copy drafter): verify rows a prompt-copy round may use (copy drafts = rows - 1; values below 3 turn copy rounds off). A copy round proposes the continuation of the longest earlier occurrence of the current tail in the request's prompt plus its generated text; the copied drafts are checked by the same verify, so output is unchanged (greedy: identical to plain decode; sampled: keyed-sampler exact). Agent, code-editing and multi-turn traffic that quotes its context commits several times more tokens per round. Rows under a plain guide or a forced token do not copy. The width is capped to the backend's certified verify width (32 for dense lane projections with compatible tile attention, 8 otherwise) and to the driver's 32-row pack. Default 32 rows (2026-10-20 32K screen, DFlash code +14.5%, identical output). MTP-drafted rows on the round driver have no prompt-copy drafter, so this value does not change them. |
| `YUNSHU_DRAFT_BITS` | int | 8 | reload | Qwen3.5-family DFlash drafter weight bits: 8 (default), 4, or 0 to keep the shipped bf16. Drafts are verified by the target, so output is token-identical for every value; fewer bits cut the drafter's bytes per round but can lower acceptance (27B on M5: 4-bit +4% to +8% decode at 1K-8K, -7% on 32K code). |
| `YUNSHU_SPEC_TREE` | `off` \| `tree` \| `auto` | auto | reload | Qwen3.5-family DFlash speculative trees: the round driver builds the draft tree for every DFlash row itself, and this value does not choose whether it does. auto (default) also pre-compiles the fast-tree verify kernels at load when prompt-copy is engaged on a supported dense 27B lane, so the first long request skips those Metal compiles; off and tree skip that warm-up and change nothing else on the served path. With the same seed, speculative tokens and requested logprobs match plain decode. |
| `YUNSHU_NGRAM_DEFAULT` | bool | off | reload | N-gram / suffix speculation on greedy requests by default (per-request spec_decode also enables it): text models, and mlx-vlm models on the generic layer (lone row, trimmable KV cache; guarantee = the verifier's top-1 over the window, not bitwise vs one-token decode). Wins on repetitive output. |
| `YUNSHU_SPEC_PROPOSER` | `ngram` \| `suffix` | ngram | reload | Proposer family for n-gram speculation (text models and the generic round-driver layer). |
| `YUNSHU_GEMMA4_ASSISTANT` | path | unset | reload | Gemma-4 models (text engine, and the round-driver generic layer for requests with spec_decode): assistant drafter directory (KV-shared speculative drafter). |
| `YUNSHU_SPEC_UNVERIFIED` | `''` \| `eagle` | unset | reload | Text models: explicitly enable the unverified external mlx-lm draft experiment. 'eagle' is the historical route name; an ordinary LM draft works, no trained EAGLE head is required. Greedy, non-streaming ordinary requests with default sampling/penalties only; schema, custom processors, stop strings, thinking budgets, LoRA and token-mask options keep the regular fast path. Native MTP/DFlash belongs to the VLM runner. Option (not the default): output is not guaranteed token-identical to plain decode (2026-10-24: differed on 4/4 prompts; speed -5..+33%). |
| `YUNSHU_DRAFT_MODEL` | path | unset | reload | External mlx-lm draft checkpoint (ordinary LM draft, not a trained EAGLE head). Round-driver generic layer: drafts for requests with spec_decode (greedy lone rows, same vocab as the target). Text engine: also needs YUNSHU_SPEC_UNVERIFIED=eagle. |

### text-engine

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_JUMP_FORWARD` | bool | off | live | Batch grammar-forced token runs into one forward; generic models may round differently. |
| `YUNSHU_JSON_SCHEMA_ENGINE` | `llguidance` \| `inhouse` | llguidance | live | Engine that masks JSON-schema / json_object constrained decoding: 'llguidance' (per-token mask about 0.25 ms median on a 248K vocabulary; properties in schema order, forced literals in canonical tokenization) or 'inhouse' (the Python state machine, about 3 ms median; any property order). A schema llguidance cannot compile falls back to the in-house engine when that supports it. |
| `YUNSHU_GRAMMAR_BITMASK` | bool | off | live | Text engine only: constrained decoding with the xgrammar-style bitmask engine instead of the allowlist sampler (round-driver constraints are llguidance-based and ignore it). |
| `YUNSHU_GRAMMAR_PREWARM` | bool | on | live | Build the llguidance token tables in the background when a model loads, so the first constrained request (response_format, regex, choice, cfg, forced tool_choice) does not spend about a second walking the vocabulary. Builds one table at the tokenizer width (about 0.45 GiB native heap at a 248K vocabulary, what the first constrained request would take anyway); the forced-tool grammar's padded-width table, when it differs, is built on its first use. 0 builds on first use instead. Needs llguidance and a Hugging Face tokenizer. |
| `YUNSHU_QUANT_MODE` | `''` \| `mxfp4` \| `nvfp4` \| `mxfp8` \| `affine` | unset | reload | Quantize weights in memory at load (lossy; memory vs quality): mxfp4, nvfp4, mxfp8 or affine ('' keeps the checkpoint). |
| `YUNSHU_QUANT_CONFIG` | str | unset | reload | Bits/group for affine in-memory quantization: JSON (&#123;"bits":4,"group_size":64&#125;) or 'bits' / 'bits,group'. |

### kernels

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_QSA_SPARSE_PREFILL` | bool | on | reload | Qwen3.8-Flash-Next (qwen4_exp), M5-class GPUs: run the prompt rows' indexed-sparse QSA attention on the tensor units, one threadgroup per (row, key head) with the 12 query heads that share a key head as one matmul operand and the selected keys read once, instead of upstream's scalar kernel that re-reads the selected keys for every query head. Each row's result depends on that row alone, so prefill stays independent of chunking; the arithmetic differs from upstream's (fp32 accumulate in a different order, not a quality change). Decode and speculative verify are untouched. On by default: cold TTFT 8K/32K/128K -25/-24/-20% on Flash-Next oQ2.5e; within-version identity holds (spec on == off, APC hit == miss) and the kld gate has the output closer to an fp32-attention reference than the stock kernel (KLD 0.0685 vs 0.0731). Off: upstream's scalar kernel. |

### voice

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_REALTIME_OMNI` | `auto` \| `on` \| `off` \| `1` \| `0` \| `true` \| `false` \| `yes` \| `no` | auto | restart | Native Qwen3-Omni speech on the Realtime socket: 'auto' when a speakable model is served, 'on', or 'off' (ASR -&gt; LLM -&gt; TTS cascade). |
| `YUNSHU_OMNI_MODEL` | path | unset | restart | Voice path model when it differs from the served model (an omni served model is reused automatically). |
| `YUNSHU_OMNI_PRELOAD` | bool | on | restart | Warm the omni model at boot so the first voice request is not cold. |
| `YUNSHU_OMNI_THINKER_MAX` | int | 256 | reload | Maximum tokens the omni Thinker writes per voice turn (the spoken reply's length cap). |
| `YUNSHU_OMNI_PERSONA` | str | unset | live | Realtime system persona when the request has none; empty string disables it. Unset: a built-in concise spoken style. |
| `YUNSHU_REALTIME_SILENCE_MS` | int | 500 | live | Server VAD: pause before the model answers, in ms. |
| `YUNSHU_REALTIME_BARGE_IN_MS` | int | 120 | live | Sustained speech needed to interrupt the model mid-reply, in ms. |
| `YUNSHU_REALTIME_VAD_THRESHOLD` | float | 0.5 | live | Server VAD speech-detection threshold. |
| `YUNSHU_REALTIME_PREFIX_PADDING_MS` | int | 300 | live | Server VAD: audio kept before detected speech, in ms. |
| `YUNSHU_REALTIME_VAD` | `energy` \| `silero` | energy | live | Server VAD implementation: 'energy' or 'silero'. |
| `YUNSHU_REALTIME_VAD_MODEL` | str | mlx-community/silero-vad | live | Silero VAD model id when YUNSHU_REALTIME_VAD=silero. |
| `YUNSHU_REALTIME_MAX_INPUT_AUDIO_BYTES` | int | 10485760 (10 MiB) | live | Realtime: largest buffered input audio, in bytes. |
| `YUNSHU_REALTIME_MAX_CONVERSATION_ITEMS` | int | 1000 | live | Realtime: conversation items kept per session. |

### image-video

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_DIFFUSION_SCHEDULER` | `''` \| `ddim` \| `dpm_plus_plus` \| `euler` \| `euler_ancestral` \| `lms` | unset | reload | Image generation sampler name ('' uses the pipeline's own). Every value currently runs the same Euler update over the same sigma schedule: the named DDIM / DPM++ / ancestral / LMS steps are not implemented, so the choice does not change the image. |

### embeddings

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_ANE_EMBEDDINGS` | bool | off | live | Compute embeddings on the Apple Neural Engine via CoreML when available. |
| `YUNSHU_ANE_EMBEDDING_MODEL` | str | intfloat/e5-small-v2 | live | Embedding model used on the ANE path. |

### mcp

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_MCP_CONFIG` | path | unset | restart | MCP client config file (JSON/YAML) listing tool servers. |
| `YUNSHU_MCP_SERVERS` | json | unset | restart | MCP tool servers as a JSON array (alternative to YUNSHU_MCP_CONFIG). |

### server-tools

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_WEB_SEARCH_PROVIDER` | `auto` \| `none` \| `searxng` \| `brave` \| `tavily` \| `exa` \| `serper` \| `perplexity` \| `ddg_html` \| `wikipedia` \| `mwmbl` \| `mojeek` \| `marginalia` | auto | live | Search backend. Auto runs lightweight DDG, Wikipedia and configured keyed providers (Mwmbl is an explicit noncommercial opt-in) in parallel with health backoff and RRF. SearXNG is optional. Queries leave the machine; none disables search. |
| `YUNSHU_WEB_SEARCH_PROVIDER_TIMEOUT` | float | 1.0 | restart | Per-provider metasearch deadline in seconds; slow providers cannot block the whole query. |
| `YUNSHU_WEB_SEARCH_HEALTH_FILE` | path | ~/.yunshu/cache/websearch-health.json | restart | Small query-free provider health snapshot read by yunshu config. No SERPs or credentials are stored. |
| `YUNSHU_WEB_MWMBL` | bool | off | restart | Opt in to Mwmbl's open small-web index in auto metasearch. Dataset is CC-BY-NC-SA 4.0 (noncommercial, attribution/share-alike); code is not vendored. Explicit provider=mwmbl also opts in. |
| `YUNSHU_WEB_KEYLESS` | bool | on | restart | DuckDuckGo HTML (best effort; may block) and Wikipedia, no API keys; on by default (user decision 2026-11-09). Query text and IP leave the machine. |
| `YUNSHU_MOJEEK_API_KEY` | str | unset | restart | Mojeek independent-index API key. Configured keys participate in auto metasearch. |
| `YUNSHU_MARGINALIA_API_KEY` | str | unset | restart | Explicit opt-in to Marginalia small-web search. Noncommercial/public API data is CC-BY-NC-SA 4.0; commercial keys have separate terms. No implicit public key. |
| `YUNSHU_SERPER_API_KEY` | str | unset | restart | Serper Google SERP API key. |
| `YUNSHU_PERPLEXITY_API_KEY` | str | unset | restart | Perplexity Search API key (raw results, not Sonar). |
| `YUNSHU_WEB_RESEARCH` | bool | off | restart | Enrich search snippets with origin pages, untrusted excerpts and local ranking. Stable opt-in pending quality evaluation; fetched URLs leave the machine. |
| `YUNSHU_WEB_RENDER` | bool | off | restart | Optional local Chromium fallback for short JavaScript shells in advanced Tavily extract/crawl/map. Requires the web-render extra and an installed Playwright Chromium; same-origin GET resources only, no cookies. Never downloads a browser automatically. |
| `YUNSHU_WEB_RESEARCH_BUDGET` | float | 4.0 | restart | Overall enrichment deadline in seconds (maximum 4). |
| `YUNSHU_WEB_RESEARCH_PAGES` | int | 6 | restart | Maximum origin pages per enrichment (capped at 6). |
| `YUNSHU_WEB_RESEARCH_MODEL` | str | unset | restart | Already-loaded local embedding model ID. Never loads a model; absent/unavailable uses BM25 only. Qwen3-Embedding-0.6B is recommended. |
| `YUNSHU_SEARXNG_URL` | str | unset | live | Base URL of a self-hosted SearXNG instance (JSON output enabled), e.g. http://127.0.0.1:8080. Optional only; built-in metasearch needs no SearXNG setup. |
| `YUNSHU_BRAVE_API_KEY` | str | unset | live | Brave Search API key. |
| `YUNSHU_TAVILY_API_KEY` | str | unset | live | Tavily API key. |
| `YUNSHU_EXA_API_KEY` | str | unset | live | Exa API key. |
| `YUNSHU_WEB_SEARCH_RESULTS` | int | 5 | live | Results returned per web_search call. |
| `YUNSHU_WEB_FETCH` | bool | on | live | Serve the server-side web_fetch tool (needs no provider). Off: web_fetch requests get an 'unavailable' error. |
| `YUNSHU_WEB_FETCH_ALLOW_PRIVATE` | bool | off | live | Let web_fetch reach private, loopback and link-local addresses. Off (default) blocks them (SSRF protection), including after redirects and DNS resolution. |
| `YUNSHU_WEB_FETCH_MAX_BYTES` | int | 2000000 | live | Largest response body web_fetch downloads. |
| `YUNSHU_WEB_FETCH_TIMEOUT` | float | 20.0 | live | Seconds web_fetch waits for a page. |
| `YUNSHU_WEB_FETCH_MAX_TEXT_CHARS` | int | 40000 | live | Extracted page text handed to the model is cut to this many characters (a request's max_content_tokens can lower it). |
| `YUNSHU_CODE_EXECUTION` | bool | off | live | Serve the server-side code execution tools on this machine (Anthropic code_execution_*; OpenAI Responses code_interpreter and hosted shell; the OpenAI /v1/containers API) inside the Anthropic sandbox-runtime (srt, optional: `npm i @anthropic-ai/sandbox-runtime`, Node &gt;= 22.12). Off: requests that declare them get a 400. On without srt: 503, never an unsandboxed run. The sandbox writes only inside a per-container directory, reads nothing of your home, and has no network unless YUNSHU_CODE_EXECUTION_NETWORK_ALLOW lists hosts. |
| `YUNSHU_CODE_EXECUTION_ROOT` | path | ~/.yunshu/sandbox | live | Directory holding the code execution containers (one sub-directory each). Created with mode 0700. |
| `YUNSHU_CODE_EXECUTION_TIMEOUT` | float | 60.0 | live | Wall-clock seconds one code execution call may run before its process group is killed (execution_time_exceeded). Also the CPU-time limit. A Python cell waiting for the client's tool results does not count. |
| `YUNSHU_CODE_EXECUTION_MEMORY_MB` | int | 2048 | live | Resident memory a code execution call may use (whole process group, sampled every 100 ms); above it the call is killed. An OpenAI container's memory_limit can only lower it. |
| `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW` | str | unset | live | Comma-separated hosts the sandbox may reach (`example.com`, `*.example.com`, `host:443`). Unset: no network at all, loopback included. Private address ranges stay blocked even for allowed names. An OpenAI container's network_policy can only narrow this list. |
| `YUNSHU_CODE_EXECUTION_TTL_MIN` | float | 20.0 | live | Minutes a code execution container may sit unused before it and its files are deleted. An OpenAI container's expires_after.minutes can only shorten it. |
| `YUNSHU_MCP_CONNECTOR` | bool | on | live | Serve the MCP connector: Anthropic mcp_servers and OpenAI Responses &#123;type: mcp&#125; tools are executed by this server, which connects to the named MCP servers over streamable HTTP / SSE. |
| `YUNSHU_MCP_CONNECTOR_ALLOW_PRIVATE` | bool | off | live | Let the MCP connector reach private, loopback and link-local MCP servers named in a request (Anthropic mcp_servers / Responses &#123;type: mcp&#125;). Off (default): only public addresses, so an inference caller cannot probe the LAN or this Mac. MCP servers you configure yourself (YUNSHU_MCP_SERVERS / YUNSHU_MCP_CONFIG) are unaffected. |
| `YUNSHU_MCP_CONNECTOR_TIMEOUT` | float | 30.0 | live | Seconds an MCP connector call (initialize, tools/list, tools/call) may take, DNS included. |
| `YUNSHU_MCP_CONNECTOR_MAX_BYTES` | int | 8388608 (8 MiB) | live | Largest single reply (JSON body, or one SSE event) an MCP connector server may send, after decompression. |
| `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` | int | 8 | live | Most generate, run-tool, continue rounds one request may take. |
| `YUNSHU_MODEL_ALIASES` | json | unset | live | Multi-model mode: map the model names agents ask for (claude-sonnet-4-5, opus, gpt-5) onto a served model, as a JSON object &#123;pattern: served model id&#125;; patterns are exact names, prefix* or * (first match wins; a real model name always wins). Single-model mode answers to every name already. |

### observability

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_OBSERVE` | bool | off | restart | Observe mode (`yunshu serve --observe`): turn on every observability feature you did not set yourself: /debug/* routes, host telemetry, the serve log, the audit log file (~/.yunshu/logs/audit.log), exact token ids in logprobs, and the generation capture file (~/.yunshu/logs/stream_capture.jsonl). A value you set explicitly (flag, env, config file) always wins and shows its own source; the others show source 'observe'. Costs: telemetry adds about +1.8% follow-up TTFT at 1K (27B A/B), the logs and capture write small files; keep it off for speed benchmarks. Without a token, /debug/* answers loopback clients only. |
| `YUNSHU_DEBUG_ROUTES` | bool | off | restart | Mount the /debug/* diagnostic routes (engine, system, kv-cache, spec-decode, ...). They need the auth token or YUNSHU_AUTH_DISABLED. /metrics is always mounted. |
| `YUNSHU_DEBUG_TREE_PROFILE` | bool | off | live | Debugging aid: time every stage of the DFlash tree verify (GDN mixer, attention, MLP, residual norms, commit) by evaluating after each one, and log the per-round means when a request ends. The sync after each stage lengthens the round; the split is for finding the dominant stage, not for speed. |
| `YUNSHU_LOG_LEVEL` | `DEBUG` \| `INFO` \| `WARNING` \| `ERROR` | INFO | restart | Log level for Yunshu's loggers (third-party loggers stay at WARNING). |
| `YUNSHU_TELEMETRY` | `on` \| `off` | off | restart | Unprivileged Apple power/GPU/temperature sampler (on/off); off by default (the 27B A/B showed a small, consistent follow-up TTFT cost when on); 1 Hz when on, restart required. |
| `YUNSHU_TELEMETRY_INTERVAL_S` | float | 1.0 | restart | Host telemetry sampling interval in seconds (restart required). |
| `YUNSHU_AUDIT_LOG_FILE` | path | unset | restart | Also write the audit log to this file. |
| `YUNSHU_LOG_MAX_MB` | float | 50.0 | live | Service log (launchd): rotate the log file at this size in MiB; 0 turns size rotation off. |
| `YUNSHU_LOG_ROTATE_HOURS` | float | 24.0 | live | Service log: also rotate when this many hours passed since the last rotation; 0 turns time rotation off. |
| `YUNSHU_LOG_KEEP` | int | 7 | live | Service log: rotated (gzip, secrets redacted) files kept. |
| `YUNSHU_LOG_RETENTION_DAYS` | float | 14.0 | live | Service log: delete rotated files older than this many days; 0 keeps them until YUNSHU_LOG_KEEP prunes them. |
| `YUNSHU_REPLAY_TOKEN_IDS` | bool | off | live | Include exact token_id in requested chat logprobs for local lossless replay verification. Off by default; never writes token IDs to the serve log. |
| `YUNSHU_RESEARCH_ACTIVITY_FILE` | path | unset | live | Opt-in local gpuq pause handshake file. Configure the same file in gpuq serving.json activity_files. No request content is written. Requests wait for a fresh safe acknowledgement before inference; timeout returns 503. |
| `YUNSHU_RESEARCH_PAUSE_TIMEOUT_S` | float | 2.0 | live | Maximum pre-admission wait for gpuq pause acknowledgement in seconds. |
| `YUNSHU_SERVE_LOG` | bool | off | live | Write one numbers-only JSON line per finished generation request (timings, token counts, speculative acceptance, cache tier, concurrency, arm, build) to a local, size-capped, rotated file. Never prompts, outputs or token ids. Off by default; nothing leaves the machine. |
| `YUNSHU_SERVE_LOG_DIR` | path | unset | live | Directory of the serve log. Unset: ~/.yunshu/logs. |
| `YUNSHU_SERVE_LOG_MAX_MB` | float | 4.0 | live | Serve log: rotate at this size in MiB; with YUNSHU_SERVE_LOG_KEEP the directory is capped at max * (keep + 1). |
| `YUNSHU_SERVE_LOG_RETENTION_DAYS` | int | 30 | live | History API metadata retention window in days; 0 disables age filtering. File storage remains bounded by SERVE_LOG_MAX_MB and SERVE_LOG_KEEP. |
| `YUNSHU_SERVE_LOG_KEEP` | int | 4 | live | Serve log: rotated files kept. |
| `YUNSHU_HISTORY_INTERVAL_S` | float | 5.0 | restart | Console history: seconds between samples of the in-memory ring behind GET /v1/yunshu/history (throughput, request counts, memory, TTFT percentiles); 0 turns the sampler off. The ring is fixed-size and never grows: 12 columns, 4 bytes each (timestamp 8), per slot. |
| `YUNSHU_HISTORY_HOURS` | float | 12.0 | restart | Console history: hours the history ring keeps (capacity = hours * 3600 / YUNSHU_HISTORY_INTERVAL_S slots, preallocated; 12 h at 5 s is 8,640 slots, about 0.4 MiB). |
| `YUNSHU_ARM` | str | unset | live | Label recorded in the serve log for the configuration arm this server runs (for offline A/B analysis); it changes no behaviour. |

### console

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_CONSOLE` | bool | on | restart | `yunshu serve` also starts the console process (the web console, the docs, and the metrics history recorder) as a sibling on YUNSHU_CONSOLE_PORT. The console is its own light process that never loads MLX: it keeps running and recording while the engine restarts or crashes, and an engine fault cannot take it down. `--no-console` turns it off; `yunshu console` runs it on its own. |
| `YUNSHU_CONSOLE_PORT` | int | 8100 | restart | Port of the console process (the web console at /console/, its reverse proxy to the engine API, and the history endpoints). 8100 stays clear of the engine's 8000 and of the usual dev servers (3000, 5173, 8080, 8888). |
| `YUNSHU_CONSOLE_HOST` | str | unset | restart | Bind host of the console process. Unset: the engine's own host for the sibling, 127.0.0.1 for a standalone `yunshu console`; 0.0.0.0 serves the local network too. |
| `YUNSHU_CONSOLE_ENGINE` | str | unset | restart | Engine URL the console process watches and proxies to. Unset: the engine that started it, else http://127.0.0.1:8000. Point it at a LAN or remote engine to watch that one. `auto` follows whichever local engine is running (see YUNSHU_CONSOLE_DISCOVER_PORTS). |
| `YUNSHU_CONSOLE_DISCOVER_PORTS` | str | all | restart | Where the console looks for Yunshu engines with `--engine auto` (or YUNSHU_CONSOLE_ENGINE=auto). `all` (default): every TCP port listening on this Mac (lsof, refreshed every 10 s), minus console processes; one engine reached through a proxy port is listed once. Or comma-separated ports and ranges on 127.0.0.1, e.g. `8000,18990-18999`. A port counts only when its /health answers like a Yunshu engine; a port that answered as something else is re-probed after 60 s. The console keeps the engine it follows while that one is healthy, then follows the most recently started one; pin one in the status island. |
| `YUNSHU_CONSOLE_DISCOVER_S` | float | 2.0 | restart | Seconds between the console's engine discovery probes in `--engine auto` mode (short-timeout GET /health on each candidate, asynchronous). |
| `YUNSHU_CONSOLE_ENGINE_TOKEN` | str | unset | restart | Bearer token the console process uses to read the engine while it records history. Unset: YUNSHU_AUTH_TOKEN. The browser's own token is passed through to the engine unchanged. |
| `YUNSHU_CONSOLE_PAUSE_FILE` | path | unset | restart | Path of a JSON pause file `{"pause": true, "until": <epoch or null>, "reason": "..."}`. While it exists and is not stale (past `until`, or older than 2 h when `until` is null) the console process sends no request to any engine (no status polling, no discovery probes) so a timing A/B is not perturbed by an asymmetric monitor; the proxy still forwards user-initiated requests and the status island shows the reason. gpuq writes `$GPUQ_DIR/console-pause.json` while a timing (--quiet or `-speed`) job runs. |
| `YUNSHU_DOCS_ASK_MAX_QUESTION` | int | 2000 | restart | Maximum characters in a console documentation question or each history message. Ask AI uses only the attached engine's already loaded text model and caller credentials. |
| `YUNSHU_DOCS_ASK_MAX_HISTORY` | int | 8 | restart | Maximum prior user/assistant messages accepted by console Ask AI. Recent messages are additionally trimmed to the model context budget. |
| `YUNSHU_DOCS_ASK_MAX_TOKENS` | int | 1024 | restart | Maximum generated tokens for console Ask AI, additionally capped to a quarter of the attached model context. Documentation retrieval is local BM25; no model is loaded implicitly. Measurement pause blocks Ask AI. |
| `YUNSHU_CONSOLE_POLL_S` | float | 1.0 | restart | Seconds between the console process's reads of the engine (status and finished requests, the same cheap endpoints the console page uses). 1 s gives the 1 s history resolution. |
| `YUNSHU_CONSOLE_HISTORY` | bool | on | restart | Record the metrics history (1 s for 1 h, 10 s for 24 h, 1 min for the retention) and the request log (metadata only, never prompts or outputs) to ~/.yunshu/console-history.sqlite, with engine outages kept as explicit gaps and events. Off keeps the console live-only. |
| `YUNSHU_CONSOLE_DB` | path | unset | restart | Where the console process keeps its history (SQLite, WAL). Unset: ~/.yunshu/console-history.sqlite. |
| `YUNSHU_CONSOLE_RETENTION_DAYS` | float | 30.0 | restart | Days the console keeps 1-minute history rows, the request log and the engine events. |
| `YUNSHU_CONSOLE_DB_MAX_MB` | float | 64.0 | restart | Size cap of the console history file in MiB: when exceeded, the oldest request rows and then the oldest 1-minute rows are dropped. |

### cli

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_GATEWAY_URL` | str | http://localhost:8000 | live | Server URL used by the yunshu CLI client commands. |
| `YUNSHU_API_KEY` | str | unset | live | Client side: the Bearer key the yunshu CLI sends to the server (`yunshu statusline`) and passes to the coding agents `yunshu launch` starts (Codex reads it as its provider key). The server never reads it; set YUNSHU_AUTH_TOKEN there. |
| `YUNSHU_HF_ENDPOINT` | str | unset | restart | Hugging Face Hub endpoint for `yunshu serve` (exported as HF_ENDPOINT). |

## 實驗性設定

| Setting | Type | Default | Applies | Description | Decided by | Added |
|---|---|---|---|---|---|---|
| `YUNSHU_SDPA_CHUNK` | bool | off | reload | M1-M4 (pre-NAX GPUs), head_dim 256 or 512 (Gemma 4 global layers): run MLX 0.32.3's unfused long-prefill attention fallback on query-row chunks so its score tensor stays under 1 GiB instead of growing with context squared (adopted from omlx sdpa256_attention). Same arithmetic per row as the stock fallback; no effect on M5 or CPU. | On an M1-M4 Mac: bitwise A/B of chunked vs stock SDPA at head_dim 256 over a long chunked prefill (causal and array masks, bf16) plus 27B-class prefill peak memory and TTFT; if bit-identical with lower peak memory it becomes the default and the flag is deleted, else kernels/sdpa_chunk.py and the flag are deleted | 2026-10-26 |
| `YUNSHU_QWEN4_PREFILL_STEP` | int | 2048 | reload | Qwen3.8-Flash-Next (qwen4_exp): prompt tokens per prefill forward, which is also the APC checkpoint grid (its prefill is not split-invariant). oMLX uses 8192 on NAX Macs with &gt;= 64 GB (64K prompt: 8 forwards instead of 32). A different value changes the prefill arithmetic (cross-version drift, not a quality change) and the activation peak. | Flash-Next oQ2.5e cold TTFT at 8K/32K/64K and peak memory for 2048/4096/8192 (yv speed + memory), KLD vs reference; the fastest value within the memory budget becomes the default and the flag is deleted | 2026-11-11 |
| `YUNSHU_QWEN4_LANE` | bool | off | reload | Qwen3.8-Flash-Next (qwen4_exp): run the dense quantized projections (GDN and attention mixers, out projections, indexer) as the row-invariant lane matmul for plain decode, speculative verify and drafting, instead of upstream's per-row singleton qmv. Upstream reads a dense weight once per verify row (T rows cost 1.4 / 2.4 / 8x the one-row dense time at T = 2 / 4 / 16); the lane matmul reads it once at any row count, with the same one-row time, and a row keeps its bits at every row count, so speculative output still equals plain decode. The output differs from the default arithmetic (last-bit drift, not a quality change). A head format upstream's fused head kernel cannot read (the oQ3e pack's 6-bit head) turns it on regardless, for the head and the dense projections. Prefill chunks wider than 32 rows keep MLX's quantized matmul. | Flash-Next oQ3e verify/decode step time at 1/2/4/16 rows lane vs singleton (microbench: dense 8-bit projections 1.0x vs 1.4-1.55x at 2 rows, 2.1-2.6x at 4, 7-9x at 16), spec on == spec off identity, MMLU drift, cold/warm TTFT with the 32-row prefill split; then default on and this flag deleted | 2026-10-25 |

## 內部設定

| Setting | Type | Default | Applies | Description |
|---|---|---|---|---|
| `YUNSHU_DEBUG_STREAM_CAPTURE` | path | unset | live | Debugging aid: append one JSON line per VLM-runner generation to this file with the generated token ids, the text pieces the engine handed to the gateway and their joined text, so a delivered answer can be compared with what was generated (soak invariant check). Off when unset. |


---

<!-- guides/debugging -->
---
title: 除錯與可觀測性
description: 一個開關同時開啟除錯路由、主機遙測、服務日誌、稽核日誌、token id 與生成擷取；主控台隨即顯示所有面板，並把引擎的請求狀態與頁面顯示並排比對。
---

`yunshu serve --observe`（或 `YUNSHU_OBSERVE=1`）會把你沒有明確設定的觀測功能全部開啟。凡是要監督的引擎都建議使用：問題直接在引擎自己的數字上看見，而不是從頁面猜。

## 會開啟什麼

| 設定 | observe 下的值 | 代價 |
| --- | --- | --- |
| `YUNSHU_DEBUG_ROUTES` | 開：`/debug/*` 路由（engine、system、requests、kv-cache、spec-decode、memory） | 只讀；不在解碼路徑上 |
| `YUNSHU_TELEMETRY` | `on`（取樣器唯一的模式，1 Hz） | 小而穩定的後續 TTFT 代價：27B、1K 文章約 +1.8%（約 11 ms），解碼速度在雜訊內相同；見[主機遙測](/docs/guides/telemetry) |
| `YUNSHU_SERVE_LOG` | 開，寫在 `~/.yunshu/logs` | 每個完成的請求一行純數字 JSON，有大小上限並輪替 |
| `YUNSHU_AUDIT_LOG_FILE` | `~/.yunshu/logs/audit.log` | 每個稽核操作一行 |
| `YUNSHU_REPLAY_TOKEN_IDS` | 開：要求的 logprobs 附上精確的 `token_id` | 每個 logprob token 數個位元組 |
| `YUNSHU_DEBUG_STREAM_CAPTURE` | `~/.yunshu/logs/stream_capture.jsonl` | 每次生成一行 JSON（token id 與文字片段）；沒有上限，用完請清除 |

你自己設定的值永遠優先，不論來源（旗標、環境變數、設定檔）；`yunshu config` 會把其餘項目的來源顯示為 `observe`。速度基準測試請關閉 observe：遙測有可量測的代價，開啟時量到的速度與關閉時不可比較。

## 誰能讀 `/debug/*`

規則不變：需要權杖（`YUNSHU_AUTH_TOKEN`）或 `YUNSHU_AUTH_DISABLED`。在 observe 下，**沒有**權杖的引擎也會回應來自本機（loopback）的 `/debug/*`，但僅限本機；來自網路的請求，或帶有 `X-Forwarded-For` 等代理標頭的請求會被拒絕。設定了權杖時一律需要權杖。不要在沒有權杖的情況下把 `/debug` 暴露在 `0.0.0.0`。

## 在主控台

當連線的引擎回報 observe 模式（`/v1/yunshu/status` 的 `observe: true`）：

- 診斷頁顯示所有群組（主機、請求、KV 與前綴快取、解碼、記憶體），並說明 observe 已開啟；若 `/debug` 讀不到，會直接說明而不是留白。
- 請求頁自動展開**除錯資料**區塊。每個進行中的請求都上下並列：本頁顯示的值，以及引擎 `/debug/requests` 回報的值——階段、預填進度（token）、已生成 token、進入引擎與首個 token 的時間。不一致的值標紅；`/debug` 不認得的請求以灰色顯示。開關可收合該區塊，選擇會記在這個瀏覽器。
- 推測解碼面板與主機面板也從同一組路由讀取計數器。

## 測試工具

`tfbench`、agentic 執行器與 `conc_probe` 會啟動或要求處於 observe 的引擎（`TFB_OBSERVE=0`、`AGENTIC_OBSERVE=0` 可讓純計時測試保持乾淨；`conc_probe` 遇到未回報 observe 的引擎會拒絕執行，除非加 `--allow-no-observe`）。`yv` 的 `smoke`、`identity`、`apc` 以 observe 執行，計時階段則明確關閉；`yv ab --observe` 讓所有階段都開啟，執行目錄的 `state.json` 會記錄各階段是否使用。


---

<!-- guides/features -->
---
title: 功能索引
description: 依領域列出 Yunshu 的每一項功能，附上狀態與涵蓋該功能的文件頁面。
---

本索引依領域列出所有已提供的功能。每一列標示功能名稱、用途、狀態，以及文件中涵蓋它的頁面。清單由儲存庫的功能索引（`docs/feature_index.json`）產生，並由測試確保與文件保持一致。

| 狀態 | 意義 |
|---|---|
| 穩定 | 如描述運作，且有測試或關卡涵蓋 |
| 部分支援 | 在摘要所述範圍內可用；其餘尚未實作或尚未驗證 |
| 實驗性 | 受實驗性設定控制；可能變更或移除 |

## 推論

| 功能 | 說明 | 狀態 | 文件 |
|---|---|---|---|
| 無損推測解碼 | DFlash2、MTP 與 prompt 複製式草稿，搭配 batch-invariant kernel；貪婪輸出與關閉推測時相同 | 穩定 | [推測解碼](/docs/internals/speculative-decoding) |
| 文字模型推測 | 針對 mlx-lm 模型的 n-gram / suffix 與 Gemma 4 assistant 草稿（外部 draft 模型是另一個輸出不相同的選項） | 穩定 | [推測解碼](/docs/internals/speculative-decoding), [選項](/docs/guides/options) |
| 前綴快取（APC） | 位於 RAM、SSD 與選用儲存層的精確混合 checkpoint；含圖片與音訊的快取鍵 | 穩定 | [前綴快取](/docs/internals/prefix-cache), [提示詞快取](/docs/guides/prompt-caching) |
| 結構化輸出 | 在解碼期間強制 JSON schema、regex、選項與 grammar，包含工具參數 | 穩定 | [結構化輸出](/docs/guides/structured-output), [約束解碼](/docs/internals/constrained-decoding) |
| 有損記憶體選項 | int8 KV、壓縮的 WARM 層與載入時量化；預設關閉 | 穩定 | [選項](/docs/guides/options), [記憶體管理](/docs/internals/memory), [設定](/docs/guides/configuration) |
| 大型 MoE 載入（部分支援） | 從張量形狀推導社群版 DeepSeek-V4-Flash 的位元數與 group size；載入前先做容量檢查 | 部分支援 | [模型支援](/docs/guides/model-support) |
| Round driver（實驗性） | Yunshu 自有、針對 dense Qwen3.5 系列模型的推測 round driver | 實驗性 | [Round driver](/docs/developers/round-driver) |
| 模型支援 | 依系列說明哪些已調校、哪些走通用路徑、哪些已驗證 | 穩定 | [模型支援](/docs/guides/model-support) |
| 下一回合預演 | 符合條件的文字回覆之後，以標準 stride 做 APC 預演；boundary/exact 是會改變數值、須明確啟用的選項 | 穩定 | [預填與預演](/docs/internals/prefill-and-rehearsal) |
| 多列推測 | 每個請求都是 round driver 的一個 row；並行 row 也會一起起草（MTP 鏈、共用驗證預算的 DFlash2 草稿） | 穩定 | [推測解碼](/docs/internals/speculative-decoding) |

## API

| 功能 | 說明 | 狀態 | 文件 |
|---|---|---|---|
| OpenAI API | Chat、Completions、Responses（HTTP 與 WebSocket）、Embeddings、Models、Files、Batches、Conversations | 穩定 | [Chat Completions](/docs/api/chat-completions), [Responses](/docs/api/responses), [Embeddings](/docs/api/embeddings), [Models](/docs/api/models), [Files](/docs/api/files), [Batches](/docs/api/batches) |
| Anthropic API | Messages、count_tokens、batches、thinking、tools、cache_control、文件與引用 | 穩定 | [Messages](/docs/api/messages), [Batches](/docs/api/batches) |
| Ollama API | /api/chat、/api/generate 與原生模型管理（pull、copy、delete、show） | 穩定 | [Ollama](/docs/api/ollama) |
| Responses 延伸功能 | 由用戶端執行的 computer 工具、conversations、compaction、previous_response_id | 穩定 | [Responses](/docs/api/responses) |
| 已儲存的 chat completions | store: true，之後可列出、取得、更新、刪除並列出訊息 | 穩定 | [儲存的 completions](/docs/api/stored-completions) |
| Evals | OpenAI Evals API，支援 string-check、相似度與本機模型 grader | 穩定 | [Evals](/docs/api/evals) |
| 型別化決策 | 單次 forward 內回傳 yes/no、選項與分數答案及機率，不產生文字 | 穩定 | [Decisions](/docs/api/decisions) |
| Batches、Files 與分詞 | OpenAI 與 Anthropic batches、Files API、tokenize / detokenize / apply-template / props | 穩定 | [Batches](/docs/api/batches), [Files](/docs/api/files), [Tokenization](/docs/api/tokenization) |
| 傳輸方式 | SSE、WebSocket 串流、Unix socket、HTTP/2、選用的 WebRTC | 穩定 | [傳輸方式](/docs/guides/transports) |
| Yunshu 擴充 | 請求 id、即時階段、prefill 進度、取消、期限、x_yunshu 統計、暖機、記憶體單位 | 穩定 | [擴充](/docs/api/extensions) |
| Prompt 快取 API | 三種方言中的 cache_control 與快取 token 計量 | 穩定 | [提示詞快取](/docs/guides/prompt-caching) |

## Agent 與工具

| 功能 | 說明 | 狀態 | 文件 |
|---|---|---|---|
| 程式碼 Agent | Claude Code、Codex 與 opencode 透過各自的 API 運作；`yunshu launch` | 穩定 | [Agent](/docs/guides/agents), [Agent 相容性](/docs/developers/agent-compat) |
| 網路搜尋與擷取 | 伺服器端 web_search / web_fetch 並附引用；DuckDuckGo、Wikipedia、SearXNG、Tavily、Serper、Perplexity | 穩定 | [網路搜尋](/docs/guides/web-search), [伺服器端工具](/docs/api/server-tools) |
| 程式碼執行 | Anthropic code_execution（bash 加文字編輯器）在 sandbox-runtime 內於本機執行；需手動啟用，預設無網路 | 部分支援 | [程式碼執行](/docs/guides/code-execution), [程式碼執行沙箱](/docs/internals/code-execution-sandbox) |
| Tavily 相容 API | search、extract、crawl、map、research 與 MCP，含提供者健康度退避 | 穩定 | [Tavily](/docs/guides/tavily) |
| MCP | 原生 MCP 端點，以及請求中指名的遠端 MCP 伺服器 | 穩定 | [MCP](/docs/api/mcp) |
| 用戶端設定 | curl、OpenAI 與 Anthropic SDK、Open WebUI | 穩定 | [用戶端](/docs/guides/clients) |
| 合格的輔助請求排程 | 已擷取的 opencode 標題指紋讓位給互動式 VLM 回合並隔離 APC；未知請求維持正常優先度 | 穩定 | [輔助請求排程](/docs/developers/auxiliary-scheduling) |

## 多模態

| 功能 | 說明 | 狀態 | 文件 |
|---|---|---|---|
| 圖片、音訊與影片輸入 | mlx-vlm 模型在 Chat、Responses 與 Messages 中接受媒體；媒體會納入快取鍵 | 穩定 | [多模態](/docs/guides/multimodal) |
| 語音對語音（部分支援） | Qwen3-Omni 原生語音；重複圖片與音訊 APC 有限定範圍的一致性收據；圖片加音訊的合併重用尚未驗證 | 部分支援 | [多模態](/docs/guides/multimodal), [Realtime](/docs/api/realtime) |
| Realtime 語音 | WebSocket 與選用的 WebRTC、伺服器端 VAD、打斷、短期 client secret、本機語音 | 穩定 | [Realtime](/docs/api/realtime) |
| 語音轉文字、文字轉語音 | transcriptions、translations、speech 與 voices | 穩定 | [Audio](/docs/api/audio) |
| OCR 與圖片生成 | GLM-OCR 文字擷取；圖片 generations、edits 與 variations | 穩定 | [OCR](/docs/api/ocr), [Images](/docs/api/images), [多模態](/docs/guides/multimodal) |
| Embeddings、rerank、score、classify | 文字與多模態 embeddings、cross-encoder rerank、訓練好的分類 head | 穩定 | [Embeddings](/docs/api/embeddings), [Rerank](/docs/api/rerank) |

## 維運與主控台

| 功能 | 說明 | 狀態 | 文件 |
|---|---|---|---|
| 網頁主控台 | 即時請求階段、歷史、日誌、模型、下載、快取、playground、金鑰、設定、狀態島 | 穩定 | [主控台](/docs/getting-started/console) |
| 主控台程序與歷史紀錄 | 主控台與引擎分開執行（yunshu console，連接埠 8100，不使用 MLX）：引擎停止時仍可使用，保留 30 天的 1 秒 / 10 秒 / 1 分鐘歷史與僅含中繼資料的請求日誌，中斷期間以空缺呈現 | 穩定 | [主控台程序](/docs/internals/console-process) |
| 主控台自動跟隨引擎 | yunshu console --engine auto 會探測本機連接埠（GET /health），跟隨最新且存活的 Yunshu 引擎，健康時持續使用，可從狀態島釘選其中一個，並顯示「等待引擎」而非錯誤；歷史會把每次引擎啟動記為獨立的工作階段 | 穩定 | [主控台](/docs/getting-started/console), [主控台程序](/docs/internals/console-process) |
| API 金鑰與配額 | 多組金鑰，支援範圍、到期、每把金鑰的用量與每日配額 | 穩定 | [驗證、API 金鑰與 CORS](/docs/guides/auth-and-keys) |
| 設定與 CORS 編輯器 | 從主控台或 API 寫入引擎設定（需重啟的會提示）並編輯 CORS | 穩定 | [驗證、API 金鑰與 CORS](/docs/guides/auth-and-keys), [主控台](/docs/getting-started/console) |
| 主機遙測 | 功耗、GPU 時脈、溫度、散熱與記憶體壓力、每個請求的能耗估計、Prometheus | 穩定 | [主機遙測與能耗](/docs/guides/telemetry) |
| 命令列 | setup、doctor、models list/pull/rm/show、top、service、completions 與推論指令 | 穩定 | [CLI 參考](/docs/guides/cli) |
| 登入服務 | launchd agent、重啟與日誌 | 穩定 | [服務](/docs/getting-started/service) |
| 設定 | 單一設定註冊表：環境變數、TOML 檔或 `--set` | 穩定 | [設定](/docs/guides/configuration) |
| 安全性 | 驗證 token、CORS 憑證規則、重新導向時剝除標頭、機密遮蔽、SSRF 防護 | 穩定 | [驗證、API 金鑰與 CORS](/docs/guides/auth-and-keys) |
| 首次執行與疑難排解 | 安裝、選擇模型、就緒檢查、修復方式 | 穩定 | [安裝](/docs/getting-started/install), [快速開始](/docs/getting-started/quickstart), [疑難排解](/docs/guides/troubleshooting) |
| 效能基準與精確度 | 每個數字的來源、如何重現，以及精確度關卡 | 穩定 | [效能實測](/docs/guides/benchmarks) |
| 模型生命週期控制 | 需驗證的載入 / 下載取消、本機與 Hugging Face 快照註冊，以及卸載影響 | 穩定 | [主控台](/docs/getting-started/console) |


---

<!-- guides/model-support -->
---
title: 模型支援
description: Yunshu 支援哪些模型系列與模態，以及每一種使用哪條服務路徑與選用的額外套件。
---

Yunshu 載入 MLX 檢查點。它會根據資料夾中的檔案與 `config.json` 偵測模型種類，再為它選擇引擎。上游（`mlx-lm`、`mlx-vlm` 或 `mlx-audio`）能載入某個模型，並不代表 Yunshu 的每個端點與功能都已針對該模型驗證。`GET /v1/models` 為每個模型回傳的模型卡（位於每個項目的 `yunshu` 欄位）描述了已載入模型能做什麼；在依賴工具呼叫、結構化輸出、logprobs 或媒體輸入之前，請先查看它。

## 支援層級

| 層級 | 模型 | 意義 |
|---|---|---|
| 完整調校 | Qwen3.8-27B（第一個完整調校的檢查點） | 推測式解碼、前綴重用與批次不變（batch-invariant）解碼路徑都是針對它開發與量測。 |
| 第一級 | Qwen3.5 系列（`qwen3_5`、`qwen3_6`、`qwen3_5_moe` 模型類型） | 推測式解碼（MTP 或相符的 drafter）與前綴快取。 |
| 通用文字 | 其他 `mlx-lm` 模型 | 由文字快速路徑服務。上限取決於上游支援。 |
| 通用視覺語言 | 其他 `mlx-vlm` 模型 | 由 VLM batch runner 服務。適用各模型特有的媒體、模板與能力限制。 |
| 其他模態 | 語音、嵌入、排序、OCR、影像生成 | 透過各自的引擎與選用額外套件提供；見下文。 |

## 服務路徑

| 路徑 | 適用對象 | 行為 |
|---|---|---|
| VLM batch runner | 所有經由 `mlx-vlm` 服務的模型，包括以 `vision` 額外套件載入的 Qwen3.5 / 3.6 / 3.8 系列 | 連續批次處理，每個請求獨立取樣。一次只預填一個請求。對可還原檢查點的模型系列（含特定模型的精確視窗支援）提供自動前綴快取，鍵值也包含圖片與音訊特徵，並可選用 SSD 層。接受圖片、音訊與影片輸入。 |
| 推測式草稿（Qwen3.5 系列與 Flash-Next） | `qwen3_5`、`qwen3_6`、`qwen3_5_moe` | 在 round driver 的封裝 row 上進行 MTP 或 DFlash 草稿生成，使用批次不變的解碼與驗證核心，使開啟草稿的輸出與關閉草稿時相同。由 `YUNSHU_MTP`（預設開啟）與 `YUNSHU_VLM_DRAFT` 控制。並行 row 會一起進行草稿生成。 |
| 文字快速路徑 | 純文字 `mlx-lm` 模型 | 透過 `mlx-lm` 一次處理一個請求；並行的請求會依序處理。 |

VLM 路徑的限制：視覺語言模型會拒絕 LoRA adapter 與自訂 logits processor。Qwen3.5 系列模型將使用哪一條推測路徑，可由 `yunshu doctor -m <model>` 的 `speculative` 列與啟動記錄得知。

## 模態與對應的路由

偵測是針對模型資料夾進行。「額外套件」欄指的是[安裝](/docs/getting-started/install)中該引擎所需的選用額外套件。

| 模型種類 | 偵測到的類型範例 | 路由 | 額外套件 | 狀態 |
|---|---|---|---|---|
| 文字 LLM | 任何 `mlx-lm` 模型類型 | `POST /v1/chat/completions`、`POST /v1/completions`、`POST /v1/responses`、`POST /v1/messages` | 無 | <Support status="supported">支援</Support> |
| 視覺語言 | 具有 `vision_config` 的模型，例如 Qwen-VL、Pixtral、Mistral 3 與 Qwen3.5 系列 | 相同的對話路由，並可帶入圖片 | `vision` | <Support status="supported">支援</Support> |
| 語音轉文字 | `whisper`、`qwen3_asr`、`parakeet`、`qwen2_audio` | `POST /v1/audio/transcriptions`、`POST /v1/audio/translations` | `audio` | <Support status="supported">支援</Support> |
| 文字轉語音 | `qwen3_tts`、`kokoro`、`chatterbox` | `POST /v1/audio/speech` | `audio` | <Support status="supported">支援</Support> |
| 原生語音對語音 | Qwen3-Omni（具有 Talker 的模型） | `POST /v1/omni/speech/stream`，以及 Realtime socket | `omni` | <Support status="partial">部分支援</Support> |
| OCR | 類型或名稱含 `ocr` 的模型 | `POST /v1/ocr` | `vision` | <Support status="supported">支援</Support> |
| 嵌入 | `mlx-embeddings` 模型、EmbeddingGemma 2、Qwen3-VL-Embedding | `POST /v1/embeddings` | `embeddings` | <Support status="supported">支援</Support> |
| 重排序與評分 | Cross-encoder 重排序模型、序列分類頭 | `POST /v1/rerank`、`POST /v1/classify`、`POST /v1/score` | 視模型而定（`embeddings` 或 `vision`） | <Support status="supported">支援</Support> |
| 影像生成 | `flux`、`sd3`、`sdxl`、`z_image` | `POST /v1/images/generations`、`POST /v1/images/edits`、`POST /v1/images/variations` | `generation` | <Support status="supported">支援</Support> |
| 型別化決策 | Clef / Clef-flash 聯合 schema 頭 | `POST /v1/decisions` | `vision` | <Support status="partial">部分支援</Support> |
| 影片生成 | Wan、LTX 等 | 無 | | <Support status="unsupported">尚未支援</Support> |
| 獨立的語音對語音 | 語音轉換、語音增強模型 | 無 | | <Support status="unsupported">尚未支援</Support> |

關於部分支援的列：

- **原生語音對語音**在所服務的模型具有 Talker（Qwen3-Omni）時運作。語音路徑會重用已載入的模型，而不會另外載入第二份。對其他模型，或設定 `YUNSHU_REALTIME_OMNI=off` 時會關閉，此時 Realtime 會退回「語音轉文字、再交給 LLM、再文字轉語音」的串接流程。大型 Omni 檢查點需要大量統一記憶體。
- **型別化決策**只接受 Clef 聯合 schema 頭。其他決策頭系列會被拒絕，把對話模型送到決策路由會回傳錯誤。

被偵測為影片或獨立語音對語音的模型會載入失敗並附上說明，同時列出支援的種類為影像、音訊與 LLM 模型。缺少額外套件時，相關路由會回報缺少的相依套件，而不是回傳佔位輸出（例如沒有 `generation` 額外套件時，`POST /v1/images/generations` 會回傳 503）。

## 單一模型與多模型服務

`yunshu serve -m <model>` 服務單一模型，並把請求的 `model` 欄位視為參考用途。`yunshu serve --models-dir <dir>` 會登錄它找到的所有模型並依需求載入；每個模型的引擎類型（文字、視覺、音訊、影像、決策）依上述偵測結果決定。請見[模型](/docs/getting-started/models)。

## 驗證模型

在依賴某個檢查點之前，請先檢查：

1. `yunshu doctor -m <model>` 檢查資料夾是否完整、記憶體是否放得下。
2. 在 `GET /v1/models` 中查看該模型項目的能力。
3. 針對你依賴的每項功能（工具呼叫、JSON schema、串流、停止序列、logprobs、取消），對執行中的伺服器送出請求實測。

此表描述的是程式碼所處理的範圍，並不保證某個系列的每個檢查點都能搭配每項功能運作。

## Qwen3.8-Flash-Next 在 80 GB 內執行(qwen4_exp)

`Jundot/Qwen3.8-Flash-Next-oQ4e-mtp` 磁碟上 106 GB,其中 32 GB 是每層 n-gram 嵌入表(PLE)。Yunshu 從 SSD 逐列讀取 PLE,不載入整張表,常駐權重剩 74.3 GB(含 1.5 GB 的 MTP head)。

1. 建立一次外部 PLE 檢視(硬連結,不複製資料,原始模型不變;來源與檢視必須在同一個磁碟):`python scripts/research/flashnext80_prepare_view.py <pack> <pack>-ple-ssd`。
2. 以檢視啟動:`YUNSHU_MAX_MEMORY_GB=74.5 yunshu serve -m <pack>-ple-ssd`。MTP head 會自動使用(每輪一個草稿);APC SSD 層預設開啟。

設定記憶體上限後,Yunshu 會把釋放緩衝池保持在 0.5 GiB,並在第一個圖片請求前不載入視覺塔。兩者皆無損;可用 `YUNSHU_PREFILL_BUFFER_CACHE_GB` 覆寫緩衝池。

Historical external-PLE prototype measurements (including pre-fused-kernel runs), not current release speed or an 80 GB served-peak guarantee. The 0.1.5 snapshot measures Flash-Next at 32K / 64K: 67.050 / 56.750 tok/s; cold TTFT 33.243 / 68.247 s, warm 0.132 / 0.229 s, immediate follow-up 2.474 / 2.918 s. [Current evidence](/docs/guides/benchmarks).

| 上下文(M5 Max 128 GB,MTP 開,整機記憶體差值) | 穩態 | 冷 prefill 峰值 | 解碼 |
|---|---:|---:|---:|
| 1K | 75-76 GB | 77 GB | 70 tok/s |
| 8K | 77 GB | 79 GB | 66 tok/s |
| 32K | 75 GB | 80 GB | 37-38 tok/s(融合核心之前) |
| 約 169K,命中 SSD APC(第二次請求) | 75 GB | 81 GB | 22 tok/s,首 token 1.2 秒 |
| 約 169K,冷啟動 | 75 GB | 84-85 GB | 21 tok/s |

冷 prefill 超過約 32K 時,峰值需要約 83-85 GB(多出的是 prefill 工作記憶體);同一個提示從 SSD 提示快取提供則維持在約 81 GB。開關推測解碼、命中或未命中提示快取,輸出完全相同。解碼使用融合的 hyper-connection 與 router/expert Metal 核心(源自 TensorFold,Apache-2.0),不開推測時 1K 為 65 tok/s、8K 為 55;MTP 在 1K 約增加 8%、8K 約增加 20%,因為每多一列驗證就多讀一批專家。思考模式 MMLU-Pro(300 題,貪婪解碼):261/300 = 0.870 (0 parse failures; the 27B oQ4e gate protocol gives 0.833)。

## 相關頁面

- [結構化輸出](/docs/guides/structured-output)
- [提示快取](/docs/guides/prompt-caching)
- [CLI 參考](/docs/guides/cli)
- [疑難排解](/docs/guides/troubleshooting)


---

<!-- guides/multimodal -->
---
title: 多模態與檢索端點
description: 哪些路由提供圖片、音訊、影片、語音、Realtime 語音、OCR、圖片生成、embeddings 與 rerank，各需要哪些 extra，以及限制在哪裡。
---

選用的 extra 會安裝所需的相依套件：`pip install 'yunshu[audio]'`、`[vision]`、`[generation]`、`[embeddings]` 與 `[omni]`。每個路由都需要支援它的模型；`GET /v1/models` 會告訴你哪些可用。請求格式請見下方連結的 API 參考頁面。

<Callout type="info">
語音、ASR、TTS、圖片生成與 OCR 是支援的能力，不是調校的主要路徑。功能依 checkpoint 而異，並逐模型驗證：請見[模型支援](/docs/guides/model-support)。
</Callout>

## 路由

| 能力 | 路由 | Extra | 備註 |
|---|---|---|---|
| 以圖片、音訊與影片作為聊天輸入 | `/v1/chat/completions`、`/v1/responses`、`/v1/messages` | 無（mlx-vlm 模型） | 媒體會納入前綴快取的鍵 |
| Qwen3-Omni 語音對語音 | `POST /v1/omni/speech/stream` | `omni` | 輸出文字與音訊；`examples/talk.py` |
| Realtime 語音 | `WS /v1/realtime`（與 `/realtime`） | `audio` | 伺服器端 VAD、插話打斷、原生 omni 語音或 ASR、LLM、TTS 串接。請見 [Realtime](/docs/api/realtime) |
| 語音轉文字 | `/v1/audio/transcriptions`、`/v1/audio/translations` | `audio` | 翻譯需要 Whisper 模型。請見[音訊](/docs/api/audio) |
| 文字轉語音 | `/v1/audio/speech`、`GET /v1/audio/voices` | `audio` | 對需要參考音訊的模型，可用音訊樣本在本機註冊聲音 |
| OCR | `POST /v1/ocr` | `vision` | GLM-OCR；`yunshu ocr`；主控台中也有；[OCR API](/docs/api/ocr) |
| 圖片生成、編輯、變化 | `/v1/images/generations`、`/edits`、`/variations` | `generation` | `yunshu image`、`image-edit`、`image-variations`。請見[圖片](/docs/api/images) |
| Embeddings | `POST /v1/embeddings` | `embeddings` | 文字，以及（支援的模型）圖片、音訊與影片。請見 [Embeddings](/docs/api/embeddings) |
| Rerank、score、classify、pooling | `/v1/rerank`、`/v1/score`、`/v1/classify`、`/v1/pooling` | `embeddings` | cross-encoder rerank 與訓練過的分類頭，採用 vLLM 語意。請見 [Rerank](/docs/api/rerank) |
| 型別化決策 | `/v1/decisions`、`/v1/systemone` | 無 | 請見 [Decisions](/docs/api/decisions) |

## 從命令列試用

<Steps>
<Step>

服務一個支援該能力的模型，例如用 `speak` 就需要 TTS 模型。

</Step>
<Step>

執行對應的指令：

```bash
yunshu speak "Hello from Yunshu" -o hello.wav     # needs a TTS model served
yunshu transcribe hello.wav                       # needs an ASR model
yunshu ocr page.png
yunshu embed "a sentence"
yunshu rerank "query" "doc one" "doc two" --top-n 1
```

</Step>
</Steps>

關於透過 WebSocket 或 WebRTC 使用 Realtime，請見[傳輸方式](/docs/guides/transports)。暫時性的 client secret 由 `POST /v1/realtime/client_secrets` 取得。

## 限制

- Realtime 的僅轉錄 session 設定會被回傳，但不會以僅轉錄 session 的方式執行。
- 前綴重用取決於快取佈局。Gemma 4 有限定範圍的精確視窗還原憑證；請勿據此推斷所有旋轉快取模型都受支援。
- Qwen3-Omni 重複圖片的前綴重用有限定範圍的命中與未命中一致性憑證；圖片加音訊合併的快取重用尚未驗證。請見[模型支援](/docs/guides/model-support)。


---

<!-- guides/options -->
---
title: 可能改變輸出的選項
description: 輸出不保證與預設路徑相同的選用設定，以及將它們與無損預設值區分開來的規則。
---

Yunshu 的規則很單純：**無損**最佳化（與一般路徑產生相同的 token）可以成為預設值；**有損或輸出不相同**的最佳化則是穩定的使用者選項，預設關閉，不會因為某次基準測試就替你打開。本頁列出所有這類選項。預設值定義在設定註冊表（`python/yunshu_engine/settings.py`），實際生效的值可用 `yunshu config` 查看。完整設定表請見[設定](/docs/guides/configuration)。

<Callout type="warn">
第一節的兩個選項（`YUNSHU_SPEC_UNVERIFIED`、`YUNSHU_DRAFT_MODEL`）是穩定選項，不是實驗功能，但**不保證產生與預設路徑相同的 token**。只有在你接受輸出可能與一般解碼不同時才開啟。每個選項的限制見下文。
</Callout>

## 輸出不相同的服務選項

這四個選項都只適用於純文字的 `mlx-lm` 模型。Qwen3.5 系列的 VLM runner 有自己的無損推測解碼（MTP、DFlash），不使用它們。請見[推測解碼](/docs/internals/speculative-decoding)。

| 設定 | 預設值 | 作用 |
|---|---|---|
| `YUNSHU_SPEC_UNVERIFIED` | `''`（關閉）或 `eagle` | 在文字模型上啟用以外部 `mlx-lm` draft 模型進行的推測解碼 |
| `YUNSHU_DRAFT_MODEL` | 未設定 | `YUNSHU_SPEC_UNVERIFIED=eagle` 使用的 draft 檢查點路徑 |

### 外部 draft 模型（`YUNSHU_SPEC_UNVERIFIED` 與 `YUNSHU_DRAFT_MODEL`）

`YUNSHU_SPEC_UNVERIFIED=eagle` 會載入由 `YUNSHU_DRAFT_MODEL` 指定的另一個較小的 `mlx-lm` 檢查點（`python/yunshu_engine/batched_engine.py` 的 `_init_external_lm_spec`），並用它產生草稿。若未設定 `YUNSHU_DRAFT_MODEL`，引擎會在模型設定中找 `draft_model_path`；兩者都沒有時就什麼都不載入，開關未設定時絕不會載入第二個模型。

- `eagle` 是歷史遺留的路由名稱。一般語言模型就能當 draft，不需要訓練過的 EAGLE head。
- 只有貪婪（temperature 為 0 或未設定）、非串流、要求推測或預設啟用推測、且使用預設取樣與懲罰參數的請求才會走這條路。Schema 或文法限制、自訂 logits processor、stop 字串、思考預算、LoRA 與 token mask 選項仍走一般快速路徑，logprobs 請求也是。
- 輸出不保證與一般解碼逐 token 相同。註冊表記錄 2026-10-24 的一次檢查中，試過的每個提示都出現差異，速度則依提示從變慢到變快不等；這些數字不在基準測試紀錄中，因此這裡不引用。
- 當你有一個與大型文字模型相配的小型 draft，且重視速度勝過精確重現時才使用。要無損推測請用 n-gram 或 suffix 草稿（`YUNSHU_NGRAM_DEFAULT`、`YUNSHU_SPEC_PROPOSER`）或 Qwen3.5 系列 runner。

## 有損記憶體選項

這些選項以品質換取記憶體或磁碟。全部預設關閉（預設值是無損值）。有損選項不會因為基準測試而變成預設值。

| 設定 | 無損預設值 | 有損值 | 作用 |
|---|---|---|---|
| `YUNSHU_KV_PRECISION` | `bf16` | `int8` | Qwen3.5 系列共用解碼批次使用 int8 KV；記憶體與頻寬較少，注意力有小誤差。單一請求與推測 lane 維持 bf16 |
| `YUNSHU_KV_QUANT_BITS` | `off` | `auto`、`2`、`3`、`4`、`8` | 文字引擎的量化 KV 快取 |
| `YUNSHU_PREFIX_HOT_LIMIT` | `0`（全部完整精度） | 一個數量 | 只讓該數量的前綴 KV 項目維持完整精度，較舊的以 4-bit 存放在 RAM；重用時有損 |
| `YUNSHU_SSD_CACHE_PRECISION` | `native` | `int8` | 文字 SSD 前綴快取以逐 tensor int8 儲存；重用時有損 |
| `YUNSHU_VLM_APC_WARM` | `off` | `int8`、`int4` | 壓縮的 WARM 前綴層；命中時還原的是反量化的 K/V，輸出可能與冷 prefill 不同。`lossless` 則是精確的 |
| `YUNSHU_QUANT_MODE` | `''`（沿用檢查點） | `mxfp4`、`nvfp4`、`mxfp8`、`affine` | 載入時在記憶體中量化權重 |

`YUNSHU_QUANT_CONFIG` 設定 `affine` 的位元數與群組大小。記憶體管理請見[記憶體管理](/docs/internals/memory)。

## 規則

| 類型 | 例子 | 可以成為預設值嗎？ |
|---|---|---|
| 無損（輸出相同） | 佈局、kernel、排程器、batch-invariant 推測、無損快取壓縮 | 可以，需先通過 A/B 與一致性檢查；可保留關閉選項 |
| 有損或輸出不相同 | 本頁所有選項 | 不可以。作為穩定選項，預設為無損值 |

要確認某個選項是否改變你的輸出，請用相同提示在開啟與關閉下各做一次貪婪解碼並比對 token；一致性工具請見[驗證](/docs/developers/verification)。


---

<!-- guides/prompt-caching -->
---
title: 提示詞快取
description: Yunshu 如何重用共同提示詞前綴的 KV 快取、命中如何顯示在 usage 中，以及控制記憶體、SSD 儲存與精度的選項。
---

代理與聊天的流量會一再重複：每一輪都會重送 system prompt、工具清單與到目前為止的整段對話。Yunshu 會保留先前提示詞的注意力狀態（KV 快取），當新的提示詞以相同的 token 開頭時，就略過那一段的預填，只處理新增的 token。這會降低第一輪之後每一輪的首 token 延遲，而且不需要修改用戶端。

重用是**自動**的。下面提到的各 API 方言欄位（`cache_control`、`prompt_cache_breakpoint`）只是建立在同一份快取之上的提示與回報控制，並非必要。

## 快取如何運作

有兩條服務路徑，各自有自己的前綴快取。

| 服務路徑 | 服務對象 | 前綴快取 | 說明 |
|---|---|---|---|
| VLM batch runner | 所有 `mlx-vlm` 模型，包含 Qwen3.5 家族 | APC（automatic prefix cache），使用精確檢查點 | 以提示詞 token 為鍵；視覺與音訊輸入另以媒體內容為鍵。預設開啟，有 RAM 預算與 SSD 層 |
| 純文字快速路徑 | 純文字 `mlx-lm` 模型 | `KVPrefixCache` | RAM 項目，另有選用的 SSD 層（預設關閉） |

命中的條件是新提示詞必須以快取中的 token 完全相同地開頭。提示詞前段任何變動（例如每一輪都會變的 system reminder）都會讓之後的內容位移，降低重用率。對含有循環層的模型（Qwen3.5 家族混用注意力與 GatedDeltaNet 層），VLM runner 儲存的是精確檢查點，同時包含某個 token 位置的注意力 KV 與循環狀態，所以命中時還原的狀態與冷啟動預填產生的完全一致。

除了對話本身的檢查點，VLM runner 也會為 system 回合的結尾（system prompt 加工具清單）保留一個檢查點，因此以相同 system prompt 與工具開始的新工作階段可以重用這個開頭。對話變長時，較新的檢查點會取代作為其前綴的舊檢查點，所以一段長對話只會保留一份，而不是每輪一份。

## 在 usage 中看到快取命中

各方言的標準 usage 欄位會回報有多少提示詞 token 來自快取。

| API | 欄位 |
|---|---|
| Chat Completions | `usage.prompt_tokens_details.cached_tokens` |
| Responses | `usage.input_tokens_details.cached_tokens` |
| Messages | `usage.cache_read_input_tokens`（從快取讀取的 token）與 `usage.cache_creation_input_tokens`（本輪寫入的可快取前綴）。`input_tokens` 是其餘部分，所以三者相加等於提示詞大小 |

串流時，相同的欄位會出現在 usage chunk（chat，需 `stream_options: {"include_usage": true}`）、`response.completed` 事件（Responses）以及 Messages 的 usage 事件中。

```json
{
  "usage": {
    "prompt_tokens": 3273,
    "completion_tokens": 120,
    "total_tokens": 3393,
    "prompt_tokens_details": { "cached_tokens": 3264 }
  }
}
```

Yunshu 另外加入一個 `x_yunshu` 物件（非串流回應還有 `X-Yunshu-Cached-Tokens`、`X-Yunshu-Cache-Tier` 與 `X-Yunshu-Cache-Reload-Ms` 標頭），說明命中來自哪一層。這些是附加欄位，SDK 會直接忽略。

```json
"x_yunshu": {
  "cached_tokens": 13867,
  "cache": { "tier": "ram", "cached_tokens": 13867, "reload_ms": 41.2 }
}
```

`tier` 為 `ram`、`warm`、`ssd` 或 `none`。`reload_ms` 是查找花費的時間，包含從 SSD 讀取。設定了多個儲存層時，`ssd` 命中還會帶有 `device`。未知的欄位為 `null`。

### 用 OpenAI SDK 驗證

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

long_context = "You are a careful assistant. " + "Reference text. " * 600
for question in ["What is this about?", "Summarize it in one line."]:
    r = client.chat.completions.create(
        model="local",
        messages=[
            {"role": "system", "content": long_context},
            {"role": "user", "content": question},
        ],
        max_tokens=64,
    )
    print(r.usage.prompt_tokens, r.usage.prompt_tokens_details.cached_tokens)
```

第一次呼叫的 `cached_tokens` 很小或為零；第二次會回報提示詞的大部分。

## 請求欄位

### Anthropic `cache_control`

在 `POST /v1/messages` 上，`cache_control: {"type": "ephemeral"}` 可標記 system 區塊、訊息內容區塊或工具上的快取斷點；頂層的 `cache_control` 也會被接受，作為自動標記。`ttl` 可為 `"5m"`（預設）或 `"1h"`；最多支援四個斷點。

```python
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:8000", api_key="sk-local")

msg = client.messages.create(
    model="local",
    max_tokens=128,
    system=[
        {"type": "text", "text": "<long reference document>", "cache_control": {"type": "ephemeral"}},
    ],
    messages=[{"role": "user", "content": "Question about the document."}],
)
print(msg.usage.cache_creation_input_tokens, msg.usage.cache_read_input_tokens)
```

需要知道的行為：

- 標記只是提示，請求不會因為標記而被拒絕。如果模型的聊天模板丟掉或重複了標記（Qwen 模板會移除先前回合的推理內容，所以放在思考區塊上的標記會消失），請求會在沒有明確檢查點的情況下處理，並在伺服器日誌中寫明原因。
- 在 VLM runner 上，標記會經由實際的聊天模板（包含原生工具定義）對應，`cache_creation_input_tokens` 與 `cache_read_input_tokens` 回報的是真實的檢查點寫入與讀取。
- 在純文字快速路徑上，只會讀取 `system` 區塊上的標記。訊息區塊上的標記在那裡不會被偵測，因此它的 `cache_creation_input_tokens` 與 `cache_read_input_tokens` 維持 0，不過前綴快取仍會自動重用該前綴。

### OpenAI `prompt_cache_*`

Chat Completions 與 Responses 都接受 OpenAI 風格的欄位。

| 欄位 | 行為 |
|---|---|
| `prompt_cache_key` | <Support status="partial">接受並傳遞，但不會路由或分割快取。是否重用只由提示詞 token 決定</Support> |
| `prompt_cache_retention` | <Support status="partial">接受；在 VLM runner 上作為 `prompt_cache_options` 的預設 `ttl`</Support> |
| `prompt_cache_options` | <Support status="supported">VLM runner：</Support>`{"mode": "implicit" \| "explicit", "ttl": "30m" \| "24h" \| "in_memory"}`。未提供時套用預設的自動重用 |
| 文字內容片段上的 `prompt_cache_breakpoint` | <Support status="supported">VLM runner：</Support>在該片段結尾設定明確斷點，必須放在文字片段上 |

在純文字快速路徑上，這些欄位會被接受，但除了自動前綴重用之外沒有其他作用。

## 哪些模型不支援

前綴重用需要能在前綴邊界還原的檢查點。VLM runner 已有特定模型的精確視窗支援（Gemma 4 有具日期的命中／未命中一致性驗證），但不代表所有 rotating cache 模型皆支援。請查閱[模型支援](/docs/guides/model-support)及已載入模型的能力契約。純文字快速路徑的混合／循環與滑動視窗快取仍無法重用已儲存前綴。

## 記憶體與儲存選項

所有設定都在設定註冊表中，完整列表見[設定](/docs/guides/configuration)。

### VLM runner（APC）

| 設定 | 預設 | 說明 |
|---|---|---|
| `YUNSHU_VLM_APC_MEMORY_GB` | 自動 | RAM 預算（GiB）；`0` 停用前綴快取。未設定時：取權重與系統保留量之後剩餘記憶體的一半，上限為機器記憶體的四分之一與 32 GiB，剩餘不到 1 GiB 時關閉 |
| `YUNSHU_VLM_APC_DISK` | 開 | SSD 層：被 RAM 淘汰的檢查點（以及關機時仍在 RAM 的檢查點）會寫到磁碟，下次直接讀回而不重新計算。位元精確、無損；快取可跨重啟保留。設為 `0` 則只用 RAM |
| `YUNSHU_VLM_APC_DISK_DIR` | `~/.yunshu/cache/apc` | SSD 層的位置；可指向快速的外接磁碟以保持內建磁碟乾淨 |
| `YUNSHU_VLM_APC_DISK_GB` | 自動 | 整個目錄的 SSD 層容量上限（未設定：磁碟區的四分之一，最多 64 GiB） |
| `YUNSHU_VLM_APC_DISK_TIERS` | 未設定 | SSD 目錄之下的更多儲存層（外接 SSD、HDD、NAS 掛載），格式為 `PATH[@GiB]`；啟動時會量測各磁碟區並依實測讀取速度排序 |
| `YUNSHU_VLM_APC_WARM` | `off` | 為被淘汰的檢查點多加一層 RAM：`lossless`（壓縮、位元精確）或有損的 `int8` / `int4` |
| `YUNSHU_CACHE_RESERVE_PCT`、`YUNSHU_CACHE_RESERVE_GB` | `10`、`20` | 磁碟區上任何快取寫入都不得動用的剩餘空間 |
| `YUNSHU_CACHE_STALE_DAYS` | `7` | 超過此天數未使用、或模型已改變的命名空間會優先被清除 |

SSD 中的狀態以檢查點的權重作為命名空間，所以就地替換模型不會讀到過期的狀態。

### 純文字快速路徑（`KVPrefixCache`）

| 設定 | 預設 | 說明 |
|---|---|---|
| `YUNSHU_PREFIX_MAX_ENTRIES` | `64` | 保留的前綴項目數 |
| `YUNSHU_SSD_CACHE` | 關 | 把前綴 KV 持久化到 SSD |
| `YUNSHU_SSD_CACHE_DIR` | `~/.cache/yunshu/kv-ssd` | SSD 目錄 |
| `YUNSHU_SSD_CACHE_MAX_GB` | `10` | 該目錄的容量上限 |
| `YUNSHU_SSD_CACHE_PREFILL_CEIL_TPS` | `20000` | 模型預填速度超過此值時略過 SSD 還原，因為此時重新計算和讀取一樣快 |

### 管理 SSD 快取

```bash
yunshu cache status        # 各 SSD 快取的大小、上限與問題
yunshu cache gc            # 試跑：回報過期或損毀的項目
yunshu cache gc --apply    # 刪除它們並修剪到容量上限
```

`yunshu doctor` 也會印出快取目錄、大小與剩餘空間。

## 預設無損，有損由你選擇

從 RAM 或 SSD 重用精確檢查點，得到的狀態與冷啟動預填完全相同。下列選項則以輸出品質換取記憶體。它們是預設為無損的使用者選項，不會被自動啟用。

| 設定 | 效果 |
|---|---|
| `YUNSHU_KV_QUANT_BITS` | 文字引擎：把 KV 快取量化為 2、3、4 或 8 位元（`auto` 會在快取超過約 2 GiB 時改用 8 位元）。預設 `off` |
| `YUNSHU_KV_PRECISION` | Qwen3.5 家族 packed 層的 row：`int8` 以 int8 編碼加每組縮放值儲存 KV，記憶體與讀取頻寬約減半。預設 `bf16`。Flash-Next 與 generic 層模型維持 bf16 |
| `YUNSHU_VLM_APC_WARM` = `int8` 或 `int4` | 被淘汰的檢查點以量化形式留在 RAM；命中時還原的是反量化的 K/V，輸出可能與冷啟動預填不同。SSD 層仍保存精確狀態 |
| `YUNSHU_PREFIX_HOT_LIMIT` | 文字引擎：只有這麼多項目保持全精度，較舊的以 4 位元儲存（預設 `0`：全部全精度） |
| `YUNSHU_SSD_CACHE_PRECISION` = `int8` | 文字引擎：以 int8 儲存 SSD 項目，位元組數約減半。預設 `native`（位元精確） |

## 支援狀況

| 功能 | 狀態 |
|---|---|
| 自動前綴重用（VLM runner 與純文字快速路徑） | <Support status="supported">支援</Support> |
| usage 中的 `cached_tokens` 與 `cache_read_input_tokens` | <Support status="supported">支援</Support> |
| `system` 區塊上的 `cache_control` | <Support status="supported">支援</Support> |
| 訊息區塊與工具上的 `cache_control` | <Support status="partial">僅 VLM runner；純文字快速路徑不計入回報</Support> |
| `prompt_cache_key` | <Support status="partial">接受，無作用</Support> |
| `prompt_cache_options`、`prompt_cache_breakpoint` | <Support status="partial">僅 VLM runner</Support> |
| 滑動視窗模型的前綴快取 | <Support status="unsupported">尚未支援</Support> |
| 具名的快取內容物件（Gemini 風格的 `cachedContents`） | <Support status="unsupported">不提供</Support> |

## 相關頁面

- [Messages](/docs/api/messages)、[Chat Completions](/docs/api/chat-completions) 與 [Responses](/docs/api/responses)
- [架構](/docs/developers/architecture)
- [設定](/docs/guides/configuration)
- [模型支援](/docs/guides/model-support)


---

<!-- guides/sampling -->
---
title: 取樣預設值
description: 請求沒帶 temperature、top_p、top_k 與懲罰項時採用的值，以及思考模式如何決定它們。
---

程式代理（Claude Code、Codex、opencode）不會送取樣參數，所以預設值直接決定它們的行為。雲舒不對所有模型用同一個數字，每個欄位依下列順序取第一個有值的來源：

1. 請求帶的值（永遠優先，即使等於舊預設值）；
2. 模型針對**這次請求**所處模式（思考或非思考）公布的建議值；
3. 模型的 `generation_config.json`；
4. 官方 API 預設（temperature 1.0、top_p 1.0，top_k / min_p / 懲罰項關閉）。

## 請求屬於哪個模式

模式的判斷與請求渲染一致：Anthropic `thinking`（`enabled` / `disabled`）、`enable_thinking` 或 `chat_template_kwargs.enable_thinking`、JSON schema 或文法限制（不思考），其餘採用聊天範本自己的預設（例如 Qwen3.5、Qwen3.8 預設思考）。`reasoning_effort` 不會切換模式。

## 已公布的建議值

| 模型                  | 模式   | temperature | top_p | top_k | presence_penalty |
| --------------------- | ------ | ----------- | ----- | ----- | ---------------- |
| Qwen3.8-27B           | 思考   | 1.0         | 0.95  | 20    | 0.0              |
| Qwen3.8-27B           | 非思考 | 0.7         | 0.80  | 20    | 1.5              |
| Qwen3.6-27B           | 思考   | 1.0         | 0.95  | 20    | 0.0              |
| Qwen3.6-27B           | 非思考 | 0.7         | 0.80  | 20    | 1.5              |
| Qwen3.5-27B / 9B / 4B | 思考   | 1.0         | 0.95  | 20    | 1.5              |
| Qwen3.5-27B / 9B / 4B | 非思考 | 0.7         | 0.80  | 20    | 1.5              |
| Qwen3.5-2B / 0.8B     | 思考   | 1.0         | 0.95  | 20    | 1.5              |
| Qwen3.5-2B / 0.8B     | 非思考 | 1.0         | 1.00  | 20    | 2.0              |
| Gemma 4 31B           | 兩者   | 1.0         | 0.95  | 64    | 關閉             |

數值抄自 Hugging Face 模型卡（一般任務的組合，不採用卡上的程式碼組合）。其他模型依序落到 `generation_config.json`、API 預設。

## 查看與修改

- 每個回應都有 `x_yunshu.sampling`：數值、模式、判定模式的原因，以及每個欄位的來源（`request`、`model_card`、`generation_config`、`api_default`）。
- `yunshu doctor -m <model>` 依模式列出預設值；主控台的模型頁顯示它們；伺服器啟動時也會記錄。
- `YUNSHU_SAMPLING_DEFAULTS=api` 忽略模型、只用 API 預設。`temperature: 0` 永遠是貪婪解碼。


---

<!-- guides/structured-output -->
---
title: 結構化輸出與工具呼叫
description: 把生成限制為 JSON schema、正規表示式、選項清單或文法，並透過 tool_choice 與平行呼叫使用工具，涵蓋 chat、Responses、Messages 與 Ollama 路由。
---

Yunshu 能在解碼的過程中，強制模型的輸出符合指定的形狀。限制是逐 token 套用的，所以結果一定符合，而不是靠提示詞拜託模型、再祈禱剖析器能處理。工具呼叫也建立在同一套機制上。

受限解碼適用於文字模型與視覺語言模型。不會生成文字的模型（embedding、ASR、圖像模型）收到限制欄位時，會回傳指出欄位名稱的 `400`。`GET /v1/models` 每個項目的 `yunshu` 物件，會在 `contract.structured_output` 與 `contract.tools` 底下列出該模型接受什麼。

## 輸出限制

| 限制 | Chat Completions | Responses | Messages | Ollama |
|---|---|---|---|---|
| JSON 物件 | `response_format: {"type": "json_object"}` | `text.format: {"type": "json_object"}` | `response_format`（Yunshu 擴充） | `format: "json"` |
| JSON schema | `response_format: {"type": "json_schema", ...}` | `text.format: {"type": "json_schema", ...}` | `output_config.format` 或 `output_format` | `format: {<schema>}` |
| 正規表示式 | `grammar: {"type": "regex", "pattern": ...}` | `grammar` | `grammar` | 無 |
| 選項（choice） | `grammar: {"type": "choice", "choices": [...]}` | `grammar` | `grammar` | 無 |
| 上下文無關文法 | `grammar: {"type": "cfg", "grammar": "<lark>"}` | `grammar` | `grammar` | 無 |

`grammar` 欄位與 vLLM 風格的別名是 Yunshu 與 vLLM 相容用的擴充。凡是接受別名的地方，別名都會折疊成同一個限制：

- `POST /v1/chat/completions` 與 `POST /v1/completions` 上的 `guided_json`、`guided_regex`、`guided_choice` 與 `guided_grammar`。
- `structured_outputs`（vLLM 的欄位），必須恰好給定 `json`、`regex`、`choice`、`grammar` 或 `json_object` 其中之一，可用於 chat、completions、Responses 與 Messages 路由。不支援 `structural_tag`。
- 你以原生欄位設定的值優先於別名。`grammar` 也接受 `{"type": "json", "schema": {...}}`。

<Callout type="info">
不支援或無效的限制會在生成開始前就回傳 `400`：無法編譯的正規表示式、格式錯誤的文法，或兩個引擎都無法強制的 schema 語法。Yunshu 不會默默地對著近似版本生成。
</Callout>

### 用 OpenAI SDK 指定 JSON schema

<Tabs items={["Python", "JavaScript", "curl"]}>
<Tab value="Python">

```python
import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

schema = {
    "type": "object",
    "properties": {
        "city": {"type": "string"},
        "population": {"type": "integer"},
        "tags": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["city", "population", "tags"],
    "additionalProperties": False,
}

r = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Give me facts about Taipei."}],
    response_format={
        "type": "json_schema",
        "json_schema": {"name": "city_facts", "schema": schema, "strict": True},
    },
)
print(json.loads(r.choices[0].message.content))
```

</Tab>
<Tab value="JavaScript">

```ts
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "sk-local" });

const r = await client.chat.completions.create({
  model: "local",
  messages: [{ role: "user", content: "Give me facts about Taipei." }],
  response_format: {
    type: "json_schema",
    json_schema: {
      name: "city_facts",
      strict: true,
      schema: {
        type: "object",
        properties: { city: { type: "string" }, population: { type: "integer" } },
        required: ["city", "population"],
        additionalProperties: false,
      },
    },
  },
});
console.log(JSON.parse(r.choices[0].message.content ?? "{}"));
```

</Tab>
<Tab value="curl">

```bash
curl http://localhost:8000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "local",
    "messages": [{"role": "user", "content": "Give me facts about Taipei."}],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "city_facts",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {"city": {"type": "string"}, "population": {"type": "integer"}},
          "required": ["city", "population"],
          "additionalProperties": false
        }
      }
    }
  }'
```

</Tab>
</Tabs>

當 `type` 為 `json_schema` 時，`response_format.json_schema.schema` 是必要的；缺少 schema 會得到 `400`。Responses 的寫法是把同一個 schema 放在 `text.format` 底下：

```python
r = client.responses.create(
    model="local",
    input="Give me facts about Taipei.",
    text={
        "format": {
            "type": "json_schema",
            "name": "city_facts",
            "schema": schema,
            "strict": True,
        }
    },
)
print(r.output_text)
```

### 正規表示式、選項與文法

使用 OpenAI SDK 時，透過 `extra_body` 傳入 `grammar`：

```python
# 一個格式固定的電話號碼
r = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Invent a phone number."}],
    extra_body={"grammar": {"type": "regex", "pattern": r"\+886-9[0-9]{2}-[0-9]{3}-[0-9]{3}"}},
)

# 固定集合中的其中一個標籤
r = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Sentiment of: I love it."}],
    extra_body={"grammar": {"type": "choice", "choices": ["positive", "negative", "neutral"]}},
)

# Lark 語法的上下文無關文法
r = client.chat.completions.create(
    model="local",
    messages=[{"role": "user", "content": "Answer yes or no."}],
    extra_body={"grammar": {"type": "cfg", "grammar": 'start: "yes" | "no"'}},
)
```

`guided_regex` 長度上限為 2048 個字元，`guided_grammar` 為 32768。

### Messages 與 Ollama

在 `POST /v1/messages` 上，結構化輸出使用 Anthropic 的欄位（也接受較舊的 beta `output_format`）：

```python
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:8000", api_key="sk-local")

msg = client.messages.create(
    model="local",
    max_tokens=512,
    messages=[{"role": "user", "content": "Give me facts about Taipei."}],
    extra_body={"output_config": {"format": {"type": "json_schema", "schema": schema}}},
)
print(msg.content[-1].text)
```

在 `POST /api/chat` 與 `POST /api/generate` 上，`format` 可以是 `"json"`，或是 JSON schema 物件（以 strict 處理）。

### 限制如何被強制

JSON schema 與 `json_object` 限制由兩個引擎之一強制執行。`YUNSHU_JSON_SCHEMA_ENGINE` 決定優先使用哪一個（預設 `llguidance`，會依 schema 順序輸出屬性；或 `inhouse`）。優先引擎無法編譯的 schema，若另一個引擎支援就會改由它處理。正規表示式與 choice 限制由內建引擎編譯；上下文無關文法（Lark 語法）需要 `llguidance`，`contract.structured_output.grammar` 會回報是否可用。

有兩個選用的效能設定（預設都關閉）適用於文字引擎：`YUNSHU_GRAMMAR_BITMASK` 把預設的 allowlist 取樣器換成 xgrammar 風格的 bitmask 引擎；`YUNSHU_JUMP_FORWARD` 則在 schema 已經決定了下一段內容時，不執行前向傳遞就直接輸出那些 token。

## 工具呼叫

工具依各方言的定義宣告：chat 用 `tools[].function`，Responses 用 `type: "function"` 的 `tools`，Messages 用 `tools[].input_schema`，`POST /api/chat` 則用 `tools`。

### 兩種模式：template 與 prompt

工具如何送到模型，取決於它的聊天模板；`GET /v1/models` 中的 `contract.tools.mode` 會告訴你目前是哪一種。

| 模式 | 條件 | 做法 |
|---|---|---|
| `template` | 聊天模板原生支援工具 | 工具由模型自己的模板以它自己的工具格式與特殊 token 渲染，模型輸出的工具呼叫再被剖析回結構化的呼叫 |
| `prompt` | 模板沒有工具支援 | 把工具定義注入提示詞，再從生成的文字中擷取呼叫 |

有 `template` 時，遵循度與剖析成功率較好。兩種模式回傳相同的回應形狀。`contract.tools.parallel` 表示模板是否能在同一個 assistant 回合帶多個呼叫。

### `tool_choice`

| 意圖 | Chat | Responses | Messages |
|---|---|---|---|
| 由模型決定 | `"auto"`（預設） | `"auto"` | `{"type": "auto"}` |
| 不使用工具 | `"none"` | `"none"` | `{"type": "none"}` |
| 必須呼叫某個工具 | `"required"` | `"required"` | `{"type": "any"}` |
| 必須呼叫指定工具 | `{"type": "function", "function": {"name": "..."}}` | `{"type": "function", "name": "..."}` | `{"type": "tool", "name": "..."}` |

`tool_choice` 為 `required` 或指定函式時，`tools` 不能是空的，而且指定的函式必須是已宣告的工具之一，否則請求會得到 `400`。`allowed_tools` 形式在 chat 與 Responses 路由中會折疊成 `tools` 加上一個模式。強制的選擇一律由受限解碼來保證，所以呼叫一定存在、一定指向正確的工具，且參數符合它的 schema。`auto` 的呼叫則是自由解碼，事後再修復。

### 平行工具呼叫

模板支援時（`contract.tools.parallel`），模型可以在一個回合發出多個呼叫。設定 `parallel_tool_calls: false`（chat 與 Responses），或在 Messages 的 `tool_choice` 內設定 `disable_parallel_tool_use: true`，就只保留第一個呼叫。在 Responses 上，`max_tool_calls` 可限制總數。

### 工具呼叫的完整往返

```python
import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="sk-local")

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "What is the weather in Taipei and Tokyo?"}]
first = client.chat.completions.create(
    model="local", messages=messages, tools=tools, tool_choice="auto"
)
call_message = first.choices[0].message
messages.append(call_message)

for call in call_message.tool_calls or []:
    args = json.loads(call.function.arguments)
    messages.append({
        "role": "tool",
        "tool_call_id": call.id,
        "content": json.dumps({"city": args["city"], "temp_c": 24}),
    })

final = client.chat.completions.create(model="local", messages=messages, tools=tools)
print(final.choices[0].message.content)
```

模型呼叫工具時，chat 的 `finish_reason` 為 `tool_calls`，Messages 的 `stop_reason` 為 `tool_use`。串流時，呼叫會以增量 delta 送出。

### 各路由上的同一個呼叫

<Tabs items={["Chat", "Responses", "Messages", "Ollama"]}>
<Tab value="Chat">

```json
{
  "model": "local",
  "messages": [{"role": "user", "content": "Weather in Taipei?"}],
  "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
  "tool_choice": {"type": "function", "function": {"name": "get_weather"}},
  "parallel_tool_calls": false
}
```

</Tab>
<Tab value="Responses">

```json
{
  "model": "local",
  "input": "Weather in Taipei?",
  "tools": [{"type": "function", "name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}],
  "tool_choice": {"type": "function", "name": "get_weather"},
  "parallel_tool_calls": false
}
```

</Tab>
<Tab value="Messages">

```json
{
  "model": "local",
  "max_tokens": 512,
  "messages": [{"role": "user", "content": "Weather in Taipei?"}],
  "tools": [{"name": "get_weather", "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}],
  "tool_choice": {"type": "tool", "name": "get_weather", "disable_parallel_tool_use": true}
}
```

</Tab>
<Tab value="Ollama">

```json
{
  "model": "local",
  "messages": [{"role": "user", "content": "Weather in Taipei?"}],
  "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
  "stream": false
}
```

Ollama 沒有 `tool_choice` 欄位；工具參數以物件回傳，而不是字串。

</Tab>
</Tabs>

## 支援狀況

| 功能 | 狀態 |
|---|---|
| chat、Responses、Messages、Ollama 上的 `json_object` 與 `json_schema` | <Support status="supported">支援</Support> |
| 透過 `grammar` 使用 `regex`、`choice` | <Support status="supported">chat、completions、Responses、Messages</Support> |
| 上下文無關文法（Lark） | <Support status="partial">需要 `llguidance`；請查看 `contract.structured_output.grammar`</Support> |
| `guided_*` 別名 | <Support status="extension">chat 與 completions</Support> |
| `structured_outputs`（vLLM） | <Support status="extension">四條生成路由；不支援 `structural_tag`</Support> |
| 對非文字模型使用限制 | <Support status="unsupported">`400`</Support> |
| `tool_choice` 的 `auto`、`none`、`required`、指定函式 | <Support status="supported">支援</Support> |
| 強制 `tool_choice` 的保證 | <Support status="supported">受限解碼</Support> |
| 以工具文法解碼 `auto` | <Support status="partial">僅在實驗性設定開啟時，預設關閉</Support> |
| `parallel_tool_calls: false` | <Support status="supported">只保留第一個呼叫</Support> |
| chat 的 `functions` / `function_call`（已棄用） | <Support status="unsupported">尚未支援</Support> |
| chat 中的 custom（非 function）工具 | <Support status="unsupported">尚未支援</Support> |

## 相關頁面

- [Chat Completions](/docs/api/chat-completions)、[Responses](/docs/api/responses)、[Messages](/docs/api/messages) 與 [Ollama](/docs/api/ollama)
- [模型支援](/docs/guides/model-support)
- [程式代理與 SDK](/docs/guides/agents)
- [架構](/docs/developers/architecture)


---

<!-- guides/tavily -->
---
title: 本機 Tavily API
description: 使用官方 Tavily Python、JavaScript 與 LangChain 用戶端，連接 Yunshu 本機相容的 search、extract、crawl、map 與 research 端點。
---

Yunshu 在 `http://localhost:8000/tavily` 掛載與 Tavily 相容的 API。Python、JavaScript 與 LangChain 用戶端會把端點路徑附加到所設定的 base URL，所以此 API 沒有 `/v1`。伺服器端的 `web_search` 與 `web_fetch` 工具以及提供者的選擇，請見[網路搜尋](/docs/guides/web-search)。

## 連接用戶端

<Tabs items={["Python", "JavaScript"]}>
<Tab value="Python">

```python
from tavily import TavilyClient, AsyncTavilyClient

client = TavilyClient(api_key="tvly-local", api_base_url="http://localhost:8000/tavily")
async_client = AsyncTavilyClient(api_key="tvly-local", api_base_url="http://localhost:8000/tavily")
print(client.search("MLX inference", include_usage=True))
```

注入的非同步 HTTP 用戶端本身也必須使用這個完整的 base URL，因為 SDK 會保留它原本的 URL。LangChain 的 `TavilySearchAPIWrapper` 接受 `api_base_url`。

</Tab>
<Tab value="JavaScript">

```javascript
const { tavily } = require('@tavily/core');
const client = tavily({apiKey: 'tvly-local', apiBaseURL: 'http://localhost:8000/tavily'});
```

</Tab>
</Tabs>

設定 `YUNSHU_AUTH_TOKEN=tvly-local` 即可要求使用該金鑰；`tvly-` 前綴會原樣接受，不會被去除。舊式的請求本文 `api_key` 也可使用。未設定驗證時，適用本機預設的開放規則（[驗證](/docs/guides/auth-and-keys)）。

## 端點

| 方法 | 路徑 |
|---|---|
| POST | `/search`、`/extract`、`/crawl`、`/map`、`/research`、`/feedback`、`/logs` |
| GET | `/research/{request_id}`、`/usage`、`/providers` |
| POST | `/mcp`（原生無狀態 MCP 端點） |

錯誤使用 `detail.error`，依情況為 400、401、403、404、413、429 與 500，欄位驗證則為 422。Tavily 僅限雲端的額度與方案狀態 432 與 433 不會被偽造。回應帶有請求 ID、經過秒數與僅供參考的本機額度，陣列欄位順序穩定。search、extract、crawl、map 與 research 輪詢只有在 `include_usage=true` 時才回傳 `usage`；內部記帳無論如何都會繼續。

## 檢索與延遲

SERP 是一個提供者。內建的 metasearch 會並行執行直接的 DDG HTML 與 Wikipedia，加上已設定的需金鑰來源，並以 reciprocal-rank fusion 去除重複的候選項。

<Callout type="warn">
查詢文字會離開這台機器，送往這些提供者。DDG 是盡力而為，可能封鎖自動化。SearXNG 為選用，需明確指定實例，既非必要，也不建議使用。
</Callout>

`yunshu config` 會顯示最近一次不含查詢內容的提供者健康快照；`GET /tavily/providers` 顯示即時健康狀態。連續失敗三次會觸發有上限的指數退避，半開探測會讓恢復的來源重新加入。驗證碼與速率限制會立即退避。

| 提供者 | 啟用方式 | 備註 |
|---|---|---|
| Mwmbl | `YUNSHU_WEB_MWMBL=1`，或 `provider=mwmbl` | 資料集為 CC-BY-NC-SA 4.0：請保留署名並遵守非商業與相同方式分享條款（[條款](https://api.mwmbl.org/static/terms-and-conditions/)）；不會悄悄啟用；沒有複製任何 Mwmbl 程式碼 |
| Mojeek | `YUNSHU_MOJEEK_API_KEY` | 加入自動 metasearch；轉送 safe-search、國家與語言加權及日期範圍；最多請求十筆候選（[API](https://www.mojeek.com/support/api/search/)） |
| Marginalia | `YUNSHU_MARGINALIA_API_KEY` | 轉送 safe-search 與結果數量；沒有隱含的 `public` 金鑰（明確設定才會使用共用的開發配額）；非商業金鑰提供 CC-BY-NC-SA 4.0 資料（[API 與條款](https://about.marginalia-search.com/article/api/)） |

可用 `YUNSHU_WEB_SEARCH_PROVIDER` 明確選擇提供者（`mojeek`、`marginalia`、`mwmbl` 等；預設 `auto`）。Common Crawl 的 URL 索引與 Wikipedia 傾印需要語料匯入與本機全文索引；它們不是關鍵字 SERP 端點，也絕不會自動下載或啟用。

一般搜尋使用 BM25、提供者先驗、精確片段與去重，不呼叫任何 LLM。每段摘錄最長 500 個字元，摘錄之間以 ` [...] ` 連接。搜尋深度決定抓取廣度與總檢索預算：

| `search_depth` | 預算 | 頁數 |
|---|---|---|
| `ultra-fast` | 0.7 秒 | 僅提供者文字 |
| `fast` | 1 秒 | 3 |
| `basic` | 1.3 秒 | 6 |
| `advanced` | 3 秒 | 20 |

這些是取消預算，不是保證的端到端 p50：DNS、禮貌間隔、提供者可用性與所要求的生成都會影響實際延遲。`Server-Timing` 標頭會回報 SERP、抓取、IR 與生成的耗時。錯過該深度抓取時窗的頁面不會被取消；它們會在自己的逾時內完成並預熱頁面快取。

時間、主題、國家、語言與 safe-search 會下推給支援的提供者；日期與嚴格語言也會在本機再檢查。Finance 是盡力而為的新聞垂直領域，不是金融索引。除非要求嚴格過濾，否則未知日期會保留。精確的引號片語需要成功抓取到頁面。正規化分數是本機相關性，並未校準到 Tavily 專有的機率。

Extract 處理靜態 HTML、文字、JSON 與有大小上限的 PDF 內容，保留可用的 markdown、程式碼與表格，並隔離失敗。Crawl 與 map 使用 BFS，搭配有逾時的正規表示式選擇器、深度、廣度與全域上限、robots 規則與主機禮貌間隔。Map 可以列出外部連結，但絕不遞迴跟隨。`instructions` 使用低成本的字詞相關性。

### JavaScript 渲染

進階的 extract、crawl 與 map 可以用 `YUNSHU_WEB_RENDER=1`（預設關閉）渲染簡短的 JavaScript 外殼頁面。

<Steps>
<Step>

安裝選用 extra：`uv sync --extra web-render`。

</Step>
<Step>

安裝本機瀏覽器：`uv run playwright install chromium`。請求絕不會自行安裝瀏覽器。

</Step>
<Step>

設定 `YUNSHU_WEB_RENDER=1`。

</Step>
</Steps>

渲染一次只使用一個無頭 Chromium，並且只透過一般的已檢查、已鎖定（pinned）抓取器重播同源的 GET 文件、腳本與 fetch。Service worker、WebSocket、下載、跨來源資源與被重新導向的資源內容都會被封鎖。robots 規則仍適用於 crawl 與 map，且請求逾時涵蓋靜態抓取加上渲染。瀏覽器缺失或逾時時會保留靜態結果。不支援依賴 CDN 的應用程式，也不支援繞過受保護網站。

## 答案、research 與 MCP

- `include_answer` 只在被要求時才呼叫所服務的聊天模型。
- Research 用所服務的 LLM 規劃查詢，搜尋並萃取證據，再附引用綜合成文。輸出 schema 使用聊天的受限 JSON 解碼（[結構化輸出](/docs/guides/structured-output)），並在事後驗證。`mini` 與 `pro` 的差別在查詢數量上限；`pro` 在單一 GPU 上依序執行，並不是 Tavily 專有的多代理實作。Research 維持選用。
- 非同步任務支援輪詢與 SSE，包含 keepalive、工具框、內容、來源與完成事件。註冊表（100 個任務）、回饋（1000）與日誌（10000）在行程內有上限，重新啟動即遺失。
- 本機額度只是估計工作量，不會計費，也不會強制執行雲端方案。
- 檔案支援 base64 的 `txt`、`md` 與 `json`，合計上限 80000 字。參考書目支援編號、APA、MLA 與 Chicago 格式。
- 圖片中繼資料來自抓取到的頁面。`include_images` 另外會查詢已設定的 SearXNG 圖片類別或 Brave 的圖片端點，套用來源網域過濾並去除重複 URL；圖片垂直領域失敗不會讓搜尋失敗，DDG 與 Wikipedia 沒有圖片後備。所要求的圖片描述使用常駐的本機 VLM（最多三張圖，快取 15 分鐘）；不會另外載入第二個模型。

<Callout type="warn">
上游 `tavily-mcp` 0.2.22 寫死 `api.tavily.com`，沒有 base URL 設定，所以 REST 相容性無法讓它轉向。請使用 Yunshu 的原生 MCP 端點 `/tavily/mcp`，它以底線與連字號兩種名稱提供 Tavily 工具。
</Callout>

## 如何驗證

- `scripts/research/tavily_sdk_parity.py` 與 `scripts/research/tavily_sdk_parity.mjs` 以注入傳輸的方式，讓真正的 SDK 套件對真正的路由器與服務執行，不需要監聽的伺服器，也不連網。請把 SDK 套件裝在獨立環境，不要裝進服務用的 venv。
- `scripts/research/tavily_stage_latency.py` 量測各階段延遲（`Server-Timing`：serp、fetch、ir、generate）；`--live` 使用真正的內建提供者與頁面，且只用 CPU。
- `scripts/research/websearch_quality_gate.py` 以明確的審查標註評估凍結的成對重播（`--snapshot`、`--pairs`、`--reviews`、`--out`），證據不完整時以 1 結束。它要求同一裝置上有至少 200 個不重複的配對，涵蓋至少 40 筆新聞、40 筆文件、40 筆程式碼與 10 筆對抗性參考，至少 10% 的配對審查須有人工檢查，且等價性最多只能有一個淨正確性差異。它不會核准改變品質的 research 預設值，也不能證明延遲。


---

<!-- guides/telemetry -->
---
title: 主機遙測與能耗
description: 啟用本機 Apple Silicon 功耗、GPU 與溫度取樣器，從 API、CLI 與 Prometheus 讀取，並了解逐請求能耗估計的意義。
---

`YUNSHU_TELEMETRY=on` 會啟用本機背景取樣器（預設 1 Hz）。它不需要 root、不會匯入 MLX，且只在自己的 `yunshu-host-telemetry` 執行緒上進行原生呼叫，不在推論執行器內。沒有任何取樣資料會離開這台機器。

## 啟用

<Steps>
<Step>

在環境變數或設定檔中設定 `YUNSHU_TELEMETRY=on`（可另外設定 `YUNSHU_TELEMETRY_INTERVAL_S`）。

</Step>
<Step>

重新啟動伺服器。這兩個設定都需要重新啟動。

</Step>
<Step>

用 `GET /v1/yunshu/host`、`yunshu top` 或 `/metrics` 讀取取樣器。

</Step>
</Steps>

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_TELEMETRY` | `off` | `on` 啟動取樣器；需重新啟動 |
| `YUNSHU_TELEMETRY_INTERVAL_S` | `1.0` | 取樣間隔（秒），最小 0.1；需重新啟動 |

<Callout type="info">
預設為關閉。一次 27B 的 A/B 顯示解碼速度在雜訊範圍內相同，但在 1K 純文字情境中，後續請求的 TTFT 有小而一致的代價，因此保持為選用項目。這些數字未記錄在基準測試紀錄中，因此此處不引用。
</Callout>

IOReport 與 HID 存取的實作衍生自 [pierre427/mlx2](https://github.com/pierre427/mlx2)（Apache-2.0），macOS 27 的計數器目錄衍生自 [vladkens/macmon](https://github.com/vladkens/macmon)（MIT）。聲明見 `THIRD_PARTY_NOTICES.md` 與 `vendor.json`。

## 主機 API 與 CLI

`GET /v1/yunshu/host` 使用主控台權限（`can_manage_models`）。它保留既有的 `thermal`、`power`、`memory` 與 `memory_pressure` 欄位（15 秒快取），並新增擁有獨立 1 Hz 快取的 `telemetry`：

```json
{
  "telemetry": {
    "state": "ok",
    "sampled_at": 1791400000.0,
    "interval_s": 1.0,
    "watts": {"cpu": 5.0, "gpu": 30.0, "ane": 0.0, "dram": 2.0, "package": 37.0},
    "gpu": {"frequency_mhz": 900.0, "active_ratio": 0.75},
    "temperature": {"state": "ok", "die_max_c": 70.0, "die_mean_c": 65.0, "battery_c": null},
    "reasons": {}
  }
}
```

- 功率是區間能量除以經過的秒數。Package 瓦數是所回報的 CPU、GPU、ANE 與 DRAM 通道總和，不是插座端功率。
- GPU MHz 以執行中的 DVFS 停留時間加權。活躍比例的分母包含閒置停留時間。
- 缺少的計數器會是 `null` 並附原因，絕不編造零值。無法取得、已停用或過期的遙測會回傳 `state: unknown` 與 `reason`。功率只有部分涵蓋時回傳 `state: partial`；溫度可以獨立為 unknown。

`yunshu top` 使用已設定的 API 金鑰監看這些快取欄位。`yunshu top --once` 印出一張表，`yunshu --json top` 輸出一份 JSON 快照。未知的值仍會顯示。CLI 本身不會取樣硬體。

## 逐請求能耗估計

`x_yunshu.energy` 與 `/v1/yunshu/requests/recent` 提供 schema `yunshu.energy.v1`。閘道會在 MLX 執行緒之外填入。每個 `prefill` 與 `decode` 物件都回報 `joules`、`joules_per_token`、`gpu_watts_mean`、`coverage_ratio` 與 `extrapolated_s`。

- 預填使用未命中快取的提示詞 token；解碼使用生成的 token。預填結束時間戳記（若沒有則用第一個 token）用來區分兩個階段。排隊時間不計入。
- 方法 `host_window_gpu_plus_dram` 對取樣的 GPU 與 DRAM 功率積分，並在階段邊界裁切區間。尚未結束的尾端最多使用兩個取樣間隔的最新功率。很短的階段只是取樣解析度下的估計。
- 缺少涵蓋、讀值過期或沒有階段時鐘時，回傳 `null` 焦耳並附原因。CPU 與 ANE 另外回報，不計入請求能耗。
- 歷史上限為 7,200 個區間；更舊的請求可能失去涵蓋。

<Callout type="warn">
這些是包含背景活動與閒置功耗的主機能耗視窗。並行請求的視窗會重疊，且並未獨立計量，因此把收據加總可能重複計入同一份主機能耗。比較效率時請使用序列式的基準測試格。取消的請求只回報實際觀察到的引擎計時，而非預測值。
</Callout>

## Prometheus

需驗證的 `/metrics` 抓取會新增：

- `yunshu_gpu_watts`、`yunshu_package_watts`
- `yunshu_gpu_frequency_mhz`、`yunshu_gpu_active_ratio`
- `yunshu_die_temperature_celsius`（最高晶片溫度）
- `yunshu_request_energy_joules_total{phase="prefill|decode"}`（估計值的本次執行期間的總和）

未知的 gauge 會被省略。請求計數器只在請求完成時更新一次，不會在抓取時更新，並帶有上述重疊視窗的限制。

## macOS 27 功耗計數器

在 macOS 27 上，沒有 Apple 授權（entitlement）時，Energy Model 的 CPU 與 ANE 計數器可能凍結。Yunshu 在 macOS 27 使用 macmon 的、依驅動程式驗證過的 CLPC 純量 IOReport 目錄（上游已在 27.0 與 27.0.1 驗證），並優先採用有效的 CLPC CPU、GPU 與 ANE 差值而非舊值。未知的驅動程式或 OS 目錄絕不猜測。當沒有有效且驗證過的差值時，macOS 27 以上的 CPU 與 ANE 值會是 unknown 並附原因，其他有效的領域仍可使用，因此凍結的零值不會被當成實測功耗。不需要 root、Apple entitlement、SMC 存取或 MLX 呼叫。

晶片溫度優先使用 HID `tdie` 感測器；沒有 `tdie` 值時，改用 `pACC`、`eACC` 與 `GPU MTR Temp Sensor` 名稱，且不混用不同的感測器家族。

## 限制與驗證方式

- 能耗是主機視窗的估計，不是逐行程計量（見上方警告）。
- 要評估取樣器的額外負擔，請在固定的 commit 上以明確的 `off` 基準對比明確的 `on` 候選，在 1K 與 32K 各至少做三次交錯重複。只有速度結論不能證明感測器運作正常，還要檢查實際執行的主機證據。
- 基準測試工具（`tfbench`、`yv`）會保留完整收據，加上解碼的 `joules_per_token` 與 `gpu_watts_mean`；`yv` 在 `efficiency` 下回報各組的中位數，但不用來決定速度是否通過。關卡說明見[驗證](/docs/developers/verification)。


---

<!-- guides/transports -->
---
title: 傳輸方式
description: Yunshu 提供的 HTTP、SSE、WebSocket、Realtime、WebRTC 與 Unix socket 傳輸方式、多工文字 WebSocket 協定，以及未提供的項目。
---

Yunshu 以多種傳輸方式提供同一個應用程式。每一種都派送到相同的處理器，所以驗證、中介軟體、請求 id、前綴快取與取消的行為完全一致。

| 傳輸方式 | 端點 | 狀態 |
|---|---|---|
| HTTP 與 SSE | `POST /v1/chat/completions`、`/v1/responses`、`/v1/messages` | 穩定 |
| 文字 WebSocket（多工） | `WS /v1/stream` | 穩定，Yunshu 協定（見下） |
| Responses WebSocket 模式 | `WS /v1/responses` | 穩定，OpenAI 的協定 |
| Realtime WebSocket | `WS /v1/realtime`（GA schema；加上 `OpenAI-Beta: realtime=v1` 為 beta）與 `/realtime`（beta） | 穩定 |
| Realtime WebRTC | `POST /v1/realtime/calls` | 選用 `yunshu[webrtc]` |
| Unix domain socket | `yunshu serve --uds PATH` | 穩定 |
| HTTP/2（h2c） | 未提供 | 無 |

## 規格怎麼說

**Responses WebSocket 模式。** 依 OpenAI 的 WebSocket 模式指南，用戶端以 WebSocket 連到 `/v1/responses`（SDK：`client.responses.connect()`），送出 `{"type":"response.create", "model", "input", "store", "previous_response_id", "generate", "stream_id"}`，並收到與 SSE 串流相同、原樣的 `response.*` 事件，外加 `error`。相同 `stream_id` 的請求依序執行、絕不重疊；不同 id 則並行。接續對話使用 `previous_response_id`，只帶新的輸入項目。Yunshu 在 `WS /v1/responses` 實作了這個模式。

**Anthropic Messages。** SSE（`stream: true`）是唯一的官方串流傳輸方式；沒有 WebSocket 模式可以對齊。Messages 可透過 Yunshu 自己的 `/v1/stream`（`api: "messages"`）使用。

**OpenAI Realtime。** WebSocket 位於 `/v1/realtime?model=M`，使用 `Authorization: Bearer`（瀏覽器使用子協定 `realtime` 與 `openai-insecure-api-key.<key>`），為 JSON 文字框。GA session 有 `type: "realtime"`、`output_modalities`、`audio.input` 與 `audio.output`、`instructions`、`tools` 與 `tool_choice`。音訊格式為 `audio/pcm`（24 kHz、單聲道、16 位元）、`audio/pcmu` 與 `audio/pcma`；回合偵測為 `server_vad`、`semantic_vad` 或 null。WebRTC 則是把 SDP offer 送到 `/v1/realtime/calls`，並在 `oai-events` 資料通道上交換相同的事件。

## 文字 WebSocket：WS /v1/stream

這是 Yunshu 協定，用於沒有官方 WebSocket 模式的情況（chat completions、completions、messages）以及多工的額外功能。一條連線可同時承載許多並行請求。伺服器事件與 SSE 串流以 `data:` 酬載攜帶的物件相同，並以用戶端的請求 id 包裝。

<Steps>
<Step>

以與 HTTP 相同的方式驗證連線（`Authorization: Bearer`、`x-api-key` 或 `?token=`）。Origin 與憑證會在升級之前檢查，所以被拒絕的用戶端會得到 HTTP 403 的握手失敗。

</Step>
<Step>

讀取伺服器的第一則訊息 `session.created`。其中列出 `apis` 與 `limits`（`max_inflight`、`max_stream_ids`、`send_queue`、`ping_interval_s`）。

</Step>
<Step>

送出請求框。`body` 就是一般的 HTTP 本文；`stream` 會被強制開啟，對 chat 與 completions，`stream_options.include_usage` 預設為 true。

```json
{"type": "request", "id": "a", "api": "chat.completions", "body": {"model": "local", "messages": [{"role": "user", "content": "Hi"}]}}
```

</Step>
<Step>

讀取 `event` 框，直到該 id 的終止 `done` 框為止。

</Step>
</Steps>

用戶端到伺服器（JSON 文字框）：

| 訊息 | 意義 |
|---|---|
| `{"type":"request","id":"a","api":"chat.completions\|completions\|responses\|messages","body":{...},"stream_id":"s"}` | 開始請求（`stream_id` 為選用） |
| `{"type":"cancel","id":"a"}` | 中止；生成停止（與 SSE 用戶端斷線相同的路徑）；以 `done(cancelled)` 結束 |
| `{"type":"stop","id":"a"}` | 依需要停止；以 `done(stopped)` 結束 |
| `{"type":"update","id":"a","max_tokens":N}` | 將串流 delta 總數（約每個 token 一個）限制為 N；以 `done(max_tokens)` 結束 |
| `{"type":"ping","t":..}` 與 `{"type":"pong"}` | 雙向存活檢查 |

伺服器到用戶端：

| 訊息 | 意義 |
|---|---|
| `{"type":"session.created","protocol":"yunshu.stream","apis":[...],"limits":{...}}` | 第一則訊息 |
| `{"type":"event","id":"a","event":"<SSE event name or null>","data":{...}}` | 一個 SSE 事件。chat 的 `data` 是 `chat.completion.chunk`；responses 與 messages 則是具名事件 |
| `{"type":"done","id":"a","reason":"completed\|cancelled\|stopped\|max_tokens\|error","stats":{"ttft_ms","duration_ms","events","deltas"}}` | 每個請求的終止訊息；同時帶有 `request_id` |
| `{"type":"error","id"?,"status":404,"error":{...}}` | 請求層級（帶 `id`）或連線層級的錯誤；上游 HTTP 錯誤保留其狀態與本文 |
| `{"type":"ping","t":...}` | 每 `YUNSHU_WS_PING_INTERVAL` 秒一次的心跳 |
| `{"type":"updated","id","max_tokens"}` | `update` 的確認 |
| `{"type":"progress","id",...}` | 排隊與預填進度：SSE `: yunshu-progress` 註解的欄位（`phase`、`percent`、`processed_tokens`、`tokens_per_second`、`eta_s`、`queue_position` 等） |
| `{"type":"stats","id",...}` | 每個回應的統計：`x_yunshu` 物件的欄位（`ttft_ms`、`decode_tps`、快取命中等）。請見 [Yunshu 擴充](/docs/api/extensions) |

### 規則

- `id` 是用戶端的請求 id。當它適合作為標頭（1 到 128 個 `A-Za-z0-9._:-` 字元）時，它同時也是 HTTP 的 `X-Request-Id`，因此 `GET` 與 `DELETE /v1/requests/{id}`、日誌與錯誤提示都使用同一個 id。否則由處理器產生一個，並以 `request_id` 在 `done` 中回報。
- 每條連線最多同時執行 `YUNSHU_WS_MAX_INFLIGHT`（預設 16）個請求；超過會得到 `429 too_many_requests`。重複使用進行中的 id 是 `409`。共用 `stream_id` 的請求依序執行；每條連線最多 32 個 stream id。
- 背壓：每條連線的輸出佇列有上限（`YUNSHU_WS_SEND_QUEUE`，預設 256 個事件），所以慢速的讀取端會阻塞應用程式的 `send()`，生成會暫停而不是緩衝。心跳絕不會排在停滯的讀取端後面。
- 關閉 socket 會取消所有進行中的請求。

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_WS_MAX_INFLIGHT` | `16` | 每條連線的並行請求數 |
| `YUNSHU_WS_PING_INTERVAL` | `15.0` | 心跳間隔（秒）；`0` 為停用 |
| `YUNSHU_WS_SEND_QUEUE` | `256` | 生成暫停前緩衝的輸出事件數 |

### Responses WebSocket 模式

`WS /v1/responses` 使用 OpenAI 的協定：送出 `{"type":"response.create", ...body..., "stream_id"?}`，並接收原樣的 `response.*` 事件。`stream_id` 通道的運作如上。Yunshu 另外加入 `{"type":"response.cancel","stream_id"|"id"}`。此方言不會送出 progress 與 stats 事件，因為 OpenAI 的協定沒有位置放它們。官方 `openai` SDK（`client.responses.connect()`）是參考用戶端。

### Python 用戶端

```python
from yunshu_client import YunshuStream

async with YunshuStream("ws://127.0.0.1:8000/v1/stream", token=None) as conn:
    async for m in conn.chat({"model": "m", "messages": [...]}, id="a", with_done=True):
        ...                      # events, then the done message
    await conn.cancel("a")       # from any task
```

`examples/ws_stream.py` 在同一條 socket 上串流兩個聊天並取消其中一個。

## Realtime

`/v1/realtime` 以握手時選定的兩種方言實作 OpenAI Realtime 協定：GA（預設，也是 `client.realtime.connect()` 使用的）與 beta（`OpenAI-Beta: realtime=v1`，以及舊式的 `/realtime` 路徑）。session 引擎是共用的；`yunshu_gateway/realtime_ga.py` 在 socket 邊界轉換事件名稱與 session 形狀。驗證與 Origin 會在升級之前檢查（HTTP 403）。請見 [Realtime API 參考](/docs/api/realtime)。

與 api.openai.com 的差異：

- `semantic_vad` 以 `server_vad` 提供；`eagerness` 會被忽略。
- `turn_detection.idle_timeout_ms`：完成一次回應後（再加上其音訊的播放時間），在這段時間內使用者沒有說話，伺服器會送出 `input_audio_buffer.timeout_triggered`，把空緩衝區當作一次無聲的使用者回合提交並回應。
- `audio.input.noise_reduction`（`near_field` 或 `far_field`）會在 VAD 與 ASR 之前套用因果式 CPU 高通濾波與噪音底限擴展器。這是輕量濾波，不是神經網路降噪。
- `rate_limits.updated` 跟在 `response.created` 之後。本機伺服器沒有配額：`requests` 回報 `YUNSHU_RATE_LIMIT_RPM`（為 0 時是 2^31-1，代表無限制），`tokens` 回報模型的 context window。
- `output_audio_buffer.started`、`.stopped` 與 `.cleared`（僅 GA 方言）標示一次回應音訊的範圍；用戶端事件 `output_audio_buffer.clear` 會取消正在說話的回應。
- `response.create.input` 會取代該次回應的對話上下文；搭配 `conversation: "none"` 可讓它不進入歷史。
- 不支援的 session 欄位會被靜默透傳，不會產生 `invalid_request_error`。

### WebRTC

<Steps>
<Step>

安裝 extra：`uv pip install 'yunshu[webrtc]'`。沒有它時，`POST /v1/realtime/calls` 會回傳 503，可改用 `WS /v1/realtime`。

</Step>
<Step>

將 SDP offer 送到 `/v1/realtime/calls`（`application/sdp`，或 multipart 的 `sdp` 加上 JSON `session`），與 `client.realtime.calls.create` 相同。伺服器回傳 201、一份 SDP answer 與 `Location` 通話 ID。

</Step>
<Step>

在 `oai-events` 資料通道上交換事件，它與 GA Realtime session 共用。音訊走 RTP 軌。

</Step>
</Steps>

輸入音訊會在 CPU 上重取樣為 24 kHz 單聲道 PCM16，輸出 PCM 使用有上限的兩秒緩衝。session 會在對端失敗、用戶端通道關閉、伺服器關閉或一小時後結束；沒有開啟通道的 offer 在 60 秒後過期；同時最多保持 16 通通話。暫時性 client secret 也可用於驗證此端點。沒有公用的 STUN 或 TURN 伺服器，所以 loopback 與區域網路的對端需要可直接連到的 ICE 候選。不提供 SIP 通話管理與監控用的旁路 WebSocket。

## Unix domain socket

`yunshu serve --uds /path/y.sock`（設定 `YUNSHU_UDS`）會在 socket 上提供相同的應用程式，而不是 TCP。`--host` 與 `--port` 會被忽略，殘留的 socket 檔會被移除。以檔案擁有者專屬的權限作為存取控制，因此這是最安全的本機傳輸方式：沒有連接埠，也沒有網路暴露。

<Tabs items={["curl", "Python"]}>
<Tab value="curl">

```bash
curl --unix-socket /path/y.sock http://localhost/v1/models
```

</Tab>
<Tab value="Python">

```python
import httpx, openai

client = openai.OpenAI(
    base_url="http://yunshu/v1",
    api_key="x",
    http_client=httpx.Client(transport=httpx.HTTPTransport(uds="/path/y.sock")),
)
```

</Tab>
</Tabs>

`YunshuStream(url, uds=path)` 對 WebSocket 也是同樣做法。OpenAI SDK 自己的 Realtime 與 Responses WebSocket 用戶端會開啟 TCP 連線，所以它們請使用 TCP 連接埠。

## HTTP/2

未提供。uvicorn 只支援 HTTP/1.1，而 h2c 需要第二套伺服器堆疊（hypercorn 或 granian），各有自己的 lifespan、WebSocket 與斷線語意。以斷線驅動的取消與多工 WebSocket，已涵蓋 HTTP/2 本來能帶來的好處：單一連線上的多個並行串流，且請求之間沒有 head-of-line 阻塞。

## 如何驗證

- `scripts/dev/realtime_conformance.py` 以官方 SDK 檢查 Realtime（使用假引擎的單元測試）；`scripts/dev/transport_smoke.py` 是真實模型的煙霧測試。
- WebRTC 信令、音訊分框、佇列上限與清理由 `tests/unit/test_respfeat.py` 涵蓋。


---

<!-- guides/troubleshooting -->
---
title: 疑難排解
description: 安裝、啟動與呼叫 Yunshu 時常見問題的解法，以及如何收集診斷檔。
---

請先執行 `yunshu doctor`。加上 `-m <model>` 可一併檢查模型。它會檢查平台、MLX 與 Metal、記憶體、設定、模型目錄、連接埠與登入服務，並為每個問題印出修復方式。有問題導致無法啟動時，會以狀態碼 1 結束。

```bash
yunshu doctor -m <model>
yunshu --json doctor -m <model>
```

## 安裝

<Accordions>
<Accordion title="cannot import mlx，或 Python 在 Rosetta 下執行">

MLX 只提供 arm64 wheel，因此 x86_64 的 Python（例如 `/usr/local` 下舊版的 Homebrew）無法載入它。`yunshu doctor` 會回報「Python runs under Rosetta」。請用 `uv python install 3.13` 安裝原生直譯器，再用它重新安裝 Yunshu。

</Accordion>
<Accordion title="requires-python >=3.13">

Yunshu 需要 Python 3.13 或更新版本。`uv tool install "yunshu[vision]" --python 3.13` 會在需要時取得由 uv 管理的 3.13。

</Accordion>
<Accordion title="Qwen3.5 / 3.6 / 3.8 或視覺模型載入失敗，且 doctor 顯示 mlx-vlm 未安裝">

安裝 `vision` 額外套件：`uv tool install "yunshu[vision]" --python 3.13`。請見[安裝](/docs/getting-started/install)。

</Accordion>
<Accordion title="macOS 版本太舊">

低於 macOS 14 時，`yunshu doctor` 的平台檢查會失敗。請更新 macOS；MLX 需要 14 或更新版本。

</Accordion>
</Accordions>

## 啟動伺服器

<Accordions>
<Accordion title="Error: no such directory，或找不到模型">

`yunshu serve` 會在載入前先檢查模型。

- `yunshu model list` 顯示磁碟上有什麼（模型目錄與 Hugging Face 快取）。
- `yunshu pull <org/name>` 下載模型。
- 存放多個模型的目錄應交給 `--models-dir`，而不是 `--model`。

</Accordion>
<Accordion title="下載中斷，或缺少權重分片">

再執行一次相同的 `yunshu pull`。它會續傳，並只取得缺少的檔案。

</Accordion>
<Accordion title="權重大於記憶體，或出現 GPU 工作集的警告">

模型放不進統一記憶體。請改用較小或量化程度更高的版本，例如 4-bit 的 MLX 轉換版。若權重放得下，但佔用了大部分的 GPU 工作集，模型可以載入，但長提示詞可能會記憶體不足。macOS 給 GPU 的工作集略小於總 RAM；`yunshu doctor -m <model>` 會印出兩個數字。

</Accordion>
<Accordion title="Cannot listen on host:port，或連接埠被其他程式佔用">

用 `--port` 選擇其他連接埠（例如 `--port 8001`），並在你的用戶端使用它。`yunshu serve` 會在載入模型之前先檢查位址，並以錯誤結束。若佔用該埠的是 Yunshu 本身（例如登入服務），`yunshu status` 會回報，`yunshu doctor` 也會顯示「Yunshu is already running」。

</Accordion>
<Accordion title="伺服器已啟動，但 GET /health/ready 回傳 503">

模型載入失敗時（路徑錯誤、權重損毀、記憶體不足），伺服器會繼續執行而不是結束，這樣像 launchd 這類監督程式就不會不斷重啟。就緒探測會回傳 503，已知載入錯誤時會附上 `reason`；需要模型的對話請求則會得到 503，直到你修正原因並重新啟動。完整的 traceback 在伺服器記錄中（終端機，或 `yunshu service logs`）；請尋找 `FATAL: model ... load failed`。

```bash
curl -i http://127.0.0.1:8000/health/ready
```

伺服器關閉中，或 GPU 記憶體使用率超過 95% 時，探測也會回傳 503。

</Accordion>
<Accordion title="目前使用哪一條推測路徑？">

`yunshu doctor -m <model>` 會印出 `speculative` 列，啟動記錄中也有 `Speculative decoding:` 一行。在模型目錄或 Hugging Face 快取中找到相符的 DFlash2 drafter 時，會自動採用。`YUNSHU_VLM_DRAFT=mtp` 強制使用檢查點的 MTP 頭，`YUNSHU_VLM_DRAFT=off` 關閉草稿生成，給目錄路徑則指定特定的 drafter。若自動選到的 drafter 無法載入，伺服器會記錄警告並退回 MTP。

</Accordion>
<Accordion title="錯誤的設定使啟動中止">

`yunshu config` 會顯示每個有效值及其來源。設定值無效時，指令會以錯誤中止。拼錯的 `YUNSHU_*` 名稱只會產生帶有最接近名稱的警告；`--set` 使用未知名稱則會報錯。

</Accordion>
<Accordion title="停止伺服器">

Ctrl-C 或 `kill`（SIGINT 或 SIGTERM）會停止接受新請求，並讓執行中的請求在 `YUNSHU_DRAIN_TIMEOUT` 秒內（預設 30）完成。之後會切斷剩餘連線、停止其生成，然後伺服器結束。請求進行中斷線的用戶端會取消其生成。

</Accordion>
</Accordions>

## 呼叫 API

<Accordions>
<Accordion title="401 Missing or invalid Authorization header">

伺服器設定了 `YUNSHU_AUTH_TOKEN`（例如透過 `--auth-token`）。請送出 `Authorization: Bearer <token>`，Anthropic 用戶端則送出 `x-api-key: <token>`。沒有設定 token 時，推論是開放的，但模型載入、卸載等操作性端點會被拒絕。健康檢查、版本與文件路由永遠不需要 token。

</Accordion>
<Accordion title="Docker 中的用戶端無法連線">

伺服器預設只監聽 `127.0.0.1`。請用 `--host 0.0.0.0 --auth-token <secret>` 啟動，並連到 `http://host.docker.internal:8000`。

</Accordion>
<Accordion title="多模型模式下出現 model not found">

請使用 `GET /v1/models` 中的 id（`yunshu model list --url http://127.0.0.1:8000`）。單一模型模式下，任何模型名稱都可以。

</Accordion>
<Accordion title="推理模型的回答是空的">

它的 token 都用在思考上了。請提高 `max_tokens`、降低 `reasoning_effort`，或在 `chat_template_kwargs` 中把 `enable_thinking` 設為 `false`。

</Accordion>
<Accordion title="請求回傳 400">

回應內容會說明原因。常見原因：

- `context_length_exceeded`：提示詞比模型的上下文視窗長。請縮短提示詞，或使用上下文更長的模型。
- `max_tokens` 超過請求驗證的上限（1,048,576），或超過由模型上下文與輸出預算所決定的較低限制。訊息中會註明數字。
- 引擎無法強制執行的 JSON schema 關鍵字或正規表達式語法（例如 `uniqueItems`、`not`、`if`/`then`/`else`、`contains`）。這些會被拒絕，而不是默默忽略。
- 模型缺少的功能，例如工具呼叫、圖片、音訊或 logprobs。`GET /v1/models` 列出每個模型支援的項目。

</Accordion>
<Accordion title="429 Rate limit exceeded">

速率限制預設是關閉的。只有在 `YUNSHU_RATE_LIMIT_RPM` 設為大於 0 時才會啟用。

</Accordion>
</Accordions>

## 磁碟與快取

前綴快取的 SSD 層（預設 `~/.yunshu/cache/apc`）每個快取根目錄有一份預算，並保留空閒空間。寫入失敗時，會以一則警告暫停寫入磁碟。磁碟空間不足時，`yunshu doctor` 會發出警告。

```bash
yunshu cache status        # 每個命名空間的項目、大小與上限
yunshu cache gc            # 回報可以移除的內容
yunshu cache gc --apply    # 移除被截斷、損毀與舊格式的項目，並修剪到上限
```

`YUNSHU_VLM_APC_DISK=0` 會讓前綴快取只留在 RAM。請見[提示快取](/docs/guides/prompt-caching)。

## 回報錯誤

`yunshu diagnose bundle` 會寫出本機診斷檔，內含版本、平台、套件版本、已遮蔽機密的設定、doctor 輸出、SSD 快取狀態，以及服務記錄中最近的錯誤行與其 trace id。其中不含提示詞或補全內容，也不會上傳。

```bash
yunshu diagnose bundle -o yunshu-diagnostics.json
```

在 [github.com/YuhuanStudio/Yunshu](https://github.com/YuhuanStudio/Yunshu/issues) 提出 issue 時，請附上：

- `yunshu --json doctor -m <model>` 的輸出
- 模型資料夾名稱
- 失敗的指令或請求
- 伺服器記錄的最後約 50 行

## 相關頁面

- [CLI 參考](/docs/guides/cli)
- [服務](/docs/getting-started/service)
- [設定](/docs/guides/configuration)


---

<!-- guides/web-search -->
---
title: 網路搜尋與擷取
description: 伺服器端的 web_search 與 web_fetch 工具、背後的搜尋來源、控制它們的設定，以及哪些資料會離開你的機器。
---

程式代理與 SDK 用戶端可以在模型生成的過程中，請 Yunshu 搜尋網路或擷取網頁。伺服器負責執行工具、把結果餵回模型，並以請求所使用的 API 方言格式，連同工具區塊與引用一併回傳答案。

| 方言 | 工具類型 | 說明 |
|---|---|---|
| Anthropic Messages（`POST /v1/messages`） | `web_search_*`（例如 `web_search_20250305`）、`web_fetch_*`（例如 `web_fetch_20250910`） | 結果以 `server_tool_use` 與 `web_search_tool_result` / `web_fetch_tool_result` 區塊回傳；文字區塊帶有 `web_search_result_location` 引用 |
| OpenAI Responses（`POST /v1/responses`） | `web_search`、`web_search_preview` | 結果以 `web_search_call` items 回傳；`open_page` 與 `find_in_page` 動作可用於搜尋已取得的頁面。`web_fetch` 不是 Responses 的工具 |

請求與回應的格式見[伺服器工具](/docs/api/server-tools)；哪些代理會用到這些工具見[程式代理與 SDK](/docs/guides/agents)。

<Callout type="warn">
網路搜尋不是離線推論。使用預設設定時，**查詢文字與你的 IP 位址會離開這台機器**，送往 DuckDuckGo、Wikipedia 以及你設定的任何搜尋來源。查詢由模型產生，可能包含對話中的內容；被擷取的 URL 對來源網站是可見的。對話歷史與用戶端憑證不會被轉送，供應商的 key 只會送給該供應商自己的搜尋 API。若要完全留在本機，請設定 `YUNSHU_WEB_SEARCH_PROVIDER=none`。
</Callout>

## 選擇搜尋來源

`YUNSHU_WEB_SEARCH_PROVIDER` 選擇後端，預設為 `auto`。

| 值 | 行為 |
|---|---|
| `auto` | 同時執行免金鑰來源（DuckDuckGo HTML 與 Wikipedia）以及所有已設定憑證的來源。結果會去重並以 reciprocal-rank fusion 融合；每個來源都有健康度退避，失敗的來源不會一直拖慢查詢 |
| `none` | 停用伺服器端搜尋。宣告了搜尋工具的請求會得到 `unavailable` 工具錯誤 |
| `searxng`、`brave`、`tavily`、`exa`、`serper`、`perplexity`、`mojeek`、`marginalia`、`ddg_html`、`wikipedia`、`mwmbl` | 只使用指定的來源 |

DuckDuckGo HTML 屬於盡力而為：它可能封鎖自動化查詢。`YUNSHU_WEB_KEYLESS=0` 會關閉免金鑰來源（DuckDuckGo 與 Wikipedia），只剩下你設定的來源。

```bash
# 預設：免金鑰來源加上已設定的來源
yunshu serve -m <model> --set web_search_provider=auto

# 全部留在本機
yunshu serve -m <model> --set web_search_provider=none

# 加入一個需要金鑰的來源
export YUNSHU_BRAVE_API_KEY=...
yunshu serve -m <model>
```

### 搜尋來源設定

以下設定都已登錄在設定註冊表中，完整列表見[設定](/docs/guides/configuration)。

| 設定 | 預設 | 說明 |
|---|---|---|
| `YUNSHU_WEB_SEARCH_PROVIDER` | `auto` | 來源選擇，見上表 |
| `YUNSHU_WEB_SEARCH_RESULTS` | `5` | 每次 `web_search` 呼叫回傳的結果數 |
| `YUNSHU_WEB_SEARCH_PROVIDER_TIMEOUT` | `1.0` | metasearch 中每個來源的期限（秒），避免慢的來源拖住整個查詢 |
| `YUNSHU_WEB_KEYLESS` | 開 | 允許免金鑰的 DuckDuckGo 與 Wikipedia |
| `YUNSHU_SEARXNG_URL` | 未設定 | 你自己的 SearXNG 實例網址（需啟用 JSON 輸出）。選用：內建 metasearch 不需要 SearXNG |
| `YUNSHU_BRAVE_API_KEY`、`YUNSHU_TAVILY_API_KEY`、`YUNSHU_EXA_API_KEY`、`YUNSHU_SERPER_API_KEY`、`YUNSHU_PERPLEXITY_API_KEY`、`YUNSHU_MOJEEK_API_KEY`、`YUNSHU_MARGINALIA_API_KEY` | 未設定 | 託管搜尋 API 的憑證。設定後該來源會加入 `auto` |
| `YUNSHU_WEB_MWMBL` | 關 | 選擇加入 Mwmbl small-web 索引。其資料採 CC-BY-NC-SA 4.0（非商業、需標示來源、相同方式分享）。明確選擇 `mwmbl` 也視為加入 |
| `YUNSHU_WEB_SEARCH_HEALTH_FILE` | `~/.yunshu/cache/websearch-health.json` | 來源健康度的小型快照，不儲存查詢文字，也不儲存結果頁面 |
| `YUNSHU_WEB_RESEARCH` | 關 | 以來源網頁的摘錄豐富化搜尋摘要（會額外擷取頁面：這些 URL 同樣會離開本機） |
| `YUNSHU_WEB_RESEARCH_BUDGET` | `4.0` | 豐富化的整體期限（秒，最多 4） |
| `YUNSHU_WEB_RESEARCH_PAGES` | `6` | 每次豐富化的來源頁面數（最多 6） |
| `YUNSHU_WEB_RESEARCH_MODEL` | 未設定 | 已載入的本機 embedding 模型 id，用來重新排序摘錄。它不會自行載入模型；未設定時只用 BM25 排序 |
| `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` | `8` | 單一請求最多可進行的「生成、執行工具、繼續」輪數 |

`yunshu config` 會顯示目前生效的值與最近一次來源健康度快照。

## 擷取網頁

`web_fetch` 會下載一個 URL，並把萃取出的文字交給模型。它不需要搜尋來源，預設開啟。

| 設定 | 預設 | 說明 |
|---|---|---|
| `YUNSHU_WEB_FETCH` | 開 | 提供 `web_fetch` 工具。關閉後請求會得到 `unavailable` 錯誤 |
| `YUNSHU_WEB_FETCH_ALLOW_PRIVATE` | 關 | 允許連到私有、loopback 與 link-local 位址。除非確實需要，請保持關閉 |
| `YUNSHU_WEB_FETCH_MAX_BYTES` | `2000000` | 下載的回應本文上限 |
| `YUNSHU_WEB_FETCH_TIMEOUT` | `20.0` | 等待頁面的秒數 |
| `YUNSHU_WEB_FETCH_MAX_TEXT_CHARS` | `40000` | 交給模型的萃取文字會截到這個長度（請求中的 `max_content_tokens` 可以再調低） |

### 網路安全規則

擷取要跟隨哪些 URL 是由模型決定的，而透過提示注入，也可能由它讀過的任何網頁決定。因此 Yunshu 對所有對外擷取（`web_fetch`、MCP connector 與 VLM 媒體下載）套用同一套網路政策：

- 只接受 `http` 與 `https` URL。含有內嵌帳密、控制字元或空白、缺少主機名稱或連接埠超出範圍的 URL 會被拒絕。
- 先解析主機名稱，再檢查**解析後的位址**。loopback、私有、link-local（包含雲端 metadata 位址）、carrier-grade NAT、multicast、保留與未指定位址一律拒絕，這些位址的 IPv4-mapped IPv6 形式也一樣。連線之後會固定到通過檢查的位址，因此檢查與連線之間 DNS 答案改變也無法繞過。
- 重新導向逐跳跟隨（最多 5 次），每一跳都經過同樣的檢查。
- 憑證綁定在接收它的來源（origin）。重新導向改變 origin 時，Authorization、API key 與 cookie 標頭會被丟棄。
- 下載受 `YUNSHU_WEB_FETCH_MAX_BYTES` 與 `YUNSHU_WEB_FETCH_TIMEOUT` 限制。只接受文字類內容型別（text、JSON、XML、XHTML、JavaScript），其他型別會回傳 `unsupported_content_type`。

MCP connector 有自己的開關：`YUNSHU_MCP_CONNECTOR_ALLOW_PRIVATE` 預設開啟，因為本機工具伺服器是最常見的情況。見[伺服器工具](/docs/api/server-tools)。

被擷取的頁面一律視為不可信資料。研究豐富化會移除隱藏元素與不可見的控制字元，並把疑似指令的文字計入指標，但這些過濾並不保證能抵擋提示注入。

## 工具錯誤

搜尋或擷取失敗不會讓請求失敗。模型會收到帶有錯誤碼的工具結果，並可以繼續。搜尋錯誤碼沿用 Anthropic 的 `web_search_tool_result_error`：`too_many_requests`、`invalid_input`、`max_uses_exceeded`、`query_too_long` 與 `unavailable`。擷取錯誤碼沿用 `web_fetch_tool_result_error`：`invalid_tool_input`、`url_too_long`、`url_not_allowed`、`url_not_accessible`、`too_many_requests`、`unsupported_content_type`、`max_uses_exceeded` 與 `unavailable`。搜尋被停用時，錯誤訊息會提示該開啟哪個設定。

## 本機 Tavily 相容 API

Yunshu 也在 `/tavily` 下掛載一組本機的 Tavily 風格檢索 API，供以 Tavily SDK 撰寫的用戶端使用。它與上述模型工具是不同的介面，但使用相同的搜尋來源。

| 路由 | 用途 |
|---|---|
| `POST /tavily/search` | 搜尋，可選擇由所服務的聊天模型產生答案 |
| `POST /tavily/extract` | 萃取頁面內容 |
| `POST /tavily/crawl`、`POST /tavily/map` | 爬取網站或列出連結（廣度優先，遵守 robots 規則與主機禮貌間隔） |
| `POST /tavily/research`、`GET /tavily/research/{request_id}` | 啟動研究任務並輪詢結果 |
| `POST /tavily/feedback`、`POST /tavily/logs` | 提交回饋與紀錄 |
| `GET /tavily/usage`、`GET /tavily/providers` | 本機用量估計與即時來源健康度 |
| `POST /tavily/mcp` | 原生的無狀態 MCP 端點 |

請把 SDK 指向這個前綴；這組 API 沒有 `/v1`：

<Tabs items={["Python", "JavaScript"]}>
<Tab value="Python">

```python
from tavily import TavilyClient

client = TavilyClient(api_key="tvly-local", api_base_url="http://localhost:8000/tavily")
print(client.search("MLX inference"))
```

</Tab>
<Tab value="JavaScript">

```ts
import { tavily } from "@tavily/core";

const client = tavily({ apiKey: "tvly-local", apiBaseURL: "http://localhost:8000/tavily" });
const result = await client.search("MLX inference");
```

</Tab>
</Tabs>

需要知道的事：

- 這是本機實作。Tavily 的點數計費與專有的排序、研究行為都沒有重現；回應中的 credits 只是參考用的估計值。
- 一般搜尋使用詞彙式排序與去重，不呼叫模型。答案或研究報告才會使用所服務的聊天模型，而且只在你要求時才使用。
- `YUNSHU_TAVILY_API_KEY` 是把託管的 Tavily 服務設為其中一個搜尋來源，與你的用戶端送到這個本機 API 的 key 無關。
- 設定了 `YUNSHU_AUTH_TOKEN` 時，請把它當作 key 送出；沒有設定 token 時，套用一般的本機開放政策。
- 上游的 `tavily-mcp` 套件把 base URL 寫死，無法改指向 Yunshu；請改用原生的 `POST /tavily/mcp` 端點。
- 對 JavaScript 密集的頁面，extract、crawl 與 map 的 Chromium 渲染為選用且預設關閉（`YUNSHU_WEB_RENDER`），需要 `web-render` extra 與已安裝的瀏覽器。

## 支援狀況

| 功能 | 狀態 |
|---|---|
| Messages `web_search_*` 伺服器工具與引用 | <Support status="supported">支援</Support> |
| Messages `web_fetch_*` 伺服器工具 | <Support status="supported">支援</Support> |
| Responses `web_search` / `web_search_preview`、`open_page`、`find_in_page` | <Support status="supported">支援</Support> |
| Responses `web_fetch` 工具 | <Support status="unsupported">不是 Responses 的工具</Support> |
| 網域過濾（`allowed_domains`、`blocked_domains`） | <Support status="partial">由伺服器套用在結果上；Responses 支援 `allowed_domains`</Support> |
| 離線搜尋 | <Support status="unsupported">搜尋一定需要網路；要停用請用 `none`</Support> |
| Tavily API 的圖片搜尋 | <Support status="partial">只能透過已設定的 SearXNG 或 Brave 來源</Support> |

## 相關頁面

- [伺服器工具](/docs/api/server-tools)
- [程式代理與 SDK](/docs/guides/agents)
- [設定](/docs/guides/configuration)
- [Messages](/docs/api/messages) 與 [Responses](/docs/api/responses)


---

<!-- index -->
---
title: 簡介
description: Yunshu 是為 Apple Silicon 打造的本機 LLM 與 VLM 推論引擎，以單一行程提供相容 OpenAI 與 Anthropic 的 API。
---

Yunshu 是為 Apple Silicon Mac 設計的單機推論引擎。單一行程透過 Apple 的 MLX 技術堆疊（`mlx-lm`、`mlx-vlm`、`mlx-audio`）載入模型，並在你自己的機器上提供相容 OpenAI 與 Anthropic 的 HTTP 端點。除非你自行設定，否則資料不會離開這台 Mac。

重點在大型語言模型與視覺語言模型：解碼速度、首個 token 的延遲（冷啟動與前綴快取命中兩種情況）、前綴重用，以及完整的請求功能，例如工具呼叫、JSON schema 輸出、停止序列、logprobs、推理內容輸出與請求取消。其他模態（語音辨識與合成、嵌入、影像生成）則作為額外支援的能力提供。

## 你會得到什麼

- 相容 OpenAI 的路由，例如 `POST /v1/chat/completions` 與 `POST /v1/responses`，以及 Anthropic 路由 `POST /v1/messages`。請見 [API 總覽](/docs/api/overview)。
- 命令列工具 `yunshu`，用於安裝、檢查、啟動，以及將引擎作為登入服務執行。請見 [CLI 參考](/docs/guides/cli)。
- 由獨立輕量行程提供的網頁主控台，可查看狀態、模型、請求並使用 Playground。請見[主控台](/docs/getting-started/console)。
- 帶有選用 SSD 層的前綴快取、Qwen3.5 系列的推測式解碼，以及針對 JSON schema 與文法的受限解碼。

## 服務的運作方式

Yunshu 會依你載入的模型選擇服務路徑。所有 GPU 工作都在單一 MLX 執行緒上進行。

| 模型 | 服務路徑 |
|---|---|
| 任何 `mlx-vlm` 模型（視覺語言模型，以及 Qwen3.5 / 3.6 / 3.8 系列） | VLM batch runner：連續批次處理、每個請求獨立取樣、自動前綴快取，並支援圖片、音訊與影片輸入。 |
| Qwen3.5 系列模型 | 同一個 round driver，另外在封裝的 row 上使用推測式解碼（MTP 或相符的 drafter）。 |
| 純文字 `mlx-lm` 模型 | 單一請求的快速路徑。並行的請求會依序處理。 |

各路徑的細節請見[模型支援](/docs/guides/model-support)。

## Yunshu 不是什麼

Yunshu 只服務一台機器。它沒有多節點或分散式模式，也不以多租戶的批次吞吐量最大化為目標。驗證支援選用的管理 token（`YUNSHU_AUTH_TOKEN`），以及這台伺服器的具名 API 金鑰、權限範圍、期限與配額。

## 文件的組織方式

<Cards>
  <Card title="開始使用" href="/docs/getting-started/install">
    安裝 Yunshu、啟動第一個模型、管理模型檔案、作為登入服務執行，以及開啟主控台。
  </Card>
  <Card title="API 參考" href="/docs/api/overview">
    伺服器註冊的每一條路由，包含參數、範例、串流事件、錯誤，以及每項功能的支援狀態。
  </Card>
  <Card title="指南" href="/docs/guides/cli">
    CLI 參考、設定、模型支援與疑難排解，以及代理程式、網路搜尋、提示快取與結構化輸出的指南。
  </Card>
  <Card title="開發者" href="/docs/developers/architecture">
    架構、貢獻方式、驗證、發行閘門與上游追蹤。
  </Card>
</Cards>

如果你是第一次使用，請依序閱讀[安裝](/docs/getting-started/install)與[快速開始](/docs/getting-started/quickstart)。

<Callout type="info">
API 參考中的每項功能都會標示為支援、部分支援、接受但忽略，或尚未支援。伺服器接受但不會實際處理的參數，會明確標示，而不會被寫成可用。
</Callout>

## 效能實測

0.1.5 已發布；main 為 0.1.6 開發週期。以下保留原始數據、樣本數與限制；不同權重的比較不能視為同權重結論。 [32K / 64K / 128K: results, strengths and gaps](/docs/guides/benchmarks).

## 在本機詢問文件

使用文件頁首或 ⌘K / Ctrl+K 的 **AI 問答**，向目前連線的 Yunshu 引擎提問。回答會串流顯示並附參考來源，可追問、複製、停止與回饋。請先以 `yunshu serve -m /path/to/mlx-model` 啟動文字模型。不使用雲端模型，量測期間暫停提問。參考來源由本機關鍵字搜尋找出：忽略贅詞、以詞組比對中文、優先使用頁面語言（未翻譯頁面退回英文），並依章節涵蓋多少你的關鍵字排序；檢索不使用模型。


---

<!-- internals/code-execution-sandbox -->
---
title: 程式碼執行沙盒
description: Anthropic code_execution 伺服器工具如何在 sandbox-runtime（srt）中執行模型撰寫的指令，並限制檔案、網路、時間、記憶體與輸出。
---

Anthropic 的 `code_execution` 工具讓模型在提供服務的機器上執行指令並編輯檔案。這只有在沙盒內才可接受。本頁說明 Yunshu 如何建立該沙盒、限制了什麼，以及這個工具如何對 API 公開。若要開啟並從用戶端使用，請見[程式碼執行指南](/docs/guides/code-execution)。

## 它做什麼

程式碼位於 `python/yunshu_gateway/sandbox/`，並由 `server_tools/runtime.py` 與 `server_tools/anthropic_loop.py` 接入為伺服器工具。

- **`srt.py`** 在 `PATH` 或 `~/.yunshu/srt` 下尋找 Anthropic 的 `sandbox-runtime` CLI（`srt`，選用，需要 Node 22.12 或更新版本），並為單一容器建立其設定。這些都是純函式，不需要 `srt` 就能測試。
- **`supervisor.py`** 以牆鐘時間、CPU、記憶體與輸出限制執行單一指令，這些是 `srt` 不提供的。
- **`containers.py`** 為每個容器保留一個工作區目錄，具備閒置過期與總大小上限。
- **`executor.py`** 把工具呼叫轉成沙盒化的行程。`bash_code_execution` 在 `srt` 下執行；`text_editor_code_execution`（`view`、`create`、`str_replace`）在行程內執行，路徑被限制在容器之內。

模型在一個宣告的工具（`code_execution_20250825`，同時接受 `20260120` 與 `20260521` 類型，行為相同）之下看到兩個子工具。伺服器執行工具迴圈，並像官方 API 一樣回傳 `server_tool_use` 與結果區塊。

## 為什麼這樣設計

有兩層保護主機。`srt` 使用 macOS 的 `sandbox-exec` 做檔案與網路隔離。Yunshu 補上 `srt` 缺少的部分：因為 macOS 不強制執行 `RLIMIT_AS`，而 `RLIMIT_NPROC` 會計入該使用者的所有行程，所以兩者都不使用；改由監督器取樣整個行程樹的常駐大小，超出時終止，之後再清掃整個 session，確保不會留下任何背景常駐行程。套件開頭的規則是絕對的：沒有任何指令在 `srt` 之外執行。若 `srt` 不存在或無法執行，請求會失敗（`SandboxUnavailableError`），而不是在沒有沙盒的情況下執行。

```mermaid
sequenceDiagram
    participant M as Model
    participant L as Server tool loop
    participant E as CodeExecutor
    participant S as Supervisor
    participant R as srt sandbox
    M->>L: bash_code_execution call
    L->>E: run in container
    E->>S: command with limits
    S->>R: srt --settings container.json
    R-->>S: stdout, stderr, exit code
    S-->>E: result or killed for limit
    E-->>L: result block and files
    L-->>M: tool result
```

## 政策：沙盒允許什麼

`build_settings` 為單一容器目錄產生政策：

| 範圍 | 規則 |
|---|---|
| 寫入 | 僅限容器目錄（`work/`、`home/`、`tmp/` 與每次呼叫專屬的 `out/`） |
| 讀取 | `/Users`、`/Volumes`、`/home` 與共用的容器根目錄都被拒絕。只有該容器與 Python 直譯器的前綴會被重新允許，所以你的家目錄、金鑰、`~/.yunshu` 與其他容器都讀不到。其他位置的系統函式庫仍可讀取。 |
| 網路 | 除非列出主機，否則一律沒有。迴路位址永遠無法連到（`allowLocalBinding` 為 false），且允許的名稱不能解析到私有網段（`10/8`、`172.16/12`、`192.168/16`、`100.64/10`、`fc00::/7`）。 |
| 其他 | Unix socket、Apple Events 與 `open` 皆關閉 |
| 環境 | 指令只看得到 `PATH`、`HOME`（容器內）、`TMPDIR`、`OUTPUT_DIR` 與語系變數，絕不包含伺服器的環境 |

允許網域清單並不會檢查流量：允許範圍很廣的主機仍可能洩漏資料，所以請讓清單保持簡短。

## 限制

| 限制 | 數值 | 來源 |
|---|---|---|
| 每次呼叫的牆鐘時間（也是 CPU 時間限制） | `YUNSHU_CODE_EXECUTION_TIMEOUT`，60 秒；超過後為 `execution_time_exceeded` | 設定 |
| 記憶體 | `YUNSHU_CODE_EXECUTION_MEMORY_MB`，2048；整個行程樹的常駐大小，每 100 ms 取樣，超出即終止 | 設定 |
| stdout 與 stderr | 各 64 KiB，超出會截斷並標記 | `supervisor.py` |
| 輸出總量（stdout 加 stderr） | 單次呼叫超過 1 MiB 即終止（`output_file_too_large`） | `supervisor.py` |
| 指令寫入的單一檔案大小 | 256 MiB（`RLIMIT_FSIZE`） | `supervisor.py` |
| 並行呼叫數 | 2（`MAX_CONCURRENT`） | `executor.py` |
| 所有容器合計 | 2 GiB（`MAX_TOTAL_BYTES`），最舊的先移除 | `containers.py` |
| 容器閒置過期 | `YUNSHU_CODE_EXECUTION_TTL_MIN`，20 分鐘 | 設定 |
| 每次呼叫附加的檔案數 | 20（`MAX_FILES_PER_CALL`） | `executor.py` |
| 文字編輯器 view | 200,000 個字元 | `executor.py` |

背景行程會隨呼叫一起結束：指令在自己的 session 中執行，發生逾時、記憶體超出或輸出溢位時，整個行程樹都會被終止。

## 作為伺服器工具對外公開

預設關閉。`YUNSHU_CODE_EXECUTION` 關閉時，宣告此工具的請求會收到指名該設定的 `400`。開啟但沒有 `srt` 時，回應為 `503`（`api_error`）並附上安裝指令。容器以 `container: "<id>"` 指定；未知或已過期的 id 會得到 `400`。`container_upload` 區塊會把 Files API 的檔案複製到工作目錄，而每次 bash 呼叫都會取得全新的 `$OUTPUT_DIR`，其頂層檔案會成為 Files API 項目。

違規只會以中繼資料記錄（容器 id、回傳碼、位元組數）。指令、輸出與檔案內容絕不寫入日誌。

## 保證

- 沒有任何指令在 `srt` 之外執行。
- 呼叫無法讀取使用者的家目錄、`~/.yunshu` 或其他容器，也無法寫到容器之外。
- 呼叫無法超出其牆鐘時間、記憶體或輸出限制；整個行程樹會被終止並清掃。
- 沙盒不會繼承伺服器的環境變數。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_CODE_EXECUTION` | 關閉 | 提供此工具 |
| `YUNSHU_CODE_EXECUTION_ROOT` | `~/.yunshu/sandbox` | 容器目錄，每個容器一個子目錄，權限模式 0700 |
| `YUNSHU_CODE_EXECUTION_TIMEOUT` | 60 | 每次呼叫的秒數 |
| `YUNSHU_CODE_EXECUTION_MEMORY_MB` | 2048 | 每次呼叫的記憶體 |
| `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW` | 無 | 沙盒可連線的主機，以逗號分隔 |
| `YUNSHU_CODE_EXECUTION_TTL_MIN` | 20 | 容器被刪除前的閒置分鐘數 |

## 與 Anthropic 容器的差異

- 它在 macOS 上執行，而不是 Linux x86_64。Python 是 Yunshu 本身執行所用的直譯器，只有標準函式庫。
- 呼叫之間沒有 REPL 狀態，也沒有程式化工具呼叫。
- 尚未提供 OpenAI 的 `code_interpreter` 與 `shell`。
- 沙盒依賴 macOS 的 `sandbox-exec`，Apple 已將其標示為棄用，而 `srt` 是 0.0.x 版本（指南記錄測試過的版本為 0.0.81）。

## 如何驗證

```bash
yunshu doctor        # the "code execution" row shows the srt version and a self-test
uv run pytest tests/unit/test_sandbox_core.py tests/unit/test_server_tools_code_execution.py -q
```

`tests/unit/test_sandbox_srt_integration.py` 在安裝了真實 `srt` 時會實際對它進行測試。


---

<!-- internals/console-process -->
---
title: 主控台行程
description: 網頁主控台為何以獨立的輕量行程執行、它代理與記錄什麼、如何找到引擎、重新啟動與 launchd 如何配合，以及量測時如何讓它暫停。
---

網頁主控台不屬於引擎行程。`yunshu console` 是一個獨立的輕量行程，負責提供主控台介面、在同一個 origin 上代理引擎 API，並記錄引擎的歷史。本頁說明其設計與各個運作部件。主控台各頁面的使用方式請見應用程式內的主控台指南；設定項目請見[設定](/docs/guides/configuration)。

## 它做什麼

主控台行程（`python/yunshu_console/`）做四件事：

- **提供**已建置的主控台與文件，路徑在 `/console/` 之下（`app.py`）。外殼是公開的，讓你可以輸入 token；推論、模型操作、金鑰與設定仍維持原本的授權。
- **代理**引擎 API：方法、內容、`Authorization` 與 `x-api-key`、SSE 串流與 WebSocket 都原封不動轉發，所以瀏覽器只和一個 origin 對話。當引擎無法連線時，代理會立即回應帶有 `engine_unreachable` 的 `502`，而不是卡住。
- **記錄**歷史（`poller.py`、`store.py`）。它每秒讀取一次引擎的低成本端點（`/v1/yunshu/status`、以游標從 `/v1/yunshu/requests/recent?after_seq=` 取得的已完成請求，以及大約每五秒一次的主機遙測），並以 WAL 模式寫入 SQLite，每十秒批次寫入一次。
- **記住中斷。** 引擎沒有回應期間不會寫入任何資料列。這段時間就是空缺，會被回報為空缺，絕不插補。事件會記錄引擎無法連線與恢復連線（含持續時間）、引擎重新啟動、模型載入或卸載，以及模型載入失敗。

它自己從資料庫回應 `/v1/yunshu/metrics/history`、`/v1/yunshu/requests/history` 與 `/v1/yunshu/console`，所以引擎停機時歷史仍然可用。

## 為什麼這樣設計

一個隨著被監控對象一起掛掉的監控頁面，在最需要的時候毫無用處。主控台是同層的獨立行程，從不匯入 MLX、mlx-lm 或 mlx-vlm（單元測試在全新的直譯器中斷言這一點），所以能立即啟動、閒置時佔用很小，也不會被引擎當機波及。引擎同樣不依賴它：主控台掛掉時，引擎不受影響。引擎本身不保留歷史，也不為此執行任何東西；每次讀取都是一般的 HTTP 請求，由引擎在其事件迴圈上回應，和網頁主控台發出的請求相同。

```mermaid
flowchart LR
    B["瀏覽器"] --> C["Console process :8100"]
    C -->|"代理，原封不動"| E["Engine :8000"]
    C -->|"1 s 輪詢"| E
    C --> S[("console-history.sqlite")]
    D["Discovery /health 探測"] --> C
    P["暫停檔"] -.->|"停止輪詢與探測"| C
```

## 歷史儲存

`store.py` 保留三張資料表，每張都以 SQL `AVG`（峰值用 `MAX`）從較細的一張彙總而來，範圍是一次寫入所觸及的區間，所以重新啟動不會遺失或重複計算部分區間：

| 資料表 | 解析度 | 保留期間 |
|---|---|---|
| `m1` | 1 秒 | 1 小時 |
| `m10` | 10 秒 | 24 小時 |
| `m60` | 1 分鐘 | `YUNSHU_CONSOLE_RETENTION_DAYS`（30） |

請求紀錄只保留中繼資料：id、模型、路由、狀態、時間戳、token 數、快取 token 數、首 token 延遲（TTFT）、解碼速度與結束原因。提示詞與輸出絕不儲存；引擎的已完成請求項目本來就不含這些，而 `request_row` 會丟棄任何不在白名單上的欄位。檔案大小以 `YUNSHU_CONSOLE_DB_MAX_MB`（64）為上限：超過時，先移除最舊的請求資料列，再移除最舊的 1 分鐘資料列。

請求游標是 `(boot_id, seq)`。主控台啟動後的第一次讀取會取得引擎環形緩衝中的全部內容；之後的讀取只取新增的部分；`boot_id` 改變（引擎重新啟動）時序列會重新開始。資料列以 `(t, request_id)` 為鍵，所以即使重播也不會重複寫入。

## 引擎自動探索

`yunshu console --engine auto`（或 `YUNSHU_CONSOLE_ENGINE=auto`）讓一個主控台在引擎於不同連接埠啟動與停止時保持開啟（`discovery.py`）。

- 每隔 `YUNSHU_CONSOLE_DISCOVER_S`（2 秒），每個候選者都會收到一次帶短逾時的非同步 `GET /health`。設定 `YUNSHU_CONSOLE_DISCOVER_PORTS=all` 時，候選者是這部 Mac 上正在監聽的 TCP 連接埠（透過 `lsof`，每 10 秒更新），扣除主控台行程（它們會代理 `/health`，看起來就像背後的引擎）。像 `8000,18990-18999` 這樣的明確清單，則只探測 `127.0.0.1` 上的那些連接埠。
- 只有 `/health` 的回應像 Yunshu 引擎時，連接埠才算數：`status: "ok"`、一個 `engine` 物件、一個 `server_state`，以及數值的 `uptime_seconds`。若連接埠的回應像是其他服務，會在 60 秒後再探測一次。
- 選擇具有黏性。正在跟隨的引擎在健康時會被保留；當它消失（連續兩次探測沒回應）時，主控台會跟隨最近啟動的存活引擎（uptime 最短者）。使用者釘選的引擎在存活期間優先。
- `/v1/yunshu/console/engines` 列出引擎；`/v1/yunshu/console/engines (POST)` 搭配 `{"url": ...}` 或 `{"port": ...}` 進行釘選，`{"url": null}` 則取消釘選。
- 歷史會隨每個請求儲存引擎 URL 與啟動時間，所以重新啟動會顯示為獨立的工作階段，而 `engine_switched` 事件標記一次切換。已對舊引擎開啟的串流不會被切斷。

## 生命週期、重新啟動與 launchd

| 啟動方式 | 執行內容 |
|---|---|
| `yunshu serve -m <model>` | 引擎，加上作為同層行程的主控台行程（`--no-console` 略過，`--console-port` 更改連接埠）。若該連接埠上已有主控台在回應，就不會再啟動。同層行程隨引擎一起結束。 |
| `yunshu console --engine URL` | 只啟動主控台，用來監看其他地方的引擎（引擎需要時加上 `--engine-token`） |
| `yunshu service install` | 兩個 launchd 工作：引擎，以及以獨立常駐工作執行的主控台，所以引擎重新啟動期間記錄仍會持續。`--no-console` 只安裝引擎；`yunshu service logs --console` 顯示主控台日誌。 |

在服務模式下，引擎以 `--no-console` 啟動，因為主控台是獨立的工作。

- **從主控台重新啟動。** 需要重新啟動的設定以 `PATCH /v1/yunshu/config` 寫入；回應會列出 `restart_for`。`POST /v1/yunshu/service/restart` 搭配 `confirm: true` 會等待進行中的請求完成，最長 `YUNSHU_DRAIN_TIMEOUT` 秒，然後執行 `launchctl kickstart -k`。在 launchd 之外會回應 `409 not_under_launchd` 並附上手動指令；主控台永遠不擁有引擎行程。這些路由需要 `admin` 權限。
- **從容應對中斷。** 引擎停機期間，介面會顯示「Engine restarting」與一般所需時間（已記錄中斷的中位數，即 `/v1/yunshu/console` 中的 `outages`），讓過期的頁面變暗，並在引擎恢復時用已記錄的歷史補上錯過的區段。只有 60 秒完全沒有存活的引擎才會變成警告。
- **部署健康度。** 記錄器也會追蹤行程佔用量及其 15 到 30 分鐘的迴歸斜率，以及請求錯誤率。斜率超過每小時 1 GiB，或最近一分鐘內 20 個以上完成請求中至少 5% 失敗時，會觸發一個主控台警示與一則警告事件。取消不計入錯誤率。這只是提示你去檢查記憶體帳本，並非洩漏診斷。

## 量測暫停

只輪詢 A/B 其中一邊的監控會擾動量測結果。當 `YUNSHU_CONSOLE_PAUSE_FILE` 所指的檔案存在，且內容為 `{"pause": true, "until": <epoch or null>, "reason": "..."}` 時，輪詢器與探索探測不會向任何引擎送出任何內容（`pause.py`）。該檔案在 `until` 之後失效；若 `until` 為 null，則在最後一次寫入兩小時後失效；檔案被移除時，主控台會自行恢復。代理仍會轉發你自己發出的請求，狀態島會顯示原因。`gpuq` 在執行安靜或速度工作時會寫入此檔案。

## 保證

- 主控台從不匯入 MLX，也不持有 GPU 工作；引擎當機波及不到它。
- 空缺就回報為空缺，絕不插補；缺少的資料顯示為無法取得，絕不顯示為零。
- 請求資料列只帶中繼資料。不會記錄任何提示詞或輸出文字。
- 請求游標在輪詢、引擎重新啟動或主控台重新啟動之間，絕不會跳過或重複任何請求。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_CONSOLE` | 開啟 | `yunshu serve` 同時啟動主控台行程 |
| `YUNSHU_CONSOLE_PORT` | 8100 | 主控台連接埠 |
| `YUNSHU_CONSOLE_HOST` | 未設定 | 綁定主機；未設定時，同層行程跟隨引擎的主機，單獨執行時為 127.0.0.1 |
| `YUNSHU_CONSOLE_ENGINE` | 未設定 | 要監看的引擎 URL；`auto` 則跟隨引擎 |
| `YUNSHU_CONSOLE_ENGINE_TOKEN` | 未設定 | 讀取引擎用的 Bearer token；退回使用 `YUNSHU_AUTH_TOKEN` |
| `YUNSHU_CONSOLE_DISCOVER_PORTS` | `all` | 自動模式下探測的連接埠 |
| `YUNSHU_CONSOLE_DISCOVER_S` | 2.0 | 探測間隔秒數 |
| `YUNSHU_CONSOLE_POLL_S` | 1.0 | 讀取引擎的間隔秒數 |
| `YUNSHU_CONSOLE_HISTORY` | 開啟 | 記錄歷史與請求紀錄 |
| `YUNSHU_CONSOLE_DB` | `~/.yunshu/console-history.sqlite` | 歷史檔案 |
| `YUNSHU_CONSOLE_RETENTION_DAYS` | 30 | 1 分鐘資料列、請求與事件的保留天數 |
| `YUNSHU_CONSOLE_DB_MAX_MB` | 64 | 大小上限 |
| `YUNSHU_CONSOLE_PAUSE_FILE` | 未設定 | 量測暫停檔 |

## 限制

- 它是供單一機器使用的操作工具。對網路提供服務（`--host 0.0.0.0`）時需要設定 token。
- 從介面重新啟動，只有在引擎以 `yunshu` launchd 服務執行時才有效。
- 歷史解析度受上述資料表限制；超過保留期限的請求細節就消失了。

## 如何驗證

```bash
uv run pytest tests/unit/test_console_proxy.py tests/unit/test_console_poller.py \
  tests/unit/test_console_store.py tests/unit/test_console_discovery.py \
  tests/unit/test_console_pause.py tests/unit/test_console_endpoints.py -q
curl -s "$CONSOLE_URL"/v1/yunshu/console | python -m json.tool
```

不匯入 MLX 的規則由 `tests/unit/test_console_proxy.py` 中的 `test_nothing_in_the_console_process_loads_mlx` 把關。


---

<!-- internals/constrained-decoding -->
---
title: 約束解碼
description: JSON schema、regex、選項、文法與工具呼叫的約束如何逐 token 強制執行、背後的兩個引擎，以及它們如何與推測解碼互動。
---

約束解碼會在每一步遮罩下一個 token 的選擇，讓模型輸出遵循指定格式。本頁為閱讀或修改程式碼的人說明 Yunshu 如何做到這一點。請求欄位與範例請見[結構化輸出](/docs/guides/structured-output)。

## 它做什麼

約束是一個小型狀態機，根據目前已生成的 token，指出下一步允許哪些 token。取樣器在選擇之前，會把其他所有 token 的 logit 設為負無限大。支援的約束種類如下：

| 種類 | 請求形式 | 實作 |
|---|---|---|
| JSON schema / `json_object` | `response_format`、`guided_json`、`structured_outputs` | 預設使用 llguidance，也可改用內建的狀態機（`YUNSHU_JSON_SCHEMA_ENGINE`） |
| Regex | `guided_regex` | `RegexConstraint`，針對文件載明的 regex 子集、自行實作的字元 DFA |
| 選項 | `guided_choice` | `ChoiceConstraint`，以字串建立的 trie |
| 上下文無關文法 | `grammar`（Lark 語法） | 建立在 llguidance 上的 `CfgGrammarConstraint` |
| 結構標籤 | `response_format.type = structural_tag` | llguidance，觸發前為自由文字 |
| 工具呼叫 | `tools` 搭配 `tool_choice` | `ToolCallGuide`（見[工具呼叫解析](/docs/internals/tool-call-parsing)） |

`ConstraintFactory.create` 會把文法類型對應到約束物件。所有約束共用同一個介面：`advance`、`get_allowed_tokens`、`is_done` 與 `reset`。

## 為什麼這樣設計

之所以有兩個引擎，是因為它們各有取捨。llguidance 引擎是原生的 Earley/lexer 解析器：登錄表記錄在 248K 詞彙表上每個 token 遮罩的中位數約 0.25 ms，屬性依 schema 順序輸出，強制的字面值使用正規 tokenization。內建的 Python 狀態機較慢（登錄表的說明文字記載中位數約 3 ms），接受任意屬性順序，並在 llguidance 無法編譯 schema 或無法綁定 tokenizer（它需要 Hugging Face fast tokenizer）時作為後備。兩個引擎都無法強制執行的 schema 會被事先拒絕，而不是只套用一半（`build_json_constraint`、`validate_constraint_spec`）。

接著，純文字快速路徑會用兩種方式之一把約束變成取樣器：

- **允許清單取樣器（預設）。** `ConstrainedSampler` 在每一步向約束詢問允許的 token id，並遮罩 logits。
- **位元遮罩引擎（選用）。** `YUNSHU_GRAMMAR_BITMASK=1` 會選用 `BitmaskConstrainedSampler`，它維護一個布林詞彙遮罩，並以一次向量化的 `mx.where` 套用。若建立位元遮罩引擎失敗，程式碼會以 debug 等級記錄，並退回允許清單路徑。

VLM runner 原生使用位元遮罩：`ConstraintGuide` 包裝一個序列的 `ConstraintProcessor`，並以封裝好的 int32 位元遮罩公開 `mask()`，由 llguidance 直接填入。

```mermaid
flowchart TD
    A["請求約束"] --> B["prepare_constraint：在事件迴圈之外編譯"]
    B --> C{"種類"}
    C -->|"json schema"| D["llguidance，否則內建"]
    C -->|"regex or choice"| E["內建 RegexConstraint 或 ChoiceConstraint"]
    C -->|"grammar or structural tag"| F["llguidance"]
    D --> G["每個請求獨立的 matcher 狀態"]
    E --> G
    F --> G
    G --> H["每一步的 token 遮罩"]
    H --> I["從允許的 token 中取樣"]
    I --> J["用該 token 推進 matcher"]
    J --> H
```

## 編譯與准入

`prepare_constraint`（`yunshu_engine/grammar_compile.py`）會在請求被接受之前，於事件迴圈之外編譯並驗證約束：每個事件迴圈最多 32 個排隊中的提交，以及兩個作用中的 CPU worker。編譯產物存放在有上限的 LRU `ArtifactCache` 中，採 single-flight 建構（同一產物同時只建構一次）；失敗的產物絕不保留，過大的輸入會略過保留。可變的 matcher 永遠屬於單一請求，絕不放進快取。取消絕不會暴露建構到一半的產物。

## 與推測解碼的互動

在 Qwen3.5 的封裝 row（MTP 與 DFlash）上，同一個約束物件同時服務序列路徑與驗證器。`yunshu_engine/constrained_spec.py` 提供下列機制：

- **交易。** `ConstraintGuide.checkpoint`、`feed` 與 `restore` 讓驗證器走過一個草稿 token 視窗，以 `plan(drafts, n_pos)` 為每個位置建立一份遮罩，然後回復。走過提案絕不會改變已提交的文法狀態。
- **強制 token。** `forced_tokens` 只會跳過遮罩內只有單一合法 token 的位置。該模組註記，強制的位元組可能有多種 BPE tokenization，所以單靠 llguidance 的位元組快轉無法做到 token 精確。
- **算術。** 帶有 response-format 或 logprob 的列會以序列單列算術驗證（`exact_verify`），讓受約束的請求在推測開或關時解出相同的 token。只有工具呼叫引導的請求（`invariant_guide`）會保留batch-invariant kernel：其下的自由文字不加遮罩，而在呼叫內部，遮罩只限制那些 logits 已由invariant kernel保證相等的列的 argmax。
- **死路。** 允許集合為空時，絕不會以未受約束的 argmax 回應。在接受狀態下，正規化後的 EOS id 是合法的；若沒有任何合法 token，`ConstrainedDecodingError` 會讓請求以失敗結束（fail closed）。

## Jump-forward 與工具文法

- `YUNSHU_JUMP_FORWARD`（關閉）：對純文字路徑上的貪婪 JSON schema 生成，文法強制的 token 不經前向傳遞直接輸出。對於 LoRA、取消事件、logit bias、被抑制的 token、`min_tokens`、logprobs、取樣，以及 regex/選項/文法約束，程式碼會關閉此功能，所以這些請求使用一般的約束解碼。

## 保證

- 受約束的輸出會被約束接受，否則請求失敗；允許集合為空時，絕不會用無約束的 argmax 敷衍過去。
- 受約束的請求在推測開與關時給出相同的 token（序列驗證算術），唯一例外是只有工具呼叫引導的請求，它們依設計保留invariant 算術。
- 遮罩絕不會移除有效的延續，所以約束不會改變模型原本會合法寫出的內容。
- 當某個文法與 tokenizer 的組合不受支援而執行無約束的後備時，解析出的工具呼叫並不能證明符合嚴格 schema。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_JSON_SCHEMA_ENGINE` | `llguidance` | JSON schema 與 `json_object` 偏好的引擎；`inhouse` 選用 Python 狀態機 |
| `YUNSHU_GRAMMAR_BITMASK` | 關閉 | 純文字引擎：用位元遮罩取樣器取代允許清單取樣器 |
| `YUNSHU_JUMP_FORWARD` | 關閉 | 純文字引擎：不經前向傳遞直接輸出文法強制的 token |

## 限制

- Regex 支援的是子集；`UnsupportedRegexError` 會指出哪些在範圍之外。上下文無關文法需要 llguidance。
- 兩個引擎都無法強制執行的 schema 會被拒絕，而不是近似處理。
- 在 VLM 路徑上，工具搭配一般 JSON 或文法約束會被拒絕，強制工具選擇搭配結構標籤也會被拒絕，這樣彼此獨立的契約就不會悄悄互相覆蓋。
- 約束會增加每個 token 的 CPU 工作量。在小型模型上並非沒有成本。

## 如何驗證

```bash
uv run pytest tests/unit/test_grammar_constraint.py tests/unit/test_json_schema_llguidance.py \
  tests/unit/test_constrained_spec.py tests/unit/test_spec_grammar_constraint.py \
  tests/unit/test_grammar_bitmask.py tests/unit/test_structural_tag.py -q
```

驗證工具的 `toolparse` 套件會透過真實 HTTP 檢查強制、串流與延遲結構標籤的輸出（見[驗證](/docs/developers/verification)）。


---

<!-- internals/memory -->
---
title: 記憶體管理
description: Yunshu 如何編列、記帳並歸還統一記憶體：快取預算、閒置修剪與保持暖機心跳、壓力下的准入控制，以及多模型模式下的模型淘汰。
---

記憶體是本機引擎的第一道限制：權重、KV 快取、前綴快取與 MLX 自己的配置器緩衝池，全都和你的應用程式共用同一塊統一記憶體。本頁說明程式碼如何編列這些記憶體、如何顯示是誰在持有，以及如何歸還不再需要的部分。內容只陳述程式碼實際做的事；設定項目請見[設定](/docs/guides/configuration)。

## 它做什麼

四個機制彼此配合，都不會改變模型輸出。

- **預算**限制可能持續成長的快取：RAM 與 SSD 上的 VLM 前綴快取（APC）、預填步驟之間保留的 MLX 已釋放緩衝池，以及純文字模型的前綴快取與 SSD 快取。
- **記帳**回答「誰持有記憶體」。`GET /v1/yunshu/memory` 會回傳持有者帳本（`yunshu_gateway/memory_ledger.py`），只由行程本來就維護的計數器建立。沒有來源的數字為 `null`，以相減推算出歸屬的持有者會標示 `estimated: true`。
- **閒置歸還**（`yunshu_engine/idle_memory.py`）在 runner 清空工作後歸還記憶體：先做循環垃圾回收，再修剪 MLX 的緩衝池與空閒的 malloc 分頁。
- **壓力控制**會拒絕可能讓行程記憶體耗盡的新工作，並在多模型模式下淘汰模型（`ModelManager`、`ProcessMemoryEnforcer`）。

## 為什麼這樣設計

對一部也會拿來做其他事的機器來說，伺服器「沒有 OOM」還不夠。設計原則是：每一 GiB 被保留的記憶體都有說得出名字的持有者，而閒置的伺服器會歸還不需要的部分。唯一刻意的例外是：有上限的已釋放 MLX 緩衝池會在請求之間保留，因為下一次快取還原與預填會重用這些緩衝區，它由閒置修剪釋放。

## 閒置歸還與保持暖機

VLM runner 沒有工作時會呼叫 `IdleMemory.drained()`；新請求會呼叫 `activity()` 並取消所有待處理的動作。

- 經過 `COLLECT_AFTER_S` = 2 秒後執行一次 `gc.collect()`。只被參照循環持有的陣列（已結束請求的產生器、閉包、快取）否則得等 Python 的循環回收器，而閒置的伺服器上它可能很久都不會執行。這段延遲讓連續到來的請求不必承擔此成本。
- 連續 `IDLE_TRIM_S` = 30 秒沒有請求後執行修剪：清除還原緩衝區、釋放 MLX 的配置器緩衝池，並在 macOS 上以 `malloc_zone_pressure_relief` 歸還空閒的 malloc 分頁。仍在使用中的物件維持配置。
- 兩者之間有一個**保持暖機心跳**，每 `HEARTBEAT_S` = 1 秒把 Metal 的 wired 記憶體上限維持在裝置建議的工作集，並執行一個不碰任何模型陣列的小型 matmul。沒有它的話，Metal 約 2 秒後就不再讓權重常駐，下一個請求得重新鎖定。原始碼記錄 27B 約需 200 ms（2026-10-22 實測：閒置後的追問首 token 延遲在 2 秒內為 0.23 秒，4 秒起為 0.44 至 0.66 秒）。修剪時會還原先前的 wired 上限。

計時器執行緒只負責提交工作。所有 MLX 呼叫都在序列化的 MLX executor 上執行，且每個階段都會再次確認 runner 仍處於閒置。

下圖顯示請求結束後的閒置排程。

```mermaid
stateDiagram-v2
    [*] --> Busy
    Busy --> Draining: "runner 清空"
    Draining --> Collected: "2 s: gc.collect"
    Collected --> Trimmed: "30 s: 釋放緩衝池與 wired 上限"
    Draining --> Busy: "新請求"
    Collected --> Busy: "新請求"
    Trimmed --> Busy: "新請求"
    note right of Draining
        1 Hz 心跳維持 wired 上限
    end note
```

## 預算

| 持有者 | 預算 | 預設行為 |
|---|---|---|
| APC RAM（VLM runner） | `YUNSHU_VLM_APC_MEMORY_GB` | 扣除權重與保留量後剩餘記憶體的一半，上限為機器記憶體的四分之一與 32 GiB；若剩下不到 1 GiB 則關閉 |
| APC SSD 層 | `YUNSHU_VLM_APC_DISK_GB` | 磁碟區的四分之一，最多 64 GiB；整個目錄共用一份預算，最久未使用的檔案先被移除 |
| 其他 APC 層 | `YUNSHU_VLM_APC_DISK_TIERS` | 未設定：僅 SSD |
| MLX 已釋放緩衝池 | `YUNSHU_PREFILL_BUFFER_CACHE_GB` | RAM 的 5%，最多 6 GiB；權重佔用後餘裕很小時為 0.5 GiB |
| APC 旁的草稿視窗 | `YUNSHU_VLM_APC_DRAFT_WINDOW_GB` | 0.25 GiB |
| 純文字前綴快取淘汰 | `YUNSHU_MEM_PRESSURE_THRESHOLD` | 記憶體使用率超過 85% 時淘汰項目 |
| 純文字 SSD 快取 | `YUNSHU_SSD_CACHE_MAX_GB` | 10 GiB |
| 預填 activation 峰值 | `YUNSHU_PREFILL_STEP_SIZE` | 每次前向傳遞處理 2048 個提示詞 token |

RAM 與 SSD 預算都是單一預算：選用的 WARM 層佔用 APC RAM 預算的 `YUNSHU_VLM_APC_WARM_SHARE`（預設 0.4），所以 APC 的 RAM 總量不會增加。各層本身請見[提示詞快取](/docs/guides/prompt-caching)。

## 壓力控制與模型淘汰

**准入控制。** `yunshu_gateway/admission.py` 以 MLX 使用中記憶體除以建議的 Metal 工作集來計算壓力。當有其他請求正在執行，且壓力達到或超過 `YUNSHU_MEMORY_PRESSURE_REJECT`（預設 0.95）時，新的生成請求會收到 `503` 並附上 `Retry-After`。閒置的伺服器永遠不會拒絕；設為 `0` 則關閉檢查。

**多模型模式。** `ModelManager` 以延遲方式載入模型，並為每個模型保留一筆含 `is_pinned`、選用的 `keep_alive_s` 與租約計數的項目。

- 載入之前，`_ensure_memory_available` 會淘汰最久未使用的模型，直到新模型能放進 `max_memory_bytes`。若找不到可淘汰的對象，會拋出 `MemoryError` 而不是無限迴圈。
- 被淘汰者必須已載入、未釘選、沒有被進行中的請求租用，且能證明處於閒置（`_find_lru_victim`）。對無法證明閒置的引擎，非強制卸載會被拒絕。
- 卸載之後，管理器會輪詢直到 Metal 真正釋放緩衝區（settle barrier，`settle_timeout_s` 為 5 秒），並使用實測的差值。
- 閒置卸載使用 `effective_keep_alive`：優先採用模型自己的 `keep_alive`（請求上 Ollama 風格的 `keep_alive` 欄位），否則使用 `YUNSHU_MODEL_TTL_SECONDS`（未設定：永不卸載）。已釘選的模型不會因閒置而卸載。
- `ProcessMemoryEnforcer` 會輪詢 MLX 使用中記憶體並與 `YUNSHU_MAX_MEMORY_GB` 比較（未設定：統一記憶體的 80%；`disabled` 則關閉），超過時淘汰最久未使用的模型。若只載入了一個未釘選的模型，它會保持載入，請求照常執行；enforcer 只會記錄警告。
- `GET /v1/yunshu/models/{id}/fit` 會模擬執行載入時的檢查（`ModelManager.fit_check`）。

在單一模型模式下，該模型會被回報為已釘選，永遠不會被釋放。

## 記憶體准入

引擎在記憶體不足時降級或等候，而不是 swap，並說明原因（`YUNSHU_MEMORY_ADMISSION`，預設開啟；只影響排程，輸出不變）。

1. **載入時。** 讀取權重之前，`plan_load` 檢查權重 + 作業系統保留量（`YUNSHU_MEMORY_RESERVE_GB`，預設為 RAM 的 5%，至少 4 GiB）+ 最小 KV 與工作區是否放得進實體記憶體（或 `YUNSHU_MAX_MEMORY_GB`）。放不下就以清楚的 `MemoryError` 拒絕載入，旁邊若有 `-ple-ssd` 檢視會直接指出。載入後 APC RAM 預算會縮小到權重之外剩餘的空間，日誌 `Memory plan:` 會說明縮了多少。
2. **請求准入。** 新請求的 KV（提示詞 + `max_tokens`）與預填工作區，對照即時餘裕檢查：macOS 空閒 + 非活躍 + 可清除頁、MLX 可回收的緩衝快取、核心壓力等級、swap 增長，再扣掉執行中請求仍會成長的部分。沒有餘裕的請求留在佇列等候；閒置伺服器的第一個請求一律放行，除非它連單獨執行都放不下（KV 與預填工作區超過權重之後 Metal 建議工作集剩下的空間）：此時回應 HTTP 507、`error.code: memory_limit` 與具體數字，而不是讓所有請求一起耗盡 Metal 記憶體。等候在即時進度的 `queue_reason: "memory"` 與 `queue_detail`、回應的 `x_yunshu.reasons.queue.waited_ms` 和 `yunshu_memory_admission_*` 指標中可見。
3. **釋出。** 可用記憶體低於保留量（或核心回報警告壓力）時，APC RAM 項目由舊到新釋出，有設定 SSD 層時寫入 SSD，不會先走到 swap（`yunshu_memory_pressure_sheds_total`、`yunshu_memory_pressure_shed_bytes_total`）。

## 保證

- 閒置歸還、緩衝池大小與保持暖機心跳都不會改變輸出。心跳的 matmul 不碰任何模型陣列，而緩衝池設定在登錄表中的描述是「allocator only; output unchanged」。
- 帳本只讀取計數器。它不執行任何 GPU 工作、不遍歷垃圾回收器，也不啟動子行程。所有 `*_gb` 欄位皆為二進位 GiB，旁邊附有精確的 `*_bytes`。
- 有損的省記憶體手段是使用者選項，預設為無損，基準測試絕不會把它們開啟：`YUNSHU_KV_PRECISION=int8`、`YUNSHU_VLM_APC_WARM=int8|int4`、`YUNSHU_KV_QUANT_BITS`、`YUNSHU_PREFIX_HOT_LIMIT`、`YUNSHU_SSD_CACHE_PRECISION=int8` 與 `YUNSHU_QUANT_MODE`。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_MAX_MEMORY_GB` | 未設定（多模型模式下為統一記憶體的 80%） | enforcer 使用的行程記憶體上限；`disabled` 則關閉 |
| `YUNSHU_MODEL_TTL_SECONDS` | 未設定 | 多模型：卸載閒置達此時間的模型 |
| `YUNSHU_MEMORY_PRESSURE_REJECT` | 0.95 | 忙碌時，超過 Metal 工作集此比例就拒絕新請求 |
| `YUNSHU_MEMORY_ADMISSION` | 開 | 沒有記憶體餘裕的請求留在佇列、壓力下釋出 APC RAM、載入時調整 APC 預算 |
| `YUNSHU_MEMORY_RESERVE_GB` | RAM 的 5%，至少 4 | 為 macOS 保留的記憶體 |
| `YUNSHU_VLM_APC_MEMORY_GB` | 自動計算 | APC 的 RAM 預算；0 則停用快取 |
| `YUNSHU_PREFILL_BUFFER_CACHE_GB` | 自動計算 | 預填步驟之間保留的已釋放緩衝池 |
| `YUNSHU_PREFILL_STEP_SIZE` | 2048 | 純文字引擎的預填區塊大小；調低可壓低 activation 峰值 |
| `YUNSHU_FOOTPRINT_SAMPLE_MS` | 0（關閉） | 取樣 `phys_footprint` 並在 `/metrics` 匯出峰值 |

在記憶體吃緊的主機上，INFERENCE 指南的長時間測試使用 `YUNSHU_VLM_APC_MEMORY_GB=4` 與 `YUNSHU_PREFILL_BUFFER_CACHE_GB=1`（27B；峰值因此降低，數字未記錄在基準測試紀錄中）。只有多模型主機才需要 `YUNSHU_MAX_MEMORY_GB`。

## 限制

- 閒置排程屬於 VLM runner。純文字 `mlx-lm` 模型有自己的前綴快取淘汰（`YUNSHU_MEM_PRESSURE_THRESHOLD`），但沒有這個心跳與修剪。
- 當沒有實測值時，帳本的權重數字會退回使用模型管理器的估計值，並以 `estimated: true` 標示。
- `yunshu_engine/memory_census.py` 可以指出每個存活陣列的持有者，但它會遍歷物件圖並暫停直譯器，所以只用於診斷，絕不會在服務路徑上執行。
- 淘汰需要引擎處於閒置。有進行中請求或租約的模型絕不會被卸載。

## 如何驗證

```bash
curl -s localhost:8000/v1/yunshu/memory | python -m json.tool
uv run pytest tests/unit/test_idle_memory.py tests/unit/test_process_memory_enforcer.py \
  tests/unit/test_memory_ledger_counters.py tests/unit/test_memory_guard_rejection.py -q
```

第一個指令會列出每個持有者、其來源，以及是否為估計值。在伺服器日誌中，`idle memory:` 開頭的行會顯示回收、修剪，以及 wired 上限的維持與釋放。保留記憶體的長時間測試是 `tests/unit/test_soak_retained_memory.py`。


---

<!-- internals/overview -->
---
title: 雲樞如何運作
description: 引擎內部地圖：服務模型、請求路徑、前綴快取、推測解碼、預填與記憶體，每個部分都連到專屬頁面。
---

這些頁面說明雲樞的內部運作，寫給閱讀或修改程式碼的人，以及想精確知道某個設定做了什麼的人。內容只陳述程式碼實際的行為。套件結構請見[架構](/docs/developers/architecture)；可調整的行為請見[設定](/docs/guides/configuration)。

## 它做什麼

雲樞是單一行程：在 Apple Silicon 上，一個 FastAPI 閘道架在以 MLX 為基礎的引擎前面。請求經過中介層與路由器，由 `ModelManager` 派送到對應模型的引擎，最後變成 token，再由閘道轉成該 API 方言的回應或串流。三個想法決定了其餘的設計：

- **兩條服務路徑。** 每個 `mlx-vlm` 模型（`VLMEngine`）都由 VLM batch runner 服務（`vlm_batch_runner.py`，由 `VLMEngine._build_batch_runner` 建立，並承載 round driver `round_driver/`）。純文字 `mlx-lm` 模型走單請求快速路徑（`_generate_fast`，直接呼叫 mlx-lm 的 `generate_step`）；對這類模型的並行請求會被序列化。
- **單一 MLX 執行緒。** 所有 GPU 工作都在擁有 Metal stream 的單一 worker 執行器上執行，事件迴圈不會碰 MLX 陣列。
- **一致性規則。** 快取命中等於未命中、推測開啟等於推測關閉、預演（rehearsal）不改變輸出。每個內部頁面都會說明適用哪條規則以及如何檢查。

## 為什麼這樣設計

雲樞是單節點引擎，因此針對單一機器最佳化首 token 時間、解碼速度與前綴重用，而不是多租戶吞吐量。最佳化預設維持無損；有損的（例如 int8 KV）是明確的使用者選項。自訂 Metal kernel 只有在相同 checkpoint 的對照顯示端到端確實有收益、且輸出相同或在容差內時才會採用。

```mermaid
flowchart TD
  C["Client"] --> M["Middleware"]
  M --> R["Router"]
  R --> D["ModelManager dispatch"]
  D --> V["VLM batch runner"]
  D --> F["Text fast path"]
  V --> T["One MLX thread"]
  F --> T
  T --> S["Detokenize, stop, SSE"]
  S --> C
```

上圖標出每個內部頁面位於請求路徑的哪個位置。

## 保證（一致性規則）

| 規則 | 頁面 |
|---|---|
| 前綴快取命中回傳的 token 與冷預填相同 | [前綴快取](/docs/internals/prefix-cache) |
| 開啟推測解碼的 greedy 輸出與關閉時相同 | [推測解碼](/docs/internals/speculative-decoding) |
| 下一輪預演與提示分段大小不會改變輸出 | [預填與預演](/docs/internals/prefill-and-rehearsal) |

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_VLM_DRAFT` | 未設定 | 覆寫 Qwen3.5 系列使用的推測 drafter |
| `YUNSHU_VLM_APC_MEMORY_GB` | 依剩餘記憶體推算 | 前綴快取的 RAM 預算；`0` 表示停用 |

所有設定都登錄在 `python/yunshu_engine/settings.py`；`yunshu config` 會列出實際生效的值與來源。

## 限制

雲樞沒有多節點模式，也不以多租戶吞吐量為目標。推測解碼在 round driver 上執行，因此並行 row 也會一起做草稿。

## 如何驗證

執行 `yunshu config` 查看生效的設定，並閱讀[驗證](/docs/developers/verification)了解檢查各項一致性規則的 `yv` 工具。

## 頁面

<Cards>
  <Card title="請求生命週期" href="/docs/internals/request-lifecycle">
    閘道、中介層、路由器、引擎派送、runner、MLX 執行緒與回傳串流。
  </Card>
  <Card title="前綴快取" href="/docs/internals/prefix-cache">
    精確 checkpoint、64 對齊切點、媒體 key、RAM 與 SSD 層。
  </Card>
  <Card title="推測解碼" href="/docs/internals/speculative-decoding">
    DFlash2 與 MTP 草稿、batch-invariant 驗證 kernel 與 round driver 的打包 row。
  </Card>
  <Card title="預填與預演" href="/docs/internals/prefill-and-rehearsal">
    Split-invariant 預填與下一輪預演。
  </Card>
  <Card title="記憶體" href="/docs/internals/memory">
    記憶體用在哪裡，以及閒置記憶體如何歸還。
  </Card>
  <Card title="受限解碼" href="/docs/internals/constrained-decoding">
    解碼時強制 JSON schema、regex 與文法。
  </Card>
  <Card title="工具呼叫解析" href="/docs/internals/tool-call-parsing">
    模型輸出如何變成工具呼叫。
  </Card>
  <Card title="主控台行程" href="/docs/internals/console-process">
    網頁主控台背後獨立的輕量行程。
  </Card>
  <Card title="程式碼執行沙盒" href="/docs/internals/code-execution-sandbox">
    伺服器端程式碼執行如何隔離。
  </Card>
</Cards>


---

<!-- internals/prefill-and-rehearsal -->
---
title: 預填與預演
description: 預填如何讓分段長度不影響 token（split-invariant 預填、64 對齊 checkpoint），以及下一輪預演如何在閒置時預填回覆而不改變輸出。
---

預填把提示轉成 KV 狀態。兩項功能讓長且重複的提示變便宜，卻不改變模型的輸出：split-invariant 預填使快取執行與冷執行的算術相同；下一輪預演則在引擎閒置時先做下一輪的預填。

## 它做什麼

**Split-invariant 預填。** 在合格路徑上（Apple M5 級 Mac 上的 Qwen3.8-27B，使用雲樞固定版本的 MLX），預填對每種分段長度都使用同一組 kernel：

- matmul：原生 NAX GEMM，短分段補到 64 列並裁切輸出（`YUNSHU_PREFILL_MATMUL`）；
- 注意力：任何 query 長度都用 BQ32 tile 注意力（`YUNSHU_PREFILL_ATTENTION`）；
- GatedDeltaNet 遞迴：分塊更新，短尾端以恆等更新補到 64，使 fp32 狀態保持精確（`YUNSHU_PREFILL_GDN`）。

提示分段與 APC checkpoint 都切在**絕對 64 token 邊界**，因此一次算完、分段算，或從 checkpoint 接續的提示，都經過相同的算術。Kernel 位於 `python/yunshu_engine/kernels/`（`nax_prefill.py`、`gdn_prefill.py`、`attn_prefill.py`）。

**下一輪預演**（`python/yunshu_engine/next_turn.py`，由 `VLMEngine` 驅動）。聊天的後續請求會重送包含引擎剛解碼回覆的對話。快取裡存的是上一輪的提示，所以後續請求得預填那段回覆。解碼期間的 KV 不能重用，因為解碼與預填的算術不同。因此，回覆送出且引擎閒置後，引擎會把回覆放在下一輪的位置來渲染對話，並以 `max_tokens=1` 當作一般請求預填，儲存精確的 APC checkpoint。之後到達的請求會還原這些 checkpoint，只預填其餘部分與新訊息。

- `YUNSHU_NEXT_TURN_PREFILL` 預設為 `stride`：預演停在助理文字結尾處（含）以前、最後一個絕對 64 token 邊界。短回覆若沒有新增完整的 atom，就不會觸發重放較舊的前綴。
- 預演在 `YUNSHU_NEXT_TURN_DELAY_S`（預設 0.3 秒）之後開始，所以立即的後續請求（如 agent 迴圈）會在任何預演工作開始前到達，只預填一次。預演期間到達的相符請求會接手進行中的工作；不相符的則在下個可搶佔邊界取消它。
- 只預演純文字聊天：回覆必須以 `stop` 或 `length` 結束、長度為 16 到 4096 個 token，且請求不可有媒體、工具或受限解碼（`next_turn.ineligible_reason`）。

**Row，而非批次。** 每個請求從進入起就是 round driver 的一個 row，因此沒有批次到推測通道的升級步驟（見[推測解碼](/docs/internals/speculative-decoding)）。

```mermaid
stateDiagram-v2
  [*] --> Serving
  Serving --> Idle: reply delivered
  Idle --> Waiting: start delay
  Waiting --> Serving: new request arrives
  Waiting --> Rehearsing: delay elapsed
  Rehearsing --> Serving: diverging request cancels
  Rehearsing --> Serving: matching request adopts work
  Rehearsing --> Idle: checkpoints stored
```

此圖顯示預演的生命週期：它只在沒有其他工作時執行，任何真實請求都優先。

## 為什麼這樣設計

快取命中要等於未命中，兩者必須使用相同的算術。讓預填 split-invariant，移除了結果對提示切在哪裡的依賴，這才讓儲存的 checkpoint、預演的前綴與冷預填彼此一致。預演再把閒置的 GPU 時間，用在下一個請求原本要在關鍵路徑上做的工作。只要準確度門檻通過，冷輸出的跨版本漂移是可接受的；同一版本內的一致性才是硬性門檻。

## 保證

- **預演是結果被丟棄的一般請求。** 它走正常的預填路徑，所以不可能改變輸出；它只決定下一個請求到達時快取裡已有什麼。
- 在 split-invariant 路徑上，**冷、快取與預演的前綴產生相同的 token**。
- 預演**從不儲存解碼期間的 KV**，只儲存預填 checkpoint。
- `boundary` 與 `exact` 會增加助理結尾的切分，可能改變多輪的浮點捨入。它們需要明確啟用，不是預設。
- 預演會耗用閒置的 GPU 時間與一份額外的快取前綴，也並非在所有情況下都能消除立即後續請求的實測延遲；見[基準測試](/docs/guides/benchmarks)。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_NEXT_TURN_PREFILL` | `stride` | `off`、`stride`、`boundary` 或 `exact` |
| `YUNSHU_NEXT_TURN_DELAY_S` | `0.3` | 回覆結束到預演之間的秒數；`0` 表示一閒置就開始 |
| `YUNSHU_PREFILL_MATMUL` | `stock` | 合格路徑上的預填 matmul（原生 NAX，短分段補到 64） |
| `YUNSHU_PREFILL_GDN` | `chunked` | 預填遞迴；短尾端以恆等更新補齊 |
| `YUNSHU_PREFILL_ATTENTION` | `tile` | 任何 query 長度皆用 BQ32 NAX 注意力 |
| `YUNSHU_PREFILL_STEP_SIZE` | `2048` | 僅文字引擎：每次預填處理的提示 token 數 |

## 限制

- Split-invariant 路徑只針對一種模型、晶片系列與 MLX 版本合格；其他情況維持較舊的預填 atom 格線。
- 預演涵蓋 VLM runner 上的純文字聊天，不含媒體、工具或受限請求，也不含純文字 `mlx-lm` 模型。
- 更改預填算術會開啟新的 APC 命名空間，因此較早算術產生的 checkpoint 不會被重用。

## 如何驗證

```bash
uv run pytest tests/unit/test_next_turn.py tests/unit/test_gdn_span_invariance.py tests/unit/test_apc_canonical_prefill.py -q
```

在真實伺服器上，以 `temperature` 0 分別送出冷的與預演後的同一段對話並比較 token；`x_yunshu.cache` 與 `usage` 會顯示快取的 token 數。`yv` 工具以其 cache-exact 階段執行這類檢查（見[驗證](/docs/developers/verification)）。快取儲存方式見[前綴快取](/docs/internals/prefix-cache)。


---

<!-- internals/prefix-cache -->
---
title: 前綴快取
description: 自動前綴快取（APC）如何儲存精確 checkpoint、以 token 與媒體作為 key、溢寫到 SSD，以及為什麼命中回傳的 token 與冷預填相同。
---

本頁說明 VLM batch runner 上前綴快取的內部機制。面向用戶端的部分（usage 欄位、`cache_control`、標頭）請見[提示快取](/docs/guides/prompt-caching)，這裡不重複。

## 它做什麼

新提示的開頭與先前某個提示相同時，引擎會還原該前綴儲存的狀態，只對其餘部分做預填。這個狀態是**精確 checkpoint**：注意力 KV，加上混合模型（例如混合注意力與 GatedDeltaNet 層的 Qwen3.5 系列）的遞迴狀態，兩者都在同一個 token 位置。checkpoint 只有以完全相同 token 開頭的提示才能重用。

- **Key。** 文字以 token id 作為 key。影像輸入以像素值的雜湊作為 key（`VLMBatchRunner._image_hash`，由來源影像摘要而來），音訊以其特徵作為 key，所以同一張圖會重用快取，不同的圖則不會。
- **切點。** 在合格的 split-invariant 路徑上，提示分段與 checkpoint 都切在絕對 64 token 的邊界，使冷執行與快取執行處理相同的分段。見[預填與預演](/docs/internals/prefill-and-rehearsal)。
- **策略**（`python/yunshu_engine/apc_manager.py`，`YunshuAPCManager`）：以位元組預算限制 RAM；請求的 checkpoint 會取代先前屬於其前綴的 checkpoint，所以長對話只保留一份；系統回合結尾（系統提示加工具清單）依每個不同的 head 各自保留為獨立的 head checkpoint，同一專案的新對話可重用它。
- **層級。** HOT 是全精度 RAM。WARM 是選用的緊湊 RAM 形式（`apc_warm.py`）。SSD 是持久層（`apc_storage.py`）；還可再加入其他目錄作為較低的儲存層。

```mermaid
flowchart LR
  P["New prompt"] --> L["Lookup longest checkpoint prefix"]
  L -->|"HOT"| H["Clone from RAM"]
  L -->|"WARM"| W["Decode into HOT"]
  L -->|"SSD"| S["Read from disk"]
  L -->|"none"| X["Full prefill"]
  H --> R["Prefill the rest"]
  W --> R
  S --> R
  X --> R
  R --> N["Store new checkpoints"]
  N --> E["RAM evicts to WARM or SSD"]
```

查詢會在所有層級中挑成本最低的候選，再只預填沒有任何 checkpoint 涵蓋的部分。

## 為什麼這樣設計

- **精確 checkpoint，而非近似重用。** 還原出來的 checkpoint 就是儲存的陣列，所以命中不會引入誤差。解碼期間的 KV 不會用於下一輪，因為解碼與預填的算術不同，快取結果就會與未命中不同。
- **預算而非筆數。** RAM 預算以位元組計。未設定時，是權重與 OS 與 activation 預留量之後剩餘記憶體的一半，最多為機器記憶體的四分之一與 32 GiB；若剩餘不足 1 GiB 則自動關閉快取。
- **預設開啟 SSD。** 重新載入遠比重算長前綴便宜，而且重啟後仍在。RAM 淘汰 checkpoint 時寫入磁碟，常駐的則在關機時於時限內寫出。儲存的狀態以 checkpoint 權重（路徑、檔案大小、修改時間）做命名空間，因此原地替換模型不會讀到舊狀態。
- **每次查詢用成本模型。** 有多個儲存層時，查詢會依觀察到的還原速度，挑「還原時間加上剩餘部分預填」最低者。

## 保證

- **命中等於未命中。** 命中會精確還原儲存的 checkpoint，而在 split-invariant 路徑上冷預填使用的分段相同，所以 token 一致。`tests/unit/test_apc_identity_probe.py` 與 `tests/unit/test_apc_canonical_prefill.py` 涵蓋此項，快取工作的輸出一致性檢查也比較了 HOT、WARM-lossless、SSD 與冷請求的 greedy 文字。
- **WARM lossless 與 SSD 位元精確。** SSD 層永遠儲存精確狀態，即使 WARM 是有損的。損毀或檢查碼驗證失敗的條目會被丟棄，查詢會落到下一層或重算。
- **有損需明確啟用。** `YUNSHU_VLM_APC_WARM=int8` 或 `int4` 會量化 WARM 層的 K/V，且永遠不會成為預設。
- **磁碟安全。** 一個預算涵蓋整個快取根目錄；過期的命名空間優先清除；保留剩餘空間下限；寫入錯誤只丟棄該 checkpoint，不影響進行中的請求。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_VLM_APC_MEMORY_GB` | 推算（見上） | RAM 預算（GiB）；`0` 停用快取 |
| `YUNSHU_VLM_APC_DISK` | 開啟 | SSD 層；`0` 表示僅用 RAM |
| `YUNSHU_VLM_APC_DISK_GB` | 磁碟區的四分之一，最多 64 GiB | 整個快取目錄的容量上限 |
| `YUNSHU_VLM_APC_WARM` | `off` | `lossless`、`int8` 或 `int4` 緊湊 RAM 層 |
| `YUNSHU_VLM_APC_WARM_SHARE` | `0.4` | WARM 層佔 APC RAM 預算的比例 |
| `YUNSHU_VLM_APC_DISK_TIERS` | 未設定 | 較低的儲存層，`PATH[@GiB],...` |
| `YUNSHU_PREFIX_MAX_ENTRIES` | `64` | 文字快速路徑 `KVPrefixCache` 的條目數 |

文字快速路徑有自己的快取（`KVPrefixCache`），其 SSD 層需明確啟用（`YUNSHU_SSD_CACHE`）。

## 限制

- **使用滑動視窗（sliding-window）快取的模型系列不在 VLM runner 的 APC 範圍內**，因為輪替快取無法由密集 KV 區塊組裝。例外是 `gemma4`：其原生快照包含視窗、絕對 offset 與環形索引；它的精確視窗還原是針對 checkpoint 的，有範圍明確的一致性檢查，而不是對所有滑動視窗模型的全面宣稱。`VLMEngine._build_batch_runner` 依 `model_apc_plan` 與後端快取能力逐模型判斷。
- Apple Paravirtual Metal 使用通用層（generic layer），沒有 APC。
- 命中需要精確的 token 前綴：提示前段有任何變動，其後所有內容都會位移。
- WARM lossless 會壓縮快取；在 2026-10-02 於 Qwen3.8-27B 上記錄的重放中，它的首 token 時間並未勝過 SSD 層，因此預設關閉。

## 如何驗證

```bash
uv run pytest tests/unit/test_apc_manager.py tests/unit/test_apc_warm.py tests/unit/test_apc_storage.py -q
yunshu cache status
```

`yunshu cache status` 顯示磁碟上有什麼，`GET /v1/yunshu/cache` 與主控台 Cache 頁面顯示條目、層級與命中。每個回應都在 `x_yunshu.cache.tier` 說明由哪一層服務。快取精確（cache-exact）規則是[驗證](/docs/developers/verification)所述檢查之一。


---

<!-- internals/request-lifecycle -->
---
title: 請求生命週期
description: 一個請求如何經過閘道中介層、路由器、ModelManager 派送、VLM batch runner、MLX 執行緒，最後以串流送回。
---

本頁追蹤一個請求，從 socket 一路走到回應的最後一個位元組，並標出每個步驟由哪個模組負責。

## 它做什麼

1. **中介層。** `python/yunshu_gateway/main.py` 的 `create_app()` 堆疊各層。因為 `add_middleware` 是往前插入，最後加入的在最外層。由外到內：`DisconnectWatchMiddleware`、`MetricsMiddleware`、`LiveCORSMiddleware`、`ModelLeaseMiddleware`、`ResidentActivityMiddleware`、`YunshuExtensionsMiddleware`（請求 id、佇列標頭、每個回應的 `x_yunshu` 統計）、`AuthMiddleware`、`RateLimitMiddleware`（僅在 `YUNSHU_RATE_LIMIT_RPM` 大於 0 時）以及 `RequestLoggingMiddleware`。Metrics 刻意放在 auth 之外，讓 401、429、413 也被計入。斷線監看層在最外面，因為 Starlette 的 `BaseHTTPMiddleware` 會隱藏用戶端斷線；它把斷線記錄在 `scope["yunshu.client_gone"]`。
2. **路由器。** `python/yunshu_gateway/routers/` 下的路由器（`chat.py`、`anthropic.py`、Responses 路由器等）驗證 body，正規化成一個內部請求並解析模型。
3. **引擎派送。** `ModelManager`（`python/yunshu_engine/model_manager.py`）延遲載入模型、在記憶體壓力下依最近最少使用淘汰，並發出租約（lease）。`ModelLeaseMiddleware` 讓請求取得的每個模型在回應結束前都持有租約，因此卸載、TTL 到期或淘汰都不會在回應途中抽走模型。
4. **VLM batch runner。** 對 `mlx-vlm` 模型，`VLMEngine.generate_stream` 在 MLX 執行緒上準備提示（chat template、媒體編碼、約束編譯），並把 job 提交給 `VLMBatchRunner`。round driver 把提示變成一個 row：在自己的快取上分塊預填、加入時查詢前綴快取，並讓所有活躍的 row 在打包的步驟中一起解碼；Qwen3.5 與 Flash-Next 的 row 會起草。純文字 `mlx-lm` 模型則改走 `_generate_fast`。
5. **MLX 執行緒。** 所有 GPU 工作都在單一 worker 執行器上執行（`python/yunshu_engine/mlx_executor.py`），它擁有 Metal generation stream。
6. **還原文字、停止、遞送。** runner 產出 token id。`VLMEngine` 執行每個請求的 detokenizer、stop 字串與推理狀態追蹤，並透過有界佇列把 `RequestOutput` 推給非同步消費者。路由器再把它們轉成該方言的 JSON 或 SSE 事件，包含 usage 與附加的 `x_yunshu` 欄位。

```mermaid
sequenceDiagram
  participant C as Client
  participant MW as Middleware
  participant R as Router
  participant MM as ModelManager
  participant E as VLMEngine
  participant B as VLMBatchRunner
  participant G as MLX thread
  C->>MW: HTTP request
  MW->>R: auth, rate limit, lease
  R->>MM: get engine for model
  MM-->>R: engine
  R->>E: generate_stream
  E->>G: template, media, constraint
  E->>B: submit job
  B->>G: prefill, then decode steps
  G-->>B: token ids
  B-->>E: tokens
  E-->>R: text, stop, usage
  R-->>C: SSE events or JSON
```

此圖呈現串流請求各交接點的順序；非串流請求會收集相同的輸出，回傳單一 body。

## 為什麼這樣設計

- **單一 GPU 執行緒。** mlx-lm 的 generation stream 是綁定建立它的執行緒的模組層級狀態，所以每個引擎都把工作提交到同一個執行器。這讓單一行程同時服務多個模型也很安全。
- **runner 產 id，引擎產文字。** 把 detokenize 與 stop 邏輯放在 `VLMEngine`，讓文字路徑與 VLM 路徑以相同方式回報結果。
- **有界遞送。** 引擎透過會監看取消事件的阻塞式 put 寫入佇列，所以慢速用戶端不會讓 GPU 執行緒無限制地緩衝。

## 保證

- 用戶端斷線會取消其生成，而不是一路解碼到 `max_tokens`；斷線監看層設定一個事件，路由器的斷線防護（`run_with_disconnect_guard`、`client_disconnected`）在事件被設定時取消生成。
- 請求持有租約期間，模型不會被卸載。
- 在引擎內失敗的串流會以錯誤事件與 `finish_reason: "error"` 結束，而不是默默截斷。
- 每個請求的 sampler、detokenizer 與 stop 狀態不會在請求間共用；detokenizer 不做池化。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_RATE_LIMIT_RPM` | `0` | 每分鐘請求數上限；大於 0 才安裝此中介層 |
| `YUNSHU_AUTH_TOKEN` | 未設定 | 管理 token；設定後才強制驗證（具名 API key 是另一套） |

## 限制

- 純文字 `mlx-lm` 請求一次只服務一個。
- VLM 模型會拒絕 LoRA adapter 與自訂 logits processor。
- 預填一次接納一個請求，並與其他列的解碼交錯進行。

## 如何驗證

`tests/unit/test_client_disconnect_watch.py` 與 `tests/unit/test_disconnect_guard.py` 涵蓋斷線取消。執行 `uv run pytest tests/unit/test_client_disconnect_watch.py -q`。對真實路徑，回應的 `X-Request-Id` 標頭與 `x_yunshu` 物件會顯示真實請求的 id、佇列狀態與快取層。另見[架構](/docs/developers/architecture)。

讓每個路由彼此保持一致的 API 層功能矩陣，請見 [API 一致性矩陣](/docs/developers/api-parity)。


---

<!-- internals/speculative-decoding -->
---
title: 推測解碼
description: 雲樞如何以 DFlash2 或 MTP head 每步起草並驗證多個 token、為什麼開關推測時 greedy 輸出相同，以及哪些模型與請求會參與。
---

推測解碼先以低成本起草數個 token，再用目標模型的一次前向傳遞驗證。雲樞用它讓解碼更快，且不改變輸出。

## 它做什麼

對於 **VLM runner 上的 Qwen3.5 系列**（`VLMEngine._SPEC_MODEL_TYPES` 中的模型類型：`qwen3_5`、`qwen3_6`、`qwen3_5_moe`、`qwen4_exp`），`spec_select.choose` 依下列順序挑選 drafter：

1. `YUNSHU_VLM_DRAFT`：drafter 目錄、`mtp`（強制使用 checkpoint 的 MTP head）或 `off`（停用起草）。
2. 否則，在 models 目錄或 Hugging Face 快取中找到、且 `config.json` 與目標相符（層數與 hidden size 相同）的 **DFlash2 drafter**。這是自動的。
3. 否則，若 checkpoint 自帶 **MTP head** 就用它（`YUNSHU_MTP`）。
4. 否則，使用一般解碼。

區塊大小：DFlash 使用 drafter 訓練時的區塊，MTP 為 6，除非設定了 `YUNSHU_MTP_BLOCK_SIZE`。起草在 **round driver** 上進行：每個請求都是一個 row，所有 row 的起草與驗證回合一起執行，每個 row 依其接受率決定深度。row 的輸出不取決於哪些 row 與它共用同一步，因此驗證是無損的。

其他起草來源：

- **提示複製回合。** 回合可以直接提議接續內容：在請求的提示與已生成文字中，找出目前尾端最長的先前出現處，提議其後的內容。同樣交由驗證步驟檢查。`YUNSHU_SPEC_COPY_ROWS` 設定驗證列數（預設 32；`0` 關閉）。僅稠密與 MoE Qwen3.5；Flash-Next 的 DFlash 列沒有複製草稿器。
- **草稿樹。** `YUNSHU_SPEC_TREE`（`auto`）對符合條件、使用 DFlash2 drafter 的 greedy 請求使用草稿樹驗證器。
- **通用 round driver 層（沒有 packed 層的 mlx-vlm 家族）。** 對 greedy 請求以 `spec_decode`（或 `YUNSHU_NGRAM_DEFAULT`）啟用同一套 n-gram / suffix 推測，僅限單一解碼 row 且 KV cache 可 trim；保證為驗證器在視窗上的 top-1，與逐 token 解碼不保證逐位元相同。packed Qwen3.5 與 Flash-Next 維持批次不變的驗證。
- **純文字 `mlx-lm` 模型。** 對 greedy 請求的無損 n-gram 或 suffix 推測（`YUNSHU_NGRAM_DEFAULT`，預設關閉；請求也可用 `spec_decode` 要求；`YUNSHU_SPEC_PROPOSER` 為 `ngram` 或 `suffix`），以及 Gemma 4 文字模型的 assistant drafter 目錄（`YUNSHU_GEMMA4_ASSISTANT`）。
- **Jump-forward** 是針對受限輸出的另一種機制（文法強制的 token 不需前向傳遞即可輸出）。見[受限解碼](/docs/internals/constrained-decoding)。

```mermaid
flowchart TD
  A["Request on Qwen3.5 family"] --> B{"YUNSHU_VLM_DRAFT"}
  B -->|"off"| P["Plain decode on invariant kernels"]
  B -->|"path"| D["DFlash drafter at path"]
  B -->|"mtp"| M["MTP head"]
  B -->|"unset"| C{"Matching DFlash2 found"}
  C -->|"yes"| D
  C -->|"no"| E{"Checkpoint has MTP head"}
  E -->|"yes"| M
  E -->|"no"| P
  D --> V["Draft, verify in one pass"]
  M --> V
```

此圖顯示模型載入時如何選擇 drafter；之後每個 row 在 round driver 上依需求起草。

## 為什麼這樣設計

推測解碼只有在使用者看不出差異時才值得提供。因此雲樞讓驗證步驟的算術與一般解碼完全相同，而不是接受微小的數值差異。草稿一律由目標模型驗證，所以錯誤的草稿只浪費時間，不影響正確性。

## 保證

- **推測開等於推測關。** 開啟推測解碼時，greedy 輸出與同一引擎關閉時 token 完全一致。解碼（一列）與驗證（數列）時，目標模型的每個 matmul 都走同一個 kernel，其每列結果與共用該次呼叫的列數無關，且注意力與 GatedDeltaNet 的驗證路徑與單列解碼位元精確相符。這些 batch-invariant kernel 是執行時編譯的 Metal kernel，位於 `python/yunshu_engine/kernels/`。關閉起草的推測系列模型仍使用通道的一般解碼算術，所以這種情況下一致性同樣成立。
- **取樣請求**使用以位置為 key 的雜訊，因此結果與哪些 token 被起草無關。
- **Draft 模型沿用原版 kernel**；只有目標模組會被改接，預填區塊維持自己的 kernel。
- **不宣稱：** 與原生 MLX 單列解碼逐位元相同。不同的歸約順序會讓 logits 有捨入等級的差異，這種漂移是可接受的。硬性門檻是同一個雲樞版本內的一致性。
- **Drafter 量化在效果上無損。** `YUNSHU_DRAFT_BITS`（預設 8）只改變 drafter 的權重；草稿會被驗證，所以任何值的輸出 token 都相同。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|
| `YUNSHU_VLM_DRAFT` | 未設定 | drafter 目錄、`mtp` 或 `off` |
| `YUNSHU_MTP` | 開啟 | 使用 checkpoint 的 MTP head |
| `YUNSHU_MTP_BLOCK_SIZE` | 未設定 | 草稿區塊；未設定時 MTP 為 6，DFlash 為訓練區塊 |
| `YUNSHU_SPEC_TREE` | `auto` | `off`、`tree` 或 `auto` 草稿樹驗證器 |
| `YUNSHU_SPEC_COPY_ROWS` | `32` | 提示複製回合的驗證列數；`0` 停用 |
| `YUNSHU_DRAFT_BITS` | `8` | DFlash drafter 權重位元數（`8`、`4`，或 `0` 保留原始 bf16） |
| `YUNSHU_NGRAM_DEFAULT` | 關閉 | 文字模型：對 greedy 請求使用 n-gram 推測 |
| `YUNSHU_SPEC_PROPOSER` | `ngram` | 文字模型的 `ngram` 或 `suffix` |
| `YUNSHU_GEMMA4_ASSISTANT` | 未設定 | Gemma 4 文字模型的 assistant drafter 目錄 |
| `YUNSHU_SPEC_UNVERIFIED`、`YUNSHU_DRAFT_MODEL` | 關閉、未設定 | 穩定的使用者選項，非無損：greedy 文字請求使用外部 `mlx-lm` draft 模型；見[可能改變輸出的選項](/docs/guides/options) |

## 限制

- 無損保證不涵蓋搭配外部 draft 模型的 `YUNSHU_SPEC_UNVERIFIED`：其輸出可能與一般解碼不同。見[可能改變輸出的選項](/docs/guides/options)。
- 封裝層（Qwen3.5 系列、Flash-Next）起草；其他 VLM 系列使用 generic 層，直接解碼不起草。
- 不在 driver 可逐 window row 套用的集合內的 processor、XTC 取樣與非 invariant guide 的 row，每輪只解碼一個 token，不起草。
- Apple Paravirtual Metal 主機使用 generic 層，沒有推測。
- VLM 會拒絕 LoRA adapter 與自訂 logits processor，而不適合起草（not draft-safe）的 processor 會讓該 row 不起草。

## 如何驗證

計數器可由 `GET /v1/yunshu/spec-decode`、Prometheus 的 `yunshu_spec_decode_*` 指標取得，每個請求的資料在 `x_yunshu.speculative`。啟動日誌會印出所選路徑（「Speculative decoding: ...」）。一致性由 `yv` 工具檢查（見[驗證](/docs/developers/verification)）；相關單元測試有 `tests/unit/test_spec_off_invariant.py`、`tests/unit/test_spec_select.py`、`tests/unit/test_invariant_wide_decode.py`、`tests/unit/test_dflash_draft.py` 與 `tests/unit/test_dflash_copy.py`。實測的解碼數字見[基準測試](/docs/guides/benchmarks)。


---

<!-- internals/tool-call-parsing -->
---
title: 工具呼叫解析
description: Yunshu 如何從聊天模板偵測模型的工具呼叫傳輸格式、從完整與串流輸出中解析呼叫、為參數指定型別，並決定 finish_reason。
---

模型會以自己的傳輸格式把工具呼叫寫成文字。Yunshu 把這些文字讀回結構化的呼叫，讓 OpenAI、Anthropic 與 Ollama 風格的用戶端都看到一般的工具呼叫欄位。本頁說明各個讀取器、串流解析器與結果判定規則。若要在生成過程中約束呼叫，請見[約束解碼](/docs/internals/constrained-decoding)。

## 它做什麼

`yunshu_engine/tool_format.py` 是登錄表。一個 `ToolFormat` 包含起始標記、結束標記（空值表示「到行尾」，如 Mistral）以及解析兩者之間文字的函式。`whole` 格式沒有起始標記：整則訊息就是呼叫（Llama 3 JSON）。

- **偵測。** `native_format` 讀取模型的聊天模板，回傳模板所教的格式，或 `None`。它先檢查 Llama 標頭模板，再檢查標記字串（`_OWN_TEMPLATE_MARKERS`），接著是 Hermes/GLM 的 `<tool_call>` 形狀，最後退回使用 `mlx-vlm` 與 `mlx-lm` 的上游登錄表（`_infer_tool_parser`）。
- **嘗試順序。** `formats_for_tokenizer` 依序回傳原生格式、`yunshu_json`（Yunshu 注入的工具提示詞所要求的 `<tool_call>{"name", "arguments"}</tool_call>` 形式），然後是 `json_message`（整則訊息只是一個 JSON 呼叫物件）。Harmony 還會嘗試後綴形式。
- **解析完成的輸出。** `parse_tool_output` 依輸出順序回傳呼叫，參數依請求的工具 schema 指定型別，並回傳移除所有已解析呼叫區段後的文字。
- **串流。** `ToolCallStreamer`（`tool_call_streamer.py`）在文字、呼叫內部與整則訊息這幾種狀態之間切換。

## 格式與模型家族

偵測依據是聊天模板，而不是模型名稱清單；下表列出格式與其服務的家族。

| 格式名稱 | 傳輸形狀 | 家族 |
|---|---|---|
| Qwen XML（上游讀取器加上寬容的後備） | `<tool_call><function=f><parameter=p>v</parameter></function></tool_call>` | Qwen3.x 與 Qwen3-Coder 風格模板 |
| `hermes` / `yunshu_json` | `<tool_call>{"name": ..., "arguments": ...}</tool_call>` | Hermes 風格 JSON 模板；模板沒有工具格式的模型（注入提示詞） |
| `glm47` | `<tool_call>` 搭配 `<arg_key>` / `<arg_value>` 或換行 JSON | GLM |
| `mistral` | `[TOOL_CALLS]` 後接 JSON，或 `[ARGS]` | Mistral |
| `kimi_k2` | `<\|tool_calls_section_begin\|>` ... `<\|tool_calls_section_end\|>` | Kimi K2 |
| `harmony` / `harmony_suffix` | 以 `<\|call\|>` 結尾的 Harmony 訊息，或 `to=` / `<\|channel\|>` 後綴 | 使用 Harmony 模板的模型 |
| `deepseek` | `<｜tool▁calls▁begin｜>` 區塊 | DeepSeek V3、R1、V3.1 |
| `deepseek_v32` | `<｜DSML｜function_calls>` | DeepSeek V3.2 |
| `deepseek_v4` | `<｜DSML｜tool_calls>` | DeepSeek V4 |
| `llama3_json` | 整則訊息是一個 JSON 呼叫，前面可選擇性加上 `<\|python_tag\|>` | Llama 3.x JSON 模板 |
| `llama3_pythonic` / `pythonic` | 字面的 Python 呼叫，例如 `[f(a=1)]`，可單獨出現或夾在 `<\|tool_call_start\|>` 與 `<\|tool_call_end\|>` 之間 | Llama Python 清單模板；有標籤的 pythonic 模板 |
| `json_message` | 整則訊息只是一個 JSON 呼叫物件 | 沒有標記格式的模型，例如 Qwen3-Omni |

未列於此的格式來自 `mlx-vlm` 與 `mlx-lm` 的上游解析器登錄表。沒有本機可用檢查點的家族以測試資料（fixture）測試，不宣稱已通過真實模型驗證。

## 為什麼這樣設計

格式是模型的屬性，所以像上游一樣從模板讀取，Yunshu 只補上上游缺少的讀取器。這些讀取器是獨立的實作（`tool_family_parsers.py`），且絕不執行模型輸出：Python 呼叫讀取器只接受 JSON 風格字面值的關鍵字引數，拒絕位置引數、展開與任何非字面值的名稱。測試資料的形狀參考 vLLM 的解析器測試，所審閱的上游版本記錄在 `vendor.json`。

## 串流解析與呼叫 ID

下圖顯示串流狀態。

```mermaid
stateDiagram-v2
    [*] --> TEXT
    TEXT --> TOOL_CALL: "看到起始標記"
    TEXT --> WHOLE: "訊息可能是 JSON 呼叫"
    TOOL_CALL --> TEXT: "結束標記，呼叫已解析或當作文字輸出"
    WHOLE --> TEXT: "不是呼叫"
    WHOLE --> [*]: "整則訊息已解析"
    TEXT --> [*]: "串流結束"
```

- 呼叫之外的文字，只要不可能是標記的開頭就立即串流。從起始標記起，文字會被保留到結束標記，然後解析呼叫。
- 每個呼叫以一個起始事件（id 與名稱）加上其完整參數送出。參數會先緩衝到取得完整呼叫，再接在名稱之後送出。每個呼叫都有自己的 ID。
- 沒有任何格式能讀取的區段會當作文字輸出。工具標記絕不會進入內容串流。
- 請求的約束在來源處就生效：指名的 `tool_choice` 會丟棄對其他函式的呼叫，`parallel_tool_calls=false` 只保留第一個呼叫，工具名稱則依請求過濾。
- 參數永遠是 JSON 物件字串。`tool_arguments.py` 依請求的 JSON schema 為文字型參數指定型別（Qwen 的 `<parameter=days>3` 會以 `"3"` 送達）：整數、數字、布林、陣列、物件與 null 在能乾淨轉換時就轉換；字串與未知型別維持不變。
- 對 GLM，`tool_thinking.py` 只在生成結束於觀察 EOS token 時，才會從推理內容中找回結尾的呼叫。長度上限、取消、使用者停止、格式錯誤的呼叫與被引用的範例，一律仍視為推理內容。

## finish_reason 與結果如何判定

- 若至少有一個呼叫通過解析以及 `tool_choice` / 平行呼叫的過濾，OpenAI chat 路由會回報 `finish_reason` 為 `tool_calls`（`chat.py`：`"tool_calls" if tool_calls else finish`）。對串流而言，只要有任何呼叫送出，就依每個 choice 決定。Anthropic 路由則把同樣的條件對應為 `stop_reason` 的 `tool_use`（`_map_stop_reason`）。
- 否則回報引擎自己的原因（`stop`、`length` 等），而沒有產生呼叫的標記區塊會當作文字輸出，而不是被丟棄。
- 每次解析都會在請求上記錄計數而非文字：`tool_calls_parsed` 與 `tool_markup_failed`（`record_tool_outcome`）。它們會寫入日誌，並透過 `x_yunshu` 中已完成請求的紀錄公開，所以被丟棄的呼叫看得見，不會悄悄消失。

## 保證

- 對請求未宣告之名稱的呼叫會被過濾掉。工具標記不會洩漏到內容中。
- Python 風格的呼叫當作資料解析，絕不執行。
- 強制的 `tool_choice` 使用原生 llguidance 文法。原生外層包裝可能跨越數個 tokenizer token；不支援的文法與 tokenizer 組合會保留無約束的後備，且解析出的呼叫並不能證明符合嚴格 schema。

## 設定

| 設定 | 預設 | 作用 |
|---|---|---|

解析本身沒有設定；它遵循聊天模板。

## 限制

- 沒有可辨識工具格式的模板會退回使用 `yunshu_json` 與 `json_message`，這取決於模型是否遵循注入的提示詞。
- Python 字面值引數僅限 JSON 風格的字面值。
- 沒有本機檢查點的家族，其格式只有測試資料的涵蓋。

## 如何驗證

```bash
uv run pytest tests/unit/test_tool_format.py tests/unit/test_tool_family_parsers.py \
  tests/unit/test_tool_streamer_tool_choice.py tests/unit/test_tool_call_grammar.py -q
```

選用的能力階段會執行四項真實 HTTP 檢查（強制、串流、延遲輸出與延遲 auto 工具）：`scripts/dev/yv ab --suite preflight,toolparse --model /path/to/small-model`。請見[驗證](/docs/developers/verification)。


## Generated OpenAPI

```json
{
  "openapi": "3.1.0",
  "info": {
    "title": "Yunshu",
    "description": "Local LLM / VLM inference engine for Apple Silicon",
    "version": "0.1.8.dev4"
  },
  "paths": {
    "/v1/chat/completions": {
      "get": {
        "tags": [
          "chat"
        ],
        "summary": "List Chat Completions",
        "operationId": "list_chat_completions_v1_chat_completions_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response List Chat Completions V1 Chat Completions Get"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "chat"
        ],
        "summary": "Create Chat Completion",
        "operationId": "create_chat_completion_v1_chat_completions_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ChatCompletionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/chat/completions/{completion_id}": {
      "get": {
        "tags": [
          "chat"
        ],
        "summary": "Get Chat Completion",
        "operationId": "get_chat_completion_v1_chat_completions__completion_id__get",
        "parameters": [
          {
            "name": "completion_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Completion Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Get Chat Completion V1 Chat Completions  Completion Id  Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "chat"
        ],
        "summary": "Update Chat Completion",
        "operationId": "update_chat_completion_v1_chat_completions__completion_id__post",
        "parameters": [
          {
            "name": "completion_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Completion Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Update Chat Completion V1 Chat Completions  Completion Id  Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "chat"
        ],
        "summary": "Delete Chat Completion",
        "operationId": "delete_chat_completion_v1_chat_completions__completion_id__delete",
        "parameters": [
          {
            "name": "completion_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Completion Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Delete Chat Completion V1 Chat Completions  Completion Id  Delete"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/chat/completions/{completion_id}/messages": {
      "get": {
        "tags": [
          "chat"
        ],
        "summary": "Get Chat Completion Messages",
        "operationId": "get_chat_completion_messages_v1_chat_completions__completion_id__messages_get",
        "parameters": [
          {
            "name": "completion_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Completion Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Get Chat Completion Messages V1 Chat Completions  Completion Id  Messages Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/realtime/client_secrets": {
      "post": {
        "tags": [
          "realtime"
        ],
        "summary": "Create Client Secret",
        "operationId": "create_client_secret_v1_realtime_client_secrets_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Create Client Secret V1 Realtime Client Secrets Post"
                }
              }
            }
          }
        }
      }
    },
    "/v1/realtime/sessions": {
      "post": {
        "tags": [
          "realtime"
        ],
        "summary": "Create Session",
        "operationId": "create_session_v1_realtime_sessions_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Create Session V1 Realtime Sessions Post"
                }
              }
            }
          }
        }
      }
    },
    "/v1/realtime/transcription_sessions": {
      "post": {
        "tags": [
          "realtime"
        ],
        "summary": "Create Transcription Session",
        "operationId": "create_transcription_session_v1_realtime_transcription_sessions_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Create Transcription Session V1 Realtime Transcription Sessions Post"
                }
              }
            }
          }
        }
      }
    },
    "/v1/audio/voice_consents": {
      "post": {
        "tags": [
          "audio"
        ],
        "summary": "Create Consent",
        "operationId": "create_consent_v1_audio_voice_consents_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/audio/voices": {
      "get": {
        "tags": [
          "audio"
        ],
        "summary": "List Voices",
        "description": "List available TTS voices.",
        "operationId": "list_voices_v1_audio_voices_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response List Voices V1 Audio Voices Get"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "audio"
        ],
        "summary": "Create Voice",
        "operationId": "create_voice_v1_audio_voices_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/completions": {
      "post": {
        "tags": [
          "completions"
        ],
        "summary": "Create Completion",
        "description": "OpenAI-compatible text completion endpoint.",
        "operationId": "create_completion_v1_completions_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CompletionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/responses/compact": {
      "post": {
        "tags": [
          "responses"
        ],
        "summary": "Compact Response",
        "operationId": "compact_response_v1_responses_compact_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/responses": {
      "post": {
        "tags": [
          "responses"
        ],
        "summary": "Create Response",
        "description": "OpenAI Responses API endpoint.",
        "operationId": "create_response_v1_responses_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ResponsesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/responses/{response_id}": {
      "get": {
        "tags": [
          "responses"
        ],
        "summary": "Get Response",
        "description": "Retrieve a stored response previously created with `store: true`.\n\nOpenAI-compatible: returns 404 if the response is unknown or was\ncreated without storage enabled.",
        "operationId": "get_response_v1_responses__response_id__get",
        "parameters": [
          {
            "name": "response_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Response Id"
            }
          },
          {
            "name": "stream",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean",
              "default": false,
              "title": "Stream"
            }
          },
          {
            "name": "starting_after",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "integer"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Starting After"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "responses"
        ],
        "summary": "Delete Response",
        "description": "Delete a stored response (OpenAI-compatible DELETE /v1/responses/{id}).\n\nthe endpoint was missing entirely — a stored response/conversation could\nnever be explicitly deleted (only LRU-evicted after the store cap), so clients got 405\nand a stored conversation lingered until eviction (a minor privacy gap). Returns the\nOpenAI delete envelope. Ownership-gated exactly like GET (delete by a different key is denied as not-found so the id space stays non-enumerable, the IDOR class).",
        "operationId": "delete_response_v1_responses__response_id__delete",
        "parameters": [
          {
            "name": "response_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Response Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/responses/{response_id}/input_items": {
      "get": {
        "tags": [
          "responses"
        ],
        "summary": "List Response Input Items",
        "description": "The input items of a stored response (OpenAI ``GET /v1/responses/{id}/input_items``).\n\nThis hop's own input only (``instructions`` and system / developer messages are not listed,\nlike the hosted API); ``previous_response_id`` history belongs to the earlier responses.\nCursor pagination with ``limit`` (1-100), ``order`` (``desc`` default) and ``after`` /\n``before`` item ids.",
        "operationId": "list_response_input_items_v1_responses__response_id__input_items_get",
        "parameters": [
          {
            "name": "response_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Response Id"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "default": 20,
              "title": "Limit"
            }
          },
          {
            "name": "order",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "default": "desc",
              "title": "Order"
            }
          },
          {
            "name": "after",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "title": "After"
            }
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Before"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/responses/{response_id}/cancel": {
      "post": {
        "tags": [
          "responses"
        ],
        "summary": "Cancel Response",
        "description": "Cancel an in-progress response generation.\n\nSignals the request tracker's cancel_event for the given response_id.\nThe active generator polls the event between steps and exits with a\ncancelled finish_reason.  Idempotent: returns the stored payload (if\nany) on subsequent calls.",
        "operationId": "cancel_response_v1_responses__response_id__cancel_post",
        "parameters": [
          {
            "name": "response_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Response Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/responses/input_tokens": {
      "post": {
        "tags": [
          "responses"
        ],
        "summary": "Count Input Tokens",
        "description": "Count the input tokens a `/v1/responses` request would use (OpenAI input_tokens API).\n\nBuilds the prompt the way ``create_response`` does (instructions, input items, conversation,\ncompaction items, ``previous_response_id`` chain, function tools rendered natively when the\ntemplate does it, injected otherwise) and counts the rendered template, so the number equals\nthe ``usage.input_tokens`` of the same request (a real-server check compares them). Not\ncounted: server-side tools (web_search / mcp definitions), the assistant prefill of a forced\ntool_choice on an engine without native tools, and the compaction a ``context_management``\nthreshold would trigger.",
        "operationId": "count_input_tokens_v1_responses_input_tokens_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/conversations": {
      "post": {
        "tags": [
          "conversations"
        ],
        "summary": "Create Conversation",
        "operationId": "create_conversation_v1_conversations_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/conversations/{conversation_id}": {
      "get": {
        "tags": [
          "conversations"
        ],
        "summary": "Get Conversation",
        "operationId": "get_conversation_v1_conversations__conversation_id__get",
        "parameters": [
          {
            "name": "conversation_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Conversation Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "conversations"
        ],
        "summary": "Update Conversation",
        "operationId": "update_conversation_v1_conversations__conversation_id__post",
        "parameters": [
          {
            "name": "conversation_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Conversation Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "conversations"
        ],
        "summary": "Delete Conversation",
        "operationId": "delete_conversation_v1_conversations__conversation_id__delete",
        "parameters": [
          {
            "name": "conversation_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Conversation Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/conversations/{conversation_id}/items": {
      "post": {
        "tags": [
          "conversations"
        ],
        "summary": "Create Items",
        "operationId": "create_items_v1_conversations__conversation_id__items_post",
        "parameters": [
          {
            "name": "conversation_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Conversation Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "get": {
        "tags": [
          "conversations"
        ],
        "summary": "List Items",
        "operationId": "list_items_v1_conversations__conversation_id__items_get",
        "parameters": [
          {
            "name": "conversation_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Conversation Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/conversations/{conversation_id}/items/{item_id}": {
      "get": {
        "tags": [
          "conversations"
        ],
        "summary": "Get Item",
        "operationId": "get_item_v1_conversations__conversation_id__items__item_id__get",
        "parameters": [
          {
            "name": "conversation_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Conversation Id"
            }
          },
          {
            "name": "item_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Item Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "title": "Response Get Item V1 Conversations  Conversation Id  Items  Item Id  Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "conversations"
        ],
        "summary": "Delete Item",
        "operationId": "delete_item_v1_conversations__conversation_id__items__item_id__delete",
        "parameters": [
          {
            "name": "conversation_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Conversation Id"
            }
          },
          {
            "name": "item_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Item Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/evals": {
      "get": {
        "tags": [
          "evals"
        ],
        "summary": "List Evals",
        "operationId": "list_evals_v1_evals_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "evals"
        ],
        "summary": "Create Eval",
        "operationId": "create_eval_v1_evals_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/evals/{eval_id}": {
      "get": {
        "tags": [
          "evals"
        ],
        "summary": "Get Eval",
        "operationId": "get_eval_v1_evals__eval_id__get",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "evals"
        ],
        "summary": "Update Eval",
        "operationId": "update_eval_v1_evals__eval_id__post",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "evals"
        ],
        "summary": "Delete Eval",
        "operationId": "delete_eval_v1_evals__eval_id__delete",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/evals/{eval_id}/runs": {
      "post": {
        "tags": [
          "evals"
        ],
        "summary": "Create Run",
        "operationId": "create_run_v1_evals__eval_id__runs_post",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "get": {
        "tags": [
          "evals"
        ],
        "summary": "List Runs",
        "operationId": "list_runs_v1_evals__eval_id__runs_get",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/evals/{eval_id}/runs/{run_id}": {
      "get": {
        "tags": [
          "evals"
        ],
        "summary": "Get Run",
        "operationId": "get_run_v1_evals__eval_id__runs__run_id__get",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          },
          {
            "name": "run_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Run Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "evals"
        ],
        "summary": "Delete Run",
        "operationId": "delete_run_v1_evals__eval_id__runs__run_id__delete",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          },
          {
            "name": "run_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Run Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/evals/{eval_id}/runs/{run_id}/cancel": {
      "post": {
        "tags": [
          "evals"
        ],
        "summary": "Cancel Run",
        "operationId": "cancel_run_v1_evals__eval_id__runs__run_id__cancel_post",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          },
          {
            "name": "run_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Run Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/evals/{eval_id}/runs/{run_id}/output_items": {
      "get": {
        "tags": [
          "evals"
        ],
        "summary": "List Output Items",
        "operationId": "list_output_items_v1_evals__eval_id__runs__run_id__output_items_get",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          },
          {
            "name": "run_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Run Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}": {
      "get": {
        "tags": [
          "evals"
        ],
        "summary": "Get Output Item",
        "operationId": "get_output_item_v1_evals__eval_id__runs__run_id__output_items__output_item_id__get",
        "parameters": [
          {
            "name": "eval_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Eval Id"
            }
          },
          {
            "name": "run_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Run Id"
            }
          },
          {
            "name": "output_item_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Output Item Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/embeddings": {
      "post": {
        "tags": [
          "embeddings"
        ],
        "summary": "Create Embedding",
        "description": "Generate embeddings for the given input text(s).",
        "operationId": "create_embedding_v1_embeddings_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EmbeddingRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/models": {
      "get": {
        "tags": [
          "models"
        ],
        "summary": "List Models",
        "description": "List available models (OpenAI + Anthropic compatible, with the full model card).\n\nEvery item carries the OpenAI fields, the Anthropic ``ModelInfo`` fields, the OpenRouter /\nvLLM / LM Studio metadata fields and the complete card under ``yunshu`` (see\n``yunshu_engine/model_card.py``). Loaded state, size and engine stats are only included for\nauthenticated requests.",
        "operationId": "list_models_v1_models_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response List Models V1 Models Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/models/{model_id}": {
      "get": {
        "tags": [
          "models"
        ],
        "summary": "Get Model",
        "description": "Get one model with its full card (404 when unknown).",
        "operationId": "get_model_v1_models__model_id__get",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Get Model V1 Models  Model Id  Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/models/load": {
      "post": {
        "tags": [
          "models"
        ],
        "summary": "Load Model",
        "description": "Load a model; fixed text/VLM checkpoints require model-manager mode.",
        "operationId": "load_model_v1_models_load_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LoadModelRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Load Model V1 Models Load Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/models/unload/{model_id}": {
      "post": {
        "tags": [
          "models"
        ],
        "summary": "Unload Model",
        "description": "Unload a model and release memory.",
        "operationId": "unload_model_v1_models_unload__model_id__post",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Unload Model V1 Models Unload  Model Id  Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/files": {
      "get": {
        "tags": [
          "files"
        ],
        "summary": "List Files",
        "operationId": "list_files_v1_files_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "files"
        ],
        "summary": "Create File",
        "operationId": "create_file_v1_files_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/files/{file_id}": {
      "get": {
        "tags": [
          "files"
        ],
        "summary": "Retrieve File",
        "operationId": "retrieve_file_v1_files__file_id__get",
        "parameters": [
          {
            "name": "file_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "File Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "files"
        ],
        "summary": "Delete File",
        "operationId": "delete_file_v1_files__file_id__delete",
        "parameters": [
          {
            "name": "file_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "File Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/files/{file_id}/content": {
      "get": {
        "tags": [
          "files"
        ],
        "summary": "File Content",
        "operationId": "file_content_v1_files__file_id__content_get",
        "parameters": [
          {
            "name": "file_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "File Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/containers": {
      "get": {
        "tags": [
          "containers"
        ],
        "summary": "List Containers",
        "operationId": "list_containers_v1_containers_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "containers"
        ],
        "summary": "Create Container",
        "operationId": "create_container_v1_containers_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/containers/{container_id}": {
      "get": {
        "tags": [
          "containers"
        ],
        "summary": "Retrieve Container",
        "operationId": "retrieve_container_v1_containers__container_id__get",
        "parameters": [
          {
            "name": "container_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Container Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "containers"
        ],
        "summary": "Delete Container",
        "operationId": "delete_container_v1_containers__container_id__delete",
        "parameters": [
          {
            "name": "container_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Container Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/containers/{container_id}/files": {
      "post": {
        "tags": [
          "containers"
        ],
        "summary": "Create Container File",
        "operationId": "create_container_file_v1_containers__container_id__files_post",
        "parameters": [
          {
            "name": "container_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Container Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "get": {
        "tags": [
          "containers"
        ],
        "summary": "List Container Files",
        "operationId": "list_container_files_v1_containers__container_id__files_get",
        "parameters": [
          {
            "name": "container_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Container Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/containers/{container_id}/files/{file_id}": {
      "get": {
        "tags": [
          "containers"
        ],
        "summary": "Retrieve Container File",
        "operationId": "retrieve_container_file_v1_containers__container_id__files__file_id__get",
        "parameters": [
          {
            "name": "container_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Container Id"
            }
          },
          {
            "name": "file_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "File Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "containers"
        ],
        "summary": "Delete Container File",
        "operationId": "delete_container_file_v1_containers__container_id__files__file_id__delete",
        "parameters": [
          {
            "name": "container_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Container Id"
            }
          },
          {
            "name": "file_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "File Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/containers/{container_id}/files/{file_id}/content": {
      "get": {
        "tags": [
          "containers"
        ],
        "summary": "Container File Content",
        "operationId": "container_file_content_v1_containers__container_id__files__file_id__content_get",
        "parameters": [
          {
            "name": "container_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Container Id"
            }
          },
          {
            "name": "file_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "File Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/batches": {
      "get": {
        "tags": [
          "batches"
        ],
        "summary": "List Batches",
        "operationId": "list_batches_v1_batches_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "batches"
        ],
        "summary": "Create Batch",
        "operationId": "create_batch_v1_batches_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/batches/{batch_id}": {
      "get": {
        "tags": [
          "batches"
        ],
        "summary": "Retrieve Batch",
        "operationId": "retrieve_batch_v1_batches__batch_id__get",
        "parameters": [
          {
            "name": "batch_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Batch Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/batches/{batch_id}/cancel": {
      "post": {
        "tags": [
          "batches"
        ],
        "summary": "Cancel Batch",
        "operationId": "cancel_batch_v1_batches__batch_id__cancel_post",
        "parameters": [
          {
            "name": "batch_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Batch Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/messages/batches": {
      "get": {
        "tags": [
          "batches"
        ],
        "summary": "List Message Batches",
        "operationId": "list_message_batches_v1_messages_batches_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "batches"
        ],
        "summary": "Create Message Batch",
        "operationId": "create_message_batch_v1_messages_batches_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/messages/batches/{batch_id}": {
      "get": {
        "tags": [
          "batches"
        ],
        "summary": "Retrieve Message Batch",
        "operationId": "retrieve_message_batch_v1_messages_batches__batch_id__get",
        "parameters": [
          {
            "name": "batch_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Batch Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "batches"
        ],
        "summary": "Delete Message Batch",
        "operationId": "delete_message_batch_v1_messages_batches__batch_id__delete",
        "parameters": [
          {
            "name": "batch_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Batch Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/messages/batches/{batch_id}/cancel": {
      "post": {
        "tags": [
          "batches"
        ],
        "summary": "Cancel Message Batch",
        "operationId": "cancel_message_batch_v1_messages_batches__batch_id__cancel_post",
        "parameters": [
          {
            "name": "batch_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Batch Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/messages/batches/{batch_id}/results": {
      "get": {
        "tags": [
          "batches"
        ],
        "summary": "Message Batch Results",
        "operationId": "message_batch_results_v1_messages_batches__batch_id__results_get",
        "parameters": [
          {
            "name": "batch_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Batch Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/messages": {
      "post": {
        "tags": [
          "anthropic"
        ],
        "summary": "Create Message",
        "description": "Run the Messages endpoint; unlink staged images unless a stream owns them.",
        "operationId": "create_message_v1_messages_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnthropicMessagesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/messages/count_tokens": {
      "post": {
        "tags": [
          "anthropic"
        ],
        "summary": "Count Tokens",
        "description": "Token counting endpoint (Anthropic compatible).\n\nReturns Anthropic-format errors on failure:\n  {\"type\": \"error\", \"error\": {\"type\": \"...\", \"message\": \"...\"}}",
        "operationId": "count_tokens_v1_messages_count_tokens_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnthropicCountTokensRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/audio/speech": {
      "post": {
        "tags": [
          "audio"
        ],
        "summary": "Create Speech",
        "description": "Generate speech from text (OpenAI /v1/audio/speech compatible).\n\nAccepts JSON body (OpenAI default) or multipart/form-data (OpenAI parity\nwith /audio/transcriptions). Form fields mirror the JSON schema; \"format\"\nis accepted as an alias for \"response_format\".",
        "operationId": "create_speech_v1_audio_speech_post",
        "responses": {
          "200": {
            "description": "Successful Response"
          }
        }
      }
    },
    "/v1/audio/speech/stream": {
      "post": {
        "tags": [
          "audio"
        ],
        "summary": "Stream Speech",
        "description": "Stream TTS synthesis as SSE events with audio chunks.\n\nStreamed chunks are always raw PCM16 (the `X-Audio-Format: pcm-s16le` header\nreports it) — `response_format` (mp3/opus/…) applies only to the non-streaming\n/audio/speech route, since per-chunk transcoding isn't supported. Clients that\nneed a compressed container should use the non-streaming endpoint.",
        "operationId": "stream_speech_v1_audio_speech_stream_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TTSRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/audio/transcriptions": {
      "post": {
        "tags": [
          "audio"
        ],
        "summary": "Create Transcription",
        "description": "Transcribe audio file (OpenAI /v1/audio/transcriptions compatible).",
        "operationId": "create_transcription_v1_audio_transcriptions_post",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/Body_create_transcription_v1_audio_transcriptions_post"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Create Transcription V1 Audio Transcriptions Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/audio/translations": {
      "post": {
        "tags": [
          "audio"
        ],
        "summary": "Create Translation",
        "description": "Translate audio into English (OpenAI /v1/audio/translations compatible).\n\nOpenAI semantics: decode non-English speech and emit the text in English. This is\na Whisper-family capability (task=\"translate\"); source-language-only backends like\nQwen3-ASR can't do it, so for those we return an honest 501 rather than\nmis-\"translating\" (which would just transcribe in the source language).",
        "operationId": "create_translation_v1_audio_translations_post",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/Body_create_translation_v1_audio_translations_post"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/images/generations": {
      "post": {
        "tags": [
          "images"
        ],
        "summary": "Create Image",
        "description": "Generate images from text prompt (OpenAI /v1/images/generations compatible).",
        "operationId": "create_image_v1_images_generations_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ImageGenerateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/images/generations/stream": {
      "post": {
        "tags": [
          "images"
        ],
        "summary": "Stream Image Generation",
        "description": "Stream image generation progress as SSE events.",
        "operationId": "stream_image_generation_v1_images_generations_stream_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ImageGenerateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/images/variations": {
      "post": {
        "tags": [
          "images"
        ],
        "summary": "Create Image Variation",
        "description": "Generate variations of an input image (OpenAI /v1/images/variations compatible).\n\nUses the input image as a conditioning signal for the diffusion model.\nThe image is decoded and used as a starting point for the generation. Multipart (the OpenAI\nSDK) or JSON with a base64 image.",
        "operationId": "create_image_variation_v1_images_variations_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/images/edits": {
      "post": {
        "tags": [
          "images"
        ],
        "summary": "Create Image Edit",
        "description": "Edit an image based on a text prompt (OpenAI /v1/images/edits compatible).\n\nCombines the input image with a text prompt to generate an edited version. Multipart (the\nOpenAI SDK) or JSON with a base64 image.",
        "operationId": "create_image_edit_v1_images_edits_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/tokenize": {
      "post": {
        "tags": [
          "tokenize"
        ],
        "summary": "Tokenize",
        "description": "Tokenize a prompt or a chat conversation (vLLM `/tokenize` schema).",
        "operationId": "tokenize_v1_tokenize_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TokenizeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/detokenize": {
      "post": {
        "tags": [
          "tokenize"
        ],
        "summary": "Detokenize",
        "description": "Convert token IDs back to text (vLLM `/detokenize` schema).",
        "operationId": "detokenize_v1_detokenize_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DetokenizeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/apply-template": {
      "post": {
        "tags": [
          "tokenize"
        ],
        "summary": "Apply Template",
        "operationId": "apply_template_v1_apply_template_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApplyTemplateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/props": {
      "get": {
        "tags": [
          "tokenize"
        ],
        "summary": "Props",
        "operationId": "props_v1_props_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tokenize": {
      "post": {
        "tags": [
          "tokenize"
        ],
        "summary": "Tokenize",
        "description": "Tokenize a prompt or a chat conversation (vLLM `/tokenize` schema).",
        "operationId": "tokenize_tokenize_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TokenizeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/detokenize": {
      "post": {
        "tags": [
          "tokenize"
        ],
        "summary": "Detokenize",
        "description": "Convert token IDs back to text (vLLM `/detokenize` schema).",
        "operationId": "detokenize_detokenize_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DetokenizeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/apply-template": {
      "post": {
        "tags": [
          "tokenize"
        ],
        "summary": "Apply Template",
        "operationId": "apply_template_apply_template_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApplyTemplateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/props": {
      "get": {
        "tags": [
          "tokenize"
        ],
        "summary": "Props",
        "operationId": "props_props_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/mcp": {
      "post": {
        "tags": [
          "mcp"
        ],
        "summary": "Mcp Endpoint",
        "description": "MCP JSON-RPC endpoint.\n\nPer JSON-RPC 2.0 spec, notifications (requests without an 'id') MUST NOT\nreceive a response. We acknowledge them silently.",
        "operationId": "mcp_endpoint_v1_mcp_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/mcp/tools": {
      "get": {
        "tags": [
          "mcp"
        ],
        "summary": "Mcp Tools Discovery",
        "description": "REST endpoint for MCP tool discovery.",
        "operationId": "mcp_tools_discovery_v1_mcp_tools_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/mcp/sse": {
      "get": {
        "tags": [
          "mcp"
        ],
        "summary": "Mcp Sse Endpoint",
        "description": "MCP SSE endpoint for streaming connections.",
        "operationId": "mcp_sse_endpoint_v1_mcp_sse_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/mcp/client/status": {
      "get": {
        "tags": [
          "mcp"
        ],
        "summary": "Mcp Client Status",
        "description": "Get MCP client connection status and discovered tools.",
        "operationId": "mcp_client_status_v1_mcp_client_status_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Mcp Client Status V1 Mcp Client Status Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/mcp/client/tools": {
      "get": {
        "tags": [
          "mcp"
        ],
        "summary": "Mcp Client Tools",
        "description": "List tools discovered from connected MCP servers.\n\nReturns tools in both MCP format and OpenAI function format.",
        "operationId": "mcp_client_tools_v1_mcp_client_tools_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Mcp Client Tools V1 Mcp Client Tools Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/pooling": {
      "post": {
        "tags": [
          "scoring"
        ],
        "summary": "Create Pooling",
        "operationId": "create_pooling_v1_pooling_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PoolingRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/score": {
      "post": {
        "tags": [
          "scoring"
        ],
        "summary": "Create Score",
        "operationId": "create_score_v1_score_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ScoreRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/rerank": {
      "post": {
        "tags": [
          "scoring"
        ],
        "summary": "Create Rerank",
        "operationId": "create_rerank_v1_rerank_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RerankRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/classify": {
      "post": {
        "tags": [
          "scoring"
        ],
        "summary": "Classify Input",
        "operationId": "classify_input_v1_classify_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ClassifyRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/decisions": {
      "post": {
        "tags": [
          "decisions"
        ],
        "summary": "Create Decision",
        "operationId": "create_decision_v1_decisions_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/systemone": {
      "post": {
        "tags": [
          "decisions"
        ],
        "summary": "Create Systemone",
        "operationId": "create_systemone_v1_systemone_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/search": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Tavily Search",
        "operationId": "tavily_search_tavily_search_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/extract": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Tavily Extract",
        "operationId": "tavily_extract_tavily_extract_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/crawl": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Tavily Crawl",
        "operationId": "tavily_crawl_tavily_crawl_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/map": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Tavily Map",
        "operationId": "tavily_map_tavily_map_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/research": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Tavily Research",
        "operationId": "tavily_research_tavily_research_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/feedback": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Tavily Feedback",
        "operationId": "tavily_feedback_tavily_feedback_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/logs": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Tavily Logs",
        "operationId": "tavily_logs_tavily_logs_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/usage": {
      "get": {
        "tags": [
          "tavily"
        ],
        "summary": "Usage",
        "operationId": "usage_tavily_usage_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/research/{request_id}": {
      "get": {
        "tags": [
          "tavily"
        ],
        "summary": "Research",
        "operationId": "research_tavily_research__request_id__get",
        "parameters": [
          {
            "name": "request_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Request Id"
            }
          },
          {
            "name": "include_usage",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean",
              "default": false,
              "title": "Include Usage"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/tavily/providers": {
      "get": {
        "tags": [
          "tavily"
        ],
        "summary": "Providers",
        "operationId": "providers_tavily_providers_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/tavily/mcp": {
      "post": {
        "tags": [
          "tavily"
        ],
        "summary": "Mcp",
        "description": "Stateless streamable HTTP MCP alternative to upstream's hard-coded stdio base URL.",
        "operationId": "mcp_tavily_mcp_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/cancel": {
      "post": {
        "tags": [
          "cancel"
        ],
        "summary": "Cancel Generation",
        "description": "Cancel an in-progress generation or all active generations.\n\nPass `request_id` to cancel a specific generation.\nPass `cancel_all: true` to cancel all active generations.",
        "operationId": "cancel_generation_v1_cancel_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CancelRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/active-generations": {
      "get": {
        "tags": [
          "cancel"
        ],
        "summary": "List Active Generations",
        "description": "List currently active (in-progress) generations — the caller's own unless\nadmin (otherwise every key's live request_id + model would leak).",
        "operationId": "list_active_generations_v1_active_generations_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/status": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Status",
        "description": "Everything an operator or a client wants to know before sending a big request.",
        "operationId": "status_v1_yunshu_status_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Status V1 Yunshu Status Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/requests/recent": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Recent Requests",
        "description": "Finished requests, newest first (the 512-entry ring), each with ``offsets_ms``: the\nphase timestamps (arrive, admit, first token, last token, done) in ms after arrival.",
        "operationId": "recent_requests_v1_yunshu_requests_recent_get",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "default": 100,
              "title": "Limit"
            }
          },
          {
            "name": "model",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Model"
            }
          },
          {
            "name": "since",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "number"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Since"
            }
          },
          {
            "name": "after_seq",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "integer",
                  "minimum": 0
                },
                {
                  "type": "null"
                }
              ],
              "title": "After Seq"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Recent Requests V1 Yunshu Requests Recent Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/history": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "History",
        "description": "Columnar samples (``t`` epoch seconds plus one array per field), oldest first. ``since``\nkeeps rows newer than that epoch; ``step`` averages them into buckets of that many seconds.",
        "operationId": "history_v1_yunshu_history_get",
        "parameters": [
          {
            "name": "since",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "number"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Since"
            }
          },
          {
            "name": "step",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "number",
                  "minimum": 0
                },
                {
                  "type": "null"
                }
              ],
              "title": "Step"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response History V1 Yunshu History Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/memory": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Memory Ledger",
        "description": "Unified memory by owner (weights, prefix cache, MLX cache, residual), peak, limits and\nOS pressure / swap. Every figure comes from a counter; unknown is null.",
        "operationId": "memory_ledger_v1_yunshu_memory_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Memory Ledger V1 Yunshu Memory Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/config": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Effective Config",
        "description": "Every setting with its effective value, default and source (cli / env / file /\ndefault), as ``yunshu config`` shows them. Secrets are masked (and URL user info).\n\nThis is operator configuration (paths, endpoints, which tools are on), so when\nauth is configured it needs the ``admin`` scope: a managed key with only\n``infer`` gets 403. With no auth configured it stays readable like inference.",
        "operationId": "effective_config_v1_yunshu_config_get",
        "parameters": [
          {
            "name": "include",
            "in": "query",
            "required": false,
            "schema": {
              "enum": [
                "stable",
                "all"
              ],
              "type": "string",
              "default": "stable",
              "title": "Include"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Effective Config V1 Yunshu Config Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "patch": {
        "tags": [
          "yunshu-admin"
        ],
        "summary": "Patch Config",
        "description": "Validate, persist and report when each change takes effect. All or\nnothing: one bad value writes none. Environment / CLI values still win at\nruntime and are reported as ``overridden``.",
        "operationId": "patch_config_v1_yunshu_config_patch",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ConfigPatch"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Patch Config V1 Yunshu Config Patch"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/requests": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "List Requests",
        "operationId": "list_requests_v1_requests_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response List Requests V1 Requests Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/requests/{request_id}": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Get Request",
        "description": "State of one request by its ``X-Request-Id``: queued, prefill (tokens, %, ETA) or decode.",
        "operationId": "get_request_v1_requests__request_id__get",
        "parameters": [
          {
            "name": "request_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Request Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Get Request V1 Requests  Request Id  Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "yunshu"
        ],
        "summary": "Cancel Request",
        "description": "Cancel a generation by the ``X-Request-Id`` the client sent (or the completion id).",
        "operationId": "cancel_request_v1_requests__request_id__delete",
        "parameters": [
          {
            "name": "request_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Request Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Cancel Request V1 Requests  Request Id  Delete"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/warmup": {
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Warmup",
        "description": "Load the model, run one tiny generation (kernel compile, allocator warm-up) and, when\n``prompt`` / ``messages`` is given, leave that prefix in the prompt cache.",
        "operationId": "warmup_v1_yunshu_warmup_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WarmupRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Warmup V1 Yunshu Warmup Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/host": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Host",
        "description": "CPU-only thermal, power, OS memory pressure and swap; cached for 15 seconds.\n\nUnsupported probes return state=unknown with a reason. No root or MLX required.",
        "operationId": "host_v1_yunshu_host_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Host V1 Yunshu Host Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/register": {
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Register Local",
        "description": "Register a local checkpoint or HF snapshot directory without loading or copying weights.",
        "operationId": "register_local_v1_yunshu_models_register_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RegisterLocalRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Register Local V1 Yunshu Models Register Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/register/{model_id}": {
      "delete": {
        "tags": [
          "yunshu"
        ],
        "summary": "Unregister Local",
        "description": "Remove an unloaded registration only; checkpoint files and HF cache are preserved.",
        "operationId": "unregister_local_v1_yunshu_models_register__model_id__delete",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Unregister Local V1 Yunshu Models Register  Model Id  Delete"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/cancel": {
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Cancel Model Operation",
        "description": "Cancel a pending load/download cooperatively; executing work is safely drained before cleanup.",
        "operationId": "cancel_model_operation_v1_yunshu_models_cancel_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CancelModelRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Cancel Model Operation V1 Yunshu Models Cancel Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/requests/history": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Request History",
        "description": "Metadata-only cursor pages over the opt-in, rotated serve log.",
        "operationId": "request_history_v1_yunshu_requests_history_get",
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "default": 50,
              "title": "Limit"
            }
          },
          {
            "name": "before",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Before"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HistoryPage"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/spec-decode": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Speculative Metrics",
        "description": "VLM MTP/DFlash lifetime counters, including accepted/drafted per depth.",
        "operationId": "speculative_metrics_v1_yunshu_spec_decode_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SpecAggregate"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/bundle/manifest": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Support Bundle Manifest",
        "description": "Describe the same local diagnostics JSON produced by the CLI.",
        "operationId": "support_bundle_manifest_v1_yunshu_bundle_manifest_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BundleManifest"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/impact": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Model Impact",
        "description": "Advisory load eviction preview and actual non-forced unload policy.",
        "operationId": "model_impact_v1_yunshu_models_impact_get",
        "parameters": [
          {
            "name": "model",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ModelImpact"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/bundle": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Support Bundle",
        "description": "Download the CLI diagnostics bundle; nothing is uploaded.",
        "operationId": "support_bundle_v1_yunshu_bundle_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DiagnosticsBundle"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/cache": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Cache Entries",
        "description": "APC entries and bounded lifecycle events; no prompt tokens are exposed.",
        "operationId": "cache_entries_v1_yunshu_cache_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CacheView"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/cache/clear": {
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Clear Cache",
        "description": "Clear idle loaded models' resident APC; persistent SSD files remain usable.",
        "operationId": "clear_cache_v1_yunshu_cache_clear_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CacheClear"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/events": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Events",
        "operationId": "events_v1_yunshu_events_get",
        "parameters": [
          {
            "name": "topics",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "maxLength": 200,
              "default": "status",
              "title": "Topics"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/downloads": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "List Downloads",
        "operationId": "list_downloads_v1_yunshu_downloads_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response List Downloads V1 Yunshu Downloads Get"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Start Download",
        "operationId": "start_download_v1_yunshu_downloads_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DownloadRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "202": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Start Download V1 Yunshu Downloads Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/downloads/{job_id}": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Get Download",
        "operationId": "get_download_v1_yunshu_downloads__job_id__get",
        "parameters": [
          {
            "name": "job_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Job Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Get Download V1 Yunshu Downloads  Job Id  Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "yunshu"
        ],
        "summary": "Cancel Download",
        "operationId": "cancel_download_v1_yunshu_downloads__job_id__delete",
        "parameters": [
          {
            "name": "job_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Job Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Cancel Download V1 Yunshu Downloads  Job Id  Delete"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/local": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Local Models",
        "operationId": "local_models_v1_yunshu_models_local_get",
        "parameters": [
          {
            "name": "refresh",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean",
              "default": false,
              "title": "Refresh"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Local Models V1 Yunshu Models Local Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/{model_id}/fit": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Model Fit",
        "operationId": "model_fit_v1_yunshu_models__model_id__fit_get",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Model Fit V1 Yunshu Models  Model Id  Fit Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/{model_id}/reload": {
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Reload Model",
        "description": "Unload and load the same model so ``reload`` settings (``needs_reload`` from\n``PATCH /v1/yunshu/config``) take effect. Refuses while the model has running\nrequests unless ``force``. Multi-model mode only; a single-engine server\nrestarts instead.",
        "operationId": "reload_model_v1_yunshu_models__model_id__reload_post",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "anyOf": [
                  {
                    "$ref": "#/components/schemas/ReloadRequest"
                  },
                  {
                    "type": "null"
                  }
                ],
                "title": "Body"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Reload Model V1 Yunshu Models  Model Id  Reload Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/models/{model_id}/prepare": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Prepare Status",
        "operationId": "prepare_status_v1_yunshu_models__model_id__prepare_get",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Prepare Status V1 Yunshu Models  Model Id  Prepare Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Prepare Start",
        "operationId": "prepare_start_v1_yunshu_models__model_id__prepare_post",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "responses": {
          "202": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Prepare Start V1 Yunshu Models  Model Id  Prepare Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "yunshu"
        ],
        "summary": "Prepare Cancel Or Remove",
        "operationId": "prepare_cancel_or_remove_v1_yunshu_models__model_id__prepare_delete",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Model Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Prepare Cancel Or Remove V1 Yunshu Models  Model Id  Prepare Delete"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/cache/tiers": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Cache Overview",
        "operationId": "cache_overview_v1_yunshu_cache_tiers_get",
        "parameters": [
          {
            "name": "entries",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "maximum": 200,
              "minimum": 0,
              "default": 200,
              "title": "Entries"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Cache Overview V1 Yunshu Cache Tiers Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/cache/tiers/clear": {
      "post": {
        "tags": [
          "yunshu"
        ],
        "summary": "Clear Cache",
        "operationId": "clear_cache_v1_yunshu_cache_tiers_clear_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "anyOf": [
                  {
                    "$ref": "#/components/schemas/ClearRequest"
                  },
                  {
                    "type": "null"
                  }
                ],
                "title": "Body"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Clear Cache V1 Yunshu Cache Tiers Clear Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/logs": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Logs",
        "operationId": "logs_v1_yunshu_logs_get",
        "parameters": [
          {
            "name": "level",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Level"
            }
          },
          {
            "name": "since",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "number"
                },
                {
                  "type": "null"
                }
              ],
              "description": "unix seconds",
              "title": "Since"
            },
            "description": "unix seconds"
          },
          {
            "name": "since_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0,
              "title": "Since Id"
            }
          },
          {
            "name": "q",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string",
                  "maxLength": 200
                },
                {
                  "type": "null"
                }
              ],
              "title": "Q"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "maximum": 2000,
              "minimum": 1,
              "default": 500,
              "title": "Limit"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Logs V1 Yunshu Logs Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/logs/stream": {
      "get": {
        "tags": [
          "yunshu"
        ],
        "summary": "Logs Stream",
        "operationId": "logs_stream_v1_yunshu_logs_stream_get",
        "parameters": [
          {
            "name": "level",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Level"
            }
          },
          {
            "name": "q",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string",
                  "maxLength": 200
                },
                {
                  "type": "null"
                }
              ],
              "title": "Q"
            }
          },
          {
            "name": "since_id",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "integer",
                  "minimum": 0
                },
                {
                  "type": "null"
                }
              ],
              "title": "Since Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/keys": {
      "get": {
        "tags": [
          "yunshu-keys"
        ],
        "summary": "List Keys",
        "operationId": "list_keys_v1_yunshu_keys_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response List Keys V1 Yunshu Keys Get"
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "yunshu-keys"
        ],
        "summary": "Create Key",
        "operationId": "create_key_v1_yunshu_keys_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/KeyCreate"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Create Key V1 Yunshu Keys Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/keys/{key_id}": {
      "patch": {
        "tags": [
          "yunshu-keys"
        ],
        "summary": "Patch Key",
        "operationId": "patch_key_v1_yunshu_keys__key_id__patch",
        "parameters": [
          {
            "name": "key_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Key Id"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": true,
                "title": "Body"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Patch Key V1 Yunshu Keys  Key Id  Patch"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "yunshu-keys"
        ],
        "summary": "Delete Key",
        "operationId": "delete_key_v1_yunshu_keys__key_id__delete",
        "parameters": [
          {
            "name": "key_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Key Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Delete Key V1 Yunshu Keys  Key Id  Delete"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/keys/{key_id}/rotate": {
      "post": {
        "tags": [
          "yunshu-keys"
        ],
        "summary": "Rotate Key",
        "operationId": "rotate_key_v1_yunshu_keys__key_id__rotate_post",
        "parameters": [
          {
            "name": "key_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "title": "Key Id"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Rotate Key V1 Yunshu Keys  Key Id  Rotate Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/usage": {
      "get": {
        "tags": [
          "yunshu-keys"
        ],
        "summary": "Usage",
        "operationId": "usage_v1_yunshu_usage_get",
        "parameters": [
          {
            "name": "key",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "title": "Key"
            }
          },
          {
            "name": "since",
            "in": "query",
            "required": false,
            "schema": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ],
              "description": "YYYY-MM-DD or a day count like 7d",
              "title": "Since"
            },
            "description": "YYYY-MM-DD or a day count like 7d"
          },
          {
            "name": "group",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "pattern": "^(day|key|total)$",
              "default": "day",
              "title": "Group"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "title": "Response Usage V1 Yunshu Usage Get"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/cors": {
      "get": {
        "tags": [
          "yunshu-admin"
        ],
        "summary": "Get Cors",
        "operationId": "get_cors_v1_yunshu_cors_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Get Cors V1 Yunshu Cors Get"
                }
              }
            }
          }
        }
      },
      "patch": {
        "tags": [
          "yunshu-admin"
        ],
        "summary": "Patch Cors",
        "operationId": "patch_cors_v1_yunshu_cors_patch",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CorsPatch"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Patch Cors V1 Yunshu Cors Patch"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/service": {
      "get": {
        "tags": [
          "yunshu-admin"
        ],
        "summary": "Get Service",
        "operationId": "get_service_v1_yunshu_service_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Get Service V1 Yunshu Service Get"
                }
              }
            }
          }
        }
      }
    },
    "/v1/yunshu/service/restart": {
      "post": {
        "tags": [
          "yunshu-admin"
        ],
        "summary": "Restart Service",
        "operationId": "restart_service_v1_yunshu_service_restart_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RestartBody"
              }
            }
          },
          "required": true
        },
        "responses": {
          "202": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Restart Service V1 Yunshu Service Restart Post"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/ocr": {
      "post": {
        "tags": [
          "ocr"
        ],
        "summary": "Extract Text From Image",
        "description": "Extract text from an uploaded image using OCR.\n\nAccepts PNG, JPG, JPEG, WEBP, TIFF image formats. The `language` field is a hint\npassed to the model (it steers output language); the response's `language`/\n`confidence` are echoed/None — no language detection is performed.",
        "operationId": "extract_text_from_image_v1_ocr_post",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/Body_extract_text_from_image_v1_ocr_post"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/v1/realtime/calls": {
      "post": {
        "tags": [
          "realtime"
        ],
        "summary": "Create Call",
        "operationId": "create_call_v1_realtime_calls_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/chat": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Chat",
        "operationId": "chat_api_chat_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/generate": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Generate",
        "operationId": "generate_api_generate_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/embed": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Embed",
        "operationId": "embed_api_embed_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/embeddings": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Embeddings Legacy",
        "operationId": "embeddings_legacy_api_embeddings_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/tags": {
      "get": {
        "tags": [
          "ollama"
        ],
        "summary": "Tags",
        "operationId": "tags_api_tags_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/ps": {
      "get": {
        "tags": [
          "ollama"
        ],
        "summary": "Ps",
        "operationId": "ps_api_ps_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/show": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Show",
        "operationId": "show_api_show_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/version": {
      "get": {
        "tags": [
          "ollama"
        ],
        "summary": "Version",
        "operationId": "version_api_version_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/copy": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Copy",
        "operationId": "copy_api_copy_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/delete": {
      "delete": {
        "tags": [
          "ollama"
        ],
        "summary": "Delete",
        "operationId": "delete_api_delete_delete",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/create": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Create",
        "operationId": "create_api_create_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/pull": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Pull",
        "operationId": "pull_api_pull_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/api/push": {
      "post": {
        "tags": [
          "ollama"
        ],
        "summary": "Push Na",
        "operationId": "push_na_api_push_post",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        }
      }
    },
    "/v1/omni/speech/stream": {
      "post": {
        "tags": [
          "omni"
        ],
        "summary": "Omni Speech Stream",
        "description": "Stream native Thinker text + Talker audio as SSE.\n\nEvents: ``{\"type\":\"text\",\"delta\":\"...\"}``, ``{\"type\":\"audio\",\"delta\":\"<b64 pcm16>\",\"sr\":24000}``,\n``{\"type\":\"done\",...}``, then ``data: [DONE]``.",
        "operationId": "omni_speech_stream_v1_omni_speech_stream_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/OmniSpeechRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/metrics": {
      "get": {
        "tags": [
          "metrics"
        ],
        "summary": "Metrics",
        "description": "Prometheus exposition. Auth follows the app-wide bearer token (open when none is set).",
        "operationId": "metrics_metrics_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "text/plain": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/health": {
      "get": {
        "summary": "Health",
        "operationId": "health_health_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Health Health Get"
                }
              }
            }
          }
        }
      }
    },
    "/health/ready": {
      "get": {
        "summary": "Readiness",
        "description": "Readiness probe — is the server ready to accept traffic?",
        "operationId": "readiness_health_ready_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Readiness Health Ready Get"
                }
              }
            }
          }
        }
      }
    },
    "/health/live": {
      "get": {
        "summary": "Liveness",
        "description": "Liveness probe — is the server alive?",
        "operationId": "liveness_health_live_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Liveness Health Live Get"
                }
              }
            }
          }
        }
      }
    },
    "/version": {
      "get": {
        "summary": "Version",
        "description": "Server version info.",
        "operationId": "version_version_get",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "additionalProperties": true,
                  "type": "object",
                  "title": "Response Version Version Get"
                }
              }
            }
          }
        }
      }
    },
    "/messages": {
      "post": {
        "tags": [
          "anthropic"
        ],
        "summary": "Create Message",
        "description": "Run the Messages endpoint; unlink staged images unless a stream owns them.",
        "operationId": "create_message_messages_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnthropicMessagesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    },
    "/messages/count_tokens": {
      "post": {
        "tags": [
          "anthropic"
        ],
        "summary": "Count Tokens",
        "description": "Token counting endpoint (Anthropic compatible).\n\nReturns Anthropic-format errors on failure:\n  {\"type\": \"error\", \"error\": {\"type\": \"...\", \"message\": \"...\"}}",
        "operationId": "count_tokens_messages_count_tokens_post",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnthropicCountTokensRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HTTPValidationError"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "AnthropicCountTokensRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "messages": {
            "items": {
              "$ref": "#/components/schemas/AnthropicMessage"
            },
            "type": "array",
            "title": "Messages"
          },
          "max_tokens": {
            "type": "integer",
            "maximum": 1048576.0,
            "minimum": 1.0,
            "title": "Max Tokens",
            "default": 1
          },
          "temperature": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Temperature"
          },
          "top_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Top P"
          },
          "top_k": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Top K"
          },
          "stream": {
            "type": "boolean",
            "title": "Stream",
            "default": false
          },
          "stop_sequences": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop Sequences"
          },
          "system": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "System"
          },
          "thinking": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Thinking"
          },
          "cache_control": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Cache Control"
          },
          "metadata": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Metadata"
          },
          "tools": {
            "anyOf": [
              {
                "items": {
                  "$ref": "#/components/schemas/AnthropicTool"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tools"
          },
          "tool_choice": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tool Choice"
          },
          "mcp_servers": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Mcp Servers"
          },
          "output_config": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Output Config"
          },
          "output_format": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Output Format"
          },
          "context_management": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Context Management"
          },
          "service_tier": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Service Tier"
          },
          "container": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Container"
          },
          "lora_adapter": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Lora Adapter"
          },
          "min_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Min P"
          },
          "repetition_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Repetition Penalty"
          },
          "frequency_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Frequency Penalty"
          },
          "presence_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Presence Penalty"
          },
          "logit_bias": {
            "anyOf": [
              {
                "additionalProperties": {
                  "type": "number"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logit Bias"
          },
          "seed": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Seed"
          },
          "reasoning_effort": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning Effort"
          },
          "stop_token_ids": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop Token Ids"
          },
          "spec_decode": {
            "type": "boolean",
            "title": "Spec Decode",
            "default": false
          },
          "xtc_probability": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Xtc Probability",
            "default": 0.0
          },
          "xtc_threshold": {
            "type": "number",
            "maximum": 0.5,
            "minimum": 0.0,
            "title": "Xtc Threshold",
            "default": 0.0
          },
          "min_tokens": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Min Tokens",
            "default": 0
          },
          "ignore_eos": {
            "type": "boolean",
            "title": "Ignore Eos",
            "default": false
          },
          "suppress_tokens": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Suppress Tokens"
          },
          "priority": {
            "type": "integer",
            "maximum": 100.0,
            "minimum": 0.0,
            "title": "Priority",
            "default": 0
          },
          "json_schema": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Json Schema"
          },
          "logprobs": {
            "type": "boolean",
            "title": "Logprobs",
            "default": false
          },
          "top_logprobs": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 20.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Top Logprobs"
          },
          "logits_processors": {
            "anyOf": [
              {
                "items": {},
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logits Processors"
          },
          "response_format": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Response Format"
          },
          "timeout": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 600.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Timeout"
          },
          "grammar": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Grammar"
          },
          "stream_options": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stream Options"
          }
        },
        "type": "object",
        "required": [
          "model",
          "messages"
        ],
        "title": "AnthropicCountTokensRequest",
        "description": "``/v1/messages/count_tokens`` takes the Messages body without ``max_tokens`` (the API's\ncount_tokens parameters do not include it), so the thinking-budget rule\n(``budget_tokens < max_tokens``) does not reject a valid count request."
      },
      "AnthropicMessage": {
        "properties": {
          "role": {
            "type": "string",
            "title": "Role"
          },
          "content": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Content"
          },
          "clear_at": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Clear At"
          },
          "output_config": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Output Config"
          }
        },
        "type": "object",
        "required": [
          "role"
        ],
        "title": "AnthropicMessage"
      },
      "AnthropicMessagesRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "messages": {
            "items": {
              "$ref": "#/components/schemas/AnthropicMessage"
            },
            "type": "array",
            "title": "Messages"
          },
          "max_tokens": {
            "type": "integer",
            "maximum": 1048576.0,
            "minimum": 1.0,
            "title": "Max Tokens"
          },
          "temperature": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Temperature"
          },
          "top_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Top P"
          },
          "top_k": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Top K"
          },
          "stream": {
            "type": "boolean",
            "title": "Stream",
            "default": false
          },
          "stop_sequences": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop Sequences"
          },
          "system": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "System"
          },
          "thinking": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Thinking"
          },
          "cache_control": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Cache Control"
          },
          "metadata": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Metadata"
          },
          "tools": {
            "anyOf": [
              {
                "items": {
                  "$ref": "#/components/schemas/AnthropicTool"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tools"
          },
          "tool_choice": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tool Choice"
          },
          "mcp_servers": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Mcp Servers"
          },
          "output_config": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Output Config"
          },
          "output_format": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Output Format"
          },
          "context_management": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Context Management"
          },
          "service_tier": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Service Tier"
          },
          "container": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Container"
          },
          "lora_adapter": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Lora Adapter"
          },
          "min_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Min P"
          },
          "repetition_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Repetition Penalty"
          },
          "frequency_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Frequency Penalty"
          },
          "presence_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Presence Penalty"
          },
          "logit_bias": {
            "anyOf": [
              {
                "additionalProperties": {
                  "type": "number"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logit Bias"
          },
          "seed": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Seed"
          },
          "reasoning_effort": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning Effort"
          },
          "stop_token_ids": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop Token Ids"
          },
          "spec_decode": {
            "type": "boolean",
            "title": "Spec Decode",
            "default": false
          },
          "xtc_probability": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Xtc Probability",
            "default": 0.0
          },
          "xtc_threshold": {
            "type": "number",
            "maximum": 0.5,
            "minimum": 0.0,
            "title": "Xtc Threshold",
            "default": 0.0
          },
          "min_tokens": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Min Tokens",
            "default": 0
          },
          "ignore_eos": {
            "type": "boolean",
            "title": "Ignore Eos",
            "default": false
          },
          "suppress_tokens": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Suppress Tokens"
          },
          "priority": {
            "type": "integer",
            "maximum": 100.0,
            "minimum": 0.0,
            "title": "Priority",
            "default": 0
          },
          "json_schema": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Json Schema"
          },
          "logprobs": {
            "type": "boolean",
            "title": "Logprobs",
            "default": false
          },
          "top_logprobs": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 20.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Top Logprobs"
          },
          "logits_processors": {
            "anyOf": [
              {
                "items": {},
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logits Processors"
          },
          "response_format": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Response Format"
          },
          "timeout": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 600.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Timeout"
          },
          "grammar": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Grammar"
          },
          "stream_options": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stream Options"
          }
        },
        "type": "object",
        "required": [
          "model",
          "messages",
          "max_tokens"
        ],
        "title": "AnthropicMessagesRequest",
        "description": "Anthropic Messages API request model.\n\nNative Anthropic fields: model, messages, max_tokens, temperature, top_p,\ntop_k, stream, stop_sequences, system, thinking, metadata, tools,\ntool_choice.\n\nExtended fields (Yunshu-specific, not in the Anthropic spec) are marked\nwith comments and forwarded to the engine for additional functionality."
      },
      "AnthropicTool": {
        "properties": {
          "name": {
            "type": "string",
            "title": "Name",
            "default": ""
          },
          "description": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Description"
          },
          "input_schema": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Input Schema"
          },
          "type": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Type"
          }
        },
        "additionalProperties": true,
        "type": "object",
        "title": "AnthropicTool",
        "description": "Anthropic tool definition.\n\nPer the Anthropic Messages API spec, tools have: name, description,\ninput_schema. The ``type`` field is NOT part of the Anthropic spec —\nAnthropic server-side tools (web_search, computer, etc.) carry versioned\ntypes like ``web_search_20250305`` but user-defined tools have no type."
      },
      "ApplyTemplateRequest": {
        "properties": {
          "model": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Model"
          },
          "messages": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array",
            "title": "Messages"
          },
          "tools": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tools"
          },
          "add_generation_prompt": {
            "type": "boolean",
            "title": "Add Generation Prompt",
            "default": true
          },
          "chat_template_kwargs": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Chat Template Kwargs"
          }
        },
        "type": "object",
        "required": [
          "messages"
        ],
        "title": "ApplyTemplateRequest"
      },
      "Body_create_transcription_v1_audio_transcriptions_post": {
        "properties": {
          "file": {
            "type": "string",
            "contentMediaType": "application/octet-stream",
            "title": "File"
          },
          "model": {
            "type": "string",
            "title": "Model"
          },
          "language": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Language"
          },
          "response_format": {
            "type": "string",
            "title": "Response Format",
            "default": "json"
          },
          "prompt": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt"
          },
          "temperature": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 1.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Temperature"
          },
          "timestamp_granularities": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Timestamp Granularities"
          },
          "timestamp_granularities[]": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Timestamp Granularities[]"
          }
        },
        "type": "object",
        "required": [
          "file",
          "model"
        ],
        "title": "Body_create_transcription_v1_audio_transcriptions_post"
      },
      "Body_create_translation_v1_audio_translations_post": {
        "properties": {
          "file": {
            "type": "string",
            "contentMediaType": "application/octet-stream",
            "title": "File"
          },
          "model": {
            "type": "string",
            "title": "Model"
          },
          "response_format": {
            "type": "string",
            "title": "Response Format",
            "default": "json"
          },
          "prompt": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt"
          },
          "temperature": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 1.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Temperature"
          }
        },
        "type": "object",
        "required": [
          "file",
          "model"
        ],
        "title": "Body_create_translation_v1_audio_translations_post"
      },
      "Body_extract_text_from_image_v1_ocr_post": {
        "properties": {
          "file": {
            "type": "string",
            "contentMediaType": "application/octet-stream",
            "title": "File"
          },
          "language": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Language"
          },
          "model": {
            "type": "string",
            "title": "Model",
            "default": ""
          },
          "task": {
            "type": "string",
            "title": "Task",
            "default": "text"
          }
        },
        "type": "object",
        "required": [
          "file"
        ],
        "title": "Body_extract_text_from_image_v1_ocr_post"
      },
      "BundleManifest": {
        "properties": {
          "object": {
            "type": "string",
            "title": "Object"
          },
          "format": {
            "type": "string",
            "title": "Format"
          },
          "included": {
            "items": {
              "type": "string"
            },
            "type": "array",
            "title": "Included"
          },
          "redacted": {
            "items": {
              "type": "string"
            },
            "type": "array",
            "title": "Redacted"
          },
          "excluded": {
            "items": {
              "type": "string"
            },
            "type": "array",
            "title": "Excluded"
          },
          "error_line_limit": {
            "type": "integer",
            "title": "Error Line Limit"
          },
          "error_line_max_chars": {
            "type": "integer",
            "title": "Error Line Max Chars"
          },
          "generator": {
            "type": "string",
            "title": "Generator"
          }
        },
        "type": "object",
        "required": [
          "object",
          "format",
          "included",
          "redacted",
          "excluded",
          "error_line_limit",
          "error_line_max_chars",
          "generator"
        ],
        "title": "BundleManifest"
      },
      "CacheClear": {
        "properties": {
          "object": {
            "type": "string",
            "title": "Object"
          },
          "models": {
            "items": {
              "type": "string"
            },
            "type": "array",
            "title": "Models"
          },
          "scope": {
            "type": "string",
            "title": "Scope"
          },
          "persistent_cleared": {
            "type": "boolean",
            "title": "Persistent Cleared"
          }
        },
        "type": "object",
        "required": [
          "object",
          "models",
          "scope",
          "persistent_cleared"
        ],
        "title": "CacheClear"
      },
      "CacheEntry": {
        "properties": {
          "device": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Device"
          },
          "model": {
            "type": "string",
            "title": "Model"
          },
          "id": {
            "type": "string",
            "title": "Id"
          },
          "namespace": {
            "type": "string",
            "title": "Namespace"
          },
          "tokens": {
            "type": "integer",
            "title": "Tokens"
          },
          "bytes_logical": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Bytes Logical"
          },
          "bytes_physical": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Bytes Physical",
            "description": "Attributed storage bytes, not allocator footprint"
          },
          "tier": {
            "type": "string",
            "title": "Tier"
          },
          "last_hit": {
            "anyOf": [
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Last Hit"
          },
          "hits": {
            "type": "integer",
            "title": "Hits"
          }
        },
        "type": "object",
        "required": [
          "model",
          "id",
          "namespace",
          "tokens",
          "bytes_logical",
          "bytes_physical",
          "tier",
          "last_hit",
          "hits"
        ],
        "title": "CacheEntry"
      },
      "CacheEvent": {
        "properties": {
          "device": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Device"
          },
          "model": {
            "type": "string",
            "title": "Model"
          },
          "id": {
            "type": "integer",
            "title": "Id"
          },
          "t": {
            "type": "number",
            "title": "T"
          },
          "action": {
            "type": "string",
            "title": "Action"
          },
          "entry_id": {
            "type": "string",
            "title": "Entry Id"
          },
          "tokens": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tokens"
          },
          "tier": {
            "type": "string",
            "title": "Tier"
          },
          "reason": {
            "type": "string",
            "title": "Reason"
          },
          "request_id": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Request Id"
          }
        },
        "type": "object",
        "required": [
          "model",
          "id",
          "t",
          "action",
          "entry_id",
          "tokens",
          "tier",
          "reason",
          "request_id"
        ],
        "title": "CacheEvent"
      },
      "CacheView": {
        "properties": {
          "object": {
            "type": "string",
            "title": "Object"
          },
          "data": {
            "items": {
              "$ref": "#/components/schemas/CacheEntry"
            },
            "type": "array",
            "title": "Data"
          },
          "count": {
            "type": "integer",
            "title": "Count"
          },
          "events": {
            "items": {
              "$ref": "#/components/schemas/CacheEvent"
            },
            "type": "array",
            "title": "Events"
          },
          "event_capacity": {
            "type": "integer",
            "title": "Event Capacity"
          },
          "models": {
            "items": {
              "type": "string"
            },
            "type": "array",
            "title": "Models"
          },
          "scope": {
            "type": "string",
            "title": "Scope"
          }
        },
        "type": "object",
        "required": [
          "object",
          "data",
          "count",
          "events",
          "event_capacity",
          "models",
          "scope"
        ],
        "title": "CacheView"
      },
      "CancelModelRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          }
        },
        "type": "object",
        "required": [
          "model"
        ],
        "title": "CancelModelRequest"
      },
      "CancelRequest": {
        "properties": {
          "request_id": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Request Id"
          },
          "cancel_all": {
            "type": "boolean",
            "title": "Cancel All",
            "default": false
          }
        },
        "type": "object",
        "title": "CancelRequest"
      },
      "ChatCompletionRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "messages": {
            "items": {
              "$ref": "#/components/schemas/ChatMessage"
            },
            "type": "array",
            "title": "Messages"
          },
          "keep_alive": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              },
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Keep Alive"
          },
          "store": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Store"
          },
          "metadata": {
            "anyOf": [
              {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Metadata"
          },
          "prompt_cache_key": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Cache Key"
          },
          "prompt_cache_retention": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Cache Retention"
          },
          "prompt_cache_options": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Cache Options"
          },
          "temperature": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Temperature"
          },
          "top_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Top P"
          },
          "top_k": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Top K"
          },
          "min_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Min P"
          },
          "repetition_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Repetition Penalty"
          },
          "frequency_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Frequency Penalty"
          },
          "presence_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Presence Penalty"
          },
          "logit_bias": {
            "anyOf": [
              {
                "additionalProperties": {
                  "type": "number"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logit Bias"
          },
          "max_tokens": {
            "type": "integer",
            "maximum": 1048576.0,
            "minimum": 1.0,
            "title": "Max Tokens"
          },
          "max_completion_tokens": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 1048576.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Max Completion Tokens"
          },
          "stream": {
            "type": "boolean",
            "title": "Stream",
            "default": false
          },
          "stream_options": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/yunshu_gateway__routers__chat__StreamOptions"
              },
              {
                "type": "null"
              }
            ]
          },
          "stop": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop"
          },
          "enable_thinking": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Enable Thinking"
          },
          "tools": {
            "anyOf": [
              {
                "items": {
                  "$ref": "#/components/schemas/ToolDefinition"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tools"
          },
          "tool_choice": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "$ref": "#/components/schemas/ToolChoiceFunction"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tool Choice"
          },
          "parallel_tool_calls": {
            "type": "boolean",
            "title": "Parallel Tool Calls",
            "default": true
          },
          "response_format": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Response Format"
          },
          "seed": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Seed"
          },
          "logprobs": {
            "type": "boolean",
            "title": "Logprobs",
            "default": false
          },
          "top_logprobs": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 20.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Top Logprobs"
          },
          "n": {
            "type": "integer",
            "maximum": 128.0,
            "minimum": 1.0,
            "title": "N",
            "default": 1
          },
          "user": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "User"
          },
          "spec_decode": {
            "type": "boolean",
            "title": "Spec Decode",
            "default": false
          },
          "thinking_budget": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 262144.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Thinking Budget"
          },
          "reasoning_effort": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning Effort"
          },
          "stop_token_ids": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop Token Ids"
          },
          "priority": {
            "type": "integer",
            "maximum": 100.0,
            "minimum": 0.0,
            "title": "Priority",
            "default": 0
          },
          "xtc_probability": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Xtc Probability",
            "default": 0.0
          },
          "xtc_threshold": {
            "type": "number",
            "maximum": 0.5,
            "minimum": 0.0,
            "title": "Xtc Threshold",
            "default": 0.0
          },
          "top_n_sigma": {
            "type": "number",
            "maximum": 10.0,
            "minimum": 0.0,
            "title": "Top N Sigma",
            "default": 0.0
          },
          "min_tokens": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Min Tokens",
            "default": 0
          },
          "ignore_eos": {
            "type": "boolean",
            "title": "Ignore Eos",
            "default": false
          },
          "suppress_tokens": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Suppress Tokens"
          },
          "prompt_logprobs": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Logprobs"
          },
          "grammar": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Grammar"
          },
          "guided_regex": {
            "anyOf": [
              {
                "type": "string",
                "maxLength": 2048
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Regex"
          },
          "guided_choice": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Choice"
          },
          "guided_grammar": {
            "anyOf": [
              {
                "type": "string",
                "maxLength": 32768
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Grammar"
          },
          "guided_json": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Json"
          },
          "lora_adapter": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Lora Adapter"
          },
          "logits_processors": {
            "anyOf": [
              {
                "items": {},
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logits Processors"
          },
          "timeout": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 600.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Timeout"
          },
          "chat_template_kwargs": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Chat Template Kwargs"
          }
        },
        "type": "object",
        "required": [
          "model",
          "messages"
        ],
        "title": "ChatCompletionRequest"
      },
      "ChatMessage": {
        "properties": {
          "role": {
            "type": "string",
            "title": "Role"
          },
          "content": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/TextContent"
                    },
                    {
                      "$ref": "#/components/schemas/ImageContent"
                    },
                    {
                      "additionalProperties": true,
                      "type": "object"
                    }
                  ]
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Content"
          },
          "tool_calls": {
            "anyOf": [
              {
                "items": {
                  "$ref": "#/components/schemas/ToolCall"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tool Calls"
          },
          "tool_call_id": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tool Call Id"
          },
          "name": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Name"
          },
          "reasoning_content": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning Content"
          },
          "reasoning": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning"
          }
        },
        "type": "object",
        "required": [
          "role"
        ],
        "title": "ChatMessage"
      },
      "ClassifyRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "input": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            ],
            "title": "Input"
          },
          "labels": {
            "items": {
              "type": "string"
            },
            "type": "array",
            "title": "Labels"
          },
          "temperature": {
            "type": "number",
            "maximum": 10.0,
            "exclusiveMinimum": 0.0,
            "title": "Temperature",
            "default": 0.07
          }
        },
        "type": "object",
        "required": [
          "model",
          "input"
        ],
        "title": "ClassifyRequest"
      },
      "ClearRequest": {
        "properties": {
          "tier": {
            "anyOf": [
              {
                "type": "string",
                "enum": [
                  "ram",
                  "warm",
                  "ssd"
                ]
              },
              {
                "type": "null"
              }
            ],
            "title": "Tier"
          },
          "model": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Model"
          }
        },
        "type": "object",
        "title": "ClearRequest"
      },
      "CompletionRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "keep_alive": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              },
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Keep Alive"
          },
          "prompt": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "items": {
                  "items": {
                    "type": "integer"
                  },
                  "type": "array"
                },
                "type": "array"
              }
            ],
            "title": "Prompt"
          },
          "max_tokens": {
            "type": "integer",
            "maximum": 1048576.0,
            "minimum": 0.0,
            "title": "Max Tokens",
            "default": 16
          },
          "max_completion_tokens": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 1048576.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Max Completion Tokens"
          },
          "temperature": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Temperature"
          },
          "top_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Top P"
          },
          "top_k": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Top K"
          },
          "min_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Min P"
          },
          "top_n_sigma": {
            "type": "number",
            "maximum": 10.0,
            "minimum": 0.0,
            "title": "Top N Sigma",
            "default": 0.0
          },
          "repetition_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Repetition Penalty"
          },
          "frequency_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Frequency Penalty"
          },
          "presence_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Presence Penalty"
          },
          "logit_bias": {
            "anyOf": [
              {
                "additionalProperties": {
                  "type": "number"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logit Bias"
          },
          "stream": {
            "type": "boolean",
            "title": "Stream",
            "default": false
          },
          "stream_options": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/yunshu_gateway__routers__completions__StreamOptions"
              },
              {
                "type": "null"
              }
            ]
          },
          "stop": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop"
          },
          "stop_token_ids": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop Token Ids"
          },
          "echo": {
            "type": "boolean",
            "title": "Echo",
            "default": false
          },
          "logprobs": {
            "type": "integer",
            "maximum": 5.0,
            "minimum": 0.0,
            "title": "Logprobs",
            "default": 0
          },
          "top_logprobs": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 5.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Top Logprobs"
          },
          "seed": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Seed"
          },
          "spec_decode": {
            "type": "boolean",
            "title": "Spec Decode",
            "default": false
          },
          "enable_thinking": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Enable Thinking"
          },
          "thinking_budget": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 262144.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Thinking Budget"
          },
          "response_format": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Response Format"
          },
          "reasoning_effort": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning Effort"
          },
          "xtc_probability": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Xtc Probability",
            "default": 0.0
          },
          "xtc_threshold": {
            "type": "number",
            "maximum": 0.5,
            "minimum": 0.0,
            "title": "Xtc Threshold",
            "default": 0.0
          },
          "min_tokens": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Min Tokens",
            "default": 0
          },
          "ignore_eos": {
            "type": "boolean",
            "title": "Ignore Eos",
            "default": false
          },
          "suppress_tokens": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Suppress Tokens"
          },
          "prompt_logprobs": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Logprobs"
          },
          "lora_adapter": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Lora Adapter"
          },
          "grammar": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Grammar"
          },
          "guided_regex": {
            "anyOf": [
              {
                "type": "string",
                "maxLength": 2048
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Regex"
          },
          "guided_choice": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Choice"
          },
          "guided_grammar": {
            "anyOf": [
              {
                "type": "string",
                "maxLength": 32768
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Grammar"
          },
          "guided_json": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Guided Json"
          },
          "user": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "User"
          },
          "suffix": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Suffix"
          },
          "best_of": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 128.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Best Of"
          },
          "priority": {
            "type": "integer",
            "maximum": 100.0,
            "minimum": 0.0,
            "title": "Priority",
            "default": 0
          },
          "n": {
            "type": "integer",
            "maximum": 128.0,
            "minimum": 1.0,
            "title": "N",
            "default": 1
          },
          "logits_processors": {
            "anyOf": [
              {
                "items": {},
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logits Processors"
          },
          "timeout": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 600.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Timeout"
          }
        },
        "type": "object",
        "required": [
          "model",
          "prompt"
        ],
        "title": "CompletionRequest"
      },
      "ConfigPatch": {
        "properties": {
          "settings": {
            "additionalProperties": true,
            "type": "object",
            "title": "Settings",
            "description": "NAME -> new value; null resets the setting to its default"
          },
          "confirm_experimental": {
            "type": "boolean",
            "title": "Confirm Experimental",
            "default": false
          },
          "dry_run": {
            "type": "boolean",
            "title": "Dry Run",
            "default": false
          }
        },
        "type": "object",
        "required": [
          "settings"
        ],
        "title": "ConfigPatch"
      },
      "CorsPatch": {
        "properties": {
          "origins": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Origins",
            "description": "allowed origins; null resets to the default"
          },
          "allow_any_origin": {
            "type": "boolean",
            "title": "Allow Any Origin",
            "description": "must be true to accept '*'",
            "default": false
          }
        },
        "type": "object",
        "title": "CorsPatch"
      },
      "DetokenizeRequest": {
        "properties": {
          "model": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Model"
          },
          "tokens": {
            "items": {
              "type": "integer"
            },
            "type": "array",
            "title": "Tokens"
          },
          "skip_special_tokens": {
            "type": "boolean",
            "title": "Skip Special Tokens",
            "default": true
          }
        },
        "type": "object",
        "required": [
          "tokens"
        ],
        "title": "DetokenizeRequest"
      },
      "DiagnosticsBundle": {
        "properties": {
          "created": {
            "type": "string",
            "title": "Created"
          },
          "version": {
            "type": "string",
            "title": "Version"
          },
          "platform": {
            "additionalProperties": true,
            "type": "object",
            "title": "Platform"
          },
          "packages": {
            "additionalProperties": true,
            "type": "object",
            "title": "Packages"
          },
          "settings_changed": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array",
            "title": "Settings Changed"
          },
          "paths": {
            "additionalProperties": true,
            "type": "object",
            "title": "Paths"
          },
          "doctor": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array",
            "title": "Doctor"
          },
          "caches": {
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array",
            "title": "Caches"
          },
          "errors": {
            "additionalProperties": true,
            "type": "object",
            "title": "Errors"
          },
          "excluded": {
            "type": "string",
            "title": "Excluded"
          }
        },
        "type": "object",
        "required": [
          "created",
          "version",
          "platform",
          "packages",
          "settings_changed",
          "paths",
          "doctor",
          "caches",
          "errors",
          "excluded"
        ],
        "title": "DiagnosticsBundle"
      },
      "DownloadRequest": {
        "properties": {
          "repo": {
            "type": "string",
            "title": "Repo"
          },
          "revision": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Revision"
          },
          "allow_patterns": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array",
                "maxItems": 32
              },
              {
                "type": "null"
              }
            ],
            "title": "Allow Patterns"
          }
        },
        "type": "object",
        "required": [
          "repo"
        ],
        "title": "DownloadRequest"
      },
      "DraftDepth": {
        "properties": {
          "position": {
            "type": "integer",
            "title": "Position"
          },
          "drafted": {
            "type": "integer",
            "title": "Drafted"
          },
          "accepted": {
            "type": "integer",
            "title": "Accepted"
          },
          "acceptance_rate": {
            "anyOf": [
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Acceptance Rate"
          }
        },
        "type": "object",
        "required": [
          "position",
          "drafted",
          "accepted",
          "acceptance_rate"
        ],
        "title": "DraftDepth"
      },
      "EmbeddingRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "input": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "items": {
                  "items": {
                    "type": "integer"
                  },
                  "type": "array"
                },
                "type": "array"
              },
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Input"
          },
          "encoding_format": {
            "type": "string",
            "title": "Encoding Format",
            "default": "float"
          },
          "dimensions": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Dimensions"
          },
          "user": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "User"
          },
          "pooling_type": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Pooling Type"
          },
          "instruction": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Instruction"
          },
          "task": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Task"
          },
          "messages": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Messages"
          }
        },
        "type": "object",
        "required": [
          "model"
        ],
        "title": "EmbeddingRequest"
      },
      "HTTPValidationError": {
        "properties": {
          "detail": {
            "items": {
              "$ref": "#/components/schemas/ValidationError"
            },
            "type": "array",
            "title": "Detail"
          }
        },
        "type": "object",
        "title": "HTTPValidationError"
      },
      "HistoryPage": {
        "properties": {
          "object": {
            "type": "string",
            "title": "Object"
          },
          "enabled": {
            "type": "boolean",
            "title": "Enabled"
          },
          "data": {
            "items": {
              "$ref": "#/components/schemas/RequestMetadata"
            },
            "type": "array",
            "title": "Data"
          },
          "count": {
            "type": "integer",
            "title": "Count"
          },
          "next_cursor": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Next Cursor"
          }
        },
        "type": "object",
        "required": [
          "object",
          "enabled",
          "data",
          "count",
          "next_cursor"
        ],
        "title": "HistoryPage"
      },
      "ImageContent": {
        "properties": {
          "type": {
            "type": "string",
            "title": "Type",
            "default": "image_url"
          },
          "image_url": {
            "$ref": "#/components/schemas/ImageURL"
          }
        },
        "type": "object",
        "required": [
          "image_url"
        ],
        "title": "ImageContent"
      },
      "ImageGenerateRequest": {
        "properties": {
          "prompt": {
            "type": "string",
            "title": "Prompt"
          },
          "model": {
            "type": "string",
            "title": "Model",
            "default": "Z-Image-Turbo-MLX-4bit"
          },
          "n": {
            "type": "integer",
            "maximum": 10.0,
            "minimum": 1.0,
            "title": "N",
            "default": 1
          },
          "size": {
            "type": "string",
            "title": "Size",
            "default": "1024x1024"
          },
          "response_format": {
            "type": "string",
            "title": "Response Format",
            "default": "b64_json"
          },
          "num_inference_steps": {
            "type": "integer",
            "maximum": 100.0,
            "minimum": 1.0,
            "title": "Num Inference Steps",
            "default": 4
          },
          "seed": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Seed"
          },
          "preview_interval": {
            "type": "integer",
            "title": "Preview Interval",
            "default": 0
          },
          "control_image": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Control Image"
          },
          "control_scale": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Control Scale",
            "default": 0.8
          }
        },
        "type": "object",
        "required": [
          "prompt"
        ],
        "title": "ImageGenerateRequest"
      },
      "ImageURL": {
        "properties": {
          "url": {
            "type": "string",
            "title": "Url"
          },
          "detail": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Detail"
          }
        },
        "type": "object",
        "required": [
          "url"
        ],
        "title": "ImageURL"
      },
      "KeyCreate": {
        "properties": {
          "name": {
            "type": "string",
            "title": "Name"
          },
          "scopes": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Scopes"
          },
          "quotas": {
            "anyOf": [
              {
                "additionalProperties": {
                  "anyOf": [
                    {
                      "type": "integer"
                    },
                    {
                      "type": "null"
                    }
                  ]
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Quotas"
          },
          "expires": {
            "anyOf": [
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Expires"
          }
        },
        "type": "object",
        "required": [
          "name"
        ],
        "title": "KeyCreate"
      },
      "LoadImpact": {
        "properties": {
          "would_evict": {
            "items": {
              "type": "string"
            },
            "type": "array",
            "title": "Would Evict"
          },
          "blocked": {
            "type": "boolean",
            "title": "Blocked"
          },
          "advisory": {
            "type": "boolean",
            "title": "Advisory"
          },
          "post_load_pressure": {
            "type": "string",
            "title": "Post Load Pressure"
          }
        },
        "type": "object",
        "required": [
          "would_evict",
          "blocked",
          "advisory",
          "post_load_pressure"
        ],
        "title": "LoadImpact"
      },
      "LoadModelRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "pin": {
            "type": "boolean",
            "title": "Pin",
            "default": false
          }
        },
        "type": "object",
        "required": [
          "model"
        ],
        "title": "LoadModelRequest"
      },
      "ModelImpact": {
        "properties": {
          "object": {
            "type": "string",
            "title": "Object"
          },
          "model": {
            "type": "string",
            "title": "Model"
          },
          "unload": {
            "$ref": "#/components/schemas/UnloadImpact"
          },
          "load": {
            "$ref": "#/components/schemas/LoadImpact"
          }
        },
        "type": "object",
        "required": [
          "object",
          "model",
          "unload",
          "load"
        ],
        "title": "ModelImpact"
      },
      "OmniSpeechRequest": {
        "properties": {
          "text": {
            "type": "string",
            "maxLength": 8000,
            "minLength": 1,
            "title": "Text"
          },
          "speaker": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Speaker"
          },
          "thinker_max_new_tokens": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 512.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Thinker Max New Tokens"
          },
          "image_path": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Image Path"
          },
          "audio_path": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Audio Path"
          }
        },
        "type": "object",
        "required": [
          "text"
        ],
        "title": "OmniSpeechRequest"
      },
      "PoolingRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "input": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            ],
            "title": "Input"
          },
          "pooling_type": {
            "type": "string",
            "title": "Pooling Type",
            "default": "CLS"
          },
          "encoding_format": {
            "type": "string",
            "title": "Encoding Format",
            "default": "float"
          }
        },
        "type": "object",
        "required": [
          "model",
          "input"
        ],
        "title": "PoolingRequest"
      },
      "RegisterLocalRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "path": {
            "type": "string",
            "title": "Path"
          }
        },
        "type": "object",
        "required": [
          "model",
          "path"
        ],
        "title": "RegisterLocalRequest"
      },
      "ReloadRequest": {
        "properties": {
          "force": {
            "type": "boolean",
            "title": "Force",
            "description": "reload even while requests are running (they are torn down)",
            "default": false
          }
        },
        "type": "object",
        "title": "ReloadRequest"
      },
      "RequestMetadata": {
        "properties": {
          "t": {
            "anyOf": [
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "T"
          },
          "request_id": {
            "type": "string",
            "title": "Request Id"
          },
          "model": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Model"
          },
          "path": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Path"
          },
          "stream": {
            "type": "boolean",
            "title": "Stream"
          },
          "status": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Status"
          },
          "prompt_tokens": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Tokens"
          },
          "completion_tokens": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Completion Tokens"
          },
          "cached_tokens": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Cached Tokens"
          },
          "prefill_tps": {
            "anyOf": [
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prefill Tps"
          },
          "decode_tps": {
            "anyOf": [
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Decode Tps"
          },
          "ttft_ms": {
            "anyOf": [
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Ttft Ms"
          },
          "latency": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Latency"
          },
          "energy": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Energy"
          },
          "speculative": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Speculative"
          },
          "cache": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Cache"
          },
          "structured_output": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Structured Output"
          },
          "reasons": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasons"
          }
        },
        "type": "object",
        "required": [
          "t",
          "request_id",
          "model",
          "path",
          "stream",
          "status",
          "prompt_tokens",
          "completion_tokens",
          "cached_tokens",
          "prefill_tps",
          "decode_tps",
          "ttft_ms",
          "latency",
          "energy",
          "speculative",
          "cache"
        ],
        "title": "RequestMetadata"
      },
      "RerankRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "query": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "additionalProperties": true,
                "type": "object"
              }
            ],
            "title": "Query"
          },
          "documents": {
            "items": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "additionalProperties": true,
                  "type": "object"
                }
              ]
            },
            "type": "array",
            "title": "Documents"
          },
          "top_n": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Top N"
          },
          "return_documents": {
            "type": "boolean",
            "title": "Return Documents",
            "default": true
          },
          "instruction": {
            "anyOf": [
              {
                "type": "string",
                "maxLength": 8192
              },
              {
                "type": "null"
              }
            ],
            "title": "Instruction"
          },
          "use_activation": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Use Activation"
          }
        },
        "type": "object",
        "required": [
          "model",
          "query",
          "documents"
        ],
        "title": "RerankRequest"
      },
      "ResponseInputText": {
        "properties": {
          "type": {
            "type": "string",
            "title": "Type",
            "default": "message"
          },
          "role": {
            "type": "string",
            "title": "Role",
            "default": "user"
          },
          "content": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Content"
          },
          "call_id": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Call Id"
          },
          "name": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Name"
          },
          "arguments": {
            "title": "Arguments"
          },
          "output": {
            "title": "Output"
          }
        },
        "additionalProperties": true,
        "type": "object",
        "title": "ResponseInputText"
      },
      "ResponseTool": {
        "properties": {
          "type": {
            "type": "string",
            "title": "Type",
            "default": "function"
          },
          "name": {
            "type": "string",
            "title": "Name",
            "default": ""
          },
          "description": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Description"
          },
          "parameters": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Parameters"
          }
        },
        "additionalProperties": true,
        "type": "object",
        "title": "ResponseTool",
        "description": "A declared tool. Besides ``function`` it can be ``web_search*``, ``mcp``, ``namespace``\n(Codex), ``custom`` ...; those keep their own fields (extra=\"allow\") and have no ``name``."
      },
      "ResponsesRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "input": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "$ref": "#/components/schemas/ResponseInputText"
                },
                "type": "array"
              }
            ],
            "title": "Input"
          },
          "instructions": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Instructions"
          },
          "previous_response_id": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Previous Response Id"
          },
          "conversation": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Conversation"
          },
          "context_management": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Context Management"
          },
          "max_output_tokens": {
            "type": "integer",
            "maximum": 1048576.0,
            "minimum": 1.0,
            "title": "Max Output Tokens"
          },
          "max_completion_tokens": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 1048576.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Max Completion Tokens"
          },
          "max_tokens": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 1048576.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Max Tokens"
          },
          "temperature": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Temperature"
          },
          "top_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Top P"
          },
          "top_k": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Top K"
          },
          "stream": {
            "type": "boolean",
            "title": "Stream",
            "default": false
          },
          "n": {
            "type": "integer",
            "maximum": 128.0,
            "minimum": 1.0,
            "title": "N",
            "default": 1
          },
          "tools": {
            "anyOf": [
              {
                "items": {
                  "$ref": "#/components/schemas/ResponseTool"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tools"
          },
          "tool_choice": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tool Choice"
          },
          "parallel_tool_calls": {
            "type": "boolean",
            "title": "Parallel Tool Calls",
            "default": true
          },
          "response_format": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Response Format"
          },
          "text": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Text"
          },
          "seed": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Seed"
          },
          "enable_thinking": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Enable Thinking"
          },
          "thinking_budget": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 262144.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Thinking Budget"
          },
          "reasoning_effort": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning Effort"
          },
          "reasoning": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Reasoning"
          },
          "generate": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Generate"
          },
          "include": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Include"
          },
          "max_tool_calls": {
            "anyOf": [
              {
                "type": "integer",
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Max Tool Calls"
          },
          "prompt_cache_key": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Cache Key"
          },
          "client_metadata": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Client Metadata"
          },
          "service_tier": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Service Tier"
          },
          "repetition_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Repetition Penalty"
          },
          "frequency_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Frequency Penalty"
          },
          "presence_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": -2.0,
            "title": "Presence Penalty"
          },
          "logit_bias": {
            "anyOf": [
              {
                "additionalProperties": {
                  "type": "number"
                },
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logit Bias"
          },
          "min_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Min P"
          },
          "top_n_sigma": {
            "type": "number",
            "maximum": 10.0,
            "minimum": 0.0,
            "title": "Top N Sigma",
            "default": 0.0
          },
          "stop": {
            "anyOf": [
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop"
          },
          "stop_token_ids": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Stop Token Ids"
          },
          "logprobs": {
            "type": "boolean",
            "title": "Logprobs",
            "default": false
          },
          "top_logprobs": {
            "anyOf": [
              {
                "type": "integer",
                "maximum": 20.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Top Logprobs"
          },
          "spec_decode": {
            "type": "boolean",
            "title": "Spec Decode",
            "default": false
          },
          "xtc_probability": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Xtc Probability",
            "default": 0.0
          },
          "xtc_threshold": {
            "type": "number",
            "maximum": 0.5,
            "minimum": 0.0,
            "title": "Xtc Threshold",
            "default": 0.0
          },
          "min_tokens": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Min Tokens",
            "default": 0
          },
          "ignore_eos": {
            "type": "boolean",
            "title": "Ignore Eos",
            "default": false
          },
          "suppress_tokens": {
            "anyOf": [
              {
                "items": {
                  "type": "integer"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Suppress Tokens"
          },
          "grammar": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Grammar"
          },
          "lora_adapter": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Lora Adapter"
          },
          "stream_options": {
            "anyOf": [
              {
                "$ref": "#/components/schemas/yunshu_gateway__routers__responses__StreamOptions"
              },
              {
                "type": "null"
              }
            ]
          },
          "store": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Store",
            "default": true
          },
          "background": {
            "type": "boolean",
            "title": "Background",
            "default": false
          },
          "user": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "User"
          },
          "metadata": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Metadata"
          },
          "truncation": {
            "anyOf": [
              {
                "type": "string",
                "enum": [
                  "auto",
                  "disabled"
                ]
              },
              {
                "type": "null"
              }
            ],
            "title": "Truncation"
          },
          "prompt_cache_retention": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Cache Retention"
          },
          "prompt_cache_options": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Cache Options"
          },
          "safety_identifier": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Safety Identifier"
          },
          "priority": {
            "type": "integer",
            "maximum": 100.0,
            "minimum": 0.0,
            "title": "Priority",
            "default": 0
          },
          "logits_processors": {
            "anyOf": [
              {
                "items": {},
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Logits Processors"
          },
          "timeout": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 600.0,
                "minimum": 1.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Timeout"
          }
        },
        "type": "object",
        "required": [
          "model",
          "input"
        ],
        "title": "ResponsesRequest"
      },
      "RestartBody": {
        "properties": {
          "confirm": {
            "type": "boolean",
            "title": "Confirm",
            "description": "must be true",
            "default": false
          }
        },
        "type": "object",
        "title": "RestartBody"
      },
      "ScoreRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "text_1": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            ],
            "title": "Text 1"
          },
          "text_2": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            ],
            "title": "Text 2"
          },
          "scoring_type": {
            "type": "string",
            "title": "Scoring Type",
            "default": "cosine"
          },
          "use_activation": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Use Activation"
          },
          "instruction": {
            "anyOf": [
              {
                "type": "string",
                "maxLength": 8192
              },
              {
                "type": "null"
              }
            ],
            "title": "Instruction"
          },
          "chat_template_kwargs": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Chat Template Kwargs"
          }
        },
        "type": "object",
        "required": [
          "model",
          "text_1",
          "text_2"
        ],
        "title": "ScoreRequest"
      },
      "SpecAggregate": {
        "properties": {
          "object": {
            "type": "string",
            "title": "Object"
          },
          "scope": {
            "type": "string",
            "title": "Scope"
          },
          "position_basis": {
            "type": "string",
            "title": "Position Basis"
          },
          "data": {
            "items": {
              "$ref": "#/components/schemas/SpecMode"
            },
            "type": "array",
            "title": "Data"
          }
        },
        "type": "object",
        "required": [
          "object",
          "scope",
          "position_basis",
          "data"
        ],
        "title": "SpecAggregate"
      },
      "SpecMode": {
        "properties": {
          "mode": {
            "type": "string",
            "title": "Mode"
          },
          "num_drafts": {
            "type": "integer",
            "title": "Num Drafts"
          },
          "num_draft_tokens": {
            "type": "integer",
            "title": "Num Draft Tokens"
          },
          "num_accepted_tokens": {
            "type": "integer",
            "title": "Num Accepted Tokens"
          },
          "per_depth": {
            "items": {
              "$ref": "#/components/schemas/DraftDepth"
            },
            "type": "array",
            "title": "Per Depth"
          }
        },
        "type": "object",
        "required": [
          "mode",
          "num_drafts",
          "num_draft_tokens",
          "num_accepted_tokens",
          "per_depth"
        ],
        "title": "SpecMode"
      },
      "TTSRequest": {
        "properties": {
          "model": {
            "type": "string",
            "title": "Model"
          },
          "input": {
            "type": "string",
            "title": "Input"
          },
          "voice": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "additionalProperties": {
                  "type": "string"
                },
                "type": "object"
              }
            ],
            "title": "Voice",
            "default": "alloy"
          },
          "speed": {
            "type": "number",
            "maximum": 4.0,
            "minimum": 0.25,
            "title": "Speed",
            "default": 1.0
          },
          "response_format": {
            "type": "string",
            "title": "Response Format",
            "default": "wav"
          },
          "temperature": {
            "anyOf": [
              {
                "type": "number",
                "maximum": 2.0,
                "minimum": 0.0
              },
              {
                "type": "null"
              }
            ],
            "title": "Temperature"
          },
          "instruct": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Instruct"
          },
          "top_k": {
            "type": "integer",
            "minimum": 0.0,
            "title": "Top K",
            "default": 50
          },
          "top_p": {
            "type": "number",
            "maximum": 1.0,
            "minimum": 0.0,
            "title": "Top P",
            "default": 0.95
          },
          "repetition_penalty": {
            "type": "number",
            "maximum": 2.0,
            "minimum": 0.0,
            "title": "Repetition Penalty",
            "default": 1.0
          },
          "max_tokens": {
            "type": "integer",
            "maximum": 32768.0,
            "minimum": 1.0,
            "title": "Max Tokens",
            "default": 4096
          },
          "ref_audio": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Ref Audio"
          },
          "ref_text": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Ref Text"
          },
          "language": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Language"
          },
          "seed": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "title": "Seed"
          },
          "segment_size": {
            "type": "integer",
            "maximum": 2000.0,
            "minimum": 50.0,
            "title": "Segment Size",
            "default": 300
          }
        },
        "type": "object",
        "required": [
          "model",
          "input"
        ],
        "title": "TTSRequest"
      },
      "TextContent": {
        "properties": {
          "type": {
            "type": "string",
            "title": "Type",
            "default": "text"
          },
          "text": {
            "type": "string",
            "title": "Text"
          },
          "prompt_cache_breakpoint": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt Cache Breakpoint"
          }
        },
        "type": "object",
        "required": [
          "text"
        ],
        "title": "TextContent"
      },
      "TokenizeRequest": {
        "properties": {
          "model": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Model"
          },
          "prompt": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt"
          },
          "messages": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Messages"
          },
          "add_special_tokens": {
            "anyOf": [
              {
                "type": "boolean"
              },
              {
                "type": "null"
              }
            ],
            "title": "Add Special Tokens"
          },
          "add_generation_prompt": {
            "type": "boolean",
            "title": "Add Generation Prompt",
            "default": true
          },
          "continue_final_message": {
            "type": "boolean",
            "title": "Continue Final Message",
            "default": false
          },
          "tools": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Tools"
          },
          "chat_template_kwargs": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Chat Template Kwargs"
          },
          "return_token_strs": {
            "type": "boolean",
            "title": "Return Token Strs",
            "default": false
          }
        },
        "type": "object",
        "title": "TokenizeRequest",
        "description": "vLLM `/tokenize` request: either `prompt` (raw text) or `messages` (chat template)."
      },
      "ToolCall": {
        "properties": {
          "id": {
            "type": "string",
            "title": "Id",
            "default": ""
          },
          "type": {
            "type": "string",
            "title": "Type",
            "default": "function"
          },
          "function": {
            "$ref": "#/components/schemas/ToolCallFunction",
            "default": {
              "name": "",
              "arguments": "{}"
            }
          }
        },
        "type": "object",
        "title": "ToolCall",
        "description": "OpenAI tool_call structure in assistant messages."
      },
      "ToolCallFunction": {
        "properties": {
          "name": {
            "type": "string",
            "title": "Name"
          },
          "arguments": {
            "type": "string",
            "title": "Arguments",
            "default": "{}"
          }
        },
        "type": "object",
        "required": [
          "name"
        ],
        "title": "ToolCallFunction",
        "description": "Function call within a tool_call."
      },
      "ToolChoiceFunction": {
        "properties": {
          "type": {
            "type": "string",
            "title": "Type",
            "default": "function"
          },
          "function": {
            "$ref": "#/components/schemas/ToolFunction"
          }
        },
        "type": "object",
        "required": [
          "function"
        ],
        "title": "ToolChoiceFunction",
        "description": "tool_choice = {\"type\": \"function\", \"function\": {\"name\": \"...\"}}\"."
      },
      "ToolDefinition": {
        "properties": {
          "type": {
            "type": "string",
            "title": "Type",
            "default": "function"
          },
          "function": {
            "$ref": "#/components/schemas/ToolFunction"
          }
        },
        "type": "object",
        "required": [
          "function"
        ],
        "title": "ToolDefinition"
      },
      "ToolFunction": {
        "properties": {
          "name": {
            "type": "string",
            "title": "Name"
          },
          "description": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Description"
          },
          "parameters": {
            "anyOf": [
              {
                "additionalProperties": true,
                "type": "object"
              },
              {
                "type": "null"
              }
            ],
            "title": "Parameters"
          }
        },
        "type": "object",
        "required": [
          "name"
        ],
        "title": "ToolFunction"
      },
      "UnloadImpact": {
        "properties": {
          "in_flight_policy": {
            "type": "string",
            "title": "In Flight Policy"
          },
          "waits": {
            "type": "boolean",
            "title": "Waits"
          },
          "interrupts": {
            "type": "boolean",
            "title": "Interrupts"
          }
        },
        "type": "object",
        "required": [
          "in_flight_policy",
          "waits",
          "interrupts"
        ],
        "title": "UnloadImpact"
      },
      "ValidationError": {
        "properties": {
          "loc": {
            "items": {
              "anyOf": [
                {
                  "type": "string"
                },
                {
                  "type": "integer"
                }
              ]
            },
            "type": "array",
            "title": "Location"
          },
          "msg": {
            "type": "string",
            "title": "Message"
          },
          "type": {
            "type": "string",
            "title": "Error Type"
          },
          "input": {
            "title": "Input"
          },
          "ctx": {
            "type": "object",
            "title": "Context"
          }
        },
        "type": "object",
        "required": [
          "loc",
          "msg",
          "type"
        ],
        "title": "ValidationError"
      },
      "WarmupRequest": {
        "properties": {
          "model": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Model"
          },
          "prompt": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "title": "Prompt"
          },
          "messages": {
            "anyOf": [
              {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              {
                "type": "null"
              }
            ],
            "title": "Messages"
          },
          "keep_alive": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              },
              {
                "type": "number"
              },
              {
                "type": "null"
              }
            ],
            "title": "Keep Alive"
          },
          "max_tokens": {
            "type": "integer",
            "title": "Max Tokens",
            "default": 1
          }
        },
        "type": "object",
        "title": "WarmupRequest"
      },
      "yunshu_gateway__routers__chat__StreamOptions": {
        "properties": {
          "include_usage": {
            "type": "boolean",
            "title": "Include Usage",
            "default": false
          },
          "continuous_usage_stats": {
            "type": "boolean",
            "title": "Continuous Usage Stats",
            "default": false
          }
        },
        "type": "object",
        "title": "StreamOptions",
        "description": "OpenAI stream_options parameter."
      },
      "yunshu_gateway__routers__completions__StreamOptions": {
        "properties": {
          "include_usage": {
            "type": "boolean",
            "title": "Include Usage",
            "default": false
          },
          "continuous_usage_stats": {
            "type": "boolean",
            "title": "Continuous Usage Stats",
            "default": false
          }
        },
        "type": "object",
        "title": "StreamOptions",
        "description": "OpenAI stream_options parameter."
      },
      "yunshu_gateway__routers__responses__StreamOptions": {
        "properties": {
          "include_usage": {
            "type": "boolean",
            "title": "Include Usage",
            "default": false
          }
        },
        "type": "object",
        "title": "StreamOptions",
        "description": "OpenAI stream_options parameter."
      }
    }
  },
  "servers": [
    {
      "url": "/",
      "description": "Console same-origin proxy"
    }
  ]
}

```
