Using the Nodejs Agent V1, we are running into unr...
# ask-ai
p
Using the Nodejs Agent V1, we are running into unrecoverable agents. If an Agent speaks, and then listens, and then is thinking how to process what the caller said, So
AgentStateChanged
goes from
speaking ->  listening -> thinking -> Executing LLM tool call -> user interrupts/interjects something during the  Execution
the entire Agent freezes, and is unrecoverable.
Copy code
execute: async ({ location }, { ctx }) => {
//simulating an api call            
await new Promise(resolve => setTimeout(resolve, 5000));
            return { weather: 'sunny', temperatureF: 70 };
          },
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.
Hey there! To help you tackle those pesky unrecoverable agent freezes during state transitions and user interruptions in Node.js Agent V1, here are some friendly steps you can try out: • Make sure you’re handling errors properly by using the
_onError()
method in
AgentSession
. This little helper logs errors, gracefully shuts things down, and keeps your agent from freezing up. • When users interrupt, call
session.interrupt()
to stop any ongoing speech and clear out pending tasks. This helps your agent switch states smoothly without getting stuck. • Use the
SpeechHandle
that
say()
or
generateReply()
gives you to keep everything coordinated and avoid stale states. For example, you can interrupt speech explicitly with
session.interrupt()
. • Customize how interruptions behave by tweaking options like
allowInterruptions
and
minInterruptionDuration
. This gives you control over how interruptions are handled. • Keep state transitions on track by using
AgentStateChangedEvent
and the
_updateAgentState()
method. This way, you can easily track and update states like
speaking
,
listening
, and
thinking
. Following these tips should help you avoid freezes and keep everything running smoothly, even when users jump in or tools are executing. If you want a hand setting any of this up, just let me know—I’m here to help! Sources: Agent speech and audio | LiveKit Docs | Agent speech and audio | LiveKit Docs | Turn detection and interruptions | LiveKit Docs | agents/src/voice/agent_activity.ts | livekit-agents/livekit/agents/voice/events.py
p
Nah, im convinved that the Tools are not handeling things properly, if i just take out the tools, the realtime agent has no issues at all with interruptions.
t
It looks like the issue might be related to how the tools handle interruptions. No worries—here are some friendly steps to help you debug and fix this: • Keep an Eye on Tool Execution: Make sure your tools are paying attention to the
AbortSignal
when interruptions happen. Wrapping your tool execution promises with the
waitUntilAborted()
utility can help them cancel smoothly. • Double-Check Task Cancellation: Confirm that
replyAbortController.abort()
and
cancelAndWait()
are being called properly during interruptions. This way, tools won’t get stuck running forever. • Turn on Debug Logging: Using debug-level logs can give you a clear picture of what’s going on during tool execution and interruptions. Watch out for messages like "Aborting all realtime generation tasks due to interruption"—they’re a good sign things are working as expected. • Manage Long-Running Tools: If some tools take a while to finish, try sending intermediate feedback to the user so it doesn’t feel like everything’s frozen. • Check Event Emission: Make sure your tools are firing the
FunctionToolsExecuted
event and updating the chat context properly after they run. • Set Timeouts: Applying suitable timeouts (like
AgentActivity.REPLY_TASK_CANCEL_TIMEOUT
) helps ensure tools respond quickly when interruptions happen. Following these steps should help you pinpoint and fix what’s causing the freezes. If you want a hand with any of this, just let me know—I’m here to help! Sources: Agent speech and audio | LiveKit Docs | Turn detection and interruptions | LiveKit Docs | agents/src/voice/agent_activity.ts | Tool definition and use | LiveKit Docs
p
• how would this even look in code, Keep an Eye on Tool Execution: Make sure your tools are paying attention to the
AbortSignal
when interruptions happen. Wrapping your tool execution promises with the
waitUntilAborted()
utility can help them cancel smoothly. • Double-Check Task Cancellation: Confirm that
replyAbortController.abort()
and
cancelAndWait()
are being called properly during interruptions. This way, tools won’t get stuck running forever.
t
Here’s a friendly guide on how you can implement these suggestions in code to handle interruptions smoothly: 1. Tool Execution with
AbortSignal
Copy code
import { tool } from '@livekit/agents';

