fresh-hospital-14455
09/26/2025, 7:30 AMroom_finished happens. I'm currently able to save the call transcript in a json file and also able to listen for the room_finished event. The code section in agent.py saving call transcript is here;
async def entrypoint(ctx: agents.JobContext):
async def write_transcript():
current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
print(f"Curent Date: {current_date}")
# This example writes to the temporary directory, but you can save to any location
filename = f"/content/transcript_{ctx.room.name}_{current_date}.json"
with open(filename, 'w') as f:
json.dump(session.history.to_dict(), f, indent=2)
print(f"Transcript for {ctx.room.name} saved to {filename}")
ctx.add_shutdown_callback(write_transcript)
....
My Webhook API looks like this;
from fastapi import FastAPI, Request, Header, HTTPException
from livekit.api import TokenVerifier, WebhookReceiver
import asyncio
import os
from datetime import datetime
app = FastAPI()
token_verifier = TokenVerifier(
api_key=os.environ["LIVEKIT_API_KEY"],
api_secret=os.environ["LIVEKIT_API_SECRET"],
)
webhok_receiver = WebhookReceiver(token_verifier)
@app.post("/webhook")
async def webhook_endpoint(request: Request):
try:
auth_token = request.headers.get("Authorization")
if not auth_token:
raise HTTPException(status_code=401, detail=f"No Auth Token")
body = await request.body()
event = webhok_receiver.receive(body.decode("utf-8"), auth_token)
print(event.event)
if event.event == "room_finished":
print("ROOM FINISHED!")
print("------")
print(event)
print("-----------")
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid webhook: {str(e)}")
I would like to have the transcript passed to this webhook so that I can further process that transcript. Can someone please tell me how to get this transcript passed over to the webhook. Thanks!fierce-zoo-69908
09/26/2025, 12:21 PMctx.add_shutdown_callback(lambda: shutdown_hook(ctx, worker_metadata, session))
2. session.history.to_dict() inside the hookfierce-zoo-69908
09/26/2025, 12:22 PMfresh-hospital-14455
09/26/2025, 1:54 PMctx.add_shutdown_callback(lambda: shutdown_hook(ctx, worker_metadata, session)) for this use case? I use ctx.add_shutdown_callback(write_transcript) before defining session in the entrypoint as mentioned in the docs here https://docs.livekit.io/agents/ops/recording/#text-transcripts
Kindly guide me on how to go about this. Thanks!fierce-zoo-69908
09/26/2025, 2:18 PM// first
session = AgentSession[SessionInfo]()
// then
ctx.add_shutdown_callback(lambda: shutdown_hook(ctx, worker_metadata, session))fierce-zoo-69908
09/26/2025, 2:21 PMfresh-hospital-14455
09/26/2025, 5:35 PMagent.py
from dotenv import load_dotenv
from livekit import agents
from livekit.agents import AgentSession, Agent, RoomInputOptions, function_tool, RunContext
from livekit.plugins import (
google,
noise_cancellation,
)
from datetime import datetime
import json
from typing import Any
from livekit.agents import metrics, MetricsCollectedEvent
load_dotenv(".env.local")
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(instructions="You are a helpful voice AI assistant.")
@function_tool()
async def lookup_weather(
self,
context: RunContext,
location: str,
) -> dict[str, Any]:
"""Look up weather information for a given location.
Args:
location: The location to look up weather information for.
"""
return {"weather": "sunny", "temperature_f": 70}
async def entrypoint(ctx: agents.JobContext):
async def write_transcript():
current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
print(f"Curent Date: {current_date}")
# This example writes to the temporary directory, but you can save to any location
filename = f"/content/transcript_{ctx.room.name}_{current_date}.json"
with open(filename, 'w') as f:
json.dump(session.history.to_dict(), f, indent=2)
print(f"Transcript for {ctx.room.name} saved to {filename}")
ctx.add_shutdown_callback(write_transcript)
session = AgentSession(
llm=google.beta.realtime.RealtimeModel(
model="gemini-live-2.5-flash-preview",
voice="Puck",
temperature=0.8,
instructions="You are a helpful assistant",
),
)
await session.start(
room=ctx.room,
agent=Assistant(),
room_input_options=RoomInputOptions(
# For telephony applications, use `BVCTelephony` instead for best results
noise_cancellation=noise_cancellation.BVC(),
),
)
await session.generate_reply(
instructions="Greet the user and offer your assistance. You should start by speaking in English."
)
if __name__ == "__main__":
agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
You have mentioned this line;
ctx.add_shutdown_callback(lambda: shutdown_hook(ctx, worker_metadata, session))
I would like to know what is worker_metadata here and where should I have this line.fresh-hospital-14455
09/26/2025, 5:39 PMevent: "room_finished"
room {
sid: "RM_3XiXw7xJzdGc"
name: "playground-Tfod-P0EO"
empty_timeout: 300
creation_time: 1758894319
enabled_codecs {
mime: "video/H264"
}
enabled_codecs {
mime: "video/VP8"
}
enabled_codecs {
mime: "video/VP9"
}
enabled_codecs {
mime: "video/AV1"
}
enabled_codecs {
mime: "audio/red"
}
enabled_codecs {
mime: "audio/opus"
}
version {
unix_micro: 1758894319861298
}
departure_timeout: 20
creation_time_ms: 1758894319765
}
id: "EV_RLKuQc9xqEAY"
created_at: 1758894400
My room name begins with playground because I'm testing on the playground.fresh-hospital-14455
09/26/2025, 5:42 PMrefined-appointment-81829
09/26/2025, 5:43 PMfresh-hospital-14455
09/26/2025, 5:45 PMrefined-appointment-81829
09/26/2025, 5:45 PMfresh-hospital-14455
09/26/2025, 5:50 PMagent.py above and please tell me what modifications I need to make or do you have any resource you can point me to.
In prod, I will most likely save the call transcript json file to Google Cloud Storage, I would like to have the path to that transcript file passed to the webhook for further processing.refined-appointment-81829
09/26/2025, 5:51 PMfresh-hospital-14455
09/26/2025, 7:06 PMwrite_transcript funtion in agent.py as shown below;
...
async def entrypoint(ctx: agents.JobContext):
# ---- BEGINNING OF THE MODIFIED SECTION -----
async def write_transcript():
current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"/content/transcript_{ctx.room.name}_{current_date}.json"
with open(filename, 'w') as f:
json.dump(session.history.to_dict(), f, indent=2)
print(f"Transcript for {ctx.room.name} saved to {filename}")
# Prepare data to send to webhook
payload = {
"event": "room_transcript_ready",
"room_name": ctx.room.name,
"filename": filename,
}
webhook_url = os.getenv("WEBHOOK_URL")
async with httpx.AsyncClient() as client:
try:
resp = await client.post(webhook_url, json=payload)
print(f"Webhook notified, status: {resp.status_code}")
except Exception as e:
print(f"Error notifying webhook: {e}")
ctx.add_shutdown_callback(write_transcript)
# ------ END OF MODIFIED SECTION --------
session = AgentSession(
llm=google.beta.realtime.RealtimeModel(
model="gemini-live-2.5-flash-preview",
voice="Puck",
temperature=0.8,
instructions="You are a helpful assistant",
),
)
await session.start(
room=ctx.room,
agent=Assistant(),
room_input_options=RoomInputOptions(
# For telephony applications, use `BVCTelephony` instead for best results
noise_cancellation=noise_cancellation.BVC(),
),
)
await session.generate_reply(
instructions="Greet the user and offer your assistance. You should start by speaking in English."
)
if __name__ == "__main__":
agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
Here is also the modified webhook server
...
@app.post("/webhook")
async def webhook_endpoint(request: Request):
try:
body = await request.body()
try:
data = json.loads(body)
except Exception:
raise HTTPException(status_code=400, detail="Invalid JSON")
# Handle the agent's transcript notification
if data.get("event") == "room_transcript_ready":
print(f"Transcript file received for room {data.get('room_name')}: {data.get('filename')}")
return {"status": "transcript received"}
# Otherwise, handle LiveKit webhook as usual
auth_token = request.headers.get("Authorization")
if not auth_token:
raise HTTPException(status_code=401, detail="No Auth Token")
event = webhok_receiver.receive(body.decode("utf-8"), auth_token)
if event.event == "room_finished":
print("ROOM FINISHED!")
print(event)
return {"status": "ok"}
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid webhook: {str(e)}")
With this modification, I'm now seeing the filename variable getting passed to the webhook from the agent. Though it now means the webhook server is listening to two different events, one is from livekit room_finished and the other is the custom event room_transcript_ready, LiveKit only sends standard event data.
The agent is sending the filename to the webhook server whenever the call transcript is created/saved. I'm testing in google colab and lk playground, the call transcript is created/saved when I interrupt execution in colab. But I have noticed that interrupting/closing agent.py execution (or disconnecting lk playground) doesn't mean/trigger the room_finished event, but rather it triggers the participant_left event. @refined-appointment-81829 I would like to ask;
1. When is the room_finished event triggered in livekit? How can I trigger it during dev testing (in colab)?
2. Or is even the room_finished event the event I should be tracking for? Given that I just want to grab a call transcript when call ends and pass it over to a webhook server? Is participant_left event sufficient for my case as that's what's triggering the transcript to be created? What is room_finished and do I need it for my case?
3. If room_finished event is what I need in question 2, then how can I make the custom room_transcript_ready event dependent on the room_finished event so that it gets sent out when room is finished?fresh-hospital-14455
10/01/2025, 8:28 PM