AGTCloud API Docs
GuidesAPI ReferenceIntegrations and resourcesUpdate and help
Realtime

OpenAI Realtime

Process realtime text, audio, and function calls over a Realtime WebSocket connection.

OpenAI Realtime uses a persistent connection and bidirectional events to process realtime text, audio, and function calls. The client sends session, audio-buffer, conversation-item, and response-control events, while the server continuously returns session status, transcripts, text, audio, function arguments, and error events.

This page primarily covers WebSocket connections. When connecting, replace MODEL_ID with a model ID that is visible to the current account and supports Realtime.

Typical use cases include realtime voice conversations, live meeting transcription and voice assistants, realtime translation, speech transcription, interactive coding, and server-side realtime integrations. A single connection can carry both text and audio while events coordinate VAD, function calls, and state updates.

WSS
wss://api.agtcloud.cn/v1/realtime?model=MODEL_ID

Authentication and connection

WebSocket authentication

Server applications establish a WSS connection with a Bearer API key and include the Realtime Beta header in the handshake request.

ItemValue
Connection URLwss://api.agtcloud.cn/v1/realtime?model=MODEL_ID
AuthorizationBearer your-api-key
OpenAI-Betarealtime=v1

Long-lived API keys should only be used on trusted servers. Do not include them in browsers, mobile application bundles, or public repositories. Always use HTTPS/WSS for connections.

Ephemeral tokens

Before a client connects, a trusted server can create an ephemeral token that is valid for one minute and limited to a single connection.

POST https://api.agtcloud.cn/v1/realtime/sessions
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "model": "MODEL_ID",
  "voice": "verse"
}

Connection flow

In the primary WebSocket flow, the server connects directly with an API key. After the handshake succeeds, it sends client events and receives server events over the same connection.

In the WebRTC flow, the client first requests an ephemeral token from its application server, which calls the session endpoint to create the token. The client then creates an SDP offer, submits it to the Realtime endpoint, receives the SDP answer, and exchanges JSON events through the oai-events data channel.

WebSocket connection examples

The examples below show Node.js, Python, event sending, and event receiving. After establishing a connection, the client sends JSON events and the server continuously returns JSON events.

WSSWebSocket connection and event exchange
import WebSocket from 'ws';

const ws = new WebSocket('wss://api.agtcloud.cn/v1/realtime?model=MODEL_ID', {
  headers: {
    Authorization: 'Bearer your-api-key',
    'OpenAI-Beta': 'realtime=v1',
  },
});

ws.on('open', () => {
  console.log('Connected to server.');
});

ws.on('message', (message) => {
  console.log(JSON.parse(message.toString()));
});

WebRTC integration

WebSocket is currently recommended. Before using WebRTC, confirm that the target model supports it. The following examples illustrate the basic connection structure for ephemeral tokens, SDP, audio tracks, and data channels.

Sessions, audio, and conversations

Realtime supports text-only, voice-only, and mixed text-and-audio conversations. Session configuration can include input and output audio formats, voice, temperature, maximum output length, tools, and VAD settings.

  • Input and output audio formats: pcm16, g711_ulaw, and g711_alaw.
  • Example voice options: alloy, echo, and shimmer.
  • VAD configuration includes the activation threshold, prefix padding, and silence duration.
  • Sessions, conversation items, content parts, and response events jointly advance the conversation.

See the event browser below for individual event fields. Shared parameters and value ranges are collected under Common types.

Event reference

Select an event to view its field definitions and JSON example. You can switch event direction, filter by category, or search by event name.

Client events · Session

session.update

Updates the default session configuration.

FieldTypeRequiredDescriptionExample
event_idstringNoClient-generated event identifier.event_123
typestringNoEvent type.session.update
modalitiesstring[]NoModalities the model can use in its response.["text", "audio"]
instructionsstringNoSystem instructions applied before the model is invoked."Respond clearly and concisely."
voicestringNoVoice used by the model.alloy, echo, shimmer
input_audio_formatstringNoInput audio format.pcm16, g711_ulaw, g711_alaw
output_audio_formatstringNoOutput audio format.pcm16, g711_ulaw, g711_alaw
input_audio_transcription.modelstringNoModel used for transcription.whisper-1
turn_detection.typestringNoVoice activity detection type.server_vad
turn_detection.thresholdnumberNoVAD activation threshold from 0.0 to 1.0.0.8
turn_detection.prefix_padding_msintegerNoAmount of audio to include before speech starts.500
turn_detection.silence_duration_msintegerNoSilence duration used to detect the end of speech.1000
toolsarrayNoTools available to the model.[]
tool_choicestringNoHow the model selects a tool.auto/none/required
temperaturenumberNoModel sampling temperature.0.8
max_output_tokensstring or integerNoMaximum number of tokens in one response."inf"/4096
JSON example
{
  "event_id": "event_123",
  "type": "session.update",
  "modalities": [
    "text",
    "audio"
  ],
  "instructions": "Respond clearly and concisely.",
  "voice": "alloy, echo, shimmer",
  "input_audio_format": "pcm16, g711_ulaw, g711_alaw",
  "output_audio_format": "pcm16, g711_ulaw, g711_alaw",
  "input_audio_transcription": {
    "model": "whisper-1"
  },
  "turn_detection": {
    "type": "server_vad",
    "threshold": 0.8,
    "prefix_padding_ms": 500,
    "silence_duration_ms": 1000
  },
  "tools": [],
  "tool_choice": "auto",
  "temperature": 0.8,
  "max_output_tokens": "inf"
}

Common types

