|
| 1 | +import { Conversation } from "@elevenlabs/client"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Example: Starting a conversation with a public ElevenLabs agent |
| 5 | + * |
| 6 | + * This example demonstrates how to initialize and manage a conversation |
| 7 | + * session with an ElevenLabs conversational AI agent using the JavaScript SDK. |
| 8 | + */ |
| 9 | +async function startConversation() { |
| 10 | + // Request microphone access before starting the conversation |
| 11 | + await navigator.mediaDevices.getUserMedia({ audio: true }); |
| 12 | + |
| 13 | + // Start a conversation session with a public agent |
| 14 | + const conversation = await Conversation.startSession({ |
| 15 | + agentId: "<your-agent-id>", |
| 16 | + connectionType: "webrtc", |
| 17 | + |
| 18 | + // Called when the WebSocket connection is established |
| 19 | + onConnect: () => { |
| 20 | + console.log("Connected to the agent"); |
| 21 | + }, |
| 22 | + |
| 23 | + // Called when the connection is closed |
| 24 | + onDisconnect: () => { |
| 25 | + console.log("Disconnected from the agent"); |
| 26 | + }, |
| 27 | + |
| 28 | + // Called when a new message is received (transcriptions or LLM replies) |
| 29 | + onMessage: (message) => { |
| 30 | + console.log("Received message:", message); |
| 31 | + }, |
| 32 | + |
| 33 | + // Called when an error occurs |
| 34 | + onError: (error) => { |
| 35 | + console.error("Conversation error:", error); |
| 36 | + }, |
| 37 | + |
| 38 | + // Called when the connection status changes |
| 39 | + onStatusChange: (status) => { |
| 40 | + console.log("Status changed:", status); |
| 41 | + }, |
| 42 | + |
| 43 | + // Called when the agent switches between speaking and listening |
| 44 | + onModeChange: (mode) => { |
| 45 | + console.log("Mode changed:", mode); |
| 46 | + }, |
| 47 | + }); |
| 48 | + |
| 49 | + return conversation; |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Example: Ending a conversation session |
| 54 | + * |
| 55 | + * Call endSession() to manually terminate the conversation |
| 56 | + * and disconnect from the WebSocket. |
| 57 | + */ |
| 58 | +async function endConversation(conversation) { |
| 59 | + await conversation.endSession(); |
| 60 | + console.log("Conversation ended"); |
| 61 | +} |
| 62 | + |
| 63 | +// Start the conversation when the page loads |
| 64 | +startConversation() |
| 65 | + .then((conversation) => { |
| 66 | + console.log("Conversation started successfully"); |
| 67 | + |
| 68 | + // End the conversation after 5 minutes |
| 69 | + setTimeout(() => { |
| 70 | + endConversation(conversation); |
| 71 | + }, 5 * 60 * 1000); |
| 72 | + }) |
| 73 | + .catch((error) => { |
| 74 | + console.error("Failed to start conversation:", error); |
| 75 | + }); |
0 commit comments