I am using open ai realtime or gemini live in my p...
# ask-ai
a
I am using open ai realtime or gemini live in my project and call this in the on_enter function:
Copy code
await session.generate_reply(
            instructions=f"You're picking up the phone right now.{name_hint} Answer naturally like a real person would when answering their phone - typically just: 'Hallo, det er {clean_name}.', 'Det er {clean_name}.', or similar. If your name includes adjectives or descriptions, use only your actual first name. Keep it very brief and natural. Do NOT welcome anyone, do NOT say you're an assistant, do NOT offer help. Just answer the phone like you normally would. Make sure to use language (language code:{language}) in the response."
        )
The agent greets correctly but if it registers any noise it will "interrupt". I tried setting the allow_interruption but that doesnt seem to work for the realtime models. Any ideas?
t
Thanks for reaching out, Malte. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you avoid any interruptions while using OpenAI Realtime or Gemini Live models, you can set
allow_interruptions=False
in your
session.generate_reply()
call. This way, the agent won’t be interrupted by any user speech during playback, making the experience smoother for you. Here’s a quick example:
Copy code
await session.generate_reply(
    instructions="Respond without being interrupted",
    allow_interruptions=False
)
If you'd like this to apply across the board, you can also set
allow_interruptions=False
at the session level in your agent configuration. Please feel free to reach out if you have any more questions or need a hand with this—I’m here to help! Sources: livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | Turn detection and interruptions | LiveKit Docs
a
Copy code
WARNING livekit.agents - the RealtimeModel uses a server-side turn detection, allow_interruptions cannot be False when using VoiceAgent.generate_reply(), disable turn_detection in the RealtimeModel and use VAD on the AgentTask/VoiceAgent instead
That doesnt seem to work for realtime / gemini though
t
Thank you for reaching out! The warning you’re seeing means that the RealtimeModel is currently using server-side turn detection, which doesn’t work well with
allow_interruptions=False
. To get everything running smoothly, you’ll want to turn off server-side turn detection and instead use VAD (Voice Activity Detection) on the agent side. Here’s a friendly step-by-step to help you out: 1. Disable Server-Side Turn Detection: If you’re using the OpenAI Realtime API, simply set
turn_detection=None
when you initialize the RealtimeModel: `llm=openai.realtime.RealtimeModel( voice="alloy", turn_detection=None, # Disable server-side turn detection input_audio_transcription=None, )`If you’re working with the Gemini Live API, just disable automatic activity detection like this:
Copy code
llm=google.realtime.RealtimeModel(
    realtime_input_config=types.RealtimeInputConfig(
        automatic_activity_detection=types.AutomaticActivityDetection(
            disabled=True,
        ),
    ),
    input_audio_transcription=None,
)
2. Enable VAD on the Agent: Next, set up your agent to use VAD for turn detection with this configuration:
Copy code
session = AgentSession(
    vad=silero.VAD.load(),
    stt=deepgram.STT(),
    llm=openai.realtime.RealtimeModel(
        voice="alloy",
        turn_detection=None,
        input_audio_transcription=None,
    ),
    turn_detection="vad",  # Use VAD for turn detection
)
This way, turn detection happens locally using VAD, which prevents any conflicts with the server-side settings. If anything’s unclear or you’d like a hand with the setup, just let me know—I’m here to help! Sources: livekit-plugins/livekit-plugins-turn-detector/README.md | examples/src/realtime_turn_detector.ts | Gemini Live API plugin | LiveKit docs | Turn detection and interruptions | LiveKit Docs
a
Any other way to do this? Using the local VAD doesnt work well with danish - at least not as good as the "included" vad from the realtime session.
t
I understand this can be a bit tricky, so let me help clarify. Unfortunately, using the server-side VAD from the RealtimeModel while also preventing interruptions isn’t possible because these two features are designed in a way that they can’t work together. The server-side turn detection focuses on accurate, context-aware turn-taking, but it does allow interruptions as part of how it operates. If you’re finding that the local VAD isn’t performing well with Danish, you might want to consider relying on the server-side VAD and adjusting your application to handle interruptions smoothly. Another option could be to explore fine-tuning or customizing a local VAD model specifically for Danish speech, though this would involve some extra development work. Please feel free to reach out if you’d like any further help or guidance on either of these options—I’m here to support you! Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | plugins/openai/src/realtime/realtime_model.ts | Operational Best Practices | livekit/livekit_composite | DeepWiki
a
I am considering another idea. Not for the interruptions but for generating a better greeting message. I want to send an empty message in the on_enter in order to trigger a response. How do I do that again?
t
If you'd like to send an empty message in
on_enter
and have it trigger a response, you can simply use the
generate_reply()
method without giving it any input text. Here's a little example to help you out:
Copy code
async def on_enter(self):
    await self.session.generate_reply()
Another way is to explicitly pass an empty string like this:
Copy code
async def on_enter(self):
    await self.session.generate_reply(user_input="")
