I have a very basic agent using speechmatic and el...
# ask-ai
b
I have a very basic agent using speechmatic and elevenlabs in Swedish. However it is always interrupted and will never finish a sentence even though I am not speaking at all
t
Thanks for reaching out, Kristoffer. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you share a bit more about your setup? For example: • Are you using any specific settings for interruptions, like
allow_interruptions
,
min_interruption_duration
, or
min_interruption_words
? • Does the issue happen with every sentence, or just in certain situations? • Have you tweaked the turn detection model or any related settings? Knowing these details will really help us figure out what’s causing the interruptions. Sources: Turn detection and interruptions | LiveKit Docs | How to Handle Speech Interruptions More Naturally
b
Here is some very basic code, I have tried many different parameters for turn detection/interruption but I just have issues
Copy code
import os
from pathlib import Path

from dotenv import load_dotenv
from livekit.agents import (
    JobContext,
    WorkerOptions,
    cli,
)
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import elevenlabs, openai, speechmatics

load_dotenv(dotenv_path=Path(__file__).parent.parent / ".env")


class Anna(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""
                You are a helpful agent.
                You speak Norwegian.
                You are here to take any messages from the user.
                Do not make up any information.
                Do not ask any questions, just take messages,
                Do not say much.
            """,
            stt=speechmatics.STT(
                api_key=os.getenv("SPEECHMATICS_API_KEY",""), language="no"
            ),
            # Tried multiple values for this, but none worked
            turn_detection="vad",
            # Tried multiple values for this, but none worked
            allow_interruptions=False,
            use_tts_aligned_transcript=True,
            llm=openai.LLM(model="gpt-4o"),
            tts=elevenlabs.TTS(
                voice_id=os.getenv("ELEVENLABS_VOICE_ID",""),
                language="no",
                model="eleven_turbo_v2_5",
                api_key=os.getenv("ELEVENLABS_API_KEY",""),
            ),
        )


async def entrypoint(ctx: JobContext):
    await ctx.connect()


    session: AgentSession = AgentSession(
        # Tried multiple values for this, but none worked
        allow_interruptions=False,

        # Tried multiple values for this, but none worked
        min_interruption_duration=1
    )
    # Cleaner realtime captions to clients (don't wait to sync back to audio)

    agent = Anna()

    await session.start(agent=agent, room=ctx.room)



if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
t
Thanks so much for sharing the code and details! Based on what you’ve got set up, here are a few key points and some friendly suggestions to help with those interruptions: • Speechmatics Turn Detection: If you’re using
turn_detection="stt"
, double-check that Speechmatics supports real-time phrase endpointing. If it doesn’t, switching to
turn_detection="vad"
might be a better bet since it’s reliable and works regardless of language. • ElevenLabs TTS Pausing: It’s a good idea to see if the ElevenLabs TTS plugin can pause audio output during interruptions. This really helps keep interruptions smooth. If pausing isn’t supported, interruptions might not work quite as expected. • Configuration Adjustments: You might want to try these settings to improve how interruptions are handled:
Copy code
turn_detection="vad"
allow_interruptions=True
min_interruption_duration=0.5
min_interruption_words=2
false_interruption_timeout=1.5
Also, enabling logging can be super helpful to keep an eye on interruption events, and you can try out manual interruptions using
session.interrupt()
to test things out. If you’d like, I’m here to help you check whether the Speechmatics or ElevenLabs plugins support these features in your setup—just let me know! Sources: Turn detection and interruptions | LiveKit Docs | AI voice agents | LiveKit Docs | Improving voice AI's turn detection with transformers | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti...
b
Could you add examples of logging on important events? Also how would manual interruptions work, any good examples here?
t
Here are some handy examples for logging important events and handling manual interruptions in LiveKit: Logging Important Events You can easily keep track of what's happening by subscribing to different events from the agent session. Here are a few key ones and how you can log them:
Copy code
from livekit.agents.voice import AgentSession

async def entrypoint(ctx):
    session = AgentSession()

    # Log when a user starts or stops speaking
    session.on("user_state_changed", lambda user, state: print(f"User {user} state changed: {state}"))

    # Log changes in the agent's state (like listening, thinking, speaking)
    session.on("agent_state_changed", lambda state: print(f"Agent state changed: {state}"))

    # Log when new conversation items come in (speech, tool outputs, etc.)
    session.on("conversation_item_added", lambda item: print(f"New conversation item: {item}"))

    # Log user speech transcripts
    session.on("user_input_transcribed", lambda user, transcript: print(f"User {user} said: {transcript}"))

    # Log performance metrics
    session.on("metrics_collected", lambda metrics: print(f"Metrics: {metrics}"))

    await session.start(agent=YourAgent(), room=ctx.room)
Handling Manual Interruptions If you ever need to manually interrupt the agent’s speech, you can use the
agent.interrupt()
method. Here’s a quick example:
Copy code
from livekit.agents.voice import AgentSession

async def entrypoint(ctx):
    session = AgentSession()

    # Start the session
    await session.start(agent=YourAgent(), room=ctx.room)

    # Manually interrupt the agent's speech
    await session.interrupt(interrupt_all=True)  # This stops all ongoing speech
Here are some important parameters to keep in mind for interruptions: • `interrupt_all=True`: This stops all pending speech in the pipeline. • `allow_interruptions=False`: Use this if you want to prevent interruptions during specific responses. If you’d like, I’m here to help you implement these examples in your setup—just let me know! Sources: plugins/openai/src/realtime/realtime_model.ts | VoicePipelineAgent | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | pipeline-llm/interrupt_user.py
b
your suggestions did not solve the problem Interruptions are still happening, without any sound from the user
Copy code
import os
from pathlib import Path

from dotenv import load_dotenv
from livekit.agents import (
    JobContext,
    WorkerOptions,
    cli,
)
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import elevenlabs, openai, silero, speechmatics

load_dotenv(dotenv_path=Path(__file__).parent.parent / ".env")


class Anna(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""
                You are a helpful agent.
                You speak Norwegian.
                You are here to take any messages from the user.
                Do not make up any information.
                Do not ask any questions, just take messages,
                Do not say much.
            """,
            stt=speechmatics.STT(
                api_key=os.getenv("SPEECHMATICS_API_KEY",""), language="no"
            ),
            # Tried multiple values for this, but none worked
            turn_detection="vad",
            vad=silero.VAD.load(
                activation_threshold=0.5,
                min_speech_duration=0.25,
                min_silence_duration=0.80,
                prefix_padding_duration=0.15,
            ),

            allow_interruptions=True,
            # Tried multiple values for this, but none worked

            use_tts_aligned_transcript=True,
            llm=openai.LLM(model="gpt-4o"),
            tts=elevenlabs.TTS(
                voice_id=os.getenv("ELEVENLABS_VOICE_ID",""),
                language="no",
                model="eleven_turbo_v2_5",
                api_key=os.getenv("ELEVENLABS_API_KEY",""),
            ),
        )


