orange-chef-9809
10/19/2025, 4:36 PMtall-airline-16756
10/19/2025, 4:36 PMtall-airline-16756
10/19/2025, 4:38 PMuseCombinedTranscriptions 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 Docsorange-chef-9809
10/19/2025, 4:39 PMimport 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))tall-airline-16756
10/19/2025, 4:40 PMorange-chef-9809
10/19/2025, 4:44 PMtall-airline-16756
10/19/2025, 4:44 PMtranscription_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 Docsorange-chef-9809
10/19/2025, 4:50 PMtall-airline-16756
10/19/2025, 4:51 PMasync 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!orange-chef-9809
10/19/2025, 4:56 PMimport 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))tall-airline-16756
10/19/2025, 4:57 PMorange-chef-9809
10/19/2025, 5:00 PM