Is it possible to add multiple conversational agen...
# ask-ai
g
Is it possible to add multiple conversational agents to the same session with a human? So it will be like a conference where different agents may ask user questions independently.
t
Thanks for reaching out, Dima. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking whether multiple conversational agents can join the same LiveKit session with a human to create a conference-like interaction. Yes — that is supported. What you can do: • Put multiple agents in the same room using an AgentSession so they share the session and conversation context. • Enable agents to hear each other by setting
RoomInputOptions.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 | LiveKit
g
python. coordinated turn talking. example would be appreciated
t
You're asking for a Python example showing coordinated turn-taking between multiple agents and a human in one LiveKit session. Below is a concise, focused pattern you can adapt. Important pieces: • Use AgentSession to run agents in one room. • Let one agent be active at a time; perform handoffs to switch active agent. • Use VAD/STT endpointing or the session's turn-detection to detect user speech end before agents reply. • Preserve chat context across handoffs by passing
chat_ctx
or shared state. Minimal example (structure to adapt):
Copy code
# 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 Agents
g
so here agent is handing over the conversation to another agent on purpose. is there a way to have, say, 4 agents and 1 human in the room, where each agent may decide whether to interact with human at this moment or not?
t
Yes — you can have 4 agents + 1 human in the same room and let each agent independently decide whether to speak, but you’ll need to design coordination so agents don't overlap or talk over the user. Key points and recommended pattern • Agents can all join the same AgentSession/room and share conversation context. • Set
RoomInputOptions.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)
Copy code
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?
g
Show an orchestrator that selects agents
t
Acknowledging you're asking for a Python orchestrator that selects which agent speaks next in a LiveKit multi-agent room — below is a focused, practical pattern you can adapt. It shows agents deciding whether to speak, an orchestrator scoring those requests, and safe turn-taking using VAD/STT endpointing + a speak lock. Notes: • This is a conceptual, runnable pattern — adapt imports, plugin wiring (STT/TTS/VAD), and LiveKit SDK calls for your environment. • The orchestrator uses agent confidence scores to pick a speaker and preserves shared chat context.
Copy code
import 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?