I'm building an AI agent with call capabilities. I...
# ask-ai
c
I'm building an AI agent with call capabilities. I want to capture the transcriptions of the calls between the user and the AI agent, and store them in my database. Please let me know if anyone is already working on this.
t
Thanks for reaching out, Arockia. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To capture and store transcriptions of calls between a user and an AI agent, you can use LiveKit's event listeners to grab user and agent messages as they happen. Then, you can save them in your database or any external storage you prefer. Here's a quick rundown: • Use event listeners like
user_speech_committed
and
agent_stopped_speaking
to catch those transcriptions. • Save these transcriptions to a file or directly into your database. • Pull the whole conversation history from the session whenever you need and export it. If you'd like a hand with the details or need help connecting this with a specific database, just give me a shout!
c
Yes, please share some code snippets.
t
Here are some handy code snippets to help you capture and store transcriptions of calls between a user and an AI agent: 1. Server-side Transcription Storage:
Copy code
from datetime import datetime

async def save_transcription(speaker, text):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("transcriptions.log", "a") as f:
        f.write(f"{timestamp} - {speaker}: {text}\n")

# Example usage for user and agent messages
await save_transcription("user", "Hello, how can I help you?")
await save_transcription("agent", "I need assistance with my account.")
2. Real-time Event Handling:
Copy code
async def on_transcript(transcript):
    if transcript.is_final:
        await save_transcription("user", transcript.transcript)

async def on_agent_message(event):
    await save_transcription("agent", event.text)
3. Frontend Integration:
Copy code
import { useEffect, useState } from "react";
import { RoomEvent } from "livekit-client";

export default function TranscriptionHandler() {
  const [transcripts, setTranscripts] = useState([]);

  useEffect(() => {
    const handleTranscription = (event) => {
      setTranscripts((prev) => [...prev, event.transcription]);
    };

    room.on(RoomEvent.TranscriptionReceived, handleTranscription);
    return () => room.off(RoomEvent.TranscriptionReceived, handleTranscription);
  }, []);

  return null;
}
4. Save Session History:
Copy code
async def save_session_history(history):
    with open("session_history.json", "w") as f:
        json.dump(history, f, indent=2)

# Example usage during shutdown
await save_session_history(session.history)
If you have any questions or want me to walk you through any part of this, just let me know! I'm here to help.