magnificent-furniture-90167
11/10/2025, 7:32 AMuv run stt_agent.py console
my local frontend:
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?tall-airline-16756
11/10/2025, 7:32 AMtall-airline-16756
11/10/2025, 7:32 AMLIVEKIT_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.mdmagnificent-furniture-90167
11/10/2025, 7:37 AMtall-airline-16756
11/10/2025, 7:38 AMautoSubscribe 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:
# 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 docsmagnificent-furniture-90167
11/10/2025, 7:51 AMtall-airline-16756
11/10/2025, 7:52 AMpush_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:
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:
@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 docsmagnificent-furniture-90167
11/10/2025, 8:01 AMtall-airline-16756
11/10/2025, 8:02 AMmagnificent-furniture-90167
11/10/2025, 8:08 AMtall-airline-16756
11/10/2025, 8:08 AMmagnificent-furniture-90167
11/10/2025, 8:30 AMtall-airline-16756
11/10/2025, 8:31 AMAgentSession. 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.mdmagnificent-furniture-90167
11/10/2025, 8:48 AMtall-airline-16756
11/10/2025, 8:49 AMmagnificent-furniture-90167
11/10/2025, 8:53 AMimport 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?tall-airline-16756
11/10/2025, 8:54 AMconst 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:
@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.pymagnificent-furniture-90167
11/10/2025, 8:56 AMtall-airline-16756
11/10/2025, 8:57 AMmagnificent-furniture-90167
11/10/2025, 8:59 AMtall-airline-16756
11/10/2025, 9:00 AMmagnificent-furniture-90167
11/10/2025, 9:01 AMtall-airline-16756
11/10/2025, 9:02 AMuser_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:
# 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