I'm using Open AI Realtime model (gpt-4o-mini-real...
# ask-ai
b
I'm using Open AI Realtime model (gpt-4o-mini-realtime-preview) for a short 1:1 conversations with the user. In the background, I'd like to use STT model that allows me to analyze user speech in more detail - I'd love more info on words/sentences timestamps, more reliably include filler words, etc. I don't need these metrics in realtime - I will calculate them after the conversation finishes. I solely need enough data after the conversation. How to orchestrate this?
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.
To help you orchestrate post-conversation speech-to-text (STT) analysis with detailed timestamps and filler words, you can definitely use LiveKit's STT capabilities. Let me walk you through how to set it up step-by-step: 1. Configure the STT Model:
from livekit.plugins.deepgram import STT
stt = STT(filler_words=True, interim_results=True, endpointing_ms=25)
This setup enables filler words and interim results, which really helps improve accuracy. 2. Process Transcriptions:
async def transcribe_track(participant, track):
audio_stream = rtc.AudioStream(track)
stt_forwarder = transcription.STTSegmentsForwarder(room=ctx.room, participant=participant, track=track)
stt_stream = stt_impl.stream()
async for ev in audio_stream:
stt_stream.push_frame(ev.frame)
3. Handle Transcription Events:
async def _forward_transcription(stt_stream, stt_forwarder):
async for ev in stt_stream:
if ev.type == stt.SpeechEventType.INTERIM_TRANSCRIPT:
logger.debug(f" -> {ev.alternatives[0].text}")
elif ev.type == stt.SpeechEventType.FINAL_TRANSCRIPT:
logger.debug(f" ~> {ev.alternatives[0].text}")
stt_forwarder.update(ev)
Also, if you want transcription timing that aligns nicely with TTS, you can use plugins like ElevenLabs or Cartesia. Just enable this feature by setting
use_tts_aligned_transcript=True
in your AgentSession configuration. Then, you’ll be able to access timing details through
TimedString
objects, which include
start_time
and
end_time
properties. Please feel free to reach out if you have any questions or need a hand with anything else—I’m here to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/stt.py | main.py | Text and transcriptions | LiveKit Docs
b
can you elaborate on which part I should initiate the STT model and transcription processing? somewhere in the Agent definition or inside the entrypoint function?
t
Hi there! To make sure everything runs smoothly, it’s best to start the STT model and transcription processing in the entrypoint function when you create an
AgentSession
, instead of placing it inside the agent definition. This way, the STT model is set up correctly and linked directly to your session. Here’s a friendly example to guide you:
Copy code
async def entrypoint(ctx: JobContext):
    session = AgentSession(
        vad=silero.VAD.load(),
        stt=deepgram.STT(model="nova-3"),
        llm=openai.LLM(model="gpt-4o-mini"),
        tts=elevenlabs.TTS(),
    )
    await session.start(agent=MyAgent(), room=ctx.room)
In this setup: • The STT model is passed as a parameter when creating the
AgentSession
. • The
entrypoint
function acts as the main connector, linking your agent to the LiveKit room and kicking off the session. While your agent class can still define methods like
stt_node()
for more advanced audio preprocessing if you want, the key is that the actual STT model instance comes through the session in the
entrypoint
. If you’d like me to walk you through this further or provide more examples, just let me know—I’m here to help! Sources: Pipeline nodes and hooks | LiveKit Docs | examples/voice_agents/long_running_function.py | Job lifecycle | LiveKit Docs
b
but remember I'm using OpenAI realtime not a STT-LLM-TTS pipeline
t
Since you're using the OpenAI Realtime model and not a full STT-LLM-TTS pipeline, you'll want to set up a separate STT plugin for post-conversation analysis. I’m here to guide you through the steps to make this happen smoothly: 1. Disable Built-in Transcription and Turn Detection: Let's configure the Realtime model to focus just on low-latency audio interaction:
Copy code
from livekit.plugins.openai.realtime import RealtimeModel

