How do you access the transcription history (What ...
# ask-ai
o
How do you access the transcription history (What the agent and user has said in turn)?
t
Thanks for reaching out, Sarang. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to help you access the transcription history of agent and user conversations in LiveKit! There are a few ways you can do this: • Real-time Access: You can use React hooks like
useCombinedTranscriptions
or
useDataStreamTranscriptions
to capture transcriptions as they happen during live sessions. • Backend Access: If you want the full conversation history, you can retrieve it using the
session.history
property or listen for events like
conversation_item_added
to get real-time updates. • Persistence: To keep a record after the session ends, you might save the conversation history to a file or database using methods such as
add_shutdown_callback
. • Loading Previous History: And if you need to load earlier chat history into a new session, the
chat_ctx.add_message
method is the way to go. Please feel free to reach out if you'd like me to walk you through any of these steps in more detail or if there’s anything else I can assist you with! Sources: src/transcriptions/TranscriptionTile.tsx | Session recording and transcripts | LiveKit Docs | Text and transcriptions | LiveKit Docs | examples/voice_agents/realtime_load_chat_history.py | Sending text | LiveKit Docs
o
Here is my current agent. Can you tell me what's wrong:
Copy code
import os
import json
from dotenv import load_dotenv

from livekit import agents
from livekit.agents import AgentSession, Agent, RoomInputOptions
from livekit.plugins import noise_cancellation, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from supabase import create_client, Client

load_dotenv(".env.local")

# Supabase client (for future interview finalization)
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY) if SUPABASE_URL and SUPABASE_SERVICE_KEY else None

