<!-- generated: do not edit. source: content/docs/integrations/pipecat/turns.md -->

# Pipecat: turn detection

`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.

| Class | Position | Use it when |
| --- | --- | --- |
| `SpragTurnDetector` | A processor after the transport input | The model starts and ends every turn, and the pipeline has no VAD |
| `SpragTurnAnalyzer` | A turn analyzer in the user stop strategy | The 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`.

```python
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`](https://github.com/sprag-ai/pipecat-sprag/blob/main/examples/turn_detection.py)
in the plugin repository is a complete voice agent built this way.

| Argument | Required | Type | Notes |
| --- | --- | --- | --- |
| `model` | No | string | A model id from the [turn detection models](/docs/turns/models). Defaults to `sprag-eot`. |
| `params` | No | `SpragTurnParams` | The session's settings; see [Parameters](#parameters). |
| `api_key` | No | string | Your Sprag API key. Defaults to `SPRAG_API_KEY`. |
| `url` | No | string | Defaults 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.

```python
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](/docs/turns/websocket#configure-the-session).

```python
from pipecat_sprag.turns import SpragTurnDetector, SpragTurnParams

turns = SpragTurnDetector(
    params=SpragTurnParams(eot_threshold=0.7, eager_eot_threshold=0.4),
)
```

| Field | Default | Effect |
| --- | --- | --- |
| `eot_threshold` | `0.6` | The probability that ends the turn. |
| `eager_eot_threshold` | `None` | The probability that reports an eager end. `None` reports none. |
| `min_silence_ms` | `200` | The silence a pause needs before its first reading. |
| `eot_timeout_ms` | `3000` | The 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.

| Handler | Event | When |
| --- | --- | --- |
| `on_turn_started` | `TurnStarted` | A turn opens. |
| `on_turn_update` | `TurnUpdate` | Each reading during a pause. |
| `on_eager_end` | `TurnEagerEnd` | The first reading in a pause to reach `eager_eot_threshold`. |
| `on_turn_resumed` | `TurnResumed` | The user speaks again after an eager end. |
| `on_turn_ended` | `TurnEnded` | The turn ends. `reason` is `model`, `timeout`, or `client`. |
| `on_session_closed` | `SessionClosed` | The session closes, with its `usage`. |

The fields of each event are listed under
[Events](/docs/turns/websocket#events) in the turns WebSocket docs.

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

```python
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](/docs/turns/websocket#usage) in the turns WebSocket docs.
