Hi, I’d like to understand how data is transferred...
# ask-ai
e
Hi, I’d like to understand how data is transferred between the frontend and backend. From what I can tell, the frontend and backend communicate through the LiveKit server. I have a scenario where a user selects a language in the frontend, and based on that language, I need to configure the STT, TTS, and LLM models on the backend. How can I accomplish this?
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.
I'm glad you're exploring how data transfer works between the frontend and backend in LiveKit! It’s all made possible through WebRTC, which allows real-time, two-way communication. The backend agent actually joins the LiveKit session just like any other participant, so it can both receive and send audio streams and data messages seamlessly. When it comes to setting up STT, TTS, and LLM models based on what users select on the frontend, here are some helpful ways to handle it: • STT (Speech-to-Text): You can easily update the STT configuration on the fly using methods like
update_options()
. For example, if someone picks a different language on the frontend, this can automatically update the STT model and language settings for you. • TTS (Text-to-Speech): Just like STT, TTS settings can be changed dynamically to switch voices or languages, making the experience feel very natural. • LLM (Large Language Model): LiveKit supports a variety of LLMs such as OpenAI, Gemini, and Qwen. You can update their configurations dynamically too, like choosing different tools or adjusting reasoning parameters, using the
updateOptions
method. All these changes from the frontend can be sent to the backend through Remote Procedure Calls (RPC). This means when a user makes a selection, the frontend sends that info to the backend, which then updates the AI pipeline accordingly. It’s a smooth way to keep everything in sync with user preferences. If you want me to walk you through any part of this with more details or examples, just let me know—I’m here to help! Sources: Speech-to-text (STT) models | LiveKit Docs | Building voice agents | LiveKit Docs | Live Conversations with AI using ChatGPT and WebRTC | plugins/openai/src/realtime/realtime_model.ts | Remote method calls | LiveKit docs
e
please share an example, i'm using your agent-starter-react and agent-starter-python
t
I’m glad to share an example of how you can use agent-starter-react (frontend) and agent-starter-python (backend) to dynamically update STT, TTS, and LLM configurations based on your selections from the frontend: Backend Implementation (Python)
Copy code
from livekit.agents import AgentSession, llm, voice
from livekit.plugins import openai, deepgram, cartesia, elevenlabs
from livekit.plugins.turn_detector.multilingual import MultilingualModel

# Configuration factory functions
stt_options = {
    "deepgram": lambda: deepgram.STT(model="nova-3"),
}

tts_options = {
    "cartesia": lambda: cartesia.TTS(voice="f786b574-daa5-4673-aa0c-cbe3e8534c02"),
}

llm_options = {
    "openai": lambda: openai.LLM(model="gpt-4o", temperature=0.45),
}

class MainAgent(voice.VoiceAgent):
    def __init__(self):
        super().__init__(
            stt=stt_options["deepgram"](),
            tts=tts_options["cartesia"](),
            llm=llm_options["openai"](),
        )
        self.llm.add_tool(
            llm.FunctionTool(
                name="update_agent_config",
                description="Update the agent's STT, TTS, and LLM configuration",
                parameters={
                    "type": "object",
                    "properties": {
                        "stt_choice": {"type": "string", "enum": list(stt_options.keys())},
                        "tts_choice": {"type": "string", "enum": list(tts_options.keys())},
                        "llm_choice": {"type": "string", "enum": list(llm_options.keys())},
                    },
                    "required": ["stt_choice", "tts_choice", "llm_choice"]
                },
                function=self._update_configuration
            )
        )

    async def _update_configuration(self, stt_choice, tts_choice, llm_choice):
        new_agent = TestAgent(stt_choice, tts_choice, llm_choice)
        return await self.session.handoff_to_agent(new_agent)

class TestAgent(voice.VoiceAgent):
    def __init__(self, stt_choice, tts_choice, llm_choice):
        super().__init__(
            stt=stt_options[stt_choice](),
            tts=tts_options[tts_choice](),
            llm=llm_options[llm_choice](),
        )
Frontend Integration (React) In agent-starter-react, you can easily trigger backend updates by: • UI Controls: Adding dropdowns or buttons that let users select preferences like language or model, which then get sent to the backend. • Chat Input: Allowing users to type commands such as "Switch to Cartesia TTS" to activate the update tool. This approach helps create a smooth experience with seamless handoffs between agents using the updated configurations. If you’d like, I’m here to help with any further details or questions you might have! Sources: templates.yaml | docs/index.yaml | Mobile SDKs (Flutter, iOS, Android) | livekit/livekit_composite | DeepWiki | examples/src/comprehensive_test.ts | Template System & Example Applications | livekit/livekit_composite | DeepWi...
e
share e xample of frontend as well for sending data to backend
t
Here’s a friendly example of how the agent-starter-react frontend can send data to the agent-starter-python backend for dynamic configuration updates: Backend (Python) On the backend side, you can define tools to handle configuration updates. For instance:
Copy code
class MainAgent(voice.VoiceAgent):
    def __init__(self):
        super().__init__(...)
        self.llm.add_tool(
            llm.FunctionTool(
                name="update_agent_config",
                description="Update the agent's STT, TTS, and LLM configuration",
                parameters={
                    "type": "object",
                    "properties": {
                        "stt_choice": {"type": "string"},
                        "tts_choice": {"type": "string"},
                        "llm_choice": {"type": "string"},
                    },
                    "required": ["stt_choice", "tts_choice", "llm_choice"]
                },
                function=self._update_configuration
            )
        )

    async def _update_configuration(self, stt_choice, tts_choice, llm_choice):
        # Update configurations dynamically
        ...
