cool-salesmen-60705
11/21/2025, 11:16 AMtall-airline-16756
11/21/2025, 11:16 AMtall-airline-16756
11/21/2025, 11:16 AMsession.history
• After the session ends, read AgentSession.session.history (or ctx.agent_session.history) and serialize it to JSON. It contains user inputs, agent responses, and tool/function calls.
2) Save on session end
• Add an on_session_end / shutdown callback that writes ctx.agent_session.history.to_dict() (or equivalent) to a file or storage bucket so you capture the full transcript when the session closes.
3) Create a session report (optional, Python)
• Call ctx.make_session_report() in on_session_end to get a structured report with history, events, metrics, and recording metadata, then save it.
4) (If you need audio) Use Egress recording
• Use LiveKit Egress (room composite) to record audio to a file/S3 while also saving the transcript from session.history for text.
Notes
• The transcript includes both user and agent text and can be synchronized with audio.
• For aligned TTS timing, enable use_tts_aligned_transcript=True if using a supported TTS.
Would you like a short code example for your stack (Python or JS) showing the on_session_end + save flow?
Sources: Observability data hooks | LiveKit docs | Text and transcriptions | LiveKit docs | Realtime model plugins | LiveKit Docscool-salesmen-60705
11/21/2025, 11:21 AMtall-airline-16756
11/21/2025, 11:22 AMcool-salesmen-60705
11/21/2025, 11:22 AMtall-airline-16756
11/21/2025, 11:22 AMon_session_end callback to read ctx.agent_session.history, convert it to a dict, and write JSON to disk (replace the file path or add S3 upload as needed).
import json
import asyncio
from livekit_server import server # example import - use your server framework
from livekit_server.types import JobContext # use the actual types from your SDK
@server.rtc_session(on_session_end="on_session_end")
async def entrypoint(ctx: JobContext):
# Your session/agent setup and runtime logic here
pass
async def on_session_end(ctx: JobContext):
try:
# Get the AgentSession history and convert to JSON-serializable dict
transcript = ctx.agent_session.history.to_dict()
# Customize filename (room name, timestamp, etc.)
filename = f"/tmp/transcript_{ctx.room.name}.json"
# Write to local file
with open(filename, "w", encoding="utf-8") as f:
json.dump(transcript, f, ensure_ascii=False, indent=2)
# Optionally: log or perform further upload (S3, DB)
print(f"Transcript saved to {filename}")
# Optionally create full session report:
# report = ctx.make_session_report()
# with open(f"/tmp/session_report_{ctx.room.name}.json", "w") as f:
# json.dump(report.to_dict(), f, indent=2)
except Exception as e:
# Handle errors (logging, retry, etc.)
print(f"Failed saving transcript: {e}")
If you'd like, I can:
• Show how to upload the JSON to S3 instead of local disk.
• Include saving audio via LiveKit Egress alongside the transcript.
Which would you prefer?cool-salesmen-60705
11/21/2025, 4:51 PMtall-airline-16756
11/21/2025, 4:52 PMawait session.say("Important information...", allow_interruptions=False)
This ensures the agent's speech completes without being preempted.
2) (Optional) Temporarily disable user audio input
• To guarantee no audio reaches STT during that time, disable audio input before speaking and re-enable after:
session.input.set_audio_enabled(False)
try:
await session.say("Important information...", allow_interruptions=False)
finally:
session.input.set_audio_enabled(True)
3) Note about handoff behavior
• Handoff does not automatically change interruption settings. You must explicitly set allow_interruptions=False (and optionally disable audio) for the second agent's critical speech.
If you want, tell me:
• where in your flow you perform the handoff (code snippet), and
• whether you use TTS or audio playback
— and I’ll give a tailored snippet integrated with your handoff logic.
Sources: Agent Session Management & Turn Detection | livekit/livekit_composite | Dee... | Text and transcriptions | LiveKit docs | Tool definition and use | LiveKit docs | OpenAI Realtime API plugin guide | LiveKit docscool-salesmen-60705
11/21/2025, 4:55 PMtall-airline-16756
11/21/2025, 4:55 PMallow_interruptions=False on the agent's speech call (e.g., say() or generate_reply()) to prevent user-triggered interruptions during playback.
• For stronger guarantees, temporarily disable audio input with session.input.set_audio_enabled(False) before speaking and re-enable it after.
• Note: Realtime's server-side VAD can still affect interruption behavior. If you need absolute control, use text-only TTS/modalities or the optional approach above.
Would you like a short OpenAI Realtime + LiveKit Python snippet showing this integrated with a handoff?cool-salesmen-60705
11/22/2025, 4:45 PMtall-airline-16756
11/22/2025, 4:45 PMhandle = await session.say("Thanks — wrapping up now.", allow_interruptions=False)
await handle # wait until playout finishes
2) Send a data event to the frontend
# publish a reliable data packet on a topic your frontend listens to
await ctx.room.local_participant.publish_data(
json.dumps({"event": "agent_ended", "room": ctx.room.name}),
kind=DataPacket_Kind.RELIABLE,
topic="agent_events"
)
3) Close the session
await session.aclose() # or ctx.shutdown("done")
4) Frontend listener (JS example)
room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => {
if (topic === "agent_events") {
const data = JSON.parse(payload);
if (data.event === "agent_ended") {
// Move UI to next step
}
}
});
Notes:
• Use the SpeechHandle await to ensure the agent fully finishes speaking before signaling.
• Send the data packet as RELIABLE so the frontend reliably receives the event.
• If you prefer RPC instead of data packets, expose a short RPC method the frontend can call or poll after speech completes.
Would you like this integrated into your existing handoff code? If so, paste the snippet and I’ll adapt it.
Sources: Agent speech and audio | LiveKit docs | Job lifecycle | LiveKit docs | Turn detection and interruptions | LiveKit Docscool-salesmen-60705
11/22/2025, 4:46 PMtall-airline-16756
11/22/2025, 4:46 PMsession.say() / session.generate_reply() to know playout finished.
• Publish a reliable data packet (or RPC) from the room/local participant to notify the frontend.
• Then close the session (session.aclose() or ctx.shutdown()).
• Optional for stronger guarantees: disable audio input during the critical speech with session.input.set_audio_enabled(False).
Minimal Realtime Python flow
import json
from livekit_server.protocol import DataPacket_Kind
# agent reads final message without interruptions
handle = session.say("Wrapping up — next steps are...", allow_interruptions=False)
await handle # wait until playout completes
# notify frontend
await ctx.room.local_participant.publish_data(
json.dumps({"event": "agent_ended", "room": ctx.room.name}),
kind=DataPacket_Kind.RELIABLE,
topic="agent_events"
)
# close session
await session.aclose()
Frontend: listen for RoomEvent.DataReceived on topic "agent_events" and advance UI when event === "agent_ended".
If you want, I can:
• Add the temporary session.input.set_audio_enabled(False) wrapper, or
• Integrate this into your existing handoff code if you paste it. Which would you prefer?cool-salesmen-60705
11/22/2025, 4:58 PMtry:
# Close the session - this will trigger shutdown callbacks
await self.session.aclose()
logger.info(f"✅ SESSION_CLOSED conv={conversation_id}")
except Exception as close_error:
logger.error(f"❌ SESSION_CLOSE_ERROR conv={conversation_id}: {close_error}")
# Even if close fails, shutdown callback should still runtall-airline-16756
11/22/2025, 4:58 PM@server.rtc_session(on_session_end=...) or ctx.add_shutdown_callback(...) to register your on-session-end handler? If not, the callback won't run.
2) Await the speech handle before closing
• Ensure you awaited the SpeechHandle from session.say() or session.generate_reply() so playout finished before calling await session.aclose().
3) Use ctx.shutdown if inside the session handler
• If you're inside the session entrypoint, call await ctx.shutdown("reason") instead of `session.aclose()`; ctx.shutdown runs shutdown flow and callbacks.
4) Check for exceptions before close
• Wrap the await in try/except and log any exceptions from earlier code that might prevent reaching the close call.
5) Ensure you’re closing the same session object
• Verify self.session is the active AgentSession for that room/ctx (no accidental new session instance).
6) Add explicit log in shutdown callback
• Put a log at the top of your shutdown callback to confirm it runs:
async def on_session_end(ctx):
logger.info("on_session_end called for room=%s", ctx.room.name)
...
7) As a fallback, publish a final data event before close
• If SESSION_CLOSED still doesn't appear, send a reliable data packet to frontend, then close:
await ctx.room.local_participant.publish_data(json.dumps({"event":"agent_ended"}), kind=DataPacket_Kind.RELIABLE, topic="agent_events")
await ctx.shutdown("done")
If you share:
• how you register your shutdown callback (code),
• whether you used await handle before close, and
• whether you call ctx.shutdown or session.aclose(),
I’ll point exactly to the missing piece and provide an adjusted snippet.