Skip to main content

Qwen-Omni-Realtime

透過 WebSocket、WebRTC 使用 Qwen-Omni-Realtime 理解文本、圖片、音訊和視訊,並生成語音回覆,適合語音聊天、智能客服等場景。

支援的地區:新加坡、北京,需使用各地區的API Key。

模型與接入方式

即時音訊與視訊對話優先使用 Qwen3.8-Omni-Flash-Realtime。模型支援音訊與視訊雙工交互,接收文本、圖片、流式音訊和視訊輸入,返回文本與音訊。
模型的名稱、上下文、價格、快照版本等資訊請參見百鍊控制台;併發限流條件請參考限流。
Qwen-Omni-Realtime 模型支援 WebSocket、WebRTC 和 AOQ 三種協議接入。WebSocket 適合服務端集成和快速接入;WebRTC 適合瀏覽器端、低延遲語音場景,音訊透過 UDP 直接傳輸,內置回聲消除和降噪。如果是用戶端對接,且更看重穩定的延遲、弱網下的交互能力、即時雙工的降噪與回聲消除,可優先考慮 AOQ。協議對比與選型請參見API 參考。 按當前任務選擇入口:

接入準備

獲取所選地域、業務空間對應的 API Key 和業務空間 ID,並將 API Key 配置到環境變量。qwen3.8-omni-flash-realtime 必須使用下方綁定業務空間的呼叫地址。
  • WebSocket
  • WebRTC
  • AOQ
配置項說明
呼叫地址新加坡地域:wss://WorkspaceId.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime呼叫時請將WorkspaceId替換為真實的業務空間ID。
查詢參數查詢參數為model,需指定為訪問的模型名。示例:?model=qwen3.8-omni-flash-realtime
請求頭使用 Bearer Token 鑒權:Authorization: Bearer DASHSCOPE_API_KEY
DASHSCOPE_API_KEY 是您在百鍊上申請的API Key。

快速開始:最小音訊問答

本例使用 WebSocket 和 Manual 模式,從本地音訊文件完成一次問答。需要持續錄音或瀏覽器交互時,參見即時對話示例。 先配置 API Key,安裝 websocket-client。在下方 Python 範例中選擇地域(cn-beijing 或 ap-southeast-1),填寫對應地址中的業務空間 ID。將 PCM_FILE 設為一段短的 16 kHz、16-bit little-endian、單聲道、無文件頭 PCM 語音文件路徑。 示例使用 Manual 模式:等待會話配置生效後發送音訊、提交緩衝區,再請求回覆。文本打印到終端,音訊寫入 reply.pcm(24 kHz PCM,非 WAV 文件)。 在 macOS 或 Linux 終端中執行以下命令。
python3 -m pip install websocket-client
export PCM_FILE="./input.pcm"
如果已有單聲道、16 kHz、16-bit PCM 編碼的 input.wav,可用 Python 提取 PCM 音訊。此步驟檢查格式,不進行重採樣。
import wave
from pathlib import Path

with wave.open("input.wav", "rb") as source:
    if (source.getnchannels(), source.getframerate(), source.getsampwidth(),
            source.getcomptype()) != (1, 16000, 2, "NONE"):
        raise ValueError("Expected mono 16 kHz, 16-bit PCM WAV audio.")
    Path("input.pcm").write_bytes(source.readframes(source.getnframes()))
準備好輸入後,運行以下用戶端。示例使用“龍安靈心”音色(longanlingxin):
import base64
import json
import os
from pathlib import Path
import websocket

url = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=qwen3.8-omni-flash-realtime"
audio = Path(os.environ["PCM_FILE"]).read_bytes()
if not audio or len(audio) % 2:
    raise ValueError("Provide non-empty 16-bit mono PCM audio.")

ws = websocket.create_connection(
    url,
    header=["Authorization: Bearer " + os.environ["DASHSCOPE_API_KEY"]],
    timeout=30,
)

def receive():
    event = json.loads(ws.recv())
    if event["type"] == "error":
        raise RuntimeError(event.get("error"))
    return event

