-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvoice-example.ts
More file actions
417 lines (345 loc) · 10.6 KB
/
Copy pathvoice-example.ts
File metadata and controls
417 lines (345 loc) · 10.6 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/**
* Example: Voice-Enabled Agents with TTS and STT
*
* This example demonstrates how to use voice capabilities with AgentSea ADK:
* - Speech-to-Text (STT) with OpenAI Whisper
* - Text-to-Speech (TTS) with OpenAI and ElevenLabs
* - Voice conversations
* - Local TTS/STT providers
*/
import { readFileSync, writeFileSync } from 'fs';
import {
Agent,
AnthropicProvider,
ToolRegistry,
VoiceAgent,
OpenAIWhisperProvider,
OpenAITTSProvider,
ElevenLabsTTSProvider,
LocalWhisperProvider,
PiperTTSProvider,
AgentContext,
} from '@lov3kaizen/agentsea-core';
/**
* Example 1: Basic Voice Agent with OpenAI
*/
async function _basicVoiceAgentExample() {
console.log('\n=== Basic Voice Agent Example ===\n');
// Create base agent
const provider = new AnthropicProvider(process.env.ANTHROPIC_API_KEY);
const toolRegistry = new ToolRegistry();
const agent = new Agent(
{
name: 'voice-assistant',
description: 'A voice-enabled assistant',
model: 'claude-sonnet-4-20250514',
provider: 'anthropic',
systemPrompt:
'You are a helpful voice assistant. Keep responses concise.',
},
provider,
toolRegistry,
);
// Create voice providers
const sttProvider = new OpenAIWhisperProvider(process.env.OPENAI_API_KEY);
const ttsProvider = new OpenAITTSProvider(process.env.OPENAI_API_KEY);
// Create voice agent
const voiceAgent = new VoiceAgent(agent, {
sttProvider,
ttsProvider,
ttsConfig: {
voice: 'alloy',
model: 'tts-1',
},
autoSpeak: true,
});
// Load audio file or use buffer
const audioInput = readFileSync('./path/to/audio.mp3');
// Process voice input
const context: AgentContext = {
conversationId: 'voice-conv-1',
sessionData: {},
history: [],
};
const result = await voiceAgent.processVoice(audioInput, context);
console.log('Transcription:', result.text);
console.log('Response:', result.response.content);
// Save audio response
if (result.audio) {
writeFileSync('./output/response.mp3', result.audio);
console.log('Audio saved to: ./output/response.mp3');
}
}
/**
* Example 2: Text-to-Speech Only
*/
async function _textToSpeechExample() {
console.log('\n=== Text-to-Speech Example ===\n');
// Create base agent
const provider = new AnthropicProvider(process.env.ANTHROPIC_API_KEY);
const toolRegistry = new ToolRegistry();
const agent = new Agent(
{
name: 'tts-assistant',
model: 'claude-sonnet-4-20250514',
provider: 'anthropic',
description: 'TTS assistant',
},
provider,
toolRegistry,
);
// Create TTS provider only (using ElevenLabs for high quality)
const ttsProvider = new ElevenLabsTTSProvider({
apiKey: process.env.ELEVENLABS_API_KEY,
});
// Note: We still need STT provider for VoiceAgent, but we won't use it
const sttProvider = new OpenAIWhisperProvider(process.env.OPENAI_API_KEY);
const voiceAgent = new VoiceAgent(agent, {
sttProvider,
ttsProvider,
ttsConfig: {
voice: 'EXAVITQu4vr4xnSDxMaL', // Bella voice
model: 'eleven_multilingual_v2',
},
});
const context: AgentContext = {
conversationId: 'tts-conv-1',
sessionData: {},
history: [],
};
// Get spoken response
const result = await voiceAgent.speak(
'Tell me a short story about a robot',
context,
);
console.log('Response:', result.text);
// Save audio
writeFileSync('./output/story.mp3', result.audio);
console.log('Audio saved to: ./output/story.mp3');
}
/**
* Example 3: Speech-to-Text Only
*/
async function _speechToTextExample() {
console.log('\n=== Speech-to-Text Example ===\n');
// Create STT provider
const sttProvider = new OpenAIWhisperProvider(process.env.OPENAI_API_KEY);
// Load audio
const audioInput = readFileSync('./path/to/audio.mp3');
// Transcribe with detailed output
const result = await sttProvider.transcribe(audioInput, {
model: 'whisper-1',
language: 'en',
responseFormat: 'verbose_json',
});
console.log('Transcription:', result.text);
console.log('Language:', result.language);
console.log('Duration:', result.duration, 'seconds');
// Show segments with timestamps
if (result.segments) {
console.log('\nSegments:');
result.segments.forEach((segment) => {
console.log(
`[${segment.start.toFixed(2)}s - ${segment.end.toFixed(2)}s]: ${segment.text}`,
);
});
}
// Show word-level timestamps
if (result.words) {
console.log('\nWords:');
result.words.forEach((word) => {
console.log(
`[${word.start.toFixed(2)}s - ${word.end.toFixed(2)}s]: ${word.word}`,
);
});
}
}
/**
* Example 4: Streaming TTS
*/
async function _streamingTTSExample() {
console.log('\n=== Streaming TTS Example ===\n');
const provider = new AnthropicProvider(process.env.ANTHROPIC_API_KEY);
const toolRegistry = new ToolRegistry();
const agent = new Agent(
{
name: 'streaming-assistant',
model: 'claude-sonnet-4-20250514',
provider: 'anthropic',
description: 'Streaming TTS assistant',
},
provider,
toolRegistry,
);
const sttProvider = new OpenAIWhisperProvider(process.env.OPENAI_API_KEY);
const ttsProvider = new OpenAITTSProvider(process.env.OPENAI_API_KEY);
const voiceAgent = new VoiceAgent(agent, {
sttProvider,
ttsProvider,
});
// Stream audio response
const text =
'This is a long text that will be streamed. ' +
'Streaming allows for faster perceived response time. ' +
'The audio starts playing before the entire response is generated.';
console.log('Streaming audio...');
const chunks: Buffer[] = [];
for await (const chunk of voiceAgent.synthesizeStream(text)) {
chunks.push(chunk);
console.log(`Received chunk: ${chunk.length} bytes`);
}
// Combine chunks and save
const fullAudio = Buffer.concat(chunks);
writeFileSync('./output/streamed.mp3', fullAudio);
console.log('Streamed audio saved to: ./output/streamed.mp3');
}
/**
* Example 5: Voice Conversation
*/
async function _voiceConversationExample() {
console.log('\n=== Voice Conversation Example ===\n');
const provider = new AnthropicProvider(process.env.ANTHROPIC_API_KEY);
const toolRegistry = new ToolRegistry();
const agent = new Agent(
{
name: 'conversation-assistant',
model: 'claude-sonnet-4-20250514',
provider: 'anthropic',
systemPrompt:
'You are a friendly conversational assistant. Keep responses natural and concise.',
description: 'Conversation assistant',
},
provider,
toolRegistry,
);
const sttProvider = new OpenAIWhisperProvider(process.env.OPENAI_API_KEY);
const ttsProvider = new OpenAITTSProvider(process.env.OPENAI_API_KEY);
const voiceAgent = new VoiceAgent(agent, {
sttProvider,
ttsProvider,
ttsConfig: {
voice: 'nova', // Female voice
},
});
const context: AgentContext = {
conversationId: 'multi-turn-1',
sessionData: {},
history: [],
};
// Simulate multi-turn conversation
const turns = ['./audio/turn1.mp3', './audio/turn2.mp3', './audio/turn3.mp3'];
for (let i = 0; i < turns.length; i++) {
console.log(`\nTurn ${i + 1}:`);
const audioInput = readFileSync(turns[i]);
const result = await voiceAgent.processVoice(audioInput, context);
console.log('User:', result.text);
console.log('Assistant:', result.response.content);
// Save audio response
if (result.audio) {
writeFileSync(`./output/response-${i + 1}.mp3`, result.audio);
}
}
// Export full conversation
await voiceAgent.exportConversation('./output/conversation');
console.log('\nFull conversation exported to: ./output/conversation');
}
/**
* Example 6: Local Voice Providers
*/
async function _localVoiceExample() {
console.log('\n=== Local Voice Providers Example ===\n');
const provider = new AnthropicProvider(process.env.ANTHROPIC_API_KEY);
const toolRegistry = new ToolRegistry();
const agent = new Agent(
{
name: 'local-voice-assistant',
model: 'claude-sonnet-4-20250514',
provider: 'anthropic',
description: 'Local voice assistant',
},
provider,
toolRegistry,
);
// Use local Whisper for STT
const sttProvider = new LocalWhisperProvider({
whisperPath: '/path/to/whisper',
modelPath: '/path/to/ggml-base.bin',
});
// Use Piper for TTS
const ttsProvider = new PiperTTSProvider({
piperPath: '/path/to/piper',
modelPath: '/path/to/en_US-lessac-medium.onnx',
});
// Check if installed
const whisperInstalled = await sttProvider.isInstalled();
const piperInstalled = await ttsProvider.isInstalled();
if (!whisperInstalled) {
console.log(sttProvider.getInstallInstructions());
return;
}
if (!piperInstalled) {
console.log(ttsProvider.getInstallInstructions());
return;
}
const voiceAgent = new VoiceAgent(agent, {
sttProvider,
ttsProvider,
});
// Use completely locally
const audioInput = readFileSync('./path/to/audio.wav');
const context: AgentContext = {
conversationId: 'local-conv-1',
sessionData: {},
history: [],
};
const result = await voiceAgent.processVoice(audioInput, context);
console.log('User:', result.text);
console.log('Assistant:', result.response.content);
if (result.audio) {
writeFileSync('./output/local-response.wav', result.audio);
}
}
/**
* Example 7: Available Voices
*/
async function listVoicesExample() {
console.log('\n=== Available Voices Example ===\n');
// OpenAI TTS
const openaiTTS = new OpenAITTSProvider(process.env.OPENAI_API_KEY);
const openaiVoices = await openaiTTS.getVoices();
console.log('OpenAI TTS Voices:');
openaiVoices?.forEach((voice) => {
console.log(`- ${voice.name} (${voice.id}): ${voice.gender}`);
});
// ElevenLabs
if (process.env.ELEVENLABS_API_KEY) {
const elevenlabsTTS = new ElevenLabsTTSProvider({
apiKey: process.env.ELEVENLABS_API_KEY,
});
const elevenlabsVoices = await elevenlabsTTS.getVoices();
console.log('\nElevenLabs Voices:');
elevenlabsVoices?.forEach((voice) => {
console.log(`- ${voice.name} (${voice.id}): ${voice.language}`);
});
}
}
// Run examples
async function main() {
console.log('🎙️ AgentSea Voice Examples\n');
try {
// Uncomment the example you want to run
// await basicVoiceAgentExample();
// await textToSpeechExample();
// await speechToTextExample();
// await streamingTTSExample();
// await voiceConversationExample();
// await localVoiceExample();
await listVoicesExample();
} catch (error) {
console.error('Error:', error);
}
}
// Run if executed directly
if (require.main === module) {
void main();
}