a
.
t
Thanks for reaching out, Aditya. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you out! Could you please share a bit more about your question or the issue you're facing? That way, I can make sure to assist you in the best possible way.
a
Give me a sample code for multi agent system where one agent is head which ask for language preference and based on that it selects from two agents hindi or marathi language .. or if you have any better approach then accordingly.. context must pass properly between agents
t
I'm happy to share a sample implementation for a multi-agent system in LiveKit where one agent acts as a head to ask for language preference and selects between two agents (Hindi or Marathi), making sure the context flows smoothly between them:
Copy code
import logging
from dataclasses import dataclass, field
from enum import Enum
from typing import Annotated, Dict, List, Any, Optional
from datetime import datetime
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.llm import function_tool
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import openai, deepgram, elevenlabs, silero

logger = logging.getLogger("multi-agent-language-system")
logger.setLevel(logging.INFO)

class LanguageChoice(str, Enum):
    HINDI = "Hindi"
    MARATHI = "Marathi"

@dataclass
class UserData:
    ctx: JobContext
    user_language: str = ""
    current_agent_type: str = "router"
    conversation_history: List[Dict[str, Any]] = field(default_factory=list)
    agents: Dict[str, Agent] = field(default_factory=dict)
    prev_agent: Optional[Agent] = None

    def record_interaction(self, role: str, content: str, agent_type: str = None):
        self.conversation_history.append({
            "timestamp": datetime.now().isoformat(),
            "role": role,
            "content": content,
            "agent_type": agent_type or self.current_agent_type,
            "language": self.user_language
        })

    def get_conversation_summary(self, last_n: int = 6) -> str:
        recent_history = self.conversation_history[-last_n:] if self.conversation_history else []
        return "\n".join([
            f"{turn['role']}: {turn['content']}" 
            for turn in recent_history
        ])

class BaseAgent(Agent):
    def __init__(self, job_context: JobContext, instructions: str, agent_type: str) -> None:
        self.job_context = job_context
        self.agent_type = agent_type
        super().__init__(
            instructions=instructions,
            stt=deepgram.STT(model="nova-2-general", language="en"),
            llm=openai.LLM(model="gpt-4o-mini"),
            tts=elevenlabs.TTS(model="eleven_turbo_v2_5", language="en"),
            vad=silero.VAD.load()
        )

class LanguageRouterAgent(BaseAgent):
    def __init__(self, job_context: JobContext) -> None:
        super().__init__(
            job_context=job_context,
            instructions="""You are a language routing agent. Your role is to:
            1. Greet users and ask them to choose between Hindi or Marathi
            2. Wait for their language preference
            3. Route them to the appropriate language specialist
            Be helpful and patient.""",
            agent_type="router"
        )

    async def on_enter(self) -> None:
        userdata: UserData = self.session.userdata
        userdata.current_agent_type = "router"
        userdata.record_interaction("system", "User connected to language router", "router")
        
        await self.session.say(
            "Hello! I can help you in Hindi or Marathi. "
            "Please choose your preferred language - Hindi or Marathi?"
        )

    @function_tool
    async def route_to_language_agent(
        self,
        preference: Annotated[
            LanguageChoice,
            "The user's preferred language: Hindi or Marathi"
        ]
    ) -> Agent:
        userdata: UserData = self.session.userdata
        
        userdata.user_language = preference.value
        userdata.record_interaction("user", f"Selected {preference.value}", "router")
        
        logger.info(f"Routing user to {preference.value} agent")
        
        if preference == LanguageChoice.HINDI:
            agent = HindiAgent(self.job_context)
            userdata.agents["hindi"] = agent
            return agent
        else:
            agent = MarathiAgent(self.job_context)
            userdata.agents["marathi"] = agent
            return agent

class HindiAgent(BaseAgent):
    def __init__(self, job_context: JobContext) -> None:
        super().__init__(
            job_context=job_context,
            instructions="""You are a helpful Hindi assistant. Your role is to:
            1. Welcome users in Hindi
            2. Answer their questions in simple Hindi
            3. Transfer to Marathi agent if requested
            4. Maintain conversation context
            You are polite, helpful and patient.""",
            agent_type="hindi"
        )

    async def on_enter(self) -> None:
        userdata: UserData = self.session.userdata
        userdata.current_agent_type = "hindi"
        userdata.prev_agent = userdata.agents.get("router")
        
        context = userdata.get_conversation_summary()
        context_msg = f"\n\nPrevious conversation: {context}" if context else ""
        
        userdata.record_interaction("system", "Switched to Hindi agent", "hindi")
        
        await self.session.say(
            f"Namaste! I am your Hindi assistant. "
            f"How can I help you?{context_msg}"
        )

    @function_tool
    async def transfer_to_marathi(self) -> Agent:
        userdata: UserData = self.session.userdata
        userdata.record_interaction("system", "Transferring to Marathi agent", "hindi")
        
        await self.session.say("I am transferring you to the Marathi assistant.")
        
        if "marathi" not in userdata.agents:
            userdata.agents["marathi"] = MarathiAgent(self.job_context)
        
        return userdata.agents["marathi"]

class MarathiAgent(BaseAgent):
    def __init__(self, job_context: JobContext) -> None:
        super().__init__(
            job_context=job_context,
            instructions="""You are a helpful Marathi assistant. Your role is to:
            1. Welcome users in Marathi
            2. Answer their questions in simple Marathi
            3. Transfer to Hindi agent if requested
            4. Maintain conversation context
            You are polite, helpful and patient.""",
            agent_type="marathi"
        )

    async def on_enter(self) -> None:
        userdata: UserData = self.session.userdata
        userdata.current_agent_type = "marathi"
        userdata.prev_agent = userdata.agents.get("router") or userdata.agents.get("hindi")
        
        context = userdata.get_conversation_summary()
        context_msg = f"\n\nPrevious conversation: {context}" if context else ""
        
        userdata.record_interaction("system", "Switched to Marathi agent", "marathi")
        
        await self.session.say(
            f"Namaskar! I am your Marathi assistant. "
            f"How can I help you?{context_msg}"
        )

    @function_tool
    async def transfer_to_hindi(self) -> Agent:
        userdata: UserData = self.session.userdata
        userdata.record_interaction("system", "Transferring to Hindi agent", "marathi")
        
        await self.session.say("I am transferring you to the Hindi assistant.")
        
        if "hindi" not in userdata.agents:
            userdata.agents["hindi"] = HindiAgent(self.job_context)
        
        return userdata.agents["hindi"]

async def entrypoint(ctx: JobContext):
    await ctx.connect()
    
    userdata = UserData(ctx=ctx)
    
    session = AgentSession[UserData](
        userdata=userdata,
        vad=silero.VAD.load()
    )
    
    router_agent = LanguageRouterAgent(ctx)
    userdata.agents["router"] = router_agent
    
    await session.start(
        agent=router_agent,
        room=ctx.room
    )
    
    participant = await ctx.wait_for_participant()
    logger.info(f"Participant joined: {participant.identity}")

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
This setup is designed to make the language selection and switching as smooth as possible while keeping the conversation context intact. If you have any questions or need help customizing this further, please feel free to ask—I’m here to help! Sources: context-readmes/USERDATA_GUIDE.md | Building Multi-Agent Architectures with LiveKit Agents