i’m running this <https://docs.livekit.io/agents/m...
# ask-ai
m
i’m running this https://docs.livekit.io/agents/models/stt/#standalone-usage stt standalone instance in the console mode like this:
uv run stt_agent.py console
my local frontend:
Copy code
async function startLivekitAsr() {
        if (lkConnected || recording) return;
        try {
            // Ask for permission first (so device labels appear)
            await navigator.mediaDevices.getUserMedia({ audio: true });

            // Enumerate audio input devices
            const devices = await navigator.mediaDevices.enumerateDevices();
            const audioInputs = devices.filter(d => d.kind === 'audioinput');
            console.log("Audio input devices:", audioInputs);

            // Try to select the system "default" device
            // In many browsers the deviceId "default" or first item corresponds to the active device
            let deviceId: string | undefined;
            const defaultDevice = audioInputs.find(d => d.deviceId === 'default')
                ?? audioInputs[0];
            if (defaultDevice) {
                deviceId = defaultDevice.deviceId;
                console.log("Using audio input device:", defaultDevice.label);
            }

            // Now get the mic stream, specifying deviceId if we found one
            const constraints: MediaStreamConstraints = {
                audio: deviceId ? { deviceId: { exact: deviceId } } : true
            };
            const micStream = await navigator.mediaDevices.getUserMedia(constraints);
            const micTrack = micStream.getAudioTracks()[0];
            if (!micTrack) throw new Error("Microphone track unavailable");

            // LiveKit connection & publish
            const room = new Room({ adaptiveStream: true, dynacast: true });

            room.on(RoomEvent.Connected, () => {
                console.log(`[FE] connected: room: ${room.name}, identity: ${room.localParticipant.identity}`);
            });

            room.on(RoomEvent.Disconnected, () => {
                console.log('[Frontend] disconnected:', {
                    serverRoomName: room.name,
                    myIdentity: room.localParticipant.identity,
                });
            });

            room.on(RoomEvent.LocalTrackPublished, (publication) => {
                console.log("[Frontend] LocalTrackPublished:", publication.track?.kind, publication.track?.id);
            });

            room.on(RoomEvent.TrackPublished, (publication, participant) => {
                console.log("[Frontend] TrackPublished by participant:", participant.identity, publication.trackSid);
            });

            room.on(RoomEvent.DataReceived, (payload: Uint8Array) => {
                const text = new TextDecoder().decode(payload);
                prompt = `${prompt}${text} `;
            });

            const p = room.localParticipant;
            const { url, token } = await getLivekitToken();
            await room.connect(url, token);
            await p.publishTrack(micTrack, {
                source: Track.Source.Microphone
            });
            console.log('Published mic track:', micTrack);

            lkRoom = room;
            lkConnected = true;
            recording = true;
            toast.success($i18n.t('Voice capture started'));
        } catch (err) {
            console.error(err);
            toast.error($i18n.t('Failed to start voice input'));
            if (lkMicTrack) { try { lkMicTrack.stop(); } catch {} lkMicTrack = null; }
        }
    }
runs with the vite dev server. how to connect my stt agent with the frontend? which LIVEKIT_URL should i use?
t
Thanks for reaching out, Alexey. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you connect your standalone STT agent with the frontend, here’s a simple step-by-step guide: • First, make sure your
LIVEKIT_URL
is correctly pointing to your LiveKit server instance. This could be a LiveKit Cloud deployment (like
wss://your-project.livekit.cloud
) or a self-hosted LiveKit server (such as
wss://your-server.com
). • Next, set up the necessary environment variables in your frontend project:
LIVEKIT_API_KEY
,
LIVEKIT_API_SECRET
, and
LIVEKIT_URL
. • Then, start your STT agent and confirm it connects to the same LiveKit room as your frontend. This way, your frontend can send audio streams and receive transcription results smoothly. If you’d like, I’m here to help you with setting up the environment or testing the connectivity—just let me know! Sources: Speech-to-text (STT) models | LiveKit Docs | avatars/hedra/README.md | README.md
m
i’ve correctly setup my env vars pointing to the livekit cloud server with the generated key and secret, started my stt agent and my frontend and backend connected to the same room, i’ve predefined for both. my frontend published the tracks, but the agent does not subscribe to tracks and doesn’t react to the published tracks. what i’m missing?
t
I understand how frustrating it can be when your STT agent isn’t subscribing to tracks as expected. Let’s walk through some common causes and solutions together: • Check the
autoSubscribe
setting:
It’s important to make sure your agent connects with
autoSubscribe=true
so it automatically subscribes to all tracks. If it’s set to
autoSubscribe=false
, you’ll need to subscribe to tracks manually. • Implement manual subscription logic: When
autoSubscribe
is off, you can add code to subscribe to both existing and future tracks. Here’s an example to guide you:
Copy code
# Subscribe to existing tracks
for participant in room.remote_participants.values():
    for publication in participant.track_publications.values():
        if publication.kind == TrackKind.KIND_AUDIO:
            await publication.set_subscribed(True)

# Handle future tracks
@room.on("track_published")
def on_track_published(publication, participant):
    if publication.kind == TrackKind.KIND_AUDIO:
        publication.set_subscribed(True)
• Debugging: It can be really helpful to log track publications and subscription attempts. This way, you can confirm whether the agent is discovering tracks and trying to subscribe to them. Please feel free to reach out if you’d like any help implementing these suggestions or if you want to troubleshoot further. I’m here to support you! Sources: pkg/sip/room.go | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | server/agent.py | agents/src/inference/stt.ts | Rooms, participants, and tracks | LiveKit docs
m
the stt agent, uses the code from the source above. it doesn’t have such setting, it only defined the entrypoint.
t
Thanks for reaching out! I want to help you get your standalone STT agent working smoothly. Just a quick note: it doesn’t automatically subscribe to tracks or use LiveKit’s track subscription system directly. Instead, it listens for audio frames through the
push_frame
method. So, to make sure your agent processes the audio tracks correctly, you’ll want to handle track subscription and audio extraction in your own application code. Here’s a simple way to approach it: • Set up track subscription logic: Whether you’re working on the frontend or backend, you’ll need to explicitly subscribe to audio tracks. For example:
Copy code
room.on(RoomEvent.TrackPublished, (publication, participant) => {
  if (publication.kind === Track.Kind.Audio) {
    publication.setSubscribed(true);
  }
});
• Extract audio frames: After subscribing, grab the audio frames from those tracks and send them to your STT agent using
push_frame
. Here’s how you might do that:
Copy code
@room.on("track_subscribed")
def on_track_subscribed(track, publication, participant):
    if track.kind == TrackKind.KIND_AUDIO:
        audio_stream = AudioStream(track)
        async for frame in audio_stream:
            stt_stream.push_frame(frame)
        await audio_stream.aclose()
