Skip to content

Commit 598fd9d

Browse files
committed
chore: add example for posterity
1 parent e15781d commit 598fd9d

File tree

1 file changed

+137
-0
lines changed

1 file changed

+137
-0
lines changed

examples/agent/tags/main.py

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# Copyright 2024 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
from signal import SIGINT, SIGTERM
5+
import asyncio
6+
import time
7+
from deepgram.utils import verboselogs
8+
from deepgram import (
9+
DeepgramClient,
10+
DeepgramClientOptions,
11+
AgentWebSocketEvents,
12+
SettingsOptions,
13+
)
14+
TTS_TEXT = "Hello, this is a text to speech example using Deepgram."
15+
global warning_notice
16+
warning_notice = True
17+
async def main():
18+
try:
19+
loop = asyncio.get_event_loop()
20+
for signal in (SIGTERM, SIGINT):
21+
loop.add_signal_handler(
22+
signal,
23+
lambda: asyncio.create_task(shutdown(signal, loop, dg_connection)),
24+
)
25+
# example of setting up a client config. logging values: WARNING, VERBOSE, DEBUG, SPAM
26+
config: DeepgramClientOptions = DeepgramClientOptions(
27+
options={
28+
"keepalive": "true",
29+
"microphone_record": "true",
30+
"speaker_playback": "true",
31+
},
32+
# verbose=verboselogs.DEBUG,
33+
)
34+
# Initialize Deepgram client - API key should be set in DEEPGRAM_API_KEY environment variable
35+
# For production testing, make sure your API key has proper permissions
36+
deepgram: DeepgramClient = DeepgramClient("", config)
37+
print("Initialized Deepgram client for production API testing")
38+
# Create a websocket connection to Deepgram
39+
dg_connection = deepgram.agent.asyncwebsocket.v("1")
40+
async def on_open(self, open, **kwargs):
41+
print(f"\n\n{open}\n\n")
42+
async def on_binary_data(self, data, **kwargs):
43+
global warning_notice
44+
if warning_notice:
45+
print("Received binary data")
46+
print("You can do something with the binary data here")
47+
print("OR")
48+
print(
49+
"If you want to simply play the audio, set speaker_playback to true in the options for DeepgramClientOptions"
50+
)
51+
warning_notice = False
52+
async def on_welcome(self, welcome, **kwargs):
53+
print(f"\n\n{welcome}\n\n")
54+
async def on_settings_applied(self, settings_applied, **kwargs):
55+
print(f"\n\n{settings_applied}\n\n")
56+
async def on_conversation_text(self, conversation_text, **kwargs):
57+
print(f"\n\n{conversation_text}\n\n")
58+
async def on_user_started_speaking(self, user_started_speaking, **kwargs):
59+
print(f"\n\n{user_started_speaking}\n\n")
60+
async def on_agent_thinking(self, agent_thinking, **kwargs):
61+
print(f"\n\n{agent_thinking}\n\n")
62+
async def on_agent_started_speaking(self, agent_started_speaking, **kwargs):
63+
print(f"\n\n{agent_started_speaking}\n\n")
64+
async def on_agent_audio_done(self, agent_audio_done, **kwargs):
65+
print(f"\n\n{agent_audio_done}\n\n")
66+
async def on_close(self, close, **kwargs):
67+
print(f"\n\n{close}\n\n")
68+
async def on_error(self, error, **kwargs):
69+
print(f"\n\n{error}\n\n")
70+
async def on_unhandled(self, unhandled, **kwargs):
71+
print(f"\n\n{unhandled}\n\n")
72+
dg_connection.on(AgentWebSocketEvents.Open, on_open)
73+
dg_connection.on(AgentWebSocketEvents.AudioData, on_binary_data)
74+
dg_connection.on(AgentWebSocketEvents.Welcome, on_welcome)
75+
dg_connection.on(AgentWebSocketEvents.SettingsApplied, on_settings_applied)
76+
dg_connection.on(AgentWebSocketEvents.ConversationText, on_conversation_text)
77+
dg_connection.on(
78+
AgentWebSocketEvents.UserStartedSpeaking, on_user_started_speaking
79+
)
80+
dg_connection.on(AgentWebSocketEvents.AgentThinking, on_agent_thinking)
81+
dg_connection.on(
82+
AgentWebSocketEvents.AgentStartedSpeaking, on_agent_started_speaking
83+
)
84+
dg_connection.on(AgentWebSocketEvents.AgentAudioDone, on_agent_audio_done)
85+
dg_connection.on(AgentWebSocketEvents.Close, on_close)
86+
dg_connection.on(AgentWebSocketEvents.Error, on_error)
87+
dg_connection.on(AgentWebSocketEvents.Unhandled, on_unhandled)
88+
# connect to websocket
89+
options = SettingsOptions()
90+
options.agent.think.provider.type = "open_ai"
91+
options.agent.think.provider.model = "gpt-4o-mini"
92+
options.agent.think.prompt = "You are a helpful AI assistant."
93+
options.greeting = "Hello, this is a text to speech example using Deepgram."
94+
options.agent.listen.provider.keyterms = ["hello", "goodbye"]
95+
options.agent.listen.provider.model = "nova-3"
96+
options.agent.listen.provider.type = "deepgram"
97+
options.agent.speak.provider.type = "deepgram"
98+
options.agent.speak.provider.model = "aura-2-thalia-en"
99+
options.agent.language = "en"
100+
# Add tags for production testing
101+
options.tags = ["production-test", "sdk-example", "agent-websocket", "tags-validation"]
102+
print(f"Using tags: {options.tags}")
103+
# Print the full options being sent
104+
print("Options being sent to API:")
105+
print(options.to_json())
106+
print("\n\n✅ Connection established with tags!")
107+
print(f"✅ Tags being used: {options.tags}")
108+
print("\n🎤 You can now speak into your microphone...")
109+
print("The agent will respond using the production API with tags.")
110+
print("Press Ctrl+C to stop.\n\n")
111+
if await dg_connection.start(options) is False:
112+
print("Failed to start connection")
113+
return
114+
# wait until cancelled
115+
try:
116+
while True:
117+
await asyncio.sleep(1)
118+
except asyncio.CancelledError:
119+
# This block will be executed when the shutdown coroutine cancels all tasks
120+
pass
121+
finally:
122+
await dg_connection.finish()
123+
print("Finished")
124+
except ValueError as e:
125+
print(f"Invalid value encountered: {e}")
126+
except Exception as e:
127+
print(f"An unexpected error occurred: {e}")
128+
async def shutdown(signal, loop, dg_connection):
129+
print(f"Received exit signal {signal.name}...")
130+
await dg_connection.finish()
131+
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
132+
[task.cancel() for task in tasks]
133+
print(f"Cancelling {len(tasks)} outstanding tasks")
134+
await asyncio.gather(*tasks, return_exceptions=True)
135+
loop.stop()
136+
print("Shutdown complete.")
137+
asyncio.run(main())

0 commit comments

Comments
 (0)