llm = RealtimeModel(
    voice="alloy",
    modalities=["audio"],
    input_audio_transcription=None,  # Disables internal transcription
    turn_detection=None  # Disables built-in VAD
)
2. Add a Separate STT Plugin: You can use an external STT service like Deepgram or OpenAI Whisper for transcription:
Copy code
from livekit.plugins import deepgram

stt = deepgram.STT(
    language="en",
    detect_language=True
)
3. Integrate into the Entrypoint Function: Here’s how to set up your session in the entrypoint function:
Copy code
from livekit.agents import AgentSession, JobContext

async def entrypoint(ctx: JobContext):
    session = AgentSession(
        allow_interruptions=True,
        stt=stt,
        llm=llm
    )
    await session.start(agent=MyAgent(), room=ctx.room)
4. Post-Conversation Analysis: You can capture transcripts using event listeners like this:
Copy code
@stt.on("transcription")
async def on_transcription(event):
    if event.is_final:
        print(f"Final transcript: {event.alternatives[0].text}")
        # Store for analysis
This setup will let you analyze detailed transcription data after your conversation, while still enjoying the benefits of the Realtime model for live interactions. If you have any questions or want me to walk you through any part, just let me know—I’m happy to help! Sources: LiveKit turn detector plugin | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | Turn detection and interruptions | LiveKit Docs | OpenAI Realtime API plugin guide | LiveKit Docs | Azure OpenAI Realtime API and LiveKit | LiveKit Docs
b
and with this setup I'd still have a full history available in
session.history
?
t
Absolutely! The
session.history
will capture the entire conversation history both during and after your session, even when you're using the OpenAI Realtime model alongside a separate STT plugin. This means it keeps track of all the text-based exchanges as your conversation unfolds. Here are a few important things to keep in mind: • Independent of STT Plugin: Using a separate STT plugin won’t impact how
session.history
gathers your conversation history. • Text-Based History: The history focuses on text and includes every message exchanged throughout the session. • Pre-Loading History: If you want to bring in previous conversation context, you can do so by initializing it with
llm.ChatContext
before starting your session. Just a heads-up—loading a lot of history might make the Realtime model lean more towards text responses rather than audio. If you have any more questions or need a hand with anything else, feel free to ask—I’m here to help! Sources: Session recording and transcripts | LiveKit Docs | Realtime model plugins | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | LiveKit turn detector plugin | LiveKit Docs | OpenAI Realtime API plugin guide | LiveKit Docs
b
so it seems it's not entirely true
Copy code
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=TurnDetection(
                type="semantic_vad",
                eagerness="low",
                create_response=True,
                interrupt_response=True,
            ),
        )
