I want to run a task in the background for the age...
# ask-ai
g
I want to run a task in the background for the agent session. I don't want it interrupted by agent handoffs or anything.
t
Thanks for reaching out, Aumesh. 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 background task during an agent session that keeps running across agent handoffs. Good news: start the task at the session level (not tied to any specific agent). Agent handoffs do not close the AgentSession, so a session-scoped task will continue until the session itself ends or you explicitly cancel it. Do you want a short example in Python or Node.js, and does the task need access to session state (like room, participants, or session.closed)? Sources: Agent session | LiveKit docs | Agents and handoffs | LiveKit docs
g
I want an example in python. The background task is an API call
t
You're asking for a Python example that runs an API-call background task inside an
AgentSession
so it persists across agent handoffs. Below is a concise pattern that starts a session-scoped background task (an HTTP API call loop) and keeps it independent of agent lifecycle. It uses
asyncio.create_task()
and checks
session.closed
to stop gracefully.
Copy code
import asyncio
import aiohttp
from livekit_agents import AgentSession, FirstAgent  # adjust imports to your SDK

async def api_poll_task(session: AgentSession, interval: float = 5.0):
    """Runs an API call periodically until the session is closed."""
    try:
        async with aiohttp.ClientSession() as http:
            while not session.closed:
                try:
                    # Example API request
                    async with http.get("https://api.example.com/status") as resp:
                        data = await resp.json()
                        # Do something with data and session (not agent-specific)
                        print("API data:", data)
                except Exception as e:
                    # Handle transient errors without terminating the loop
                    print("API call error:", e)

                await asyncio.sleep(interval)
    except asyncio.CancelledError:
        # Task was explicitly cancelled
        pass
    finally:
        print("Background API task stopped.")

async def start_session_and_task():
    # Create and start the session (example; adjust as needed)
    session = AgentSession(...)
    await session.start(room="my_room", agent=FirstAgent())

    # Start background API task once session is active
    api_task = asyncio.create_task(api_poll_task(session, interval=10.0))

    # Example: run until session closes
    try:
        await session.wait_closed()  # or your session lifecycle handling
    finally:
        # Ensure background task is cleaned up when session ends
        api_task.cancel()
        try:
            await api_task
        except asyncio.CancelledError:
            pass

# Run the entrypoint
if __name__ == "__main__":
    asyncio.run(start_session_and_task())
Would you like this adapted to: • include authentication for the API call, • perform one-off API calls instead of polling, or • access specific session state (participants, room APIs) inside the task?
g
The background task should: 1. do an api call 2. update the session userdata
t
You're asking for a Python example where a background task makes an API call and updates the session
userdata
, and the task must persist across agent handoffs. Below is a concise, ready-to-adapt pattern that does exactly that.
Copy code
import asyncio
from dataclasses import dataclass
import httpx
from livekit.agents import Agent, AgentSession, RunContext  # adjust imports for your SDK

# 1) Define session userdata structure
@dataclass
class SessionUserData:
    api_result: dict | None = None
    last_updated: float = 0.0

# 2) Background task: perform API call and update session.userdata
async def api_background_task(session: AgentSession, interval: float = 10.0):
    async with httpx.AsyncClient(timeout=10.0) as client:
        try:
            while not session.closed:
                try:
                    resp = await client.get("https://api.example.com/endpoint")
                    resp.raise_for_status()
                    result = resp.json()
                    # Update session userdata (persists across handoffs)
                    userdata: SessionUserData = session.userdata
                    userdata.api_result = result
                    userdata.last_updated = asyncio.get_running_loop().time()
                    # Optionally log or generate session-side message
                    print("Updated userdata:", userdata.api_result)
                except Exception as e:
                    # handle transient errors without killing the loop
                    print("API call error:", e)

                await asyncio.sleep(interval)
        except asyncio.CancelledError:
            pass
        finally:
            print("API background task stopped.")

# 3) Agent that starts the background task on session start / agent enter
class MyAgent(Agent):
    async def on_enter(self) -> None:
        # Only start the task once: check if already started via a flag in userdata
        userdata: SessionUserData = self.session.userdata
        if not getattr(userdata, "_api_task_started", False):
            # Mark started so subsequent agents/handoffs don't create duplicates
            userdata._api_task_started = True
            # Launch session-scoped background task
            asyncio.create_task(api_background_task(self.session, interval=10.0))

        await self.session.generate_reply(instructions="Background API monitoring started.")

# 4) Entry point: create session with userdata and start with initial agent
async def entrypoint(ctx: RunContext):
    userdata = SessionUserData()
    session = AgentSession(userdata=userdata, /* other config */)
    await session.start(room=ctx.room, agent=MyAgent())

    # Wait until session ends; ensure background task cleanup on session close
    try:
        await session.wait_closed()
    finally:
        # If you need to explicitly cancel any remaining tasks, do so here
        # (The background task checks `session.closed` and will exit naturally.)
        pass
Key points: • Start the task at the session level (not tied to any single agent). Agent handoffs do not close the session, so the task keeps running. • Store shared state in
session.userdata
so updates persist across handoffs. • Use a startup flag (e.g.,
userdata._api_task_started
) to avoid launching duplicate tasks on subsequent
on_enter
calls. • The task checks
session.closed
and exits gracefully when the session ends. Would you like this adapted to include API auth, structured error retry/backoff, or an example that writes results into the room/chat via
session.generate_reply()
? Sources: Agents and handoffs | LiveKit docs | Tasks and task groups | LiveKit docs | Agent session | LiveKit docs