livekit agent latest version, inside on_track_subs...
# ask-ai
c
livekit agent latest version, inside on_track_subscribed execute well but agent session not received speech
t
Thanks for reaching out, Khanh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you share a bit more about your setup? For example: • Are you working with a particular SDK or API for the LiveKit agent? • Which exact version of the LiveKit agent are you using? • Have you noticed any error messages or logs when the speech isn’t coming through? • Does this happen all the time, or just sometimes? Knowing these details will really help us get to the bottom of this and find a solution together.
c
here my full code, i use version 1.0, no error mesage, it alway happen
t
Hey there! If you’re seeing that
on_track_subscribed
is running but no speech is coming through, let’s walk through a few things together to get it sorted: 1. Agent Track Subscription Configuration: Double-check that your agent is set to subscribe to audio tracks using
AutoSubscribe.AUDIO_ONLY
or
AutoSubscribe.SUBSCRIBE_ALL
. If it’s set to
SUBSCRIBE_NONE
, you’ll need to handle the subscription manually. 2. Proper Audio Stream Handling: In your
on_track_subscribed
callback, make sure you’re creating and iterating over an
AudioStream
object asynchronously to process those audio frames. Also, keep an eye out for any exceptions that might be quietly stopping the async loop. 3. Source Participant Audio Activity: Check that the participant sending the audio is actually speaking and hasn’t muted their track. If you can, use events like
IsSpeakingChanged
to keep track of their speaking status. 4. Detailed Logging: It really helps to add some logging around when tracks get subscribed, when audio frames come in, and if any errors pop up. For example, log the participant’s identity and the track SID when a subscription happens, and keep count of the audio frames you receive. 5. Track Subscription Failures: Don’t forget to subscribe to
TrackSubscriptionFailed
events. These can tell you if there are any subscription hiccups, like network issues. If you’re still running into trouble, try deploying the agent closer to the media source to cut down on latency. Also, make sure audio isn’t being muted because of silence detection or codec mismatches. Lastly, check your network and any downstream processing to ensure nothing’s accidentally blocking the audio. Feel free to reach out if you want me to walk you through any of these steps or if you have any other questions — I’m here to help! Sources: Speech-to-text (STT) integrations | LiveKit Docs | terminal-client/client.py | pkg/loadtester/agentloadtester.go | Getting Help | livekit/livekit_composite | DeepWiki | Speech & Audio Processing | livekit/livekit_composite | DeepWiki
c
Track Subscription sucess, how to Proper Audio Stream Handlin
t
Hey there! To smoothly handle audio streams after you’ve successfully subscribed to a track, here’s a simple step-by-step guide: 1. Create an AudioStream Object: Start by using the subscribed track to create an
AudioStream
object. This lets you process audio frames asynchronously, which is super handy. 2. Iterate Over Audio Frames: Use an asynchronous loop to go through each audio frame from the stream. Don’t forget to handle exceptions so nothing slips by unnoticed. 3. Log and Process Frames: It’s a good idea to log the frames you receive for debugging, and then process them as your app needs. 4. Close the Stream: When you’re done, make sure to properly close the stream to free up resources. Here’s a friendly example to help you get started:
Copy code
@ctx.room.on("track_subscribed")
def on_track_subscribed(track: rtc.Track, publication: rtc.TrackPublication, participant: rtc.RemoteParticipant):
    if track.kind == rtc.TrackKind.KIND_AUDIO:
        asyncio.create_task(process_audio(track, participant))

async def process_audio(track: rtc.Track, participant: rtc.RemoteParticipant):
    audio_stream = rtc.AudioStream(track)
    frame_count = 0
    try:
        async for event in audio_stream:
            if event.frame:
                frame_count += 1
                logger.debug(f"Received audio frame {frame_count} from {participant.identity}")
                # Process the frame here
    except Exception as e:
        logger.error(f"Error processing audio stream: {e}")
    finally:
        await audio_stream.aclose()