with these two models initiated I'm getting correct logs
Copy code
2025-10-09 21:40:43,296 - INFO livekit.agents - STT metrics {"model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.05, "pid": 22188, "job_id": "AJ_pfumDFSmeGNk"}
2025-10-09 21:40:45,517 - DEBUG livekit.agents - received user transcript {"user_transcript": "follow OWASP guidelines.", "language": "en", "pid": 22188, "job_id": "AJ_pfumDFSmeGNk"}
but in the
session.history
I'm only seeing assistant messages
t
Thanks so much for reaching out! I understand that seeing only assistant messages in
session.history
can be a bit confusing. This happens because the OpenAI Realtime model and the separate STT plugin work independently. The Realtime model doesn’t automatically pull in user transcripts from the external STT into the session history. Let me walk you through why this happens and how you can fix it: • Delayed Transcription: The OpenAI Realtime model processes user speech from start to finish and delivers transcriptions after the agent has responded. Because of this delay, user messages don’t appear in real time. • Separate STT Plugin: The external STT gives you real-time user transcripts, but these aren’t automatically added to
session.history
. You’ll need to sync the STT output with the session’s chat context yourself. • Turn Detection: If you’re using LiveKit’s turn detector alongside the external STT, its output also needs to be manually integrated into the session to keep track of user messages properly. Here are some friendly tips to help you get full history visibility: 1. Try manually adding user transcripts from the STT plugin into the shared
llm.ChatContext
that the agent uses. 2. Consider using
modalities=["text"]
in the Realtime model along with a separate TTS plugin for audio output. This setup tends to handle transcription and history more smoothly. 3. It’s a good idea to limit or avoid loading too much history into the Realtime model, as it might then default to text-only responses, which can interrupt the audio flow and history tracking. If you’d like, I’m here to help guide you through these steps or answer any questions you have. Just let me know! Sources: OpenAI Realtime API plugin guide | LiveKit Docs | Azure OpenAI Realtime API and LiveKit | LiveKit Docs | Realtime model plugins | LiveKit Docs | LiveKit turn detector plugin | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
b
can't I just use STT for the entire transcript? if yes, how to do that? if not, how to do that: Try manually adding user transcripts from the STT plugin into the shared
llm.ChatContext
that the agent uses.?
t
STT plugins in LiveKit are designed for real-time transcription and aren't able to process the entire conversation transcript all at once. But don’t worry—you can manually add user transcripts from the STT plugin into the shared
llm.ChatContext
that the agent uses. Here’s a friendly guide on how to do it: 1. Manually Insert Transcripts: You can easily insert user messages directly into the chat context:
Copy code
from livekit.agents.llm import ChatContext, ChatMessage

# Create a chat context and insert a user transcript
chat_ctx = ChatContext()
chat_ctx.insert(ChatMessage(text="Hello, how can you help me?", role="user"))

# Update the agent's chat context
await agent.update_chat_ctx(chat_ctx)
2. Real-Time Transcription: If you’re using a separate STT plugin, just listen for transcription events (like
on_final_transcript
) and add the results bit by bit to the chat context. If your situation involves working with a pre-recorded conversation, you can run STT separately (for example, with external tools) and then programmatically add the results into the agent’s context. Please feel free to reach out if you’d like any more help or guidance with this—I’m here to support you! Sources: Realtime model plugins | LiveKit Docs | LiveKit turn detector plugin | LiveKit Docs | Speech-to-text (STT) models | LiveKit Docs | livekit-plugins/livekit-plugins-soniox/livekit/plugins/soniox/stt.py
b
how to reliably combine speech chunks from Deepgram STT to create a full user transcript for a turn
t
To help you smoothly combine speech chunks from Deepgram STT into a full user transcript for a turn, LiveKit uses a thoughtful process that buffers and finalizes transcription segments. Here’s a friendly walkthrough of how it works: 1. Track and Buffer Segments: Deepgram STT sends interim and final transcription events. Each segment is carefully stored in a buffer, keyed by its segment ID, so everything stays in the right order. When a segment is marked as final, the system brings together all buffered segments into one complete transcript:
Copy code
sorted_segments = sorted(self._transcript_state.items(), key=lambda item: int(item[0]))
full_transcript = " ".join([text for _, text in sorted_segments])
2. Detect Turn Boundaries: Turn boundaries are identified using Deepgram’s endpointing signals. A turn ends when silence follows speech, making sure that only meaningful speech is included in the transcript. 3. Integrate with LiveKit: LiveKit listens for
FINAL_TRANSCRIPT
events from Deepgram and adds the results to the current turn’s transcript:
Copy code
if ev.type == stt.SpeechEventType.FINAL_TRANSCRIPT:
    transcript = ev.alternatives[0].text
    self._audio_transcript += f" {transcript}"
Configuration Options: • You can adjust
endpointing_ms
to control how long silence lasts before a turn ends. • Try enabling
eager_eot_threshold
for early turn detection based on pauses in speech. If your goal is simply to log full transcripts without worrying about turn logic, you can listen to the
user_input_transcribed
event and save final transcripts directly like this:
Copy code
@session.on("user_input_transcribed")
def on_transcript(transcript):
    if transcript.is_final:
        with open("user_speech_log.txt", "a") as f:
            f.write(f"{transcript.transcript}\n")
Feel free to reach out if you'd like me to clarify anything or help you implement this — I’m here to support you! Sources: examples/voice_agents/realtime_turn_detector.py | plugins/deepgram/src/stt.ts | pipeline-stt/transcriber/transcriber.py | Deepgram STT plugin guide | LiveKit Docs