<!-- api/audio -->
---
title: Audio
description: OpenAI-style speech-to-text, translation and text-to-speech endpoints, plus local custom voices, served by mlx-audio models.
---

The audio routes follow the OpenAI `/v1/audio/*` dialect. Transcription and translation take a multipart upload and return JSON or subtitle text. Speech synthesis takes JSON and returns encoded audio, or a Server-Sent Events stream of raw PCM chunks. Yunshu adds local custom voices (consent plus voice enrollment) on top.

Audio models come from the optional `audio` extra (`pip install "yunshu[audio]"`, backed by `mlx-audio`). The model you request must be a loaded audio model of the right kind (ASR for transcription, TTS for speech); otherwise the server answers `404` with a message that names the modality mismatch.

<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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. When it is set, send `Authorization: Bearer <token>` (or `x-api-key`). Without a token, inference routes such as these are open on the bound address.
</Callout>

## Model selection

- In single-model mode (`yunshu serve` with one model) the served model is used; the `model` field is advisory.
- In multi-model mode the model must already be loaded, otherwise the request fails with `503` and a message pointing to `POST /v1/models/load`. Setting `YUNSHU_ALLOW_AUTO_LOAD=1` lets audio requests load a model on demand.
- With several audio engines loaded, the engine whose id matches `model` (case-insensitive) is used.

Model families recognised as ASR are `whisper`, `qwen3_asr`, `parakeet` and `qwen2_audio`; TTS families are `qwen3_tts`, `kokoro` and `chatterbox` (plus names containing `tts`). Which individual checkpoints work is decided by the installed `mlx-audio`; see [Models](/docs/getting-started/models).

## Transcriptions

`POST /v1/audio/transcriptions` takes `multipart/form-data`.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `file` | file | yes | Audio or video upload, at most 25 MB. Audio: `.wav .mp3 .ogg .flac .m4a .webm .aac`. Video: `.mp4 .mkv .avi .mov .wmv .ts .mts` (audio track is extracted with `ffmpeg`). | supported |
| `model` | string | yes | ASR model id. Empty string is rejected with `400`. | supported |
| `language` | string | no | Language hint passed to the model. | supported |
| `response_format` | string | no | `json` (default), `text`, `srt`, `vtt`, `verbose_json`. Anything else returns `400`. | supported |
| `prompt` | string | no | Text prompt passed to the model. | supported |
| `temperature` | number | no | 0 to 1. Omitted means the model uses its own default. | supported |
| `timestamp_granularities` | list of string | no | Pass `word` to request word timestamps. Both `timestamp_granularities` and the SDK spelling `timestamp_granularities[]` are accepted. | supported |

### Response formats

| `response_format` | Content-Type | Body |
| --- | --- | --- |
| `json` | `application/json` | `{"text", "language"}` plus `segments` and `duration` when the model produced them |
| `verbose_json` | `application/json` | `text`, `language`, `task: "transcribe"`, `duration`, `segments` (padded to the OpenAI segment schema with neutral defaults for fields the model did not emit), and `words` when available |
| `text` | `text/plain` | Plain transcript |
| `srt` | `text/plain` | SubRip subtitles built from the segments |
| `vtt` | `text/vtt` | WebVTT subtitles built from the segments |

`srt` and `vtt` need segment timestamps. If the model returns no segments, the subtitle body is empty.

## Translations

`POST /v1/audio/translations` decodes speech into English text. It accepts `file`, `model`, `response_format` (same five values) , `prompt` and `temperature`. It has no `language` field.

Translation is a Whisper capability. If neither the loaded model path nor the requested id contains `whisper`, the server returns `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` returns `{"text": ...}`. `verbose_json` adds `task: "translate"`, `language: "english"`, `duration` and `segments`. `text`, `srt` and `vtt` return plain text bodies (`text/plain` for all three here).

## Speech

`POST /v1/audio/speech` accepts a JSON body (or `multipart/form-data` with the same field names). It returns the audio bytes with a `Content-Disposition: attachment; filename=speech.<ext>` header.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | TTS model id. | supported |
| `input` | string | yes | Text to speak. Non-empty, at most 32768 characters. | supported |
| `voice` | string or object | no | Voice name (default `alloy`), or `{"id": "voice_..."}` for a custom voice enrolled through `POST /v1/audio/voices`. Built-in names reported by `GET /v1/audio/voices`; the fallback list is `alloy`, `chelsie`, `ethan`, `aiden`. | supported |
| `response_format` | string | no | `mp3`, `opus`, `aac`, `flac`, `wav`, `pcm`. The server default is `wav`; the official OpenAI SDK sends `mp3` unless you override it. `format` is accepted as an alias. | supported |
| `speed` | number | no | 0.25 to 4.0, default 1.0. | supported |
| `temperature` | number | no | 0 to 2. | supported |
| `instruct` | string | no | Free-form voice description for VoiceDesign-style models. When omitted, a short description is derived from the voice name. | extension |
| `top_k` | integer | no | Default 50. | extension |
| `top_p` | number | no | 0 to 1, default 0.95. | extension |
| `repetition_penalty` | number | no | 0 to 2, default 1.0. | extension |
| `max_tokens` | integer | no | 1 to 32768, default 4096. | extension |
| `ref_audio` | string | no | Local path of a reference recording for voice cloning. URI schemes and `..` segments are rejected; absolute paths need `YUNSHU_ALLOW_LOCAL_FILES=1`. Cannot be combined with a custom `voice`. | extension |
| `ref_text` | string | no | Transcript of the reference recording. | extension |
| `language` | string | no | Language code for multilingual models. | extension |
| `seed` | integer | no | Random seed. | extension |
| `segment_size` | integer | no | 50 to 2000, default 300. Only used by the streaming route. | extension |
| `instructions`, `stream_format` | | no | OpenAI fields that are not part of the schema; they are ignored. | accepted and ignored |

### Output formats and the ffmpeg fallback

The engine produces WAV. Other formats are produced by transcoding with `ffmpeg`:

| `response_format` | Content-Type | Notes |
| --- | --- | --- |
| `wav` | `audio/wav` | No transcoding. |
| `pcm` | `audio/L16; rate=<sample rate>; channels=<n>` | Raw 16-bit little-endian samples with the WAV header stripped; done in Python, no `ffmpeg` needed. |
| `mp3` | `audio/mpeg` | Needs `ffmpeg`. |
| `opus` | `audio/ogg` | Ogg-encapsulated Opus; needs `ffmpeg` with `libopus`. |
| `aac` | `audio/aac` | ADTS stream; needs `ffmpeg`. |
| `flac` | `audio/flac` | Needs `ffmpeg`. |

If `ffmpeg` is not on `PATH` (or the transcode fails), the server does not mislabel bytes. It returns the WAV audio as `audio/wav` with the response header `X-Yunshu-Audio-Format-Fallback: wav` and a `.wav` filename. Check that header if you depend on a compressed format. Install `ffmpeg` (for example `brew install ffmpeg`) to avoid the fallback. Video transcription also depends on `ffmpeg`; without it the request fails with `415`.

## Speech streaming

`POST /v1/audio/speech/stream` takes the same JSON body and responds with `text/event-stream`. Response headers include `X-Audio-Format: pcm-s16le` and `X-Sample-Rate: <rate>`. Compressed formats are not available while streaming: chunks are always raw 16-bit PCM, and `response_format` is validated but otherwise has no effect.

Long input is split into segments of `segment_size` characters and synthesized one after another. Events, in order:

| Event `type` | Fields | When |
| --- | --- | --- |
| `header` | `wav_header` (base64), `sample_rate` | First event. The WAV header declares unknown length. |
| `audio` | `audio` (base64 PCM16), `text`, `segment` | One per audio chunk. |
| `done` | none | After the last segment. |
| `cancelled` | none | The request was cancelled, for example through `POST /v1/cancel`. |
| `error` | `error.message`, `error.type` | Synthesis failed part-way. |

The stream ends with `data: [DONE]` after `done` or `error`. A `cancelled` event ends the stream without `[DONE]`.

## Custom voices

Custom voices are local. A recording is stored in the bounded Files store, so Files quota and expiry apply to it, see [Files](/docs/api/files). Enrollment records a consent recording; it does not verify who is speaking.

1. `POST /v1/audio/voice_consents` creates a consent record.
2. `POST /v1/audio/voices` creates a voice that references the consent.
3. Use `"voice": {"id": "voice_..."}` in a speech request.

`POST /v1/audio/voice_consents` takes `multipart/form-data`:

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | yes | 1 to 256 characters. |
| `language` | string | yes | Up to 64 characters. |
| `recording` | file | yes | Audio, at most 10 MiB and at most 60 seconds once decoded. MIME type must be one of `audio/mpeg`, `audio/wav`, `audio/x-wav`, `audio/ogg`, `audio/aac`, `audio/flac`, `audio/webm`, `audio/mp4`. |

It returns `{"object": "audio.voice_consent", "id": "cons_...", "name", "language", "created_at"}`.

`POST /v1/audio/voices` takes `multipart/form-data`:

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | yes | 1 to 256 characters. |
| `consent` | string | yes | A `cons_...` id from the previous step. |
| `audio_sample` | file | yes | Same limits as `recording` above. |
| `type` | string | no | Only `audio_sample` is supported. Any other value returns `400` (prompt-designed voices are not supported). |
| `ref_text` | string | no | Transcript of the sample, up to 32768 characters. |

It returns `{"object": "audio.voice", "id": "voice_...", "name", "type": "audio_sample", "created_at"}`. Enrollment decodes the sample with `soundfile` (part of the audio extra); an undecodable sample returns `400`, and a missing dependency returns `503`.

Using a custom voice requires a TTS model that supports reference audio. Otherwise the speech request returns `400`. Qwen3-TTS must be a Base model and needs a transcript, from `ref_text` at enrollment or in the speech request; CustomVoice and VoiceDesign variants are rejected.

`GET /v1/audio/voices` returns `{"object": "list", "data": [{"id": "alloy", "object": "voice"}, ...]}` with the built-in names of the loaded TTS model followed by the enrolled custom voices (full voice objects).

## Examples

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

## Errors

Errors use the OpenAI envelope `{"error": {"message", "type", "param", "code"}}`.

| Status | When |
| --- | --- |
| `400` | Bad `response_format`, empty `model`/`input`, out-of-range number, invalid `voice` object, upload that is not decodable audio, bad custom voice or consent. |
| `404` | No loaded model of the right modality for `model`. |
| `413` | Upload larger than 25 MB (transcription, translation) or recording larger than 10 MiB (voices). |
| `415` | Video upload but `ffmpeg` is missing or cannot extract audio. |
| `501` | Translation requested on a non-Whisper ASR model. |
| `503` | Model not loaded in multi-model mode, or `soundfile` missing for voice enrollment. |
| `507` | Out of GPU memory. |
| `500` | Transcription, translation or synthesis failed. |

Streaming failures after the response has started arrive as an `error` event rather than an HTTP status.

## Support

| Feature | Status |
| --- | --- |
| Transcription, `json` / `text` / `srt` / `vtt` / `verbose_json` | <Support status="supported">supported</Support> |
| Word timestamps | <Support status="partial">when the ASR model produces them</Support> |
| Translation to English | <Support status="partial">Whisper models only; others return 501</Support> |
| Speech `wav` and `pcm` | <Support status="supported">supported</Support> |
| Speech `mp3`, `opus`, `aac`, `flac` | <Support status="partial">needs ffmpeg, otherwise WAV with a fallback header</Support> |
| Compressed audio while streaming | <Support status="unsupported">raw PCM16 only</Support> |
| Custom voices | <Support status="partial">needs a reference-audio capable TTS model</Support> |
| Prompt-designed voices (`type` other than `audio_sample`) | <Support status="unsupported">rejected with 400</Support> |
| `diarized_json`, `gpt-4o-transcribe` streaming events | <Support status="unsupported">not supported</Support> |

## Related

- [Realtime](/docs/api/realtime) for voice conversations over WebSocket.
- [Extensions](/docs/api/extensions) for `POST /v1/omni/speech/stream`, native speech-to-speech.
- [Files](/docs/api/files) for the store that holds enrolled voices.
- [Models](/docs/getting-started/models) for choosing and loading audio models.


---

<!-- api/batches -->
---
title: Batches
description: The OpenAI Batch API, backed by a single loopback worker that replays each JSONL line against this same server and resumes after a restart.
---

`/v1/batches` follows the OpenAI Batch API. You upload a JSONL file of requests with `purpose=batch` through the [Files API](/docs/api/files), create a batch that points at it, poll until it ends, and download the output file. Anthropic message batches live on the same machinery and are documented with the [Messages](/docs/api/messages) API.

<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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. The worker re-uses that token when it calls the server, so a batch runs with the same auth, model routing, prefix cache and tools as a normal request.
</Callout>

## How batches run

- A single background worker drains queued batches one at a time, oldest first, and runs the requests inside a batch one at a time.
- Each line is sent as an ordinary HTTP `POST` to the batch's endpoint on this server (over the same host and port the batch was created through). Interactive traffic is interleaved; the engine serializes GPU work.
- `stream` is forced to `false` for every line.
- Batch state is stored in the file store (`~/.yunshu/files` unless `YUNSHU_FILES_DIR` is set). After a restart the worker picks up unfinished batches and skips lines that already have a result, so a batch resumes where it stopped.
- The completion window is fixed at 24 hours from creation. If the batch is still running after that, it ends as `expired` and the remaining lines are not run.

## Create a batch

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `input_file_id` | string | yes | A file uploaded with `purpose=batch`. | supported |
| `endpoint` | string | yes | One of `/v1/chat/completions`, `/v1/completions`, `/v1/embeddings`, `/v1/responses`. | supported |
| `completion_window` | string | yes | Must be `24h`. | supported |
| `metadata` | object | no | Up to 16 keys, string values only. | supported |
| `output_expires_after` | object | no | OpenAI field for output file expiry. | accepted and ignored |

### Input file format

One JSON object per line (blank lines are skipped):

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

Rules checked when the batch is created:

- `custom_id` is required, a string, and unique within the file.
- `method` must be `POST`.
- `url` must equal the batch's `endpoint`.
- `body` must be a JSON object and must not set `stream: true`.
- At most 50,000 requests.
- The file must not be empty.

If any line fails validation the batch is still created, but with `status: "failed"` and an `errors` list (at most 20 entries) with `code`, `message`, `param` and `line`. Nothing runs.

## Batch object

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

Statuses: `validating`, `failed`, `in_progress`, `finalizing`, `completed`, `expired`, `cancelling`, `cancelled`. A batch whose input validated stays `validating` until the worker picks it up. The `batch-...` spelling of an id is accepted and mapped to `batch_...`.

## Results

When the batch ends, successful lines are written to the output file and non-2xx lines to the error file. Both are normal files in the store (purposes `batch_output` and `batch_error`); a file is only created when it has content. Fetch them with `GET /v1/files/{file_id}/content` using `output_file_id` and `error_file_id`.

Each result line:

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

If a request could not be sent at all (transport failure), the line has `response: null` and `error: {"code": "request_failed", "message": ...}` and is counted as failed.

## List and cancel

`GET /v1/batches` takes `limit` (1 to 100, default 20) and `after` (a batch id) and returns `{"object": "list", "data", "first_id", "last_id", "has_more"}`, newest first.

`POST /v1/batches/{batch_id}/cancel` moves a `validating` or `in_progress` batch to `cancelling`; the worker stops before its next line and the batch ends as `cancelled`. Cancelling an already-cancelling batch returns it unchanged. Any other state returns `409` with code `invalid_state`. Lines already completed keep their results.

## Examples

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

## Errors

OpenAI dialect: `{"error": {"message", "type", "param", "code"}}`.

| Status | Code | When |
| --- | --- | --- |
| `400` | `missing_required_parameter` | No `input_file_id`. |
| `400` | `invalid_value` | Bad `endpoint`, `completion_window` other than `24h`, bad `metadata`, input file with a purpose other than `batch`, unknown input file. |
| `404` | `batch_not_found` | Unknown batch id. |
| `409` | `invalid_state` | Cancelling a finished batch. |

## Anthropic message batches

The Anthropic Message Batches routes (`POST /v1/messages/batches` and friends) share the same worker, store and 24 hour window, and are covered on the [Messages](/docs/api/messages) page. Differences: requests are sent inline (`requests` array with `custom_id` and `params`), at most 100,000 per batch, results are streamed as JSONL from `GET /v1/messages/batches/{batch_id}/results`, and ended batches can be deleted with `DELETE /v1/messages/batches/{batch_id}`.

## Support

| Feature | Status |
| --- | --- |
| Create, retrieve, list, cancel | <Support status="supported">supported</Support> |
| Endpoints `/v1/chat/completions`, `/v1/completions`, `/v1/embeddings`, `/v1/responses` | <Support status="supported">supported</Support> |
| Resume after restart | <Support status="supported">unfinished batches continue</Support> |
| Parallel execution of lines | <Support status="unsupported">lines run one at a time</Support> |
| Streaming lines | <Support status="unsupported">rejected at creation</Support> |
| Completion windows other than `24h` | <Support status="unsupported">rejected</Support> |
| Other endpoints (for example `/v1/images/generations`) | <Support status="unsupported">rejected</Support> |
| Deleting an OpenAI batch | <Support status="unsupported">no delete route</Support> |

## Related

- [Files](/docs/api/files) for uploading input and downloading output.
- [Messages](/docs/api/messages) for the Anthropic batch routes.
- [Chat completions](/docs/api/chat-completions), [Responses](/docs/api/responses) and [Embeddings](/docs/api/embeddings) for the request bodies.


---

<!-- api/chat-completions -->
---
title: Chat completions
description: The OpenAI Chat Completions endpoint, with tools, structured output, logprobs, reasoning, image/audio/video input and streaming, plus the legacy text completions endpoint.
---

`POST /v1/chat/completions` follows the OpenAI Chat Completions format, so the official `openai` SDKs, LangChain, LiteLLM and most agent tools work by changing the base URL. Text-only `mlx-lm` models and vision-language `mlx-vlm` models are served by the same route; a request that contains an image, audio or video part is routed to a VLM. `POST /v1/completions` is the legacy prompt-in, text-out endpoint and is documented at the end of this page.

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

<Callout type="info">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. See [API overview](/docs/api/overview). In single-model mode the `model` value is advisory; in multi-model mode it selects the model.
</Callout>

## Request

Unknown top-level fields are ignored, so a client can keep sending OpenAI fields Yunshu has no use for (`service_tier`, `modalities`, `prediction`, `web_search_options`, `safety_identifier` and so on). A JSON `null` on any optional field means "not set" and the default applies. A negative `top_k` (the vLLM spelling of "disabled") becomes `0`.

### Core fields

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Model id. Advisory in single-model mode. | supported |
| `messages` | array | yes | Conversation. Must contain at least one `user` message with content. See [Messages](#messages). | supported |
| `stream` | boolean | no | Server-sent events. Default `false`. | supported |
| `stream_options` | object | no | Only valid with `stream: true`. `include_usage` adds a final usage chunk. `continuous_usage_stats` (a vLLM extension) puts a running `usage` on every chunk. | supported |
| `max_tokens` | integer | no | Completion limit, `0` to `1048576`. Omitted: the model's output limit (262144, the Qwen3.8 card's thinking-mode figure; the OpenAI reference says "up to the model's limit"), lowered only by the operator cap `YUNSHU_DEFAULT_MAX_TOKENS`. The context window still clamps it; `x_yunshu.budget` reports the effective value and its source (`max_tokens_source`: `request`, `model_limit`, `operator_cap`). | supported |
| `max_completion_tokens` | integer | no | OpenAI's newer name. Wins over `max_tokens` when both are set. | supported |
| `n` | integer | no | Number of choices, `1` to `128`. With `stream: true` every chunk carries its choice `index`; the choices stream one after another (one request at a time on the text path; concurrently on vision-language models) and `seed` derives a per-choice seed (`seed + index`) exactly as without streaming. Usage in the final chunk is the prompt once plus all completions. | supported |
| `stop` | string or array | no | Up to 16 stop sequences. Empty strings are dropped. | supported |
| `user` | string | no | Logged with the request id. No other effect. | accepted and ignored |
| `store` | boolean | no | Keep the finished completion for retrieval. See [Stored completions](/docs/api/stored-completions). | supported |
| `metadata` | object | no | Up to 16 string pairs, stored with the completion when `store` is true. | supported |
| `keep_alive` | string or number | no | Ollama-style residency hint (`"5m"`, `300`, `-1`, `0`). Applies in multi-model mode. | extension |
| `timeout` | number | no | Seconds, `1` to `600`. Ends generation with a partial answer and `finish_reason: "length"`. | extension |

### Sampling

| Parameter | Type | Default | Description | Status |
| --- | --- | --- | --- | --- |
| `temperature` | number | `0.7` | `0` to `2`. Note the default differs from OpenAI's `1.0`. | supported |
| `top_p` | number | `1.0` | `0` to `1`. | supported |
| `top_k` | integer | `0` | `0` disables. | supported |
| `min_p` | number | `0.0` | `0` to `1`. | supported |
| `repetition_penalty` | number | `1.0` | `0` to `2`. Not an OpenAI field: it follows mlx-lm and looks at the last 20 prompt and generated tokens. | supported |
| `frequency_penalty` | number | `0.0` | `-2` to `2`. As OpenAI: counts every generated token (the prompt is not counted). | supported |
| `presence_penalty` | number | `0.0` | `-2` to `2`. As OpenAI: applies once a token has been generated. | supported |
| `logit_bias` | object | none | Map of token id to bias, each `-100` to `100`. Keys are token ids as strings. | supported |
| `seed` | integer | none | 64-bit signed. Makes sampling reproducible. | supported |
| `top_n_sigma` | number | `0.0` | `0` to `10`. Keeps tokens whose logit is within n sigma of the maximum; `0` is off. | extension |
| `xtc_probability`, `xtc_threshold` | number | `0.0` | XTC sampler. Probability `0` to `1`, threshold `0` to `0.5`. | extension |
| `min_tokens` | integer | `0` | Mask end-of-sequence until this many tokens exist. | extension |
| `ignore_eos` | boolean | `false` | Keep generating past end-of-sequence up to `max_tokens`. | extension |
| `suppress_tokens` | array of integer | none | Token ids that may never be produced. | extension |
| `stop_token_ids` | array of integer | none | Up to 16 token ids that end generation. | extension |
| `spec_decode` | boolean | `false` | Ask for speculative decoding on this request. Takes effect only where the model and path have a drafter; otherwise ignored. | partial |
| `priority` | integer | `0` | `0` to `100`. Forwarded to the engine as a request priority. | partial |
| `lora_adapter` | string | none | LoRA adapter id for this request. Text models only; a VLM answers `400`. | partial |
| `logits_processors` | array | none | Custom logits processors. A VLM answers `400`. | partial |

### Messages

Each message has a `role` of `system`, `developer`, `user`, `assistant`, `tool` or `function`. Any other role is a `400`.

| Field | Type | Description | Status |
| --- | --- | --- | --- |
| `content` | string, array or null | Text, or an array of content parts. Whitespace-only text and empty arrays are rejected on `system`, `developer` and `user` messages. | supported |
| `tool_calls` | array | On `assistant` messages: calls the model made earlier, with `id`, `type` and `function.name` / `function.arguments`. | supported |
| `tool_call_id` | string | Required on `tool` messages. | supported |
| `name` | string | Function name on `tool` messages. | supported |
| `reasoning_content` or `reasoning` | string | Earlier reasoning on `assistant` messages, passed back to the chat template. | extension |

Content parts:

| Part `type` | Shape | Notes |
| --- | --- | --- |
| `text` | `{"type": "text", "text": "..."}` | May carry a `prompt_cache_breakpoint` object; see [Prompt caching](/docs/guides/prompt-caching). |
| `image_url` | `{"type": "image_url", "image_url": {"url": "..."}}` | `http`, `https` and `data:` URLs. `file://` URLs and URLs that point at loopback, private or link-local hosts are rejected with `400`. `detail` is accepted and advisory; the pixel budget comes from the model's processor. `image` and `image_data` parts are normalized to this shape. |
| `input_audio` | `{"type": "input_audio", "input_audio": {"data": "<base64>", "format": "wav"}}` | Routes to a model that accepts audio input. |
| `audio_url` | `{"type": "audio_url", "audio_url": {"url": "..."}}` | As above. |
| `video_url`, `video_file` | OpenAI-style video part | Routes to a model that accepts video input. |

A model that does not accept the modality of a part answers `400` naming the part, for example `messages.content[type=image_url]: this model accepts text input, not image`. A request with media for a model that is not a vision-language model answers `400` as well.

### Tools

| Parameter | Type | Description | Status |
| --- | --- | --- | --- |
| `tools` | array | Function tools: `{"type": "function", "function": {"name", "description", "parameters"}}`. | supported |
| `tool_choice` | string or object | `auto`, `none`, `required`, or `{"type": "function", "function": {"name": "..."}}`. `required` and a named function need a non-empty `tools`, and the name must be in `tools`. The `allowed_tools` form is folded into `tools` plus a mode. | supported |
| `parallel_tool_calls` | boolean | Default `true`. With `false`, at most one call is returned. | supported |

When the model's chat template renders tools natively, Yunshu hands the tools to the template; otherwise it injects a tool prompt and parses the calls from the output. `yunshu.contract.tools.mode` on the model card says which (`template` or `prompt`). Calls come back in `message.tool_calls` with `finish_reason: "tool_calls"`. After generation the server enforces `tool_choice: "none"` (no calls are returned), a named function (calls to other functions are dropped) and `parallel_tool_calls: false` (only the first call is kept). A call the model did not make is never invented. String argument values are coerced to the types in your `parameters` schema. On a VLM, tools cannot be combined with `response_format` or `grammar`; that request is a `400`.

### Structured output

| Parameter | Description | Status |
| --- | --- | --- |
| `response_format` | `{"type": "text"}`, `{"type": "json_object"}` or `{"type": "json_schema", "json_schema": {"name", "schema", "strict"}}`. `json_schema` requires the `json_schema` object. With `strict: true`, `additionalProperties: false` is added to object schemas. Any other `type` is a `400`. | supported |
| `grammar` | Native constraint: `{"type": "json", "schema": {...}}`, `{"type": "regex", "pattern": "..."}`, `{"type": "choice", "choices": [...]}` or `{"type": "cfg", "grammar": "..."}`. Wins over `response_format`. | extension |
| `guided_json`, `guided_regex`, `guided_choice`, `guided_grammar` | vLLM spellings of the same constraints. `guided_regex` is limited to 2048 characters and `guided_grammar` to 32768. | extension |
| `structured_outputs` | vLLM object with exactly one of `json`, `regex`, `choice`, `grammar`, `json_object`. `structural_tag` is not supported. | extension |

Constrained decoding masks the logits, so output that matches the schema is produced from the first token. A schema or pattern the engine cannot compile is a `400`. See [Structured output](/docs/guides/structured-output).

### Reasoning

| Parameter | Description | Status |
| --- | --- | --- |
| `enable_thinking` | Turn the model's thinking mode on or off. Also read from `chat_template_kwargs.enable_thinking`. | supported |
| `reasoning_effort` | Effort level. Also read from `chat_template_kwargs.reasoning_effort`. Values outside the template's own list are mapped (`high` becomes `xhigh` on templates that use it). `none` and `minimal` turn thinking off (as `enable_thinking: false`). Any other value is passed to the model's chat template as its own `reasoning_effort` variable (Qwen3.8: `low`, `medium`, `xhigh`); a value the template does not list is mapped onto its levels (`high` and `max` become `xhigh`). It is never turned into a thinking-token cap: use `thinking_budget` for a cap. A template without the variable ignores it, as does a model without a reasoning mode. | supported |
| `thinking_budget` | Maximum thinking tokens, `1` to `262144` (the model's thinking limit). | extension |
| `chat_template_kwargs` | Extra variables for the chat template. | supported |

Reasoning text is returned in `message.reasoning_content`, separate from `content`. The reasoning tokens are part of `completion_tokens`, and `usage.completion_tokens_details.reasoning_tokens` says how many.

### Logprobs

| Parameter | Type | Description | Status |
| --- | --- | --- | --- |
| `logprobs` | boolean | Return per-token log probabilities in `choices[].logprobs.content`. | supported |
| `top_logprobs` | integer | `0` to `20` alternatives per token. Requires `logprobs: true`. | supported |
| `prompt_logprobs` | integer | Per-token logprobs for the prompt, returned in `choices[].prompt_logprobs`. | extension |

### Caching

| Parameter | Description | Status |
| --- | --- | --- |
| `prompt_cache_key`, `prompt_cache_retention`, `prompt_cache_options` | OpenAI prompt-cache hints. Used on the vision-language path; accepted and ignored on text-only models, whose prefix cache is automatic. | partial |

## Examples

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

### Streaming

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

### Tool calling

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

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

### Image input

Use a vision-language model such as a Qwen3.5 VLM checkpoint.

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

### Reasoning

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

## Response

```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` is present only when the model produced reasoning. `tool_calls` replaces or accompanies `content` when the model called a tool; each call has `id` (`call_...`), `type: "function"` and `function.name` / `function.arguments` (a JSON string).
- `finish_reason` is `stop`, `length` or `tool_calls`. Internal reasons are mapped: a cancel or error to `stop`, a timeout or memory limit to `length`.
- `usage.completion_tokens` already includes reasoning tokens; `reasoning_tokens` and `cached_tokens` are details inside their totals, never extra. `cached_tokens` is the prompt prefix served from the prefix cache.
- `choices[].logprobs.content[]` items are `{token, logprob, bytes, top_logprobs: [{token, logprob, bytes}]}`.
- `x_yunshu` is the Yunshu extension described in [API overview](/docs/api/overview). `mcp_tool_results` appears when a returned tool call matched a tool of a configured MCP client and was executed by the gateway.
- `max_tokens` and `max_completion_tokens` below 1 answer `400`, as OpenAI does (only `/v1/completions` takes 0, for echo-only scoring). To count a prompt, POST the same `messages` to `/tokenize`: `count` is the prompt length generation would run.
- If a structured-output result still fails validation on a VLM, the answer is a `422` with `x_yunshu.validation`.

## Streaming

With `stream: true` the response is `text/event-stream`. Every event is `data: <json>` followed by a blank line.

1. The first chunk carries `delta: {"role": "assistant", "content": null}`.
2. Content chunks carry `delta.content`. Reasoning arrives first as `delta.reasoning_content`, then the answer.
3. Tool calls stream as `delta.tool_calls`: one chunk with `index`, `id`, `type` and `function.name`, then chunks with `function.arguments` fragments for the same `index`.
4. A chunk with the `finish_reason` and an empty delta ends the choice.
5. With `stream_options.include_usage`, one more chunk follows with `choices: []` and the `usage` object, and the `x_yunshu` stats.
6. `data: [DONE]` ends the stream.

Chunks have `object: "chat.completion.chunk"`. Between chunks the server may send SSE comment lines (`: keep-alive`, `: yunshu-progress {...}` while a long prompt prefills). Comments are ignored by SSE parsers. If generation fails after the stream started, the stream carries a single `data: {"error": {...}}` event and then `[DONE]`.

## Errors

| Status | When |
| --- | --- |
| 400 | Schema or value validation (`code: validation_error`, `param` names the field), an unsupported capability for the model, a bad image URL, a prompt that exceeds the context window, a malformed `response_format` or `grammar`. |
| 401 | Token configured and missing or wrong. |
| 404 | Unknown model in multi-model mode. |
| 429 | The queue is full, with `Retry-After`. |
| 500 | Engine failure (`server_error`). |
| 503 | No model loaded, a model still loading, or memory pressure with other requests running. |
| 504 | The `X-Yunshu-Deadline-Ms` deadline passed. |
| 507 | Out of GPU memory (`type: memory_error`). |

## Support

| Feature | Status |
| --- | --- |
| Text, system, developer, tool messages | <Support status="supported">supported</Support> |
| Image input | <Support status="supported">vision-language models</Support> |
| Audio and video input parts | <Support status="partial">models that accept them</Support> |
| Streaming, `stream_options.include_usage` | <Support status="supported">supported</Support> |
| `n` greater than 1 | <Support status="supported">streaming and non-streaming, chunks carry `index`</Support> |
| Function tools, `tool_choice`, `parallel_tool_calls` | <Support status="supported">supported</Support> |
| `response_format` `json_object` and `json_schema` | <Support status="supported">constrained decoding</Support> |
| `logprobs`, `top_logprobs` | <Support status="supported">up to 20 alternatives</Support> |
| `reasoning_effort`, `enable_thinking`, `reasoning_content` | <Support status="supported">models with a reasoning mode</Support> |
| `store`, `metadata` | <Support status="supported">see Stored completions</Support> |
| `user`, `service_tier`, `modalities`, `prediction` | <Support status="unsupported">accepted and ignored</Support> |
| Audio output (`audio` request field) | <Support status="unsupported">not supported; use the audio routes</Support> |
| LoRA and custom logits processors on a VLM | <Support status="unsupported">400</Support> |

## Legacy text completions

`POST /v1/completions` takes a raw prompt and returns text, with no chat template. It supports the same sampling parameters as the chat route, `stream`, `stream_options`, `stop`, `seed`, `logit_bias`, `response_format` and the `grammar` / `guided_*` constraints, `logprobs`, `n`, `echo` and `best_of`. Reasoning and tool parameters do not exist here.

| Parameter | Type | Description | Status |
| --- | --- | --- | --- |
| `model` | string | Model id. | supported |
| `prompt` | string, array of strings, array of token ids, or array of token-id arrays | Required. An array of strings or token-id arrays produces choices for each prompt, in order. Not allowed with `stream: true` when it has more than one prompt. | supported |
| `max_tokens` | integer | Default `16` (the OpenAI completions reference), up to `1048576`. `max_completion_tokens` is also accepted. | supported |
| `echo` | boolean | Prepend the prompt to the returned text. With `logprobs` the prompt tokens get logprobs too (single string prompt). | supported |
| `logprobs` | integer | `0` to `5`. The response uses the legacy `tokens`, `token_logprobs`, `top_logprobs`, `text_offset` arrays. | supported |
| `best_of` | integer | Generates this many candidates per prompt and returns the `n` with the best average logprob. Must be at least `n`; not with streaming or several prompts. All candidates are billed in `usage`. | supported |
| `n` | integer | `1` to `128`. With `stream: true` the chunks carry `choices[].index`, as on the chat route. | supported |
| `suffix` | string | Accepted. There is no fill-in-the-middle template, so it is not used and never appended to the text. | accepted and ignored |
| `stop`, `seed`, `temperature`, `top_p`, `top_k`, `min_p`, penalties, `logit_bias`, `stream_options` | | As on the chat route. | supported |

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

Streaming uses `object: "text_completion"` chunks with `choices[].text`, then the optional usage chunk and `[DONE]`. Errors have the same shapes as on the chat route. The model's capability contract is enforced here too (`response_format`, `grammar` and `logprobs` on a model that does not generate text are a `400`).

## Related

- [Stored completions](/docs/api/stored-completions)
- [Responses](/docs/api/responses)
- [Structured output](/docs/guides/structured-output)
- [Prompt caching](/docs/guides/prompt-caching)
- [Models and the capability contract](/docs/api/models)
- [Extensions](/docs/api/extensions)


---

<!-- api/decisions -->
---
title: Decisions
description: Typed questions (yes/no, pick one, ordinal score) answered with probabilities from a decision-head model in a single forward pass, with no generated text.
---

A decision model answers structured questions about some input without writing any text. You send an input and a list of typed questions. The model reads the input and the question schema once, and returns a probability for each answer. This is different from chat completion and from JSON-schema constrained decoding: nothing is generated, so output tokens are always zero and latency is one prefill.

Use it for routing, classification, guardrail checks and scoring, where you want calibrated probabilities rather than a sampled answer.

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

`POST /v1/systemone` is a second wire format for the same engine, described under [Extensions](/docs/api/extensions).

<Callout type="info">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. The route is stateless and non-streaming.
</Callout>

## Decision models

The route needs a decision checkpoint, which is a backbone plus a trained decision head. Yunshu loads the Cloudflare Clef joint schema head in MLX format, including Clef-flash. The checkpoint is detected from its files; if you load one, it is classified as a decision model instead of a chat model.

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

Other decision-head families are not supported, and a checkpoint with an unknown head fails to load. Asking a chat model for a decision returns `400`. Images require a vision-capable checkpoint (the `vision` extra); on a text-only checkpoint, requests with images return `400`.

## Request

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Decision model id (single-model mode: the served model). | supported |
| `input` | string or array | yes | Text, or user messages. See below. | supported |
| `questions` | array | yes | 1 to 128 questions. Answers come back in the same order. | supported |
| `safety_identifier` | string | no | Up to 64 characters. | accepted and ignored |

Unknown top-level keys are ignored, so SDK `extra_body` fields do not break the call. Question objects are strict: unknown keys inside a question or message are rejected with `400`.

### Input

A string, or an array of messages `{"role": "user", "content": ...}` where `content` is a string or a list of parts:

| Part | Fields | Notes |
| --- | --- | --- |
| `input_text` | `text` | Texts are joined with newlines. |
| `input_image` | `image_url`, optional `detail` | Must be an inline `data:image/...;base64,...` URL. External URLs and file ids are rejected. At most 128 images. |

The text may be at most 1,000,000 characters, and the combined input and schema length must fit in 16,384 tokens. Overflow is rejected, not truncated. Only the `user` role is allowed.

### Questions

| `type` | Fields | Answer |
| --- | --- | --- |
| `predicate` | `instructions`, optional `name` | A yes/no probability. |
| `choice` | `instructions`, `choices` (2 to 64 of `{"value", "description"?}`), optional `name` | The most likely `value`, its confidence, and all probabilities. `value` is a string or boolean and must be distinct (the boolean `true` collides with the string `"true"`). |
| `score` | `instructions`, `levels` (2 to 64 of `{"label", "description"?}`), optional `name` | The expected zero-based level index, confidence and per-level probabilities. The head reads the level `description` (the `label` when there is none), and labels must be distinct. |

Names, when given, must be unique.

## Response

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

If the head returns a non-finite result for a question, that answer is `{"type": "refusal", "name": ...}`. A probability is never made up. `usage.input_tokens` is the prefill length; `cached_tokens` is always 0.

## Examples

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

The `decisions` resource needs a recent `openai` SDK. With an older SDK, post the same JSON body with `httpx` or `requests`.

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

## Errors

Errors use the OpenAI envelope `{"error": {"message", "type", "param", "code"}}`.

| Status | When |
| --- | --- |
| `400` | Invalid JSON or schema, empty input, duplicate names or choices, fewer than 2 choices or levels, external image URL, images sent to a text-only checkpoint, the model is not a decision model, input over 16,384 tokens. |
| `404` | The model is not found or not loaded. |
| `507` | Out of GPU memory. |
| `500` | The decision failed. |

## Support

| Feature | Status |
| --- | --- |
| Predicate, choice and score questions | <Support status="supported">supported</Support> |
| Image input (inline base64) | <Support status="partial">vision-capable checkpoints only</Support> |
| Cloudflare Clef checkpoints in MLX format | <Support status="supported">supported</Support> |
| Other decision-head families | <Support status="unsupported">fail to load</Support> |
| Streaming, prompt caching, stored state | <Support status="unsupported">stateless, one forward pass</Support> |
| `safety_identifier` | <Support status="unsupported">accepted and ignored</Support> |

## Related

- [Extensions](/docs/api/extensions) for the System One wire format on `POST /v1/systemone`.
- [Structured output](/docs/guides/structured-output) when you need generated text that follows a JSON schema instead.
- [Models](/docs/getting-started/models) for loading checkpoints.


---

<!-- api/embeddings -->
---
title: Embeddings
description: The OpenAI embeddings endpoint for text and multimodal embedding models, plus the vLLM-style pooling endpoint that returns raw pooled vectors.
---

`POST /v1/embeddings` follows the OpenAI embeddings format: you send text (or token ids) and get one vector per input. With a multimodal embedding checkpoint the same route also embeds images, audio and video. `POST /v1/pooling` is the vLLM-style companion that returns pooled hidden states without normalization.

Embedding models are separate checkpoints from chat models. In multi-model mode name the embedder in `model`; in single-model mode the loaded model has to be the embedder. `GET /v1/models` shows `yunshu.kind: "embedding"` and the vector size under `yunshu.embeddings`.

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

<Callout type="info">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. See [API overview](/docs/api/overview).
</Callout>

## Request

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Embedding model id. | supported |
| `input` | string, array of strings, array of integers, array of integer arrays, or array of objects | yes (or `messages`) | Text to embed. A string array embeds each string. An integer array is one text given as token ids; an array of integer arrays is several. Objects (`{"text": ..., "image": ...}`) are for multimodal embedders. | supported |
| `messages` | array | no | vLLM-style chat messages holding text, `image_url`, `input_audio`, `audio_url` or `video` parts, turned into one multimodal item. Use instead of `input`, not with it. | extension |
| `encoding_format` | string | no | `float` (default) or `base64` (little-endian float32 packed, then base64). | supported |
| `dimensions` | integer | no | `1` to `8192`. Truncates the vector to this many leading values and re-normalizes it (Matryoshka style). Asking for more than the model's native size is a `400`. | supported |
| `pooling_type` | string | no | `MEAN`, `CLS` or `LAST` (case-insensitive). Overrides the model's own pooling. Applies to text models that can pool; the result is L2-normalized. | extension |
| `instruction` | string | no | Text models: prefixed to every input as `instruction`, a newline, then the text. Multimodal models: passed to the embedder as its instruction. | extension |
| `task` | string | no | Multimodal embedders only: the embedder's task name. An unknown task is a `400`. | extension |
| `user` | string | no | Accepted for compatibility. | accepted and ignored |

Limits: at most 2048 inputs per request and 65536 characters per text. Lists must be homogeneous (all strings, or all token ids, or all token-id lists). Empty and whitespace-only inputs are rejected.

Vectors are L2-normalized unless the model returns something else; non-finite values are replaced by `0`.

## Examples

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

### Multimodal input

With a multimodal embedding model each `input` item is a string or an object with `text`, `image`, `audio` or `video` keys (at least one). Images are URLs or data URIs.

```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"}
    ]
  }'
```

The chat-message form puts media in order inside one item:

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

Text-only embedding models reject object items and `messages` with a `400`.

## Response

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

The vectors above are shortened; real vectors have the model's full dimension (or `dimensions`). With `encoding_format: "base64"`, `embedding` is a base64 string instead of an array. For text models `usage` counts the input tokens, special tokens excluded. For multimodal models it is the token count the embedder reports, or the number of items when it does not.

## Pooling

`POST /v1/pooling` returns the pooled hidden state of each input, not normalized, for tools that do their own post-processing.

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | string | yes | Embedding model id. |
| `input` | string or array of strings | yes | Up to 2048 texts of at most 8192 characters. |
| `pooling_type` | string | no | `CLS` (default), `MEAN` or `LAST`. |
| `encoding_format` | string | no | `float` (default) or `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 }
}
```

Multimodal embedding models are not served by `POST /v1/pooling` (`400`); use `POST /v1/embeddings` for them. A model that cannot produce embeddings (for example a hybrid chat architecture) answers `400` with a message that says so.

## Errors

| Status | When |
| --- | --- |
| 400 | Validation failures (empty input, mixed list types, `encoding_format` or `pooling_type` out of range, too many inputs, `dimensions` over the native size); media sent to a text-only embedder; a bad `task`. |
| 401 | Token configured and missing or wrong. |
| 404 | The embedding model is not found. |
| 422 | A list entry is empty, or a token-id list holds a non-integer. |
| 507 | Out of GPU memory. |
| 500 | Embedding generation failed (`server_error`). |

## Support

| Feature | Status |
| --- | --- |
| String, string-array and token-id input | <Support status="supported">supported</Support> |
| `encoding_format` `float` and `base64` | <Support status="supported">supported</Support> |
| `dimensions` (truncate and re-normalize) | <Support status="supported">supported</Support> |
| Multimodal input (image, audio, video) | <Support status="partial">multimodal embedding models only</Support> |
| `pooling_type`, `instruction`, `task`, `messages` | <Support status="extension">extension</Support> |
| A chat model used as an embedder | <Support status="partial">falls back to mean-pooled hidden states, which are not trained for retrieval; load an embedding checkpoint instead</Support> |
| `user` | <Support status="unsupported">accepted and ignored</Support> |
| Embeddings on the Neural Engine | <Support status="partial">opt-in with `YUNSHU_ANE_EMBEDDINGS` for the configured embedding model; see [Configuration](/docs/guides/configuration)</Support> |

## Related

- [Rerank and scoring](/docs/api/rerank)
- [Models](/docs/api/models)
- [Model support](/docs/guides/model-support)
- [Ollama layer](/docs/api/ollama)


---

<!-- api/evals -->
---
title: Evals
description: The OpenAI Evals API on a local store - define graders, run them over JSONL or stored completions, and read per-item results.
---

The `/v1/evals` routes follow the OpenAI Evals API. An eval describes a data schema and a list of graders (`testing_criteria`). A run feeds rows through those graders, optionally sampling a model first, and records an output item per row plus pass/fail counts. Everything is stored as JSON under `~/.yunshu/evals` (`YUNSHU_EVALS_DIR` changes the directory).

Runs execute inside the server process in the background. Sampling and model-based graders call this server's own Chat Completions route in-process, so they use the same loaded models, auth and sampling behaviour as normal requests.

<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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. A run keeps the `Authorization` or `x-api-key` header of the request that created it in memory only (never written to disk) and uses it for its internal calls.
</Callout>

## Create an eval

`POST /v1/evals` takes a JSON body that must also pass the OpenAI SDK's `EvalCreateParams` type check.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `name` | string | no | Display name. | supported |
| `metadata` | object | no | Up to 16 string key-value pairs. | supported |
| `data_source_config` | object | yes | `{"type": "custom", "item_schema": {...}, "include_sample_schema": bool}`. `type` may also be `stored_completions` or `logs`. | partial |
| `testing_criteria` | array | yes | Non-empty list of graders, with unique non-empty `name` values. | supported |

`custom` requires `item_schema`, which must be a valid JSON Schema (Draft 2020-12); every row's `item` is validated against it when a run is created. The stored `data_source_config` is returned as `{"type", "schema"}` where `schema` wraps your `item_schema` under `item` (and adds a `sample.output_text` property when `include_sample_schema` is true).

### Graders

| Grader `type` | Fields | What it does |
| --- | --- | --- |
| `string_check` | `name`, `input`, `reference`, `operation` (`eq`, `ne`, `like`, `ilike`) | Compares two template strings. `like` means `reference` is a substring of `input`; `ilike` ignores case. Score is 1 or 0. |
| `text_similarity` | `name`, `input`, `reference`, `evaluation_metric`, `pass_threshold` | Lexical similarity computed locally with no model. Metrics: `cosine`, `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1` to `rouge_5`, `rouge_l`. Passes when the score reaches `pass_threshold`. |
| `score_model` | `name`, `model`, `input` (messages), optional `range` (default `[0, 1]`), `pass_threshold`, `sampling_params` | A model returns a number in `range`; passes when the score reaches `pass_threshold` (default 1). |
| `label_model` | `name`, `model`, `input` (messages), `labels`, `passing_labels`, `sampling_params` | A model returns one of `labels`; passes when the label is in `passing_labels`. |

Grader fields are templates: `{{item.field}}` and `{{sample.output_text}}` placeholders are replaced from the row (nested paths and list indexes use dots). An unknown reference fails that row with an error. The lexical metrics are Yunshu's own implementations: cosine uses token frequencies, METEOR uses exact-token alignment without a synonym corpus, and BLEU is sentence BLEU without smoothing, so scores can differ slightly from other implementations.

Model graders ask for structured JSON output (a `score` number or a `label` string) through the local `response_format` JSON Schema path, then validate it.

Any other grader type, such as `python` or `endpoint`, returns `400`.

## Update, list, delete evals

- `POST /v1/evals/{eval_id}` updates `name` and `metadata`.
- `GET /v1/evals` takes `limit` (1 to 100, default 20), `order` (`asc` or `desc`, default `desc`), `after` and `order_by` (`created_at` or `updated_at`).
- `DELETE /v1/evals/{eval_id}` deletes the eval, cancels and removes all its runs, and returns `{"object": "eval.deleted", "deleted": true, "eval_id": ...}`.

Lists return `{"object": "list", "data", "has_more", "first_id", "last_id"}`. An unknown `after` cursor returns `400`.

## Create a run

`POST /v1/evals/{eval_id}/runs` takes a body validated against the SDK's `RunCreateParams`:

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `name`, `metadata` | | no | Display name and up to 16 string pairs. | supported |
| `data_source.type` | string | yes | `jsonl` (grade the rows as given) or `completions` (sample a model first). Other types return `400`. | partial |
| `data_source.source` | object | yes | Where the rows come from, see below. | supported |
| `data_source.model` | string | no | With `type: "completions"`, the model to sample. Without it the rows' own `sample` is graded. | supported |
| `data_source.input_messages` | object | with `model` | `{"type": "template", "template": [messages]}` or `{"type": "item_reference", "item_reference": "item.input"}`. | supported |
| `data_source.sampling_params` | object | no | Passed to Chat Completions (`temperature`, `top_p`, `seed`, `max_completion_tokens`, ...). | supported |

Row sources (`data_source.source.type`):

| Source | Fields | Notes |
| --- | --- | --- |
| `file_content` | `content`: array of `{"item": {...}, "sample": {...}}` | Inline rows. |
| `file_id` | `id` of a file in the [Files](/docs/api/files) store | JSONL file, one row per line, same row shape. |
| `stored_completions` | optional `model`, `metadata`, `created_after`, `created_before`, `limit` | Rows built from Chat Completions stored by this server (see [Stored completions](/docs/api/stored-completions)). `limit` is 1 to 10000. |

At most 10,000 rows; every `item` must match the eval's `item_schema`. A bad source fails the create call with `400` before anything runs.

The call returns the run immediately with `status: "queued"`; the work happens in the background.

```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` values: `queued`, `in_progress`, `completed`, `canceled`, `failed`. Rows are processed one at a time. A restart fails runs that were queued or in progress (`error.code` is `interrupted`); create a new run to retry. `report_url` is always empty.

## Runs and output items

- `GET /v1/evals/{eval_id}/runs` takes `status`, `limit`, `order` (default `asc`) and `after`.
- `GET /v1/evals/{eval_id}/runs/{run_id}` returns the run with its running counts and per-model token usage.
- `POST /v1/evals/{eval_id}/runs/{run_id}/cancel` cancels a queued or in-progress run (status becomes `canceled`); finished runs are returned unchanged.
- `DELETE /v1/evals/{eval_id}/runs/{run_id}` cancels and deletes it and returns `{"object": "eval.run.deleted", "deleted": true, "run_id": ...}`.
- `GET .../output_items` lists items; `status` filters on `pass` or `fail`. `GET .../output_items/{output_item_id}` returns one.

An 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` is `pass` when every grader passed, `fail` when at least one did not, and `error` when the row failed (for example a template reference was missing or a model call failed); the message is in `sample.error`. Error items are counted under `result_counts.errored` and are not returned by the `pass`/`fail` filter.

## Examples

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

## Errors

Errors use the OpenAI envelope with codes such as `invalid_value`, `invalid_type`, `not_found` and `unsupported_value`.

| Status | When |
| --- | --- |
| `400` | Body does not match the SDK types, unsupported `data_source_config`, grader or data source type, invalid JSON Schema, bad template, more than 10,000 rows, a row that violates `item_schema`, bad pagination or filter value. |
| `404` | Unknown eval, run, output item or file. |

Failures that happen while a run executes do not change the HTTP status. They appear as `error` output items, or as `status: "failed"` with `error` on the run.

## Support

| Feature | Status |
| --- | --- |
| Eval CRUD, runs, output items, cancel | <Support status="supported">supported</Support> |
| Graders `string_check`, `text_similarity`, `score_model`, `label_model` | <Support status="supported">supported</Support> |
| Graders `python`, `endpoint`, `multi` | <Support status="unsupported">rejected with 400</Support> |
| Run data sources `jsonl` and `completions` | <Support status="supported">supported</Support> |
| Run data sources `responses`, `logs` and others | <Support status="unsupported">rejected with 400</Support> |
| `data_source_config.type: "logs"` | <Support status="partial">accepted for the eval, but no run source reads logs</Support> |
| Parallel rows | <Support status="unsupported">rows run one at a time</Support> |
| Resuming a run after restart | <Support status="unsupported">interrupted runs are marked failed</Support> |
| `report_url` | <Support status="unsupported">always empty</Support> |

## Related

- [Files](/docs/api/files) for uploading JSONL rows with `purpose=evals`.
- [Stored completions](/docs/api/stored-completions) for the completions that `stored_completions` sources read.
- [Chat completions](/docs/api/chat-completions) for the sampling that runs use.


---

<!-- api/extensions -->
---
title: Extensions
description: Everything Yunshu adds on top of the OpenAI, Anthropic and Ollama APIs - status, warmup, cancellation, per-response stats, a multiplexed WebSocket, native speech, and System One.
---

Yunshu's extensions are additive and namespaced, so the official SDKs keep working unchanged. They show up in three places:

- JSON: a top-level `x_yunshu` object on responses (or inside `usage` on Messages and Responses), and `error.x_yunshu` on errors. The OpenAI SDKs keep unknown fields in `model_extra`; the Anthropic and Ollama SDKs ignore them.
- SSE: comment lines such as `: yunshu-progress {...}`. Every SSE parser skips comments.
- Headers: `X-Request-Id` and `X-Yunshu-*`.

Authentication follows the normal rule: only enforced when `YUNSHU_AUTH_TOKEN` is set.

<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" />

The request-inspection routes `GET /v1/requests`, `GET /v1/requests/{request_id}` and `DELETE /v1/requests/{request_id}` are documented on [Operations](/docs/api/operations).

## Request ids

Every request has an id: your `X-Request-Id` header when it is 1 to 128 characters of `A-Za-z0-9._:-`, otherwise a generated `req_...` value. It is echoed on every response (errors included), written to the server log, and placed in `x_yunshu.request_id` and `error.x_yunshu.request_id`. The same id is the handle for status and cancellation:

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

A cancel that arrives before the request reached the engine (while it is tokenizing or decoding an image) is remembered and applied the moment generation starts.

## Per-response stats: `x_yunshu`

`x_yunshu` appears in the JSON body of non-streaming Chat and Completions responses, in the final usage chunk of streams, and (when the client did not ask for usage) in a trailing `: yunshu-stats {...}` comment before `[DONE]`. On Messages and Responses the same object sits inside `usage`. The Ollama routes map it to Ollama's own nanosecond fields.

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

| Field | Meaning |
| --- | --- |
| `queue_wait_ms` | Time between reaching the engine and the start of prefill. |
| `ttft_ms` | Request arrival to the first generated token. |
| `prefill_tps` | Uncached prompt tokens divided by prefill time. |
| `decode_tps` | (completion tokens - 1) divided by the time between first and last token. |
| `cached_tokens` | Prompt tokens served from the prefix cache. |
| `speculative` | Present when a drafter (`mtp` or `dflash`) served the request; `null` when nothing was drafted. |
| `timings` | The same measurements under llama.cpp-style key names. |
| `cancelled` | `true` when the answer was cut short by a cancel or a deadline. |
| `context_policy` | Present when the prompt was shortened to fit: the strategy, tokens and messages before and after, and what was removed. |
| `budget` | Present when `max_tokens` was clamped to the room the prompt leaves in the context window, or when the request sent none: `max_tokens_requested`, `max_tokens_granted`, `max_tokens_source` (`request`, `model_limit`, `operator_cap`, `api_spec_default`) and `clamped_by` when clamped. |
| `server_tools` | Server-side tool loop report on Messages and Responses: `rounds`, `round_usage[]`, `tools[]`. |

Fields are `null` when a path cannot measure them. Non-streaming responses also carry the compact headers `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` and `X-Yunshu-Context-Policy`, for clients that log headers and never parse bodies.

A prompt that does not fit is never silently cut: the latest user turn and system messages are never removed, and when they alone exceed the window the request fails with `400` and code `context_length_exceeded`.

## Queue, progress and overload

Generation responses carry `X-Yunshu-Queue-Position` (requests that arrived earlier and are still in flight; 0 means served at once) and `X-Yunshu-Queue-Est-Wait-Ms` (a lower bound based on the prefill still owed ahead of you).

While a streaming Chat or Completions request is queued or prefilling, the server writes an SSE comment every `YUNSHU_PROGRESS_INTERVAL_S` seconds (default 2, `0` turns it off) until the first 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` counts only tokens that are actually computed; a prefix cache hit is reported as `cached_tokens`. Non-streaming requests cannot report progress mid-flight, so poll `GET /v1/requests/{request_id}` with the id you sent.

Overload is refused instead of queued without bound. Chat, Completions, Messages and Responses requests that arrive while `YUNSHU_QUEUE_LIMIT` (default 64, `0` for no limit) requests are in flight get `429` with `Retry-After` and `error.x_yunshu` of `{"reason": "queue_full", "queue_depth", "queue_limit", "retry_after_s"}`. While MLX memory is above `YUNSHU_MEMORY_PRESSURE_REJECT` (default 0.95 of the Metal working set) and other requests are running, a new generation request gets `503` with reason `memory_pressure`. An idle server never refuses on memory.

`X-Yunshu-Deadline-Ms: N` (1 to 86,400,000) is the wall time you are willing to wait, counted from arrival and including queue time. Past it the generation is cancelled and the client gets `504` with code `deadline_exceeded` (Messages: `timeout_error`); once a stream has started it ends with one terminal error event. This is different from the request body `timeout` field, which ends generation with a partial answer.

## `keep_alive` and status

`keep_alive` on `POST /v1/chat/completions` and `POST /v1/completions` follows Ollama's grammar: seconds, a duration string such as `"5m"`, a negative value for "keep loaded", `0` to free the model once idle. It applies in multi-model mode, where an idle model is unloaded after its keep-alive or after `YUNSHU_MODEL_TTL_SECONDS` when the request set none. A single-model server never frees its model, so it accepts the field and does nothing.

`GET /v1/yunshu/status` returns one object with everything an operator wants before sending a large request:

```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` is `running`, `shutdown_requested` or `shutting_down`. Memory fields named `*_gb` use binary GiB (1 GiB is 1024^3 bytes) and each has an exact `*_bytes` sibling. In multi-model mode each model also has `size_gb`, `size_bytes`, `idle_s`, `keep_alive_s` and `expires_in_s`. `gpu` holds cumulative GPU-busy seconds per engine that tracks them.

## Warmup

`POST /v1/yunshu/warmup` loads a model if needed, runs a small generation through the normal path (kernel compile, allocator warm-up) and leaves the given prompt in the prefix cache, so the first real request is warm.

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | string | no | Defaults to the served model. Unknown model in multi-model mode returns `404`. |
| `prompt` | string | no | A system prompt or prefix to leave in the cache. Default `"Hello"`. |
| `messages` | array | no | Chat messages to warm instead of `prompt`. |
| `keep_alive` | string, number | no | Sets the model's keep-alive (multi-model mode). Invalid value returns `400`. |
| `max_tokens` | integer | no | Default 1. |

Response:

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

`generated` is `false` for model types that cannot generate text (ASR, TTS, embeddings and so on). If the warm-up generation itself fails, the call still succeeds and the response carries a `warning` string instead of `x_yunshu`.

## Cancel

`POST /v1/cancel` takes `{"request_id": "job-7"}` or `{"cancel_all": true}` and returns `{"status": "cancelled", "request_id": ...}` or `{"status": "cancelled", "count": N}`. An unknown id returns `404`, a body with neither field `400`. `GET /v1/active-generations` returns `{"object": "list", "data": [...], "active": [...], "count": N}` of in-flight generations. These accept the same ids as `DELETE /v1/requests/{request_id}`.

## `WS /v1/stream`

One WebSocket carries many concurrent requests. Server events are the same objects the SSE streams carry, wrapped with your request id. The handshake uses the same auth as HTTP (`Authorization: Bearer`, `x-api-key` or `?token=`) and is checked before the upgrade; a failed check rejects the handshake. The first server message is `session.created`.

Client messages (JSON text frames):

| Message | Meaning |
| --- | --- |
| `{"type": "request", "id": "a", "api": "chat.completions", "body": {...}, "stream_id": "s"}` | Start a request. `api` is `chat.completions`, `completions`, `responses` or `messages`; `body` is the normal HTTP body (`stream` is forced on; `stream_options.include_usage` defaults on for chat). `stream_id` is optional. |
| `{"type": "cancel", "id": "a"}` | Abort; ends with `done` and reason `cancelled`. |
| `{"type": "stop", "id": "a"}` | Stop on demand; ends with reason `stopped`. |
| `{"type": "update", "id": "a", "max_tokens": N}` | Cap the total streamed deltas; answered with `updated`, ends with reason `max_tokens`. |
| `{"type": "ping", "t": ...}` | Liveness. Answered with `pong`. |

Server messages:

| Message | Meaning |
| --- | --- |
| `session.created` | `{"protocol": "yunshu.stream", "apis": [...], "limits": {"max_inflight", "max_stream_ids", "send_queue", "ping_interval_s"}}` |
| `event` | `{"id", "event": "<SSE event name or null>", "data": {...}}`, one SSE event. |
| `progress`, `stats` | The fields of the `yunshu-progress` and `yunshu-stats` comments. |
| `done` | Terminal message of every request: `reason` (`completed`, `cancelled`, `stopped`, `max_tokens`, `error`), `request_id`, `stats` (`ttft_ms`, `duration_ms`, `events`, `deltas`). |
| `error` | `{"id"?, "status", "error": {"message", "type", ...}}`, request-scoped when it has an `id`. |
| `ping` | Heartbeat every `YUNSHU_WS_PING_INTERVAL` seconds (default 15; `0` disables). |

Limits: at most `YUNSHU_WS_MAX_INFLIGHT` (default 16) concurrent requests per connection (more get `429` with code `too_many_requests`), a duplicate active `id` is `409`, and at most 32 distinct `stream_id` values. Requests with the same `stream_id` run in order; different ids run concurrently. Outbound events are buffered up to `YUNSHU_WS_SEND_QUEUE` (default 256); beyond that generation pauses until the reader catches up. Closing the socket cancels everything in flight. When your `id` is 1 to 128 characters of `A-Za-z0-9._:-` it is also the HTTP `X-Request-Id`.

`WS /v1/responses` speaks OpenAI's Responses WebSocket mode on the same transport; see [Responses](/docs/api/responses).

## Native speech: `POST /v1/omni/speech/stream`

For models with a Talker (Qwen3-Omni), this route streams text and speech from one model, without an ASR to LLM to TTS cascade. If the served model can speak it is reused; otherwise `YUNSHU_OMNI_MODEL` can point at a separate omni model. With no speakable model the route returns `503`.

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `text` | string | yes | 1 to 8000 characters. |
| `speaker` | string | no | A speaker of the model or an alias. An unknown speaker returns `400` listing the valid names. |
| `thinker_max_new_tokens` | integer | no | 0 to 512. |
| `image_path` | string | no | Image input: a file path on the server, a `data:` URI (base64) or an http(s) URL. |
| `audio_path` | string | no | Audio input, same forms. |

Inline and downloaded media is capped at 64 MiB (`413`). The response is `text/event-stream`:

| Event | Payload |
| --- | --- |
| `{"type": "text", "delta": "..."}` | A piece of the Thinker text. |
| `{"type": "audio", "delta": "<base64 PCM16>", "sr": 24000}` | A speech chunk, mono 16-bit little-endian. |
| `{"type": "done", ...}` | Final statistics. Followed by `data: [DONE]`. |
| `{"type": "error", "message": ...}` | Failure after the stream started. |

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

A second wire format for the [decision](/docs/api/decisions) engine: questions are a map keyed by name, and answers come back keyed by the same names. It needs the same decision checkpoint.

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | string | yes | Decision model id. |
| `state` | any | yes | The input, text or any JSON value. |
| `questions` | object | yes | Map of name to `{"type", "instructions"?, "criteria"?}`. 1 to 128 questions. |
| `images` | array of string | no | Base64 images or `data:image/...;base64,...` URLs. At most 128. |

Question types: `noul` (boolean; optional `criteria` map with `true` and `false` descriptions), `choice` (`criteria` is a map of option to description, at least 2) and `score` (`criteria` is a list of level descriptions, at least 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 }
}
```

Validation errors on this route return `422` (the decisions route returns `400`); a non-decision model, a missing model or an engine error return `400` or `404` as on `POST /v1/decisions`. A question the head cannot answer returns `{"type": "refusal"}`.

## Errors that say what to do

OpenAI-format errors, middleware ones included, get the fix twice: appended to `error.message`, and structured in `error.x_yunshu` (`hint`, `request_id`, and for overload the queue fields). Hints exist for context too long, out of memory, authentication, unknown model, oversized body, rate limit, model loading or shutting down, validation and internal errors. Anthropic-format errors stay exactly as the Anthropic spec defines them.

## Support

| Feature | Status |
| --- | --- |
| `x_yunshu` stats, `X-Yunshu-*` headers, progress comments | <Support status="extension">Yunshu extension</Support> |
| Request ids, cancel by id, deadline header | <Support status="extension">Yunshu extension</Support> |
| `keep_alive` | <Support status="partial">has an effect in multi-model mode only</Support> |
| Status and warmup | <Support status="extension">Yunshu extension</Support> |
| `WS /v1/stream` | <Support status="extension">Yunshu protocol</Support> |
| Progress for non-streaming requests | <Support status="unsupported">poll `GET /v1/requests/{request_id}` instead</Support> |
| Native speech | <Support status="partial">needs a model with a Talker</Support> |

## Related

- [Operations](/docs/api/operations) for health, metrics and request inspection.
- [Realtime](/docs/api/realtime) for the OpenAI Realtime WebSocket.
- [Decisions](/docs/api/decisions) for `POST /v1/decisions`.
- [Chat completions](/docs/api/chat-completions) for the routes that carry these fields.


---

<!-- api/files -->
---
title: Files
description: A local file store that speaks both the OpenAI Files API and the Anthropic Files API on the same /v1/files paths.
---

Yunshu keeps uploaded files in one local store (default `~/.yunshu/files`). The same routes answer in two dialects, and the server picks the dialect from the request: if the request carries an `anthropic-version` header (every Anthropic SDK sends it) the Anthropic shapes are used, otherwise the OpenAI shapes. The OpenAI SDK never sends that header.

Stored files are used as inputs elsewhere: batch input and output files ([Batches](/docs/api/batches)), eval data ([Evals](/docs/api/evals)), enrolled custom voices ([Audio](/docs/api/audio)), and file references in [Responses](/docs/api/responses) and [Messages](/docs/api/messages) requests.

<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">
Authentication is enforced when a static token or API keys are configured. Authenticated keys share the same Files store; without configured auth, anyone who can reach the server sees every file.
</Callout>

## Limits and storage

| Setting | Default | Effect |
| --- | --- | --- |
| `YUNSHU_FILES_DIR` | `~/.yunshu/files` | Directory of the store. |
| `YUNSHU_FILES_MAX_BYTES` | 536870912 (512 MB) | Maximum size of one upload; larger uploads fail with `413` `file_too_large`. |
| `YUNSHU_FILES_MAX_TOTAL_BYTES` | 0 (unlimited) | Total size of the store; an upload that would exceed it fails with `413` `storage_quota_exceeded` (expired files are removed first). |
| `YUNSHU_FILES_TTL_DAYS` | unset | Delete files this many days after upload. Unset keeps them until deleted. |

Other behaviour:

- Ids look like `file_` followed by 24 hex characters. The OpenAI spelling `file-...` is accepted wherever an id is expected and mapped to `file_...`.
- Metadata and bytes are written atomically; expired files are removed lazily and at store start.
- If the disk is full the upload returns `507` with code `insufficient_storage`.

## Upload

`POST /v1/files` takes `multipart/form-data`.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `file` | file | yes | The file part. | supported |
| `purpose` | string | OpenAI: yes | One of `assistants`, `batch`, `fine-tune`, `vision`, `user_data`, `evals`. Other values return `400`. Ignored for Anthropic requests (stored as `user_data`). | supported |
| `expires_after` | object | no | OpenAI only. `{"anchor": "created_at", "seconds": 3600..2592000}`, sent as `expires_after[anchor]` and `expires_after[seconds]` form fields or as one JSON string. | supported |

OpenAI uploads must not be empty. All `purpose` values are accepted, but only the ones Yunshu consumes do anything: `batch` for [Batches](/docs/api/batches) and `evals` for [Evals](/docs/api/evals). Nothing here runs fine-tuning.

OpenAI response:

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

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

The stored `mime_type` is the declared content type if it is specific, otherwise it is sniffed from the bytes (PDF, PNG, JPEG, GIF, WebP) and then the filename.

## List, retrieve, delete

| Route | OpenAI dialect | Anthropic dialect |
| --- | --- | --- |
| `GET /v1/files` | Query: `purpose`, `limit` (1 to 10000, default 10000), `order` (`asc` or `desc`, default `desc`), `after` (a file id). Returns `{"object": "list", "data", "has_more", "first_id", "last_id"}`. | Query: `limit` (1 to 1000, default 20), `after_id`, `before_id`. Returns `{"data", "first_id", "last_id", "has_more"}`. `purpose` is not filtered. |
| `GET /v1/files/{file_id}` | The file object. | The file object. |
| `DELETE /v1/files/{file_id}` | `{"id", "object": "file", "deleted": true}` | `{"id", "type": "file_deleted"}` |

Files are listed newest first.

## Download content

`GET /v1/files/{file_id}/content` returns the stored bytes as an attachment with the stored content type and filename.

In the Anthropic dialect the Anthropic rule applies: only files created by tools are downloadable, uploaded files are not. Yunshu marks every uploaded file `downloadable: false`, so an Anthropic-style request (one with an `anthropic-version` header) gets `403`. Use the OpenAI dialect (no `anthropic-version` header) to read a file back.

## Using stored files in requests

Stored files are inlined into model requests when referenced by id:

| Where | Reference |
| --- | --- |
| [Messages](/docs/api/messages) | `{"type": "image"}` or `{"type": "document"}` block with `"source": {"type": "file", "file_id": "file_..."}`. Text documents become text sources, others base64. |
| [Responses](/docs/api/responses) | `input_file` or `input_image` items with `file_id`. |

An unknown id fails with `404` `file_not_found`.

## Examples

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

## Errors

OpenAI dialect errors use `{"error": {"message", "type", "param", "code"}}`. Anthropic dialect errors use `{"type": "error", "error": {"type", "message"}}`.

| Status | Code | When |
| --- | --- | --- |
| `400` | `invalid_value` | Bad `purpose`, bad `expires_after`, bad `limit` or `order`. |
| `400` | | Not a multipart body, missing `file`, empty file (OpenAI). |
| `404` | `file_not_found` | Unknown, malformed or expired id. |
| `403` | | Anthropic dialect content download of an uploaded file. |
| `413` | `file_too_large`, `storage_quota_exceeded` | Over the per-file or total limit. |
| `507` | `insufficient_storage` | Disk full. |

## Support

| Feature | Status |
| --- | --- |
| OpenAI Files: upload, list, retrieve, delete, content | <Support status="supported">supported</Support> |
| Anthropic Files shapes, selected by `anthropic-version` | <Support status="supported">supported</Support> |
| `expires_after` | <Support status="supported">1 hour to 30 days, `created_at` anchor only</Support> |
| Anthropic content download of uploaded files | <Support status="unsupported">403, as in the Anthropic API</Support> |
| Multipart / resumable `uploads` API | <Support status="unsupported">not served</Support> |
| Fine-tuning, assistants and vision pipelines behind `purpose` | <Support status="unsupported">purpose values are accepted and stored only</Support> |

## Related

- [Batches](/docs/api/batches) for input and output JSONL files.
- [Evals](/docs/api/evals) for datasets uploaded with `purpose=evals`.
- [Audio](/docs/api/audio) for custom voices stored in this store.
- [Messages](/docs/api/messages) and [Responses](/docs/api/responses) for file references.


---

<!-- api/images -->
---
title: Images and OCR
description: OpenAI-style image generation, edits and variations from a local diffusion model, plus a Yunshu OCR endpoint for extracting text from images.
---

This page covers two groups of routes. The image routes follow the OpenAI `/v1/images/*` dialect and run a local Z-Image style diffusion pipeline. `POST /v1/ocr` is a Yunshu route (not part of the OpenAI API) that turns an uploaded image into text with an OCR model or any loaded vision-language model.

<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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. Image generation needs an image model to be loaded (see [Models](/docs/getting-started/models)); the optional `generation` extra provides the extra dependencies.
</Callout>

## Image generation

`POST /v1/images/generations` takes a JSON body.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `prompt` | string | yes | Text prompt. Must not be blank. | supported |
| `model` | string | no | Image model id. Default `Z-Image-Turbo-MLX-4bit`. If it does not match a loaded image model but exactly one image model is loaded, that one is used. | supported |
| `n` | integer | no | 1 to 10, default 1. Images are generated one after another. | supported |
| `size` | string | no | `WIDTHxHEIGHT`, default `1024x1024`. Both sides must be between 64 and 2048 and multiples of 64. | supported |
| `response_format` | string | no | `b64_json` (default) or `url`. | supported |
| `num_inference_steps` | integer | no | 1 to 100, default 4 (tuned for Turbo models). | extension |
| `seed` | integer | no | Image `i` uses `seed + i`. Without a seed each image gets a fresh random seed. | extension |
| `control_image` | string | no | Base64 image (a `data:` URL prefix is allowed) used as a control signal. | extension |
| `control_scale` | number | no | 0 to 2, default 0.8. Only used with `control_image`. | extension |
| `preview_interval` | integer | no | Streaming route only: emit a decoded preview every N steps (0 = off). | extension |
| `quality`, `style`, `background`, `output_format`, `moderation` | | no | OpenAI fields that are not part of the schema; ignored. | accepted and ignored |

The response is always PNG data:

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

With `response_format: "url"`, each item has `url` set to a `data:image/png;base64,...` URI (plus `b64_json`). Yunshu does not host generated files, so `url` is never an http link.

### Streaming generation

`POST /v1/images/generations/stream` takes the same body and returns `text/event-stream`. Each event is a `data:` line with a JSON object and no `event:` name:

| Event shape | Meaning |
| --- | --- |
| `{"step", "total_steps", "progress", "is_final": false}` | Denoising progress. |
| `{"step", "total_steps", "progress", "image", "is_final": false, "is_preview": true}` | Progress with a base64 PNG preview (only when `preview_interval` is above 0). |
| `{"step", "progress": 1.0, "image", "is_final": true}` | Final image as base64 PNG. Followed by `data: [DONE]`. |
| `{"type": "cancelled"}` | Request cancelled (for example by `POST /v1/cancel`), followed by `[DONE]`. |
| `{"error": {"message", "type"}}` | Failure after the stream started, followed by `[DONE]`. |

The streaming route produces a single image; `n` and `control_image` are not used by it.

## Edits and variations

`POST /v1/images/edits` and `POST /v1/images/variations` accept either `multipart/form-data` (what the OpenAI SDKs send: an `image` file plus text fields) or JSON with a base64 `image`. Only the first `image` file is read; a `mask` or additional files are ignored. Images larger than 25 MB return `413`.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `image` | file or base64 string | yes | Source image. | supported |
| `prompt` | string | edits: yes | Edit instruction. Variations have no `prompt` field (any value is ignored). | supported |
| `model` | string | no | As for generations. | supported |
| `n` | integer | no | 1 to 10, default 1. | supported |
| `size` | string | no | As for generations. | supported |
| `response_format` | string | no | `b64_json` (default) or `url` (a data URI, without `b64_json`). | supported |
| `num_inference_steps`, `seed` | | no | As for generations. | extension |
| `denoise_strength` | number | no | 0 to 1. How much of the source is re-denoised: default 0.8 for edits, 0.45 for variations. | extension |
| `mask` | file | no | Inpainting mask. | accepted and ignored |

Edits are image-to-image: the source image is the starting point and `denoise_strength` sets how far the result may move away from it. There is no mask-based inpainting on these routes.

## OCR

`POST /v1/ocr` takes `multipart/form-data`.

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `file` | file | yes | Image, at most 10 MB. PNG, JPEG, WebP, TIFF and BMP are read; the file is verified with Pillow and a non-image returns `400`. |
| `model` | string | no | OCR or VLM model id. Empty means the first loaded OCR engine. |
| `task` | string | no | `text` (default), `formula` or `table`. |
| `language` | string | no | A hint that steers the output language. No language detection is performed. |

Engine selection: a loaded OCR-type model (for example a GLM-OCR checkpoint) is used first. If there is none, the request falls back to a loaded vision-language model with a text-recognition prompt. With neither, the server returns `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` is always `null`: neither path produces a confidence score. `language` echoes your hint on the VLM fallback and is `null` on the OCR-engine path.

## Examples

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

## Errors

Errors use the OpenAI envelope `{"error": {"message", "type", "param", "code"}}`.

| Status | When |
| --- | --- |
| `400` | Blank `prompt` or `image`, `size` not parseable or not a multiple of 64 in 64 to 2048, invalid `response_format`, invalid base64, non-image OCR upload. |
| `404` | No image generation model matches `model`, or the model is of a different modality. |
| `413` | Image upload over 25 MB (OCR: over 10 MB). |
| `501` | Generations only: the loaded image model uses a layout the pipeline cannot run (flat Lance/Wan style checkpoints). Edits and variations report this case as `500`. |
| `503` | OCR: no OCR or vision-language model is loaded. |
| `507` | Out of GPU memory. |
| `500` | Generation, edit, variation or OCR failed. |

## Support

| Feature | Status |
| --- | --- |
| Text-to-image, `b64_json` and data-URI `url` | <Support status="supported">supported</Support> |
| Streaming progress and previews | <Support status="extension">Yunshu extension</Support> |
| Image edits and variations (image-to-image) | <Support status="partial">no mask inpainting</Support> |
| Hosted `url` links | <Support status="unsupported">data URIs only</Support> |
| Control image guidance | <Support status="extension">Yunshu extension</Support> |
| `gpt-image-1` options (`quality`, `background`, `output_format`) | <Support status="unsupported">ignored</Support> |
| Lance/Wan style image checkpoints | <Support status="unsupported">501</Support> |
| OCR with OCR models or VLM fallback | <Support status="supported">supported</Support> |

## Related

- [Models](/docs/getting-started/models) for loading image and OCR models.
- [Chat completions](/docs/api/chat-completions) for sending images to a vision-language model instead.
- [Extensions](/docs/api/extensions) for cancelling running requests.


---

<!-- api/mcp -->
---
title: MCP
description: Yunshu as an MCP server (JSON-RPC over HTTP) that exposes generation, speech and image tools, plus routes that report the MCP client pool.
---

Yunshu speaks the Model Context Protocol in two directions.

- As an **MCP server**, `POST /v1/mcp` accepts JSON-RPC 2.0 requests and exposes the local models as tools: text generation, speech synthesis and image generation. Any MCP-capable agent can use your local models this way.
- As an **MCP client**, Yunshu can connect at startup to MCP tool servers you configure and report what it found on two read-only routes.

Calling remote MCP servers from a Messages or Responses request (the `mcp_servers` and `mcp` tool features) is a separate feature, described in [Server tools](/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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set; send `Authorization: Bearer <token>` or `x-api-key`. An authentication or permission failure on `POST /v1/mcp` is returned as a JSON-RPC error object (code `-32600`) with the HTTP status, so MCP clients can parse it. Keys that are restricted to certain models are also checked for the `generate`, `synthesize_speech` and `generate_image` tools.
</Callout>

## The MCP server

### Protocol as implemented

- Transport: one JSON-RPC 2.0 message per `POST /v1/mcp`, answered with a single `application/json` response. Batch arrays are not supported (an error object is returned). The server is stateless: it issues no session id and keeps no per-client state.
- A message without an `id` is a notification and gets `204 No Content`. An explicit `id: null` is treated as a request.
- `initialize` reports `protocolVersion` `2024-11-05`, `serverInfo` `{"name": "yunshu", "version": ...}` and the capabilities `tools`, `resources` and `prompts` (none of them with `listChanged` or `subscribe`).
- Server-initiated messages (sampling, roots, logging, progress notifications, resource subscriptions) are not implemented.

Methods:

| Method | Behavior |
| --- | --- |
| `initialize` | Returns the capabilities above. |
| `notifications/initialized` | Accepted. |
| `ping` | Returns `{}`. |
| `tools/list` | Lists the tools below, plus any tools registered in-process by embedding code. |
| `tools/call` | Runs a tool. Unknown tool: error `-32601`. |
| `resources/list` | One resource per registered model, `yunshu://models/<model id>`, MIME `application/json`. Empty in single-model mode. |
| `resources/read` | Reads one of those URIs (model info as JSON text). Unknown URI: error `-32602`. |
| `prompts/list`, `prompts/get` | Four built-in prompt templates: `summarize` (`text`), `translate` (`text`, `target_language`), `code_review` (`code`, `language`) and `explain` (`concept`). Missing required arguments: error `-32602`. |

Other methods return error `-32601` (method not found). Invalid JSON is `-32700`, a malformed envelope is `-32600`, bad parameters are `-32602`, and an unexpected failure is `-32603` with the generic message `Internal error`.

### Tools

| Tool | Arguments | Result |
| --- | --- | --- |
| `generate` | `model` (required in the schema; if omitted the default model is used), `messages` (array of `{role, content}`, required), `max_tokens` (512), `temperature` (0.7), `top_p`, `top_k`, `min_p`, `repetition_penalty`, `frequency_penalty`, `presence_penalty`, `enable_thinking`, `seed`, `stop` | One `text` content item with the generated text. |
| `synthesize_speech` | `text` (required), `voice` (default `alloy`) | A `text` item and an `audio` item (base64 WAV, `audio/wav`). Needs multi-model mode with a TTS model loaded. |
| `generate_image` | `prompt` (required), `width`, `height` (default 512), `num_inference_steps` (default 4), `seed` | An `image` item (base64 PNG, `image/png`) and a `text` item. Needs multi-model mode with an image model loaded. |

Results use the standard shape `{"content": [...], "isError": false}`. A failure while a tool runs (model not loaded, engine error) is a normal result with `isError: true` and the message in a `text` item; a missing required argument is a JSON-RPC error `-32602`. Text and base64 payloads are truncated at about 1 MB.

`generate` has a smaller argument set than Chat Completions: no tools, no streaming and no structured output. Use [Chat Completions](/docs/api/chat-completions) for those.

### Examples

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

Response to `tools/call`:

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

### REST discovery

`GET /v1/mcp/tools` returns the same tool list as `tools/list` without the JSON-RPC envelope: `{"tools": [{name, description, inputSchema}]}`.

`GET /v1/mcp/sse` opens a Server-Sent Events stream that sends `event: endpoint` with `data: /v1/mcp` once, then `event: ping` roughly every 15 seconds until the client disconnects. It only announces where to POST: responses still come back in the body of each `POST /v1/mcp`, not on this stream. A legacy HTTP+SSE client that expects replies on the event stream will therefore not get them; use a client that accepts plain JSON responses to POST.

### Connecting a client

An MCP client that supports HTTP servers and accepts a JSON reply to each POST can use `http://localhost:8000/v1/mcp` as its server URL, with the bearer token as an `Authorization` header when authentication is on. For Claude Code that is the HTTP transport of `claude mcp add`; Codex and other agents have an equivalent setting in their MCP configuration. Because the server implements protocol version `2024-11-05` and the tools above, expect to use it for "call my local model as a tool", not as a replacement for the agent's own tools. Coding agents that run against Yunshu as their model endpoint (see [Agents](/docs/guides/agents)) do not need this server: they connect to their own MCP servers themselves, and the tools reach the model as ordinary function tools.

## The MCP client pool

At startup Yunshu can connect to MCP tool servers, from a file (`YUNSHU_MCP_CONFIG`) or from a JSON array in `YUNSHU_MCP_SERVERS`. The file holds either `{"mcpServers": {"<id>": {...}}}` or `{"servers": [...]}`. Each entry:

| Key | Description |
| --- | --- |
| `id` / `name` | Server id (the key, when `mcpServers` is an object). |
| `transport` | `stdio` (default), `sse` or `streamable_http`. |
| `command`, `args` | The process to start for `stdio`. |
| `url`, `headers` | The endpoint and headers for `sse` and `streamable_http`. |
| `enabled` | `true` by default. |

Servers are connected once at startup (a restart is needed after changing the configuration), and servers that fail to connect are skipped. When a non-streaming Chat Completions response contains a tool call whose name matches a pooled tool, Yunshu executes it and adds the outputs to the response body as `mcp_tool_results` (a list of `{tool_call_id, output}`); the results are not fed back to the model automatically, and the model is only offered a tool if the request declares it. Tool calls that match no pooled tool are returned to your client as usual.

### Status and tools

`GET /v1/mcp/client/status`:

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

With no pool configured it returns `{"enabled": false, "connected_servers": 0, "total_tools": 0}`.

`GET /v1/mcp/client/tools` returns `{"tools": [{name, description, server_id, input_schema}], "openai_format": [{type: "function", function: {name, description, parameters}}]}`; with no pool both lists are empty. The `openai_format` list can be passed directly as `tools` in a Chat Completions request.

## Errors

| Case | Result |
| --- | --- |
| Invalid JSON | HTTP 200, JSON-RPC error `-32700`. |
| Not a JSON object, bad envelope, wrong `jsonrpc` | JSON-RPC error `-32600`. |
| Unknown method or tool | JSON-RPC error `-32601`. |
| Missing or invalid parameters | JSON-RPC error `-32602`. |
| Unexpected failure | JSON-RPC error `-32603`, message `Internal error`. |
| Authentication or permission failure | JSON-RPC error `-32600` with HTTP `401` or `403`. |
| Tool runs but fails | A result with `isError: true`. |

## Support

| Feature | Status |
| --- | --- |
| `POST /v1/mcp` with `initialize`, tools, resources, prompts, `ping` | <Support status="supported">supported</Support> |
| `generate`, `synthesize_speech`, `generate_image` tools | <Support status="supported">supported (the last two need a loaded TTS or image model)</Support> |
| Sessions, JSON-RPC batches, server-to-client requests, progress, subscriptions | <Support status="unsupported">not supported</Support> |
| Replies on the legacy SSE stream | <Support status="unsupported">not supported (replies are in the POST body)</Support> |
| MCP client pool (stdio, SSE, streamable HTTP), status routes | <Support status="partial">configured at startup; results are reported, not fed back to the model</Support> |

## Related

- [Server tools](/docs/api/server-tools)
- [Agents](/docs/guides/agents)
- [Chat Completions](/docs/api/chat-completions)
- [Configuration](/docs/guides/configuration)


---

<!-- api/messages -->
---
title: Messages
description: Anthropic Messages API with tools, thinking, images, documents with citations, token counting and message batches.
---

Yunshu serves the Anthropic Messages API on `POST /v1/messages` (also reachable as `POST /messages`), token counting on `POST /v1/messages/count_tokens`, and Message Batches under `/v1/messages/batches`. The official `anthropic` Python and TypeScript SDKs work by pointing `base_url` at the server root, with no `/v1` suffix. Claude Code and other Anthropic-dialect agents connect the same way (see [Agents](/docs/guides/agents)).

Requests are translated to the same engine path as [Chat Completions](/docs/api/chat-completions), so the local model, prefix cache and constrained decoding are shared. Server-side tools (`web_search_20250305`, `web_fetch_20250910`, the MCP connector) are described in [Server tools](/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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. The Anthropic SDK sends its key as `x-api-key`, which the server accepts in place of `Authorization: Bearer`. In single-model mode the `model` field is advisory: the loaded model answers under any name (for example `claude-sonnet-4-5`) and the response echoes the name you sent. In multi-model mode `YUNSHU_MODEL_ALIASES` can map such names onto a served model.
</Callout>

## Headers

| Header | Behavior |
| --- | --- |
| `x-api-key` | Honored as the bearer token when `YUNSHU_AUTH_TOKEN` is set. |
| `Authorization: Bearer ...` | Also accepted. |
| `anthropic-version` | Accepted from any client; the value is not validated and does not change behavior. |
| `anthropic-beta` | Accepted; not required. Beta features such as the MCP connector, structured outputs and the Files API are driven by the request body, not by this header. |

## Request

### Core fields

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Model id; advisory in single-model mode. | supported |
| `messages` | array | yes | Non-empty list of `{role, content}`. `content` is a string or a list of blocks. A leading or in-conversation `system` role entry is lifted into the system prompt. | supported |
| `max_tokens` | integer | no | 1 to 1048576. Required, as in the Anthropic API: omitting it is a `400` `invalid_request_error` (`max_tokens: Field required`). | supported |
| `system` | string or array of text blocks | no | System prompt. Blocks may carry `cache_control`. | supported |
| `temperature` | number | no | 0 to 2. Default 0.7 when omitted. | supported |
| `top_p`, `top_k` | number, integer | no | `top_p` 0 to 1 (default 1.0); `top_k` 0 disables. | supported |
| `stop_sequences` | array of string | no | Up to 16 non-empty strings. A match ends the turn with `stop_reason: "stop_sequence"` and the matched string in `stop_sequence`. | supported |
| `stream` | boolean | no | Server-Sent Events. | supported |
| `metadata` | object | no | Accepted. | accepted and ignored |
| `service_tier`, `container` | string, object | no | Accepted so SDK requests validate. | accepted and ignored |
| `context_management` | object | no | Context editing: `{"edits": [...]}` with `clear_tool_uses_20250919` (`trigger` input tokens or tool uses, `keep`, `clear_at_least`, `exclude_tools`, `clear_tool_inputs`) and `clear_thinking_20251015` (`keep`, first edit only). Cleared tool results become `[cleared]`. The response carries `context_management.applied_edits` (the `message_delta` when streaming); `count_tokens` returns `context_management.original_input_tokens`. `compact_20260112` (server-side compaction): when the input crosses `trigger` (default and minimum `150000`/`50000` input tokens) the served model summarizes the earlier turns with the same machinery as Responses compaction (`YUNSHU_COMPACT_MAX_TOKENS` caps the summary), the reply starts with a `compaction` block (streamed as `compaction_delta`; `usage.iterations` lists the compaction and message passes) and `instructions` steers the summary. `pause_after_compaction` returns just the block with `stop_reason: "compaction"`. Send the block back and everything before it is dropped; a block with null content is a no-op. `count_tokens` does not compact. An unknown edit type is a `400`. | supported |

### Thinking

| Parameter | Description | Status |
| --- | --- | --- |
| `thinking: {"type": "enabled", "budget_tokens": N}` | Turns thinking on with a budget. `budget_tokens` must be a positive integer below `max_tokens`, otherwise `400`. The reasoning is returned as `thinking` content blocks. | supported |
| `thinking: {"type": "disabled"}` | Turns thinking off. | supported |
| `thinking: {"type": "adaptive"}` | Leaves the model's template default. | supported |
| no `thinking` field | Thinking is off, as in the Anthropic API (it is opt-in). | supported |
| `output_config.effort` | Becomes the template's reasoning effort. `reasoning_effort` is the Yunshu spelling. | supported |

Thinking is a property of the loaded model. For models whose chat template does not think natively, `enabled` adds an instruction to wrap reasoning in `<think>` tags and constrains the start of the reply to do so, so a `thinking` block is still returned. A forced `tool_choice` (`any` or `tool`) turns thinking off, as Anthropic does not combine them. Thinking blocks carry an empty `signature`; there are no redacted thinking blocks.

### Tools

| Parameter | Type | Description | Status |
| --- | --- | --- | --- |
| `tools` | array | Custom tools `{name, description, input_schema}`. | supported |
| `tool_choice` | object or string | `{"type": "auto"}`, `{"type": "any"}`, `{"type": "tool", "name": "..."}`, `{"type": "none"}`. `disable_parallel_tool_use: true` caps the reply to one call. Forced choices are enforced by constrained decoding; a call to a tool other than the forced one is dropped. | supported |
| `tools[].cache_control` | object | Participates in cache accounting (see below). | supported |
| `bash_*`, `text_editor_*`, `memory_*`, `computer_*` typed tools | object | Declared by `type` and `name` only. Yunshu fills in the documented `input_schema` so a local model can produce a valid `tool_use`; your client executes the tool and sends back the `tool_result`. `computer_*` supports `display_width_px`, `display_height_px`, `display_number` and `enable_zoom`. The newer `computer_toolset_20260801` protocol is not implemented. | partial |
| `web_search_*`, `web_fetch_*`, `mcp_toolset` and top-level `mcp_servers` | array | Executed by the server. See [Server tools](/docs/api/server-tools). | supported |
| `code_execution_*` and other hosted tools | | Not available. | not supported |

Client tool results go back as `tool_result` blocks in a user message, as in the hosted API. A `tool_result` may contain text and image blocks.

### Content blocks

| Block | Description | Status |
| --- | --- | --- |
| `text` | Plain text, optional `cache_control`. | supported |
| `image` | `source` of type `base64` (png, jpeg, gif, webp), `url` (checked against SSRF rules; private and non-HTTP(S) URLs are a `400`), or `file` (a [Files](/docs/api/files) id). Needs a vision-language model; a text-only model answers `400`. | supported |
| `document` | `source` of type `text` (`text/plain`), `content` (text and image blocks), `base64` PDF (up to 32 MiB and 100 pages, unencrypted), `url` (a PDF; private addresses are blocked) or `file`. `title`, `context` and `citations: {"enabled": true}` are honored. The text layer is read; a vision model also receives page images, and image-only PDFs need a vision model. Extracted text is capped at 2 million characters. | supported |
| `tool_use`, `tool_result` | Client tool round trips. | supported |
| `thinking` | Returned for reasoning models; accepted back in assistant turns. | supported |
| `server_tool_use`, `web_search_tool_result`, `web_fetch_tool_result`, `mcp_tool_use`, `mcp_tool_result` | Returned by server tools; accepted back in history. | supported |
| `search_result`, `container_upload`, `redacted_thinking` | Not interpreted. | not supported |

#### Citations

When a `document` block has `citations: {"enabled": true}`, the model is shown the document with exact character offsets and asked to mark sources. Markers are validated against the real document and translated to the public schema: `char_location` (text), `page_location` (PDF) or `content_block_location` (content documents), each with `cited_text`, `document_index` and `document_title`. A marker outside the document, or a citation to a document without citations enabled, fails the request with `502` (an SSE `error` event when streaming) rather than returning a made-up citation. In a stream the citations arrive as `citations_delta` events. Citation quality depends on the local model following the marker instruction.

### Structured output and engine controls

| Parameter | Description | Status |
| --- | --- | --- |
| `output_config.format` / `output_format` | `{"type": "json_schema", "schema": {...}}` constrains decoding to the schema. | supported |
| `cache_control` (top level, block level) | Marks prefix-cache breakpoints (see below). | supported |
| `json_schema`, `response_format`, `grammar` | Yunshu extensions for constrained decoding (`json_object`, `json_schema`; `regex`, `choice`, `cfg` grammars). | extension |
| `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` | Engine controls shared with the other routes. | extension |

### Prompt caching

`cache_control: {"type": "ephemeral"}` on system blocks, messages, tool definitions or documents marks cache breakpoints. Yunshu's prefix cache is automatic; the hints tell it where durable breakpoints are. Usage reports the split: `cache_read_input_tokens` is the reused prefix, `cache_creation_input_tokens` is the cacheable prefix written this turn (up to the last breakpoint), and `input_tokens` is the rest, so the three add up to the prompt length. See [Prompt caching](/docs/guides/prompt-caching).

## Examples

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

### Tool use

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

### Image

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

### Document with citations

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

### Thinking

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

### Count tokens

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

## Response

```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` is `end_turn`, `max_tokens` (also used when generation was cut short by a timeout or the memory guard), `stop_sequence`, `tool_use`, or `pause_turn` (a server-tool loop that hit its iteration limit; see [Server tools](/docs/api/server-tools)). When the model reasoned, `usage.output_tokens_details.reasoning_tokens` is present. Server-tool requests add `usage.server_tool_use`.

### Count tokens

`POST /v1/messages/count_tokens` takes the same body as `POST /v1/messages` and returns `{"input_tokens": N}`. It renders the prompt like generation does (system prompt including lifted `system` messages, tools, thinking instructions, documents, files) through the chat template, so the count matches the `input_tokens` of the real call. Each image is counted with a fixed estimate of 576 tokens.

### Message batches

Batches run on a background worker that calls this server over loopback and resumes after a restart. `POST /v1/messages/batches` takes `{"requests": [{"custom_id", "params"}]}` where `params` is a normal Messages body (`model`, `max_tokens` and `messages` required); `custom_id` must match `^[a-zA-Z0-9_-]{1,64}$` and be unique, with at most 100000 requests. The batch object has `type: "message_batch"`, `processing_status` (`in_progress`, `canceling`, `ended`), `request_counts`, timestamps and `results_url`. List with `limit` (1-1000), `after_id`, `before_id`. Results (`GET .../results`) are JSONL and are only available after the batch has ended (`409` before). Cancelling an ended batch, or deleting one that is still processing, is a `400`. The OpenAI-style batch API is on [Batches](/docs/api/batches).

## Streaming

With `stream: true` the server sends Server-Sent Events in Anthropic's order:

1. `message_start` (the message with empty `content` and the prompt `usage`)
2. For each block: `content_block_start`, one or more `content_block_delta`, `content_block_stop`. Delta types are `thinking_delta` (thinking blocks come first), `text_delta`, `input_json_delta` (tool arguments, streamed as partial JSON) and `citations_delta` (documents with citations, server-tool results).
3. `message_delta` with `delta.stop_reason`, `delta.stop_sequence` and cumulative `usage`
4. `message_stop`

`: keep-alive` comment lines are sent during long prefill so clients with short read timeouts stay connected. A failure after the stream starts is a single `event: error` with `{"type": "error", "error": {"type", "message"}}`, with no `message_delta` or `message_stop` after it. Dropping the connection cancels the generation.

## Errors

Errors use Anthropic's envelope, also for denials from the authentication and rate-limit layers on these paths:

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

| Status | `error.type` | Cause |
| --- | --- | --- |
| `400` | `invalid_request_error` | Invalid body (empty `messages`, `thinking.budget_tokens` not below `max_tokens`, more than 16 `stop_sequences`), prompt over the context window, an image sent to a text-only model, a blocked URL, an unreadable document, a model that does not support a requested feature. |
| `401` | `authentication_error` | Missing or wrong key while `YUNSHU_AUTH_TOKEN` is set. |
| `403` | `permission_error` | A key without access to the model. |
| `404` | `not_found_error` | Unknown model in multi-model mode, unknown file id or batch id. |
| `413` | `request_too_large` | Prompt too large to prefill, or an oversized document. |
| `429` | `rate_limit_error` | A configured limit was hit. |
| `500` | `api_error` | Internal error. |
| `502` | `api_error` | A document citation the model produced did not validate. |
| `503` / `529` | `overloaded_error` | No model loaded or the server is saturated. |

## Support

| Feature | Status |
| --- | --- |
| Messages, streaming and non-streaming | <Support status="supported">supported</Support> |
| `count_tokens` | <Support status="supported">supported</Support> |
| Message batches | <Support status="supported">supported</Support> |
| Tools, `tool_choice`, parallel tool use control | <Support status="supported">supported</Support> |
| `bash`, `text_editor`, `memory`, `computer` client tools | <Support status="partial">schemas supplied; the client executes them</Support> |
| `thinking` enabled, disabled, adaptive | <Support status="supported">supported</Support> |
| Images (base64, url, file) | <Support status="supported">supported (vision model)</Support> |
| Documents and citations | <Support status="supported">supported</Support> |
| Server tools: web search, web fetch, MCP connector | <Support status="supported">supported</Support> |
| `cache_control` | <Support status="partial">hints and accounting; the cache itself is automatic</Support> |
| `metadata`, `service_tier`, `container` | <Support status="partial">accepted and ignored</Support> |
| `context_management` (`clear_tool_uses`, `clear_thinking`) | <Support status="supported">applied; `applied_edits` reported</Support> |
| Code execution, hosted memory tool, `search_result` blocks, signed or redacted thinking | <Support status="unsupported">not supported</Support> |

## Related

- [Server tools](/docs/api/server-tools)
- [Chat Completions](/docs/api/chat-completions)
- [Files](/docs/api/files)
- [Batches](/docs/api/batches)
- [Agents](/docs/guides/agents)
- [Prompt caching](/docs/guides/prompt-caching)


---

<!-- api/models -->
---
title: Models
description: List and inspect served models with cards that speak the OpenAI, Anthropic, OpenRouter, vLLM and LM Studio dialects at once, and load or unload models in multi-model mode.
---

`GET /v1/models` returns the models this server can serve. Each item is a model card derived from the checkpoint files on disk (config, chat template, safetensors headers), so the answer states what the loaded weights can do rather than what a name suggests. One item carries the field names of several ecosystems at the same time, so the OpenAI, Anthropic, OpenRouter, vLLM and LM Studio clients all find what they look for. Yunshu's own detail sits under a single `yunshu` key.

<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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. Listing and retrieving models are open without a token. Loading and unloading are operational routes: they need a configured token (or `YUNSHU_AUTH_DISABLED=true`); see [Load and unload](#load-and-unload).
</Callout>

## List models

`GET /v1/models` has no parameters. The response is a list object that satisfies both the OpenAI and the Anthropic SDK list types.

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

An abbreviated item:

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

The values are illustrative and many fields are omitted; a real item has every field listed below. In multi-model mode the list contains every registered model, loaded or not. In single-model mode it contains the one loaded model. There is no pagination: `has_more` is always `false`.

### What an item contains

| Dialect | Fields |
| --- | --- |
| 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` (all `"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` or `not-loaded`), `max_context_length`, `publisher`, `compatibility_type` (`"mlx"`), `model_type` |
| Yunshu | `yunshu`: the full card, described below |

The Anthropic `capabilities` object has every key the Anthropic SDK model requires (`batch`, `citations`, `code_execution`, `context_management`, `effort`, `image_input`, `pdf_input`, `structured_outputs`, `thinking`) with `supported` flags that come from the card. Flat booleans used by LM Studio and vLLM clients (`vision`, `trained_for_tool_use`, `tools`, `function_calling`, `reasoning`, `embedding`) ride inside the same object.

### The `yunshu` card

| Field | Meaning |
| --- | --- |
| `kind` | `chat`, `vlm`, `omni`, `embedding`, `reranker`, `classifier`, `decision`, `asr`, `tts`, `sts`, `image`, `ocr` or `video`. |
| `family`, `architecture`, `parameters` | Model family, architecture class and parameter count read from the checkpoint. |
| `quantization` | Bit width, group size and mode, with per-layer groups for mixed-precision checkpoints. |
| `input_modalities`, `output_modalities` | Subsets of `text`, `image`, `video`, `audio`, `embedding`, `score`, `decision`. |
| `context` | `length` and how it was derived. `max_output_tokens` is the advertised output limit. |
| `reasoning` | Whether the model has a thinking mode, the toggle, default state, effort levels and aliases. |
| `tools`, `structured_output`, `logprobs` | Tool-calling support and modes, supported constraint types, the largest `top_logprobs`. |
| `embeddings` | Vector size, pooling and normalization for embedding models. |
| `audio`, `image` | Modality-specific details for speech and image models. |
| `speculative` | The speculative-decoding method the model has (for example `mtp`) and whether it is lossless. |
| `prefix_cache` | Whether the prefix cache serves this model and what kind. |
| `state`, `memory` | Loaded, loading, pinned, error; weight bytes and estimated memory. |
| `api` | Which routes and wire formats serve this model. |
| `supported_parameters` | The request fields the chat routes accept for this model. |
| `generation_defaults` | Sampling defaults from the checkpoint's `generation_config.json`. |
| `contract` | The capability contract, below. |
| `capability_tags` | Flat tags such as `chat`, `tools`, `vision`, `thinking`. |
| `server_tools` | For text-like models: which gateway-run tools (web search provider, MCP connector) are configured. |

Anonymous callers never see file system paths or residency. A request that presents the configured `YUNSHU_AUTH_TOKEN` also gets `loaded`, `size_gb`, `size_bytes` and `stats` on each item, `yunshu.path`, and a top-level `registry` object with model manager counters. Without a configured token everyone is anonymous.

## Retrieve a model

`GET /v1/models/{model_id}` returns one item in the same shape. The id may contain slashes (`mlx-community/Qwen3.5-0.8B-MLX-bf16`) and is resolved like inference does: exact id, alias, case-insensitive match. An unknown id is a `404`:

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

This route returns `404` for an id the server does not list even in single-model mode, where generation routes accept any name.

## The capability contract

Every card has a `yunshu.contract` object, and every generation route enforces the same object, so the list tells you exactly what a request may use.

| Key | States |
| --- | --- |
| `tools` | `supported`; `mode` (`template` when the chat template renders tools, `prompt` when Yunshu injects a tool prompt); `parallel`; accepted `tool_choice` values. |
| `structured_output` | `json_object`; `json_schema` with its engines (`in-house`, plus `llguidance` for schemas outside the in-house subset); `regex`; `choice`; `grammar` (Lark syntax, via `llguidance`). |
| `logprobs`, `reasoning` | Support, the largest `top_logprobs`, effort levels. |
| `media` | Input and output modalities beyond text. |
| `speculative` | `mode` (`mtp`, `dflash2` or `none`) and `lossless`. |
| `cache_tiers` | `ram`, and `ssd` when that tier is enabled. |
| `context` | Window length and maximum output tokens. |
| `unsupported_fields` | Always `"400"`. |

A request that uses what the contract rules out gets a `400` that names the field, in the error shape of the dialect:

- an `image`, `audio` or `video` content part on a model that does not accept that input;
- `tools`, `tool_choice`, `response_format`, `grammar`, the `guided_*` fields or `logprobs` on a model that does not generate text (embedding, reranker, speech, image models).

`reasoning_effort` and `thinking_budget` on a model without a reasoning mode are deliberately accepted and have no effect, because coding agents send an effort on every request. A checkpoint whose config cannot be read has no contract and is not gated.

## Load and unload

<Callout type="warn">
These routes change what is in memory. They need authentication: with no `YUNSHU_AUTH_TOKEN` set (and `YUNSHU_AUTH_DISABLED` not true) they answer `401` with `No authentication configured. Set YUNSHU_AUTH_TOKEN or YUNSHU_AUTH_DISABLED=true.` With a token set, send it as for any route.
</Callout>

### Load a model

`POST /v1/models/load` loads a model and starts its engine.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Model id as registered in the model manager. `model_id` is accepted as an alias; `model` wins when both are sent. | supported |
| `pin` | boolean | no | Default `false`. | accepted and ignored |

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

In multi-model mode the model must be registered (found under `YUNSHU_MODELS_DIR`), else `404`. Without a model manager the route loads the given path into the single engine; a batched engine refuses (`400`).

### Unload a model

`POST /v1/models/unload/{model_id}` releases a model's memory. It works in multi-model mode only (`400` otherwise). The id is resolved through aliases and case like inference does.

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

A model with requests in flight is not unloaded (`409`), so a running generation is never torn down.

### Errors

| Status | When |
| --- | --- |
| 400 | Empty `model`; load failed with a model-specific reason (the message says why); single-engine load on a batched engine; unload outside multi-model mode. |
| 401 | No token configured, or the token is missing or wrong. |
| 404 | Unknown model (`GET`, unload) or a model that is not registered (load). |
| 409 | The same model is already being loaded or unloaded; unload while requests are active, or the model became active during the unload. |
| 500 | Load failed for an unexpected reason (`Model loading failed`). |
| 503 | The engine is not initialized. |

## Support

| Feature | Status |
| --- | --- |
| `GET /v1/models` in OpenAI and Anthropic list shapes | <Support status="supported">supported</Support> |
| OpenRouter, vLLM, LM Studio metadata on every item | <Support status="supported">supported</Support> |
| Pagination parameters (`limit`, `after`) | <Support status="unsupported">not supported; the full list is returned</Support> |
| Capability contract enforced on generation routes | <Support status="supported">supported</Support> |
| Model load and unload | <Support status="supported">authenticated, multi-model mode for unload</Support> |
| `pin` on load | <Support status="unsupported">accepted and ignored</Support> |
| Deleting a model from disk through the API | <Support status="unsupported">not on these routes; see the Ollama layer or the CLI</Support> |

## Related

- [API overview](/docs/api/overview)
- [Chat completions](/docs/api/chat-completions)
- [Model support](/docs/guides/model-support)
- [Models getting started](/docs/getting-started/models)
- [Ollama layer](/docs/api/ollama)


---

<!-- api/ocr -->
---
title: OCR
description: POST /v1/ocr turns an uploaded image into text with an OCR model or, when none is loaded, any loaded vision-language model.
---

`POST /v1/ocr` is a Yunshu route, not part of the OpenAI API. It takes one image upload and returns the text read from it. The same route backs `yunshu ocr` and the console's "Image to text" dialog.

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

<Callout type="info">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. With API keys, the key needs inference permission and access to the model that ends up serving the request.
</Callout>

## Request

`multipart/form-data`.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `file` | file | yes | The image, at most 10 MB. The upload is verified with Pillow; a file that is not an image returns `400`. PNG, JPEG, WebP, TIFF and BMP are read. |
| `model` | string | no | Id of an OCR model or a vision-language model. Empty means the first loaded OCR model. |
| `task` | string | no | `text` (default), `formula` or `table`. Selects the recognition prompt (`Text Recognition:`, `Formula Recognition:`, `Table Recognition:`); an unknown value behaves like `text`. |
| `language` | string | no | A hint that steers the output language ("Respond in ..."). No language detection is performed. |

## How the model is chosen

1. A loaded OCR-type model is used first: the one named by `model`, or the first loaded one when `model` is empty. If `model` names an OCR model that is registered but not loaded, the model manager tries to load it.
2. Otherwise the request falls back to a loaded vision-language model, the one named by `model` if it is a loaded VLM, else any loaded VLM. The image is sent with the task prompt plus "Extract all text from this image verbatim", greedy (`temperature` 0) and at most 2048 new tokens. The OCR engine path allows 4096.
3. With neither, the server returns `503`.

The key's model scope is checked again against the model that was actually resolved, so a model-scoped key cannot reach another model by leaving `model` empty.

## Response

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

| Field | Description |
| --- | --- |
| `text` | The extracted text. It can be empty when the model reads nothing. |
| `model` | The id of the model that served the request. |
| `confidence` | Always `null`: neither path produces a confidence score, and Yunshu does not invent one. |
| `language` | Your `language` hint on the VLM fallback; `null` on the OCR engine path. No detection is done. |
| `task` | Echo of the request's `task`. |
| `prompt_tokens`, `completion_tokens`, `usage` | Token counts. `usage.image_tokens` is the image's share; on the VLM fallback it is estimated from the image size and the vision config when the engine does not report it. |

The response has no text boxes or positions: it is the text only.

## Examples

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

## Cancellation

The request is registered with the request tracker and is cancelled when the client disconnects, or by `POST /v1/cancel` (see [Extensions](/docs/api/extensions)). On the OCR engine path the generation call itself runs to its token limit; the handler returns promptly and the result is discarded. On the VLM fallback the generation stops between decode steps.

## Errors

| Status | When |
| --- | --- |
| `400` | The upload is not an image the server can read. |
| `401`, `403` | Missing or invalid credentials, or the key may not infer or may not use the resolved model. |
| `413` | The image is larger than 10 MB. |
| `503` | No OCR model and no vision-language model is loaded. |
| `507` | Out of GPU memory. |
| `500` | Extraction failed; the server log has the cause. |

## Support

| Feature | Status |
| --- | --- |
| Text, formula and table tasks | <Support status="extension">Yunshu extension</Support> |
| Vision-language model fallback | <Support status="supported">supported</Support> |
| Confidence scores | <Support status="unsupported">always null</Support> |
| Text positions or boxes | <Support status="unsupported">text only</Support> |
| PDF input | <Support status="unsupported">images only</Support> |

## Related

- [Images](/docs/api/images) for image generation, edits and variations.
- [Multimodal](/docs/guides/multimodal) for which routes serve which input.
- [Console](/docs/getting-started/console) for the "Image to text" dialog.


---

<!-- api/ollama -->
---
title: Ollama
description: Ollama-compatible /api routes so Ollama clients and SDKs can talk to Yunshu, with a precise list of what is real and what is not.
---

Yunshu answers the Ollama native API under `/api`, so tools written for Ollama (the official `ollama` Python and JavaScript libraries, Open WebUI, Continue and similar) can point at the server without changes. The routes are a thin translation layer: each `/api/chat`, `/api/generate`, `/api/embed` or `/api/embeddings` request is converted to the matching OpenAI request and sent back to the same server, so model routing, authentication, the prefix cache, tool calling and constrained decoding behave exactly as on the OpenAI routes.

<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">
The default port is 8000, not Ollama's 11434, so set the host explicitly (for example `http://localhost:8000`). Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set; the `Authorization` header is forwarded on the internal request. Errors use Ollama's shape, `{"error": "message"}`, with the HTTP status of the underlying failure. Models are named as Yunshu names them: a `:latest` suffix is accepted and ignored, and the response echoes the name you sent.
</Callout>

## What is real

| Route | Status | Behavior |
| --- | --- | --- |
| `POST /api/chat` | <Support status="supported">real</Support> | Chat with `messages`, `tools`, `format`, `options`, `think`, images. Streams NDJSON by default. |
| `POST /api/generate` | <Support status="supported">real</Support> | Single prompt with optional `system` and `images`. An empty prompt returns `{"done": true, "done_reason": "load"}` without generating. |
| `POST /api/embed` | <Support status="supported">real</Support> | `input` is a string or list; optional `dimensions`. |
| `POST /api/embeddings` | <Support status="supported">real</Support> | Legacy single-prompt form. |
| `GET /api/tags` | <Support status="supported">real</Support> | Lists the models Yunshu serves. |
| `POST /api/show` | <Support status="supported">real</Support> | Model card in Ollama's shape. |
| `GET /api/ps` | <Support status="supported">real</Support> | Models currently loaded. |
| `GET /api/version` | <Support status="supported">real</Support> | Yunshu's version. |
| `POST /api/pull` | <Support status="partial">Hugging Face repositories only, multi-model mode</Support> | Downloads a native MLX repository. |
| `POST /api/create` | <Support status="partial">naming an existing model only</Support> | `from` plus a name; no Modelfile features. |
| `POST /api/copy` | <Support status="partial">alias, no duplicate weights</Support> | Creates a symlinked name. |
| `DELETE /api/delete` | <Support status="partial">multi-model mode, models directory only</Support> | Removes an alias or a checkpoint inside the models directory. |
| `POST /api/push` | <Support status="unsupported">not supported</Support> | Always `501`. |

Ollama's blob upload and existence-check routes are not served. Ollama's OpenAI-compatible `/v1` routes are Yunshu's own OpenAI routes, see [Chat Completions](/docs/api/chat-completions).

## Chat and generate

Both routes accept these fields.

| Field | Routes | Status | Behavior |
| --- | --- | --- | --- |
| `model` | both | supported | Required. Single-model mode serves the loaded model under any name. |
| `messages` | chat | supported | Required array of `{role, content, images, tool_calls, tool_name}`. |
| `prompt`, `system`, `images` | generate | supported | `system` becomes a system message; `images` are base64 strings. |
| `stream` | both | supported | Default `true` (NDJSON, `application/x-ndjson`). `false` returns one JSON object. |
| `format` | both | supported | `"json"` or a JSON schema object; enforced by constrained decoding. |
| `tools` | both | supported | Function tools in Ollama/OpenAI form. Calls come back in `message.tool_calls` with `arguments` as an object. |
| `think` | both | supported | `true`/`false` toggles thinking; `"low"`, `"medium"`, `"high"` set the reasoning effort. Reasoning comes back as `message.thinking` (chat) or `thinking` (generate). |
| `options.temperature`, `top_p`, `top_k`, `min_p`, `seed`, `presence_penalty`, `frequency_penalty` | both | supported | Passed to the engine. |
| `options.repeat_penalty` | both | supported | Mapped to `repetition_penalty`. |
| `options.num_predict` | both | supported | Positive values are the token limit. `-1`, `-2` or omitted use 8192. |
| `options.stop` | both | supported | String or list. |
| `options.num_ctx`, `num_batch`, `num_gpu`, `mirostat*`, `typical_p`, `penalize_newline`, `use_mmap` and other runner options | both | accepted and ignored | The context size is a property of the loaded model. |
| `keep_alive` | both | accepted and ignored | Model lifetime is managed by Yunshu, not per request. |
| `template`, `raw`, `context`, `suffix`, `truncate` | generate/chat | accepted and ignored | Prompt templating always uses the model's own chat template. |

Message `images` are base64 strings (data is wrapped as a PNG data URL) and need a vision-language model.

## Examples

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

### Structured output

```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"]}
}'
```

## Response

Non-streaming `/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` returns `response` instead of `message`. `done_reason` is `stop` or `length` (a tool call ends with `stop`). Durations are nanoseconds; when the engine reports its own timings they are used, otherwise they are measured at the gateway. `load_duration` is 0 unless the engine reports a load time.

## Streaming

With `stream` true (the default) the response is NDJSON, one JSON object per line: repeated chunks with `done: false` carrying `message.content` (or `response`) and, when the model reasons, `message.thinking`, then one final object with `done: true`, `done_reason`, the timing fields and any `message.tool_calls`. Tool calls are delivered on the last object, not incrementally. A failure after the stream has started is a single `{"error": "..."}` line and no `done: true` line.

## Models and embeddings

- `GET /api/tags` returns `{"models": [{name, model, modified_at, size, digest, details}]}`. `size` is the weight size from the model card when known. `digest` is a hash of the model id, not of file contents.
- `POST /api/show` takes `model` (or `name`) and returns the model card in Ollama's shape (`details`, `model_info`, `capabilities`, `modelfile`, `parameters`, `template`, `modified_at`). An unknown model is `404`.
- `GET /api/ps` returns loaded models with `expires_at` always `0001-01-01T00:00:00Z` (they do not expire).
- `POST /api/embed` returns `{"model", "embeddings": [[...]], "total_duration", "load_duration", "prompt_eval_count"}`; `POST /api/embeddings` returns `{"embedding": [...]}`. Both need an embedding model and use the same engine as [Embeddings](/docs/api/embeddings).

## Model management

These routes only work in multi-model mode (`yunshu serve --models-dir`), and need the same permission as loading or unloading models; in single-model mode they answer `400`.

- `POST /api/pull` with `{"model": "org/name"}` downloads a Hugging Face repository that holds native safetensors weights and registers it. A name that is already registered returns success at once. Ollama registry names (`library/llama3:8b`) and GGUF repositories are rejected with `400`. The reply is a single `{"status": "success"}` line (or JSON with `"stream": false`); there are no progress events.
- `POST /api/create` accepts only `{"model": "new-name", "from": "existing-model"}` and creates a persistent alias. Fields `files`, `adapters`, `quantize`, `parameters`, `template`, `system` and `messages` are rejected with `400`.
- `POST /api/copy` with `source` and `destination` creates an alias as a symlink to the same weights. An existing destination is `409`.
- `DELETE /api/delete` with `model` unloads and removes the alias, or deletes a checkpoint directory inside the models directory. A checkpoint outside the models directory is refused (`400`), a checkpoint that still has aliases is `409`, and a model in use is `409`.
- `POST /api/push` always returns `501` with the message that registry uploads are unsupported.

## Errors

`{"error": "message"}` with the status of the failure: `400` for a bad body or missing `model` or `messages`, `401`/`403` for authentication and permission, `404` for an unknown model, `409` for model-management conflicts, `501` for `/api/push`, and the upstream status (for example `400` for a prompt over the context window) for generation errors.

## Support

| Feature | Status |
| --- | --- |
| Chat, generate, streaming NDJSON | <Support status="supported">supported</Support> |
| Tools, structured `format`, `think`, images | <Support status="supported">supported</Support> |
| Embeddings (`/api/embed`, `/api/embeddings`) | <Support status="supported">supported</Support> |
| Tags, show, ps, version | <Support status="supported">supported</Support> |
| Pull, create, copy, delete | <Support status="partial">native MLX repositories and aliases only</Support> |
| Runner options such as `num_ctx`, `keep_alive`, Modelfile `template` | <Support status="partial">accepted and ignored</Support> |
| Registry upload (`/api/push`), GGUF import, blobs | <Support status="unsupported">not supported</Support> |

## Related

- [Chat Completions](/docs/api/chat-completions)
- [Embeddings](/docs/api/embeddings)
- [Models](/docs/api/models)
- [Model support](/docs/guides/model-support)


---

<!-- api/operations -->
---
title: Operations
description: Health probes, Prometheus metrics, live request inspection and cancellation, server properties, interactive docs, rate limiting and logging.
---

These routes are for running Yunshu as a service: probes for a service manager or load balancer, a Prometheus endpoint, a live view of in-flight requests, and the OpenAPI documents. For the richer status object see `GET /v1/yunshu/status` on [Extensions](/docs/api/extensions).

<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" />

## Which routes need the token

Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. When it is set, these paths stay public so probes and docs keep working: `/health`, `/health/live`, `/health/ready`, `/version`, `/docs`, `/redoc`, `/openapi.json`, `/` and the console assets. Everything else, including `/metrics`, `/props` and the request routes, needs `Authorization: Bearer <token>` or `x-api-key`.

## Health probes

| Route | Purpose | Response |
| --- | --- | --- |
| `GET /health` | Minimal liveness summary. Always `200` while the process answers. | `{"status": "ok", "engine": {"loaded": bool}, "server_state": "running", "uptime_seconds": 12.3}` |
| `GET /health/live` | Liveness probe. | `{"alive": true, "state": "running"}` |
| `GET /health/ready` | Readiness probe. `200` when ready, `503` when not. | `{"ready": bool, "checks": {...}}` |

`server_state` and `state` are `running`, `shutdown_requested` or `shutting_down`. These endpoints are public and deliberately return no model names, queue depth or memory figures.

`GET /health/ready` is `503` when any of these holds:

- the server is draining for shutdown (`checks.not_shutting_down` is `false`),
- no model is loaded and none can be loaded on demand (`checks.model_loaded` is `false`),
- Metal memory use is at or above 95 percent of system memory (`checks.gpu_memory_ok` is `false`).

In multi-model mode, models that are registered but not yet loaded count as ready, because a request loads them on demand; `checks.models_registered` reports how many. When no model is loaded because loading failed, the body carries a `reason` with the load error.

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

Use `GET /health/live` as the liveness check and `GET /health/ready` as the readiness check.

## Prometheus metrics

`GET /metrics` returns the Prometheus text exposition format. It is always mounted and follows the bearer token when one is set, so configure bearer authentication in your Prometheus scrape job. Metrics are exposed under the `yunshu_` prefix:

| Family | Contents |
| --- | --- |
| `yunshu_request_total`, `yunshu_request_duration_seconds` | HTTP requests by method, status and endpoint bucket; request latency histogram. |
| `yunshu_gateway_active_requests` | Inference requests currently in flight. |
| `yunshu_tokens_generated_total`, `yunshu_ttft_seconds`, `yunshu_itl_seconds`, `yunshu_inference_duration_seconds`, `yunshu_prefill_duration_seconds` | Generated tokens, time to first token, inter-token latency, inference and prefill duration histograms. |
| `yunshu_itl_p50_ms`, `yunshu_itl_p99_ms`, `yunshu_step_duration_ms`, `yunshu_compute_utilization_pct` | Latency percentiles and step timing gauges. |
| `yunshu_kv_cache_*`, `yunshu_kv_prefix_cache_*`, `yunshu_radix_*` | KV block usage, prefix cache entries, hits, misses and evictions. |
| `yunshu_apc_*` | The automatic prefix cache of the VLM runner: RAM and SSD tiers, lookups by tier, matched tokens, evictions, WARM tier bytes and compression ratio. |
| `yunshu_spec_*`, `yunshu_mtp_*` | Speculative decoding: draft and accepted tokens, acceptance rate, MTP cycles, n-gram proposals. Labeled with `model_id`. |
| `yunshu_gpu_busy_seconds_total`, `yunshu_round_driver_busy_seconds_total` | Cumulative GPU-busy seconds; the idle fraction over a window is one minus the rate of the first. |
| `yunshu_scheduler_*`, `yunshu_chunked_prefill_*`, `yunshu_attention_eviction_*` | Scheduler and prefill gauges of the batched engine. |
| `yunshu_model_warmup_*`, `yunshu_lora_*`, `yunshu_response_cache_*` | Warm-up runs, LoRA adapter bookkeeping, response cache hits and misses. |

Which families carry data depends on the engine and features in use; unused families stay at zero. Memory figures in metrics are in bytes.

## Inspect and cancel requests

Every request has an id (your `X-Request-Id` or a generated one, see [Extensions](/docs/api/extensions)). These routes work on that id.

`GET /v1/requests` lists in-flight 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` is `starting`, `queued`, `prefill` or `decode`. A queued request shows `queue_position` and `queue_est_wait_ms`; a decoding request shows `completion_tokens`. Generations that did not come through a tracked HTTP path (for example batch jobs) appear with phase `running`.

`GET /v1/requests/{request_id}` returns one request as `{"object": "yunshu.request", ...}` with the same fields, or `404` when it is unknown or already finished. Poll it to follow a long non-streaming prefill.

`DELETE /v1/requests/{request_id}` cancels by the client request id or the completion id. It returns `{"object": "yunshu.request", "id": ..., "status": "cancelled"}`, or `"cancelling"` when the request has been admitted but not yet handed to the engine (it is cancelled as soon as it registers). Unknown ids return `404`. `POST /v1/cancel` does the same by body; see [Extensions](/docs/api/extensions).

## Server properties

`GET /props` and `GET /v1/props` (the same handler) return llama.cpp-style properties of the served model, for tools that probe for them:

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

It reports a single served model; with no model loaded, or in multi-model mode where there is no single served engine, it returns `503`. For per-model details use `GET /v1/models`; see [Models](/docs/api/models).

`GET /version` returns `{"version", "service": "yunshu", "description"}`.

## Interactive docs

`GET /docs` serves Swagger UI, `GET /redoc` serves ReDoc and `GET /openapi.json` serves the OpenAPI document of every registered route. All three are public even when a token is set.

## Management endpoints

Yunshu-only routes under `/v1/yunshu/*` (see also [Auth and keys](/docs/guides/auth-and-keys) and [Telemetry](/docs/guides/telemetry)). Per-route detail and test status: `docs/guides/API_SURFACE.md`. Routes marked admin need an admin token.

| Route | What it returns or does |
|---|---|
| `GET /v1/yunshu/memory` | memory ledger: owners (weights, prefix cache RAM and warm tier, MLX cache, live KV), working set, host pressure |
| `GET /v1/yunshu/cache, /cache/tiers` | prefix-cache entries and per-tier usage, hits and SSD read rates (hash labels only, never tokens) |
| `POST /v1/yunshu/cache/clear, /cache/tiers/clear` | drop resident APC entries or one tier (admin; refuses with 409 unless engines are idle for the global clear) |
| `POST /v1/yunshu/downloads`, `GET /v1/yunshu/downloads`, `DELETE /v1/yunshu/downloads/{id}` | queue, list and cancel Hugging Face downloads into the models dir; refuses with 507 when the disk cannot hold the repo |
| `GET /v1/yunshu/models/local` | every model on disk, registered or not |
| `POST /v1/yunshu/models/register`, `DELETE /v1/yunshu/models/register/{model_id}` | register or unregister a local checkpoint without loading it (multi-model mode) |
| `POST /v1/yunshu/models/{id}/reload`, `GET /v1/yunshu/models/{id}/fit`, `GET /v1/yunshu/models/impact`, `POST /v1/yunshu/models/cancel` | reload to apply settings, dry-run memory fit, eviction impact, cancel a load or pull |
| `GET /v1/yunshu/logs, /logs/stream` | redacted in-memory server log ring (admin), plain or as server-sent events |
| `GET /v1/yunshu/spec-decode` | MTP / DFlash drafted and accepted tokens per draft depth |
| `GET /v1/yunshu/requests/recent, /requests/history` | finished-request ring and rotated serve-log metadata (numbers only, no prompt text) |
| `GET /v1/yunshu/bundle, /bundle/manifest` | local diagnostics file and the list of what it contains; never uploaded |

## Tavily-compatible routes

Under `/tavily` Yunshu serves a local implementation of the Tavily REST API, backed by its own search and fetch layers: `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` and an MCP endpoint `POST /tavily/mcp`. There is no `/v1` in these paths, and errors use `{"detail": {"error": "..."}}`. When a token is set, Tavily clients may pass it as the bearer token or as `api_key` in the request body. Credits are not billed: `GET /tavily/usage` always reports zero. See the [Web search guide](/docs/guides/web-search) for providers and setup.

## Rate limiting and admission

- **Per-IP rate limit.** Off by default. Setting `YUNSHU_RATE_LIMIT_RPM` to a positive number turns on a token bucket per client IP (requests per minute, burst equal to the limit). Exceeding it returns `429` with `Retry-After` in the error format of the route. Health, docs and `/metrics` are exempt, and so are CORS preflights. `X-Forwarded-For` is only honored from proxies listed in `YUNSHU_TRUSTED_PROXIES`.
- **Admission control.** Always on for generation routes. `YUNSHU_QUEUE_LIMIT` (default 64) caps requests in flight and answers `429` beyond it; high memory pressure with other requests running answers `503`. Both carry `Retry-After`. See [Extensions](/docs/api/extensions).
- **Deadlines.** The `X-Yunshu-Deadline-Ms` request header bounds how long a request may wait and run.

## Logging

Each request is logged with its request id, method, path, status and latency, and the id is returned in the `X-Request-ID` response header. Successful requests are logged at debug level, `4xx` at warning and `5xx` at error, so the default `INFO` level shows only problems; set `YUNSHU_LOG_LEVEL=DEBUG` to see every request. Requests slower than `YUNSHU_SLOW_REQUEST_THRESHOLD` seconds (default 30) log a `SLOW_REQUEST` warning, and memory use above 85 percent of unified memory logs a `MEMORY_PRESSURE` warning. Health, docs and `/metrics` requests are not logged. When Yunshu runs as a launchd service, the service log is rotated and compressed with secrets redacted; see [Service](/docs/getting-started/service).

Extra introspection routes under `/debug` exist but are mounted only when `YUNSHU_DEBUG_ROUTES=1`, and need the token or `YUNSHU_AUTH_DISABLED`. They are diagnostic aids, not a stable API.

## Examples

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

## Errors

| Status | When |
| --- | --- |
| `401` | A token is set and the route is not public, and the request has no valid token. |
| `404` | Unknown request id. |
| `429` | Rate limit (when enabled) or queue limit. |
| `503` | Readiness failing, memory pressure refusal, or `GET /props` with no single model loaded. |

## Support

| Feature | Status |
| --- | --- |
| Liveness, readiness, minimal health | <Support status="supported">supported</Support> |
| Prometheus `/metrics` | <Support status="supported">supported</Support> |
| Request listing, polling and cancellation | <Support status="extension">Yunshu extension</Support> |
| `/props` | <Support status="partial">minimal llama.cpp-style subset, single model</Support> |
| Per-IP rate limit | <Support status="partial">off unless `YUNSHU_RATE_LIMIT_RPM` is set</Support> |
| Slot management routes (`/slots`) | <Support status="unsupported">not provided</Support> |
| Tavily credit billing | <Support status="unsupported">local implementation, no billing</Support> |

## Related

- [Extensions](/docs/api/extensions) for `GET /v1/yunshu/status`, warm-up and request ids.
- [Service](/docs/getting-started/service) for running under launchd.
- [Troubleshooting](/docs/guides/troubleshooting) for what to check when a probe fails.
- [Web search guide](/docs/guides/web-search) for the Tavily-compatible routes.


---

<!-- api/overview -->
---
title: API overview
description: Base URLs, the dialects Yunshu serves, authentication, how the model field is resolved, error shapes, request ids and the route map for the whole API.
---

One Yunshu process serves several wire formats at once: the OpenAI API, the Anthropic Messages API, an Ollama-compatible layer, a JSON-RPC MCP endpoint and a set of vLLM-style utility routes (tokenize, score, rerank). All of them are thin layers over the same engine. This page covers what all of them share. The per-route details are on the pages linked in the [route map](#route-map).

## Base URLs

The server listens on port `8000` by default.

| Client | Base URL | Notes |
| --- | --- | --- |
| OpenAI SDKs and any OpenAI-compatible tool | `http://localhost:8000/v1` | The SDK appends `/chat/completions`, `/embeddings` and so on. |
| Anthropic SDKs | `http://localhost:8000` | The SDK appends `/v1/messages`. Do not add `/v1` yourself. |
| Ollama clients | `http://localhost:8000` | Routes live under `/api/*`. |
| vLLM-style tools (tokenize) | `http://localhost:8000` | `/tokenize` and `/detokenize` also exist without the `/v1` prefix. |

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

## Authentication

Authentication supports the static admin token and named API keys with scopes, expiry and rolling quotas.

- `YUNSHU_AUTH_TOKEN` is unset and no API keys exist (the default): inference routes (chat, completions, embeddings, tokenize and so on) are open. Operational routes such as `POST /v1/models/load` answer `401` because there is no way to authorize them.
- `YUNSHU_AUTH_TOKEN` is set: every request except a short public list needs a valid token or API key. The public paths are `/health`, `/health/live`, `/health/ready`, `/version`, `/docs`, `/openapi.json`, `/redoc`, `/`, `/console` and the static asset prefixes.
- `YUNSHU_AUTH_DISABLED=true` turns authentication off entirely, operational routes included. Use it for local development only.

Send the token either way; the server accepts both on every route, whatever the dialect:

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

If both headers are present the `Authorization: Bearer` value is used. The comparison is constant time. A missing token answers `401` with the message `Missing or invalid Authorization header`; a wrong token answers `401` with `Invalid or missing API key`. Both carry a `WWW-Authenticate: Bearer` header.

Named API keys use the same headers; `infer` and `admin` scopes restrict access, expired/revoked keys fail, and exceeded quotas return `429`. Keys share one server’s data, except Files and Conversations: an infer key sees only its own.

<Callout type="info">
When neither a token nor API keys are configured the key your SDK sends is ignored, so any placeholder such as `not-needed` or `sk-local` works. Bind to localhost (the default) or set a token before exposing the server to a network.
</Callout>

## The `model` field

What `model` means depends on how the server was started.

| Mode | How it is started | Meaning of `model` |
| --- | --- | --- |
| Single-model | `YUNSHU_MODEL` set, or one model passed to `yunshu serve` | Advisory. Every generation route serves the one loaded model whatever name you send, and the name is echoed back in the response. `GET /v1/models/{id}` still returns `404` for an id the server does not list. |
| Multi-model | `YUNSHU_MULTI_MODEL=1` with models under `YUNSHU_MODELS_DIR` | A selector. The name is resolved against the registry (aliases, case-insensitive match, and the part after the last `/`), the model is loaded on first use, and an unknown name answers `404`. |

`GET /v1/models` lists the ids you can use; see [Models](/docs/api/models). Embedding, reranking and scoring models are separate checkpoints: in multi-model mode you name them in `model`, in single-model mode the one loaded model must itself be the embedder or reranker.

Every generation route also checks the model's capability contract before running. A request that uses something the model does not have (an image part on a text-only model, tools on an embedding model, `logprobs` on a model that does not generate text) is a `400` that names the field. See [Models](/docs/api/models) for the contract.

## Errors

The error body follows the dialect of the route that failed, including errors raised by authentication, rate limiting and request validation before the route runs.

OpenAI-shaped routes (everything except Anthropic, Ollama, MCP and 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 routes (`/v1/messages`, `/messages`, and the `count_tokens` routes):

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

| Status | OpenAI `type` / `code` | Anthropic `error.type` |
| --- | --- | --- |
| 400 | `invalid_request_error` / `validation_error` for schema failures, `bad_request` otherwise | `invalid_request_error` |
| 401 | `authentication_error` / `invalid_api_key` | `authentication_error` |
| 404 | `invalid_request_error` / `model_not_found` (an unknown route is `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`, with `Retry-After` | `rate_limit_error` |
| 500 | `server_error` / `internal_error` | `api_error` |
| 503 | `server_error` / `service_unavailable`, with `Retry-After` | `overloaded_error` |

Other dialects: the Ollama routes answer `{"error": "message"}`, the MCP endpoint answers a JSON-RPC 2.0 error object, and the Tavily routes answer `{"detail": {"error": "message"}}`.

Details worth knowing:

- Request-body validation failures are `400`, not `422`, on every dialect. `error.param` names the offending field.
- A prompt that does not fit the model's context window is a `400` with `code: "context_length_exceeded"`.
- The `x_yunshu.hint` is a one-line fix for common errors; the same text is appended to `message` as `(hint: ...)` because many SDKs show only the message.
- A server that is full (`YUNSHU_QUEUE_LIMIT`) answers `429` with `Retry-After`; one short of memory answers `503`. The OpenAI and Anthropic SDKs retry both.
- An error after a stream has started cannot change the HTTP status. The stream carries one final `data: {"error": ...}` event and then `data: [DONE]`.

## Request ids and headers

Every request gets an id. Send `X-Request-Id` (1 to 128 characters of `A-Z a-z 0-9 . _ : -`) to choose it, otherwise the server generates `req_...`. The id is echoed in the `X-Request-Id` response header, errors included, and appears in `error.x_yunshu.request_id` and `x_yunshu.request_id`. It identifies the request in the server log.

Other headers the generation routes understand or return:

| Header | Direction | Meaning |
| --- | --- | --- |
| `X-Request-Id` | both | Request id described above. |
| `X-Yunshu-Deadline-Ms` | request | Wall-clock budget from arrival, queue wait included. Past it the generation is cancelled and the answer is a `504` (or one terminal error event on a stream). |
| `X-Yunshu-Queue-Position`, `X-Yunshu-Queue-Est-Wait-Ms` | response | How busy the server was when the request arrived. |
| `X-Yunshu-TTFT-Ms`, `X-Yunshu-Prefill-Tps`, `X-Yunshu-Decode-Tps`, `X-Yunshu-Cached-Tokens`, `X-Yunshu-Cache-Tier`, `X-Yunshu-Total-Ms` | response (non-streaming) | Compact copies of the numbers in `x_yunshu`. A header is omitted when the value is unknown. |
| `X-Yunshu-Cancelled` | response | `true` when the answer was cut short by a cancel or a deadline. |
| `X-Yunshu-Spec`, `X-Yunshu-Spec-Acceptance` | response | Speculative decoding mode and acceptance rate, when it ran. |
| `Retry-After` | response | Seconds to wait on `429` and `503`. |

A generation in progress can be cancelled by its request id; see [Operations](/docs/api/operations).

## Yunshu extension fields

Everything Yunshu adds is namespaced so the official SDKs keep working unchanged.

- `x_yunshu` in the JSON body of a non-streaming chat, completions, Responses or Messages answer: queue wait, time to first token, prefill and decode speed, cached tokens and the cache tier, speculative decoding counters, and `cancelled`, `budget` or `context_policy` when they apply. Streaming answers carry the same object in the final usage chunk (OpenAI) or inside `usage` (Messages, Responses).
- `error.x_yunshu` on OpenAI-shaped errors: `hint`, `request_id` and, for overload errors, the reason and queue depth.
- Server-sent comment lines such as `: yunshu-progress {...}` while a request waits or prefills. SSE parsers ignore comments.
- `yunshu` inside every model object from `GET /v1/models`.
- Extra request fields (for example `top_n_sigma`, `spec_decode`, `thinking_budget`, `keep_alive`, `grammar`) on the generation routes.

The fields and their meaning are listed in [Extensions](/docs/api/extensions).

## Route map

| Route | Page |
| --- | --- |
| `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` | [Stored 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` (also without `/v1`) | [Messages](/docs/api/messages) |
| Server-side web search, web fetch and MCP connector tools | [Server tools](/docs/api/server-tools) |
| `POST /v1/embeddings`, `POST /v1/pooling` | [Embeddings](/docs/api/embeddings) |
| `POST /v1/rerank`, `POST /v1/score`, `POST /v1/classify` | [Rerank and scoring](/docs/api/rerank) |
| `POST /v1/tokenize`, `POST /v1/detokenize`, `POST /v1/apply-template` (also without `/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` | [Audio](/docs/api/audio) |
| `POST /v1/images/generations`, `POST /v1/images/edits`, `POST /v1/images/variations` | [Images](/docs/api/images) |
| `GET /v1/models`, `GET /v1/models/{id}`, `POST /v1/models/load`, `POST /v1/models/unload/{id}` | [Models](/docs/api/models) |
| `POST /v1/files`, `GET /v1/files`, `GET /v1/files/{id}`, `GET /v1/files/{id}/content`, `DELETE /v1/files/{id}` | [Files](/docs/api/files) |
| `POST /v1/batches`, `GET /v1/batches`, `POST /v1/messages/batches` and related | [Batches](/docs/api/batches) |
| `POST /v1/evals` and related | [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` and related | [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` | [Operations](/docs/api/operations) |

## OpenAI and Anthropic features that are not served

Yunshu is a local inference engine, so APIs that exist to run hosted services have no counterpart. A request to one of these routes answers `404`.

<NotServed>

| Not served | API | Reason |
| --- | --- | --- |
| `/v1/fine_tuning/jobs` | OpenAI | No training on this server. Use `mlx-lm` tooling to produce LoRA adapters and load them with `lora_adapter` where the engine supports it. |
| `/v1/moderations` | OpenAI | No hosted moderation model. |
| `/v1/assistants`, `/v1/threads`, `/v1/threads/{id}/runs` | OpenAI (legacy) | Superseded by the Responses API, which Yunshu serves. |
| `/v1/vector_stores`, file search | OpenAI | No hosted retrieval store. Use `POST /v1/embeddings` with your own index. |
| `/v1/uploads` | OpenAI | Multipart chunked uploads are not implemented. `POST /v1/files` accepts a single upload. |
| `/v1/containers`, code interpreter | OpenAI | No hosted sandbox. |
| `/v1/videos` (Sora) | OpenAI | No video generation endpoint. |
| `/v1/organizations/*`, `/v1/skills` | Anthropic | Account and hosted-skill management does not exist locally. |
| Code execution, computer use and memory tools | Anthropic and OpenAI | Hosted tools with no local meaning. Client-side function tools work. |

</NotServed>

The tools Yunshu does run inside the generation loop (web search, web fetch, MCP connector) are described under [Server tools](/docs/api/server-tools).

## Related

- [Chat completions](/docs/api/chat-completions)
- [Models](/docs/api/models)
- [Extensions](/docs/api/extensions)
- [Configuration](/docs/guides/configuration)


---

<!-- api/realtime -->
---
title: Realtime
description: The OpenAI Realtime protocol over WebSocket (GA and beta schemas) and WebRTC, with ephemeral client secrets, text and voice turns, and tool calls.
---

Yunshu serves the OpenAI Realtime protocol: a long-lived WebSocket (or WebRTC data channel) that carries JSON events in both directions. You configure a session, add conversation items or stream microphone audio, and the server streams back text, audio and tool-call events. The official `openai` SDK (`client.realtime.connect()`) works against it.

<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" />

## Connecting

Open a WebSocket to `ws://localhost:8000/v1/realtime?model=local`. The `model` query parameter selects the model for the session (in single-model mode any name resolves to the served model; an unknown model in multi-model mode produces an `error` event with code `model_not_found` and closes the socket).

| Dialect | How it is chosen | Notes |
| --- | --- | --- |
| GA (default) | `WS /v1/realtime` without a beta header | What `client.realtime.connect()` speaks: nested `audio.input` / `audio.output` session, `response.output_text.delta` style event names. |
| Beta | `OpenAI-Beta: realtime=v1` on `WS /v1/realtime`, or always on `WS /realtime` | Flat session (`modalities`, `voice`, `input_audio_format`, ...), `response.text.delta` style names, plus `conversation.created`. |

Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. Then the socket needs one of:

- an `Authorization: Bearer <token>` header,
- the browser subprotocol `openai-insecure-api-key.<token>` (send `realtime` as a second subprotocol),
- a `?token=` query parameter,
- an ephemeral client secret (`ek_...`) in any of those places, see below.

An `Origin` header, when present, must be allowed by `YUNSHU_CORS_ORIGINS` (unless that is `*`). Failed checks close the connection before the upgrade, so the client sees a failed handshake.

The first server message is `session.created`. The GA dialect then stays quiet until you speak; the beta dialect also sends `conversation.created`. If no model is loaded the server sends an `error` event right away.

## Session configuration

Send `session.update` with a `session` object. Shown in the GA shape, with the beta name in parentheses.

| Field | Description | Status |
| --- | --- | --- |
| `output_modalities` (`modalities`) | `["text"]` (default) or `["audio"]`. The beta form also accepts `["text", "audio"]`. | supported |
| `instructions` | System prompt for responses. | supported |
| `audio.output.voice` (`voice`) | One of `alloy`, `echo`, `shimmer`, `ash`, `ballad`, `coral`, `sage`, `verse`, or a native speaker of an omni model. An invalid voice is ignored. | supported |
| `audio.input.format`, `audio.output.format` (`input_audio_format`, `output_audio_format`) | GA: `audio/pcm` (24 kHz mono 16-bit), `audio/pcmu`, `audio/pcma`. Beta: `pcm16`, `g711_ulaw`, `g711_alaw`. | supported |
| `audio.input.turn_detection` (`turn_detection`) | `null` (manual commits) or `{"type": "server_vad", "threshold", "prefix_padding_ms", "silence_duration_ms", "idle_timeout_ms"}`. | supported |
| `audio.input.noise_reduction` (`input_audio_noise_reduction`) | `{"type": "near_field"}` or `far_field`, or `null`. | supported |
| `tools`, `tool_choice` | Function tools; `tool_choice` is `auto`, `none`, `required` or a named function. | supported |
| `max_output_tokens` (`max_response_output_tokens`) | Integer. | supported |
| `temperature` | Sampling temperature, default 0.7. | supported |
| `audio.input.transcription` | The ASR model is whichever ASR engine is loaded; the field does not pick one. | accepted and ignored |
| `top_p`, `top_k`, `min_p`, `repetition_penalty`, `frequency_penalty`, `presence_penalty`, `logit_bias`, `seed`, `enable_thinking` | Yunshu sampling extensions, passed through. | extension |
| `tracing`, `include`, `type` | Ignored. | accepted and ignored |

Defaults for server VAD are `threshold` 0.5, `prefix_padding_ms` 300, `silence_duration_ms` 500, and a barge-in threshold of 120 ms of sustained speech (`barge_in_min_ms`, not exposed in the GA session). They can be changed server-wide with `YUNSHU_REALTIME_VAD_THRESHOLD`, `YUNSHU_REALTIME_PREFIX_PADDING_MS`, `YUNSHU_REALTIME_SILENCE_MS` and `YUNSHU_REALTIME_BARGE_IN_MS`. `YUNSHU_REALTIME_VAD=silero` switches from the default energy-based detector to Silero VAD (model `YUNSHU_REALTIME_VAD_MODEL`). `turn_detection.type` of `semantic_vad` is served as `server_vad`; `eagerness`, `create_response` and `interrupt_response` are ignored (a response is always created after a detected turn, and speech interrupts a playing response).

Invalid values for a field (for example an unknown audio format) are skipped silently and the previous value is kept; the `session.updated` event shows the effective session.

## Client events

| Event | Behaviour |
| --- | --- |
| `session.update` | Changes the session; answered with `session.updated`. |
| `conversation.item.create` | Adds an item (message, function call, function call output). Answered with `conversation.item.added` and `conversation.item.done` (GA) or `conversation.item.created` (beta). Duplicate ids and oversized items are rejected with `error`. |
| `conversation.item.delete` | Removes an item; answered with `conversation.item.deleted`. |
| `conversation.item.truncate` | Records how much audio of an assistant item was heard; answered with `conversation.item.truncated`. |
| `input_audio_buffer.append` | Appends base64 audio. |
| `input_audio_buffer.commit` | Transcribes the buffer and adds it as a user message. |
| `input_audio_buffer.clear` | Discards the buffer. |
| `response.create` | Starts a response. `response` may carry `output_modalities`, `instructions`, `tools`, `tool_choice`, `temperature`, `max_output_tokens`, `input` (items to use as the whole context for this response; `[]` clears it) and `conversation: "none"` (keep it out of the history). |
| `response.cancel` | Cancels the running response. |
| `output_audio_buffer.clear` | Cuts a response that is currently speaking. |

Only one response runs per session. A `response.create` while another is running returns an `error`. An unknown event type returns an `error` with `type: "invalid_request_error"`.

## Server events

Text turn, in order: `response.created`, `rate_limits.updated`, `response.output_item.added`, `response.content_part.added`, repeated `response.output_text.delta`, `response.output_text.done`, `response.content_part.done`, `response.output_item.done`, `response.done`. In the beta dialect the names are `response.text.delta` and `response.text.done`.

A turn with a tool call emits a `function_call` output item with `response.function_call_arguments.delta` and `response.function_call_arguments.done`. Return the result with `conversation.item.create` of type `function_call_output`, then send `response.create` again.

`response.done` carries `status` (`completed`, `cancelled` or `failed`), the output items and `usage` (`input_tokens`, `output_tokens`, `total_tokens`).

Voice turn events:

| Event | When |
| --- | --- |
| `input_audio_buffer.speech_started`, `input_audio_buffer.speech_stopped` | Server VAD detected the start and end of speech. |
| `input_audio_buffer.committed` | Buffer committed, by VAD or by your `commit`. |
| `conversation.item.added` / `.done` | The user item with the transcript. |
| `conversation.item.input_audio_transcription.completed` | The ASR transcript of the user turn. |
| `response.output_audio.delta`, `response.output_audio.done` | Base64 audio chunks in the session output format (`response.audio.delta` in beta). |
| `response.output_audio_transcript.delta`, `.done` | Text of the spoken reply. |
| `output_audio_buffer.started`, `.stopped`, `.cleared` | GA dialect only: bracket the audio of a response; `cleared` when it was cut by a cancel or barge-in. |
| `input_audio_buffer.timeout_triggered` | `idle_timeout_ms` elapsed with no speech; an empty user turn is committed and answered. |
| `error` | Any failure. The body is `{"type": "error", "event_id", "error": {"message", "type", "code"?}}`. |

## Text turns and voice turns

A text turn needs only a loaded chat model: create a user message item, send `response.create`, and read `output_text` events.

A voice turn has two implementations:

- **Cascade (default).** Input audio is transcribed by a loaded ASR model, the text goes to the chat model, and the reply is synthesized by a loaded TTS model. This needs a multi-model setup with an ASR model and (for audio output) a TTS model loaded next to the chat model. Without an ASR model, a commit returns an `error` with code `no_asr_engine`. Without a TTS model an audio response finishes with no audio chunks.
- **Native speech-to-speech.** When the served model has a Talker (Qwen3-Omni), the raw audio goes straight to the model and speech comes straight back. `YUNSHU_REALTIME_OMNI` is `auto` by default (native when a speakable model is served), `on` forces it, `off` forces the cascade.

Audio limits: the input buffer is capped by `YUNSHU_REALTIME_MAX_INPUT_AUDIO_BYTES` (10 MiB), exceeding it clears the buffer and sends an `input_audio_buffer_overflow` error. A session keeps at most `YUNSHU_REALTIME_MAX_CONVERSATION_ITEMS` (1000) items; the oldest are dropped.

## Ephemeral client secrets

For browsers, mint a short-lived key on your backend and hand it to the page. The `ek_...` value is accepted wherever the static token is, for `WS /v1/realtime` and `POST /v1/realtime/calls`.

`POST /v1/realtime/client_secrets` (GA) takes `{"expires_after": {"anchor": "created_at", "seconds": 10..7200}, "session": {...}}` (default 600 seconds; `session.type` is `realtime` or `transcription`) and returns `{"value": "ek_...", "expires_at", "session": {...}}`. The session you pass is the one applied to the connection that uses the key; it cannot be overridden later by that connection. `POST /v1/realtime/sessions` and `POST /v1/realtime/transcription_sessions` are the beta forms and return the session with a `client_secret` object. Secrets live in memory only (at most 1000 live), so they do not survive a restart. A transcription secret can transcribe but cannot create responses.

## WebRTC

`POST /v1/realtime/calls` negotiates a WebRTC call: send an SDP offer as `application/sdp` (or multipart `sdp` plus a JSON `session`), get an SDP answer with status `201`. Audio flows on the media tracks (resampled to 24 kHz mono PCM internally) and the same JSON events flow on a data channel labeled `oai-events`, using the GA dialect.

Requirements and limits:

- Install the optional extra: `pip install "yunshu[webrtc]"`. Without it the route returns `503` and suggests the WebSocket.
- No STUN or TURN servers are configured, so peers must be directly reachable (same machine or LAN).
- At most 16 live calls (`429` beyond that). An offer larger than 128 KiB returns `413`.
- A call ends when the peer fails or closes, on server shutdown, one hour after it opened, or 60 seconds after the offer if the data channel never opens.
- The response carries a `Location` header naming the call, but there is no route to fetch or hang up a call; close the peer connection instead.

## Examples

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

## Differences from the hosted API

- `semantic_vad` is served as `server_vad`.
- `rate_limits.updated` follows `response.created`, but there is no quota: `requests` reports `YUNSHU_RATE_LIMIT_RPM` (or the maximum 32-bit integer when it is 0) and `tokens` the model context window.
- `audio.input.noise_reduction` is a light causal high-pass filter plus noise-floor expander on the CPU, not a neural denoiser.
- `output_audio_buffer.started`, `.stopped` and `.cleared` are sent on the WebSocket too (OpenAI sends them on WebRTC and SIP).
- Unsupported session fields are accepted silently rather than rejected.
- Audio input needs a separate ASR model or a native speech model; there is no built-in speech recognizer.
- SIP calls and a monitoring sideband WebSocket are not provided.

## Support

| Feature | Status |
| --- | --- |
| WebSocket, GA and beta schemas | <Support status="supported">supported</Support> |
| Text turns, tool calls, truncation, cancel | <Support status="supported">supported</Support> |
| Voice turns through ASR, LLM and TTS | <Support status="partial">needs ASR and TTS models loaded</Support> |
| Native speech-to-speech | <Support status="partial">needs a model with a Talker (Qwen3-Omni)</Support> |
| Server VAD | <Support status="supported">energy based, optional Silero</Support> |
| `semantic_vad` | <Support status="partial">served as `server_vad`</Support> |
| Ephemeral client secrets | <Support status="supported">in memory only</Support> |
| WebRTC | <Support status="partial">optional `webrtc` extra, no STUN/TURN</Support> |
| SIP, sideband connections | <Support status="unsupported">not provided</Support> |

## Related

- [Audio](/docs/api/audio) for the HTTP speech and transcription endpoints.
- [Extensions](/docs/api/extensions) for `WS /v1/stream` and `POST /v1/omni/speech/stream`.
- [Chat completions](/docs/api/chat-completions) for the text sampling behaviour that Realtime reuses.


---

<!-- api/rerank -->
---
title: Rerank and scoring
description: Rerank documents against a query, score text pairs and classify text with embedding models, cross-encoder rerankers and sequence-classifier checkpoints.
---

Three vLLM-style routes cover retrieval post-processing: `POST /v1/rerank` orders documents by relevance to a query, `POST /v1/score` scores text pairs, and `POST /v1/classify` assigns labels. They run on whatever scoring-capable model you name:

- A trained cross-encoder reranker (text, or a multimodal reranker such as Qwen3-VL-Reranker) scores each query/document pair jointly. This is the accurate option.
- A sequence-classifier checkpoint (a model with a trained classification head) is used by `POST /v1/classify` with the labels stored in the checkpoint.
- An embedding model works as a fallback: similarity between separately computed vectors. It is cheaper but less precise than a cross-encoder, and for `rerank` the cosine similarity is mapped to the `0` to `1` range.

A chat model cannot be used for these routes; they answer `400` with a message that the model cannot produce embeddings.

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

<Callout type="info">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. See [API overview](/docs/api/overview). In multi-model mode `model` selects the scoring model; in single-model mode the loaded model itself must be one.
</Callout>

## Rerank

### Request

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Reranker or embedding model id. | supported |
| `query` | string or object | yes | The query. An object `{"text": ..., "image": ...}` needs a multimodal cross-encoder. | supported |
| `documents` | array | yes | Up to 2048 items, each a string or a `{"text": ..., "image": ...}` object. Strings longer than 8192 characters are truncated. | supported |
| `top_n` | integer | no | Return only the best `n`, `1` to `2048`. | supported |
| `return_documents` | boolean | no | Default `true`: each result carries its `document`. | supported |
| `instruction` | string | no | Task instruction for cross-encoders that take one, up to 8192 characters. | supported |
| `use_activation` | boolean | no | Text cross-encoders only: apply the score activation (default on). Any other model answers `400`. | extension |

### Example

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

### Response

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

Results are sorted by `relevance_score`, best first; `index` is the position in the request's `documents`. `relevance_score` is rounded to six decimals. For a cross-encoder it is the model's score; for an embedding model it is `(cosine + 1) / 2`.

## Score

`POST /v1/score` scores pairs of texts and returns one number per pair.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Model id. | supported |
| `text_1` | string or array | yes | First texts. Aliases: `queries`, `data_1`. | supported |
| `text_2` | string or array | yes | Second texts. Aliases: `documents`, `items`, `data_2`. | supported |
| `scoring_type` | string | no | `cosine` (default), `dot` or `euclidean` (the negative distance). Only configurable for embedding models; cross-encoders answer `400` for anything but `cosine`. | supported |
| `use_activation` | boolean | no | Text cross-encoders only. | extension |
| `instruction` | string | no | Task instruction for cross-encoders. Also accepted as `chat_template_kwargs.instruction`; other `chat_template_kwargs` keys are a `400`. | supported |

The two sides are paired element by element. If one side has a single item it is broadcast against the other; otherwise the lengths must match. At most 2048 items per side and 8192 characters per text.

```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` works in two modes, chosen by the model.

**Trained classifier.** If the model is a sequence-classifier checkpoint, `input` is a string or an array of strings and `labels` must be omitted (the checkpoint's own labels are used; sending `labels` is a `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 }
  ]
}
```

`results` (labels sorted by score) is added when `input` was a single string.

**Zero-shot with an embedding model.** `input` is one string and `labels` has at least two entries (`candidate_labels` is accepted as an alias). The input and each label are embedded, cosine similarities are divided by `temperature` (default `0.07`, range above `0` up to `10`) and passed through a 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` is the label's position in the request; `results` is sorted by `score`. Scores sum to one.

## Errors

| Status | When |
| --- | --- |
| 400 | Validation (empty text, length mismatch that cannot broadcast, unknown `scoring_type`, fewer than two labels, text over 8192 characters, `labels` sent to a trained classifier); a multimodal query or document sent to a model that is not a cross-encoder reranker; `use_activation` on a model that is not a text cross-encoder; a chat model that cannot embed. |
| 401 | Token configured and missing or wrong. |
| 404 | The model is not found. |
| 507 | Out of GPU memory. |
| 500 | Scoring failed (`server_error`). |

## Support

| Feature | Status |
| --- | --- |
| Text cross-encoder reranking | <Support status="supported">supported</Support> |
| Multimodal reranking (image query or documents) | <Support status="partial">multimodal cross-encoder models only</Support> |
| Embedding-model fallback for rerank, score, classify | <Support status="supported">supported</Support> |
| Trained sequence-classifier heads | <Support status="supported">supported</Support> |
| `dot` and `euclidean` scoring | <Support status="partial">embedding models only</Support> |
| Cohere or Jina specific fields (`max_chunks_per_doc`, `rank_fields`) | <Support status="unsupported">not supported; unknown fields are ignored</Support> |

## Related

- [Embeddings](/docs/api/embeddings)
- [Models](/docs/api/models)
- [Model support](/docs/guides/model-support)


---

<!-- api/responses -->
---
title: Responses
description: OpenAI Responses API with stored responses, background mode, conversations, compaction, client tools and WebSocket mode.
---

Yunshu serves the OpenAI Responses API on `POST /v1/responses` and the routes around it: retrieve, delete, cancel, list input items, count input tokens, compact a conversation, and the Conversations API. A WebSocket mode is available on the same path. The official `openai` SDK works unchanged (`client.responses.create`, `.retrieve`, `.delete`, `.cancel`, `.input_items.list`, `.compact`, `.input_tokens.count`, `.connect`, `client.conversations.*`).

Every request is translated to the same engine path as [Chat Completions](/docs/api/chat-completions), so sampling, constrained decoding, the prefix cache, vision input and tool calling behave the same. Web search and the `mcp` tool are executed by the server; see [Server tools](/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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. In single-model mode the `model` field is advisory: the loaded model answers under any name and the response echoes the name you sent. In multi-model mode an unknown model is a `404`.
</Callout>

## Request

`POST /v1/responses` takes a JSON body.

### Input and state

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | yes | Model id. Empty string is rejected. | supported |
| `input` | string or array of items | yes | A plain string, or items: `message` (roles `user`, `assistant`, `system`, `developer`; `developer` is treated as `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`. Content parts: `input_text`, `input_image`, `input_file`, `input_audio`. Empty strings and empty lists are rejected (except with `generate: false`). | supported |
| `instructions` | string | no | System prompt for this request. Not carried over by `previous_response_id`. | supported |
| `previous_response_id` | string | no | Continue from a stored response. The earlier turns are replayed into the prompt, following at most 16 links back. An id that is unknown, not stored or not yours is not an error: the chain simply stops there and the request runs without that history. | supported |
| `conversation` | string or object | no | A conversation id (or `{"id": ...}`). The conversation items are prepended to `input`, and this turn is appended to the conversation when the response finishes. Cannot be combined with `previous_response_id` (`400`). | supported |
| `context_management` | array | no | `[{"type": "compaction", "compact_threshold": N}]` compacts the input first when it exceeds N tokens. | supported |
| `store` | boolean | no | Default `true`, as in the hosted API. A stored response can be retrieved, deleted, cancelled, chained and listed. | supported |
| `background` | boolean | no | Generate in the background. Without `stream`, a `queued` response comes back at once; with `stream: true` the events stream live and are kept, so a dropped client can resume with `GET /v1/responses/{id}?stream=true&starting_after=N`. Works with `web_search` and `mcp` tools. | supported |
| `truncation` | `auto` or `disabled` | no | `auto` drops the oldest non-system messages when the prompt would exceed the context window and reports what was removed in `x_yunshu.context_policy`. `disabled` (default) answers `400` instead. | supported |
| `generate` | boolean | no | `false` prefills the prompt prefix into the cache and returns a response id with no output (WebSocket prewarm used by Codex). | supported |
| `metadata` | object | no | At most 16 pairs; echoed on the response. | supported |
| `include` | array of string | no | `reasoning.encrypted_content` adds an opaque `encrypted_content` to reasoning items; `web_search_call.action.sources` lists search sources. Other values are accepted and have no effect. | partial |
| `max_tool_calls` | integer | no | Caps the server-tool calls of one response (web search and `mcp`). | supported |
| `prompt_cache_key`, `prompt_cache_retention`, `prompt_cache_options`, `safety_identifier`, `service_tier`, `client_metadata`, `user` | various | no | Accepted and echoed where the Response object has the field. They do not change behavior; prefix caching is automatic. | accepted and ignored |

### Generation

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `max_output_tokens` | integer | no | 1 to 1048576. Omitted (Codex sends none): the model's output limit including reasoning tokens (262144), clamped to the context window; the operator cap `YUNSHU_DEFAULT_MAX_TOKENS` can lower it. `x_yunshu.budget.max_tokens_source` says which applied. `max_completion_tokens` is accepted as an alias. | supported |
| `temperature` | number | no | 0 to 2, default 1.0. | supported |
| `top_p` | number | no | 0 to 1, default 1.0. | supported |
| `top_k`, `min_p`, `top_n_sigma`, `repetition_penalty`, `frequency_penalty`, `presence_penalty`, `xtc_probability`, `xtc_threshold` | number | no | Extra sampling controls, same ranges as Chat Completions. | extension |
| `seed` | integer | no | Deterministic sampling seed. | supported |
| `stop`, `stop_token_ids` | array | no | Up to 16 non-empty stop strings (a single string is accepted). | extension |
| `min_tokens`, `ignore_eos`, `suppress_tokens`, `logit_bias`, `logprobs`, `top_logprobs`, `n` | various | no | Passed to the engine. `logit_bias` values must be finite and within -100 to 100. `n` greater than 1 is rejected with `stream: true`. | extension |
| `reasoning` | object | no | `{"effort": "none\|minimal\|low\|medium\|high\|xhigh\|max"}` maps to the template's reasoning effort; `none` and `minimal` turn thinking off. `summary` is not read. | partial |
| `reasoning_effort`, `enable_thinking`, `thinking_budget` | various | no | Flat equivalents of `reasoning`. | extension |
| `text` | object | no | `text.format` of type `json_schema` or `json_object` becomes constrained decoding; `text` type is the default. | supported |
| `response_format`, `grammar` | object | no | Chat-style structured output and grammar constraints (`json`, `regex`, `choice`, `cfg`). | extension |
| `stream` | boolean | no | Server-Sent Events. | supported |
| `stream_options` | object | no | Accepted. Usage always arrives in the final event. | accepted and ignored |
| `timeout`, `priority`, `lora_adapter`, `spec_decode` | various | no | Engine controls shared with the other routes. `lora_adapter` and custom `logits_processors` are rejected for vision-language models. | extension |

### Tools

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `tools` | array | no | See the tool types below. | partial |
| `tool_choice` | string or object | no | `auto`, `none`, `required`, a named function (`{"type": "function", "name": "..."}`) or an `allowed_tools` object (folded into the tool list). Forced choices are checked before the stream starts. | supported |
| `parallel_tool_calls` | boolean | no | Default `true`. | supported |

Supported tool types:

| `type` | Executed by | Status |
| --- | --- | --- |
| `function` | Your client. The model's call comes back as a `function_call` item. | supported |
| `namespace` | Your client. Child tools are flattened for the model; the namespace is kept on the returned call. Duplicate names across namespaces are a `400`. | supported |
| `custom` | Your client. Comes back as `custom_tool_call` with a plain-text `input`. Text format, and `grammar` formats with `syntax` `regex` or `lark`, are supported (constrained decoding). | supported |
| `local_shell` | Your client. Comes back as `local_shell_call`. | supported |
| `tool_search` | Your client, with `execution: "client"` only. `defer_loading` tools stay hidden until a `tool_search_output` loads them. Hosted tool search is a `400`. | partial |
| `computer` | Your client. See below. | partial |
| `web_search`, `web_search_preview` | The server. See [Server tools](/docs/api/server-tools). | supported |
| `mcp` | The server connects to the MCP server you name. See [Server tools](/docs/api/server-tools). | partial |
| `code_interpreter`, hosted `shell` | The server, in a sandbox on this machine. Opt-in. See [Server tools](/docs/api/server-tools). | partial |
| `file_search`, `image_generation` and other hosted tools | Not available. | not supported |

Client tools (`custom`, `local_shell`, `tool_search`, `computer`) can be combined with `web_search` and `mcp` in one request: the server runs its own tools inside the loop and hands a client tool call back to you, ending the response like any client tool call.

#### The computer tool

`tools: [{"type": "computer"}]` is supported as a client-executed tool. The gateway turns it into a function whose arguments are an ordered `actions` array, and returns a `computer_call` item with `actions` (each action is one of `click`, `double_click`, `drag`, `move`, `scroll`, `keypress`, `type`, `wait`, `screenshot`). `pending_safety_checks` is always empty.

Yunshu never executes a computer action. Your client performs the actions, takes a screenshot and sends it back as a `computer_call_output` item whose `output` is `{"type": "computer_screenshot", "image_url": "..."}` or `{"file_id": "..."}`; the model needs vision input to read it. A `computer_call_output` without a `computer_screenshot` is a `400`. The model is a local model: it is not trained for computer use the way hosted computer-use models are, so action quality depends on the model you load.

## Examples

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

### Structured output

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

### Function tool loop

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

### Background mode

```python
job = client.responses.create(model="local", input="Write a long story.", background=True)
print(job.status)  # queued
done = client.responses.retrieve(job.id)       # poll until status leaves queued / in_progress
client.responses.cancel(job.id)                # or cancel

# background + stream: read the events, reconnect from any 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):
    ...
```

A cancel that arrives while the response is still `queued` is honored before any generation runs. If a background generation fails, the stored status becomes `failed` with `error.code` `internal_error`.

## Response

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

The object also echoes the request configuration (`temperature`, `top_p`, `max_output_tokens`, `tools`, `text`, `reasoning`, `service_tier`, ...). When the model reasons, a `reasoning` item with a `summary` of type `summary_text` comes first in `output`. Tool calls appear as `function_call` items with `call_id`, `name` and `arguments`. A response cut short by the token limit has `status: "incomplete"` and `incomplete_details.reason`. Yunshu adds an `x_yunshu` object (timing, cache and speculative-decoding statistics, and `context_policy` when turns were dropped) described in [Extensions](/docs/api/extensions).

### Retrieve, delete, cancel

- `GET /v1/responses/{response_id}` returns the stored response, or `404` with code `response_not_found`.
- `DELETE /v1/responses/{response_id}` returns `{"id": "...", "object": "response.deleted", "deleted": true}`.
- `POST /v1/responses/{response_id}/cancel` stops a running generation. For a stored `queued` or `in_progress` response it stores and returns `status: "cancelled"`; for an already finished response it returns that response unchanged; for an unknown id it returns `404`.

Stored responses live in the server process memory (the most recent 1024 are kept) and are lost on restart. A response is only visible to the caller that created it.

### List input items

`GET /v1/responses/{response_id}/input_items` returns this request's own input as Responses items (`message` with `input_text` or `input_image` parts, `function_call`, `function_call_output`). `instructions` and system or developer messages are not listed, and history reached through `previous_response_id` belongs to the earlier responses.

| Query | Description |
| --- | --- |
| `limit` | 1 to 100, default 20. |
| `order` | `desc` (default) or `asc`. |
| `after`, `before` | Item ids as cursors. An unknown cursor is a `404` with code `item_not_found`. |

The result is `{"object": "list", "data": [...], "first_id", "last_id", "has_more"}`.

### Count input tokens

`POST /v1/responses/input_tokens` accepts the same body as `POST /v1/responses` (`model` is still required) and returns:

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

The prompt is built like generation (instructions, items, conversation, compaction items, the `previous_response_id` chain, tools) and rendered through the chat template, so the number equals `usage.input_tokens` of the same request. It does not count server-side tool definitions (`web_search`, `mcp`) and does not run an automatic compaction.

### Compact

`POST /v1/responses/compact` compresses a conversation. It takes `model`, and `input` (string or items) and/or `previous_response_id`, plus optional `instructions` and `tools`. All user and developer messages are kept verbatim; the rest is replaced by one opaque `compaction` item that wraps a model-written summary (up to `YUNSHU_COMPACT_MAX_TOKENS` tokens, default 2048). Long histories are summarized in several passes when they do not fit the context window.

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

Pass `output` back as `input` in the next request. The `encrypted_content` is a base64 envelope of the summary, not encryption; it only lets a client treat the item as opaque.

## Conversations

The Conversations API stores items server side so you can reuse them with `conversation` instead of resending history. Each conversation is a JSON file under `YUNSHU_CONVERSATIONS_DIR` (default `~/.yunshu/conversations`), so conversations survive restarts.

| Route | Description |
| --- | --- |
| `POST /v1/conversations` | Body `{"items": [...], "metadata": {...}}`, both optional. At most 20 items per call and 16 metadata keys. Returns `{"id": "conv_...", "object": "conversation", "created_at", "metadata"}`. |
| `GET /v1/conversations/{conversation_id}` | Retrieve. |
| `POST /v1/conversations/{conversation_id}` | Replace `metadata` (required in the body). |
| `DELETE /v1/conversations/{conversation_id}` | Returns `{"id", "object": "conversation.deleted", "deleted": true}`. |
| `POST /v1/conversations/{conversation_id}/items` | Body `{"items": [...]}` (required), up to 20 per call. Returns a list. |
| `GET /v1/conversations/{conversation_id}/items` | `limit` 1-100 (default 20), `order` `desc` (default) or `asc`, `after` cursor. |
| `GET /v1/conversations/{conversation_id}/items/{item_id}` | Retrieve one item. |
| `DELETE /v1/conversations/{conversation_id}/items/{item_id}` | Remove one item. |

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

Errors use the OpenAI shape with codes such as `conversation_not_found`, `item_not_found`, `invalid_json`, `missing_required_parameter` and `insufficient_storage` (`507`, disk full).

## Streaming

With `stream: true` the response is Server-Sent Events: each message has an `event:` line equal to the `type` of its JSON `data:` and an ascending `sequence_number`. The stream ends with `data: [DONE]`. Comment lines (`: keep-alive`) may appear while a long prompt is prefilled.

Plain generation emits, in order:

1. `response.created`, `response.in_progress`
2. For reasoning: `response.output_item.added` (a `reasoning` item), `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. For the message: `response.output_item.added`, `response.content_part.added`, repeated `response.output_text.delta`, `response.output_text.done`, `response.content_part.done`, `response.output_item.done`
4. For each function call: `response.output_item.added` (already carrying `call_id`, `name`, `arguments`), `response.function_call_arguments.done`, `response.output_item.done`. A function call is delivered whole rather than as argument deltas.
5. A terminal event: `response.completed`, `response.incomplete` (token limit, timeout or cancellation) or `response.failed`

Other events, depending on the request:

| Event | When |
| --- | --- |
| `response.custom_tool_call_input.delta`, `response.custom_tool_call_input.done` | A `custom` tool call. |
| `response.output_text.annotation.added` | URL citations from web search. |
| `response.web_search_call.in_progress`, `.searching`, `.completed` | Server-side web search. |
| `response.mcp_list_tools.in_progress`, `.completed` | The `mcp` tool listed a server's tools. |
| `response.mcp_call.in_progress`, `response.mcp_call_arguments.delta`, `response.mcp_call_arguments.done`, `response.mcp_call.completed`, `response.mcp_call.failed` | A server-side `mcp` call. |

An error after the stream has started is a terminal `response.failed` event on the same stream (never a second HTTP response); an unknown model with `stream: true` is also reported as `response.failed` with code `model_not_found`.

## WebSocket mode

`WS /v1/responses` speaks OpenAI's Responses WebSocket mode (`client.responses.connect()` in the SDK). Origin and token checks run before the upgrade; with `YUNSHU_AUTH_TOKEN` set, send the token as `Authorization: Bearer ...`, `x-api-key` or a `token` query parameter.

Client messages (JSON text frames):

| Message | Description |
| --- | --- |
| `{"type": "response.create", ...body}` | The body fields are the same as `POST /v1/responses`; `stream` is forced on. Optional `stream_id` puts requests in a lane (first in, first out within a lane, parallel across lanes; at most 32 lanes) and optional `client_request_id` names the request. |
| `{"type": "response.cancel", "id": "..."}` | Cancels by `client_request_id` or `stream_id`. Without an id it cancels every active request on the socket. An unknown id returns a `404` error message. |
| `{"type": "ping"}` | Answered with `{"type": "pong"}`. |

The server sends the same `response.*` events as the SSE stream, as one JSON object per frame. Failures that are not part of a response arrive as `{"type": "error", "status": 400, "error": {"message", "type"}}`: invalid JSON, an unknown message type, a duplicate active request id (`409`), or too many concurrent requests (`429`, default 16 per connection, setting `YUNSHU_WS_MAX_INFLIGHT`). Outbound events are buffered per connection (`YUNSHU_WS_SEND_QUEUE`); a slow reader pauses generation instead of growing the buffer. Closing the socket cancels its active requests.

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

## Errors

Errors use the OpenAI envelope `{"error": {"message", "type", "param", "code"}}`.

| Status | Cause |
| --- | --- |
| `400` | Invalid body or field (empty `input`, `stop` over 16 items, `logit_bias` out of range, `metadata` over 16 pairs), prompt over the context window with `truncation` disabled (`context_length_exceeded`), a model that does not support a requested feature, `conversation` with `previous_response_id`, unsupported tool combinations, a malformed `computer_call_output`. |
| `401` / `403` | Missing or wrong token; a key without permission for the model. |
| `404` | Unknown model (multi-model mode), unknown response (`response_not_found`) or file reference. |
| `413` | Prompt too large to prefill in memory. |
| `424` | An `mcp` tool server could not be reached (`external_connector_error`). |
| `502` | The model produced malformed arguments for a client tool, for example invalid `computer` actions. |
| `503` | No model loaded. |

## Support

| Feature | Status |
| --- | --- |
| `POST /v1/responses`, stream and non-stream | <Support status="supported">supported</Support> |
| Retrieve, delete, cancel, input items, input tokens, compact | <Support status="supported">supported</Support> |
| `previous_response_id` chaining, `store` | <Support status="supported">supported (in memory, lost on restart)</Support> |
| Background mode | <Support status="supported">supported, with `stream` and with server tools</Support> |
| Conversations API | <Support status="supported">supported (persistent)</Support> |
| `text.format` json_schema and json_object | <Support status="supported">supported</Support> |
| Function, namespace, custom, local_shell, client tool_search | <Support status="supported">supported</Support> |
| `computer` tool | <Support status="partial">client-executed; the server never runs actions</Support> |
| `web_search`, `mcp` | <Support status="supported">supported, server-side</Support> |
| `code_interpreter`, hosted `shell` | <Support status="partial">server-side in srt, opt-in (`YUNSHU_CODE_EXECUTION`)</Support> |
| `reasoning.summary` generation, hosted `tool_search`, `file_search`, `image_generation` | <Support status="unsupported">not supported</Support> |
| Resuming a background stream (`starting_after`) | <Support status="supported">supported (events kept in memory, lost on restart)</Support> |
| WebSocket mode | <Support status="supported">supported</Support> |

## Related

- [Chat Completions](/docs/api/chat-completions)
- [Server tools](/docs/api/server-tools)
- [Structured output](/docs/guides/structured-output)
- [Prompt caching](/docs/guides/prompt-caching)
- [Extensions](/docs/api/extensions)


---

<!-- api/server-tools -->
---
title: Server tools
description: Web search, web fetch and the MCP connector, executed by Yunshu inside the generation loop for Anthropic Messages and OpenAI Responses requests.
---

Some tools in the Anthropic and OpenAI APIs are run by the server, not by your client. Yunshu supports three of them: web search, web fetch (Anthropic only) and a connector that calls remote MCP servers. When a request declares one, Yunshu runs a loop inside the single request: the model generates, calls a server tool, Yunshu executes it (asynchronously, off the model thread, with timeouts), appends the result and generates again, until the model answers without a server tool call. You get one response whose content interleaves the tool blocks and the final text. Every round re-sends the same conversation plus the new turn, so the prefix cache serves the shared prefix and a continuation only prefills the new tokens.

| Tool | Anthropic Messages | OpenAI Responses |
| --- | --- | --- |
| Web search | `web_search_20250305` | `web_search`, `web_search_preview` |
| Web fetch | `web_fetch_20250910` | not part of the API |
| MCP connector | `mcp_servers` + `mcp_toolset` | `{"type": "mcp"}` |

The routes are [`POST /v1/messages`](/docs/api/messages) and [`POST /v1/responses`](/docs/api/responses); there is no separate endpoint.

<Callout type="warn">
Web search with the default providers sends your query text (and your IP address) to third-party search services. Nothing is sent unless a request declares a web search tool and the model calls it. Set `YUNSHU_WEB_SEARCH_PROVIDER=none` to disable search entirely. See [Web search](/docs/guides/web-search).
</Callout>

## Configuration

Server tools are configured on the server through settings (see [Configuration](/docs/guides/configuration)); the request only declares the tool.

| Setting | Default | Meaning |
| --- | --- | --- |
| `YUNSHU_WEB_SEARCH_PROVIDER` | `auto` | Search backend: `auto`, `none`, `searxng`, `brave`, `tavily`, `exa`, `serper`, `perplexity`, `ddg_html`, `wikipedia`, `mwmbl`, `mojeek`, `marginalia`. `auto` queries several lightweight and configured providers in parallel and merges the results; `none` disables search. |
| `YUNSHU_WEB_KEYLESS` | on | Allow keyless DuckDuckGo (best effort, may be blocked) and Wikipedia in `auto` mode. |
| `YUNSHU_SEARXNG_URL` | unset | Base URL of a self-hosted SearXNG instance (JSON output enabled). Optional. |
| `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` | unset | Keys for the keyed providers. A configured key joins `auto`. |
| `YUNSHU_WEB_SEARCH_RESULTS` | 5 | Results returned per search call. |
| `YUNSHU_WEB_SEARCH_PROVIDER_TIMEOUT` | 1.0 s | Per-provider deadline in `auto` mode. |
| `YUNSHU_WEB_RESEARCH` | off | Enrich snippets with excerpts from the origin pages (the fetched URLs leave the machine). |
| `YUNSHU_WEB_FETCH` | on | Serve `web_fetch`. Off: web fetch requests get an `unavailable` error. |
| `YUNSHU_WEB_FETCH_ALLOW_PRIVATE` | off | Let `web_fetch` reach private, loopback and link-local addresses. |
| `YUNSHU_WEB_FETCH_MAX_BYTES` | 2000000 | Largest body downloaded. |
| `YUNSHU_WEB_FETCH_TIMEOUT` | 20 s | Per-page deadline. |
| `YUNSHU_WEB_FETCH_MAX_TEXT_CHARS` | 40000 | Extracted text handed to the model is cut to this length. |
| `YUNSHU_MCP_CONNECTOR` | on | Serve the MCP connector. |
| `YUNSHU_MCP_CONNECTOR_ALLOW_PRIVATE` | on | Let the connector reach private and loopback MCP servers (local tool servers are the common case). Off: public addresses only. |
| `YUNSHU_MCP_CONNECTOR_TIMEOUT` | 30 s | Per call (initialize, `tools/list`, `tools/call`). |
| `YUNSHU_MCP_CONNECTOR_MAX_BYTES` | 8 MiB | Largest single reply from an MCP server. |
| `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` | 8 | Most generate-run-continue rounds in one request. |

With no usable search provider, a search request does not fail the whole call: the tool result carries an `unavailable` error and the response's `x_yunshu.server_tools` object includes a setup hint. `GET /v1/models` shows the current state of each tool under `yunshu.server_tools` (`web_search.available` and provider, `web_fetch.available`, `mcp_connector.available`).

## Anthropic Messages

### Web search

Declare the tool in `tools`:

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

| Field | Status | Description |
| --- | --- | --- |
| `max_uses` | supported | After this many calls in one request, further calls return a `max_uses_exceeded` error result. |
| `allowed_domains`, `blocked_domains` | supported | Filter results by domain (a domain also matches its subdomains). |
| `user_location` | supported | Passed to the search provider as a location hint. |
| `cache_control`, `allowed_callers`, `defer_loading` | accepted and ignored | |

The response content interleaves these blocks:

```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": "..." }
    ]
  }
]
```

A failed search returns `content: {"type": "web_search_tool_result_error", "error_code": "..."}` with codes `unavailable`, `max_uses_exceeded`, `too_many_requests`, `invalid_input`, `query_too_long` (queries over 400 characters). `usage.server_tool_use.web_search_requests` counts the calls.

### Web fetch

```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` and `max_content_tokens` (lowers the text cap to roughly four characters per token) are honored. The result block:

```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 is converted to Markdown; text, JSON and XML types are returned as text. Other content types (including PDF and images) fail with `unsupported_content_type`. Errors come back as `web_fetch_tool_result_error` with `error_code` `url_not_allowed`, `url_not_accessible`, `unsupported_content_type`, `url_too_long` (URLs over 250 characters), `invalid_tool_input`, `too_many_requests`, `max_uses_exceeded` or `unavailable`. `usage.server_tool_use.web_fetch_requests` counts the calls. Fetched content is not citable: the result document has `citations.enabled` false.

### Citations

Citations on text blocks are built from the `[n]` markers the model writes next to results it used. Each is a `web_search_result_location` with the result's `url` and `title`, a `cited_text` of up to 150 characters taken from the best-matching passage or snippet, and `encrypted_index`. `encrypted_content` and `encrypted_index` are opaque envelopes that let a later request replay the results; a local server has nothing to hide from its own client, so they are not encrypted. `page_age` is whatever the provider returns and is often `null`. Whether the model writes `[n]` markers depends on the model, so a small model may answer from search results without producing citations. Document citations are a different feature, described on [Messages](/docs/api/messages).

### pause_turn

If the loop reaches `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` rounds and the model is still calling server tools, the message ends with `stop_reason: "pause_turn"`. Send the response content back as an assistant turn to continue.

### Code execution

`code_execution_20250522`, `_20250825`, `_20260120` and `_20260521` run on this machine inside Anthropic's sandbox-runtime. Off by default: set `YUNSHU_CODE_EXECUTION=1` and install `@anthropic-ai/sandbox-runtime` (Node 22.12 or newer). Off, a request that declares the tool gets a `400`; on without the runtime, a `503`; a command never runs unsandboxed. The response has `*_tool_result` blocks and a `container` to pass back. The sandbox writes only inside its container, cannot read your home, and has no network unless `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW` lists hosts.

| Version | Sub-tools | Python interpreter |
| --- | --- | --- |
| `20250522` | `code_execution` (Python) | fresh process per call |
| `20250825` | `bash_code_execution`, `text_editor_code_execution` (plus `code_execution` when a client tool lists a code-execution caller) | fresh process per call |
| `20260120`, `20260521` | all three | one process per container: variables persist between calls (REPL state) |

Files written to `$OUTPUT_DIR` by bash, and files a Python cell creates, come back as Files API ids. **Programmatic tool calling:** a client tool with `"allowed_callers": ["code_execution_20260120"]` becomes an `async` Python function in the interpreter. When the code awaits it the turn ends with `stop_reason: "tool_use"` and one `tool_use` block per call, each with `caller: {type, tool_id}`; send the tool results back with the `container` and the response continues with the `code_execution_tool_result`. The model's own history holds only the code call and its final result. A paused cell waits 270 seconds for the answer. See the [guide](https://github.com/yuhuanowo/Yunshu/blob/main/docs/guides/CODE_EXECUTION.md).

### OpenAI code interpreter, shell and containers

With the same setting, OpenAI Responses requests can declare `{"type": "code_interpreter", "container": {"type": "auto"}}` (or a container id) and the hosted `{"type": "shell", "environment": {"type": "container_auto"}}` (or `container_reference`). The response has `code_interpreter_call` items (`code`, `container_id`, `outputs` with `include: ["code_interpreter_call.outputs"]`), `shell_call` / `shell_call_output` items, the streaming events `response.code_interpreter_call.*`, `response.code_interpreter_call_code.*`, `response.shell_call_command.*` and `response.shell_call_output_content.*`, and `container_file_citation` annotations for files the code made. Python state persists inside the container; `previous_response_id` reuses it. A `shell` tool with a `local` environment is run by your client.

The containers behind them have the OpenAI containers API. `expires_after` is the idle lifetime (capped by `YUNSHU_CODE_EXECUTION_TTL_MIN`), `memory_limit` a ceiling under `YUNSHU_CODE_EXECUTION_MEMORY_MB`, and `network_policy` can only narrow `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW`. Files are at `/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 connector

Declare remote MCP servers in the top-level `mcp_servers` and, optionally, one `mcp_toolset` entry per server in `tools`:

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

| Field | Status | Description |
| --- | --- | --- |
| `mcp_servers[].name`, `url` | supported | Both required. |
| `mcp_servers[].authorization_token` | supported | Sent as a bearer token. |
| `mcp_servers[].headers` | extension | Extra request headers. |
| `mcp_servers[].tool_configuration` | supported | The earlier beta form: `enabled` and `allowed_tools`. |
| `mcp_toolset.default_config.enabled`, `configs.{tool}.enabled` | supported | Enable or disable tools. |
| `defer_loading`, `cache_control` in a toolset | accepted and ignored | |

The gateway connects when the request starts (streamable HTTP, falling back to the older HTTP+SSE transport), lists the tools and shows the enabled ones to the model as `<server>__<tool>`. A tool call produces `mcp_tool_use` (with `server_name`) and `mcp_tool_result` (with `is_error` and text `content`). Tool results are cut to 100000 characters. Calls in the same turn run concurrently. There is no approval step. An unreachable server is a `400 invalid_request_error`.

## OpenAI Responses

### Web search

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

`filters.allowed_domains` and `user_location` are honored; `search_context_size` is accepted and has no effect. The model can also open a page and search inside it (the actions `open_page` and `find_in_page`). The output contains a `web_search_call` item (`action` with `type`, `query`; `status` `completed` or `failed`) followed by a `message` whose `output_text` carries `url_citation` annotations (`start_index`, `end_index`, `url`, `title`) built from the model's `[n]` markers. Add `include: ["web_search_call.action.sources"]` to list the result URLs in `action.sources`. `max_tool_calls` caps the number of searches; calls past the cap fail with a message the model sees.

### The mcp tool

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

| Field | Status | Description |
| --- | --- | --- |
| `server_label`, `server_url` | supported | Both required (`400` otherwise). |
| `authorization`, `headers` | supported | Credentials for the MCP server; they are not echoed back in the response `tools`. |
| `allowed_tools` | supported | A list of names, or `{"tool_names": [...]}`. |
| `require_approval` | supported | `"never"` runs tools immediately. The default (`"always"`), or an object listing `never.tool_names`, makes the model's call stop at an `mcp_approval_request` item; send an `mcp_approval_response` item (`approval_request_id`, `approve`, `reason`) in the next request (with `previous_response_id`) to run or refuse it. |
| `connector_id` | not supported | OpenAI-hosted connectors are a `400` (`unsupported_connector`); pass the server URL instead. |

The first response for a server includes an `mcp_list_tools` item; a later request that carries that item (or a stored response that has it) skips the listing. Calls appear as `mcp_call` items with `arguments`, `output`, `error` and `approval_request_id`. An unreachable server is a `424` with code `external_connector_error`.

## Network safety

- `web_fetch` resolves the hostname itself and refuses private, loopback and link-local addresses, including cloud metadata addresses, before connecting, and again for every redirect (at most 5, each re-validated). The connection is pinned to the validated address, so a DNS answer cannot change between the check and the request. Cookies are not sent. `YUNSHU_WEB_FETCH_ALLOW_PRIVATE=1` lifts the restriction.
- Image and PDF `url` sources on Messages are checked the same way.
- The MCP connector is the exception by default: it can reach private and loopback servers (`YUNSHU_MCP_CONNECTOR_ALLOW_PRIVATE`), because local tool servers are the normal case. Turn that off if untrusted clients can reach your server.
- Search queries and fetched pages are model-controlled input. Fetched text reaches the model as tool output, so a page can try to steer it; treat server tools as you would any tool that reads the open web.

## Limits and what is not supported

- The hosted memory tool, file search, image generation and OpenAI-hosted connectors are not available. Code execution (Anthropic `code_execution_*`, OpenAI `code_interpreter` and hosted `shell`) is opt-in (see above); OpenAI `programmatic_tool_calling` and container skills are not implemented.
- `web_fetch` does not read PDFs or images and cannot execute JavaScript.
- Web search quality depends on the provider you configure; the keyless defaults are best effort.
- The Responses API has no web fetch tool; use an `mcp` fetch server or the Anthropic route.
- Server tools cannot be mixed with `custom`, `local_shell`, `tool_search` or `computer` tools in one Responses request (`400`). Ordinary function tools can be combined with server tools; function calls are returned to your client.
- `background: true` is not supported together with `web_search` or `mcp` in a Responses request (`400`).

## Support

| Feature | Status |
| --- | --- |
| Anthropic `web_search_20250305` | <Support status="supported">supported</Support> |
| Anthropic `web_fetch_20250910` | <Support status="supported">supported (text, HTML)</Support> |
| Anthropic `mcp_servers` + `mcp_toolset` | <Support status="supported">supported</Support> |
| Responses `web_search` / `web_search_preview` | <Support status="supported">supported</Support> |
| Responses `mcp` tool, approvals | <Support status="supported">supported</Support> |
| Responses `connector_id` connectors | <Support status="unsupported">not supported</Support> |
| `pause_turn` for long loops | <Support status="supported">Anthropic only</Support> |
| Web fetch citations, PDF fetch | <Support status="unsupported">not supported</Support> |

## Related

- [Messages](/docs/api/messages)
- [Responses](/docs/api/responses)
- [Web search guide](/docs/guides/web-search)
- [Configuration](/docs/guides/configuration)
- [Agents](/docs/guides/agents)


---

<!-- api/stored-completions -->
---
title: Stored completions
description: Keep chat completions on disk with store true, then list, retrieve, label and delete them with the OpenAI stored-completions routes.
---

Set `store: true` on a chat completion request and Yunshu keeps the finished completion together with the messages you sent. The routes below list, fetch, relabel and delete the stored records, following the OpenAI stored-completions API. Everything lives on your disk; nothing is sent anywhere.

<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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set; these routes then need the token like every other inference route. See [API overview](/docs/api/overview).
</Callout>

## How storing works

- Send `store: true` (and optionally `metadata`) on `POST /v1/chat/completions`. Without `store`, nothing is written.
- A non-streaming completion is stored when the response is a `200`. A streaming completion is stored when the stream finishes cleanly with `data: [DONE]`: the chunks are folded back into one `chat.completion` object (content, `reasoning_content`, tool calls, logprobs, usage). A stream that is cut off or ends with an error is not stored.
- Each record holds the completion object and the input messages. All choices are stored when `n` is greater than 1.
- Records are JSON files, one per completion, under `~/.yunshu/chat_completions` (change it with `YUNSHU_CHAT_COMPLETIONS_DIR`). When more than `YUNSHU_CHAT_COMPLETIONS_MAX` records exist (default 5000) the oldest are deleted.
- A storing failure never fails the request: it is logged and the response is returned as usual.
- The files are plain JSON. Image data URLs in your messages are stored as sent, so a record can be large.

### Metadata

`metadata` is an object of up to 16 string pairs; keys are at most 64 characters and values at most 512. Anything else is a `400` with `param: "metadata"`. It is returned on the stored completion and can be used as a list filter.

## List stored completions

`GET /v1/chat/completions` returns a page of stored completions.

| Query parameter | Type | Description |
| --- | --- | --- |
| `limit` | integer | `1` to `100`. Default `20`. |
| `order` | string | `asc` (oldest first, the default) or `desc`. |
| `after` | string | Completion id to continue after. An unknown id is a `400`. |
| `model` | string | Only completions whose `model` equals this value. |
| `metadata[key]` | string | Only completions whose metadata has this exact value. Repeat for several keys; all must match. |

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

## Retrieve, update and delete

| Route | Behavior |
| --- | --- |
| `GET /v1/chat/completions/{completion_id}` | Returns the stored `chat.completion` object, including `metadata`. |
| `POST /v1/chat/completions/{completion_id}` | Body `{"metadata": {...}}`. Replaces the whole metadata object (send `{}` to clear it) and returns the updated completion. `metadata` is required. |
| `DELETE /v1/chat/completions/{completion_id}` | Deletes the record and returns `{"id": "...", "object": "chat.completion.deleted", "deleted": true}`. |
| `GET /v1/chat/completions/{completion_id}/messages` | Lists the input messages of the completion. Takes `limit`, `order` and `after` like the list route. |

Each message in the messages list is the message you sent, plus a generated `id` (`msg_...`). When `content` was an array, `content` becomes the concatenated text and `content_parts` keeps the `text` and `image_url` parts; otherwise `content_parts` is `null`.

## Examples

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

## Errors

Errors use the OpenAI shape `{"error": {"message", "type": "invalid_request_error", "param", "code"}}`.

| Status | `code` | When |
| --- | --- | --- |
| 400 | `invalid_type`, `invalid_value` | `limit` is not an integer or is outside `1` to `100`; `order` is not `asc` or `desc`; `after` is not in the list (`param` names the field). |
| 400 | `invalid_json` | The update body is not JSON. |
| 400 | `missing_required_parameter` | The update body has no `metadata`. |
| 400 | `invalid_type`, `metadata_too_large` | Metadata is not an object of strings, has more than 16 keys, or a key or value is too long. |
| 401 | | Token configured and missing or wrong. |
| 404 | `not_found` | No stored completion has that id. An id that does not look like `chatcmpl-...` is also a `404`. |

## Support

| Feature | Status |
| --- | --- |
| `store: true` on non-streaming and streaming chat completions | <Support status="supported">supported</Support> |
| List with `limit`, `order`, `after`, `model`, `metadata[...]` filters | <Support status="supported">supported</Support> |
| Retrieve, update metadata, delete, list messages | <Support status="supported">supported</Support> |
| Storing Responses API objects here | <Support status="unsupported">not applicable; see Responses</Support> |
| Storage outside the local disk, per-record expiry | <Support status="unsupported">not supported; only the count limit evicts</Support> |

## Related

- [Chat completions](/docs/api/chat-completions)
- [Responses](/docs/api/responses)
- [API overview](/docs/api/overview)
- [Configuration](/docs/guides/configuration)


---

<!-- api/tokenization -->
---
title: Tokenization
description: Count and inspect tokens with the vLLM-style tokenize, detokenize and apply-template routes, plus the llama.cpp-style props route.
---

These routes expose the loaded model's tokenizer and chat template. Use them to count tokens before sending a long prompt, to check how a conversation is rendered, or to turn token ids back into text. The request and response shapes follow vLLM's `/tokenize` and `/detokenize`. Every route is served both with and without the `/v1` prefix.

<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">
Authentication is only enforced when `YUNSHU_AUTH_TOKEN` is set. See [API overview](/docs/api/overview). For Anthropic-style token counting use `POST /v1/messages/count_tokens`, described on the [Messages](/docs/api/messages) page.
</Callout>

## Choosing the tokenizer

`model` is optional on all three routes. The tokenizer comes from a loaded model:

- In single-model mode the loaded model's tokenizer is always used and `model` is advisory.
- In multi-model mode the model must already be loaded. The name is matched exactly, then case-insensitively, then by the part after the last `/`. An unloaded or unknown model is a `404` with `No tokenizer available for model '...'`. The server never answers with another model's vocabulary.

## Tokenize

### Request

Send exactly one of `prompt` or `messages`; sending both or neither is a `400`.

| Parameter | Type | Required | Description | Status |
| --- | --- | --- | --- | --- |
| `model` | string | no | See above. | supported |
| `prompt` | string or array of strings | one of | Raw text. An array tokenizes each string. `text` and `input` are accepted as aliases. | supported |
| `messages` | array | one of | Chat messages, rendered with the model's chat template before tokenizing. Array `content` is reduced to its `text` parts; images and other media are not counted. | supported |
| `add_special_tokens` | boolean | no | With `prompt`: default `true`. With `messages`: default `false`, because the template already contains the special tokens. | supported |
| `add_generation_prompt` | boolean | no | `messages` only. Default `true`: end with the assistant turn opener. | supported |
| `continue_final_message` | boolean | no | `messages` only. Continue the last message instead of starting a new turn; turns `add_generation_prompt` off. | supported |
| `tools` | array | no | `messages` only. Tool definitions the template renders. | supported |
| `chat_template_kwargs` | object | no | `messages` only. Extra template variables, for example `enable_thinking`. | supported |
| `return_token_strs` | boolean | no | Also return each token decoded to text. Default `false`. | supported |

### Response

```json
{
  "count": 7,
  "max_model_len": 262144,
  "tokens": [9707, 11, 1879, 0],
  "token_strs": ["Hello", ",", " world", "!"]
}
```

- `count` is the total number of tokens across all inputs.
- `max_model_len` is the model's context window, or `null` when it cannot be determined.
- `tokens` is a flat list for a single `prompt` string or for `messages`, and a list of lists when `prompt` is an array.
- `token_strs` appears only with `return_token_strs` and has the same nesting as `tokens`.

### Examples

<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` turns token ids into text.

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | string | no | See above. |
| `tokens` | array of integers | yes | Token ids. |
| `skip_special_tokens` | boolean | no | Default `true`: drop special tokens from the text. |

```bash
curl http://localhost:8000/v1/detokenize \
  -H "Content-Type: application/json" \
  -d '{"tokens": [9707, 11, 1879, 0]}'
```

```json
{ "prompt": "Hello, world!" }
```

A token id outside the vocabulary is a `422`.

## Apply template

`POST /v1/apply-template` renders messages with the model's chat template and returns the resulting prompt string without tokenizing it.

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | string | no | See above. |
| `messages` | array | yes | Chat messages. |
| `tools` | array | no | Tool definitions for the template. |
| `add_generation_prompt` | boolean | no | Default `true`. |
| `chat_template_kwargs` | object | no | Extra template variables. |

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

The exact text depends on the model's template. A template that raises an error (for example a message order it does not allow) is a `400` with `chat template failed: ...`.

## Server properties

`GET /v1/props` (also `GET /props`) is a small llama.cpp-style description of the loaded model for tools that look for it.

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

It answers `503` when no model is loaded. For the full model description use [`GET /v1/models`](/docs/api/models).

## Errors

| Status | When |
| --- | --- |
| 400 | Both or neither of `prompt` and `messages`; a chat template error; malformed JSON. |
| 401 | Token configured and missing or wrong. |
| 404 | No tokenizer is available for the named model. |
| 422 | A token id in `tokens` is invalid. |
| 503 | `GET /v1/props` with no model loaded. |

## Support

| Feature | Status |
| --- | --- |
| Tokenize text and chat messages | <Support status="supported">supported</Support> |
| Detokenize, apply-template | <Support status="supported">supported</Support> |
| Unprefixed routes (`/tokenize`, `/detokenize`, `/apply-template`) | <Support status="supported">supported</Support> |
| Image, audio or video tokens in `messages` | <Support status="unsupported">not counted; only text parts are tokenized</Support> |
| Token counting for tools, images and system blocks in the Anthropic format | <Support status="supported">use `POST /v1/messages/count_tokens`</Support> |

## Related

- [Chat completions](/docs/api/chat-completions)
- [Messages](/docs/api/messages)
- [Models](/docs/api/models)


---

<!-- developers/accuracy -->
---
title: Accuracy alignment
description: "How Yunshu shows that its serving path computes what stock MLX and mlx-vlm compute on the same checkpoint, in three tiers: logit divergence, greedy divergence and paired task evaluation."
---

A 300-question benchmark run carries roughly 13 questions of 95% noise, so it cannot see small numeric drift. Yunshu therefore checks accuracy in three tiers, cheapest and most sensitive first. This page is for maintainers who change kernels, cache layouts or schedulers. For the day-to-day candidate check see [Verification](/docs/developers/verification); for how the tiers gate a release see [Release gate](/docs/developers/release-gate).

## What it does

| Tier | What it compares | Script |
|---|---|---|
| 1 | next-token distributions on fixed text (teacher forcing): KL divergence, top-1 agreement, perplexity | `scripts/research/accuracy/kld.py` |
| 2 | greedy continuations of 50 fixed prompts, up to 256 tokens: exact match and first differing position | `scripts/research/accuracy/greedy_div.py` |
| 3 | paired downstream evaluations through the HTTP endpoint users hit: GSM8K, IFEval, MMLU-Pro, BFCL (tool calls), needle retrieval | `scripts/research/accuracy/paired_eval.py` |

The reference is always stock `mlx-vlm` on the same checkpoint with no Yunshu kernel imported (no batch-invariant, ragged KV, lane or oMLX kernels); the run asserts this. The candidate is what `VLMEngine._build_batch_runner` installs.

### Tier 1: teacher-forced logit alignment

This is the method behind llama.cpp `perplexity --kl-divergence` and vLLM's logprob-closeness tests.

- **Corpus.** `common.build_corpus` builds a pinned token corpus (prose, code, Chinese and math windows of 2048 tokens, plus long documents at 8K and 32K). Only token ids are stored, privately.
- **Reference file.** Top-64 log-probabilities for every position, plus the full-vocabulary log-softmax for a fixed random subset of positions, so later comparisons never rerun the reference. Positions outside the subset use top-64 plus one lumped tail bucket, which is a lower bound of the true divergence.
- **Parts** (the `PARTS` table in `kld.py`): `prefill`, `dec1` (one token per step, earlier the speculative lane), `dec6` (6-token verify blocks), `decb` and `decb8` (two-row shared batch on a ragged bf16 or int8 KV cache), `stockb2` (stock two-row batch, a noise floor).
- **Metrics.** KL divergence (reference to candidate) mean, median, 99th percentile and max; top-1 agreement; mean change of the top-1 probability; perplexity of both, overall and by corpus type and position bucket.

### Tier 2: greedy divergence

50 fixed chat prompts (English, code, math, Chinese and long summarization prompts), greedy, up to 256 tokens (`N_PROMPTS, MAX_TOKENS = 50, 256` in `greedy_div.py`). Each pair of runs is scored by exact match of the whole continuation and by the first differing position. The `engine` configuration runs each prompt with speculation off and on (`allow_draft`);

### Tier 3: paired downstream evaluation

`paired_eval.py` sends the same items to the reference server (stock `mlx_vlm.server`) and to Yunshu, greedy, over the same chat endpoint. Items are paired by id; only items that completed without a transport error in both arms enter the pair. It reports, per benchmark, the paired difference with a 95% interval, the discordant counts `b` (reference right, Yunshu wrong) and `c` (the reverse), and the exact McNemar p-value (`mcnemar_exact`, `loss_p`). Independent accuracy intervals are not used, because they are two to three times wider than paired ones. Failed attempts, truncations and completion lengths are reported, not hidden.

## Why (design decision)

- A benchmark score cannot distinguish a numerically legitimate implementation from a drifting one at affordable sample sizes; a distribution-level check on fixed text can.
- A candidate must be judged against what stock MLX does to itself. Reruns are bit-exact, so any nonzero difference is a real path difference. Changing the batch size or the prefill chunk size already moves stock output by a small, measurable amount; that spread (the `stockb2` part and a chunk-size comparison) is the noise floor the thresholds are built from.
- Tier 3 exists to catch what distribution metrics miss: broken formats, tool calls and long-context retrieval.

## Guarantees

Tier 1 pass criteria, per slice of corpus type and position:

- mean KL divergence at most twice the stock-versus-stock floor, and the median and 99th percentile likewise;
- top-1 agreement of at least 98.4%;
- absolute perplexity change of at most 0.5%;
- hard gate: Yunshu `prefill`, and `dec6` against `dec1`, are bit-identical (divergence exactly 0). This is what makes speculative decoding on equal speculative decoding off through the verify kernels.

Tier 2 pass criteria:

- speculation on equals speculation off, 50 of 50 identical (hard gate);
- exact match against the reference and the median first divergence must not fall below the recorded baseline for the same checkpoint;
- a stock rerun is 50 of 50 identical (harness sanity).

Tier 3 pass criterion: no significant loss (McNemar p at least 0.05 for `b` greater than `c`) on every set. A significant gain is read as noise around equal accuracy, not as an improvement. Partial runs are labelled partial and are not quoted as benchmark scores.

Lossy options (int8 KV, weight quantization) are judged against their own published gap, not against the lossless limits above.

<Callout type="info">
Measured score tables are kept out of this page on purpose: they go stale with every kernel change. Dated numbers live in the benchmark log (`docs/reports/PERF_TREND.md`) and in [Benchmarks](/docs/guides/benchmarks).
</Callout>

## Knobs

| Setting or option | Default | Effect |
|---|---|---|
| `YUNSHU_KV_PRECISION` | `bf16` | `decb8` runs with int8 KV codes; this is a lossy option judged on its own gap |
| `paired_eval.py report --bench B --ref ref --cand default` | n/a | Recomputes a benchmark row from the resumable arm files |
| `kld.py run --config stock\|serve --part ...` | n/a | Selects which arm and which parts to run |

## Limits

- Tier 1 and 2 are only as good as the pinned corpus and prompts; a checkpoint change requires rebuilding the reference (`kld.py run --config stock` without `--ref`).
- The reference server is effectively serial (no batching), so on long jobs its requests can time out where Yunshu's finish; those attempts are counted in the report.
- MMLU-Pro runs use a seeded random sample, not a stratified one, and partial runs have wide intervals.
- Results from one checkpoint and machine do not transfer: rerun on the target checkpoint.

## How to verify

```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 runs go through `scripts/dev/gpuq`. Every change to a kernel, cache layout or scheduler runs Tier 1 and Tier 2 on Qwen3.8-27B, and a failed criterion blocks the merge; reference files are stored once per checkpoint and corpus version, so a check costs only the candidate side. Tier 3 runs before each release and after any lossy option changes. The `yv` tool's `quality` stage is the cheap per-change version of Tier 3; see [Verification](/docs/developers/verification).

## Related

- [Verification](/docs/developers/verification)
- [Release gate](/docs/developers/release-gate)
- [Benchmarks](/docs/guides/benchmarks)


---

<!-- developers/agent-compat -->
---
title: Agent compatibility
description: What Claude Code, Codex CLI and opencode actually call, how Yunshu serves each request, and the scripts that re-earn those claims against the newest CLIs.
---

The goal for coding agents is near-native fidelity: Claude Code, Codex CLI, opencode and the official SDKs should find every endpoint, header, beta, tool type and server-side tool they use working like the real Anthropic and OpenAI APIs, not only correct generation. This page records what each agent calls (from a census of the real CLIs), what Yunshu does with it, and how the claim is verified. For the user-facing setup see [Agents](/docs/guides/agents).

## What it does

A census harness runs the real CLIs against a recording mock server, so the list of requests an agent makes comes from observation, not from documentation. The tools live in `scripts/research/agent_compat/`.

| Piece | What it does |
|---|---|
| `census_server.py` | A scripted, recording mock model server. Records every request (method, path, query, headers, body), answers a script of tool calls so the agent walks a session, returns 404 for unknown paths, and answers `web_search_*` requests with spec-shaped server-tool blocks. No GPU |
| `census.py` | Runs the pinned CLIs through scripted sessions: plain, bash and edit, sub-agents, web search and fetch, MCP, images, thinking, `/context`, `/cost`, `/compact`, status line, model discovery, Codex reasoning, compaction, websocket and catalog, opencode. Isolation: scrubbed environment, isolated `HOME`, `CLAUDE_CONFIG_DIR` and `CODEX_HOME`, `sandbox-exec` denying everything but loopback |
| `census_tui.py` | Drives an agent's interactive TUI in a pty (`/status`, `/model`) |
| `replay.py`, `replay_report.py` | Replay every recorded request against a real Yunshu and compare status and stream validity |
| `e2e_agents.py`, `e2e_sdk.py`, `capture_proxy.py`, `fake_searxng.py`, `tiny_mcp.py` | End-to-end runs of the real agents and official SDKs against a real model, with a fake SearXNG (fixed corpus with a checkable fact), a tiny MCP server and a full-capture proxy |
| `stream_check.py`, `synthetic_requests.py` | Stream validation and SDK-shaped synthetic requests used by the replay stages |

Raw census data is private (a local, ignored per-date `agent-census` directory).

## What each agent calls

### Claude Code

| Request | When | Yunshu |
|---|---|---|
| `POST /v1/messages?beta=true`, `stream: true` | Every turn. Several `anthropic-beta` values, `system` as multiple blocks with `cache_control`, mid-conversation `role: "system"` entries, many client tools, `thinking: {type: "adaptive"}`, `output_config`, `context_management`, `metadata.user_id` | Served. Betas are never rejected. `adaptive` thinking and `output_config` are accepted |
| `POST /v1/messages/count_tokens?beta=true` | `/context` | Served (counts system, messages, tools) |
| `GET /v1/models?limit=1000` | Only with `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`; fills `/model` | Served with `max_input_tokens`, `max_tokens` and `capabilities` |
| `POST /v1/messages` with a `web_search_20250305` tool | Its WebSearch tool: the search runs server-side and the client renders `web_search_tool_result` blocks | Implemented as a server tool, see below |
| Small-model calls | Titles, summaries, the WebFetch page summary | Served |
| MCP servers | Client-side: tools reach the model as `mcp__server__tool` function tools | Nothing to serve; needs ordinary tool calling |
| WebFetch | Client-side fetch, then a small-model summary call | Nothing to serve |
| Sub-agents, `/compact` | Ordinary `/v1/messages` calls | Served |

With traffic to Anthropic blocked, nothing else was requested: no telemetry, OAuth or update calls. Two things the CLI does not learn from a custom server: the context window (it assumes 200K for an unknown model id, which is why `CLAUDE_CODE_MAX_CONTEXT_TOKENS` exists) and prices (it prints its own arithmetic for an unknown model; this cannot be corrected from the server).

### Codex CLI

| Request | When | Yunshu |
|---|---|---|
| `POST /v1/responses`, `stream: true`, `store: false` | Every turn. `instructions`, `input` items (`developer` and `user` messages, `function_call`, `function_call_output`, `reasoning`), `tools` of type `function`, `namespace` (with nested `tools`) and `web_search`, `parallel_tool_calls`, `reasoning`, `include: ["reasoning.encrypted_content"]`, `prompt_cache_key` | Served, including `namespace` and `web_search` tools |
| `/v1/responses` with `Upgrade: websocket` | Only when the provider sets `supports_websockets = true`; three attempts, then POST | `WS /v1/responses` exists; see [Transports](/docs/guides/transports) |
| Compaction | Local: an ordinary `POST /v1/responses` with `tools: []`; there is no `/responses/compact` for a custom provider | Served |
| Model metadata | Never fetched from a custom provider; without a catalog Codex prints "Model metadata not found", sends no reasoning effort and offers only built-in models | `yunshu launch codex` writes `model_catalog_json` |
| `web_search = "live"` | Adds a `{type: "web_search"}` tool and expects `web_search_call` items | Implemented |
| MCP servers | Client-side function tools | Nothing to serve |

### opencode

| Request | When | Yunshu |
|---|---|---|
| `POST /v1/chat/completions`, `stream_options: {include_usage: true}` | Every turn; title generation runs a first request with `reasoning_effort: "low"`; headers `x-session-id`, `x-session-affinity` | Served |
| `/models` | Not fetched; limits come from `provider.*.models.*.limit` | `yunshu launch opencode` writes them |

## Guarantees

The feature matrix below uses these labels: **works** (verified, evidence named), **partial**, **missing**, **n/a** (the agent never asks for it). Evidence: "E2E" is the real pinned agent against a real Yunshu with the launch-helper configuration and a capture proxy; "SDK" is the official SDK against a real server; "unit" is `tests/unit` with fakes.

| Feature | Claude Code | Codex | opencode | SDK users | Evidence |
|---|---|---|---|---|---|
| Streaming generation, tool calls | works | works | works | works | E2E edit and bash tasks in all three, unit |
| Mid-conversation system messages | works (text and image turns) | works (`developer` items) | n/a | works | unit |
| Thinking and reasoning in the native shape | works (`thinking` blocks) | works (`reasoning` items, `encrypted_content` round trip) | works (`reasoning_content`) | works | unit, SDK |
| Effort control | works (`output_config.effort`) | works (`reasoning.effort` via catalog levels) | works (`reasoning_effort`) | works | unit, launch |
| Web search, server-side | works | works | n/a (client tool) | works (Messages and Responses, streamed and not) | E2E, SDK |
| Web fetch | client-side in the CLI | n/a | n/a | works (server-side, SSRF-guarded) | SDK |
| MCP | client-side, works | client-side, works | n/a | server-side connector works | E2E, SDK |
| Images (tool result or input) | works | n/a in exec | n/a | works | E2E |
| Model discovery and picker | works | works (catalog) | n/a | works | TUI capture, census |
| Context window and auto-compact point | works | works (catalog) | works (`limit.context`) | works | E2E `/context`, launch |
| Cost display | shows zero; the per-turn cost is the CLI's own arithmetic | n/a | n/a | n/a | TUI capture |
| Rate-limit headers | n/a: no agent needs them; Yunshu has no quota and invents none | n/a | n/a | n/a | census |
| `count_tokens` | works | n/a | n/a | works | census replay |
| Usage fields | works (including cache read and thinking tokens) | works | works (`include_usage`) | works | E2E capture |
| Engine failure mid-request | works: an SSE `error` event with the engine message | works: `response.failed` | works: an error chunk | works | unit |
| Websocket transport | n/a | works (`WS /v1/responses`) | n/a | n/a | E2E |
| Live engine state in the agent UI | works: `yunshu launch claude` installs `yunshu statusline` unless you have your own | not available | not available | `x_yunshu` fields, `: yunshu-progress` SSE comments | unit |
| Prefix-cache reuse on agent traffic | works: per-request `x_yunshu.cache` and `X-Yunshu-Cache-*` | works | works | works | cache audit in the benchmark log |

### Request-shape rules learned from real clients

These are behaviors that failed against real SDKs and clients, fixed and now covered by tests:

| Client behavior | What Yunshu does |
|---|---|
| An explicit `cache_control` marker that the chat template drops | The request is served without explicit checkpoints and the log names the marker; markers are hints, never a failure |
| `"temperature": null`, `"max_tokens": null`, `"stream": null` (LangChain, LiteLLM, Vercel AI SDK, Zed) | An explicit null means unset on all generation routes (`schemas/nulls.py`) |
| `top_k: -1` | A negative `top_k` means disabled |
| Omitted `max_tokens` | `YUNSHU_DEFAULT_MAX_TOKENS` (default 32768) is the default; the context budget still clamps it |
| Chat `tool_choice: {"type": "allowed_tools"}` and the Responses form | Folded into `tools` plus a mode on both routes |
| Responses `usage.input_tokens_details` | Includes `cache_write_tokens` as the current `openai` `Response` type requires (real writes are in `x_yunshu`) |
| A template or engine error after the stream started | An `error` event on Messages, chat and Responses, never an empty successful reply |
| Claude Code turn after an image `Read` | The vision path runs the family message adapter, so per-turn system notes do not break Qwen's template |

Known gaps (each listed with a reason in `tests/unit/test_spec_field_inventory.py`): chat `functions` and `function_call` (deprecated), custom tools in chat, Responses `prompt` templates, messages with no `user` turn, Responses `input` omitted. Yunshu ends Responses streams with `data: [DONE]` (the real API does not); every SDK and Codex stop on it.

### Sampled speculative decoding

Sampled requests (temperature above zero, what coding agents send) draft through the MTP lane with position-keyed Gumbel sampling (`keyed_sampling.py`). Noise uses 23 random bits (24 bits rounded to 1.0 in float32 and produced an infinite Gumbel value) and filtered logits are masked after the noise is added, so a filtered token can never win. Greedy requests were never affected. The check is the lane being token-identical to keyed serial draws, the draws matching the filtered softmax, and the agent E2E tasks passing with clean output.

## Server-side tools

Web search, web fetch and the MCP connector run inside Yunshu so Claude Code, Codex and the SDKs see the native server-tool blocks. The user guide is [Web search](/docs/guides/web-search); the registered settings and their defaults are:

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_WEB_SEARCH_PROVIDER` | `auto` | Search backend; `none` disables search |
| `YUNSHU_WEB_KEYLESS` | on | Allows keyless DuckDuckGo and Wikipedia (best effort); set `0` to disable the keyless fallback |
| `YUNSHU_WEB_RESEARCH` | off | Opt-in origin fetch, extraction and local ranking; stays off pending paired quality evaluation |
| `YUNSHU_WEB_RESEARCH_MODEL` | unset | Names an already-loaded local embedding model; Yunshu never loads one or falls back to the generation model |
| `YUNSHU_WEB_FETCH` | on | Serves the server-side `web_fetch` tool; private, loopback and link-local addresses are blocked |
| `YUNSHU_WEB_FETCH_MAX_BYTES`, `YUNSHU_WEB_FETCH_TIMEOUT` | 2000000, 20.0 | Largest body and wait per page |
| `YUNSHU_MCP_CONNECTOR` | on | Serves the MCP connector for Anthropic `mcp_servers` and OpenAI Responses `{type: mcp}` |
| `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` | 8 | Generate, run and continue rounds per request |

<Callout type="warn">
Search queries leave the machine. Model-generated query text can contain conversation context, and the search provider sees that query and your IP; origin pages see fetch URLs. Conversation history and client credentials are not forwarded. Excerpts from fetched pages are untrusted data and the filters do not guarantee resistance to prompt injection.
</Callout>

## Launching an agent

`yunshu launch claude|codex|opencode` reads the model card from `/v1/models` and passes the agent what it would otherwise guess wrong; `--dry-run` prints it.

| Agent | What is set |
|---|---|
| Claude Code | `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, every model alias to the served model, `CLAUDE_CODE_MAX_CONTEXT_TOKENS` (the real window), `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY`, optional `CLAUDE_CODE_EFFORT_LEVEL` (`--effort`), and a `--settings` status line running `yunshu statusline` (skipped when you have your own `statusLine`, off with `--no-statusline`). Environment and flags only: `~/.claude` is not written |
| Codex | `~/.codex/config.toml` (`model_provider`, `model_context_window`, `model_auto_compact_token_limit`, `web_search = "live"` when a provider is configured) and `~/.codex/yunshu-models.json` (`model_catalog_json`) |
| opencode | `provider.yunshu` in `opencode.json` with `limit.context`, `limit.output`, `reasoning`, `tool_call`, `modalities` |

## Knobs

| Setting or option | Default | Effect |
|---|---|---|
| `YUNSHU_DEFAULT_MAX_TOKENS` | 32768 | Completion length when a request omits `max_tokens` |
| `scripts/dev/agentcompat --stages` | `census,m3` | Which verification stages run |
| `scripts/dev/agentcompat --model` | `Qwen3.5-9B-MLX-4bit` | Model served for the M3 stage |

## Limits

- Claude Code's `/model` still lists its built-in rows, and the default row carries a `[1m]` label: both come from the client's own catalog. The window it works with is the real one (`/context`).
- The non-streaming Responses `web_search` SDK check is model dependent: a small model sometimes answers without calling the tool.
- Codex `/status` needs a completed turn before it prints token usage.
- Cline, Continue and Open WebUI are configuration guidance, not per-release end-to-end claims.

## How to verify

Documents drift, so the claims above are re-earned by one command with one verdict (exit 0 only on positive evidence, written as `verdict.json` to a local, ignored per-date `agentcompat-<commit>` directory):

```bash
scripts/dev/agentcompat                      # census,m3
scripts/dev/agentcompat --stages install,census,m3
```

| Stage | What it proves |
|---|---|
| `install` | Installs the newest Claude Code, Codex and opencode under `/Volumes/P5Plus/yunshu-build/agentic-clis-latest` (never global; `install_agents.sh` with `*_V=latest`) |
| `census` | The scripted sessions with those CLIs against the recording mock; diffed against the pinned census (paths, query keys, headers, beta values, body fields, tool and block types). Every new item must be written down in this page |
| `m3` | Two bounded gpuq jobs on the M3 laptop (`m3_serve.py`, a small Qwen3.5 model, loopback only behind an `ssh -L` forward). Job 1 replays the first and last request of every census session plus SDK-shaped synthetic requests (status 2xx, SSE event order and fields, bodies validated by the official `anthropic` and `openai` models). Job 2 runs scripted agent tasks with the latest CLIs (edit, bash, MCP, image, `/context`). A dropped tunnel or a job that does not end cleanly fails the run and quarantines the lane for a person to check |

Spec drift in `python/` is covered by `tests/unit/test_spec_field_inventory.py`: every parameter of the installed `openai` and `anthropic` SDK request types is either a field of the request model or listed with a reason, so a new SDK release that adds a field fails CI instead of being silently dropped.  Agent compatibility is one of the blocking checks of `scripts/dev/release_check`; see [Release readiness](/docs/developers/release-readiness).

## Related

- [Agents](/docs/guides/agents)
- [Agentic coding benchmark](/docs/developers/agentic-bench)
- [Release gate](/docs/developers/release-gate)


---

<!-- developers/agentic-bench -->
---
title: Agentic coding benchmark
description: How Yunshu is measured under real coding-agent loops (Claude Code, Codex CLI, opencode) with hidden tests, and how to run, repeat and extend the benchmark.
---

Single-request numbers do not show how an engine behaves under what people actually run: multi-turn coding-agent loops with a growing context, many tool calls, prefix reuse between turns and long sessions. `scripts/research/agentic/` drives real coding agents against a local server and lets hidden tests decide whether the code they wrote works.

## What it does

Per (agent, engine, task, repeat) run it records:

- pass or fail from tests the agent never sees, wall time, agent exit status and timeouts;
- number of model requests; total prompt, completion and cached tokens; cache-hit ratio; largest prompt;
- per-request TTFT and decode tokens per second, measured at the wire by a recording proxy (`proxy.py`), so every engine is measured the same way;
- API errors (4xx, 5xx, incomplete or error streams; metadata only), malformed tool-call arguments and tool-call markup leaking into text;
- the server's peak physical footprint during the run.

Agents are pinned copies installed by `scripts/research/agentic/install_agents.sh` under `/Volumes/P5Plus/yunshu-test-envs/agentic-clis`, never the ones on your `PATH`: **opencode** (Chat Completions), **Claude Code** (Messages) and **Codex CLI** (Responses). Each run gets a fresh `HOME`, XDG directories, `TMPDIR`, `CLAUDE_CONFIG_DIR` and `CODEX_HOME`, a scrubbed environment and a dummy key, and runs under `sandbox-exec` that blocks all network except loopback, hides the real `~/.claude`, `~/.codex`, `~/.config`, the keychain and shell rc files, and only allows writes inside the run directory. Sampling is whatever each agent sends by default.

There are 20 tasks: 12 Exercism Python exercises from the Aider polyglot benchmark (fetched to `/Volumes/P5Plus/datasets/agentic`, with the commit recorded in the meta row, never committed to the repository) and 8 custom multi-file tasks (bug fix, CLI flag plus tests, three-file refactor, stdlib HTTP JSON API, parser from a spec, long-context locate-and-change in a package of about 2,100 lines, shell round trips over messy data, failing-suite triage).

## Why (design decision)

- Agent traffic is the real workload: long contexts, repeated prefixes and many short tool turns. Prefix-cache reuse and TTFT matter more there than peak decode speed.
- Hidden tests make the result a task outcome, not a style judgement.
- Measuring at a recording proxy removes engine-specific timing bias.
- Failed runs stay in the denominator; timeouts count as failures.

## Guarantees

- The verdict of the repeatable run fails closed: API errors, malformed tool calls, markup leaks and missing runs all fail it.
- Output files begin with a `meta` row (engine, checkpoint, git SHA, agent version, flags). Runs are resumable: a task and repeat already present in `--output` is skipped.
- Only dated, aggregate results with snapshot SHAs, denominators, timeouts and uncertainty are published; raw run metadata, agent artifacts and JSONL stay private in an ignored local directory.

## Knobs

| Option | Default | Effect |
|---|---|---|
| `run_agentic.py run --serve yunshu` | n/a | Starts a server (Yunshu defaults or TensorFold) for the job and kills it at the end |
| `--engine-url URL --engine-label X` | n/a | Use a server you started yourself |
| `--agent`, `--tasks`, `--repeat` | n/a | Select the agent, tasks (`all` or a list) and repeats |
| `--shard-i`, `--shard-n` | n/a | Split the run list across jobs |
| `--budget-min` | n/a | Stop starting new runs so a job ends inside its queue timeout |
| `scripts/dev/agentbench --priority` | -1 | gpuq priority of the matrix cells (nightly standalone runs) |

## Run it

```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 runs go through `scripts/dev/gpuq`.

### The whole matrix: `scripts/dev/agentbench`

`scripts/dev/agentbench` runs Claude Code, Codex and opencode on all 20 tasks against the default 27B server on a ref (`--ref`, default `main`): one low-priority gpuq job per cell, a verdict that fails closed, and a comparison with the earlier recorded run. `--dry-run` previews, `--no-wait` returns after submitting and `--collect` gathers a submitted run. `scripts/dev/release_check` submits it for the release candidate at priority -3 and prints a later collect command. Agentbench is informational: the release gate, the M3 sweep and agent compatibility block a release, agentbench does not. Collect and record every submitted result anyway.

## Add a task

Create `scripts/research/agentic/tasks/<id>/` with:

- `task.json`: `id`, `title`, `prompt`, `test` (argv), optional `protected` files restored before grading, optional `generate` script that writes extra files into the working directory;
- `repo/`: the starting files;
- `hidden/`: test files copied to `_hidden_tests/` only at grading time (`AGENTIC_TASK_DIR` and `AGENTIC_TASK_SRC` are set);
- `reference/`: an overlay, or `apply.py`, that solves the task.

`check-tasks` must report the starting repo failing and the reference passing. Keep tasks deterministic and offline. Polyglot exercises are listed in `tasks.py` and materialized from the dataset.

## Recorded results

Only one dated result is published, from `docs/reports/PERF_TREND.md` (2026-10-02, partial matrix; Qwen3.8-27B oQ4e-mtp, M5 Max, Yunshu default settings, 20 tasks; the two snapshots differ in code and run mix, so they are not pooled):

| snapshot (git SHA, date) | agent | runs | pass | rate (Wilson 95%) | wall med / p90 (s) | cache hit | timeouts |
|---|---|---:|---:|---|---|---:|---:|
| 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 |

Intervals are wide at n of 10 to 15, and the change between snapshots is a direction, not a measured speedup. Codex and TensorFold cells have no published result.

## Limits

- The matrix is partial; no cell has all three repeats of all 20 tasks.
- Agents are pinned for repeatability; compatibility with the newest CLIs is a separate check, see [Agent compatibility](/docs/developers/agent-compat).
- Timing is meaningful only when the job was not paused by serving traffic or contaminated by foreign CPU load; see [Serve and develop](/docs/developers/serve-and-develop).

## How to verify

`check-tasks` proves the task set is sound. `scripts/dev/agentbench --dry-run` previews the matrix, and `run_agentic.py summarize` prints the aggregate for a set of JSONL files. For the user-facing agent setup see [Agents](/docs/guides/agents).

## Related

- [Agent compatibility](/docs/developers/agent-compat)
- [Release gate](/docs/developers/release-gate)
- [Benchmarks](/docs/guides/benchmarks)


---

<!-- developers/api-parity -->
---
title: API parity matrix
description: One row per request or response feature of the OpenAI and Anthropic APIs we serve, one column per route and stream mode; executable probes keep every engaged cell honest and every gap counted.
---

The API layer is four routers that serve the same engine through different dialects: chat completions, Responses, Messages and legacy completions. A feature (tools, `seed`, `logprobs`, structured output, background, server tools, ...) has to work on every route where the spec has it, streamed and not. The **API parity matrix** (`python/yunshu_gateway/api_matrix.json`) is the list of those features and what each route does with them. `tests/unit/test_api_parity.py` and `tests/unit/test_api_parity_wire.py` enforce it. It is the API-layer sibling of the engine path matrix (`python/yunshu_engine/path_matrix.json`, [Architecture](/docs/developers/architecture)).

## Shape

- **Rows** (61): sampling fields, `max_tokens`, `stop`, `n`, `logprobs`, tools / `tool_choice` / parallel calls / tool results, structured output and grammars, reasoning and thinking controls, usage and cached tokens, background, store / retrieve / delete, `previous_response_id` and conversations, cancel and client disconnect, context management and overflow, server tools (web search, web fetch, MCP, code execution, shell), prompt caching fields and `cache_control`, image / audio / video / file input, metadata, `service_tier`, `include`, engine switches, `x_yunshu` and request ids, error envelopes, token counting and batches.
- **Columns** (9): `chat`, `responses`, `messages` and `completions`, each streamed and non-stream, plus `responses/background`.
- **Cells**: `engaged` (code evidence plus a probe or a named test that runs exactly that cell), `na` (the spec says it does not apply, with the reason), `partial` or `missing` (a gap, with a `kind` of `unimplemented`, `divergent` or `untested`, an impact and an owner).

## Probes

A cell is `engaged` only while a test exercises it. `test_api_parity_wire.py` runs 434 probes against a scripted engine behind the real routers: it posts the request through the actual route (raw HTTP or the official OpenAI and Anthropic SDKs), streamed, non-stream and as a background response, and checks what reached the engine (forwarding probes: every sampling and constraint field) or what came back (behaviour probes: usage, cached tokens, reasoning split, tool calls, structured output, stored objects, previous-response chains, cancel, client disconnect, context overflow, error envelopes). A `partial` cell whose probe starts passing fails the test until the cell is flipped to `engaged`, so a gap cannot be closed silently.

## Where things stand

| Column | 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 cells engaged, 159 not applicable, 62 gaps. `gap_budget` in the matrix is that last number; it may only go down.

## Guards

- A new request field on any of the four request models, a new server-tool kind (`ServerToolDef.kind`) or a new `server_tools` module fails the test until it has a row.
- Evidence (code needles, test functions) that moves or disappears fails the test.
- `duplicates` lists 14 features implemented more than once across routers (tool-call streaming, usage building, sampling resolution, server-tool loops, error mapping, disconnect handling, stop and finish mapping, reasoning split, `response_format` parsing, `tool_choice` enforcement, message conversion, `n > 1`, text and VLM branches, stored objects), each with the file paths and a one-line unification proposal.

## Adding or changing a feature

1. Add the request field to the router, then a row (or the field on an existing row) in `api_matrix.json`.
2. Fill the nine cells. Prefer a probe in `test_api_parity_wire.py`; otherwise cite a route-level test by file and function.
3. If you close a gap, flip the cell and lower `gap_budget` in the same commit.

Run `uv run pytest tests/unit/test_api_parity.py tests/unit/test_api_parity_wire.py -q`. See also [Request lifecycle](/docs/internals/request-lifecycle) and [Agent compatibility](/docs/developers/agent-compat).


---

<!-- developers/architecture -->
---
title: Architecture
description: How a request moves through the gateway and the engine, the two serving paths, the prefix cache, speculative decoding, batch-invariant kernels and constrained decoding.
---

Yunshu is a single-node inference engine for Apple Silicon. One process runs a FastAPI gateway and the MLX-based engine, and it exposes OpenAI-, Anthropic- and Ollama-style APIs. This page describes how the pieces fit together, for people who read or change the code. It states only what the code does; for tunable behavior see [Configuration](/docs/guides/configuration).

## Package layout

The repository is a flat monorepo. Python packages live under `python/`.

| Package | Responsibility |
|---|---|
| `yunshu_gateway` | FastAPI app. The routers (`routers/`) implement the OpenAI, Anthropic, Ollama, MCP, Realtime and Tavily-compatible surfaces; `schemas/` holds shared request normalization; `server_tools/` runs server-side web search, fetch and the MCP connector; `middleware/` has auth, metrics, request logging, rate limiting, disconnect handling and the `x_yunshu` extensions |
| `yunshu_engine` | Everything that runs a model: modality dispatch (LLM, VLM, OCR, ASR, TTS, image, embeddings), the two text serving paths, sampling and constraints, speculative decoding, the prefix caches, Metal kernels (`kernels/`) and the settings registry (`settings.py`) |
| `yunshu_kv` | KV cache building blocks: block pool and hashing, serialization, compression, SSD stores and the warm tier. The engine's prefix caches are built from these parts |
| `yunshu_cli` | The `yunshu` command: `serve`, `chat`, `launch`, `service`, `config`, `doctor`, `cache` and more |
| `yunshu_control` | Small shared helpers: the audit log and token counting |

## From request to tokens

```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** authenticates the request (a token is required only when `YUNSHU_AUTH_TOKEN` is set), assigns an `X-Request-Id`, records metrics and watches for client disconnects, which cancel the generation.
2. **A router** validates the body against its dialect's schema, normalizes it (null fields mean unset, `guided_*` and `structured_outputs` fold into one constraint form, tool choice is validated) and turns it into one internal generation request.
3. **Engine dispatch** looks up the model (`ModelManager` loads models lazily, evicts by LRU under memory pressure and can pin models) and hands the request to the engine for its type.
4. The engine returns tokens; the gateway turns them into the dialect's response or stream, including usage, tool-call blocks, reasoning split and the additive `x_yunshu` fields.

## Two serving paths

All GPU work runs on **one MLX thread**: a global single-worker executor owns a thread-local Metal stream, and every engine submits its work there. This is what makes multi-model serving safe, and it is why the code never touches MLX arrays from the event loop.

### VLM batch runner

Every model served through `mlx-vlm` (`VLMEngine`) runs on the VLM batch runner (`vlm_batch_runner.py`), built by `VLMEngine._build_batch_runner`, which hosts the round driver. The driver serves every row through one of three model layers: packed Qwen3.5 (dense and MoE), packed Flash-Next (Qwen4), and the generic layer (the model's own upstream forward per row) for all other families. This includes text-only requests to a VLM checkpoint such as Qwen3.5.

- **Continuous batching** with per-request sampling parameters and seeds (`RowSampler`). Prefill is admitted one request at a time and interleaved with decode of the other rows.
- **Prefix cache (APC)** for every family without a sliding-window cache, using exact checkpoints for hybrid models, image-pixel and audio-feature keys for media, and an optional SSD tier. See [Prompt caching](/docs/guides/prompt-caching).
- **Image, audio and video input** through the media preparation step of the runner.
- **Speculative decoding** for the Qwen3.5 family only (see below).
- LoRA adapters and custom logits processors are rejected for VLMs.

The runner only yields token ids. Detokenizing, stop strings, thinking state and delivery to the HTTP layer stay in `VLMEngine`, so every text path reports results the same way.

### Text-only fast path

Text-only `mlx-lm` models run through `_generate_fast`, which calls mlx-lm's `generate_step` directly for one request at a time. Concurrent requests to such a model are serialized. This path has its own prefix cache (`KVPrefixCache`), KV quantization, n-gram and jump-forward options, and the constrained-decoding samplers.

### Per-request state

- **Sampler**: temperature, top-p, top-k, min-p, penalties, logit bias and seed are applied per request. Sampled requests that use speculative decoding draw position-keyed noise so the result does not depend on which tokens were drafted.
- **Stop and reasoning state**: stop strings, end-of-sequence tokens and reasoning boundaries are tracked with a per-request state machine built on an Aho-Corasick trie, so a stop sequence is found even when it spans token boundaries.
- **Detokenizer**: each request gets its own streaming detokenizer. Detokenizers are never pooled, because resetting one can leak byte buffers.

## Prefix cache

Both paths reuse the KV cache of an earlier prompt that shares a prefix with the new one. The VLM runner's APC stores exact checkpoints (attention KV plus recurrent state at a token position), keeps a head checkpoint per distinct system-prompt-plus-tools, supersedes older checkpoints of the same conversation, and writes evicted checkpoints to an SSD tier that survives restarts. Exact-window restore is checkpoint-specific; Gemma 4 has scoped parity receipts, without certifying every sliding-window model. The lossless and lossy options, and what appears in usage, are described in [Prompt caching](/docs/guides/prompt-caching).

## Speculative decoding

For the Qwen3.5 family on the VLM runner (model types `qwen3_5`, `qwen3_6` and `qwen3_5_moe`), decoding can draft several tokens and verify them in one forward pass:

- **MTP**: draft with the checkpoint's own multi-token-prediction head. This is the default (`YUNSHU_MTP`), with a default block of 6 tokens (`YUNSHU_MTP_BLOCK_SIZE`).
- **DFlash**: draft with an external block-diffusion drafter. `YUNSHU_VLM_DRAFT` points at a drafter directory, forces `mtp`, or turns drafting `off`; when unset, a matching drafter found in the models directory or the Hugging Face cache is used.

Speculative decoding runs on the round driver's packed rows, so concurrent requests draft too. Other model families use the generic paths without speculation.

### Batch-invariant kernels and the lossless guarantee

The guarantee Yunshu makes is: **with speculative decoding on, greedy output is token-identical to the same engine with it off.** To get it, every target-model matmul for decode (one row) and verify (a few rows) goes through one kernel whose per-row result does not depend on how many rows share the call, and the attention and GatedDeltaNet verify paths are bit-exact against single-row decode. Only modules the engine marks as targets are rerouted; draft models keep stock kernels. Prefill chunks keep the stock kernels.

What the guarantee does not say: the output is not required to be bit-identical to stock MLX single-row decoding. Different reductions move logits by rounding-level amounts, and that drift is expected. The kernels are Metal kernels compiled at runtime (`mx.fast.metal_kernel`) and live in `python/yunshu_engine/kernels/`; some are vendored or derived from other projects, tracked in [Upstream tracking](/docs/developers/upstream-tracking). A custom kernel is adopted only when a same-checkpoint end-to-end comparison shows a real win with identical (or tolerance-checked) output; see [Verification](/docs/developers/verification).

## Constrained decoding

`response_format`, `grammar`, `guided_*` and forced `tool_choice` become a constraint object. At each step the sampler masks tokens the constraint cannot accept. JSON schema and `json_object` use an `llguidance` matcher by default or an in-house state machine (`YUNSHU_JSON_SCHEMA_ENGINE`); regex and choice are compiled in-house; context-free grammars use `llguidance`. The default masking is an allowlist sampler, with an opt-in xgrammar-style bitmask engine (`YUNSHU_GRAMMAR_BITMASK`) and jump-forward decoding (`YUNSHU_JUMP_FORWARD`). Invalid constraints are rejected with a `400` before generation. See [Structured output](/docs/guides/structured-output).

## Settings

Every `YUNSHU_*` setting is registered in `python/yunshu_engine/settings.py` with a type, default, description and group, and is read through `settings.get(...)`; code never reads `os.environ` for them (a unit test enforces this). Values come from, in order of precedence, the command line (`--set`), the environment, `~/.yunshu/config.toml` and the registered default, and `yunshu config` shows the effective value and its source. See [Contributing](/docs/developers/contributing) for the rules on adding one.

## Related

- [Prompt caching](/docs/guides/prompt-caching)
- [Structured output](/docs/guides/structured-output)
- [Contributing](/docs/developers/contributing)
- [Verification](/docs/developers/verification)


---

<!-- developers/auxiliary-scheduling -->
---
title: Auxiliary scheduling
description: How captured client side requests (opencode title generation) yield to interactive agent turns, how prefill work is ordered, and what stays identical in the output.
---

An agent client sends more than one request per user action. opencode, for example, starts a title-generation request next to the main agent turn. On a single GPU the title request can sit in front of a long prefill that the user is waiting for. Yunshu recognizes captured auxiliary requests exactly, lets interactive turns go first, and keeps every output token-identical to ordinary scheduling. This page is the design reference for maintainers; for client behavior see [Agent clients](/docs/guides/agents).

## What it does

One policy runs on the VLM batch runner, and it is on by default only for a loaded backend that engages the qualified batch-invariant kernels (`_prefix_invariant_dispatch`, the tuned Qwen3.5 family such as 27B):

- **Auxiliary yielding** (`YUNSHU_AUXILIARY_SCHEDULING`). `python/yunshu_gateway/admission.py` classifies the validated Chat Completions body with `auxiliary_kind`. A request is auxiliary only when it matches the captured opencode title fingerprint: no tools or functions, the captured client model name, `max_tokens` of 32000, exactly three plain-text messages with roles `system,user,user`, and a SHA-256 of the system message equal to the captured one. Anything else, including requests from Claude Code and Codex, keeps priority 0, because no auxiliary request from those clients was captured and no fingerprint is invented. The result is `scheduling_priority = -1` on the request record; it never enters the prompt or the sampling parameters.
- **Prefill order** is the round driver's own: every request is a row, and its prefill is ordered shortest remainder first. The earlier uncached-work ordering setting (`YUNSHU_UNCACHED_SCHEDULING`) was removed with the stock runner.

The sequence below shows one title request and one agent turn arriving together.

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

A recognized auxiliary request waits 500 ms (`defer_auxiliary`) so the companion agent turn can arrive, then waits until no interactive request is active, or until it has aged 10 seconds (`AGING_S`), before entering the engine. Ordinary requests pay no wait. The deferral also keeps auxiliary work out of the serialized text fast path while a primary is present.

### Runner behavior

- The VLM runner holds pending auxiliary rows while primary work exists, keeps the two priorities in separate batches, and pauses an active auxiliary batch while a primary is present. The [round driver](/docs/developers/round-driver) has a separate auxiliary driver with the same model, chunking and sampling path.
- An auxiliary row that has waited 10 seconds since its last service gets a service opportunity. That is not a completion deadline: in-flight atoms, older work, client cancellation and deadlines still apply.
- Interactive prefills gain persistent FIFO protection after one overtaking atom, so later short arrivals cannot repeatedly skip a long cold request. A selected request finishes its last 2048-token window and delivers its first token before decode debt is repaid.
- Decode time owed to running rows after a prefill atom is at least 75 ms (`DECODE_QUANTUM_S`) and at most `DECODE_QUANTUM_MAX_S`, with a larger share for rows still in their first tokens. A short primary completion handoff (`PRIMARY_HANDOFF_S`, 100 ms) keeps a finishing primary ahead of auxiliary admission, with a CPU-only timer so MLX work stays on the single executor thread.

## Why

Evidence comes from saved client traffic, not a client-name or small-model heuristic. `scripts/research/agentic/characterize_auxiliary.py` inventories captured request bodies. In the captured set, opencode sent title requests (small prompts, large output limit) next to agent turns, while no auxiliary request was captured for Claude Code or Codex. A broader heuristic would risk deprioritizing real user work. The cost of being narrow is that unknown side requests stay interactive.

## Guarantees

- **Output identity.** Auxiliary scheduling changes order, not token spans, sampling or grammar state. Captured replays on the 27B checkpoint compare complete content, reasoning, tool-call and finish-reason digests with the policy on and off, for both primary and auxiliary responses; the gate requires every comparison to match.
- **No cancellation of auxiliary work.** Auxiliary output is never cancelled, dropped, restarted or truncated; a paused row resumes with its state. Cancelled paused rows are cleaned up at the next slice.
- **Cache isolation.** Auxiliary requests do not read or write the prefix cache (APC), cannot supersede or evict primary RAM or disk checkpoints, and do not update the prefill cost model. They still run the same canonical checkpoint arithmetic, which keeps their numerics equal to ordinary scheduling. The text fast path bypasses prefix and prompt caching for them too.
- **Unqualified backends keep ordinary scheduling** (FIFO admission and normal APC) unless the setting is explicitly enabled.
- **Non-preemptible kernels.** A GPU operation already submitted cannot be interrupted. A primary arriving after auxiliary prefill started waits for the current slice, never for the whole auxiliary generation. The text-only `mlx-lm` fast path still runs a started request to completion; only the gateway deferral and cache protection apply there.
- **Exact token counts for the context guard.** Qualified VLM backends keep a tokenizer-scoped LRU of successful text token counts (128 strings, 2 MiB of estimated text) so repeated prompts are not re-tokenized in the gateway context and prefill guard. Role and tool overhead and media costs are still counted per request, and a failed encode is never cached. This saves host work only.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_AUXILIARY_SCHEDULING` | `true` for qualified backends only | `0` disables, `1` also opts an unqualified backend in. A stable deployment override |

The default resolves in `settings.scheduling_enabled`: when the value comes from the default source, the loaded backend's qualification decides; an explicit value always wins.

## Limits

- Only the captured opencode title fingerprint is recognized. Requests that differ in model name, output limit or system text are interactive.
- The measured claim is the 27B VLM runner. Evidence comes from one captured session replayed in interleaved fresh-server pairs; it is a scheduling tradeoff, not a general speed improvement. The captured median time to first token was slightly worse with the policy on, while the tail, the six-turn completion time and a long-prefill mix improved (below).
- Auxiliary latency gets worse by design: the mean title time to first token was higher with the policy on in the replay.
- The round driver retains strict auxiliary priority without aging, so endless primary driver traffic can defer auxiliary service indefinitely.
- Non-captured clients and APIs (Responses, Messages) are not classified.

## How to verify

- Unit tests: `tests/unit/test_auxiliary_inventory.py`, `tests/unit/test_auxiliary_scheduling.py`, `tests/unit/test_priority_scheduling.py` and `tests/unit/test_priority_queue.py` cover fingerprint near misses, opt-out, priority propagation across executor threads, pending and active priority inversion, state-preserving resume, separate speculative and driver lanes, and APC exclusion.
- GPU replay: `scripts/research/agentic/i8_summarize.py` rejects incomplete runs and compares complete response digests for primary and auxiliary requests; CPU-only ordering is simulated by `scripts/research/agentic/i8_admission_sim.py`. These run through the GPU queue; see [Verification](/docs/developers/verification).
- Measured result (Qwen3.8-27B, 2026-10-03, `docs/reports/PERF_TREND.md`): captured main time to first token p50 0.7515 s to 0.7570 s, p90 8.5990 s to 7.6239 s, six-turn completion sum 40.226 s to 33.504 s; long-prefill mix p50 23.098 s to 8.6795 s. Digests matched in all pairs.


---

<!-- developers/contributing -->
---
title: Contributing
description: Set up a development checkout, run lint and tests, follow the settings registry rule, and open a pull request.
---

Yunshu lives at [github.com/YuhuanStudio/Yunshu](https://github.com/YuhuanStudio/Yunshu) and is licensed under Apache 2.0. By contributing you agree that your contributions are licensed the same way. This page covers the working loop; the repository's `CONTRIBUTING.md` and `AGENTS.md` are the short versions of the same rules.

## Prerequisites

- A Mac with Apple Silicon and a native arm64 Python. Yunshu requires macOS.
- Python 3.13 or newer.
- [uv](https://github.com/astral-sh/uv), the only Python package manager the project uses.
- [just](https://github.com/casey/just) as the command runner (`brew install just`).

## Set up

```bash
git clone https://github.com/YuhuanStudio/Yunshu.git
cd Yunshu
just setup
```

`just setup` runs `uv sync --all-extras --dev`. For a lighter checkout, install only the extras you need:

```bash
uv sync --extra vision        # mlx-vlm: VLMs, OCR, the Qwen3.5 family
uv sync --extra audio         # mlx-audio: ASR, TTS and the Realtime voice cascade
uv sync --extra omni          # mlx-vlm + torch: native Qwen3-Omni speech-to-speech
uv sync --extra generation    # image generation
uv sync --extra embeddings    # /v1/embeddings and /v1/rerank
```

Start a development server against a local MLX model:

```bash
YUNSHU_MODEL=/path/to/mlx-model just dev    # uvicorn on 127.0.0.1:8000
just dev-multi                              # multi-model mode, models in ./models
```

## The development loop

| Command | What it does |
|---|---|
| `just lint` | `ruff check` on `python/` and `tests/`, plus the mypy baseline gate |
| `just format` | `ruff format` on `python/` and `tests/` |
| `just test-unit` | the unit suite (`tests/`, integration tests excluded); needs no models |
| `just test` | currently the same unit suite |
| `just test-integration` | integration tests, which need real models or running services (opt-in) |
| `just test-single tests/unit/test_foo.py` | one file |

A single test also runs with `uv run pytest tests/unit/test_foo.py -q`. The pytest configuration lives in `pyproject.toml`: strict `xfail`, asyncio auto mode, and the markers `gpu`, `integration` and `slow`.

Code style: Python 3.13, ruff-formatted with an 88-column line length and the lint rules `E, F, W, I, N, UP, B, SIM`. `just lint` is authoritative. Comments should explain the why (a hidden constraint, a subtle invariant, a workaround), not restate the code.

## Repository layout

| Path | Contents |
|---|---|
| `python/yunshu_gateway/` | FastAPI gateway: routers, schemas, middleware, server-side tools |
| `python/yunshu_engine/` | inference engine: serving paths, sampling, speculative decoding, prefix caches, kernels, the settings registry |
| `python/yunshu_kv/` | KV cache building blocks |
| `python/yunshu_cli/` | the `yunshu` CLI |
| `python/yunshu_control/` | audit log and token counter |
| `tests/` | `unit/`, `integration/` and `e2e/` tests |
| `scripts/` | tooling: `gen_config_docs.py`, `dev/` (verification and release helpers), `vendor/`, `release/` |
| `docs/` | reference guides |
| `frontend/` | the web console, including these docs (`frontend/docs/`, MDX in three languages) |

[Architecture](/docs/developers/architecture) explains how the packages fit together. The Metal kernels compile at runtime (`mx.fast.metal_kernel`), so there is no separate kernel build step.

## The settings registry rule

Every `YUNSHU_*` setting is registered in `python/yunshu_engine/settings.py` and read with `settings.get(...)` or one of its typed getters. Code never reads `os.environ` or `getenv` for a `YUNSHU_*` name; a unit test enforces this.

Adding a setting:

1. Add one `_add(...)` line to `settings.py` with the name, type, default, a one-line description and a category.
2. Read it through `settings.get("YUNSHU_NAME")` where it is used.
3. Regenerate the reference and commit the result:

   ```bash
   uv run python scripts/gen_config_docs.py
   uv run python scripts/gen_config_docs.py --check    # CI-style check that it is current
   ```

4. If the setting changes a default, an API or a CLI behavior, note it in the Unreleased section of `CHANGELOG.md`, with migration steps when users must act.

Values resolve, highest precedence first, from `yunshu serve --set KEY=VALUE` and the typed `serve` flags, then the process environment, then the config file (`~/.yunshu/config.toml`, written by `yunshu config set`), then the registered default. `yunshu config` prints the effective value and where it came from.

### Experimental flags are temporary

A setting can be marked `stability="experimental"`. Each one must name the measurement that will decide it (`decide=`) and when it was added (`added=`), and at most eight may exist at once. Once measured, the winner becomes the default and both the flag and the losing code path are deleted. Only **lossless** optimizations (layouts, kernels, schedulers, anything that leaves output unchanged) may replace a default this way; an opt-out can stay when it has real value. **Lossy** options (KV int8, weight quantization, anything that changes output quality) are stable user options with a lossless default, and a benchmark alone never makes them the default.

## Hot-path changes

Performance work is judged end to end. A faster isolated kernel is not enough: a change to the hot path needs a same-checkpoint comparison of output (token-identical, or within a stated tolerance) and of the measured effect on time to first token, decode speed or prefix reuse. [Verification](/docs/developers/verification) describes the tooling.

## Commits and pull requests

Commit messages follow [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
```

Open a pull request against `main` that says what changed and why, with the output of `just test-unit`. Include a benchmark comparison only when the change touches the hot path. Review expectations:

- Keep changes focused and describe the user-visible before and after.
- A bug fix needs a regression test that fails without the fix.
- Record what you ran and anything you did not verify. Documentation-only changes do not need model benchmarks.
- Disclose AI assistance and review the result yourself, including sources and license notices.
- Large architecture changes go through a short RFC first.

## Public documentation checks

If you change documented behavior, these checks keep the docs and the code in agreement:

```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>` reproduces the release build checks in a clean Python 3.13 checkout without using a model: lint, format, mypy, the unit tests, the package build, `twine` validation and a wheel-install smoke test.

## Scope

Yunshu is a single-node inference engine. Distributed or multi-node serving and a multi-tenant control plane are out of scope. Single-node decoding and optimization work (speculative decoding, constrained decoding, quantization, caching, kernels) is in scope and welcome, as is compatibility work that makes real clients behave as they do against the vendor APIs.

## Related

- [Architecture](/docs/developers/architecture)
- [Verification](/docs/developers/verification)
- [Release gate](/docs/developers/release-gate)
- [Upstream tracking](/docs/developers/upstream-tracking)
- [Configuration](/docs/guides/configuration)


---

<!-- developers/hardware-validation -->
---
title: Hardware validation
description: "The plan for validating Yunshu across Apple Silicon generations, and the M5 Max hardware map: what each unit measured, what Yunshu uses of it and which ideas survived a roofline check."
---

This page has two sections. The first is the validation plan for Apple Silicon support, which is a product target and not evidence that every chip and macOS combination has been tested. The second is the hardware map of one machine, an M5 Max, used to decide where optimization effort goes.

## Hardware validation plan

Hosted `macos-14` CI jobs do not prove a particular M-series GPU generation or real Metal availability. The current workflows are `.github/workflows/ci.yml` and `release.yml`; no extra runner is provisioned for hardware coverage.

### What it does

| Tier | Trigger | Checks | Evidence to retain |
|---|---|---|---|
| Fast | Each change | Linux lint and build; model-free public-contract and CLI tests where dependencies permit | Source SHA, dependency lock and test counts |
| Correctness | Trusted PR or pre-release | Apple Silicon unit suite; tiny-model API, cache and constraint smoke | Chip, memory, macOS, Python and MLX versions, checkpoint revision, passed, failed and skipped |
| Hardware coverage | Scheduled or pre-release | M1 to M5; oldest supported and current macOS, with available hosts | Explicit tested and untested cells; output, cache and logprob parity |
| Performance | Controlled scheduled run | Same-checkpoint decode and cold, warm and turn-2 TTFT; three interleaved repetitions | Raw receipts, engaged mode, output lengths, digests, medians and regressions |

### Guarantees

- Hardware that was unavailable for a release is listed as untested, never marked passed.
- GPU coverage is never inferred from runner names.
- Untrusted PR code does not run on a personal model host.
- Correctness failures stay separate from performance noise and infrastructure failures. Failed cases are retained, not silently retried out of the report.
- Benchmark thresholds become gates only after a stable noise baseline exists.

### Limits

A maintainer must inventory available hosts and the supported macOS minimums before this plan becomes required CI. Today the M5 Max is the timing machine, and a 36 GB M3 laptop provides correctness and portability evidence only: M3 results never approve an M5 hot-path default, and an M3 failure needs M5 reproduction before it rejects an M5 optimization. The lane is documented in [Serve and develop](/docs/developers/serve-and-develop).

### How to verify

The correctness tier is `scripts/dev/ci-local <sha>` plus the `install` stage of the release gate; see [Release gate](/docs/developers/release-gate). The M3 lane is `scripts/dev/m3sweep` and `gpuq submit --device m3`. Benchmark methodology is in [Benchmarks](/docs/guides/benchmarks) and accuracy evidence in [Accuracy alignment](/docs/developers/accuracy).

## M5 Max hardware map

This section is a historical probe record for one machine (M5 Max, 40-core GPU, 128 GB). It is not a statement of current dependency versions or release performance; for dated numbers use [Benchmarks](/docs/guides/benchmarks). The probes live in `scripts/research/hw/` and each writes JSONL, which holds the numbers (they are kept out of this page because they come from one machine at one time). Every GPU, ANE and heavy CPU probe ran under the shared GPU lock, because these units share one memory system and one run disturbs another.

### What each unit is used for

| Unit | Probe scripts | What Yunshu uses of it |
|---|---|---|
| Memory bandwidth | `bw_unified_memory.py`, `decode_proxy_step.py`, `decode_step_model.py`, `decode_step_engine.py` | Decode streams the model weights once per step, so it is bandwidth bound |
| GPU tensor units (NAX) | `gpu_compute.py`, `tensor_unit_peak.py` | NAX quantized matmul in MLX for prefill; a NAX-packed 4-bit kernel for decode and verify |
| GPU launch and sync | `launch_overhead.py` | Launch cost is hidden behind GPU work through `async_eval` |
| ANE | `ane_probe.py`, `pick_best_ane.py`, `bg_gpu_concurrency.py`, `session_ane_prefill.sh` | An embedding co-processor only (`ane_embedding.py`) |
| CPU | `cpu_probe.py` | Detokenization, grammar and sampling glue |
| Prefill beside decode | `gpu_stream_overlap.py`, `bench_prefill_interleave.py` | Prefill chunk size as a policy (`ROUND_PREFILL_CHUNK`) |

### Findings

- **Decode is weight-bandwidth bound.** A step cannot go below its weight-read time at the best measured read bandwidth, and stock decode was already close to that line. Only fewer bytes per token (more accepted tokens per weight read, lower bits) or sharing reads across rows moves it. Small projections (K/V, GDN gate) run well below the bandwidth line and are the place where fusing launches could help.
- **Wide verify is nearly free.** Quantized matmul stays weight-bandwidth bound through a few rows, and compute only binds past a few dozen rows, so one weight read serves several verify rows. This is why speculative and multi-row decode pay.
- **Launch overhead is not the bottleneck.** The CPU builds the next step's graph while the GPU runs the previous one. `mx.compile` on a decode layer, `MLX_MAX_OPS_PER_BUFFER` and `MLX_METAL_FAST_SYNCH` changed nothing measurable, and MLX has no graph replay to exploit.
- **The ANE is not free bandwidth.** It keeps nearly all of its own rate while the GPU decodes, but each ANE call streams its weights from the same DRAM and slows GPU decode. Alone it prefills at roughly a third of the idle GPU rate, so it is useful at most for a prompt arriving while another request streams, and its numerics differ from the MLX 4-bit weights (a lossy option, not a default).
- **The CPU cannot help decode.** Sampling over a large vocabulary is cheap for one row (argmax is hidden behind the next step) but not for top-k or sort over many rows, so sampling stays on the GPU. CPU memory traffic also slows the GPU, and CPU drafting is impractical.
- **Wired memory and power.** `mx.set_wired_limit` and cache-limit changes gave no gain on a 128 GB machine; no throttling was visible in sustained decode loops.
- **Prefill and decode contend.** Two GPU command queues do not overlap prefill and decode, and decode gets no priority. On one queue, a smaller prefill span keeps a running request decoding much faster at the cost of a longer time to first token for the arriving prompt. The prompt's tokens are identical to running it alone for both chunk sizes. `ROUND_PREFILL_CHUNK` sets the span.

### Proposals and outcome

| Idea | Outcome |
|---|---|
| Prefill chunk as a policy | Done: `ROUND_PREFILL_CHUNK`, default 512; adapting it to decoding rows is open |
| Keep decode kernels at the bandwidth line (fuse small projections) | Open |
| Wider verify and multi-row decode | In progress through the round driver; see [Round driver](/docs/developers/round-driver) |
| Int8-activation prefill on the tensor units | Lossy, so only a user option; not adopted |
| Batched sequence mixers in the round driver | Open, small expected gain |
| ANE prefill beside GPU decode | Lossy option, very high effort; ranked last |
| Sampling on the CPU | Rejected: stays on the GPU |
| Drafter on the ANE overlapped with GPU verify | Dropped: drafting depends on the previous round's accepted tokens, and the ANE takes GPU bandwidth |
| `mx.compile` on decode layers, wired-memory tuning, High Power mode, a second command queue for prefill | Dropped: no measured effect or worse |

### Knobs

| Setting | Default | Effect |
|---|---|---|

### How to verify

Run a probe under the GPU queue so the shared units are not disturbed, for example:

```bash
scripts/dev/gpuq submit --label hw-decode-proxy --mem-gb 30 -- \
  python scripts/research/hw/decode_proxy_step.py
```

Work out a roofline before starting an optimization: the theoretical ceiling and its dependencies. Compare in-runtime rather than from an isolated microbenchmark, because eval-per-call parts overstate small kernels.

## Related

- [Release readiness](/docs/developers/release-readiness)
- [Verification](/docs/developers/verification)
- [Benchmarks](/docs/guides/benchmarks)


---

<!-- developers/prior-art-formats -->
---
title: Retrieval and prior-art formats
description: Which published embedding, reranker and classifier checkpoint formats Yunshu loads, which loader each one uses, and how the loaders are checked against their upstream implementations.
---

For retrieval models, Yunshu loads the formats that are actually published instead of requiring a private conversion. Before writing a loader it checks for an existing MLX port, checkpoint format or runtime and loads that format. This page lists what is covered, what is deliberately not, and how the parity checks work. It is a maintainer reference; for the endpoints see [Embeddings](/docs/api/embeddings) and [Rerank](/docs/api/rerank), and for provenance of derived files see [Upstream tracking](/docs/developers/upstream-tracking).

## What it does

| Family | Loader | Notes |
|---|---|---|
| EmbeddingGemma 2 (bf16 and affine 4-bit and other published quantizations) | `load_published_model` in `python/yunshu_engine/embedding_gemma2_loader.py`: the maintained `mlx_vlm.embedding_loader.load_embedding_model` (strict) when `mlx_vlm.models.embedding_gemma2` is installed; otherwise a derived loader | The derived fallback uses a vendored MIT port of the text tower written from the Hugging Face `embedding_gemma2` architecture, and mlx-vlm's Gemma 4 vision and audio towers. Quantized modules are built from the checkpoint's scales; vision and audio towers may keep floating weights; packed integer tensors are never cast to float. Unquantized checkpoints keep the original float loader. Provenance is in `vendor.json` |
| BERT, RoBERTa, XLM-RoBERTa encoders and sequence classifiers | mlx-vlm's maintained encoder loader with `SequenceClassificationModel` | Published BGE converters with bare backbone names, single-label and multi-label heads, and quantized encoder layers with floating or quantized heads. A missing backbone or head tensor is a load error |
| Qwen3 yes/no rerankers | the official instruction, prefix and suffix recipe on mlx-lm's quantized loader | Matches the converted checkpoint's own `query` and `document` role template |
| Qwen3-VL retrieval | the installed `mlx-embeddings` `model.process` API | No GPL source is copied into Yunshu |

Empty embedding input returns an empty list, and adding a default instruction never mutates the caller's input dictionaries.

## Why

Users bring checkpoints from Hugging Face as published. A loader that silently substitutes a different head or template would return plausible but wrong vectors and scores, so each format either loads exactly as its upstream does or fails with an actionable error.

## Guarantees

- A head or backbone that is missing from a checkpoint is a load error, never a silent replacement.
- `JinaForRanking` (Jina v3) is a separate architecture and remains unsupported: its trained ranking head must not be replaced by Qwen yes/no logits.
- The Qwen3 reranker template matters: the published 0.6B 4-bit chat template expects `query` and `document` roles. A service that supplies `user` makes that template drop the query and document, so distinct pairs produce identical token ids and logits. Yunshu uses the official recipe that matches the converted role template.

## Limits

- The 2026-10-08 Hugging Face inventory lists a single `model.safetensors` for Google EmbeddingGemma 2 and for each mlx-community conversion checked, so a multi-shard loading defect was not reachable with those published snapshots. Repacked or private multi-shard checkpoints could reach it. This is a dated inventory, not a claim about future uploads.
- The diffusion comparison against `mflux` is an audit, not a serving path. The reviewed `mflux` mapping drops the scales and biases of an affine 4-bit diffusers checkpoint without `mflux` safetensors metadata, so the probe decodes weights first and labels the result a floating reference with a format bridge. It is not native quantized loading and changes no serving default.

## How to verify

- CPU unit tests: `tests/unit/test_prior_art_check.py`, `tests/unit/test_priorfix_capabilities.py`, `tests/unit/test_priorfix_probes.py` and `tests/unit/test_priorfix_mflux_reference.py`.
- `scripts/dev/yv ab --base <sha> --cand <sha> --suite embedding --label <name>` loads bf16, 4-bit and a real bf16 checkpoint repacked into two shards, compares Yunshu's wrapper with direct upstream model invocation on the Mac, and applies a 0.99985 fp32 cosine floor to the bf16 vectors. Quantization accuracy is reported separately.
- `--suite priorart` runs bounded retrieval, Omni prepared-input and fixed-seed diffusion comparisons; `--env PRIORART_KINDS=capabilities` runs the Gemma formats, retrieval, classifier, diffusion audit and Omni preparation as separate child processes in one GPU admission, keeping one evidence file and return code per arm and rejecting missing, stale or wrong-device evidence. `PRIORART_KINDS=diffusion-timing` runs three interleaved pairs at 256 px, 2 steps and seed 7 and reports medians with the exact workload.

These are modality-specific audits and are excluded from the generic LLM suite. Timing from the diffusion comparison does not decide performance or defaults. All of these use the GPU queue; see [Verification](/docs/developers/verification).


---

<!-- developers/release-gate -->
---
title: Release gate
description: The checks a Yunshu version must pass before it ships, how the gate tests an installed build, and the readiness checklist for a new user's first hour.
---

A version ships only when the release gate passes on the exact commit being released. The gate tests Yunshu the way a user gets it: built into a wheel, installed with `uv tool install` into a clean environment, and driven over HTTP with the official OpenAI and Anthropic SDKs. Every check prints `PASS`, `FAIL` or `SKIP`, and the run ends with a table and a non-zero exit if anything failed. A documented capability that fails is a `FAIL`; a model family whose checkpoint path is not configured is reported as `SKIP` with the reason.

The gate keeps everything it installs and writes under its own root directory: its own `HOME`, tool directories and caches. It never touches your `~/.yunshu` or `~/.local`.

## Stages

| Stage | What must hold |
|---|---|
| `install` | `uv build` succeeds. `yunshu[vision]` and `yunshu[all]` install from the wheel. `--version` matches `pyproject.toml`. `yunshu doctor` reports no failed check. `model list` finds the models directory. `pull` of a model already on disk refuses to download. `config set models_dir` round-trips. `service install --dry-run` prints the launchd agent and writes nothing |
| `serve-27b` | The flagship Qwen3.8-27B model runs on the installed binary. The capability matrix passes completely. The OpenAI SDK passes chat, streaming, tools (auto, forced, streamed deltas), JSON schema, stop, logprobs, reasoning split and image input; the Anthropic SDK passes messages, streaming, tool use and thinking. Dropping a stream mid-generation still leaves the next request answered correctly. A 32K-token prompt recalls its needle. Eight concurrent requests all answer. The server decodes as fast as the engine does in-process (same greedy prompts through both, identical text required, with a throughput ratio threshold). The server log has no traceback |
| `families` | Each supported family boots, answers its smoke checks and exits without a traceback: the Qwen3.5 family on the VLM runner, a text-only `mlx-lm` model (fast path, tools and schema), Gemma-4 (tools and image), OCR, ASR, TTS, Qwen3-Omni and image generation |
| `soak` | The 27B model completes a paired MMLU-Pro run at eight requests in flight with zero errors and accuracy not meaningfully below the recorded baseline, then a realistic mixed soak with zero errors and a high correct rate. After each part the process footprint must return to within a few GiB of where it started |
| `agent-sessions` | What long agent traffic does, each check on its own cold server. A Claude Code-style `POST /v1/messages` loop of about 50K tokens must produce a valid tool call every turn, recall every needle and reuse nearly all of the previous prompt from the cache each turn. Long documents, a short question, a tool call and a JSON-schema answer run alone and concurrently, and each concurrent output must equal its solo output. After an idle period (memory release) and after a restart on the same SSD cache tier, the same request returns the same text with most of the prompt cached. The server's greedy text equals stock `mlx-lm` or `mlx-vlm` on the same checkpoint |
| `long` | The `long` suite of [Verification](/docs/developers/verification) at 32K, 64K and 128K against the previous release as the reference: token identity (including drafting on and off over long replies), prefix-cache equality, speed, memory, needle retrieval against stock and concurrent long requests. The verdict must exist and every planned stage must pass; a missing cell, a stage that did not run, an infrastructure error or a regression beyond the thresholds fails the gate |
| `service` | Off by default, because it loads a real launchd agent. With it enabled, `service install` must serve the model and `service uninstall` must free the port |

Model-backed stages run through `scripts/dev/yv gate`, which runs the stages as separate jobs and remembers which passed on the commit, so a rerun after a late failure skips what already passed (`--fresh` reruns everything; `--stages` selects some). Do not invoke the underlying script directly: `yv` is what preserves successful stage evidence.

```bash
scripts/dev/yv gate                                   # all stages
scripts/dev/yv gate --stages install,serve-27b        # selected stages
```

The checks themselves live in `scripts/release/gate_checks.py`. Model paths come from the environment (`scripts/release/local.env.example` lists the variable names). When a baseline legitimately moves, for example because a new default kernel changes an accuracy score, the baseline constant in the script is updated together with the measurement that justifies it.

## Cutting a release

The version lives in `pyproject.toml` and each release needs a dated `CHANGELOG.md` entry. All verification refers to that final commit; a change afterwards needs another check.

1. Run CI-equivalent checks locally with `scripts/dev/ci-local <sha>`: lint, format, mypy, frontend checks, unit tests, package build, `twine` validation and a wheel-install smoke test.
2. Run the full gate and the other release checks on the same commit. The model-backed agent benchmark is collected separately and is informational, not a release blocker.
3. Tag the commit (`v<version>`) and push the tag. The release workflow checks that the tag matches `pyproject.toml` and the changelog, runs lint, type checks, the console build and unit tests on an Apple Silicon runner, builds the sdist and wheel, runs `twine check`, installs the wheel into a clean environment, waits for a maintainer's approval on the `pypi` environment, publishes to PyPI with trusted publishing (no token is stored) and opens a draft GitHub release for review.

If something fails before the publish step, nothing was published: delete the tag, fix the problem and tag again. Versions go up in small steps; a patch carries fixes and improvements and a minor marks a real capability jump. The full procedure is in `RELEASING.md` in the repository.

## Release readiness checklist

The readiness checklist covers what a new user meets before the first token. It is a capability inventory, not a test result: it states what exists, and the gate above is what proves a given commit.

| Area | What a user can expect | Status |
|---|---|---|
| Install | `uv tool install "yunshu[vision]"` from PyPI, from a wheel or from git; source install with `uv sync` | <Support status="supported">supported</Support> |
| Install | Homebrew through the shared `YuhuanStudio/homebrew-tap` formula | <Support status="partial">added after each PyPI release</Support> |
| Install | macOS app, menu-bar app, DMG | <Support status="unsupported">not planned: CLI plus a launchd service</Support> |
| First run | `yunshu doctor` checks platform, Rosetta, macOS, Python, MLX and Metal, `mlx-lm` and `mlx-vlm`, memory, settings, the models directory and disk, whether the model fits, the port and the service, and gives a fix for each problem | <Support status="supported">supported</Support> |
| First run | `yunshu pull org/name` downloads to `~/.yunshu/models`, resumes interrupted downloads and refuses to re-download a model already on disk (models directory or Hugging Face cache) | <Support status="supported">supported</Support> |
| First run | A curated model picker by available RAM | <Support status="planned">planned: users currently need to know a repository id</Support> |
| Serving | `yunshu serve -m <model>` or `--models-dir`; safe default bind to `127.0.0.1` with a warning on a network bind without a token | <Support status="supported">supported</Support> |
| Serving | A model that fails to load after the pre-flight leaves the server up with `GET /health/ready` returning 503 and a fatal log line | <Support status="supported">by design, so a background service reports its state</Support> |
| Serving | Background service: `yunshu service install`, `start`, `stop`, `restart`, `status`, `logs`, `rotate-logs` (launchd, restart on crash, size and age log rotation) | <Support status="supported">supported</Support> |
| Operations | `GET /health`, `GET /health/ready`, `GET /health/live`, `GET /version`, `GET /metrics`, and `yunshu status` | <Support status="supported">supported</Support> |
| Settings | One entry point: the registry, `~/.yunshu/config.toml`, `--set`, and `yunshu config` with a generated reference | <Support status="supported">supported</Support> |
| Clients | OpenAI SDKs, curl and the Anthropic SDK; `yunshu launch` for Claude Code, Codex, opencode and Pi | <Support status="supported">supported</Support> |
| Clients | Cline, Continue, Open WebUI | <Support status="partial">configuration guidance; not tested every release</Support> |
| Upgrade | `uv tool upgrade yunshu`; a running service needs `yunshu service restart` | <Support status="supported">supported</Support> |
| Telemetry | none is collected. Outbound connections happen on user action only: model downloads, MCP servers you configure, the configured web search provider, and `web_fetch` for URLs a request names | <Support status="supported">by design</Support> |
| CI | lint and build on every push; the macOS unit suite on release or manual trigger | <Support status="partial">the full unit suite is not run on every push</Support> |

See [Agents](/docs/guides/agents), [Web search](/docs/guides/web-search) and the [service guide](/docs/getting-started/service) for the user-facing side of these items.

## Related

- [Verification](/docs/developers/verification)
- [Contributing](/docs/developers/contributing)
- [Upstream tracking](/docs/developers/upstream-tracking)
- [Install](/docs/getting-started/install)


---

<!-- developers/release-readiness -->
---
title: Release readiness
description: The outward-facing checklist for a release, what is evidence and what is only a capability inventory, and the maintainer procedure summarized from RELEASING.md.
---

This page is for maintainers. It covers what a new user meets before the first token (install, first run, serving, clients, upgrade, uninstall), what evidence each item has, and the order of the release procedure. The checklist table itself, with its support status per item, is on [Release gate](/docs/developers/release-gate); this page does not repeat it.

## What it does

The readiness checklist is a capability inventory, not a test result. It states what exists. What proves a given commit is the release gate (`scripts/dev/yv gate`), and what proves the packaging is `scripts/dev/ci-local`. Engine speed and accuracy are tracked separately in [Benchmarks](/docs/guides/benchmarks) and [Accuracy alignment](/docs/developers/accuracy).

| Area | Where the evidence comes from |
|---|---|
| Install from a wheel, `doctor`, `pull`, `model list`, `config set models_dir`, `service install --dry-run` | Gate stage `install` |
| Serving, SDK clients, flagship model | Gate stage `serve-27b` |
| Supported families | Gate stage `families` |
| Memory return and error-free soak | Gate stage `soak` |
| Long agent traffic, idle release, restart on the SSD cache tier | Gate stage `agent-sessions` |
| Long-context identity, cache equality, speed, memory | Gate stage `long` |
| Real launchd service | Gate stage `service` (off by default) |
| Package build, lint, types, unit tests, clean install | `scripts/dev/ci-local`, then the release workflow |
| Claude Code, Codex, opencode behavior | `scripts/dev/agentcompat`, see [Agent compatibility](/docs/developers/agent-compat) |
| M3 portability | `scripts/dev/m3sweep` |

## Why (design decision)

- Versions go up in small steps: a patch carries fixes and improvements, a minor marks a real capability jump.
- The repository is public and the install path is a CLI plus a launchd service. A macOS app is not planned. Homebrew goes through the shared tap `YuhuanStudio/homebrew-tap`.
- Models live in `~/.yunshu/models` by default; Hugging Face cache models are usable in place, and the location changes with `yunshu config set models_dir`.
- A model that fails to load after the pre-flight keeps the server up and not ready (`GET /health/ready` returns 503 with a fatal log line), which is right for a background service.
- No telemetry is collected. Outbound connections happen only on user action.
- Nothing is published except by the steps below, run by a maintainer.

## Guarantees

- All verification refers to the final release commit; a change afterwards needs another check.
- A version that reached PyPI cannot be re-uploaded; fix forward with the next patch version. If something fails before the publish step, nothing was published: delete the tag, fix and tag again.
- Pre-1.0 does not make silent breakage acceptable. A user-facing removal or changed API or default needs an upgrade note naming its replacement and effect; stable settings and CLI options should get a warning and at least one published release of overlap unless security or correctness requires immediate removal. Python internals are not a stable embedding API.
- Release notes follow a fixed order: a paragraph on what users gain, `Highlights`, `Upgrade notes / breaking changes`, `Performance` (machine, checkpoint, workload, before and after, source link), then `Added`, `Changed`, `Fixed`, `Security`, and a compare footer. Every measured number links to a dated benchmark.

## Procedure

<Steps>
<Step>

### One-time setup

On pypi.org add a trusted publisher for project `yunshu` (owner `YuhuanStudio`, repository `Yunshu`, workflow `release.yml`, environment `pypi`); no API token is stored. In the repository settings create the GitHub environment `pypi` with a required reviewer, so every publish waits for approval.

</Step>
<Step>

### Prepare the commit

Between releases `main` carries the next version as a PEP 440 development version (for example `0.1.6.dev0`). Drop the `.devN` suffix in `pyproject.toml`, add the dated `CHANGELOG.md` entry and commit. After the tag, set `main` to the next `.dev0`.

</Step>
<Step>

### Verify the exact 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` keeps SHA-keyed evidence under `/Volumes/P5Plus/yunshu-build/release-check/`, pins a clean tree and prints the agentbench collect command. CI, the gate, the M3 sweep and agent compatibility block the release; agentbench runs at priority -3 and is informational, but its result must still be collected and recorded. Never run `gate.sh` directly: `yv gate` submits through the GPU queue and preserves successful stage evidence, so a rerun skips what already passed. Read every completed job's exit status and final evidence record.

</Step>
<Step>

### Tag and push

```bash
git tag -a v<version> -m "Yunshu <version>"
git push origin main v<version>
```

The release workflow checks that the tag matches `pyproject.toml` and the changelog, runs ruff, mypy, the console checks and the unit tests on an Apple Silicon runner, builds the sdist and wheel, runs `twine check`, installs the wheel into a clean tool environment, waits for approval on the `pypi` environment, publishes to PyPI and opens a draft GitHub release with the changelog section as its notes. Review and publish the draft.

</Step>
<Step>

### After the release

Check a clean install (`uv tool install "yunshu[vision]"`, then `yunshu doctor`). Update the Homebrew formula in the shared tap: the `sha256` of the sdist PyPI now serves, then copy `packaging/homebrew/yunshu.rb` to `Formula/yunshu.rb`.

Then start the next cycle from current upstream: `uv lock --upgrade` followed by the tests and lint; re-check on the 27B that speculative output equals plain output, that the paired accuracy set agrees within one question, and that decode and TTFT did not regress (record the before and after in `docs/reports/PERF_TREND.md`); run `just vendor-check` and review every vendored kernel, ported file or monkeypatch whose upstream changed (see [Upstream tracking](/docs/developers/upstream-tracking)); read upstream release notes for fixes and ideas. Land the sync as its own merge so later regressions can be bisected to it.

</Step>
</Steps>

## Knobs

| Option | Default | Effect |
|---|---|---|
| `yv gate --stages` | all stages | Run selected gate stages; `--fresh` reruns everything |
| `yv gate --priority` | per command | GPU queue priority of the gate jobs |
| `release_check --label-prefix` | `releng015-release` | Labels the submitted jobs |
| `release_check --dry-run` | off | Preview without CI or GPU jobs |

## Limits

- CI on push runs lint and build on Linux; the macOS unit tests run on release or on a manual run, so the checklist does not claim a fresh CI run.
- A curated model picker by available RAM does not exist yet; users need to know a repository id.
- Cline, Continue and Open WebUI are configuration guidance, not tested every release.
- A CPU-only documentation candidate can use `yv ab --suite preflight`; it does not certify engine output or performance.

## How to verify

Preview the notes that a release would publish and check the public docs:

```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` adds pinned pip and uv commands, Homebrew instructions with the tap-delay caveat and the previous-version comparison. Before tagging, review `git log <previous-tag>..main`, reconcile numbers with `docs/reports/PERF_TREND.md`, state machine, checkpoint, modes and repetition count, include workload regressions, and resolve every TODO.

## Related

- [Release gate](/docs/developers/release-gate)
- [Verification](/docs/developers/verification)
- [Agent compatibility](/docs/developers/agent-compat)
- [Install](/docs/getting-started/install)


---

<!-- developers/roadmap -->
---
title: Roadmap and proposals
description: What Yunshu prioritizes, what is out of scope, and the lightweight RFC process for substantial changes.
---

Yunshu prioritizes fast local LLM and VLM inference on Apple Silicon: decode speed, cold and cached first-token latency, prefix reuse, and complete client behavior. Qwen3.8-27B is the first tuned model. This page records direction, not dates or claims that work has shipped. Released behavior belongs in the changelog; measured results belong in [Benchmarks](/docs/guides/benchmarks).

## Priorities

| Priority | Work | Completion evidence |
|---|---|---|
| Now | Close measured long-context gaps in 27B and Flash-Next | Cold, warm and follow-up time to first token and decode compared separately at 32K, 64K and 128K; see the current gaps in [Benchmarks](/docs/guides/benchmarks) |
| Next | Apple Silicon portability evidence | Recorded M1 to M5 and macOS checks distinguish passed, failed and untested combinations |
| Next | Model and client capability evidence | Checkpoint- and client-version-specific results; unsupported features give actionable errors |
| Next | Reproducible performance publication | Same-checkpoint cold, warm and second-turn runs with correctness checks and raw receipt links |
| Later | Broader model tuning | Measured end-to-end gains without reducing output correctness |

Audio, speech, image and video generation, and embeddings remain supported capabilities. Shared-path regressions and explicitly prioritized work take precedence. Distributed serving and multi-tenant infrastructure are outside scope.

## Lightweight RFC process

Routine fixes use the normal contribution and review process (see [Contributing](/docs/developers/contributing)). For substantial changes to public APIs, settings, cache formats, supported hardware or architecture, record a proposal before implementation with:

- the user problem and the concrete proposed behavior;
- scope, alternatives and the reasons for the choice;
- compatibility, migration, privacy and failure behavior;
- correctness checks, the measurement that decides success, and a rollback plan;
- owner, status (proposed, accepted, implemented or superseded) and the decision rationale.

Use an existing discussion or a reviewable Markdown proposal; no new issue is required for a small fix. Maintainers record the decision where the proposal is reviewed. Accepted is not shipped: close the proposal with links to the implementation and its validation. Private vulnerability details follow `SECURITY.md` instead of a public proposal.

## Decisions and maintenance

Contributors own the quality and explanation of their changes. Maintainers review scope, compatibility and evidence; repository administrators control merges, release publication and access. Reviewers should identify unresolved objections and record the chosen tradeoff. Governance changes need an explicit maintainer review; this page does not grant repository permissions or create new roles.


---

<!-- developers/round-driver -->
---
title: Round driver
description: "The packed-row engine that serves every mlx-vlm model: one forward per step over every decoding row, row-invariant arithmetic, and cost-aware MTP or DFlash drafting for several rows at once."
---

The round driver (`python/yunshu_engine/round_driver/`) is the serving path for every model loaded through `mlx-vlm`. Each request is a row, and the driver serves rows through one of three model layers: the packed Qwen3.5 layer (dense and MoE Qwen3.5-family models), the packed Flash-Next layer (Qwen4), and the generic layer (the model's own upstream forward per row, no drafter by default) for every other family and for Apple Paravirtual Metal. Speculative decoding runs on the packed layers: concurrent requests draft too (MTP chains, or DFlash2 drafts sharing a fair 32-node verify budget). With `YUNSHU_VLM_DRAFT=off` the driver still serves every request, without drafting, and speculation on equals speculation off, token for token. This page is a maintainer reference; for the other serving paths see [Architecture](/docs/developers/architecture).

## What it does

Every request is a **row**. A row prefills on its own single-row caches (a `KVCache` per attention layer, an `ArraysCache` per GatedDeltaNet layer, a `KVCache` for its MTP head). When its prompt is done it joins the decode batch (`round_driver/batch.py`, `DecodeBatch`), where all decoding rows share slot buffers:

- attention K/V in slot buffers per attention layer, the row owning one slot, with capacity that grows in 512-key steps;
- GDN state and conv window as batch arrays per layer (a join concatenates, a finish takes);
- the MTP head's KV in the same kind of slot buffers.

`RoundDriver` (`driver.py`) advances rows in **steps**, each one forward of one kind:

- **Decode step**: every decoding row's window (the pending token plus `d >= 0` drafts), right-padded to the longest window. Norms, projections and the MLP run over the packed rows; attention writes all rows' keys with one scatter and reads them with one ragged-attention launch (`kernels/ragged_attention.py`); the GDN conv and recurrence are one batched launch (`kernels/gdn_rows.py`).
- **Prefill step**: waiting prompts' fixed-size **atoms** (`ROUND_PREFILL_CHUNK` in `vlm_engine.py`, 512 tokens; 2048 on Flash-Next), on a grid from the prompt start, cut at the prompt's checkpoints and end. One atom while rows decode; more consecutive full atoms together when no row decodes.

While rows decode and prompts wait, prefill and decode steps alternate one to one. Steps stay single-kind: packing decode rows into the prefill forward measured no better than alternating at the same chunk size on Qwen3.8-27B (2026-09-29).

One row from admission to finish; decode steps alternate with prefill steps of other rows.

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

### Routing

`VLMEngine._build_batch_runner` picks the layer when a model loads:

- **Apple Paravirtual Metal**: the generic layer, with no APC and no speculation.
- **Qwen3.5-family or Qwen4 models** (`_SPEC_MODEL_TYPES`) whose language model the packed layer supports (`_round_driver_wanted`): the packed Qwen3.5 layer, or the Flash-Next layer for Qwen4. A quantized Qwen3.5 checkpoint whose lane arithmetic self-test fails serves on the generic layer.
- **Every other model**: the generic layer, one upstream call per row, plain decode. A generic row drafts only when it asks for it (`spec_decode: true`) or `YUNSHU_NGRAM_DEFAULT=1` turns n-gram on. A draft LM (`YUNSHU_DRAFT_MODEL`) or the Gemma-4 assistant (`YUNSHU_GEMMA4_ASSISTANT`) is used when set; otherwise n-gram.

The draft is chosen separately (`spec_select.choose`). `YUNSHU_VLM_DRAFT=off` gives no draft; a DFlash drafter directory or `mtp` selects that path; unset uses a matching DFlash2 drafter when one is found, else the checkpoint MTP head. `YUNSHU_MTP=0` disables the MTP head.

Every request, text or media, is a row of the same driver. A media prompt carries its own prompt features (`VLMBatchRunner._media_request` on the packed layers, `_generic_request` on the generic layer). A row draws its drafts only when its processors allow it (below).

## Why

Upstream `mlx-vlm`'s `BatchGenerator` runs one `_prompt_batch` at a time, speculative batches that cannot take joins, and MTP drafter state for one batch. Measured on 27B (M5 Max):

- MMLU-Pro 300 b8 (long reasoning, 8 in flight): Yunshu 139 tok/s (drafts only while a request is alone), TensorFold MTP parallel-8 159, Splash 223.
- 8 concurrent 1K prompts: the last TTFT is ~10 s (prefill one request at a time).

These are the numbers of the earlier stock shared-batch path, kept as the motivation for the driver.

The driver is Yunshu's own loop (inspired by TensorFold's lane engine, MIT; see [Upstream tracking](/docs/developers/upstream-tracking)) so that several rows can share a forward, join at any step and still produce the tokens they would produce alone. Earlier prototype runs measured the earlier stock path behind competitors on concurrent long-reasoning load; the current cross-engine comparison of this driver (Yunshu 0.1.7.dev0, 2026-11-04 to 2026-11-08) is on [Benchmarks](/docs/guides/benchmarks), and the figures above are from the earlier stock path.

## Guarantees

A row's arithmetic does not depend on which rows share the step, how many drafts the others verify, or whether it drafts at all.

- **Projections** (every target linear and the LM head) use a lane matmul (`kernels/tensorfold/lane_qmm.py`, MIT): per-row bits follow the weight shape, not the row count, for 1 to 128 rows; wider calls are cut into 128-row pieces (`kernels/lane_linear.py`).
- **Decode and verify attention** (`T <= 8` tokens) uses the ragged token-tile kernel: per-token bits do not depend on `T` or on other rows.
- **GDN** runs as one launch over the rows' states; a row that keeps part of its window continues from the saved intermediate state (`DecodeBatch.commit`).
- **Prefill** follows an atom plan that is a function of the prompt alone, so a repeated prompt, or a row restored from a checkpoint on the grid, prefills with the same atoms as a cold run: APC hit equals miss token for token.
- **Greedy rows**: speculation on equals speculation off, and a row alone equals the same row in any batch or join order. **Sampled rows** draw with `keyed_sampling.KeyedSampler` (seed and generation index), so the token at index `g` is a pure function of the row's logits, seed and `g`.
- **Generic layer**: every decoding row makes one upstream call per round on its own cache, so a row's output does not depend on the other rows: solo equals concurrent, greedy and seeded.

On the packed layers, drafting uses the checkpoint's MTP head, or the DFlash2 drafter when one is selected, for every draftable row. The head's KV is kept current every step, so any row can start drafting at any step. Draft depth per row comes from `round_driver/allocate.py` (TensorFold allocation rule, MIT): per-depth acceptance is tracked as an EMA, rows receive drafts greedily by marginal expected tokens, and the step keeps the allocation that maximizes expected committed tokens per millisecond using forward cost measured online. There are no row-count thresholds.

Every row uses the model's `APCManager` prefix cache through `APCCoordinator` (checkpoint strategy) on every family without a sliding-window cache, and on Gemma 4 (its exact-window snapshot). Entries are salted by the model and processor identity (`VLMBatchRunner._driver_extra_hash`), so a prefix cached under one identity is cold under another.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_KV_PRECISION` | `bf16` | `int8` applies to the packed Qwen3.5 layer's rows; the Flash-Next and generic layers keep bf16 |
| `YUNSHU_MTP` | `true` | Draft with the checkpoint MTP head; `false` disables that draft |
| `YUNSHU_VLM_DRAFT` | unset | `off` disables drafting; a drafter directory or `mtp` selects the draft (see Routing) |

## Limits

- XTC sampling rows never draft. Rows with logits processors outside the driver's windowable set (pure token masks and logit bias, repetition penalty, at most one frequency or presence penalty) decode one token a round. Logprobs rows and rows under invariant tool-call or response-format guides draft; other constraints decode one token a round and never draft.
- A prompt feature that the packed layer does not carry raises an error at admission (`VLMBatchRunner._media_request`).
- Open work: a per-row cost of about 25 ms per round (draft, verify, draw) keeps four-row seeded decoding level with the earlier shared batch.

## How to verify

- `tests/unit/test_round_driver.py` (greedy invariance on a random small Qwen3.5), `tests/unit/test_round_driver_apc.py` (hit equals miss), `tests/unit/test_round_driver_routing.py` (layer and draft routing), and `tests/unit/test_round_driver_generic.py` (the generic layer).
- `scripts/research/sweep_round_driver.py` on a real checkpoint (alone, batch, staggered and autoregressive parity) and `scripts/research/probe_span_bits.py` (identical hidden states and caches across prefill span sizes). These need the GPU queue; see [Verification](/docs/developers/verification).


---

<!-- developers/serve-and-develop -->
---
title: Serve and develop on one machine
description: How the GPU queue lets a production Yunshu server and development GPU jobs share one Mac, with idle gating, preemption, memory and CPU admission, and measurement-integrity rules.
---

The GPU queue (`scripts/dev/gpuq`) supports running a production Yunshu server for real users while development GPU jobs (benchmarks, evals) use the same machine. The queue is aware of the production server: development jobs run only while it is idle and are frozen the instant user traffic arrives. This page is for maintainers; it describes the queue and the engine-side hooks it relies on.

## What it does

Jobs are separate processes submitted to a queue daemon. Each job moves through states the daemon reports in `gpuq status`:

Caption: the life of a gated job, from waiting for an idle server to finishing, with the pause path taken when user traffic arrives.

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

| Piece | Behavior |
|---|---|
| Poller | The daemon GETs `/v1/yunshu/status` of each configured server every `poll_s` and reads only `requests.active` and `requests.queued`. No prompts, no request items |
| Start gate | A job starts only after every server has been idle (no active, no queued) for `idle_start_s` |
| Preemption | When a request appears, `SIGSTOP` goes to the job's own process group (the queue starts each job in its own session; nothing else is ever signalled, never the server) |
| Resume | `SIGCONT` after the servers have been idle for `idle_resume_s` |
| Pause record | Each interval is stored in the job JSON (`pauses: [[t0, t1], ...]`, wall clock) and in the file named by `$GPUQ_PAUSE_FILE` |
| Timeouts | `--timeout` and `--stall` count active time only; paused time is excluded |
| Memory admission | A job declares `--mem-gb` (0 with `--serving-ok`). It starts only if free memory minus `mem_gb` leaves `reserve_gb` |
| Bypass | `--serving-ok` skips the idle gate and serving pauses (CPU-only jobs). Priority preemption still applies |
| Priority preemption | Pending priority 0 or higher work can `SIGSTOP` a running priority -1 or lower job when memory admits both resident jobs; no job is killed to reclaim memory |
| Status | `gpuq status` shows `wait-idle`, `wait-mem`, `wait-cpu`, `paused` and a `pauses=N` count; an `idle:` line explains why pending jobs have no active runner |

## Why (design decision)

- A production server must never be slowed by a benchmark, and a benchmark must never silently measure user traffic. The queue therefore pauses the job, not the server, and records the pause.
- The poll reads counters only, so no user content ever reaches the queue.
- It fails closed: an unreachable server (connection refused) counts as idle, but a timeout, a 5xx or an unparsable answer counts as busy.

## Guarantees

- Without configured server URLs or an explicit reserve there is no serving gate, serial memory admission and no serving pause.
- Priority preemption still checks memory: measured available memory minus the new job's `mem_gb` must leave `reserve_gb`. Unknown memory prevents preemption, and a blocked high-priority job is shown as `wait-mem`.
- An active label (pending, running or paused) is exclusive; the same label cannot be submitted twice concurrently. Submission never deletes earlier logs, pause records, return codes or output files.

### Measurement integrity

A benchmark number that includes paused time measures the user's traffic, not the engine, so harnesses must never report such a sample.

- `scripts/dev/gpuq_pause.py` (standard library only) provides `was_paused(t0, t1)`, `timed(fn)` and `pause_intervals()`. `timed` discards and re-runs a sample that overlapped a pause and raises `PausedSampleError` after repeated overlaps. It fails closed: an unreadable `$GPUQ_PAUSE_FILE` means paused; outside gpuq the variable is unset and nothing is ever paused.
- It is wired into `scripts/research/agentic/replay_traffic.py`, `scripts/research/bench_engine_matrix.py` and the release gate's `cancel_then_next` wall-time check. The offline live-A/B replay (`scripts/servedev/replay.py`, `ab()`) also drops any pair whose window overlaps a pause from both arms, reports `paused_pairs_dropped`, and fails closed when no clean pair remains. New benchmark scripts must wrap each timed sample in `timed(...)`. Accuracy evals need nothing: a pause only makes them slower.
- Preemption lands within one poll interval of the first request, so a sample can briefly share the GPU before the stop. Keep `poll_s` small. For the handshake that closes this window, see below.

### Foreign-CPU and memory contamination

Every started job records `cpu_samples` (`load_1m`, `load_5m`, `foreign_cpu_pct` and the largest foreign processes) at start, periodically and at the end. Foreign CPU includes all processes except the job's own tree and background processes with `nice` of 10 or more. A job is latched `contended` when the threshold is reached or sampling fails.

- Jobs submitted with `--quiet` wait for a quiet CPU before starting (`--quiet-window`, `--quiet-max-wait`; environment defaults `GPUQ_CPU_THRESHOLD`, `GPUQ_QUIET_WINDOW_S`, `GPUQ_QUIET_MAX_WAIT_S`, `GPUQ_CPU_SAMPLE_S`). The hold is bounded by the smaller of the job's max wait and `GPUQ_QUIET_HOLD_MAX_S` (daemon environment, default 300 seconds); on expiry the job starts flagged `quiet_timeout` and `contended`. Serving and memory admission still apply, and `--serving-ok` does not bypass the CPU gate.
- A memory contention rule rejects a job when its process tree has too much compressed or swapped memory (`GPUQ_SWAP_MB`), host swap-ins during the job are too large (`GPUQ_HOST_SWAP_MB`), or host free plus inactive memory falls below a floor (`GPUQ_MEMORY_FLOOR_MB`). Unreadable evidence fails closed. The job JSON records `host_swap_mb`, `job_swap_mb`, `available_min_mb`, `memory_processes` and `memory_policy_version`.
- `gpuq wait` returns 3 for an otherwise successful contended perf or quiet job. `scripts/dev/gpuq_contention.py:was_contended()` lets harnesses read the flag; the release gate retries a contended server-path comparison once after a bounded quiet wait, and two contended attempts are reported as contended (gate exit 3) while text or speculative-decoding mismatches stay failures.
- CPU-only test suites and builds run under `nice -n 15` so they are excluded from foreign-CPU monitoring. Do not add `taskpolicy -b` to unit tests: efficiency-core scheduling can break timing-sensitive checks.

## Knobs

Serving gate configuration lives either in daemon environment variables or in `$GPUQ_DIR/serving.json`, which is re-read every loop so it can be edited live:

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

| Setting | Default | Effect |
|---|---|---|
| `GPUQ_SERVING_URLS` (`urls`) | none | Comma-separated servers to poll; none means no serving gate |
| `GPUQ_IDLE_START_S` (`idle_start_s`) | 120 | Idle time before a job may start |
| `GPUQ_IDLE_RESUME_S` (`idle_resume_s`) | 30 | Idle time before a paused job resumes |
| `GPUQ_SERVING_POLL_S` (`poll_s`) | 1 | Poll interval in seconds |
| `GPUQ_RESERVE_GB` (`reserve_gb`) | 16 | Memory kept free after admitting a job |
| `GPUQ_SERVING_KEY` (`api_key`) | none | Bearer token if the server needs one |
| `GPUQ_SHORT_MIN`, `GPUQ_SHORT_WAIT_S`, `GPUQ_SHORT_SHARE` | 10 min, 5 min, 0.15 | Short-job lane limits |
| `GPUQ_FILLER_WAIT_S`, `GPUQ_FILLER_MAX_MIN` | 30 s, 30 min | Filler-job limits for a CPU-quiet-blocked head |
| `YUNSHU_SERVE_LOG` | off | Numbers-only event log (timings, token counts, cache tier, speculative acceptance, concurrency, arm, build); never prompts, outputs or token ids. `YUNSHU_SERVE_LOG_DIR`, `YUNSHU_SERVE_LOG_MAX_MB` and `YUNSHU_SERVE_LOG_KEEP` control location and rotation |
| `YUNSHU_RESEARCH_ACTIVITY_FILE` | unset | Local pause handshake file; also configure it as `activity_files` in `serving.json` |
| `YUNSHU_RESEARCH_PAUSE_TIMEOUT_S` | 2.0 | Longest pre-admission wait for gpuq's acknowledgement; a timeout returns 503 |
| `YUNSHU_ARM` | unset | Labels a manually chosen configuration in the log without changing behavior |

The server reports cumulative GPU-busy seconds in `/v1/yunshu/status` and `yunshu_gpu_busy_seconds_total` in `/metrics`. These are busy-time counters, not hardware utilization samples.

### Co-serving handshake

With `YUNSHU_RESEARCH_ACTIVITY_FILE` set, the server writes a numbers-only activity file and, before inference, waits up to `YUNSHU_RESEARCH_PAUSE_TIMEOUT_S` for gpuq's fresh acknowledgement that every research process is observed stopped. This closes the poll-interval window in which the first request could share the GPU with a timing sample.

### Submitting jobs

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

- Queue-level `--out` arguments go before the `--` separator. `--expect-complete` requires every output to be a nonempty file containing a line with the literal `complete`.
- `wait` uses one deadline for the whole id list and prints one line per job. Exit 0: every job is done with rc 0 and verified outputs. Exit 1: a job failed, was cancelled, is missing or has invalid outputs. Exit 2: some jobs are still pending or running at the deadline (takes precedence over failures in finished peers). Exit 3: a successful but contended perf or quiet job.
- `gpuq digest` (`scripts/dev/gpuq_digest.py`) lists jobs finished since the last digest, grouped by label family, and exits 1 on any job that ended `failed`, `lost`, `stalled`, `timeout` or `cancelled`, has an absent or nonzero rc, or has missing or empty outputs. `--peek` leaves the marker (`$GPUQ_DIR/.digest_marker`) untouched, `--since` never moves it, and a label-filtered digest never moves the global marker. The coordinator runs it at every check-in and acts on every flagged line.
- Short-job lane: a job with `--timeout` of at most 10 minutes, or submitted with `--short`, may run ahead of a long job after waiting 5 minutes, within a rolling share of long-job time and never twice in a row. A short job that exceeds its timeout is killed and marked `timeout`.
- Priorities are non-positive for dev work; `--gate` admits a gate ahead of the same priority's backlog. Timing cells require quiet admission; correctness cells do not.

### Reloading the daemon

The daemon keeps its Python code loaded at startup. After a queue change merges, hold new submissions and restart the daemon at a job boundary; running and paused jobs are adopted on restart. Terminate only the process holding `daemon.lock` (by PID, never a process group) and start the replacement with `/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
```

Only the queue owner does this; workers never restart the live daemon during a measurement.

### Optional M3 correctness lane

`gpuq submit --device m5|m3|any` keeps `m5` as the default. One daemon runs a local M5 slot and a remote M3 slot concurrently; `any` is reserved once by whichever slot admits it first. Local serving, quiet admission and priority preemption apply to the M5 slot, and `--quiet` is rejected with `m3` and `any`, because timing belongs on the M5. Configure `M3_HOST`, `M3_KEY` and `M3_REPO` as for `scripts/dev/m3run`; all worktrees, outputs, models, caches and temporary files stay inside that checkout, because the M3 is a personal laptop. The laptop admits declared memory up to a fixed limit that reserves capacity for its user, so declare a realistic peak.

The remote snapshot is HEAD plus tracked edits in a detached worktree. Declared outputs return to their original paths even when the command fails. SSH or transfer failure is a failed job, never a successful receipt; if remote cleanup cannot be confirmed, `m3-quarantine.json` blocks further M3 dispatch until a person inspects it. M3 digest entries are labelled portability evidence (not M5), and mixed-device accuracy or parity arms and M3 performance verdicts are refused by the research analysis helpers. An M3 failure needs M5 reproduction before it rejects an M5 optimization; an M3 pass never approves an M5 hot-path default.

## Limits

The engine-side pieces described above are implemented. The offline scripts in `scripts/servedev/` are `replay.py` (shape-only replay A/B, token-identical or fail), `bandit.py` (a UCB1 bandit over registered lossless knobs with a reversible ledger) and `loop.py` (a gated candidate loop); none of them selects an arm on live traffic. Offline switchback, CUPED and mSPRT helpers and run-history variance profiling exist; no online arm selection is enabled.

Planned and not implemented:

- online lossless A/B on live traffic, recording metrics only (no prompts);
- bandit auto-tuning of lossless knobs against those metrics;
- a gated autonomous improvement loop that proposes, measures and lands changes only through the existing gates.

Always-on 27B serving next to development remains gated on long-context parity across cold, warm and follow-up TTFT, decode, concurrency and memory. The queue mechanisms are implemented; that does not claim the performance gate has passed. Point sampling cannot observe every short-lived process between polls, and no tokens-per-second or TTFT improvement is implied by the queue.

## How to verify

```bash
scripts/dev/gpuq status          # states, pauses, idle explanation
scripts/dev/gpuq digest --peek   # finished jobs, flagged failures
```

Queue behavior is covered by the gpuq tests under `tests/unit`; test queue changes across priorities in an isolated queue before the live daemon restarts. A benchmark script is correct only if it wraps each timed sample in `timed(...)` from `scripts/dev/gpuq_pause.py`. See also [Verification](/docs/developers/verification), [Release readiness](/docs/developers/release-readiness) and [Agentic coding benchmark](/docs/developers/agentic-bench).

## Related

- [Verification](/docs/developers/verification)
- [Hardware validation](/docs/developers/hardware-validation)
- [Telemetry](/docs/guides/telemetry)


---

<!-- developers/upstream-tracking -->
---
title: Upstream tracking
description: How Yunshu records code it took from other projects in vendor.json, the four kinds of dependency on upstream, and how just vendor-check reports what changed.
---

Yunshu builds on MLX, `mlx-lm`, `mlx-vlm` and ideas from several other open-source projects. Every place where it copies, rewrites, reimplements or monkeypatches upstream code is recorded in `vendor.json`, so upstream changes and fixes can be followed and licenses are honored. `THIRD_PARTY_NOTICES.md` carries the matching license texts and ships inside the wheel and sdist.

## The four kinds

Each entry lists the upstream `repo`, the `clone` (a checkout under `reference/`, which is git-ignored), the `commit` (the upstream commit or release tag the local code is based on), the `license` and the local `path`.

| Kind | Meaning | How to sync |
|---|---|---|
| `vendored` | A file copied from upstream. `local_changes` lists the deliberate edits | Re-copy the file and re-apply `local_changes` |
| `derived` | Rewritten from specific upstream files (`upstream_paths`) | Read the upstream diff and port what matters |
| `inspired` | The same algorithm or design, as independent code | Read the upstream diff for ideas or bug fixes |
| `patches` | A monkeypatch of an upstream symbol, described by `module`, `symbol`, `signature` and `source_sha256` | Re-check the replacement against the new upstream source |

Every source file that falls into one of these kinds starts with an `# Upstream (kind): repo (license) paths @ commit` comment (patches use `# Patches upstream ...`). The self-check described below fails when such a header exists without a manifest entry.

The manifest has more sections than the four kinds:

- `watch`: reference clones that are followed for ideas or fixes, with the file globs that matter and the commit reviewed up to.
- `watch_excluded`: every other clone under `reference/`, with the reason it is not followed.
- `packages`: extra package pins on top of what `pyproject.toml` declares.
- `prior_art` and the other `*_prior_art` lists: discovery-only candidates with their own licenses and revisions. These are notes about what exists elsewhere; they are not adopted code, qualified loaders or parity claims.

## Run the check

```bash
just vendor-check                                          # fetch the clones, then report
uv run python scripts/vendor/check_upstream.py --no-fetch  # offline: report from what is already cloned
```

The report has sections for patched symbols, vendored files, derived entries, inspired entries, watched paths, packages and self-checks.

| Exit code | Meaning |
|---|---|
| `0` | clean |
| `1` | something is behind upstream (new commits on a tracked path, or a newer package release) |
| `2` | a patched symbol changed or is missing, or a self-check failed |

### What is watched

- **Patched symbols** are hashed from the installed package (normalized AST source). `UPSTREAM SOURCE CHANGED` means the code that our replacement wraps or copies has changed. Read the new source, update the replacement in `python/yunshu_engine/`, run the tests and the parity checks, then record the new hash:

  ```bash
  uv run python scripts/vendor/check_upstream.py --update-hashes
  ```

- **Watched repos** list the upstream commits that touch the configured globs since the reviewed commit, and files added upstream that match them. Repos pinned to an installed package are compared against that release's tag. After reading the report, move the `commit` forward.
- **Packages** are read from `pyproject.toml` (base dependencies, every extra and every dependency group). The report shows the installed version, the latest on PyPI and the declared specifier, so a new dependency cannot be missed.
- **Self-check**: a file under `python/` whose first lines say `# Upstream`, or "ported from", "adapted from", "studied from" or "Inspired by", must be in `vendor.json`. A clone under `reference/` that is in neither `watch` nor `watch_excluded` also fails, so a new clone cannot go unclassified.

## Sync a derived or inspired entry

1. `just vendor-check` lists the upstream commits on the entry's paths since its last reviewed commit (or `commit`, before the first review).
2. Read them, for example with `git -C reference/<clone> show <sha>`, and port what applies.
3. When you re-copy a file, set `commit` to the new upstream source. When you deliberately keep the local implementation, keep `commit` as its provenance and add `reviewed_commit`, `reviewed_date` and `review_reason`, explaining which upstream changes are already covered, not applicable, or need their own correctness and performance gate. The next check still reports changes after that review, and local differences are always compared with the originally copied source.

Ports that touch a kernel or a decode path follow the usual evidence rule: a same-checkpoint comparison with identical (or tolerance-checked) output and a measured end-to-end effect, see [Verification](/docs/developers/verification).

## Add a new one

1. Add the entry to the right list in `vendor.json`. For a patch, run `--update-hashes` to record the hash.
2. Start the source file with the `# Upstream (kind): repo (license) paths @ commit` comment.
3. Add the upstream's license to `THIRD_PARTY_NOTICES.md`.
4. If the clone is missing, clone the repo into `reference/<name>` (`reference/` is git-ignored).

## Third-party notices

`THIRD_PARTY_NOTICES.md` summarizes each upstream, its license and how Yunshu uses it (vendored kernels, derived modules, inspired code, patches), then reproduces the license text for each. The upstreams include `mlx`, `mlx-lm` and `mlx-vlm` (MIT), oMLX, vLLM, sglang and others under Apache-2.0, and llama.cpp (MIT). When you add a dependency on someone else's code, the notice file is part of the change, not a follow-up.

## Related

- [Architecture](/docs/developers/architecture)
- [Verification](/docs/developers/verification)
- [Contributing](/docs/developers/contributing)


---

<!-- developers/verification -->
---
title: Verification
description: How Yunshu checks that an optimization is lossless and not slower, using the yv verify tool, and how accuracy is compared against stock MLX.
---

Yunshu accepts an optimization only with evidence: the output must match (or stay within a stated tolerance), the path must demonstrably run, and the measured effect must be real. This page describes the tooling that produces that evidence and the rules it applies. It is aimed at contributors who change the decode, prefill, cache or scheduling paths.

## What has to hold

| Requirement | Meaning |
|---|---|
| **Token-identical** | A lossless change leaves greedy output unchanged: the candidate produces the same tokens as the base commit on the same checkpoint. For speculative decoding, output with drafting on must equal output with drafting off |
| **Engaged** | A new path must be proven to run (a counter, a log line or a response field), not assumed. A comparison of two runs that both used the old path proves nothing |
| **Cache-exact** | A request served from the prefix cache must equal the same request served cold, and must report `cached_tokens > 0` |
| **No regression** | Decode speed, time to first token and memory must not get worse beyond measured noise |
| **Fail closed** | No evidence means no pass. An incomplete run, a missing result or a job that ended early is a failure, never a skipped check |

Lossy options (KV int8, weight quantization, anything that changes output quality) are user settings with a lossless default and are not adopted by a benchmark. See [Contributing](/docs/developers/contributing).

## The `yv` tool

`scripts/dev/yv` runs the standard verification of a candidate change and returns one verdict. Use it instead of a one-off measurement script. It builds a pinned tree for each arm, runs the stages in order, stops at the first failure, remembers what finished, and writes `verdict.json` and `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>      # state of a run
scripts/dev/yv wait <run>        # block until the verdict
scripts/dev/yv suites            # list suites
scripts/dev/yv gate              # the release gate, with per-stage persistence
```

The exit code is `0` when every stage passed, `1` when a stage failed and `2` for an infrastructure error (the tool, git or a parameter mismatch). `yv ab` blocks until done; `--detach` returns at once.

### Arms

For a reviewable verdict, commit both arms and pass their full commit SHAs, so the base and the candidate are distinct, named states. `--base` and `--cand` also accept a checkout directory; uncommitted changes are hashed into the arm key so a resume never mixes two states of one tree. Both arms run the same interpreter. `--env K=V` applies to both arms, `--cand-env` to the candidate only and `--base-env` to the base. `--model` selects the checkpoint.

### Stages

Stages run in this order and stop at the first failure (unless the suite is marked to keep going).

| Stage | What it does | Passes when |
|---|---|---|
| `preflight` | CPU only. Both trees import, and the unit tests related to the diff are run | imports work, tests pass |
| `smoke` | Both arms serve and answer. `--engaged SPEC` proves the candidate path ran: `log:REGEX` (candidate server log), `field:KEY=REGEX` (an `x_yunshu` response field) or `spec:MODE` (the speculative mode in use) | it answers and every `--engaged` check matched |
| `identity` | Greedy decode of fixed code and prose prompts at each suite context length (cold, warm, follow-up turn); a digest over text, reasoning, tool calls, finish reason and token count. With `--spec-off`, the candidate with drafting off must also equal the candidate with it on | every cell is equal |
| `apc` | The warm request (served from the prefix cache) must equal the cold one and report `cached_tokens > 0`. `--no-apc-hit-required` is for paths without a prefix cache | hit equals miss |
| `quality` | 200-item paired MMLU-Pro run, interleaving base and candidate | all items scored in both arms, and the difference in correct answers within one question |
| `speed` | Decode tok/s, cold TTFT and follow-up TTFT over several reps, interleaved base, candidate, base, candidate. Medians, paired deltas and a noise estimate are reported | no median worsens by more than the larger of 2% and the measured noise (`--speed-tol`); a contended rep is rerun once |
| `memory` | Peak footprint, footprint after idle, footprint held after a short follow-up | no metric exceeds the base by more than 3% plus 0.25 GiB |
| `longqa` | Deterministic key-value needles placed in 32K, 64K and 128K prompts, one greedy question each | the correct count is within one of the base |
| `conc` | Two concurrent requests, each a warm 32K prefix plus new text | TTFT and per-request decode within 10% of the base |

`--spec-modes default,mtp,dflash` repeats the identity stage once per speculative method.

### Suites

| Suite | Stages and contexts |
|---|---|
| `decode` | preflight, smoke, identity, apc, speed at 1K and 8K |
| `prefill` | adds quality, up to 32K |
| `scheduler` | preflight, smoke, identity, apc, quality, speed at 1K and 8K |
| `memory` | preflight, smoke, identity, memory |
| `quick` | a fast iteration ladder; run `full` before merging |
| `full` | every stage at 1K, 8K and 32K |
| `long` | 32K, 64K and 128K cells with 2048-token replies: identity including drafting on and off, apc, speed, memory, longqa and conc; every stage runs even after a failure |
| `longtrend` | one rep of the headline long cells, for comparing releases |
| `tiny` | every stage on a small model, as a dry run of the tool |

An ad-hoc ladder such as `--suite smoke,identity,speed` keeps the canonical stage order. Overrides: `--ctx`, `--reps`, `--mmlu-n`, `--mem-sizes`, `--mem-reps`, `--speed-tol` and `--spec-off`.

### Resume and the verdict

Every stage writes its evidence as it goes. A cell's evidence counts only when its job exited cleanly and the record ends with `complete: true`; a job that ended early leaves no evidence and the stage fails. Running the same command again resumes: finished cells are reused (the verdict marks them), and a failure costs only the cell in flight. Changing the base, candidate, env, suite or model under an existing label is refused, so use a new label.

`verdict.json` has the label, both commits, the environment, the suite, the model, the overall result, the failed stage and per-stage status, reasons and numbers. `verdict.md` is a human summary.

## Accuracy against stock MLX

Equivalence to stock MLX or `mlx-vlm` on the same checkpoint is checked in three tiers, cheapest and most sensitive first. A 300-question benchmark carries roughly 13 questions of 95% noise, so it cannot see small numeric drift on its own.

| Tier | Compares | Sensitive to |
|---|---|---|
| 1 | next-token distributions on fixed text (teacher forcing): KL divergence and top-1 agreement | very small numeric drift |
| 2 | greedy continuations of 50 fixed prompts, up to 256 tokens | the first differing token |
| 3 | paired downstream evals (GSM8K, IFEval, MMLU-Pro, needle retrieval, tool calls), paired by item with McNemar tests and confidence intervals | task-level differences |

The reference is always stock `mlx-vlm` on the same checkpoint with none of Yunshu's kernels imported, and the run asserts this. A candidate is judged against what stock MLX does to itself: reruns are bit-exact, so any nonzero difference is a real path difference, but changing the batch size or the prefill chunk size already moves the mean KL divergence by about 1e-3 to 3e-3 and top-1 agreement to about 98.8%. That is the scale of a numerically legitimate implementation.

Tier 1 pass criteria:

- mean KL divergence at most twice the stock-versus-stock floor, and the median and the 99th percentile likewise;
- top-1 agreement of at least 98.4%;
- perplexity change of at most 0.5%;
- hard gates: with speculative decoding, the multi-token verify block must be bit-identical to single-token decode, so drafting on equals drafting off.

Tier 2: with drafting on and off the 50 prompts must be identical, and the match against the reference must not fall below the recorded baseline for the same checkpoint.

Tier 3 is reported as a paired difference with an interval, and equivalent paths must agree within one question on a paired set of roughly 200 to 300 items. The full benchmarks are not rerun for every change.

## Verifying agent and API behavior

Behavior that clients depend on is checked with the official tools rather than assumed:

- Unit tests (`tests/unit`) cover the request and response shapes, including a test that compares every request parameter of the installed `openai` and `anthropic` SDK types with the request models, so a new SDK field that is neither supported nor listed as ignored fails CI.
- A route-coverage test fails when the application registers a route that no check or reviewed exemption names.
- The release gate drives an installed build over HTTP with the official SDKs; see [Release gate](/docs/developers/release-gate).

## Related

- [Release gate](/docs/developers/release-gate)
- [Contributing](/docs/developers/contributing)
- [Architecture](/docs/developers/architecture)


---

<!-- getting-started/console -->
---
title: Console
description: The web console the Yunshu server hosts for watching the engine, managing models and keys, reading logs, trying the API and reading these docs.
---

The console is a web application served by its own light process (`yunshu console`, port 8100), apart from the engine. That process serves the console and these docs, passes the console's API calls on to the engine, and records the history, so the console stays usable and keeps recording while the engine restarts or crashes. It is a view onto one engine: live status, requests, models, caches, logs, API keys, settings and this documentation. It does not own the engine process; service restart is available under launchd. It is not a chat product.

<Callout type="info">
The console speaks Traditional Chinese, Simplified Chinese and English. It follows your browser's language and the choice is kept in the browser; switch it from the language button in the top bar. This documentation follows the same choice.
</Callout>

## Open the console

Start the server as usual: `yunshu serve` starts the console process next to the engine. Open `/console/` on the console's port, `http://127.0.0.1:8100/console/` by default (the engine keeps 8000). `--no-console` skips it, `--console-port` moves it, and `yunshu console --engine http://host:8000` runs it alone, for example against an engine on another machine. `yunshu service install` runs it as its own launchd job, so it keeps serving and recording while the engine restarts. The old `http://127.0.0.1:8000/console/` still works for one release as a redirect to the console process.

The static pages are public so that you can enter a token in the browser. Every API call the console makes still follows the normal authentication rules. Reading status, history, requests, models and cache views needs no token on a default local server. Management pages (API keys, logs, service, CORS) need the admin token, and show a notice with a link to Settings when it is missing. Enter `YUNSHU_AUTH_TOKEN` or an admin key in Settings; by default it stays in page memory only and is cleared when you reload.

If `/console/` answers 404 with the text "Yunshu Console is not built", the installed package does not contain the console build. The API is not affected. A source checkout builds the console with Node.js 22.18 or newer and pnpm:

```bash
cd frontend
pnpm install --frozen-lockfile
pnpm build
```

The build is written to `python/yunshu_gateway/console_static`, which the console process serves.

## Pages

The sidebar has six sections: Overview, Requests, Diagnostics, Models, Playground and Settings. Logs is a Diagnostics tab; Downloads and Cache are Models tabs; Keys and API access are Settings tabs. Docs opens from the top bar. Existing tab addresses remain valid.

| Page | What it does |
|---|---|
| Overview | Live engine state: phase (queued, prefill, decode), throughput, memory, caches, active requests. Updates about four times a second while a request runs and calmly when idle. |
| Requests | Live and finished requests with phase timelines, token and cache details, filtering, CSV export and per-request cancel. |
| Logs | The server log ring with level and text filters and a live tail. |
| Diagnostics | Health checks, host readouts, a support-bundle preview and raw diagnostic data. |
| Models | Loaded and available models with memory figures; load, unload, warm up, fit checks and idle retention. |
| Downloads | Download models from Hugging Face with progress, disk-space check and cancel. |
| Cache | Prefix-cache tiers (memory, warm, SSD) with entries, lifecycle events and clear actions. |
| Playground | Streaming chat with generation settings, tools, images, token confidence and generated code snippets. |
| API access | Connection snippets for your server and a catalogue of the routes it registers. |
| Docs | These pages, searchable from the command palette. |
| Keys | Named API keys with scopes, expiry and rolling-day quotas, and per-key usage. |
| Settings | Server address and token, theme and language, every engine setting with its source, CORS and service restart. |

## History and what happens when the engine is down

The console process reads the engine once a second and keeps the history in `~/.yunshu/console-history.sqlite`: 1 s resolution for the last hour, 10 s for 24 hours, 1 minute for 30 days, plus the finished-request log (numbers only, never prompts or outputs). On open, the charts (15 minutes to 30 days) and the request list backfill from it, then the live feed continues. While the engine is unreachable nothing is recorded, so the span shows as a gap and an event ("engine unreachable", "engine reachable again", "engine restarted", "model failed to load"), never as a line drawn across it.

When the engine does not answer, the console says "engine offline since 18:02:11, retrying in 4 s" and keeps retrying (backing off to about ten seconds, and at once when you return to the tab or the network comes back). Pages that show engine data keep their last data, dimmed and marked stale; the docs and Settings are unaffected. If the engine is up but the model failed to load, the page shows the error and Load model stays usable. A page that fails does not take the console down.

## Status and the status band

The separate floating status pills at the bottom of a desktop page shows the engine state, the loaded model and memory. Click it (or the compact pill on a phone) to open the status island: live phase, throughput, memory by owner and the host. Values the server did not report are shown as unavailable, not as zero.

If a refresh fails the console keeps the last numbers and says so; when the engine cannot be reached it shows an offline banner with Retry and Connection settings.

## Command palette

Press `⌘K` (`Ctrl K` on other systems) to open the command palette. It jumps to pages, runs actions such as loading a model or clearing a cache, switches language, and searches these docs: type two or more characters and matching pages and sections appear under Docs. `?` lists the keyboard shortcuts.

## Connection settings

By default the console talks to the same origin that served it. In Settings you can point it at another Yunshu server; that server must then allow the console's origin through its CORS configuration (`YUNSHU_CORS_ORIGINS`, editable in Settings when you have the admin token). Only the server address, theme and language are saved in the browser; the token is saved only if you ask for it.

## Notifications

The bell in the top bar opens the notification center (Notifications). It lists what changed while the console was watching, newest first, at most 50; the badge counts unread items, and opening the panel marks them read. Clear all empties it. Each row links to the page that explains it.

| Event | Raised when | Leads to |
|---|---|---|
| Model loaded / Model failed to load | a model's loaded or error state changes between two status reads | Models |
| Download finished / Download failed | a download that was queued or running ends | Downloads |
| Engine unreachable / Engine back online | the engine stops or starts answering | Diagnostics / Overview |
| Engine restarted | the reported uptime goes backwards | Diagnostics |
| Memory pressure is high | Metal active memory reaches 80% of unified memory; clears 5 points lower | Models |
| Server errors are rising | 3 or more 5xx responses within a minute; at most once per 5 minutes | Requests |

Only warnings and errors also pop up as a toast; the rest wait in the center. The first reading after you open the page never raises anything, and downloads that had already finished are not announced.

<Callout type="info">
The events are derived in your browser from the status, request and download reads the console already makes. They are kept in `sessionStorage` per server address, so they survive a reload of the tab but not a new tab, and nothing is sent to the server. This is separate from the recorded history and its engine events, which the console process stores.
</Callout>

## Memory ledger

The ledger answers "who holds the unified memory". It is fed by `/v1/yunshu/memory` on the engine, which needs inference permission, and the console re-reads it every few seconds while the page is visible. It appears in three places:

- **Models**, in a model's detail, under Memory holders.
- **Status island**, under Metal memory (with Swap, Memory pressure and the Reserve pool).
- **Cache**, where the prefix-cache share is shown as "from the memory ledger".

The table (Owner, Size, Reclaimable) lists Model weights, Prefix cache (RAM), Prefix cache (warm tier), KV of active requests, Reserve pool and Other, drawn as one bar against Metal memory. Marks show the peak since the server started, the Metal recommended limit and the wired limit.

- A size the server has no counter for is shown as Unknown, not as 0; an estimate is labelled estimated.
- When the owners add up to more than active Metal memory, "Other" shows 0 and the overshoot is stated.
- An engine without the route shows "This engine version does not report memory owners"; polling then stops.

See [Memory](/docs/internals/memory) for how each owner is counted.

## Speculation and stage latency

Both panels live on the Requests page and read the engine's finished-request records (`/v1/yunshu/requests/recent`).

**Speculative decoding** sits under the request list. It says how many of the last finished requests reported speculation, then groups them by Mode with Requests, Acceptance (total accepted tokens divided by total drafted tokens, over requests that reported both), Accepted / drafted tokens and Rounds; copy-draft rounds are called out. Requests with no speculation record are counted as plain decode, and requests with a mode but no counters are left out of the rate. The engine reports only per-request totals, so there is no per-depth chart. A second block, Engine counters (Model, MTP cycles, Accepted, Rejected, Adaptive draft), is read from `/debug/spec-decode` and covers everything since the engine started; if `/debug` is off it says the engine does not provide them.

**Stage latency** is the request waterfall, shown in a request's detail. Stages are Model lease, Gateway admit, Engine queue, Template, tokenize, Prefix-cache restore, Prefill, First decode and First flush, with time zero at gateway receive.

<Callout type="warn">
A stage the engine did not observe is listed under "Not reported", never drawn as zero. Prefill end is a host callback boundary, not a GPU profile; template and tokenize include media preparation; First flush is the server finishing the send, not the client receiving it. Rows that the page assembled from status polls (no engine record) have no waterfall, and an older engine shows "does not report stage latency yet". If the engine has host telemetry, the detail also shows an energy estimate for the prefill and decode windows; it includes other processes and idle power.
</Callout>

## Realtime health

On Diagnostics, the Realtime connection card (Test connection) checks the path from this browser to the engine's Realtime WebSocket (`/v1/realtime`, over `ws` or `wss` to match the page). It opens the socket once and waits for the first event, then shows Connect, First event, Server latency and Buffer depth, each marked browser or server. It sends no audio and uses no GPU, so it proves reachability, not speech quality; a figure the engine does not report is left out rather than shown as 0. See the [Realtime API](/docs/api/realtime).

## Tools tester and image to text

Both open from the Playground toolbar and use the model selected there.

### Tools

Tools opens the tool-call and structured-output tester. On the Tool calls tab, paste tool definitions as JSON (checked as you type: a name of 1 to 64 letters, digits, underscores or hyphens, `parameters` as an object schema), enter a prompt and press Send first round. Each round shows whether the engine called a tool, and whether the arguments are valid JSON, name a tool you defined and follow the schema. Fill in a result and press Send results and continue for the next round, up to a round limit; Start over resets. On the Structured output tab, give a JSON schema and press Send: the reply is checked as JSON and against the schema. The page checks a subset of JSON Schema and lists the keywords it skipped, and the response does not say whether constrained decoding enforced the schema; only the result is checked. Requests go to `/v1/chat/completions`. See [Structured output](/docs/guides/structured-output).

### Image to text

Image to text (OCR dialog) takes a PNG, JPG, WEBP, TIFF or BMP up to 10 MB, sends it to `/v1/ocr` and shows the text read, with the model and token usage. The button is disabled with "No OCR or vision model is loaded" when no loaded model can answer; an OCR-type model is preferred, else the first loaded vision model. The image goes to the engine only and is not kept. The engine returns text only, so there are no boxes on the image and no confidence figure. See the [OCR API](/docs/api/ocr).

## Engine pinning, auto-discovery and measurement pause

These features belong to the console process (`yunshu console`), see [Console process](/docs/internals/console-process).

- **Auto-discovery.** `yunshu console --engine auto` (or `YUNSHU_CONSOLE_ENGINE=auto`) keeps one console open across engine restarts and port changes. Every `YUNSHU_CONSOLE_DISCOVER_S` seconds (2) it probes the candidate ports with `/health`; `YUNSHU_CONSOLE_DISCOVER_PORTS=all` (the default) takes every TCP port listening on this Mac, or give a list such as `8000,18990-18999`. Only a port that answers like a Yunshu engine counts. It stays on the engine it follows, and moves to the most recently started live engine after two missed probes.
- **Pinning.** The status island lists the live engines (Engines: port, model, uptime). Use pins one, and it wins while it is live; Follow the newest unpins. The same is available through the console process's engines route (`/console/api/engines`, also under `/v1/yunshu/console/engines`).
- **Waiting.** With no live engine the island says "Waiting for an engine" and the console connects as soon as one starts; a short outage is shown calmly as a restart rather than a fault.
- **Measurement pause.** While the file named by `YUNSHU_CONSOLE_PAUSE_FILE` holds `{"pause": true, "until": ..., "reason": "..."}`, the console polls and probes no engine, so a monitor cannot perturb a timing run, and the island shows "Paused for a measurement: reason". Requests you make yourself still go through. The pause ends at `until`, two hours after the file's last write when `until` is null, or when the file is removed.

<Callout type="info">
Request history records the engine URL and start time with each request, so a switch shows as a separate session, marked by an `engine_switched` event.
</Callout>

## Network and CORS

Settings has a Network and CORS tab; changing it needs the admin token.

- **Network** is read-only: the address the console uses, and Reachable from, either This machine only or Local network. It shows the `yunshu service install --force --host 127.0.0.1` or `--host 0.0.0.0` command to switch, because the listen address is changed by reinstalling the service. Before opening the local network, set `YUNSHU_AUTH_TOKEN` or create an API key, and allow only the origins you need.
- **CORS origins** edits which websites may call the server from a browser. Add an origin as `http://` or `https://` plus host, with no path, or a lone `*`; `*` cannot be mixed with other origins and needs an explicit confirmation, because it lets any website call the server (without credentials). The page says whether this console's own origin is allowed. Save applies immediately; Reset to default restores the default.
- If `YUNSHU_CORS_ORIGINS` or a command-line flag sets the list, that wins over the config file: the editor says so, and edits are saved but do not change the running value.

See [Authentication and keys](/docs/guides/auth-and-keys) for the full CORS rules.

## What the console does not do

- It is not a multi-user control plane: keys carry scopes and quotas for one local server, nothing more.
- It keeps no durable chat history; the playground library is stored in your browser only.
- Prompts and responses are never stored by the console's request views, only metadata.

## Related

- [Quickstart](/docs/getting-started/quickstart)
- [Configuration](/docs/guides/configuration)
- [Operations API](/docs/api/operations)
- [Models API](/docs/api/models)


---

<!-- getting-started/install -->
---
title: Install
description: Install Yunshu from PyPI with uv or pip, or with Homebrew, and check the installation with yunshu doctor.
---

## Requirements

| Requirement | Detail |
|---|---|
| Hardware | A Mac with Apple Silicon (arm64). MLX does not run on Intel Macs or on Python running under Rosetta. |
| macOS | 14 (Sonoma) or newer. `yunshu doctor` fails the check on older versions. |
| Python | 3.13 or newer. `uv tool install` can fetch a managed 3.13 for you. |
| Memory | Enough unified memory for the model weights plus the KV cache. `yunshu doctor -m <model>` warns when a model does not fit. |

## Install with uv (recommended)

Install [uv](https://docs.astral.sh/uv/getting-started/installation/) first, then install the package from [PyPI](https://pypi.org/project/yunshu):

```bash
uv tool install "yunshu[vision]" --python 3.13
yunshu --version
```

The `vision` extra installs `mlx-vlm`. You need it for the Qwen3.5 / 3.6 / 3.8 families and for every vision-language model; it also serves text requests to those models. The base install (without extras) serves text-only `mlx-lm` models.

To upgrade later:

```bash
uv tool upgrade yunshu
```

## Install with pip

```bash
python3.13 -m venv ~/yunshu-env
source ~/yunshu-env/bin/activate
pip install "yunshu[vision]"
```

## Install with Homebrew

Yunshu is published in the shared tap `YuhuanStudio/homebrew-tap`:

```bash
brew install yuhuanstudio/tap/yunshu
```

The formula builds a Python 3.13 virtual environment and installs the package with the `vision` extra. It requires Apple Silicon and macOS Sonoma or newer. The formula does not define a Homebrew service; to run Yunshu in the background use [`yunshu service`](/docs/getting-started/service), which is the same for every install method.

## Optional extras

Install extras by name, for example `uv tool install "yunshu[vision,audio]" --python 3.13`.

| Extra | Adds | Needed for |
|---|---|---|
| `vision` | `mlx-vlm`, Pillow | Qwen3.5 / 3.6 / 3.8 and other vision-language models, image and video input |
| `audio` | `mlx-audio` | Speech-to-text, text-to-speech, and the Realtime voice WebSocket |
| `omni` | `mlx-vlm`, torch, torchvision, Pillow | Native speech-to-speech with Qwen3-Omni |
| `embeddings` | `mlx-embeddings` | `POST /v1/embeddings` |
| `generation` | diffusers, torch, torchvision, Pillow | Image generation. Without it, `POST /v1/images/generations` returns 503. |
| `compression` | zstandard, lz4 | Optional codecs for the prefix cache SSD tiers |
| `webrtc` | aiortc | Realtime over WebRTC (`POST /v1/realtime/calls`) |
| `web-render` | playwright | Browser rendering for web fetch (needs an installed browser) |
| `all` | `vision`, `audio`, `omni`, `embeddings`, `generation`, `compression` | Every modality above |

## Check the installation

```bash
yunshu doctor
```

`yunshu doctor` checks the platform (Apple Silicon, macOS version, Rosetta), Python, MLX and Metal, memory, installed package versions and extras, your settings, the models directory and unfinished downloads, free disk space, cache integrity, the port you will serve on, and whether the login service is installed. Each problem comes with a suggested fix. The command exits with status 1 when something blocks serving.

Add `-m <model>` to also check a model (path or Hugging Face repo id) for existence, completeness and fit in memory, and for Qwen3.5-family models which speculative path will be used. Use `--no-metal` to skip importing MLX; that check cannot prove that Metal or a checkpoint works.

```bash
yunshu doctor -m mlx-community/Qwen3.5-0.8B-MLX-bf16
yunshu --json doctor --no-metal
```

## Uninstall

```bash
yunshu service uninstall      # only if you installed the login service
uv tool uninstall yunshu      # or: brew uninstall yunshu, pip uninstall yunshu
```

Downloaded models live under `~/.yunshu/models` and are not removed. See [Service](/docs/getting-started/service) for a complete clean-up list.

## Next

Continue with the [Quickstart](/docs/getting-started/quickstart). If installation fails, see [Troubleshooting](/docs/guides/troubleshooting).


---

<!-- getting-started/models -->
---
title: Models
description: Where Yunshu keeps and finds models, how to download, list and remove them, and how to serve several models from one directory.
---

Yunshu loads MLX-format checkpoints. A model is a folder with a `config.json` and `*.safetensors` weights (or a diffusers pipeline with `model_index.json`).

## Where models live

Yunshu looks in two places.

| Location | Default | Notes |
|---|---|---|
| Models directory | `~/.yunshu/models` | Where `yunshu pull` writes. A model is stored as `<org>/<name>`, for example `~/.yunshu/models/mlx-community/Qwen3.5-0.8B-MLX-bf16`. The scanner also reads folders placed directly in the directory. |
| Hugging Face cache | Hugging Face's own cache location (`HF_HOME`, `HF_HUB_CACHE`) | Snapshots that have a config and weights are discovered and reused in place; they are not copied. |

When you pass a model reference to `yunshu serve -m`, Yunshu resolves it in this order before it considers downloading: an existing path, a name under the models directory (`name` or `org/name`), then a repo id that is already in the Hugging Face cache. If none matches, the loader treats the reference as a Hugging Face repo id.

### Change the models directory

Set `models_dir` (the setting `YUNSHU_MODELS_DIR`) with `yunshu config set`:

```bash
yunshu config set models_dir /path/to/models
yunshu config path          # prints the file it wrote: ~/.yunshu/config.toml
```

This changes where future `yunshu pull` downloads go and where the server scans in multi-model mode. It does not move models you already downloaded. The key may be written with or without the `YUNSHU_` prefix, and a path value is stored as an absolute path. An environment variable of the same name takes precedence over the config file, and `yunshu config set` prints a note when that is the case. Remove the setting with `yunshu config unset models_dir`. `yunshu config` shows every effective value with its source; see [Configuration](/docs/guides/configuration).

## List models

```bash
yunshu model list                     # models directory + Hugging Face cache
yunshu model list --no-hf-cache       # models directory only
yunshu model list --dir /path/to/dir  # scan a different directory
yunshu model list --url http://localhost:8000   # ask a running server instead
yunshu --json model list
```

For each model on disk the table shows the name, detected type, size, and whether it is in the models directory or the Hugging Face cache. With `--url`, the command calls `GET /v1/models` on the server and lists what the server reports. `yunshu models` is an alias of `yunshu model`.

## Download a 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
```

| Option | Meaning |
|---|---|
| `--dir`, `-d` | Download under this directory instead of the models directory. |
| `--revision`, `-r` | Branch, tag or commit to resolve. Resolved even if the model is already present. |
| `--force` | Download even if the model is already on disk. Only missing or changed files are fetched; nothing is deleted. |

The argument must be a Hugging Face repo id of the form `org/name`. If a complete copy already exists in the models directory or the Hugging Face cache, `yunshu pull` reports that and does not download again. An interrupted download is resumed by running the same command. `yunshu model pull` is the same command. The command never chooses a model for you.

Check a download with `yunshu doctor -m <model>`, which reports missing weight shards and whether the model fits in memory.

## Inspect and remove

```bash
yunshu model info mlx-community/Qwen3.5-9B-MLX-4bit   # alias: model show
yunshu model rm mlx-community/Qwen3.5-9B-MLX-4bit --yes
```

`model info` prints the model's type, size, file count, and key architecture and quantization fields from `config.json`. `model rm` removes a model by its exact name from the models directory. It asks for confirmation unless `--yes` is given, and in `--json` mode `--yes` is required. Models in the Hugging Face cache, symlinked models and models outside the models directory are never removed; manage those at their source. Unload a model from a running server before removing its files.

## Serve one model or many

**Single-model mode.** Give `--model` (or the model as the first argument). Every request maps to that model regardless of the `model` name it sends.

```bash
yunshu serve -m mlx-community/Qwen3.5-9B-MLX-4bit
yunshu serve ~/.yunshu/models/mlx-community/Qwen3.5-9B-MLX-4bit
```

**Multi-model mode.** Give `--models-dir` (or `-d`) to serve the models found in a directory. Models are registered at startup and loaded on demand, when a request names them. `GET /v1/models` lists the ids to use.

```bash
yunshu serve --models-dir ~/.yunshu/models
yunshu model list --url http://localhost:8000
```

A server with registered models and nothing loaded yet is reported as ready by `GET /health/ready`. The `model` field of a request must be one of the listed ids.

### Load and unload on a running server

```bash
yunshu model load mlx-community/Qwen3.5-9B-MLX-4bit
yunshu model unload mlx-community/Qwen3.5-9B-MLX-4bit
```

These call `POST /v1/models/load` and `POST /v1/models/unload/{model_id}`. They are operational endpoints: when `YUNSHU_AUTH_TOKEN` is not set they are denied, so set a token on the server and export the same value in the shell where you run the CLI. See the [models API](/docs/api/models).

## Related

- [Quickstart](/docs/getting-started/quickstart)
- [Model support](/docs/guides/model-support): which model families and types are supported.
- [CLI reference](/docs/guides/cli)


---

<!-- getting-started/quickstart -->
---
title: Quickstart
description: Download a model, start the server, check readiness and send a first request with curl, the OpenAI SDK or yunshu chat.
---

This page takes you from an installed `yunshu` command to a first answer. If `yunshu --version` does not work yet, start with [Install](/docs/getting-started/install).

<Steps>
<Step>

### Download a model

Check what is already on disk, then pull a small model for a first run:

```bash
yunshu model list
yunshu pull mlx-community/Qwen3.5-0.8B-MLX-bf16
```

`yunshu pull` downloads into `~/.yunshu/models` (see [Models](/docs/getting-started/models)). It resumes an interrupted download and reuses a complete copy that is already in the models directory or the Hugging Face cache. The 0.8B model is meant for a smoke test; use a larger MLX checkpoint for real work.

</Step>
<Step>

### Check the model, then serve it

```bash
yunshu doctor -m mlx-community/Qwen3.5-0.8B-MLX-bf16
yunshu serve -m mlx-community/Qwen3.5-0.8B-MLX-bf16
```

The model can also be passed as the first argument (`yunshu serve mlx-community/Qwen3.5-0.8B-MLX-bf16`) or as a local directory. The server listens on `127.0.0.1:8000` by default. Keep this terminal open; stop the server with Ctrl-C.

If you run `yunshu serve` with no model configured in an interactive terminal, it asks you to choose one of the models on disk or to enter a Hugging Face repository. It never downloads a model on its own. Without a terminal it exits with an error and next steps.

</Step>
<Step>

### Wait until it is ready

Open a second terminal:

```bash
curl --fail http://127.0.0.1:8000/health/ready
curl --fail http://127.0.0.1:8000/v1/models
```

`GET /health/ready` returns HTTP 503 while the model is loading or if it failed to load, and 200 once the server can take requests. An open port alone does not mean the model is ready. When the load failed, the 503 body carries a `reason`.

</Step>
<Step>

### Send a request

In single-model mode the `model` field is advisory: any name maps to the model you started. By default no API key is required; authentication is enforced only when `YUNSHU_AUTH_TOKEN` is set.

<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 clients use the base URL `http://localhost:8000/v1`. Anthropic clients use `http://localhost:8000` without `/v1`, and call `POST /v1/messages`. See the [API overview](/docs/api/overview).

## Chat in the terminal

`yunshu chat` is an interactive client for a server that is already running. It does not download a model or start a server.

```bash
yunshu chat
yunshu chat --system "Answer briefly." --temperature 0.2 --thinking
```

Inside the chat, `/clear` resets the conversation, `/thinking` toggles thinking mode, `/model <name>` switches model, `/help` lists commands, and `/quit` (or Ctrl-C) leaves. Options are listed in the [CLI reference](/docs/guides/cli).

For a single non-interactive request, use `yunshu complete`:

```bash
yunshu complete "Say hello in one sentence." --max-tokens 64
yunshu --json complete "Say hello in one sentence."
```

## When port 8000 is taken

`yunshu serve` checks that it can bind the address before loading the model and stops with an error if it cannot. Pick another port and use it everywhere:

```bash
yunshu serve -m mlx-community/Qwen3.5-0.8B-MLX-bf16 --port 8001
yunshu chat --url http://127.0.0.1:8001
```

Another process can still take the port between the check and the real bind; the final bind error is authoritative. The server listens on `127.0.0.1` only. To accept connections from other machines use `--host 0.0.0.0`, and set `--auth-token` as well; `yunshu serve` warns when you bind a non-local address without a token.

## Use a coding agent

`yunshu launch` writes the configuration for a coding tool and starts it against your server. Preview first:

```bash
yunshu launch claude --dry-run
yunshu launch codex --dry-run
yunshu launch opencode --dry-run
```

Then run the same command without `--dry-run`. Supported tools are `claude`, `codex`, `opencode` and `pi`; `yunshu launch list` shows which are installed. The launcher reads the context window, output limit, reasoning-effort levels and vision support of the served model from the server and passes them to the tool. See [Agents](/docs/guides/agents).

## Next

- [Models](/docs/getting-started/models): where models live and how to manage them.
- [Service](/docs/getting-started/service): start Yunshu at login.
- [Console](/docs/getting-started/console): a web view of the running engine.


---

<!-- getting-started/service -->
---
title: Service
description: Run Yunshu in the background at login with a per-user launchd agent managed by yunshu service.
---

`yunshu service` manages a per-user launchd agent on macOS. The agent starts Yunshu when you log in, restarts it after a crash (but not after a clean stop), and writes its output to a log file that is rotated automatically. It runs as you; it needs no root access and touches nothing outside the two paths below.

| What | Where |
|---|---|
| launchd agent | `~/Library/LaunchAgents/com.yuhuanstudio.yunshu.plist` |
| Log | `~/Library/Logs/Yunshu/yunshu.log` |

The command exists on macOS only. It is the same for every install method (uv, pip or Homebrew); the Homebrew formula defines no separate service.

## Install

Check the model first if you like, then install:

```bash
yunshu doctor -m mlx-community/Qwen3.5-9B-MLX-4bit
yunshu service install -m mlx-community/Qwen3.5-9B-MLX-4bit
```

`install` takes the options that decide what to serve and where:

| Option | Meaning |
|---|---|
| `--model`, `-m` | A model folder or a Hugging Face repo id. An existing path is stored as an absolute path. |
| `--models-dir`, `-d` | Serve every model in this directory (multi-model mode). |
| `--host` | Bind host. Default `127.0.0.1`. |
| `--port`, `-p` | Bind port. Default `8000`. |
| `--config`, `-c` | A TOML settings file that the service reads on every start. It must exist. |
| `--set KEY=VALUE` | A setting fixed at install time. Repeatable. |
| `--dry-run` | Print the launchd agent as a property list and change nothing. |
| `--no-start` | Write the agent but do not start it now. |
| `--force` | Replace an agent that is already installed. |

You must say what to serve: pass `--model` or `--models-dir`, or have `YUNSHU_MODEL` set. `install` refuses a model that fails the same model check as `yunshu doctor -m` (for example a missing path or an incomplete download). If an agent is already installed, `install` stops with an error unless you pass `--force`.

`install` writes two agents: the engine, and the console process as its own job (`com.yuhuanstudio.yunshu.console`, kept alive whenever it stops), so the console keeps serving and recording while the engine restarts or crashes. `--no-console` installs the engine only, `--console-port` moves the console (default 8100), `yunshu service logs --console` reads its log, and `yunshu service restart` restarts the engine only. The engine agent runs `python -m yunshu_cli serve --no-console ...` using the Python of the installation that ran `install`. After you upgrade Yunshu in the same environment, run `yunshu service restart`. After you move to a different environment, run `yunshu service install --force ...` again.

```bash
yunshu service install -m mlx-community/Qwen3.5-9B-MLX-4bit --dry-run   # review first
```

### Settings for the service

Settings that you `export` in your shell are not copied into the service. Put them in a config file passed with `--config`, or fix them with `--set`. The environment variables `HF_HOME`, `HF_HUB_CACHE`, `HF_ENDPOINT` and `HF_HUB_OFFLINE` are the exception: they are copied, so the service finds the same Hugging Face cache. Without `--config`, the service still reads the per-user file `~/.yunshu/config.toml` that `yunshu config set` writes. The service's `PATH` is fixed to `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`.

A config file is flat `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
```

If you bind a non-local `--host`, set an auth token as well. See [Configuration](/docs/guides/configuration) for every setting.

## Everyday commands

```bash
yunshu service status        # installed / running (pid) / healthy, plus paths
yunshu service logs -n 100   # last 100 lines (default 50)
yunshu service logs -f       # follow the log
yunshu service restart       # for example after editing the config file
yunshu service stop          # stop until the next login or `service start`
yunshu service start
yunshu service uninstall     # stop and remove the agent; models and logs stay
```

| Command | Behavior |
|---|---|
| `status` | Reports whether the agent is installed and loaded, its pid and last exit code, the URL it was installed with, and whether `GET /health` answers. `--json` returns the same facts. |
| `logs` | Shows the last `--lines`/`-n` lines. `--follow`/`-f` keeps printing and cannot be combined with `--json`. Fails if no log exists yet. |
| `start` | Starts an installed agent. Fails if nothing is installed. |
| `stop` | Unloads the agent. It stays stopped until the next login or `start`. |
| `restart` | Restarts a running agent. Fails if the service is not running; use `start` then. |
| `uninstall` | Stops the agent and deletes the plist. Models and logs are kept. |

The agent is configured to restart after a crash, not after a clean exit, and launchd waits at least 10 seconds between restarts. If the model cannot load, the server stays up and `GET /health/ready` returns 503 with a reason rather than the process exiting in a loop.

## Log rotation

The service rotates its own log while it runs. Rotation happens by size and by age; rotated files are gzip archives with tokens and API keys redacted. These settings control it:

| Setting | Default | Meaning |
|---|---|---|
| `YUNSHU_LOG_MAX_MB` | 50 | Rotate at this size in MiB. 0 turns size rotation off. |
| `YUNSHU_LOG_ROTATE_HOURS` | 24 | Also rotate after this many hours. 0 turns time rotation off. |
| `YUNSHU_LOG_KEEP` | 7 | Rotated files kept. |
| `YUNSHU_LOG_RETENTION_DAYS` | 14 | Delete rotated files older than this. 0 keeps them until `YUNSHU_LOG_KEEP` prunes them. |

`yunshu service rotate-logs` rotates the log immediately, which is useful for a stopped service.

## Uninstall completely

```bash
yunshu service uninstall
uv tool uninstall yunshu               # or: brew uninstall yunshu, pip uninstall yunshu
rm -rf ~/Library/Logs/Yunshu
rm -rf ~/.yunshu                       # downloaded models and config: check before deleting
```

The prefix cache SSD tier lives in `~/.yunshu/cache/apc` unless `YUNSHU_VLM_APC_DISK_DIR` points elsewhere; delete that directory too if you set it.

## Related

- [Install](/docs/getting-started/install)
- [Troubleshooting](/docs/guides/troubleshooting)
- [CLI reference](/docs/guides/cli)


---

<!-- guides/agents -->
---
title: Coding agents and SDKs
description: Point Claude Code, Codex, opencode, Pi and the official OpenAI and Anthropic SDKs at a local Yunshu server, with the launcher or by hand.
---

Yunshu serves the OpenAI API under `/v1` and the Anthropic Messages API at `/v1/messages`, so any coding agent or SDK that lets you set a base URL can use it. For Claude Code, Codex, opencode and Pi, `yunshu launch` goes one step further: it reads the model card from the server and hands the agent the numbers it would otherwise guess wrong (context window, output limit, reasoning levels, vision support).

| | Value |
|---|---|
| OpenAI base URL | `http://localhost:8000/v1` |
| Anthropic base URL | `http://localhost:8000` (the SDK appends `/v1/messages`) |
| API key | any placeholder. A key is checked only when the server runs with `YUNSHU_AUTH_TOKEN` (or `--auth-token`) |
| Model name | in single-model mode the name is advisory, `local` works. In multi-model mode use an id from `GET /v1/models` |

When a token is set, the server accepts it as `Authorization: Bearer <token>` (OpenAI clients) or `x-api-key: <token>` (Anthropic clients).

## Launch an agent

Start a server first (`yunshu serve -m <model>`, see [Quickstart](/docs/getting-started/quickstart)), then:

```bash
yunshu launch list                      # which tools are installed
yunshu launch claude                    # Claude Code
yunshu launch codex                     # Codex CLI
yunshu launch opencode                  # opencode
yunshu launch pi                        # Pi
yunshu launch codex --dry-run           # print the configuration, write nothing
```

| Option | Meaning |
|---|---|
| `--model`, `-m` | model id to use. Default: the first model from `GET /v1/models` that looks like a known chat family, else the first model listed |
| `--url`, `-u` | server URL. Default `http://localhost:8000`, or the `YUNSHU_GATEWAY_URL` environment variable |
| `--api-key`, `-k` | API key to hand to the tool |
| `--effort` | Claude Code only: sets `CLAUDE_CODE_EFFORT_LEVEL` |
| `--statusline` / `--no-statusline` | Claude Code only: add (default) or skip the Yunshu status line |
| `--dry-run` | print what would be written or exported and exit |

The launcher checks `GET /health` first and exits with a hint if no server answers. It fails if the tool is not installed (`--dry-run` skips that check).

### What each launcher sets

<Tabs items={["Claude Code", "Codex", "opencode", "Pi"]}>
<Tab value="Claude Code">

Environment variables only. Nothing is written under `~/.claude`.

| Variable | Value |
|---|---|
| `ANTHROPIC_BASE_URL` | the server URL, without `/v1` |
| `ANTHROPIC_AUTH_TOKEN` | the API key, or `yunshu` when none is given (a bearer token, not `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` | the served model id, so every alias and sub-agent resolves to it |
| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | the model's real context window (Claude Code assumes 200K for an unknown model id) |
| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | the model's output limit, capped at 32000 |
| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | `1`: `/model` lists the models from `GET /v1/models` |
| `DISABLE_TELEMETRY`, `DISABLE_ERROR_REPORTING`, `DISABLE_AUTOUPDATER` | `1` |
| `CLAUDE_CODE_EFFORT_LEVEL` | only with `--effort` |

Before launching, the launcher removes `ANTHROPIC_API_KEY`, `CLAUDE_CODE_USE_BEDROCK` and `CLAUDE_CODE_USE_VERTEX` from the environment so a stray setting cannot send requests elsewhere.

It also passes `--settings` with a status line that runs `yunshu statusline` (prefill progress, decode speed, last cache hit, context use). The status line is skipped when your own Claude Code `settings.json` already defines a `statusLine`, or with `--no-statusline`.

</Tab>
<Tab value="Codex">

Writes two files and backs up an existing `config.toml` next to it with a `.<timestamp>.bak` suffix.

- `~/.codex/config.toml`: sets `model`, `model_provider = "yunshu"`, `model_catalog_json`, `model_context_window`, `model_auto_compact_token_limit` (85% of the window), `web_search` and, for reasoning models, `model_reasoning_summary = "auto"`. It adds a `[model_providers.yunshu]` table with `base_url = "<server>/v1"`, `env_key = "YUNSHU_API_KEY"` and `wire_api = "responses"`. Other settings and tables in the file are kept.
- `~/.codex/yunshu-models.json`: a model catalog entry with the real context window, the reasoning levels the chat template accepts, input modalities and a compact `base_instructions`. Codex never fetches model metadata from a custom provider; without the catalog it prints "Model metadata not found" and sends no reasoning effort.

`web_search` is `"live"` when the model card reports server-side web search as available, otherwise `"disabled"`. The launcher exports `YUNSHU_API_KEY` (the API key, or `yunshu`) and starts `codex -m <model>`.

</Tab>
<Tab value="opencode">

Updates `~/.config/opencode/opencode.json` (a timestamped `.bak` copy is kept) with a `provider.yunshu` entry and `"model": "yunshu/<id>"`. The provider uses `@ai-sdk/openai-compatible` with `baseURL` set to `<server>/v1`, and the model entry carries `tool_call`, `reasoning`, `limit.context`, `limit.output` and `modalities`. opencode does not fetch `/models` from custom providers, so these limits are what drives its context percentage and compaction.

</Tab>
<Tab value="Pi">

Updates `~/.pi/agent/models.json` (provider `yunshu`, `api: "openai-completions"`, `baseUrl` `<server>/v1`) and `~/.pi/agent/settings.json` (`defaultProvider`, `defaultModel`), then starts `pi --model yunshu/<model>`. Unlike the other three, the Pi entry does not carry context or output limits from the model card.

</Tab>
</Tabs>

## Manual configuration

Use these when you do not want the launcher to touch your config.

<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   # your model's real window
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
```

Without a `model_catalog_json` Codex does not know the model: expect "Model metadata not found" and no reasoning-effort choices.

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

Other OpenAI-compatible tools work with a base URL and a key: Cline and Roo Code (provider "OpenAI Compatible", base URL `http://localhost:8000/v1`), Continue (`provider: openai`, `apiBase: http://localhost:8000/v1`) and Open WebUI (Settings, Connections, OpenAI API). These are configuration guidance; they are not tested release by release the way the three agents above are.

## Which endpoints each agent uses

These are the calls the agents make against a custom provider, and how Yunshu answers them.

| Agent | Request | Yunshu |
|---|---|---|
| Claude Code | `POST /v1/messages` with `stream: true`, every turn, with `anthropic-beta` headers, `cache_control` on system blocks, `thinking` and `output_config.effort` | served. Betas are never rejected |
| Claude Code | `POST /v1/messages/count_tokens` (`/context`) | served: counts system, messages and tools |
| Claude Code | `GET /v1/models` (with discovery on, fills `/model`) | served, with `max_input_tokens`, `max_tokens` and `capabilities` |
| Claude Code | `POST /v1/messages` with a `web_search_20250305` tool | executed server side, see [Web search and fetch](/docs/guides/web-search) |
| Claude Code | small-model calls (titles, summaries) and sub-agents | ordinary `POST /v1/messages` calls |
| Codex | `POST /v1/responses` with `stream: true`, `store: false`, function, namespace and `web_search` tools, `reasoning`, `include` | served |
| Codex | `WS /v1/responses` (only when the provider sets `supports_websockets`; the launcher does not) | served |
| Codex | compaction | an ordinary `POST /v1/responses` call with no tools |
| opencode | `POST /v1/chat/completions` with `stream_options.include_usage`, a large `max_tokens`, function tools; title generation with `reasoning_effort: "low"` | served |

MCP servers configured in an agent are client side: the agent connects to them and sends their tools to the model as ordinary function tools, so Yunshu only needs working tool calling. Claude Code's WebFetch is also client side. The server-side MCP connector (`mcp_servers` on Messages, `{type: mcp}` tools on Responses) is a separate feature, see [Server tools](/docs/api/server-tools).

## What works and what does not

| Feature | Claude Code | Codex | opencode | Status |
|---|---|---|---|---|
| Streaming, tool calls | yes | yes | yes | <Support status="supported">supported</Support> |
| Mid-conversation system or developer notes | yes | yes (`developer` items) | not used | <Support status="supported">supported</Support> |
| Effort control | `output_config.effort` is mapped to the chat template's `reasoning_effort` | `reasoning.effort` through the catalog levels | `reasoning_effort` | <Support status="supported">supported</Support> |
| Web search | server side `web_search` | server side `web_search` | not used (client tool) | <Support status="supported">supported</Support> when a provider is available |
| Web fetch | client side in the CLI | not used | not used | SDK users get the server-side `web_fetch` tool |
| MCP | client side | client side | client side | <Support status="supported">supported</Support> as plain tool calling |
| Image input | yes (a `Read` of a PNG) | not used in `exec` mode | not used | <Support status="partial">needs a vision model</Support> |
| Model picker and context window | from `/v1/models` and the launch environment | from the catalog | from `limit` | <Support status="supported">supported</Support> with `yunshu launch` |
| Live engine state in the UI | `yunshu statusline` | not available | not available | <Support status="extension">Claude Code only</Support> |
| Cost display | shows made-up numbers for an unknown model; nothing is billed | not applicable | not applicable | <Support status="unsupported">cannot be corrected server side</Support> |
| Rate-limit headers | not sent: Yunshu has no quota | not sent | not sent | <Support status="unsupported">not provided</Support> |

Other things to know:

- A failure after a stream has started is reported as an in-stream error (an SSE `error` event on Messages, `response.failed` on Responses, an error chunk on chat) instead of an empty successful reply.
- Explicit `cache_control` markers are hints. If the chat template drops a marker (Qwen templates remove the reasoning of earlier turns), the request is served without explicit checkpoints instead of failing. See [Prompt caching](/docs/guides/prompt-caching).
- A JSON `null` for `temperature`, `max_tokens`, `stream` or similar fields means "unset" and is accepted, because several SDKs send it.
- Responses streams end with `data: [DONE]`, which the real API does not send. The official SDKs and Codex stop on it without trouble.
- Known gaps in the request models: the deprecated chat `functions` / `function_call` fields, custom tools in chat, Responses `prompt` templates, and a Responses request with no `input`.
- Claude Code keeps listing its built-in model rows in `/model`; those come from the client's own catalog. The context window it works with is the real one (check `/context`).
- Agents send long prompts that repeat from turn to turn. Yunshu's prefix cache reuses the shared part, so after the first turn only the new tokens are prefilled.

## SDK setup

All four snippets use a placeholder key. Replace `local` with a model id if you serve several models.

<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"},  # passed to templates that support it
)
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>

For the OpenAI SDK the base URL ends in `/v1`; for the Anthropic SDK it does not. Streaming (`stream=True`), tools, `response_format`, `stop`, `logprobs` and `seed` work through the official SDKs. The thinking output of reasoning models is streamed separately from the answer (`delta.reasoning_content` on chat).

To reach the server from another machine or a container, start it with `--host 0.0.0.0 --auth-token <secret>` and use the secret as the key. The default bind is `127.0.0.1`.

## Related

- [Chat Completions](/docs/api/chat-completions), [Responses](/docs/api/responses) and [Messages](/docs/api/messages)
- [Web search and fetch](/docs/guides/web-search)
- [Prompt caching](/docs/guides/prompt-caching)
- [CLI reference](/docs/guides/cli)
- [Troubleshooting](/docs/guides/troubleshooting)


---

<!-- guides/auth-and-keys -->
---
title: Authentication, API keys and CORS
description: How to protect a Yunshu server with a token or per-key quotas, write settings from the API, edit CORS origins, and what the built-in protections do.
---

Yunshu is a single-node, single-operator server. Access control has three layers, all local: a static token, optional API keys with quotas, and CORS origins.

## Static token

Set `YUNSHU_AUTH_TOKEN` (or start with `--auth-token`). Then every request except health, version and docs needs `Authorization: Bearer <token>` or `x-api-key`. The text WebSocket endpoints also accept `?token=`.

| State | Inference routes | Operational routes (model load/unload, settings, keys, logs, diagnostics) |
|---|---|---|
| Token set | need the token | need the token |
| No token and no stored API keys | open | denied |
| `YUNSHU_AUTH_DISABLED=1` | open | open |

<Callout type="warn">
The token is an admin credential. `YUNSHU_AUTH_DISABLED=1` opens everything and is for local development only. `YUNSHU_HOST` defaults to `127.0.0.1`; set a token before binding `0.0.0.0`.
</Callout>

## API keys with quotas

Besides the static token, the operator can create several keys. Each key has scopes (`infer`, `admin`), an optional expiry and quotas (`requests_per_day`, `tokens_per_day`, `max_concurrent`). Manage them on the console Keys page or through the API with admin scope.

<Steps>
<Step>

Create a key. The response carries `secret` once; only a hash is stored in `~/.yunshu/keys.json` (mode 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>

Give the secret to the client as its API key.

</Step>
<Step>

Watch per-key daily usage (requests, prompt, completion and cached tokens, errors):

```bash
curl -s localhost:8000/v1/yunshu/usage -H "Authorization: Bearer $YUNSHU_AUTH_TOKEN"
```

</Step>
</Steps>

`PATCH` and `DELETE` on a key edit and remove it, and `POST /v1/yunshu/keys/{id}/rotate` re-issues it. Over a quota the answer is `429` in the route's own error dialect with `Retry-After`. The routes are listed in [Yunshu extensions](/docs/api/extensions) and [Operations](/docs/api/operations).

Keys are not tenants. An infer key sees only the Files and Conversations it created (another key's object answers 404); the static token, auth-disabled mode and admin-scope keys see all. Stored completions and Evals data are still shared; there is no RBAC. The Realtime WebSocket accepts keys but does not count quotas.

## Write settings

`GET /v1/yunshu/config` lists every setting with its value, default, source and when a change applies (`live`, `reload` or `restart`). `PATCH /v1/yunshu/config` validates and persists changes atomically (all or nothing, file mode 0600). An environment or CLI value still wins and is reported as `overridden`. `dry_run` previews a change.

Settings that need a restart are flagged so the console prompts you. `POST /v1/yunshu/service/restart` restarts the server only when it runs under launchd. The console Settings page does the same with a search box and per-setting controls. All settings are described in [Configuration](/docs/guides/configuration).

## CORS

`GET` and `PATCH /v1/yunshu/cors`, and the console Settings page, edit the allowed origins live. The default `YUNSHU_CORS_ORIGINS` is `http://localhost:3000,http://localhost:8000`.

- Origins are `scheme://host[:port]`, at most 50.
- A wildcard (`*`) needs an explicit confirmation, is never combined with other origins, and disables credentials. Browsers that send cookies or authorization headers must use explicit origins.
- The same list is checked against the `Origin` header of the Realtime and text WebSockets.
- Bind address and LAN exposure are read-only through this API.

## Host and Origin checks

A server bound to a loopback address checks the `Host` header, so a web page cannot reach it through DNS rebinding. Accepted: `localhost` (also `localhost.` and `*.localhost`), any `127.0.0.0/8` form (`127.0.0.1`, `127.1`), `[::1]`, and the unspecified address (`0.0.0.0`, `[::]`), with any port. Anything else gets `403` naming the header value and the setting. A server bound to `0.0.0.0` checks nothing unless `YUNSHU_ALLOWED_HOSTS` is set.

- A reverse proxy, `tailscale serve`, a cloudflared tunnel or `ssh -L` that forwards a public name as `Host` to a loopback server needs that name in `YUNSHU_ALLOWED_HOSTS` (comma-separated; `*` turns the check off).
- `host.docker.internal` is not accepted on a loopback bind: a container reaches the host's loopback only if the server listens beyond it (`YUNSHU_HOST=0.0.0.0`), and then the check is off anyway.
- A state-changing request with an `Origin` header and no credentials must come from loopback, the request's own origin, or `YUNSHU_CORS_ORIGINS`. For custom schemes list `scheme://*` (for example `vscode-webview://*`) or the exact origin (`app://.`). `Origin: null` is always refused. Requests that carry `Authorization` or `x-api-key` are exempt.

## Failed sign-ins

A non-loopback client address that presents a wrong credential 20 times within 60 seconds gets `429` with `Retry-After` for further wrong credentials. A correct token or key is always accepted and clears that client's count, and a request without any credential is answered `401` and not counted. When `YUNSHU_TRUSTED_PROXIES` lists the connecting proxy, the last `X-Forwarded-For` entry is the client address; otherwise the peer address is used.

## Other protections

- Authorization, API-key and cookie headers are dropped when a model download redirects to another origin.
- Realtime ephemeral secrets (`ek_...`) and credentials in log lines are redacted. Transcription secrets cannot create model responses.
- `web_fetch` blocks private, loopback and link-local addresses, also after redirects, unless `YUNSHU_WEB_FETCH_ALLOW_PRIVATE=1`. Repository IDs with path traversal are rejected before disk access.
- `YUNSHU_RATE_LIMIT_RPM` (default `0`, off) limits requests per client per minute; set it when the server is exposed to other machines.
- No usage analytics are sent. See [Host telemetry](/docs/guides/telemetry) for what is sampled locally.


---

<!-- guides/benchmarks -->
---
title: Benchmarks
description: Full 27B comparison run 2026-11-04 to 2026-11-08 on Apple M5 Max, audited study gaps_full_1109. Same numbers as docs/BENCHMARKS.md.
---

Apple M5 Max, 128 GB unified memory, Qwen3.8-27B 4-bit. Yunshu 0.1.7.dev0 (main, round driver)
and its Phase B build (`yunshu-pb2`). Full comparison run 2026-11-04 to 2026-11-08. Every number
below comes from the audited study `gaps_full_1109` (2026-11-09; private research notes, not in this
repository), which was generated from the raw rows. Competitors: TensorFold 1.1.8 and 1.2.1, Splash 1.5.0,
llama.cpp b12061, oMLX 0.7.3 and 0.7.3rc1, mlx-lm-server 0.32.2, mlx-vlm-server 0.7.11 and mlx-serve 26.11.1.
Kapitsa 0.2.26 and LM Studio are excluded (see below).

The 2026-10-19 27B snapshot is superseded by this run and is not repeated here. It stays as a dated
report: [RELEASE_016 snapshot 2026-10-19](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_016_BENCHMARKS_2026-10-19.md). The
[0.1.5 snapshot](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_015_BENCHMARKS.md) remains unchanged as history.

## How to read these numbers

- Each value is a median over 2 or 3 repetitions. A third repetition was run unplanned in many Yunshu cells.
- The study has two views. STRICT counts a row only when both sides pass every audit check; that leaves
  18 comparable rows, all from batch B1. REF also ignores two bookkeeping failures: a mix of harness commits
  in B2, and an unplanned extra repetition file. Every number below is a REF number. Under REF, the Yunshu
  side used for each number carries only checks that REF waives, except the restart row (see Other cells).
- Excluded: every Kapitsa cell (the launched binary hash does not match the pinned one, so its RAW wins
  are not used); tool-chat decode tok/s (27-token replies make the timing window too short; tool-chat TTFT
  is kept); the 128K mixed per-row median (the roles differ; the aggregate is used); restart decode tok/s
  (not comparable across engines); LM Studio (never run).
- Percentages follow the study. Positive means Yunshu is better. A percentage uses the better of Yunshu
  main and Yunshu pb2, while the Yunshu value shown is the main column (the same values as the README).
  Where pb2 is faster, the displayed ratio can differ from the percentage.
- Scope: code and prose prompts at 32K, 64K and 128K, plus the concurrency, mixed and restart cells listed
  below. The study does not establish general quality or a general ranking.

## Where Yunshu stands

Across the full matrix, REF has 114 comparable rows. Yunshu wins 17 and loses 97: losses are to Splash (37),
TensorFold 1.1.8 (36), TensorFold 1.2.1 (22), llama.cpp (1) and mlx-serve (1). Forty of the losses are at 32K or above.

TensorFold leads 27B decode at every depth for code, and at 32K and 64K for prose; Splash leads prose decode
at 128K. Cold TTFT is behind Splash at 32K and 64K and ahead at 128K. Warm TTFT is ahead at 32K and behind at
64K and 128K. Follow-up (turn-2) TTFT loses at every depth, and the largest loss is at 64K (-61.5% code).

### Code prompt

| Metric | 32K | 64K | 128K |
|---|---|---|---|
| Decode tok/s, cold | 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% |
| Decode tok/s, warm | 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% |
| Cold 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% |
| Warm 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% |
| Follow-up 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% |

### Prose prompt

| Metric | 32K | 64K | 128K |
|---|---|---|---|
| Decode tok/s, cold | 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% |
| Decode tok/s, warm | 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% |
| Decode tok/s, follow-up | 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% |
| Cold 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% |
| Warm 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% |
| Follow-up 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% |

### Other cells

- Distinct 8K prompts, aggregate decode tok/s, code. Yunshu main (pb2) at 2, 4 and 8 concurrent requests:
  27.3 (36.8), 33.0 (38.5) and 37.1 (39.1). Best competitor (REF): TensorFold 1.2.1 42.3, TensorFold 1.2.1 45.1,
  TensorFold 1.1.8 45.2. Yunshu vs best: -13.1%, -14.7% and -13.5%. Kapitsa is excluded.
- Mixed 128K, code, 8 concurrent (one 128K long request and 7 short ones). Aggregate tok/s: 16.1 (pb2 18.1)
  against Splash 17.7, +2.0%. Long-request TTFT: 222.256 s (pb2 212.084 s) against Splash 224.558 s, +5.9%.
  The per-row median is not like-for-like and is not reported.
- Turn-2 at near-equal cache (the study's idle5 cell, code, 32K): TTFT 0.983 s with 32704 cached tokens,
  against TensorFold 1.1.8 at 0.070 s with 33283 cached tokens, -92.9%. Turn-2 at 64K and 128K loses by
  31 to 61 percent across code and prose.
- Code turn-2 decode at 32K: 342.2 tok/s (pb2 347.0) against Splash 127.2, +168.9%. The study does not
  explain this result, so it is not treated as a general claim.
- Restart, code, 32K: restart TTFT 32.868 s against mlx-serve 26.11.1 at 0.313 s, -99.0%. Both Yunshu
  engines show 0 cached tokens after the restart (audit `cold_cache` fails), so disk-tier restore is not
  demonstrated. The restart item is reopened.
- Structured output (json-schema, 8K, cold decode): 74.3 tok/s (pb2 24.0, which fails engaged mode)
  against TensorFold 1.1.8 at 163.8, -54.6%.
- Flash-Next (Qwen4) is not part of this comparison.

### Open items from the study

- Kapitsa must be re-pinned (its binary hash has changed) before its cells can count.
- The 50 cells with an unplanned r2 file need a decision, and then a re-audit.
- Pin one harness commit for the whole batch (B2 mixes two).
- Re-run the B1 pb2 round-time outliers at 32K and 64K turn-2.
- Run LM Studio or remove it from the manifest.
- Measure tool-chat decode over the real decode window (27-token replies make the current tok/s meaningless).

## History

- 2026-10-19 27B snapshot (TensorFold 1.1.0, llama.cpp b11721): [RELEASE_016 snapshot](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_016_BENCHMARKS_2026-10-19.md). Superseded by the 2026-11-04 to 2026-11-08 comparison above.
- 0.1.5 snapshot: [RELEASE_015 benchmarks](https://github.com/YuhuanStudio/Yunshu/blob/main/docs/reports/RELEASE_015_BENCHMARKS.md).


---

<!-- guides/cli -->
---
title: CLI reference
description: Every yunshu command, subcommand and option, with the global flags, JSON mode and exit codes.
---

The `yunshu` command starts and manages the server, and also works as a client for a running server. Run `yunshu --help` or `yunshu <command> --help` for the live help text; this page lists what each command does and the options it accepts.

## Global options

Global options go before the command name.

| Option | Meaning |
|---|---|
| `--url`, `-u` | Server URL used by commands that talk to a server. Default `http://localhost:8000`. Also read from the environment variable `YUNSHU_GATEWAY_URL`. |
| `--json` | Machine-readable output. A finite command prints one JSON result on stdout and sends progress and tables to stderr. Failures print `{"error": "..."}` and exit non-zero. |
| `--version`, `-V` | Print the version and exit. |

```bash
yunshu --json model list
yunshu --url http://localhost:8001 --json complete "Hello"
```

In `--json` mode, usage errors (an unknown option, a missing argument) are also reported as a JSON error object on stdout. Exit codes are not uniform: 2 is used for input and connectivity errors, 1 for failed operations. `yunshu doctor` exits 1 when a check fails.

Commands that call a server send `Authorization: Bearer <token>` when `YUNSHU_AUTH_TOKEN` is set in the CLI's own environment or config file.

## Command overview

| Group | Commands |
|---|---|
| Get started | `setup`, `doctor`, `pull`, `serve`, `service`, `chat`, `completion` |
| Server and models | `model` (alias `models`), `config`, `status`, `top`, `launch`, `cache` |
| Evaluate and diagnose | `statusline`, `eval`, `bench`, `diagnose` |
| Inference (calls a running server) | `complete`, `embed`, `tokenize`, `detokenize`, `rerank`, `classify`, `score`, `transcribe`, `speak`, `ocr`, `image`, `image-edit`, `image-variations`, `voices`, `cancel` |

## Get started

### `yunshu setup`

Choose a complete local model (from the models directory and the Hugging Face cache) or enter a Hugging Face MLX repository to download, then print the `yunshu serve` command to run. It does not start a server. It needs an interactive terminal; in `--json` mode or without a terminal it exits with an error listing the models it found and the next steps.

### `yunshu doctor`

Checks that this Mac can run Yunshu and prints a fix for each problem. See [Install](/docs/getting-started/install) for what it covers.

| Option | Meaning |
|---|---|
| `--model`, `-m` | Also check this model (path or repo id). Default: the `YUNSHU_MODEL` setting. |
| `--host` | Host you will serve on (for the port check). Default `127.0.0.1`. |
| `--port`, `-p` | Port you will serve on. Default `8000`. |
| `--no-metal` | Skip importing MLX and the GPU probe. |

Exit status is 1 when any check fails. `--json` returns `{version, ok, checks}`.

### `yunshu pull REPO_ID`

Download a Hugging Face model into the models directory. Also available as `yunshu model pull`.

| Option | Meaning |
|---|---|
| `--dir`, `-d` | Download under this directory. |
| `--revision`, `-r` | Branch, tag or commit. |
| `--force` | Download even if the model is already on disk (fetches missing or changed files only). |

See [Models](/docs/getting-started/models).

### `yunshu serve [MODEL]`

Start the inference server. The model may be given as the positional argument or with `--model`; giving two different values is an error. With neither a model nor a models directory configured, an interactive terminal prompts for a model; otherwise the command fails with next steps. A reference that matches a model in the models directory or the Hugging Face cache serves that local copy instead of downloading.

| Option | Meaning |
|---|---|
| `--model`, `-m` | Model path or Hugging Face id (single-model mode). |
| `--models-dir`, `-d` | Directory to scan for models (multi-model mode). |
| `--host`, `-h` | Bind host. Default `127.0.0.1`. A non-local host without a token prints a warning. |
| `--port`, `-p` | Bind port. Default `8000`. |
| `--uds` | Serve on this Unix domain socket instead of TCP; `--host` and `--port` are ignored. |
| `--workers`, `-w` | Number of worker processes. Default `1`. |
| `--max-memory` | Maximum GPU memory for models, for example `32GB`, or `disabled`. |
| `--auth-token` | Bearer token required on requests (setting `YUNSHU_AUTH_TOKEN`). |
| `--mcp-config` | Path to an MCP configuration file. |
| `--hf-endpoint` | Custom Hugging Face Hub endpoint. |
| `--http-proxy`, `--https-proxy`, `--no-proxy` | Proxy settings for downloads. |
| `--log-level` | `trace`, `debug`, `info`, `warning` or `error`. Default `info`. |
| `--startup-timeout` | Maximum seconds to wait for model loading. |
| `--slow-request-threshold` | Log a warning for requests slower than this many seconds. |
| `--drain-timeout` | Seconds to let in-flight requests finish on shutdown. |
| `--keep-alive-timeout` | Seconds to keep idle connections open (0 disables). |
| `--max-request-size` | Maximum request body size in bytes. |
| `--server-header` | Send `Server: Yunshu` in responses. |
| `--reload` | Auto-reload for development. |
| `--no-console` | Do not start the console process next to the engine. |
| `--console-port` | Port of the console process. Default `8100` (`YUNSHU_CONSOLE_PORT`). |
| `--config`, `-c` | TOML file of `YUNSHU_*` settings. |
| `--set KEY=VALUE` | Override any setting; the `YUNSHU_` prefix is optional. Repeatable. An unknown name is an error with the closest matches. |

Flags and `--set` have the highest precedence, above the environment and config file. Before loading, `serve` checks that the address can be bound and runs the same model check as `doctor`; a model that cannot load still lets the server start, and `GET /health/ready` reports why. With `--json`, a `starting` event is printed first and the process keeps running; readiness comes from `GET /health/ready`, not from that event. See [Configuration](/docs/guides/configuration) for every setting.

### `yunshu console`

Run the console process on its own: the web console and docs, a reverse proxy to the engine API, and the recorded history. It never loads MLX. `yunshu serve` starts one next to the engine; run this to watch an engine on another machine or to keep one running by hand.

| Option | Meaning |
|---|---|
| `--engine`, `-e` | Engine URL to watch and proxy to. Default `http://127.0.0.1:8000` (`YUNSHU_CONSOLE_ENGINE`). |
| `--host`, `-h` | Bind host. Default `127.0.0.1`. |
| `--port`, `-p` | Bind port. Default `8100`. |
| `--engine-token` | Bearer token for reading the engine (`YUNSHU_CONSOLE_ENGINE_TOKEN`, else `YUNSHU_AUTH_TOKEN`). |
| `--config`, `-c` | TOML file of `YUNSHU_*` settings. |
| `--no-history` | Do not record the metrics history or request log. |

### `yunshu service`

Run Yunshu at login with launchd, as two jobs: the engine and the console process (so the console keeps recording while the engine restarts). Subcommands: `install`, `uninstall`, `start`, `stop`, `restart`, `status`, `logs`, `rotate-logs`. Full options are on the [Service](/docs/getting-started/service) page.

`yunshu service logs` accepts `--follow`/`-f` and `--lines`/`-n` (default 50). `yunshu service install` accepts `--no-start` (write the agent without starting it); `--instance` and `--state-dir` (together) run an isolated development launchd label (`dev-*`). `yunshu console --static-dir DIR` serves a console build from a directory (development and tests).

### `yunshu chat`

Interactive terminal chat with a running server. Not available with `--json`.

| Option | Meaning |
|---|---|
| `--model`, `-m` | Model name. Default: the first model the server lists, preferring known chat families. |
| `--url`, `-u` | Server URL. Default `http://localhost:8000`. |
| `--system`, `-s` | System prompt. |
| `--temperature`, `-t` | Sampling temperature. Default `0.7`. |
| `--max-tokens` | Maximum output tokens. Default `2048`. |
| `--thinking` | Enable thinking mode. |
| `--no-stream` | Disable streaming. |

In the session: `/clear`, `/thinking`, `/model <name>`, `/help`, `/quit` (also `/exit`, `/q`).

### `yunshu completion SHELL`

Print a shell completion script for `zsh`, `bash` or `fish`. It does not edit your shell files.

```bash
mkdir -p ~/.zfunc
yunshu completion zsh > ~/.zfunc/_yunshu     # add ~/.zfunc to fpath before compinit
yunshu completion bash > ~/.yunshu-completion.bash
yunshu completion fish > ~/.config/fish/completions/yunshu.fish
```

## Server and models

### `yunshu model` (alias `models`)

| Subcommand | Purpose |
|---|---|
| `list` | List models on disk, or on a server with `--url`. Options: `--dir`/`-d`, `--hf-cache`/`--no-hf-cache`, `--url`/`-u`. |
| `pull REPO_ID` | Same as `yunshu pull`. |
| `info MODEL` (alias `show`) | Show type, size, file count and key `config.json` fields for a model name or path. |
| `rm MODEL` | Remove a downloaded model by exact name. `--yes`/`-y` skips confirmation (required with `--json`). |
| `load MODEL` | Load a model on the running server (`POST /v1/models/load`). |
| `unload MODEL` | Unload a model from the running server (`POST /v1/models/unload/{model_id}`). |
| `benchmark MODEL` | Run a local generation benchmark in-process (loads the model with mlx-lm, so it is for text models; it uses the GPU). Options: `--prompt-tokens` (128), `--max-tokens` (256), `--runs`/`-n` (3), `--warmup` (1). |

`load` and `unload` accept `--url`/`-u`.

### `yunshu config`

Show every stable setting with its effective value and source (`cli`, `env`, `file` or `default`), plus warnings and web search provider health.

| Option | Meaning |
|---|---|
| `--all`, `-a` | Include experimental and internal settings. |
| `--json` | Print JSON. |
| `--config`, `-c` | Also read this TOML file. |

Subcommands:

| Subcommand | Purpose |
|---|---|
| `config set KEY VALUE` | Save a setting in `~/.yunshu/config.toml` (or the file given with `--config`/`-c`). The key may omit `YUNSHU_`; values are validated. Path settings are stored as absolute paths. |
| `config unset KEY` | Remove a setting from the file. |
| `config path` | Print the user config file location. |

### `yunshu status`

Show server health, GPU and memory use, request counters and the models the server lists. Option: `--url`/`-u`. It exits with an error if the server cannot be reached.

### `yunshu top`

Like `status`, refreshed on a loop. Options: `--url`/`-u`, `--once` (print one snapshot and exit), `--interval` (seconds, default `2.0`, minimum `0.5`). With `--json` it returns one snapshot.

### `yunshu launch [TOOL]`

Configure an external coding tool for your server and start it. `TOOL` is `claude`, `codex`, `opencode`, `pi`, or `list` (the default) to show the tools and whether they are installed.

| Option | Meaning |
|---|---|
| `--model`, `-m` | Model to use. Default: the model the server serves. |
| `--url`, `-u` | Server URL. |
| `--api-key`, `-k` | API key to hand to the tool. |
| `--effort` | Claude Code reasoning effort (`low`, `medium`, `high`, ...). |
| `--statusline` / `--no-statusline` | Claude Code: show live engine state in its status line (default on) unless you already have your own. |
| `--dry-run` | Print the configuration instead of writing it and launching the tool. |

### `yunshu cache`

Inspect and clean the SSD prefix caches (only the ones that are enabled).

| Subcommand | Purpose |
|---|---|
| `status` | Size, cap and problems of each cache. Changes nothing. |
| `gc` | Find truncated, corrupt and old-format entries and orphaned temp files, stale namespaces, and entries over the size cap. Reports only, unless `--apply` is given. |

## Evaluate and diagnose

### `yunshu diagnose`

| Subcommand | Purpose |
|---|---|
| `gpu` | GPU and Metal capability details (uses MLX locally). |
| `server` | Check a running server's health and stats. Option: `--url`/`-u`. |
| `bundle` | Write a local diagnostics file: version, platform, package versions, settings with secrets redacted, the doctor checks, SSD cache state and recent error lines from the service log. It never includes prompts, completions or model weights and is never uploaded. Options: `--output`/`-o` (default `./yunshu-diagnostics-<time>.json`), `--host`, `--port`/`-p`. |

### `yunshu eval BENCHMARK`

Run an accuracy benchmark against a running server. `BENCHMARK` is one of `mmlu`, `gsm8k`, `hellaswag`, `truthfulqa`, `humaneval`, `arc`, `piqa`, or `all` to run each, or `list` (the default) to show them.

| Option | Meaning |
|---|---|
| `--url`, `-u` | Server URL. |
| `--model`, `-m` | Model to evaluate. |
| `--sample`, `-n` | Sample size (0 means the full dataset). |
| `--quick`, `-q` | Quick run with 50 samples. |

### `yunshu bench`

| Subcommand | Purpose |
|---|---|
| `roofline` | Matrix-multiply roofline on the local GPU. Options: `--min` (64), `--max` (8192), `--dtype` (`float16`), `--steps` (8). |
| `memory` | Show the Apple Silicon memory layout and MLX allocation. |
| `inference` | Local in-process generation benchmark. Options: `--model`/`-m` (path), `--prompt-len`, `--max-tokens`, `--requests`/`-n`, `--batch`/`-b`, `--warmup`. |
| `latency` | Latency against a running server. Options: `--url`/`-u`, `--model`/`-m`, `--prompt` (32 tokens), `--max-tokens` (64), `--requests`/`-n` (10). |
| `throughput` | Throughput against a running server. Options: `--url`/`-u`, `--model`/`-m`, `--concurrency`/`-c` (4), `--requests`/`-n` (20), `--max-tokens` (128). |

`roofline`, `memory` and `inference` run MLX locally and use the GPU; do not run them while a server is busy with real work.

### `yunshu statusline`

Print one line of engine status for a coding-agent status line: prefill progress, decode speed and prefix-cache hit of the request in flight, read from `GET /v1/yunshu/status`. When piped it reads Claude Code's session JSON on stdin. An unreachable server prints a short marker rather than failing. Options: `--url`/`-u`, `--api-key`/`-k` (or `YUNSHU_API_KEY`).

## Inference commands

These send one request to a running server (`--url`/`-u`, default `http://localhost:8000`). They are non-interactive and work with `--json`. The `--model`/`-m` option defaults to `local`, which is accepted in single-model mode.

| Command | Request | Notes |
|---|---|---|
| `complete PROMPT` | `POST /v1/chat/completions` | Options: `--max-tokens` (256), `--temperature`/`-t` (0.7), `--system`/`-s`. |
| `embed TEXT` | `POST /v1/embeddings` | Prints the dimension and the first values; `--json` returns the full vector. |
| `tokenize TEXT` | `POST /v1/tokenize` | Prints the token count; `--ids` returns the token ids. |
| `detokenize TOKEN...` | `POST /v1/detokenize` | Token ids to text. |
| `rerank QUERY DOC...` | `POST /v1/rerank` | `--top-n` limits results (0 returns all). |
| `classify TEXT LABEL...` | `POST /v1/classify` | Zero-shot classification over the given labels. |
| `score TEXT1 TEXT2` | `POST /v1/score` | `--type` is `cosine` (default), `dot` or `euclidean`. |
| `transcribe FILE` | `POST /v1/audio/transcriptions` | `--language`/`-l`; `--translate` uses `POST /v1/audio/translations`. |
| `speak TEXT` | `POST /v1/audio/speech` | Required `--out`/`-o` (.wav or .mp3); `--voice` (default `ethan`). |
| `voices` | `GET /v1/audio/voices` | Lists voices for `speak`. |
| `ocr FILE` | `POST /v1/ocr` | Extracts text from an image file. |
| `image PROMPT` | `POST /v1/images/generations` | Required `--out`/`-o`; `--model`/`-m` (default `Z-Image-Turbo-MLX-4bit`), `--size` (`1024x1024`), `--steps` (4). |
| `image-edit FILE PROMPT` | `POST /v1/images/edits` | Required `--out`/`-o`; `--model`/`-m`, `--steps`, `--strength` (0.8). |
| `image-variations FILE` | `POST /v1/images/variations` | Required `--out`/`-o`; `--model`/`-m`, `--steps`. |
| `cancel [REQUEST_ID]` | `POST /v1/cancel` | Cancel one generation, or all with `--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
```

Whether a request succeeds depends on the loaded model and installed extras; see [Model support](/docs/guides/model-support).

## Related

- [Quickstart](/docs/getting-started/quickstart)
- [Configuration](/docs/guides/configuration)
- [Troubleshooting](/docs/guides/troubleshooting)


---

<!-- guides/clients -->
---
title: Connecting clients
description: Point the OpenAI and Anthropic SDKs, curl, Open WebUI and coding agents at a local Yunshu server, and check that the server is healthy.
---

Yunshu speaks the OpenAI API under `/v1` and the Anthropic Messages API at `/v1/messages`. Anything that lets you set a base URL can use it.

| | Value |
|---|---|
| OpenAI base URL | `http://127.0.0.1:8000/v1` |
| Anthropic base URL | `http://127.0.0.1:8000` (the SDK appends `/v1/messages`) |
| API key | any string, unless the server has a token or API keys (then that credential) |
| Model name | single-model mode (`yunshu serve -m ...`): any name maps to the served model. Multi-model mode (`--models-dir`): use an id from `GET /v1/models` |

With `--auth-token`, the key is accepted as `Authorization: Bearer <token>` (OpenAI clients) or `x-api-key: <token>` (Anthropic clients). See [Authentication and API keys](/docs/guides/auth-and-keys).

<Callout type="warn">
`yunshu serve` binds `127.0.0.1` by default. To reach it from another machine or from a Docker container, start it with `--host 0.0.0.0 --auth-token <secret>`. Serving on a non-loopback host without a token prints a warning.
</Callout>

## Call the server

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

Streaming, tools, `response_format` (JSON schema), `stop`, `logprobs` and `seed` are supported; see [Chat Completions](/docs/api/chat-completions), [Responses](/docs/api/responses) and [Messages](/docs/api/messages). Thinking output of reasoning models streams separately from the answer, in `delta.reasoning_content`.

## Coding agents

<Tabs items={["Claude Code", "Codex, OpenCode, Pi", "Cline and Roo Code", "Continue"]}>
<Tab value="Claude Code">

Claude Code uses the 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>` writes the tool's configuration so it points at the running server. `yunshu launch list` shows which tools are installed.

</Tab>
<Tab value="Cline and Roo Code">

Choose the provider "OpenAI Compatible", base URL `http://127.0.0.1:8000/v1`, any key, model `local`.

</Tab>
<Tab value="Continue">

Add a model entry with `provider: openai`, `apiBase: http://127.0.0.1:8000/v1` and `model: local`.

</Tab>
</Tabs>

`yunshu launch claude` also sets the model's real context window and adds `yunshu statusline` (prefill progress, decode speed, last cache hit) to Claude Code's status line unless you have your own. Server-side `web_search` and `web_fetch`, the MCP connector and what each agent supports are in [Agents](/docs/guides/agents) and [Server tools](/docs/api/server-tools).

Agents send long, repeated prompts. The prefix cache reuses the shared part, so after the first turn only the new tokens are prefilled ([Prompt caching](/docs/guides/prompt-caching)).

## Open WebUI

<Steps>
<Step>

Start Yunshu so the container can reach it: `yunshu serve -m <model> --host 0.0.0.0 --auth-token <secret>`. This is needed only when Open WebUI runs in Docker.

</Step>
<Step>

In Open WebUI open Settings, then Connections, then OpenAI API.

</Step>
<Step>

Set the URL to `http://host.docker.internal:8000/v1` (Docker) or `http://127.0.0.1:8000/v1` (native), and the key to your secret.

</Step>
</Steps>

Yunmo, a separate consumer project, has an OpenAI-compatible `llm_adapter`: set its `base_url` to `http://127.0.0.1:8000/v1`.

## Check the server

| Endpoint | Auth | Use |
|---|---|---|
| `GET /health` | none | liveness and whether a model is loaded |
| `GET /health/ready` | none | 200 while running with a loaded model or registered on-demand models and with active GPU memory below 95% of unified memory; otherwise 503 |
| `GET /version` | none | installed Yunshu version |
| `GET /v1/models` | token if set | served models |
| `GET /metrics` | token if set | Prometheus metrics |

`yunshu status` prints the same from the command line.

## Related

- [Transports](/docs/guides/transports) for WebSocket and Unix socket access.
- [Web search](/docs/guides/web-search) and the [Tavily-compatible API](/docs/guides/tavily).
- [Decisions](/docs/api/decisions), [Evals](/docs/api/evals) and [Stored completions](/docs/api/stored-completions) (`store=True` with the regular OpenAI SDK).


---

<!-- guides/code-execution -->
---
title: Code execution
description: Turn on the Anthropic code_execution tool, which runs model-written commands on your Mac inside the sandbox-runtime, and learn its containers, files and limits.
---

The Anthropic `code_execution_20250522`, `_20250825`, `_20260120` and `_20260521` tools run on this machine, inside Anthropic's [sandbox-runtime](https://github.com/anthropics/sandbox-runtime) (`srt`). The feature is off by default. For how the sandbox is built, see [Code execution sandbox](/docs/internals/code-execution-sandbox).

## Turn it on

<Steps>
<Step>

Install the sandbox runtime. It needs Node 22.12 or newer, and `srt` is an optional dependency.

```bash
npm install -g @anthropic-ai/sandbox-runtime
```

</Step>
<Step>

Serve with code execution enabled:

```bash
yunshu serve -m <model> --set code_execution=1
```

</Step>
<Step>

Run `yunshu doctor` and look for the "code execution" row, which shows the `srt` version and a self-test.

</Step>
</Steps>

| Setting | Default | Meaning |
|---|---|---|
| `YUNSHU_CODE_EXECUTION` | `false` | Serve the tool. Off: a request that declares it gets a `400` naming this setting. On without `srt`: `503` (`api_error`) with the install command. A command never runs outside `srt`. |
| `YUNSHU_CODE_EXECUTION_ROOT` | `~/.yunshu/sandbox` | One sub-directory per container, mode 0700. |
| `YUNSHU_CODE_EXECUTION_TIMEOUT` | `60.0` s | Wall clock per call (also the CPU-time limit); then `execution_time_exceeded`. |
| `YUNSHU_CODE_EXECUTION_MEMORY_MB` | `2048` | Resident memory of the call's whole process group, sampled every 100 ms; above it the call is killed. |
| `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW` | unset | Comma-separated hosts the sandbox may reach (`example.com`, `*.example.com`, `host:443`). Unset: no network, loopback included. |
| `YUNSHU_CODE_EXECUTION_TTL_MIN` | `20.0` | Minutes a container may sit unused before it and its files are deleted. |

## Use it from the Messages API

Declare the tool in a [Messages](/docs/api/messages) request, with no beta header:

```json
{"type": "code_execution_20250825", "name": "code_execution"}
```

The model gets two sub-tools, `bash_code_execution` and `text_editor_code_execution` (`view`, `create`, `str_replace`). The response carries `server_tool_use` blocks and `bash_code_execution_tool_result` or `text_editor_code_execution_tool_result` blocks as in Anthropic's documentation. Streaming works the same way: the sub-tool input arrives as `input_json_delta` and each result block arrives whole in one `content_block_start`. The response also carries `container: {id, expires_at}` (in `message_delta.delta` when streaming).

- **Containers.** Pass `container: "<id>"` (or `{id}`) back to keep the working directory. An unknown or expired id is a `400`. A container is deleted after the idle TTL, and the total is capped at 2 GiB (oldest first).
- **Files.** `container_upload` content blocks copy a [Files API](/docs/api/files) file into the working directory. Every bash call gets a fresh `$OUTPUT_DIR`; its top-level files become Files API entries returned as `bash_code_execution_output {file_id}` (download with `GET /v1/files/{id}/content`).
- **Output limits.** stdout and stderr are each cut at 64 KiB (marked). A call whose stdout and stderr together exceed 1 MiB is killed (`output_file_too_large`). Background processes die with the call. The command sees only `PATH`, `HOME` (the container), `TMPDIR`, `OUTPUT_DIR` and locale variables, never the server's environment.

## Python, REPL state and programmatic tool calling

`20250522` offers one Python tool (`code_execution`, a fresh process per call). `20250825` offers bash and the text editor (plus Python, also fresh per call, when a client tool lists a code-execution caller in `allowed_callers`). `20260120` and `20260521` offer all three, and the Python process lives with the container: variables and imports persist between calls. It is killed and replaced cleanly on a timeout, a memory overrun, more than 1 MiB of output, 10 idle minutes, a container delete, or when more than four containers hold one.

A client tool with `"allowed_callers": ["code_execution_20260120"]` becomes an `async` Python function in the interpreter. When the code awaits it, the turn ends with `stop_reason: "tool_use"` and one `tool_use` block per call, each with `caller: {type, tool_id}`. Send the results back (with the `container`) and the response continues with the `code_execution_tool_result`. The cell waits 270 seconds for the answer; one cell may make 256 calls.

## OpenAI Responses and containers

With the same setting, a [Responses](/docs/api/responses) request can declare `{"type": "code_interpreter", "container": {"type": "auto"}}` (or a `cntr_` id) and the hosted `{"type": "shell", "environment": {"type": "container_auto"}}`. The response has `code_interpreter_call`, `shell_call` and `shell_call_output` items, the matching streaming events, and `container_file_citation` annotations for files the code made. They also work in background mode. The containers have the OpenAI containers API (`/v1/containers`, with files); `expires_after`, `memory_limit` and `network_policy` can only narrow the settings above. See [Server tools](/docs/api/server-tools).

## What the sandbox allows

- **Writes:** the container directory only.
- **Reads:** `/Users`, `/Volumes`, `/home` and the container root are denied; only this container and the Python interpreter's prefix are allowed back. Your home, keys, `~/.yunshu` and other containers are unreadable.
- **Network:** none unless listed. Loopback is never reachable, and allowed names cannot resolve into private ranges.
- **Other:** Unix sockets, Apple Events and `open` are off.

Violations are logged as metadata (container id, return code, byte counts); commands, output and file contents are never logged.

<Callout type="warn">
An allowed domain list does not inspect traffic. Allowing a broad host such as `github.com` can still leak data, so keep the list short.
</Callout>

## Differences from Anthropic's container

- macOS, not Linux x86_64. The Python is the interpreter Yunshu runs on (standard library only, no pandas or numpy).
- No Content Credentials.
- No Content Credentials, container skills or OpenAI `programmatic_tool_calling`.
- The sandbox runs under macOS `sandbox-exec`, which Apple marks deprecated, and `srt` is a 0.0.x release (tested: 0.0.81).


---

<!-- guides/configuration -->
---
title: Configuration
description: Every YUNSHU_* setting, its type and default, generated from the settings registry.
---

Every Yunshu setting is a `YUNSHU_*` name registered in
`python/yunshu_engine/settings.py`, with one type, one default and one parse
rule. Nothing else reads `YUNSHU_*` environment variables.

## Where values come from

Highest precedence first:

1. `yunshu serve` flags and `--set KEY=VALUE` (repeatable; `KEY` with or
   without the `YUNSHU_` prefix, e.g. `--set mtp_block_size=4`),
2. the process environment,
3. a TOML config file: `yunshu serve --config yunshu.toml` or
   `YUNSHU_CONFIG=yunshu.toml`,
4. the default listed below.

The config file holds `KEY = value` pairs, flat or grouped under any tables
(table names are ignored; keys may be short or full names):

```toml
model = "~/models/Qwen3.8-27B-4bit"

[server]
default_max_tokens = 1024

[voice]
YUNSHU_REALTIME_SILENCE_MS = 400
```

Booleans accept `1/true/yes/on` and `0/false/no/off`. A value that does not
parse is a startup error listing every bad setting. A `YUNSHU_*` name that is
not registered is ignored with a warning naming the closest registered
setting.

`yunshu config` prints the effective value of every stable setting and its
source (`cli`, `env`, `file`, `default`); `--all` adds experimental and
internal ones, `--json` prints JSON, `--config FILE` includes a config file.

## When a change applies

Each setting is classified from where the code reads it (`Applies` column):

- **live**: re-read on every use; a change applies at once.
- **reload**: read when a model, runner or connection is built; applies on the
  next model load.
- **restart**: read once at startup; applies after a restart.

The console writes settings with `PATCH /v1/yunshu/config`, which saves to the
config file and answers `applied` / `needs_reload` / `needs_restart` per
setting. A `YUNSHU_*` environment variable or `--set` value set at launch
still wins at runtime (reported as `overridden`).

## Stability

- **stable**: supported deployment settings.
- **experimental**: temporary. Each names the measurement that decides it and
  when it was added; once measured, the winner becomes the default and the
  flag and losing code path are deleted. At most 8 exist at a time.
- **internal**: debugging aids.

The descriptions below come straight from the settings registry and are in English in every language.

## Stable settings

### 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). |

## Experimental settings

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

## Internal settings

| 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: Debugging and observability
description: One switch turns on the debug routes, host telemetry, serve log, audit log, token ids and generation capture; the console then shows every panel and compares the engine's request state with what it displays.
---

`yunshu serve --observe` (or `YUNSHU_OBSERVE=1`) turns on every observability feature you did not set yourself. Use it for any engine you want to supervise: problems show up in the engine's own numbers instead of being guessed from a page.

## What it turns on

| Setting | Under observe | What it costs |
| --- | --- | --- |
| `YUNSHU_DEBUG_ROUTES` | on: the `/debug/*` routes (engine, system, requests, kv-cache, spec-decode, memory) | Reads only; nothing on the decode path |
| `YUNSHU_TELEMETRY` | `on` (the sampler's only mode; 1 Hz) | A small, consistent follow-up TTFT cost: +1.8% (about 11 ms) at 1K prose on 27B, decode identical within noise; see [Host telemetry](/docs/guides/telemetry) |
| `YUNSHU_SERVE_LOG` | on, in `~/.yunshu/logs` | One numbers-only JSON line per finished request, size-capped and rotated |
| `YUNSHU_AUDIT_LOG_FILE` | `~/.yunshu/logs/audit.log` | One line per audited operation |
| `YUNSHU_REPLAY_TOKEN_IDS` | on: exact `token_id` in requested logprobs | A few bytes per logprob token |
| `YUNSHU_DEBUG_STREAM_CAPTURE` | `~/.yunshu/logs/stream_capture.jsonl` | One JSON line per generation (token ids and text pieces); grows without bound, so clear it when you are done |

A value you set yourself always wins, whatever its source (flag, environment, config file), and `yunshu config` shows the others with source `observe`. Keep observe off for speed benchmarks: telemetry is a measurable cost, and speed numbers taken with it on are not comparable with numbers taken with it off.

## Who may read `/debug/*`

The same rule as before: the token (`YUNSHU_AUTH_TOKEN`) or `YUNSHU_AUTH_DISABLED`. Under observe, an engine **without** a token also answers `/debug/*` to clients on this Mac (loopback) only; a request from the network, or one that carries a proxy header such as `X-Forwarded-For`, is refused. With a token set, the token is always required. Never expose `/debug` on `0.0.0.0` without one.

## In the console

When the attached engine reports observe mode (`observe: true` in `/v1/yunshu/status`):

- Diagnostics shows every group (host, requests, KV and prefix cache, decode, memory) and says that observe mode is on; if `/debug` cannot be read it says so instead of showing nothing.
- The Requests page opens its **Debug data** section. For each in-flight request it shows, one above the other, what the page displays and what the engine's `/debug/requests` reports: phase, prefill progress in tokens, generated tokens, and the admit and first-token times. A value that disagrees is marked red; a request `/debug` does not know is greyed. The switch hides the section; your choice is remembered in this browser.
- The speculation panel and the host panel read their counters from the same routes.

## Harnesses

`tfbench`, the agentic runner and `conc_probe` start or require an observing engine (`TFB_OBSERVE=0` and `AGENTIC_OBSERVE=0` keep a pure timing run clean; `conc_probe` refuses an engine that does not report observe unless `--allow-no-observe`). `yv` runs `smoke`, `identity` and `apc` with observe on and the timing stages with it explicitly off; `yv ab --observe` turns it on everywhere, and the run's `state.json` records which stages used it.


---

<!-- guides/features -->
---
title: Feature index
description: Every Yunshu feature in one table per area, with its status and the documentation page that covers it.
---

This index lists every shipped feature by area. Each row names the feature, what it does, its status and where the docs cover it. The list is generated from the repository feature index (`docs/feature_index.json`), which a test keeps in step with the documentation.

| Status | Meaning |
|---|---|
| Stable | Works as described and is covered by tests or gates |
| Partial | Works for the scope named in the summary; the rest is not implemented or not verified |
| Experimental | Behind an experimental setting; may change or be removed |

## Inference

| Feature | What it does | Status | Docs |
|---|---|---|---|
| Lossless speculative decoding | DFlash2, MTP and prompt-copy drafting with batch-invariant kernels; greedy output equals speculation off | Stable | [Speculative decoding](/docs/internals/speculative-decoding) |
| Text-model speculation | n-gram / suffix and Gemma 4 assistant drafting for mlx-lm models (an external draft model is a separate non-identical option) | Stable | [Speculative decoding](/docs/internals/speculative-decoding), [Options](/docs/guides/options) |
| Prefix cache (APC) | exact hybrid checkpoints in RAM, SSD and optional storage tiers; image and audio keys | Stable | [Prefix cache internals](/docs/internals/prefix-cache), [Prompt caching](/docs/guides/prompt-caching) |
| Structured output | JSON schema, regex, choice and grammar enforced during decoding, including tool arguments | Stable | [Structured output](/docs/guides/structured-output), [Constrained decoding internals](/docs/internals/constrained-decoding) |
| Lossy memory options | int8 KV, compressed WARM tier and load-time quantization; off by default | Stable | [Options](/docs/guides/options), [Memory accounting](/docs/internals/memory), [Configuration](/docs/guides/configuration) |
| Large MoE loading (partial) | bits and group size derived from tensor shapes for community DeepSeek-V4-Flash packs; fit check before loading | Partial | [Model support](/docs/guides/model-support) |
| Round driver (experimental) | own speculative round driver for dense Qwen3.5-family models | Experimental | [Round driver](/docs/developers/round-driver) |
| Model support | what is tuned, generic and validated, per family | Stable | [Model support](/docs/guides/model-support) |
| Next-turn rehearsal | Canonical stride APC rehearsal after eligible text replies; boundary/exact are explicit numeric-changing opt-ins | Stable | [Prefill and rehearsal](/docs/internals/prefill-and-rehearsal) |
| Multi-row speculation | Every request is a round-driver row; concurrent rows draft together (MTP chains, DFlash2 drafts sharing a verify budget) | Stable | [Speculative decoding](/docs/internals/speculative-decoding) |

## APIs

| Feature | What it does | Status | Docs |
|---|---|---|---|
| OpenAI API | Chat, Completions, Responses (HTTP and WebSocket), Embeddings, Models, Files, Batches, Conversations | Stable | [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, documents and citations | Stable | [Messages](/docs/api/messages), [Batches](/docs/api/batches) |
| Ollama API | /api/chat, /api/generate and native model management (pull, copy, delete, show) | Stable | [Ollama](/docs/api/ollama) |
| Responses extras | client-executed computer tool, conversations, compaction, previous_response_id | Stable | [Responses](/docs/api/responses) |
| Stored chat completions | store: true, then list, retrieve, update, delete and list messages | Stable | [Stored completions](/docs/api/stored-completions) |
| Evals | OpenAI Evals API with string-check, similarity and local model graders | Stable | [Evals](/docs/api/evals) |
| Typed decisions | yes/no, choice and score answers with probabilities in one forward pass, no text generation | Stable | [Decisions](/docs/api/decisions) |
| Batches, Files and tokenizer | OpenAI and Anthropic batches, Files API, tokenize / detokenize / apply-template / props | Stable | [Batches](/docs/api/batches), [Files](/docs/api/files), [Tokenization](/docs/api/tokenization) |
| Transports | SSE, WebSocket streams, Unix socket, HTTP/2, optional WebRTC | Stable | [Transports](/docs/guides/transports) |
| Yunshu extensions | request ids, live phases, prefill progress, cancel, deadlines, x_yunshu stats, warmup, memory units | Stable | [Extensions](/docs/api/extensions) |
| Prompt-caching APIs | cache_control and cached-token accounting across the three dialects | Stable | [Prompt caching](/docs/guides/prompt-caching) |

## Agents & tools

| Feature | What it does | Status | Docs |
|---|---|---|---|
| Coding agents | Claude Code, Codex and opencode through their own APIs; `yunshu launch` | Stable | [Agents](/docs/guides/agents), [Agent compatibility](/docs/developers/agent-compat) |
| Web search and fetch | server-side web_search / web_fetch with citations; DuckDuckGo, Wikipedia, SearXNG, Tavily, Serper, Perplexity | Stable | [Web search](/docs/guides/web-search), [Server tools](/docs/api/server-tools) |
| Code execution | Anthropic code_execution (bash + text editor) run locally inside the sandbox-runtime; opt-in, no network by default | Partial | [Code execution](/docs/guides/code-execution), [Code execution sandbox](/docs/internals/code-execution-sandbox) |
| Tavily-compatible API | search, extract, crawl, map, research and MCP, with provider health backoff | Stable | [Tavily](/docs/guides/tavily) |
| MCP | native MCP endpoint, and remote MCP servers named in a request | Stable | [MCP](/docs/api/mcp) |
| Client setup | curl, OpenAI and Anthropic SDKs, Open WebUI | Stable | [Clients](/docs/guides/clients) |
| Qualified auxiliary scheduling | Captured opencode title fingerprints yield to interactive VLM turns with APC isolation; unknown requests retain normal priority | Stable | [Auxiliary scheduling](/docs/developers/auxiliary-scheduling) |

## Multimodal

| Feature | What it does | Status | Docs |
|---|---|---|---|
| Image, audio and video input | mlx-vlm models take media in Chat, Responses and Messages; media enters the cache key | Stable | [Multimodal](/docs/guides/multimodal) |
| Speech-to-speech (partial) | Qwen3-Omni native speech; repeated-image and audio APC have scoped parity receipts; combined image+audio reuse is unverified | Partial | [Multimodal](/docs/guides/multimodal), [Realtime](/docs/api/realtime) |
| Realtime voice | WebSocket and optional WebRTC, server VAD, barge-in, ephemeral client secrets, local voices | Stable | [Realtime](/docs/api/realtime) |
| Speech to text, text to speech | transcriptions, translations, speech and voices | Stable | [Audio](/docs/api/audio) |
| OCR and image generation | GLM-OCR text extraction; image generations, edits and variations | Stable | [OCR](/docs/api/ocr), [Images](/docs/api/images), [Multimodal](/docs/guides/multimodal) |
| Embeddings, rerank, score, classify | text and multimodal embeddings, cross-encoder rerank, trained classification heads | Stable | [Embeddings](/docs/api/embeddings), [Rerank](/docs/api/rerank) |

## Operations & console

| Feature | What it does | Status | Docs |
|---|---|---|---|
| Web console | live request phases, history, logs, models, downloads, cache, playground, keys, settings, status island | Stable | [Console](/docs/getting-started/console) |
| Console process and recorded history | the console runs apart from the engine (yunshu console, port 8100, no MLX): usable while the engine is down, 1 s / 10 s / 1 min history for 30 days and a metadata-only request log, outages kept as gaps | Stable | [Console process](/docs/internals/console-process) |
| Console follows engines automatically | yunshu console --engine auto probes local ports (GET /health), follows the newest live Yunshu engine, keeps it while healthy, lets you pin one from the status island, and shows waiting for an engine instead of an error; history records each engine start as its own session | Stable | [Console](/docs/getting-started/console), [Console process](/docs/internals/console-process) |
| API keys and quotas | several keys with scopes, expiry, per-key usage and daily quotas | Stable | [Auth and keys](/docs/guides/auth-and-keys) |
| Settings and CORS editor | write engine settings (restart-required ones prompt) and edit CORS from the console or API | Stable | [Auth and keys](/docs/guides/auth-and-keys), [Console](/docs/getting-started/console) |
| Host telemetry | power, GPU clock, temperatures, thermal and memory pressure, per-request energy estimate, Prometheus | Stable | [Telemetry](/docs/guides/telemetry) |
| Command line | setup, doctor, models list/pull/rm/show, top, service, completions and inference commands | Stable | [CLI](/docs/guides/cli) |
| Login service | launchd agent, restart and logs | Stable | [Login service](/docs/getting-started/service) |
| Configuration | one settings registry: environment, TOML file or `--set` | Stable | [Configuration](/docs/guides/configuration) |
| Security | auth token, CORS credentials rule, redirect header stripping, secret redaction, SSRF guard | Stable | [Auth and keys](/docs/guides/auth-and-keys) |
| First run and troubleshooting | install, choose a model, readiness checks, fixes | Stable | [Install](/docs/getting-started/install), [Quickstart](/docs/getting-started/quickstart), [Troubleshooting](/docs/guides/troubleshooting) |
| Benchmarks and accuracy | where each number comes from, how to reproduce it, accuracy gates | Stable | [Benchmarks](/docs/guides/benchmarks) |
| Model lifecycle controls | Authenticated load/download cancellation, local and Hugging Face snapshot registration, and unload impact | Stable | [Console](/docs/getting-started/console) |


---

<!-- guides/model-support -->
---
title: Model support
description: Which model families and modalities Yunshu serves, and which serving path and optional extra each one uses.
---

Yunshu loads MLX checkpoints. It detects what kind of model a folder holds from its files and `config.json`, then picks an engine for it. Being loadable upstream (in `mlx-lm`, `mlx-vlm` or `mlx-audio`) does not certify every Yunshu endpoint or feature for that model. The model card that `GET /v1/models` returns for each model (under the `yunshu` field of each item) describes what the loaded model can do; check it before relying on tools, structured output, logprobs or media input.

## Support tiers

| Tier | Models | What it means |
|---|---|---|
| Tuned | Qwen3.8-27B (the first fully tuned checkpoint) | Speculative decoding, prefix reuse and the batch-invariant decode path are developed and measured on it. |
| Tier 1 | The Qwen3.5 family (`qwen3_5`, `qwen3_6`, `qwen3_5_moe` model types) | Speculative decoding (MTP or a matching drafter) and prefix caching. |
| Generic text | Other `mlx-lm` models | Served by the text fast path. Upstream support is the limit. |
| Generic vision-language | Other `mlx-vlm` models | Served by the VLM batch runner. Model-specific media, template and capability limits apply. |
| Other modalities | Speech, embeddings, ranking, OCR, image generation | Available through their own engines and optional extras; see below. |

## Serving paths

| Path | Used for | Behavior |
|---|---|---|
| VLM batch runner | Every model served through `mlx-vlm`, including the Qwen3.5 / 3.6 / 3.8 family when it is loaded with the `vision` extra | Continuous batching of rows with per-request sampling; each prompt is prefilled in atoms on its row's own caches. Automatic prefix cache for families with a restorable checkpoint (including scoped exact-window support), keyed also on image and audio features, with an optional SSD tier. Accepts image, audio and video input. |
| Speculative drafting (Qwen3.5 family and Flash-Next) | `qwen3_5`, `qwen3_6`, `qwen3_5_moe`, Qwen4 | MTP or DFlash drafting on the round driver's packed rows, using batch-invariant decode and verify kernels so that output with drafting on matches output with drafting off. `YUNSHU_MTP` (default on) and `YUNSHU_VLM_DRAFT` control it. Concurrent rows draft together. |
| Text fast path | Text-only `mlx-lm` models | One request at a time through `mlx-lm`; concurrent requests are served one after another. |

Limits of the VLM path: LoRA adapters and custom logits processors are rejected for vision-language models. Which speculative path will be used for a Qwen3.5-family model is shown by `yunshu doctor -m <model>` (the `speculative` row) and by the startup log.

## Modalities and the routes that use them

Detection runs on the model folder. The extra column names the optional install extra from [Install](/docs/getting-started/install) that the engine needs.

| Model kind | Examples of detected types | Routes | Extra | Status |
|---|---|---|---|---|
| Text LLM | Any `mlx-lm` model type | `POST /v1/chat/completions`, `POST /v1/completions`, `POST /v1/responses`, `POST /v1/messages` | none | <Support status="supported">supported</Support> |
| Vision-language | `vision_config` models such as Qwen-VL, Pixtral, Mistral 3 and the Qwen3.5 family | The same chat routes, with image parts | `vision` | <Support status="supported">supported</Support> |
| Speech-to-text | `whisper`, `qwen3_asr`, `parakeet`, `qwen2_audio` | `POST /v1/audio/transcriptions`, `POST /v1/audio/translations` | `audio` | <Support status="supported">supported</Support> |
| Text-to-speech | `qwen3_tts`, `kokoro`, `chatterbox` | `POST /v1/audio/speech` | `audio` | <Support status="supported">supported</Support> |
| Native speech-to-speech | Qwen3-Omni (a model with a Talker) | `POST /v1/omni/speech/stream`, and the Realtime sockets | `omni` | <Support status="partial">partial</Support> |
| OCR | Models whose type or name contains `ocr` | `POST /v1/ocr` | `vision` | <Support status="supported">supported</Support> |
| Embeddings | `mlx-embeddings` models, EmbeddingGemma 2, Qwen3-VL-Embedding | `POST /v1/embeddings` | `embeddings` | <Support status="supported">supported</Support> |
| Reranking and scoring | Cross-encoder rerankers, sequence-classification heads | `POST /v1/rerank`, `POST /v1/classify`, `POST /v1/score` | depends on the model (`embeddings` or `vision`) | <Support status="supported">supported</Support> |
| Image generation | `flux`, `sd3`, `sdxl`, `z_image` | `POST /v1/images/generations`, `POST /v1/images/edits`, `POST /v1/images/variations` | `generation` | <Support status="supported">supported</Support> |
| Typed decisions | Clef / Clef-flash joint schema heads | `POST /v1/decisions` | `vision` | <Support status="partial">partial</Support> |
| Video generation | Wan, LTX and similar | none | | <Support status="unsupported">not supported</Support> |
| Standalone speech-to-speech | Voice conversion, speech enhancement models | none | | <Support status="unsupported">not supported</Support> |

Notes on the partial rows:

- **Native speech-to-speech** works when the served model has a Talker (Qwen3-Omni). The voice path then reuses the already loaded model instead of loading a second copy. It is switched off for other models, or with `YUNSHU_REALTIME_OMNI=off`, in which case Realtime falls back to speech-to-text, then the LLM, then text-to-speech. Large Omni checkpoints need a lot of unified memory.
- **Typed decisions** accept only the Clef joint schema head. Other decision-head families are rejected, and a chat model sent to the decision route returns an error.

A model that is detected as video or standalone speech-to-speech fails to load with a message saying so, and image, audio and LLM models are listed as the supported kinds. When extras are missing, the related routes report the missing dependency instead of returning placeholder output (for example `POST /v1/images/generations` returns 503 without the `generation` extra).

## Single-model and multi-model serving

`yunshu serve -m <model>` serves one model and treats the `model` field of a request as advisory. `yunshu serve --models-dir <dir>` registers every model it finds and loads them on demand; the engine type (text, vision, audio, image, decision) is chosen per model by the detection above. See [Models](/docs/getting-started/models).

## Validating a model

Check a checkpoint before depending on it:

1. `yunshu doctor -m <model>` checks that the folder is complete and fits in memory.
2. Read the model's entry in `GET /v1/models` for its capabilities.
3. Send a request for each feature you rely on (tools, JSON schema, streaming, stop sequences, logprobs, cancel) against the running server.

Support in this table describes what the code handles. It is not a promise that every checkpoint of a family works with every feature.

## Qwen3.8-Flash-Next under 80 GB (qwen4_exp)

Default Flash-Next checkpoint (2026-11-09): `Jundot/Qwen3.8-Flash-Next-oQ2.5e-mtp` (77 GB on disk, PLE read from the SSD), chosen for the smaller footprint and more concurrent headroom. `Jundot/Qwen3.8-Flash-Next-oQ3e-mtp` (86 GB) stays a supported higher-precision alternative.

`Jundot/Qwen3.8-Flash-Next-oQ4e-mtp` is 106 GB on disk, of which 32 GB is the per-layer n-gram embedding (PLE). Yunshu reads PLE rows from the SSD instead of loading the table, which leaves 74.3 GB of resident weights (the 1.5 GB MTP head included).

1. Build the external-PLE view once (hard links, nothing is copied, the original pack is untouched; source and view must be on the same volume): `python scripts/research/flashnext80_prepare_view.py <pack> <pack>-ple-ssd`.
2. Serve the view: `YUNSHU_MAX_MEMORY_GB=74.5 yunshu serve -m <pack>-ple-ssd`. The MTP head is used automatically (one draft per round); the APC SSD tier is on by default.

With a memory ceiling set, Yunshu keeps the freed-buffer pool at 0.5 GiB and leaves the vision tower unloaded until the first image request. Both are lossless; set `YUNSHU_PREFILL_BUFFER_CACHE_GB` to override the pool.

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

| Context (M5 Max 128 GB, MTP on, whole-system memory delta) | Steady | Cold-prefill peak | Decode |
|---|---:|---:|---:|
| 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 (before the fused kernels) |
| about 169K, SSD APC hit (second request) | 75 GB | 81 GB | 22 tok/s, first token in 1.2 s |
| about 169K, cold | 75 GB | 84-85 GB | 21 tok/s |

A cold prefill beyond roughly 32K needs about 83-85 GB at its peak (the extra is prefill working memory); the same prompt served from the SSD prompt cache stays near 81 GB. Output is identical with speculation on and off and with a prompt-cache hit or miss. Decode uses fused hyper-connection and router/expert Metal kernels (derived from TensorFold, Apache-2.0), 65 tok/s without speculation at 1K and 55 at 8K; MTP adds 8% at 1K and 20% at 8K because every extra verify row reads more experts. Thinking-mode MMLU-Pro (300 questions, greedy): 261/300 = 0.870 (0 parse failures; the 27B oQ4e gate protocol gives 0.833).

## Related

- [Structured output](/docs/guides/structured-output)
- [Prompt caching](/docs/guides/prompt-caching)
- [CLI reference](/docs/guides/cli)
- [Troubleshooting](/docs/guides/troubleshooting)


---

<!-- guides/multimodal -->
---
title: Multimodal and retrieval endpoints
description: Which routes serve images, audio, video, speech, Realtime voice, OCR, image generation, embeddings and rerank, which extras they need, and where the limits are.
---

Optional extras install the dependencies: `pip install 'yunshu[audio]'`, `[vision]`, `[generation]`, `[embeddings]` and `[omni]`. Each route needs a model that supports it; `GET /v1/models` says which. Request shapes live in the API reference pages linked below.

<Callout type="info">
Speech, ASR, TTS, image generation and OCR are supported capabilities, not the tuned path. Features differ per checkpoint and are verified per model: see [Model support](/docs/guides/model-support).
</Callout>

## Routes

| Capability | Route | Extra | Notes |
|---|---|---|---|
| Images, audio and video as chat input | `/v1/chat/completions`, `/v1/responses`, `/v1/messages` | none (mlx-vlm models) | media enters the prefix-cache key |
| Qwen3-Omni speech to speech | `POST /v1/omni/speech/stream` | `omni` | text and audio out; `examples/talk.py` |
| Realtime voice | `WS /v1/realtime` (and `/realtime`) | `audio` | server VAD, barge-in, native omni speech or an ASR, LLM, TTS cascade. See [Realtime](/docs/api/realtime) |
| Speech to text | `/v1/audio/transcriptions`, `/v1/audio/translations` | `audio` | translation needs a Whisper model. See [Audio](/docs/api/audio) |
| Text to speech | `/v1/audio/speech`, `GET /v1/audio/voices` | `audio` | local voice enrollment from audio samples for reference-audio models |
| OCR | `POST /v1/ocr` | `vision` | GLM-OCR; `yunshu ocr`; also in the console; [OCR API](/docs/api/ocr) |
| Image generation, editing, variations | `/v1/images/generations`, `/edits`, `/variations` | `generation` | `yunshu image`, `image-edit`, `image-variations`. See [Images](/docs/api/images) |
| Embeddings | `POST /v1/embeddings` | `embeddings` | text and, for supported models, image, audio and video. See [Embeddings](/docs/api/embeddings) |
| Rerank, score, classify, pooling | `/v1/rerank`, `/v1/score`, `/v1/classify`, `/v1/pooling` | `embeddings` | cross-encoder rerank and trained classification heads, vLLM semantics. See [Rerank](/docs/api/rerank) |
| Typed decisions | `/v1/decisions`, `/v1/systemone` | none | See [Decisions](/docs/api/decisions) |

## Try it from the command line

<Steps>
<Step>

Serve a model that supports the capability, for example a TTS model for `speak`.

</Step>
<Step>

Run the matching command:

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

For Realtime over WebSocket or WebRTC see [Transports](/docs/guides/transports). Ephemeral client secrets come from `POST /v1/realtime/client_secrets`.

## Limits

- Realtime transcription-only session configuration is echoed but not executed as a transcription-only session.
- Prefix reuse depends on the cache layout. Gemma 4 has scoped exact-window restore receipts; do not infer support for every rotating-cache model.
- Qwen3-Omni repeated-image prefix reuse has scoped hit and miss parity receipts; combined image and audio cache reuse is unverified. See [Model support](/docs/guides/model-support).


---

<!-- guides/options -->
---
title: Options that can change output
description: The opt-in settings whose output is not guaranteed identical to the default path, and the rule that separates them from lossless defaults.
---

Yunshu's rule is simple: a **lossless** optimization (same tokens as the plain path) may become the default; a **lossy or non-identical** one is a stable user option that is off by default, and a benchmark never turns it on for you. This page lists every such option. Defaults are in the settings registry (`python/yunshu_engine/settings.py`); effective values are shown by `yunshu config`. For the full table of settings see [Configuration](/docs/guides/configuration).

<Callout type="warn">
The two options in the first section (`YUNSHU_SPEC_UNVERIFIED`, `YUNSHU_DRAFT_MODEL`) are stable options, not experiments, but they are **not guaranteed to produce the same tokens as the default path**. Turn one on only if you accept that output can differ from plain decoding. Each has its own constraints below.
</Callout>

## Non-identical serving options

Both apply to text-only `mlx-lm` models. The Qwen3.5-family VLM runner has its own lossless speculation (MTP, DFlash) and does not use them. See [Speculative decoding](/docs/internals/speculative-decoding).

| Setting | Default | What it does |
|---|---|---|
| `YUNSHU_SPEC_UNVERIFIED` | `''` (off), or `eagle` | Enables speculative decoding with an external `mlx-lm` draft model on text models |
| `YUNSHU_DRAFT_MODEL` | unset | Path of the draft checkpoint used by `YUNSHU_SPEC_UNVERIFIED=eagle` |

### External draft model (`YUNSHU_SPEC_UNVERIFIED` and `YUNSHU_DRAFT_MODEL`)

`YUNSHU_SPEC_UNVERIFIED=eagle` loads a second, smaller `mlx-lm` checkpoint named by `YUNSHU_DRAFT_MODEL` (`_init_external_lm_spec` in `python/yunshu_engine/batched_engine.py`) and drafts with it. If `YUNSHU_DRAFT_MODEL` is unset the engine looks for a `draft_model_path` in the model config; with neither, nothing is loaded, and an unset switch never loads a second model.

- `eagle` is a historical route name. An ordinary language model works as the draft; no trained EAGLE head is needed.
- The route is taken only for greedy (temperature 0 or unset), non-streaming requests that ask for speculation or default to it, with default sampling and penalties. Schema or grammar constraints, custom logits processors, stop strings, thinking budgets, LoRA and token-mask options keep the regular fast path, and so do logprob requests.
- Output is not guaranteed to be token-identical to plain decode. The registry records that a check on 2026-10-24 differed on every prompt it tried, and that speed ranged from slower to faster depending on the prompt; no figure from it is quoted here, because it is not in the benchmark log.
- Use it when you have a well-matched small draft for a large text model and prefer speed over exact reproducibility. For lossless speculation use n-gram or suffix drafting (`YUNSHU_NGRAM_DEFAULT`, `YUNSHU_SPEC_PROPOSER`) or the Qwen3.5-family runner.

## Lossy memory options

These trade quality for memory or disk. All are off by default (a lossless value is the default). A lossy option never becomes a default because of a benchmark.

| Setting | Lossless default | Lossy value | Effect |
|---|---|---|---|
| `YUNSHU_KV_PRECISION` | `bf16` | `int8` | int8 KV for Qwen3.5-family rows on the packed layer; less memory and bandwidth, small attention error. Flash-Next and generic-layer models stay bf16 |
| `YUNSHU_KV_QUANT_BITS` | `off` | `auto`, `2`, `3`, `4`, `8` | Quantized KV cache on the text engine |
| `YUNSHU_PREFIX_HOT_LIMIT` | `0` (all full precision) | a count | Keeps that many prefix KV entries at full precision and stores older ones 4-bit in RAM; lossy on reuse |
| `YUNSHU_SSD_CACHE_PRECISION` | `native` | `int8` | Text SSD prefix cache stored as per-tensor int8; lossy on reuse |
| `YUNSHU_VLM_APC_WARM` | `off` | `int8`, `int4` | Compressed WARM prefix tier; a hit restores dequantized K/V, so output can differ from a cold prefill. `lossless` is exact |
| `YUNSHU_QUANT_MODE` | `''` (keep checkpoint) | `mxfp4`, `nvfp4`, `mxfp8`, `affine` | Quantizes weights in memory at load |

`YUNSHU_QUANT_CONFIG` sets bits and group size for `affine`. Memory accounting is in [Memory accounting](/docs/internals/memory).

## The rule

| Kind | Examples | May become the default? |
|---|---|---|
| Lossless (same output) | layouts, kernels, schedulers, batch-invariant speculation, lossless cache compression | Yes, after an A/B and an identity check; an opt-out may stay |
| Lossy or non-identical | everything on this page | No. A stable option with a lossless default |

To check whether an option changes your output, run the same prompts greedily with and without it and compare tokens; the identity tooling is described in [Verification](/docs/developers/verification).


---

<!-- guides/prompt-caching -->
---
title: Prompt caching
description: How Yunshu reuses the KV cache of a shared prompt prefix, how cache hits show up in usage, and which options control memory, SSD storage and precision.
---

Agent and chat traffic repeats itself: every turn resends the system prompt, the tool list and the whole conversation so far. Yunshu keeps the attention state (the KV cache) of earlier prompts and, when a new prompt starts with the same tokens, skips the prefill for that part and only processes the new tokens. This lowers time to first token on every turn after the first, and it needs no client changes.

Reuse is **automatic**. The dialect-specific fields below (`cache_control`, `prompt_cache_breakpoint`) are hints and reporting controls on top of the same cache; they are never required.

## How the cache works

There are two serving paths and each has its own prefix cache.

| Serving path | Serves | Prefix cache | Notes |
|---|---|---|---|
| VLM batch runner | every `mlx-vlm` model, including the Qwen3.5 family | APC (automatic prefix cache) with exact checkpoints | keyed by the prompt tokens and, for vision and audio input, by the media content. On by default with a RAM budget and an SSD tier |
| Text fast path | text-only `mlx-lm` models | `KVPrefixCache` | RAM entries, with an optional SSD tier that is off by default |

A hit requires the new prompt to begin with exactly the cached tokens. Changing anything early in the prompt (for example a system reminder that varies per turn) moves everything after it and reduces reuse. For models with recurrent layers (the Qwen3.5 family mixes attention with GatedDeltaNet layers), the VLM runner stores exact checkpoints that hold both the attention KV and the recurrent state at one token position, so a hit restores precisely the state a cold prefill would have produced.

The VLM runner keeps a checkpoint for the end of the system turn (system prompt plus tool list) in addition to checkpoints for the conversation, so a new session that starts with the same system prompt and tools reuses that head. When a conversation grows, the newer checkpoint replaces earlier ones that are prefixes of it, so a long session holds one copy rather than one per turn.

## See cache hits in usage

The standard usage fields of each dialect report how many prompt tokens came from the cache.

| API | Field |
|---|---|
| Chat Completions | `usage.prompt_tokens_details.cached_tokens` |
| Responses | `usage.input_tokens_details.cached_tokens` |
| Messages | `usage.cache_read_input_tokens` (tokens served from the cache) and `usage.cache_creation_input_tokens` (the cacheable prefix written this turn). `input_tokens` is the remainder, so the three add up to the prompt size |

For streams, the same fields arrive in the usage chunk (chat, with `stream_options: {"include_usage": true}`), the `response.completed` event (Responses) and the Messages usage events.

```json
{
  "usage": {
    "prompt_tokens": 3273,
    "completion_tokens": 120,
    "total_tokens": 3393,
    "prompt_tokens_details": { "cached_tokens": 3264 }
  }
}
```

Yunshu also adds an `x_yunshu` object (and `X-Yunshu-Cached-Tokens`, `X-Yunshu-Cache-Tier` and `X-Yunshu-Cache-Reload-Ms` headers on non-streaming responses) that says which tier served the hit. These are additive fields; SDKs ignore them.

```json
"x_yunshu": {
  "cached_tokens": 13867,
  "cache": { "tier": "ram", "cached_tokens": 13867, "reload_ms": 41.2 }
}
```

`tier` is `ram`, `warm`, `ssd` or `none`. `reload_ms` is the time the lookup took, including reading from SSD. With more than one storage tier configured, an `ssd` hit also carries `device`. Fields are `null` when unknown.

### Check it with the 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)
```

The first call reports a small or zero `cached_tokens`; the second reports most of the prompt.

## Request fields

### Anthropic `cache_control`

On `POST /v1/messages`, `cache_control: {"type": "ephemeral"}` marks a cache breakpoint on a system block, a message content block or a tool, and a top-level `cache_control` is accepted as an automatic marker. `ttl` may be `"5m"` (default) or `"1h"`; at most four breakpoints are supported.

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

Behavior to know:

- Markers are hints. A request is never rejected because of one. If the model's chat template drops or repeats a marker (Qwen templates remove the reasoning of earlier turns, so a marker on a thinking block disappears), the request is served without explicit checkpoints and the server log names the reason.
- On the VLM runner, markers are mapped through the actual chat template, including native tool definitions, and `cache_creation_input_tokens` and `cache_read_input_tokens` report real checkpoint writes and reads.
- On the text fast path, only markers on `system` blocks are read. A marker on a message block is not detected there, so `cache_creation_input_tokens` and `cache_read_input_tokens` stay 0 for it, although the prefix cache still reuses the prefix automatically.

### OpenAI `prompt_cache_*`

The OpenAI-style fields are accepted on Chat Completions and Responses.

| Field | Behavior |
|---|---|
| `prompt_cache_key` | <Support status="partial">accepted and passed through; it does not route or partition the cache. Reuse is decided by the prompt tokens alone</Support> |
| `prompt_cache_retention` | <Support status="partial">accepted; on the VLM runner it supplies the default `ttl` for `prompt_cache_options`</Support> |
| `prompt_cache_options` | <Support status="supported">VLM runner:</Support> `{"mode": "implicit" \| "explicit", "ttl": "30m" \| "24h" \| "in_memory"}`. Without it, the default automatic reuse applies |
| `prompt_cache_breakpoint` on a text content part | <Support status="supported">VLM runner:</Support> an explicit breakpoint at the end of that part. It must be on a text part |

On the text fast path these fields are accepted and have no effect beyond the automatic prefix reuse.

## Which models are excluded

Prefix reuse requires a restorable checkpoint at a prefix boundary. The VLM runner has checkpoint-specific exact-window support (Gemma 4 has dated hit/miss parity receipts); this does not certify every rotating-cache model. See [model support](/docs/guides/model-support) and the loaded model contract. On the text fast path, hybrid/recurrent and sliding-window cache layouts cannot reuse a stored prefix.

## Memory and storage options

All settings are in the settings registry; see [Configuration](/docs/guides/configuration) for the full list.

### VLM runner (APC)

| Setting | Default | Meaning |
|---|---|---|
| `YUNSHU_VLM_APC_MEMORY_GB` | auto | RAM budget in GiB; `0` disables the prefix cache. Unset: half the memory left after the weights and an OS reserve, capped at a quarter of the machine and 32 GiB, and off when less than 1 GiB would remain |
| `YUNSHU_VLM_APC_DISK` | on | SSD tier: checkpoints that RAM evicts (and those still resident at shutdown) are written to disk and read back instead of recomputed. Bit-exact and lossless; the cache survives a restart. Set to `0` for RAM only |
| `YUNSHU_VLM_APC_DISK_DIR` | `~/.yunshu/cache/apc` | where the SSD tier lives; point it at a fast volume to keep the internal disk clean |
| `YUNSHU_VLM_APC_DISK_GB` | auto | size cap of the SSD tier for the whole directory (unset: a quarter of the volume, at most 64 GiB) |
| `YUNSHU_VLM_APC_DISK_TIERS` | unset | further storage tiers below the SSD directory (an external SSD, an HDD, a NAS mount), each `PATH[@GiB]`; volumes are profiled at startup and ordered by measured read speed |
| `YUNSHU_VLM_APC_WARM` | `off` | an extra RAM tier for evicted checkpoints: `lossless` (compressed, bit-exact) or the lossy `int8` / `int4` |
| `YUNSHU_CACHE_RESERVE_PCT`, `YUNSHU_CACHE_RESERVE_GB` | `10`, `20` | free space on the volume that no cache write may use |
| `YUNSHU_CACHE_STALE_DAYS` | `7` | namespaces unused this long, or whose model changed, are removed first |

SSD states are namespaced by the checkpoint's weights, so replacing a model in place never reads stale states.

### Text fast path (`KVPrefixCache`)

| Setting | Default | Meaning |
|---|---|---|
| `YUNSHU_PREFIX_MAX_ENTRIES` | `64` | number of prefix entries kept |
| `YUNSHU_SSD_CACHE` | off | persist prefix KV to SSD |
| `YUNSHU_SSD_CACHE_DIR` | `~/.cache/yunshu/kv-ssd` | SSD directory |
| `YUNSHU_SSD_CACHE_MAX_GB` | `10` | size cap for the directory |
| `YUNSHU_SSD_CACHE_PREFILL_CEIL_TPS` | `20000` | skip an SSD restore when the model prefills faster than this, because recomputing is then as fast as reading |

### Manage the SSD caches

```bash
yunshu cache status        # size, cap and problems of each SSD cache
yunshu cache gc            # dry run: report stale or corrupt entries
yunshu cache gc --apply    # delete them and trim to the size cap
```

`yunshu doctor` also prints the cache directory, its size and the free space.

## Lossless by default, lossy by choice

Reuse of an exact checkpoint, from RAM or from SSD, gives the same state a cold prefill would. The options below trade output quality for memory. They are user options with a lossless default, and nothing enables them for you.

| Setting | Effect |
|---|---|
| `YUNSHU_KV_QUANT_BITS` | text engine: quantize the KV cache to 2, 3, 4 or 8 bits (`auto` switches to 8-bit once the cache would exceed about 2 GiB). Default `off` |
| `YUNSHU_KV_PRECISION` | Qwen3.5-family rows on the packed layer: `int8` stores the KV as int8 codes with a per-group scale, about half the memory and read bandwidth. Default `bf16`. Flash-Next and generic-layer models stay bf16 |
| `YUNSHU_VLM_APC_WARM` = `int8` or `int4` | keep evicted checkpoints quantized in RAM; a hit restores dequantized K/V, so output can differ from a cold prefill. The SSD tier keeps exact states |
| `YUNSHU_PREFIX_HOT_LIMIT` | text engine: keep only this many entries at full precision and store older ones in 4-bit (default `0`: all full precision) |
| `YUNSHU_SSD_CACHE_PRECISION` = `int8` | text engine: store SSD entries as int8, about half the bytes. Default `native` (bit-exact) |

## Support

| Capability | Status |
|---|---|
| Automatic prefix reuse (VLM runner and text fast path) | <Support status="supported">supported</Support> |
| `cached_tokens` and `cache_read_input_tokens` in usage | <Support status="supported">supported</Support> |
| `cache_control` on `system` blocks | <Support status="supported">supported</Support> |
| `cache_control` on message blocks and tools | <Support status="partial">VLM runner only; ignored for accounting on the text fast path</Support> |
| `prompt_cache_key` | <Support status="partial">accepted, no effect</Support> |
| `prompt_cache_options`, `prompt_cache_breakpoint` | <Support status="partial">VLM runner only</Support> |
| Prefix cache for sliding-window models | <Support status="unsupported">not supported</Support> |
| Named cached-content objects (Gemini-style `cachedContents`) | <Support status="unsupported">not provided</Support> |

## Related

- [Messages](/docs/api/messages), [Chat Completions](/docs/api/chat-completions) and [Responses](/docs/api/responses)
- [Architecture](/docs/developers/architecture)
- [Configuration](/docs/guides/configuration)
- [Model support](/docs/guides/model-support)


---

<!-- guides/sampling -->
---
title: Sampling defaults
description: What temperature, top_p, top_k and the penalties a request gets when it sends none, and how the thinking mode picks them.
---

Coding agents (Claude Code, Codex, opencode) send no sampling parameters, so the defaults decide how they behave. Yunshu does not use one number for every model. For each field it takes the first value found in this order:

1. the value in the request (always wins, even when it equals an old default);
2. the model's published recommendation for the mode **this request** runs in (thinking or non-thinking);
3. the model's `generation_config.json`;
4. the official API default (temperature 1.0, top_p 1.0, top_k / min_p / penalties off).

## Which mode a request is in

The mode is resolved the way the request is rendered: Anthropic `thinking` (`enabled` / `disabled`), `enable_thinking` or `chat_template_kwargs.enable_thinking`, a JSON-schema or grammar constraint (runs without thinking), and otherwise the chat template's own default (for example Qwen3.5 and Qwen3.8 think by default). `reasoning_effort` does not switch the mode.

## Published recommendations

| Model                 | Mode         | temperature | top_p | top_k | presence_penalty |
| --------------------- | ------------ | ----------- | ----- | ----- | ---------------- |
| Qwen3.8-27B           | thinking     | 1.0         | 0.95  | 20    | 0.0              |
| Qwen3.8-27B           | non-thinking | 0.7         | 0.80  | 20    | 1.5              |
| Qwen3.6-27B           | thinking     | 1.0         | 0.95  | 20    | 0.0              |
| Qwen3.6-27B           | non-thinking | 0.7         | 0.80  | 20    | 1.5              |
| Qwen3.5-27B / 9B / 4B | thinking     | 1.0         | 0.95  | 20    | 1.5              |
| Qwen3.5-27B / 9B / 4B | non-thinking | 0.7         | 0.80  | 20    | 1.5              |
| Qwen3.5-2B / 0.8B     | thinking     | 1.0         | 0.95  | 20    | 1.5              |
| Qwen3.5-2B / 0.8B     | non-thinking | 1.0         | 1.00  | 20    | 2.0              |
| Gemma 4 31B           | both         | 1.0         | 0.95  | 64    | off              |

Values are copied from the Hugging Face model cards (general-task sets; the cards' coding sets are not used). Other models fall through to `generation_config.json`, then the API default.

## See and change it

- Every response reports `x_yunshu.sampling`: the values, the mode, why that mode, and the source of each field (`request`, `model_card`, `generation_config`, `api_default`).
- `yunshu doctor -m <model>` prints the defaults per mode; the console shows them on the model page; the server logs them at startup.
- `YUNSHU_SAMPLING_DEFAULTS=api` ignores the model and uses the API defaults only. `temperature: 0` is always greedy.


---

<!-- guides/structured-output -->
---
title: Structured output and tool calling
description: Constrain generation to a JSON schema, regex, choice list or grammar, and call tools with tool_choice and parallel calls, across the chat, Responses, Messages and Ollama routes.
---

Yunshu can force the model's output into a shape while it decodes. The constraint is applied token by token, so the result always matches. It is not a prompt that asks nicely and a parser that hopes. Tool calling is built on the same machinery.

Constrained decoding is available for text and vision-language models. A model that does not generate text (an embedding, ASR or image model) rejects constraint fields with a `400` that names the field. The `yunshu` object of each entry in `GET /v1/models` lists what the served model accepts under `contract.structured_output` and `contract.tools`.

## Output constraints

| Constraint | Chat Completions | Responses | Messages | Ollama |
|---|---|---|---|---|
| JSON object | `response_format: {"type": "json_object"}` | `text.format: {"type": "json_object"}` | `response_format` (Yunshu extension) | `format: "json"` |
| JSON schema | `response_format: {"type": "json_schema", ...}` | `text.format: {"type": "json_schema", ...}` | `output_config.format` or `output_format` | `format: {<schema>}` |
| Regex | `grammar: {"type": "regex", "pattern": ...}` | `grammar` | `grammar` | not available |
| Choice | `grammar: {"type": "choice", "choices": [...]}` | `grammar` | `grammar` | not available |
| Context-free grammar | `grammar: {"type": "cfg", "grammar": "<lark>"}` | `grammar` | `grammar` | not available |

The `grammar` field and the vLLM-style aliases are Yunshu and vLLM compatibility extensions. Where an alias is accepted, it folds into the same constraint:

- `guided_json`, `guided_regex`, `guided_choice` and `guided_grammar` on `POST /v1/chat/completions` and `POST /v1/completions`.
- `structured_outputs` (vLLM's field) with exactly one of `json`, `regex`, `choice`, `grammar` or `json_object`, on the chat, completions, Responses and Messages routes. `structural_tag` is not supported.
- A field you set natively wins over an alias. `grammar` with `{"type": "json", "schema": {...}}` is also accepted.

<Callout type="info">
An unsupported or invalid constraint is a `400` before generation starts: an uncompilable regex, a malformed grammar, or a schema construct that neither engine can enforce. Yunshu does not silently generate against an approximation.
</Callout>

### JSON schema with the OpenAI SDK

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

`response_format.json_schema.schema` is required when `type` is `json_schema`; a missing schema is a `400`. The Responses form is the same schema under `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)
```

### Regex, choice and grammar

These go in `grammar` through `extra_body` with the OpenAI SDK:

```python
# A phone number, exactly
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}"}},
)

# One of a fixed set of labels
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"]}},
)

# A context-free grammar in Lark syntax
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` is limited to 2048 characters and `guided_grammar` to 32768.

### Messages and Ollama

On `POST /v1/messages`, structured output uses Anthropic's field (the older beta `output_format` is accepted too):

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

On `POST /api/chat` and `POST /api/generate`, `format` is `"json"` or a JSON schema object (treated as strict).

### How a constraint is enforced

JSON schema and `json_object` constraints are enforced by one of two engines. `YUNSHU_JSON_SCHEMA_ENGINE` picks the preferred one (`llguidance` by default, which keeps properties in schema order, or `inhouse`). A schema that the preferred engine cannot compile falls back to the other when it supports the schema. Regex and choice constraints are compiled in-house; context-free grammars (Lark syntax) need `llguidance`, which `contract.structured_output.grammar` reports as supported or not.

Two optional performance settings, both off by default, apply to the text engine: `YUNSHU_GRAMMAR_BITMASK` switches the default allowlist sampler to an xgrammar-style bitmask engine, and `YUNSHU_JUMP_FORWARD` emits tokens the schema forces without running a forward pass.

## Tool calling

Tools are declared the way each dialect defines them: `tools[].function` on chat, `tools` with `type: "function"` on Responses, `tools[].input_schema` on Messages, and `tools` on `POST /api/chat`.

### Two modes: template and prompt

How the tools reach the model depends on its chat template, and `contract.tools.mode` in `GET /v1/models` tells you which one applies.

| Mode | When | What happens |
|---|---|---|
| `template` | the chat template has native tool support | tools are rendered by the model's own template, in its own tool format and special tokens, and the model's tool-call output is parsed back into structured calls |
| `prompt` | the template has no tool support | the tool definitions are injected into the prompt and calls are extracted from the generated text |

`template` gives better adherence and parse rates when it is available. Both modes return the same response shape. In `contract.tools`, `parallel` says whether the template can carry several calls in one assistant turn.

### `tool_choice`

| Value | Chat | Responses | Messages |
|---|---|---|---|
| let the model decide | `"auto"` (default) | `"auto"` | `{"type": "auto"}` |
| no tools | `"none"` | `"none"` | `{"type": "none"}` |
| must call some tool | `"required"` | `"required"` | `{"type": "any"}` |
| must call this tool | `{"type": "function", "function": {"name": "..."}}` | `{"type": "function", "name": "..."}` | `{"type": "tool", "name": "..."}` |

A `tool_choice` of `required` or a named function needs a non-empty `tools` list, and a named function must be one of the declared tools; otherwise the request is a `400`. The `allowed_tools` form is folded into `tools` plus a mode on the chat and Responses routes. A forced choice is always enforced by constrained decoding, so the call is guaranteed to exist and to name the right tool with arguments matching its schema.  For `auto`, calls are decoded freely and repaired after the fact.

### Parallel tool calls

A model can emit several calls in one turn when its template supports it (`contract.tools.parallel`). Set `parallel_tool_calls: false` (chat and Responses) or `disable_parallel_tool_use: true` inside the Messages `tool_choice` to keep only the first call. On Responses, `max_tool_calls` caps the total.

### A tool-call round trip

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

When the model calls tools, `finish_reason` is `tool_calls` on chat and `stop_reason` is `tool_use` on Messages. Streaming sends the call as incremental deltas.

### The same call on each route

<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 has no `tool_choice` field; tool arguments come back as objects, not strings.

</Tab>
</Tabs>

## Support

| Capability | Status |
|---|---|
| `json_object` and `json_schema` on chat, Responses, Messages, Ollama | <Support status="supported">supported</Support> |
| `regex`, `choice` through `grammar` | <Support status="supported">chat, completions, Responses, Messages</Support> |
| Context-free grammar (Lark) | <Support status="partial">needs `llguidance`; check `contract.structured_output.grammar`</Support> |
| `guided_*` aliases | <Support status="extension">chat and completions</Support> |
| `structured_outputs` (vLLM) | <Support status="extension">all four generation routes; no `structural_tag`</Support> |
| Constraints on a non-text model | <Support status="unsupported">`400`</Support> |
| `tool_choice` `auto`, `none`, `required`, a named function | <Support status="supported">supported</Support> |
| Forced `tool_choice` guarantee | <Support status="supported">constrained decoding</Support> |
| `auto` decoded with the tool grammar | <Support status="partial">only with the experimental setting, off by default</Support> |
| `parallel_tool_calls: false` | <Support status="supported">keeps the first call</Support> |
| Chat `functions` / `function_call` (deprecated) | <Support status="unsupported">not supported</Support> |
| Custom (non-function) tools on chat | <Support status="unsupported">not supported</Support> |

## Related

- [Chat Completions](/docs/api/chat-completions), [Responses](/docs/api/responses), [Messages](/docs/api/messages) and [Ollama](/docs/api/ollama)
- [Model support](/docs/guides/model-support)
- [Coding agents and SDKs](/docs/guides/agents)
- [Architecture](/docs/developers/architecture)


---

<!-- guides/tavily -->
---
title: Local Tavily API
description: Use the official Tavily Python, JavaScript and LangChain clients against Yunshu's local Tavily-compatible search, extract, crawl, map and research endpoints.
---

Yunshu mounts a Tavily-compatible API at `http://localhost:8000/tavily`. The Python, JavaScript and LangChain clients append endpoint paths to the configured base URL, so there is no `/v1` in this API. For the server-side `web_search` and `web_fetch` tools and provider choice, see [Web search](/docs/guides/web-search).

## Connect a client

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

An injected async HTTP client must itself use this full base URL, because the SDK preserves its existing URL. LangChain's `TavilySearchAPIWrapper` accepts `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>

Set `YUNSHU_AUTH_TOKEN=tvly-local` to require that key; the `tvly-` prefix is accepted verbatim, not stripped. A legacy body `api_key` also works. With auth unconfigured, the normal local open policy applies ([Authentication](/docs/guides/auth-and-keys)).

## Endpoints

| Method | Path |
|---|---|
| POST | `/search`, `/extract`, `/crawl`, `/map`, `/research`, `/feedback`, `/logs` |
| GET | `/research/{request_id}`, `/usage`, `/providers` |
| POST | `/mcp` (native stateless MCP endpoint) |

Errors use `detail.error`, with 400, 401, 403, 404, 413, 429 and 500 as applicable and 422 for field validation. Tavily's cloud-only credit and plan statuses 432 and 433 are not fabricated. Responses carry request IDs, elapsed seconds and informational local credits, and array fields are stable. Search, extract, crawl, map and research polling return `usage` only with `include_usage=true`; internal accounting continues either way.

## Retrieval and latency

The SERP is a provider. Built-in metasearch runs direct DDG HTML and Wikipedia, plus configured keyed sources, in parallel, and reciprocal-rank fusion deduplicates candidates.

<Callout type="warn">
Query text leaves the machine to these providers. DDG is best effort and can block automation. SearXNG is optional and needs an explicit instance; it is never required or recommended.
</Callout>

`yunshu config` shows the most recent query-free provider health snapshot; `GET /tavily/providers` shows live health. Three consecutive failures trigger bounded exponential backoff, and a half-open probe restores a recovered source. Captcha and rate limits back off immediately.

| Provider | How to enable | Notes |
|---|---|---|
| Mwmbl | `YUNSHU_WEB_MWMBL=1`, or `provider=mwmbl` | dataset is CC-BY-NC-SA 4.0: keep attribution and observe the noncommercial and share-alike terms ([terms](https://api.mwmbl.org/static/terms-and-conditions/)); not silently enabled; no Mwmbl code is copied |
| Mojeek | `YUNSHU_MOJEEK_API_KEY` | joins auto metasearch; forwards safe-search, country and language boosts and date bounds; requests at most ten candidates ([API](https://www.mojeek.com/support/api/search/)) |
| Marginalia | `YUNSHU_MARGINALIA_API_KEY` | forwards safe-search and result count; no implicit `public` key (setting it opts into the shared development quota); noncommercial keys serve CC-BY-NC-SA 4.0 data ([API and terms](https://about.marginalia-search.com/article/api/)) |

Select a provider explicitly with `YUNSHU_WEB_SEARCH_PROVIDER` (`mojeek`, `marginalia`, `mwmbl`, and so on; default `auto`). Common Crawl's URL index and Wikipedia dumps need corpus ingestion and a local full-text index; they are not keyword SERP endpoints and are never downloaded or enabled automatically.

Plain search uses BM25, provider priors, exact spans and deduplication, with no LLM calls. Each excerpt is at most 500 characters, and excerpts join with ` [...] `. The search depth sets the fetch breadth and the total retrieval budget:

| `search_depth` | Budget | Pages |
|---|---|---|
| `ultra-fast` | 0.7 s | provider text only |
| `fast` | 1 s | 3 |
| `basic` | 1.3 s | 6 |
| `advanced` | 3 s | 20 |

These are cancellation budgets, not guaranteed end-to-end p50: DNS, politeness, provider availability and requested generation affect real latency. The `Server-Timing` header reports SERP, fetch, IR and generation durations. Pages that miss the depth's fetch window are not cancelled; they finish under their own timeout and warm the page cache.

Time, topic, country, language and safe-search are pushed to providers that support them; dates and strict language are also checked locally. Finance is a best-effort news vertical, not a financial index. Unknown dates survive unless strict filtering is requested. Exact quoted phrases need a successfully fetched page. The normalized score is local relevance, not calibrated to Tavily's proprietary probability.

Extract handles static HTML, text, JSON and bounded PDF bodies, keeps available markdown, code and tables, and isolates failures. Crawl and map use BFS with regex selectors (with timeouts), depth, breadth and global caps, robots rules and host politeness. Map may list external links but never follows them recursively. `instructions` uses cheap lexical relevance.

### JavaScript rendering

Advanced extract, crawl and map can render short JavaScript shells with `YUNSHU_WEB_RENDER=1` (default off).

<Steps>
<Step>

Install the optional extra: `uv sync --extra web-render`.

</Step>
<Step>

Install a local browser: `uv run playwright install chromium`. Requests never install a browser.

</Step>
<Step>

Set `YUNSHU_WEB_RENDER=1`.

</Step>
</Steps>

Rendering uses one headless Chromium at a time and replays only same-origin GET documents, scripts and fetches through the normal checked and pinned fetcher. Service workers, WebSockets, downloads, cross-origin resources and redirected resource bodies are blocked. Robots rules still apply to crawl and map, and the request timeout covers the static fetch plus rendering. A missing browser or a timeout keeps the static result. CDN-dependent applications and protected-site bypass are not supported.

## Answers, research and MCP

- `include_answer` calls the served chat model only when requested.
- Research plans queries with the served LLM, searches and extracts evidence, then synthesizes with citations. Output schemas use the chat constrained JSON decoding ([Structured output](/docs/guides/structured-output)) and are validated afterwards. `mini` and `pro` differ in query caps; `pro` is serial on the single GPU and is not Tavily's proprietary multi-agent implementation. Research stays opt-in.
- Async tasks support polling and SSE with keepalives, tool frames, content, sources and done events. The registry (100 tasks), feedback (1000) and logs (10000) are bounded in process and lost on restart.
- Local credits estimate effort; they do not bill or enforce cloud plans.
- Files support base64 `txt`, `md` and `json` with an 80000-word combined cap. Bibliographies support numbered, APA, MLA and Chicago formatting.
- Image metadata comes from fetched pages. `include_images` additionally queries a configured SearXNG image category or Brave's image endpoint, applies source-domain filters and deduplicates URLs; a failed image vertical does not fail the search, and DDG and Wikipedia have no image fallback. Requested image descriptions use a resident local VLM (at most three images, cached for 15 minutes); no second model is loaded.

<Callout type="warn">
Upstream `tavily-mcp` 0.2.22 hard-codes `api.tavily.com` and has no base URL setting, so REST compatibility cannot redirect it. Use Yunshu's native MCP endpoint, `/tavily/mcp`, which exposes the Tavily tools under both underscore and hyphen names.
</Callout>

## How to verify

- `scripts/research/tavily_sdk_parity.py` and `scripts/research/tavily_sdk_parity.mjs` run the real SDK packages against the real router and service with transport injection, no listening server and no live network. Install the SDK packages in an isolated environment, not the serving venv.
- `scripts/research/tavily_stage_latency.py` measures per-stage latency (`Server-Timing`: serp, fetch, ir, generate); `--live` uses the real built-in providers and pages and runs on the CPU only.
- `scripts/research/websearch_quality_gate.py` evaluates frozen paired replays with explicit review annotations (`--snapshot`, `--pairs`, `--reviews`, `--out`) and exits 1 when evidence is incomplete. It requires at least 200 distinct pairs, covering at least 40 news, 40 docs, 40 code and 10 adversarial references on one device, human checks on at least 10% of pair reviews, and at most one net correctness difference for equivalence. It does not approve a quality-changing research default or establish latency.


---

<!-- guides/telemetry -->
---
title: Host telemetry and energy
description: Enable the local Apple Silicon power, GPU and temperature sampler, read it from the API, the CLI and Prometheus, and understand what the per-request energy estimates mean.
---

`YUNSHU_TELEMETRY=on` enables a local background sampler (1 Hz by default). It needs no root, never imports MLX, and makes native calls only on its own `yunshu-host-telemetry` thread, outside the inference executor. No samples leave the machine.

## Turn it on

<Steps>
<Step>

Set `YUNSHU_TELEMETRY=on` (and optionally `YUNSHU_TELEMETRY_INTERVAL_S`) in the environment or the config file.

</Step>
<Step>

Restart the server. Both settings need a restart.

</Step>
<Step>

Read the sampler with `GET /v1/yunshu/host`, `yunshu top`, or `/metrics`.

</Step>
</Steps>

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_TELEMETRY` | `off` | `on` starts the sampler; restart required |
| `YUNSHU_TELEMETRY_INTERVAL_S` | `1.0` | sampling interval in seconds, minimum 0.1; restart required |

<Callout type="info">
It is off by default. A 27B A/B showed identical decode speed within noise, but a small, consistent follow-up TTFT cost at 1K prose, so it is opt-in. The numbers are not recorded in the benchmark log, so none are quoted here.
</Callout>

The implementation derives its IOReport and HID access from [pierre427/mlx2](https://github.com/pierre427/mlx2) (Apache-2.0) and its macOS 27 counter catalog from [vladkens/macmon](https://github.com/vladkens/macmon) (MIT). Notices are in `THIRD_PARTY_NOTICES.md` and `vendor.json`.

## Host API and CLI

`GET /v1/yunshu/host` uses the console permission (`can_manage_models`). It keeps the existing `thermal`, `power`, `memory` and `memory_pressure` fields (15-second cache) and adds `telemetry` with its own 1 Hz cache:

```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": {}
  }
}
```

- Power is interval energy divided by elapsed seconds. Package watts is the sum of the reported CPU, GPU, ANE and DRAM channels, not wall-plug power.
- GPU MHz is weighted by active DVFS residency. The active ratio includes idle residency in its denominator.
- Missing counters are `null` with a reason, never invented zeroes. Unavailable, disabled or stale telemetry returns `state: unknown` with `reason`. Partial power coverage returns `state: partial`; temperature can independently be unknown.

`yunshu top` watches these cached fields using the configured API key. `yunshu top --once` prints one table and `yunshu --json top` emits one JSON snapshot. Unknown values stay visible. The CLI does not sample hardware itself.

## Request energy estimates

`x_yunshu.energy` and `/v1/yunshu/requests/recent` expose the schema `yunshu.energy.v1`. The gateway fills it off the MLX thread. Each `prefill` and `decode` object reports `joules`, `joules_per_token`, `gpu_watts_mean`, `coverage_ratio` and `extrapolated_s`.

- Prefill uses uncached prompt tokens; decode uses generated tokens. The prefill-end timestamp, or the first token when that is unavailable, separates the phases. Queue time is excluded.
- The method `host_window_gpu_plus_dram` integrates sampled GPU and DRAM power, clipping intervals at phase boundaries. The unfinished tail uses the latest power for at most two sampling intervals. Short phases are estimates at sampler resolution.
- Missing coverage, stale readings and absent phase clocks return `null` joules with a reason. CPU and ANE are reported separately and excluded from request energy.
- History is bounded to 7,200 intervals; older requests can lose coverage.

<Callout type="warn">
These are host energy windows that include background activity and idle power. Concurrent requests have overlapping windows and are not metered independently, so summing receipts can count the same host energy more than once. Use serial benchmark cells for efficiency comparisons. Cancellation reports only observed engine timing, not a forecast.
</Callout>

## Prometheus

The authenticated `/metrics` scrape adds:

- `yunshu_gpu_watts`, `yunshu_package_watts`
- `yunshu_gpu_frequency_mhz`, `yunshu_gpu_active_ratio`
- `yunshu_die_temperature_celsius` (maximum die temperature)
- `yunshu_request_energy_joules_total{phase="prefill|decode"}` (session sum of the estimates)

Unknown gauges are omitted. The request counter is updated once at request completion, never on scrapes, and has the overlapping-window caveat above.

## macOS 27 power counters

On macOS 27 the Energy Model CPU and ANE counters can freeze without Apple's entitlement. Yunshu uses macmon's driver-qualified CLPC scalar IOReport catalog for macOS 27 (qualified upstream on 27.0 and 27.0.1) and prefers valid CLPC CPU, GPU and ANE deltas over legacy values. Unknown driver or OS catalogs are never guessed. When no valid qualified delta exists, CPU and ANE values on macOS 27 and later are unknown with a reason, while other valid domains stay available, so a frozen zero is never reported as measured power. No root, Apple entitlement, SMC access or MLX calls are needed.

Die temperature prefers HID `tdie` sensors and falls back to `pACC`, `eACC` and `GPU MTR Temp Sensor` names when no `tdie` values exist, without mixing sensor families.

## Limits and how to verify

- Energy is a host-window estimate, not a per-process meter (see the warning above).
- For sampler overhead, compare an explicit `off` baseline with an explicit `on` candidate on pinned commits, with at least three interleaved repetitions at 1K and 32K. A speed verdict alone does not prove the sensors worked; check the real-run host evidence too.
- Benchmark tooling (`tfbench`, `yv`) keeps the full receipt plus decode `joules_per_token` and `gpu_watts_mean`; `yv` reports per-arm medians under `efficiency` but they do not decide speed acceptance. The gate is described in [Verification](/docs/developers/verification).


---

<!-- guides/transports -->
---
title: Transports
description: The HTTP, SSE, WebSocket, Realtime, WebRTC and Unix socket transports Yunshu serves, the multiplexed text WebSocket protocol, and what is not offered.
---

Yunshu serves the same app over several transports. Every one dispatches into the same handlers, so auth, middleware, request ids, the prefix cache and cancellation behave identically.

| Transport | Endpoint | Status |
|---|---|---|
| HTTP and SSE | `POST /v1/chat/completions`, `/v1/responses`, `/v1/messages` | stable |
| Text WebSocket, multiplexed | `WS /v1/stream` | stable, Yunshu protocol (below) |
| Responses WebSocket mode | `WS /v1/responses` | stable, OpenAI's protocol |
| Realtime WebSocket | `WS /v1/realtime` (GA schema; beta with `OpenAI-Beta: realtime=v1`) and `/realtime` (beta) | stable |
| Realtime WebRTC | `POST /v1/realtime/calls` | optional `yunshu[webrtc]` |
| Unix domain socket | `yunshu serve --uds PATH` | stable |
| HTTP/2 (h2c) | not offered | none |

## What the specs say

**Responses WebSocket mode.** Per OpenAI's WebSocket mode guide, a client connects to `/v1/responses` as a WebSocket (SDK: `client.responses.connect()`), sends `{"type":"response.create", "model", "input", "store", "previous_response_id", "generate", "stream_id"}`, and receives the same `response.*` events as the SSE stream, raw, plus `error`. Requests with the same `stream_id` run in order and never overlap; different ids run concurrently. Continuation uses `previous_response_id` with only the new input items. Yunshu implements this at `WS /v1/responses`.

**Anthropic Messages.** SSE (`stream: true`) is the only official streaming transport; there is no WebSocket mode to match. Messages is reachable through Yunshu's own `/v1/stream` (`api: "messages"`).

**OpenAI Realtime.** WebSocket at `/v1/realtime?model=M` with `Authorization: Bearer` (browsers use the subprotocols `realtime` and `openai-insecure-api-key.<key>`), JSON text frames. The GA session has `type: "realtime"`, `output_modalities`, `audio.input` and `audio.output`, `instructions`, `tools` and `tool_choice`. Audio formats are `audio/pcm` (24 kHz, mono, 16-bit), `audio/pcmu` and `audio/pcma`; turn detection is `server_vad`, `semantic_vad` or null. WebRTC posts an SDP offer to `/v1/realtime/calls` and exchanges the same events on an `oai-events` data channel.

## Text WebSocket: WS /v1/stream

This is the Yunshu protocol, used where no official WebSocket mode exists (chat completions, completions, messages) and for the multiplexing extras. One connection carries many concurrent requests. Server events are the same objects the SSE stream carries as `data:` payloads, wrapped with the client's request id.

<Steps>
<Step>

Connect with the same auth as HTTP (`Authorization: Bearer`, `x-api-key` or `?token=`). Origin and credentials are checked before the upgrade, so a rejected client gets an HTTP 403 handshake failure.

</Step>
<Step>

Read the first server message, `session.created`. It lists `apis` and `limits` (`max_inflight`, `max_stream_ids`, `send_queue`, `ping_interval_s`).

</Step>
<Step>

Send a request frame. `body` is the normal HTTP body; `stream` is forced on and, for chat and completions, `stream_options.include_usage` defaults to true.

```json
{"type": "request", "id": "a", "api": "chat.completions", "body": {"model": "local", "messages": [{"role": "user", "content": "Hi"}]}}
```

</Step>
<Step>

Read `event` frames until the terminal `done` frame for that id.

</Step>
</Steps>

Client to server (JSON text frames):

| Message | Meaning |
|---|---|
| `{"type":"request","id":"a","api":"chat.completions\|completions\|responses\|messages","body":{...},"stream_id":"s"}` | start a request (`stream_id` optional) |
| `{"type":"cancel","id":"a"}` | abort; generation stops (the same path as an SSE client disconnect); ends with `done(cancelled)` |
| `{"type":"stop","id":"a"}` | stop on demand; ends with `done(stopped)` |
| `{"type":"update","id":"a","max_tokens":N}` | cap total streamed deltas (about one per token) at N; ends with `done(max_tokens)` |
| `{"type":"ping","t":..}` and `{"type":"pong"}` | liveness in both directions |

Server to client:

| Message | Meaning |
|---|---|
| `{"type":"session.created","protocol":"yunshu.stream","apis":[...],"limits":{...}}` | first message |
| `{"type":"event","id":"a","event":"<SSE event name or null>","data":{...}}` | one SSE event. For chat, `data` is the `chat.completion.chunk`; for responses and messages, the named events |
| `{"type":"done","id":"a","reason":"completed\|cancelled\|stopped\|max_tokens\|error","stats":{"ttft_ms","duration_ms","events","deltas"}}` | terminal message of every request; also carries `request_id` |
| `{"type":"error","id"?,"status":404,"error":{...}}` | request-scoped (with `id`) or connection-scoped error; upstream HTTP errors keep their status and body |
| `{"type":"ping","t":...}` | heartbeat every `YUNSHU_WS_PING_INTERVAL` seconds |
| `{"type":"updated","id","max_tokens"}` | acknowledgement of `update` |
| `{"type":"progress","id",...}` | queue and prefill progress: the fields of the SSE `: yunshu-progress` comment (`phase`, `percent`, `processed_tokens`, `tokens_per_second`, `eta_s`, `queue_position`, ...) |
| `{"type":"stats","id",...}` | per-response stats: the fields of the `x_yunshu` object (`ttft_ms`, `decode_tps`, cache hits, ...). See [Yunshu extensions](/docs/api/extensions) |

### Rules

- `id` is the client request id. When it is header-safe (1 to 128 characters of `A-Za-z0-9._:-`) it is also the HTTP `X-Request-Id`, so `GET` and `DELETE /v1/requests/{id}`, logs and error hints use the same id. Otherwise the handler generates one and reports it as `request_id` in `done`.
- At most `YUNSHU_WS_MAX_INFLIGHT` (default 16) requests run at once per connection; more get `429 too_many_requests`. Reusing an active id is `409`. Requests sharing a `stream_id` run in order; at most 32 stream ids per connection.
- Backpressure: the per-connection outbound queue is bounded (`YUNSHU_WS_SEND_QUEUE`, default 256 events), so a slow reader blocks the app's `send()` and generation pauses instead of buffering. Heartbeats never queue behind a stalled reader.
- Closing the socket cancels every in-flight request.

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_WS_MAX_INFLIGHT` | `16` | concurrent requests per connection |
| `YUNSHU_WS_PING_INTERVAL` | `15.0` | seconds between heartbeats; `0` disables |
| `YUNSHU_WS_SEND_QUEUE` | `256` | buffered outbound events before generation pauses |

### Responses WebSocket mode

`WS /v1/responses` speaks OpenAI's protocol: send `{"type":"response.create", ...body..., "stream_id"?}` and receive raw `response.*` events. `stream_id` lanes work as above. Yunshu adds `{"type":"response.cancel","stream_id"|"id"}`. Progress and stats events are not emitted in this dialect, because OpenAI's protocol has no slot for them. The official `openai` SDK (`client.responses.connect()`) is the reference client.

### Python client

```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` streams two chats on one socket and cancels one.

## Realtime

`/v1/realtime` implements the OpenAI Realtime protocol in two dialects chosen at the handshake: GA (the default, what `client.realtime.connect()` speaks) and beta (`OpenAI-Beta: realtime=v1`, and the legacy `/realtime` path). The session engine is shared; `yunshu_gateway/realtime_ga.py` translates event names and the session shape at the socket boundary. Auth and Origin are checked before the upgrade (HTTP 403). See the [Realtime API reference](/docs/api/realtime).

Differences from api.openai.com:

- `semantic_vad` is served as `server_vad`; `eagerness` is ignored.
- `turn_detection.idle_timeout_ms`: that long after a completed response (plus the playback time of its audio) without user speech, the server sends `input_audio_buffer.timeout_triggered`, commits the empty buffer as a silent user turn and answers.
- `audio.input.noise_reduction` (`near_field` or `far_field`) applies a causal CPU high-pass and noise-floor expander before VAD and ASR. It is a light filter, not a neural denoiser.
- `rate_limits.updated` follows `response.created`. A local server has no quota: `requests` reports `YUNSHU_RATE_LIMIT_RPM` (2^31-1 when 0, meaning unlimited) and `tokens` reports the model's context window.
- `output_audio_buffer.started`, `.stopped` and `.cleared` (GA dialect only) bracket the audio of a response; the client event `output_audio_buffer.clear` cancels the speaking response.
- `response.create.input` replaces the conversation as the context of that response; combine it with `conversation: "none"` to keep it out of the history.
- Unsupported session fields pass through silently, with no `invalid_request_error`.

### WebRTC

<Steps>
<Step>

Install the extra: `uv pip install 'yunshu[webrtc]'`. Without it, `POST /v1/realtime/calls` returns 503 and `WS /v1/realtime` is the alternative.

</Step>
<Step>

Post an SDP offer to `/v1/realtime/calls` (`application/sdp`, or multipart `sdp` plus JSON `session`), as `client.realtime.calls.create` does. The server returns 201, an SDP answer and a `Location` call ID.

</Step>
<Step>

Exchange events on the `oai-events` data channel, which shares the GA Realtime session. Audio travels on RTP tracks.

</Step>
</Steps>

Incoming audio is resampled on CPU to mono PCM16 at 24 kHz, and outgoing PCM uses a bounded two-second buffer. Sessions close on peer failure, client channel close, server shutdown or after one hour; offers without an opened channel expire after 60 seconds; at most 16 calls stay live. Ephemeral client secrets also authenticate this endpoint. There are no public STUN or TURN servers, so loopback and LAN peers need directly reachable ICE candidates. SIP call management and a monitoring sideband WebSocket are not provided.

## Unix domain socket

`yunshu serve --uds /path/y.sock` (setting `YUNSHU_UDS`) serves the identical app on a socket instead of TCP. `--host` and `--port` are ignored, and a stale socket file is removed. Owner-only file permissions are the access control, which makes this the safest local transport: no port and no network exposure.

<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)` does the same for the WebSocket. The OpenAI SDK's own Realtime and Responses WebSocket clients open TCP connections, so use a TCP port for them.

## HTTP/2

Not offered. uvicorn speaks HTTP/1.1 only, and h2c would need a second server stack (hypercorn or granian) with its own lifespan, WebSocket and disconnect semantics. Disconnect-driven cancellation and the multiplexed WebSocket already cover what HTTP/2 would add: many concurrent streams on one connection, with no head-of-line blocking between requests.

## How to verify

- `scripts/dev/realtime_conformance.py` checks Realtime against the official SDK (a unit test with a fake engine); `scripts/dev/transport_smoke.py` is the real-model smoke.
- WebRTC signalling, audio framing, queue bounds and cleanup are covered in `tests/unit/test_respfeat.py`.


---

<!-- guides/troubleshooting -->
---
title: Troubleshooting
description: Fixes for common problems with installing, starting and calling Yunshu, and how to collect a diagnostics bundle.
---

Start with `yunshu doctor`. Add `-m <model>` to check a model as well. It checks the platform, MLX and Metal, memory, settings, the models directory, the port and the login service, and prints a fix for each problem. It exits with status 1 when something blocks serving.

```bash
yunshu doctor -m <model>
yunshu --json doctor -m <model>
```

## Install

<Accordions>
<Accordion title="cannot import mlx, or Python runs under Rosetta">

MLX ships arm64 wheels only, so an x86_64 Python (for example an old Homebrew under `/usr/local`) cannot load it. `yunshu doctor` reports "Python runs under Rosetta". Install a native interpreter with `uv python install 3.13`, then reinstall Yunshu with it.

</Accordion>
<Accordion title="requires-python >=3.13">

Yunshu needs Python 3.13 or later. `uv tool install "yunshu[vision]" --python 3.13` fetches a uv-managed 3.13 if needed.

</Accordion>
<Accordion title="A Qwen3.5 / 3.6 / 3.8 or vision model fails to load, and doctor shows mlx-vlm not installed">

Install the `vision` extra: `uv tool install "yunshu[vision]" --python 3.13`. See [Install](/docs/getting-started/install).

</Accordion>
<Accordion title="macOS version is too old">

`yunshu doctor` fails the platform check below macOS 14. Update macOS; MLX needs 14 or newer.

</Accordion>
</Accordions>

## Starting the server

<Accordions>
<Accordion title="Error: no such directory, or the model is not found">

`yunshu serve` checks the model before loading it.

- `yunshu model list` shows what is on disk (the models directory and the Hugging Face cache).
- `yunshu pull <org/name>` downloads a model.
- A directory that holds several models belongs in `--models-dir`, not `--model`.

</Accordion>
<Accordion title="interrupted download, or weight shards missing">

Run the same `yunshu pull` again. It resumes and fetches only the missing files.

</Accordion>
<Accordion title="weights larger than memory, or a warning about the GPU working set">

The model cannot fit in unified memory. Use a smaller or more quantized build, for example a 4-bit MLX conversion. When weights fit but use most of the GPU working set, the model loads but long prompts may run out of memory. macOS gives the GPU a working set somewhat below total RAM; `yunshu doctor -m <model>` prints both numbers.

</Accordion>
<Accordion title="Cannot listen on host:port, or the port is used by another program">

Pick another port with `--port` (for example `--port 8001`) and use it in your clients. `yunshu serve` checks the address before loading the model and exits with an error. If the program on the port is Yunshu itself, such as the login service, `yunshu status` reports it and `yunshu doctor` says "Yunshu is already running".

</Accordion>
<Accordion title="The server starts, but GET /health/ready returns 503">

When a model fails to load (wrong path, damaged weights, not enough memory) the server stays up instead of exiting, so a supervisor such as launchd does not restart-loop. The readiness probe returns 503, with a `reason` when a load error is known, and chat requests that need a model get a 503 until you fix the cause and restart. The full traceback is in the server log (the terminal, or `yunshu service logs`); look for `FATAL: model ... load failed`.

```bash
curl -i http://127.0.0.1:8000/health/ready
```

The probe also returns 503 while the server is shutting down or when GPU memory use is above 95%.

</Accordion>
<Accordion title="Which speculative path is in use?">

`yunshu doctor -m <model>` prints a `speculative` row, and the startup log has a `Speculative decoding:` line. A matching DFlash2 drafter found in the models directory or the Hugging Face cache is picked up automatically. `YUNSHU_VLM_DRAFT=mtp` forces the checkpoint's MTP head, `YUNSHU_VLM_DRAFT=off` turns drafting off, and a directory path selects a specific drafter. If an automatic drafter cannot be loaded, the server logs a warning and falls back to MTP.

</Accordion>
<Accordion title="A bad setting stops startup">

`yunshu config` shows every effective value and where it came from. A setting with an invalid value stops the command with an error. A misspelled `YUNSHU_*` name only produces a warning with the closest match; `--set` with an unknown name is an error.

</Accordion>
<Accordion title="Stopping the server">

Ctrl-C or `kill` (SIGINT or SIGTERM) stops accepting new requests and lets running ones finish for `YUNSHU_DRAIN_TIMEOUT` seconds (default 30). After that the remaining connections are cut, their generation stops, and the server exits. A client that disconnects mid-request cancels its generation.

</Accordion>
</Accordions>

## Calling the API

<Accordions>
<Accordion title="401 Missing or invalid Authorization header">

The server has `YUNSHU_AUTH_TOKEN` set (for example through `--auth-token`). Send `Authorization: Bearer <token>`, or `x-api-key: <token>` from Anthropic clients. Without a token, inference is open, but model load and unload and similar operational endpoints are denied. Health, version and documentation routes never need a token.

</Accordion>
<Accordion title="A client in Docker cannot connect">

By default the server listens on `127.0.0.1` only. Start it with `--host 0.0.0.0 --auth-token <secret>` and connect to `http://host.docker.internal:8000`.

</Accordion>
<Accordion title="model not found in multi-model mode">

Use an id from `GET /v1/models` (`yunshu model list --url http://127.0.0.1:8000`). In single-model mode any model name works.

</Accordion>
<Accordion title="A reasoning model's answer is empty">

Its tokens went to thinking. Raise `max_tokens`, lower `reasoning_effort`, or pass `chat_template_kwargs` with `enable_thinking` set to `false`.

</Accordion>
<Accordion title="A request returns 400">

The response body says why. Typical causes:

- `context_length_exceeded`: the prompt is longer than the model's context window. Shorten the prompt or use a model with a longer context.
- `max_tokens` above the request validation cap (1,048,576), or above a lower limit from the model's context and output budget. The message states the numbers.
- A JSON-schema keyword or regex construct that the engine cannot enforce (for example `uniqueItems`, `not`, `if`/`then`/`else`, `contains`). These are rejected rather than silently ignored.
- A feature the model lacks, such as tools, images, audio or logprobs. `GET /v1/models` lists what each model supports.

</Accordion>
<Accordion title="429 Rate limit exceeded">

Rate limiting is off by default. It is on only if `YUNSHU_RATE_LIMIT_RPM` is set above 0.

</Accordion>
</Accordions>

## Disk and cache

The prefix cache SSD tier (default `~/.yunshu/cache/apc`) has one budget per cache root and keeps a free-space reserve. When a write fails, spilling to disk pauses with one warning. `yunshu doctor` warns when the disk is short.

```bash
yunshu cache status        # entries per namespace, size and cap
yunshu cache gc            # report what could be removed
yunshu cache gc --apply    # remove truncated, corrupt and old-format entries, trim to the cap
```

`YUNSHU_VLM_APC_DISK=0` keeps the prefix cache in RAM only. See [Prompt caching](/docs/guides/prompt-caching).

## Reporting a bug

`yunshu diagnose bundle` writes a local diagnostics file with the version, platform, package versions, settings with secrets redacted, the doctor output, SSD cache state and recent error lines from the service log with their trace ids. It never contains prompts or completions and is never uploaded.

```bash
yunshu diagnose bundle -o yunshu-diagnostics.json
```

When you open an issue at [github.com/YuhuanStudio/Yunshu](https://github.com/YuhuanStudio/Yunshu/issues), include:

- the output of `yunshu --json doctor -m <model>`
- the model folder name
- the command or request that failed
- the last 50 or so lines of the server log

## Related

- [CLI reference](/docs/guides/cli)
- [Service](/docs/getting-started/service)
- [Configuration](/docs/guides/configuration)


---

<!-- guides/web-search -->
---
title: Web search and fetch
description: Server-side web_search and web_fetch tools, the search providers behind them, the settings that control them, and what leaves your machine.
---

Coding agents and SDK clients can ask Yunshu to search the web or fetch a page while a model is generating. The server runs the tool, feeds the result back to the model and returns the answer together with the tool blocks and citations in the format of the dialect the request used.

| Dialect | Tool types | Notes |
|---|---|---|
| Anthropic Messages (`POST /v1/messages`) | `web_search_*` (for example `web_search_20250305`), `web_fetch_*` (for example `web_fetch_20250910`) | results come back as `server_tool_use` and `web_search_tool_result` / `web_fetch_tool_result` blocks; text blocks carry `web_search_result_location` citations |
| OpenAI Responses (`POST /v1/responses`) | `web_search`, `web_search_preview` | results come back as `web_search_call` items; `open_page` and `find_in_page` actions work on pages the search already retrieved. `web_fetch` is not a Responses tool |

See [Server tools](/docs/api/server-tools) for the request and response shapes, and [Coding agents and SDKs](/docs/guides/agents) for which agents use them.

<Callout type="warn">
Web search is not offline inference. With the default settings the **query text, and your IP address, leave the machine** to reach DuckDuckGo, Wikipedia and any provider you configured. Queries are written by the model and can contain context from the conversation. Fetched URLs are visible to the origin sites. No conversation history and no client credentials are forwarded, and provider keys go only to their own search APIs. To keep everything local, set `YUNSHU_WEB_SEARCH_PROVIDER=none`.
</Callout>

## Choose a search provider

`YUNSHU_WEB_SEARCH_PROVIDER` selects the backend. The default is `auto`.

| Value | Behavior |
|---|---|
| `auto` | Runs the keyless sources (DuckDuckGo HTML and Wikipedia) and every provider that has credentials in parallel. Results are deduplicated and fused with reciprocal-rank fusion, and each source has health backoff so a failing source stops slowing queries down |
| `none` | Disables server-side search. Requests that declare a search tool get an `unavailable` tool error |
| `searxng`, `brave`, `tavily`, `exa`, `serper`, `perplexity`, `mojeek`, `marginalia`, `ddg_html`, `wikipedia`, `mwmbl` | Use exactly that provider |

DuckDuckGo HTML is best effort: it may block automated queries. `YUNSHU_WEB_KEYLESS=0` turns off the keyless sources (DuckDuckGo and Wikipedia), which leaves only providers you configured.

```bash
# Default: keyless sources plus any configured provider
yunshu serve -m <model> --set web_search_provider=auto

# Keep everything local
yunshu serve -m <model> --set web_search_provider=none

# Add a keyed provider
export YUNSHU_BRAVE_API_KEY=...
yunshu serve -m <model>
```

### Provider settings

All of these are registered in the settings registry and listed in [Configuration](/docs/guides/configuration).

| Setting | Default | Meaning |
|---|---|---|
| `YUNSHU_WEB_SEARCH_PROVIDER` | `auto` | provider selector, see above |
| `YUNSHU_WEB_SEARCH_RESULTS` | `5` | results returned per `web_search` call |
| `YUNSHU_WEB_SEARCH_PROVIDER_TIMEOUT` | `1.0` | per-provider deadline in seconds in metasearch, so a slow source cannot hold up the query |
| `YUNSHU_WEB_KEYLESS` | on | allow keyless DuckDuckGo and Wikipedia |
| `YUNSHU_SEARXNG_URL` | unset | base URL of your own SearXNG instance with JSON output enabled. Optional: the built-in metasearch needs no 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` | unset | credentials for hosted search APIs. A configured key joins `auto` |
| `YUNSHU_WEB_MWMBL` | off | opt in to the Mwmbl small-web index. Its data is CC-BY-NC-SA 4.0 (noncommercial, attribution, share-alike). Choosing `mwmbl` explicitly also opts in |
| `YUNSHU_WEB_SEARCH_HEALTH_FILE` | `~/.yunshu/cache/websearch-health.json` | a small snapshot of provider health. It stores no query text and no result pages |
| `YUNSHU_WEB_RESEARCH` | off | enrich snippets with excerpts from the origin pages (extra fetches: those URLs leave the machine too) |
| `YUNSHU_WEB_RESEARCH_BUDGET` | `4.0` | overall enrichment deadline in seconds (4 at most) |
| `YUNSHU_WEB_RESEARCH_PAGES` | `6` | origin pages per enrichment (6 at most) |
| `YUNSHU_WEB_RESEARCH_MODEL` | unset | id of an already loaded local embedding model used to re-rank excerpts. It never loads a model; without it ranking uses BM25 only |
| `YUNSHU_SERVER_TOOL_MAX_ITERATIONS` | `8` | most generate, run-tool, continue rounds one request may take |

`yunshu config` shows the effective values and the latest provider health snapshot.

## Fetch pages

`web_fetch` downloads a URL and hands the extracted text to the model. It needs no provider and is on by default.

| Setting | Default | Meaning |
|---|---|---|
| `YUNSHU_WEB_FETCH` | on | serve the `web_fetch` tool. Off: requests get an `unavailable` error |
| `YUNSHU_WEB_FETCH_ALLOW_PRIVATE` | off | allow private, loopback and link-local destinations. Leave it off unless you know why you need it |
| `YUNSHU_WEB_FETCH_MAX_BYTES` | `2000000` | largest response body downloaded |
| `YUNSHU_WEB_FETCH_TIMEOUT` | `20.0` | seconds to wait for a page |
| `YUNSHU_WEB_FETCH_MAX_TEXT_CHARS` | `40000` | extracted text handed to the model is cut to this length (a request's `max_content_tokens` can lower it) |

### Network safety rules

The URLs a fetch follows are chosen by the model, and so, through prompt injection, by any web page it read. Yunshu therefore applies one network policy to every outbound fetch (`web_fetch`, the MCP connector and VLM media download):

- Only `http` and `https` URLs are accepted. URLs with embedded credentials, control characters or spaces, a missing host or an out-of-range port are rejected.
- The hostname is resolved first and the **resolved addresses** are checked. Loopback, private, link-local (including cloud metadata addresses), carrier-grade NAT, multicast, reserved and unspecified addresses are refused, and so are IPv4-mapped IPv6 forms of those. The connection is then pinned to an address that passed the check, so a DNS answer that changes between check and connect cannot slip through.
- Redirects are followed one hop at a time (at most 5), and every hop goes through the same check.
- Credentials are bound to the origin that received them. Authorization, API-key and cookie headers are dropped when a redirect changes origin.
- Downloads are limited by `YUNSHU_WEB_FETCH_MAX_BYTES` and `YUNSHU_WEB_FETCH_TIMEOUT`. Only text-like content types (text, JSON, XML, XHTML, JavaScript) are accepted; other types return `unsupported_content_type`.

The MCP connector has its own switch: `YUNSHU_MCP_CONNECTOR_ALLOW_PRIVATE` is on by default because local tool servers are the common case. See [Server tools](/docs/api/server-tools).

Extracted pages are treated as untrusted data. The research enrichment removes hidden elements and invisible control characters and counts suspected instruction text in a metric, but these filters do not guarantee resistance to prompt injection.

## Tool errors

A failed search or fetch does not fail the request. The model gets a tool result with an error code and can continue. Search codes follow Anthropic's `web_search_tool_result_error`: `too_many_requests`, `invalid_input`, `max_uses_exceeded`, `query_too_long` and `unavailable`. Fetch codes follow `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` and `unavailable`. When search is disabled, the error hints at the setting that enables it.

## Local Tavily-compatible API

Yunshu also mounts a local, Tavily-style retrieval API under `/tavily`, for clients written against the Tavily SDKs. It is a separate surface from the model tools above and uses the same providers.

| Route | Purpose |
|---|---|
| `POST /tavily/search` | search, with optional answer generation by the served chat model |
| `POST /tavily/extract` | extract page content |
| `POST /tavily/crawl`, `POST /tavily/map` | crawl a site or list its links (breadth-first, robots rules and host politeness applied) |
| `POST /tavily/research`, `GET /tavily/research/{request_id}` | start a research task and poll it |
| `POST /tavily/feedback`, `POST /tavily/logs` | feedback and log submission |
| `GET /tavily/usage`, `GET /tavily/providers` | local usage estimates and live provider health |
| `POST /tavily/mcp` | native stateless MCP endpoint |

Point the SDKs at the prefix; there is no `/v1` in this API:

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

Things to know:

- It is a local implementation. Credit billing and Tavily's proprietary ranking and research behavior are not reproduced; credits in responses are informational estimates.
- Plain search uses lexical ranking and deduplication and makes no model call. An answer or a research report uses the served chat model, and only when you ask for it.
- `YUNSHU_TAVILY_API_KEY` configures the hosted Tavily service as one of the search providers. It is unrelated to the key your clients send to this local API.
- When `YUNSHU_AUTH_TOKEN` is set, send it as the key. With no token configured the normal local open policy applies.
- The upstream `tavily-mcp` package has its base URL hard-coded and cannot be redirected to Yunshu; use the native `POST /tavily/mcp` endpoint instead.
- Optional Chromium rendering for JavaScript-heavy pages in extract, crawl and map is off by default (`YUNSHU_WEB_RENDER`) and needs the `web-render` extra and an installed browser.

## Support

| Capability | Status |
|---|---|
| Messages `web_search_*` server tool with citations | <Support status="supported">supported</Support> |
| Messages `web_fetch_*` server tool | <Support status="supported">supported</Support> |
| Responses `web_search` / `web_search_preview`, `open_page`, `find_in_page` | <Support status="supported">supported</Support> |
| Responses `web_fetch` tool | <Support status="unsupported">not a Responses tool</Support> |
| Domain filters (`allowed_domains`, `blocked_domains`) | <Support status="partial">applied to results by the server; Responses supports `allowed_domains`</Support> |
| Offline search | <Support status="unsupported">search always needs the network; use `none` to disable</Support> |
| Image search in the Tavily API | <Support status="partial">only through a configured SearXNG or Brave provider</Support> |

## Related

- [Server tools](/docs/api/server-tools)
- [Coding agents and SDKs](/docs/guides/agents)
- [Configuration](/docs/guides/configuration)
- [Messages](/docs/api/messages) and [Responses](/docs/api/responses)


---

<!-- index -->
---
title: Introduction
description: Yunshu is a local LLM and VLM inference engine for Apple Silicon that serves OpenAI- and Anthropic-compatible APIs from one process.
---

Yunshu is a single-node inference engine for Apple Silicon Macs. One process loads a model through Apple's MLX stack (`mlx-lm`, `mlx-vlm`, `mlx-audio`) and exposes OpenAI-compatible and Anthropic-compatible HTTP endpoints on your own machine. Nothing leaves the Mac unless you configure it to.

The focus is large language models and vision-language models: decode speed, time to first token (cold and with a warm prefix cache), prefix reuse, and a complete set of request features such as tools, JSON schema output, stop sequences, logprobs, reasoning output and request cancellation. Other modalities (speech recognition and synthesis, embeddings, image generation) are supported as additional capabilities.

## What you get

- OpenAI-compatible routes such as `POST /v1/chat/completions` and `POST /v1/responses`, and the Anthropic route `POST /v1/messages`. See the [API overview](/docs/api/overview).
- A command line (`yunshu`) for installing, checking, serving and running the engine as a login service. See the [CLI reference](/docs/guides/cli).
- A web console served by its separate lightweight console process for status, models, requests and a playground. See [Console](/docs/getting-started/console).
- Prefix caching with an optional SSD tier, speculative decoding for the Qwen3.5 family, and constrained decoding for JSON schema and grammars.

## How serving works

Yunshu picks a serving path from the model that you load. All GPU work runs on one MLX thread.

| Model | Serving path |
|---|---|
| Any `mlx-vlm` model (vision-language, and the Qwen3.5 / 3.6 / 3.8 family) | The VLM batch runner: continuous batching with per-request sampling, an automatic prefix cache, and image, audio and video input. |
| Qwen3.5-family models | The same round driver, plus speculative decoding (MTP or a matching drafter) on its packed rows. |
| Text-only `mlx-lm` models | A single-request fast path. Concurrent requests are served one after another. |

See [Model support](/docs/guides/model-support) for the details of each path.

## What Yunshu is not

Yunshu serves one machine. It has no multi-node or distributed mode, and it does not aim to maximize batch throughput for many tenants. Authentication supports an optional admin token (`YUNSHU_AUTH_TOKEN`) plus named API keys with scopes, expiry and quotas for this single server.

## How these docs are organised

<Cards>
  <Card title="Getting started" href="/docs/getting-started/install">
    Install Yunshu, serve a first model, manage model files, run it as a login service and open the console.
  </Card>
  <Card title="API reference" href="/docs/api/overview">
    Every route the server registers, with parameters, examples, streaming events, errors and a support status for each feature.
  </Card>
  <Card title="Guides" href="/docs/guides/cli">
    The CLI reference, configuration, model support and troubleshooting, plus guides for agents, web search, prompt caching and structured output.
  </Card>
  <Card title="Developers" href="/docs/developers/architecture">
    Architecture, contributing, verification, the release gate and upstream tracking.
  </Card>
</Cards>

If you are new, follow [Install](/docs/getting-started/install) and then [Quickstart](/docs/getting-started/quickstart).

<Callout type="info">
Each feature in the API reference is marked as supported, partial, accepted and ignored, or not supported. A parameter that the server accepts but does not act on is labelled as such rather than described as working.
</Callout>

## Benchmarks

Release 0.1.5; main is in the 0.1.6 development cycle. [32K / 64K / 128K: results, strengths and gaps](/docs/guides/benchmarks).

## Ask these docs locally

Use **Ask AI** in the docs header or ⌘K / Ctrl+K to ask your attached Yunshu engine. Answers stream with source links; ask follow-up questions, copy or stop the answer, and leave feedback. Start a text model with `yunshu serve -m /path/to/mlx-model` first. No cloud model is used. Questions pause during measurements. Sources are found by local keyword search that ignores filler words, matches Chinese by word pairs, answers from the page language first (English for untranslated pages) and ranks by how many of your words a section covers; no model is used for retrieval.


---

<!-- internals/code-execution-sandbox -->
---
title: Code execution sandbox
description: How the Anthropic code_execution server tool runs model-written commands inside sandbox-runtime (srt) with file, network, time, memory and output limits.
---

The Anthropic `code_execution` tool lets a model run commands and edit files on the machine that serves it. That is only acceptable inside a sandbox. This page explains how Yunshu builds that sandbox, what it limits, and how the tool is exposed to the API. For turning it on and using it from a client, see the [code execution guide](/docs/guides/code-execution).

## What it does

The code lives in `python/yunshu_gateway/sandbox/` and is wired in as a server tool by `server_tools/runtime.py` and `server_tools/anthropic_loop.py`.

- **`srt.py`** finds Anthropic's `sandbox-runtime` CLI (`srt`, optional, needs Node 22.12 or newer) on `PATH` or under `~/.yunshu/srt`, and builds its settings for one container. These are pure functions, testable without `srt`.
- **`supervisor.py`** runs one command with wall-clock, CPU, memory and output limits, which `srt` does not provide.
- **`containers.py`** keeps one workspace directory per container, with idle expiry and a total size cap.
- **`executor.py`** turns a tool call into a sandboxed process. `bash_code_execution` runs under `srt`; `text_editor_code_execution` (`view`, `create`, `str_replace`) runs in-process with paths confined to the container.

The model sees two sub-tools under one declared tool (`code_execution_20250825`, with the `20260120` and `20260521` types accepted and behaving the same). The server runs the tool loop and returns `server_tool_use` and result blocks like the official API.

## Why

Two layers protect the host. `srt` uses macOS `sandbox-exec` for file and network isolation. Yunshu adds what `srt` lacks, because macOS does not enforce `RLIMIT_AS` and `RLIMIT_NPROC` counts every process of the user, so neither is used: a supervisor samples the resident size of the whole process tree, kills it on overrun and sweeps the session afterwards so no daemon is left behind. The rule at the top of the package is absolute: nothing runs a command outside `srt`. If `srt` is missing or cannot run, the request fails (`SandboxUnavailableError`) instead of running unsandboxed.

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

## Policy: what the sandbox allows

`build_settings` produces the policy for one container directory:

| Area | Rule |
|---|---|
| Writes | The container directory only (`work/`, `home/`, `tmp/` and a per-call `out/`) |
| Reads | `/Users`, `/Volumes`, `/home` and the shared containers root are denied. Only this container and the Python interpreter's prefix are allowed back, so your home, keys, `~/.yunshu` and other containers are unreadable. System libraries elsewhere stay readable. |
| Network | None unless hosts are listed. Loopback is never reachable (`allowLocalBinding` is false), and allowed names cannot resolve into private ranges (`10/8`, `172.16/12`, `192.168/16`, `100.64/10`, `fc00::/7`). |
| Other | Unix sockets, Apple Events and `open` are off |
| Environment | The command sees only `PATH`, `HOME` (the container), `TMPDIR`, `OUTPUT_DIR` and locale variables, never the server's environment |

An allowed-domain list does not inspect traffic: allowing a broad host can still leak data, so keep the list short.

## Limits

| Limit | Value | Source |
|---|---|---|
| Wall clock per call (also the CPU-time limit) | `YUNSHU_CODE_EXECUTION_TIMEOUT`, 60 s; then `execution_time_exceeded` | settings |
| Memory | `YUNSHU_CODE_EXECUTION_MEMORY_MB`, 2048; resident size of the whole process tree, sampled every 100 ms, then killed | settings |
| stdout and stderr | 64 KiB each, cut and marked | `supervisor.py` |
| Total output (stdout plus stderr together) | More than 1 MiB in a call kills it (`output_file_too_large`) | `supervisor.py` |
| Size of any single file a command writes | 256 MiB (`RLIMIT_FSIZE`) | `supervisor.py` |
| Concurrent calls | 2 (`MAX_CONCURRENT`) | `executor.py` |
| All containers together | 2 GiB (`MAX_TOTAL_BYTES`), oldest removed first | `containers.py` |
| Container idle expiry | `YUNSHU_CODE_EXECUTION_TTL_MIN`, 20 minutes | settings |
| Files attached per call | 20 (`MAX_FILES_PER_CALL`) | `executor.py` |
| Text-editor view | 200,000 characters | `executor.py` |

Background processes die with the call: the command runs in its own session, and on timeout, memory overrun or output overflow the whole tree is killed.

## Exposure as a server tool

Off by default. With `YUNSHU_CODE_EXECUTION` off, a request that declares the tool gets a `400` naming the setting. On without `srt`, the response is `503` (`api_error`) with the install command. Containers are addressed with `container: "<id>"`; an unknown or expired id is a `400`. `container_upload` blocks copy Files API files into the working directory, and each bash call gets a fresh `$OUTPUT_DIR` whose top-level files become Files API entries.

Violations are logged as metadata only (container id, return code, byte counts). Commands, output and file contents are never logged.

## Guarantees

- No command runs outside `srt`.
- A call cannot read the user's home, `~/.yunshu` or another container, and cannot write outside its container.
- A call cannot exceed its wall-clock, memory or output limits; the whole process tree is killed and swept.
- The sandbox does not inherit the server's environment variables.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_CODE_EXECUTION` | off | Serve the tool |
| `YUNSHU_CODE_EXECUTION_ROOT` | `~/.yunshu/sandbox` | Container directory, one subdirectory per container, mode 0700 |
| `YUNSHU_CODE_EXECUTION_TIMEOUT` | 60 | Seconds per call |
| `YUNSHU_CODE_EXECUTION_MEMORY_MB` | 2048 | Memory per call |
| `YUNSHU_CODE_EXECUTION_NETWORK_ALLOW` | none | Comma-separated hosts the sandbox may reach |
| `YUNSHU_CODE_EXECUTION_TTL_MIN` | 20 | Idle minutes before a container is deleted |

## Differences from Anthropic's container

- It runs on macOS, not Linux x86_64. The Python is the interpreter Yunshu runs on, with the standard library only.
- There is no REPL state between calls and no programmatic tool calling.
- OpenAI `code_interpreter` and `shell` are not served yet.
- The sandbox depends on macOS `sandbox-exec`, which Apple marks deprecated, and `srt` is a 0.0.x release (the guide records 0.0.81 as tested).

## How to verify

```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` exercises a real `srt` when one is installed.


---

<!-- internals/console-process -->
---
title: The console process
description: Why the web console runs as a separate light process, what it proxies and records, how it finds engines, how restarts and launchd fit in, and how a measurement can pause it.
---

The web console is not part of the engine process. `yunshu console` is a separate, light process that serves the console UI, proxies the engine API on one origin and records the engine's history. This page explains the design and its moving parts. For using the console pages, see the console guide in the app; for the settings, see [Configuration](/docs/guides/configuration).

## What it does

The console process (`python/yunshu_console/`) does four things:

- **Serves** the built console and the docs under `/console/` (`app.py`). The shell is public so you can enter a token; inference, model operations, keys and settings keep their normal authorization.
- **Proxies** the engine API: methods, bodies, `Authorization` and `x-api-key`, SSE streams and WebSockets are forwarded unchanged, so the browser talks to one origin. When the engine is unreachable, the proxy answers `502` with `engine_unreachable` at once instead of hanging.
- **Records** history (`poller.py`, `store.py`). Once a second it reads the engine's cheap endpoints (`/v1/yunshu/status`, finished requests by cursor from `/v1/yunshu/requests/recent?after_seq=`, and about every five seconds the host telemetry) and writes them to SQLite in WAL mode, batched every ten seconds.
- **Remembers outages.** While the engine does not answer, no rows are written. That span is the gap, and it is reported as a gap and never interpolated. Events record engine unreachable and reachable again (with duration), engine restarted, model loaded or unloaded, and a model that failed to load.

It answers `/v1/yunshu/metrics/history`, `/v1/yunshu/requests/history` and `/v1/yunshu/console` itself from the store, so history works while the engine is down.

## Why

A monitoring page that dies with the thing it monitors is useless exactly when needed. The console is a sibling process that never imports MLX, mlx-lm or mlx-vlm (a unit test asserts that in a fresh interpreter), so it starts instantly, idles at a small footprint and cannot be reached by an engine crash. The engine does not depend on it either: if the console dies, the engine is unaffected. The engine itself keeps no history and runs nothing for it; every read is an ordinary HTTP request the engine answers on its event loop, the same ones the web console makes.

```mermaid
flowchart LR
    B["Browser"] --> C["Console process :8100"]
    C -->|"proxy, unchanged"| E["Engine :8000"]
    C -->|"1 s poll"| E
    C --> S[("console-history.sqlite")]
    D["Discovery /health probes"] --> C
    P["Pause file"] -.->|"stops polling and probes"| C
```

## History store

`store.py` keeps three tables, each rolled up from the finer one with SQL `AVG` (and `MAX` for peaks) for the buckets a flush touched, so a restart never loses or doubles a partial bucket:

| Table | Resolution | Retention |
|---|---|---|
| `m1` | 1 s | 1 hour |
| `m10` | 10 s | 24 hours |
| `m60` | 1 minute | `YUNSHU_CONSOLE_RETENTION_DAYS` (30) |

The request log keeps metadata only: id, model, route, status, timestamps, token counts, cached tokens, TTFT, decode speed and finish reason. Prompts and outputs are never stored; the engine's finished-request entries hold none, and `request_row` drops anything not on its whitelist. The file is capped by `YUNSHU_CONSOLE_DB_MAX_MB` (64): when exceeded, the oldest request rows and then the oldest 1-minute rows go first.

The request cursor is `(boot_id, seq)`. The first read after the console starts takes everything in the engine's ring; later reads take only what is new; a changed `boot_id` (the engine restarted) starts the sequence over. Rows are keyed by `(t, request_id)`, so even a replay writes nothing twice.

## Engine auto-discovery

`yunshu console --engine auto` (or `YUNSHU_CONSOLE_ENGINE=auto`) lets one console stay open while engines start and stop on different ports (`discovery.py`).

- Every `YUNSHU_CONSOLE_DISCOVER_S` (2 s) each candidate gets an asynchronous `GET /health` with a short timeout. With `YUNSHU_CONSOLE_DISCOVER_PORTS=all` the candidates are the TCP ports listening on this Mac (via `lsof`, refreshed every 10 s) minus console processes, which proxy `/health` and would look like the engine behind them. An explicit list such as `8000,18990-18999` probes exactly those ports on `127.0.0.1`.
- A port counts only when `/health` answers like a Yunshu engine: `status: "ok"`, an `engine` object, a `server_state` and a numeric `uptime_seconds`. A port that answered as something else is asked again after 60 s.
- Selection is sticky. The followed engine is kept while healthy; when it disappears (two missed probes in a row) the console follows the most recently started live engine (smallest uptime). An engine pinned by the user wins while it is live.
- `/v1/yunshu/console/engines` lists engines; `/v1/yunshu/console/engines (POST)` with `{"url": ...}` or `{"port": ...}` pins, and `{"url": null}` unpins.
- The history stores the engine URL and start time with each request, so a restart shows as a separate session, and an `engine_switched` event marks a move. A stream already open to the old engine is not cut.

## Lifecycle, restarts and launchd

| How you start it | What runs |
|---|---|
| `yunshu serve -m <model>` | the engine, plus the console process as a sibling (`--no-console` skips it, `--console-port` moves it). If a console already answers on the port, none is started. The sibling exits with the engine. |
| `yunshu console --engine URL` | the console alone, to watch an engine elsewhere (`--engine-token` when it needs one) |
| `yunshu service install` | two launchd jobs: the engine and the console as its own always-kept-alive job, so recording continues while the engine restarts. `--no-console` installs the engine only; `yunshu service logs --console` shows the console log. |

Under the service, the engine is started with `--no-console` because the console is its own job.

- **Restart from the console.** A setting that requires a restart is written with `PATCH /v1/yunshu/config`; the response lists `restart_for`. `POST /v1/yunshu/service/restart` with `confirm: true` drains active requests for up to `YUNSHU_DRAIN_TIMEOUT` seconds and then runs `launchctl kickstart -k`. Outside launchd it answers `409 not_under_launchd` with the manual command; the console never owns the engine process. These routes need the `admin` permission.
- **Calm outages.** While the engine is down, the UI shows "Engine restarting" with the typical time (the median of recorded outages, `outages` in `/v1/yunshu/console`), dims stale pages and fills the missed stretch from recorded history when the engine returns. Only 60 s without any live engine becomes a warning.
- **Deployment health.** The recorder also tracks process footprint and its 15 to 30 minute regression slope and the request error rate. A slope above 1 GiB per hour, or at least 5% failed requests among 20 or more completions in the last minute, raises a console alert and one warning event. Cancellation is excluded from the error rate. This is a reason to inspect the memory ledger, not a leak diagnosis.

## Measurement pause

A monitor that polls only one arm of an A/B perturbs the measurement. While the file named by `YUNSHU_CONSOLE_PAUSE_FILE` exists and holds `{"pause": true, "until": <epoch or null>, "reason": "..."}`, the poller and the discovery probes send nothing to any engine (`pause.py`). The file stops counting after `until`, or two hours after its last write when `until` is null, and the console resumes by itself when it is removed. The proxy still forwards requests you make yourself, and the status island shows the reason. `gpuq` writes the file while a quiet or speed job runs.

## Guarantees

- The console never imports MLX and holds no GPU work; an engine crash cannot reach it.
- Gaps are reported as gaps, never interpolated; missing data is shown as unavailable, never as zero.
- Request rows carry metadata only. No prompt or output text is recorded.
- Request cursors never skip or repeat a request across polls, engine restarts or console restarts.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_CONSOLE` | on | `yunshu serve` also starts the console process |
| `YUNSHU_CONSOLE_PORT` | 8100 | Console port |
| `YUNSHU_CONSOLE_HOST` | unset | Bind host; unset follows the engine's host for the sibling and 127.0.0.1 standalone |
| `YUNSHU_CONSOLE_ENGINE` | unset | Engine URL to watch; `auto` follows engines |
| `YUNSHU_CONSOLE_ENGINE_TOKEN` | unset | Bearer token for reading the engine; falls back to `YUNSHU_AUTH_TOKEN` |
| `YUNSHU_CONSOLE_DISCOVER_PORTS` | `all` | Ports probed in auto mode |
| `YUNSHU_CONSOLE_DISCOVER_S` | 2.0 | Seconds between probes |
| `YUNSHU_CONSOLE_POLL_S` | 1.0 | Seconds between engine reads |
| `YUNSHU_CONSOLE_HISTORY` | on | Record history and the request log |
| `YUNSHU_CONSOLE_DB` | `~/.yunshu/console-history.sqlite` | History file |
| `YUNSHU_CONSOLE_RETENTION_DAYS` | 30 | Days of 1-minute rows, requests and events |
| `YUNSHU_CONSOLE_DB_MAX_MB` | 64 | Size cap |
| `YUNSHU_CONSOLE_PAUSE_FILE` | unset | Measurement pause file |

## Limits

- It is an operator tool for one machine. Serving the network (`--host 0.0.0.0`) needs a token set.
- Restart from the UI works only when the engine runs under the `yunshu` launchd service.
- History resolution is bounded by the tables above; request detail older than the retention is gone.

## How to verify

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

The no-MLX-import rule is `test_nothing_in_the_console_process_loads_mlx` in `tests/unit/test_console_proxy.py`.


---

<!-- internals/constrained-decoding -->
---
title: Constrained decoding
description: How JSON schema, regex, choice, grammar and tool-call constraints are enforced token by token, the two engines behind them, and how they interact with speculative decoding.
---

Constrained decoding makes the model's output follow a format by masking the next-token choice at every step. This page explains how Yunshu does it, for people who read or change the code. For the request fields and examples, see [Structured output](/docs/guides/structured-output).

## What it does

A constraint is a small state machine that, given the tokens generated so far, says which tokens may come next. The sampler sets every other token's logit to negative infinity before choosing. The supported constraint kinds are:

| Kind | Request form | Implementation |
|---|---|---|
| JSON schema / `json_object` | `response_format`, `guided_json`, `structured_outputs` | llguidance by default, the in-house state machine as the alternative (`YUNSHU_JSON_SCHEMA_ENGINE`) |
| Regex | `guided_regex` | `RegexConstraint`, an in-house character DFA over a documented regex subset |
| Choice | `guided_choice` | `ChoiceConstraint`, a trie over the strings |
| Context-free grammar | `grammar` (Lark syntax) | `CfgGrammarConstraint` on llguidance |
| Structural tags | `response_format.type = structural_tag` | llguidance, free text until a trigger |
| Tool calls | `tools` with `tool_choice` | `ToolCallGuide` (see [Tool-call parsing](/docs/internals/tool-call-parsing)) |

`ConstraintFactory.create` maps a grammar type to the constraint object. All constraints share one interface: `advance`, `get_allowed_tokens`, `is_done` and `reset`.

## Why

Two engines exist because they trade differently. The llguidance engine is a native Earley/lexer parser: the registry records about 0.25 ms median per-token mask on a 248K vocabulary, properties come out in schema order, and forced literals use canonical tokenization. The in-house Python state machine is slower (about 3 ms median in the registry text), accepts any property order, and is the fallback when llguidance cannot compile a schema or cannot bind a tokenizer (it needs a Hugging Face fast tokenizer). A schema that neither engine can enforce is rejected up front rather than half-applied (`build_json_constraint`, `validate_constraint_spec`).

The text fast path then turns a constraint into a sampler in one of two ways:

- **Allowlist sampler (default).** `ConstrainedSampler` asks the constraint for the allowed token ids at each step and masks the logits.
- **Bitmask engine (opt-in).** `YUNSHU_GRAMMAR_BITMASK=1` selects `BitmaskConstrainedSampler`, which keeps a boolean vocabulary mask and applies it with one vectorised `mx.where`. If building the bitmask engine fails, the code logs at debug level and falls back to the allowlist path.

The VLM runner works on bitmasks natively: `ConstraintGuide` wraps a serial `ConstraintProcessor` and exposes `mask()` as a packed int32 bitmask, which llguidance fills directly.

```mermaid
flowchart TD
    A["Request constraint"] --> B["prepare_constraint: compile off the event loop"]
    B --> C{"Kind"}
    C -->|"json schema"| D["llguidance, else in-house"]
    C -->|"regex or choice"| E["in-house RegexConstraint or ChoiceConstraint"]
    C -->|"grammar or structural tag"| F["llguidance"]
    D --> G["Per request matcher state"]
    E --> G
    F --> G
    G --> H["Token mask at each step"]
    H --> I["Sample from allowed tokens"]
    I --> J["Advance matcher with the token"]
    J --> H
```

## Compilation and admission

`prepare_constraint` (`yunshu_engine/grammar_compile.py`) compiles and validates a constraint off the event loop before the request is admitted: at most 32 queued submissions per event loop and two active CPU workers. Compiled artifacts live in a bounded LRU `ArtifactCache` with single-flight construction; failed artifacts are never retained and oversized inputs bypass retention. Mutable matchers always belong to one request, never to the cache. Cancellation never exposes a half-built artifact.

## Interaction with speculation

On the Qwen3.5 packed rows (MTP and DFlash) the same constraint object serves both the serial path and the verifier. `yunshu_engine/constrained_spec.py` provides this:

- **Transactions.** `ConstraintGuide.checkpoint`, `feed` and `restore` let the verifier walk a window of drafted tokens, build one mask per position with `plan(drafts, n_pos)`, and then roll back. Walking proposals never changes the committed grammar state.
- **Forced tokens.** `forced_tokens` jumps only over positions whose mask has a single legal token. The module notes that forced bytes can have several BPE tokenizations, so llguidance's byte fast-forward alone would not be token-exact.
- **Arithmetic.** A response-format or logprob row verifies with serial one-row arithmetic (`exact_verify`) so a constrained request decodes the same tokens with speculation on or off. A request whose only guide is a tool-call guide (`invariant_guide`) keeps the batch-invariant kernels: free text under it is unmasked, and inside a call the mask only restricts the argmax of a row whose logits the invariant kernels already make equal.
- **Dead ends.** An empty allowed set is never answered with the unconstrained argmax. At an accepting state the normalised EOS ids are legal; if nothing is legal, `ConstrainedDecodingError` fails the request closed.

## Jump-forward and tool grammar

- `YUNSHU_JUMP_FORWARD` (off): for greedy JSON-schema generation on the text path, tokens the grammar forces are emitted without a forward pass. The code turns it off for LoRA, cancel events, logit bias, suppressed tokens, `min_tokens`, logprobs, sampling and regex/choice/grammar constraints, so those requests use the normal constrained decode.

## Guarantees

- A constrained output is accepted by the constraint, or the request fails; an empty allowed set is never papered over with the unconstrained argmax.
- Speculation on and off give the same tokens for constrained requests (serial verify arithmetic), apart from tool-call-guide-only requests, which keep the invariant arithmetic by design.
- The mask never removes a valid continuation, so constraints do not change what a model would validly have written.
- A parsed tool call is not a strict-schema proof when a grammar and tokenizer combination is unsupported and the unconstrained fallback runs.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_JSON_SCHEMA_ENGINE` | `llguidance` | Preferred engine for JSON schema and `json_object`; `inhouse` selects the Python state machine |
| `YUNSHU_GRAMMAR_BITMASK` | off | Text engine: bitmask sampler instead of the allowlist sampler |
| `YUNSHU_JUMP_FORWARD` | off | Text engine: emit grammar-forced tokens without a forward pass |

## Limits

- Regex support is a subset; `UnsupportedRegexError` names what is outside it. Context-free grammars need llguidance.
- A schema neither engine can enforce is rejected, not approximated.
- On the VLM path, tools combined with an ordinary JSON or grammar constraint are rejected, and a forced tool choice combined with structural tags is rejected, so independent contracts cannot silently override each other.
- Constraints add per-token CPU work. They are not free on small models.

## How to verify

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

The `toolparse` suite of the verify tool checks forced, streaming and lazy structural-tag output over real HTTP (see [Verification](/docs/developers/verification)).


---

<!-- internals/memory -->
---
title: Memory management
description: How Yunshu budgets, accounts for and gives back unified memory - cache budgets, the idle trim and keep-warm heartbeat, admission under pressure, and model eviction in multi-model mode.
---

Memory is the first constraint of a local engine: weights, the KV cache, the prefix cache and MLX's own allocator pool all live in the same unified memory as your applications. This page describes how the code budgets that memory, shows who holds it, and returns what is no longer needed. It states only what the code does; for the settings see [Configuration](/docs/guides/configuration).

## What it does

Four mechanisms cooperate. None of them changes model output.

- **Budgets** cap the caches that can grow: the VLM prefix cache (APC) in RAM and on SSD, the MLX freed-buffer pool kept across prefill steps, and, for text models, the prefix cache and SSD cache.
- **Accounting** answers "who holds the memory". `GET /v1/yunshu/memory` returns a ledger of owners (`yunshu_gateway/memory_ledger.py`) built only from counters the process already keeps. A figure with no source is `null`, and an owner attributed by subtraction is marked `estimated: true`.
- **Idle return** (`yunshu_engine/idle_memory.py`) gives memory back after the runner drains: a cycle-garbage collection, then a trim of MLX's buffer pool and free malloc pages.
- **Pressure control** refuses new work that would run the process out of memory, and in multi-model mode evicts models (`ModelManager`, `ProcessMemoryEnforcer`).

## Why

A server that "did not OOM" is not good enough for a machine people also use for other work. The design rule is that every retained GiB has an owner you can name, and that an idle server returns what it does not need. The one exception is deliberate: a bounded pool of freed MLX buffers stays between requests because the next cache restore and prefill reuse those buffers, and it is released by the idle trim.

## Idle return and keep-warm

When the VLM runner has no work left it calls `IdleMemory.drained()`; a new request calls `activity()` and cancels whatever is pending.

- After `COLLECT_AFTER_S` = 2 s one `gc.collect()` runs. Arrays held only by reference cycles (the finished request's generator, closures, caches) would otherwise wait for Python's cyclic collector, which may not run for a long time on an idle server. The delay keeps back-to-back requests from paying for it.
- After `IDLE_TRIM_S` = 30 s without a request the trim runs: restore buffers are cleared, MLX's allocator pool is released, and on macOS `malloc_zone_pressure_relief` returns free malloc pages. Live objects stay allocated.
- Between those, a **keep-warm heartbeat** every `HEARTBEAT_S` = 1 s holds the Metal wired-memory limit at the device's recommended working set and runs a tiny matmul that touches no model array. Without it Metal stops keeping the weights resident after about 2 s and the next request re-pins them. The source records about 200 ms for the 27B (measured 2026-10-22: idle follow-up TTFT 0.23 s within 2 s, 0.44-0.66 s from 4 s on). The trim restores the previous wired limit.

The timer thread only submits work. Every MLX call runs on the serialized MLX executor, and each stage re-checks that the runner is still idle.

The following diagram shows the idle schedule after a request ends.

```mermaid
stateDiagram-v2
    [*] --> Busy
    Busy --> Draining: "runner drains"
    Draining --> Collected: "2 s: gc.collect"
    Collected --> Trimmed: "30 s: release pool and wired limit"
    Draining --> Busy: "new request"
    Collected --> Busy: "new request"
    Trimmed --> Busy: "new request"
    note right of Draining
        1 Hz heartbeat holds the wired limit
    end note
```

## Budgets

| Owner | Budget | Default behavior |
|---|---|---|
| APC RAM (VLM runner) | `YUNSHU_VLM_APC_MEMORY_GB` | Half of the memory left after weights and a reserve, capped at a quarter of the machine and 32 GiB; off when under 1 GiB would remain |
| APC SSD tier | `YUNSHU_VLM_APC_DISK_GB` | A quarter of the volume, at most 64 GiB; one budget for the whole directory, least recently used files go first |
| Further APC tiers | `YUNSHU_VLM_APC_DISK_TIERS` | Unset: SSD only |
| MLX freed-buffer pool | `YUNSHU_PREFILL_BUFFER_CACHE_GB` | 5% of RAM, at most 6 GiB; 0.5 GiB when the weights leave little headroom |
| Drafter windows beside APC | `YUNSHU_VLM_APC_DRAFT_WINDOW_GB` | 0.25 GiB |
| Text prefix cache eviction | `YUNSHU_MEM_PRESSURE_THRESHOLD` | Evict entries above 85% memory use |
| Text SSD cache | `YUNSHU_SSD_CACHE_MAX_GB` | 10 GiB |
| Prefill activation peak | `YUNSHU_PREFILL_STEP_SIZE` | 2048 prompt tokens per forward pass |

The RAM and SSD budgets are single budgets: the optional WARM tier takes `YUNSHU_VLM_APC_WARM_SHARE` (default 0.4) of the APC RAM budget, so total APC RAM does not grow. See [Prompt caching](/docs/guides/prompt-caching) for the tiers themselves.

## Pressure control and model eviction

**Admission.** `yunshu_gateway/admission.py` computes pressure as MLX active memory over the recommended Metal working set. While other requests are running and pressure is at or above `YUNSHU_MEMORY_PRESSURE_REJECT` (default 0.95), a new generation request gets `503` with `Retry-After`. An idle server never refuses; `0` turns the check off.

**Multi-model mode.** `ModelManager` loads models lazily and keeps an entry per model with `is_pinned`, an optional `keep_alive_s` and a lease count.

- Before a load, `_ensure_memory_available` evicts least-recently-used models until the new one fits under `max_memory_bytes`. If no victim can be evicted it raises `MemoryError` rather than looping.
- A victim must be loaded, not pinned, not leased by an in-flight request and provably idle (`_find_lru_victim`). A non-forced unload is refused for an engine that cannot be proven idle.
- After an unload the manager polls until Metal has actually released the buffers (a settle barrier, `settle_timeout_s` 5 s) and uses the measured delta.
- Idle unload uses `effective_keep_alive`: the model's own `keep_alive` (the Ollama-style `keep_alive` field on requests), else `YUNSHU_MODEL_TTL_SECONDS` (unset: never). Pinned models are never unloaded for idleness.
- `ProcessMemoryEnforcer` polls MLX active memory against `YUNSHU_MAX_MEMORY_GB` (unset: 80% of unified memory; `disabled` turns it off) and evicts the least-recently-used model when over. When only one unpinned model is loaded it stays loaded and its requests keep running; the enforcer only logs a warning.
- `GET /v1/yunshu/models/{id}/fit` dry-runs the load-time check (`ModelManager.fit_check`).

In single-model mode the model is reported as pinned and is never freed.

## Memory admission

The engine degrades or waits instead of swapping, and says why (`YUNSHU_MEMORY_ADMISSION`, on by default; scheduling only, outputs are unchanged).

1. **Load time.** Before the weights are read, `plan_load` checks weights + OS reserve (`YUNSHU_MEMORY_RESERVE_GB`, default 5% of RAM, at least 4 GiB) + a minimum KV and working set against physical memory (or `YUNSHU_MAX_MEMORY_GB`). A load that cannot fit is refused with a clear `MemoryError` that names a `-ple-ssd` view of the checkpoint when one sits next to it. After the load the APC RAM budget shrinks to what the resident weights leave, and the log line `Memory plan:` says by how much.
2. **Request admission.** A new request's KV (prompt + `max_tokens`) and prefill workspace are checked against the live headroom: macOS free + inactive + purgeable pages, MLX's reclaimable buffer cache, the kernel pressure level, swap growth, minus the part the running requests will still grow into. A request without headroom waits in the queue. The first request of an idle server is always admitted, unless it cannot fit even alone (its KV and prefill workspace exceed what the Metal recommended working set leaves after the weights): it is refused with HTTP 507, `error.code: memory_limit` and the numbers, instead of running every request out of Metal memory. The wait is visible as `queue_reason: "memory"` and `queue_detail` in the live progress payload, `x_yunshu.reasons.queue.waited_ms` in the response, and the `yunshu_memory_admission_*` metrics.
3. **Shedding.** When available memory falls below the reserve (or the kernel reports warning pressure), APC RAM entries are dropped oldest first, to the SSD tier where it is configured, before anything swaps (`yunshu_memory_pressure_sheds_total`, `yunshu_memory_pressure_shed_bytes_total`).

## Guarantees

- Idle return, buffer-pool sizing and the keep-warm heartbeat do not change output. The heartbeat's matmul touches no model array, and the pool setting is described in the registry as "allocator only; output unchanged".
- The ledger reads counters only. It runs no GPU work, does not walk the garbage collector and starts no subprocess. All `*_gb` fields are binary GiB with exact `*_bytes` beside them.
- Lossy memory savers are user options with a lossless default, and a benchmark never turns one on: `YUNSHU_KV_PRECISION=int8`, `YUNSHU_VLM_APC_WARM=int8|int4`, `YUNSHU_KV_QUANT_BITS`, `YUNSHU_PREFIX_HOT_LIMIT`, `YUNSHU_SSD_CACHE_PRECISION=int8` and `YUNSHU_QUANT_MODE`.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_MAX_MEMORY_GB` | unset (80% of unified memory in multi-model mode) | Process memory ceiling for the enforcer; `disabled` turns it off |
| `YUNSHU_MODEL_TTL_SECONDS` | unset | Multi-model: unload a model idle for this long |
| `YUNSHU_MEMORY_PRESSURE_REJECT` | 0.95 | Refuse new requests above this share of the Metal working set while busy |
| `YUNSHU_MEMORY_ADMISSION` | on | Queue requests without memory headroom, shed APC RAM under pressure, fit the APC budget at load |
| `YUNSHU_MEMORY_RESERVE_GB` | 5% of RAM, min 4 | Memory kept free for macOS |
| `YUNSHU_VLM_APC_MEMORY_GB` | computed | APC RAM budget; 0 disables the cache |
| `YUNSHU_PREFILL_BUFFER_CACHE_GB` | computed | Freed-buffer pool kept across prefill steps |
| `YUNSHU_PREFILL_STEP_SIZE` | 2048 | Text engine prefill chunk; lower to cap the activation peak |
| `YUNSHU_FOOTPRINT_SAMPLE_MS` | 0 (off) | Sample `phys_footprint` and export the peak on `/metrics` |

On tight hosts the INFERENCE guide's soak measurement used `YUNSHU_VLM_APC_MEMORY_GB=4` and `YUNSHU_PREFILL_BUFFER_CACHE_GB=1` (27B; it lowered the peak, the figures are not in the benchmark log). `YUNSHU_MAX_MEMORY_GB` is only needed on multi-model hosts.

## Limits

- The idle schedule belongs to the VLM runner. Text-only `mlx-lm` models have their own prefix-cache eviction (`YUNSHU_MEM_PRESSURE_THRESHOLD`) but not this heartbeat and trim.
- The ledger's weight figure falls back to the model manager's estimate when a measured value is unavailable, and says so with `estimated: true`.
- `yunshu_engine/memory_census.py` can name the holder of each live array, but it walks the object graph and pauses the interpreter, so it is diagnostic only and never runs on the serving path.
- Eviction needs an idle engine. A model with an active request or a lease is never unloaded.

## How to verify

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

The first command lists every owner with its source and whether it is estimated. In the server log, `idle memory:` lines show the collect, the trim and the wired-limit hold and release. The retained-memory soak test is `tests/unit/test_soak_retained_memory.py`.


---

<!-- internals/overview -->
---
title: How Yunshu works
description: A map of the engine internals - the serving model, the request path, the prefix cache, speculative decoding, prefill and memory - with a link to a page for each part.
---

These pages explain how Yunshu works inside, for people who read or change the code or who want to know exactly what a setting does. They state only what the code does. For the package layout see [Architecture](/docs/developers/architecture); for tunable behavior see [Configuration](/docs/guides/configuration).

## What it does

Yunshu is one process: a FastAPI gateway in front of an MLX-based engine on Apple Silicon. A request passes through middleware and a router, is dispatched by `ModelManager` to the engine for its model, and ends as tokens that the gateway turns into the dialect's response or stream. Three ideas shape everything else:

- **Two serving paths.** Every `mlx-vlm` model (`VLMEngine`) is served by the VLM batch runner (`vlm_batch_runner.py`, built by `VLMEngine._build_batch_runner`), which hosts the round driver (`round_driver/`). Text-only `mlx-lm` models use a single-request fast path (`_generate_fast`, which calls mlx-lm's `generate_step`); concurrent requests to such a model are serialized.
- **One MLX thread.** All GPU work runs on a single-worker executor that owns the Metal stream. Nothing touches MLX arrays from the event loop.
- **Identity rules.** A cache hit equals a miss, speculation on equals speculation off, and rehearsal never changes outputs. Each internals page states which rule applies and how it is checked.

## Why (design decision)

Yunshu is a single-node engine, so it optimizes time to first token, decode speed and prefix reuse for one machine rather than throughput across tenants. Optimizations stay lossless by default; lossy ones (for example int8 KV) are explicit user options. A custom Metal kernel is adopted only when a same-checkpoint comparison shows a real end-to-end win with identical or tolerance-checked output.

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

The map above shows where each internals page sits on the path of a request.

## Guarantees (identity rules)

| Rule | Page |
|---|---|
| A prefix-cache hit returns the same tokens as a cold prefill | [Prefix cache](/docs/internals/prefix-cache) |
| Greedy output with speculative decoding on equals output with it off | [Speculative decoding](/docs/internals/speculative-decoding) |
| Next-turn rehearsal and prompt piece sizes do not change outputs | [Prefill and rehearsal](/docs/internals/prefill-and-rehearsal) |

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_VLM_DRAFT` | unset | Override the speculative drafter for the Qwen3.5 family |
| `YUNSHU_VLM_APC_MEMORY_GB` | derived from free memory | RAM budget of the prefix cache; `0` disables it |

Every setting is registered in `python/yunshu_engine/settings.py`; `yunshu config` prints the effective values and their sources.

## Limits

Yunshu has no multi-node mode and does not aim at multi-tenant throughput. Speculative decoding runs on the round driver, so concurrent rows draft together.

## How to verify

Run `yunshu config` to see effective settings, and read [Verification](/docs/developers/verification) for the `yv` tool that checks each identity rule.

## Pages

<Cards>
  <Card title="Request lifecycle" href="/docs/internals/request-lifecycle">
    Gateway, middleware, router, engine dispatch, the runner, the MLX thread and the stream back.
  </Card>
  <Card title="Prefix cache" href="/docs/internals/prefix-cache">
    Exact checkpoints, 64-aligned cuts, media keys, the RAM and SSD tiers.
  </Card>
  <Card title="Speculative decoding" href="/docs/internals/speculative-decoding">
    DFlash2 and MTP drafting, batch-invariant verify kernels and the round driver's packed rows.
  </Card>
  <Card title="Prefill and rehearsal" href="/docs/internals/prefill-and-rehearsal">
    Split-invariant prefill and next-turn rehearsal.
  </Card>
  <Card title="Memory" href="/docs/internals/memory">
    Where memory goes and how idle memory is returned.
  </Card>
  <Card title="Constrained decoding" href="/docs/internals/constrained-decoding">
    JSON schema, regex and grammar enforcement while decoding.
  </Card>
  <Card title="Tool-call parsing" href="/docs/internals/tool-call-parsing">
    How model output becomes tool calls.
  </Card>
  <Card title="Console process" href="/docs/internals/console-process">
    The separate lightweight process behind the web console.
  </Card>
  <Card title="Code execution sandbox" href="/docs/internals/code-execution-sandbox">
    How server-side code execution is isolated.
  </Card>
</Cards>


---

<!-- internals/prefill-and-rehearsal -->
---
title: Prefill and rehearsal
description: How prefill gives the same tokens whatever the piece length (split-invariant prefill, 64-aligned checkpoints) and how next-turn rehearsal prefills a reply while idle without changing outputs.
---

Prefill turns a prompt into KV state. Two features make long, repeated prompts cheap without changing what the model says: split-invariant prefill, which makes cached and cold runs arithmetically the same, and next-turn rehearsal, which does the prefill of the next turn while the engine is idle.

## What it does

**Split-invariant prefill.** On the qualified path (Qwen3.8-27B on an M5-class Mac with the MLX version Yunshu pins), prefill uses one kernel family for every piece length:

- matmul: native NAX GEMM, with short pieces padded to 64 rows and the output cropped (`YUNSHU_PREFILL_MATMUL`);
- attention: BQ32 tile attention for any query length (`YUNSHU_PREFILL_ATTENTION`);
- GatedDeltaNet recurrence: the chunked update, with short tails padded to 64 using identity updates that keep the fp32 state exact (`YUNSHU_PREFILL_GDN`).

Prompt pieces and APC checkpoints are cut at **absolute 64-token boundaries**, so a prompt computed in one go, in pieces, or resumed from a checkpoint passes through the same arithmetic. Kernels live in `python/yunshu_engine/kernels/` (`nax_prefill.py`, `gdn_prefill.py`, `attn_prefill.py`).

**Next-turn rehearsal** (`python/yunshu_engine/next_turn.py`, driven from `VLMEngine`). A chat follow-up resends the conversation including the reply the engine just decoded. The cache holds the prompt of the finished turn, so the follow-up would have to prefill that reply. Decode-time KV cannot be reused, because decode and prefill arithmetic differ. Instead, after a reply is delivered and the engine is idle, it renders the conversation with the reply where it will sit next turn and prefills it as an ordinary request with `max_tokens=1`, which stores exact APC checkpoints. A request that arrives later restores them and prefills only the remainder and its new message.

- `YUNSHU_NEXT_TURN_PREFILL` defaults to `stride`: rehearsal stops at the last absolute 64-token boundary at or before the end of the assistant text. A short reply that adds no full atom triggers no replay of an older prefix.
- Rehearsal starts after `YUNSHU_NEXT_TURN_DELAY_S` (default 0.3 s), so an immediate follow-up, as in an agent loop, arrives before any rehearsal work starts and prefills once. A matching request that arrives during rehearsal adopts the work in progress; a diverging one cancels it at the next preemptible boundary.
- Only plain-text chats are rehearsed: the reply must finish with `stop` or `length`, have 16 to 4096 tokens, and the request must have no media, no tools and no constrained decoding (`next_turn.ineligible_reason`).

**Rows, not batches.** Every request is a round-driver row from admission, so there is no batch-to-lane promotion step (see [Speculative decoding](/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
```

The diagram shows the lifecycle of a rehearsal: it only runs while nothing else does, and any real request takes priority.

## Why (design decision)

A cache hit can only equal a miss if both run the same arithmetic. Making prefill split-invariant removes the dependence on where a prompt was cut, which is what lets a stored checkpoint, a rehearsed prefix and a cold prefill agree. Rehearsal then spends idle GPU time on work the next request would otherwise do on the critical path. Cross-version drift in cold outputs is accepted when the accuracy gate passes, while identity within one version is the hard gate.

## Guarantees

- **Rehearsal is an ordinary request whose result is discarded.** It uses the normal prefill path, so it cannot change an output; it only decides what is already cached when the next request arrives.
- **Cold, cached and rehearsed prefixes yield the same tokens** on the split-invariant path.
- **Decode-time KV is never stored** by rehearsal, only prefill checkpoints.
- `boundary` and `exact` add assistant-end splits and can change multi-turn floating-point rounding. They are explicit opt-ins, not defaults.
- Rehearsal costs idle GPU time and one extra cached prefix. It does not remove the measured latency of an immediate follow-up in every case; see [Benchmarks](/docs/guides/benchmarks).

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_NEXT_TURN_PREFILL` | `stride` | `off`, `stride`, `boundary` or `exact` |
| `YUNSHU_NEXT_TURN_DELAY_S` | `0.3` | Seconds between a finished reply and rehearsal; `0` starts as soon as idle |
| `YUNSHU_PREFILL_MATMUL` | `stock` | Prefill matmul on the qualified path (native NAX, short pieces padded to 64) |
| `YUNSHU_PREFILL_GDN` | `chunked` | Prefill recurrence; short tails padded with identity updates |
| `YUNSHU_PREFILL_ATTENTION` | `tile` | BQ32 NAX attention for any query length |
| `YUNSHU_PREFILL_STEP_SIZE` | `2048` | Text engine only: prompt tokens per prefill pass |

## Limits

- The split-invariant path is qualified for one model, chip family and MLX version; elsewhere the older prefill atom grid is kept.
- Rehearsal covers plain-text chats on the VLM runner, not media, tool or constrained requests, and not text-only `mlx-lm` models.
- Changing the prefill arithmetic starts a new APC namespace, so checkpoints from an earlier arithmetic are not reused.

## How to verify

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

Check a real server by sending the same conversation cold and after a rehearsal, with `temperature` 0, and compare tokens; `x_yunshu.cache` and `usage` show the cached tokens. The `yv` tool runs this class of check as its cache-exact stage (see [Verification](/docs/developers/verification)). Cache storage is described in [Prefix cache](/docs/internals/prefix-cache).


---

<!-- internals/prefix-cache -->
---
title: Prefix cache
description: How the automatic prefix cache (APC) stores exact checkpoints, keys them by tokens and media, spills to SSD, and why a hit returns the same tokens as a cold prefill.
---

This page explains the internals of the prefix cache on the VLM batch runner. For the client-facing side (usage fields, `cache_control`, headers) see [Prompt caching](/docs/guides/prompt-caching); that content is not repeated here.

## What it does

When a new prompt starts with the same tokens as an earlier one, the engine restores the stored state for that prefix and prefills only the rest. The state is an **exact checkpoint**: the attention KV plus, for hybrid models such as the Qwen3.5 family (attention mixed with GatedDeltaNet layers), the recurrent state, both at one token position. A checkpoint is reusable only by a prompt that begins with exactly those tokens.

- **Keys.** Text is keyed by token ids. Image input is keyed by a hash of the pixel values (`VLMBatchRunner._image_hash`, from the source image digest), audio by its features, so the same picture reuses the cache and a different one does not.
- **Cut points.** Prompt pieces and checkpoints are cut at absolute 64-token boundaries on the qualified split-invariant path, so a cold run and a cached run process the same pieces. See [Prefill and rehearsal](/docs/internals/prefill-and-rehearsal).
- **Policy** (`python/yunshu_engine/apc_manager.py`, `YunshuAPCManager`): a byte budget limits RAM; a request's checkpoints supersede earlier checkpoints that are prefixes of it, so a long session holds one copy; the end of the system turn (system prompt plus tool list) is kept as its own head checkpoint per distinct head, so a new session in the same project reuses it.
- **Tiers.** HOT is full-precision RAM. WARM is an optional compact RAM form (`apc_warm.py`). SSD is the persistent tier (`apc_storage.py`); further directories can be added as lower storage tiers.

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

The lookup picks the cheapest candidate over all tiers, then prefills only the part that no checkpoint covers.

## Why (design decision)

- **Exact checkpoints, not approximate reuse.** A restored checkpoint is the stored arrays, so a hit does not introduce error. Decode-time KV is never reused for the next turn, because decode and prefill arithmetic differ and the cache would not equal a miss.
- **Budget, not entry count.** The RAM budget is bytes. Unset, it is half of the memory left after weights and an OS and activation reserve, at most a quarter of the machine and 32 GiB, and the cache turns itself off when under 1 GiB would remain.
- **SSD on by default.** A reload is far cheaper than recomputing a long prefix, and it survives a restart. Evicted checkpoints go to disk when RAM drops them, and resident ones are written at shutdown, within a time limit. Stored states are namespaced by the checkpoint's weights (path, file sizes, modification times), so replacing a model in place never reads old states.
- **Cost model per lookup.** With several storage tiers, a lookup takes the cheapest of restore time plus prefill of the remainder, using observed restore speed.

## Guarantees

- **Hit equals miss.** A hit restores the stored checkpoint exactly, and on the split-invariant path the pieces a cold prefill uses are the same, so tokens match. The tests `tests/unit/test_apc_identity_probe.py` and `tests/unit/test_apc_canonical_prefill.py` cover this, and the output-identity check of the cache work compared greedy text across HOT, WARM-lossless, SSD and cold requests.
- **WARM lossless and SSD are bit-exact.** The SSD tier always stores exact states, including when WARM is lossy. A corrupt or failed-checksum entry is dropped and the lookup falls through to the next tier or to recompute.
- **Lossy is opt-in.** `YUNSHU_VLM_APC_WARM=int8` or `int4` quantizes K/V in the WARM tier and is never a default.
- **Disk safety.** One budget covers a whole cache root; stale namespaces go first; a free-space reserve is kept; a write error drops that checkpoint without affecting the request in flight.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_VLM_APC_MEMORY_GB` | derived (see above) | RAM budget in GiB; `0` disables the cache |
| `YUNSHU_VLM_APC_DISK` | on | SSD tier; `0` keeps the cache in RAM only |
| `YUNSHU_VLM_APC_DISK_GB` | a quarter of the volume, at most 64 GiB | Cap for the whole cache directory |
| `YUNSHU_VLM_APC_WARM` | `off` | `lossless`, `int8` or `int4` compact RAM tier |
| `YUNSHU_VLM_APC_WARM_SHARE` | `0.4` | Share of the APC RAM budget the WARM tier takes |
| `YUNSHU_VLM_APC_DISK_TIERS` | unset | Lower storage tiers, `PATH[@GiB],...` |
| `YUNSHU_PREFIX_MAX_ENTRIES` | `64` | Entry count of the text fast path's `KVPrefixCache` |

The text fast path has its own cache (`KVPrefixCache`), with an SSD tier that is opt-in (`YUNSHU_SSD_CACHE`).

## Limits

- **Families with a sliding-window cache are excluded** from the VLM runner's APC, because a rotating cache cannot be assembled from dense KV blocks. The exception is `gemma4`, whose native snapshot includes the window, absolute offset and ring index; its exact-window restore is checkpoint-specific and has scoped parity checks rather than a blanket claim for every sliding-window model. `VLMEngine._build_batch_runner` decides this per model from `model_apc_plan` and the backend cache capabilities.
- Apple Paravirtual Metal runs the generic layer with no APC.
- A hit needs an exact token prefix: anything that changes early in the prompt moves everything after it.
- WARM lossless compresses the cache and, in the recorded replay of 2026-10-02 on Qwen3.8-27B, did not beat the SSD tier on time to first token, which is why it is off by default.

## How to verify

```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` shows what is on disk, and `GET /v1/yunshu/cache` and the console Cache page show entries, tiers and hits. Each response says which tier served it in `x_yunshu.cache.tier`. The cache-exact rule is one of the checks described in [Verification](/docs/developers/verification).


---

<!-- internals/request-lifecycle -->
---
title: Request lifecycle
description: The path of one request through the gateway middleware, the router, ModelManager dispatch, the VLM batch runner, the MLX thread and back out as a stream.
---

This page follows one request from the socket to the last byte of the response, and names the module that owns each step.

## What it does

1. **Middleware.** `create_app()` in `python/yunshu_gateway/main.py` stacks the layers. Because `add_middleware` prepends, the last one added is outermost. From the outside in: `DisconnectWatchMiddleware`, `MetricsMiddleware`, `LiveCORSMiddleware`, `ModelLeaseMiddleware`, `ResidentActivityMiddleware`, `YunshuExtensionsMiddleware` (request id, queue headers, per-response `x_yunshu` stats), `AuthMiddleware`, `RateLimitMiddleware` (only when `YUNSHU_RATE_LIMIT_RPM` is above 0) and `RequestLoggingMiddleware`. Metrics sits outside auth on purpose, so a 401, 429 or 413 is counted. The disconnect watcher is outermost because Starlette's `BaseHTTPMiddleware` hides a client hang-up; it records it in `scope["yunshu.client_gone"]`.
2. **Router.** A router under `python/yunshu_gateway/routers/` (`chat.py`, `anthropic.py`, the Responses router and others) validates the body, normalizes it into one internal request and resolves the model.
3. **Engine dispatch.** `ModelManager` (`python/yunshu_engine/model_manager.py`) loads models lazily, evicts by least recent use under memory pressure, and hands out a lease. `ModelLeaseMiddleware` holds a lease on every model the request acquires until the response ends, so an unload, TTL expiry or eviction cannot pull the model mid-response.
4. **VLM batch runner.** For an `mlx-vlm` model, `VLMEngine.generate_stream` prepares the prompt (chat template, media encoding, constraint compilation) on the MLX thread and submits a job to `VLMBatchRunner`. The round driver makes the prompt a row: it prefills the row on its own caches in atoms, looks up the prefix cache when the row is added, and decodes all active rows together in packed steps; Qwen3.5 and Flash-Next rows draft. Text-only `mlx-lm` models take `_generate_fast` instead.
5. **MLX thread.** All GPU work runs on a single-worker executor (`python/yunshu_engine/mlx_executor.py`) that owns the Metal generation stream.
6. **Detokenize, stop, deliver.** The runner yields token ids. `VLMEngine` runs the per-request detokenizer, stop-string and reasoning-state tracking, and pushes `RequestOutput` items through a bounded queue to the async consumer. The router turns them into the dialect's JSON or SSE events, including usage and the additive `x_yunshu` fields.

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

The diagram shows the ordering of the hand-offs for a streamed request; a non-streaming request collects the same outputs and returns one body.

## Why (design decision)

- **One GPU thread.** mlx-lm's generation stream is module-level state bound to the thread that created it, so every engine submits work to one executor. This is what makes serving several models in one process safe.
- **Runner emits ids, engine emits text.** Keeping detokenizing and stop logic in `VLMEngine` means the text path and the VLM path report results the same way.
- **Bounded delivery.** The engine delivers through a queue with a blocking put that watches the cancel event, so a slow client cannot make the GPU thread buffer without limit.

## Guarantees

- A client that disconnects cancels its generation instead of decoding to `max_tokens`; the disconnect watcher sets an event, and the router's disconnect guard (`run_with_disconnect_guard`, `client_disconnected`) cancels the generation when it is set.
- A model cannot be unloaded while a request holds its lease.
- A stream that fails inside the engine ends with an error event and `finish_reason: "error"` rather than silently truncating.
- Per-request sampler, detokenizer and stop state are never shared between requests; detokenizers are not pooled.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_RATE_LIMIT_RPM` | `0` | Requests per minute limit; the middleware is only installed above 0 |
| `YUNSHU_AUTH_TOKEN` | unset | Admin token; auth is enforced only when set (named API keys are separate) |

## Limits

- Text-only `mlx-lm` requests are served one at a time.
- LoRA adapters and custom logits processors are rejected for VLM models.
- Prefill admits one request at a time, interleaved with decode of the other rows.

## How to verify

`tests/unit/test_client_disconnect_watch.py` and `tests/unit/test_disconnect_guard.py` cover cancellation on disconnect. Run `uv run pytest tests/unit/test_client_disconnect_watch.py -q`. For the live path, a response's `X-Request-Id` header and `x_yunshu` object show the id, queue state and cache tier of a real request. See also [Architecture](/docs/developers/architecture).

The API-layer feature matrix that keeps every route in step with the others is described in [API parity matrix](/docs/developers/api-parity).


---

<!-- internals/speculative-decoding -->
---
title: Speculative decoding
description: How Yunshu drafts and verifies several tokens per step with DFlash2 or the MTP head, why greedy output is identical with speculation on or off, and which models and requests take part.
---

Speculative decoding drafts several tokens cheaply and verifies them in one forward pass of the target model. Yunshu uses it so that decode runs faster without changing the output.

## What it does

For the **Qwen3.5 family on the VLM runner** (model types in `VLMEngine._SPEC_MODEL_TYPES`: `qwen3_5`, `qwen3_6`, `qwen3_5_moe`, `qwen4_exp`), `spec_select.choose` picks a drafter in this order:

1. `YUNSHU_VLM_DRAFT`: a drafter directory, `mtp` to force the checkpoint's MTP head, or `off` to disable drafting.
2. Otherwise, a **DFlash2 drafter** found in the models directory or the Hugging Face cache whose `config.json` matches the target (same layer count and hidden size). This is automatic.
3. Otherwise, the checkpoint's own **MTP head** when it has one (`YUNSHU_MTP`).
4. Otherwise, plain decode.

The block size is the drafter's trained block for DFlash and 6 for MTP unless `YUNSHU_MTP_BLOCK_SIZE` is set. Drafting runs on the **round driver**: every request is a row, and draft-and-verify rounds run for all rows together, each row drafting at the depth its acceptance allows. A row's output does not depend on which rows share its step, so verification is lossless.

Other drafting sources:

- **Prompt-copy rounds.** A round can propose the continuation of the longest earlier occurrence of the current tail in the request's prompt plus generated text. The same verify checks it. `YUNSHU_SPEC_COPY_ROWS` sets the verify rows (default 32; `0` turns it off). Dense and MoE Qwen3.5 only; Flash-Next's DFlash rows have no copy drafter.
- **Draft tree.** `YUNSHU_SPEC_TREE` (`auto`) uses a draft-tree verifier for eligible greedy requests with the DFlash2 drafter.
- **Generic round-driver layer (every mlx-vlm family without a packed layer).** The same n-gram or suffix speculation for greedy requests with `spec_decode` (or `YUNSHU_NGRAM_DEFAULT`), on a lone decoding row with a trimmable KV cache; the guarantee is the verifier's top-1 over the window, not bitwise equality with one-token decode. Packed Qwen3.5 and Flash-Next rows keep their batch-invariant verify.
- **Text-only `mlx-lm` models.** Lossless n-gram or suffix speculation on greedy requests (`YUNSHU_NGRAM_DEFAULT`, off by default; a request can ask for it with `spec_decode`; `YUNSHU_SPEC_PROPOSER` is `ngram` or `suffix`), and an assistant drafter directory for Gemma 4 text models (`YUNSHU_GEMMA4_ASSISTANT`).
- **Jump-forward** is a different mechanism for constrained output (tokens forced by a grammar are emitted without a forward pass). See [Constrained decoding](/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
```

The diagram shows how the drafter is chosen when a model loads; speculation then runs per row on the round driver.

## Why (design decision)

Speculation is only worth shipping if it is invisible to the user. Yunshu therefore makes the verify step arithmetically identical to ordinary decode instead of accepting small numerical differences. Drafts are always verified by the target, so a wrong draft costs time, never correctness.

## Guarantees

- **Spec on equals spec off.** With speculative decoding on, greedy output is token-identical to the same engine with it off. Every target-model matmul for decode (one row) and verify (a few rows) goes through one kernel whose per-row result does not depend on how many rows share the call, and the attention and GatedDeltaNet verify paths are bit-exact against single-row decode. These batch-invariant kernels are Metal kernels compiled at runtime under `python/yunshu_engine/kernels/`. A spec-family model with drafting off still runs the lane's plain-decode arithmetic, so the identity holds for that case too.
- **Sampled requests** draw position-keyed noise, so the result does not depend on which tokens were drafted.
- **Draft models keep stock kernels**; only target modules are rerouted, and prefill chunks keep their own kernels.
- **Not claimed:** bit-identity to stock MLX single-row decoding. Different reductions move logits by rounding-level amounts, and that drift is accepted. The hard gate is identity within one Yunshu version.
- **Drafter quantization is lossless in effect.** `YUNSHU_DRAFT_BITS` (default 8) changes only the drafter's weights; drafts are verified, so output is token-identical for every value.

## Knobs

| Setting | Default | Effect |
|---|---|---|
| `YUNSHU_VLM_DRAFT` | unset | Drafter directory, `mtp`, or `off` |
| `YUNSHU_MTP` | on | Use the checkpoint's MTP head |
| `YUNSHU_MTP_BLOCK_SIZE` | unset | Draft block; unset means 6 for MTP and the trained block for DFlash |
| `YUNSHU_SPEC_TREE` | `auto` | `off`, `tree` or `auto` draft-tree verifier |
| `YUNSHU_SPEC_COPY_ROWS` | `32` | Verify rows for prompt-copy rounds; `0` disables |
| `YUNSHU_DRAFT_BITS` | `8` | DFlash drafter weight bits (`8`, `4`, or `0` for shipped bf16) |
| `YUNSHU_NGRAM_DEFAULT` | off | Text models: n-gram speculation on greedy requests |
| `YUNSHU_SPEC_PROPOSER` | `ngram` | `ngram` or `suffix` for text models |
| `YUNSHU_GEMMA4_ASSISTANT` | unset | Assistant drafter directory for Gemma 4 text models |
| `YUNSHU_SPEC_UNVERIFIED`, `YUNSHU_DRAFT_MODEL` | off, unset | Stable user options, not lossless: external `mlx-lm` draft model for greedy text requests; see [Options that can change output](/docs/guides/options) |

## Limits

- The lossless guarantee does not cover `YUNSHU_SPEC_UNVERIFIED` with an external draft model: its output can differ from plain decode. See [Options that can change output](/docs/guides/options).
- Packed layers (Qwen3.5 family, Flash-Next) draft; other VLM families run the generic layer and decode without drafting.
- Rows with processors outside the driver's windowable set, XTC sampling or non-invariant guides decode one token a round without drafting.
- An Apple Paravirtual Metal host runs the generic layer without speculation.
- LoRA adapters and custom logits processors are rejected for VLMs, and processors that are not draft-safe keep a row from drafting.

## How to verify

Counters are available at `GET /v1/yunshu/spec-decode`, as Prometheus `yunshu_spec_decode_*` metrics, and per request in `x_yunshu.speculative`. The startup log prints the chosen path ("Speculative decoding: ..."). Identity is checked by the `yv` tool (see [Verification](/docs/developers/verification)); relevant unit tests are `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` and `tests/unit/test_dflash_copy.py`. Measured decode numbers are in [Benchmarks](/docs/guides/benchmarks).


---

<!-- internals/tool-call-parsing -->
---
title: Tool-call parsing
description: How Yunshu detects a model's tool-call wire format from its chat template, parses calls from complete and streamed output, types the arguments, and decides finish_reason.
---

A model writes a tool call as text in its own wire format. Yunshu reads that text back into structured calls, so OpenAI-, Anthropic- and Ollama-style clients all see ordinary tool-call fields. This page describes the readers, the streaming parser and the outcome rules. For constraining the call while it is generated, see [Constrained decoding](/docs/internals/constrained-decoding).

## What it does

`yunshu_engine/tool_format.py` is the registry. A `ToolFormat` is a start marker, an end marker (empty means "to the end of the line", as in Mistral) and a parse function for the text between them. A `whole` format has no start marker: the entire message is the call (Llama 3 JSON).

- **Detection.** `native_format` reads the model's chat template and returns the format the template teaches, or `None`. It checks Llama header templates first, then marker strings (`_OWN_TEMPLATE_MARKERS`), then Hermes/GLM `<tool_call>` shapes, then falls back to the upstream registries of `mlx-vlm` and `mlx-lm` (`_infer_tool_parser`).
- **Order to try.** `formats_for_tokenizer` returns the native format, then `yunshu_json` (the `<tool_call>{"name", "arguments"}</tool_call>` form Yunshu's injected tool prompt asks for), then `json_message` (a message that is only a JSON call object). Harmony also tries a suffix form.
- **Parsing a finished output.** `parse_tool_output` returns the calls in output order, with arguments typed by the request's tool schemas, and the text with every parsed call span removed.
- **Streaming.** `ToolCallStreamer` (`tool_call_streamer.py`) moves between text, inside-a-call and whole-message states.

## Formats and families

Detection is from the chat template, not from a model-name list; the table gives the format and the families it serves.

| Format name | Wire shape | Families |
|---|---|---|
| Qwen XML (upstream reader plus tolerant fallbacks) | `<tool_call><function=f><parameter=p>v</parameter></function></tool_call>` | Qwen3.x and Qwen3-Coder style templates |
| `hermes` / `yunshu_json` | `<tool_call>{"name": ..., "arguments": ...}</tool_call>` | Hermes-style JSON templates; models with no template tool format (injected prompt) |
| `glm47` | `<tool_call>` with `<arg_key>` / `<arg_value>` or newline JSON | GLM |
| `mistral` | `[TOOL_CALLS]` followed by JSON, or `[ARGS]` | Mistral |
| `kimi_k2` | `<\|tool_calls_section_begin\|>` ... `<\|tool_calls_section_end\|>` | Kimi K2 |
| `harmony` / `harmony_suffix` | Harmony messages ending in `<\|call\|>`, or a `to=` / `<\|channel\|>` suffix | Harmony-template models |
| `deepseek` | `<｜tool▁calls▁begin｜>` blocks | DeepSeek V3, R1, V3.1 |
| `deepseek_v32` | `<｜DSML｜function_calls>` | DeepSeek V3.2 |
| `deepseek_v4` | `<｜DSML｜tool_calls>` | DeepSeek V4 |
| `llama3_json` | the whole message is a JSON call, optionally after `<\|python_tag\|>` | Llama 3.x JSON templates |
| `llama3_pythonic` / `pythonic` | literal Python calls such as `[f(a=1)]`, bare or between `<\|tool_call_start\|>` and `<\|tool_call_end\|>` | Llama Python-list templates; tagged pythonic templates |
| `json_message` | a message that is nothing but a JSON call object | models without a marker format, such as Qwen3-Omni |

Formats not listed here come from the upstream parser registries of `mlx-vlm` and `mlx-lm`. Families without a locally available checkpoint are tested with fixtures and not claimed as real-model validated.

## Why

The format is a property of the model, so it is read from the template the way upstream does, and Yunshu only adds readers upstream lacks. The readers are independent implementations (`tool_family_parsers.py`) and never execute model output: the Python-call reader accepts only keyword arguments that are JSON-style literals and rejects positional arguments, expansions and any non-literal name. Fixture shapes are inspired by vLLM's parser tests, with the reviewed upstream revision recorded in `vendor.json`.

## Streaming parse and call IDs

The following diagram shows the streaming states.

```mermaid
stateDiagram-v2
    [*] --> TEXT
    TEXT --> TOOL_CALL: "start marker seen"
    TEXT --> WHOLE: "message may be a JSON call"
    TOOL_CALL --> TEXT: "end marker, call parsed or released as text"
    WHOLE --> TEXT: "not a call"
    WHOLE --> [*]: "whole message parsed"
    TEXT --> [*]: "stream ends"
```

- Text outside calls streams as soon as it cannot be the start of a marker. From a start marker on, text is held until the end marker, then the call is parsed.
- Each call is emitted as a start (id and name) followed by its complete arguments. Arguments are buffered until a complete call is available, then sent after the name. Each call gets its own ID.
- A span that no format can read is released as text. Tool markup never reaches the content stream.
- Request constraints apply at the source: a named `tool_choice` drops calls to other functions, `parallel_tool_calls=false` keeps only the first call, and tool names are filtered against the request.
- Arguments are always a JSON object string. `tool_arguments.py` types text-valued parameters (Qwen's `<parameter=days>3` arrives as `"3"`) using the request's JSON schema: integer, number, boolean, array, object and null convert when they convert cleanly; string and unknown types stay unchanged.
- For GLM, `tool_thinking.py` recovers trailing calls inside reasoning only when generation ends on the observation EOS token. Length stops, cancels, user stops, malformed calls and quoted examples stay reasoning.

## How finish_reason and the outcome are decided

- If at least one call survives parsing and the `tool_choice` / parallel filters, the OpenAI chat route reports `finish_reason` `tool_calls` (`chat.py`: `"tool_calls" if tool_calls else finish`). For a stream this is decided per choice when any call was emitted. The Anthropic route maps the same condition to `stop_reason` `tool_use` (`_map_stop_reason`).
- Otherwise the engine's own reason (`stop`, `length`, ...) is reported, and a markup block that yielded no call is released as text rather than dropped.
- Every parse records counts, never text, on the request: `tool_calls_parsed` and `tool_markup_failed` (`record_tool_outcome`). They are logged and exposed through the finished-request record in `x_yunshu`, so a dropped call is visible instead of silent.

## Guarantees

- Calls to names the request did not declare are filtered out. Tool markup does not leak into content.
- Python-style calls are parsed as data and never executed.
- A forced `tool_choice` uses a native llguidance grammar. Native envelopes can span several tokenizer tokens; unsupported grammar and tokenizer combinations keep the unconstrained fallback, and a parsed call is not a strict-schema proof.

## Knobs

| Setting | Default | Effect |
|---|---|---|

Parsing itself has no setting; it follows the chat template.

## Limits

- A template with no recognizable tool format falls back to `yunshu_json` and `json_message`, which depend on the model following the injected prompt.
- Python-literal arguments are limited to JSON-style literals.
- Formats for families without a local checkpoint have fixture coverage only.

## How to verify

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

The optional capability stage runs four real HTTP checks (forced, streaming, lazy output and lazy auto-tools): `scripts/dev/yv ab --suite preflight,toolparse --model /path/to/small-model`. See [Verification](/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"
    }
  ]
}

```