async def entrypoint(ctx: JobContext):
    await ctx.connect()


    session: AgentSession = AgentSession(
        # Tried multiple values for this, but none worked
        allow_interruptions=False,

        # Tried multiple values for this, but none worked
        min_interruption_duration=0.5,
            min_interruption_words=2,
            false_interruption_timeout=1.5,
    )
    # Cleaner realtime captions to clients (don't wait to sync back to audio)
    # Log when a user starts or stops speaking
    session.on("user_state_changed", lambda user, state: print(f"User {user} state changed: {state}"))

    # Log changes in the agent's state (like listening, thinking, speaking)
    session.on("agent_state_changed", lambda state: print(f"Agent state changed: {state}"))

    # Log when new conversation items come in (speech, tool outputs, etc.)
    session.on("conversation_item_added", lambda item: print(f"New conversation item: {item}"))

    # Log user speech transcripts
    session.on("user_input_transcribed", lambda transcript: print(f"User said: {transcript}"))

    # Log performance metrics
    session.on("metrics_collected", lambda metrics: print(f"Metrics: {metrics}"))

    agent = Anna()

    await session.start(agent=agent, room=ctx.room)



if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
t
Hey there! To help with those interruptions happening without any user input, here are some focused troubleshooting steps and tweaks you can try: 1. Adjust Interruption Thresholds: • Try increasing
min_interruption_duration
to around 0.7-1.0 seconds to make it less sensitive to quick noises. • Set
min_interruption_words
to 3-5 if you’re using STT, so interruptions only happen when there’s meaningful input. 2. Enable Detailed Logging: Turning on detailed logs can really help spot any conflicts or misconfigurations. For example:
Copy code
import logging
logging.basicConfig(level=logging.DEBUG)
Keep an eye out for warnings about conflicting settings or anything unexpected. 3. Review Turn Detection Mode: • If you’re using
turn_detection="vad"
, make sure the VAD parameters fit your environment. Something like this might work: • You might also want to try the Turn Detection Model for interruptions that understand context better, especially if there’s a lot of background noise. 4. False Interruption Recovery: • Turn on
resume_false_interruption=True
so the agent can pick up speaking again if it detects an interruption but no real input follows. • Setting
false_interruption_timeout
to about 1.5 seconds usually works well for this. 5. Test and Monitor: Here are some event listeners you can use to keep an eye on interruptions and help with debugging:
Copy code
session.on("user_state_changed", lambda user, state: print(f"User {user} state changed: {state}"))
session.on("agent_state_changed", lambda state: print(f"Agent state changed: {state}"))
If you want, I’m happy to help you implement these tweaks or dig into the logs together to find out what’s going on. Just let me know! Sources: Improving voice AI's turn detection with transformers | AI voice agents | LiveKit Docs | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | VoicePipelineAgent | LiveKit Docs | VoicePipelineAgent | LiveKit Docs
b
all converstation items from the agaent are
interrupted=True
t
Hey there! If you’re noticing that all conversation items from the agent are marked as
interrupted=True
, it usually means interruptions are being triggered unintentionally. No worries though—I’ve got some steps to help you figure this out and fix it: 1. Check for Manual Interruptions: Take a look at your code to see if there are any calls to
session.interrupt()
or
agent.interrupt()
that might be firing off when they shouldn’t. For example:
Copy code
@ctx.room.on("participant_connected")
def on_participant_connected(participant):
    agent.interrupt(interrupt_all=True)  # This might be causing interruptions you didn’t expect
2. Review VAD and STT Settings: • Try increasing
min_interruption_duration
to around 0.7-1.0 seconds so short noises don’t accidentally trigger interruptions. • Set
min_interruption_words
to 3-5, which means more words need to be transcribed before an interruption happens. • Adjust
min_endpointing_delay
to fine-tune how silence is detected. 3. Verify Audio Output and Transcription Sync: Make sure the audio playback and transcription are in sync, because if they’re out of sync, it might incorrectly mark items as
interrupted
. 4. Use Event Logs for Debugging: Keep an eye on events like
agent_state_changed
,
playback_finished
, and
conversation_item_added
to see exactly when interruptions happen. For example:
Copy code
session.on("playback_finished", lambda event: print(f"Playback finished: interrupted={event.interrupted}"))
If you’d like, I’m here to help you review your interruption setup or dig into specific events together. Just let me know! Sources: examples/voice_agents/session_close_callback.py | Turn detection and interruptions | LiveKit Docs | VoicePipelineAgent | LiveKit Docs
b
what about manually control the interruptions ?
t
Hey there! You can take control of interruptions in LiveKit with these handy methods: 1. Manually Trigger Interruptions: Just use
session.interrupt()
to pause the agent’s current speech. If you want to stop all pending speeches in the queue, try this:
Copy code
session.interrupt(interrupt_all=True)
This comes in super handy when someone joins or leaves a room and you want to pause the agent. 2. Prevent Interruptions for Specific Outputs: If you want the agent to finish a message without being cut off, set
allow_interruptions=False
when calling
session.say()
or
generate_reply()
like this:
Copy code
speech_handle = await session.say("This message cannot be interrupted.")
3. Configure Interruption Behavior: • `allow_interruptions`: Turn user interruptions on or off globally (default is
True
). • `min_interruption_duration`: Decide the minimum speech length before interruptions can happen (default is 0.5 seconds). • `min_interruption_words`: Set the minimum number of words transcribed before allowing interruptions (default is 0). 4. Use Manual Turn Management: If you want to manage the conversation flow yourself, just set
turn_detection="manual"
when creating your `AgentSession`:
Copy code
session = AgentSession(turn_detection="manual")

# Start listening manually
session.input.set_audio_enabled(True)

