I've a frontend app, how can i have multiple agent...
# ask-ai
e
I've a frontend app, how can i have multiple agents in python backend or how frontend can connect to different agent
t
Thanks for reaching out, Aman. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To connect a frontend app to multiple agents in a Python backend, here’s a friendly guide to help you through the process: 1. Backend Setup: Start by implementing your agents in Python using LiveKit's agent framework. It’s helpful to define a lead agent to manage initial interactions, and then have specialized agents take over for specific tasks. Using the
@function_tool
decorator makes agent handoffs smooth and organized. 2. Frontend Connection: You’ll want to create a token generation endpoint in your backend. This endpoint provides the necessary access tokens so your frontend can easily connect to LiveKit rooms. 3. Real-Time Communication: For seamless updates between your backend and frontend, consider using RPC or media streams. This way, your backend agents can send structured updates that keep your frontend content dynamic and responsive. 4. Shared Context: To keep things consistent, maintain shared context or user data across agents. This ensures a smooth experience during agent handoffs without losing any important information. If you’d like, I’m here to provide detailed code examples or walk you through any specific part of this setup. Just let me know how I can assist you best! Sources: Workflows | LiveKit Docs | requirements.txt | Generating tokens | LiveKit docs | complex-agents/note-taking-assistant/README.md | Building Multi-Agent Architectures with LiveKit Agents
e
i would like to do following in agent-starter-python, i have agent.py file for agent, can i create other file for other agents and call them i believe python backend is worker, can we create multiple worker and connect to different one's
t
Absolutely, you can create multiple agent files in the
agent-starter-python
project! Each file can define its own agent class, and you have the flexibility to dynamically call these agents from your main agent logic. For instance, using the
@function_tool
decorator is a great way to switch between agents during a session, which helps keep your code modular and reusable. When it comes to multiple workers, the LiveKit Python backend fully supports creating and running several workers. Each worker can be set up with its own
WorkerOptions
and entrypoint function. You can run these workers in separate processes or containers, making it easier to scale horizontally and manage different tasks or agent types independently. If you'd like, I’d be happy to provide detailed examples on how to set up multiple agent files or configure multiple workers. Just let me know! Sources: templates.yaml | README.md | An open source stack for real-time multimodal AI | Deploying to custom environments | LiveKit Docs | Agent Deployment & Docker Configuration | livekit/livekit_composite | DeepW...
e
yes please share detailed example
t
Here’s a detailed example to help you set up multiple agent files and configure multiple workers in the
agent-starter-python
project. I hope this makes things clearer and easier to follow! 1. Setting Up Multiple Agent Files Imagine you want to create two agents: a
LeadAgent
and a
SpecialistAgent
. You can keep them organized in separate files like this: File Structure:
Copy code
project/
├── agents/
│   ├── lead_agent.py
│   ├── specialist_agent.py
│   └── __init__.py
├── main.py
└── requirements.txt
lead_agent.py:
Copy code
from livekit.agents import Agent

class LeadAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are the lead agent.")

    async def on_enter(self):
        self.session.generate_reply()

    async def delegate_task(self, context):
        from .specialist_agent import SpecialistAgent
        return SpecialistAgent(), "Switching to SpecialistAgent."
specialist_agent.py:
Copy code
from livekit.agents import Agent

class SpecialistAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are the specialist agent.")

    async def on_enter(self):
        self.session.generate_reply()
main.py:
Copy code
from livekit.agents import cli, WorkerOptions
from agents.lead_agent import LeadAgent

async def entrypoint(ctx):
    await ctx.connect()
    session = ctx.create_session(agent=LeadAgent())
    await session.start()

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
With this setup, your
LeadAgent
can easily call on the
SpecialistAgent
whenever needed. Pretty neat, right? 2. Configuring Multiple Workers If you want to run multiple workers, you can define separate entrypoint functions for each one and run them in different processes or containers. Here’s an example:
Copy code
# worker_lead.py
from livekit.agents import cli, WorkerOptions
from agents.lead_agent import LeadAgent

