Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 122 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,124 @@ consume its mailbox. The event limit bounds output per turn, but does not bound
the owner's mailbox across turns. An adapter must also bound individual output
sizes. Do not pass an untrusted client directly as the owner.

## Transcription

### Speech-to-text interface

All speech-to-text adapters use one interface, `AudioFlow.STT`. External
services go through ReqLLM with `AudioFlow.STT.ReqLLM`. Local models go through
Bumblebee with `AudioFlow.STT.Bumblebee`. Both take the same options and give
the same output, so you can change the engine without other changes:

```elixir
voxtral = {AudioFlow.STT.ReqLLM, model: "mistral:voxtral-mini-latest", language: "en"}
deepgram = {AudioFlow.STT.ReqLLM, model: "deepgram:nova-3", segments: true}
whisper = {AudioFlow.STT.Bumblebee, model: "openai/whisper-small", language: "en"}
```

| Option | Meaning |
| --- | --- |
| `:model` | Required. A ReqLLM model, or a Hugging Face Whisper repository. |
| `:language` | An ISO 639-1 code, or `nil` (the default) for detection. |
| `:segments` | `true` to emit timed `AudioFlow.Transcript.Segment` values in place of text. |

The input is one `AudioFlow.Audio` utterance at any sample rate. The adapter
converts it for the engine. Output arrives when the engine finishes; there are
no partial results. Errors fail the turn.

| Engine | Adapter | Models |
| --- | --- | --- |
| External services | `AudioFlow.STT.ReqLLM` | Mistral Voxtral, Deepgram, OpenAI Whisper and GPT-4o transcription, Groq Whisper, ElevenLabs Scribe, OpenRouter |
| Self-hosted servers | `AudioFlow.STT.ReqLLM` with `:base_url` | vLLM with Voxtral, Qwen3-ASR or Whisper, and other OpenAI-compatible `/audio/transcriptions` servers |
| Local models | `AudioFlow.STT.Bumblebee` | Bumblebee Whisper checkpoints |

`AudioFlow.STT.ReqLLM` sends each utterance as one WAV upload. ReqLLM reads the
provider key from its environment variable, for example `MISTRAL_API_KEY` or
`DEEPGRAM_API_KEY`, or from `:api_key`, which can be a function. Other options
go to `ReqLLM.transcribe/3`. Retries are off by default, because the session
deadline bounds the turn. ReqLLM has no Deepgram provider, so AudioFlow
registers `AudioFlow.STT.DeepgramProvider` for the Deepgram `/v1/listen` API.

```elixir
local_voxtral = {AudioFlow.STT.ReqLLM,
model: "vllm:mistralai/Voxtral-Mini-3B-2507", base_url: "http://localhost:8000/v1"}
```

With `segments: true`, the adapter asks Mistral and Deepgram for segment times.
OpenAI-compatible Whisper servers return segments without a request. GPT-4o
transcription models give only text, so the adapter then emits text. Mistral
does not accept segment times together with `:language`; the adapter then
sends only the language and emits text.

`AudioFlow.STT.Bumblebee` loads one shared serving for each model, revision,
language and serving options, through `AudioFlow.Servings`, on first use.
Bumblebee fixes the Whisper language when it builds the serving. Add
`AudioFlow.Servings` to the inference children, and call
`AudioFlow.STT.Bumblebee.preload/1` at startup, because the first load can take
minutes. `:serving_options` select the backend and compiler (EXLA by default).
The adapter converts the input to 16 kHz with `AudioFlow.Resampler`. With the
pinned Bumblebee 0.8.0 and EXLA 1.0.0, Whisper `timestamps: :segments` fails to
compile, so local segments have no times inside a session.

The graph editor has `whisper.stt` (local), `deepgram.stt` and `mistral.stt`
nodes. The remote nodes use a fixed provider and the server key.

### Transcription sessions

A session without `:llm` and `:tts` is a transcription session. Each audio turn
runs only the STT adapter and then ends with `{:done, metrics}`. Text input
returns `{:error, {:unsupported_input, :llm}}`, and `:history` is rejected.

```elixir
{:ok, session} = AudioFlow.start_session(stt: deepgram)
{:ok, turn} = AudioFlow.submit(session, audio)
```