This should make sure your audio frames are handled nicely, and any hiccups get logged so you can troubleshoot easily. If you want me to walk you through any part or if you have questions, just give me a shout!
c
i mean agent session not receive audio
t
Hey there! If your agent session isn’t picking up audio after a successful track subscription, no worries—here’s a friendly checklist to help you troubleshoot and get things back on track: 1. Verify Event Emission: First, make sure the
track_subscribed
event is actually firing and showing up in your logs. If it’s not, take a look for muted tracks or subscription hiccups by checking the
track_subscription_failed
event. 2. Log Frame Reception: Next, double-check that audio frames are coming through by iterating over the
AudioStream
. Try logging each frame to catch if any are getting silently dropped. 3. Check Auto-Subscribe Setting: Make sure you’re joining the room with
auto_subscribe=True
. If that’s set to
False
, you’ll want to add some manual subscription logic for those audio tracks. 4. Validate RoomIO Setup: If RoomIO is in play, confirm that the
subscribed_fut
future completes successfully—that’s your green light that the initial subscriptions are all set. 5. Inspect Audio Forwarding: In your agent session, double-check that
audio_input
is properly assigned and that the audio forwarding task is up and running. 6. Handle Pre-Connect Audio: If this applies to you, peek at the
TF_PRECONNECT_BUFFER
feature flag to see if there’s any buffered audio waiting to be processed before the user joins. Here’s a little example of how you might log those audio frames:
Copy code
async def play_audio(audio_stream: rtc.AudioStream):
    try:
        frame_count = 0
        async for event in audio_stream:
            if event.frame:
                logging.debug(f"Received audio frame ({len(event.frame.data)} bytes)")
                frame_count += 1
        logging.info(f"Audio stream ended. Total frames received: {frame_count}")
    except Exception as e:
        logging.error(f"Error during audio stream playback: {e}")
