Hi, if I use realtime model, can I do handoffs?
# ask-ai
h
Hi, if I use realtime model, can I do handoffs?
t
Thanks for reaching out, Valentin. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking if handoffs are possible when using a realtime model — yes, they are. Handoffs (transferring control from one agent to another) can be initiated during a tool call with any LLM, including realtime models. Implementation examples: • Node.js: return a handoff via
llm.handoff({ agent: new AnotherAgent(), returns: 'Transferring control' })
. • Python: return a tuple like
AnotherAgent(), "Transferring control"
. The framework records the transition (
AgentHandoff
) and you can preserve conversation history and user state by passing
chat_ctx
or
userdata
during the handoff. Would you like a short Node.js or Python example tailored to your current agent setup? Sources: Agents and handoffs | LiveKit docs
h
what could be the reason a handoff is not happening (second agent does not speak, although we see in the log - handing off to next agent
t
Thanks — you're asking why the logs show "handing off" but the second agent never speaks. Below are the most likely causes and short checks you can run to pinpoint the issue. Key things to check • Are you using a realtime model? If yes, realtime sessions often hold audio/control and can prevent a clean handoff. Realtime models require explicit relinquishing of control or closing the realtime session before the next agent can speak. • Does the second agent have TTS configured? If it has no TTS plugin or its TTS is misconfigured, it will not produce audio. • Is the previous agent still speaking or holding the audio stream? Ongoing speech or an active SpeechHandle can block new audio. Ensure you wait for play-out or call interrupt/stop. • Was the new agent actually made active in the session? Confirm you update the session’s active agent (or return the new agent correctly from the tool) and monitor agent state events. • Are you seeing any errors or state events? Check
agent_state_changed
events and any error logs; logs that say “handing off” may occur before cleanup fails. Quick debugging steps 1. Confirm model type (Realtime vs STT→LLM→TTS pipeline). 2. Verify TTS is set on the second agent and audio output is enabled. 3. After the handoff log, check agent state events to see if the new agent enters `listening`/`speaking`. 4. Ensure the prior speech finished: wait_for_playout() or call session.interrupt()/stop before handing off. 5. Try ending the realtime session and starting the next agent session as a workaround (realtime models often need that). If you want, share: • A minimal snippet of your handoff code (Node or Python) • Which model type you're using (realtime or pipeline) • Any agent state events or error lines after the handoff log I’ll use that to point to the exact fix. Sources: Agents and handoffs | LiveKit docs | Agents v0.x migration guide - Node.js | LiveKit Docs | Agent speech and audio | LiveKit docs | Events and error handling | LiveKit docs | OpenAI Realtime API plugin guide | LiveKit docs
h
on this:
Copy code
import { llm, voice } from '@livekit/agents';
import * as openai from '@livekit/agents-plugin-openai';

import { getTemporalClient } from './temporal.js';

const initialPromptSegments: string[] = [
  'You are a professional debt collection agent named Laura representing eCollect.',
  "Your goal is to explain to the user that they haven't paid their invoice, and try make them pay the full amount or through a debt collection plan",
  'The invoice value is 240 euros, the invoice number is INV-123 and you are 18 days past the due date. The invoice is for a car rental service booked on the 18th of October 2025 in Berlin, Germany',
  `Begin the call with introducing yourself and asking to whom you're speaking with. SPEAK ONLY IN ENGLISH`,
];

const frontDeskAgentPrompt: string[] = [
  'You are calling for an outstanding debt of 220 euros as agent called Laura from ecollect.',
  'Your goal is to get the customers name and then route/handoff them to another agent depending if they want to submit a complaint or pay their invoice',
  `Begin the call with introducing yourself and asking to whom you're speaking with. SPEAK ONLY IN ENGLISH`,
];

const frontDeskTools = {
  'handoff-to-complaint-agent': llm.tool({
    description: 'handoff to another agent',
    parameters: {
      type: 'object',
      properties: {
        name: {
          type: 'string',
          description: 'the name of the customer',
        },
      },
    },
    execute: async ({ name }, { ctx }) => {
      if (name) {
        return llm.handoff({
          agent: new ComplaintAIAgent(),
          returns: 'Transferring to complaint agent',
        });
      }

      return 'Please provide your name.';
    },
  }),
  'handoff-to-pay-invoice-agent': llm.tool({
    description: 'handoff to another agent',
    parameters: {
      type: 'object',
      properties: {
        name: {
          type: 'string',
          description: 'the name of the customer',
        },
      },
    },
    execute: async ({ name }, { ctx }) => {
      // @ts-ignore fix typing
      ctx.userData.name = name;

      // @ts-ignore fix typing
      if (ctx.userData.name) {
        return llm.handoff({
          agent: new PayInvoiceAIAgent(),
          returns: 'Transferring to invoice agent',
        });
      }

      return 'Please provide your name.';
    },
  }),
};

const initialPrompt = initialPromptSegments.join(' ');

type Props = {
  voiceId: string;
  instructions: string;
  currentRoomId: string;
};

// TODO (alex): Create a factory method, create agent from db using factory
export class AIAgent extends voice.Agent {
  constructor({ voiceId, instructions, currentRoomId }: Props) {
    super({
      instructions: instructions ?? initialPrompt,
      allowInterruptions: true,
      // tools: {
      //   'check-weather': llm.tool({
      //     description: 'get the latest weather information in Sofia',
      //     parameters: {},
      //     execute: async () => {
      //       // 1. get workflow id
      //       //  2. send sigal

      //       const client = await getTemporalClient();

      //       const handle = client.workflow.getHandle(`room-${currentRoomId}`);
      //       await handle.signal('fetch-weather', {
      //         text: 'hello world',
      //       });
      //     },
      //   }),
      // },
      stt: 'cartesia',
      llm: new openai.realtime.RealtimeModel({ speed: 0.99, voice: voiceId }),
      tts: 'elevenlabs',
    });
  }
}

export class ComplaintAIAgent extends voice.Agent {
  constructor() {
    super({
      instructions: 'introduce yourself as the complaint agent and understand the customers complaint making them feel understood',
      allowInterruptions: true,
      stt: 'cartesia',
      llm: new openai.realtime.RealtimeModel({ speed: 0.99, voice: 'ballad' }),
      tts: 'elevenlabs',
    });
  }

  async onEnter(): Promise<void> {
    const userData = this.session.userData;
    this.session.generateReply({
      instructions: `Greet ${userData.name} personally and offer your assistance.`,
    });
  }
}

export class PayInvoiceAIAgent extends voice.Agent {
  constructor() {
    super({
      instructions: 'introduce yourself as the payment agent and start collecting the payment details',
      allowInterruptions: true,
      stt: 'cartesia',
      llm: new openai.realtime.RealtimeModel({ speed: 0.99, voice: 'ash' }),
      tts: 'elevenlabs',
    });
  }

  async onEnter(): Promise<void> {
    console.log('we come here');
    const userData = this.session.userData;

    this.session.generateReply({
      instructions: `Greet ${userData.name} personally and offer your assistance.`,
    });
  }
}

export class FrontDeskAIAgent extends voice.Agent {
  constructor({ voiceId, instructions, currentRoomId }: Props) {
    super({
      instructions: frontDeskAgentPrompt.join(' '),
      allowInterruptions: true,
      tools: frontDeskTools,
      stt: 'cartesia',
      llm: new openai.realtime.RealtimeModel({ speed: 0.99, voice: voiceId }),
      tts: 'elevenlabs',
    });
  }
}
I am getting error: "Voice agent userData is not set"
t
Thanks — you're getting "Voice agent userData is not set" because the new agent's session doesn't have an initialized
userData
object when
onEnter()
reads
this.session.userData
. Quick fixes and checks: 1) Initialize shared userData when you create the AgentSession • Create a typed
UserData
interface and pass an empty object to `AgentSession`:
Copy code
interface UserData { name?: string }