# Stop listening and process input
session.input.set_audio_enabled(False)
session.commit_user_turn()
This works great for push-to-talk setups or when you’re handling conversations with multiple participants. If you want, I’m here to help you get these set up or answer any questions you might have! Sources: pipeline-llm/interrupt_user.py | Agent speech and audio | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | Turn detection and interruptions | LiveKit Docs | VoicePipelineAgent | LiveKit Docs
b
how would this look with session events to turn it on/off when the user speaks ?
t
Here’s a friendly little example showing how you can use session events to dynamically enable or disable interruptions while the user is speaking: Example Implementation:
Copy code
import asyncio
import re
from livekit.agents.voice import AgentSession

# Helper function to count sentences based on punctuation
def count_sentences(transcript):
    return len(re.findall(r'[.!?]', transcript))

async def entrypoint(ctx):
    session = AgentSession()

    # Buffer to accumulate user transcripts
    transcript_buffer = []

    # Event listener for user input transcription
    session.on("user_input_transcribed", lambda user, transcript: handle_transcription(user, transcript, session, transcript_buffer))

    await session.start(agent=YourAgent(), room=ctx.room)

# Function to handle user transcription events
def handle_transcription(user, transcript, session, transcript_buffer):
    # Add interim transcripts to the buffer
    transcript_buffer.append(transcript)

    # Count sentences in the buffer
    sentence_count = count_sentences(" ".join(transcript_buffer))

    # If sentence count exceeds threshold, interrupt and respond
    if sentence_count >= 3:
        asyncio.create_task(interrupt_and_respond(session, transcript_buffer))

async def interrupt_and_respond(session, transcript_buffer):
    # Interrupt the agent's current speech
    await session.interrupt()

    # Respond with a polite interruption message
    await session.say("Please allow me to respond before continuing.", allow_interruptions=False)

    # Clear the transcript buffer
    transcript_buffer.clear()
Key Points: •
session.interrupt()
gently stops the agent's current speech when the user has spoken enough (3 sentences here). •
allow_interruptions=False
makes sure the agent’s response gets through without being cut off. • The
user_input_transcribed
event keeps an eye on what the user is saying in real-time. If you’d like, I’m here to help you tweak this example or tailor it just right for your needs. Just let me know! Sources: basics/interrupts_user.py | Turn detection and interruptions | LiveKit Docs | Agent speech and audio | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
b
seems that the problem is elevnlabs as other tts providers work fine ?
t
It looks like the issue might be connected to ElevenLabs TTS. No worries—here are some friendly steps to help you troubleshoot and fine-tune those interruptions: 1. Double-Check Your Interruption Settings: • Make sure
allow_interruptions=True
is set in your
AgentSession
so users can jump in smoothly. • Try setting
min_interruption_duration
between 0.7 and 1.0 seconds to prevent accidental triggers from brief noises. • Use
min_interruption_words
(around 3-5) to ensure interruptions happen only with meaningful input. 2. Take a Peek at ElevenLabs TTS Settings: • If your ElevenLabs TTS supports aligned transcription, turn on
use_tts_aligned_transcript=True
. • Also, check that
sync_alignment
and
auto_mode
are enabled for smooth real-time streaming and transcript alignment. 3. Tweak Timeout Parameters: • Set
false_interruption_timeout
to around 1.5-2.0 seconds to handle any false interruptions more gracefully. • Enable
resume_false_interruption=True
so the agent can pick up speaking again if an interruption turns out to be a false alarm. 4. Keep an Eye on Logs and Telemetry: Watching out for events like
agent_false_interruption
can really help you spot if interruptions are being triggered by mistake. This insight can guide you in fine-tuning your setup. If you’d like, I’m here to help review your ElevenLabs TTS configuration or dig into any specific interruption behaviors you’re seeing. Just let me know! Sources: livekit-agents/livekit/agents/voice/agent.py | plugins/elevenlabs/src/tts.test.ts | ElevenLabs TTS integration guide | LiveKit Docs
b
Copy code
voice_id (str): Voice ID. Defaults to `DEFAULT_VOICE_ID`.
            voice_settings (NotGivenOr[VoiceSettings]): Voice settings.
            model (TTSModels | str): TTS model to use. Defaults to "eleven_turbo_v2_5".
            api_key (NotGivenOr[str]): ElevenLabs API key. Can be set via argument or `ELEVEN_API_KEY` environment variable.
            base_url (NotGivenOr[str]): Custom base URL for the API. Optional.
            streaming_latency (NotGivenOr[int]): Optimize for streaming latency, defaults to 0 - disabled. 4 for max latency optimizations. deprecated
            inactivity_timeout (int): Inactivity timeout in seconds for the websocket connection. Defaults to 300.
            auto_mode (bool): Reduces latency by disabling chunk schedule and buffers. Sentence tokenizer will be used to synthesize one sentence at a time. Defaults to True.
            word_tokenizer (NotGivenOr[tokenize.WordTokenizer | tokenize.SentenceTokenizer]): Tokenizer for processing text. Defaults to basic WordTokenizer.
            enable_ssml_parsing (bool): Enable SSML parsing for input text. Defaults to False.
            chunk_length_schedule (NotGivenOr[list[int]]): Schedule for chunk lengths, ranging from 50 to 500. Defaults are [120, 160, 250, 290].
            http_session (aiohttp.ClientSession | None): Custom HTTP session for API requests. Optional.
            language (NotGivenOr[str]): Language code for the TTS model, as of 10/24/24 only valid for "eleven_turbo_v2_5".
            sync_alignment (bool): Enable sync alignment for the TTS model. Defaults to True.
