I want to have word level timestamp for both user ...
# ask-ai
b
I want to have word level timestamp for both user and agent's transcript. I am using deepgram stt and eleven lab tts. How can I configure this?
t
Thanks for reaching out, Harsh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Let's walk through how to set up word-level timestamps for both user and agent transcripts using Deepgram STT and Eleven Labs TTS. Here’s a simple step-by-step guide to help you: 1. Install Required Plugins: You can easily get started by running
pip install livekit-agents livekit-plugins-deepgram livekit-plugins-elevenlabs
to install all the necessary plugins. 2. Set Environment Variables: Make sure to configure your API keys in a
.env
file for LiveKit, Deepgram, and Eleven Labs. This will keep everything connected smoothly. 3. Enable TTS-Aligned Transcription: In your
AgentSession
configuration, just set
use_tts_aligned_transcript=True
. This turns on word-level timing for your agent’s transcripts. 4. Implement Agent Transcript Handling: Use a
transcription_node
to process
TimedString
objects for agent speech. This way, you get precise word-level timing that’s really helpful. 5. Handle User Transcripts: Capture user speech with the
user_input_transcribed
event. Keep in mind, the timing detail depends on what Deepgram supports. If you’d like, I’m here to provide detailed code examples or help you with any specific part of this setup. Just let me know! Sources: Understanding Transcript Timing in Voice Conversations | Text and transcriptions | LiveKit Docs | ElevenLabs TTS plugin guide | LiveKit Docs | livekit-plugins/livekit-plugins-deepgram/livekit/plugins/deepgram/stt.py | docs/index.yaml
b
Provide me a detailed code example for step 4 and 5
t
Here are detailed code examples for steps 4 and 5: Step 4: Implement Agent Transcript Handling To process agent transcripts with word-level timing, you can try the following implementation:
Copy code
import asyncio
import logging
from collections.abc import AsyncGenerator, AsyncIterable
from livekit.agents import Agent
from livekit.agents.voice.agent import ModelSettings
from livekit.agents.voice.io import TimedString

class TimestampAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant.")

    async def transcription_node(
        self, text: AsyncIterable[str | TimedString], model_settings: ModelSettings
    ) -> AsyncGenerator[str | TimedString, None]:
        async for chunk in text:
            if isinstance(chunk, TimedString):
                # Log agent speech with word-level timing
                logging.info(f"Agent: '{chunk}' ({chunk.start_time} - {chunk.end_time})")
                # Process and store agent transcript with timing here
            yield chunk
Step 5: Handle User Transcripts To capture user transcripts, you can use the
user_input_transcribed
event like this:
Copy code
import datetime

@session.on("user_input_transcribed")
def on_user_transcript(transcript):
    if transcript.is_final:
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # Log user transcript
        print(f"[{timestamp}] User: {transcript.transcript}")
        # Note: Timing granularity depends on the STT provider
If you have any questions or would like a hand integrating these examples into your setup, please don’t hesitate to reach out. I’m here to help!
b
user input transcribed will give me the time when the transcript was final, not when the user is actually speaking. Can we configure the STT node to capture real-time timestamps?
t
To capture real-time timestamps for user speech, you have a couple of great options to configure the STT node: 1. Word-Level Timestamps: You can use the
transcription_node
method to get precise start and end times for each word. Here’s a simple example to guide you:
Copy code
@agent.transcription_node()
async def transcription_handler(transcription_stream):
    async for timed_string in transcription_stream:
        # Access word-level timestamps
        print(f"Text: {timed_string.text}")
        print(f"Start time: {timed_string.start_time} seconds")
        print(f"End time: {timed_string.end_time} seconds")
This method gives you word-level timing data in seconds relative to the start of the current turn, which can be really helpful for detailed timing needs. 2. Transcript-Level Timestamps: Another approach is to use the
user_input_transcribed
event to capture timestamps when the transcript is finalized. Here’s how you might do that:
Copy code
@agent.on("user_input_transcribed")
async def on_user_input_transcribed(ctx, transcript):
    timestamp = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
    print(f"{timestamp} {transcript}")
This gives you transcript-level timestamps, though it doesn’t include the real-time word-level details. For smooth real-time processing, just make sure your STT provider (like Deepgram) is set up with streaming and interim results enabled. If you’d like, I’m here to help you implement either method or assist with configuring your STT provider—just let me know! Sources: Text and transcriptions | LiveKit Docs | complex-agents/turn-taking/README.md | Pipeline nodes and hooks | LiveKit Docs