how to reliably combine speech chunks from Deepgra...
# ask-ai
b
how to reliably combine speech chunks from Deepgram STT to create a full user transcript for a turn while using OpenAI realtime model as LLM?
t
Thanks for reaching out, mateuszkasprowicz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd be happy to guide you through combining speech chunks from Deepgram STT into a full user transcript for a turn while using the OpenAI Realtime model as the LLM. Here’s a simple way to approach it: 1. Start by using LiveKit's turn detection system with Deepgram as your STT provider. Make sure to configure OpenAI's Realtime model to turn off its built-in turn detection and audio transcription features. 2. Keep track of the transcript by collecting the final transcript chunks from Deepgram. You can build the full transcript for each turn by concatenating these chunks. 3. Listen for events like
user_input_transcribed
to know when a turn ends and process the complete user transcript accordingly. 4. If you want to check the transcript while a turn is still active, you can access it through the
current_transcript
property. This setup helps ensure you get accurate transcriptions from Deepgram and smooth integration with OpenAI's Realtime model for generating responses. If you'd like, I’m here to provide more details or share some code examples to make this even clearer! Sources: LiveKit turn detector plugin | LiveKit Docs | livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt_v2.py | pipeline-stt/transcriber/README.md
b
give me some code examples. One caveat is I'd like to use OpenAI's semantic vad turn detection
t
Thank you for reaching out! I wanted to share that using OpenAI's Semantic VAD for turn detection alongside Deepgram STT for transcription isn’t supported at the moment. This is because OpenAI's Semantic VAD needs the audio to be processed directly through OpenAI's Realtime API, which means it doesn’t work with external transcription services like Deepgram. If you're interested in using Deepgram STT for transcription, a great option is to set up LiveKit's turn detection models (like
MultilingualModel
) to manage turn detection. Here's a friendly example to guide you:
Copy code
from livekit.agents import AgentSession
from livekit.plugins import deepgram, openai, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel

session = AgentSession(
    vad=silero.VAD.load(),
    stt=deepgram.STT(),
    llm=openai.realtime.RealtimeModel(
        voice="alloy",
        turn_detection=None,                     # Disable OpenAI's turn detection
        input_audio_transcription=None,          # Use Deepgram for transcription
    ),
    turn_detection=MultilingualModel(),          # Use LiveKit’s turn detector on Deepgram text
)
On the other hand, if you’d like to use OpenAI's Semantic VAD, it’s important to let OpenAI handle both transcription and turn detection. That means Deepgram STT wouldn’t be part of that setup. Please feel free to reach out if you want any help deciding which route works best for you or if you have any other questions—I’m here to support you! Sources: livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt_v2.py | examples/src/push_to_talk.ts | LLM Integration & Real-time Models | livekit/livekit_composite | DeepWiki
b
how to parametrize silero vad and EnglishModel turn detection to approximately match these OpenAI's turn detection settings
Copy code
TurnDetection(
                type="semantic_vad",
                eagerness="low",
                create_response=True,
                interrupt_response=True,
            ),