async def entrypoint(ctx):
    await ctx.connect()
    session = ctx.create_session(agent=LeadAgent())
    await session.start()

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Copy code
# worker_specialist.py
from livekit.agents import cli, WorkerOptions
from agents.specialist_agent import SpecialistAgent

async def entrypoint(ctx):
    await ctx.connect()
    session = ctx.create_session(agent=SpecialistAgent())
    await session.start()

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Then, you can run these workers separately like this:
Copy code
python worker_lead.py
python worker_specialist.py
This way, you can scale your workers independently and assign specific tasks to each one, which is super helpful! If you have any questions or want me to walk you through more examples, just let me know. I’m here to help!
e
ok let's assume i ran multiple agents how frontend knows which one to connect?
t
Thanks for reaching out! I want to help clarify how the frontend interacts with agents and workers. The frontend itself doesn’t directly choose which agent or worker to connect to. Instead, the LiveKit server takes care of dispatching jobs and assigns available workers to rooms. Once an agent or worker joins a room, the frontend can recognize them by looking at their participant properties. For instance, the frontend can check a participant’s kind and attributes like this:
Copy code
const agent = room.remoteParticipants.find(
  p => p.kind === Kind.Agent && p.attributes['lk.publish_on_behalf'] === null
);

const avatarWorker = room.remoteParticipants.find(
  p => p.kind === Kind.Agent && p.attributes['lk.publish_on_behalf'] === agent.identity
);
This way, the frontend can tell agents and avatar workers apart. If you’re working with React, the
useVoiceAssistant
hook can make things easier by automatically identifying agents and giving you access to their audio and video tracks. Please feel free to ask if you’d like me to walk you through this further or provide more examples—I’m here to help! Sources: README.md | LiveKit Docs | Deploying to custom environments | LiveKit Docs | Virtual avatar plugins | LiveKit Docs
e
please share example with useVoiceAssistant
t
Here’s a friendly example of how you can use the
useVoiceAssistant
hook in React to identify agents and workers, and manage their media tracks with ease:
Copy code
`import { useVoiceAssistant } from '@livekit/components-react';

function SimpleVoiceAssistant() {
  const {
    agent, // The agent participant (logic-running process)
    state, // Current agent state: 'connecting', 'listening', 'thinking', 'speaking'
    audioTrack, // Audio track from agent or avatar worker
    videoTrack, // Video track from avatar worker (if available)
    agentTranscriptions, // Real-time transcriptions of agent speech
    agentAttributes, // Custom attributes set on the agent
  } = useVoiceAssistant();

  if (!audioTrack) {
    return <p>Connecting to voice assistant...</p>;
  }

  return (
    <div>
      <p>Agent State: {state}</p>
      <audio autoplay="" muted="{false}" ref="{(ref)" ==""> {
          if (ref && audioTrack?.isSubscribed) {
            ref.srcObject = audioTrack?.mediaStream;
          }
        }}
      />
      {videoTrack && (
        <video autoplay="" playsinline="" ref="{(ref)" ==""> {
            if (ref && videoTrack?.isSubscribed) {
              ref.srcObject = videoTrack?.mediaStream;
            }
          }}
        />
      )}
    </div>
  );
}</code></pre><br/><p><b>How It Works:</b></p><ul><li>This hook helps you identify the agent and its avatar worker by looking at participant kind and attributes.</li><li>It smartly picks the right audio and video tracks, giving priority to the avatar worker’s tracks when available.</li><li>You’ll get the agent’s current state (like <code>listening</code> or <code>speaking</code>) along with real-time transcriptions.</li></ul><br/><p>This approach makes building responsive UIs for voice assistants much simpler. If you have any questions or want me to walk you through more examples, just let me know — I’m here to help!</p>`
Sources: Web and mobile frontends | LiveKit Docs | packages/react/src/components/participant/BarVisualizer.tsx | Virtual avatar plugins | LiveKit Docs | frontend/src/components/Assistant.tsx | client/web/src/app/page.tsx