How can I set the OpenAI Realtime plugin to start ...
# ask-ai
a
How can I set the OpenAI Realtime plugin to start the conversation in English?
t
Thanks for reaching out, Jeff. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you set the OpenAI Realtime plugin to start the conversation in English, here are a few simple ways you can configure the language settings: • Set Agent Instructions: You can kindly instruct the agent to always respond in English. For example, in Python:
Copy code
from livekit.plugins.openai.realtime import RealtimeModel
from livekit.agents.voice import Agent, AgentSession

agent = Agent(instructions="You are a helpful assistant created by LiveKit, always speaking English.")
session = AgentSession(llm=RealtimeModel(voice="alloy"))
await session.start(agent=agent, room=ctx.room)
• Configure Input Audio Transcription: Another way is to specify the transcription model to use English. For example:
Copy code
from openai.types import realtime
model = RealtimeModel(voice="alloy", input_audio_transcription=realtime.AudioTranscription(model="gpt-4o-mini-transcribe"))
• Use Separate STT: You might also consider using a separate speech-to-text model set to English like this:
Copy code
from livekit.plugins import openai, deepgram
session = AgentSession(stt=deepgram.STT(language="en"), llm=openai.realtime.RealtimeModel(voice="alloy"))
These options will help ensure that both the audio input processing and text generation start off in English smoothly. If you have any questions or need a hand with anything else, please feel free to ask—I’m here to help! Sources: examples/voice_agents/realtime_turn_detector.py | OpenAI Realtime API plugin guide | LiveKit Docs | plugins/openai/src/realtime/realtime_model.ts
a
Great, a more simple prompt starting with "Start the conversation in English." Seemed to fix it. Another question, why would the JobContext metadata field have all the passed information, but the room_started webhook not have it?
t
Thank you for your question! The
JobContext
metadata field is designed to hold all the information you pass along because it’s meant to carry custom, user-defined data during agent dispatch. This means you can access this metadata within the agent's runtime context to help initialize or customize its behavior. On the other hand, the
room_started
webhook doesn’t include this metadata by default. Webhook payloads are kept simple and standardized, including only key details like
id
,
createdAt
, and basic room or participant identifiers. This helps keep webhooks lightweight and focused on sending external notifications, while the
JobContext
metadata stays securely available inside the agent process. If you want to access metadata outside the agent, such as in a webhook, a great approach is to store it in the room metadata field using server APIs. This way, you can retrieve it independently whenever you need. Please feel free to reach out if you'd like me to walk you through how to set this up—I’m here to help! Sources: Job lifecycle | LiveKit Docs | Agent dispatch | LiveKit Docs | Webhooks | LiveKit Docs | Room metadata | LiveKit Docs
a
How do I make the AI agent speak first?
t
I'd be happy to help you get the AI agent to speak first in LiveKit! You have two great options to choose from: • Use
generate_reply()
for Dynamic Greetings:
This lets the agent create a response that fits the context. For example, in Python:
Copy code
agent.generate_reply(instructions="Greet the user and ask how you can help them today.")
• Use
say()
for Predefined Messages:
This makes the agent say a specific message right away. For example:
Copy code
await agent.say("Hi there, how are you doing today?", allow_interruptions=True)
Both of these methods will make sure your agent starts the conversation smoothly. If you'd like, I’m here to help you implement this or answer any other questions you might have! Sources: agent/main.py | Voice AI quickstart | LiveKit Docs | agent.py | delay-handling/agent.py | examples/src/push_to_talk.ts
a
How can I report on LLM metrics in the call?
t
I'm glad you're interested in reporting on LLM metrics during a LiveKit call! Here are some helpful methods you can use to get those insights: • Log Metrics to Console: You can listen to the
metrics_collected
event to see performance details like duration, time to first token, and token usage right in your console. Here's a simple example:
Copy code
@agent.on("metrics_collected")
def _on_metrics_collected(mtrcs):
    print(f"LLM Response Duration: {mtrcs.duration:.4f}s")
    print(f"Total Tokens Used: {mtrcs.total_tokens}")
• Aggregate Metrics: If you'd like to track metrics throughout the entire session, the
UsageCollector
class is a great tool. It helps you gather totals like tokens used or audio durations seamlessly.
Copy code
collector = metrics.UsageCollector()
@agent.on("metrics_collected")
def _on_metrics_collected(mtrcs):
    collector.collect(mtrcs)
summary = collector.get_summary()
print(f"Total Tokens: {summary.llm_prompt_tokens}")
• Export Metrics: For sharing your metrics with other systems or for deeper analysis, you can send them via HTTP. Just swap out
<METRICS_SERVER_URL>
with your own endpoint.
Copy code
async def send_metrics_to_server(data):
    await requests.post("<METRICS_SERVER_URL>/metrics", json=data)
