Hi elevenlabs last few characters are getting cuto...
# ask-ai
g
Hi elevenlabs last few characters are getting cutoff when using livekit sample project
t
Thanks for reaching out, Abhishek. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks so much for reaching out! To help you better, could you please share a bit more about what’s going on? Specifically: • Which LiveKit sample project are you working with? • Are you using ElevenLabs for text-to-speech, or is it for something else? • Does the issue happen every time, or just in certain situations? • Have you seen any error messages or logs that might give us a clue? Your details will really help us get to the bottom of this together. Looking forward to your reply!
g
elevenlabs for test top speech am using https://github.com/livekit-examples/agent-starter-python/tree/main happens everytime and only with elevenlabs other tts works fine
t
It sounds like you’re encountering an issue with ElevenLabs text-to-speech cutting off the last few characters in the LiveKit agent-starter-python example. This usually happens when the stream isn’t properly finalized during synthesis. Don’t worry, I’m here to help you fix this! Please make sure your code includes these important steps: 1. Call
stream.flush()
to send all the pending text for synthesis. 2. Call
stream.end_input()
to let the system know you’ve finished sending text. 3. Await the completion of both synthesis and playout tasks before closing the stream by using
await asyncio.gather(synth_task, playout_task)
. Here’s a friendly example to guide you through the correct implementation:
Copy code
stream = tts_11labs.stream()
for chunk in _text_to_chunks(streamed_text):
    stream.push_text(chunk)

stream.flush()
stream.end_input()

# Start synthesis and playout tasks
synth_task = asyncio.create_task(_synth_task())
playout_task = asyncio.create_task(_playout_task(playout_q, source))

# Wait for both tasks to complete
await asyncio.gather(synth_task, playout_task)
await stream.aclose()
Also, if you’re using SSML tags, double-check that all of them are properly closed since incomplete XML can sometimes cause synthesis hiccups. If you have any questions or need a hand with anything else, just let me know—I’m happy to assist! Sources: examples/other/text-to-speech/rime_tts.py
g
my code is
Copy code
import asyncio
import logging

from dotenv import load_dotenv
from livekit.agents import (
    NOT_GIVEN,
    Agent,
    AgentFalseInterruptionEvent,
    AgentSession,
    JobContext,
    JobProcess,
    MetricsCollectedEvent,
    RoomInputOptions,
    RunContext,
    WorkerOptions,
    cli,
    metrics,
)
from livekit.agents.llm import function_tool
from livekit.plugins import cartesia, deepgram, noise_cancellation, openai, silero,elevenlabs
from livekit.plugins.turn_detector.multilingual import MultilingualModel

logger = logging.getLogger("agent")

