This message was deleted.
# ask-ai
s
This message was deleted.
t
Thanks for reaching out, elish. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To bring both the AssistanceTools and TransferTools functionalities together in the same session, a multi-agent architecture pattern can be really helpful. Think of it as creating a shared space where everything stays connected, and control moves smoothly between agents as needed. Here’s a friendly overview of how you might approach this: • Create a shared
UserData
class to keep track of session-wide information and help manage transitions between agents. • Define each agent (like AssistanceAgent and TransferAgent) with their own specific tools and roles. • Use the
@function_tool
decorator to set up methods that let you switch control between agents or call on their abilities. • Initialize all your agents at the beginning and register them within the shared context so they’re ready to work together. • Kick off the session with one agent (for example, AssistanceAgent) and allow smooth transitions to others (like TransferAgent) depending on what the user needs or the logic you’ve set up. By following this approach, you’ll create a seamless experience that keeps everything connected and flowing naturally. If you’d like, I’m here to help with more details or some example code—just let me know! Sources: main.py | Workflows | LiveKit Docs | Building Multi-Agent Architectures with LiveKit Agents | complex-agents/personal_shopper/personal_shopper.py | Tool definition and use | LiveKit Docs
s
Give me code where you impemeneted both agents
t
Here is an example implementation that integrates both AssistanceTools and TransferTools into a single session using a multi-agent architecture:
Copy code
from dataclasses import dataclass, field
from typing import Optional
from livekit.agents import JobContext, Agent, AgentSession, RunContext
from livekit.agents.llm import function_tool

@dataclass
class UserData:
    """Stores data and agents to be shared across the session"""
    personas: dict[str, Agent] = field(default_factory=dict)
    prev_agent: Optional[Agent] = None
    ctx: Optional[JobContext] = None

RunContext_T = RunContext[UserData]

class BaseAgent(Agent):
    async def on_enter(self) -> None:
        """Handle context preservation when entering agent"""
        userdata: UserData = self.session.userdata

        if userdata.prev_agent:
            chat_ctx = self.chat_ctx.copy()
            items_copy = userdata.prev_agent.chat_ctx.items
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [item for item in items_copy if item.id not in existing_ids]
            chat_ctx.items.extend(items_copy)
            await self.update_chat_ctx(chat_ctx)

        self.session.generate_reply()

    async def _transfer_to_agent(self, name: str, context: RunContext_T) -> Agent:
        """Transfer to another agent while preserving context"""
        userdata = context.userdata
        current_agent = context.session.current_agent
        next_agent = userdata.personas[name]
        userdata.prev_agent = current_agent
        return next_agent

class AssistanceAgent(BaseAgent):
    def __init__(self) -> None:
        super().__init__(
            instructions="You are a helpful assistance agent. You can help with general inquiries and transfer to specialists when needed.",
        )

    @function_tool
    async def transfer_to_specialist(self, context: RunContext_T, specialist_type: str) -> Agent:
        await self.session.say(f"I'll transfer you to our {specialist_type} specialist who can better assist you.")
        return await self._transfer_to_agent(specialist_type, context)

class TransferAgent(BaseAgent):
    def __init__(self) -> None:
        super().__init__(
            instructions="You are a transfer specialist. You handle escalations and can connect customers with human agents.",
        )

    @function_tool
    async def escalate_to_human(self, context: RunContext_T) -> str:
        await self.session.say("I'm connecting you with a human agent. Please hold.")
        return "Transfer initiated to human agent"

# Entry point
async def entrypoint(ctx: JobContext):
    userdata = UserData(ctx=ctx)

    assistance_agent = AssistanceAgent()
    transfer_agent = TransferAgent()

    userdata.personas.update({
        "assistance": assistance_agent,
        "transfer": transfer_agent,
    })

    session = AgentSession[UserData](userdata=userdata)

    await session.start(
        agent=assistance_agent,
        room=ctx.room,
    )
This code demonstrates how to: • Define multiple agents with distinct functionalities (AssistanceAgent and TransferAgent). • Use a shared
UserData
class to manage session-wide state and transitions. • Enable seamless transitions between agents while preserving context. If you have any questions or would like me to walk you through any part of this example, please don’t hesitate to ask! I’m here to help and make sure everything works smoothly for you.
s
How about using
Copy code
session.add_agent(agent_name)
is this correct method?
How about using
Copy code
session.add_agent(agent_name)
is this correct method? is there any mehtod likes that?
t
The method session.add_agent(agent_name) isn’t quite the right way to add multiple agents in LiveKit, but no worries—I’m here to help you through it! LiveKit actually uses an agent handoff pattern, which works like this: • You begin your session with a single agent using
session.start()
. • When you want to switch between agents, you create function tools that return a new agent based on certain conditions. • The new agent is then returned along with a message that triggers the handoff. This method helps keep everything clear and organized between agents. If you’d like, I’d be happy to share an example to show you how to set this up! Just let me know. Sources: livekit-agents/livekit/agents/voice/agent.py | Workflows | LiveKit Docs | Building voice agents | LiveKit Docs
The method session.add_agent(agent_name) isn't the way to add multiple agents in LiveKit, but no worries—I'm here to help you navigate this! LiveKit actually uses an agent handoff pattern. You start your session with one agent and then use function tools to smoothly transition to other agents whenever needed. If you're aiming to manage multiple agents, here’s the best approach: • Begin your session with one agent using
session.start(agent=YourAgent(), room=ctx.room)
. • Within that agent, use function tools to hand off to a new agent as necessary. For example:
Copy code
@function_tool
async def switch_to_transfer_agent(self, context):
    transfer_agent = TransferAgent()
    return transfer_agent, "Switching to transfer agent."
This way, you get seamless transitions between agents while keeping the session context intact. If you’d like, I’m happy to walk you through more examples or clarify anything else—just let me know!