how do i switch between voice and text mode with j...
# ask-ai
j
how do i switch between voice and text mode with javascript react sdk?
t
Thanks for reaching out, Tyler. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you help me understand a bit better what you mean by switching between voice and text mode? Are you talking about turning the audio and text chat features on and off, or is it something else?
j
i am using the JS raw connection on the front end. i want to start the session with text chat. then have the abiility to switch to audio mode and carry on the covnersation and switch back to the text in the same session
t
Hey there! If you want to switch between text and audio modes in the same session using the LiveKit JavaScript SDK, here’s a simple way to do it: 1. Start the session in text mode: Just initialize the session with audio turned off by setting
audioEnabled: false
in your input and output options. 2. Send and receive text messages: Use
sendText()
to send messages on the
lk.chat
topic, and make sure to register a text stream handler so you can get responses or transcriptions. 3. Toggle audio mode: You can set up a Remote Procedure Call (RPC) to easily turn audio input and output on or off. For example, create an RPC method called
toggle_audio
to switch between modes. 4. Switch back to text mode: Just use the same RPC to turn audio off again and keep chatting via text. This way, you can smoothly switch between text and audio without leaving the session. If you’d like, I’m happy to share more details or some code examples—just let me know! Sources: Docs::Agents | examples/voice_agents/toggle_io.py | Text and transcriptions | LiveKit Docs | Text and transcriptions | LiveKit Docs
j
yes share me some code example
t
Hey there! I’ve put together some code examples to help you switch smoothly between text and audio modes within the same session. Let’s dive in: 1. Initialize the Session in Text Mode
Copy code
import { voice } from '@livekit/agents';

const session = new voice.AgentSession({
  vad: livekitVAD,  // Your VAD model
  stt: sttModel,    // Your STT model
  llm: llmModel,    // Your LLM model
  tts: ttsModel,    // Your TTS model
  inputOptions: {
    audioEnabled: false, // Starting off with audio disabled
  },
  outputOptions: {
    audioEnabled: false, // No audio output for now
    transcriptionEnabled: true, // Text responses enabled
  },
});
2. Send and Receive Text Messages Here’s how you can send a text message to the agent:
Copy code
const text = 'Hello, how are you?';
await room.localParticipant.sendText(text, { topic: 'lk.chat' });
And to receive text responses or transcriptions, just set up this handler:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader) => {
  const message = await reader.readAll();
  if (reader.info.attributes['lk.transcribed_track_id']) {
    console.log('Transcription:', message);
  } else {
    console.log('Text response:', message);
  }
});
3. Toggle Between Text and Audio Modes Want to switch audio input/output on or off? Here’s an RPC method you can use:
Copy code
ctx.room.localParticipant.registerRpcMethod('toggle_audio', async (data) => {
  const enable = !session.input.audioEnabled;

  session.input.setAudioEnabled(enable);
  session.output.setAudioEnabled(enable);

  return { audioEnabled: enable };
});
Then, just call this from your client to flip the mode:
Copy code
await room.localParticipant.rpc('toggle_audio');
4. Example Workflow 1. Start in text mode – your agent replies with text. 2. Switch to audio mode – call
rpc('toggle_audio')
to turn audio input/output on. 3. Switch back to text mode – call
rpc('toggle_audio')
again to turn audio off. If anything’s unclear or you want more examples, just let me know—I’m here to help!
j
so do i ned to implment this in python for RPC? also how does CTRL+B work in the agent mode?
t
Hey there! Let me help clear things up for you: 1. Do you need to implement RPC in Python for LiveKit JavaScript SDK? Good news—you don’t have to build RPC from scratch! LiveKit already has built-in support for RPC (Remote Procedure Calls) across platforms. You can easily register RPC methods in Python or JavaScript and call them back and forth without a hitch. Here’s a quick example: Python Agent:
Copy code
@ctx.room.local_participant.register_rpc_method("toggle_audio")
async def toggle_audio(data):
    # Toggle audio settings
    return {"audioEnabled": True}