load_dotenv(".env.local")


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice AI assistant.
            You eagerly assist users with their questions by providing information from your extensive knowledge.
            Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols.
            You are curious, friendly, and have a sense of humor.""",
        )

    # all functions annotated with @function_tool will be passed to the LLM when this
    # agent is active
    @function_tool
    async def lookup_weather(self, context: RunContext, location: str):
        """Use this tool to look up current weather information in the given location.

        If the location is not supported by the weather service, the tool will indicate this. You must tell the user the location's weather is unavailable.

        Args:
            location: The location to look up weather information for (e.g. city name)
        """

        logger.info(f"Looking up weather for {location}")

        return "sunny with a temperature of 70 degrees."


def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext):
    # Logging setup
    # Add any other context you want in all log entries here
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    # Set up a voice AI pipeline using OpenAI, Cartesia, Deepgram, and the LiveKit turn detector
    session = AgentSession(
        # A Large Language Model (LLM) is your agent's brain, processing user input and generating a response
        # See all providers at https://docs.livekit.io/agents/integrations/llm/
        llm=openai.LLM(model="gpt-4.1-mini"),
        # Speech-to-text (STT) is your agent's ears, turning the user's speech into text that the LLM can understand
        # See all providers at https://docs.livekit.io/agents/integrations/stt/
        stt=deepgram.STT(model="nova-3", language="multi"),
        # Text-to-speech (TTS) is your agent's voice, turning the LLM's text into speech that the user can hear
        # See all providers at https://docs.livekit.io/agents/integrations/tts/


        tts = elevenlabs.TTS(
            voice_id="2bNrEsM0omyhLiEyOwqY",
            model="eleven_multilingual_v2",  # or "eleven_turbo_v2_5" if you prefer speed
            streaming_latency=0,  # 0 = minimal tail-truncation; 3 (default) = moderate, 4 = aggressive low-latency
            enable_ssml_parsing=True,  # if you want to fine-tune pronunciation via SSML
            auto_mode=True  # handles chunking automatically for full sentences
        ),

        #cartesia.TTS(voice="6f84f4b8-58a2-430c-8c79-688dad597532"),
        # VAD and turn detection are used to determine when the user is speaking and when the agent should respond
        # See more at https://docs.livekit.io/agents/build/turns
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
        # allow the LLM to generate a response while waiting for the end of turn
        # See more at https://docs.livekit.io/agents/build/audio/#preemptive-generation
        preemptive_generation=True,
    )

    # To use a realtime model instead of a voice pipeline, use the following session setup instead:
    # session = AgentSession(
    #     # See all providers at https://docs.livekit.io/agents/integrations/realtime/
    #     llm=openai.realtime.RealtimeModel(voice="marin")
    # )

    # sometimes background noise could interrupt the agent session, these are considered false positive interruptions
    # when it's detected, you may resume the agent's speech
    @session.on("agent_false_interruption")
    def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
        logger.info("false positive interruption, resuming")
        session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)

    # Override TTS synthesis to ensure complete playback using streaming
    original_tts = session.tts
    if hasattr(original_tts, 'stream'):
        original_synthesize = original_tts.synthesize

        async def enhanced_synthesize(text: str, **kwargs):
            logger.info(f"🔊 TTS synthesis starting: '{text}' (length: {len(text)})")
            try:
                # Create TTS stream
                stream = original_tts.stream()

                # Push text to stream in chunks
                def _text_to_chunks(text: str, chunk_size: int = 50):
                    words = text.split()
                    for i in range(0, len(words), chunk_size):
                        yield ' '.join(words[i:i + chunk_size])

                for chunk in _text_to_chunks(text):
                    stream.push_text(chunk)

                # Flush all pending text and signal end of input
                stream.flush()
                stream.end_input()

                # Create synthesis and playout tasks
                async def _synth_task():
                    async for audio_chunk in stream:
                        yield audio_chunk

                async def _playout_task():
                    # Handle audio playout
                    pass

                synth_task = asyncio.create_task(_synth_task())
                playout_task = asyncio.create_task(_playout_task())

                # Wait for both tasks to complete
                await asyncio.gather(synth_task, playout_task)
                await stream.aclose()

                logger.info("✅ TTS synthesis and playout completed successfully")
                return synth_task.result()

            except Exception as e:
                logger.error(f"❌ TTS streaming failed: {e}")
                # Fall back to original method
                return await original_synthesize(text, **kwargs)

        original_tts.synthesize = enhanced_synthesize

    # Metrics collection, to measure pipeline performance
    # For more information, see https://docs.livekit.io/agents/build/metrics/
    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}")

    ctx.add_shutdown_callback(log_usage)

    # # Add a virtual avatar to the session, if desired
    # # For other providers, see https://docs.livekit.io/agents/integrations/avatar/
    # avatar = hedra.AvatarSession(
    #   avatar_id="...",  # See https://docs.livekit.io/agents/integrations/avatar/hedra
    # )
    # # Start the avatar and wait for it to join
    # await avatar.start(session, room=ctx.room)

    # Start the session, which initializes the voice pipeline and warms up the models
    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(),
        ),
    )

    # Join the room and connect to the user
    await ctx.connect()


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
t
Thank you so much for sharing your code! I can see you’ve put a lot of thought into your implementation. The issue with ElevenLabs TTS cutting off the last few characters can sometimes happen if the stream isn’t properly finalized. Your enhanced TTS synthesis method is definitely on the right track. To help you further, here are a few things to double-check: 1. Make sure you’re calling
stream.flush()
and
stream.end_input()
right after pushing all your text chunks to the stream. 2. It’s important to await both the synthesis and playout tasks using
await asyncio.gather(synth_task, playout_task)
before you close the stream with
await stream.aclose()
. 3. Take a look at your
_playout_task()
function to confirm it’s handling audio playback smoothly and finishing without any hiccups. If you’re still running into issues, a helpful next step might be to log the audio chunks in the
_synth_task()
to see if the ElevenLabs API is sending the complete audio. Please feel free to reach out if you want me to walk through any of these steps with you or if you have any other questions—I’m here to help!
g
now i have avery simple agent still cutting off , this is directly from example
Copy code
import asyncio
import logging

from dotenv import load_dotenv
from livekit.agents import (
    NOT_GIVEN,
    Agent,
    AgentFalseInterruptionEvent,
    AgentSession,
    JobContext,
    JobProcess,
    MetricsCollectedEvent,
    RoomInputOptions,
    RunContext,
    WorkerOptions,
    cli,
    metrics,
)
from livekit.agents.llm import function_tool
from livekit.plugins import (
    deepgram,
    elevenlabs,
    noise_cancellation,
    openai,
    silero,
)
from livekit.plugins.turn_detector.multilingual import MultilingualModel

logger = logging.getLogger("agent")

load_dotenv(".env.local")


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice AI assistant.
            You eagerly assist users with their questions by providing information from your extensive knowledge.
            Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols.
            You are curious, friendly, and have a sense of humor.""",
        )

    # all functions annotated with @function_tool will be passed to the LLM when this
    # agent is active
    @function_tool
    async def lookup_weather(self, context: RunContext, location: str):
        """Use this tool to look up current weather information in the given location.

        If the location is not supported by the weather service, the tool will indicate this. You must tell the user the location's weather is unavailable.

        Args:
            location: The location to look up weather information for (e.g. city name)
        """

        logger.info(f"Looking up weather for {location}")

        return "sunny with a temperature of 70 degrees."


