wonderful-wolf-51568
12/02/2025, 1:28 PMtall-airline-16756
12/02/2025, 1:28 PMtall-airline-16756
12/02/2025, 1:29 PM@function_tool()
async def perform_long_operation(self, context: RunContext, query: str) -> str:
async def _background_work():
try:
result = await _do_long_running_job(query)
await context.session.generate_reply(
instructions=f"The operation completed successfully: {result}"
)
except Exception as e:
await context.session.generate_reply(
instructions=f"The operation failed: {e}"
)
asyncio.create_task(_background_work())
return "The operation has started and will continue in the background."
2) Node.js (use Task.from)
const performLongOperation = llm.tool({
description: 'Perform a long-running operation in the background',
parameters: z.object({ query: z.string() }),
execute: async ({ query }, { ctx }) => {
const backgroundWork = async (controller: AbortController) => {
try {
const result = await doLongRunningJob(query);
ctx.session.generateReply({
instructions: `The operation completed successfully: ${result}`,
});
} catch (error) {
ctx.session.generateReply({
instructions: `The operation failed: ${error.message}`,
});
}
};
Task.from(backgroundWork);
return 'The operation has started and will continue in the background.';
},
});
Key points:
• Return immediately so the agent can continue the conversation.
• Run the actual job in a background task.
• Use session.generate_reply() (Python) or ctx.session.generateReply() (Node) inside the background task to notify success/failure.
• Handle cancellation/abort if you need to stop the background task when the user interrupts.
Would you like a variant that includes progress updates, cancellation handling, or an example using a specific long-running job?
Sources: External data and RAG | LiveKit Docswonderful-wolf-51568
12/02/2025, 1:33 PMtall-airline-16756
12/02/2025, 1:34 PMimport asyncio
from livekit.agents import Agent, function_tool, RunContext
class MyAgent(Agent):
@function_tool()
async def async_task(self, context: RunContext, operation: str):
async def background_task():
try:
# replace with your long-running work
await asyncio.sleep(5)
result = f"✅ {operation} completed successfully."
except Exception as e:
result = f"❌ {operation} failed: {e}"
# send a chat message (no new LLM reply / no TTS)
await context.room.local_participant.send_text(
result,
topic="lk.chat"
)
asyncio.create_task(background_task())
# return None so the agent does not generate a new reply
return None
If you want:
• periodic progress updates in chat, I can show how to send interim messages; or
• cancellation handling (stop the background task on user interrupt), I can add an abort pattern. Which would you like? Sources: Tool definition and use | LiveKit docs | Text and transcriptions | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docswonderful-wolf-51568
12/02/2025, 1:38 PMtall-airline-16756
12/02/2025, 1:39 PMchat_ctx (so it becomes part of conversation history) rather than generating a new reply. Use self.chat_ctx.add_message(...) and then persist with await self.update_chat_ctx(self.chat_ctx) from the background task. Example:
import asyncio
from livekit.agents import Agent, function_tool, ChatMessage
class MyAgent(Agent):
@function_tool()
async def async_task(self, context, operation: str):
async def background_task():
try:
await asyncio.sleep(5)
content = f"✅ {operation} completed successfully."
except Exception as e:
content = f"❌ {operation} failed: {e}"
msg = ChatMessage(role="system", content=content)
# append to in-memory chat context
self.chat_ctx.add_message(msg)
# persist so future turns (and LLM) see it
await self.update_chat_ctx(self.chat_ctx)
asyncio.create_task(background_task())
# return None so no LLM reply / speech is generated
return None
If you want the message to target a different role (e.g., "assistant" or "user"), change role. Do you want the background task to also send a plain chat text to the room frontend (e.g., lk.chat) in addition to updating chat_ctx?
Sources: Agents and handoffs | LiveKit docs | Agent speech and audio | LiveKit docs | Events and error handling | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docswonderful-wolf-51568
12/02/2025, 2:04 PMtall-airline-16756
12/02/2025, 2:05 PMreturn None. Any non-None return is sent to the LLM and causes another inference round.
1. Offload long work to a background task
◦ Use asyncio.create_task(...) for the heavy work and return immediately. Send results later via self.chat_ctx + await self.update_chat_ctx(...) or context.room.local_participant.send_text(...).
1. Avoid unnecessary state updates while the tool runs
◦ Minimize calls to update_chat_ctx() or other persistent updates unless needed; each update can trigger downstream processing.
1. Prevent interruptions/retries during execution
◦ If interruptions cause re-invocations, disable them for the critical section (e.g., run_ctx.disallow_interruptions()).
1. Ensure all I/O is truly asynchronous and concurrent
◦ Use non-blocking async I/O, and batch concurrent calls with asyncio.gather() where possible.
1. Cache idempotent or frequent results
◦ Return quickly by reading cached data when appropriate.
Quick checklist to debug your case:
• Is the tool returning a non-None value? If yes, make it return None.
• Are you doing heavy synchronous/blocking work inside the tool? Make it async or move it to a background task.
• Are you calling update_chat_ctx() or generate_reply() right after the tool? Remove or delay those if not required.
• Are interrupts enabled that could re-trigger the tool? Disable during execution.
If you want, paste the current tool function code and I’ll point out exactly where to change it for immediate gains.
Sources: Tool definition and use | LiveKit docs | External data and RAG | LiveKit Docs | Agents and handoffs | LiveKit docs | examples/frontdesk | livekit/livekit_composite | DeepWiki