Context: Realtime agent, TypeScript I want to cont...
# ask-ai
h
Context: Realtime agent, TypeScript I want to control when an agent is allowed to speak It should not speak even if the user speaks to it unless I have allowed it to do so
t
Thanks for reaching out, tri.nguyen. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to keep a TypeScript realtime agent from speaking unless you explicitly allow it. You can achieve this by disabling automatic turn detection, blocking the agent's audio output, and only calling the agent's reply/say methods when you allow it. Key steps and a minimal example: 1. Disable automatic responses • Use
turnDetection: '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:
Copy code
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 docs
h
I want the agent to listen to the user's first message If it determines it's from a voicemail, don't respond to it
t
You're asking for the agent to listen to the first user message, detect if it's a voicemail greeting, and suppress any reply if it is. Below is a concise TypeScript approach that follows that flow using a realtime AgentSession and the recommended hook to inspect the first user turn. Key idea: • Let the agent transcribe the first user turn. • In the user-turn-completed handler, classify that utterance (keyword check or LLM) as voicemail or not. • If voicemail, stop the response; otherwise generate the reply. Minimal TypeScript example:
Copy code
import { 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 Docs
h
StopResponse doesn't exist
t
You're right — "StopResponse" isn't in the TypeScript SDK. For TypeScript realtime agents, suppress replies by rejecting the user turn or by disabling/clearing input. Below are the concise, supported options and a minimal example that listens to the first user message, classifies voicemail, and suppresses the agent reply when detected. Options • Use the user-turn completed event and call
ev.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):
Copy code
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