happy-diamond-58115
12/09/2025, 8:09 AMtall-airline-16756
12/09/2025, 8:09 AMtall-airline-16756
12/09/2025, 8:10 AMturnDetection: 'manual' in AgentSession so the agent won't auto-generate replies.
1. Block agent audio output / listening initially
• Call session.input.setAudioEnabled(false) to prevent the agent from sending audio (and to keep it silent).
• Keep a flag like agentAllowed to track permission.
1. Manually trigger replies when allowed
• When you want the agent to speak, set agentAllowed = true, enable audio if needed with session.input.setAudioEnabled(true), then call session.generateReply() or session.say().
Minimal TypeScript example:
const session = new voice.AgentSession({
llm: new openai.realtime.RealtimeModel({ voice: 'alloy' }),
turnDetection: 'manual',
vad: await silero.VAD.load(),
});
await session.start({ agent, room });
session.input.setAudioEnabled(false); // keep agent silent initially
let agentAllowed = false;
// RPC or UI action to allow agent to speak
room.localParticipant.registerRpcMethod('allowAgent', async () => {
agentAllowed = true;
session.input.setAudioEnabled(true);
await session.say('I am now allowed to speak.');
});
// On user stop speaking: only generate a reply if allowed
session.on(voice.AgentSessionEventTypes.UserStoppedSpeaking, () => {
if (agentAllowed) {
session.generateReply({ instructions: 'Respond to the user.' });
}
});
If you want finer control:
• Keep audio enabled but skip calling generateReply() until allowed.
• Use session.say() for short TTS messages you control directly.
• Use an RPC/UI toggle to switch agentAllowed on/off at runtime.
Would you like a version that mutes only TTS output while keeping other agent features active, or help wiring the allow/deny toggle into your UI or signaling flow?
Sources: Turn detection and interruptions | LiveKit Docs | Agent speech and audio | LiveKit docshappy-diamond-58115
12/09/2025, 8:12 AMtall-airline-16756
12/09/2025, 8:12 AMimport { voice } from 'livekit';
import { StopResponse } from 'livekit/agents/voice'; // adjust import as needed
export default defineAgent({
entry: async (ctx) => {
const session = new voice.AgentSession({
llm: new openai.realtime.RealtimeModel({ voice: 'alloy' }),
turnDetection: 'server_vad', // ensure turns fire
vad: await silero.VAD.load(),
});
await session.start({ agent, room: ctx.room });
let seenFirstUserTurn = false;
// run when a user turn completes and transcript is available
session.on(voice.AgentSessionEventTypes.UserStoppedSpeaking, async (turn) => {
// get last user message transcript
const messages = session.history?.messages ?? [];
const lastMsg = messages[messages.length - 1];
if (!lastMsg || lastMsg.role !== 'user') return;
if (!seenFirstUserTurn) {
seenFirstUserTurn = true;
const text = lastMsg.text_content?.() ?? '';
// Simple keyword check
const voicemailPhrases = [
'leave a message',
'after the beep',
'voicemail',
'not available',
'out of office',
];
const looksLikeVoicemail = voicemailPhrases.some(p => text.toLowerCase().includes(p));
// Optional: use LLM to improve accuracy
// const judgment = await session.llm.classify({ prompt: `Is this a voicemail greeting? "${text}"` });
// const looksLikeVoicemail = judgment.is_yes();
if (looksLikeVoicemail) {
// Suppress any reply for this turn
throw new StopResponse(); // prevents generateReply/say
}
}
// If not voicemail (or not first turn) proceed only when allowed
if (shouldRespond()) {
await session.generateReply({ instructions: 'Respond to the user.' });
}
});
function shouldRespond() {
// your existing allow/deny logic, e.g., a flag or RPC-controlled toggle
return ctx.room.metadata?.agentAllowed === 'true';
}
},
});
Notes and options:
• Use keyword matching for a fast, local check; add LLM classification for higher accuracy.
• Ensure turn detection is enabled (server_vad, semantic_vad, or manual + VAD) so the user turn completion event fires.
• Throwing StopResponse() inside the user-turn-completed handler prevents the agent from auto-generating a reply.
• You can hang up or schedule a callback after detecting voicemail if desired.
Would you like a version that uses an LLM-based classifier for the voicemail decision, or help wiring the allow/deny flag into your UI or RPC methods?
Sources: Pipeline nodes and hooks | LiveKit docs | Agents Framework | livekit/livekit_composite | DeepWiki | Agents telephony integration | LiveKit docs | How to detect and handle silence during calls | Turn detection and interruptions | LiveKit Docshappy-diamond-58115
12/09/2025, 8:18 AMtall-airline-16756
12/09/2025, 8:18 AMev.reject() to cancel the reply for that turn.
• Or disable listening / clear the user turn with session.input.setAudioEnabled(false) and session.clearUserTurn() to discard input.
• Combine keyword checks or an LLM classification on the first transcript for robust voicemail detection.
Minimal TypeScript example (first-turn voicemail detection + suppression):
import { voice } from '@livekit/agents';
export default defineAgent({
entry: async (ctx) => {
const session = new voice.AgentSession({
llm: new openai.realtime.RealtimeModel({ voice: 'alloy' }),
turnDetection: 'server_vad',
vad: await silero.VAD.load(),
});
await session.start({ agent, room: ctx.room });
let seenFirst = false;
session.on(voice.AgentSessionEventTypes.UserTurnCompleted, (ev) => {
const newMsg = ev.newMessage;
const text = newMsg?.textContent?.() ?? '';
if (!seenFirst) {
seenFirst = true;
const voicemailPhrases = [
'leave a message', 'after the beep', 'voicemail',
'you have reached', 'not available', 'out of office'
];
const isVoicemail = voicemailPhrases.some(p => text.toLowerCase().includes(p));
if (isVoicemail) {
// Supported TypeScript way to suppress a reply for this turn
ev.reject();
// Optionally disable further listening or hang up:
// session.input.setAudioEnabled(false);
return;
}
}
// Normal reply flow (only if your allow/deny logic permits)
if (shouldRespond()) {
session.generateReply({ instructions: 'Reply to the user.' });
}
});
function shouldRespond() {
// implement your allow/deny logic (flag, RPC toggle, etc.)
return true;
}
},
});
Would you like a version that uses the LLM to classify voicemail (higher accuracy) or help wiring an RPC/UI toggle for the allow/deny flag?
Sources: Turn detection and interruptions | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs