The agent does not respond at all sometimes, it ge...
# ask-ai
m
The agent does not respond at all sometimes, it gets interrupted by background noise (detected by VAD) Are there any possible fixes for this without sacrificing latency? also what are some ways to reduce latency between agent and user conversations so that they feel natural?
t
Thanks for reaching out, Soumyadeep. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking two things: how to stop VAD-triggered false interruptions without adding latency, and how to reduce end-to-end latency so agent/user turns feel natural. Below are focused actions you can take. Fixes for false interruptions (no added latency) • Enable Background Voice Cancellation (BVC) on the agent to remove background noise and secondary voices before VAD/STT processes audio: ◦ Python:
noise_cancellation.BVC()
◦ Node:
BackgroundVoiceCancellation()
• Use the
false_interruption_timeout
and
resume_false_interruption=True
settings so the agent ignores brief noise that produces no transcript and resumes speaking if no real words arrive (default timeout ≈ 2.0s). • Keep noise filtering at the agent/plugin layer (BVC) instead of adding client-side buffering — this prevents extra processing latency. Ways to reduce latency for more natural turns • Deploy agent, STT, LLM, and TTS in the same LiveKit Cloud region to cut network hops and routing delays. • Use provisioned inference capacity so model requests avoid public endpoints and queuing delays. • Enable
preemptive_generation=True
so LLM inference begins on interim transcripts and yields earlier tokens (the preview is discarded if final input changes). • Choose low-latency model providers for STT/LLM/TTS where available. • Monitor TTFT (Time To First Token) and TTFB via Agents metrics to find which stage (network, STT, LLM, or TTS) is the main bottleneck. If you’d like, tell me: • which SDK/language you’re using (Python/Node), • whether you currently use BVC, and • which STT/LLM/TTS providers/regions you have configured— and I’ll give exact config snippets and the best next tuning steps. Sources: Enhanced noise cancellation | LiveKit docs | Turn detection and interruptions | LiveKit Docs | Introducing LiveKit Inference: A unified model interface for voice AI | Agent speech and audio | LiveKit docs | How can I reduce latency in voice agents using STT, TTS and LLM?
Thanks — I hear you: noise cancellation isn’t working in your self‑hosted LiveKit. I can help troubleshoot and give workable alternatives. Quick facts relevant to your setup • Krisp-based enhanced noise cancellation (BVC) is a LiveKit Cloud feature and is not available in self‑hosted LiveKit. • Self‑hosted options are: enable native WebRTC suppression on clients, run third‑party noise filters (e.g., RNNoise or local models) in the client/agent audio pipeline, or use the
livekit-plugins-noise-cancellation
package with locally-managed models. To help further, please tell me: 1. Which SDK/language are you using for agent and client (Node/Python/browser/native)? 2. Are you self-hosting agents alongside LiveKit or running them separately? 3. What noise settings have you already tried (e.g.,
krisp_enabled
,
noiseSuppression
,
echoCancellation
, any plugins)? 4. Do you control the client (browser/mobile) audio capture code so you can enable
noiseSuppression: true
or insert a filter? Based on your answers I’ll provide exact config snippets and a step‑by‑step plan (client-side RNNoise example, agent plugin setup, or how to wire a local model into your audio pipeline). Sources: Enhanced noise cancellation | LiveKit docs | Noise & echo cancellation | LiveKit docs | Voice AI quickstart | LiveKit docs | sip | livekit/livekit_composite | DeepWiki
m
I am only self-hosting the agents
t
Thanks — since you’re only self‑hosting agents, Krisp/BVC isn’t available. I can help you implement workable alternatives on the agent side. Quick options you can use • Use the
livekit-plugins-noise-cancellation
package in your agent and run local models for filtering (you must download/manage the models locally). • Integrate a third‑party noise filter (e.g., RNNoise) into the agent audio pipeline to remove background noise before VAD/STT. • Ensure clients enable native WebRTC capture options (
noiseSuppression: true
,
echoCancellation: true
) so agents receive cleaner audio to start with. To give exact code/config and a step‑by‑step plan, please tell me: 1. Which agent SDK/language are you running (Node or Python)? 2. Are agents processing raw PCM audio streams, or are you receiving browser/media tracks directly? 3. What have you already tried (e.g., attempted
krisp_enabled
, any plugins, or RNNoise)? Send those details and I’ll provide the precise setup and snippets to wire a local noise filter into your agent audio pipeline and improve VAD reliability without adding latency.
m
using the Node SDK
t
Thanks — since you’re running Node agents only, here’s a concise plan you can implement now to get reliable noise cancellation without Cloud-only Krisp. Short summary • Krisp/BVC is Cloud-only and not available for self‑hosted agents. • You must apply noise suppression on the client (preferred) or inside your Node agent using an open-source denoiser or local model. Recommended approaches (ordered by ease / impact) 1) Ensure client-side WebRTC preprocessing is enabled • Ask clients to publish with
noiseSuppression: true
and
echoCancellation: true
so agents receive cleaner audio. • Example (browser):
Copy code
import { createLocalAudioTrack } from "livekit-client";

const audioTrack = await createLocalAudioTrack({
  noiseSuppression: true,
  echoCancellation: true,
});
await room.localParticipant.publishTrack(audioTrack);
2) Agent-side real-time denoising (Node) • Run a local denoiser (RNNoise, DeepFilterNet, or similar) in your agent process and feed cleaned frames into VAD/STT. • High-level flow: a. Read audio frames from the incoming track/stream. b. Convert PCM16 -> float32. c. Pass frames to denoiser (local library or WASM). d. Convert back to PCM16 and forward to VAD/STT. • Conceptual snippet:
Copy code
for await (const frame of audioStream) {
  const floatData = int16ToFloat32(frame.data);
  const cleaned = await denoise(floatData); // RNNoise/DeepFilterNet
  const pcm = float32ToInt16(cleaned);
  sttStream.pushFrame({ data: pcm, sampleRate: frame.sampleRate, ... });
}
• Note: pick a denoiser with Node bindings or WASM for minimal added latency. 3) Use a local microservice for denoising (scalable) • If you prefer separation of concerns, host denoising as a local gRPC/HTTP service that your Node agent posts raw audio to and receives cleaned audio back. • This makes it easier to swap models (RNNoise, DeepFilterNet) without changing agent code. Practical tips to avoid added latency • Use models/bindings that process small frames (e.g., 10–20ms) and run inference in-process or on a local server to avoid network hops. • Prefer WASM/native bindings over remote API calls. • Batch minimal frames only when necessary; avoid large buffers that increase turn latency. • Profile pipeline TTFT/TTFB to find any slow stage. Next step — I’ll give exact code and package recommendations if you tell me: 1. Are you receiving raw PCM frames in your agent or MediaTracks? 2. Do you prefer an in-process library (WASM/native) or a local denoiser service? 3. Any constraints on CPU or latency budget (ms)? Sources: Enhanced noise cancellation | LiveKit docs | Noise & echo cancellation | LiveKit docs | Speech-to-text (STT) models | LiveKit Docs | Processing raw media tracks | LiveKit docs
m
livekit-plugins-noise-cancellation can we use this?
t
Short answer: No —
livekit-plugins-noise-cancellation
(the Krisp-based plugin) requires LiveKit Cloud and cannot be used to provide Krisp/BVC noise cancellation in a self‑hosted agent. What you can do instead (concise options) • Enable client-side WebRTC preprocessing: set
noiseSuppression: true
and
echoCancellation: true
when clients publish audio. • Use an in‑process denoiser in your Node agent (RNNoise, DeepFilterNet, or a WASM binding) to clean frames before VAD/STT. • Run a local denoising microservice (gRPC/HTTP) that your agent sends raw frames to and receives cleaned audio from. If you want exact code/config, tell me: 1) Are you getting raw PCM frames in the agent or MediaTracks? 2) Prefer in‑process (WASM/native) or a local denoiser service? I’ll provide the concrete Node snippets and package recommendations based on your answers.
m
Short answer: No —
livekit-plugins-noise-cancellation
(the Krisp-based plugin) requires LiveKit Cloud and cannot be used to provide Krisp/BVC noise cancellation in a self‑hosted agent. so this cannot be used with the livekit agents sdk?
t
Correct —
livekit-plugins-noise-cancellation
(the Krisp-based plugin) cannot be used with self‑hosted LiveKit Agents SDK. Krisp/BVC is Cloud-only. What you can do instead: • Enable client-side WebRTC preprocessing:
noiseSuppression: true
,
echoCancellation: true
when publishing audio. • Integrate an in‑process denoiser in your Node agent (RNNoise, DeepFilterNet, or a WASM binding) to clean frames before VAD/STT. • Run a local denoising microservice (gRPC/HTTP) that the agent sends raw audio to and receives cleaned audio from. If you want, tell me: 1) Do your agents receive raw PCM frames or MediaTracks? 2) Do you prefer in‑process (WASM/native) or a separate denoiser service? I’ll provide exact Node snippets and package recommendations based on your answers.
m
what is the best approach here?
t
You're asking for the best approach for noise cancellation in a self‑hosted Node agent. Here’s a clear recommendation with tradeoffs and next steps. Best approach (practical, low-latency, reliable) 1. Primary: Enable client-side WebRTC preprocessing ◦ Have clients publish with
noiseSuppression: true
and
echoCancellation: true
. ◦ Pros: zero extra server CPU, minimal latency, immediate improvement. ◦ Cons: depends on client device/browser quality. 1. Secondary (recommended): In‑process denoiser in your Node agent ◦ Run a lightweight local model (RNNoise or DeepFilterNet) inside the agent process to clean frames before VAD/STT. ◦ Pros: consistent denoising regardless of client, low added latency if you use a WASM/native binding and small frame sizes (10–20ms). ◦ Cons: requires integration effort and some CPU; choose efficient bindings to stay within latency budget. 1. Optional: Local denoising microservice ◦ Agent sends raw frames to a local gRPC/HTTP service running the denoiser, receives cleaned frames. ◦ Pros: easier to scale/swap models, isolates CPU load. ◦ Cons: adds a local network hop; keep it on the same host or LAN to avoid latency. Which to pick • If you control clients: always enable client-side preprocessing first. • If client quality varies or you need deterministic behavior: combine client-side preprocessing + in‑process denoiser in the agent (best balance of latency and reliability). • If you expect heavy load or want model swap flexibility: use the denoiser microservice. If you want, I can now: • Provide exact Node snippets for reading frames and wiring RNNoise/DeepFilterNet (WASM/native) into your agent, or • Outline a minimal microservice API and example integration. Which would you like (in‑process code or microservice example)? Also confirm whether your agents receive raw PCM frames or MediaTracks.
m
Provide exact Node snippets for reading frames and wiring RNNoise/DeepFilterNet (WASM/native) into your agent
t
I can provide Node.js snippets to read audio frames from your agent, run them through a local denoiser (RNNoise via WASM or DeepFilterNet via a native/WASM binding), and forward cleaned frames to your STT/VAD pipeline. Before the snippets — two quick clarifications: 1. Are your agents receiving raw PCM frames (e.g., via an AudioStream abstraction) or MediaTracks? 2. Do you prefer RNNoise (very lightweight, lower CPU) or DeepFilterNet (higher quality, higher CPU)? Tell me those and I’ll give the exact code you should drop into your agent.
m
yes the agent receives linear pcm 16 frames and lets do RNNoise
t
Below are concrete Node.js snippets to read 16-bit linear PCM frames from your agent, run them through an RNNoise WASM binding, and forward cleaned frames to your STT/VAD pipeline. Keep frames small (10–20ms) to minimize added latency. Prerequisites • Node 18+ (or appropriate WASM support) • An RNNoise WASM binding. Example used below: a minimal wrapper named
rnnoise-wasm
(you may use an existing package or compile RNNoise to WASM). The wrapper exposes
init()
,
createState()
, and
processFrame(state, float32Frame)
. 1) Helper conversions (PCM16 <-> Float32)
Copy code
// int16 PCM -> Float32 [-1..1]
function int16ToFloat32(int16Buffer) {
  const len = int16Buffer.length / 2;
  const view = new DataView(int16Buffer.buffer, int16Buffer.byteOffset, int16Buffer.byteLength);
  const float32 = new Float32Array(len);
  for (let i = 0; i < len; i++) {
    const s = view.getInt16(i * 2, true);
    float32[i] = s / 32768;
  }
  return float32;
}

// Float32 [-1..1] -> int16 PCM
function float32ToInt16(float32) {
  const buffer = new ArrayBuffer(float32.length * 2);
  const view = new DataView(buffer);
  for (let i = 0; i < float32.length; i++) {
    let s = Math.max(-1, Math.min(1, float32[i]));
    view.setInt16(i * 2, Math.floor(s * 32767), true);
  }
  return Buffer.from(buffer);
}
2) Minimal RNNoise WASM wrapper interface (conceptual)
Copy code
// This assumes you have a WASM module exposing necessary functions.
// Replace with the actual import for your RNNoise WASM binding/package.
const RNNoise = require('rnnoise-wasm'); // placeholder name

async function initRNNoise() {
  await RNNoise.init(); // loads WASM, etc.
  const state = RNNoise.createState();
  return { RNNoise, state };
}
3) Process incoming PCM16 frames through RNNoise • RNNoise expects 16kHz mono audio with frame size 480 samples (30ms) or 160 samples (10ms) depending on implementation. Confirm your STT VAD sample rate and, if needed, resample to 16 kHz before denoising. • Example below assumes 16kHz mono and 480-sample frames (modify frame size if your binding requires 160).
Copy code
async function denoiseStream(audioFrameIterator, sttSink) {
  // audioFrameIterator: async iterator yielding { data: Buffer (PCM16LE), sampleRate, numChannels, samplesPerChannel }
  // sttSink: object with pushFrame({ data: Buffer(Pcm16LE), sampleRate, ... })

  const { RNNoise, state } = await initRNNoise();

  for await (const frame of audioFrameIterator) {
    // If not 16kHz mono, resample and/or mixdown here (not shown).
    // frame.data is Buffer of PCM16LE interleaved or mono depending on source.
    // Ensure mono: if multi-channel, mix channels to mono:
    let pcmBuffer = frame.data;
    if (frame.numChannels && frame.numChannels > 1) {
      pcmBuffer = mixToMono(pcmBuffer, frame.numChannels);
    }

    // Convert PCM16 -> Float32
    const floatInput = int16ToFloat32(pcmBuffer);

    // RNNoise often expects frames of fixed length (e.g., 480). Process in chunks:
    const FRAME_SAMPLES = RNNoise.frameSize || 480; // adjust to your binding
    let outBuffers = [];
    for (let offset = 0; offset < floatInput.length; offset += FRAME_SAMPLES) {
      const slice = floatInput.subarray(offset, offset + FRAME_SAMPLES);
      if (slice.length < FRAME_SAMPLES) {
        // pad with zeros
        const pad = new Float32Array(FRAME_SAMPLES);
        pad.set(slice);
        // processFrame returns cleaned Float32Array length FRAME_SAMPLES
        const cleaned = RNNoise.processFrame(state, pad);
        outBuffers.push(cleaned);
      } else {
        const cleaned = RNNoise.processFrame(state, slice);
        outBuffers.push(cleaned);
      }
    }

    // Concatenate cleaned frames
    const totalSamples = outBuffers.reduce((s, b) => s + b.length, 0);
    const cleanedFloat = new Float32Array(totalSamples);
    let pos = 0;
    for (const b of outBuffers) {
      cleanedFloat.set(b, pos);
      pos += b.length;
    }

    // Convert back to PCM16
    const cleanedPcm = float32ToInt16(cleanedFloat);

    // Forward to STT/VAD (maintain sampleRate and channel info)
    sttSink.pushFrame({
      data: cleanedPcm,
      sampleRate: 16000,
      numChannels: 1,
      samplesPerChannel: cleanedFloat.length,
    });
  }
}
4) Mixing multi-channel to mono helper
Copy code
function mixToMono(pcmBuffer, numChannels) {
  // pcmBuffer: Buffer of int16 interleaved channels
  const totalSamples = pcmBuffer.length / 2 / numChannels;
  const mixed = new Float32Array(totalSamples);
  const view = new DataView(pcmBuffer.buffer, pcmBuffer.byteOffset, pcmBuffer.byteLength);
  for (let i = 0; i < totalSamples; i++) {
    let sum = 0;
    for (let ch = 0; ch < numChannels; ch++) {
      sum += view.getInt16((i * numChannels + ch) * 2, true) / 32768;
    }
    mixed[i] = sum / numChannels;
  }
  // Convert float -> int16 buffer
  return float32ToInt16(mixed);
}
5) Integration notes and performance tips • Resampling: If incoming sampleRate != 16000, resample (low-latency resamplers such as
soxr
native binding or a small JS resampler can be used). Resampling must be low-latency and done per small frame. • Frame size: RNNoise commonly processes 480-sample frames at 16kHz (~30ms). Some bindings accept 160-sample frames. Smaller frames reduce latency but may change noise suppression quality. • WASM vs native: Use native bindings if CPU/time is tight. WASM is portable and easier to deploy but slightly slower. • Threading: Run denoiser in a dedicated worker or thread pool to avoid blocking the agent main loop. • Buffering: Keep minimal buffering — process frames immediately to avoid increasing response latency. • Testing: Validate by feeding real audio and checking VAD false positives before/after. If you want, I can: • Provide an exact RNNoise WASM build recipe or point to a maintained binding (if you prefer an existing package). • Add a small resampling snippet (e.g., using
audio-resampler
or native
soxr
) if your input isn’t 16 kHz. • Convert the example to use your concrete agent audio API shapes (paste a sample audio frame object shape and STT push API). Which follow-up would help you most?
m
how much latency will this add?
t
Short answer: expect roughly 2–30 ms of added latency depending on frame size, binding (WASM vs native), and CPU. Here’s a concise breakdown and how to keep it low. Estimated added latency components • Frame buffering: 10–30 ms (depends on frame size you choose; e.g., 10ms, 20ms, or 30ms frames). You must buffer at least one frame before processing. • RNNoise processing: ◦ Native binding/C++: typically ~0.5–3 ms per 10–20 ms frame on a modest CPU. ◦ WASM binding: typically ~1–8 ms per 10–20 ms frame (WASM is slower than native). • Resampling/mixing overhead (if needed): ~0.5–3 ms depending on method and implementation. • Thread/queue hop if you offload to worker or microservice: add ~0.2–5 ms if on same host; more if across network. Typical totals (realistic ranges) • Optimized native in‑process + 10–20 ms frame: ~2–8 ms added latency. • WASM in‑process + 10–20 ms frame: ~4–15 ms added latency. • Using 30 ms frames (common RNNoise default) increases base buffering: add ~30 ms + processing, so total ~32–40+ ms. How to minimize added latency • Use small frames (10–20 ms) if your RNNoise binding supports them. • Prefer native bindings over WASM for best CPU/latency. • Run denoiser in‑process or in a same‑host worker to avoid network hops. • Use a thread/worker pool so denoising doesn't block the main loop. • Avoid batching multiple frames before processing. • Profile TTFT/TTFB to identify slow stages and tune frame size vs. quality. Tradeoffs • Smaller frames reduce buffering latency but may reduce noise suppression quality slightly. • Native code = lower latency but more deployment complexity; WASM = easier deploy, slightly higher latency. If you want, I can: • Provide microbenchmarks (sample code) you can run on your target host to measure RNNoise WASM vs native latency per frame. • Recommend specific bindings/packages and a configuration (frame size, worker pool) tuned for low latency on your CPU. Which would you like?
m
but i have a doubt, i use silero vad plugin and the turn detector plugin and they work well with the self-hosted agents sdk. then whats the issue with the noise cancellation plugin?
t
Good question — the difference comes down to external model licensing and where processing runs. • Silero VAD and the turn detector are self-contained, local algorithms you can ship and run inside your self‑hosted agent process — no external licensing or cloud-only models required. That’s why they work fine in self‑hosted setups. • The
livekit-plugins-noise-cancellation
plugin relies on Krisp’s BVC models, which are provided under LiveKit Cloud licensing and run via LiveKit Cloud integrations. Those Krisp models and the Cloud integration are not available for self‑hosted deployments, so the plugin cannot perform Krisp/BVC denoising locally. What to do instead • Keep using Silero VAD/turn detector for VAD and turn logic. • For noise cancellation in self‑hosted agents, use client-side WebRTC preprocessing (
noiseSuppression: true
) and/or run a local denoiser (RNNoise or DeepFilterNet) in‑process or as a same‑host microservice — the RNNoise snippets I provided are a practical drop‑in. If you want, I can: • Show how to wire Silero VAD + RNNoise together in your agent so VAD sees cleaned audio, or • Provide a quick checklist to verify your current pipeline (where to insert denoiser, buffering/frame size, threading). Which would you prefer?
m
Show how to wire Silero VAD + RNNoise together in your agent so VAD sees cleaned audio
t
Below is a concise, ready-to-adapt Node.js pattern that pipes incoming 16-bit linear PCM frames through RNNoise first, then into Silero VAD (so the VAD sees cleaned audio). It assumes your agent yields async PCM frames and that you have a working RNNoise binding and Silero VAD available in Node. High-level flow 1. Read PCM16 frames from agent. 2. Mix to mono and resample to 16kHz if needed. 3. Convert PCM16 -> Float32 and run RNNoise per frame. 4. Convert cleaned Float32 -> PCM16 and feed into Silero VAD. 5. Use VAD output for turn detection / STT forwarding. Prereqs • Node 18+. • RNNoise binding (WASM or native) exposing:
init()
,
createState()
,
processFrame(state, Float32Array)
, and
frameSize
(samples). • Silero VAD binding exposing:
vad.isSpeech(pcm16Buffer, sampleRate)
or similar synchronous API (adjust call shape to your Silero wrapper). Helpers (conversions + mix)
Copy code
function int16ToFloat32Buffer(buffer) {
  const len = buffer.length / 2;
  const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  const out = new Float32Array(len);
  for (let i = 0; i < len; i++) out[i] = view.getInt16(i * 2, true) / 32768;
  return out;
}

function float32ToInt16Buffer(float32) {
  const buf = new ArrayBuffer(float32.length * 2);
  const view = new DataView(buf);
  for (let i = 0; i < float32.length; i++) {
    let s = Math.max(-1, Math.min(1, float32[i]));
    view.setInt16(i * 2, Math.floor(s * 32767), true);
  }
  return Buffer.from(buf);
}

function mixToMonoInt16(pcmBuffer, numChannels) {
  if (!numChannels || numChannels === 1) return pcmBuffer;
  const totalSamples = pcmBuffer.length / 2 / numChannels;
  const floatOut = new Float32Array(totalSamples);
  const view = new DataView(pcmBuffer.buffer, pcmBuffer.byteOffset, pcmBuffer.byteLength);
  for (let i = 0; i < totalSamples; i++) {
    let sum = 0;
    for (let ch = 0; ch < numChannels; ch++) {
      sum += view.getInt16((i * numChannels + ch) * 2, true) / 32768;
    }
    floatOut[i] = sum / numChannels;
  }
  return float32ToInt16Buffer(floatOut);
}
Pipeline implementation
Copy code
// imports - replace with your actual bindings
const RNNoise = require('rnnoise-wasm'); // placeholder
const SileroVAD = require('silero-vad-node'); // placeholder

