I use livekit agents with gpt-realtime and create ...
# ask-ai
l
I use livekit agents with gpt-realtime and create a session like this:
Copy code
session = AgentSession(
    llm=openai.realtime.RealtimeModel.with_azure(
            azure_deployment="gpt-realtime",
            azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
            api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
            api_version="2024-10-01-preview",
            voice="marin",
            turn_detection=TurnDetection(type="semantic_vad", create_response=True, interrupt_response=True),
    )
)
I also added a handler for debugging to check whether transcription works like this:
Copy code
@session.on("user_input_transcribed")
def on_user_input_transcribed(event: UserInputTranscribedEvent):
    logger.info(f"[{event.speaker_id}] User input transcribed: {event.transcript}, final: {event.is_final}")
The problem is, that the speaker_id is always None for user speech. In my frontend, I have a transcription handler subscriped on the 'lk.transcriptions' topic and it receives all transcripts. But the transcripts from the user are sent with the agent's participantIdentity and not the user's participantIdentity. Do you know why and is the root cause for this behaviour that the event.speaker_id is None?
t
Thanks for reaching out, Dariush. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you better and make sure we get to the bottom of this, could you please share a bit more info with me? • Are you using any custom configurations or middleware that might be influencing participant identities or how transcription is handled? • Is the agent and user chatting within the same room, and do participants have any special roles or permissions assigned? • Have you noticed if this issue happens across different sessions or environments as well? Knowing these details will really help us understand why the speaker_id is showing as None and why the transcript identity might not be matching up. I’m here to help you through this!
l
1. No I am not, I don't touch livekit's transcription logic. 2. yes, they are in the same room, they do not have any special roles or permissions (I don't assign any miself) 3. It happens all the time in every session
t
Thank you for sharing the details! The issue with
speaker_id
showing up as
None
in the
user_input_transcribed
event often happens because the Speech-to-Text (STT) plugin might not support speaker diarization, or the event is dealing with interim results. Usually, speaker identification needs the final transcript with high confidence, and some plugins only fill in the
speaker_id
for those final transcripts. About the user transcripts appearing with the agent's
participantIdentity
, this can happen if the agent is re-sending or echoing the user's transcription back into the room using its own output methods like
session.say()
. Ideally, user transcripts should be published under the user's own participant identity through the
RoomIO._user_tr_output
component. Here are a few steps that might help you move forward: • Check if your STT plugin supports speaker diarization and make sure it’s set up properly. • Review your transcription forwarding logic to confirm user transcriptions go through the right output sink (
_user_tr_output
) and aren’t being re-sent by the agent. • Look over any use of
session.say()
or similar functions to ensure the agent isn’t unintentionally creating new messages with user transcriptions. Please feel free to reach out if you'd like me to walk you through any of these steps or if you have more questions. I’m here to help! Sources: Events and error handling | LiveKit Docs | livekit-plugins/livekit-plugins-speechmatics/livekit/plugins/speechmatics/s...
l
I have a very basic setup, this is everything there is for my agent:
Copy code
import json
import os

from dotenv import load_dotenv
from livekit.agents import (
    Agent,
    AgentSession,
    AutoSubscribe,
    JobContext,
    UserInputTranscribedEvent,
    WorkerOptions,
    cli,
    log
)
from livekit.plugins import openai
from openai.types.beta.realtime.session import TurnDetection

logger = log.logger

# Only load .env when local, not when running in a Docker container
if os.path.isfile('.env'):
    load_dotenv(dotenv_path=".env", override=False)


async def entrypoint(ctx: JobContext):
    """Main logic for handling one job (i.e., one room interaction)."""

    logger.info(f"Connecting to room {ctx.room.name}")
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)

    remote_participant = await ctx.wait_for_participant()
    metadata: dict = json.loads(remote_participant.metadata)
    logger.info(f"Participant connected: {remote_participant.identity}, with metadata: {metadata}")

    agent = Agent(instructions="you are an Agent.")
    session = AgentSession(
        llm=openai.realtime.RealtimeModel.with_azure(
                azure_deployment="gpt-realtime",
                azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
                api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
                api_version="2024-10-01-preview",
                voice="marin",
                turn_detection=TurnDetection(type="semantic_vad", create_response=True, interrupt_response=True),
        )
    )

    @session.on("user_input_transcribed")
    def on_user_input_transcribed(event: UserInputTranscribedEvent):
        logger.info(f"[{event.speaker_id}] User input transcribed: {event.transcript}, final: {event.is_final}")

    await session.start(agent=agent, room=ctx.room)
    await session.generate_reply(instructions=f"Say 'Hi!'")


def main():
    """Run the worker CLI with prewarm and job entrypoint."""
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            port=os.getenv("AGENT_PORT", 35087),
        )
    )


if __name__ == "__main__":
    main()