try:
    while receive()["type"] != "session.created":
        pass
    ws.send(json.dumps({
        "type": "session.update",
        "session": {
            "modalities": ["text", "audio"],
            "turn_detection": None,
            "audio": {
                "input": {"format": {
                    "type": "pcm", "sample_rate": 16000,
                    "sample_format": "s16le", "channels": 1,
                    "packing": "interleaved", "channel_layout": "mono",
                }},
                "output": {
                    "voice": "longanlingxin",
                    "format": {"type": "pcm", "sample_rate": 24000},
                },
            },
        },
    }))
    while receive()["type"] != "session.updated":
        pass
    for offset in range(0, len(audio), 3200):
        ws.send(json.dumps({
            "type": "input_audio_buffer.append",
            "audio": base64.b64encode(audio[offset:offset + 3200]).decode("ascii"),
        }))
    ws.send(json.dumps({"type": "input_audio_buffer.commit"}))
    while receive()["type"] != "input_audio_buffer.committed":
        pass
    ws.send(json.dumps({"type": "response.create"}))
    with open("reply.pcm", "wb") as output:
        while True:
            event = receive()
            if event["type"] == "response.audio.delta":
                output.write(base64.b64decode(event["delta"]))
            elif event["type"] in ("response.audio_transcript.delta", "response.text.delta"):
                print(event["delta"], end="", flush=True)
            elif event["type"] == "response.done":
                print("\nResponse status:", event["response"]["status"])
                break
finally:
    ws.close()
成功收到回覆後,將 reply.pcm 包裝為 WAV 文件,再使用音訊播放器播放:
import wave
from pathlib import Path

with wave.open("reply.wav", "wb") as target:
    target.setnchannels(1)
    target.setsampwidth(2)
    target.setframerate(24000)
    target.writeframes(Path("reply.pcm").read_bytes())

即時對話示例

WebSocket 示例提供 VAD 和 Manual 兩種模式;WebRTC 使用 VAD。
  • WebSocket
  • WebRTC
  • AOQ
  • DashScope Python SDK
  • DashScope Java SDK
  • Python 原生 WebSocket
  • 準備運行環境
您的 Python 版本需要不低於 3.10。首先根據您的操作系統安裝 pyaudio。
  • macOS
  • Debian/Ubuntu
  • CentOS
  • Windows
brew install portaudio && pip install pyaudio
安裝完成後,透過 pip 安裝依賴:
pip install websocket-client dashscope
  • 選擇交互模式
    • VAD 模式(Voice Activity Detection,自動檢測語音起止) 服務端自動判斷用戶何時開始與停止說話並作出回應。
    • Manual 模式(手動控制語音起止) 用戶端控制語音起止。用戶說話結束後,用戶端需主動發送消息至服務端。
    • VAD 模式
    • Manual 模式
    新建一個 python 文件,命名为vad_dash.py,並將以下代碼複製到文件中:
    # Dependencies: dashscope >= 2.0.1, pyaudio
    import os
    import base64
    import time
    
    import pyaudio
    from concurrent.futures import ThreadPoolExecutor
    
    import dashscope
    
    # 以下為新加坡(ap-southeast-1)地區的設定。請在範例中填寫實際的業務空間 ID。region 的值因地區而異。
    client = dashscope.Client(
        # If you have not set an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
        # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
    )
    # Specify the voice
    voice = 'Tina'
    # Specify the model
    model = 'qwen3.8-omni-flash-realtime'
    # Specify the model persona
    instructions = "你是个人助理小云,请用幽默风趣的方式回答用户的问题"
    
    # 1. Initialize the audio device and output stream
    pya = pyaudio.PyAudio()
    out = pya.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
    
    # 2. Receiver thread: iterate server events, play audio and print text
    def receive_events(session):
        for response in session.events():
            if response['type'] == 'response.audio.delta':
                # Play the audio
                out.write(base64.b64decode(response['delta']))
            elif response['type'] == 'conversation.item.input_audio_transcription.delta':
                # Streaming preview: text is the confirmed prefix, stash is the pending suffix
                preview = response.get('text', '') + response.get('stash', '')
                print(f"\r[User] {preview}", end='', flush=True)
            elif response['type'] == 'conversation.item.input_audio_transcription.completed':
                # Transcription completed: print the final text and a newline
                print(f"\r[User] {response['transcript']}")
            elif response['type'] == 'response.audio_transcript.done':
                # Print the assistant reply text
                print(f"[LLM] {response['transcript']}")
    
    # 3. Create the session (the connection is established automatically on entering the with context) and configure it
    with client.audio.realtime.connect(model=model) as session:
        session.update_session(
            output_modalities=['audio', 'text'],
            voice=voice,
            instructions=instructions,
        )
        # 4. Initialize the audio input stream
        mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
        # 5. Main loop for audio input
        print("对话已开始,对着麦克风说话 (Ctrl+C 退出)...")
        try:
            with ThreadPoolExecutor(max_workers=1) as pool:
                receiver = pool.submit(receive_events, session)
                while True:
                    audio_data = mic.read(3200, exception_on_overflow=False)
                    session.append_audio(audio_data)
                    time.sleep(0.01)
        except KeyboardInterrupt:
            # Clean up resources
            session.close()
            mic.close()
            out.close()
            pya.terminate()
            print("\n对话结束")
    
    運行vad_dash.py,透過麥克風即可與 Qwen-Omni-Realtime 模型即時對話,系統會檢測您的音訊起始位置並自動發送到服務器,無需您手動發送。