t
To help you approximate OpenAI's Semantic VAD settings using Silero VAD and EnglishModel turn detection, here’s a friendly guide on how you can configure it: 1. Silero VAD Configuration Try adjusting these parameters to mimic a "low eagerness" setting by increasing the silence duration before ending a turn:
Copy code
vad = silero.VAD.load(
    min_silence_duration=1.2,       # Wait a bit longer before ending the turn
    activation_threshold=0.45,      # Slightly lower threshold to catch softer speech
    min_speech_duration=0.05,
    prefix_padding_duration=0.5
)
2. EnglishModel Turn Detection For a more natural feel, use the EnglishModel for language-aware turn detection. It works on the transcribed text to spot natural sentence endings:
Copy code
session = voice.AgentSession(
    vad=vad,
    stt=deepgram.STT(),
    llm=openai.realtime.RealtimeModel(
        turnDetection=None,           # Turn off OpenAI's Semantic VAD here
        inputAudioTranscription=None  # Optional: turn off to save on costs
    ),
    turn_detection=livekit.turnDetector.EnglishModel()
)
3. Default Behaviors • Create Response: This is automatically enabled in LiveKit when turn detection is on. • Interrupt Response: Users can interrupt the agent mid-speech by default, which is super handy! While this setup might not capture every nuance of OpenAI’s semantic understanding, it’s a great way to get close with delayed turn endings and natural language awareness. If you have any questions or want to dive deeper, I’m here to help! Sources: LLM Integration & Real-time Models | livekit/livekit_composite | DeepWiki | examples/src/multi_agent.ts | livekit-plugins/livekit-plugins-silero/livekit/plugins/silero/vad.py | Turn detection and interruptions | LiveKit Docs
b
with this setup
Copy code
class Interviewer(Agent):
    def __init__(self, *args, **kwargs) -> None:
        tts = agents.tts.StreamAdapter(
            tts=openai.TTS(model="gpt-4o-mini-tts", voice=VOICE, speed=1)
        )

        stt = deepgram.STT(model="nova-2", language="en")

        llm = openai.realtime.RealtimeModel(
            model="gpt-4o-mini-realtime-preview",
            voice=VOICE,
            speed=1,
            tool_choice="none",
            modalities=["audio"],
            input_audio_transcription=None,
            turn_detection=None,
        )
        vad = silero.VAD.load(
            min_silence_duration=1.2,  # Wait a bit longer before ending the turn
            activation_threshold=0.45,  # Slightly lower threshold to catch softer speech
            min_speech_duration=0.05,
            prefix_padding_duration=0.5,
        )
        turn_detection = EnglishModel()

        super().__init__(
            *args,
            **kwargs,
            llm=llm,
            tts=tts,
            stt=stt,
            vad=vad,
            turn_detection=turn_detection,
        )
   async def stt_node(
        self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings
    ) -> AsyncIterable[stt.SpeechEvent] | None:
        async def filtered_audio():
            async for frame in audio:
                yield frame

        async for event in Agent.default.stt_node(self, filtered_audio(), model_settings):
            if event.type == stt.SpeechEventType.FINAL_TRANSCRIPT:
                speech_analyzer.analyze(event)
                logger.info(f"Speech analyzer: {speech_analyzer.get_current_stats()}")
            yield event
