Create a realtime conversation
/v1/realtimeEstablish a continuous two-way realtime session over WebSocket, stream in voice, camera, or screen frames, and receive streamed text and voice responses. It supports natural interruptions and delegates complex reasoning and long-running tasks to your own backend, continuing to talk with the user while they run.
Connection and authentication
Upgrade an HTTP GET request to WebSocket. Connect to wss://api.mosi.cn/v1/realtime with the model query parameter specifying the model; place the API Key only in the Authorization request header.
Model ID. Use the stable ID; snapshot IDs are also supported. Pass it in the model query parameter of the WebSocket URL.
Your own stable end-user ID, URL-encoded. Required when memory_scope=user; use the same user when reconnecting. Example: wss://api.mosi.cn/v1/realtime?model=moss-live-1.0&user=customer_001.
Bearer <API Key>; put it in the Authorization request header of the WebSocket handshake.
Session flow
| Stage | Client | Server events and checks |
|---|---|---|
| Connect | Complete the WebSocket handshake and send attach_session | Join the session after the connection opens |
| Configure | To choose a voice, send change_voice; for a persona, session instructions, or custom tools, send session.update; to change the audio format, send media.configure; client delegation is set in attach_session | Wait for session_attached; if you sent change_voice, wait for voice_changed; if you sent session.update, wait for session.updated and confirm data.error is an empty string; if you sent media.configure, wait for media.configured |
| Send audio and video | Turn on the microphone and keep uploading audio; enable video as needed | Receive voice and frame input |
| Answer | Display text, play voice, and send playback acknowledgements | Receive input.transcript.done, output.transcript.done, and response.ended; the conversation can continue after a voice reply completes or is interrupted |
| Continue or end | Keep sending input, or close the WebSocket | The connection can continue after a turn completes; closing the connection ends the session |
Client events
Creates a new session or resumes an existing one. Send this event as the first message after connecting.
To reconnect, first close the old connection, then use the original session_id, the same user, and the same creation options; if the session cannot be resumed, create a new one. Your application keeps its own records of tasks and tool executions.
Configures the persona, session instructions, and custom tools. During initialization, finish configuring before enabling audio.
Omitted settings keep their values, and an update that fails validation is not applied. Sending only instructions keeps the current persona; persona=null restores the default persona.
Switches the voice for the current session. Send it on the same WebSocket after receiving session_attached.
Turns microphone input on or off.
Enables the media format with type prefixes before you send video.
Chooses the audio format, image capture parameters, and playback acknowledgement mode for this connection. You can send it at any time after attach_session, and more than once; if you do not send it, the default format is used; with no fields, it only returns the current settings; send it again after reconnecting. On poor networks, set profile to low to switch to low-bitrate transport.
Reports the device's time zone and, optionally, the device location. The assistant uses this time zone to answer with the local time and date and to work out times such as "3 p.m."; if it is not reported, Beijing time is used. We recommend sending it once after the connection is established and again when the time zone or location changes; pass null for context to clear it.
Adjusts the volume and speaking rate of the speech sent on this connection; useful when the user's device speaker is too quiet or too loud, or when the user wants slower speech. Include at least one of the two fields. You can send it at any time after attach_session, and more than once; it takes effect from the next audio chunk (the reply currently playing changes too); if you do not send it, the default volume and normal speaking rate are used; send it again after reconnecting.
Controls camera or screen frames; turning frames off does not end the session.
Chooses the main frame source to focus on.
Send it after an audio chunk has actually finished playing in full.
response.audio.done has been received, and all audio of that reply has actually finished playing.
Reports actual progress after playback has stopped. First acknowledge the chunks that finished playing, then report the partial duration of the current unfinished chunk.
Submits a tool execution result. On failure, also send back a failure description the model can use.
Has the model continue its reply using tool results already submitted. Use it to continue answering after a tool call; in ordinary voice conversations, the model responds automatically.
Sends facts or progress.
Sends progress or results that can be expressed to the user.
Appends session-level instructions.
Requests cancellation of the specified delegation. Your application is also responsible for stopping its own executor or device operations.
Optional connection keepalive event; send it at your application's keepalive interval.
Server events
The session is ready. Save the session ID and continue with the actual configuration returned.
Result of processing the session configuration. Check data.error first, then decide whether to start input.
Notification that the voice was set; data.name is the voice ID set for the current session.
Response to media.configure, containing the settings currently in effect for this connection; decode subsequent downstream speech according to its output_audio.
Response to client_context.update.
Response to media.output.configure; when the user asks during the conversation for slower or faster speech, the server also sends this event to tell your application the new speaking rate.
Notification that user voice activity started. Your application can use it to update the user's speaking state; stopping playback and acknowledgements still follow the interruption events.
Notification that user voice activity stopped, used to update the user's speaking state. Handle the model reply and the connection state through their own events.
The server may send this notification before the connection closes. Your application handles the connection closing through the WebSocket close event.
The current user transcript was updated.
The current user transcript was confirmed.
Revises a confirmed user transcript. Update the history entry by turn instead of adding a new conversation entry.
The model transcript was updated.
The final model transcript on the normal completion path.
The corresponding reply started outputting audio.
Association information for the next binary audio chunk. Save it and pair it with the PCM frame that follows.
All audio for the corresponding reply has been sent. You still need to wait for the local player to finish.
Stop playback of the specified reply immediately and clear its queued audio. Keep receiving new replies.
This reply has ended, and the connection can still be used. Normal completion, an abort before any audio was spoken, or a failure can be reported through this event.
A reply that was already speaking was interrupted, or playback failed. This event is the final state of that reply; your application ends the reply based on it.
The complete tool call arguments are ready. Choose the tool by name, parse arguments, and run it.
Summary of tool call output. It may contain the same call as the arguments-done event, so deduplicate by call_id; it does not mean the tool has run or that voice playback has finished.
The tool result has been received; next, send response.create to continue the reply.
A task needs to be run by your application. Save delegation.id and prepare the call from objective and context; keep handling realtime audio while the task runs asynchronously.
Confirms that the server has accepted this update. Audio playback state is tracked by the player and playback acknowledgements.
Confirms that the server has accepted this update. Audio playback state is tracked by the player and playback acknowledgements.
Confirms that the server has accepted this update. Audio playback state is tracked by the player and playback acknowledgements.
The delegation has been marked as cancelled. Your application should stop the actual execution and discard old results not yet sent back.
The public keepalive response uses {action, data}, with all time fields inside data.
Request or session error. Handle the corresponding request according to the error code, and continue the session or reconnect depending on the connection state.
Custom tool calls
Define tools in session.update.session.tools; your application runs them. Custom tools work in both client and none modes.
Do not block WebSocket sending and receiving or audio processing while running tools. Tools are synchronous by default: the model's reply for this turn waits for the tool result, the wait has an upper limit, and a timeout is treated as no result received. Declare tools that may take longer than about 2 seconds to run (querying your backend, placing orders, approvals, calling third-party services) as async tools; see "Async tools": the user can keep talking, and the assistant continues answering after the result is sent back.
Tool definition
Set to function.
Starts with a letter or underscore and contains only letters, digits, and underscores, up to 64 characters; names must be unique within the list. If a name cannot be used, the configuration confirmation returns an error.
Non-empty; describe the purpose and when to use the tool.
JSON Schema of the parameters; if omitted, an object with no properties is used. Your application validates the arguments before running the tool.
Execution mode; defaults to sync. See "Async tools".
Whether the tool is read-only. It must be true for async_query and false for async_effect; otherwise the whole session.update is rejected.
sync tools can set it too: true marks a read-only query, which is run again after the user says something new or a write operation happens in between; within the same turn, queries with the same arguments reuse the previous result.
{
"action": "session.update",
"session": {
"tools": [
{
"type": "function",
"name": "get_order_status",
"description": "Look up the current status of the specified order",
"parameters": {
"type": "object",
"properties": {
"order_id": {
"type": "string"
}
},
"required": [
"order_id"
]
}
}
]
}
}session.updated confirms the configuration succeeded → receive response.function_call_arguments.done → your application runs the tool → send the result back with conversation.item.create → receive conversation.item.created → send response.create to continue the reply.
response.done may also contain the same call; deduplicate by call_id and run each call once. Updating the tool list replaces it entirely; pass tools: [] to clear it.
Keep the tool list stable
- Use the same tool definitions for all sessions of the same application, with names, order, descriptions, and parameters unchanged word for word.
- Do not put dynamic information such as the user, time, or order number in tool descriptions; put it in session instructions or tool results.
- Finish configuring with a single session.update before enabling audio; avoid changing the tool list in the middle of a session.
Send back tool results and continue answering
After running the tool, submit the result with the same call_id. output is text or a JSON string.
{
"action": "conversation.item.create",
"item": {
"type": "function_call_output",
"call_id": "<received call_id>",
"output": "{\"status\":\"shipped\"}"
}
}You then receive the corresponding result confirmation:
{
"action": "conversation.item.created",
"data": {
"type": "conversation.item.created",
"item": {
"id": "<item_id>",
"type": "function_call_output",
"call_id": "<received call_id>"
}
}
}Then send response.create to ask the model to continue answering:
{
"action": "response.create",
"response": {
"call_ids": [
"<confirmed call_id>"
]
}
}response.done summarizes function call output. Run each call_id once; custom tools work in both client and none modes.
Async tools
A sync tool makes the model's reply for this turn wait until the result comes back, and the user can only wait in the meantime. For tools that may take longer than about 2 seconds to run, add execution_mode to the tool definition: use async_query for read-only queries and async_effect for operations with side effects.
{
"action": "session.update",
"session": {
"tools": [
{
"type": "function",
"name": "lookup_inventory",
"description": "Look up the current inventory",
"parameters": {"type": "object", "properties": {"sku": {"type": "string"}}, "required": ["sku"]},
"execution_mode": "async_query"
}
]
}
}- When the model calls an async tool, the server sends response.function_call_arguments.done as usual, with execution_mode, task_id, revision, and arguments_sha256. The assistant first briefly tells the user it is working on it, the turn then ends, and the user can keep talking.
- Your application runs the call outside the WebSocket send/receive and audio loop.
- When you have the result, send conversation.item.create with the same call_id; after you receive conversation.item.created, send response.create (with that call in call_ids), and the server starts a new reply that tells the user the result.
Each revision has a different call_id; deduplicate execution by call_id. Both the model and your application can revise or cancel unfinished tasks:
Revises the arguments of an unfinished async task. The server reissues the call with a new call_id and revision.
Cancels an unfinished async task. Operations with side effects that have already been carried out cannot be undone by cancelling.
Response after a successful revision or cancellation.
The server asks you to stop a call: the task was revised or cancelled by the model, or the wait timed out. Stop execution and discard any results that arrive late. This event does not mean your executor or device has stopped.
- If expected_revision does not match the server, or the arguments do not conform to the schema, the error tool_task_conflict is returned; if the task does not exist, unknown_tool_task is returned.
- Each session allows up to 128 async tasks (including finished ones), up to 32 revisions per task, and up to 4 running at the same time; a single execution takes at most 120 seconds from dispatch to receiving the result. When capacity is used up, new tasks are rejected; tasks in progress are not evicted.
Client delegation
The backend model, Agent, and tools run in your environment. Enable client when creating the session; if omitted, it is none, which does not affect frontend custom tools.
{
"action": "attach_session",
"delegation": {
"type": "client"
}
}Confirm session_attached.data.delegation=client → receive session.delegation.created → run asynchronously → send back progress or results → handle the corresponding appended acknowledgements. Keep sending and receiving audio during the task.
| Event | Use |
|---|---|
| session.thinking.append | Silently sends back facts or progress for later answers. |
| session.commentary.append | in_progress sends back progress that can be spoken; completed / failed sends back the final result, including for reasoning tasks. |
| session.instructions.append | Appends business instructions for the rest of the conversation. |
Link tasks by delegation.id and fill in delegation_id when sending back. timeout_ms specifies how long the current reply waits for the result; after the wait ends, the background task keeps running, and your application controls the execution timeout.
After receiving session.delegation.cancelled, mark the task as cancelled, stop the executor, and discard any further progress and results for that task. Your application handles undoing business operations that have already taken place.
A send-back retry reuses the original task result, event_id, and payload. The server deduplicates within the most recent 256 successful event_ids of the current session; for retries outside that window or after a service restart, your application checks the processing state. Each message carries at most 2000 Unicode characters; summarize long results first.
JavaScript SDK and executors
Use @mossai/mosslive to connect Pi or a custom execution framework over your existing realtime connection. Both use the same executor contract.
npm install @mossai/mosslive@0.1.0Connect Pi
First create a session with delegation: { type: "client" } enabled, then attach the executor on the same connection. In the example below, ws and sessionId come from the existing connection.
import { attachDelegation } from '@mossai/mosslive';
import { createPiRunner } from '@mossai/mosslive/pi';
// ws and sessionId come from the existing voice connection; the session must be
// created with delegation: { type: 'client' }.
const run = createPiRunner({
provider: 'custom',
model: 'YOUR-BACKEND-MODEL',
baseUrl: 'https://YOUR-PROVIDER/v1',
api: 'openai-completions',
keyEnv: 'CUSTOMER_BACKEND_KEY',
workspaceRoot: './workspace',
stateDir: './private-pi-state',
tools: ['read', 'grep', 'find', 'ls'],
});
const bridge = attachDelegation({ socket: ws, sessionId, run });
// When the app shuts down, await bridge.close(), then close the ws the app owns.When you create the connection with connectLive, set url to wss://api.mosi.cn/v1/realtime without query parameters, and pass the model separately as model: "moss-live-1.0".
Unified executor contract
type TaskRunner = (
task: {
sessionId: string;
delegationId: string;
objective: string;
purpose: 'task' | 'reasoning';
context: readonly { role: string; content: string }[];
},
context: {
signal: AbortSignal;
reportProgress: (text: string, options?: { spoken?: boolean }) => boolean;
limits?: { maxProgressBytes: number; maxResultChars: number };
}
) => Promise<string>;The executor receives a task and returns the final text. Report new progress with reportProgress; when signal signals cancellation, stop the actual work and release resources before settling the Promise.
By default each progress message is limited to 600 UTF-8 bytes; adjust this with maxProgressBytes. The final result is limited to 2000 Unicode characters; summarize longer results with summarizeResult. Each append in the protocol carries at most 2000 Unicode characters.
reportProgress(text) sends back task progress; with { spoken: true } it submits progress the model can speak about. The SDK sends back the final text the executor returns; throw an error when execution fails.
Connect other execution frameworks
npx @mossai/mosslive@0.1.0 init-adapter --directory my-adapter
cd my-adapter
npm install
npm testThe generated project includes an executor template, AGENTS.md, and contract tests. Implement TaskRunner by following the guide, then pass it to attachDelegation({ socket, sessionId, run }).
To manage event dispatch yourself, use createDelegationBridge. When the app exits, close the Bridge and the connection the app owns.
Current protocol values
| Item | Requirement |
|---|---|
| Audio | By default, 16 kHz upstream and 48 kHz downstream, mono PCM S16LE, no WAV header; you can change this with media.configure. Upload continuously at realtime speed and keep sending silence after the user stops speaking; keep capturing during playback to support interruptions. |
| Media framing | Audio-only input can send PCM directly. With tagged-v1 enabled: audio 0x00 + PCM (or an Opus packet table), camera 0x01 + JPEG, screen 0x02 + JPEG; audio keeps the prefix after frames are turned off. Downstream binary messages carry no prefix. |
| Video | One binary message per JPEG frame, sharing the WebSocket with audio; no Base64, MP4, or H.264. Capture according to media.configured.video; the default is a long side of 512, quality 0.75, and 1 frame per second. Under load, older frames may be dropped. |
| Text updates | text is a full snapshot that replaces the display; the user's turn and the model's turn_id link to their respective records. Send playback acknowledgements based on the player's actual playback progress. |
| Persona and instructions | persona.prompt is up to 8000 Unicode characters; session instructions total up to 16000. |
| Tools | Up to 128; names up to 64 characters. |
| Context send-back | Up to 2000 Unicode characters per append. Delegation context includes up to the 6 most recent entries, 600 characters each. instructions are up to 16000 Unicode characters. |
| Delegation records | Up to 32 per session; finished tasks can be reclaimed, and sending back to an old ID may return unknown_delegation_id. |
Error codes
For authentication, permissions, rate limiting, and general HTTP errors during connection, see Error Codes. The following are protocol errors specific to the MOSS-LIVE endpoint.
| Error codes | Action |
|---|---|
| memory_scope_requires_user | Provide a stable user, or create a session-scoped session. |
| memory_scope_immutable / invalid_memory_scope | Use a valid memory scope; keep the original setting when resuming a session. |
| session_option_mismatch / invalid_session_option | Check the creation options; keep the original settings when reconnecting. |
| invalid_content / content_too_long | Content must be non-empty, and a single item must not exceed 2000 Unicode characters; content over the limit returns content_too_long. |
| invalid_delegation_id / unknown_delegation_id | Check the delegation ID and the session it belongs to; use null for session-level context. |
| invalid_status | Use completed, in_progress, or failed for commentary.status. |
| instructions_full | Session instructions have reached the total limit, and further calls return this error. Tidy up the instructions and reconfigure, or create a new session as your business requires. |
| unknown_call_id | Check the state of the call for that call_id, and reuse the result of a completed call. |
| invalid_public_request | Returned when the event name, fields, types, or action/type do not agree; check them and retry. It is also returned when a single session.update submits instructions longer than 16000 Unicode characters, and that configuration does not take effect. |
| invalid_event_id | event_id must be a string; the current length limit is 256 bytes. |
| event_id_conflict | The same event_id maps to different requests; check the ID and payload. |
| delegation_terminal | The delegation has ended; stop sending new progress and results. |
| delegation_cancel_failed | Check the task ID and status, and confirm whether the executor actually stopped. |
| presentation_capacity | Too many results are waiting to be spoken; keep the completed task results and retry the send-back later. |
Simultaneous interpretation
Translates one stream of realtime speech into another language and streams back the source text, the translated text, and the translated speech; it only translates and does not answer the content. It is the same service as realtime conversation, with the same connection method and authentication, at the path /v1/realtime/interpret. Example: wss://api.mosi.cn/v1/realtime/interpret?model=moss-live-1.0&source=en&target=zh.
Model ID, the same as for realtime conversation.
Target language code: zh Chinese, en English, ja Japanese, ko Korean, de German, fr French, es Spanish, ru Russian, it Italian, pt Portuguese, tr Turkish, el Greek, id Indonesian, ms Malay.
Source language code, with the same values as target; detected automatically when omitted, and required when bidirectional=1.
Switch for two-way interpretation.
Voice ID for the translated speech, that is, the data[].id returned by List Voices; the default voice is used when omitted.
After connecting, send attach_session as the first message, then send media.mode (tagged-v1), and media.configure if needed. Then keep streaming audio at realtime speed (0x00 + 16 kHz PCM16, or 0x00 + an Opus packet table), keep streaming silence when no one is speaking, and close the connection only after response.audio.done for the last sentence arrives. Each connection takes only one speaker; for multiple speakers, use one connection per person.
Client events
Only the following events are accepted; other events return error (invalid_request), and the connection stays open.
Creates a session; it is the first message after connecting, and other fields are ignored. Each connection is a new session; resuming is not supported.
Declares that upstream binary messages carry a type byte; audio is 0x00.
Chooses the audio format and playback acknowledgement mode, with the same values as media.configure above; video is not used.
Send it after a chunk of translated speech has actually finished playing. Required when playback is client (default), otherwise the next sentence keeps waiting; not needed when it is server.
Send it after response.audio.done for a translated sentence has arrived and all its chunks have finished playing.
Send it when the client stops playing a sentence on its own.
Turns microphone input on or off.
Optional connection keepalive event.
Server events
The session is established.
Response to media.configure, with the same fields as media.configured above (without video).
Source speech started.
Source speech paused.
Realtime snapshot of a source segment; each one is the full text of that segment and replaces the display.
Final text of a source segment.
Translated speech for a sentence started. One source segment may be translated into several sentences; translated speech may start before the source segment's input.transcript.done.
The binary message that follows is a chunk of this sentence's speech.
Progressive snapshot of this sentence's translated text.
Final translated text of this sentence.
All speech for this sentence has been sent.
Speech for this sentence stopped midway; discard the part not yet played.
This sentence has ended.
Notification before the server closes the connection.
The request was invalid or a server error occurred.
Errors
- Invalid query parameters: the handshake returns HTTP 400 and no connection is established.
- The first message is not attach_session: error (invalid_request) is returned, and the connection is then closed with close code 1008.
- Concurrency is full or the service is under maintenance: the connection is closed with close code 1013 (reason Session limit or Server draining); reconnect later, increasing the retry interval each time.