EndToEndRealTimeDialog
This API uses the WebSocket protocol to perform real-time conversational transcription, intent recognition, and speech synthesis. It supports various audio formats for both input and output to ensure real-time performance and high compatibility.
Debug
You can run this API directly in OpenAPI Explorer without having to calculate signatures. After a successful run, OpenAPI Explorer can automatically generate SDK code examples.
Authorization information
The following table describes the authorization information for this API. You can use it in the Action element of a RAM permission policy statement to grant a RAM user or RAM role the permission to call this API. The details are as follows:
-
Operation: the specific permission point.
-
Access level: the access level of each operation. Valid values: Write, Read, or List.
-
Resource type: the resource types that support authorization in the operation. The details are as follows:
- For required resource types, an asterisk (*) is prefixed.
- For operations that do not support resource-level authorization,
All Resourcesis used.
-
Condition key: the condition keys defined by the cloud service itself.
-
Related action: other permissions required to successfully perform the operation. The caller must also have the permissions of the related actions for the operation to succeed.
| Operation | Access level | Resource type | Condition key | Related action |
|---|---|---|---|---|
| dianjin:EndToEndRealTimeDialog | none | *All Resources * |
| None |
Request syntax
GET /{workspaceId}/ws/realtime/dialog HTTP/1.1
Request parameters
| Name | Type | Required | Description | Example |
|---|---|---|---|---|
| workspaceId | string | Yes | The workspace ID. | llm-xxxxx |
| asrModelId | string | No | The speech recognition model ID. The default value is nls-base. Currently, paraformer-realtime-v2 and paraformer-realtime-8k-v2 are supported. Valid values:
| nls-base |
| ttsModelId | string | No | The speech synthesis model ID. The default value is nls-base. cosyvoice-v2 is supported. | nls-base |
| inputFormat | string | No | The input audio format. pcm/wav/mp3 are supported. | pcm |
| outputFormat | string | No | The output audio format. | wav |
| sampleRate | string | No | The sample rate. | SAMPLE_RATE_16K |
| voiceCode | string | Yes | The voice parameter value. It is limited to word/sentence-level timestamps. | longxiaochun_v2 |
| volume | integer | No | The volume. The value ranges from 0~100. This parameter is optional, and the default value is 50. | 50 |
| speechRate | integer | No | The speech rate. ● If ttsModelId is nls-base: the value ranges from -500~500, and the default value is 0. ● If ttsModelId is cosyvoice-v2: specifies the speech rate of the synthesized audio. The value ranges from 0.5~2. ○ 0.5: half the default speech rate. ○ 1: the default speech rate. The default speech rate refers to the speech rate of the model's default synthesized output, which varies slightly depending on the speaker. It is about four characters per second. ○ 2: twice the default speech rate. | 0 |
| pitchRate | integer | No | The pitch. ● If ttsModelId is nls-base: the value ranges from -500~500, and the default value is 0. ● If ttsModelId is cosyvoice-v2: specifies the pitch of the synthesized audio. The value ranges from 0.5~2. | 0 |
Client request messages
Common fields
| Field | Description |
|---|---|
| type | The message type |
| seq | The message sequence number |
| timestamp | The timestamp in milliseconds |
StartTranscription (Start real-time transcription)
Purpose: starts real-time transcription and creates a real-time session.
type:StartTranscription
seq:1
timestamp:1719242591197
{
"playCode": "c00aa8467a", // Scenario code
"metaData": {}, // Metadata. You can add key-value pairs here for purposes such as placeholders in the opening remarks. For example, if the placeholder ${name} is set in the opening remarks in scenario management, you can pass {"name": "Zhang San"} here.
"selfDirected": true // Whether to enable autonomous Q&A (when the intent recognition result is "other", the model's autonomous answering capability is used)
}
ProcessTranscription (Send audio data)
Purpose: uploads a segment of audio data.
type:ProcessTranscription
seq:1
timestamp:1719242591197
ack:required
{
"dataSourceType": "customer", // Data source type
"data": [0,0,0,0,0] // Binary audio stream
}
-
dataSourceType indicates the data source (such as "customer", "service")
- customer indicates the audio data of the customer
- service indicates the audio data of third-party prompt tones such as those from carriers
- Note that you must distinguish between them. You can send only the customer's audio data. This API does not currently process audio data from the service source.
StopTranscription (Stop transcription)
Purpose: actively ends the real-time session.
type:StopTranscription
seq:1
timestamp:1719242591197
{}
The payload is empty
Response parameters
| Name | Type | Description | Example |
|---|---|---|---|
| object | RealTimeDialogResp | ||
| requestId | string | The request ID | 1C98B466-D6E0-5252-A60B-F345CBB33DDB |
Server-side response (push) messages
TranscriptionStarted (Session/transcription started)
type:TranscriptionStarted
seq:1
timestamp:1752922002409
{
"sessionId": "1752922001S001nojxboa26z", // Unique identifier of the business session
"openingRemarks": "Hello, is this Mr. Li?" // Opening remarks text
}
- sessionId: the unique identifier of the business session
- openingRemarks: the opening remarks content; text content
TranscriptionResultChanged (Transcription text changed [ASR result])
type:TranscriptionResultChanged
seq:29
timestamp:1754659632826
{
"content": "Yes, you",
"messageId":"5da6a7211fd54f7087f74f2f028308e7"
}
- content: the current transcribed text content
- messageId: the unique message identifier
SentenceEnd (Sentence transcription complete [streaming return of the agent reply audio data])
type:SentenceEnd
seq: 3
timestamp: 1754659629166
{
"data": [73,68,51,4,0,0,0], // Binary data of the voice
"messageId": "", // Unique message identifier
"messageEnd": true // End-of-round message flag
}
BizProcessing (Business intent recognition result)
type:BizProcessing
seq: 3
timestamp: 1754659629166
{
"id": "175465963554371b6ffdea5eb446188fc366df451b23b",
"choices": [
{
"index": 0,
"finishReason": "stop",
"delta": {
"intentionCode": "1940679612569849856",
"intentionScript": "Hello, this is xxx. We noticed that you have a pre-approved credit line of x, so we are reminding you to check it in our WeChat mini program or app.",
"intentionName": "Customer asks about the caller identity",
"callTime": "819",
"hangUpDialog": false,
"interrupt": false
}
}
],
"created": "1754659635543",
"success": true
}
- It mainly outputs text content related to intent recognition. For descriptions of the output fields, see the API: RealTimeDialog
SentenceInterrupted (Sentence interrupted [audio cache needs to be cleared])
type:SentenceInterrupted
seq: 32
timestamp: 1754659635543
{}
- The body is empty. When this message is received, you must clear the audio cache and stop playing the previous audio content to achieve the interruption effect.
TranscriptionEnd (Transcription ended [session suggested to end: the agent determines that the session can end])
type:TranscriptionEnd
seq: 367
timestamp: 1754659669964
{}
TranscriptionCompleted (Transcription fully complete. You can actively close the WebSocket connection.)
type:TranscriptionCompleted
seq:3
timestamp:1752922030325
{}
Status codes and error handling
If an error occurs when connecting or sending a message, the server returns a standard Error message:
type:Error
seq:3
timestamp:1752922030325
{
"code": "401",
"message": "Token is invalid or has expired"
}
Common error codes:
| code | Description |
|---|---|
| 400 | Invalid request parameters |
| 401 | Authentication failed |
| 500 | Internal service error |
Examples
Normal response example
JSON format
{
"requestId": "1C98B466-D6E0-5252-A60B-F345CBB33DDB"
}
Error codes
Visit Error Center to view more error codes.
Change history
| Change time | Change summary | Operation |
|---|---|---|
| 2025-10-28 | New OpenAPI | View change details |
Interaction process
Java Sdk Demo
Note: the current example is a general-purpose SDK. A dedicated SDK for this API will be provided later.
Add the dependency
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-gateway-pop</artifactId>
<version>${version}</version>
</dependency>
Contact the DianJin developers to obtain the version number.
Sample code
String WORKSPACE_ID = "xxx";
//构造身份提供器, 匿名调用可使用 AnonymousCredentialProvider
StaticCredentialProvider provider = StaticCredentialProvider.create(
Credential.builder()
.accessKeyId("xxx")
.accessKeySecret("xxx")
.build()
);
//构造 WebSocket 客户端
CommonWebSocketClient client = CommonWebSocketClient.builder()
.credentialsProvider(provider)
.overrideConfiguration(
ClientOverrideConfiguration.create()
.setProtocol("wss")
.setEndpointOverride("dianjin.cn-beijing.aliyuncs.com") //设置产品域名
).build();
//构造握手请求
CommonRequest commonRequest = CommonRequest.builder()
.product("Dianjin")
.version("2024-06-28")
.action("EndToEndRealTimeDialog")
.path(String.format("/%s/ws/realtime/dialog", WORKSPACE_ID))
.putQueryParameters("asrModelId", "paraformer-realtime-v2")
.putQueryParameters("ttsModelId", "cosyvoice-v2")
.putQueryParameters("voiceCode", "longxiaochun_v2")
.putQueryParameters("speechRate", 1)
.putQueryParameters("pitchRate", 1)
.build();
//通过 CommonWebSocketClient 构造适配 awap 协议的专用子协议客户端或适配 general 协议的客户端
//这里的 WebSocketClient 其实可以理解为一个会话,其内部保存了连接状态,可以手动重连,使用完毕后需要主动 close
WebSocketClient session = client.awapClient(commonRequest);
WebSocketClient session = client.generalClient(commonRequest);
// 添加事件监听器
session.addEventListener(WebSocketEvent.CONNECTION_OPENED, event -> {
ConnectionOpenedEvent openedEvent = (ConnectionOpenedEvent)event;
//连接建立时打印会话信息,其中的 sessionId 即为握手请求的 RequestId,可用于链路诊断
System.out.println("Connection established: " + openedEvent.getSessionInfo());
});
session.addEventListener(WebSocketEvent.CONNECTION_CLOSED, event -> {
ConnectionClosedEvent closedEvent = (ConnectionClosedEvent)event;
System.out.println("Connection closed: " + closedEvent.getReason());
});
session.addEventListener(WebSocketEvent.CONNECTION_ERROR, event -> {
ConnectionErrorEvent errorEvent = (ConnectionErrorEvent)event;
System.err.println("Connection error: " + errorEvent.getError());
});
session.addEventListener(WebSocketEvent.MESSAGE_SENT, event -> {
MessageSentEvent sentEvent = (MessageSentEvent)event;
System.out.println("Message sent: " + sentEvent.getMessageId());
});
//接收消息的逻辑通过添加 MESSAGE_RECEIVED 事件监听来实现
session.addEventListener(WebSocketEvent.MESSAGE_RECEIVED, event -> {
MessageReceivedEvent receiveEvent = (MessageReceivedEvent)event;
IncomingMessage message = (IncomingMessage)receiveEvent.getMessage();
//对于 awap 协议,可以获取消息的 header,general 协议没有 header
Map<String, String> awapHeaders = message.getHeaders();
String type = awapHeaders.get("type"); //业务侧定义的消息类型
String timestamp = awapHeaders.get("timestamp"); //服务端消息生成的时间
String id = awapHeaders.get("id"); //消息唯一 id,可为空
System.out.println("Receive message, type: " + type + ", receiveTime: " + receiveEvent.getTimestamp());
ByteBuffer data = message.getData();
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
if ("json".equals(message.getFormat())) { //这里的 format 有 json 和 binary 两种
//可以根据 type 将 payload 反序列化为对应的对象结构
System.out.println("Receive text payload: " + new String(bytes, StandardCharsets.UTF_8));
} else {
System.out.println("Receive binary payload,length: " + bytes.length);
}
});
//发起握手,这里为了方便,直接用 CompletableFuture.join()同步等待响应
HandshakeResult result = session.connect().join();
if (!result.isSuccess()) {
throw new RuntimeException("Connect fail", result.getError());
}
//发送文本消息
SendOptions sendOptions = SendOptions.builder()
.format("string") //文本消息 format=string
.header("type", "StartTranscription") //awap 协议的消息需要通过 header()方法设置消息类型,general 协议不需要
.build();
String json = "{\"playCode\":\"xxx\", \"selfDirected\":true}";
SendResult sendResult = session.send(json, sendOptions).join();
if (sendResult.isSuccess()) {
System.out.println("text message sent: " + sendResult.getMessageId());
} else {
throw new RuntimeException("send message error", sendResult.getError());
}