I'm not seeing user's transcript
t
Let's make sure your user's transcript shows up properly in your setup by checking a few things together: 1. Deepgram STT Integration: Could you please confirm that Deepgram STT is set up correctly and is receiving audio input? It's important that the
stt_node
method is generating
FINAL_TRANSCRIPT
events as expected. 2. Turn Detection: Make sure the
EnglishModel
is active and accurately processing the transcriptions coming from Deepgram STT. This model depends on the STT output to identify when turns are completed. 3. Speech Analyzer: Take a look at your
speech_analyzer.analyze(event)
method to verify it’s handling and logging the transcript properly. Adding some debug logs to check if
event.alternatives[0].text
is being captured can be really helpful. 4. LLM Turn Detection: Please check that OpenAI's turn detection is turned off (
turn_detection=None
) to prevent any conflicts with the EnglishModel. If you’ve gone through these steps and things still aren’t working quite right, just let me know! I’m here to help you dig deeper and figure out exactly what’s going on.
b
1. Yes, it does e.g.,
2025-10-10 10:55:57,306 - DEBUG livekit.agents - received user transcript {"user_transcript": "Validate input,", "language": "en", "pid": 52159, "job_id": "AJ_m9gvi36LpZCL"} 2025-10-10 10:55:59,485 - INFO livekit.agents - STT metrics {"model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.0, "pid": 52159, "job_id": "AJ_m9gvi36LpZCL"}
3. it's correct
4. yes
t
I'm here to help you get those missing user transcripts sorted out! Let's walk through a few things together to make sure everything is set up just right: 1. Ensure Separate STT Plugin: Could you please check that Deepgram STT is included in your configuration and that it’s providing both interim and final transcription results independently from the LLM? This is key to capturing your transcripts accurately. 2. Configure Synchronization: Try setting
syncTranscription: false
in your output options. This helps avoid any delays in getting the transcripts delivered to you. 3. Verify Room Settings: Take a moment to confirm that
transcription_enabled
isn’t disabled in your room output options, as that could prevent transcription from being forwarded properly. 4. Check Component Integration: Make sure Silero VAD is correctly detecting speech and triggering the Deepgram STT pipeline—this connection is crucial for processing the transcriptions. 5. Monitor Event Flow: Lastly, please verify that speech events from Deepgram, like
FINAL_TRANSCRIPT
, are being captured and forwarded correctly by the agent session. Following these steps should help your user transcripts show up as expected. If you run into any hiccups or want to dive deeper into any part of the setup, just let me know—I’m here to support you every step of the way! Sources: examples/src/basic_tool_call_agent.ts | livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt_v2.py | Realtime model plugins | LiveKit Docs
b
2025-10-10 110428,013 - DEBUG livekit.agents - received user transcript {"user_transcript": "So, um, I would use HTTPS", "language": "en", "pid": 53848, "job_id": "AJ_TRdwagG7c3mT"} I have logs like this yet no user transcript appears in the session history
t
Hi there! If you’re seeing user transcripts logged as received but they’re not showing up in the session history, don’t worry—this can happen for a few common reasons. Let me walk you through them and how you can address each one: 1. Finality Requirement: Only transcripts marked as
FINAL_TRANSCRIPT
are actually added to the session history. So, it’s important to check that the transcripts you’re seeing are final and not just interim results. 2. Content Validity: Sometimes transcripts that contain only whitespace or incomplete content won’t be added to the history. It’s a good idea to verify that the transcripts you receive have meaningful content. 3. Event Handling: The
conversation_item_added
event fires only when a transcript is officially committed to the history. Interim results might be logged temporarily but won’t be stored permanently. 4. Persistence: Just a heads up—LiveKit doesn’t offer built-in long-term storage for session history. To keep transcripts beyond the session, you’ll want to set up a persistence layer by saving the
session.history
property to a database or file at the end of the session. If you’d like, I’m here to help you double-check these points or guide you through setting up a persistence solution. Just let me know! Sources: Events and error handling | LiveKit Docs | Session recording and transcripts | LiveKit Docs | Sending text | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
b
it looks like I can't use STT user transcription with realtime models. Take a look at this
AgentActivity
method:
Copy code
@utils.log_exceptions(logger=logger)
    async def _user_turn_completed_task(
        self, old_task: asyncio.Task[None] | None, info: _EndOfTurnInfo
    ) -> None:
        if old_task is not None:
            # We never cancel user code as this is very confusing.
            # So we wait for the old execution of on_user_turn_completed to finish.
            # In practice this is OK because most speeches will be interrupted if a new turn
            # is detected. So the previous execution should complete quickly.
            await old_task

        # When the audio recognition detects the end of a user turn:
        #  - check if realtime model server-side turn detection is enabled
        #  - check if there is no current generation happening
        #  - cancel the current generation if it allows interruptions (otherwise skip this current
        #  turn)
        #  - generate a reply to the user input

        # interrupt all background speeches and wait for them to finish to update the chat context
        await asyncio.gather(*self._interrupt_background_speeches(force=False))

        if isinstance(self.llm, llm.RealtimeModel):
            if self.llm.capabilities.turn_detection:
                return

            if self._rt_session is not None:
                self._rt_session.commit_audio()

        if self._current_speech is not None:
            if not self._current_speech.allow_interruptions:
                logger.warning(
                    "skipping reply to user input, current speech generation cannot be interrupted",
                    extra={"user_input": info.new_transcript},
                )
                return
            await self._interrupt_paused_speech(self._interrupt_paused_speech_task)

            if self._current_speech:
                await self._current_speech.interrupt()

            if self._rt_session is not None:
                self._rt_session.interrupt()

        user_message = llm.ChatMessage(
            role="user",
            content=[info.new_transcript],
            transcript_confidence=info.transcript_confidence,
        )

        if self._scheduling_paused:
            logger.warning(
                "skipping on_user_turn_completed, speech scheduling is paused",
                extra={"user_input": info.new_transcript},
            )
            if self._session._closing:
                self._agent._chat_ctx.items.append(user_message)
                self._session._conversation_item_added(user_message)
            return

        # create a temporary mutable chat context to pass to on_user_turn_completed
        # the user can edit it for the current generation, but changes will not be kept inside the
        # Agent.chat_ctx
        temp_mutable_chat_ctx = self._agent.chat_ctx.copy()
        start_time = time.time()
        try:
            await self._agent.on_user_turn_completed(
                temp_mutable_chat_ctx, new_message=user_message
            )
        except StopResponse:
            return  # ignore this turn
        except Exception:
            logger.exception("error occured during on_user_turn_completed")
            return

        callback_duration = time.time() - start_time

        if isinstance(self.llm, llm.RealtimeModel):
            # ignore stt transcription for realtime model
            user_message = None  # type: ignore
        elif self.llm is None:
            return  # skip response if no llm is set

        if self._scheduling_paused:
            logger.warning(
                "skipping reply to user input, speech scheduling is paused",
                extra={"user_input": info.new_transcript},
            )
            if user_message and self._session._closing:
                self._agent._chat_ctx.items.append(user_message)
                self._session._conversation_item_added(user_message)
            return

        speech_handle: SpeechHandle | None = None
        if preemptive := self._preemptive_generation:
            # make sure the on_user_turn_completed didn't change some request parameters
            # otherwise invalidate the preemptive generation
            if (
                preemptive.info.new_transcript == user_message.text_content
                and preemptive.chat_ctx.is_equivalent(temp_mutable_chat_ctx)
                and preemptive.tools == self.tools
                and preemptive.tool_choice == self._tool_choice
            ):
                speech_handle = preemptive.speech_handle
                self._schedule_speech(speech_handle, priority=SpeechHandle.SPEECH_PRIORITY_NORMAL)
                logger.debug(
                    "using preemptive generation",
                    extra={"preemptive_lead_time": time.time() - preemptive.created_at},
                )
            else:
                logger.warning(
                    "preemptive generation enabled but chat context or tools have changed after `on_user_turn_completed`",  # noqa: E501
                )
                preemptive.speech_handle._cancel()

            self._preemptive_generation = None

        if speech_handle is None:
            # Ensure the new message is passed to generate_reply
            # This preserves the original message_id, making it easier for users to track responses
            speech_handle = self._generate_reply(
                user_message=user_message, chat_ctx=temp_mutable_chat_ctx
            )

        if self._user_turn_completed_atask != asyncio.current_task():
            # If a new user turn has already started, interrupt this one since it's now outdated
            # (We still create the SpeechHandle and the generate_reply coroutine, otherwise we may
            # lose data like the beginning of a user speech).
            # await the interrupt to make sure user message is added to the chat context before the new task starts
            await speech_handle.interrupt()

        metadata: Metadata | None = None
        if isinstance(self.turn_detection, str):
            metadata = Metadata(model_name="unknown", model_provider=self.turn_detection)
        elif self.turn_detection is not None:
            metadata = Metadata(
                model_name=self.turn_detection.model, model_provider=self.turn_detection.provider
            )

        eou_metrics = EOUMetrics(
            timestamp=time.time(),
            end_of_utterance_delay=info.end_of_utterance_delay,
            transcription_delay=info.transcription_delay,
            on_user_turn_completed_delay=callback_duration,
            speech_id=speech_handle.id,
            last_speaking_time=info.last_speaking_time,
            metadata=metadata,
        )
        self._session.emit("metrics_collected", MetricsCollectedEvent(metrics=eou_metrics))
is there a workaround?
t
I understand you're looking to work around the limitation in the
_user_turn_completed_task
method and want to use STT-based user transcription with realtime models. A helpful approach is to integrate a separate STT plugin alongside the realtime model. This way, you can manage transcription and turn detection separately from the realtime model's internal processing, which often makes things smoother. Here are some friendly steps to guide you through the implementation: 1. Disable Turn Detection in Realtime Model: You’ll want to set
turn_detection=None
and
input_audio_transcription=None
in the realtime model configuration. 2. Add a Separate STT Plugin: Consider using a streaming-compatible STT plugin like Deepgram, which provides both interim and final transcription results. 3. Configure a Turn Detector: You can use a model such as
MultilingualModel
to detect turns based on the STT output. Here’s an example configuration to illustrate this:
Copy code
from livekit.agents import AgentSession
from livekit.plugins import deepgram, openai, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel

session = AgentSession(
    vad=silero.VAD.load(),
    stt=deepgram.STT(model="nova-3", language="multi"),
    turn_detection=MultilingualModel(),
    llm=openai.realtime.RealtimeModel(
        voice="alloy",
        turn_detection=None,  # Disable RT model’s VAD
        input_audio_transcription=None,  # Disable transcription from RT model
    ),
)
This setup lets the STT plugin handle the transcription for turn detection and user transcript management, while the realtime model can focus on generating responses. If you have any questions or want me to walk you through any part of this, please don’t hesitate to ask—I’m here to help! Sources: examples/voice_agents/realtime_turn_detector.py | Pipeline nodes and hooks | LiveKit Docs | LiveKit turn detector plugin | LiveKit Docs | Realtime model plugins | LiveKit Docs
b
but that's not the point - the thing there's no way to plug in user messages from STT while using a realtime model. STT generates transcription correctly but they are not added to the session history. Should I add them somewhere manually as a workaround?
t
If you'd like to manually add STT-generated user messages to the session history while using a realtime model, you can do so with the
update_chat_ctx
method. This way, your messages are securely added to the chat context and will be taken into account in future conversations. Here's a simple example to guide you:
Copy code
# Copy the current chat context
chat_ctx = self._rt_session.chat_ctx.copy()

# Add the STT-generated user message
msg = chat_ctx.add_message(role="user", content=stt_text)

# Update the chat context permanently
await self._rt_session.update_chat_ctx(chat_ctx)

# Also update the agent's chat context for consistency
self._agent._chat_ctx.items.append(msg)
self._session._conversation_item_added(msg)
This method helps make sure your STT-generated messages are part of the session history and ready to be used in upcoming interactions. If you have any questions or need a hand with this, feel free to reach out—I'm here to help! Sources: plugins/openai/src/realtime/realtime_model.ts | Realtime model plugins | LiveKit Docs | OpenAI Realtime API plugin guide | LiveKit Docs | Azure OpenAI Realtime API and LiveKit | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs
b
in which part of the pipeline should I add this? where do I have access for the entire message for a user's turn?
t
I'm glad you asked! The best way to access the entire user message for a turn and add it to the session history is by using the
on_user_turn_completed
method. This method is called right after the user's turn ends, giving you access to the
new_message
object, which holds the full transcribed user input as a
llm.ChatMessage
. Here’s a simple way to do it: 1. Grab the
new_message
object inside
on_user_turn_completed
. 2. Then, use the
update_chat_ctx
method to add this message to the session history permanently:
Copy code
async def on_user_turn_completed(self, chat_ctx, new_message):
    # Add the user message to the chat context
    updated_ctx = self._rt_session.chat_ctx.copy()
    updated_ctx.add_message(role="user", content=new_message.text_content)

    # Update the session history
    await self._rt_session.update_chat_ctx(updated_ctx)

    # Optionally log or process the message
    print("User message added to history:", new_message.text_content)
This way, the user’s message is safely stored in the session history and ready for any future interactions. If you’d like me to walk you through any part of this or if you have more questions, just let me know—I’m here to help! Sources: Pipeline nodes and hooks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py | Session recording and transcripts | LiveKit Docs | How to capture real-time agent transcriptions during conversations | Turn detection and interruptions | LiveKit Docs