-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
172 lines (147 loc) · 5.15 KB
/
example.py
File metadata and controls
172 lines (147 loc) · 5.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "pipecat-getstream",
# "pipecat-ai[google,deepgram,silero]",
# "python-dotenv",
# "loguru",
# ]
#
# [tool.uv.sources]
# pipecat-getstream = { path = ".", editable = true }
# ///
import asyncio
import os
import sys
import uuid
import webbrowser
from urllib.parse import urlencode
from dotenv import load_dotenv
from loguru import logger
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.frames.frames import LLMRunFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.runner import PipelineRunner
from pipecat.pipeline.task import PipelineParams, PipelineTask
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import (
LLMContextAggregatorPair,
LLMUserAggregatorParams,
)
from pipecat.services.deepgram.stt import DeepgramSTTService
from pipecat.services.deepgram.tts import DeepgramTTSService
from pipecat.services.google.llm import GoogleLLMService
from pipecat_getstream.transport import GetstreamParams, GetstreamTransport
from pipecat_getstream.utils import GetstreamRESTHelper
load_dotenv()
logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
async def _open_browser(url: str) -> None:
logger.info(f"🌐 Opening browser to: {url}")
try:
# Run webbrowser.open in a separate thread to avoid blocking the event loop
await asyncio.to_thread(webbrowser.open, url)
logger.info("✅ Browser opened successfully!")
except Exception as e:
logger.error(f"❌ Failed to open browser: {e}")
logger.warning(f"Please manually open this URL: {url}")
async def main():
stream_base_url = os.getenv("STREAM_BASE_URL")
if not stream_base_url:
raise ValueError("STREAM_BASE_URL environment variable not set.")
stream_api_key = os.getenv("STREAM_API_KEY")
stream_api_secret = os.getenv("STREAM_API_SECRET")
stream_call_type = os.getenv("STREAM_CALL_TYPE", "default")
stream_call_id = os.getenv("STREAM_CALL_ID", str(uuid.uuid4()))
transport = GetstreamTransport(
api_key=stream_api_key,
api_secret=stream_api_secret,
call_type=stream_call_type,
call_id=stream_call_id,
user_id=os.getenv("STREAM_USER_ID", "pipecat-bot"),
params=GetstreamParams(
audio_out_enabled=True,
audio_in_enabled=True,
video_out_enabled=True,
video_in_enabled=True,
video_out_is_live=True,
),
)
helper = GetstreamRESTHelper(
api_key=stream_api_key,
api_secret=stream_api_secret,
)
stt = DeepgramSTTService(api_key=os.getenv("DEEPGRAM_API_KEY"))
llm = GoogleLLMService(
api_key=os.getenv("GOOGLE_API_KEY"),
settings=GoogleLLMService.Settings(
system_instruction="You are a helpful assistant in a voice conversation. Your responses will be spoken aloud, so avoid emojis, bullet points, or other formatting that can't be spoken. Respond to what the user said in a creative, helpful, and brief way.",
),
)
tts = DeepgramTTSService(
api_key=os.getenv("DEEPGRAM_API_KEY"),
voice="aura-2-thalia-en",
)
context = LLMContext()
user_aggregator, assistant_aggregator = LLMContextAggregatorPair(
context,
user_params=LLMUserAggregatorParams(vad_analyzer=SileroVADAnalyzer()),
)
pipeline = Pipeline(
[
transport.input(),
stt,
user_aggregator,
llm,
tts,
transport.output(),
assistant_aggregator,
]
)
runner = PipelineRunner()
task = PipelineTask(
pipeline,
params=PipelineParams(
enable_metrics=True,
enable_usage_metrics=True,
),
)
@transport.event_handler("on_stream_custom_event")
def on_stream_custom_event(*args, **kwargs):
"""
A callback to react on Custom events sent to the call in Stream
"""
...
@transport.event_handler("on_connected")
async def on_connected(*_):
"""
Create a demo call link and automatically open it in the browser
once the agent joins the call.
"""
user_id = "demo-user"
token = helper.create_token(user_id=user_id, expiration=60)
params = {
"api_key": stream_api_key,
"token": token,
"skip_lobby": "true",
"user_name": user_id,
"video_encoder": "h264",
"bitrate": 12000000,
"w": 1920,
"h": 1080,
}
call_url = f"{stream_base_url}/join/{stream_call_id}?{urlencode(params)}"
await _open_browser(call_url)
@transport.event_handler("on_first_participant_joined")
async def on_first_participant_joined(*_):
await asyncio.sleep(1)
context.add_message(
{
"role": "user",
"content": "Start by greeting the user and ask how you can help.",
}
)
await task.queue_frames([LLMRunFrame()])
await runner.run(task)
if __name__ == "__main__":
asyncio.run(main())