-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathpipeline_translator.py
More file actions
337 lines (262 loc) · 9.06 KB
/
Copy pathpipeline_translator.py
File metadata and controls
337 lines (262 loc) · 9.06 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
---
title: Pipeline Translator Agent
category: translation
tags: [translation, multilingual, french, elevenlabs, deepgram, openai]
difficulty: intermediate
description: Simple translation pipeline that converts English speech to French
demonstrates:
- Direct language translation workflow
- Multilingual TTS configuration with ElevenLabs
- Simple translation-focused agent instructions
- Clean input-to-output translation pipeline
- Voice-to-voice translation system
---
This example shows how to build a simple voice-to-voice translator: listen in English, translate with an LLM, and speak the result in French with ElevenLabs TTS. Instead of using LiveKit Inference, this example uses agent plugins to connect directly to OpenAI and ElevenLabs.
## Prerequisites
- Add a `.env` in this directory with your credentials:
```
LIVEKIT_URL=your_livekit_url
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret
OPENAI_API_KEY=your_api_key
ELEVENLABS_API_KEY=your_api_key
DEEPGRAM_API_KEY=your_api_key
```
- Install dependencies:
```bash
pip install "livekit-agents[silero,openai,elevenlabs,deepgram]" python-dotenv
```
<!-- {% step %} -->
<!-- {% instructions %} -->
## Load environment, logging, and define an AgentServer
Load your `.env` and set up logging to trace translation events.
<!-- {% /instructions %} -->
<!-- {% stepCode %} -->
```python
import logging
from dotenv import load_dotenv
from livekit.agents import JobContext, JobProcess, AgentServer, cli, Agent, AgentSession
from livekit.plugins import openai, silero, deepgram, elevenlabs
load_dotenv()
logger = logging.getLogger("pipeline-translator")
logger.setLevel(logging.INFO)
server = AgentServer()
```
<!-- {% /stepCode %} -->
<!-- {% /step %}-->
<!-- {% step %} -->
<!-- {% instructions %} -->
## Define the translation agent
Keep the agent lightweight with focused instructions: always translate from English to French and respond only with the translation.
<!-- {% /instructions %} -->
<!-- {% stepCode %} -->
```python
import logging
from dotenv import load_dotenv
from livekit.agents import JobContext, JobProcess, AgentServer, cli, Agent, AgentSession
from livekit.plugins import openai, silero, deepgram, elevenlabs
load_dotenv()
logger = logging.getLogger("pipeline-translator")
logger.setLevel(logging.INFO)
server = AgentServer()
```
<!-- {% added %} -->
```python
class TranslatorAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""
You are a translator. You translate the user's speech from English to French.
Every message you receive, translate it directly into French.
Do not respond with anything else but the translation.
"""
)
async def on_enter(self):
self.session.generate_reply()
```
<!-- {% /added %} -->
<!-- {% /stepCode %} -->
<!-- {% /step %}-->
<!-- {% step %} -->
<!-- {% instructions %} -->
## Prewarm VAD for faster connections
Preload the VAD model once per process to reduce connection latency.
<!-- {% /instructions %} -->
<!-- {% stepCode %} -->
```python
import logging
from dotenv import load_dotenv
from livekit.agents import JobContext, JobProcess, AgentServer, cli, Agent, AgentSession
from livekit.plugins import openai, silero, deepgram, elevenlabs
load_dotenv()
logger = logging.getLogger("pipeline-translator")
logger.setLevel(logging.INFO)
server = AgentServer()
class TranslatorAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""
You are a translator. You translate the user's speech from English to French.
Every message you receive, translate it directly into French.
Do not respond with anything else but the translation.
"""
)
async def on_enter(self):
self.session.generate_reply()
```
<!-- {% added %} -->
```python
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
server.setup_fnc = prewarm
```
<!-- {% /added %} -->
<!-- {% /stepCode %} -->
<!-- {% /step %}-->
<!-- {% step %} -->
<!-- {% instructions %} -->
## Define the rtc session with translation pipeline
Create the session with Deepgram STT, OpenAI LLM, and ElevenLabs multilingual TTS for French output.
<!-- {% /instructions %} -->
<!-- {% stepCode %} -->
```python
import logging
from dotenv import load_dotenv
from livekit.agents import JobContext, JobProcess, AgentServer, cli, Agent, AgentSession
from livekit.plugins import openai, silero, deepgram, elevenlabs
load_dotenv()
logger = logging.getLogger("pipeline-translator")
logger.setLevel(logging.INFO)
server = AgentServer()
class TranslatorAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""
You are a translator. You translate the user's speech from English to French.
Every message you receive, translate it directly into French.
Do not respond with anything else but the translation.
"""
)
async def on_enter(self):
self.session.generate_reply()
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
server.setup_fnc = prewarm
```
<!-- {% added %} -->
```python
@server.rtc_session()
async def entrypoint(ctx: JobContext):
ctx.log_context_fields = {"room": ctx.room.name}
session = AgentSession(
stt=deepgram.STT(),
llm=openai.LLM(),
tts=elevenlabs.TTS(model="eleven_multilingual_v2"),
vad=ctx.proc.userdata["vad"],
preemptive_generation=True,
)
await session.start(agent=TranslatorAgent(), room=ctx.room)
await ctx.connect()
```
<!-- {% /added %} -->
<!-- {% /stepCode %} -->
<!-- {% /step %}-->
<!-- {% step %} -->
<!-- {% instructions %} -->
## Run the server
Start the agent server with the CLI runner.
<!-- {% /instructions %} -->
<!-- {% stepCode %} -->
```python
import logging
from dotenv import load_dotenv
from livekit.agents import JobContext, JobProcess, AgentServer, cli, Agent, AgentSession
from livekit.plugins import openai, silero, deepgram, elevenlabs
load_dotenv()
logger = logging.getLogger("pipeline-translator")
logger.setLevel(logging.INFO)
server = AgentServer()
class TranslatorAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""
You are a translator. You translate the user's speech from English to French.
Every message you receive, translate it directly into French.
Do not respond with anything else but the translation.
"""
)
async def on_enter(self):
self.session.generate_reply()
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
server.setup_fnc = prewarm
@server.rtc_session()
async def entrypoint(ctx: JobContext):
ctx.log_context_fields = {"room": ctx.room.name}
session = AgentSession(
stt=deepgram.STT(),
llm=openai.LLM(),
tts=elevenlabs.TTS(model="eleven_multilingual_v2"),
vad=ctx.proc.userdata["vad"],
preemptive_generation=True,
)
await session.start(agent=TranslatorAgent(), room=ctx.room)
await ctx.connect()
```
<!-- {% added %} -->
```python
if __name__ == "__main__":
cli.run_app(server)
```
<!-- {% /added %} -->
<!-- {% /stepCode %} -->
<!-- {% /step %}-->
## Run it
```bash
python pipeline_translator.py console
```
## How it works
1. Deepgram handles English speech-to-text transcription.
2. OpenAI generates a French translation from the transcript.
3. ElevenLabs multilingual TTS speaks the translated text in French.
4. Silero VAD controls turn-taking between user and agent.
5. The agent triggers an initial response on entry so the user hears French output immediately.
## Full example
```python
import logging
from dotenv import load_dotenv
from livekit.agents import JobContext, JobProcess, AgentServer, cli, Agent, AgentSession
from livekit.plugins import openai, silero, deepgram, elevenlabs
load_dotenv()
logger = logging.getLogger("pipeline-translator")
logger.setLevel(logging.INFO)
class TranslatorAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""
You are a translator. You translate the user's speech from English to French.
Every message you receive, translate it directly into French.
Do not respond with anything else but the translation.
"""
)
async def on_enter(self):
self.session.generate_reply()
server = AgentServer()
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
server.setup_fnc = prewarm
@server.rtc_session()
async def entrypoint(ctx: JobContext):
ctx.log_context_fields = {"room": ctx.room.name}
session = AgentSession(
stt=deepgram.STT(),
llm=openai.LLM(),
tts=elevenlabs.TTS(model="eleven_multilingual_v2"),
vad=ctx.proc.userdata["vad"],
preemptive_generation=True,
)
await session.start(agent=TranslatorAgent(), room=ctx.room)
await ctx.connect()
if __name__ == "__main__":
cli.run_app(server)
```