# Global state
current_interview_id = None


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.""",
        )


async def entrypoint(ctx: agents.JobContext):
    await ctx.connect()
    
    global current_interview_id
    
    # Extract interview_id from room metadata (for website integration)
    room_metadata = json.loads(ctx.room.metadata) if ctx.room.metadata else {}
    interview_id = room_metadata.get("interviewId")
    current_interview_id = interview_id
    print(f"🎙️  Assistant started for interview: {interview_id}")
    
    # Manually capture transcript from transcription events
    transcript_log = []
    
    def on_transcription_received(transcription):
        """Capture all speech-to-text results"""
        try:
            # Get participant identity to determine role
            participant = transcription.participant if hasattr(transcription, 'participant') else None
            participant_identity = participant.identity if participant else 'unknown'
            
            # Determine if this is user or agent
            is_agent = participant_identity.startswith('agent-')
            role = 'assistant' if is_agent else 'user'
            
            # Get the transcribed text
            text = transcription.text if hasattr(transcription, 'text') else str(transcription)
            
            if text and text.strip():
                transcript_log.append({
                    "role": role,
                    "content": text,
                    "timestamp": None
                })
                print(f"📝 [{role}]: {text[:60]}...")
        except Exception as e:
            print(f"⚠️  Transcription capture error: {e}")
    
    # Subscribe to transcription events
    ctx.room.on("transcription_received", on_transcription_received)
    
    session = AgentSession(
        stt="assemblyai/universal-streaming:en",
        llm="openai/gpt-4o-mini",
        tts="cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc",
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
    )
    
    # Add shutdown callback to capture and send transcript
    async def on_shutdown():
        """Capture transcript and send termination event when interview ends"""
        print("\n🛑 Interview ending - capturing transcript...")
        
        # Use our manually captured transcript
        transcript = transcript_log.copy()
        
        print(f"\n📊 Total transcript entries: {len(transcript)}")
        if len(transcript) > 0:
            print(f"   First message: {transcript[0]}")
            print(f"   Last message: {transcript[-1]}")
        else:
            print("   ⚠️  No transcript captured - this is unexpected!")
        
        # Send termination event with transcript to frontend
        try:
            await ctx.room.local_participant.publish_data(
                payload=json.dumps({
                    "type": "interview_terminated",
                    "transcript": transcript
                }).encode('utf-8'),
                reliable=True,
                topic="interview"
            )
            print("✅ Sent termination event with transcript to frontend")
        except Exception as e:
            print(f"⚠️  Failed to send termination event: {e}")
    
    ctx.add_shutdown_callback(on_shutdown)

    await session.start(
        room=ctx.room,
        agent=Assistant(),
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(), 
        ),
    )

    await session.generate_reply(
        instructions="Greet the user and offer your assistance."
    )


if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
t
Thanks for reaching out! Could you please share a bit more about the specific issue you're having with this agent? For example: • Are you seeing any errors or exceptions? • Is the agent not responding the way you expected? • Are there any challenges with transcription, audio, or how sessions are handled? The more details you can provide, the better I can understand what's going on and help you find the right solution. Sources: agents/CHANGELOG.md | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | Debugging Audio/Video Sync Issues in LiveKit Publishing | context-readmes/USERDATA_GUIDE.md
o
Well, I haven't figured out a way to get the transcriptions whatsoever. Whatever method or function I use yields an empty variable
t
I understand how frustrating it can be when your transcription data appears empty. Let’s explore some common reasons together and see how we can fix them: • Configuration Issues: Double-check that
transcription_enabled=True
is set in your
RoomOutputOptions
. This little step is crucial! • STT Setup: Make sure your Speech-to-Text service is correctly configured—it’s the heart of transcription. • API Updates: If you’re still using the old
TranscriptionEvent
, consider switching to the newer text streams API with the topic
lk.transcription
for better results. • VAD Settings: If you’re working with non-streaming STT, tweaking the Voice Activity Detection parameters might help capture speech more accurately. • Missing Data: Take a look at your logs for any warnings about missing participants or track publications—that could give us clues. Please feel free to reach out if you want to dive deeper into any of these points or need a hand troubleshooting your specific situation. I’m here to help! Sources: Sources/LiveKit/Core/Room+EngineDelegate.swift | Agents v0.x migration guide - Python | LiveKit Docs | examples/other/transcription/transcriber.py | agent/main.py | Session recording and transcripts | LiveKit Docs
o
the agent itself works fine, and i set the configurtion correctly. It doesn't seem like i can actually retrieve the transcription no matter what i code. Can you give me a specific example that would enable me to print out the transcription or call log
t
To help you retrieve and print out transcriptions or call logs, here’s a friendly example implementation you can try out:
Copy code
async def entrypoint(ctx: agents.JobContext):
    await ctx.connect()
    
    # Initialize a list to store transcriptions
    transcript_log = []
    
    def on_transcription_received(transcription):
        try:
            # Extract participant identity and role
            participant = transcription.participant if hasattr(transcription, 'participant') else None
            participant_identity = participant.identity if participant else 'unknown'
            role = 'assistant' if participant_identity.startswith('agent-') else 'user'
            
            # Extract transcription text
            text = transcription.text if hasattr(transcription, 'text') else str(transcription)
            
            if text and text.strip():
                transcript_log.append({
                    "role": role,
                    "content": text,
                    "timestamp": None
                })
                print(f"📝 [{role}]: {text}")
        except Exception as e:
            print(f"⚠️  Error capturing transcription: {e}")
    
    # Subscribe to transcription events
    ctx.room.on("transcription_received", on_transcription_received)
    
    # Add a shutdown callback to print the full transcript
    async def on_shutdown():
        print("\n🛑 Session ending - Full Transcript:")
        for entry in transcript_log:
            print(f"[{entry['role']}]: {entry['content']}")
    
    ctx.add_shutdown_callback(on_shutdown)
    
    # Start the session
    session = AgentSession(
        stt="assemblyai/universal-streaming:en",
        llm="openai/gpt-4o-mini",
        tts="cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"
    )
    await session.start(room=ctx.room, agent=Assistant())
This example listens for transcription events, keeps a real-time log, and then prints out the full transcript when your session wraps up. If anything feels unclear or you’d like me to help tweak it, just let me know—I’m here to support you!
o
Can you look at my code and tell me what's wrong:
Copy code
import os
import json
from dotenv import load_dotenv

from livekit import agents
from livekit.agents import AgentSession, Agent, RoomInputOptions, RoomOutputOptions
from livekit.plugins import noise_cancellation, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from supabase import create_client, Client

load_dotenv(".env.local")

# Supabase client (for future interview finalization)
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY) if SUPABASE_URL and SUPABASE_SERVICE_KEY else None

# Global state
current_interview_id = None


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.""",
        )