An STT adapter can emit three kinds of values, in any session:

| Adapter output | Session event | In the prompt and history |
| --- | --- | --- |
| `text` | `{:transcript, text}` | yes |
| `%AudioFlow.Transcript.Segment{}` | `{:segment, segment}` | yes, joined with spaces |
| `{:partial, text}` | `{:partial_transcript, text}` | no |

A segment has `text`, `start_ms` and `end_ms` from the start of the turn audio,
and optional `words` with their own times. Times are `nil` when the engine does
not give them. The `AudioFlow.STT` adapters do not emit partials. A custom
adapter can emit them: a partial is an unstable hypothesis for the text that
follows the final text emitted so far. The metrics add
`first_partial_transcript_us`. The WebSocket transport sends segments as
`transcript` messages with timing fields, and partials as `partial_transcript`
messages. Recordings keep segment text and drop partials. Graph sessions do not
use these values.

### Long recordings

For a long recording, use `AudioFlow.transcribe/3`. It cuts the audio into
sections, runs the STT adapter on each section in a supervised task, and returns
an `AudioFlow.Transcript` with times from the start of the input:

```elixir
{:ok, audio} = AudioFlow.Wav.read("meeting.wav")
{:ok, transcript} = AudioFlow.transcribe(audio, voxtral, chunk_ms: 30_000, max_concurrency: 4)
transcript.text
File.write!("meeting.srt", AudioFlow.Transcript.to_srt(transcript))
```

Fixed sections can cut a word at a boundary. Set `:vad` to a voice detector
tuple to send only detected utterances; the audio must then use the detector
sample rate. Each section has its own `:timeout_ms` (120 seconds by default),
and the first failure returns `{:error, {:section, index, reason}}`.
`:on_segment` receives each segment in order. Segments without times get the
times of their section. `AudioFlow.Wav` reads only mono 16-bit PCM WAV. Convert
other files with FFmpeg. To print captions for a file:

```sh
AUDIOFLOW_ML=1 mix run examples/transcribe.exs input.wav openai/whisper-small
DEEPGRAM_API_KEY=... mix run examples/transcribe.exs input.wav deepgram:nova-3
MISTRAL_API_KEY=... mix run examples/transcribe.exs input.wav mistral:voxtral-mini-latest
```

## Conversation history

Enable history when the LLM adapter accepts chat messages:
Expand Down Expand Up @@ -178,6 +296,7 @@ AUDIOFLOW_ML=1 mix run path/to/your_session.exs
```

`AudioFlow.Models.whisper/2` builds a Whisper serving with Bumblebee and EXLA.
`AudioFlow.STT.Bumblebee` uses it.
`AudioFlow.Models.language_model/2` builds a streaming text serving. The selected
repository must have a model architecture and tokenizer supported by Bumblebee.
There is no automatic claim of support for each model named in the brief.
Expand Down Expand Up @@ -257,8 +376,9 @@ the calling process. It can call an application-owned ONNX serving in the same
way. `AudioFlow.Adapters.Function` can call a remote API or another local engine.
Remote clients must set their own connection and request timeouts.

Whisper input conversion requires 16 kHz PCM. Resample before submission.
Whisper output is currently read after utterance transcription. LLM output is
For speech recognition, use `AudioFlow.STT.Bumblebee` (see
[Transcription](#transcription)). It converts the input to 16 kHz. Whisper
output is read after utterance transcription. LLM output is
streamed and grouped into sentences before synthesis. This is not yet a
continuous streaming speech recognizer.

Expand Down
22 changes: 12 additions & 10 deletions docs/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ accepting the same types). Model and voice IDs must be available to your account
Keys may be strings or zero-argument functions; functions allow runtime rotation.

```elixir
stt = {AudioFlow.Adapters.Deepgram,
[model: "nova-3", api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]}
stt = {AudioFlow.STT.ReqLLM,
[model: "deepgram:nova-3", api_key: fn -> System.fetch_env!("DEEPGRAM_API_KEY") end]}

