-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
445 lines (382 loc) · 16.9 KB
/
Copy pathapp.js
File metadata and controls
445 lines (382 loc) · 16.9 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Configuration - Replace these with your actual values
const BEY_API_KEY = 'sk-XGoSueiPVAfwth2O1ObgFYgyeOFqc8J5w2uEE1DGIco';
const BEY_AVATAR_ID = '694c83e2-8895-4a98-bd16-56332ca3f449'; // Required: specific avatar ID from Beyond Presence dashboard
// You can find avatar IDs by:
// 1. Going to Beyond Presence dashboard -> Avatars section
// 2. Or using the List Avatars API endpoint
// 3. Or check the example: "Nelly" avatar has ID: 694c83e2-8895-4a98-bd16-56332ca3f449
// Debug: Log configuration on load
console.log('=== Configuration Loaded ===');
console.log('BEY_API_KEY:', BEY_API_KEY ? 'SET' : 'NOT SET');
console.log('BEY_AVATAR_ID:', BEY_AVATAR_ID);
console.log('===========================');
// Import Beyond Presence SDK (using CDN or npm)
// For production, you may want to use: npm install @bey-dev/sdk
// For now, we'll use the API directly with fetch
let currentSession = null;
let agentId = null;
// Get DOM elements
const startButton = document.getElementById('start-conversation-button');
const endButton = document.getElementById('end-conversation-button');
const videoContainer = document.getElementById('video-container');
const avatarContainer = document.getElementById('avatar-container');
const statusMessage = document.getElementById('status-message');
// Show status message
function showStatus(message, type = 'info') {
statusMessage.textContent = message;
statusMessage.className = `status-message ${type}`;
statusMessage.classList.remove('hidden');
}
// Hide status message
function hideStatus() {
statusMessage.classList.add('hidden');
}
// List available avatars
async function listAvatars() {
try {
const headers = {
'Content-Type': 'application/json',
'X-API-Key': BEY_API_KEY,
'Authorization': `Bearer ${BEY_API_KEY}`
};
console.log('Fetching available avatars...');
const response = await fetch('https://api.bey.dev/v1/avatars', {
method: 'GET',
headers: headers
});
if (!response.ok) {
const errorText = await response.text();
let errorData;
try {
errorData = JSON.parse(errorText);
} catch (e) {
errorData = { message: errorText };
}
console.error('Error fetching avatars:', {
status: response.status,
statusText: response.statusText,
body: errorData
});
return null;
}
const data = await response.json();
console.log('Available avatars:', data);
// Handle different response formats
let avatars = [];
if (Array.isArray(data)) {
avatars = data;
} else if (data.data && Array.isArray(data.data)) {
avatars = data.data;
} else if (data.avatars && Array.isArray(data.avatars)) {
avatars = data.avatars;
}
// Return the first available avatar ID
if (avatars.length > 0) {
const avatarId = avatars[0].id || avatars[0].avatar_id || avatars[0]._id;
console.log('Using avatar ID:', avatarId);
return avatarId;
}
console.warn('No avatars found in response');
return null;
} catch (error) {
console.error('Error listing avatars:', error);
return null;
}
}
// Create an agent with Beyond Presence API
async function createAgent() {
try {
showStatus('Creating your French tutor agent...', 'info');
// Try different authentication header formats
// Many APIs use X-API-Key, but some use Authorization Bearer
const headers = {
'Content-Type': 'application/json',
'X-API-Key': BEY_API_KEY // Try X-API-Key first (common format)
};
// Also try Authorization Bearer as fallback
headers['Authorization'] = `Bearer ${BEY_API_KEY}`;
// Get avatar_id - it's required
let avatarId = BEY_AVATAR_ID;
console.log('=== Avatar ID Check ===');
console.log('BEY_AVATAR_ID constant:', BEY_AVATAR_ID);
console.log('avatarId variable:', avatarId);
console.log('Type of avatarId:', typeof avatarId);
console.log('Is empty?', !avatarId);
console.log('Is YOUR_AVATAR_ID_HERE?', avatarId === 'YOUR_AVATAR_ID_HERE');
console.log('Trimmed empty?', avatarId && avatarId.trim ? avatarId.trim() === '' : 'N/A');
// Check if avatarId is valid
const isInvalid = !avatarId ||
avatarId === 'YOUR_AVATAR_ID_HERE' ||
(typeof avatarId === 'string' && avatarId.trim() === '');
console.log('Will fetch from API?', isInvalid);
console.log('======================');
if (isInvalid) {
// Try to get a default avatar
console.log('Avatar ID not set, fetching from API...');
showStatus('Getting available avatars...', 'info');
avatarId = await listAvatars();
if (!avatarId) {
// Show more helpful error message
const errorMsg = 'avatar_id is required. Please:\n' +
'1. Set BEY_AVATAR_ID in app.js with an avatar ID from your Beyond Presence dashboard, OR\n' +
'2. Ensure you have avatars available in your account.\n' +
'You can find avatar IDs in the Beyond Presence dashboard or by using the List Avatars API.';
console.error(errorMsg);
throw new Error(errorMsg);
}
showStatus('Found avatar, creating agent...', 'info');
} else {
console.log('Using provided avatar ID:', avatarId);
}
// Final check - make sure we have an avatar ID
if (!avatarId || avatarId.trim() === '') {
throw new Error('avatar_id is required but was not found. Please set BEY_AVATAR_ID in app.js');
}
// Build request body based on API requirements
const requestBody = {
name: 'French Learning Tutor',
avatar_id: avatarId, // Required field
system_prompt: 'You are a friendly and patient French language tutor. Help students learn French through natural conversation. Speak clearly and encourage them. Correct mistakes gently and provide explanations when helpful. Keep conversations engaging and appropriate for the student\'s level.',
language: 'fr',
greeting: 'Bonjour! Je suis votre tuteur de français. Comment puis-je vous aider à apprendre le français aujourd\'hui?',
max_session_length_minutes: 30,
// Only valid capabilities are 'webcam_vision' and 'wakeup_mode'
capabilities: [
{ type: 'webcam_vision' } // Use object format with 'type' field
],
// LLM config must use 'type' not 'provider'
llm: {
type: 'openai'
}
};
console.log('Creating agent with headers:', { ...headers, 'X-API-Key': '***hidden***', 'Authorization': 'Bearer ***hidden***' });
console.log('Request body:', requestBody);
console.log('Avatar ID in request body:', requestBody.avatar_id);
// Final validation before sending
if (!requestBody.avatar_id || requestBody.avatar_id.trim() === '') {
throw new Error('avatar_id is missing in request body. This should not happen - please check the code.');
}
const response = await fetch('https://api.bey.dev/v1/agents', {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text();
let errorData;
try {
errorData = JSON.parse(errorText);
} catch (e) {
errorData = { message: errorText || `HTTP error! status: ${response.status}` };
}
console.error('API Error Response:', {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body: errorData
});
// Show detailed error message - log everything to help debug
console.error('Full error response body:', JSON.stringify(errorData, null, 2));
// Parse error details from the API response
let errorMessage = `HTTP error! status: ${response.status}`;
if (errorData.detail && Array.isArray(errorData.detail)) {
// Format validation errors nicely
const errorMessages = errorData.detail.map(err => {
const field = err.loc ? err.loc.join('.') : 'unknown';
return `${field}: ${err.msg}`;
});
errorMessage = errorMessages.join('; ');
} else if (errorData.message) {
errorMessage = errorData.message;
} else if (errorData.error) {
errorMessage = errorData.error;
} else if (errorData.detail) {
errorMessage = typeof errorData.detail === 'string' ? errorData.detail : JSON.stringify(errorData.detail);
}
// Show the full error in the UI
showStatus(`Error: ${errorMessage}. Check console for details.`, 'error');
throw new Error(errorMessage);
}
const data = await response.json();
return data.id; // Return agent ID
} catch (error) {
console.error('Error creating agent:', error);
showStatus(`Error creating agent: ${error.message}`, 'error');
throw error;
}
}
// Create a session with the agent
async function createSession(agentId) {
try {
showStatus('Starting your practice session...', 'info');
const headers = {
'Content-Type': 'application/json',
'X-API-Key': BEY_API_KEY,
'Authorization': `Bearer ${BEY_API_KEY}`
};
const response = await fetch(`https://api.bey.dev/v1/agents/${agentId}/sessions`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
type: 'realtime'
})
});
if (!response.ok) {
const errorText = await response.text();
let errorData;
try {
errorData = JSON.parse(errorText);
} catch (e) {
errorData = { message: errorText || `HTTP error! status: ${response.status}` };
}
console.error('Session API Error Response:', {
status: response.status,
statusText: response.statusText,
body: errorData
});
console.error('Full error details:', JSON.stringify(errorData, null, 2));
// If 404, maybe we need to use the agent directly without creating a session
if (response.status === 404) {
console.warn('Session endpoint returned 404. Trying to use agent directly...');
// Return null to indicate we should use agent directly
return null;
}
throw new Error(errorData.message || errorData.error || errorData.detail || `HTTP error! status: ${response.status}`);
}
const data = await response.json();
return {
sessionId: data.id,
sessionUrl: data.url,
token: data.token
};
} catch (error) {
console.error('Error creating session:', error);
showStatus(`Error creating session: ${error.message}`, 'error');
throw error;
}
}
// Embed the avatar using iframe (Beyond Presence provides iframe embedding)
function embedAvatar(agentId, sessionData = null) {
try {
// Create iframe for Beyond Presence avatar
// Based on Beyond Presence docs, agents can be embedded directly using bey.chat/{agent_id}
const iframe = document.createElement('iframe');
let iframeUrl;
if (sessionData && sessionData.sessionUrl) {
// If we have a session URL, use it
iframeUrl = sessionData.token
? `${sessionData.sessionUrl}?token=${sessionData.token}`
: sessionData.sessionUrl;
} else {
// Otherwise, use the direct agent embedding format
iframeUrl = `https://bey.chat/${agentId}`;
}
console.log('Embedding avatar with URL:', iframeUrl);
iframe.src = iframeUrl;
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.border = 'none';
iframe.style.borderRadius = '15px 15px 0 0';
iframe.allow = 'camera; microphone; fullscreen; autoplay';
iframe.allowFullscreen = true;
iframe.title = 'French Learning AI Tutor';
avatarContainer.innerHTML = '';
avatarContainer.appendChild(iframe);
return iframe;
} catch (error) {
console.error('Error embedding avatar:', error);
throw error;
}
}
// Alternative: Use Beyond Presence SDK if available
async function startConversationWithSDK() {
try {
// If using npm package: import { Bey } from '@bey-dev/sdk';
// For now, we'll use the API directly
showStatus('Initializing conversation...', 'info');
// Create or get agent
if (!agentId) {
agentId = await createAgent();
}
// Try to create session (optional - some agents work without sessions)
let sessionData = null;
try {
sessionData = await createSession(agentId);
if (sessionData) {
currentSession = {
sessionId: sessionData.sessionId,
sessionUrl: sessionData.sessionUrl,
token: sessionData.token
};
console.log('Session created successfully:', sessionData);
} else {
console.log('No session created, using direct agent embedding');
}
} catch (error) {
console.warn('Could not create session, will use direct agent embedding:', error.message);
// Continue without session - we'll embed the agent directly
}
// Embed avatar - use agent ID directly if no session
embedAvatar(agentId, sessionData);
showStatus('Connected! Your French tutor is ready. Start speaking!', 'success');
setTimeout(() => hideStatus(), 3000);
videoContainer.classList.remove('hidden');
} catch (error) {
console.error('Error starting conversation:', error);
showStatus(`Failed to start practice session: ${error.message}`, 'error');
resetUI();
}
}
// Start the conversation
async function startConversation() {
try {
startButton.disabled = true;
startButton.textContent = 'Connecting...';
await startConversationWithSDK();
} catch (error) {
console.error('Error starting conversation:', error);
showStatus(`Failed to start practice session: ${error.message}`, 'error');
resetUI();
}
}
// End the conversation
async function endConversation() {
try {
if (currentSession && currentSession.sessionId) {
showStatus('Ending session...', 'info');
const headers = {
'X-API-Key': BEY_API_KEY,
'Authorization': `Bearer ${BEY_API_KEY}`
};
// End the session via API
await fetch(`https://api.bey.dev/v1/sessions/${currentSession.sessionId}`, {
method: 'DELETE',
headers: headers
}).catch(err => {
console.warn('Error ending session:', err);
// Continue anyway to reset UI
});
}
currentSession = null;
resetUI();
showStatus('Practice session ended. Great job practicing French!', 'info');
setTimeout(() => hideStatus(), 3000);
} catch (error) {
console.error('Error ending conversation:', error);
resetUI();
}
}
// Reset UI to initial state
function resetUI() {
startButton.disabled = false;
startButton.textContent = 'Start Practicing French';
videoContainer.classList.add('hidden');
avatarContainer.innerHTML = '';
}
// Event listeners
startButton.addEventListener('click', startConversation);
endButton.addEventListener('click', endConversation);
// Check if API key is configured
if (BEY_API_KEY === 'YOUR_API_KEY_HERE') {
showStatus('⚠️ Please configure your Beyond Presence API key in app.js', 'error');
}