powerful-dog-59275
09/08/2025, 8:14 PMAgentStateChanged goes from speaking -> listening -> thinking -> Executing LLM tool call -> user interrupts/interjects something during the Execution the entire Agent freezes, and is unrecoverable.
execute: async ({ location }, { ctx }) => {
//simulating an api call
await new Promise(resolve => setTimeout(resolve, 5000));
return { weather: 'sunny', temperatureF: 70 };
},tall-airline-16756
09/08/2025, 8:14 PMtall-airline-16756
09/08/2025, 8:15 PM_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.pypowerful-dog-59275
09/08/2025, 8:27 PMtall-airline-16756
09/08/2025, 8:27 PMAbortSignal 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 Docspowerful-dog-59275
09/08/2025, 8:30 PMAbortSignal 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.tall-airline-16756
09/08/2025, 8:30 PMAbortSignal
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
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:
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 Docspowerful-dog-59275
09/08/2025, 8:39 PMtall-airline-16756
09/08/2025, 8:40 PMparallel_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 Docspowerful-dog-59275
09/08/2025, 8:43 PMtall-airline-16756
09/08/2025, 8:43 PMtracableToolExecution 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