tts = {AudioFlow.Adapters.Cartesia,
[model: "sonic-3.6", voice_id: System.fetch_env!("CARTESIA_VOICE_ID"),
Expand All @@ -26,13 +26,15 @@ tts = {AudioFlow.Adapters.ElevenLabs,
api_key: fn -> System.fetch_env!("ELEVENLABS_API_KEY") end]}
```

Deepgram uses Listen v1 WebSocket with mono `linear16` PCM at the input
`Audio.sample_rate`, sends bounded binary frames, then `CloseStream`. It emits
only final transcript segments, separated by spaces; the concluding Metadata
message completes the run. Interim results are ignored. This is a streaming
provider response for an already committed utterance, **not** microphone-to-STT
live ingress or a persistent recognition session. Optional `:language` is sent
as a query parameter. Empty final transcripts (silence) emit nothing.
All speech-to-text from external services goes through ReqLLM with
`AudioFlow.STT.ReqLLM`, for Mistral Voxtral, Deepgram, OpenAI, Groq, ElevenLabs,
OpenRouter and self-hosted vLLM servers. See the common STT interface in the
[README](https://github.com/flowcopilot/audioflow#transcription). ReqLLM has no
Deepgram provider, so AudioFlow registers `AudioFlow.STT.DeepgramProvider`.
It sends the utterance as one WAV body to the pre-recorded `POST /v1/listen`
API, with `model`, optional `language` and `:provider_options` as query
parameters. With `segments: true`, it requests `utterances=true` and emits each
utterance as a timed segment. Deepgram interim results are not used.

Cartesia uses `/tts/bytes` and ElevenLabs uses `/text-to-speech/:voice_id/stream`.
Both stream raw signed 16-bit little-endian mono PCM as `AudioFlow.Audio`, default
Expand Down Expand Up @@ -158,7 +160,7 @@ Wire shapes were checked against official documentation on 2026-11-03:

- [OpenAI Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations)
- [Gemini Live WebSocket reference](https://ai.google.dev/api/live)
- [Deepgram Listen streaming reference](https://developers.deepgram.com/reference/speech-to-text/listen-streaming)
- [Deepgram pre-recorded utterances](https://developers.deepgram.com/docs/utterances)
- [Cartesia bytes TTS](https://docs.cartesia.ai/api-reference/tts/bytes)
- [ElevenLabs streaming TTS](https://elevenlabs.io/docs/api-reference/text-to-speech/stream)

Expand Down
18 changes: 11 additions & 7 deletions examples/chat/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ or model downloads are needed. Use the same profile for all Mix commands.
## Run native models on Apple Silicon

The repository `mise.toml` pins Erlang, Elixir, Node.js, and
[uv](https://docs.astral.sh/uv/). uv runs the separate Qwen3-ASR Python
process; reply model downloads use Elixir's `hf_hub` and need no Python or
`uvx`. Kokoro also needs `espeak-ng`, which mise does not provide.
[uv](https://docs.astral.sh/uv/). Model downloads use Elixir's `hf_hub` and
need no Python. Kokoro also needs `espeak-ng`, which mise does not provide.

```sh
mise install
Expand All @@ -54,7 +53,7 @@ model per stage stays loaded.
| Stage | Models | Runtime |
| --- | --- | --- |
| Speech recognition | Whisper tiny, small, large v3 turbo | Bumblebee on the EMLX GPU backend |
| Speech recognition | Qwen3-ASR 0.6B and 1.7B, 8-bit | mlx-audio in a Python process managed by uv |
| Speech recognition | Qwen3-ASR 0.6B and 1.7B | a vLLM server at `CHAT_ASR_BASE_URL`, through ReqLLM |
| Reply | Qwen3 0.6B, 1.7B, 4B, and 8B, 4-bit | native EMLXAxon Qwen3 generation |
| Speech | Kokoro 82M, four voices | Transmuter on the EMLX GPU backend |

Expand All @@ -69,11 +68,16 @@ Measured on an Apple M5 with 24 GB of memory, after the first turn:
| Models | First text | First audio |
| --- | ---: | ---: |
| Whisper small, Qwen3 1.7B | 0.9 s | 1.5 s |
| Qwen3-ASR 0.6B, Qwen3 0.6B | 0.3 s | 0.8 s |

The first turn after a switch compiles the new model. It took up to 6 s to the
first audio. Bumblebee has no Qwen3-ASR model, so Qwen3-ASR runs outside the
BEAM. Its log is `$TMPDIR/audioflow-chat-qwen3-asr.log`. Model checkpoints for
first audio.

Speech recognition uses the common `AudioFlow.STT` interface: local Whisper
through `AudioFlow.STT.Bumblebee`, and external services through
`AudioFlow.STT.ReqLLM`. Bumblebee has no Qwen3-ASR model, so Qwen3-ASR needs a
separate vLLM server, for example `vllm serve Qwen/Qwen3-ASR-1.7B`. Set
`CHAT_ASR_BASE_URL` when it does not listen on `http://localhost:8000/v1`. vLLM
needs a supported GPU; it does not use the Apple GPU. Model checkpoints for
the reply stage use hf_hub's cache, by default
`~/.cache/huggingface/hub/models--OWNER--REPO/snapshots/REVISION`.
The pinned revisions in `Chat.Catalog` are passed unchanged, and this directory
Expand Down
24 changes: 13 additions & 11 deletions examples/chat/lib/chat/catalog.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
defmodule Chat.Catalog do
@moduledoc """
The models the chat can switch between. All run on the Apple GPU through MLX.
The models the chat can switch between. Local models run on the Apple GPU
through MLX. Qwen3-ASR runs on a separate vLLM server.

`:memory_gb` estimates the loaded weights. Whisper loads in f32, so it uses
about twice its f16 download. Compiled kernels and caches add to this.
Expand Down Expand Up @@ -31,21 +32,22 @@ defmodule Chat.Catalog do
revision: "41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
memory_gb: 3.2
},
# Bumblebee has no Qwen3-ASR model. These use a vLLM server at
# CHAT_ASR_BASE_URL (default http://localhost:8000/v1) through ReqLLM.
# The server holds the weights, so they do not count in this process.
%{
id: "qwen3-asr-0.6b",
label: "Qwen3-ASR 0.6B (8-bit)",
engine: :qwen3_asr,
repo: "mlx-community/Qwen3-ASR-0.6B-8bit",
revision: "89e96d92ba34aca20b3e29fb10cc284097d1219f",
memory_gb: 1.0
label: "Qwen3-ASR 0.6B (vLLM)",
engine: :req_llm,
model: "vllm:Qwen/Qwen3-ASR-0.6B",
memory_gb: 0.0
},
%{
id: "qwen3-asr-1.7b",
label: "Qwen3-ASR 1.7B (8-bit)",
engine: :qwen3_asr,
repo: "mlx-community/Qwen3-ASR-1.7B-8bit",
revision: "a8379a2e2f9e313c9292cdf1af4055ab56d50d55",
memory_gb: 2.5
label: "Qwen3-ASR 1.7B (vLLM)",
engine: :req_llm,
model: "vllm:Qwen/Qwen3-ASR-1.7B",
memory_gb: 0.0
}
]

Expand Down
3 changes: 2 additions & 1 deletion examples/chat/lib/chat/engine.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ defmodule Chat.Engine do
do: %{
id: __MODULE__,
start:
{Supervisor, :start_link, [[Chat.Qwen3ASR, Chat.LocalEngine], [strategy: :one_for_one]]}
{Supervisor, :start_link,
[[AudioFlow.Servings, Chat.LocalEngine], [strategy: :one_for_one]]}
},
else: %{id: __MODULE__, start: {Agent, :start_link, [fn -> nil end]}}
end
Expand Down
4 changes: 2 additions & 2 deletions examples/chat/lib/chat/setup.ex
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ defmodule Chat.Setup do

[
stt:
{Adapters.Deepgram,
{AudioFlow.STT.ReqLLM,
[
model: env.("DEEPGRAM_MODEL") || "nova-3",
model: "deepgram:" <> (env.("DEEPGRAM_MODEL") || "nova-3"),
api_key: key(env, "DEEPGRAM_API_KEY"),
language: s["language"]
]},
Expand Down
66 changes: 29 additions & 37 deletions examples/chat/native/engine.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ defmodule Chat.LocalEngine do
Loads, swaps, and reports the shared models. One model per stage is loaded.

Whisper and Kokoro run through Bumblebee and Transmuter on the EMLX GPU
backend. Qwen3 replies run through the native EMLXAxon generator. Qwen3-ASR
runs in the `Chat.Qwen3ASR` sidecar. Sessions call `Chat.Stage`, which reads
backend. Whisper uses the common local STT adapter, `AudioFlow.STT.Bumblebee`.
Qwen3 replies run through the native EMLXAxon generator. Qwen3-ASR runs on a
vLLM server through `AudioFlow.STT.ReqLLM`. Sessions call `Chat.Stage`, which reads
the current adapter for each turn, so a switch applies to the next turn and
keeps conversation history.

Expand All @@ -18,8 +19,8 @@ defmodule Chat.LocalEngine do
alias AudioFlow.Adapters.Function
alias AudioFlow.Audio
alias AudioFlow.NxAdapter
alias AudioFlow.STT.Bumblebee, as: LocalSTT
alias Chat.Catalog
alias Chat.Qwen3ASR
alias EMLXAxon.Qwen3.Loader

@gpu {EMLX.Backend, device: :gpu}
Expand Down Expand Up @@ -178,31 +179,21 @@ defmodule Chat.LocalEngine do
model = Catalog.fetch!(:stt, id)
silence = %Audio{data: :binary.copy(<<0, 0>>, 16_000), sample_rate: 16_000}

case model.engine do
:whisper ->
{:ok, serving} =
AudioFlow.Models.whisper(model.repo,
load_options: [revision: model.revision],
model_options: [backend: @gpu],
defn_options: @defn
)

{name, pid} = start_serving(:"Chat.STT.#{id}", serving)

adapter =
{NxAdapter,
serving: name, input: &NxAdapter.whisper_input/1, output: &NxAdapter.transcript/1}

Nx.Serving.batched_run(name, NxAdapter.whisper_input(silence))
{:ok, %{adapter: adapter, serving: name, pid: pid}}

:qwen3_asr ->
with {:ok, _} <- Qwen3ASR.load(model),
{:ok, _} <- Qwen3ASR.transcribe(model, silence.data) do
run = &transcribe_qwen3(model, &1, &2)
{:ok, %{adapter: {Function, run: run}, sidecar: true}}
end
end
adapter =
case model.engine do
:whisper ->
{LocalSTT,
model: model.repo,
revision: model.revision,
serving_options: [model_options: [backend: @gpu], defn_options: @defn]}

:req_llm ->
base_url = System.get_env("CHAT_ASR_BASE_URL", "http://localhost:8000/v1")
{AudioFlow.STT.ReqLLM, model: model.model, base_url: base_url, api_key: "local"}
end

# The first request loads the model, or checks the server, and compiles kernels.
with :ok <- warm_up(adapter, silence), do: {:ok, %{adapter: adapter}}
end

defp load(:llm, id) do
Expand All @@ -214,11 +205,13 @@ defmodule Chat.LocalEngine do
{:ok, %{adapter: {Function, run: &generate(tokenizer, weights, &1, &2)}}}
end

defp transcribe_qwen3(model, %Audio{data: data}, emit) do
case Qwen3ASR.transcribe(model, data) do
{:ok, text} -> emit.(text)
{:error, reason} -> {:error, reason}
defp warm_up({module, options} = adapter, audio) do
with {:ok, _} <-
if(module == LocalSTT, do: module.preload(options), else: {:ok, nil}) do
AudioFlow.Adapter.run(adapter, audio, fn _ -> :ok end)
end
catch
{:adapter_error, _module, reason} -> {:error, reason}
end

# Streams sentence chunks, so speech starts after the first sentence.
Expand Down Expand Up @@ -257,11 +250,10 @@ defmodule Chat.LocalEngine do

defp release(_state, %{pid: pid}), do: DynamicSupervisor.terminate_child(Chat.Servings, pid)

# The sidecar holds one model. Keep it while the STT stage uses it.
defp release(state, %{sidecar: true}) do
if not Map.get(state.loaded[:stt] || %{}, :sidecar, false) and
Catalog.fetch!(:stt, state.selection.stt).engine != :qwen3_asr,
do: Qwen3ASR.stop()
# Loads of the same model share one serving. Keep it while the STT stage uses it.
defp release(state, %{adapter: {LocalSTT, options} = adapter}) do
if get_in(state.loaded, [:stt, :adapter]) != adapter,
do: LocalSTT.release(options)

:ok
end
Expand Down
Loading
Loading