Skip to content

Commit 1c49957

Browse files
committed
feat(examples): add WebSocket connection options example
Demonstrates how to pass custom request options (headers) when connecting to Deepgram WebSocket API.
1 parent 006dd77 commit 1c49957

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

examples/72-ws-connect-options.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
"""
2+
Example: WebSocket Request Options - Additional Headers and Query Parameters
3+
4+
This example shows how to use request_options with WebSocket connections
5+
to add additional headers and query parameters to the connection request.
6+
"""
7+
8+
import os
9+
import threading
10+
import time
11+
12+
from dotenv import load_dotenv
13+
14+
load_dotenv()
15+
16+
from deepgram import DeepgramClient
17+
from deepgram.core.events import EventType
18+
from deepgram.listen.v1.types import ListenV1Results
19+
20+
# Audio streaming configuration
21+
CHUNK_SIZE = 8192
22+
SAMPLE_RATE = 44100
23+
SAMPLE_WIDTH = 2
24+
CHANNELS = 1
25+
CHUNK_DELAY = CHUNK_SIZE / (SAMPLE_RATE * SAMPLE_WIDTH * CHANNELS)
26+
27+
client = DeepgramClient()
28+
29+
try:
30+
print("Connecting to Deepgram WebSocket with custom request options...")
31+
32+
# Connect with additional headers and query parameters
33+
with client.listen.v1.connect(
34+
model="nova-3",
35+
language="en",
36+
smart_format=True,
37+
request_options={
38+
"additional_headers": {
39+
"X-Custom-Header": "custom-value",
40+
"X-Request-ID": "example-request-123",
41+
},
42+
# Note: additional_query_parameters are currently not working
43+
# for WebSocket connections, but the structure is shown here
44+
# for future compatibility
45+
"additional_query_parameters": {
46+
"detect_language": ["en", "es"],
47+
},
48+
},
49+
) as connection:
50+
51+
print("Connected successfully with custom headers!")
52+
53+
# Register event handlers
54+
def on_open(_):
55+
print("Connection opened")
56+
57+
def on_message(message):
58+
if isinstance(message, ListenV1Results):
59+
if message.channel and message.channel.alternatives:
60+
transcript = message.channel.alternatives[0].transcript
61+
if transcript:
62+
print(f"Transcript: {transcript}")
63+
64+
def on_error(error):
65+
print(f"Error: {error}")
66+
67+
def on_close(_):
68+
print("Connection closed")
69+
70+
connection.on(EventType.OPEN, on_open)
71+
connection.on(EventType.MESSAGE, on_message)
72+
connection.on(EventType.ERROR, on_error)
73+
connection.on(EventType.CLOSE, on_close)
74+
75+
# Define a function to send audio in a background thread
76+
def send_audio():
77+
audio_path = os.path.join(os.path.dirname(__file__), "fixtures", "audio.wav")
78+
79+
with open(audio_path, "rb") as audio_file:
80+
print(f"Streaming audio from {audio_path}")
81+
82+
while True:
83+
chunk = audio_file.read(CHUNK_SIZE)
84+
if not chunk:
85+
break
86+
87+
connection.send_media(chunk)
88+
time.sleep(CHUNK_DELAY)
89+
90+
print("Finished sending audio")
91+
92+
# Start sending audio in a background thread
93+
threading.Thread(target=send_audio, daemon=True).start()
94+
95+
# Start listening - this blocks until the connection closes or times out
96+
connection.start_listening()
97+
98+
# Additional request_options that can be used:
99+
# with client.listen.v1.connect(
100+
# model="nova-3",
101+
# language="en",
102+
# smart_format=True,
103+
# request_options={
104+
# "additional_headers": {
105+
# "X-Custom-Header": "custom-value",
106+
# "X-Request-ID": "example-request-123",
107+
# "X-Client-Version": "1.0.0",
108+
# },
109+
# "additional_query_parameters": {
110+
# "detect_language": ["en", "es"],
111+
# # Note: Additional query parameters for WebSocket are
112+
# # currently not working, but may be supported in the future
113+
# },
114+
# "timeout_in_seconds": 30,
115+
# }
116+
# ) as connection:
117+
# # ... register handlers and start listening
118+
119+
except Exception as e:
120+
print(f"Error: {e}")

0 commit comments

Comments
 (0)