const searchWebTool = tool({
  description: 'Search the web for information requested by the user',
  parameters: {
    type: 'object',
    properties: {
      query: { type: 'string', description: 'The search query to look up' },
    },
    required: ['query'],
  },
  execute: async ({ query }, opts) => {
    console.log(`Starting web search for: ${query}`);

    const longTaskPromise = new Promise(resolve => {
      setTimeout(() => {
        resolve(`Results for "${query}": sunny in Tokyo, nice weather!`);
      }, 10000); // Simulate a 10-second task
    });

    const { result, isAborted } = await waitUntilAborted(longTaskPromise, opts.abortSignal);

    if (isAborted) {
      console.log('Web search was interrupted by user speech.');
      return null;
    }

    console.log(`Web search completed: ${result}`);
    return result;
  },
});
2.
waitUntilAborted
Utility
Copy code
async function waitUntilAborted(promise, signal) {
  const abortFut = new Promise((resolve, reject) => {
    const resolveAbort = () => resolve({ result: undefined, isAborted: true });

    signal.addEventListener('abort', resolveAbort);

    promise
      .then(result => resolve({ result, isAborted: false }))
      .catch(reject)
      .finally(() => signal.removeEventListener('abort', resolveAbort));
  });

  return await abortFut;
}
3. Interrupting the Agent You can easily interrupt the agent yourself or let the user do it like this:
Copy code
const handle = session.say("Hello world");
// Later...
handle.interrupt(); // or session.interrupt()
These examples help make sure your tools listen for interruptions and stop gracefully. If anything’s unclear or you want to dive deeper, just let me know—I’m here to help! Sources: agents/src/llm/tool_context.ts | Agent speech and audio | LiveKit Docs | Agent speech and audio | LiveKit Docs | Turn detection and interruptions | LiveKit Docs
p
So are you suggesting that when i spam a bunch of Tool calls that have a promise, that its essentialy borking the system?
t
Hey there! Could you help me understand a bit more about the issues you’re running into when spamming multiple tool calls? For example: • Are you noticing crashes, memory leaks, or maybe some delays? • Which LLM provider and agent setup are you working with? • Are you using
parallel_tool_calls: true
, and if so, how many tool calls are happening at the same time? Knowing these details will really help us get to the bottom of this and find the best solution for you. Sources: Fireworks AI LLM integration guide | LiveKit Docs | DeepSeek LLM integration guide | LiveKit Docs | Perplexity LLM integration guide | LiveKit Docs | Together AI LLM integration guide | LiveKit Docs | Telnyx LLM integration guide | LiveKit Docs
p
we are noticing that if a user spams a bunch of utterances, and it invokes tools, and those tools have promises in them...at some point the agent just completely bombs out
t
Hey there! To help with those agent crashes when multiple user utterances trigger tools with promises, here are some friendly tips to keep things running smoothly: • Proper Error Handling: Make sure your tools are wrapped in error-handling logic so they can catch exceptions and still return valid outputs, even if something goes wrong. LiveKit’s handy
tracableToolExecution
can help you log and manage errors without a fuss. • Abort Long-Running Promises: Use
AbortSignal
to cancel any unnecessary or long-running tool promises if a new user utterance comes in and interrupts the current task. This keeps things responsive! • Limit Tool Steps: Setting a
maxToolSteps
limit in your agent options is a great way to avoid those pesky infinite loops of tool calls. • Graceful Shutdown: The
drain()
method is your friend here—it lets pending tasks finish up nicely before the agent exits, so nothing gets left hanging. • Monitor Events: Keep an eye on events like
function_tools_executed
and
error_event
to catch issues early and handle failures smoothly in your code. • Sanitize Tool Outputs: Double-check that your tool outputs are clean and safe to prevent any malformed data from causing crashes. Following these steps should really help keep your system stable, even when multiple tool calls happen at once. If you want, I’m here to help you set these up or answer any questions you have! Sources: agents/src/voice/generation.ts | Events and error handling | LiveKit Docs