def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext):
    # Logging setup
    # Add any other context you want in all log entries here
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    # Set up a voice AI pipeline using OpenAI, Cartesia, Deepgram, and the LiveKit turn detector
    session = AgentSession(
        # A Large Language Model (LLM) is your agent's brain, processing user input and generating a response
        # See all providers at https://docs.livekit.io/agents/integrations/llm/
        llm=openai.LLM(model="gpt-4.1-mini"),
        # Speech-to-text (STT) is your agent's ears, turning the user's speech into text that the LLM can understand
        # See all providers at https://docs.livekit.io/agents/integrations/stt/
        stt=deepgram.STT(model="nova-3", language="multi"),
        # Text-to-speech (TTS) is your agent's voice, turning the LLM's text into speech that the user can hear
        # See all providers at https://docs.livekit.io/agents/integrations/tts/


        tts = elevenlabs.TTS(
            voice_id="2bNrEsM0omyhLiEyOwqY",
            model="eleven_multilingual_v2",  # or "eleven_turbo_v2_5" if you prefer speed
            streaming_latency=0,  # 0 = minimal tail-truncation; 3 (default) = moderate, 4 = aggressive low-latency
            enable_ssml_parsing=False,  # if you want to fine-tune pronunciation via SSML
            auto_mode=True  # handles chunking automatically for full sentences
        ),

        #cartesia.TTS(voice="6f84f4b8-58a2-430c-8c79-688dad597532"),
        # VAD and turn detection are used to determine when the user is speaking and when the agent should respond
        # See more at https://docs.livekit.io/agents/build/turns
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
        # allow the LLM to generate a response while waiting for the end of turn
        # See more at https://docs.livekit.io/agents/build/audio/#preemptive-generation
        preemptive_generation=False,
    )

    # To use a realtime model instead of a voice pipeline, use the following session setup instead:
    # session = AgentSession(
    #     # See all providers at https://docs.livekit.io/agents/integrations/realtime/
    #     llm=openai.realtime.RealtimeModel(voice="marin")
    # )

    # sometimes background noise could interrupt the agent session, these are considered false positive interruptions
    # when it's detected, you may resume the agent's speech
    @session.on("agent_false_interruption")
    def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
        logger.info("false positive interruption, resuming")
        session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)


    # Metrics collection, to measure pipeline performance
    # For more information, see https://docs.livekit.io/agents/build/metrics/
    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}")

    ctx.add_shutdown_callback(log_usage)

    

    # Start the session, which initializes the voice pipeline and warms up the models
    await session.start(
        agent=Assistant(),
        room=ctx.room,
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(),
        ),
    )

    # Join the room and connect to the user
    await ctx.connect()


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm))
t
It sounds like the issue with ElevenLabs TTS cutting off the last characters in your simplified agent setup might be related to how the
streaming_latency
parameter and stream termination are configured. Don’t worry, I’m here to help you through this! Here are some steps that should get things working smoothly: 1. Try to avoid setting
streaming_latency=0
. Instead, sticking with the default value (
3
) or one of the supported values (1, 2, or 3) helps keep the streaming optimized. 2. Make sure you call
stream.end_input()
right after the final
flush()
. This signals the end of input properly and lets the TTS system process any remaining text. 3. Double-check that you’re using
auto_mode=True
along with a
SentenceTokenizer
, as this is recommended to handle sentence boundaries effectively. Here’s a quick example of how you might configure your TTS:
Copy code
tts = elevenlabs.TTS(
    voice_id="your-voice-id",
    model="eleven_turbo_v2_5",
    auto_mode=True,
    streaming_latency=3  # Use default or valid value
)
Also, just make sure all text chunks are sent and flushed before you call
end_input()
. If you run into any more questions or need a hand with this, please feel free to reach out—I’m happy to help! Sources: ElevenLabs TTS integration guide | LiveKit Docs | livekit-agents/livekit/agents/tts/tts.py