The event.speaker_id is always None, and in my frontend I receive all transcripts with the agents participantIdentity.
t
It looks like the issue with
speaker_id
being
None
is probably because the Speech-to-Text (STT) plugin you’re using doesn’t have speaker diarization enabled. LiveKit depends on the STT plugin to provide that info, so if diarization isn’t supported or turned on,
speaker_id
will stay
None
. For instance, with plugins like Speechmatics, you’ll want to make sure you explicitly enable diarization by setting
enable_diarization=True
in the plugin’s configuration. About the user transcripts showing up with the agent’s
participantIdentity
, this can happen if the agent is unintentionally re-sending or echoing the user’s transcription back into the room. By default, LiveKit assigns the first participant as the agent unless you’ve configured it differently. It’s a good idea to double-check your transcription forwarding logic to confirm that user transcriptions are going through the right output sink (
_user_tr_output
) and not accidentally being re-sent by the agent. Here are a couple of steps that might help clear things up: • Take a look at your STT plugin configuration and enable speaker diarization if it’s available. • Review your transcription handling to make sure user transcripts aren’t being re-sent by the agent. If you’d like, I’m here to help you walk through these steps or dive into specific plugin settings. Just let me know! Sources: tests/test_speaker_id_grouping.py | Events and error handling | LiveKit Docs | How to set a fixed participant for agent audio processing | Events and error handling | LiveKit Docs | Speechmatics STT integration guide | LiveKit Docs
l
I don't have an STT plugin. Is there something I need to configure for the llm=openai.realtime.RealtimeModel.with_azure ?
t
Thank you for your question! I wanted to let you know that the
openai.realtime.RealtimeModel.with_azure
configuration doesn’t currently support speaker diarization or the
speaker_id
parameter. This setup mainly focuses on parameters like
azure_deployment
,
api_version
,
voice
, and
turn_detection
, but unfortunately, it doesn’t include options for diarization or speaker identification. If speaker diarization is really important for your project, I’d recommend trying a different Speech-to-Text (STT) plugin. For example, the Speechmatics integration specifically supports diarization and can fill in the
speaker_id
field in LiveKit events. Please feel free to reach out if you’d like some help setting up an alternative STT plugin or if you have any other questions about your current setup—I’m here to help! Sources: plugins/openai/src/realtime/realtime_model.ts | livekit-plugins/livekit-plugins-speechmatics/README.md | Speechmatics STT integration guide | LiveKit Docs | Speechmatics STT integration guide | LiveKit Docs | Azure OpenAI Realtime API and LiveKit | LiveKit Docs
l
I did some more testing:
Copy code
import asyncio
import json
import os

from dotenv import load_dotenv
from livekit.agents import (
    Agent,
    AgentSession,
    AutoSubscribe,
    JobContext,
    UserInputTranscribedEvent,
    WorkerOptions,
    cli,
    log
)
from livekit.plugins import openai
from openai.types.beta.realtime.session import TurnDetection

logger = log.logger

# Only load .env when local, not when running in a Docker container
if os.path.isfile('.env'):
    load_dotenv(dotenv_path=".env", override=False)


async def entrypoint(ctx: JobContext):
    """Main logic for handling one job (i.e., one room interaction)."""

    logger.info(f"Connecting to room {ctx.room.name}")
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)

    remote_participant = await ctx.wait_for_participant()
    metadata: dict = json.loads(remote_participant.metadata)
    logger.info(f"Participant connected: {remote_participant.identity}, with metadata: {metadata}")

    agent = Agent(instructions="you are an Agent.")
    session = AgentSession(
        llm=openai.realtime.RealtimeModel.with_azure(
                azure_deployment="gpt-realtime",
                azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
                api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
                api_version="2024-10-01-preview",
                voice="marin",
                turn_detection=TurnDetection(type="semantic_vad", create_response=True, interrupt_response=True),
        )
    )

    @session.on("user_input_transcribed")
    def on_user_input_transcribed(event: UserInputTranscribedEvent):
        logger.info(f"[{event.speaker_id}] User input transcribed: {event.transcript}, final: {event.is_final}")
        if event.speaker_id is None:
            logger.info(f"sending to user: SOMETEXT")
            asyncio.create_task(ctx.room.local_participant.send_text(text='SOMETEXT', topic="lk.transcription"))

    await session.start(agent=agent, room=ctx.room)
    await session.generate_reply(instructions=f"Say 'Hi!'")


def main():
    """Run the worker CLI with prewarm and job entrypoint."""
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            port=os.getenv("AGENT_PORT", 35087),
        )
    )


if __name__ == "__main__":
    main()
Even these SOMETEXT strings are received in the frontend but their participantIdentity is the agent's participant identity. How is this possible?
t
When you use
local_participant.send_text
in your agent's session, LiveKit kindly takes care of assigning the agent's
participantIdentity
to the message for you. This happens because the
local_participant
represents the agent within the room, so any message sent this way naturally reflects the agent's identity. This thoughtful design helps keep all messages clearly linked to their source. If you'd like to distinguish between user and agent messages, you might consider adding some custom logic to tag and handle messages before sending them. I'm here to help if you'd like guidance on setting this up or if you have any other questions. Just let me know! Sources: src/room/participant/LocalParticipant.ts | livekit-ffi/src/server/participant.rs | livekit-agents/livekit/agents/voice/room_io/room_io.py | Text and transcriptions | LiveKit Docs | Rooms, participants, and tracks | LiveKit Docs