呼叫流程與會話管理

一次呼叫依次完成建連、會話配置、輸入、觸發響應和接收結果。

建立連接

以下 WebSocket 和 WebRTC 建連示例使用 qwen3.8-omni-flash-realtime。
  • WebSocket
  • WebRTC
  • AOQ
  • WebSocket 原生連接
  • DashScope Python SDK
  • DashScope Java SDK
呼叫地址與鑒權見接入準備。
# pip install websocket-client
import json
import websocket
import os

API_KEY=os.getenv("DASHSCOPE_API_KEY")
# 以下為新加坡地區的 URL,請在範例中填寫實際的業務空間 ID,各地區的 URL 不同。
API_URL = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=qwen3.8-omni-flash-realtime"

headers = [
    "Authorization: Bearer " + API_KEY
]

def on_open(ws):
    print(f"Connected to server: {API_URL}")
def on_message(ws, message):
    data = json.loads(message)
    print("Received event:", json.dumps(data, indent=2))
def on_error(ws, error):
    print("Error:", error)

ws = websocket.WebSocketApp(
    API_URL,
    header=headers,
    on_open=on_open,
    on_message=on_message,
    on_error=on_error
)

ws.run_forever()

配置會話

在 session.update 的 session 對象中,用 instructions 設置業務背景和回覆要求。 透過用戶端事件 session.update 配置輸出模態、音色、音訊格式和 VAD。下面是 Qwen3.8-Omni-Flash-Realtime 的 WebSocket Manual 模式配置,與最小音訊問答示例一致。本例使用“龍安靈心”音色(longanlingxin):
{
  "type": "session.update",
  "session": {
    "modalities": [
      "text",
      "audio"
    ],
    "turn_detection": null,
    "audio": {
      "input": {
        "format": {
          "type": "pcm",
          "sample_rate": 16000,
          "sample_format": "s16le",
          "channels": 1,
          "packing": "interleaved",
          "channel_layout": "mono"
        }
      },
      "output": {
        "voice": "longanlingxin",
        "format": {
          "type": "pcm",
          "sample_rate": 24000
        }
      }
    }
  }
}
以下示例使用 Qwen3.5-Omni-Realtime、Ethan 音色和 semantic_vad 模式。
{
    // 该事件的id,由客户端生成
    "event_id": "event_ToPZqeobitzUJnt3QqtWg",
    // 事件类型,固定为session.update
    "type": "session.update",
    // 会话配置
    "session": {
        // 输出模态,支持设置为["text"](仅输出文本)或["text","audio"](输出文本与音频)。
        "modalities": [
            "text",
            "audio"
        ],
        // 输出音频的音色
        "voice": "Ethan",
        // 推荐写法:同时配置音频格式和采样率(仅 qwen3.5-omni-plus-realtime / qwen3.5-omni-flash-realtime 支持)
        // 输入格式:pcm / wav,默认 pcm;采样率:8000/16000/24000/48000,默认 16000
        // 输出格式:pcm / wav,默认 pcm;采样率:8000/16000/24000/48000,默认 24000
        "audio": {
            "input": {
                "format": {
                    "type": "pcm",
                    "sample_rate": 16000
                }
            },
            "output": {
                "format": {
                    "type": "pcm",
                    "sample_rate": 24000
                }
            }
        },
        // 系统消息,用于设定模型的目标或角色。
        "instructions": "你是某五星级酒店的AI客服专员,请准确且友好地解答客户关于房型、设施、价格、预订政策的咨询。请始终以专业和乐于助人的态度回应,杜绝提供未经证实或超出酒店服务范围的信息。",
        // 是否开启语音活动检测。若需启用,需传入一个配置对象,服务端将据此自动检测语音起止。
        // 设置为null表示由客户端决定何时发起模型响应。
        "turn_detection": {
            // VAD类型,取值为server_vad或semantic_vad。使用qwen3.5-omni-realtime系列模型时推荐设为semantic_vad。
            "type": "semantic_vad",
            // VAD检测阈值。建议在嘈杂的环境中增加,在安静的环境中降低。
            "threshold": 0.5,
            // 检测语音停止的静音持续时间,超过此值后会触发模型响应。取值范围 200-6000,默认 800。金融核实等短回答场景建议 500-600。
            "silence_duration_ms": 800
        }
    }
}
本段列舉的音訊格式與採樣率選項適用於 qwen3.5-omni-plus-realtime 和 qwen3.5-omni-flash-realtime 模型,歷史兼容欄位 input_audio_format / output_audio_format 仍有效,建議採用 audio.input.format / audio.output.format 欄位。
媒體格式和多通道配置見輸入與輸出功能,工具配置見工具呼叫與聯網搜索。

