gifted-umbrella-88686
12/03/2025, 8:02 PMtall-airline-16756
12/03/2025, 8:02 PMtall-airline-16756
12/03/2025, 8:03 PMRoomInputOptions.participant_kinds to include rtc.ParticipantKind.PARTICIPANT_KIND_AGENT.
• Use agent handoffs or orchestration logic so agents take turns, collaborate, or interject as needed; conversation context can be preserved across handoffs.
• Build coordination logic (external or within agents) to avoid overlapping speech and to control who asks questions and when.
If you want, tell me: 1) Do you need simultaneous audible speech between agents, or coordinated turn-taking? 2) Which SDK/language are you using (JS, Go, etc.) so I can give focused implementation steps.
Sources: Workflows | LiveKit docs | How to Enable Agent-to-Agent Speech Detection in LiveKit | Agents and handoffs | LiveKit docs | LiveKit DevDay | LiveKitgifted-umbrella-88686
12/03/2025, 8:04 PMtall-airline-16756
12/03/2025, 8:05 PMchat_ctx or shared state.
Minimal example (structure to adapt):
# core idea — not a drop-in package; adapt to your project imports and runtime
from livekit.agents import Agent, function_tool, AgentSession, RunContext
class GreeterAgent(Agent):
def __init__(self):
super().__init__(instructions="Greet user and ask what they need help with.")
async def on_enter(self) -> None:
await self.session.generate_reply("Hi — how can I help you today?")
@function_tool()
async def route_to_billing(self, ctx: RunContext):
return BillingAgent(chat_ctx=self.session.chat_ctx), "Routing to billing."
class BillingAgent(Agent):
def __init__(self, chat_ctx=None):
super().__init__(instructions="Handle billing questions.")
if chat_ctx: self.chat_ctx = chat_ctx
async def on_enter(self) -> None:
await self.session.generate_reply("Billing here — can you confirm your account email?")
@function_tool()
async def done(self, ctx: RunContext):
return GreeterAgent(chat_ctx=self.session.chat_ctx), "Returning to general agent."
async def start_session(room, token):
session = AgentSession(
# configure STT, TTS, VAD plugins here so turn detection works
)
await session.start(room=room, agent=GreeterAgent(), token=token)
# AgentSession will handle incoming audio/stt and trigger agent logic/handoffs
Turn-taking flow to implement:
1. User speaks → STT & VAD detect end of utterance.
2. Session forwards text to active agent's LLM.
3. Agent decides to reply or call a function_tool() that returns another agent (handoff).
4. If handoff occurs, new agent's on_enter() runs; session preserves chat_ctx.
5. Wait for next user utterance (VAD/STT) before agents speak again.
Practical tips:
• Enable participant_kinds including PARTICIPANT_KIND_AGENT only if agents need to hear each other.
• Use short agent utterances and rely on STT endpoint detection to avoid overlap.
• Store shared state (userdata or chat_ctx) so any agent has full conversation context after a handoff.
• Test with simulated audio and STT to tune VAD/endpointing thresholds for clean turns.
If you want, I can:
• Provide a fuller runnable example for your specific Python environment/SDK version.
• Show how to wire STT/TTS/VAD plugins and sample AgentSession configuration. Which would you prefer? Sources: Agents and handoffs | LiveKit docs | Agents Framework | livekit/livekit_composite | DeepWiki | Building Multi-Agent Architectures with LiveKit Agentsgifted-umbrella-88686
12/03/2025, 8:10 PMtall-airline-16756
12/03/2025, 8:11 PMRoomInputOptions.participant_kinds to include rtc.ParticipantKind.PARTICIPANT_KIND_AGENT if you want agents to hear each other.
• Use STT + VAD (or STT endpointing) to detect user turn boundaries; only allow agents to speak after a user turn ends.
• Prevent overlapping by adding a lightweight coordination layer (router/orchestrator) or a shared locking mechanism that agents check before speaking.
• Preserve shared context via chat_ctx or shared userdata so every agent can decide based on full history.
Concise Python pattern (coordination via a simple orchestrator/lock)
from asyncio import Lock
from livekit.agents import Agent, AgentSession
# shared orchestrator
class Orchestrator:
def __init__(self):
self.speak_lock = Lock() # only one agent speaks at a time
self.chat_ctx = {}
orchestrator = Orchestrator()
class AutonomousAgent(Agent):
def __init__(self, name):
super().__init__(instructions=f"You are {name}. Decide if you should speak.")
self.name = name
async def consider_and_speak(self):
# called whenever new user utterance arrives (session logic)
should_speak = await self.decide() # custom LLM logic
if not should_speak:
return
# try to acquire speaking lock to avoid overlap
async with orchestrator.speak_lock:
# ensure turn boundary (VAD/STT endpointing) happened before speaking
await self.session.generate_reply(f"{self.name}: <your reply here>", chat_ctx=orchestrator.chat_ctx)
# session setup
async def start(room, token):
session = AgentSession( /* include STT, VAD, TTS plugins */ )
# join all agents into the room (they can be non-active listeners)
agents = [AutonomousAgent(f"Agent{i}") for i in range(4)]
await session.start(room=room, agent=agents[0], token=token) # start with one active entrypoint
# register other agents so they are present and can be invoked by orchestrator
for a in agents[1:]:
session.register_agent(a) # conceptual: ensure they exist in session context
# on each user utterance (STT endpoint event), call each agent.consider_and_speak()
Coordination approaches you can choose
• Central orchestrator (recommended): single service decides which agent may speak next (based on priorities, confidence, user intent).
• Decentralized locks: agents race for a lock (first wins); simpler but needs retry/timeout.
• Priority routing: orchestrator grants turns based on role (e.g., triage > billing).
• Soft-interjections: agents post suggestions to chat_ctx and only speak when orchestrator promotes them.
If you want, I can:
• Provide a runnable example wiring STT/VAD/TTS plugins and the session event hooks for Python.
• Show an orchestrator that selects agents by intent/confidence scores from their LLM outputs. Which would you like?gifted-umbrella-88686
12/03/2025, 8:21 PMtall-airline-16756
12/03/2025, 8:21 PMimport asyncio
from typing import List, Dict, Optional
from dataclasses import dataclass
# Replace these with actual LiveKit agent/session imports
from livekit.agents import Agent, AgentSession, RunContext
@dataclass
class SpeakRequest:
agent: "AutonomousAgent"
score: float # higher = stronger desire to speak
reason: str
class Orchestrator:
def __init__(self):
self.speak_lock = asyncio.Lock() # ensures one agent speaks at a time
self.chat_ctx: Dict = {} # shared conversation context
self.pending: List[SpeakRequest] = [] # pending requests for next turn
async def request_to_speak(self, req: SpeakRequest):
# Called by agents when they decide they might want to speak after user turn
self.pending.append(req)
async def pick_and_grant(self):
# Called once per user turn (after VAD/STT endpointing)
if not self.pending:
return None
# pick highest score (tie-break by earliest request)
self.pending.sort(key=lambda r: r.score, reverse=True)
chosen = self.pending.pop(0)
# clear other pending requests for this turn
self.pending.clear()
return chosen
orchestrator = Orchestrator()
class AutonomousAgent(Agent):
def __init__(self, name: str):
super().__init__(instructions=f"You are {name}. Decide if and when to speak.")
self.name = name
async def decide_after_user_turn(self, user_text: str) -> Optional[SpeakRequest]:
"""
Decide whether to speak. Return SpeakRequest if yes, else None.
Implement LLM logic here to return a confidence score and a short reason/utterance.
"""
# Example heuristic — replace with LLM call evaluating user_text and chat_ctx
# For demonstration, random or rule-based logic:
import random
wants = random.random() > 0.6
if not wants:
return None
score = random.random() # replace with model-produced confidence
reason = f"{self.name} thinks user intent matches its role."
return SpeakRequest(agent=self, score=score, reason=reason)
async def speak(self, text: str):
# Acquire orchestrator lock to avoid overlap, generate reply via session
async with orchestrator.speak_lock:
# Use session.generate_reply or TTS pipeline depending on your setup
await self.session.generate_reply(text, chat_ctx=orchestrator.chat_ctx)
# Session orchestration glue
class SessionManager:
def __init__(self, room: str, token: str, agents: List[AutonomousAgent]):
self.room = room
self.token = token
self.agents = agents
self.session: Optional[AgentSession] = None
async def start(self):
# Configure AgentSession with STT, VAD, TTS plugins so you get user-turn events
self.session = AgentSession(
# plugin configuration: stt, vad, tts, llm providers as needed
)
# Start session with a primary entry agent (others registered/listeners)
await self.session.start(room=self.room, agent=self.agents[0], token=self.token)
# Register additional agents in the session context so they can access session & chat_ctx
for a in self.agents[1:]:
# If your SDK has register API; otherwise attach session to agents manually
a.session = self.session
# Hook into STT/VAD endpoint events — adapt to actual event handlers
self.session.on_user_turn(self._on_user_turn)
async def _on_user_turn(self, user_text: str):
"""
Called when STT + VAD indicate the user finished speaking.
Flow:
1. Ask each agent to decide whether they'd like to speak (in parallel).
2. Collect SpeakRequests and let orchestrator pick winner.
3. Grant speak and call chosen agent.speak(...)
"""
# update shared chat context with latest user_text
orchestrator.chat_ctx.setdefault("messages", []).append({"role": "user", "text": user_text})
# ask agents to decide in parallel
decide_tasks = [a.decide_after_user_turn(user_text) for a in self.agents]
decisions = await asyncio.gather(*decide_tasks)
# register all requests with orchestrator
for d in decisions:
if d:
await orchestrator.request_to_speak(d)
chosen = await orchestrator.pick_and_grant()
if not chosen:
# no agent wishes to speak this turn
return
# build reply text — ideally agent LLM generates reply using chat_ctx
reply_text = f"{chosen.agent.name}: {chosen.reason} (auto-generated reply here)"
# append to shared context so subsequent agents see it
orchestrator.chat_ctx["messages"].append({"role": "agent", "agent": chosen.agent.name, "text": reply_text})
# have chosen agent speak (handles lock)
await chosen.agent.speak(reply_text)
# Example usage
async def run_example():
agents = [AutonomousAgent(f"Agent{i}") for i in range(4)]
mgr = SessionManager(room="room-id", token="join-token", agents=agents)
await mgr.start()
# SessionManager will now react to user turns via `on_user_turn` events
# To run:
# asyncio.run(run_example())
Next steps I can provide:
• A version that shows how to call an actual LLM per agent to produce score and reply_text.
• Wiring examples for specific STT/VAD/TTS plugins and the exact AgentSession event hooks for your LiveKit SDK version.
Which would you like next?