t
Thanks so much for sharing the ElevenLabs TTS configuration details! Based on what you’ve provided, here are a few friendly tips to help optimize interruptions and smooth out any issues you might be facing: 1. Enable Sync Alignment: • Make sure
sync_alignment=True
is set. This helps sync the TTS output with the transcription, which can really improve how interruptions are handled. 2. Use Auto Mode: • Keep
auto_mode=True
turned on. It lowers latency by synthesizing one sentence at a time—perfect for real-time chats. 3. Adjust Inactivity Timeout: • Check that
inactivity_timeout
is set to a good length (like 300 seconds) to keep your WebSocket connection steady during longer sessions. 4. SSML Parsing: • If you’re using SSML for your text input, turning on
enable_ssml_parsing=True
will make sure those SSML tags are handled just right. 5. Streaming Latency: • Even though
streaming_latency
is deprecated, double-check it’s not set to a non-default value that could clash with
auto_mode
. If you’d like, I’d be happy to help you implement these tweaks or troubleshoot anything else with your ElevenLabs TTS setup. Just let me know!
b
after downgrading to v.1.2.6, i can see the following error wth the library
Copy code
2025-09-07 12:45:08,958 - ERROR livekit.agents - Error in _tts_inference_task
Traceback (most recent call last):
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/livekit/agents/tts/tts.py", line 529, in __anext__
    val = await self._event_aiter.__anext__()
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
StopAsyncIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs
    return await fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
    return await func(*args, **kwargs)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/livekit/agents/voice/generation.py", line 212, in _tts_inference_task
    async for audio_frame in tts_node:
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/livekit/agents/voice/agent.py", line 408, in tts_node
    async for ev in stream:
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/livekit/agents/tts/tts.py", line 532, in __anext__
    raise exc  # noqa: B904
    ^^^^^^^^^
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
    return await func(*args, **kwargs)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/larsen/Code/noque-agent/.venv/lib/python3.12/site-packages/livekit/agents/tts/tts.py", line 368, in _main_task
    raise APIError(f"no audio frames were pushed for text: {self._pushed_text}")
t
Hey there! Those errors
StopAsyncIteration
and
APIError: no audio frames were pushed for text
in LiveKit v1.2.6 with ElevenLabs TTS usually pop up when the TTS engine can’t generate audio. No worries though—here are some friendly steps to help you troubleshoot and get things back on track: 1. Validate Input Text: • Make sure the text you’re sending to the TTS engine isn’t empty or just whitespace. The integration actually checks for
text.strip()
before it processes, so it’s a good place to start. 2. Verify SSML Formatting: • If you’re using SSML with
enable_ssml_parsing=True
, double-check that all your tags are properly formatted and closed. For example: 3. Check API Configuration: • Make sure your
ELEVEN_API_KEY
environment variable is set up correctly and is valid. • Also, confirm that your voice ID, model parameters, and language codes are all correct and supported. 4. Implement Error Handling: • Try wrapping your code in try-except blocks to catch errors like
StopAsyncIteration
and
APIError
. This way, you can handle issues smoothly or try again if needed. 5. Use Retry Mechanisms: • Consider setting up retry attempts using
APIConnectOptions
to help with any temporary network hiccups. If you’d like, I’m here to help you walk through these steps or dig deeper into what’s going on. Just let me know! Sources: livekit-agents/livekit/agents/voice/agent.py | ElevenLabs TTS integration guide | LiveKit Docs