> This page is for Audio Decisions.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://dev.hume.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://dev.hume.ai/_mcp/server.

# Audio Decisions in LiveKit

> Run a LiveKit voice agent in your terminal and follow how Hume Audio Decisions answers reach its LLM.

**Run a LiveKit agent that sends the user's audio to Hume Audio Decisions with `hume.DecisionModel` each time the user stops speaking, and puts the answers at the head of the user's message before the LLM replies.** Clone this example to follow along, or fork it as a starting point.

By the end you will have the agent running in your terminal, and you will know how the agent keeps the user's audio, when it cuts and sends each clip, how the answers reach the LLM, and how to log the user message the LLM receives.

<table>
  <tbody>
    <tr>
      <th width="20%">
        Repository
      </th>

      <td>
        [hume-audio-decisions-livekit-example](https://github.com/HumeAI/hume-audio-decisions-livekit-example)

         on GitHub
      </td>
    </tr>

    <tr>
      <th>
        Packages
      </th>

      <td>
        [`livekit-agents`](https://pypi.org/project/livekit-agents/)

         and 

        [`livekit-plugins-hume`](https://pypi.org/project/livekit-plugins-hume/)

         on PyPI, version 1.9.1 or later
      </td>
    </tr>

    <tr>
      <th>
        Python
      </th>

      <td>
        3.10 to 3.14
      </td>
    </tr>
  </tbody>
</table>

## Prerequisites

1. Python 3.10 to 3.14, and Git.
2. A microphone, and headphones so the agent doesn't hear its own voice.
3. An API key with Hume Audio Decisions access, from the [API keys page](https://cloud.hume.ai/settings/organization/api-keys) of the Hume Platform. Request access on the [Decisions API page](https://www.hume.ai/products/decision-model-api). See [Authentication](/audio-decisions/docs/authentication).
4. A [LiveKit Cloud](https://cloud.livekit.io/) project. The agent's speech-to-text, LLM, and text-to-speech run through [LiveKit Inference](https://docs.livekit.io/agents/models/inference/), which uses the project's API key.
5. The LiveKit CLI, which runs the agent in [console mode](https://docs.livekit.io/agents/server/startup-modes/#console-mode): on your machine, with your microphone and speakers, without joining a LiveKit room. Install it with `brew install livekit-cli` on macOS, or as in [Install the CLI](https://docs.livekit.io/reference/developer-tools/livekit-cli/#install-the-cli) on Linux and Windows.

## Run the example

Clone the repository and install its dependencies. If you use uv, it needs version 0.13.6 or later and installs the Python version in `.python-version` for you. If you use pip, first check that `python3 --version` reports 3.10 to 3.14.

#### uv

#### Shell

```bash
git clone https://github.com/HumeAI/hume-audio-decisions-livekit-example.git
cd hume-audio-decisions-livekit-example
uv sync
```

#### pip

#### Shell

```bash
git clone https://github.com/HumeAI/hume-audio-decisions-livekit-example.git
cd hume-audio-decisions-livekit-example
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

Copy the example environment file.

#### Shell

```bash
cp .env.example .env.local
```

Set your Hume API key in `.env.local`, and set the three LiveKit values from your project's settings in LiveKit Cloud. A value exported in your shell takes precedence over the file.

#### .env.local

```bash
HUME_API_KEY=your_hume_api_key
LIVEKIT_URL=your_livekit_url
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
```

Start the agent, which introduces itself and then listens. Press `q` to stop it.

#### Shell

```bash
lk agent console
```

Speak, then pause. When your turn ends, the agent logs the user message as the LLM receives it: the reading, which holds the answers, then your words. The reading has one signal per decision, named by the decision's key and followed by its answer: a probability's value, a choice's two likeliest options with their probabilities, and a score's position on its levels. With the example's three decisions, `frustration`, `speakers`, and `intelligibility`, a line looks like this one, shown without the log prefix.

#### Terminal

```text
User: ([frustration value=0.82],[speakers one=0.97, two=0.02],[intelligibility value=2.9]) This is the third time I've asked.
```

When a reading is missing or unexpected, check these causes.

1. `(no reading)` on a turn means that turn has no answers. Either Hume Audio Decisions didn't answer within 2 seconds of you stopping, which logs a warning, or the request failed, which logs an error, or it answered none of the decisions, which logs a warning for each. `401` in that error means the Hume API key is wrong, and `403` means your organization lacks access to Hume Audio Decisions. The agent keeps running without readings until you fix the key.
2. `(no reading)` with nothing logged means the turn holds no new speech. Part of your transcript arrived after LiveKit ended the turn, and became a turn of its own.
3. Most questions need at least 5 seconds of audio. A short reply such as "Yes." is still sent, since each clip starts half a second before you speak, but its answers are less reliable. See [How it sends audio](/audio-decisions/docs/integrations/livekit#how-it-sends-audio).

## How it works

`agent.py` is the voice agent, and `audio_decisions.py` holds the `AudioDecisions` class, which cuts each clip, sends it with `hume.DecisionModel`, and returns the reading. Each step below links the section of the [LiveKit integration](/audio-decisions/docs/integrations/livekit) guide that explains its pieces.

#### Choose the decisions

`DECISIONS` holds the questions, keyed by name, and each name labels its answer in the reading. Each LiveKit decision type is sent as one Hume Audio Decisions primitive and reads differently: a `Probability` as the estimated share of raters who would say yes, a `Choice` as its likeliest options with their probabilities, and a `Score` as a position on its levels, counted from 0. See [Map LiveKit decisions to primitives](/audio-decisions/docs/integrations/livekit#map-livekit-decisions-to-primitives).

**`agent.py (lines 25-36)`**

```python agent.py (lines 25-36)
DECISIONS: dict[str, llm.Decision] = {
    "frustration": llm.Probability("Does the speaker sound frustrated?"),
    "speakers": llm.Choice(
        "How many distinct speakers are there?",
        # An option's description is optional.
        options={"one": "", "two": "", "three_or_more": ""},
    ),
    "intelligibility": llm.Score(
        "How much of the speaker's speech can a listener understand?",
        levels=["Almost none", "Some", "Most", "All"],
    ),
}
```

A `Choice` option can carry a description. An empty string sends the option without one.

**`agent.py (lines 27-31)`**

```python agent.py (lines 27-31)
    "speakers": llm.Choice(
        "How many distinct speakers are there?",
        # An option's description is optional.
        options={"one": "", "two": "", "three_or_more": ""},
    ),
```

#### Explain the reading to the LLM

`INSTRUCTIONS` is the agent's system prompt. It shows the LLM the shape of the reading, says what `(no reading)` means, and tells the LLM not to mention the reading, which is for the LLM only.

**`agent.py (lines 43-46)`**

```python agent.py (lines 43-46)
Each user message starts with a reading of how the user sounded, in parentheses, such \
as ([frustration value=0.12],[speakers one=0.98, two=0.01],[intelligibility \
value=2.8]). The user's words follow it. The user never sees the reading, so don't \
mention it or its numbers. (no reading) means there is none for that message.
```

Each decision gets a paragraph that says what its value means and the threshold at which the LLM acts on it. See [Add it to a voice agent](/audio-decisions/docs/integrations/livekit#add-it-to-a-voice-agent).

**`agent.py (lines 48-61)`**

```python agent.py (lines 48-61)
frustration is the estimated share of raters who would say the user sounded \
frustrated, from 0 to 1. If it is 0.6 or above, acknowledge once that the user sounds \
frustrated, then focus on helping.

speakers is how many distinct voices were in the user's audio, with how likely each \
count is. If two or three_or_more is 0.5 or above, someone near the user may be \
talking too: answer only what the user asked you, and if the words seem meant for \
someone else, ask whether they're talking to you.

intelligibility is how much of the user's speech a listener could understand, as a \
position on a scale from 0 (almost none) to 3 (all). It is a measure, not a \
confidence, so a low value is a real reading. If it is below 1.5, the transcription \
may be wrong: say back what you heard and ask the user to confirm or repeat it before \
acting on it.
```

#### Pass the audio through listen

`stt_node` is the step of the agent that turns the user's audio into a transcript. The override passes the audio through `AudioDecisions.listen` on its way to LiveKit's default `stt_node`, so speech-to-text gets every frame unchanged. See [Add it to a voice agent](/audio-decisions/docs/integrations/livekit#add-it-to-a-voice-agent).

**`agent.py (lines 70-75)`**

```python agent.py (lines 70-75)
    def stt_node(
        self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings
    ) -> AsyncGenerator[stt.SpeechEvent, None]:
        return Agent.default.stt_node(
            self, self._audio_decisions.listen(audio), model_settings
        )
```

#### Keep the most recent audio

`AudioDecisions` takes the session and the decisions, with `clip_seconds` and `wait_limit` defaulting to 5 and 2 seconds. `hume.DecisionModel()` reads `HUME_API_KEY` and raises `ValueError` when it is not set. The class listens for three session events: the user's state, each transcript, and the agent's state.

**`audio_decisions.py (lines 56-76)`**

```python audio_decisions.py (lines 56-76)
    def __init__(
        self,
        session: AgentSession[Any],
        decisions: Mapping[str, llm.Decision],
        *,
        clip_seconds: float = 5.0,
        wait_limit: float = 2.0,
    ) -> None:
        self._session = session
        self._decisions = decisions
        self._clip_seconds = clip_seconds
        self._wait_limit = wait_limit
        # It reads HUME_API_KEY from the environment.
        self._model = hume.DecisionModel()
        self._recent_audio: deque[tuple[float, rtc.AudioFrame]] = deque()
        self._turn_started_at: float | None = None
        self._turn_transcribed = False
        self._request: asyncio.Task[str] | None = None
        session.on("user_state_changed", self._on_user_state_changed)
        session.on("user_input_transcribed", self._on_user_input_transcribed)
        session.on("agent_state_changed", self._on_agent_state_changed)
```

`listen` yields each frame unchanged and keeps the frames that arrived in the last `clip_seconds`, with their arrival times. When the audio stream ends, it cancels a running request.

**`audio_decisions.py (lines 78-90)`**

```python audio_decisions.py (lines 78-90)
    async def listen(
        self, audio: AsyncIterable[rtc.AudioFrame]
    ) -> AsyncIterator[rtc.AudioFrame]:
        """Yields the caller's audio unchanged, and keeps the last few seconds of it."""
        try:
            async for frame in audio:
                now = time.time()
                self._recent_audio.append((now, frame))
                while self._recent_audio[0][0] < now - self._clip_seconds:
                    self._recent_audio.popleft()
                yield frame
        finally:
            self._drop_request()
```

#### Cut a clip at the end of speech

`user_state_changed` fires a moment after VAD detects the start or end of speech, and `speech_timestamp` carries when it happened. The first speech of a turn sets the turn's start.

**`audio_decisions.py (lines 99-107)`**

```python audio_decisions.py (lines 99-107)
    def _on_user_state_changed(self, event: UserStateChangedEvent) -> None:
        # LiveKit reports the start and the end of speech a moment after each happens,
        # and the event carries the time it happened.
        happened_at = event.speech_timestamp or event.created_at
        if event.new_state == "speaking":
            if self._turn_started_at is None:
                self._turn_started_at = happened_at
                self._turn_transcribed = False
            return
```

When the user goes from speaking to listening, the clip is every frame kept since 0.5 seconds before the turn's first speech, pauses included. A clip shorter than 1 second is not sent, since Hume Audio Decisions rejects it. See [How it sends audio](/audio-decisions/docs/integrations/livekit#how-it-sends-audio).

**`audio_decisions.py (lines 108-114)`**

```python audio_decisions.py (lines 108-114)
        if event.old_state != "speaking" or self._turn_started_at is None:
            return

        clip_start = self._turn_started_at - LEAD_IN_SECONDS
        clip = [frame for arrived, frame in self._recent_audio if arrived >= clip_start]
        if sum(frame.duration for frame in clip) < MIN_CLIP_SECONDS:
            return
```

A newer clip holds the latest speech of the turn, so it cancels a request that is still running. The request runs in a background task, with a timeout that ends at the [wait limit](/audio-decisions/docs/realtime#set-the-wait-limit-in-code), counted from when the user stopped.

**`audio_decisions.py (lines 116-121)`**

```python audio_decisions.py (lines 116-121)
        # The newest clip holds the latest speech of the turn, so it replaces a running
        # request.
        self._drop_request()
        # The wait limit counts from when the caller stopped.
        timeout = self._wait_limit - (time.time() - happened_at)
        self._request = asyncio.create_task(self._ask(clip, timeout=max(timeout, 0.0)))
```

#### Drop speech that never becomes a turn

While the agent can't be interrupted, such as during its first 3 seconds of speech in a session while echo cancellation warms up, LiveKit by default sends speech-to-text silence in place of the user's audio. That speech never becomes a turn, so when the agent stops speaking, `AudioDecisions` drops the speech's clip and its request, and the next clip starts after it.

**`audio_decisions.py (lines 127-140)`**

```python audio_decisions.py (lines 127-140)
    def _on_agent_state_changed(self, event: AgentStateChangedEvent) -> None:
        # While the agent can't be interrupted, as in its first 3 seconds of speech in a
        # session while echo cancellation warms up, LiveKit by default sends
        # speech-to-text silence in place of the caller's audio. That speech never
        # becomes a turn, so its start and its request are dropped. A caller still
        # speaking, or whose words were transcribed, is taking a turn.
        if (
            event.old_state != "speaking"
            or self._session.user_state == "speaking"
            or self._turn_transcribed
        ):
            return
        self._turn_started_at = None
        self._drop_request()
```

A user who is still speaking, or whose words were transcribed, is taking a turn, so their clip is kept.

**`audio_decisions.py (lines 123-125)`**

```python audio_decisions.py (lines 123-125)
    def _on_user_input_transcribed(self, event: UserInputTranscribedEvent) -> None:
        if event.transcript.strip():
            self._turn_transcribed = True
```

#### Send the clip

`evaluate` sends the clip and the decisions to Hume Audio Decisions, after mixing the audio to mono and resampling it to 16 kHz. `max_retry=0` turns off retries, since a retry would outlast the wait limit. See [Handle setup and request failures](/audio-decisions/docs/integrations/livekit#handle-setup-and-request-failures).

**`audio_decisions.py (lines 149-154)`**

```python audio_decisions.py (lines 149-154)
            response = await self._model.evaluate(
                audio=clip,
                decisions=self._decisions,
                # A retry would outlast the wait limit.
                conn_options=APIConnectOptions(max_retry=0, timeout=timeout),
            )
```

Every failure logs and returns `(no reading)`, so the reply goes ahead without answers: a timeout as a warning, an error status with the status and the Hume Audio Decisions error message, and any other failure, such as a failed DNS lookup, in full.

**`audio_decisions.py (lines 155-169)`**

```python audio_decisions.py (lines 155-169)
        except APITimeoutError:
            logger.warning(
                "Hume did not answer within %.1f seconds of the caller stopping",
                self._wait_limit,
            )
            return NO_READING
        except APIStatusError as error:
            # The message has the HTTP status and Hume's explanation, without the body
            # that the full error repeats.
            logger.error("%s", error.message)
            return NO_READING
        except APIError as error:
            # The full error names the cause, such as a failed DNS lookup.
            logger.error("%s", error)
            return NO_READING
```

A decision that Hume Audio Decisions could not answer is logged as a warning, and the other answers become the reading.

**`audio_decisions.py (lines 170-172)`**

```python audio_decisions.py (lines 170-172)
        for name, reason in response.errors.items():
            logger.warning("Hume gave no answer for %s: %s", name, reason)
        return _format_reading(response.results)
```

#### Return the reading

`reading` waits for the turn's running request, which gives up at the wait limit, and returns `(no reading)` when the turn has none. It also clears the turn's start, so no clip joins speech from before and after the agent's reply.

**`audio_decisions.py (lines 92-97)`**

```python audio_decisions.py (lines 92-97)
    async def reading(self) -> str:
        """Waits for a running request, which gives up at the wait limit."""
        request, self._request = self._request, None
        # The next clip must not join speech from before and after the agent's reply.
        self._turn_started_at = None
        return await request if request else NO_READING
```

`_format_reading` writes a probability's value with two decimals, a score's position with one, and a choice's two likeliest options with their probabilities. See [How the answers reach the LLM](/audio-decisions/docs/integrations/livekit#how-the-answers-reach-the-llm).

**`audio_decisions.py (lines 175-196)`**

```python audio_decisions.py (lines 175-196)
def _format_reading(results: Mapping[str, llm.DecisionResult]) -> str:
    """Formats results as `([frustration value=0.82],[speakers one=0.97, two=0.02])`.

    A probability is the estimated share of raters who would say yes. A choice is its
    two likeliest options with their probabilities. A score is a position on the
    decision's levels, counted from 0.
    """
    signals = []
    for name, result in results.items():
        if isinstance(result, llm.ProbabilityResult):
            signals.append(f"[{name} value={result.value:.2f}]")
        elif isinstance(result, llm.ScoreResult):
            signals.append(f"[{name} value={result.value:.1f}]")
        # Hume gives a probability for every option of a choice, though LiveKit's type
        # allows `None`.
        elif result.probabilities:
            likeliest = sorted(
                result.probabilities.items(), key=lambda item: item[1], reverse=True
            )[:2]
            options = ", ".join(f"{option}={share:.2f}" for option, share in likeliest)
            signals.append(f"[{name} {options}]")
    return f"({','.join(signals)})" if signals else NO_READING
```

#### Add the reading to the turn

LiveKit calls `on_user_turn_completed` before the LLM replies. The agent awaits the reading, puts it at the head of the user's message, and logs the message as the LLM receives it. See [Check that answers reach the LLM](/audio-decisions/docs/integrations/livekit#check-that-answers-reach-the-llm).

**`agent.py (lines 77-82)`**

```python agent.py (lines 77-82)
    async def on_user_turn_completed(
        self, turn_ctx: llm.ChatContext, new_message: llm.ChatMessage
    ) -> None:
        reading = await self._audio_decisions.reading()
        new_message.content = [f"{reading} {new_message.text_content}"]
        logger.info("User: %s", new_message.text_content)
```

#### Start the session

The session's speech-to-text, LLM, and text-to-speech models run through LiveKit Inference.

**`agent.py (lines 90-96)`**

```python agent.py (lines 90-96)
    session = AgentSession[None](
        stt=inference.STT(model="assemblyai/assemblyai-stt-3-7-realtime-agent"),
        llm=inference.LLM(model="google/gemma-4-31b-it"),
        tts=inference.TTS(
            model="fishaudio/s2.1-pro",
            voice="fa4c9eb3dccc4806b382b40d61c6b10a",
        ),
```

Preemptive generation is off. A preemptive reply starts on the transcript before the reading is in the user's message, and LiveKit discards it when the message changes. See [Add it to a voice agent](/audio-decisions/docs/integrations/livekit#add-it-to-a-voice-agent).

**`agent.py (lines 97-102)`**

```python agent.py (lines 97-102)
        turn_handling=TurnHandlingOptions(
            turn_detection=inference.TurnDetector(),
            # A preemptive reply starts before the reading is in the caller's message,
            # and LiveKit discards it when the message changes.
            preemptive_generation={"enabled": False},
        ),
```

The session gets one `AudioDecisions`, which the agent receives, and the agent greets the user once the session starts.

**`agent.py (lines 105-109)`**

```python agent.py (lines 105-109)
    audio_decisions = AudioDecisions(session, DECISIONS)

    await session.start(agent=Assistant(audio_decisions), room=ctx.room)

    await session.generate_reply(instructions="Introduce yourself to the user.")
```

#### Complete files

**`agent.py`**

```python title="agent.py"
import logging
from collections.abc import AsyncGenerator, AsyncIterable

from dotenv import load_dotenv
from livekit import rtc
from livekit.agents import (
    Agent,
    AgentServer,
    AgentSession,
    JobContext,
    ModelSettings,
    TurnHandlingOptions,
    cli,
    inference,
    llm,
    stt,
)

from audio_decisions import AudioDecisions

load_dotenv(".env.local")

logger = logging.getLogger("agent")

DECISIONS: dict[str, llm.Decision] = {
    "frustration": llm.Probability("Does the speaker sound frustrated?"),
    "speakers": llm.Choice(
        "How many distinct speakers are there?",
        # An option's description is optional.
        options={"one": "", "two": "", "three_or_more": ""},
    ),
    "intelligibility": llm.Score(
        "How much of the speaker's speech can a listener understand?",
        levels=["Almost none", "Some", "Most", "All"],
    ),
}

INSTRUCTIONS = """\
You are a helpful assistant in a voice conversation. Your responses will be spoken \
aloud, so avoid emojis, bullet points, or other formatting that can't be spoken. Keep \
your responses brief.

Each user message starts with a reading of how the user sounded, in parentheses, such \
as ([frustration value=0.12],[speakers one=0.98, two=0.01],[intelligibility \
value=2.8]). The user's words follow it. The user never sees the reading, so don't \
mention it or its numbers. (no reading) means there is none for that message.

frustration is the estimated share of raters who would say the user sounded \
frustrated, from 0 to 1. If it is 0.6 or above, acknowledge once that the user sounds \
frustrated, then focus on helping.

speakers is how many distinct voices were in the user's audio, with how likely each \
count is. If two or three_or_more is 0.5 or above, someone near the user may be \
talking too: answer only what the user asked you, and if the words seem meant for \
someone else, ask whether they're talking to you.

intelligibility is how much of the user's speech a listener could understand, as a \
position on a scale from 0 (almost none) to 3 (all). It is a measure, not a \
confidence, so a low value is a real reading. If it is below 1.5, the transcription \
may be wrong: say back what you heard and ask the user to confirm or repeat it before \
acting on it.
"""


class Assistant(Agent):
    def __init__(self, audio_decisions: AudioDecisions) -> None:
        super().__init__(instructions=INSTRUCTIONS)
        self._audio_decisions = audio_decisions

    def stt_node(
        self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings
    ) -> AsyncGenerator[stt.SpeechEvent, None]:
        return Agent.default.stt_node(
            self, self._audio_decisions.listen(audio), model_settings
        )

    async def on_user_turn_completed(
        self, turn_ctx: llm.ChatContext, new_message: llm.ChatMessage
    ) -> None:
        reading = await self._audio_decisions.reading()
        new_message.content = [f"{reading} {new_message.text_content}"]
        logger.info("User: %s", new_message.text_content)


server = AgentServer()


@server.rtc_session()
async def entrypoint(ctx: JobContext) -> None:
    session = AgentSession[None](
        stt=inference.STT(model="assemblyai/assemblyai-stt-3-7-realtime-agent"),
        llm=inference.LLM(model="google/gemma-4-31b-it"),
        tts=inference.TTS(
            model="fishaudio/s2.1-pro",
            voice="fa4c9eb3dccc4806b382b40d61c6b10a",
        ),
        turn_handling=TurnHandlingOptions(
            turn_detection=inference.TurnDetector(),
            # A preemptive reply starts before the reading is in the caller's message,
            # and LiveKit discards it when the message changes.
            preemptive_generation={"enabled": False},
        ),
    )

    audio_decisions = AudioDecisions(session, DECISIONS)

    await session.start(agent=Assistant(audio_decisions), room=ctx.room)

    await session.generate_reply(instructions="Introduce yourself to the user.")


if __name__ == "__main__":
    cli.run_app(server)
```

**`audio_decisions.py`**

```python title="audio_decisions.py"
"""Hume Audio Decisions for a LiveKit agent.

The agent passes the caller's audio through `AudioDecisions.listen`, which keeps the
last few seconds of it. Each time the caller stops speaking, `AudioDecisions` sends
Hume a clip through LiveKit's Hume plugin. When the caller's turn ends, the agent
awaits `AudioDecisions.reading` and puts the answers at the head of the caller's
message.
"""

import asyncio
import logging
import time
from collections import deque
from collections.abc import AsyncIterable, AsyncIterator, Mapping
from typing import Any

from livekit import rtc
from livekit.agents import (
    AgentSession,
    AgentStateChangedEvent,
    APIConnectOptions,
    APIError,
    APIStatusError,
    APITimeoutError,
    UserInputTranscribedEvent,
    UserStateChangedEvent,
    llm,
)
from livekit.plugins import hume

logger = logging.getLogger("audio_decisions")

NO_READING = "(no reading)"

# Hume rejects audio shorter than this.
MIN_CLIP_SECONDS = 1.0

# A clip starts this long before the caller's first speech of the turn, so that a
# short reply still reaches the minimum.
LEAD_IN_SECONDS = 0.5


class AudioDecisions:
    """Asks Hume how the caller sounded on each turn.

    Args:
        session: The session the caller speaks in.
        decisions: The decisions to ask for, keyed by the name each has in the
            reading.
        clip_seconds: The most audio a clip holds, counted back from when the
            caller stops speaking.
        wait_limit: How long after the caller stops speaking the reply waits for
            the answers.
    """

    def __init__(
        self,
        session: AgentSession[Any],
        decisions: Mapping[str, llm.Decision],
        *,
        clip_seconds: float = 5.0,
        wait_limit: float = 2.0,
    ) -> None:
        self._session = session
        self._decisions = decisions
        self._clip_seconds = clip_seconds
        self._wait_limit = wait_limit
        # It reads HUME_API_KEY from the environment.
        self._model = hume.DecisionModel()
        self._recent_audio: deque[tuple[float, rtc.AudioFrame]] = deque()
        self._turn_started_at: float | None = None
        self._turn_transcribed = False
        self._request: asyncio.Task[str] | None = None
        session.on("user_state_changed", self._on_user_state_changed)
        session.on("user_input_transcribed", self._on_user_input_transcribed)
        session.on("agent_state_changed", self._on_agent_state_changed)

    async def listen(
        self, audio: AsyncIterable[rtc.AudioFrame]
    ) -> AsyncIterator[rtc.AudioFrame]:
        """Yields the caller's audio unchanged, and keeps the last few seconds of it."""
        try:
            async for frame in audio:
                now = time.time()
                self._recent_audio.append((now, frame))
                while self._recent_audio[0][0] < now - self._clip_seconds:
                    self._recent_audio.popleft()
                yield frame
        finally:
            self._drop_request()

    async def reading(self) -> str:
        """Waits for a running request, which gives up at the wait limit."""
        request, self._request = self._request, None
        # The next clip must not join speech from before and after the agent's reply.
        self._turn_started_at = None
        return await request if request else NO_READING

    def _on_user_state_changed(self, event: UserStateChangedEvent) -> None:
        # LiveKit reports the start and the end of speech a moment after each happens,
        # and the event carries the time it happened.
        happened_at = event.speech_timestamp or event.created_at
        if event.new_state == "speaking":
            if self._turn_started_at is None:
                self._turn_started_at = happened_at
                self._turn_transcribed = False
            return
        if event.old_state != "speaking" or self._turn_started_at is None:
            return

        clip_start = self._turn_started_at - LEAD_IN_SECONDS
        clip = [frame for arrived, frame in self._recent_audio if arrived >= clip_start]
        if sum(frame.duration for frame in clip) < MIN_CLIP_SECONDS:
            return

        # The newest clip holds the latest speech of the turn, so it replaces a running
        # request.
        self._drop_request()
        # The wait limit counts from when the caller stopped.
        timeout = self._wait_limit - (time.time() - happened_at)
        self._request = asyncio.create_task(self._ask(clip, timeout=max(timeout, 0.0)))

    def _on_user_input_transcribed(self, event: UserInputTranscribedEvent) -> None:
        if event.transcript.strip():
            self._turn_transcribed = True

    def _on_agent_state_changed(self, event: AgentStateChangedEvent) -> None:
        # While the agent can't be interrupted, as in its first 3 seconds of speech in a
        # session while echo cancellation warms up, LiveKit by default sends
        # speech-to-text silence in place of the caller's audio. That speech never
        # becomes a turn, so its start and its request are dropped. A caller still
        # speaking, or whose words were transcribed, is taking a turn.
        if (
            event.old_state != "speaking"
            or self._session.user_state == "speaking"
            or self._turn_transcribed
        ):
            return
        self._turn_started_at = None
        self._drop_request()

    def _drop_request(self) -> None:
        if self._request:
            self._request.cancel()
            self._request = None

    async def _ask(self, clip: list[rtc.AudioFrame], *, timeout: float) -> str:
        try:
            response = await self._model.evaluate(
                audio=clip,
                decisions=self._decisions,
                # A retry would outlast the wait limit.
                conn_options=APIConnectOptions(max_retry=0, timeout=timeout),
            )
        except APITimeoutError:
            logger.warning(
                "Hume did not answer within %.1f seconds of the caller stopping",
                self._wait_limit,
            )
            return NO_READING
        except APIStatusError as error:
            # The message has the HTTP status and Hume's explanation, without the body
            # that the full error repeats.
            logger.error("%s", error.message)
            return NO_READING
        except APIError as error:
            # The full error names the cause, such as a failed DNS lookup.
            logger.error("%s", error)
            return NO_READING
        for name, reason in response.errors.items():
            logger.warning("Hume gave no answer for %s: %s", name, reason)
        return _format_reading(response.results)


def _format_reading(results: Mapping[str, llm.DecisionResult]) -> str:
    """Formats results as `([frustration value=0.82],[speakers one=0.97, two=0.02])`.

    A probability is the estimated share of raters who would say yes. A choice is its
    two likeliest options with their probabilities. A score is a position on the
    decision's levels, counted from 0.
    """
    signals = []
    for name, result in results.items():
        if isinstance(result, llm.ProbabilityResult):
            signals.append(f"[{name} value={result.value:.2f}]")
        elif isinstance(result, llm.ScoreResult):
            signals.append(f"[{name} value={result.value:.1f}]")
        # Hume gives a probability for every option of a choice, though LiveKit's type
        # allows `None`.
        elif result.probabilities:
            likeliest = sorted(
                result.probabilities.items(), key=lambda item: item[1], reverse=True
            )[:2]
            options = ", ".join(f"{option}={share:.2f}" for option, share in likeliest)
            signals.append(f"[{name} {options}]")
    return f"({','.join(signals)})" if signals else NO_READING
```

## Adapt it to your agent

1. **Add it to an existing agent.** Follow [Install](/audio-decisions/docs/integrations/livekit#install) and then [Add it to a voice agent](/audio-decisions/docs/integrations/livekit#add-it-to-a-voice-agent) in the LiveKit integration guide. The two sections cover what this example sets up: the plugin, `audio_decisions.py`, and the changes in `Assistant` and `entrypoint`.
2. **Change the decisions.** Edit or add decisions in `DECISIONS`. See [Map LiveKit decisions to primitives](/audio-decisions/docs/integrations/livekit#map-livekit-decisions-to-primitives) and [Writing questions](/audio-decisions/docs/writing-questions).
3. **Describe each decision to the LLM.** Give each decision in `DECISIONS` a paragraph in `INSTRUCTIONS` that says what its value means, as the example does.
4. **Set your own thresholds.** The thresholds in `INSTRUCTIONS` are the example's. Set yours from your own calls, as in [Setting thresholds](/audio-decisions/docs/interpreting-answers#setting-thresholds), once your decisions and their order are final, since adding, removing, or reordering decisions can change the other answers.
5. **Change the clip length or the wait limit.** Pass `clip_seconds` or `wait_limit` to `AudioDecisions`. See [Choose which audio to send](/audio-decisions/docs/realtime#choose-which-audio-to-send) and [Set the wait limit in code](/audio-decisions/docs/realtime#set-the-wait-limit-in-code).
6. **Use other models.** Any LiveKit Inference model, or a LiveKit plugin for a provider you have an account with, can replace the models in `entrypoint`.
7. **Act on answers outside the LLM.** `_ask` has every answer in `response.results` before it formats the reading. Act on them there in your backend, such as alerting a supervisor.
8. **Serve users in LiveKit rooms.** Console mode serves only your own machine. To reach users in a room, run the agent in one of LiveKit's other [startup modes](https://docs.livekit.io/agents/server/startup-modes/).

## Next steps

#### [LiveKit integration](/audio-decisions/docs/integrations/livekit)

Add `hume.DecisionModel` and the `AudioDecisions` class to your own LiveKit agent.

#### [Interpreting answers](/audio-decisions/docs/interpreting-answers)

Learn how to read each answer and set thresholds for acting on it.