Frontend (React) On the frontend, the React app can send data to the backend using LiveKit’s RPC system like this:
Copy code
// Sending configuration updates to the backend
const sendConfigUpdate = async (room, sttChoice, ttsChoice, llmChoice) => {
  await room.localParticipant.publishData(
    JSON.stringify({
      method: "update_agent_config",
      params: { stt_choice: sttChoice, tts_choice: ttsChoice, llm_choice: llmChoice },
    }),
    DataPacket_Kind.RELIABLE
  );
};

// Example usage
sendConfigUpdate(room, "deepgram", "cartesia", "openai");
Integration • Make sure both the frontend and backend connect to the same LiveKit room. • Use the backend’s tool system to handle incoming RPC calls and update configurations accordingly. • Customize the frontend UI so users can select options (like dropdowns or buttons) that trigger the
sendConfigUpdate
function. This approach allows smooth, real-time communication between your frontend and backend to keep configurations up to date. If you have any questions or want me to walk you through any part, just let me know—I’m here to help! Sources: complex-agents/nova-sonic/README.md | livekit/livekit_composite | DeepWiki | README.md
e
on the agent-starter-react, how can i call right after when user has joined?
t
I'm glad you're exploring ways to trigger a function in agent-starter-react right after a user joins a LiveKit room! Here are a couple of friendly approaches that might help you out: 1. Using the LiveKitRoom Component Callbacks
Copy code
<LiveKitRoom 
  serverUrl={serverUrl} 
  token={token} 
  onConnected={() => {
    console.log("Connected to room");
    // Your function here
    myCustomFunction();
  }}
>
  {/* Room content */}
</LiveKitRoom>
2. Using Room Event Listeners
Copy code
import { useRoom } from '@livekit/components-react';
import { RoomEvent } from 'livekit-client';
import { useEffect } from 'react';

function MyComponent() {
  const room = useRoom();

  useEffect(() => {
    if (!room) return;

    const handleParticipantConnected = (participant) => {
      console.log(`Participant ${participant.identity} joined`);
      // Your custom function here
      myCustomFunction(participant);
    };

    room.on(RoomEvent.ParticipantConnected, handleParticipantConnected);

    return () => {
      room.off(RoomEvent.ParticipantConnected, handleParticipantConnected);
    };
  }, [room]);

  const myCustomFunction = (participant) => {
    // Your logic when a participant joins
  };

  return <div>{/* Your component JSX */}</div>;
}
These options give you the flexibility to run your own logic—like updating the UI or sending data to your backend—as soon as someone joins the room. If you want to chat more about this or need a hand with anything else, just let me know. I’m here to help! Sources: Building an Automated IVR Menu Caller | LiveKit Docs | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | packages/react/src/components/LiveKitRoom.tsx | Job lifecycle | LiveKit Docs
e
i added tool in python script and getting error self.llm.add_tool( llm.FunctionTool( name="enable_avatar", description="Add Avatar to Sesson", parameters={ "type": "object", "properties": { "avatar_enabled": {"type": "boolean"}, }, "required": ["avatar_enabled"] }, function=self._handle_avatar ) ) ERROR livekit.agents - unhandled exception while running the job task Traceback (most recent call last): File "/home/karandeep/Development/livekit-v1/agent-starter-python/.venv/lib/python3.10/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore File "/home/karandeep/Development/livekit-v1/agent-starter-python/.venv/lib/python3.10/site-packages/livekit/agents/ipc/job_proc_lazy_main.py", line 240, in _traceable_entrypoint await self._job_entrypoint_fnc(job_ctx) File "/home/karandeep/Development/livekit-v1/agent-starter-python/src/agent.py", line 312, in entrypoint agent=Assistant(), File "/home/karandeep/Development/livekit-v1/agent-starter-python/src/agent.py", line 174, in init self.llm.add_tool( AttributeError: 'NotGiven' object has no attribute 'add_tool' {"room": "voice_assistant_room_4350", "pid": 192695, "job_id": "AJ_uzXM9qHz7c2Q"}
t
I'm here to help you with the error
AttributeError: 'NotGiven' object has no attribute 'add_tool'
you're encountering. This usually happens when the LLM instance isn't initialized properly or configured the right way. Let's walk through how you can fix this together: 1. Proper LLM Initialization First, make sure your LLM is set up correctly before you start using it. Here's a simple example:
Copy code
from livekit.plugins import openai

llm = openai.LLM(
    model="gpt-4o",
    api_key="your-api-key",  # Or set OPENAI_API_KEY as an environment variable
    temperature=0.7
)
2. Correct Tool Definition Instead of adding tools directly to the LLM, it's best to define them inside your Agent class using the
@function_tool
decorator. Here's how you can do it:
Copy code
from livekit.agents import Agent, function_tool, RunContext

class MyAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant.")

    @function_tool
    async def enable_avatar(self, context: RunContext, avatar_enabled: bool):
        """Enable or disable avatar in the session."""
        return f"Avatar enabled: {avatar_enabled}"
3. Complete Example To bring it all together, here’s how you can integrate your agent with a properly initialized LLM:
Copy code
from livekit.agents import AgentSession
from livekit.plugins import openai, deepgram

async def entrypoint(ctx):
    session = AgentSession(
        llm=openai.LLM(model="gpt-4o"),
        stt=deepgram.STT(),
        tts=openai.TTS(),
    )

    await session.start(agent=MyAgent(), room=ctx.room)
Also, please double-check that your environment variables like
OPENAI_API_KEY
are set up correctly. If you have any questions or need more help, feel free to reach out—I’m here to support you! Sources: Agents v0.x migration guide - Python | LiveKit docs | main.py | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/llm.py | Tool definition and use | LiveKit docs