輪次控制與事件時序

  • VAD 模式
  • Manual 模式
將session.update事件的session.turn_detection.type 設為"server_vad"或"semantic_vad"以啓用 VAD 模式。適用於語音通話場景。WebSocket 和 WebRTC 均支援 VAD 模式;音訊和圖片的傳輸方式及部分服務端事件不同。使用 Qwen3.8-Omni-Flash-Realtime 系列模型進行客服或商務對話時,可將 session.turn_detection.type 設為 "semantic_vad_ec"。相比 semantic_vad,該模式更易於檢測到用戶說話並打斷模型回覆,同時仍可過濾背景音等無意義聲音。
WebRTC 僅支援 VAD 模式,不支援 Manual 模式。WebRTC 的音訊透過 RTP 直接傳輸,無需發送 input_audio_buffer.append 事件;圖片透過視訊軌道傳輸,不支援 input_image_buffer.append 事件。控制指令和服務端事件透過 DataChannel 傳輸,具體事件參見服務端事件。
交互流程如下:
  1. 用戶端發送音訊資料。WebSocket 透過 input_audio_buffer.append 事件發送;WebRTC 透過音訊軌道(RTP)自動傳輸,無需手動發送事件。
  2. 服務端檢測到語音開始,透過 DataChannel(WebRTC)或 WebSocket 發送 input_audio_buffer.speech_started 事件。
  3. 服務端檢測到語音結束,發送input_audio_buffer.speech_stopped 事件。
  4. 服務端自動提交音訊緩衝區,發送input_audio_buffer.committed 事件。
  5. 服務端開始生成響應,依次發送 response.created、conversation.item.created 等事件。模型的音訊回覆透過 WebSocket 的 response.audio.delta 事件增量返回,或透過 WebRTC 的音訊軌道(RTP)直接傳輸。
  6. 響應過程中,服務端透過 response.audio_transcript.delta 事件增量返回文字轉錄,最終發送 response.done 事件標誌響應完成。
生命週期用戶端事件服務端事件
會話初始化session.update
會話配置
session.created
會話已建立
session.updated
會話配置已更新
用戶音訊輸入input_audio_buffer.append
WebSocket:透過此事件添加音訊到緩衝區
input_image_buffer.append
WebSocket:透過此事件添加圖片到緩衝區
WebRTC:音訊透過 RTP 音訊軌道自動傳輸,圖片透過視訊軌道傳輸,無需發送上述事件。
input_audio_buffer.speech_started
檢測到語音開始
input_audio_buffer.speech_stopped
檢測到語音結束
input_audio_buffer.committed
服務器收到提交的音訊
服務器音訊輸出無response.created
服務端開始生成響應
response.output_item.added
響應時有新的輸出內容
conversation.item.created
對話項被建立
response.content_part.added
新的輸出內容添加到assistant message
response.audio_transcript.delta
增量生成的轉錄文字
response.audio.delta
WebSocket:模型增量生成的音訊透過此事件返回。WebRTC:音訊透過 RTP 音訊軌道直接傳輸,不返回此事件。
response.audio_transcript.done
文本轉錄完成
response.audio.done
音訊生成完成
response.content_part.done
Assistant message 的文本或音訊內容流式輸出完成
response.output_item.done
Assistant message 的整個輸出項流式傳輸完成
response.done
響應完成
conversation.item.input_audio_transcription.delta
用戶語音輸入的文字流式轉錄(需在 session.update 中啓用 input_audio_transcription)
conversation.item.input_audio_transcription.completed
用戶語音輸入的文字轉錄完成(需在 session.update 中啓用 input_audio_transcription)