const session = new voice.AgentSession<UserData>({
  userData: {}, // ← initialize here
  stt: 'cartesia',
  llm: new openai.realtime.RealtimeModel({ speed: 0.99, voice: 'jane' }),
  tts: 'elevenlabs',
});
2) Ensure tools write into that same
userData
(safe assignment) • In your tool, require name then assign to
ctx.userData
before handing off:
Copy code
execute: async ({ name }, { ctx }) => {
  if (!name) return 'Please provide your name.';
  ctx.userData.name = name;    // persists to session.userData
  return llm.handoff({ agent: new PayInvoiceAIAgent(), returns: 'Transferring...' });
}
3) Defensively read
userData
in the new agent’s onEnter • Avoid crashes if it's missing or empty:
Copy code
async onEnter(): Promise<void> {
  const name = this.session.userData?.name ?? 'there';
  this.session.generateReply({ instructions: `Greet ${name} personally...` });
}
4) Realtime-model handoff caveat (likely reason second agent doesn’t speak) • Realtime models often hold audio/control; even with
llm.handoff()
the realtime session may still be active and block playback. Ensure you: ◦ Confirm the handoff actually changed the active agent via agent state events. ◦ Wait for any current speech to finish (
wait_for_playout()
), or call `session.interrupt()`/stop before handing off. ◦ Verify the new agent has TTS configured (your agents do—good). ◦ Add logs for
agent_state_changed
and any errors in
onEnter()
. 5) Quick debug steps • Add console logs in the tool execute, right after
ctx.userData.name = name
, and in
ComplaintAIAgent.onEnter()
/
PayInvoiceAIAgent.onEnter()
to confirm
this.session.userData
. • After handoff, check agent state events to confirm the new agent enters `listening`/`speaking`. • If using a realtime model and the new agent never speaks, try ending the realtime session and starting the new agent session as a workaround. If you want, paste: • How you create/start the AgentSession (session code), • The exact tool execution log + agent_state_changed events, and I’ll point to the exact line to change. Sources: Agents and handoffs | LiveKit docs | Realtime model plugins | LiveKit Docs