Skip to content

[Bug]: Error connect websocket STT streaming #654

@phamkhactu

Description

@phamkhactu

Summary

Unexpected error when initializing websocket connection

What happened?

sometimes, I can not connect to wss and sometimes can connect

Steps to reproduce

  1. pip install deepgram-sdk

Minimal code sample

import asyncio
import os
from deepgram import AsyncDeepgramClient
from deepgram.core.events import EventType
from deepgram.extensions.types.sockets import ListenV2SocketClientResponse
from deepgram.extensions.types.sockets import ListenV2ControlMessage

from dotenv import load_dotenv

load_dotenv()


api_key = os.getenv("DEEPGRAM_API_KEY")
client = AsyncDeepgramClient(
    api_key=api_key,
)


async def main():
    async with client.listen.v2.connect(
        model="flux-general-en",
        encoding="linear16",
        sample_rate="16000",
    ) as connection:

        async def on_message(message: ListenV2SocketClientResponse) -> None:
            msg_type = getattr(message, "type", "Unknown")
            print(f"\n=== Received {msg_type} event ===")
            sentence = message.channel.alternatives[0].transcript
            print(f"Transcript: {sentence}")

        connection.on(EventType.OPEN, lambda _: print("Connection opened"))
        connection.on(EventType.MESSAGE, on_message)
        connection.on(EventType.CLOSE, lambda _: print("Connection closed"))
        connection.on(EventType.ERROR, lambda error: print(f"Error: {error}"))

        # Start listening
        asyncio.create_task(connection.start_listening())

        print("Started listening...")

        # Send audio data
        with open(
            "/home/pktu/tupk/My Learning/AI-Agent/appointment_wellcome.wav", "rb"
        ) as audio_file:
            audio_bytes = audio_file.read()

        print("Sending audio data...")
        await connection.send_media(audio_bytes)

        # Send control message to close stream
        await connection.send_control(ListenV2ControlMessage(type="CloseStream"))

        # Đợi để nhận hết các response
        await asyncio.sleep(3)


asyncio.run(main())

Logs / traceback

File "/home/pktu/tupk/My Learning/AI-Agent/twilio/test.py", line 57, in <module>
    asyncio.run(main())
  File "/home/pktu/miniconda3/envs/mywork/lib/python3.12/asyncio/runners.py", line 195, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/home/pktu/miniconda3/envs/mywork/lib/python3.12/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/pktu/miniconda3/envs/mywork/lib/python3.12/asyncio/base_events.py", line 691, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/home/pktu/tupk/My Learning/AI-Agent/twilio/test.py", line 20, in main
    async with client.listen.v2.connect(
               ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/pktu/miniconda3/envs/mywork/lib/python3.12/contextlib.py", line 210, in __aenter__
    return await anext(self.gen)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/pktu/miniconda3/envs/mywork/lib/python3.12/site-packages/deepgram/listen/v2/client.py", line 256, in connect
    raise ApiError(
deepgram.core.api_error.ApiError: headers: {'X-Fern-Language': 'Python', 'X-Fern-SDK-Name': 'deepgram', 'X-Fern-SDK-Version': '5.3.2', 'x-deepgram-session-id': '811a7c5f-550b-4fc1-b6e7-33b1e608c79d', 'Authorization': 'Token 1de8ec29ae4c6d7d28efb39fc135ef8c1a9a1d0b'}, status_code: 400, body: Unexpected error when initializing websocket connection.

Transport

HTTP

API endpoint / path

client.listen.v2

Model(s) used

flux-general-en

How often?

Always

Is this a regression?

  • Yes, it worked in an earlier version

Last working SDK version (if known)

No response

SDK version

5.3.2

Python version

3.12.12

Install method

None

OS

Linux (arm64)

Environment details


Link to minimal repro (optional)

No response

Session ID (optional)

No response

Project ID (optional)

No response

Request ID (optional)

No response

Code of Conduct

  • I agree to follow this project’s Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions