hey guys how is it going? I am using livekit agen...
# agents
a
hey guys how is it going? I am using livekit agents v1 and I am wondering why my TTS is mispronouncing numbers, i.e the bitcoin price is $118,152.31. the model is basically just reading the numbers or sometimes skipping them. I am using the elevenlabs tts multilingual v2. On my custom stt - llm - tts pipeline, even the elevenlabs turbo v2 has no issue with this. I checked on the website https://elevenlabs.io/app/speech-synthesis/text-to-speech, and gave it the same sentence, and this can do it perfectly. Does anyone on the team know why I am having issues with this? Any help here would be massive. I am wondering if it is something with the plumbing. PS. I am trying to display the numeric form but have the TTS output the spoken form. I also have auto=False
r
Different eleven labs models have different abilities. Check their docs. But smaller models it is up to you to convert it to the way you want it to say it.
a
@refined-appointment-81829 i am aware of that.
I see that kit is built using agents, and it seems to be able to pronounce prices perfectly. Is something wrong with my setup here?
import logging import os import aiohttp import asyncio from dotenv import load_dotenv from livekit.agents import ( Agent, AgentSession, JobContext, JobProcess, RoomInputOptions, RoomOutputOptions, RunContext, WorkerOptions, cli, metrics, ) from livekit.agents.llm import function_tool from livekit.agents.voice import MetricsCollectedEvent from livekit.plugins import cartesia, deepgram, elevenlabs, noise_cancellation, openai, silero from livekit.plugins.turn_detector.multilingual import MultilingualModel logger = logging.getLogger("agent") load_dotenv(".env.local") # Server configuration ELECTRA_SERVER_URL = os.getenv("ELECTRA_SERVER_URL", "http://localhost:3000") ELECTRA_API_TOKEN = os.getenv("ELECTRA_API_TOKEN") class Assistant(Agent): def __init__(self) -> None: super().__init__( instructions="""You are Electra, an AI financial assistant. RESPONSE STYLE - CRITICAL: - Keep responses to 1-2 sentences maximum - Give direct answers immediately - No long explanations or descriptions - No "I'm thinking" or "Let me think" phrases - Only introduce yourself as "I'm Electra" if the user greets you or asks for your name NUMBER FORMATTING: - Always display exact formatted prices from data sources (e.g., "$64,115.25") - Round dollar amounts to whole numbers when possible ($50 not $50.00) - Use simple decimal format for BTC (0.01 BTC not 0.0100000 BTC) CONVERSATION MEMORY: - Pay attention to conversation context provided in messages - When users mention Bitcoin, crypto, or specific amounts after previous discussions - they're modifying previous requests - When users say "continue", "proceed", "my order", "that transaction", "yes", "ok" - they're referring to previous conversation - Recent conversation history will be provided when users reference previous discussions - CRITICAL: If user mentions a different amount than originally discussed, ask for clarification immediately MEMORY EXAMPLES: - User: "Buy Bitcoin" → AI: "How much?" → User: "What's Tesla's price?" → AI: "Tesla is $313.51" → User: "Continue my Bitcoin order" → AI should remember the Bitcoin discussion - User: "I want to buy $50 of bitcoin" → AI: "Confirm $50 Bitcoin order?" → User: "I want 0.01 BTC instead" → AI should recognize this as modifying the previous order - User: "Continue my 0.1 BTC order" (when original was 0.01 BTC) → AI should ask: "I see you originally wanted 0.01 BTC but now mentioned 0.1 BTC. Which amount did you mean?" Available tools allow you to access real-time market data, analyze portfolios, and execute investment analysis. Use these tools to provide quick, actionable financial guidance. Remember: You provide educational information. Users should consult qualified financial advisors for personalized investment decisions.""", ) _# all functions annotated with @function_tool will be passed to the LLM when this_ # agent is active @function_tool async def get_bitcoin_price(self, context: RunContext): """Use this tool to get the current Bitcoin price in USD from Glassnode. This tool fetches real-time Bitcoin market data and returns the current price. """ logger.info("Fetching Bitcoin price from Electra server") if not ELECTRA_API_TOKEN: logger.error("No API token configured for Electra server") return "Unable to fetch Bitcoin price: API token not configured" try: async with aiohttp.ClientSession() as session: headers = { "Authorization": f"Bearer {ELECTRA_API_TOKEN}", "Content-Type": "application/json" } async with session.get( f"{ELECTRA_SERVER_URL}/api/v1/glassnode/bitcoin/price", headers=headers, timeout=aiohttp.ClientTimeout(total=10) ) as response: if response.status == 401: logger.error("Authentication failed with Electra server") return "Unable to fetch Bitcoin price: Authentication failed" if response.status != 200: logger.error(f"Server error: {response.status}") return f"Unable to fetch Bitcoin price: Server error ({response.status})" data = await response.json() price = data.get("price") if price: formatted_price = f"${price:,.2f}" logger.info(f"Bitcoin price fetched: {formatted_price}") return f"The current Bitcoin price is {formatted_price}" else: logger.error("No price data in server response") return "Unable to fetch Bitcoin price: No price data received" except asyncio.TimeoutError: logger.error("Timeout fetching Bitcoin price") return "Unable to fetch Bitcoin price: Request timed out" except aiohttp.ClientError as e: logger.error(f"HTTP error fetching Bitcoin price: {e}") return "Unable to fetch Bitcoin price: Network error" except Exception as e: logger.error(f"Unexpected error fetching Bitcoin price: {e}") return "Unable to fetch Bitcoin price: Unexpected error" def prewarm(proc: JobProcess): proc.userdata["vad"] = silero.VAD.load() async def entrypoint(ctx: JobContext): # each log entry will include these fields ctx.log_context_fields = { "room": ctx.room.name, } session = AgentSession( # any combination of STT, LLM, TTS, or realtime API can be used llm=openai.LLM(model="gpt-4o"), stt=deepgram.STT(model="nova-3", language="multi"), tts=elevenlabs.TTS( voice_id="cgSgspJ2msm6clMCkdW9", model="eleven_multilingual_v2", voice_settings=elevenlabs.VoiceSettings( stability=0.5, similarity_boost=0.75, style=0.0, use_speaker_boost=True ), enable_ssml_parsing=False, auto_mode=True, ), # use LiveKit's turn detection model turn_detection=MultilingualModel(), vad=ctx.proc.userdata["vad"], ) # To use the OpenAI Realtime API, use the following session setup instead: # session = AgentSession( # llm=openai.realtime.RealtimeModel() # ) # log metrics as they are emitted, and total usage after session is over usage_collector = metrics.UsageCollector() @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage: {summary}") # shutdown callbacks are triggered when the session is over ctx.add_shutdown_callback(log_usage) await session.start( agent=Assistant(), room=ctx.room, room_input_options=RoomInputOptions( # LiveKit Cloud enhanced noise cancellation # - If self-hosting, omit this parameter # - For telephony applications, use
BVCTelephony
for best results
noise_cancellation=noise_cancellation.BVC(), ), room_output_options=RoomOutputOptions(transcription_enabled=True), ) # join the room when agent is ready await ctx.connect() if name == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
kit even does the conversions right as well when i tell her to do them so i am just trying to understand how i can get to that - basically just pulled the livekit agents in python and set it up
would appreciate any help! i understand its just starter code but i did assume just hooking it up to the elevenlabs would be able to read my prices propely from my server with the tool calls etc
and yes ik not good to put tool inside this file but wanted to test it before i built this out. was using a custom pipeline before for everything
and this i dont think is the issue right - f this property was not set at Agent creation, but an
AgentSession
provides an STT component, the session's STT will be used at runtime instead.
and on kit yall use elevenlabs. i would love some help! gonna take a break
are you doing something similar to this?
but then id do it dynamically
Why Use Number-to-Words (Like num2words) with ElevenLabs TTS? ElevenLabs is a high-quality TTS service that excels at lifelike, multilingual speech synthesis, but like many TTS models, it can struggle with automatically pronouncing numbers, dates, currencies, symbols, or acronyms in a natural, context-aware way. For instance: • A number like "$188,000" might be read as "one eight eight comma zero zero zero dollars" (digit-by-digit) instead of the intended "one hundred eighty-eight thousand dollars." • Phone numbers, dates (e.g., "2025-07-26"), or large figures could be misinterpreted or spoken unclearly, especially across languages. ElevenLabs explicitly recommends preprocessing by writing out numbers and symbols fully in words to control exactly how they're delivered, as their models perform best with explicit, human-like text input. Using a tool like num2words automates this: You convert the number programmatically (e.g., in your code before sending to ElevenLabs API), ensuring consistent, natural output without manual editing. This is especially helpful for dynamic content (e.g., in apps, games, or real-time agents via LiveKit integrations), where numbers change frequently.