This will encourage the agent to create a response based on its instructions or the current context. Please feel free to ask if you'd like me to explain anything further—I’m here to help! Sources: Text and transcriptions | LiveKit docs | avatars/hedra/education_avatar/agent.py | Pipeline nodes and hooks | LiveKit docs
a
Im having another issue where I see the transcript for the greeting: "Det er Freja", but no audio is coming through. Is there an event where I can debug the responses from realtime. And do you by any chance have an idea?
t
I'm sorry to hear you're experiencing the transcript without audio. This usually points to a hiccup with the audio channel or playback setup. Let's work through some steps together to get this sorted out: 1. Verify Audio Events: First, check if
ResponseAudioDeltaEvent
events are coming through. These handle the audio frames, so if something’s off here, it might stop the audio from playing. 2. Confirm Modality Configuration: Make sure your RealtimeModel is set up to include audio modality, like this:
Copy code
model = RealtimeModel(
    modalities=["text", "audio"],
    voice="marin"
)
3. Monitor Audio Frame Processing: Double-check that audio frames are being decoded and sent properly to the audio channel, with the right sample rate (24kHz) and data size. 4. Check Audio Output: Ensure audio output is turned on and that buffers are cleared before playback starts. For example:
Copy code
if audio_output is not None:
    audio_output.clear_buffer()
    playback_ev = await audio_output.wait_for_playout()
5. Debugging Events: It might help to add listeners for both audio and transcript events so you can watch the response pipeline closely and spot where things might be going wrong. Please feel free to reach out if you'd like me to walk you through any of these steps or if you have any questions — I’m here to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | OpenAI Realtime API plugin guide | LiveKit docs | Azure OpenAI Realtime API and LiveKit | LiveKit Docs | How to Set Up Speech-to-Text Input with Text-Only Output in LiveKit Agents | plugins/openai/src/realtime/realtime_model.ts
a
It only happens on the first response, so this one:
Copy code
async def on_enter(self):
        try:
            await self.session.generate_reply()
        except Exception as e:
            logger.error(f"Error generating initial reply: {e}")
However works fine on the following responses. And only happens sometimes (which makes it tough to debug) How do I debug what is being sent in response?
t
To help you debug the first response in
on_enter
, here are some friendly techniques you can try: 1. Enable Logging: It’s really helpful to add logging inside
on_enter
so you can see when the method is called and
generate_reply
is triggered:
Copy code
async def on_enter(self):
    logger.info("Agent is entering the session and will generate a reply")
    await self.session.generate_reply()
2. Use Instructions: Try giving specific instructions in
generate_reply
to get a more predictable output:
await self.session.generate_reply(instructions="Greet the user and ask how you can help")
3. Monitor Events: Listening to the
speech_created
event can confirm that the response is being processed:
Copy code
@session.on("speech_created")
def on_speech_created(event):
    logger.debug(f"Speech created: {event.source}")
