What’s the relationship between returning instruct...
# ask-ai
p
What’s the relationship between returning instructions from a Tool call, and calling generateReply
t
Thanks for reaching out, Scott. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
When a Tool call in LiveKit sends back instructions, it immediately kicks off the
generateReply
function to craft a fresh agent response based on those instructions. If a tool returns something other than
null
, that value gets passed as the
instructions
parameter to an internal method, which then calls
generateReply
. How
generateReply
works depends on the type of LLM you're using: • For real-time LLMs, like Google Realtime API or OpenAI Realtime,
generateReply
sends the instructions straight to the real-time LLM API to create a response on the fly. • For non-realtime LLMs, the instructions go through a few internal steps, mixing them with the agent's base instructions to build a response. This process includes LLM inference, text forwarding, and TTS inference. If a tool returns
null
or nothing at all, the system simply skips the
generateReply
step, letting background tasks finish quietly without any fuss. Sources: Tool definition and use | LiveKit Docs | agents/src/voice/generation.ts | livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime...
p
What if we call generateReply inside of a tool, is there a queue of sorts?
t
When you call
generateReply
inside a tool in LiveKit, it creates a new speech response for the agent. By default, the
toolChoice
is set to
'none'
, which means the LLM won’t immediately jump to another tool unless you’ve set it up to do so. LiveKit uses a speech queue to keep things running smoothly. This queue, managed by the
AgentActivity
class, organizes speech tasks by priority and timestamp, making sure everything happens in the right order. If tasks share the same priority, they’re handled on a first-in, first-out (FIFO) basis. And just so you know, if
generateReply
is called while a previous generation is still in progress, the earlier one gets canceled and replaced by the new request. Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Agents Core Architecture | livekit/livekit_composite | DeepWiki | Tool definition and use | LiveKit Docs | agents/src/voice/agent_activity.ts
p
What if we send off a generateReply in a tool, and then also return instructions from the tool, but need those to execute in the correct order
t
Hey there! Just to make sure everything runs smoothly when
generateReply
is called within a tool and instructions come back too, LiveKit has some handy built-in features: • When you call
generateReply
, the
toolChoice
automatically switches to
'none'
, so no extra tool calls happen while the reply is being generated. • Any instructions you pass to
generateReply
get added right on top of the agent’s base instructions, keeping the context clear and layered properly. • The speech queue, managed by
AgentActivity
, handles tasks by priority and processes items in the order they came in if they share the same priority—this keeps everything running in the right sequence. • If you happen to call
generateReply
multiple times, any earlier pending generations get canceled to avoid confusion, so only the most recent request moves forward. Thanks to these thoughtful touches, both your generated reply and returned instructions happen in the right order without you needing to worry about extra syncing. Sources: README.md | livekit-agents/livekit/agents/voice/agent_activity.py
p
Does the instructions returned from the Tool also get added to the base instructions?
t
Just a quick heads-up: when a Tool in LiveKit sends back instructions, they don’t get added to the agent’s base instructions. Instead, these are treated as tool outputs and sent back to the LLM for the next steps. While these outputs can shape what the agent says next, they won’t change the base instructions themselves. The base instructions are kept separate and stay the same unless you specifically update them using
update_instructions()
. You can also pass temporary instructions on the fly during a reply, but these won’t be merged into the base instructions either. Sources: agents/src/voice/agent.test.ts | Tool definition and use | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | complex-agents/drive-thru/agent_config.py | Agent speech and audio | LiveKit Docs
p
But generateReply does add to the base instructions? So if I keep calling generateReply, the base instructions just keep building up?
t
Just so you know, the
generateReply
function doesn’t permanently change the base instructions. When you call it, it simply mixes the base instructions with any extra ones you provide for that specific response. But don’t worry—the original base instructions stay just as they were. Also, if you call
generateReply
multiple times with different instructions, it won’t keep piling them up. Each call works on its own, combining the base instructions with the new ones only for that particular moment. Sources: examples/src/multi_agent.ts
p
So I’m not sure what the best course of action is, if a Tool is invoked, and during that execution I need to have the Agent say something, and then still return out of the Tool with a set of instructions, what’s the best way to handle this
t
When your Agent needs to use a Tool, say something while it’s working, and then give instructions afterward, here are some friendly tips to keep things smooth: • Give real-time updates: Use
session.say()
inside the tool’s execution so the Agent can chat while it’s busy. For example, the Agent might say, "Checking the weather, please wait a moment..." as the tool does its thing. • Send instructions after finishing: Once the tool’s done, return a string. This will be passed to the LLM, which will then craft a follow-up reply. For example, returning
'The weather in {location} is sunny.'
helps the LLM respond just right. • Skip automatic replies if you want: If you’d prefer the LLM not to reply after the tool runs, just return
None
or call
cancel_tool_reply()
in the
function_tools_executed
event handler to keep things quiet. Here’s a quick example to show how it works:
Copy code
const getWeather = llm.tool({
  description: 'Called when the user asks about the weather.',
  parameters: z.object({
    location: z.string().describe('The location to get the weather for'),
  }),
  execute: async ({ location }, { ctx }) => {
    ctx.session.say('Checking the weather, please wait a moment...');
    // Simulate tool processing delay
    await new Promise(resolve => setTimeout(resolve, 2000));
    return `The weather in ${location} is sunny today.`;
  },
});
This way, the conversation flows naturally — your Agent keeps you in the loop while working and follows up with the right info once it's done. Sources: agents/src/voice/agent_activity.ts | Tool definition and use | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | Tool definition and use | LiveKit Docs
p
I don’t think the Nodejs V1 agent using Realtime session has the ability to use say()
t
Hey there! Just a quick heads-up about the Node.js V1 agent using a Realtime session: it does support
session.say()
, but you’ll need to add a TTS plugin explicitly in your
AgentSession
setup. Without that TTS plugin,
say()
won’t work because it depends on text-to-speech (TTS) to turn text into audio. If you’re working with a realtime model, make sure to include a TTS plugin like
elevenlabs.TTS()
or
cartesia.TTS()
when you set up your session. Here’s a quick example to guide you:
Copy code
const session = new voice.AgentSession({
  llm: new openai.realtime.RealtimeModel(),
  tts: new elevenlabs.TTS(), // this is needed for session.say()
});

