polite-dog-12152
04/17/2026, 4:45 PMtall-airline-16756
04/17/2026, 4:45 PMtall-airline-16756
04/17/2026, 4:46 PMuserdata on AgentSession to store session-specific state.
• Define userdata as a typed structure (a Python dataclass or a TypeScript interface) so it’s easy to read and update.
• Pass userdata when you create the `AgentSession`; access it during the session via session.userdata and inside tools via context.userdata.
• Keep the agent implementation stateless; put mutable session state only in userdata so agents remain scalable and reusable.
If you meant a different agent pattern, tell me which runtime or SDK you’re using (Python/TypeScript, client/server, single-agent vs multi-agent) and I’ll give concrete code samples.
Sources: Agents and handoffs | LiveKit Documentation | Building Multi-Agent Architectures with LiveKit Agents, with interactive elementspolite-dog-12152
04/17/2026, 4:46 PMtall-airline-16756
04/17/2026, 4:46 PMuserdata, and is the memory per-user session or shared across sessions?
If you confirm, I’ll give a concise example and recommended patterns (initialization, read/update, retention/expiry, and when to persist to long-term storage).
, with interactive elementspolite-dog-12152
04/17/2026, 4:46 PMtall-airline-16756
04/17/2026, 4:47 PMAgentSession.userdata.
1) Define a typed userdata dataclass for short-term memory:
from dataclasses import dataclass, field
from typing import List
import time
@dataclass
class ShortTermMemory:
recent_messages: List[str] = field(default_factory=list)
last_updated: float = field(default_factory=lambda: time.time())
ttl_seconds: int = 300 # keep recent memory for 5 minutes
2) Initialize the AgentSession with `userdata`:
session = AgentSession(userdata=ShortTermMemory())
3) Access, update, and enforce TTL inside handlers/tools:
def add_to_memory(session, message: str):
mem: ShortTermMemory = session.userdata
# drop expired memory
if time.time() - mem.last_updated > mem.ttl_seconds:
mem.recent_messages.clear()
# append and trim (keep small window)
mem.recent_messages.append(message)
if len(mem.recent_messages) > 10:
mem.recent_messages.pop(0)
mem.last_updated = time.time()
session.userdata = mem # persist back to session
4) Read memory for decisions:
def get_recent_context(session) -> str:
mem: ShortTermMemory = session.userdata
return " ".join(mem.recent_messages)
Best practices (brief):
• Keep userdata small and focused (recent messages, last intent, short flags).
• Use a TTL and bounded length to avoid unbounded memory growth.
• Treat userdata as the single source of runtime session state; agents remain stateless beyond it.
• Persist to long-term storage only when you need history beyond short-term (e.g., conversation logs).
If you want, I can provide a full handler example wired into your AgentSession lifecycle or adjust TTL/size recommendations for your expected traffic. Which would you prefer?
, with interactive elements