The sections below summarize shared parameter tables for rate limits, function calls, audio, VAD, tools, models, events, sessions, conversation items, content, responses, transcription, audio streams, and WebRTC.

Rate-limit event parameters4 fields
FieldTypeRequiredDescriptionOptions or example
namestringYesRate-limit name.Example: requests_per_min
limitintegerYesRate limit.Example: 60
remainingintegerYesRemaining capacity.Example: 45
reset_secondsintegerYesSeconds until reset.Example: 35
Function-call parameters4 fields
FieldTypeRequiredDescriptionOptions or example
typestringYesFunction type.Example: function
namestringYesFunction name.Example: get_weather
descriptionstringNoFunction description.Example: Get the current weather
parametersobjectYesFunction parameter schema.Example: {"type": "object", "properties": {...}}
Audio-format parameters4 fields
FieldTypeRequiredDescriptionOptions or example
sample_rateinteger—Sample rate.Options: 8000, 16000, 24000, 44100, 48000
channelsinteger—Channel count.Options: 1 (mono), 2 (stereo)
bits_per_sampleinteger—Bits per sample.Options: 16 (pcm16), 8 (g711)
encodingstring—Encoding.Options: pcm16, g711_ulaw, g711_alaw
Voice activity detection parameters3 fields
FieldTypeRequiredDescriptionOptions or example
thresholdnumber—VAD activation threshold.Default: 0.5; range: 0.0-1.0
prefix_padding_msinteger—Speech prefix padding in milliseconds.Default: 500; range: 0-5000
silence_duration_msinteger—Silence-detection duration in milliseconds.Default: 1000; range: 100-10000
Tool-selection parameters2 fields
FieldTypeRequiredDescriptionOptions or example
tool_choicestring—Tool-selection mode.Options: auto, none, required
toolsarray—Available tools.Options: [{type, name, description, parameters}]
Model-configuration parameters4 fields
FieldTypeRequiredDescriptionOptions or example
temperaturenumber—Sampling temperature.Range/options: 0.0-2.0;Default: 1.0
max_output_tokensinteger or string—Maximum output length.Range/options: 1-4096/"inf";Default: "inf"
modalitiesstring[]—Response modalities.Range/options: ["text", "audio"];Default: ["text"]
voicestring—Voice.Range/options: alloy, echo, shimmer;Default: alloy
Common event parameters3 fields
FieldTypeRequiredDescriptionOptions or example
event_idstringYesUnique event identifier.Example: event_123
typestringYesEvent type.Example: session.update
timestampintegerNoEvent timestamp in milliseconds.Example: 1677649363000
Session-status parameters3 fields
FieldTypeRequiredDescriptionOptions or example
statusstring—Session status.Options: active, ended, error
errorobject—Error details.Options: {"type": "error_type", "message": "error message"}
metadataobject—Session metadata.Options: {"client_id": "web", "session_type": "chat"}
Conversation-item status parameters3 fields
FieldTypeRequiredDescriptionOptions or example
statusstring—Conversation item status.Options: completed, in_progress, incomplete
rolestring—Sender role.Options: user, assistant, system
typestring—Conversation item type.Options: message, function_call, function_call_output
Content-type parameters3 fields
FieldTypeRequiredDescriptionOptions or example
typestring—Content type.Options: text, audio, transcript
formatstring—Content format.Options: plain, markdown, html
encodingstring—Encoding.Options: utf-8, base64
Response-status parameters3 fields
FieldTypeRequiredDescriptionOptions or example
statusstring—Response status.Options: completed, cancelled, failed, incomplete
status_detailsobject—Status details.Options: {"reason": "user_cancelled"}
usageobject—Usage statistics.Options: {"total_tokens": 50, "input_tokens": 20, "output_tokens": 30}
Audio-transcription parameters4 fields
FieldTypeRequiredDescriptionOptions or example
enabledboolean—Whether transcription is enabled.Example: true
modelstring—Transcription model.Example: whisper-1
languagestring—Transcription language.Example: en, zh, auto
promptstring—Transcription prompt.Example: "Transcript of a conversation"
Audio-stream parameters3 fields
FieldTypeRequiredDescriptionOptions or example
chunk_sizeinteger—Audio chunk size in bytes.Options: 1024, 2048, 4096
latencystring—Latency mode.Options: low, balanced, high
compressionstring—Compression.Options: none, opus, mp3
WebRTC configuration parameters3 fields
FieldTypeRequiredDescriptionOptions or example
ice_serversarray—ICE server list.Default: [{"urls": "stun:stun.l.google.com:19302"}]
audio_constraintsobject—Audio constraints.Default: {"echoCancellation": true}
connection_timeoutinteger—Connection timeout in milliseconds.Default: 30000

Error handling and recovery

Realtime errors generally fall into four categories: connection, authentication, audio, or session errors.

TypeCommon causeRecommended action
Connection errorNetwork interruption, handshake failure, or invalid connection configurationCheck the WSS URL, network, and handshake request, then reconnect a limited number of times
Authentication errorInvalid API key, expired ephemeral token, or credentials that do not match the API addressRefresh the credential and make sure the API key matches the API address used by the request
Audio errorDevice permissions, an unsupported format, or mismatched encodingCheck device permissions, sample rate, and encoding, then reestablish the audio path
Session errorSession timeout, concurrency limits, or inconsistent event stateSave the error event, create a new session, and fall back to a non-realtime API when necessary

Recovery strategies can include automatic reconnection, session recovery, limited retries, and feature fallback. When an error occurs, first inspect the error event and save its event_id, error.type, error.code, error.message, and related-event information before deciding whether to resend anything.