結束會話

每通會話結束後,應斷開連接。WebSocket 接入可呼叫 close() 關閉連接;WebRTC 接入需停止媒體並關閉 PeerConnection,具體步驟參見結束會話與資源清理。同一會話不關閉會導致上下文持續累積。 呼叫 close() 關閉 WebSocket 連接時,若連接剛建立即關閉(無會話交互),關閉耗時約 5-10 秒,此為正常現象。服務端需完成音訊流處理、上下文緩存及推理資源初始化後才能響應關閉請求。建議異步執行 close() 操作,避免阻塞主流程。

會話時長與上下文限制

qwen3.8-omni-flash-realtime 的全部輸入 Token 總數上限為 196608,輸入長度計算規則與 Qwen3.5-Omni-Realtime 一致。
  • 歷史對話與本輪輸入的 Token 總數超過最大輸入長度時,服務端會自動截斷歷史對話並繼續對話。文本和工具返回結果也計入輸入長度。
  • 本輪輸入本身超過最大輸入長度時,服務端會返回錯誤。
  • 單次會話最長可持續 120 分鐘,達到此上限後服務將主動關閉連接。
  • 模型會維護對話歷史上下文,當對話輪次或累計時長超過以下限制時,將自動丟棄更早的歷史資訊。最大時長指模型上下文中能保留的音訊或視訊(圖像幀)累計時長上限。該時長不是整個會話的持續時間。
    由於視訊以抽幀方式輸入(建議 1 幀/秒),視訊最大時長即模型能保留的圖像幀累計時長。例如 240 秒錶示模型最多保留最近 240 秒內收到的幀,超過後更早的幀將被丟棄。

    模型

    音訊最大輪次

    視訊最大輪次

    音訊最大時長

    視訊最大時長

    qwen3.8-omni-flash-realtime

    100輪

    50輪

    600秒

    240秒

    qwen3.5-omni-plus-realtime

    100輪

    50輪

    600秒

    240秒

    qwen3.5-omni-flash-realtime

    80輪

    50輪

    480秒

    120秒

輸入與輸出功能

按任務選擇音訊輸入、圖片與視訊、多通道音訊或音色。工具呼叫介紹 Function Calling、MCP 和聯網搜索配置。

音訊輸入

音訊是推薦的主要輸入方式,可按需搭配圖片。 WebSocket 透過 input_audio_buffer.append 追加 Base64 編碼音訊;WebRTC 透過建連時添加的音訊軌道(RTP)自動傳輸,無需該事件。音訊格式見會話配置,錄音與發送實現見即時對話示例。

圖片與視訊輸入

圖片可來自本地文件,也可從視訊流中即時採集。按協議選擇發送方式:
  • WebSocket
  • WebRTC
透過 input_image_buffer.append 發送 Base64 編碼圖片到服務端緩衝區。發送圖片前,至少發送過一次 input_audio_buffer.append。
  • VAD 模式:服務端在檢測到語音結束時自動提交音訊與圖片並觸發響應。本輪圖片應在 input_audio_buffer.speech_stopped 前發送。
  • Manual 模式:追加完本輪音訊與圖片後,發送 input_audio_buffer.commit,收到 input_audio_buffer.committed 後發送 response.create 請求回覆,見事件時序。
本地圖片示例:進入即時對話示例,選擇“WebSocket → Python 原生 WebSocket → Manual 模式”,展開 manual_mode.py,取消圖片輸入與發送兩部分代碼的注釋。視訊通話場景可對視訊抽幀,建議以 1 張/秒的頻率透過 input_image_buffer.append 發送圖像。DashScope SDK 代碼見Omni-Realtime 示例代碼。

可選:視訊聚合

