broad-painter-9222
12/10/2025, 6:29 PMtall-airline-16756
12/10/2025, 6:30 PMtall-airline-16756
12/10/2025, 6:30 PMsession.aclose() or session.shutdown(drain=True) (Python) to gracefully close the agent session.
• If you need to terminate the entire LiveKit room for all participants, call the server SDK's delete_room API.
2) Hook to send the transcript on session end
• Use the on_session_end callback. In that hook access session.history or generate a report with ctx.make_session_report() and send it to your API.
• Perform the API call inside on_session_end so it runs immediately after the session closes.
3) RoomOptions and reliability recommendations
• There are no special RoomOptions that guarantee external API delivery.
• Ensure your shutdown has enough time for I/O (default shutdown timeout is 60 seconds). Send the transcript in on_session_end and:
◦ Implement retries with backoff for transient network errors.
◦ Persist a local copy (file or DB) before/after sending so you can retry later if the process exits.
◦ If you need stronger guarantees, have a background worker or job queue pick up unsent transcripts from persistent storage and retry independently.
If you want, tell me your runtime language (Python/JS) and whether you prefer in-process retries or a persistent queue, and I’ll give a short example for the on_session_end hook.
Sources: Job lifecycle | LiveKit docs | Observability data hooks | LiveKit docsbroad-painter-9222
12/10/2025, 6:33 PMon_session_end run immediately after closing the session?tall-airline-16756
12/10/2025, 6:33 PMon_session_end runs immediately after the session is closed and before the agent process shuts down. Use it to perform final work (for example, generate ctx.make_session_report() or read session.history) and send the transcript. Ensure your API call completes within the shutdown timeout (default 60 seconds) and add retries/persistence if you need stronger delivery guarantees.broad-painter-9222
12/10/2025, 6:34 PMtall-airline-16756
12/10/2025, 6:35 PMon_session_end to generate a transcript, and send it to your API with retries and local persistence if sending fails.
import json
import time
from pathlib import Path
import requests
from requests.exceptions import RequestException
SHARED_STORE = Path("/tmp/transcripts") # local persistence for retries
SHARED_STORE.mkdir(exist_ok=True)
SHOULD_STOP = False
class Session:
# stub: your real session object will provide aclose(), history, etc.
def __init__(self):
self.history = []
async def aclose(self):
# graceful close implementation
pass
class Context:
def make_session_report(self):
# return structured transcript/report (dict or JSON-serializable)
return {"messages": session.history, "ended_at": time.time()}
session = Session()
ctx = Context()
def send_with_retries(payload: dict, url: str, max_attempts=3, backoff=2):
data = json.dumps(payload)
for attempt in range(1, max_attempts + 1):
try:
resp = requests.post(url, data=data, headers={"Content-Type": "application/json"}, timeout=10)
resp.raise_for_status()
return True
except RequestException:
if attempt == max_attempts:
return False
time.sleep(backoff ** attempt)
def persist_locally(payload: dict, filename: str):
path = SHARED_STORE / filename
with open(path, "w") as f:
json.dump(payload, f)
def enqueue_unsent():
url = "https://your.api/endpoint"
for p in SHARED_STORE.glob("*.json"):
with open(p) as f:
payload = json.load(f)
if send_with_retries(payload, url, max_attempts=5, backoff=2):
p.unlink()
# This is the on_session_end hook that runs immediately after session close
def on_session_end():
report = ctx.make_session_report() # or session.history
url = "https://your.api/endpoint"
filename = f"transcript_{int(time.time())}.json"
# Try in-process send with retries
ok = send_with_retries(report, url, max_attempts=3, backoff=2)
if not ok:
# Persist locally so a background worker can retry
persist_locally(report, filename)
# Example of ending the session and calling the hook
async def end_session_and_send():
# 1) End the session gracefully
await session.aclose() # or session.shutdown(drain=True)
# 2) on_session_end runs immediately after close
on_session_end()
# Background worker (run separately, e.g., cron or separate process)
def background_retry_worker():
while True:
enqueue_unsent()
time.sleep(60) # check every minute
Notes:
• on_session_end runs immediately after the session is closed and before the agent process exits — put your final send logic there.
• Keep API calls short and use retries/backoff. Persist unsent transcripts so a background worker can retry outside the shutdown window.
• Adjust timeouts, retry counts, and persistence paths to match your environment.
Do you want a concrete async example wired into your real session object (I can adapt to your framework or provide an asyncio version)?broad-painter-9222
12/10/2025, 6:37 PMtall-airline-16756
12/10/2025, 6:37 PMon_session_end hook definition. It focuses only on the hook and how it's registered in the entrypoint.
import time
import json
import requests
def send_transcript(report: dict):
url = "https://your.api/endpoint"
requests.post(url, json=report, timeout=10)
def entrypoint():
# Define the on_session_end hook
def on_session_end(ctx, session):
"""
Called immediately after the session closes.
`ctx` can provide helpers like `make_session_report()`.
`session` exposes `history` if you need raw messages.
"""
report = ctx.make_session_report() # or use session.history
try:
send_transcript(report)
except Exception:
# persist or enqueue for retry outside shutdown window
with open(f"/tmp/transcript_{int(time.time())}.json", "w") as f:
json.dump(report, f)
# Register hook with your framework/agent runtime
# Example: runtime.register_hook("on_session_end", on_session_end)
# (Replace the line above with your actual registration call.)
# Entrypoint returns the hook or starts the runtime as required
return on_session_end
If you want an async version or the exact registration call for your runtime, tell me which framework or SDK you use and I’ll adapt it.broad-painter-9222
12/10/2025, 6:38 PM# Register hook with your framework/agent runtime
# Example: runtime.register_hook("on_session_end", on_session_end)
# (Replace the line above with your actual registration call.)
how to do that? or you're jsut hallucianting?tall-airline-16756
12/10/2025, 6:39 PMin Python, pass it to the @server.rtc_session(...)` decorator.
Minimal entrypoint example:
from livekit.agents import AgentServer, JobContext
import aiohttp
server = AgentServer()
async def on_session_end(ctx: JobContext):
report = ctx.make_session_report()
transcript = report.to_dict().get("history", [])
async with aiohttp.ClientSession() as http:
await http.post("https://your.api/endpoint", json={"transcript": transcript}, timeout=10)
@server.rtc_session(on_session_end=on_session_end)
async def my_agent(ctx: JobContext):
# session logic here
...
If you want, tell me:
• your preferred HTTP client (aiohttp or requests)
• whether you need retries/persistence in the hook
and I’ll give a short adapted snippet.
Sources: Observability data hooks | LiveKit docs | Agent session | LiveKit docsbroad-painter-9222
12/10/2025, 6:40 PMtall-airline-16756
12/10/2025, 6:41 PMon_session_end with run_app and agents.WorkerOptions. Add the callback to WorkerOptions (no AgentServer needed). Minimal example:
from livekit.agents import cli, WorkerOptions, JobContext, WorkerType
import aiohttp
async def on_session_end(ctx: JobContext):
report = ctx.make_session_report()
payload = report.to_dict()
async with aiohttp.ClientSession() as http:
await http.post("https://your.api/endpoint", json=payload, timeout=10)
async def entrypoint(ctx: JobContext):
# your session logic here
await ctx.connect()
# start session...
...
if __name__ == "__main__":
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
worker_type=WorkerType.ROOM,
agent_name="experimental_interviewer",
prewarm_fnc=None,
on_session_end=on_session_end,
)
)
Want this adapted to use requests (sync), include retries, or persist unsent transcripts?
Sources: Agent session | LiveKit docs | Job lifecycle | LiveKit docsbroad-painter-9222
12/10/2025, 6:43 PMtall-airline-16756
12/10/2025, 6:43 PMon_session_end in WorkerOptions.
• To run an on_session_end callback when using run_app, define it and register it on the same entrypoint via the @server.rtc_session(on_session_end=...) decorator.
Minimal example you can drop into your app:
from livekit.agents import AgentServer, JobContext, cli, WorkerOptions
import aiohttp
server = AgentServer()
async def on_session_end(ctx: JobContext):
report = ctx.make_session_report()
payload = report.to_dict()
async with aiohttp.ClientSession() as http:
await http.post("https://your.api/endpoint", json=payload, timeout=10)
@server.rtc_session(on_session_end=on_session_end)
async def entrypoint(ctx: JobContext):
await ctx.connect()
# create/start your AgentSession here...
...
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
If you want this adapted to avoid AgentServer() (pure run_app style) or need retries/persistence in on_session_end, tell me which pattern you prefer and I’ll give the exact snippet.
Sources: Agent session | LiveKit docs