await session.start({ agent, room });
session.say("Hello, how can I help you today?");
And if you don’t have a TTS plugin set up, no worries—you can always use
generate_reply()
to get speech going instead. Sources: Agent speech and audio | LiveKit Docs | examples/src/comprehensive_test.ts
p
Is there ever a situation where I won’t want to call waitForPlayout after the generateReply?
t
Hey there! The sources don’t mention any situations where you shouldn’t call
waitForPlayout
after
generateReply
. Usually,
waitForPlayout
is there to make sure the audio finishes playing before moving on, and it helps keep everything in sync with other parts of your system, like remote avatars or chat updates. If you’re dealing with a specific scenario or running into issues—maybe with timing or how it works with other systems—just let me know! I’m happy to help figure out the best approach for you. Sources: agents/src/voice/agent_activity.ts | Bringing AI avatars to voice agents
p
Is there ever a case where you have a Tool call a Tool?
t
Hey there! Just a quick heads-up about LiveKit: a Tool can’t directly call another Tool within the same agent. But no worries! You can have a Tool hand off to a different agent, which can have its own set of tools. This is actually the best way to connect different tools together. For example, if you’re working with Node.js, you can use
llm.handoff
to pass control over to another agent like this: Sources: Workflows | LiveKit Docs | Building Multi-Agent Architectures with LiveKit Agents | Tool definition and use | LiveKit Docs | examples/src/basic_tool_call_agent.ts | Tool definition and use | LiveKit Docs
p
But what if you return instructions from a tool, to tell the agent to call another tool?
t
Hey there! So, in LiveKit, a tool can actually send instructions back to the agent to smoothly trigger another tool or pass control along. Usually, this happens by returning an agent instance or some clear instructions that help the LLM know what to do next. For instance, if you're working with Node.js, you can use
llm.handoff()
to hand over control to a different agent like this: Sources: Tool definition and use | LiveKit Docs | examples/src/comprehensive_test.ts | Tool definition and use | LiveKit Docs | Workflows | LiveKit Docs
p
I noticed that when I call generateReply inside a Tool and then also have the Tool return an instruction, if I interrupt between the generateReply and the Tool instruction response, the whole agent freezes and doesn’t continue.
t
Hey there! The agent freezes in this scenario because the tool execution isn’t handling interruption signals properly, which leaves the agent stuck. When
generateReply
is called inside a tool, it creates a
SpeechHandle
linked to that tool’s execution. If the tool doesn’t keep an eye on interruption signals and respect them, the agent can’t move on to the next task. Here’s how you can avoid that freezing: • Keep an eye on interruptions: Use
run_ctx.speech_handle.wait_if_not_interrupted()
in tools that run for a while. This makes sure they notice if there’s an interruption. If interrupted, the tool should stop what it’s doing and return a response or
None
. • Clean up properly: After an interruption, make sure all related tasks are wrapped up and the
SpeechHandle
is removed from the agent’s background task list. • Use interruption blocks wisely: For important parts of your code, you can use
run_ctx.disallow_interruptions()
to prevent interruptions in the middle of something critical—but don’t forget to turn interruptions back on afterward so things stay responsive. Following these tips helps your tool work smoothly with the agent’s speech lifecycle, avoiding freezes and keeping everything running nicely. Sources: agents/src/voice/generation.ts | examples/voice_agents/long_running_function.py
p
Can you show me what that would look like in a snippet of a tool that does the above using the agent Node V1 agent
t
Here’s a friendly example of a Node.js V1 agent tool that handles
generateReply
, interruptions, and returns instructions:
Copy code
const exampleTool = llm.tool({
  description: 'Example tool that handles generateReply and interruptions.',
  parameters: z.object({
    query: z.string().describe('The query to process'),
  }),
  execute: async ({ query }, { ctx }) => {
    // Let’s start by letting the user know we’re on it
    const speechHandle = await ctx.session.generateReply({
      instructions: "Processing your request, please hold on...",
    });

    // Now, we wait for the speech to finish or handle if the user interrupts
    try {
      await speechHandle.waitIfNotInterrupted();
    } catch (err) {
      if (speechHandle.interrupted) {
        // If the user interrupts, we clean up and let them know
        console.log("User interrupted the agent.");
        return "The process was interrupted by the user.";
      }
      throw err; // If something unexpected happens, we pass it along
    }

    // Simulate a task that takes a bit of time (like an API call)
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // Once done, we send back the result for the user’s query
    return `The result for your query '${query}' is ready.`;
  },
});
Here’s what’s happening: • Speech generation: We use
generateReply
to keep the user in the loop right from the start. • Interruption handling:
waitIfNotInterrupted
makes sure we respect if the user wants to stop things and tidy up properly. • Returning instructions: After finishing the task, the tool sends back a response so the conversation can keep going smoothly. This way, everything flows nicely, interruptions are handled thoughtfully, and the responses feel natural and helpful. Sources: Agent speech and audio | LiveKit Docs | Agent speech and audio | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent_activity.ts
p
What if we just want to turn off interruptions before we do the generateReply and turn it back on, show snippet
t
Here’s a quick example to show you how to temporarily disable interruptions during a
generateReply
call in a Node.js V1 agent:
Copy code
const exampleTool = llm.tool({
  description: 'Example tool that disables interruptions temporarily.',
  parameters: z.object({
    query: z.string().describe('The query to process'),
  }),
  execute: async ({ query }, { ctx }) => {
    // Generate a reply without allowing interruptions
    const speechHandle = await ctx.session.generateReply({
      instructions: "Processing your request, please hold on...",
      allowInterruptions: false, // Disable interruptions for this speech
    });

    // Wait for the speech to complete
    await speechHandle.waitForPlayout();

    // Generate another reply with interruptions allowed
    const nextSpeechHandle = await ctx.session.generateReply({
      instructions: `The result for your query '${query}' is ready.`,
      allowInterruptions: true, // Re-enable interruptions for this speech
    });

    // Wait for the second speech to complete
    await nextSpeechHandle.waitForPlayout();
  },
});
Here’s what’s happening: • Disable interruptions: Using
allowInterruptions: false
makes sure the user can’t interrupt the agent during the first speech. • Re-enable interruptions: Then, with
allowInterruptions: true
, interruptions are allowed again for the second speech. This way, you get precise control over when interruptions are allowed during specific tool actions. Pretty handy, right? Sources: examples/src/comprehensive_test.ts | livekit-agents/livekit/agents/voice/agent_session.py
p
allowInterruptions is not allowed for OAI Realtime, is there another option
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
p
Is there a way to be informed when the Agent does freeze in this sort of scenario if we don’t implement the interrupt stuff