If any of this feels tricky or if you want to chat through the steps, just let me know—I’m here to help! Sources: livekit-rtc/livekit/rtc/room.py | Subscribing to tracks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | terminal-client/client.py
c
how to check that: Inspect Audio Forwarding: In your agent session, double-check that
audio_input
is properly assigned and that the audio forwarding task is up and running.
t
Let’s take a look at your agent session to make sure the
audio_input
is set up right and the audio forwarding task is running smoothly. Here’s a simple way to check: 1. Check the
audio_input
Assignment:
First, double-check that the
audio_input
property in your agent session is assigned properly. Usually, the
RoomIO
setup handles this automatically, but it’s a good idea to log it and be sure:
if self._input.audio is None:\n    logging.error("Audio input is not assigned.")\nelse:\n    logging.info("Audio input is properly assigned.")
2. Verify the Audio Forwarding Task: Next, see if the audio forwarding task (
_forward_audio_atask
) is up and running. Logging its status can help:
if self._forward_audio_atask is None:\n    logging.error("Audio forwarding task is not running.")\nelse:\n    logging.info("Audio forwarding task is active.")
3. Manually Start the Forwarding Task (if needed): If you find the task isn’t running, make sure it starts once
audio_input
is assigned. For example:
if self._input.audio and self._forward_audio_atask is None:\n    self._forward_audio_atask = asyncio.create_task(self._forward_audio_task())
Following these steps should help you confirm everything’s set up correctly and working as it should. If you hit any snags or want a hand with anything else, just let me know—I’m here to help!
c
where to put this code:
if self._input.audio is None:\n    logging.error("Audio input is not assigned.")\nelse:\n    logging.info("Audio input is properly assigned.")
t
Hey! You’ll want to tuck this code into your agent session class, ideally somewhere you’re setting up or double-checking the audio input. Here are a few friendly suggestions: 1. During Initialization: If you’ve got an initialization method (like
__init__
or a setup method), this is a great spot to add the check right after you expect the audio input to be assigned. 2. In a Diagnostic Method: You could create a special method just for checking the audio input and call it whenever you need. For example:
def check_audio_input(self):\n    if self._input.audio is None:\n        logging.error("Audio input is not assigned.")\n    else:\n        logging.info("Audio input is properly assigned.")
3. Before Starting the Forwarding Task: If you have some logic that kicks off the audio forwarding task, it’s a good idea to run this check first to make sure everything’s ready to go. If anything’s unclear or you want a hand weaving this into your setup, just give me a shout—I’m here to help!
c
check my entry point code: async def entrypoint(ctx: JobContext): """LiveKit agent entry point.""" logger.info("Starting LiveKit agent") await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY) # Wait for participant to join participant = await ctx.wait_for_participant() try: json_metadata = participant.metadata or "{}" logger.info("Decoding participant metadata %s", json_metadata) participant_metadata = json.loads(json_metadata) except json.JSONDecodeError: logger.error("Failed to decode participant metadata, using defaults") participant_metadata = { "call_sid": "unknown", "caller_phone": "unknown", "to_number": "unknown" } with Session(engine) as session: call_sid = participant_metadata.get("call_sid", "unknown") caller_phone = participant_metadata.get("caller_phone", "unknown") to_number = participant_metadata.get("to_number", "unknown") business_context = await get_business_data_for_call( session=session, call_sid=call_sid, caller_phone=caller_phone, to_number=to_number, ) conversation_agent = LiveKitConversationAgent( business_data=business_context, session=session, ) ctx.add_shutdown_callback(conversation_agent.stop_conversation) @ctx.room.on("track_subscribed") def on_track_subscribed(track: rtc.RemoteTrack): print(f"Subscribed to track: {track.name}") asyncio.create_task(process_track(track)) async def process_track(track: rtc.RemoteTrack): stt = deepgram.STT(model="nova-3") stt_stream = stt.stream() audio_stream = rtc.AudioStream(track) async with asyncio.TaskGroup() as tg: # Create task for processing STT stream stt_task = tg.create_task(process_stt_stream(stt_stream)) # Process audio stream async for audio_event in audio_stream: stt_stream.push_frame(audio_event.frame) # Indicates the end of the audio stream stt_stream.end_input() # Wait for STT processing to complete await stt_task async def process_stt_stream(stream: AsyncIterable[SpeechEvent]): try: async for event in stream: if event.type == SpeechEventType.FINAL_TRANSCRIPT: print(f"Final transcript: {event.alternatives[0].text}") elif event.type == SpeechEventType.INTERIM_TRANSCRIPT: print(f"Interim transcript: {event.alternatives[0].text}") elif event.type == SpeechEventType.START_OF_SPEECH: print("Start of speech") elif event.type == SpeechEventType.END_OF_SPEECH: if event.alternatives: print("End of speech", event.alternatives[0].text) finally: await stream.aclose() # Start conversation await conversation_agent.start_conversation(ctx.room) # Keep the agent running await asyncio.sleep(float('inf'))
t
Thanks so much for sharing your entry point code! Based on what you’ve got, here are a few friendly suggestions to help make sure your audio forwarding and debugging go smoothly: 1. Double-check Audio Input Assignment: Right after connecting to the room, it’s a good idea to verify that
ctx.room.audio_input
is actually set. You could add a simple check like this:
if ctx.room.audio_input is None:\n    logger.error("Audio input is not assigned.")\nelse:\n    logger.info("Audio input is properly assigned.")
2. Keep an Eye on the Audio Forwarding Task: If you’re using a task to forward audio, make sure it only starts once you’ve confirmed the audio input is there. Something like this works well:
if ctx.room.audio_input and self._forward_audio_atask is None:\n    self._forward_audio_atask = asyncio.create_task(self._forward_audio_task())
3. Debug Track Subscription: In your
on_track_subscribed
callback, logging the track details can really help confirm everything’s subscribed properly:
@ctx.room.on("track_subscribed")\ndef on_track_subscribed(track: rtc.RemoteTrack):\n    logger.info(f"Subscribed to track: {track.name}, kind: {track.kind}")\n    asyncio.create_task(process_track(track))
4. Log When Audio Frames Arrive: Inside your
process_track
function, it’s helpful to log the audio frames as they come in, so you know they’re being received:
async for audio_event in audio_stream:\n    logger.debug(f"Received audio frame: {len(audio_event.frame.data)} bytes")\n    stt_stream.push_frame(audio_event.frame)
Adding these checks will give you a clearer picture that the audio input is set up right, the forwarding task is running, and the audio frames are flowing through. If you want to chat more or need any help with this, just let me know—I’m here for you!