Give me an example in Python on how to handle gett...
# ask-ai
m
Give me an example in Python on how to handle getting transcripts for Google real-time API., both for input audio transcription and output audio transcription.
t
Thanks for reaching out, Rishabh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to handle both input and output audio transcription using the Google Realtime API in Python, you can set up the transcription settings and manage events for both user and agent speech. Here’s a simple example to get you started:
Copy code
import asyncio
import os
from livekit import rtc
from livekit.agents import JobContext, cli, stt
from livekit.plugins import google

# Make sure to set your GOOGLE_API_KEY in your .env file or right here
# os.environ["GOOGLE_API_KEY"] = "your-api-key"

async def entrypoint(ctx: JobContext):
    # Set up the RealtimeModel with transcription enabled
    llm = google.beta.realtime.RealtimeModel(
        api_key=os.environ.get("GOOGLE_API_KEY"),
        input_audio_transcription=google.genai.types.AudioTranscriptionConfig(),
        output_audio_transcription=google.genai.types.AudioTranscriptionConfig(),
    )

    session = llm.session()

    # Listen for user speech transcription
    @session.on("input_audio_transcription_completed")
    def on_input_transcription(event: stt.SpeechEvent):
        transcript = event.alternatives[0].text
        print(f"User said: {transcript}")

    # Listen for agent speech transcription
    @session.on("generation_created")
    def on_generation_created(event: stt.SpeechEvent):
        async def handle_text_stream():
            async for text in event.message_stream:
                print(f"Agent response (partial): {text}")
        asyncio.create_task(handle_text_stream())

    @session.on("generation_completed")
    def on_generation_completed(event: stt.SpeechEvent):
        print("Agent finished speaking")

    # Connect to the room and start processing audio
    # await session.connect(ctx.room)

if __name__ == "__main__":
    cli.run_app(JobContext(entrypoint_fnc=entrypoint))
This example shows you how to set up transcription and handle events for both input and output audio. If you want, I’m here to help you with setting up room audio or any other integration details you might need. Just let me know! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | agent/main.py
m
session = AgentSession() @session.on("input_audio_transcription_completed") def on_input_transcription(event: stt.SpeechEvent): transcript = event.alternatives[0].text print("*"*10) print(f"User said: {transcript}") print("*"*10) # Listen for agent speech transcription @session.on("generation_created") def on_generation_created(event: stt.SpeechEvent): async def handle_text_stream(): async for text in event.message_stream: print(f"Agent response (partial): {text}") asyncio.create_task(handle_text_stream()) @session.on("generation_completed") def on_generation_completed(event: stt.SpeechEvent): print("*"*10) print("Agent finished speaking") print("*"*10) await session.start( agent=VisionAssistant(), room=ctx.room, room_input_options=RoomInputOptions( video_enabled=True, noise_cancellation=noise_cancellation.BVC(), ), ) if name == "__main__": cli.run_app( WorkerOptions( entrypoint_fnc=entrypoint ) ) Above is my code, how should I see this print statements?
t
Hey there! To check out the
print
statements in your code, here’s a quick guide depending on where you’re working: • Locally: Just run your script like usual with
python your_script.py
. You’ll see all the
print
outputs right in your terminal. • Deployed on LiveKit Cloud: Use the command
lk agent logs
to stream the runtime logs from the latest running instance of your agent. This will show you all the
print
outputs there. • For testing: Turn on verbose output by setting the environment variable
LIVEKIT_EVALS_VERBOSE=1
, then run your tests with
pytest -s
so the stdout won’t be captured and you can see the prints. If you want me to walk you through any of these or have other questions, just let me know—I’m here to help! Sources: Testing and evaluation | LiveKit Docs | translators/tts_translator.py | livekit-agents/livekit/agents/cli/_run.py | Log collection | LiveKit Docs
m
Where these events are not getting triggered and I don't see the prints locally.
t
Hey there! Just wanted to share a few reasons why the events
input_audio_transcription_completed
and
generation_created
might not be triggering: • Prerequisites: These events rely on earlier ones like
input_speech_started
or certain server-side triggers. If those aren’t happening, the later events won’t either. • Session Configuration: Double-check that
input_audio_transcription
and
output_audio_transcription
are turned on in your session setup. • Server Activity: The server needs to be actively processing input and kicking off responses. If there’s no input or a server hiccup, events like
generation_created
won’t fire. • Audio Input: Make sure audio is streaming properly to the session. Without good input, transcription events just won’t trigger. Take a look at your session setup and confirm the audio input is flowing through. And if you want, I’m here to help you check these settings or troubleshoot anything else! Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | plugins/openai/src/realtime/realtime_model.ts
m
Can I just get the entire chat history at the end of the session?
t
Hey there! If you want to grab the entire chat history at the end of a LiveKit session, you can use the
session.history
property. Here are a couple of ways to do it: • Using a shutdown callback: You can add a function that saves the history right when the session ends:
Copy code
def entrypoint(ctx: JobContext):
    async def write_transcript():
        current_date = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"/tmp/transcript_{ctx.room.name}_{current_date}.json"
        with open(filename, 'w') as f:
            json.dump(session.history.to_dict(), f, indent=2)
        print(f"Transcript for {ctx.room.name} saved to {filename}")

    ctx.add_shutdown_callback(write_transcript)
• Listening for the session close event: Another way is to access the history right when the session closes:
Copy code
@session.on("close")
def on_close(ev: CloseEvent):
    print("Chat History:")
    for item in session.history.items:
        if item.type == "message":
            text = f"{item.role}: {item.text_content.replace('\n', '\\n')}"
            if item.interrupted:
                text += " (interrupted)"
            print(text)
If you want, I’m here to help you set this up or even get long-term storage going for your chat history. Just let me know! Sources: Session recording and transcripts | LiveKit Docs | Workflows | LiveKit Docs | livekit-agents/livekit/agents/voice/audio_recognition.py | Sending text | LiveKit Docs | Sending text | LiveKit Docs
Thank you for reaching out! I want to make sure I fully understand how to assist you. Could you please share a bit more detail or clarify your last message? I'm here to help!