JavaScript Client:
Copy code
await room.localParticipant.rpc('toggle_audio');
This makes communication between your frontend and backend super smooth—no extra setup needed. 2. How does CTRL+B work in agent mode? CTRL+B is a handy keyboard shortcut in the LiveKit Agents CLI that lets you switch between Text Input Mode and Audio Input Mode. When you hit it: • You toggle between Audio Mode and Text Mode. • The microphone and speaker streams turn on or off accordingly. • It’s great for debugging or just switching up how you interact while developing. If you want me to walk you through anything else or need more examples, just say the word—I’m here to help! Sources: README.md | complex-agents/drive-thru/rpc_handlers.py | Remote method calls (RPC) | LiveKit Docs | examples/voice_agents/toggle_io.py | livekit-rtc/livekit/rtc/_proto/rpc_pb2.pyi
j
so what happens on the backend for CTRL+B to work? i basically hve to do the same thing in RPC call
t
Hey there! When you press CTRL+B in the LiveKit Agents CLI, the backend smoothly switches between Text Input Mode and Audio Input Mode by adjusting the agent's input and output settings. Here's a quick rundown of what happens: • The agent picks up the CTRL+B keypress (ASCII code
\x02
). • It flips an internal flag (like
_cli_mode
) to toggle between text and audio modes. • Audio Input Mode: Turns on the microphone input and handles audio streams. • Text Input Mode: Turns off the microphone and processes text messages instead. • All these updates happen dynamically in the agent's input/output setup. If you want to mimic this behavior in an RPC call, you can create a method that toggles the input/output settings on the fly. Here's an example:
Copy code
ctx.room.localParticipant.registerRpcMethod('toggle_audio_text', async (data) => {\n  const enableAudio = !session.input.audioEnabled;\n\n  session.input.setAudioEnabled(enableAudio);\n  session.output.setAudioEnabled(enableAudio);\n\n  return { mode: enableAudio ? 'Audio' : 'Text' };\n});
This way, you can switch modes programmatically just like pressing CTRL+B in the CLI. If you want me to walk you through it or have any questions, just let me know—I'm here to help!
j
is this correct? on the python side? @ctx.room.local_participant.register_rpc_method("toggle_mode") async def toggle_mode(data: dict): """Toggle between text and audio modes""" try: mode = data.get("mode", "toggle") if mode == "text": # Disable audio, enable text only session.input.set_audio_enabled(False) session.output.set_audio_enabled(False) logger.info("Switched to TEXT mode") return {"mode": "text", "success": True} elif mode == "audio": # Enable audio session.input.set_audio_enabled(True) session.output.set_audio_enabled(True) logger.info("Switched to AUDIO mode") return {"mode": "audio", "success": True} else: # Toggle current state current_audio = session.input.audio_enabled new_state = not current_audio session.input.set_audio_enabled(new_state) session.output.set_audio_enabled(new_state) mode_name = "audio" if new_state else "text" logger.info(f"Toggled to {mode_name.upper()} mode") return {"mode": mode_name, "success": True} except Exception as e: logger.error(f"Error toggling mode: {e}") return {"error": str(e), "success": False}
t
Hey there! Your Python implementation for toggling between text and audio modes looks spot on and does exactly what we’d expect. Here’s a quick rundown of what your code is doing: • Explicit Mode Switching: It lets you switch directly to "text" or "audio" modes by checking the
mode
parameter and turning audio on or off accordingly. • Toggle Functionality: When the mode is set to "toggle," it smartly flips the current state (audio or text) by toggling the
audio_enabled
flag. • Error Handling: The
try-except
block is there to catch any hiccups during toggling, logging them and including the info in the response. • Logging: Using
logger.info
and
logger.error
gives you clear messages that help with debugging and keeping an eye on things. Just a couple of friendly tips to make it even better: • Double-check that
session
is properly set up and accessible where you’re using it. • Make sure to validate the
data
input so it has the structure you expect before diving in. Other than that, you’ve done a great job! If you want to chat more or need a hand with anything else, just let me know!
j
so what does the JS side would look like?
t
Here’s a friendly walkthrough of how the JavaScript side can chat with your Python implementation of the
toggle_mode
RPC method: 1. Perform an RPC Call to Toggle Modes To switch modes, you can use the
performRpc
method to call the
toggle_mode
method on your Python backend like this:
Copy code
// Example: Toggle between text and audio modes\nconst toggleMode = async (mode) => {\n  try {\n    const response = await room.localParticipant.rpc({\n      method: 'toggle_mode',\n      payload: JSON.stringify({ mode }), // Pass 'text', 'audio', or 'toggle'\n    });\n\n    const result = JSON.parse(response.payload);\n    if (result.success) {\n      console.log(`Successfully switched to ${result.mode.toUpperCase()} mode`);\n    } else {\n      console.error('Failed to toggle mode:', result.error);\n    }\n  } catch (error) {\n    console.error('RPC call failed:', error);\n  }\n};
2. Example Usage Whenever your user wants to switch modes, just call the
toggleMode
function like this:
Copy code
// Switch to text mode\ntoggleMode('text');\n\n// Switch to audio mode\ntoggleMode('audio');\n\n// Toggle the current mode\ntoggleMode('toggle');
3. Handle Responses The Python backend will send back a response letting you know if the switch worked or not. Make sure your JavaScript handles this so you can give your users clear feedback. If anything’s unclear or you want me to walk through more examples, just let me know—I’m here to help!
j
is this correct for the frontend SDK to get messages? we are not getting any messages at all on the frontend // Minimal LiveKit chat integration - no React, just native SDK import { Room, RoomEvent } from 'livekit-client'; console.log('LiveKit SDK loaded:', { Room, RoomEvent }); class LiveKitChat { constructor() { this.room = new Room(); this.isConnected = false; } async connect(token, url) { console.log('Connecting to LiveKit...', { url, token: token.substring(0, 50) + '...' }); try { // Set up event listeners BEFORE connecting this.setupEventListeners(); // Connect to the room console.log('Calling room.connect...'); await this.room.connect(url, token); this.isConnected = true; console.log('✅ Connected to LiveKit room:', this.room.name); console.log('Room SID:', this.room.sid); console.log('Local participant:', this.room.localParticipant?.identity); console.log('Local participant SID:', this.room.localParticipant?.sid); console.log('Remote participants:', Array.from(this.room.remoteParticipants.keys())); // Check for agent every 2 seconds for debugging let checkCount = 0; const checkInterval = setInterval(() => { checkCount++; const remotes = Array.from(this.room.remoteParticipants.values()); console.log(
[Check ${checkCount}] Remote participants:
, remotes.map(p => p.identity)); if (remotes.some(p => p.identity.includes('agent')) || checkCount > 10) { clearInterval(checkInterval); } }, 2000); return true; } catch (error) { console.error('❌ Failed to connect to LiveKit:', error); console.error('Error details:', error.message, error.stack); return false; } } setupEventListeners() { // Check if agent is already connected const existingAgent = Array.from(this.room.remoteParticipants.values()) .find(p => p.identity.includes('agent')); if (existingAgent) { console.log('🤖 Agent already connected:', existingAgent.identity); console.log('Agent starts in TEXT mode by default - no switch needed'); } // Listen for participants joining this.room.on(RoomEvent.ParticipantConnected, (participant) => { console.log('👤 Participant connected:', participant.identity); if (participant.identity.includes('agent')) { console.log('🤖 Agent detected - already in TEXT mode by default'); } }); // Listen for data messages (this is how we receive text) this.room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => { console.log('📨 Data received:', { from: participant?.identity, topic: topic, kind: kind, payload: payload }); // Try to decode as text try { if (payload instanceof Uint8Array) { const text = new TextDecoder().decode(payload); console.log('📝 Decoded text:', text); // Try to parse as JSON try { const json = JSON.parse(text); console.log('📦 Parsed JSON:', json); } catch (e) { // Not JSON, just text } } } catch (e) { console.log('Could not decode payload:', e); } }); // Listen for RPC responses this.room.localParticipant.on('rpcResponseReceived', (payload) => { console.log('🔄 RPC Response:', payload); }); // Register handler for transcriptions (this is how agent sends text responses) this.room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => { console.log('📝 Transcription stream from:', participantInfo.identity); try { const message = await reader.readAll(); // Check if this is a transcription (has audio track ID) or direct text message if (reader.info.attributes && reader.info.attributes['lk.transcribed_track_id']) { console.log(
:studio_microphone: Transcription from ${participantInfo.identity}: ${message}
); } else { console.log('💬 AGENT TEXT RESPONSE:', message); console.log('================================='); console.log(message); console.log('================================='); } } catch (e) { console.error('Error reading transcription stream:', e); } }); // Also register for chat topic in case agent uses that this.room.registerTextStreamHandler('lk.chat', async (reader, participant) => { console.log('📝 Chat stream from:', participant.identity); try { const message = await reader.readAll(); console.log('💬 CHAT MESSAGE:', message); } catch (e) { console.error('Error reading chat stream:', e); } }); // Also listen for the chat topic specifically this.room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => { if (topic === 'lk.chat') { console.log('💬 CHAT MESSAGE from', participant?.identity, ':', payload); } }); } async switchToTextMode() { // Find the agent participant const agentParticipant = Array.from(this.room.remoteParticipants.values()) .find(p => p.identity.includes('agent')); if (!agentParticipant) { console.log('⚠️ Agent not found, cannot switch to text mode'); return; } console.log('🤖 Found agent:', agentParticipant.identity); try { // Send RPC to switch to text mode const response = await this.room.localParticipant.performRpc({ destinationIdentity: agentParticipant.identity, method: 'toggle_mode', payload: JSON.stringify({ mode: 'text' }) }); console.log('✅ RPC Success - Switched to text mode:', response); } catch (error) { console.error('❌ RPC Failed:', error); // Try alternative: send control message via data channel try { const encoder = new TextEncoder(); const message = JSON.stringify({ type: 'control', command: 'text_mode' }); await this.room.localParticipant.publishData( encoder.encode(message), { reliable: true, topic: 'control' } ); console.log('📤 Sent control message for text mode'); } catch (e) { console.error('❌ Control message failed:', e); } } } async sendMessage(text) { if (!this.isConnected) { console.error('Not connected to LiveKit'); return false; } console.log('📤 Sending message:', text); try { // Method 1: Send as text stream (new LiveKit chat API) const info = await this.room.localParticipant.sendText(text, { topic: 'lk.chat', reliable: true }); console.log('✅ Message sent via sendText:', info); return true; } catch (error) { console.error('❌ sendText failed, trying publishData:', error); // Method 2: Send as data packet (legacy) try { const encoder = new TextEncoder(); const chatMessage = { id: crypto.randomUUID(), timestamp: Date.now(), message: text }; await this.room.localParticipant.publishData( encoder.encode(JSON.stringify(chatMessage)), { reliable: true, topic: 'lk.chat' } ); console.log('✅ Message sent via publishData'); return true; } catch (e) { console.error('❌ publishData also failed:', e); return false; } } } disconnect() { if (this.room) { this.room.disconnect(); console.log('Disconnected from LiveKit'); } } } // Export for use in Phoenix LiveView window.LiveKitChat = LiveKitChat;
t
Your frontend code for receiving messages looks mostly on point! Just a few things to double-check and some tips to help it run even smoother: 1. Make Sure Your Event Listeners Are Set Up Right: • To catch transcriptions, use
registerTextStreamHandler
with the topic
'lk.transcription'
like this:
Copy code
this.room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  console.log(`Transcription from ${participantInfo.identity}: ${message}`);
});
• For regular chat messages, listen for
RoomEvent.DataReceived
and check the topic:
Copy code
this.room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => {
  if (topic === 'lk.chat') {
    console.log('Chat message from', participant?.identity, ':', payload);
  }
});
2. Double-Check That Your Backend or Agent Is Publishing: • Make sure the agent or backend is connected to the same room and sending messages on the right topic (like
'lk.chat'
or
'lk.transcription'
). • For example, the agent can send messages with
sendText()
like this:
Copy code
await room.localParticipant.sendText('Hello!', { topic: 'lk.chat' });
3. A Few Debugging Tips: • Turn on detailed logging to see what's happening behind the scenes:
Copy code
import { setLogLevel, LogLevel } from 'livekit-client';
setLogLevel(LogLevel.debug);
• Also, keep an eye on the connection state to make sure your room is connected:
Copy code
console.log('Room connection state:', this.room.state);
4. Watch Out for These Common Gotchas: • Check that your SDK versions match up nicely (for example,
livekit-client@2.15.2
). • Make sure data channels are open and not throwing any errors. If you want, I’m here to help with any other questions or if you want me to walk through some specific debugging steps with you! Sources: Text and transcriptions | LiveKit Docs | Transcription Applications | livekit/livekit_composite | DeepWiki | Community & Support | livekit/livekit_composite | DeepWiki | Community & Support | livekit/livekit_composite | DeepWiki | packages/core/src/components/chat.ts