jolly-apartment-95291
09/06/2025, 2:09 PMtall-airline-16756
09/06/2025, 2:09 PMtall-airline-16756
09/06/2025, 2:10 PMjolly-apartment-95291
09/06/2025, 2:11 PMtall-airline-16756
09/06/2025, 2:11 PMaudioEnabled: 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 Docsjolly-apartment-95291
09/06/2025, 2:12 PMtall-airline-16756
09/06/2025, 2:12 PMimport { 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:
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:
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:
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:
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!jolly-apartment-95291
09/06/2025, 2:45 PMtall-airline-16756
09/06/2025, 2:46 PM@ctx.room.local_participant.register_rpc_method("toggle_audio")
async def toggle_audio(data):
# Toggle audio settings
return {"audioEnabled": True}
JavaScript Client:
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.pyijolly-apartment-95291
09/06/2025, 2:46 PMtall-airline-16756
09/06/2025, 2:47 PM\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:
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!jolly-apartment-95291
09/06/2025, 2:56 PMtall-airline-16756
09/06/2025, 2:57 PMmode 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!jolly-apartment-95291
09/06/2025, 2:57 PMtall-airline-16756
09/06/2025, 2:57 PMtoggle_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:
// 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:
// 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!jolly-apartment-95291
09/06/2025, 3:57 PM[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;tall-airline-16756
09/06/2025, 3:58 PMregisterTextStreamHandler with the topic 'lk.transcription' like this:
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:
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:
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:
import { setLogLevel, LogLevel } from 'livekit-client';
setLogLevel(LogLevel.debug);
• Also, keep an eye on the connection state to make sure your room is connected:
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