how do i get the conversation transcript from an o...
# ask-ai
c
how do i get the conversation transcript from an openai-realtime conversation. it doesnt have to be live, i just want a record of it,
t
Thanks for reaching out, Nick. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You want a post-session record of an OpenAI Realtime conversation — here are the simplest ways to get it with LiveKit. 1) Use
session.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 Docs
c
y
t
Thanks — which language would you like the code example in: Python or JavaScript/TypeScript?
c
python
t
Below is a concise Python example that saves the conversation transcript when a Realtime session ends. It uses an
on_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).
Copy code
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?
c
i've used handoff to pass the conversation on to another agent but i want that second agent not to be interrupted when it reads something important out. how do i do that?
t
You're asking how to prevent the second agent (after a handoff) from being interrupted while it reads something important aloud — here's how to do that. 1) Block interruptions on the speak call • When the second agent speaks, call say() or generate_reply() with allow_interruptions=False:
Copy code
await 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:
Copy code
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 docs
c
does this work for openai-realtime?
t
Yes — this works for OpenAI Realtime. • Use
allow_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?
c
how can i send get the chat to end after the agent that wraps up has finished speaking and generate a signal for my frontend to move on?
t
You're asking how to end the chat after the final agent finishes speaking and signal your frontend to move on — here’s a concise Python pattern using LiveKit/OpenAI Realtime: 1) Wait for speech playout
Copy code
handle = await session.say("Thanks — wrapping up now.", allow_interruptions=False)
await handle  # wait until playout finishes
2) Send a data event to the frontend
Copy code
# 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
Copy code
await session.aclose()  # or ctx.shutdown("done")
4) Frontend listener (JS example)
Copy code
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 Docs
c
this is using realtime
t
Yes — the pattern I described works with OpenAI Realtime. Quick checklist and a minimal Python snippet tailored for Realtime: Checklist • Await the speech handle returned by
session.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
Copy code
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?
c
i tried this but never gotr SESSION_CLOSED
Copy code
try:
    # 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 run
t
Sorry that didn't trigger SESSION_CLOSED — let's narrow this down and get it working. Quick checklist and troubleshooting steps: 1) Confirm shutdown callback is registered • Are you using
@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:
Copy code
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:
Copy code
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.