gorgeous-hydrogen-44699
11/28/2025, 7:52 PMtall-airline-16756
11/28/2025, 7:52 PMtall-airline-16756
11/28/2025, 7:52 PM@server.rtc_session() entrypoint which creates its own AgentSession, so multiple sessions run concurrently on the same AgentServer.
Example pattern:
server = AgentServer()
@server.rtc_session()
async def my_agent(ctx: JobContext):
session = AgentSession(
stt="assemblyai/universal-streaming:en",
llm="openai/gpt-4.1-mini",
tts="cartesia/sonic-3:…",
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
)
await session.start(room=ctx.room, agent=Assistant())
Scaling notes:
• Concurrency is handled by processes; no code changes required to support multiple sessions.
• A 4‑core, 8GB machine typically supports ~10–25 concurrent jobs depending on component complexity.
• LiveKit Cloud load balances jobs across agent servers (round‑robin + geographic affinity).
If you’d like, tell me:
• roughly how many concurrent sessions you expect, and
• which heavy components you use (noise cancellation, turn detection, large LLMs),
and I’ll suggest sizing or configuration tips.
Sources: Agent server | LiveKit docs | Job lifecycle | LiveKit docs | Deploying to custom environments | LiveKit Docsgorgeous-hydrogen-44699
11/28/2025, 7:53 PMtall-airline-16756
11/28/2025, 7:53 PMAgent subclasses), or the same code with different configuration/personality data?
If you want, I can then outline the exact pattern to instantiate sessions with different agent names and provide sizing recommendations.gorgeous-hydrogen-44699
11/28/2025, 7:56 PMtall-airline-16756
11/28/2025, 7:56 PMAgentSession per job. Below is a concise pattern and a few practical tips.
1) Pattern (inside your @server.rtc_session() entrypoint)
@server.rtc_session()
async def dynamic_agent(ctx: JobContext):
# read identifier from job/room metadata
metadata = json.loads(ctx.job.metadata) if ctx.job.metadata else {}
agent_id = metadata.get("agent_id")
# fetch config from your DB (async or sync as appropriate)
config = await db.get_agent_config(agent_id)
# build session using config values
session = AgentSession(
stt=config["stt"],
llm=config["llm"],
tts=config["tts"],
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
)
# build agent with name, instructions, and session-specific tools
tools = [create_tool(tcfg) for tcfg in config.get("tools", [])]
agent = Agent(name=config["agent_name"], instructions=config["instructions"], tools=tools)
await session.start(room=ctx.room, agent=agent)
2) How job metadata gets the agent id
• Include an identifier when accepting or routing the job so the entrypoint knows which config to load, e.g.:
await req.accept(metadata=json.dumps({"agent_id":"12345"}))
3) Isolation & concurrency
• Each job runs in its own process and gets its own AgentSession and tools; sessions are isolated.
• No code changes required to support different agent names/configs per session.
4) Practical tips
• Cache shared heavy resources (VAD models, common tool binaries) at module scope to avoid reloading per process if feasible.
• Record which config version a session used (agent_id + config_version) for debugging and replay.
• Provide reasonable limits in DB for large model choices (to prevent accidentally launching extremely heavy LLMs at scale).
If you want, send:
• an example of one stored config row,
• how you pass metadata into jobs,
and I’ll give a tailored snippet and sizing suggestions.
Sources: Job lifecycle | LiveKit docs | Agent session | LiveKit docs | External data and RAG | LiveKit Docs | examples/drive-thru | livekit/livekit_composite | DeepWiki | Agents v0.x migration guide - Python | LiveKit docsgorgeous-hydrogen-44699
11/28/2025, 7:57 PMtall-airline-16756
11/28/2025, 7:58 PMAgentSession and Agent with dynamic STT/TTS/LLM/tools,
• starting isolated sessions on one AgentServer.
Replace mock DB, plugin constructors, and env vars with your real implementations.
# agent_server.py
import asyncio
import json
import logging
from dataclasses import dataclass
from typing import List, Dict, Any
from livekit.agents import AgentServer, JobRequest, JobContext, AgentSession, Agent
from livekit.agents.llm import FunctionTool
# import your plugin adapters, e.g.:
# from livekit.plugins import deepgram, cartesia, openai, silero
# from livekit.plugins.turn_detector.multilingual import MultilingualModel
# ------- Mock DB (replace with real DB calls) -------
@dataclass
class AgentConfig:
agent_id: str
agent_name: str
stt: str
tts: str
llm: str
instructions: str
tools: List[Dict[str, Any]]
config_version: str = "v1"
# Example configs; replace with DB fetch
AGENT_STORE: Dict[str, AgentConfig] = {
"support_agent": AgentConfig(
agent_id="support_agent",
agent_name="Customer Support Bot",
stt="deepgram/nova-2-general",
tts="cartesia/sonic-3:voice-id",
llm="openai/gpt-4.1-mini",
instructions="You are a friendly support agent. Keep replies concise.",
tools=[],
),
"sales_agent": AgentConfig(
agent_id="sales_agent",
agent_name="Sales Assistant",
stt="assemblyai/universal-streaming:en",
tts="elevenlabs/eleven_turbo_v2:daniel",
llm="openai/gpt-4.1",
instructions="You are persuasive and helpful. Promote product benefits.",
tools=[{"name": "check_pricing", "fn": lambda product: f"Price of {product} is $99"}],
),
}
async def fetch_agent_config(agent_id: str) -> AgentConfig:
# replace with async DB call
return AGENT_STORE.get(agent_id)
# ------- Request handler: accept/reject and set per-job metadata -------
async def on_request(req: JobRequest):
metadata = json.loads(req.job.metadata) if req.job.metadata else {}
agent_id = metadata.get("agent_id")
if not agent_id:
await req.reject("Missing 'agent_id' in job metadata")
return
cfg = await fetch_agent_config(agent_id)
if not cfg:
await req.reject(f"Unknown agent_id: {agent_id}")
return
# Accept and set display name, identity, metadata for the job
await req.accept(
name=cfg.agent_name,
identity=f"{agent_id}_agent_{req.job.id}",
metadata=json.dumps({"agent_id": agent_id, "config_version": cfg.config_version}),
attributes={"agent_type": agent_id},
)
# ------- Entrypoint: create per-job AgentSession using DB config -------
async def rtc_entrypoint(ctx: JobContext):
# read job metadata (populated at accept time or dispatch time)
metadata = json.loads(ctx.job.metadata) if ctx.job.metadata else {}
agent_id = metadata.get("agent_id")
if not agent_id:
await ctx.shutdown("No agent_id provided")
return
cfg = await fetch_agent_config(agent_id)
if not cfg:
await ctx.shutdown(f"Invalid agent_id: {agent_id}")
return
logging.info(f"Starting session for agent_id={agent_id}, job={ctx.job.id}")
# Build model/plugin instances according to cfg
# Replace these with your plugin constructors/mapping logic
# stt = deepgram.STT(model=cfg.stt)
# tts = cartesia.TTS(model=cfg.tts)
# llm = openai.LLM(model=cfg.llm)
# vad = silero.VAD.load()
# turn_detector = MultilingualModel()
# For simplicity in this template, we'll use placeholders
stt = cfg.stt
tts = cfg.tts
llm = cfg.llm
vad = "silero_vad"
turn_detector = "multilingual_turn"
# Create function tools dynamically from cfg.tools
tools = []
for t in cfg.tools:
# wrap or map stored definitions into FunctionTool instances
# tools.append(FunctionTool(name=t["name"], fn=t["fn"], ...))
tools.append(t)
# Create a simple Agent subclass per-session that uses instructions and tools
class DynamicAgent(Agent):
def __init__(self, instructions: str, tools_list: List[Any]):
super().__init__()
self.instructions = instructions
self.tools_list = tools_list
async def on_enter(self):
# send an initial greeting using session API
await self.session.generate_reply(instructions=f"Greeting: {self.instructions}")
# Instantiate a new AgentSession using session-specific models
session = AgentSession(
stt=stt,
tts=tts,
llm=llm,
vad=vad,
turn_detection=turn_detector,
)
# attach session userdata for debugging / audit
session.userdata["agent_id"] = cfg.agent_id
session.userdata["config_version"] = cfg.config_version
# start session (isolated process per job)
await session.start(ctx.room, agent=DynamicAgent(instructions=cfg.instructions, tools_list=tools))
# ------- Boot the AgentServer -------
if __name__ == "__main__":
server = AgentServer()
# register entrypoint and request handler
server.rtc_session(on_request=on_request)(rtc_entrypoint)
# start server (CLI helper run_app typically provided by SDK)
# e.g., agents.cli.run_app(server) # uncomment when using the SDK CLI helper
server.set_entrypoint(rtc_entrypoint) # ensure entrypoint is set if not using decorator helper
# run server main loop (replace with your framework start method)
try:
server.start() # replace with actual SDK start/run call
except Exception:
logging.exception("AgentServer failed to start")
Dispatch jobs with metadata including agent_id. Example metadata when accepting/dispatching: {"agent_id":"support_agent", "user_name":"Alice"}
Key notes and small checklist:
• Use job metadata (agent_id) so entrypoint can fetch config from DB per job.
• Each job runs in its own process and will create its own AgentSession and Agent instance — isolation is automatic.
• Map stored strings (STT/TT S/LLM IDs) to concrete plugin constructors in your code.
• Dynamically create FunctionTool wrappers from DB tool entries so tools are session-specific.
• Persist session metadata (agent_id, config_version) to logs or DB for debugging/audit.
• Cache heavy shared resources (if safe) to reduce startup cost per process, or host them as shared service.
If you want, I can:
• convert this to a runnable example with concrete plugin constructors (OpenAI/Deepgram/Cartesia) and environment var setup,
• or produce a Node.js/TypeScript version. Which would you prefer? Sources: Agent Builder | LiveKit docs | Agent dispatch | LiveKit docs | Agent server options | LiveKit docs | Job lifecycle | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs