Skip to content
IntroducingSPEV, the first audio-in decision modelRead the launch →
SPEV, the first audio-in decision model →
sprag

Pipecat: turn detection

Decide when the user has finished their turn in a Pipecat pipeline with a Sprag turn detection model.

SpragTurnDetector and SpragTurnAnalyzer decide when the user has finished their turn in a Pipecat pipeline. Each one streams the user's audio over wss://api.sprag.ai/v1/turns and ends the turn when the model does.

ClassPositionUse it when
SpragTurnDetectorA processor after the transport inputThe model starts and ends every turn, and the pipeline has no VAD
SpragTurnAnalyzerA turn analyzer in the user stop strategyThe pipeline keeps its own VAD and transcription

Setup

SpragTurnDetector goes between the transport input and the transcription service. Pass commit_on_turn_end=True to SpragSTTService so that each turn is transcribed when the detector ends it, and give the user aggregator Pipecat's external turn strategies. Pass the parameters when you create the aggregator pair from your existing LLMContext.

from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineWorker
from pipecat.processors.aggregators.llm_response_universal import (
    LLMContextAggregatorPair,
    LLMUserAggregatorParams,
)
from pipecat.turns.user_start import ExternalUserTurnStartStrategy
from pipecat.turns.user_stop import ExternalUserTurnStopStrategy
from pipecat.turns.user_turn_strategies import UserTurnStrategies
from pipecat_sprag.stt import SpragSTTService
from pipecat_sprag.turns import SpragAgentTextObserver, SpragTurnDetector

turns = SpragTurnDetector()
stt = SpragSTTService(commit_on_turn_end=True)
user_params = LLMUserAggregatorParams(
    user_turn_strategies=UserTurnStrategies(
        start=[ExternalUserTurnStartStrategy()],
        stop=[ExternalUserTurnStopStrategy(timeout=0.1)],
    )
)

user_aggregator, assistant_aggregator = LLMContextAggregatorPair(context, user_params=user_params)
pipeline = Pipeline([
    transport.input(),
    turns,
    stt,
    user_aggregator,
    llm,
    tts,
    transport.output(),
    assistant_aggregator,
])
worker = PipelineWorker(pipeline, observers=[SpragAgentTextObserver(turns)])

A turn.started event starts the user's turn and interrupts the bot. A turn.ended event commits the turn's audio for transcription, and the turn ends once its transcript arrives.

examples/turn_detection.py in the plugin repository is a complete voice agent built this way.

ArgumentRequiredTypeNotes
modelNostringA model id from the turn detection models. Defaults to sprag-eot.
paramsNoSpragTurnParamsThe session's settings; see Parameters.
api_keyNostringYour Sprag API key. Defaults to SPRAG_API_KEY.
urlNostringDefaults to wss://api.sprag.ai/v1/turns.

SpragTurnAnalyzer takes the same arguments.

Use a turn analyzer

SpragTurnAnalyzer is a Pipecat turn analyzer. Pass it to TurnAnalyzerUserTurnStopStrategy, and the user's turn stops when the model ends it. Create one analyzer for each pipeline.

Use this setup instead of the detector setup above. Keep your existing transcription service and user_params (LLMUserAggregatorParams, including your VAD settings). Replace only the turn stop strategies before creating the aggregator pair and building the pipeline.

from dataclasses import replace

from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineWorker
from pipecat.processors.aggregators.llm_response_universal import LLMContextAggregatorPair
from pipecat.turns.user_stop import TurnAnalyzerUserTurnStopStrategy
from pipecat.turns.user_turn_strategies import UserTurnStrategies
from pipecat_sprag.turns import SpragAgentTextObserver, SpragTurnAnalyzer

analyzer = SpragTurnAnalyzer()
existing_strategies = user_params.user_turn_strategies
user_params = replace(
    user_params,
    user_turn_strategies=UserTurnStrategies(
        start=existing_strategies.start if existing_strategies is not None else None,
        stop=[TurnAnalyzerUserTurnStopStrategy(turn_analyzer=analyzer)],
    ),
)
user_aggregator, assistant_aggregator = LLMContextAggregatorPair(context, user_params=user_params)
pipeline = Pipeline([
    transport.input(),
    stt,
    user_aggregator,
    llm,
    tts,
    transport.output(),
    assistant_aggregator,
])
worker = PipelineWorker(pipeline, observers=[SpragAgentTextObserver(analyzer)])

Agent context

SpragAgentTextObserver sends the model the words of the agent's last reply that were played, as the session's agent_text. Pass the detector or the analyzer to it, and add it to the worker's observers.

Parameters

SpragTurnParams carries the session's settings. Each field takes the same values as the field of the same name in the turns WebSocket.

from pipecat_sprag.turns import SpragTurnDetector, SpragTurnParams

turns = SpragTurnDetector(
    params=SpragTurnParams(eot_threshold=0.7, eager_eot_threshold=0.4),
)
FieldDefaultEffect
eot_threshold0.6The probability that ends the turn.
eager_eot_thresholdNoneThe probability that reports an eager end. None reports none.
min_silence_ms200The silence a pause needs before its first reading.
eot_timeout_ms3000The silence that ends the turn at any probability.

If a value is out of range, SpragTurnParams raises a pydantic ValidationError.

Turn events

Both classes report each event of the session to an event handler, with the event as a typed model.

HandlerEventWhen
on_turn_startedTurnStartedA turn opens.
on_turn_updateTurnUpdateEach reading during a pause.
on_eager_endTurnEagerEndThe first reading in a pause to reach eager_eot_threshold.
on_turn_resumedTurnResumedThe user speaks again after an eager end.
on_turn_endedTurnEndedThe turn ends. reason is model, timeout, or client.
on_session_closedSessionClosedThe session closes, with its usage.

The fields of each event are listed under Events in the turns WebSocket docs.

To prepare a reply early, handle on_eager_end, and drop the reply in on_turn_resumed.

from pipecat_sprag.turns import SpragTurnDetector, SpragTurnParams, TurnEagerEnd, TurnResumed

turns = SpragTurnDetector(params=SpragTurnParams(eager_eot_threshold=0.4))


@turns.event_handler("on_eager_end")
async def on_eager_end(detector: SpragTurnDetector, event: TurnEagerEnd) -> None:
    logger.info(f"Turn {event.turn_index} is probably over ({event.probability:.2f})")


@turns.event_handler("on_turn_resumed")
async def on_turn_resumed(detector: SpragTurnDetector, event: TurnResumed) -> None:
    logger.info(f"Turn {event.turn_index} resumed at {event.audio_window_end:.2f} s")

Usage

usage on the detector or the analyzer holds the usage of its latest session once that session has closed. usage.invocations is the session's count of pause determinations. While the session is open, usage is None.

More information about what a pause determination counts can be found under Usage in the turns WebSocket docs.