glamorous-oil-12326
11/25/2025, 8:56 PMtall-airline-16756
11/25/2025, 8:56 PMtall-airline-16756
11/25/2025, 8:56 PMglamorous-oil-12326
11/25/2025, 9:03 PMtall-airline-16756
11/25/2025, 9:03 PMAgentSession 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.
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?glamorous-oil-12326
11/25/2025, 9:04 PMtall-airline-16756
11/25/2025, 9:05 PMuserdata, and the task must persist across agent handoffs. Below is a concise, ready-to-adapt pattern that does exactly that.
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