give me an example of how to save the full call tr...
# ask-ai
r
give me an example of how to save the full call transcript between the user and agent to my database when the call ends/user leaves the room via session.history in the python file
t
Thanks for reaching out, Prince. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To save the full call transcript using
session.history
in Python when the call ends or the user leaves the room, here’s a helpful approach you can try:
Copy code
from datetime import datetime
import json
import logging

async def entrypoint(ctx: JobContext):
    session = AgentSession(
        stt=deepgram.STT(),
        llm=openai.LLM(),
        tts=cartesia.TTS(),
        vad=silero.VAD.load(),
    )

    # Define shutdown callback for saving transcript
    async def write_transcript():
        try:
            # Ensure any pending agent responses are flushed
            await session.aclose()

            current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"/tmp/transcript_{ctx.room.name}_{current_date}.json"
            
            # Convert history to dictionary and save
            transcript_data = session.history.to_dict()
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(transcript_data, f, indent=2)

            <http://logging.info|logging.info>(f"Transcript saved to {filename}")
        except Exception as e:
            logging.error(f"Failed to save transcript: {e}")

    # Register the shutdown callback
    ctx.add_shutdown_callback(write_transcript)

    # Start the session
    await session.start(agent=MyAgent(), room=ctx.room)
Key Points: • Make sure to use
session.aclose()
so all conversation items are properly finalized before saving. • It’s a good idea to wrap file operations in a
try-except
block to gracefully handle any unexpected errors. • For production, consider saving the transcript to a persistent and easily accessible location, like cloud storage. If you have any questions or would like me to walk you through this further, just let me know—I’m here to help! Sources: basics/exit_message.py | Inside a session | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/stt.py | Session recording and transcripts | LiveKit Docs | Workflows | LiveKit Docs