4. Check Agent State: Keeping an eye on state transitions (like
thinking
→
speaking
) helps validate the response flow. 5. Enable Debug Logs: You can set
LK_OPENAI_DEBUG=1
in your environment to get detailed logs from the RealtimeModel. 6. Use OpenTelemetry: For more advanced debugging, integrating tracing will capture the full lifecycle of the session. These steps should guide you toward finding where the issue might be. Please feel free to reach out if you’d like any help implementing them—I’m here to support you! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Agent speech and audio | LiveKit docs | agents/src/voice/agent_activity.ts
a
Heres some debugging
Copy code
2025-11-12 13:35:06,269 - DEBUG livekit.plugins.openai - <<< {'type': 'response.content_part.done', 'event_id': 'event_Cb4LyEDegkytQXgyE4jpm', 'response_id': 'resp_Cb4LxBhY5Ue6mi8KtaJRJ', 'item_id': 'item_Cb4LxXblJSR1yk0rFReth', 'output_index': 0, 'content_index': 0, 'part': {'type': 'audio', 'transcript': 'Det er Freja.'}} {"pid": 6554, "job_id": "AJ_v3qcwWHSnRGW"}
2025-11-12 13:35:06,269 - DEBUG livekit.plugins.openai - unhandled event: response.content_part.done {"event": {"type": "response.content_part.done", "event_id": "event_Cb4LyEDegkytQXgyE4jpm", "response_id": "resp_Cb4LxBhY5Ue6mi8KtaJRJ", "item_id": "item_Cb4LxXblJSR1yk0rFReth", "output_index": 0, "content_index": 0, "part": {"type": "audio", "transcript": "Det er Freja."}}, "pid": 6554, "job_id": "AJ_v3qcwWHSnRGW"}
2025-11-12 13:35:06,269 - DEBUG livekit.plugins.openai - <<< {'type': 'conversation.item.done', 'event_id': 'event_Cb4LynXG3F9A0cnW5JybK', 'previous_item_id': None, 'item': {'id': 'item_Cb4LxXblJSR1yk0rFReth', 'type': 'message', 'status': 'completed', 'role': 'assistant', 'content': [{'type': 'output_audio', 'transcript': 'Det er Freja.'}]}} {"pid": 6554, "job_id": "AJ_v3qcwWHSnRGW"}
2025-11-12 13:35:06,269 - DEBUG livekit.plugins.openai - unhandled event: conversation.item.done {"event": {"type": "conversation.item.done", "event_id": "event_Cb4LynXG3F9A0cnW5JybK", "previous_item_id": null, "item": {"id": "item_Cb4LxXblJSR1yk0rFReth", "type": "message", "status": "completed", "role": "assistant", "content": [{"type": "output_audio", "transcript": "Det er Freja."}]}}, "pid": 6554, "job_id": "AJ_v3qcwWHSnRGW"}
2025-11-12 13:35:06,269 - DEBUG livekit.plugins.openai - <<< {'type': 'response.output_item.done', 'event_id': 'event_Cb4LyDJHUAPAUD09RR6ze', 'response_id': 'resp_Cb4LxBhY5Ue6mi8KtaJRJ', 'output_index': 0, 'item': {'id': 'item_Cb4LxXblJSR1yk0rFReth', 'type': 'message', 'status': 'completed', 'role': 'assistant', 'content': [{'type': 'output_audio', 'transcript': 'Det er Freja.'}]}} {"pid": 6554, "job_id": "AJ_v3qcwWHSnRGW"}
2025-11-12 13:35:06,273 - DEBUG livekit.plugins.openai - <<< {'type': 'response.done', 'event_id': 'event_Cb4LyPUeD3fLv2z2grLIY', 'response': {'object': 'realtime.response', 'id': 'resp_Cb4LxBhY5Ue6mi8KtaJRJ', 'status': 'completed', 'status_details': None, 'output': [{'id': 'item_Cb4LxXblJSR1yk0rFReth', 'type': 'message', 'status': 'completed', 'role': 'assistant', 'content': [{'type': 'output_audio', 'transcript': 'Det er Freja.'}]}], 'conversation_id': 'conv_Cb4LxG2OdsumeJiR8MluU', 'output_modalities': ['audio'], 'max_output_tokens': 'inf', 'audio': {'output': {'format': {'type': 'audio/pcm', 'rate': 24000}, 'voice': 'alloy'}}, 'usage': {'total_tokens': 1273, 'input_tokens': 1248, 'output_tokens': 25, 'input_token_details': {'text_tokens': 1248, 'audio_tokens': 0, 'image_tokens': 0, 'cached_tokens': 0, 'cached_tokens_details': {'text_tokens': 0, 'audio_tokens': 0, 'image_tokens': 0}}, 'output_token_details': {'text_tokens': 11, 'audio_tokens': 14}}, 'metadata': {'client_event_id': 'response_create_8f88366004e0'}}} {"pid": 6554, "job_id": "AJ_v3qcwWHSnRGW"}
Seems no audio is part of this. Can you find anything in this?
t
Thanks for sharing the debug logs! It looks like the response includes a transcript but doesn’t have any audio data. This can sometimes happen if the RealtimeModel’s first response is treated as text-only, even when audio is set up. This usually relates to how the OpenAI Realtime API handles those initial responses, especially if there’s conversation history loaded or if the expected
response_audio_delta
event isn’t received. Here are a few steps that might help: 1. Verify Modality Configuration: Double-check that the RealtimeModel is initialized with
modalities=["text", "audio"]
and that the voice configuration is valid. 2. Check Audio Events: Make sure you’re receiving
response_audio_delta
events for that first response. If not, it could be an issue with the API itself. 3. Fallback to TTS: As a helpful workaround, you might try setting the RealtimeModel to text-only (
modalities=["text"]
) and then use a TTS instance alongside it to get consistent audio output. If you’d like, I’m here to guide you through these steps or help with any further troubleshooting. Just let me know! Sources: agents/src/voice/audio_recognition.ts | OpenAI Realtime API plugin guide | LiveKit docs | Azure OpenAI Realtime API and LiveKit | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | Realtime model plugins | LiveKit Docs
a
How do I check the response_audio_delta Im doing this: @session.on("speech_created") def on_speech_created(event): logger.debug(f"Speech created: {event}") But dont really see anything
t
To check
response_audio_delta
events and debug audio responses, you’ll want to listen to the audio stream provided by the
MessageGeneration
object. Here’s a simple way to do that: 1. Access the Audio Stream: When you trigger a response, the
MessageGeneration
object includes an
audio_stream
that you can tap into:
Copy code
async for message in session.message_stream:
    async for audio_frame in message.audio_stream:
        print(f"AudioFrame: sample_rate={audio_frame.sample_rate}, duration={len(audio_frame.data) / (audio_frame.sample_rate * audio_frame.num_channels) * 1000:.1f}ms")
2. Verify Audio Events: Make sure that
response.audio.delta
events are coming through and being handled properly. These events carry base64-encoded PCM16 audio chunks, which you can decode into
AudioFrame
objects. 3. Debugging Tools: Feel free to log audio frame details, play the audio live using libraries like
sounddevice
, or save it to a file so you can analyze it later at your own pace. If you’d like, I’m here to help you implement this or clarify anything further—just let me know! Sources: livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | plugins/openai/src/realtime/realtime_model.ts | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki