Audio-Based Turn Detection Support
Feature Request: Audio-Based Turn Detection Support
Problem
LiveKit currently only supports text-based turn detection (analyzing STT transcriptions) + VAD. This misses important audio cues like prosody, pitch, and intonation that humans use for natural turn-taking.
Proposed Solution
Add support for audio-based turn detection models, specifically:
- Krisp Integration: Support for [Krisp's new audio turn-taking model](https://krisp.ai/blog/turn-taking-for-voice-ai/) (6.1M params, 65MB, CPU-optimized)
- Native Audio Model: Develop a LiveKit audio-based turn detection model
- Multimodal Option: Combine audio + text features for maximum accuracy
Benefits
- Lower latency: Direct audio analysis eliminates STT dependency in turn detection
- Better accuracy: Access to prosodic features (pitch, energy, speaking rate)
- Smaller models: Audio models can be more efficient than large text transformers
- Natural conversation: Better handling of hesitations, pauses, and speaking patterns
Implementation
session = AgentSession(
vad=silero.VAD.load(),
turn_detector=AudioTurnDetector(), # New audio-based option
stt=deepgram.STT(model="nova-3"),
llm=openai.LLM(model="gpt-4o-mini"),
tts=elevenlabs.TTS(),
)
Questions
- Are there plans to support audio-based turn detection?
- Interest in developing native audio/multimodal turn detection?
The current text-based approach is great but audio-based detection could provide more natural conversation flow with lower latency.
Turn detection is a hard problem, humans use all of these signals when making a decision:
- content of what's said
- context of the current conversation (including what the listener has previously said)
- how they are saying it (intonation, prosody)
In our research earlier on, we determined the content & context carried more information. (i.e. it's impossible to create a high accuracy model without having content & context). For that reason, our initial model is focused on using text (including conversational history) to make a determination.
If you have to trade-off between use either audio-only or text-only, we strongly believe audio-only wouldn't give you sufficient accuracy. While it may demo well (speaker could speak in a way that highlights "pause features"), real-world applications rely heavily on the context.
That said, to reach human-level performance, you'd need all three features. We are actively researching how to incorporate audio features into our model mix to produce the most accurate decisions.
If you are interested in trying out Krisp's audio-only approach, you are welcome to stub it out within the framework and see how it performs. (It could be done by implementing the VAD interface)
Feature Request: Audio-Based Turn Detection Support
Problem
LiveKit currently only supports text-based turn detection (analyzing STT transcriptions) + VAD. This misses important audio cues like prosody, pitch, and intonation that humans use for natural turn-taking.
Proposed Solution
Add support for audio-based turn detection models, specifically:
- Krisp Integration: Support for [Krisp's new audio turn-taking model](https://krisp.ai/blog/turn-taking-for-voice-ai/) (6.1M params, 65MB, CPU-optimized)
- Native Audio Model: Develop a LiveKit audio-based turn detection model
- Multimodal Option: Combine audio + text features for maximum accuracy
Benefits
- Lower latency: Direct audio analysis eliminates STT dependency in turn detection
- Better accuracy: Access to prosodic features (pitch, energy, speaking rate)
- Smaller models: Audio models can be more efficient than large text transformers
- Natural conversation: Better handling of hesitations, pauses, and speaking patterns
Implementation
session = AgentSession( vad=silero.VAD.load(), turn_detector=AudioTurnDetector(), # New audio-based option stt=deepgram.STT(model="nova-3"), llm=openai.LLM(model="gpt-4o-mini"), tts=elevenlabs.TTS(), )
Questions
- Are there plans to support audio-based turn detection?
- Interest in developing native audio/multimodal turn detection?
The current text-based approach is great but audio-based detection could provide more natural conversation flow with lower latency.
Feature Request: Audio-Based Turn Detection Support
Problem
LiveKit currently only supports text-based turn detection (analyzing STT transcriptions) + VAD. This misses important audio cues like prosody, pitch, and intonation that humans use for natural turn-taking.
Proposed Solution
Add support for audio-based turn detection models, specifically:
- Krisp Integration: Support for [Krisp's new audio turn-taking model](https://krisp.ai/blog/turn-taking-for-voice-ai/) (6.1M params, 65MB, CPU-optimized)
- Native Audio Model: Develop a LiveKit audio-based turn detection model
- Multimodal Option: Combine audio + text features for maximum accuracy
Benefits
- Lower latency: Direct audio analysis eliminates STT dependency in turn detection
- Better accuracy: Access to prosodic features (pitch, energy, speaking rate)
- Smaller models: Audio models can be more efficient than large text transformers
- Natural conversation: Better handling of hesitations, pauses, and speaking patterns
Implementation
session = AgentSession( vad=silero.VAD.load(), turn_detector=AudioTurnDetector(), # New audio-based option stt=deepgram.STT(model="nova-3"), llm=openai.LLM(model="gpt-4o-mini"), tts=elevenlabs.TTS(), )
Questions
- Are there plans to support audio-based turn detection?
- Interest in developing native audio/multimodal turn detection?
The current text-based approach is great but audio-based detection could provide more natural conversation flow with lower latency.
Have you implemented any alternative for VAD in livekit ?
I have read the blog post, but couldn't found any doc or links to that specific model or API. Does anyone have any pointers?
I have used another text-based turn detection model (https://github.com/TEN-framework/ten-turn-detection) in my local whisper setup, which worked well. Happy to test an audio-based solution if the model is accessible.
@ChenghaoMou Even I couldn’t find the turn detection model from Krisp. However you can try the one from Pipecat if you want to. https://huggingface.co/pipecat-ai/smart-turn-v2
https://developers.cloudflare.com/workers-ai/models/smart-turn-v2/
@shivamkataria2000 can we use pipecat's turn detection model with livekit agent's framework?
Here is the code to use Smart Turn model in Livekit. The idea is to combine Silero and Smart Turn under one VAD interface and only emits End of Speech event when EOU is predicted, based on what @davidzhao suggested.
vad.py
# Copyright 2023 LiveKit, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import time
from dataclasses import dataclass
from typing import Literal
from typing import cast
import numpy as np
import numpy.typing as npt
import onnxruntime # type: ignore
from huggingface_hub import hf_hub_download
from livekit import agents
from livekit import rtc
from livekit.agents import utils
from livekit.plugins.silero import onnx_model
from livekit.plugins.silero.log import logger
from livekit.plugins.silero.vad import SLOW_INFERENCE_THRESHOLD
from livekit.plugins.silero.vad import VAD as SileroVAD
from livekit.plugins.silero.vad import VADStream as SileroVADStream
from livekit.plugins.silero.vad import _VADOptions
from transformers import WhisperFeatureExtractor
@dataclass
class EOUPrediction:
prediction: Literal[0, 1]
probability: float
class VAD(SileroVAD):
"""
Silero Voice Activity Detection (VAD) + Smart Turn Detection class.
This class provides functionality to detect speech segments within audio data using the Silero VAD model and perform
turn detection based on the Smart Turn model.
""" # noqa: E501
# region: modification
def __init__(
self,
*,
session: onnxruntime.InferenceSession,
opts: _VADOptions,
repo_id: str = "pipecat-ai/smart-turn-v3",
filename: str = "smart-turn-v3.0.onnx",
sample_rate: int = 16000,
) -> None:
opts.sample_rate = sample_rate
super().__init__(session=session, opts=opts)
self._feature_extractor = WhisperFeatureExtractor(chunk_length=8)
self._st_session = self.build_session(hf_hub_download(repo_id, filename=filename))
self._sample_rate = sample_rate
# * copied from pipecat
@staticmethod
@utils.log_exceptions(logger=logger)
def build_session(onnx_path: str, force_cpu: bool = False):
opts = onnxruntime.SessionOptions()
opts.inter_op_num_threads = 1
opts.intra_op_num_threads = 1
opts.execution_mode = onnxruntime.ExecutionMode.ORT_SEQUENTIAL
opts.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
if force_cpu and "CPUExecutionProvider" in onnxruntime.get_available_providers():
session = onnxruntime.InferenceSession(onnx_path, providers=["CPUExecutionProvider"], sess_options=opts)
else:
session = onnxruntime.InferenceSession(onnx_path, sess_options=opts)
return session
# * copied from pipecat
@staticmethod
@utils.log_exceptions(logger=logger)
def _truncate_or_pad(audio_array: npt.NDArray, target_size: int, padding: Literal["left", "right"] = "left"):
"""Truncate audio to last n seconds or pad with zeros to meet n seconds."""
if len(audio_array) > target_size:
return audio_array[-target_size:]
elif len(audio_array) < target_size:
# Pad with zeros at the beginning
padding_size = target_size - len(audio_array)
if padding == "left":
return np.pad(audio_array, (padding_size, 0), mode="constant", constant_values=0)
else:
return np.pad(audio_array, (0, padding_size), mode="constant", constant_values=0)
return audio_array
# * copied from pipecat
@utils.log_exceptions(logger=logger)
def predict_endpoint(self, audio_array: npt.NDArray[np.float32]) -> EOUPrediction:
"""
Predict whether an audio segment is complete (turn ended) or incomplete.
Args:
audio_array: Numpy array containing audio samples at 16kHz
Returns:
Dictionary containing prediction results:
- prediction: 1 for complete, 0 for incomplete
- probability: Probability of completion (sigmoid output)
"""
# Keep 8 second of audio
audio_array = self._truncate_or_pad(audio_array, target_size=8 * self._sample_rate, padding="left")
inputs = self._feature_extractor(
audio_array,
sampling_rate=16000,
return_tensors="pt",
padding="max_length",
max_length=8 * 16000,
truncation=True,
do_normalize=True,
)
input_features = inputs.input_features.squeeze(0).numpy().astype(np.float32)
input_features = np.expand_dims(input_features, axis=0) # Add batch dimension
outputs = self._st_session.run(None, {"input_features": input_features})
probability = outputs[0][0].item()
return EOUPrediction(1 if probability > 0.5 else 0, probability)
# endregion
# * This is needed so that it can use the VADStream defined here, not the original one
def stream(self) -> VADStream:
"""
Create a new VADStream for processing audio data.
Returns:
VADStream: A stream object for processing audio input and detecting speech.
"""
stream = VADStream(
self,
self._opts,
onnx_model.OnnxModel(onnx_session=self._onnx_session, sample_rate=self._opts.sample_rate),
)
self._streams.add(stream)
return stream
class VADStream(SileroVADStream):
# This is just to quiet the type checker
def __post_init__(self):
self._vad = cast(VAD, self._vad)
@utils.log_exceptions(logger=logger)
async def _main_task(self) -> None:
inference_f32_data = np.empty(self._model.window_size_samples, dtype=np.float32)
speech_buffer_index: int = 0
# "pub_" means public, these values are exposed to the users through events
pub_speaking = False
pub_speech_duration = 0.0
pub_silence_duration = 0.0
pub_current_sample = 0
pub_timestamp = 0.0
speech_threshold_duration = 0.0
silence_threshold_duration = 0.0
input_frames: list[rtc.AudioFrame] = []
inference_frames: list[rtc.AudioFrame] = []
# Smart turn variables
st_buffer: npt.NDArray[np.float32] | None = None
st_started: bool = False
resampler: rtc.AudioResampler | None = None
# used to avoid drift when the sample_rate ratio is not an integer
input_copy_remaining_fract = 0.0
extra_inference_time = 0.0
async for input_frame in self._input_ch:
if not isinstance(input_frame, rtc.AudioFrame):
continue # ignore flush sentinel for now
if not self._input_sample_rate:
self._input_sample_rate = input_frame.sample_rate
# alloc the buffers now that we know the input sample rate
self._prefix_padding_samples = int(self._opts.prefix_padding_duration * self._input_sample_rate)
self._speech_buffer = np.empty(
int(self._opts.max_buffered_speech * self._input_sample_rate) + self._prefix_padding_samples,
dtype=np.int16,
)
if self._input_sample_rate != self._opts.sample_rate:
# resampling needed: the input sample rate isn't the same as the model's
# sample rate used for inference
resampler = rtc.AudioResampler(
input_rate=self._input_sample_rate,
output_rate=self._opts.sample_rate,
quality=rtc.AudioResamplerQuality.QUICK, # VAD doesn't need high quality
)
elif self._input_sample_rate != input_frame.sample_rate:
logger.error("a frame with another sample rate was already pushed")
continue
assert self._speech_buffer is not None
input_frames.append(input_frame)
if resampler is not None:
# the resampler may have a bit of latency, but it is OK to ignore since it should be
# negligible
inference_frames.extend(resampler.push(input_frame))
else:
inference_frames.append(input_frame)
while True:
start_time = time.perf_counter()
available_inference_samples = sum([frame.samples_per_channel for frame in inference_frames])
if available_inference_samples < self._model.window_size_samples:
break # not enough samples to run inference
input_frame = utils.combine_frames(input_frames)
inference_frame = utils.combine_frames(inference_frames)
# convert data to f32
np.divide(
inference_frame.data[: self._model.window_size_samples],
np.iinfo(np.int16).max,
out=inference_f32_data,
dtype=np.float32,
)
# run the inference
p = await self._loop.run_in_executor(self._executor, self._model, inference_f32_data)
p = self._exp_filter.apply(exp=1.0, sample=p)
window_duration = self._model.window_size_samples / self._opts.sample_rate
pub_current_sample += self._model.window_size_samples
pub_timestamp += window_duration
resampling_ratio = self._input_sample_rate / self._model.sample_rate
to_copy = self._model.window_size_samples * resampling_ratio + input_copy_remaining_fract
to_copy_int = int(to_copy)
input_copy_remaining_fract = to_copy - to_copy_int
# copy the inference window to the speech buffer
available_space = len(self._speech_buffer) - speech_buffer_index
to_copy_buffer = min(to_copy_int, available_space)
if to_copy_buffer > 0:
self._speech_buffer[speech_buffer_index : speech_buffer_index + to_copy_buffer] = input_frame.data[
:to_copy_buffer
]
speech_buffer_index += to_copy_buffer
elif not self._speech_buffer_max_reached:
# reached self._opts.max_buffered_speech (padding is included)
self._speech_buffer_max_reached = True
logger.warning(
"max_buffered_speech reached, ignoring further data for the current speech input" # noqa: E501
)
inference_duration = time.perf_counter() - start_time
extra_inference_time = max(
0.0,
extra_inference_time + inference_duration - window_duration,
)
if inference_duration > SLOW_INFERENCE_THRESHOLD:
logger.warning(
"inference is slower than realtime",
extra={"delay": extra_inference_time},
)
def _reset_write_cursor() -> None:
nonlocal speech_buffer_index
assert self._speech_buffer is not None
if speech_buffer_index <= self._prefix_padding_samples:
return
padding_data = self._speech_buffer[
speech_buffer_index - self._prefix_padding_samples : speech_buffer_index
]
self._speech_buffer_max_reached = False
self._speech_buffer[: self._prefix_padding_samples] = padding_data
speech_buffer_index = self._prefix_padding_samples
def _copy_speech_buffer() -> rtc.AudioFrame:
# copy the data from speech_buffer
assert self._speech_buffer is not None
speech_data = self._speech_buffer[:speech_buffer_index].tobytes() # noqa: B023
return rtc.AudioFrame(
sample_rate=self._input_sample_rate,
num_channels=1,
samples_per_channel=speech_buffer_index, # noqa: B023
data=speech_data,
)
if pub_speaking:
pub_speech_duration += window_duration
else:
pub_silence_duration += window_duration
self._event_ch.send_nowait(
agents.vad.VADEvent(
type=agents.vad.VADEventType.INFERENCE_DONE,
samples_index=pub_current_sample,
timestamp=pub_timestamp,
silence_duration=pub_silence_duration,
speech_duration=pub_speech_duration,
probability=p,
inference_duration=inference_duration,
frames=[
rtc.AudioFrame(
data=input_frame.data[:to_copy_int].tobytes(),
sample_rate=self._input_sample_rate,
num_channels=1,
samples_per_channel=to_copy_int,
)
],
speaking=pub_speaking,
raw_accumulated_silence=silence_threshold_duration,
raw_accumulated_speech=speech_threshold_duration,
)
)
st_buffer = inference_f32_data if st_buffer is None else np.concatenate([st_buffer, inference_f32_data])
if p >= self._opts.activation_threshold:
speech_threshold_duration += window_duration
silence_threshold_duration = 0.0
if not pub_speaking:
if speech_threshold_duration >= self._opts.min_speech_duration:
pub_speaking = True
pub_silence_duration = 0.0
pub_speech_duration = speech_threshold_duration
if not st_started:
st_started = True
# reset at the beginning of a turn
st_buffer = inference_f32_data
self._event_ch.send_nowait(
agents.vad.VADEvent(
type=agents.vad.VADEventType.START_OF_SPEECH,
samples_index=pub_current_sample,
timestamp=pub_timestamp,
silence_duration=pub_silence_duration,
speech_duration=pub_speech_duration,
frames=[_copy_speech_buffer()],
speaking=True,
)
)
else:
silence_threshold_duration += window_duration
speech_threshold_duration = 0.0
if not pub_speaking:
_reset_write_cursor()
vad_ending = pub_speaking and silence_threshold_duration >= self._opts.min_silence_duration
eou_pred: EOUPrediction | None = None
if st_started and vad_ending:
start_time = time.perf_counter()
eou_pred = await self._loop.run_in_executor(
self._executor,
self._vad.predict_endpoint,
st_buffer,
)
elapsed_time = time.perf_counter() - start_time
if eou_pred is not None and eou_pred.prediction == 1:
# reset at the end of a turn
st_buffer = None
st_started = False
else:
# truncate buffer so it doesn't grow indefinitely
# as the model looks at the last 8 seconds only (at most)
st_buffer = st_buffer[-8 * 16000 :]
if vad_ending and eou_pred and eou_pred.prediction == 1:
pub_speaking = False
pub_speech_duration = 0.0
pub_silence_duration = silence_threshold_duration
self._event_ch.send_nowait(
agents.vad.VADEvent(
type=agents.vad.VADEventType.END_OF_SPEECH,
samples_index=pub_current_sample,
timestamp=pub_timestamp,
silence_duration=pub_silence_duration,
speech_duration=pub_speech_duration,
frames=[_copy_speech_buffer()],
speaking=False,
)
)
_reset_write_cursor()
# remove the frames that were used for inference from the input and inference frames
input_frames = []
inference_frames = []
# add the remaining data
if len(input_frame.data) - to_copy_int > 0:
data = input_frame.data[to_copy_int:].tobytes()
input_frames.append(
rtc.AudioFrame(
data=data,
sample_rate=self._input_sample_rate,
num_channels=1,
samples_per_channel=len(data) // 2,
)
)
if len(inference_frame.data) - self._model.window_size_samples > 0:
data = inference_frame.data[self._model.window_size_samples :].tobytes()
inference_frames.append(
rtc.AudioFrame(
data=data,
sample_rate=self._opts.sample_rate,
num_channels=1,
samples_per_channel=len(data) // 2,
)
)
Ofc, you also have to change turn_detection in your Agent to turn_detection="vad".
Please be aware the code is not reviewed and not meant to be used in production. This is just a POC.