> ## Documentation Index
> Fetch the complete documentation index at: https://docs.m-star.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Clients

> Send requests to a running server with the Python SDK, the native /generate routes, or an OpenAI client.

A server started with [`mstar serve`](https://docs.m-star.org/serving) takes requests three ways: the Python SDK, the native `/generate` routes that every model serves, and OpenAI-compatible `/v1` routes for the models that have an OpenAI adapter. [HTTP API](https://docs.m-star.org/reference/http-api.md) lists every route and the models behind each one.

Poll `GET /health` until it returns 200 `{"status": "healthy"}`; it answers 503 when the backend does not respond or is shutting down ([Health](https://docs.m-star.org/reference/http-api.md#health)).

## Python SDK

`MStarClient` wraps `POST /generate`. It imports only `requests`, and `numpy` for the audio helpers, not torch.

```python theme={null}
from mstar import MStarClient

client = MStarClient("http://localhost:8000")

print(client.chat("What is the capital of France?").text)       # a chat model, e.g. bagel
client.tts("Hi there", voice="tara").to_wav("out.wav")          # mstar serve orpheus
print(client.transcribe("speech.wav", language="en"))           # mstar serve whisper_large_v3_turbo

for event in client.stream(text="Tell me a story"):
    print(getattr(event, "text", ""), end="", flush=True)
```

* Keyword arguments other than the named ones are sent as the model's `model_kwargs` (`voice="tara"`, `temperature=0.7`, `max_output_tokens=256`). `None` values are dropped.
* `tts(text, *, voice=None, reference_audio=None, **kw)` clones a voice from `reference_audio` (a path, bytes or a `(filename, bytes)` tuple) on models that take a reference clip. `examples/sdk_tts_qwen3.py` shows it for `qwen3_tts_base`.
* `api_key="..."`, or `MSTAR_API_KEY` in the client's environment, sends the server's key as a bearer token ([API key](https://docs.m-star.org/serving.md#api-key)).
* `session=` takes your own `requests.Session`. `enable_nvtx=True` adds NVTX ranges around the client's reads and decodes for a CUDA profile (it imports torch).
* A non-streaming call returns a `GenerateResult` with `.request_id`, `.text`, `.images`, `.audio` and `.raw`. Video (mp4) and action (float32) outputs land only in `.raw`, a list of `{"modality", "bytes", "metadata"}` entries. Request them with `stream=False`: streamed, they arrive as `TextChunk`s decoded with `errors="replace"`, which corrupts the bytes.

[Python SDK](https://docs.m-star.org/api.md) lists every method, argument and result type.

## OpenAI-compatible API

Point an OpenAI client (`pip install openai`, not installed with M\*) at `http://<host>:<port>/v1`.

```python theme={null}
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")
reply = client.chat.completions.create(
    model="qwen3_5_4b",                      # mstar serve qwen3_5_4b
    messages=[{"role": "user", "content": "Give me one fun fact."}],
    extra_body={"enable_thinking": False},   # Qwen3.5 reasons first by default
)
print(reply.choices[0].message.content)
```

* `api_key` can be any string unless the server sets a key ([API key](https://docs.m-star.org/serving.md#api-key)); the client sends it as `Authorization: Bearer <key>`.
* The `model` field is read only when the deployment serves LoRA adapters, where it names one ([LoRA adapters](https://docs.m-star.org/models/lora.md)).
* The routes a model serves are in the [OpenAI coverage table](https://docs.m-star.org/reference/http-api.md#openai-coverage). A route the model does not serve answers 404; use `/generate` or the SDK for it.
* A field that is not an OpenAI field (`top_k`, `repetition_penalty`, a model's own knob) goes in `extra_body` and reaches the model as `model_kwargs` ([Generation parameters](#generation-parameters)).
* Media references (`image_url` parts, a video route's `image` or `video`) are data URLs. An `http(s)` URL is fetched only when the server sets `MSTAR_ALLOW_REMOTE=1`.
* Image and video results come back inline as `b64_json`; `response_format: "url"` is refused.

### Chat

`POST /v1/chat/completions`, streamed (server-sent events) or not.

* Refused with a 400 when set (`0`, `false` or empty counts as unset): `n` or `best_of` above 1, `stop`, `stop_token_ids`, `logprobs`, `top_logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty`, and a `response_format` other than `{"type": "text"}`.
* Tool calling is refused: a non-empty `tools` (or `functions`) unless `tool_choice` (or `function_call`) is `"none"`, a `tool_choice` of `"required"`, or a named function. An empty `tools` and `tool_choice: "auto"` are accepted.
* `parallel_tool_calls`, `user`, `store`, `metadata` and `service_tier` are accepted and change nothing.
* `stream_options: {"include_usage": true}` ends a stream with one chunk whose `choices` is empty and which carries `usage`.
* On the Qwen3.5-family adapters (`qwen3_5_*`, `qwen3_8_27b`, `muse_glimmer`, `phi4mm`) and on `cosmos3_edge` and `cosmos3_edge_droid`, each `chat_template_kwargs` key is read as a flat `model_kwargs` key, and a flat key sent beside it wins. `extra_body={"chat_template_kwargs": {"enable_thinking": False}}` turns off Qwen's `<think>` block.
* `qwen3_omni` also speaks when `modalities` includes `"audio"`. `audio.format` is `wav` (the default) or `pcm16`, or `mp3`, `flac` and `opus` with `mstar-ai[audio]` installed; a stream sends `pcm16`.

### Speech

`POST /v1/audio/speech` takes `input`, `voice`, `response_format`, `speed` and `stream`.

* `response_format` is `wav` (the default) or `pcm`, and with `mstar-ai[audio]` also `mp3`, `flac` and `opus` (`opus` only at 8, 12, 16, 24 or 48 kHz output). A stream is `wav` or `pcm`.
* A request streams with `stream: true` or with OpenAI's `stream_format`: `"audio"` sends the bytes as they are made, `"sse"` sends `speech.audio.delta` events and then `speech.audio.done`.
* Orpheus, Qwen3-TTS, Fish S2 Pro and CosyVoice3 split a long input into sentences, synthesized as ordered requests that run ahead of playback (at most 32 pieces). `sentence_chunking: true` or `false` in `extra_body` turns this on or off for one request.
* On `qwen3_omni` the route returns the audio of the model's reply to `input`, not a reading of `input`.

`GET /v1/audio/voices` returns `{"voices": [{"id", "name"}], "default_voice"}`. `kokoro`, `orpheus` and `cosyvoice3` (when its voices directory exists) publish a list; other speech models answer 404.

### Transcription

`POST /v1/audio/transcriptions` takes a multipart `file` plus optional fields. Use `language` to specify the language, `temperature` to set the sampling temperature, and `stream` for `transcript.text.delta` events.

Whisper uses `prompt` as decoder context and Qwen3-ASR uses it as system-turn context. Both receive it as `initial_prompt`. Higgs Audio receives the prompt as its text instruction. The Canary, Canary-Qwen, Parakeet and Nemotron ASR adapters drop the prompt. Omnilingual ASR ignores it.

`response_format` defaults to `json`. Other formats are `text`, `verbose_json`, `srt` and `vtt`. Leave `timestamp_granularities[]` unset by default. On Whisper, a timed format requests segment timestamps and `word` requests word timestamps. Canary, Canary-Qwen, Parakeet and Nemotron ASR reject an explicit granularity with HTTP 400.

An upload longer than the model's clip is cut into windows at quiet points, and the windows run as parallel requests. Upload audio that decodes past 30 minutes is refused.

| Keys | Clip |
| - | - |
| `whisper_large`, `whisper_large_v3_turbo`, `higgs_audio` | 30 s |
| `canary`, `canary_qwen`, `omnilingual_asr_ctc_*` | 40 s (Omnilingual transcribes up to 20 s whole, then cuts windows of at most 16 s) |
| `parakeet`, `nemotron_asr` | 600 s |
| `qwen3_asr`, `qwen3_asr_realtime` | 1200 s, cut into 30 s windows by default |

In `extra_body`, `window_seconds` (5 up to the clip) sets the window length for one request, and `long_form: "sequential"` runs the windows in order, passing each one the transcript so far as `initial_prompt` on a model that reads it. Per-model language and timestamp support is in [Speech recognition](https://docs.m-star.org/asr.md).

For Whisper, set `task=translate` for English output. For Canary, set `language` to the source language, `target_language` to the translation target and `punctuation` to control punctuation.

### Realtime

`WS /v1/realtime` speaks OpenAI's Realtime events; a model without the requested intent closes the socket with code 1008.

#### Conversation

With no `intent`, a full-duplex model (`nemotron_duplex`, see [Nemotron VoiceChat](https://docs.m-star.org/models/nemotron-voicechat.md)) holds a conversation in OpenAI's GA events.

* The call is one engine request, opened by the first append (`input_audio_buffer.append`, or `conversation.item.create` with `input_audio` parts), with the session's `instructions` as its prompt. Instructions, formats and voice are fixed from then on.
* `audio.input.format` and `audio.output.format` are `{"type": "audio/pcm", "rate": N}` (24 kHz when left out; 8, 11.025, 16, 22.05, 32, 44.1 and 48 kHz too), `{"type": "audio/pcmu"}` or `{"type": "audio/pcma"}`. One append holds at most 300 s.
* The model decides when to speak. `turn_detection` `server_vad` and `semantic_vad` are accepted and their knobs unused; null, or `create_response` or `interrupt_response` false, are refused.
* When the client's audio falls behind real time (a muted mic), the server appends silence for it, at most 30 s per pause, counted against the call's length.
* Each reply is one response, `response.created` to `response.done`, with `response.output_audio.delta` and `response.output_audio_transcript.delta` between. One response is in progress at a time.
* `response.create`, `response.cancel`, `output_audio_buffer.clear` and the item-editing events get an `unsupported` error, and the call goes on. Input transcription and tools are not supported. `voice` is the model's own (`Aria`).
* When the call ends, the server sends `error`, closes an open reply with `response.done`, and closes the socket.

#### Transcription

`?intent=transcription` streams speech-to-text with partial results on `qwen3_asr` and `qwen3_asr_realtime`, in OpenAI's transcription-session events.

* In: `transcription_session.update`, `input_audio_buffer.append` (base64 audio), `input_audio_buffer.commit` (end of utterance) and `input_audio_buffer.clear`. Out: `conversation.item.input_audio_transcription.delta` (append-only text), `mstar.transcription.partial` (the whole current hypothesis, unstable tail included) and `conversation.item.input_audio_transcription.completed`.
* `input_audio_format` is `"pcm16"` (PCM16 at 16 kHz, the default; OpenAI reads it as 24 kHz, so a 24 kHz client declares `{"type": "audio/pcm", "rate": 24000}`), `"g711_ulaw"`, `"g711_alaw"`, or a GA format object at the rates above.
* Every `chunk_seconds` (default 2, at least 0.5) of new audio, the session transcribes everything heard so far, continuing from the previous hypothesis minus its last `unfixed_tokens`. Set `chunk_seconds`, `unfixed_chunks` and `unfixed_tokens` under `session.mstar`.
* An item holds at most 300 s of audio; commit before then.
* `turn_detection` null (the default) leaves the commit to the client. `{"type": "server_vad"}` lets the server end turns with Silero VAD (`threshold` 0.5, `prefix_padding_ms` 300, `silence_duration_ms` 500). `{"type": "semantic_vad", "eagerness": "auto"}` asks Pipecat's Smart Turn v3 at each pause (`low`, `medium`, `high` or `auto`). Both send `input_audio_buffer.speech_started`, `speech_stopped` and `committed`.
* `server_vad` needs `mstar-ai[vad]`, or `onnxruntime` and `MSTAR_SILERO_VAD_PATH` set to a `silero_vad.onnx`. `semantic_vad` needs `mstar-ai[vad]` and weights at `MSTAR_SMART_TURN_PATH` or in the Hugging Face cache (`hf download pipecat-ai/smart-turn-v3 smart-turn-v3.2-cpu.onnx`). Weights are never downloaded; without them the update gets an `error` and the session keeps its settings.

### Images

* `POST /v1/images/generations` takes `prompt`, `size` (`WxH`), `n` and `seed`. `n` runs as `n` requests batched together, up to `MSTAR_MAX_IMAGES_PER_REQUEST` (default 10). With a seed, image `i` uses `seed + i`.
* `POST /v1/images/edits` is multipart: one `image` (or `image[]`), `prompt`, optional `size`, and other fields passed to the model. The route edits one whole image. An inpainting `mask`, a second image or `n` above 1 receives a 400. `bagel`, `flux2_klein` and `flux2_klein_9b` edit; other image models refuse it.
* BAGEL, FLUX.2 klein and Z-Image read `output_format` (`png` default, `jpeg`, `webp`), `output_compression` (0 to 100) and `png_compress_level` (0 to 9, default 1) from `extra_body`.

### Videos

`POST /v1/videos/generations` takes JSON: `prompt`, `size` (`WxH`), `seed`, `num_frames`, `fps`, `image` (image-to-video), `video` (video-to-video), `n` (1 only) and `response_format` (`b64_json` only); model knobs such as `guidance_scale` go in `extra_body`. The reply is `{"created", "data": [{"b64_json"}]}` holding an mp4.

* `ltx2_5` and `minimax_h3` mux their generated audio into the mp4; `audio: false` in `extra_body` returns video alone.
* `wan22` takes `image` but not `video`. `ltx2_5` takes neither. `minimax_h3` takes `image` as the first frame and `last_image` in `extra_body` as the last, at 24 fps only.
* A Cosmos3 deployment with windowed video (`configs/cosmos3_nano_ar.yaml`, `configs/cosmos3_edge.yaml`) takes `stream_video: true` in `extra_body` and answers NDJSON: one `{"modality", "data", "metadata"}` line per window with a running `metadata.index`, then a `done` line.

### LoRA adapters

`POST /v1/load_lora_adapter` (`{"lora_name", "lora_path"}`) and `POST /v1/unload_lora_adapter` (`{"lora_name"}`) change the served adapters while the server runs. They work only on a deployment whose `resources: lora:` block sets `runtime_updates: true`, and answer 404 otherwise. `GET /v1/models` lists the served model and each adapter, with `parent` naming the base model. See [LoRA adapters](https://docs.m-star.org/models/lora.md).

## Native `/generate`

`POST /generate` takes form fields, as `multipart/form-data` (needed for file uploads) or `application/x-www-form-urlencoded`; any other content type is a 400. It returns one JSON document or an NDJSON stream.

| Field | Default | Meaning |
| - | - | - |
| `text` | none | Text prompt (optional if media is provided). |
| `files` | none | One or more media uploads; each file's modality is inferred from its extension. |
| `input_modalities` | auto | Comma-separated input modalities, one entry per prompt element in order. Auto-detected from the uploads and text when omitted, which keeps the ordering and the count of same-modality attachments; an explicit list replaces it. |
| `output_modalities` | `text` | Comma-separated desired outputs (`text`, `image`, `audio`, `video`, `video_frame`, `action`). A model that makes no text, such as Kokoro or FLUX.2 klein, refuses the default; send the modality it makes. `video_frame` is streaming-only raw RGB24. |
| `streaming` | `true` | `true` returns an NDJSON stream of chunks; `false` returns one JSON document. |
| `model_kwargs` | none | JSON object of model-specific parameters (`{"voice": "tara"}`). |
| `request_id` | generated | Optional client id. An id whose request is still in flight is refused with `409`; it is free again once that request finished, failed or was aborted. |

A client `request_id` is at most 128 characters from `[A-Za-z0-9._:-]`; any other is refused with `400` (on `/generate/ws`, with the in-band error below). An empty `request_id` counts as none: the server mints a fresh one.

A non-streaming response groups outputs by modality, each payload base64-encoded:

```json theme={null}
{
  "request_id": "…",
  "outputs": {
    "text":  [{"data": "<base64>",     "metadata": {}}],
    "image": [{"data": "<base64-png>", "metadata": {}}]
  }
}
```

A streaming response is `application/x-ndjson`: one `{"modality", "data", "metadata"}` object per line as chunks arrive, `data` base64-encoded. A request that fails after its stream has started ends it with one chunk of modality `error` (the HTTP status in `metadata.status`); nothing follows it. A client that sends `Accept: application/vnd.mstar.frames` receives length-framed binary chunks instead, which skips the base64 pass on multi-megabyte `video_frame` payloads. A server without the framing keeps answering NDJSON, so a client parses by the response `Content-Type`.

Streamed `text` chunks (`/generate` and `/generate/ws`) are the raw UTF-8 bytes of each token, so one character can be split across two chunks. Decode the stream incrementally (`codecs.getincrementaldecoder("utf-8")`, as the Python SDK does) or join the chunks before decoding.

```bash theme={null}
# text in, text out, one JSON document (mstar serve bagel)
curl -f http://localhost:8000/generate -F 'text=Hello' -F 'streaming=false'

# image understanding (image in, text out)
curl -f http://localhost:8000/generate -F 'text=What is in this image?' -F 'files=@cat.jpg'

# text-to-speech (base64 PCM in outputs.audio), mstar serve orpheus
curl -f http://localhost:8000/generate \
  -F 'text=hello there' -F 'output_modalities=audio' \
  -F 'model_kwargs={"voice":"tara"}' -F 'streaming=false'
```

## WebSocket `/generate/ws`

`/generate/ws` streams replies over a persistent WebSocket, for control loops that cannot afford an HTTP round trip per step (robot policies, streaming world models). The start fields are `text`, `files` as `[{"name": ..., "data": ...}]`, `input_modalities`, `output_modalities`, `model_kwargs`, and `request_id`. Send modality lists and the `model_kwargs` object as native values. It always streams and has no `streaming` field. Send a JSON text frame (`data` base64) or a msgpack binary frame (`data` raw bytes); a field sent as `null` counts as absent.

Replies use the same encoding as the message: one frame per result chunk, `{"request_id", "modality", "data", "metadata"}`, then `{"request_id", "finish": true}`. A rejected message answers `{"request_id", "error": ..., "status": ...}` with the HTTP status `/generate` would have returned (`409` for a `request_id` still in flight), and the socket stays open; a request that fails after it was accepted ends the same way, and no `finish` follows.

Messages may be pipelined: send the next observation before the current action chunk has returned, and the `request_id` tells the replies apart. Pipelined messages are submitted in order, so of two under one `request_id` the later one gets the `409`; replies may interleave. Closing the socket aborts whatever is still in flight. A message larger than `ws_max_message_mb` (by default `MSTAR_MAX_BODY_MB`) closes the socket with `1009`.

`mstar-server` does not compress WebSocket frames. The deprecated Python frontend (`--python-frontend`) negotiates per-message deflate unless the config sets `ws_per_message_deflate: false`, as the Nemotron VoiceChat configs do. It parses a message on its event loop, or in a helper process past 1 MiB of JSON or 32 MiB of msgpack, and a large message holds up its other requests, so keep bulk data in `files` there.

```python theme={null}
import msgpack, numpy as np, websockets.sync.client

with websockets.sync.client.connect("ws://localhost:8000/generate/ws", max_size=None) as ws:
    ws.send(msgpack.packb({
        "text": prompt,  # task + view, duration and resolution text
        "files": [{"name": "obs.png", "data": open("obs.png", "rb").read()}],  # 736x544 composite
        "output_modalities": ["action"],
        "model_kwargs": {"size": "736x544",
                         "robot_state": joints + [gripper]},  # current state, as DROID records it
        "request_id": "step-0",
    }, use_bin_type=True))
    while True:
        reply = msgpack.unpackb(ws.recv(), raw=False)
        if reply.get("modality") == "action":
            actions = np.frombuffer(reply["data"], dtype=np.float32).reshape(32, -1)[:, :8]
        if reply.get("finish") or reply.get("error"):
            break
```

The chunk (32 rows), the fps and the domain come from the checkpoint, and the reply holds the predicted rows after the state, in the robot's values. `examples/cosmos3_action_ws_client.py` is a complete openpi-style client for `mstar serve cosmos3_droid`: it builds the observation the way NVIDIA's RoboLab server does for the DROID policies and reports the loop rate and latency.

### Live input

A model that listens while it runs (a full-duplex speech model, or a TTS model fed text as it is written) can keep a request's input open after the opening message. An opening with `"end_input": false` opens a live call, and may then carry no media at all. An append feeds the running request more input, in order, while its output keeps streaming back:

```python theme={null}
ws.send(msgpack.packb({"request_id": "call", "output_modalities": ["text", "audio"],
                       "end_input": False}))
for chunk in microphone_chunks():  # e.g. 80 ms WAV files
    ws.send(msgpack.packb({"request_id": "call",
                           "append": [{"name": "chunk.wav", "data": chunk}]}))
# the record form: text, files aimed at a stream, and this append's own settings
ws.send(msgpack.packb({"request_id": "call", "append": {
    "text": "and now in French",
    "files": [{"name": "chunk.wav", "data": chunk, "stream": "audio_in"}],
    "model_kwargs": {"gain": 2.0},  # what this model's hook reads, not a sampling setting
}}))
ws.send(msgpack.packb({"request_id": "call", "end_input": True}))
```

An append carries a record. `"append": [files]` is short for `"append": {"files": [files]}`.

```text theme={null}
{"request_id": ..., "append": {"text": ..., "files": [{"name": ..., "data": ..., "stream": ...}],
                               "model_kwargs": {...}}}
```

* Every field of the record is optional, but an append needs text, files, `model_kwargs` or `end_input`.
* `stream` names the client stream a file is for. Without it the model decides, and a name the model doesn't have is rejected.
* An append's `model_kwargs` reach only the model's `process_stream_chunk`, so they mean what that model reads from them. The opening message's `model_kwargs`, such as its sampling settings, still hold for the request. An append's `model_kwargs` count toward the call's `max_call_input_mb`, as JSON.
* Text, files and `model_kwargs` go inside the record. Beside it they are rejected.
* A message is an append if it carries `append` at its top level, or `end_input` (true or a list) and no `text` or `files`.

`{"request_id", "end_input": true}` ends the input, alone or on an append, and the request then finishes as usual. An opening without `end_input` is one-shot, as a request over `/generate` is. A model may take several client streams, such as audio and video. `end_input` may then name the ones it ends as a list (`"end_input": ["video_in"]`, on the opening too), and the call's input has ended once every stream has. The opening message's files may name a `stream` too (an unknown name gets a 400), but the model routes them itself.

| Message | What happens |
| - | - |
| A rejected append, such as an unknown file type, or text or `model_kwargs` alone (a game controller's actions) that ends no stream and that the model turns into no stream item | The call ends with its error (`status` 400), and no finish follows. |
| An append the server fails to load or process, such as a corrupt file | The call ends with that failure's status. |
| Input past a limit on how much a stream may carry over a call (`client_streams` in [Config keys](https://docs.m-star.org/reference/config.md)) | The call ends with a 400 that names the limit. |
| An append after `end_input`, after the model has ended the call, or to a request this socket has no live call under | A reply to that append, `{"request_id", "append": true, "error"}`, and the call goes on. |
| An append aimed at a stream already ended, by a file's `stream`, in `end_input` or by the model's routing | Answered as late, as above. What it carried for that stream is dropped and the rest goes on. |
| Text sent with files | Reaches the model. If the model ignores it, the text is dropped without an error. |
| A message that opens a request under the call's id | A 409, and the call goes on. |
| A live call that opens while the server is at `max_concurrent_requests` | The call ends at once with `status` 503. A one-shot request waits in the queue instead. |

A live call needs a `request_id`. Only the socket that opened it can append to it, and closing the socket aborts it. Input resets the request timeout. Models without live input ignore `end_input` and reject an append. A model that declares its audio frame (Nemotron VoiceChat: 80 ms, 1280 samples at 16 kHz) takes a live call's audio in whole frames: each whole frame of an append is a step of its own, and the rest waits for the next append or the stream's end, so appends of whole frames add no wait.

## openpi WebSocket `/`

A deployment whose config has an `openpi:` block (`configs/pi05_droid.yaml`, served with `mstar serve pi05 --config configs/pi05_droid.yaml`) also serves openpi's policy protocol at the server's root, so robot clients written against openpi's `openpi_client.WebsocketClientPolicy` connect unchanged. Those include openpi's DROID example and its `examples/simple_client --env DROID`. The protocol:

* On connect the server sends one msgpack frame, the block's `metadata` (`{}` by default).
* The client then sends one observation and waits for one reply, and repeats. Arrays travel as `openpi_client.msgpack_numpy` encodes them, so camera frames arrive as raw pixels and reach the model with no PNG and no file in between.
* The reply is `{"actions": float32 [H, action_dims], "server_timing": {"infer_ms", "prev_total_ms"}}`. For `pi05_droid` that is `(15, 8)`, as openpi's own `pi05_droid` server returns. The DROID example's `assert shape == (10, 8)` was written for pi0-FAST.
* A call that fails is answered with a text frame holding the error, which the client raises, and the socket closes with `1011`.
* An observation may carry `seed` (an int), which openpi does not have. It pins the call's noise, as `seed` in `/generate`'s `model_kwargs` does. Without it each call gets a fresh seed.

On a server with the block, `GET /healthz` answers `OK` without a key, as openpi's server does, and with `--api-key` the handshake takes `Authorization: Api-Key <key>` (what the client sends for `api_key`) as well as `Bearer`. Every other route still takes only `Bearer`. A server without the block has none of this: it refuses the handshake and answers 404 on `/healthz`. Both frontends serve this route; the Dynamo worker serves without it.

The server caps a message at `ws_max_message_mb` (by default `MSTAR_MAX_BODY_MB`), which `openpi_client` does not. A larger observation closes the socket with `1009` and no error frame, so raise the cap for robots that send several raw high-resolution cameras.

```python theme={null}
from openpi_client import websocket_client_policy

policy = websocket_client_policy.WebsocketClientPolicy("localhost", 8000)
actions = policy.infer({
    "observation/exterior_image_1_left": exterior,  # uint8 [224, 224, 3]
    "observation/wrist_image_left": wrist,
    "observation/joint_position": joints,           # 7 floats
    "observation/gripper_position": gripper,        # 1 float
    "prompt": "put the marker in the cup",
})["actions"]                                       # float32 (15, 8)
```

## Generation parameters

The shared sampling parameters have the meanings below on models that use them. The server checks their ranges at intake and returns HTTP 400 for an invalid value, including on streaming requests. Models can narrow those ranges. CosyVoice3 accepts `top_k` from 1 to 128 and nonnegative seeds. Chatterbox caps `temperature` at 5 and `repetition_penalty` at 2. [Model guides](https://docs.m-star.org/models.md)

| Knob | Allowed | Meaning |
| - | - | - |
| `temperature` | number `>= 0` | `0` is greedy (the most likely token; ties go to the lower id). Values below `1e-5` are greedy too. A greedy request ignores `top_k`, `top_p` and `min_p`. |
| `top_k` | integer `>= 0` | `0` is off; so is any value at or above the vocabulary size. |
| `top_p` | number in `(0, 1]` | `1` is off. `0` is refused: ask for greedy with `temperature: 0`. |
| `min_p` | number in `[0, 1]` | `0` is off. A model whose sampler has no min-p filter refuses `min_p > 0`. |
| `repetition_penalty` | number `> 0` | `1` is off. Counts the prompt's tokens as well as generated ones unless `penalize_prompt` is `false`. A model whose sampler has no penalty refuses any value other than `1`. |
| `penalize_prompt` | `true` / `false` | Whether `repetition_penalty` also counts the prompt (default `true`). |
| `do_sample` | `true` / `false` | `false` is greedy, on a model that reads it per request (Fish S2 Pro). |
| `seed` | signed 64-bit integer | If omitted, the server derives a seed from the request ID. Each sampler derives its own stream. The fused sampler uses each row’s seed. The FlashInfer batch path reads the first row’s seed. For repeatability on that path, send one request at a time. |
| `max_output_tokens` | integer `>= 1` | In the model's output unit (text tokens, codec frames). `max_tokens`, `max_completion_tokens` and `max_new_tokens` are accepted as aliases, in that order of increasing precedence below `max_output_tokens` itself. A value above the model's limit is refused rather than cut short. |
| `ignore_eos` | `true` / `false` | Keep generating past the end-of-sequence token, up to `max_output_tokens`. |
| `return_token_ids` | `true` / `false` | Each text chunk's `metadata.token_ids` holds its sampled ids, stop tokens included. |
| `return_logprobs` | `true` / `false` | Each chunk's `metadata.logprobs` holds its sampled tokens' log-probs. Needs `resources: {sampler: {enable_logprobs: true}}` in the deployment and a model that reports them (Qwen3.5); otherwise it is a 400. |
| `logprobs_mode` | `raw` / `processed` | `raw` (the default) scores `softmax(logits / T)` before the penalty and filters, at T = 1 for greedy requests. `processed` scores the distribution the token was drawn from and needs `enable_processed_logprobs: true` as well. |
| `enable_thinking` | `true` / `false` | Read by models whose chat template has a thinking block: Qwen3.5 and Cosmos3-Edge's reasoner (default `true`), Higgs-Audio and MiniCPM-o (default `false`), and Muse Glimmer, where `false` means reasoning strength `low`. |
| `num_inference_steps` | integer `>= 1` | Denoising steps of an image or video model. Past the denoise loop's `max_iters` is a 400. |
| `num_step` | integer `>= 1` | OmniVoice's unmask steps. Past the unmask loop's `max_iters` is a 400. |
| `rollout_horizon` | integer `>= 0` | V-JEPA2's rollout length. Past the rollout loop's `max_iters` is a 400. |
| `height`, `width`, `num_frames` | integer `>= 1` | Output size of an image or video model, which may refuse sizes its VAE cannot tile. |
| `fps` | number `> 0` | Frame rate of a video model's output. |
| `guidance_scale` | number | Classifier-free guidance strength. |
| `speed` | number `> 0` | Speech rate, for a model that reads it (Kokoro, OmniVoice); any other model logs it as ignored. Only a sent `speed` is forwarded, not the OpenAI default of 1.0. |

A string that spells a number is read as that number: `"0.7"` or `" 0.7 "` for a real-valued knob, `"5"` or `"5.0"` for an integer one (`"5e0"`, `"5.5"` and `"0x1"` are not integers and are a 400). Booleans stay strict: `"false"` is not a boolean, and `true` is not a number. `null` is the same as leaving the knob out: the model's default applies, which is the checkpoint's own `generation_config.json` value where it ships one. BAGEL and Orpheus are the exception: their files are the backbone's chat presets, so only their `do_sample: false` is read and the models' own defaults stay. MiniCPM-o keeps upstream `chat`'s defaults over its file. Multi-stage models take a stage prefix (`talker_temperature`, `code_predictor_top_k`) with the same rules; an unprefixed knob sets the primary stage (the thinker of Qwen3-Omni, the talker of Qwen3-TTS), and a prefixed one wins over it for its stage.

Each model defines its other request fields. A request can succeed with an unknown key such as `temprature`. Models that declare the keys they read log ignored names the first time they see that set of names. LTX-2.5 also accepts `num_inference_steps` and `guidance_scale` and warns that its fixed schedule ignores them.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.