async function initPipeline() {
  await RNNoise.init();
  const rnState = RNNoise.createState();
  await SileroVAD.init(); // if needed
  const vad = new SileroVAD.Vad(); // adjust to your API

  const FRAME_SAMPLES = RNNoise.frameSize || 480; // RNNoise frame size in samples (16kHz)
  const FRAME_BYTES = FRAME_SAMPLES * 2; // 16-bit mono

  return { rnState, vad, FRAME_SAMPLES, FRAME_BYTES };
}

async function processAgentFrames(audioFrameIterator, sttSink, turnDetector) {
  const { rnState, vad, FRAME_SAMPLES, FRAME_BYTES } = await initPipeline();

  for await (const frame of audioFrameIterator) {
    // frame: { data: Buffer (PCM16LE), sampleRate, numChannels, samplesPerChannel }
    // 1) Ensure mono + sample rate 16kHz
    let pcm = frame.data;
    if (frame.numChannels && frame.numChannels > 1) pcm = mixToMonoInt16(pcm, frame.numChannels);
    if (frame.sampleRate !== 16000) {
      // resample pcm -> 16kHz. Implement a low-latency resampler here.
      pcm = await resampleTo16k(pcm, frame.sampleRate, frame.numChannels || 1);
    }

    // 2) Process in RNNoise-sized chunks
    const totalSamples = pcm.length / 2;
    let sampleOffset = 0;
    while (sampleOffset < totalSamples) {
      const remaining = totalSamples - sampleOffset;
      // build Float32 input of FRAME_SAMPLES (pad with zeros if needed)
      const inFloat = new Float32Array(FRAME_SAMPLES);
      const bytesSlice = pcm.slice(sampleOffset * 2, Math.min((sampleOffset + FRAME_SAMPLES) * 2, pcm.length));
      const floatSlice = int16ToFloat32Buffer(bytesSlice);
      inFloat.set(floatSlice);
      // 3) RNNoise denoise
      const cleanedFloat = RNNoise.processFrame(rnState, inFloat); // returns Float32Array length FRAME_SAMPLES
      // 4) Convert cleaned float -> PCM16 buffer
      const cleanedPcm = float32ToInt16Buffer(cleanedFloat);
      // 5) Feed cleaned PCM to Silero VAD
      const isSpeech = vad.isSpeech(cleanedPcm, 16000); // adjust API if different
      // 6) Use VAD output for turn detection / STT decisions
      turnDetector.processVADResult(isSpeech, cleanedPcm);

      // 7) Optionally push cleaned audio to STT if VAD indicates speech
      if (isSpeech) {
        sttSink.pushFrame({
          data: cleanedPcm,
          sampleRate: 16000,
          numChannels: 1,
          samplesPerChannel: FRAME_SAMPLES,
        });
      }

      sampleOffset += FRAME_SAMPLES;
    }
  }
}
Integration notes and best practices • Resampling: insert a low-latency resampler if incoming sampleRate != 16kHz. Use native
soxr
binding or a small JS resampler; resample per-frame to avoid buffering large windows. • Threading: run RNNoise in a worker thread or worker pool to avoid blocking the main event loop. Use worker threads or a dedicated denoiser pool. • Frame-size / latency: prefer 10–20ms frames if your RNNoise binding supports them. If using 480-sample (30ms) RNNoise frames, VAD latency rises by that buffer. • VAD sensitivity: Silero VAD thresholds can be tuned; after denoising you may need to reduce threshold to avoid missing weak speech. • Error handling: handle partial frames by zero-padding, and gracefully handle RNNoise state resets on discontinuities. • Monitoring: measure TTFT and VAD false-interruption rate before/after to validate improvement. If you want, I can: • Provide a resampling snippet (soxr or JS-based) you can drop in, or • Convert the pipeline to use worker threads with a small worker pool example. Which follow-up would you like?
m
what are the best stt, llm and tts models to achieve the lowest latency? or should i use realtime models?
t
Short answer: use realtime models if your priority is absolute lowest end-to-end latency and simpler pipeline; otherwise use a pipeline with low-latency providers (STT: Deepgram/Cartesia, LLM: Groq/Cerebras/Mistral, TTS: Cartesia/ElevenLabs) and optimizations like provisioned inference, preemptive generation, and co-located deployment. Concise guidance • Realtime vs pipeline ◦ Realtime model: lowest end-to-end latency (audio→response) and simpler flow. Use if you can accept reduced control over TTS voices and output formatting. ◦ Pipeline (STT → LLM → TTS): more control (SSML, voice selection) but adds hops. Use only if you need custom voices, strict compliance, or finer control. • Low-latency provider recommendations ◦ STT: Deepgram Nova series or Cartesia Ink Whisper for fastest streaming transcription. ◦ LLM: Groq or Cerebras for very low TTFT; Mistral models (7B) for efficient token streaming. ◦ TTS: Cartesia Sonic series or ElevenLabs for fast streaming output and low TTFB. • Key optimizations (apply regardless of model choice) a. Co-locate agent, STT, LLM, TTS in the same region / host to reduce network RTTs. b. Use provisioned inference or dedicated capacity to avoid public queuing. c. Enable preemptive generation so LLM starts on interim transcripts (
preemptive_generation=True
). d. Choose models/providers that support streaming tokens/audio. e. Tune VAD (Silero) + noise suppression (client-side RNNoise or WebRTC) to avoid false interrupts. f. Monitor TTFT and TTFB via metrics to identify bottlenecks. • Practical target numbers ◦ Aim for TTFT < 500 ms and TTFB < 300 ms for a natural feel; total turn latency < ~1.5 s. ◦ Realtime setups can be substantially lower (audio→audio under 500 ms in many cases). If you want, I can: • Recommend specific provider/model configs for your region and expected load, or • Map a concrete low-latency pipeline (provider + config + LiveKit settings) for your app. Which follow-up would you prefer? Sources: Speech-to-text (STT) models | LiveKit Docs | Realtime model plugins | LiveKit Docs | Silero VAD plugin | LiveKit docs | Cerebras and LiveKit | LiveKit Docs | Voice AI quickstart | LiveKit docs
m
preemptive_generation=True where do we add this?
t
Add
preemptive_generation: true
in your Agent's LLM/provider configuration so the agent begins LLM inference on interim transcripts. In Node/Agents SDK this is supplied when you configure the model/provider for the agent. Example pattern (adjust to your provider API shape):
Copy code
// conceptual example — adapt to your Agent SDK/provider wrapper
const agent = new Agent({
  // other agent settings...
  llm: {
    provider: 'your-llm-provider', // e.g., 'groq', 'openai', etc.
    model: 'your-model-name',
    preemptive_generation: true,
    // any provider-specific options
  }
});
Effect: LLM inference starts on interim (partial) transcripts as they arrive; the preemptive response is used if final input matches, or discarded otherwise. This reduces perceived latency by overlapping transcription and generation. Keep VAD/false-interruption settings tuned (e.g.,
false_interruption_timeout
) so preemptive outputs aren't prematurely triggered by noise.
m
RNNois eis the best option available right? for noise cancellation?
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!
m
RNNoise* is the best option available right? for noise cancellation?