If you’d like, I’m here to walk you through implementing this or help troubleshoot any issues you might run into. Just let me know! Sources: Subscribing to tracks | LiveKit docs | Speech-to-text (STT) models | LiveKit Docs | Rooms, participants, and tracks | LiveKit docs
m
what are the key differences between the agents processing audio track locally and in the livekit cloud? do they use the same asr engine?
t
Thanks for reaching out! Could you help me understand your question a bit better? Are you curious about: • The STT models used for transcription in local versus cloud setups? • The audio preprocessing steps, like noise cancellation, that happen before transcription? • Or maybe the differences between deployment environments, such as self-hosted versus LiveKit Cloud? Knowing this will really help me give you a clearer and more helpful answer about the ASR engine and how processing might differ. Looking forward to your reply! Sources: examples/avatar_agents/README.md | Speech-to-text (STT) models | LiveKit Docs | README.md | Enhanced noise cancellation | LiveKit docs
m
• The STT models used for transcription in local versus cloud setups • The audio preprocessing steps, like noise cancellation, that happen before transcription
t
I'd love to help clarify the key differences between STT models and audio preprocessing in local versus cloud setups for you: • STT Models: ◦ Cloud-based (LiveKit Cloud): Here, you get access to some powerful models like Deepgram (Nova-3, Nova-2), Cartesia Ink Whisper (covering 98 languages!), and AssemblyAI Universal-Streaming (English only). These are all hosted and managed smoothly by LiveKit Inference, so you don’t have to worry about the backend. ◦ Local (Self-hosted): In this setup, there aren’t built-in STT models included. However, you have the flexibility to integrate your own favorite STT providers, like Deepgram, OpenAI, or Groq, through plugins. It does take a bit of extra setup, but it’s a great way to tailor things exactly how you want. • Audio Preprocessing: ◦ Cloud-based: This comes with some really advanced noise cancellation features powered by Krisp, including Standard Noise Cancellation to remove background noise and Background Voice Cancellation to filter out ambient speech. These are exclusive benefits of LiveKit Cloud. ◦ Local: For self-hosted setups, audio preprocessing relies on WebRTC’s built-in noise suppression and echo cancellation, which are solid and available everywhere. However, Krisp’s enhanced noise cancellation isn’t available here. Please don’t hesitate to reach out if you’d like me to walk you through integrating custom STT models or setting up audio preprocessing. I’m here to help! Sources: Speech-to-text (STT) models | LiveKit Docs | AI Agents Framework | livekit/livekit_composite | DeepWiki | main.py | server/main.py | Enhanced noise cancellation | LiveKit docs
m
what’s the key difference between local stt agent processing audio frames and the local att agent https://github.com/livekit-examples/python-agents-examples/blob/main/pipeline-stt/transcriber/transcriber.py using agent session to process audio?
t
I'm glad you asked about the difference between a local STT agent processing audio frames and a local ATT agent using an
AgentSession
. Let me walk you through it in a way that’s easy to follow: • Standalone STT Processing: ◦ This works independently of an
AgentSession
, directly using the streaming interface. ◦ You push audio frames to the STT instance via
push_frame
, and then you get transcription results as
SpeechEvent
outputs. ◦ It’s perfect for simple, isolated transcription tasks where you don’t need to connect with other components like LLM or TTS. ◦ If your STT model doesn’t support native streaming, you might need some extra setup, like Voice Activity Detection. • AgentSession-Based Processing: ◦ This integrates STT into a smooth pipeline that includes VAD, LLM, and TTS working together. ◦ It manages the whole workflow—from audio input and speech detection to transcription, response generation, and verbal replies. ◦ It supports some really neat features like turn detection, real-time interaction, and event-driven handling (such as
user_input_transcribed
). ◦ You can even configure fixed participants for focused audio processing. ◦ Plus, it automatically handles the lifecycle and coordination of all these components, making it easier for you to develop interactive voice agents. To sum it up, standalone STT is great if you just need straightforward transcription, while
AgentSession
offers a powerful framework for creating rich, interactive voice AI applications. If you’d like, I’m here to help with any more details or questions you have! Sources: Speech-to-text (STT) models | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | How to set a fixed participant for agent audio processing | README.md
m
` ``
t
It looks like your last message might have gotten cut off. Could you please share a bit more detail or clarify your question? I’m here to help and want to make sure we get everything sorted out for you!
m
Copy code
import asyncio

from dotenv import load_dotenv

from livekit import agents, rtc
from livekit.agents.stt import SpeechEventType, SpeechEvent
from typing import AsyncIterable
from livekit.plugins import (
    deepgram,
)

load_dotenv()

async def entrypoint(ctx: agents.JobContext):
    @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-2")
        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:
                    print("End of speech")
        finally:
            await stream.aclose()


if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
above is the standalone local stt agent code. my fe (above) and the agent already connect to the same room. how to send audio frames from my frontend to the agent?
t
I'd be happy to help you send audio frames from your frontend to the standalone STT agent! Here are a couple of approaches you can try: • WebSocket-Based Audio Streaming: ◦ First, set up a WebSocket connection between your frontend and the STT agent. ◦ Then, convert your audio frames to the required format (PCM 16-bit little-endian, 16kHz, mono) and send them as base64-encoded messages. Here's a simple example to guide you:
Copy code
const audioBytes = audioFrame.data;
const base64Audio = btoa(String.fromCharCode(...new Uint8Array(audioBytes)));
const audioMsg = {
  type: "input_audio",
  audio: base64Audio,
};
webSocket.send(JSON.stringify(audioMsg));
• Room-Based Communication: ◦ Make sure both your frontend and the STT agent are connected to the same LiveKit room. ◦ The STT agent can then subscribe to the frontend's audio track and process it seamlessly. Here's a snippet to illustrate this:
Copy code
@ctx.room.on("track_subscribed")
def on_track_subscribed(track):
    if track.kind == rtc.TrackKind.KIND_AUDIO:
        asyncio.create_task(process_track(track))
• Audio Format Requirements: ◦ It's important that your audio frames are in PCM 16-bit little-endian format, with a 16kHz sample rate and mono channel. ◦ Also, try to send frames in 50ms chunks (sample_rate / 20) for optimal processing. If you have any questions or need more help implementing these steps, please feel free to reach out. I'm here to support you! Sources: livekit-plugins/livekit-plugins-baseten/livekit/plugins/baseten/stt.py | Speech-to-text (STT) models | LiveKit Docs | How to set a fixed participant for agent audio processing | complex-agents/teleprompter/cartesia-ink.py
m
can i use webrtc instead of websocket in the fe?
t
I wanted to share a little insight about using WebRTC directly from the frontend to the standalone STT agent—it’s actually not supported in this setup. Here’s how it typically works: • Your frontend publishes audio to the LiveKit room using WebRTC. • The STT agent then subscribes to that audio track via WebRTC within the room. • After that, the agent forwards the audio frames to the STT backend service using WebSocket. This approach helps ensure the audio is processed smoothly by combining WebRTC for streaming and WebSocket for communicating with the STT services. If you’d like, I’m here to help you get this flow set up—just let me know! Sources: agents/src/inference/stt.ts | livekit-plugins/livekit-plugins-baseten/livekit/plugins/baseten/stt.py | Speech-to-text (STT) models | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Web and mobile frontends | LiveKit Docs
m
so in order to be able to use webrtc i must deploy the agent to the livekit cloud and publish my audio tracks?
t
Absolutely! Deploying the agent to LiveKit Cloud is a great way to use WebRTC for audio track publishing and processing. Here’s a simple overview of how it works: • The frontend publishes audio tracks to the LiveKit room using WebRTC. • The agent, once deployed in LiveKit Cloud, subscribes to these tracks and processes them in real time. • The agent can also publish its own audio tracks, like synthesized speech or pre-recorded audio, back to the room using WebRTC. If you’d like, I can guide you through deploying the agent using the LiveKit CLI to create and manage it. Just let me know if you want detailed steps or any help with the configuration—I’m here for you! Sources: examples/src/play_local_audio_file.ts | CLI Tools & Token Management | livekit/livekit_composite | DeepWiki | packages/livekit-rtc/README.md | agent/README.md | Camera & microphone | LiveKit Docs
m
i only want to transcribe audio and send final transcription back to the frontend.
t
I'm happy to guide you through setting up a LiveKit agent for transcribing audio and sending the final transcriptions back to the frontend. Here’s a simple way to get started: • Enable STT in the Agent: First, configure your agent to use an STT provider like Deepgram or Cartesia. Make sure it listens for the
user_input_transcribed
event, and look out for
is_final=True
so you can process the completed transcriptions. • Send Transcriptions via RPC: To send the final transcription to the frontend, you can use Remote Procedure Calls (RPC). Here’s a quick example:
Copy code
# In the agent
async def send_transcript():
    remote_participants = list(ctx.room.remote_participants.values())
    if remote_participants:
        client_participant = remote_participants[0]
        await ctx.room.local_participant.perform_rpc(
            destination_identity=client_participant.identity,
            method="receive_transcript",
            payload=json.dumps({
                "transcript": transcript.transcript,
                "timestamp": getattr(transcript, 'timestamp', None)
            })
        )

asyncio.create_task(send_transcript())
• Frontend Integration: On the frontend side, make sure you’re listening for the
receive_transcript
RPC method so you can display or handle the transcription as needed. • Optional: If you prefer not to use RPC, you can also use the
lk.transcription
text stream to automatically publish transcriptions. If you have any questions or want me to walk you through any of these steps in more detail, please don’t hesitate to ask. I’m here to help! Sources: README.md | Text and transcriptions | LiveKit docs | How to Set Up Speech-to-Text Input with Text-Only Output in LiveKit Agents | hardware/pi-zero-transcriber/README.md | examples/other/transcription/transcriber.py