• OpenTelemetry Integration: If you're aiming for comprehensive monitoring, enabling telemetry in your worker configuration captures these metrics as part of distributed traces, giving you end-to-end visibility. I hope these options make it easier for you to log, aggregate, or export your LLM metrics. If you'd like, I’m here to help guide you through implementing any of these—just let me know! Sources: livekit-agents/livekit/agents/metrics/base.py | agent/main.py | docs/index.yaml | Community & Support | livekit/livekit_composite | DeepWiki | Logs, metrics, and telemetry | LiveKit Docs
a
What does the schema for the metrics to post look like?
t
I'm happy to walk you through the schema for posting LLM metrics in LiveKit! It’s defined by the
LLMMetrics
type and includes these important fields: • type: This is a string literal "llm_metrics" that indicates the type of metrics we’re dealing with. • label: A string that identifies the component or model generating the metrics. • request_id: A unique identifier for each request, helping us keep track. • timestamp: The exact time when the metrics were recorded, given in seconds as a float. • duration: How long the LLM inference took, measured in seconds. • ttft: The time to first token, also in seconds. • cancelled: A simple true/false indicating whether the request was cancelled. • completion_tokens: The number of tokens generated by the LLM in its completion. • prompt_tokens: How many tokens were in the input prompt sent to the LLM. • prompt_cached_tokens: Tokens that were cached in the input prompt. • total_tokens: The total token usage, which is the sum of prompt and completion tokens. • tokens_per_second: The rate at which tokens were generated, measured in tokens per second. • speech_id: An optional unique identifier representing a turn in the user input. • metadata: An optional object that can include extra details like
model_name
and
model_provider
. This schema is emitted right after each LLM inference finishes, and it’s super useful for logging, analyzing, or exporting data to external systems. If you’d like, I’m here to provide more details or examples—just let me know! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Logs, metrics, and telemetry | LiveKit Docs
a
How can I export a transcript of the call at the end?
t
To help you export a transcript of a LiveKit call at the end, here’s a simple step-by-step guide you can follow: 1. Enable Transcription: When you start the agent session, just use
RoomOutputOptions(transcription_enabled=True)
to turn on real-time transcription. This sets everything up nicely from the start. 2. Capture Final Transcripts: Keep an eye out for the
SpeechEventType.FINAL_TRANSCRIPT
event to gather the finalized speech segments. Here’s a quick example to show you how:
Copy code
async def on_final_transcript(ev):
    text = ev.alternatives[0].text
    print(f"Final transcript: {text}")
    # Append to a buffer or save to a file
1. Save the Transcript: When your session wraps up, you can write the collected transcript to a file like this:
Copy code
with open("transcript.txt", "w") as f:
    f.write(transcript_buffer)
1. Optional - Use Egress: If you want to take it a step further, you can combine transcription with LiveKit’s Egress feature to record the session’s audio/video and sync it with the transcript for later use. Right now, LiveKit doesn’t offer a built-in export to formats like
.vtt
or
.srt
, but you can definitely create these formats yourself using the transcript data you’ve collected. If you’d like, I’m here to help you with how to implement a specific export format—just let me know! Sources: livekit-agents/livekit/agents/stt/multi_speaker_adapter.py | agents/src/stt/stt.ts | packages/livekit-rtc/src/transcription.ts | Session recording and transcripts | LiveKit Docs | Recording and export | LiveKit docs
a
What is the event handler type for the final transcript speech event?
t
I'm glad you asked about the event handler type for the final transcript speech event in LiveKit! It's called
SpeechEventType.FINAL_TRANSCRIPT
. This event happens when the speech-to-text system wraps up a segment of speech, making sure the transcription won’t change anymore. You’ll find this is commonly used in many STT plugins like Deepgram, AWS, and AssemblyAI to indicate finalized transcriptions during streaming sessions. If you'd like, I’m here to help with more details or even some examples to get you started! Sources: livekit-agents/livekit/agents/stt/stt.py | Text and transcriptions | LiveKit Docs
a
Does that event come with the openAI realtime api?
t
Absolutely! The
SpeechEventType.FINAL_TRANSCRIPT
event does work with the OpenAI Realtime API in LiveKit. This event is triggered once the OpenAI Realtime API finishes transcribing a user's audio input and sends a
conversation.item.input_audio_transcription.completed
message. This event makes sure you have a finalized transcription ready, following the standard
FINAL_TRANSCRIPT
approach used across LiveKit's STT plugins. If you'd like, I’m here to help with any more details or guide you through the implementation—just let me know! Sources: plugins/openai/src/realtime/realtime_model.ts | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | Realtime model plugins | LiveKit Docs
a
Do I need a
@session.on
to register the event handler?
t
Hi there! You actually don’t need to use
@session.on
to register the
SpeechEventType.FINAL_TRANSCRIPT
event handler. The final transcription events are handled behind the scenes by the STT plugins and are automatically emitted whenever a finalized transcription result is ready. If you’re working on agent-level logic, a great way to access transcription results is by using the
user_input_transcribed
event in the
AgentSession
. This event includes a handy boolean
is_final
property that helps you tell final results apart from interim ones. If you’d like, I’m here to help you set this up—just let me know! Sources: livekit-plugins/livekit-plugins-gladia/livekit/plugins/gladia/stt.py | plugins/deepgram/src/stt.ts | Text and transcriptions | LiveKit Docs | Events and error handling | LiveKit Docs | How to detect when an agent has finished speaking
a
Yes please, can you provide the code to set that up in the Python agent?
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
a
Is there an agent equivalent to the
UserInputTranscribedEvent
event?