Qwen3.8-Omni-Flash-Realtime 的 session.video.input.representation_compact 預設為 none;設為 normal 可聚合視訊表徵,降低計算開銷,適用於不依賴細粒度視覺資訊的場景。需在首段音訊前配置,開始輸入後不得修改。 以下配置使用 Manual 模式、文本與音訊輸出、Tina 音色,並關閉輸入轉寫。conversation 為已連接的 SDK 會話。SDK 會同時發送音色、VAD 等配置,如需調整,在同一次呼叫中完整設置。
  • Python
  • Java
使用 DashScope Python SDK 2.0.1 及以上版本,在即時對話示例中選擇“WebSocket → DashScope Python SDK → Manual 模式”:
  1. 在 manual_dash.py 中,將模型設為 qwen3.8-omni-flash-realtime。
  2. 用下方呼叫替換原 update_session 呼叫(input_video_representation_compact 即視訊聚合配置),在首段音訊前呼叫一次。
  3. 因本例關閉輸入轉寫,省略提交後的 ctx['transcription_done'].wait(timeout=10),繼續執行原有提交與發起回覆流程。
Python
session.update_session(
    output_modalities=['audio', 'text'],
    voice="Tina",
    enable_turn_detection=False,
    enable_input_audio_transcription=False,
    input_video_representation_compact="normal",
)
配置後按圖片與視訊輸入的步驟發送畫面,視訊 Token 計量見計費規則。

多通道音訊

以下配置適用於 Qwen3.8-Omni-Flash-Realtime 的 WebSocket 接入。 在首段音訊前設置 session.audio.input.format。支援 1、2、4 聲道;多通道必須為 PCM、16000 Hz、s16le、interleaved。2 聲道使用 raw_mic_array,4 聲道使用 foa_ambix。欄位約束和 JSON 片段見用戶端事件。 輸入 Token 的倍數見計費規則。

接收文本與音訊

模型的響應格式取決於配置的輸出模態。
  • WebSocket
  • WebRTC

音色與聲音複刻

以下配置適用於 Qwen3.8-Omni-Flash-Realtime。 預設音色為 Tina。新接入使用 session.audio.output.voice;如果同時設置了它和兼容欄位 session.voice,輸出音訊使用 session.audio.output.voice 指定的音色。可選音色和試聽見Qwen3.8 音色,自定義音色見聲音複刻,其他型號見完整音色列表。

工具呼叫與聯網搜索

  • 聯網搜索和工具呼叫不兼容,不可同時開啓。
需要自定義工具時,參見Function Calling;接入遠程服務時,使用下方 MCP 入口;獲取即時資訊時,使用聯網搜索。 Function Calling 的工具結果透過 conversation.item.create 回填,item.type 設為 function_call_output。

MCP

以下配置適用於 Qwen3.8-Omni-Flash-Realtime。 在 session.tools 中配置公網 HTTPS MCP Streamable HTTP 服務;僅在沒有活動 Response 時更新 MCP 配置。預設需要審批。先確認工具發現完成,再發起需要該工具的 Response。執行結果、拒絕和失敗處理以及續答步驟見MCP 交互流程。

連網搜尋

連網搜尋功能使模型能夠基於即時檢索資料進行回複,適用於股票價格、天氣預報等需要即時資訊的情境。模型可自主判斷是否需要搜尋來回應使用者的即時問題。
連網搜尋僅 Qwen3.5-Omni-Realtime 系列模型支援,且預設關閉,需通過 session.update 事件啟用。
計費請參考計費說明中的agent策略。

啟用方式

在 session.update 事件中添加以下參數:
  • enable_search:設定為 true 啟用連網搜尋功能。
  • search_options.enable_source:設定為 true 返回搜尋結果來源列表。
參數詳情請參見session.update。

回覆與搜索執行情況

回覆仍透過文本與音訊事件接收。下方示例在收到 response.done 後讀取搜索計量中的 count 和 strategy,打印搜索次數與策略;計量欄位見搜索計量。

程式碼範例

以下樣本展示如何在即時對話中啟用連網搜尋功能。
  • DashScope Python SDK
  • DashScope Java SDK
  • WebSocket(Python)
在 update_session 調用中傳入 enable_search 和 search_options 參數:
import os
import base64
import time

import pyaudio
from concurrent.futures import ThreadPoolExecutor

import dashscope

# 以下為新加坡(ap-southeast-1)地區的設定。請在範例中填寫實際的業務空間 ID。region 的值因地區而異。
client = dashscope.Client(
    # If you have not set an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
    # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)
model = 'qwen3.8-omni-flash-realtime'
voice = 'Tina'

pya = pyaudio.PyAudio()
out = pya.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)

# Receiver thread: iterate server events
def receive_events(session):
    for response in session.events():
        if response['type'] == 'response.audio.delta':
            out.write(base64.b64decode(response['delta']))
        elif response['type'] == 'conversation.item.input_audio_transcription.delta':
            preview = response.get('text', '') + response.get('stash', '')
            print(f"\r[User] {preview}", end='', flush=True)
        elif response['type'] == 'conversation.item.input_audio_transcription.completed':
            print(f"\r[User] {response['transcript']}")
        elif response['type'] == 'response.audio_transcript.done':
            print(f"[LLM] {response['transcript']}")
        elif response['type'] == 'response.done':
            usage = response.get('response', {}).get('usage', {})
            plugins = usage.get('plugins', {})
            if plugins.get('search'):
                print(f"[Search] count={plugins['search']['count']}, strategy={plugins['search']['strategy']}")

with client.audio.realtime.connect(model=model) as session:
    session.update_session(
        output_modalities=['audio', 'text'],
        voice=voice,
        instructions="你是个人助理小云",
        enable_search=True,
        search_options={'enable_source': True}
    )
    mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
    print("联网搜索已启用,对着麦克风说话 (Ctrl+C 退出)...")
    try:
        with ThreadPoolExecutor(max_workers=1) as pool:
            receiver = pool.submit(receive_events, session)
            while True:
                audio_data = mic.read(3200, exception_on_overflow=False)
                session.append_audio(audio_data)
                time.sleep(0.01)
    except KeyboardInterrupt:
        session.close()
        mic.close()
        out.close()
        pya.terminate()
        print("\n对话结束")

響應格式

啟用連網搜尋後,response.done 事件中的 usage 會新增 plugins 欄位,用於記錄搜尋計量資訊:
{
    "usage": {
        "total_tokens": 2937,
        "input_tokens": 2554,
        "output_tokens": 383,
        "input_tokens_details": {
            "text_tokens": 2512,
            "audio_tokens": 42
        },
        "output_tokens_details": {
            "text_tokens": 90,
            "audio_tokens": 293
        },
        "plugins": {
            "search": {
                "count": 1,
                "strategy": "agent"
            }
        }
    }
}

計費與限流

計費規則

Qwen-Omni-Realtime 模型根據不同模態(音訊、圖像)對應的Token數計費。計費詳情請參見百鍊控制台。 輸出語音時,qwen3.8-omni-flash-realtime 的音訊及對應文字分別按音訊輸出和文字輸出單價計費;Qwen3.5-Omni-Realtime 系列僅對音訊計費,對應文字不計費。 MCP 工具呼叫不額外收費,模型推理仍按模型價格計費。MCP 的呼叫流程與使用限制見MCP 交互流程。
在多輪即時對話中,模型每次生成響應時,需要將上下文窗口內的所有歷史對話內容(包括之前各輪的音訊、圖片和文本)與本輪新增輸入一並作為輸入 Token 進行處理。因此,輸入 Token 會隨對話輪次的增加而逐輪累積,而非僅計算當前輪次的新增輸入。例如,假設一段 10 秒的音訊輸入轉換為 70 個 Token(Qwen3.5-Omni-Realtime 系列模型),在第 3 輪對話時,該音訊仍在上下文窗口內,則它依然會被計入第 3 輪的輸入 Token。實際計費的輸入 Token 數 = 上下文窗口內所有歷史輪次的內容 Token 數 + 本輪新增輸入的 Token 數。
  • 音頻
  • 圖片
  • 視訊
  • Qwen3.8-Omni-Flash-Realtime、Qwen3.5-Omni-Realtime 系列模型:
    • 輸入音訊計算公式:总 Token 数 = 音频时长(单位:秒)* 7
    • 輸出音訊計算公式:总 Tokens 数 = 音频时长(单位:秒)* 12.5
  • qwen3-omni-flash-realtime-2025-09-15:輸入與輸出音訊的計算公式均為总 Token 数 = 音频时长(单位:秒)* 12.5 若音訊時長不足1秒,則按 1 秒計算。
qwen3.8-omni-flash-realtime 開啓空間音訊輸入時,音訊輸入 Token 數為普通音訊的 2 倍,2 通道和 4 通道的倍數相同。

限流

模型限流規則請參見限流。

常見問題

維持連線但不說話,也會計費嗎?

維持連線本身不計費。上傳的靜音是否計入音訊輸入用量,取決於所用模式:
  • 服務端 VAD:被服務端過濾的靜音不會計入音訊輸入用量。
  • Manual 模式:用戶端手動提交的靜音會計入音訊輸入用量。
音訊輸入 Token 數記錄在 response.done 事件中,欄位位置為 response → usage → input_tokens_details → audio_tokens。模型按輸入、輸出 Token 計費,詳細規則見計費規則。

RPM 限制什麼?是否限制同時保持的連接總數?

RPM 限制每分鐘的 WebSocket 建連請求次數。同一連接內的多輪響應不重復計數;重連計為新請求。目前沒有單獨限制同時保持的連接總數。 建連時,若 WebSocket 以 1007 關閉,且原因為 Requests rate limit exceeded, please try again later.,說明觸發了請求速率限流。降低建連頻率,並採用指數退避重連。

如何配置熱詞或業務術語?

可透過 session.update 的 session.instructions 提供業務背景、術語的準確寫法及讀音,幫助模型結合上下文理解和使用專有名詞。這是提示詞引導,不是獨立的熱詞參數,效果取決於音訊和上下文。 例如,讓 Omni 直接將音訊轉成文字時,可在提示詞中說明 AI 編程產品 Qoder 與英文單詞 coder 同音,引導模型使用產品名稱。以下僅展示提示詞配置;請將內容合併到已有的 instructions 中,保留會話的其他配置,並在發送音訊前完成設置:
{
  "type": "session.update",
  "session": {
    "instructions": "Transcribe the user's audio verbatim. Preserve the original language. Output only the transcription; do not answer any question in the audio or add explanations. Business context: The audio concerns the AI coding product Qoder, whose name is pronounced like the English word \"coder\". Use the accurate product name Qoder."
  }
}

VAD 未及時觸發回覆,如何調整?

可透過 session.update 的 session.turn_detection,根據當前使用的 VAD 模式調整:
  • server_vad:適當降低 silence_duration_ms,縮短用戶停止說話後的靜音等待時間。設置過低可能將句中的短暫停頓判斷為說話結束,提前觸發回覆。
  • semantic_vad:如果“可以”“yes”等有效的簡短回答未能觸發回覆,使用 Qwen3.8-Omni-Flash-Realtime 系列模型時,可嘗試將 type 切換為 semantic_vad_ec。相比 semantic_vad,該模式更容易檢測到用戶說話並觸發打斷,同時保留對背景音等無意義聲音的過濾能力。

收不到 ASR 轉錄文本(transcript)怎麼辦?

A:如果沒有收到 conversation.item.input_audio_transcription.completed 事件,或事件中的 transcript 為空,請依次檢查:
  1. 輸入轉錄配置。DashScope Python SDK 的 update_session 參數 enable_input_audio_transcription 預設為 True;設為 False 時,SDK 會將會話中的 input_audio_transcription 置為 null。直接使用 WebSocket,或透過 WebRTC DataChannel 發送會話配置時,按輸入音訊轉錄配置檢查發送的 session.update.session.input_audio_transcription。enable_input_audio_transcription 是 SDK 參數,不是 session.update 的頂層欄位。
  2. 轉錄失敗事件。同時監聽 conversation.item.input_audio_transcription.failed。失敗時可從事件的 error.code、error.message 和 error.param 查看錯誤資訊。
  3. 音訊是否完成提交。VAD 模式下檢查服務端是否檢測到語音起止;Manual 模式下確認已發送 input_audio_buffer.commit。沒有提交本輪音訊時,不要只等待轉錄完成事件。
  4. 連接和 SDK 版本。確認本輪音訊輸入期間連接未中斷;WebRTC 接入還需檢查 DataChannel 狀態。使用 DashScope Python SDK 時,核對版本符合本文的最低要求(2.0.1)。

錯誤碼

如果模型調用失敗並返回報錯資訊,請參見錯誤碼進行解決。

API 與 SDK 參考

透過 AOQ 接入的流程和示例,請參見AOQ 接入。協議選型和參考入口請參見API 參考。