```import aiohttp import requests import json impo...
# ask-ai
q
Copy code
import aiohttp
import requests
import json
import urllib.parse
from datetime import datetime
import asyncio
import logging
from collections.abc import AsyncIterable
from enum import Enum
from typing import Optional, Dict, Any

from dotenv import load_dotenv

from livekit import agents
from livekit import rtc
from livekit.agents import (
    AgentSession, Agent, function_tool,
    JobContext,
    JobProcess,
    MetricsCollectedEvent,
    ModelSettings,
    RoomInputOptions,
    RoomOutputOptions,
    RunContext,
    WorkerOptions,
    cli,
    metrics,
)
from livekit.plugins import (
    openai,
    elevenlabs,
    deepgram,
    noise_cancellation,
    silero,
)
from livekit.agents.voice.transcription.filters import filter_markdown
from livekit.plugins.turn_detector.multilingual import MultilingualModel

logger = logging.getLogger("multi-agent")

load_dotenv(".env.local^T")
Copy code
# Approach 1: Single Multi-Modal Agent (Recommended)
class MultiModalAgent(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""Your name is AVA, a multi-purpose AI assistant. You can help with:
            - Weather information (current conditions and forecasts)
            - News headlines and search for specific news topics
            - General questions and conversations
            - Travel recommendations

            Keep responses concise for voice interaction. Current location is Kolkata.
            When users ask about switching modes or agents, explain your capabilities.
            For news, you can provide top headlines or search for specific topics.""",

        )
        self.weather_api = WeatherAPI()
        self.news_api = GNewsHeadlines()
        self.current_mode = AgentMode.GENERAL

    async def on_enter(self):
        logger.info("Multi-modal agent entering room")
        await self.session.generate_reply(instructions=
            "Hello! I'm AVA, your multi-purpose assistant. I can help with weather, news headlines, travel, and general questions. What can I do for you today?")

    async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings) -> AsyncIterable[rtc.AudioFrame]:
        filtered_text = filter_markdown(text)
        return super().tts_node(filtered_text, model_settings)

    @function_tool
    async def switch_agent_mode(self, context: RunContext, mode: str):
        """Switch the agent to a different mode/specialization.

        Args:
            mode: The mode to switch to (weather, general, travel, news)
        """
        try:
            new_mode = AgentMode(mode.lower())
            self.current_mode = new_mode

            mode_messages = {
                AgentMode.WEATHER: "I'm now in weather mode. Ask me about current conditions or forecasts for any location.",
                AgentMode.GENERAL: "I'm now in general mode. I can help with various questions and conversations.",
                AgentMode.TRAVEL: "I'm now in travel mode. I can help with travel recommendations and planning.",
                AgentMode.NEWS: "I'm now in news mode. I can help you stay updated with current events."
            }

            message = mode_messages.get(new_mode, "Mode switched successfully.")
            await self.session.generate_reply(instructions=message)
            return f"Switched to {mode} mode."

        except ValueError:
            error_msg = "Invalid mode. Available modes are: weather, general, travel, news."
            await self.session.generate_reply(instructions=error_msg)
            return "Mode switch failed."

    @function_tool
    async def get_weather(self, context: RunContext, location: str = "Kolkata"):
        """Get current weather information for a location."""
        logger.info(f"Getting weather for {location}")

        try:
            loop = asyncio.get_event_loop()
            weather_data = await loop.run_in_executor(None, self.weather_api.get_current_weather, location)

            if weather_data:
                weather_response = self.weather_api.format_weather_response(weather_data)
                logger.info(f"Weather response: {weather_response}")
                await self.session.generate_reply(instructions=weather_response)
                return "Weather information provided."
            else:
                error_msg = f"Couldn't find weather for {location}. Please try another location."
                await self.session.generate_reply(instructions=error_msg)
                return "Weather lookup failed."

        except Exception as e:
            logger.error(f"Error in get_weather: {e}")
            await self.session.generate_reply(instructions="I'm having trouble getting weather information right now.")
            return "Weather error occurred."

    @function_tool
    async def get_travel_info(self, context: RunContext, destination: str):
        """Get travel information and recommendations for a destination."""
        logger.info(f"Getting travel info for {destination}")

        # This is a placeholder - you can integrate with actual travel APIs
        travel_response = f"Here are some travel tips for {destination}: Check visa requirements, research local customs, pack appropriate clothing for the climate, and book accommodations in advance. Would you like specific information about flights or hotels?"

        await self.session.generate_reply(instructions=travel_response)
        return "Travel information provided."

    @function_tool
    async def get_news_headlines(self, context: RunContext, max_results: int = 5):
        """Get current top news headlines from India.

        Args:
            max_results: Number of headlines to retrieve (1-10, default 5)
        """
        logger.info(f"Getting top {max_results} news headlines")

        try:
            # Ensure max_results is within valid range
            max_results = max(1, min(max_results, 10))

            # Run the API call in a thread pool to avoid blocking
            loop = asyncio.get_event_loop()
            articles = await loop.run_in_executor(
                None, self.news_api.get_descriptions, 'en', 'in', max_results
            )

            if articles:
                news_response = self.news_api.format_headlines_for_voice(articles, max_results)
                await self.session.generate_reply(instructions=news_response)
                return "News headlines provided."
            else:
                error_msg = "I couldn't fetch the latest news headlines right now. Please try again later."
                await self.session.generate_reply(instructions=error_msg)
                return "News headlines fetch failed."

        except Exception as e:
            logger.error(f"Error in get_news_headlines: {e}")
            await self.session.generate_reply(instructions="I'm having trouble getting the news headlines right now.")
            return "News headlines error occurred."

    @function_tool
    async def search_news(self, context: RunContext, query: str, max_results: int = 5):
        """Search for news articles about a specific topic.

        Args:
            query: The search term or topic to search for
            max_results: Number of results to retrieve (1-10, default 5)
        """
        logger.info(f"Searching news for: {query}")

        try:
            # Ensure max_results is within valid range
            max_results = max(1, min(max_results, 10))

            # Run the API call in a thread pool to avoid blocking
            loop = asyncio.get_event_loop()
            search_results = await loop.run_in_executor(
                None, self.news_api.search_gnews_json, query, 'en', 'in', max_results
            )

            if search_results:
                news_response = self.news_api.format_search_results_for_voice(search_results, query)
                await self.session.generate_reply(instructions=news_response)
                return "News search results provided."
            else:
                error_msg = f"I couldn't find any news about {query}. Please try a different search term."
                await self.session.generate_reply(instructions=error_msg)
                return "News search failed."

        except Exception as e:
            logger.error(f"Error in search_news: {e}")
            await self.session.generate_reply(instructions="I'm having trouble searching for news right now.")
            return "News search error occurred."

    @function_tool
    async def get_news_summary(self, context: RunContext, topic: str = "general"):
        """Get news summary for a specific topic or general news.

        Args:
            topic: The topic to search for, or "general" for top headlines
        """
        logger.info(f"Getting news for topic: {topic}")

        if topic.lower() in ["general", "headlines", "top", "latest"]:
            # Get top headlines
            return await self.get_news_headlines(context, 5)
        else:
            # Search for specific topic
            return await self.search_news(context, topic, 5)


# Main entrypoint functions for different approaches

# Approach 1: Single Multi-Modal Agent (Recommended)
async def entrypoint_multimodal(ctx: agents.JobContext):
    """Single agent that handles multiple domains - RECOMMENDED"""
    session = AgentSession(
        stt=deepgram.STT(model="nova-3", language="multi"),
        llm=openai.LLM(model="gpt-4o-mini"),
        tts=elevenlabs.TTS(
            voice_id="wlmwDR77ptH6bKHZui0l",
            model="eleven_turbo_v2_5"
        ),
        vad=silero.VAD.load()
    )
    tts = elevenlabs.TTS(
        voice_id="wlmwDR77ptH6bKHZui0l",
        model="eleven_turbo_v2_5"
    )
    
    await session.start(
        room=ctx.room,
        agent=MultiModalAgent(),
        room_input_options=RoomInputOptions(noise_cancellation=noise_cancellation.BVC()),
    )


# Approach 2: Dynamic switching (more complex)
async def entrypoint_dynamic(ctx: agents.JobContext):
    """Dynamic agent switching system"""
    dynamic_session = DynamicAgentSession()
    await dynamic_session.start_session(ctx)


# Use the recommended approach
async def entrypoint(ctx: agents.JobContext):
    return await entrypoint_multimodal(ctx)


if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
This is my implementation for using livekit agent .But the issue is , the tts message is playing not in streaming mode for Weather and news agent . Other than these 2 agents the tts responses are faster for general queries.Can you suggest how to enable the streaming mode.
t
Thanks for reaching out, Utsav. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To get streaming mode up and running for Text-to-Speech (TTS) in your Weather and News agents, here’s a simple guide to help you out: • Pick a Streaming-Friendly TTS Provider: Make sure the TTS engine you’re using supports streaming. For instance, OpenAI’s TTS has streaming built in right from the start. • Enable Streaming on Engines That Don’t Support It Natively: If your TTS engine doesn’t do streaming on its own, you can wrap it with a
StreamAdapter
. This handy adapter breaks down the text and sends audio in a way that works smoothly with streaming. • Boost Synchronization: Try using the
use_tts_aligned_transcript
option in your
AgentSession
. It helps keep the speech and transcription nicely in sync while streaming. • Fine-Tune Streaming Behavior: You can control how the text flows to the TTS engine by setting up a
SentenceStreamPacer
. This makes sure the speech sounds natural and continuous. If you’d like a hand putting these steps into action or want me to whip up a sample for your News agent, just give me a shout! Sources: plugins/resemble/src/tts.ts | livekit-plugins/livekit-plugins-upliftai/livekit/plugins/upliftai/tts.py
q
i am using elevenlabs tts api for generating the tts response
t
Streaming mode is turned on by default when you use the ElevenLabs TTS API in LiveKit agents. This integration uses WebSockets to send text in real-time and receive audio bit by bit, so you get quick, low-latency responses. To help everything run smoothly, here are a few things to check: • Make sure your ElevenLabs TTS instance is set up correctly in your agent configuration. For example:
Copy code
from livekit.plugins import elevenlabs

tts_instance = elevenlabs.TTS(
    voice_id="your_voice_id",
    model="eleven_multilingual_v2",
    streaming_latency=3  # Optional: Adjust latency
)
• Double-check that your agent framework is using the
tts.stream()
method — this is the default for ElevenLabs TTS. • Confirm that the
capabilities.streaming
property is set to
True
for your ElevenLabs TTS instance. If you’re still noticing delays, especially with Weather and News agents, there might be some extra processing or blocking happening in their code. Feel free to reach out if you want me to help take a look at those parts! Sources: livekit-plugins/livekit-plugins-playai/livekit/plugins/playai/tts.py | plugins/elevenlabs/src/index.ts | ElevenLabs TTS integration guide | LiveKit Docs
q
I used self.session.say and self.session.generate_response method but found latency in the tts response
t
To help speed up TTS responses when using self.session.say and self.session.generate_response, here are some tips you might find useful: • Enable Preemptive Generation: Try setting
preemptive_generation=True
in your
AgentSession
setup. This way, the system starts generating responses as soon as it has the final transcript, so it overlaps processing with the user’s speech and saves time. • Optimize Network Proximity: Hosting your agent close to the LLM, STT, and TTS services can really help cut down on transit delays. • Use Pre-synthesized Audio: When you use
session.say
, you can provide audio that’s already been generated. This skips the real-time TTS step and makes playback quicker. • Monitor Latency Metrics: Keep an eye on performance using the Agents metrics API. Tracking things like Time To First Token (TTFT) and Time To First Byte (TTFB) can help you spot where delays happen. • Tune Endpointing Delays: Adjust
min_endpointing_delay
and
max_endpointing_delay
in your
AgentSession
to detect when the user finishes speaking a bit faster. • Choose High-Performance TTS Models: Make sure you’re using a low-latency TTS model—ElevenLabs’ optimized streaming models are a great option. If you want a hand setting any of this up, just let me know—I’m happy to help! Sources: Agent speech and audio | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | Voice Assistants | livekit/livekit_composite | DeepWiki | How can I reduce latency in voice agents using STT, TTS and LLM? | Agent Testing & Evaluation | livekit/livekit_composite | DeepWiki