async def entrypoint(ctx: agents.JobContext):
    await ctx.connect()
    
    global current_interview_id
    
    # Extract interview_id from room metadata (for website integration)
    room_metadata = json.loads(ctx.room.metadata) if ctx.room.metadata else {}
    interview_id = room_metadata.get("interviewId")
    current_interview_id = interview_id
    print(f"🎙️  Assistant started for interview: {interview_id}")
    
    # Manually capture transcript from transcription events
    transcript_log = []
    
    def on_transcription_received(transcription):
        """Capture all speech-to-text results"""
        print(f"🔔 Transcription event received! Type: {type(transcription)}")
        try:
            # Get participant identity to determine role
            participant = transcription.participant if hasattr(transcription, 'participant') else None
            participant_identity = participant.identity if participant else 'unknown'
            
            # Determine if this is user or agent
            is_agent = participant_identity.startswith('agent-')
            role = 'assistant' if is_agent else 'user'
            
            # Get the transcribed text
            text = transcription.text if hasattr(transcription, 'text') else str(transcription)
            
            if text and text.strip():
                transcript_log.append({
                    "role": role,
                    "content": text,
                    "timestamp": None
                })
                print(f"📝 [{role}]: {text[:60]}...")
            else:
                print(f"   ⚠️  Empty transcription text")
        except Exception as e:
            print(f"⚠️  Transcription capture error: {e}")
    
    # Subscribe to transcription events
    ctx.room.on("transcription_received", on_transcription_received)
    print("✅ Subscribed to transcription_received events")
    
    session = AgentSession(
        stt="assemblyai/universal-streaming:en",
        llm="openai/gpt-4o-mini",
        tts="cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc",
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
    )
    
    # Add shutdown callback to capture and send transcript
    async def on_shutdown():
        """Capture transcript and send termination event when interview ends"""
        print("\n🛑 Interview ending - capturing transcript...")
        
        # Use our manually captured transcript
        transcript = transcript_log.copy()
        
        print(f"\n📊 Total transcript entries: {len(transcript)}")
        if len(transcript) > 0:
            print(f"   First message: {transcript[0]}")
            print(f"   Last message: {transcript[-1]}")
            print("\n📋 FULL TRANSCRIPT:")
            print(json.dumps(transcript, indent=2))
        else:
            print("   ⚠️  No transcript captured - this is unexpected!")
        
        # Send termination event with transcript to frontend
        try:
            await ctx.room.local_participant.publish_data(
                payload=json.dumps({
                    "type": "interview_terminated",
                    "transcript": transcript
                }).encode('utf-8'),
                reliable=True,
                topic="interview"
            )
            print("✅ Sent termination event with transcript to frontend")
        except Exception as e:
            print(f"⚠️  Failed to send termination event: {e}")
    
    ctx.add_shutdown_callback(on_shutdown)

    await session.start(
        room=ctx.room,
        agent=Assistant(),
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(), 
        ),
        room_output_options=RoomOutputOptions(
            transcription_enabled=True,  # Enable transcription events
        ),
    )

    await session.generate_reply(
        instructions="Greet the user and offer your assistance."
    )


if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
o
is there anyway to access conversation log history using chat_ctx? I believe the livekit agent used to actually update in the console/terminal with text on what each side said, no longer?