I want to that a tool is executed asynchron, so th...
# ask-ai
w
I want to that a tool is executed asynchron, so that the Agent continues with the conversation and after the tool is finished the agent gets informed about the success / failure
t
Thanks for reaching out, Lukas. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to run a tool asynchronously so the agent can keep the conversation going and later be notified of success/failure. You can do that by starting the work in a background task and returning immediately — then send a follow-up reply when the task completes. Two concise examples: 1) Python (use asyncio.create_task)
Copy code
@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)
Copy code
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 Docs
w
okay i need python. I dont want to generate a new reply but only a message in the chat
t
Got it — you want a Python tool that runs asynchronously, returns no LLM reply, and posts a plain chat message on completion (success/failure). Below is a minimal example you can drop into your agent:
Copy code
import 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 docs
w
and adding it to the chat_ctx?
t
You're asking how to add the background task result to the agent's
chat_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:
Copy code
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 docs
w
i need to reduce the time of tool calls further. For some reason the tool is called and then the llm is triggered again. This takes to much time. How can i optimize this?
t
You're seeing the LLM re-run after your tool call, which adds latency. Focus on stopping that trigger and moving work off the critical path. Key actions: 1. Return None from the tool ◦ If the tool doesn't need an LLM reply, explicitly
return 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