From ad371d67bc80871da7fa956df45b211f438117ef Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Sun, 15 Nov 2026 13:47:53 +0200 Subject: [PATCH] refactor: remove dead code and consolidate documentation - Remove obsolete ChatHTTP and Jido modules and related tests - Rename the HTTP inference adapter and update its docs and examples - Trim legacy documentation and adjust CI and Markdown configuration --- .github/workflows/tests.yml | 2 +- .rumdl.toml | 2 - Brief.md | 73 -- README.md | 1058 +---------------- docs/guides/conversation-and-retrieval.md | 136 --- docs/guides/conversation-evaluations.md | 52 - docs/guides/interruption.md | 108 -- docs/guides/model-languages.md | 54 - docs/guides/req-llm.md | 15 +- docs/guides/telemetry-audit.md | 23 - docs/input-processing.md | 128 -- docs/providers.md | 517 -------- docs/recording-and-privacy.md | 98 -- docs/refactoring/test-audit.md | 59 - docs/refactoring/untangle.md | 68 -- docs/transports.md | 170 --- docs/webrtc-avatars.md | 212 ---- examples/chat/README.md | 2 +- examples/network/README.md | 2 +- examples/rtvi-client/README.md | 2 +- lib/audio_flow/adapters/cartesia.ex | 5 +- lib/audio_flow/adapters/chat_http.ex | 65 - lib/audio_flow/adapters/eleven_labs.ex | 5 +- lib/audio_flow/adapters/fish_audio.ex | 4 +- lib/audio_flow/adapters/fish_audio_api.ex | 4 +- lib/audio_flow/adapters/gemini_live.ex | 3 +- lib/audio_flow/adapters/openai_realtime.ex | 4 +- lib/audio_flow/application.ex | 1 - lib/audio_flow/graph.ex | 8 +- lib/audio_flow/graph/nodes/chat_http.ex | 101 -- lib/audio_flow/graph/nodes/req_llm.ex | 56 + lib/audio_flow/jido.ex | 7 - lib/audio_flow/rtvi/web_socket.ex | 3 +- lib/audio_flow/smart_turn.ex | 3 +- lib/audio_flow/speex_dsp.ex | 3 +- lib/audio_flow/telemetry.ex | 2 +- lib/audio_flow/telephony/web_socket.ex | 4 +- lib_media/audio_flow/adapters/moshi.ex | 3 +- priv/audio_flow/smart_turn.py | 2 +- site/src/content/docs/docs/chat-example.md | 10 + .../content/docs/docs/features/providers.md | 203 +++- .../docs/docs/features/webrtc-avatars.md | 3 +- site/src/content/docs/docs/guides/history.md | 19 +- .../docs/docs/guides/http-inference.md | 46 +- site/src/content/docs/docs/guides/images.md | 28 +- .../content/docs/docs/guides/local-models.md | 55 +- .../docs/docs/guides/membrane-input.md | 24 +- site/src/content/docs/docs/guides/output.md | 34 +- site/src/content/docs/docs/guides/routing.md | 21 +- site/src/content/docs/docs/guides/sessions.md | 18 + .../src/content/docs/docs/guides/telemetry.md | 4 + site/src/content/docs/docs/guides/video.md | 35 +- site/src/content/docs/docs/index.md | 15 +- site/src/content/docs/docs/quickstart.md | 3 + .../docs/docs/validation/benchmarks.md | 51 +- .../docs/docs/validation/model-checks.md | 57 +- .../docs/validation/pipecat-comparison.md | 12 +- test/audio_flow/application_test.exs | 15 - test/conversation_evaluation_test.exs | 9 +- test/conversation_http_test.exs | 192 ++- test/cross_feature_acceptance_test.exs | 7 +- test/graph_test.exs | 17 +- ...at_http_test.exs => req_llm_http_test.exs} | 80 +- ..._model_test.exs => req_llm_model_test.exs} | 22 +- ..._tools_test.exs => req_llm_tools_test.exs} | 34 +- ui/README.md | 11 +- ui/lib/audio_flow_ui.ex | 2 +- .../audio_flow_ui_web/live/examples_live.ex | 4 +- ui/test/mcp_test.exs | 4 +- 69 files changed, 899 insertions(+), 3200 deletions(-) delete mode 100644 Brief.md delete mode 100644 docs/guides/conversation-and-retrieval.md delete mode 100644 docs/guides/conversation-evaluations.md delete mode 100644 docs/guides/interruption.md delete mode 100644 docs/guides/model-languages.md delete mode 100644 docs/guides/telemetry-audit.md delete mode 100644 docs/input-processing.md delete mode 100644 docs/providers.md delete mode 100644 docs/recording-and-privacy.md delete mode 100644 docs/refactoring/test-audit.md delete mode 100644 docs/refactoring/untangle.md delete mode 100644 docs/transports.md delete mode 100644 docs/webrtc-avatars.md delete mode 100644 lib/audio_flow/adapters/chat_http.ex delete mode 100644 lib/audio_flow/graph/nodes/chat_http.ex create mode 100644 lib/audio_flow/graph/nodes/req_llm.ex delete mode 100644 lib/audio_flow/jido.ex delete mode 100644 test/audio_flow/application_test.exs rename test/{chat_http_test.exs => req_llm_http_test.exs} (78%) rename test/{chat_http_model_test.exs => req_llm_model_test.exs} (77%) rename test/{chat_http_tools_test.exs => req_llm_tools_test.exs} (88%) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f8efdd6..20df9e8 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -8,7 +8,7 @@ on: - 'site/**' - '.github/workflows/pages.yml' push: - branches: [main, feat/parallel-issue-integration] + branches: [main] paths-ignore: *docs-only permissions: diff --git a/.rumdl.toml b/.rumdl.toml index feaa084..6be4f1e 100644 --- a/.rumdl.toml +++ b/.rumdl.toml @@ -5,5 +5,3 @@ disable = ["MD013"] [per-file-ignores] # Starlight links are site routes, not file paths. "site/src/content/docs/**/*.md" = ["MD057"] -# Brief.md is a pasted research note without a title. -"Brief.md" = ["MD041"] diff --git a/Brief.md b/Brief.md deleted file mode 100644 index e193b09..0000000 --- a/Brief.md +++ /dev/null @@ -1,73 +0,0 @@ -Exactly. With Nx + Axon + Bumblebee + EXLA, we could build a Pipecat alternative where not just orchestration but also much of the ML inference runs natively within the Elixir ecosystem. - -And there's a particularly interesting new development: Transmuter, announced on October 26, 2026, which enables running ONNX models through Nx without implementing each architecture manually. - -[image](https://www.google.com/s2/favicons?domain=https://forum.elixirforum.com\&sz=32) - -Elixir Programming Language Forum - -## The expanded architecture - -## What could run locally? - -| Stage | Candidate implementation | Feasibility | -| ------------------ | ------------------------------------ | ----------------------- | -| VAD | Silero VAD through ONNX/Nx | Needs validation | -| Speech recognition | Whisper via Bumblebee | Supported | -| LLM | Qwen3, Gemma, SmolLM3 | Supported architectures | -| Speech synthesis | Kokoro, VITS via Transmuter | Emerging | -| Embeddings | BERT, NomicBERT | Supported | -| Vision | CLIP, SigLIP, vision-language models | Supported or emerging | - -Bumblebee already implements Whisper and several text-generation architectures. Transmuter expands possible coverage to models including Kokoro, SpeechT5, and VITS. - -[image](https://www.google.com/s2/favicons?domain=https://github.com\&sz=32) - -GitHub+1 - -Importantly, model support doesn't guarantee real-time streaming performance. Low-latency incremental STT, TTS generation, and cancellation would need benchmarking. - -## The architectural decision I'd make - -I'd treat `Nx.Serving` as the shared inference infrastructure, rather than loading a separate model for every conversation. - -For example: - -```text -children = [ - {Nx.Serving, - name: MyApp.Whisper, - serving: whisper_serving, - batch_size: 4}, - - {Nx.Serving, - name: MyApp.LLM, - serving: llm_serving} -] -``` - -These are illustrative child specifications; the servings themselves must be initialized first. - -That would allow multiple voice sessions to share model weights and GPU resources, with batching where appropriate. - -For low-latency conversations, we'd need to be especially careful with batching delays, inference queues, and streaming output. - -## One more interesting opportunity - -This could become more than a Pipecat clone. - -With Membrane, Nx, and OTP, we'd have the foundations for an Elixir-native multimodal agent runtime supporting: - -- Voice-to-voice conversations -- Video and image understanding -- Local and cloud inference -- Multiple concurrent agents -- Dynamic model routing -- Distributed inference workers -- Supervised, long-lived conversation sessions - -I'd keep the model inference interface independent of the underlying engine, so that Nx, ONNX, llama.cpp, and remote inference APIs could all be used interchangeably. - -The biggest research question is whether we can achieve competitive speech-to-speech latency with an Nx-native inference pipeline. If we can, the combination of BEAM concurrency and integrated media processing becomes particularly compelling. - -I'd start by benchmarking Membrane → Whisper/Nx → Qwen3/Nx → Kokoro/Nx → Membrane, comparing time-to-first-transcript, time-to-first-audio, interruption latency, and maximum concurrent sessions against Pipecat. diff --git a/README.md b/README.md index 9a22ab1..ed47212 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ Optional bounded history keeps successful conversation turns in each session. This implements the session runtime, model routing, distributed inference workers, native Silero voice detection, Whisper and text-generation adapters, Kokoro and -VITS speech synthesis, and Membrane audio and video input from -[Brief.md](Brief.md). The native media path has a recorded-speech integration +VITS speech synthesis, and Membrane audio and video input. +The native media path has a recorded-speech integration check and a controlled Pipecat comparison. Output interruption is measured at the software transport. Acoustic interruption needs a device loopback check. HTTP language inference can use a compatible local server or cloud endpoint. @@ -22,1035 +22,85 @@ Use the tool versions in `mise.toml`, or Elixir 1.18 or later with a compatible OTP version. ```sh +mix deps.get mix test mix run examples/demo.exs mix audio_flow.bench --runs 20 --concurrency 4 ``` -For a browser chat with typed and spoken messages, see -[examples/chat](examples/chat/README.md). Its Linux demo needs no model download; -the app also exposes server-configured speech providers, languages, redacted -recordings, playback progress and provisional pause/resume. Its always-on -modes use `AudioFlow.Duplex` with OpenAI Realtime or a local Moshi server: the -microphone stays open from Start to Stop and the model audio plays at the same -time. OpenAI detects each utterance, replies by voice and stops the reply when -you speak. +The core needs no model downloads. Optional parts are enabled with environment +variables: -To build agents as node graphs, see [ui](ui/README.md). It is a local dashboard -with a canvas editor and an MCP endpoint for coding agents. A session runs an -`AudioFlow.Graph` with the `:graph` option. - -The website and documentation are at -. Their source is in [site](site/README.md). +| Variable | Adds | Source directory | +| --- | --- | --- | +| none | Sessions, history, routing, HTTP inference, remote providers | `lib` | +| `AUDIOFLOW_ML=1` | Bumblebee, EXLA, Transmuter models | `lib_ml` | +| `AUDIOFLOW_MEDIA=1` | Membrane audio and video | `lib_media` | +| `AUDIOFLOW_WEBRTC=1` | ExWebRTC media output and the PCM bridge | `lib_webrtc` | Core, ML, media, and combined ML/media builds use separate `_build` directories. Changing a feature flag does not remove modules used by another build profile. -Optional WebRTC audio/video and its PCM Session bridge have -[runnable network examples](examples/network/README.md). The -[avatar viewer](examples/avatar/README.md) subscribes to finite provider -publications when explicitly configured with an account. - -## Sessions - -```elixir -{:ok, session} = AudioFlow.start_session(AudioFlow.Adapters.Demo.options()) -audio = %AudioFlow.Audio{data: <<0, 0>>, sample_rate: 16_000} -{:ok, turn} = AudioFlow.submit(session, audio) - -receive do - {AudioFlow, ^session, ^turn, event} -> IO.inspect(event) -end - -AudioFlow.cancel(session) -AudioFlow.stop_session(session) -``` - -For hosted Fish Audio TTS, use `AudioFlow.Adapters.FishAudioAPI` with an API -key, model and hosted voice ID. For self-hosted Fish Speech, use -`AudioFlow.Adapters.FishAudio` with a server endpoint and optional voice reference. -See [Fish Audio backends](docs/providers.md#fish-audio-hosted-api). -Native Fish inference on Nx needs a separate model/codec integration; see the -[Nx feasibility assessment](docs/providers.md#native-fish-speech-on-nx). - -For OpenAI Realtime, Gemini Live or a local -[Moshi](docs/providers.md#local-moshi-speech-to-speech) server without chained -stages, use the explicit -[Session speech-to-speech mode](docs/providers.md#session-speech-to-speech-mode). -It accepts committed PCM and does not replay cross-turn history. For a -continuous conversation with the microphone open, use `AudioFlow.Duplex` with -[OpenAI Realtime](docs/providers.md#continuous-openai-realtime-conversation) or -[Moshi](docs/providers.md#continuous-full-duplex-moshi). - -The owner receives transcript, text, audio, and terminal events. See -`AudioFlow` for the event format. Each turn has a unique reference. A session -accepts one turn at a time. Further input returns `{:error, :busy}`. To interrupt -a reply, call `cancel/1`, then submit the new utterance. With an `:output` -transport, cancellation also flushes queued output. Without a transport, the -caller must flush its playback device. Cancellation kills the turn task. A shared hardware batch can still -run to completion. - -A typed message uses `%AudioFlow.Text{data: "Hello"}`. Text turns skip STT -and emit no transcript event. The trimmed text goes directly to the LLM, and the -reply follows the same TTS and history path. Text must be valid UTF-8, and -`:max_input_bytes` applies to it. - -Audio input must be mono signed 16-bit little-endian PCM. Input limits, output event -limits, and timeouts are set per session. Defaults are 960,000 input bytes, -1,024 output events, and 30 seconds. An empty transcript ends the turn without -generation. STT chunks form one prompt. LLM chunks go to TTS in sequence. -Use complete sentences for LLM output when possible. - -The session stops when its owner exits. Turn failures do not stop the session. -Sessions are temporary supervisor children: a session crash does not restart a -conversation with lost state. The caller must start a new session after a crash. - -Adapter calls acknowledge each output before they continue. The owner must -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: - -```elixir -{:ok, session} = AudioFlow.start_session( - Keyword.put(session_options, :history, [max_turns: 8, max_bytes: 16_384])) -``` - -`history: true` uses these defaults. History is disabled by default, so existing -adapters continue to receive one transcript string. With history enabled, the -LLM receives a list of `%{role: :user | :assistant, content: text}` maps. Saved -user/assistant pairs precede the current user message. `Prompt.qwen3/2` and -`Adapters.ReqLLM` accept this format. Custom adapters and routing functions -must accept the message list when history is enabled. System instructions stay -in the model adapter or prompt formatter. - -`max_turns` counts complete saved pairs. `max_bytes` counts UTF-8 text content. -The runtime removes the oldest complete pairs to fit the new prompt. It also -removes old pairs when a successful reply makes saved history exceed a limit. -Current input and reply text must fit as one pair; excess text ends the turn -with `{:error, :context_limit, metrics}`. The input limit also applies while -transcript or description chunks arrive. The budget excludes role fields, -prompt delimiters, and system instructions. It is a byte limit, not a model -token limit. Set model sequence limits for the chosen workload. - -Only nonempty user and assistant text becomes a saved pair. The session saves -it after successful inference and acknowledgement from `Output.finish/2`. -Failed or cancelled active turns leave the previous saved pairs intact. -Transport completion can precede physical playback. A cancellation after -`:done` flushes output and keeps that completed pair. Each session owns its -history, including when sessions share the same inference worker. - -Image descriptions use the user role, so later voice turns can refer to the -described image. History stores text, rather than raw image or audio data. -Clear the saved text while the session is idle: - -```elixir -:ok = AudioFlow.clear_history(session) -``` - -An active turn returns `{:error, :busy}`. Clearing a session with history -disabled is an idempotent operation. History lasts for the session process; -owner exit or a session crash ends it. - -Set `AUDIOFLOW_HISTORY=1` for `examples/models.exs`, `examples/media.exs`, and -`examples/local.exs`. The supplied history prompt supports native Qwen3 or an -HTTP chat engine. Other native models need their own message formatter. -Benchmark attempts use new sessions, so their history starts empty. - -For sequential recorded turns on one session: - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_HISTORY=1 AUDIOFLOW_LLM=Qwen/Qwen3-0.6B \ - mix run examples/conversation.exs output first.s16le second.s16le -``` - -Inputs are mono 16 kHz s16le PCM. The example loads shared models once and -writes one PCM file plus JSON metadata per turn. It does not open a sound device. -The native conversation model check uses one Qwen3 serving for two turns and -checks recall of a codeword from the first turn. Its STT and TTS adapters are -controlled test adapters. Qwen3 message prompts are also compared with the -original pinned Jinja template. - -The saved [speech conversation checks](validation/conversation-smoke.json) -use the same two utterances with eSpeak NG and Kokoro input voices. With Kokoro -inputs, Whisper transcribed both utterances correctly and the second spoken -reply recalled the codeword `banana`. Whisper tiny misread the eSpeak inputs. -Both results are retained with model revisions and PCM hashes. These are small -checks of transcription and context use; model quality needs a broader workload. - -## Shared local models - -Enable the model code for all model commands: +To run an example with real inference, enable the model code: ```sh AUDIOFLOW_ML=1 mix deps.get -AUDIOFLOW_ML=1 mix compile --warnings-as-errors -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. -Both builders accept `:load_options` for repository revisions and caches, and -`:model_options` for parameter type and backend. The language builder also -accepts `:generation_options` for token limits and decoding strategy. Serving -options remain separate. The examples load parameters onto `EXLA.Backend`. - -The Qwen3 example uses `AudioFlow.Prompt.qwen3/2`, with thinking disabled and a -short spoken-reply instruction. Its format is checked against the pinned model's -original Jinja template. Other language models need their own prompt format. -Streamed text retains its whitespace. Common English titles and initials stay -with the following word. Empty text chunks do not cause a TTS request. - -`AudioFlow.Models.text_to_speech/2` builds a VITS or SpeechT5 serving through -Transmuter. `AudioFlow.NxAdapter.speech_audio/1` converts the float waveform to -mono s16le PCM in 20 ms chunks. Values outside the PCM range are clamped. -The model first generates a full sentence waveform. Splitting it into PCM -chunks does not make model inference incremental. - -`AudioFlow.Kokoro.serving/1` builds a shared Kokoro service. It loads the pinned -model, vocabulary, and selected voice style files once. The service accepts -English text with espeak-ng, or direct Kokoro phonemes. Its output is 24 kHz -PCM through `AudioFlow.Kokoro.audio/1`. - -Install espeak-ng for text input (`brew install espeak-ng` on macOS, or the -`espeak-ng` package on Linux). The tested version is 1.52.0. The executable only -converts text to phonemes. Kokoro inference runs through Nx, Transmuter, and -EXLA. Direct phoneme input does not need this executable. To write a WAV file: - -```sh AUDIOFLOW_ML=1 mix run examples/kokoro.exs "Hello from AudioFlow." output.wav ``` -Voice and speed controls use a request map: - -```elixir -serving = AudioFlow.Kokoro.serving(voices: ["af_heart", "am_adam"]) -# Start serving once with AudioFlow.Models.child_spec/3, under AudioFlow.TTS. -stream = Nx.Serving.batched_run(AudioFlow.TTS, - %{text: "Hello.", voice: "am_adam", speed: 1.2}) -pcm_chunks = AudioFlow.Kokoro.audio(stream) |> Enum.to_list() -``` - -Consume the result stream in the calling process. Set the adapter output mapper -to `&AudioFlow.Kokoro.audio/1`. Speed must be between 0.5 and 2.0. Only loaded -voices are accepted. Inputs longer than 510 phoneme symbols are split at spaces, -or at the limit when no space exists. No symbols are silently removed. Each -section runs as one batch because its waveform length depends on the text. -It emits PCM after that section is generated. It is not a continuous streaming -vocoder. A section's new token and waveform lengths can cause compilation; -`:cache_size` bounds the compiled shapes retained by Transmuter (default 64). - -The default phonemizer supports `en-us` and `en-gb`. It preserves punctuation -and converts the English diphthongs and affricates to Kokoro symbols. It does -not provide Misaki's dictionary and text normalization. Numbers, abbreviations, -and names can therefore sound different. Supply a custom phonemizer tuple or -`%{phonemes: phonemes}` when the application needs another front end. - -The pinned ONNX graph has a phase error at DC and Nyquist. The builder applies -the Transmuter phase correction before compilation. Voice style row selection -uses `phoneme_count - 1`, as in the original Kokoro inference code. - -Transmuter is pinned to a Git revision in `mix.exs` and `mix.lock`. Its current -source API differs from the older Hex release. `examples/local.exs` uses Kokoro -by default. Set `AUDIOFLOW_TTS=vits` for the pinned `Xenova/mms-tts-eng` model. -A custom TTS config is optional. - -Build each serving once. Start it under a supervisor with -`AudioFlow.Models.child_spec/3`. Use a distinct atom as each serving name. -The default batch size is 1 and the batch timeout is 5 ms. Tune these values -with real workload measurements. See [examples/local.exs](examples/local.exs). - -`AudioFlow.NxAdapter` calls `Nx.Serving.batched_run/2`. Input and output -functions translate model-specific values. It consumes streaming results in -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. - -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. - -## HTTP language inference - -`AudioFlow.Adapters.ReqLLM` accepts ReqLLM's model, context and generation -options directly. The AudioFlow bridge groups generated text into sentences -with whitespace preserved and executes caller-bound tools. Local Nx adapters -remain independent of ReqLLM. - -```elixir -llm = {AudioFlow.Adapters.ReqLLM, - model: %{provider: :openai, id: "audioflow-qwen"}, - base_url: "http://127.0.0.1:18082/v1", - api_key: "local", - system_prompt: AudioFlow.Prompt.default_system(), - temperature: 0.0, max_tokens: 64, - audio_flow: [tools: [MyApp.Actions.Weather], - tool_context: %{user_id: user_id}, tool_filler: "One moment."]} -{:ok, session} = AudioFlow.start_session( - Keyword.put(session_options, :llm, llm)) -``` - -Use a ReqLLM catalog model such as `"anthropic:claude-sonnet-4-5"`, or an inline -model for a local endpoint. `:base_url`, `:api_key`, `:system_prompt`, -`:provider_options`, `:req_http_options` and native `ReqLLM.Tool` definitions -are ReqLLM options. Resolve credentials when constructing the turn options; -ReqLLM also supports its provider credential configuration. No implicit system -prompt is added by the new bridge. Input accepts `ReqLLM.Context`, messages or -a string; session history still uses messages. - -The execution bridge currently supports HTTP SSE transports. It uses ReqLLM's -request builders, SSE parser, provider decoders and chunk accumulator, with -synchronous Finch reads to enforce byte budgets and backpressure. It does not -invoke ReqLLM's automatic retries, caches or fixture replays. WebSocket and -in-process ReqLLM transports are outside this bridge. Refusal, truncation, -empty replies and incomplete streams return errors; earlier complete sentences -may already have reached TTS. OpenAI-compatible streams require both a finish -reason and `[DONE]` before emitting the final fragment. - -Put AudioFlow execution settings under `:audio_flow`. `:tools` there accepts -Jido actions and `AudioFlow.Tool` definitions, while top-level `:tools` accepts -native `ReqLLM.Tool` structs. Both execute in linked tasks with bounded results -and deadlines, and cancellation stops them. `:tool_filler` is emitted for a -silent tool round. `:max_tool_rounds` defaults to 4, `:max_tool_calls` to 8, -`:tool_timeout_ms` to 10,000 and `:max_tool_result_bytes` to 8,192. - -`AudioFlow.Adapters.ChatHTTP` is a deprecated configuration shim, with no HTTP -implementation. Its complete `endpoint` URL maps to ReqLLM `base_url` without -`/chat/completions`; bare model IDs map to inline OpenAI models; `system` maps -to `system_prompt`; token limits and temperature map to ReqLLM options. Other -legacy arbitrary `parameters` are no longer forwarded: use ReqLLM generation -and provider options. ReqLLM chooses token field names, enables usage streaming, -omits implicit `n: 1`, and normalizes tool argument JSON and empty assistant -content. These wire differences preserve execution guarantees. - -The shared Finch pool uses HTTP/1 so the output callback applies back pressure -to socket reads. Cancellation closes the active connection. A failed output -callback also releases the connection. The following limits belong under `:audio_flow`: - -| Option | Default | Bound | -| --- | ---: | --- | -| `max_request_bytes` | 65,536 | Encoded request body | -| `max_response_bytes` | 262,144 | Complete response body | -| `max_event_bytes` | 16,384 | One SSE event | -| `max_text_bytes` | 8,192 | Generated text | -| `timeout_ms` | 30,000 | Budget for response reads | -| `receive_timeout_ms` | 10,000 | Wait for a response chunk | -| `pool_timeout_ms` | 5,000 | Wait for a connection | - -Connections have a five-second connection timeout. The response-read budget -excludes pool checkout, connection setup, and time blocked in the output -callback. Use a session or worker deadline to bound the complete operation. - -Run a direct text request: - -```sh -AUDIOFLOW_CHAT_ENDPOINT=http://127.0.0.1:18082/v1/chat/completions \ - AUDIOFLOW_LLM=audioflow-qwen mix run examples/http.exs "Say hello." -``` - -Set `AUDIOFLOW_CHAT_API_KEY` locally when authentication is required. To use -HTTP language inference with native Whisper and Kokoro, set -`AUDIOFLOW_LLM_ENGINE=http` and `AUDIOFLOW_CHAT_ENDPOINT` for -`examples/local.exs` or `examples/media.exs`. `AUDIOFLOW_LLM` becomes the server's -model ID. This mode does not load a native language model. The benchmark -metadata uses `mode=hybrid_inference` and records the language engine as HTTP. -Optional `AUDIOFLOW_LLM_SOURCE` and `AUDIOFLOW_LLM_REVISION` identify the deployed -weights. The metadata does not contain the API key or endpoint query string. - -The real HTTP check compares streamed output through a session with an -independent nonstreamed request to the same deterministic server: - -```sh -AUDIOFLOW_HTTP_MODEL_TESTS=1 \ - AUDIOFLOW_CHAT_ENDPOINT=http://127.0.0.1:18082/v1/chat/completions \ - AUDIOFLOW_LLM=audioflow-qwen mix test test/chat_http_model_test.exs -``` - -This check uses controlled STT and TTS adapters. It validates transport output. -Model answer accuracy requires a separate evaluation. The checked local server -was llama.cpp 0.8.0, build 11960 (`8642541b2`), with zero GPU layers. It used -`Qwen/Qwen3-0.6B-GGUF`, revision -`23749fefcc72300e3a2ad315e1317431b06b590a`, file `Qwen3-0.6B-Q8_0.gguf`. -The file SHA-256 was -`9465e63a22add5354d9bb4b99e90117043c7124007664907259bd16d043bb031`. -The server used four threads, two slots, a 4,096-token context, and reasoning -disabled. Hybrid voice inference also passed with real Whisper and Kokoro. -No hosted cloud account was used for these checks. - -## Images and embeddings - -`AudioFlow.Models.text_embedding/2` builds a shared text embedding serving. Its -defaults use attention-masked mean pooling and L2 normalization. These defaults -match `sentence-transformers/all-MiniLM-L6-v2`, a BERT model with 384 output -values. Other models can need different pooling, output attributes, or input -prefixes. Set these through the serving options and the adapter input mapper. -The library does not infer a retrieval task or add a query prefix. - -`AudioFlow.Models.clip_image_embedding/2` loads the CLIP vision model and its -trained projection. It emits normalized vectors in the joint CLIP text-image -space. The tested CLIP model emits 512 values. BERT and CLIP vectors use -different spaces; do not compare them directly. -`AudioFlow.Models.image_captioning/2` builds a caption serving for supported -models such as BLIP. It generates a complete caption before returning it. - -All three builders accept `:load_options` for revisions and caches, and -`:model_options` for parameter type and backend. Captioning also accepts -`:generation_options`. Set `:compile` to bound input shapes. Text embedding -sequence lengths can truncate long input; set the length for the chosen model -and workload. Load the models once and use `Models.child_spec/3` to start their -shared servings. The same `NxAdapter`, `Worker`, and `Router` interfaces apply -to these models. - -Use `NxAdapter.embedding/1` to emit one portable list of numbers, or supply an -output mapper that retains the tensor. This allows applications to keep vectors -on the device. `NxAdapter.captions/1` emits caption strings. The examples pin -the model revisions and use EXLA parameters: - -```sh -AUDIOFLOW_ML=1 mix run examples/multimodal.exs embed "Two cats on a couch." -AUDIOFLOW_ML=1 mix run examples/multimodal.exs image-embedding image.png -AUDIOFLOW_ML=1 mix run examples/multimodal.exs describe image.png -``` - -Image modes need the FFmpeg and ffprobe CLIs. They decode the first frame to -RGB. The models run through Bumblebee, Nx, and EXLA. - -A session with a `:vision` adapter can accept an `AudioFlow.Image`: - -```elixir -vision = {AudioFlow.NxAdapter, - serving: MyApp.CaptionModel, - input: &AudioFlow.NxAdapter.image_input/1, - output: &AudioFlow.NxAdapter.captions/1} -{:ok, session} = AudioFlow.start_session( - Keyword.put(session_options, :vision, vision)) -{:ok, turn} = AudioFlow.submit(session, - %AudioFlow.Image{data: rgb_bytes, width: width, height: height}) -``` - -Image data must use packed RGB, with three unsigned 8-bit channels per pixel -in row order. Its byte count must equal `width * height * 3`. The session rejects -invalid images and images above `:max_image_bytes` (6,291,456 by default). Image -turns emit `{:description, text}` events. All description chunks form one prompt -for the LLM, then the reply follows the normal TTS and playback path. The -terminal metrics include `first_description_us`. Image-only sessions can omit -`:stt`. Submission without the required input adapter returns -`{:error, {:unsupported_input, stage}}`. - -Audio and image turns share one active-turn limit. Both support cancellation, -deadlines, and output limits. An image can include an integer `:pts` in -nanoseconds. The session adds this time to the description sent to the LLM and -saved in history. The `:description` event keeps the original model text. - -## Video input - -With `AUDIOFLOW_MEDIA=1`, `AudioFlow.Video.frames/2` reads H.264 video from a -local MP4 file. It also accepts an application-supplied Membrane raw-video -source, such as a camera source. It converts selected frames to packed RGB: - -```elixir -for frame <- AudioFlow.Video.frames("input.mp4", - interval_ms: 1_000, width: 384, height: 384) do - {:ok, turn} = AudioFlow.submit(session, frame) - # Wait for this turn to finish before you read the next frame. -end -``` - -The interval is the minimum time between selected frames. The reader uses -presentation timestamps, rather than frame counts. By default, time starts at -the first decoded frame. Set `normalize_timestamps?: false` to keep decoder -timestamps, including MP4 composition offsets. These times do not account for -MP4 edit lists or provide audio and video synchronization. - -The default track is the H.264 track with the lowest ID. Use `:track_id` to -select another H.264 track. Other tracks, including audio, are discarded. Files -with metadata at either end are supported. Unsupported tracks and decode errors -produce errors; they do not end the calling process when you use the manual API. - -The reader allows one pending read and uses small RGB queues. The default frame -limit is 6,291,456 bytes. Set `:max_frame_bytes` to change it. Optional `:width` -and `:height` values must be positive even integers. Scaling keeps the aspect -ratio and adds padding. The frame limit applies after scaling. Decoder working -memory and MP4 indexes are separate from this limit. Decoding follows demand; -the reader does not pace frames against a clock. - -`frames/2` closes the reader at EOF, on an early halt, or after a consumer error. -It raises on a read error. Its `:timeout_ms` option sets the limit for each read -(30 seconds by default). For manual control, use -`Video.start_link(location: path)` or `Video.start_link(source: source)`, then -`Video.next_frame(reader, timeout_ms)` and `Video.close(reader)`. A reader also -stops when its owner exits. - -The video example uses shared BLIP, Qwen3, and Kokoro services. It waits for one -frame turn before it reads another. History supplies the previous description -for comparison. It saves descriptions, replies, timings, and speech PCM: - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 mix run examples/video.exs input.mp4 output -``` - -`AUDIOFLOW_VIDEO_INTERVAL_MS` sets the interval (1,000 by default), and -`AUDIOFLOW_VIDEO_FRAMES` sets the frame limit (16 by default). This is sampled -frame analysis. It does not track objects or motion between frames. A two-scene -model check produced correct individual descriptions, but Qwen3-0.6B added an -unsupported action during comparison. Model output needs assessment for the -intended use. - -## Model routing and distributed workers - -`AudioFlow.Worker` runs an adapter with a fixed limit on active requests. It -rejects requests above that limit. It does not keep a waiting queue. Start -shared model services first, then start their workers under a supervisor: - -```elixir -llm_adapter = {AudioFlow.NxAdapter, - serving: AudioFlow.LLM, - input: &AudioFlow.Prompt.qwen3/1, - output: &AudioFlow.NxAdapter.sentences/1} - -children = [ - {AudioFlow.Worker, - name: MyApp.LocalLLM, adapter: llm_adapter, - max_concurrency: 4, timeout_ms: 120_000}, - {AudioFlow.Router, - name: MyApp.Routes, - routes: %{voice: [MyApp.LocalLLM, {MyApp.RemoteLLM, :"ml@worker"}]}} -] -{:ok, supervisor} = Supervisor.start_link(children, strategy: :one_for_one) - -options = Keyword.put(session_options, :llm, - {AudioFlow.Router, router: MyApp.Routes, route: :voice, timeout_ms: 120_000}) -{:ok, session} = AudioFlow.start_session(options) -``` - -The remote node must run AudioFlow and a worker named `MyApp.RemoteLLM`. Its -adapter uses model services on that node. Erlang distribution must already -connect the nodes. Use compatible code on trusted nodes. Inputs and outputs -cross the connection. Model weights remain in their shared services. -Only connected remote nodes are eligible. Reconnect a node before routing to -it again. If a node fails while admission is in progress, the request ends with -an error. Its admission status is unknown, so the router does not retry it. -All engines use the same adapter interface. A worker can use `NxAdapter` or an -application adapter for ONNX, llama.cpp, or a cloud API. Cloud clients must set -their own connection and request timeouts. - -Routes rotate the starting worker for each request. A busy or unavailable worker -is skipped. An error after admission ends the request. The router does not -repeat partial speech on another worker. If all workers reject the request, the -caller receives `{:error, {:no_worker_available, route, reasons}}`. - -Change a route while sessions remain open: - -```elixir -AudioFlow.Router.put_route(MyApp.Routes, :voice, [{MyApp.RemoteLLM, :"ml@worker"}]) -``` - -The change applies to subsequent adapter calls. Active requests keep their -worker. An empty worker list disables the route. `:route` can also be a function -that selects a route key from the adapter input. For example, a text-length or -language policy can select a model without changing the session pipeline. +## Documentation -Each output chunk waits for its caller's acknowledgement. Caller exit and -session cancellation stop the worker task, including on a remote node. Worker -exit or node loss ends the active request with an error. Each worker has a -request deadline, and the router has a deadline for the complete call. Cleanup -can take up to one additional second. A hardware batch already submitted to a -shared serving can still run to completion. Set worker limits and deadlines to -match measured model capacity and the session timeout. - -Run the local routing example without model downloads: - -```sh -mix run examples/routing.exs -``` - -The distributed checks start a second local Erlang node. They check remote -output, cancellation, and node loss through the worker protocol: - -```sh -AUDIOFLOW_DISTRIBUTED_TESTS=1 elixir --sname audioflow_test -S mix test -``` - -These checks use controlled adapters. They do not measure network latency or -model capacity across machines. - -## Membrane input - -```sh -AUDIOFLOW_MEDIA=1 mix deps.get -AUDIOFLOW_MEDIA=1 mix compile --warnings-as-errors -``` - -`AudioFlow.PCMSink` accepts mono `:s16le` raw audio. With its `vad` option, it -accepts audio chunks and submits utterances after endpoint detection: - -```elixir -%AudioFlow.PCMSink{ - session: session, - vad: {AudioFlow.Silero, serving: AudioFlow.VAD}, - endpoint_options: [min_speech_ms: 96, min_silence_ms: 320] -} -``` - -Start `AudioFlow.VAD` once with `AudioFlow.Silero.serving/2` and -`AudioFlow.Models.child_spec/3`. The Silero source can be a local ONNX file or -`{:hf, "onnx-community/silero-vad", "onnx/model.onnx"}`. Pin the model with -`load_options: [revision: "e71cae966052b992a7eca6b17738916ce0eca4ec"]`. -Each sink keeps its own recurrent state and audio context. Only the weights are -shared. Input must be 16 kHz. Put a resampler before the sink for other rates. - -After speech confirmation, the sink cancels the active reply and sends -`{:audio_flow_speech_started, session}` to its parent. A configured output -transport is flushed by the session. Otherwise, the parent must flush playback. -After endpoint detection, it sends `{:audio_flow_input, result}`. -The parent must handle busy input. At end of stream, the sink flushes the final -utterance. Without `vad`, each input buffer must be one complete utterance. - -`AudioFlow.VoiceInput` supplies the same frame processing without Membrane. It -retains pre-roll, confirms speech, uses separate start and stop thresholds, and -limits utterance length. It pads a partial final frame with silence. Endpoint -options are documented in the module. Try it with a mono 16 kHz PCM recording: - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_PCM=recording.s16le mix run examples/vad.exs -``` - -`AudioFlow.Input.attach/3` adds FFmpeg resampling and the session sink to a -Membrane source chain. It requires a voice detector tuple. It converts supported -mono or stereo input to mono s16le at the selected rate (16 kHz by default). -`AudioFlow.InputPipeline` supplies this chain as a complete pipeline. The source -can be `AudioFlow.PCMFileSource` or `Membrane.PortAudio.Source`. The file source -reads bounded chunks and preserves sample timestamps. It rejects incomplete -PCM frames. Set the source format to match the actual file or device. - -Echo cancellation is not included. Speaker audio can therefore trigger the detector. - -## Output transport - -Attach a playback process to a session: - -```elixir -sink = %Membrane.PortAudio.Sink{latency: :low, - ringbuffer_size: 2048, portaudio_buffer_size: 256} -{:ok, playback} = AudioFlow.Playback.start_link(sink: sink) -{:ok, session} = AudioFlow.start_session( - Keyword.put(session_options, :output, {AudioFlow.Playback, playback})) -``` +The website and documentation are at . +Their source is in [site](site/README.md). -The sink is application-selected. A sound device opens only when PCM arrives. -Each turn gets its own output pipeline. The queue is limited by `:max_bytes` -(96,000 by default). One further chunk can wait for capacity. Each chunk must -fit within that limit. A full queue blocks the turn worker, while cancellation -remains available in the session. Membrane input prefetch is limited to one -buffer; the device has its own ring buffer. PCM chunks must keep the same sample -rate throughout a turn. +Start here: -Normal completion drains queued output. PortAudio output is padded to a whole -device block and has a final ring-buffer drain interval before close. The -playback process sends `:drained` after pipeline cleanup. Inference `:done` can -arrive before playback finishes. Cancellation drops the application queue and -closes the old pipeline before it acknowledges. Old turn references are rejected. -A completed inference turn can still be cancelled while its audio is queued. -Session exit also closes its output pipeline. +- [Introduction](https://flowcopilot.github.io/audioflow/docs/): what AudioFlow is, and how its parts fit together. +- [Quickstart](https://flowcopilot.github.io/audioflow/docs/quickstart/): running the tests, the demo session, and real models. +- [Chat example](https://flowcopilot.github.io/audioflow/docs/chat-example/): a LiveView voice and text chat. -The observer receives `{AudioFlow.Playback, pid, turn_key, event}`. Events include -`:drained`, `{:first_buffer, %{elapsed_us: us}}`, `{:flushed, %{control_us: us}}`, -back pressure, and failure. First-buffer time ends at the Membrane source; -flush time ends after pipeline cleanup. Neither is a microphone-to-speaker -measurement. A device close can drain a short native buffer. Acoustic -interruption latency still requires a loopback recording and a common clock. +Guides: -`AudioFlow.Output` defines the transport interface for other output engines. -`push/3` runs in the turn worker, so it can apply back pressure. `flush/2` must -release blocked producers and stop old output. The playback process belongs to -one conversation; use a separate process for each session. - -`examples/models.exs` starts shared models. `examples/local.exs` adds a single -utterance for inference benchmarks. `examples/media.exs` connects a PCM file, -resampling, Silero, the session, and PortAudio output. It plays sound when run: - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 AUDIOFLOW_PCM=recording.s16le \ - AUDIOFLOW_LLM=Qwen/Qwen3-0.6B mix run examples/media.exs -``` - -Set `AUDIOFLOW_INPUT_RATE` and `AUDIOFLOW_INPUT_CHANNELS` for other input formats. -The file example reads at processing speed. Use one utterance for this check. -A live PortAudio source follows the device clock. -The media tests use a controlled sink. They verify back pressure, drain, -cancellation, pipeline failure, and cleanup without opening a sound device. - -## WebSocket transport - -`AudioFlow.WebSocket` connects one browser or network client to one session -over a WebSocket. It sends raw PCM and JSON events. It is a `WebSock` handler, -so it runs in Bandit or Cowboy through `WebSockAdapter`. In a Plug or Phoenix -route: - -```elixir -conn -|> WebSockAdapter.upgrade(AudioFlow.WebSocket, - [session: session_options, vad: {MyDetector, []}], - max_frame_size: 1_000_000) -|> Plug.Conn.halt() -``` - -Each connection starts its own session and owns it. When the connection -closes, the session stops. The client never becomes the session owner. The -connection is also the session's `AudioFlow.Output` transport, so it replaces -an `:output` option. The turn worker waits until the connection accepts each -output chunk. Your application must add `websock_adapter` and a server, such -as `bandit`. AudioFlow uses them only for development and tests. - -The client sends binary frames of mono s16le PCM at the input rate (16 kHz by -default). Each frame must contain whole samples, and it must not be larger -than `:max_chunk_bytes` (64,000). Text frames are JSON commands: - -| Command | Effect | -| --- | --- | -| `{"type": "text", "text": "Hi"}` | Submit a typed message. | -| `{"type": "commit"}` | Submit the collected PCM. With a detector, end the current utterance. | -| `{"type": "cancel"}` | Cancel the active reply. | -| `{"type": "clear_history"}` | Clear saved history while idle. | - -Without `:vad`, PCM collects until `commit`. The collected input must not be -larger than `:max_buffer_bytes` (960,000). With `:vad`, PCM goes through -`AudioFlow.VoiceInput`, and `:endpoint_options` sets its endpoint detection. -Confirmed speech cancels the active reply, and an endpoint submits the -utterance. The input rate must then be the detector rate. - -The server sends binary frames of mono s16le reply PCM for the current turn. -An `output_format` event with `sample_rate` comes before the first binary -frame, and before each change of rate. JSON events have a `type` field: -`ready`, `speech_started`, `turn_started`, `transcript`, `description`, `text`, -`done`, `cancelled`, `flush`, `history_cleared`, and `error`. Turn events -include a connection-local integer `turn`. When the client receives `flush`, -it must discard its queued playback. After a cancellation, the connection -drops output from the old turn. An invalid client message gets an `error` -event, and the connection stays open. - -The browser example uses the Demo adapters. Hold the button to speak, or type -a message: - -```sh -mix run --no-halt examples/websocket.exs -``` - -Then open . The Demo replies are silent PCM. The -transport does not include echo cancellation, encoding, or packet loss -recovery. Use the browser's echo cancellation for speaker playback. - -## Telemetry - -Sessions emit `:telemetry` events. `[:audio_flow, :session, ...]` and -`[:audio_flow, :turn, ...]` have start and stop events. Each adapter call is a -`[:audio_flow, :stage, ...]` span with `:stage` set to `:stt`, `:vision`, -`:llm`, or `:tts`, or the node type in a graph session. A turn stop event has -the turn `:status` (`:done`, `:cancelled`, or `:error`) and the terminal -event metrics. See `AudioFlow.Telemetry` for every event. Turn and stage -events carry `:telemetry_span_context` for an `opentelemetry_telemetry` bridge, -and `opentelemetry_process_propagator` nests stage spans under their turn. -The [telemetry guide](site/src/content/docs/docs/guides/telemetry.md) has an -example handler. - -## Model validation - -The regular tests need no model downloads. With the model flags, tests also -check shared EXLA calls, PCM conversion, and Membrane interruption: - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 mix test -``` - -Model tests are opt-in. They download pinned Silero, VITS, and Kokoro models, unless the -files are already cached. Set `AUDIOFLOW_SILERO_MODEL` to use a local Silero file. - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 AUDIOFLOW_MODEL_TESTS=1 mix test -``` - -Silero probabilities are compared with independent ONNX Runtime values in -`test/fixtures/silero_reference.json`, for two concurrent streams. The reference -generator is `scripts/silero_reference.py`. The VITS test uses the independent -PyTorch duration recorded in the pinned Transmuter speech guide. It also checks -PCM size and non-silent output. These tests do not measure speech quality. -Kokoro checks compare waveform lengths against ONNX Runtime for two voices, -two speeds, and text input. The reference generator is -`scripts/kokoro_reference.py`. They also check finite samples, PCM output, -and use through a session. These model tests require espeak-ng. - -The multimodal model checks compare BERT and projected CLIP vectors against -independent PyTorch outputs. They also check a real BLIP caption through an -image session. The text model has two concurrent callers on one shared serving. -The pinned cat image comes from the Transmuter test fixtures. FFmpeg RGB output -must have the same SHA-256 as the reference image bytes. The reference generator -is `scripts/multimodal_reference.py`. CLIP comparison allows small differences -between image resize implementations; BLIP checks the complete reference text. -These checks need FFmpeg, but no microphone or sound device. - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_MODEL_TESTS=1 mix test test/multimodal_model_test.exs -``` - -The image session check uses real BLIP with controlled LLM and TTS adapters. -It checks delivery through the session, rather than spoken audio quality. - -The full native media test is a separate opt-in check. It needs the FFmpeg CLI -and espeak-ng. It uses the public LibriSpeech sample in the pinned Transmuter -repository, real Silero, Whisper, Qwen3, and Kokoro models, and a Membrane test -sink. It checks transcript content, reply text, non-silent PCM, and complete -delivery through the output pipeline. It does not open a sound device. - -```sh -AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 AUDIOFLOW_PIPELINE_TESTS=1 \ - mix test test/native_pipeline_test.exs -``` - -Set `AUDIOFLOW_PIPELINE_ARTIFACT_DIR` to retain the transcript, reply, PCM, and -timings in a selected directory. Model loading and compilation can take time. - -## Benchmarks - -The benchmark writes one CSV row per attempt. It records time to first transcript, -first text, first audio, and turn completion in microseconds. These times start -when the session accepts the utterance. They include task scheduling, serving -queue time, and inference. They exclude microphone capture, endpoint detection, -and playback device delay. Blank fields mean that the event did not occur. -Errors remain in the CSV so that failed runs cannot improve the latency result. -A completed turn with no audio is an error for this voice benchmark. Rejected -input, session exit, cancellation, and benchmark deadlines also produce rows. -Error rows use elapsed attempt time where available. Unobserved timings remain -blank. - -`first_text_us` measures the first sentence-sized text chunk from the language -model adapter. - -For real inference, supply a script that starts shared models and returns -`{session_options, audio}` or `{session_options, audio, metadata}`: - -```sh -AUDIOFLOW_ML=1 mix audio_flow.bench --config examples/local.exs \ - --runs 100 --warmup 4 --concurrency 4 --output benchmarks/native.csv -``` - -`--warmup` rows use `phase=warmup`; other rows use `phase=measured`. Both phases -run at the selected concurrency. Use measured rows for reported latency, and -count all measured failures in the error rate. `--timeout-ms` sets the attempt -deadline. Its default is the session timeout plus five seconds. Cleanup follows -the deadline. A final worker limit also prevents a stalled runner from waiting -without an end. - -`--output` writes clean CSV and a `.meta.json` sidecar. Model logs remain on the -console. The sidecar records input SHA-256, model revisions from the config, -warmup settings, runtime and library versions, and loaded AudioFlow module -fingerprints. `setup_us` covers config evaluation and model setup, separately -from turn timings. Without `--output`, stdout also contains any model logs. - -The local example requires `AUDIOFLOW_PCM` and `AUDIOFLOW_LLM`. It uses local -Kokoro by default. Set `AUDIOFLOW_VOICE` to select its voice, or -`AUDIOFLOW_TTS=vits` to use VITS. Set `AUDIOFLOW_TTS_CONFIG` for another adapter. -Repeat with concurrency 1, 2, 4, and higher. -The example pins Whisper tiny, Qwen3-0.6B, and the selected TTS model. Set -`AUDIOFLOW_LLM_REVISION` to pin another language model and `AUDIOFLOW_HARDWARE` -to add a hardware label to its metadata. The metadata leaves unpinned revisions -empty. The default example uses greedy decoding with at most 64 new tokens, -batch size 1, and a 5 ms batch timeout. -Record hardware, model revisions, precision, batch settings, and warmup count. -Keep cold runs separate. Use the same recordings, endpoint rules, and models for -a Pipecat comparison. Report p50/p95 latency and error rate. Set the latency and -error limits before selecting a maximum session count. The inference-only run -below does not include a Pipecat comparison or establish real-time performance. - -The saved [CPU run data](validation/native-cpu.csv), -[metadata](validation/native-cpu.csv.meta.json), and -[chart](validation/native-cpu.html) contain one warmup turn and three measured -turns. They use one recording and one active session. This small check confirms -that the inference path runs. It does not establish session capacity. Capture, -VAD, transport, and playback device delays are excluded from these measurements. - -The [common-engine comparison guide](scripts/COMPARISON.md) provides a full media -runner for AudioFlow and Pipecat. Both use the same shared Silero, Whisper, -Qwen3, and Kokoro services. The run includes Membrane file input, resampling, -endpoint detection, model queues, and software output delivery. Pipecat calls -the model stages through private local pipes. Its result includes that transfer -cost. This comparison does not compare Nx against Python inference engines. - -```sh -uv run scripts/compare_pipecat.py FIRST.s16le SECOND.s16le \ - --output benchmarks/comparison.json --concurrency 1 2 4 8 \ - --warmup 8 --runs 16 --interrupt-runs 4 -python3 scripts/comparison_report.py \ - benchmarks/comparison.json benchmarks/comparison.html -``` +- [Sessions](https://flowcopilot.github.io/audioflow/docs/guides/sessions/): turns, events, cancellation, and limits for one conversation. +- [Transcription](https://flowcopilot.github.io/audioflow/docs/guides/transcription/): speech-to-text adapters, transcription sessions, and long recordings. +- [Conversation history](https://flowcopilot.github.io/audioflow/docs/guides/history/): keeping earlier turns in the prompt, with limits. +- [Local models](https://flowcopilot.github.io/audioflow/docs/guides/local-models/): Whisper, Qwen3, Kokoro, and VITS as shared Nx services. +- [HTTP language models](https://flowcopilot.github.io/audioflow/docs/guides/http-inference/): streaming replies from llama.cpp or any ReqLLM provider. +- [Images and embeddings](https://flowcopilot.github.io/audioflow/docs/guides/images/): CLIP and BERT embeddings, BLIP captions, and image turns. +- [Video input](https://flowcopilot.github.io/audioflow/docs/guides/video/): reading H.264 frames from MP4 files or a camera source. +- [Routing and workers](https://flowcopilot.github.io/audioflow/docs/guides/routing/): bounded workers, model routes, and inference on other nodes. +- [Membrane input](https://flowcopilot.github.io/audioflow/docs/guides/membrane-input/): voice detection, endpointing, and resampling for live audio. +- [Output transport](https://flowcopilot.github.io/audioflow/docs/guides/output/): playing reply audio, and flushing it when the user interrupts. +- [WebSocket transport](https://flowcopilot.github.io/audioflow/docs/guides/websocket/): streaming PCM and events between a browser and a session. +- [Telemetry](https://flowcopilot.github.io/audioflow/docs/guides/telemetry/): session, turn, and stage spans, with an OpenTelemetry bridge. -The runner retains failed attempts, input hashes, detected-utterance hashes, -output PCM hashes, model revisions, and source fingerprints. It separates warmup, -measured turns, and serial interruption checks. Choose `--max-first-output-ms` -before the run. The default rule allows no measured errors and requires p95 -first output within 10 seconds. The report checks input agreement and all lower -tested levels before it assigns a highest passing tested concurrency. This -threshold is a test rule; it does not establish conversational quality. +Features: -The saved [comparison data](validation/comparison.json) and -[report](validation/comparison.html) contain two recordings, 128 measured turns, -64 warmup turns, and 32 serial interruption checks. Both frameworks passed the -10-second rule at four simultaneous turns and exceeded it at eight. All measured -turns completed without errors. Detected input and output PCM hashes agreed. -Transcripts and replies matched. These results apply to the listed models, CPU, software sinks, -and closed workload. They do not establish production capacity. +- [Remote speech providers](https://flowcopilot.github.io/audioflow/docs/features/providers/): Deepgram, Cartesia, ElevenLabs, Fish Audio, OpenAI Realtime, and Gemini Live adapters. +- [Network transports](https://flowcopilot.github.io/audioflow/docs/features/transports/): raw PCM WebSocket, Twilio and Telnyx telephony, and the Pipecat RTVI client. +- [Input processing](https://flowcopilot.github.io/audioflow/docs/features/input-processing/): server-side denoising, echo cancellation, and Smart Turn endpoints. +- [WebRTC and avatars](https://flowcopilot.github.io/audioflow/docs/features/webrtc-avatars/): optional encoded WebRTC media and LiveAvatar publishing. +- [Conversations and retrieval](https://flowcopilot.github.io/audioflow/docs/features/conversation-and-retrieval/): conversation states, Jido handoffs, and pgvector retrieval graphs. +- [Conversation evaluations](https://flowcopilot.github.io/audioflow/docs/features/conversation-evaluations/): scripted regression tests over real session turns. +- [Interruption](https://flowcopilot.github.io/audioflow/docs/features/interruption/): playback acknowledgements, provisional interruption, and heard reply history. +- [Speech languages](https://flowcopilot.github.io/audioflow/docs/features/model-languages/): language choices for native Whisper and MMS VITS nodes. +- [Recording and privacy](https://flowcopilot.github.io/audioflow/docs/features/recording-and-privacy/): opt-in recordings and transcript redaction. -## Deployment checks and further measurements +Validation: -- Add echo cancellation for microphone use. -- Measure interruption through a real playback device with loopback audio. -- Use sustained loads, more speakers, noise, and real-time input pacing. -- Compare independent Pipecat model engines with equivalent precision and decoding. +- [Model checks](https://flowcopilot.github.io/audioflow/docs/validation/model-checks/): how model output is compared with independent references. +- [Benchmarks](https://flowcopilot.github.io/audioflow/docs/validation/benchmarks/): time to first transcript, text, and audio per turn. +- [Pipecat comparison](https://flowcopilot.github.io/audioflow/docs/validation/pipecat-comparison/): AudioFlow and Pipecat over the same model services. -## API references +## Examples and tools -- [Bumblebee audio](https://bumblebee.hexdocs.pm/Bumblebee.Audio.html) -- [Chat completion stream protocol](https://developers.openai.com/api/reference/resources/chat/subresources/completions/streaming-events) -- [llama.cpp server](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md) -- [Finch streaming](https://hexdocs.pm/finch/Finch.html#stream_while/5) -- [Bumblebee text generation](https://bumblebee.hexdocs.pm/Bumblebee.Text.html) -- [Nx.Serving](https://nx.hexdocs.pm/Nx.Serving.html) -- [Membrane sinks](https://membrane-core.hexdocs.pm/Membrane.Sink.html) -- [Transmuter package](https://hex.pm/packages/transmuter) -- [Pinned Transmuter speech guide](https://github.com/georgeguimaraes/transmuter/blob/231028d9ff6f53bd58fa15d9f24d632258369805/guides/speech_and_audio.md) -- [Silero frame and context protocol](https://github.com/snakers4/silero-vad/blob/master/src/silero_vad/utils_vad.py) -- [Kokoro voice style selection](https://github.com/hexgrad/kokoro/blob/main/kokoro/pipeline.py) -- [Misaki phoneme mapping](https://github.com/hexgrad/misaki/blob/main/misaki/espeak.py) -- [FFmpeg resampler](https://membrane-ffmpeg-swresample-plugin.hexdocs.pm/Membrane.FFmpeg.SWResample.Converter.html) -- [PortAudio plugin](https://hexdocs.pm/membrane_portaudio_plugin/) -- [telemetry span](https://hexdocs.pm/telemetry/telemetry.html#span/3) -- [opentelemetry_telemetry](https://hexdocs.pm/opentelemetry_telemetry/) -- [opentelemetry_process_propagator](https://hexdocs.pm/opentelemetry_process_propagator/) +- [examples/](examples/): runnable scripts. Most need `AUDIOFLOW_ML=1` or `AUDIOFLOW_MEDIA=1`. +- [examples/chat](examples/chat/README.md): browser voice and text chat, with always-on OpenAI Realtime and Moshi modes. +- [examples/network](examples/network/README.md): optional WebRTC audio and video output, and the PCM Session bridge. +- [examples/avatar](examples/avatar/README.md): standalone viewer for LiveAvatar publications. It subscribes only when configured with an account. +- [ui](ui/README.md): local dashboard with a canvas editor for node graphs, and an MCP endpoint for coding agents. A session runs an `AudioFlow.Graph` with the `:graph` option. +- [scripts/COMPARISON.md](scripts/COMPARISON.md): the method for the AudioFlow and Pipecat comparison. +- [validation](validation/): saved reports and data, including the [native CPU run](validation/native-cpu.html), the [conversation checks](validation/conversation-smoke.json), and the [Pipecat comparison](validation/comparison.html). ## License diff --git a/docs/guides/conversation-and-retrieval.md b/docs/guides/conversation-and-retrieval.md deleted file mode 100644 index bbf90b6..0000000 --- a/docs/guides/conversation-and-retrieval.md +++ /dev/null @@ -1,136 +0,0 @@ -# Conversation states and retrieval - -## Conversation and handoff - -`AudioFlow.Graph.Conversation` orchestrates independently validated graph DAGs. -Conversation transitions can cycle; node edges still cannot. The same Session PID, -owner, output transport and saved user/assistant history survive a handoff. Each -state graph supplies its own prompt and tool profile. A handoff requested during a -turn is staged, then committed after successful output completion. Cancelled, -failed and timed-out turns discard staged transitions. The current turn finishes -using its original agent; the next turn uses the destination agent. This is not -mid-generation interruption or transfer of the provider's internal tool messages. - -```elixir -alias AudioFlow.Graph.Conversation - -# triage_graph and billing_graph are ordinary JSON-compatible AudioFlow graphs. -# Each must enable settings.history and have exactly one history-capable node. -flow = Conversation.new( - %{"triage" => triage_graph, "billing" => billing_graph}, - "triage", - %{{"triage", {:intent, "billing"}} => "billing", - {"billing", {:tool_result, "resolved", :ok}} => "triage"} -) -{:ok, session} = Conversation.start_session(flow, owner: self()) -AudioFlow.submit(session, %AudioFlow.Text{data: "Hello"}) -# After your classifier selects the intent: -Conversation.event(session, {:intent, "billing"}) -# After your application tool completes successfully: -Conversation.event(session, {:tool_result, "resolved", :ok}) -Conversation.state(session) -``` - -Events match exact terms; no LLM classifier or intent inference is fabricated. -An unlisted event returns `{:error, :invalid_transition}`. Application callers can -use `Conversation.tool/3` for explicit tool-result transitions. For an LLM-selected -handoff, register the existing Jido-compatible action in trusted server config: - -```elixir -config :audio_flow, :chat_tool_profiles, %{ - "triage" => [AudioFlow.Graph.Handoff], - "billing" => [MyApp.ResolveInvoice] -} -``` - -Set the triage `llm.req_llm` node's `tools_profile` option to `"triage"`, its -`system_prompt` prompt to describe the billing intent, and the billing node's profile to -`"billing"`. The graph runner supplies `%{session: pid, turn: ref}` as tool context. -`AudioFlow.Graph.Handoff` accepts an `intent` string and stages `{:intent, intent}`. -It checks the turn reference so late tool results cannot affect another turn. -Your Jido action can likewise call -`GenServer.call(context.session, {:conversation_event, context.turn, event})`. -The transition map allowlists destinations; model output cannot select arbitrary -graphs or execute arbitrary modules. Do not expose trusted profile configuration -to untrusted clients. - -Jido's installed `Jido.Agent.Strategy.FSM` is an **execution-phase** FSM, including -a required `processing` phase. Conversation states deliberately live above that -strategy, rather than treating an execution phase as an agent persona. Existing -Jido action execution through `AudioFlow.Tool` remains unchanged. - -State plans compile once. Change a state's `system_prompt` and `tools_profile` before -constructing the conversation. Graph settings other than history do not override -session limits per state; set timeout and event limits on `start_session/2`. -The UI lists retrieval nodes, but conversation authoring/running currently uses -this Elixir API; the UI's single-graph run API is unchanged. - -## pgvector retrieval - -`text.embedding -> rag.retrieve` reuses the existing ML embedding node. The latter -has a vector input and text output (a JSON array with `id`, `content`, `metadata`, -`distance`). Add both `input.text -> llm` and `rag.retrieve -> llm` edges to join -the original question and context at the LLM; instruct its system prompt to treat -retrieved documents as untrusted data, cite document IDs, and admit absent context. -No matches emits `[]`; database errors fail the turn, never synthetic documents. -The ML profile is needed for local embeddings; retrieval itself is core-only. - -Provision the extension and schema separately (not automatically at app startup): - -```sql -CREATE EXTENSION IF NOT EXISTS vector; -CREATE TABLE audio_flow_documents ( - id text PRIMARY KEY, - collection text NOT NULL, - content text NOT NULL, - metadata jsonb NOT NULL DEFAULT '{}', - embedding vector(384) NOT NULL -); -CREATE INDEX ON audio_flow_documents USING hnsw (embedding vector_cosine_ops); -CREATE INDEX ON audio_flow_documents (collection); -``` - -Start a supervised Postgrex connection in your host application, then configure: - -```elixir -config :audio_flow, :retrieval_profiles, %{ - "support" => [ - dimensions: 384, - max_distance: 0.6, - backend: {AudioFlow.RAG.Pgvector, - [connection: MyApp.VectorDB, collection: "support", timeout_ms: 5_000]} - ] -} -``` - -Use node options `{"profile":"support","limit":5,"max_bytes":32768}`. -Profiles are allowlisted server configuration, never database credentials or -module names supplied by graph JSON. Missing profiles fail compilation rather -than silently falling back. Limits allow 1–100 documents; zero vectors and wrong -dimensions fail before querying; oversized context returns an explicit error. -Cosine distance ranges from 0 to 2. SQL binds vector text, collection, limit and -threshold as separate parameters. The fixed table/schema avoids identifier -interpolation and requires no custom Postgrex vector encoder. Results are ordered -by ascending cosine distance. Approximate HNSW filtering may return fewer matches; -tune pgvector's index/search settings for your dataset. - -Ingestion is application-owned: chunk documents, embed each chunk with the **same -model, normalization, and dimensionality** used for queries, and insert content, -source metadata, collection and vector using parameterized SQL. Equal dimensions -do not establish model compatibility. This change does not download a corpus, -perform ingestion, claim retrieval quality, or infer missing embeddings. - -Tests use deterministic backend and SQL-driver fakes. To run the real database -regression, supply a disposable PostgreSQL database with pgvector installed and -permission to create the extension and temporary tables: - -```sh -AUDIOFLOW_PGVECTOR_URL=postgresql://localhost/audioflow_test mix test test/rag_pgvector_test.exs -``` - -That test creates only a temporary documents table and checks actual cosine -ordering, collection isolation, thresholds and empty results. - -Protocol references: [pgvector](https://github.com/pgvector/pgvector), -[Postgrex parameterized query API](https://hexdocs.pm/postgrex/Postgrex.html#query/4), -[Jido FSM](https://hexdocs.pm/jido/Jido.Agent.Strategy.FSM.html). diff --git a/docs/guides/conversation-evaluations.md b/docs/guides/conversation-evaluations.md deleted file mode 100644 index 3e3fac0..0000000 --- a/docs/guides/conversation-evaluations.md +++ /dev/null @@ -1,52 +0,0 @@ -# Scripted conversation regression tests - -`AudioFlow.Evaluation.Conversation` submits real text turns to a session owned -by the test process. Enable history when testing follow-up behavior. It waits -for completion before submitting the next turn and concatenates streamed reply -chunks. Replies can match an exact string, regex, or one-argument predicate. - -```elixir -alias AudioFlow.Evaluation.Conversation - -{tools, observer} = Conversation.observe_tools([ - %{name: "weather", run: fn %{"city" => city} -> {:ok, "Sunny in #{city}"} end} -]) - -{:ok, session} = AudioFlow.start_session( - history: true, - llm: {AudioFlow.Adapters.ReqLLM, - base_url: "http://localhost:8080/v1", - model: %{provider: :openai, id: "your-tool-capable-model"}, - api_key: "local", - audio_flow: [tools: tools]} -) -on_exit(fn -> if Process.alive?(session), do: AudioFlow.stop_session(session) end) - -results = Conversation.run!(session, [ - %{input: "Weather in Oslo?", reply: ~r/sunny/i, - tools: [{"weather", %{"city" => "Oslo"}}]}, - %{input: "Which city did I ask about?", reply: ~r/Oslo/, tools: []} -], observer: observer, timeout_ms: 30_000) -assert length(results) == 2 -``` - -Tool assertions compare the exact ordered list of executed tools and decoded -arguments per turn. `observe_tools/1` preserves tool behavior and Jido action -context; it does not replace tools with mocks. It sees actual executions, not -malformed or unknown calls rejected before execution. Use a fresh observer per -session; do not share wrapped tools across concurrent sessions. The test -process must own the session and observer. Unrelated mailbox messages remain -untouched. For graphs with several text-producing nodes, select the reply with -`node: "reply-node-id"`. - -A failed/cancelled turn, submission error, timeout, or mismatched expectation -raises `ExUnit.AssertionError` with the step number. Timeout is a per-turn wall -clock deadline and cancels the turn. Results include raw nonterminal events and -terminal metrics for further assertions. The caller manages session cleanup. - -The regression suite uses the existing local HTTP fixture to exercise real SSE -parsing, tool execution, follow-up requests, and session history without provider -credentials. Those fixtures verify protocol handling and assertions, not model -reasoning. Against an actual endpoint, model selection, availability, latency, -and nondeterminism are the test author's responsibility. No simulated-user LLM -or acoustic quality scoring is included. diff --git a/docs/guides/interruption.md b/docs/guides/interruption.md deleted file mode 100644 index 05d8bd0..0000000 --- a/docs/guides/interruption.md +++ /dev/null @@ -1,108 +0,0 @@ -# Interruption and heard reply history - -Issue #12 implementation: explicit playback acknowledgements, conservative -history truncation on cancellation, an optional minimum-word trigger gate, and -opt-in provisional pause/resume. Chat implements the pausable Web Audio endpoint; -native and network transports currently return unsupported. Device render -acknowledgements, within-chunk word alignment and automatic false-trigger -classification remain outside this implementation. - -## Transport contract - -A trusted endpoint driver calls -`AudioFlow.Output.acknowledge(session, turn_ref, cumulative_nanoseconds)` -after the endpoint reports that it rendered that much PCM. For the Membrane -output use `AudioFlow.Playback.acknowledge(playback, {session, turn_ref}, ns)`; -this additionally checks the offset against PCM dispatched to the sink and -records `played_ns` in playback stats. Offsets start at zero each turn and -increase monotonically; duplicates are accepted, regressions, future offsets -and stale keys return errors. Always await this call before requesting cancel -when processing an endpoint's final progress report. Concurrent cancel wins -over later acknowledgements; these are ignored as stale. - -Count mono signed 16-bit PCM samples at the output sample rate, independent of -input PTS. Each PCM chunk duration is rounded up to whole nanoseconds. Maintain -the same cumulative duration convention in the endpoint driver (the rounding -error is less than one nanosecond per chunk). A push, a sink demand, Membrane -end-of-stream, or elapsed wall time is **not** a playback acknowledgement. -Only use authenticated reports for the current turn, generated at the actual -rendering endpoint. Even a rendering acknowledgement is a transport assertion, -not proof of acoustic audibility. - -Chat reports its Web Audio render clock and serializes suspension/resumption -acknowledgements. PortAudio supplies no automatic rendered-frame offset here; -other network endpoints must integrate their own reports. Without reports, -zero reply text is known heard on cancellation. The existing Output behaviour -remains compatible; pausable endpoints opt into a separate extension. - -## History and cancellation - -In the chained STT/LLM/TTS pipeline, each fully synthesized LLM text chunk -creates an audio-end/text-byte checkpoint. Cancel kills the worker and flushes -output as before, then the next prompt contains only complete text chunks whose -audio ends were acknowledged before cancellation. Cancellation computes that -prefix before flushing; it deliberately omits audio that renders during flush -or whose report arrives later. Mid-chunk text is omitted rather than guessed -using a duration ratio. Unicode boundaries are preserved. A TTS chunk producing -no audio breaks the contiguous known-spoken prefix; later chunks cannot make -that missing text heard. - -The last completed generation also remains truncatable by cancel while its -audio is queued. Normal completion still commits the generated reply for -compatibility; `done` does not mean played. Starting the next turn accepts that -completed history and discards its cancellation snapshot. Clear-history removes -the snapshot, so a later cancel cannot restore cleared turns. Failed turns -retain existing history semantics. - -Graph sessions now create whole-chunk checkpoints on a single active path whose -history text node feeds one streaming terminal audio node directly. A checkpoint -is made only after that text chunk's TTS call returns successfully and output -pushes have been accepted. There must be one active root, no active fan-in or -fan-out, and no other audio-producing adapter. Inactive input sources do not -prevent alignment (for example, typed and STT inputs sharing an LLM). - -Branches, joined TTS, intervening text transformations and other ambiguous paths -retain no new assistant text on cancellation. Partial synthesis and missing audio -are conservative as in the chained pipeline. Failed turns roll back history and -staged conversation handoffs; cancellation may retain acknowledged aligned text -while rolling back its staged handoff. Completed handoffs remain committed when -queued playback is subsequently cancelled. Mixed speech-to-speech provider deltas -have no trustworthy alignment here and history is explicitly unsupported. - -## False triggers - -`AudioFlow.Output.interrupt(session, transcript, min_words: 2)` returns -`{:ok, :ignored}` for fewer whitespace-delimited words, leaving the worker and -playback running. At the threshold it invokes the existing cancel/flush path. -Call this with one accumulated candidate transcript, not independent STT deltas. -It neither submits the user's next input nor changes the busy-input policy. -It is a caller-controlled heuristic, not semantic interruption detection. -After cancel, workers and queued audio have been discarded and cannot resume. - -## Provisional pause/resume - -An endpoint implementing `AudioFlow.PausableOutput` accepts ordered pause and -resume commands and separately reports actual endpoint completion through -`Output.control_ack/5`. `Output.provisional(session, deadline_ms)` returns a -candidate reference. After the pause acknowledgement, resolve it with -`Output.resolve(session, candidate, :resume)` for a false trigger, or `:confirm` -to cancel. The deadline must be positive and at most 30 seconds; expiration -confirms/cancels, including when an endpoint never acknowledges. The original -turn timeout continues to apply. Legacy endpoints return `{:error, :unsupported}`. - -The runtime preserves the worker, turn reference, checkpoints and history, and -backpressures at most one pending worker emit. Existing event/byte limits remain -effective. Successful generation completion during a candidate is held until -resume; failures, owner exit, explicit stop and deadline expiry discard held -output. A confirmed interruption flushes the endpoint queue and retains only -the explicitly acknowledged aligned text prefix. Stale commands and offsets -are rejected. A resumed false candidate neither starts a new turn nor rewrites -history. - -Chat exposes Pause, Resume and Confirm/Stop controls using actual serialized -Web Audio suspension/resumption. Scheduled sources remain queued and progress -uses the frozen AudioContext clock while paused. This is a manual provisional -decision, not automatic VAD or proof of acoustic audibility. Native Playback, -telephony and WebRTC do not implement provisional pause. Upstream providers must -tolerate blocked emits; the chat's per-turn queue is finite rather than a sliding -latency window. See [chat setup and controls](../../examples/chat/README.md). diff --git a/docs/guides/model-languages.md b/docs/guides/model-languages.md deleted file mode 100644 index 8756149..0000000 --- a/docs/guides/model-languages.md +++ /dev/null @@ -1,54 +0,0 @@ -# Native speech languages - -Whisper graph nodes accept `"language"`: `"auto"` (the existing automatic -detection default), `"en"`, `"es"`, `"fr"`, `"de"`, `"it"`, `"pt"`, `"ro"`, -`"ja"`, `"zh"`, or `"hi"`. These are a curated subset of Whisper languages. -Bumblebee expects ISO alpha-2 codes and transcribes in the input language by -default; selecting a language does not request translation. `.en` models only -accept `auto` or `en`; conflicting selections raise before model loading. -Each model/language combination gets a separate shared serving cache entry. - -```json -{"id":"stt","type":"whisper.stt","options":{"model":"openai/whisper-tiny","language":"es"}} -``` - -MMS VITS graph nodes now select among real, pinned ONNX repositories: - -| Model | Language | Voice | -| --- | --- | --- | -| `Xenova/mms-tts-eng` | English (unchanged default) | Model's single speaker | -| `Xenova/mms-tts-spa` | Spanish | Model's single speaker | -| `Xenova/mms-tts-fra` | French | Model's single speaker | -| `Xenova/mms-tts-deu` | German | Model's single speaker | - -```json -{"id":"tts","type":"vits.tts","options":{"model":"Xenova/mms-tts-spa"}} -``` - -The language comes from the selected model, not a voice label or runtime -translation. These models run through the existing Transmuter VITS serving and -PCM adapter. Kokoro retains its existing English voices and phonemizers; -selecting an English Kokoro voice does not enable multilingual synthesis. -`AudioFlow.ModelLanguages.vits_models/0` exposes language/revision metadata. -Models require the ML profile (`AUDIOFLOW_ML=1`), model downloads, and EXLA. -MMS model cards specify CC-BY-NC-4.0; review their terms for your use case. - -Upstream references checked 2026-11-03: - -- [Bumblebee Whisper options](https://bumblebee.hexdocs.pm/Bumblebee.Audio.html#speech_to_text_whisper/5) -- ONNX model cards: [Spanish](https://huggingface.co/Xenova/mms-tts-spa), [French](https://huggingface.co/Xenova/mms-tts-fra), [German](https://huggingface.co/Xenova/mms-tts-deu) -- [Pinned Transmuter TTS implementation](https://github.com/georgeguimaraes/transmuter/blob/231028d9ff6f53bd58fa15d9f24d632258369805/lib/transmuter/audio/text_to_speech.ex) - -Configuration tests do not prove intelligibility or acoustic quality. Run the -opt-in synthesis smoke test with -`AUDIOFLOW_ML=1 AUDIOFLOW_MODEL_TESTS=1 mix test test/model_language_graph_test.exs`. - -For `.en` Whisper repositories the graph omits the language token and passes -`task: nil`: Bumblebee 0.8's monolingual generation config has no language/task -token mappings. This lets both `auto` and `en` use English transcription without -trying to force multilingual tokens. - -Validation on 2026-11-03: the opt-in test passed for all three added models, -loading their pinned weights and emitting valid, non-silent 16 kHz s16le PCM -through `Graph.ModelAdapter`. This is an inference/transport smoke test; no -listening panel or intelligibility/quality evaluation was performed. diff --git a/docs/guides/req-llm.md b/docs/guides/req-llm.md index 61c8f2b..2da9bd2 100644 --- a/docs/guides/req-llm.md +++ b/docs/guides/req-llm.md @@ -4,8 +4,7 @@ Use `{AudioFlow.Adapters.ReqLLM, model: model, ...req_llm_options}` for HTTP inference. The input is a ReqLLM context, message list or prompt. AudioFlow's `:audio_flow` keyword contains execution limits and Jido tools; native ReqLLM `:tools` remain at the top level. See the README for examples and migration. -`llm.req_llm` is the graph node; `llm.chat_http` remains a deprecated migration -node. The native Nx path does not use ReqLLM. +`llm.req_llm` is the graph node. The native Nx path does not use ReqLLM. Graph execution supplies session and turn context to Jido tools through `audio_flow: [tool_context: ...]`, including conversation handoff actions. @@ -67,11 +66,7 @@ tool. OpenAI completion requires a finish reason and `[DONE]`; other providers use their terminal event. OpenAI-compatible and Anthropic decoding are tested against local TCP fixtures. Live provider credentials were not available. -The deprecated ChatHTTP shim maps the old options to ReqLLM, without retaining -an HTTP implementation. Its legacy `:parameters` map supports `max_tokens`, -`max_completion_tokens` and `temperature`; other entries raise an explicit -migration error instead of silently losing configuration. Use direct ReqLLM -generation options for those settings. ReqLLM now controls token field choice, usage streaming, -empty assistant content, tool-result names and argument JSON normalization. -The tests assert these equivalent wire changes while preserving cancellation, -size limits, refusal, truncation, tool execution and stream-completeness checks. +ReqLLM controls token field choice, usage streaming, empty assistant content, +tool-result names and argument JSON normalization. The tests assert these wire +differences while preserving cancellation, size limits, refusal, truncation, +tool execution and stream-completeness checks. diff --git a/docs/guides/telemetry-audit.md b/docs/guides/telemetry-audit.md deleted file mode 100644 index 7ef4b53..0000000 --- a/docs/guides/telemetry-audit.md +++ /dev/null @@ -1,23 +0,0 @@ -# Issue #11 verification - -PR [#25](https://github.com/flowcopilot/audioflow/pull/25) is merged and already -implements the issue's proposed session, turn, and stage telemetry events. -No second instrumentation layer is added here. - -Evidence in this checkout: - -- `lib/audio_flow/telemetry.ex` defines lifecycle events and adapter spans. -- `lib/audio_flow/session.ex` invokes lifecycle events, includes terminal - status/metrics, and closes an active turn on session termination. -- `lib/audio_flow/graph/runner.ex` wraps graph adapter calls with node metadata. -- `test/telemetry_test.exs` covers lifecycle/stages, adapter error, cancellation, - shutdown during an active turn, and graph node attribution. -- `site/src/content/docs/docs/guides/telemetry.md` documents native time units, - metadata, cancellation limitations, and an `opentelemetry_telemetry` bridge - with process propagation for stage parentage. - -Verification: `mix test test/telemetry_test.exs` passed all five tests on -2026-11-03. This audit verifies the existing issue scope without closing #11. -As documented, killed turn tasks cannot emit stage stop events; the turn stop -reports cancellation/timeout instead. Session lifecycle events are not part of -the documented OpenTelemetry bridge; that bridge exports turn and stage spans. diff --git a/docs/input-processing.md b/docs/input-processing.md deleted file mode 100644 index 666a7ec..0000000 --- a/docs/input-processing.md +++ /dev/null @@ -1,128 +0,0 @@ -# Server input processing and semantic endpoints - -Both features are opt-in. Existing VoiceInput callers keep silence endpoints and -unmodified PCM. The order is resampling → SpeexDSP → VAD → Smart Turn on silence -→ utterance submission. The audio submitted to STT is the processed audio. - -## SpeexDSP 1.2.1 - -This uses the real native SpeexDSP preprocessor and reference AEC, rather than -claiming RNNoise/WebRTC compatibility. Install SpeexDSP development headers, a C -compiler, and pkg-config, then build once for your deployment platform: - -```sh -cc -O2 -Wall -Wextra -Werror native/speex_dsp.c \ - $(pkg-config --cflags --libs speexdsp) -o /absolute/path/audioflow-speex-dsp -``` - -The worker is a standalone process (no NIF). Each input stream needs its own -worker; adaptive filter state must not be shared between microphones. Its fixed -format matches Silero: mono signed 16-bit little-endian PCM, 16 kHz, 512 samples. -It uses a 200 ms echo tail and -20 dB noise suppression. AGC is disabled. Native -state persists across utterances; stop/recreate the worker for a new stream. - -```elixir -{:ok, dsp} = AudioFlow.SpeexDSP.start_link(executable: "/absolute/path/audioflow-speex-dsp") -input = AudioFlow.VoiceInput.new({AudioFlow.Silero, serving: silero}, - preprocessor: {AudioFlow.SpeexDSP, worker: dsp}) -{events, input} = AudioFlow.VoiceInput.push(input, captured_audio, aligned_speaker_audio) -``` - -`push/3` requires equally sized capture/reference chunks with the same sample -rate. Splits across detector frames are buffered together. `push/2` supplies zero -reference: noise suppression still runs, but this cannot cancel speaker echo. -Worker failure/200 ms timeout raises, preventing accidental unfiltered VAD; restart -the input stream and its worker explicitly. The native executable accepts -`aec-only` to disable preprocessing for isolation/diagnostics. - -For Membrane, pass the same `:preprocessor` in `:endpoint_options` to -`AudioFlow.Input.attach/3` or `InputPipeline.start_link/1`. The PCMSink runs it -after FFmpeg resampling and before VAD. `InputPipeline.reference(pipeline, audio)` -queues speaker PCM for subsequent capture. Reference must already be resampled to -the capture rate, delivered after stream format negotiation and before the -corresponding capture, and aligned by the caller. The queue is capped at one -second; missing samples are treated as zero. Overruns/invalid format raise. - -**Remaining integration for #9:** the existing PortAudio playback path does not -provide a synchronized render-reference tap. Merely queuing TTS generated audio -is insufficient: it must represent audio actually rendered at the device, with -appropriate latency alignment. This PR provides the working canceller and ingress, -but does not wire or validate that device clock/alignment. It does not claim -measured room acoustics, double-talk robustness, nonlinear echo removal, or -background voice removal. See the [official Speex AEC timing requirements](https://www.speex.org/docs/manual/speex-manual/node7.html). - -## Smart Turn v3.1 CPU - -The model runs in a persistent Python ONNX Runtime process. This avoids pretending -that the existing Transmuter import supports the quantized graph. Python 3.12 and -the pinned dependencies are required; the ordinary Elixir suite needs neither. - -```sh -uv venv /tmp/audioflow-turn --python 3.12 -uv pip install --python /tmp/audioflow-turn/bin/python \ - -r priv/audio_flow/requirements-smart-turn.txt -curl -L --fail -o /absolute/path/smart-turn-v3.1-cpu.onnx \ - https://huggingface.co/pipecat-ai/smart-turn-v3/resolve/f766f81d3cfdf7737ac64aad813d91bbfd56bf93/smart-turn-v3.1-cpu.onnx -sha256sum /absolute/path/smart-turn-v3.1-cpu.onnx -# fb68d55c2d542ce79e44b12013bfd571e90df8594ab096d757198e851b0c6594 -``` - -The worker verifies this hash on startup and makes no runtime downloads. Model -license: BSD-2-Clause; retain upstream license when redistributing weights. -Preprocessing follows the pinned upstream -[inference](https://github.com/pipecat-ai/smart-turn/blob/4786657e242dfe77dd138699ac564ee074a2a543/inference.py) -and [audio padding](https://github.com/pipecat-ai/smart-turn/blob/4786657e242dfe77dd138699ac564ee074a2a543/audio_utils.py): -last eight seconds of 16 kHz PCM, left zero padding, normalized Whisper features, -`input_features` ONNX input, and sigmoid probability output. - -```elixir -{:ok, turn} = AudioFlow.SmartTurn.start_link( - executable: "/tmp/audioflow-turn/bin/python", - args: [Path.expand("priv/audio_flow/smart_turn.py"), "/absolute/path/smart-turn-v3.1-cpu.onnx"]) -endpoint_options = [ - preprocessor: {AudioFlow.SpeexDSP, worker: dsp}, - turn_detector: {AudioFlow.SmartTurn, worker: turn}, - turn_threshold: 0.5, - turn_timeout_ms: 600, - turn_retry_ms: 320, - max_semantic_silence_ms: 2000 -] -input = AudioFlow.VoiceInput.new({AudioFlow.Silero, serving: silero}, endpoint_options) -# Or supply endpoint_options to InputPipeline.start_link/1. -``` - -After minimum VAD silence, completion emits `:semantic`; incompletion retains the -utterance, allowing resumed speech to join it. Inference retries at most once per -`turn_retry_ms` of audio. Two seconds of continuous silence forces -`:semantic_limit`; the existing maximum utterance and EOS bounds still apply. -Errors, invalid probabilities, and timeouts emit `:semantic_fallback`, using the -already satisfied silence endpoint. The Smart Turn worker bounds each native -request to 500 ms and terminates on timeout so late results cannot be reused. -VoiceInput bounds the whole model call (1–5000 ms configurable); workers have a -30-second startup limit. Callers own worker supervision and shutdown. - -Calls are synchronous: each silence decision may pause capture processing for up -to the configured timeout. Capture queued during inference is processed on the -next push; this is not an asynchronous speech-resumption invalidation mechanism. -Use a worker per stream to avoid cross-session inference queues. These tests -establish execution and endpoint behavior, not speech accuracy or latency targets. - -## Verification - -```sh -mix test -AUDIOFLOW_SPEEX_EXECUTABLE=/absolute/path/audioflow-speex-dsp \ - mix test test/native_input_processing_test.exs -AUDIOFLOW_MODEL_TESTS=1 \ -AUDIOFLOW_SMART_TURN_PYTHON=/tmp/audioflow-turn/bin/python \ -AUDIOFLOW_SMART_TURN_MODEL=/absolute/path/smart-turn-v3.1-cpu.onnx \ - mix test test/native_input_processing_test.exs -AUDIOFLOW_MEDIA=1 mix test test/input_test.exs -``` - -Core tests use deterministic detector/model fixtures to check joining, -completion, limits, failures, timeout, preprocessing order, and reference splits. -Optional native tests check stationary-noise attenuation, delayed scaled echo -convergence, and near-end signal retention. Optional model tests verify the exact -model hash, deterministic real inference and a reference probability, and the -last-eight-second cropping contract. No regular test downloads model weights. diff --git a/docs/providers.md b/docs/providers.md deleted file mode 100644 index a5912b9..0000000 --- a/docs/providers.md +++ /dev/null @@ -1,517 +0,0 @@ -# Remote speech providers - -These adapters make real network requests. The regression suite uses local HTTP -and WebSocket fixtures; it does **not** establish provider account access, model -availability, latency, recognition accuracy, or acoustic quality. No live -credential tests have been run. - -## Session-compatible STT and TTS - -Use these tuples in existing `:stt` and `:tts` session options (or graph stages -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.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"), - api_version: "2026-08-14", - api_key: fn -> System.fetch_env!("CARTESIA_API_KEY") end]} - -# Alternative TTS: -tts = {AudioFlow.Adapters.ElevenLabs, - [model: "eleven_multilingual_v2", voice_id: System.fetch_env!("ELEVENLABS_VOICE_ID"), - api_key: fn -> System.fetch_env!("ELEVENLABS_API_KEY") end]} -``` - -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 -24 kHz, while the HTTP response is arriving. They buffer only an incomplete -sample when HTTP chunks split a 16-bit value. Optional `:sample_rate` supports -8000, 16000, 22050, 24000, 44100 and 48000 (account restrictions may apply). -Optional `:language` maps to the provider's language field. Cartesia requires an -explicit `:api_version`; the request schema here follows `2026-08-14` (voice ID -string). Older Cartesia schemas are not supported. These are text-in/audio-out -HTTP streams, not bidirectional text WebSocket streams. MP3, WAV and μ-law are -not decoded and are not requested. - -## Fish Audio hosted API - -`AudioFlow.Adapters.FishAudioAPI` calls the hosted service. It requires a model, -a hosted voice model ID and an API key. It does not require a local Python server. - -```elixir -tts = {AudioFlow.Adapters.FishAudioAPI, - [model: "s2.1-pro", reference_id: System.fetch_env!("FISH_AUDIO_VOICE_ID"), - api_key: fn -> System.fetch_env!("FISH_AUDIO_API_KEY") end, - sample_rate: 24_000]} -``` - -It streams raw mono s16le PCM from `https://api.fish.audio/v1/tts`, using JSON, -Bearer authentication and a `model` header. `:sample_rate` defaults to 44,100; -supported rates are 8,000, 16,000, 24,000, 32,000 and 44,100 Hz. Optional -`:language` affects text normalization; `:latency` accepts `"normal"` (default), -`"balanced"` or `"low"`. Inline tags pass through unchanged. `:reference_id` -is a single hosted voice ID; uploading references and multi-speaker voice ID -arrays are not exposed by this adapter. Account access and model availability -still apply. Empty keys, models and voice IDs fail before making a request. - -The graph/UI node is `fish_audio_api.tts`. Set `FISH_AUDIO_API_KEY` in the server -environment. Its options are `model`, `reference_id`, `sample_rate`, `language`, -`latency`, `timeout_ms` and `receive_timeout_ms`. The endpoint defaults to the -hosted service; trusted server code can override it using -`speech_provider_endpoints["fish_audio_api.tts"]`. Graph data cannot set keys -or endpoints. Shared HTTP bounds apply; the idle timeout defaults to the -request timeout (30 seconds). For slow or long requests, raise both timeouts -and the graph/Session turn deadline. - -The [hosted API reference](https://docs.fish.audio/api-reference/endpoint/openapi-v1/text-to-speech) -and [official SDK endpoints](https://github.com/fishaudio/fish-audio-python/blob/main/_autodocs/endpoints.md) -were checked on 2026-11-15. Tests use local fixtures, not a paid API account. - -## Fish Audio / self-hosted Fish Speech - -`AudioFlow.Adapters.FishAudio` connects to a running -[Fish Speech API server](https://github.com/fishaudio/fish-speech). Install its -runtime and model weights using the upstream [installation guide](https://speech.fish.audio/install/). -In that checkout, launch the server with the downloaded checkpoint: - -```sh -python tools/api_server.py --listen 127.0.0.1:8080 \ - --llama-checkpoint-path checkpoints/s2-pro -``` - -The checkpoint selects the model. AudioFlow does not load weights or launch a -Python process. Select a stored server voice with `:reference_id`, or omit it -for unconditioned generation. Empty or whitespace-only reference IDs are omitted. -Register voice references through the server's -`POST /v1/references/add` API (multipart `id`, `audio`, and transcript `text`). - -```elixir -tts = {AudioFlow.Adapters.FishAudio, - [endpoint: "http://127.0.0.1:8080/v1/tts", reference_id: "narrator"]} - -# Use in an existing pipeline: -{:ok, session} = AudioFlow.start_session(stt: stt, llm: llm, tts: tts) -``` - -The default endpoint is `http://127.0.0.1:8080/v1/tts`. Authentication is -optional; if the server was launched with `--api-key`, pass `:api_key` as a -string or zero-argument function. The adapter sends Bearer authentication only -when the resolved key is nonempty. This adapter targets the self-hosted -server. Use `AudioFlow.Adapters.FishAudioAPI` for the hosted service. -The graph uses `FISH_SPEECH_API_KEY`, independently of the hosted API key. - -Requests use JSON with `format: "wav"` and `streaming: true`. The adapter strips -Fish Speech's canonical 44-byte streaming WAV header, accepts both zero and -`0xFFFFFFFF` unknown-length markers, and emits mono signed 16-bit little-endian -PCM during the response. The header determines the actual sample rate; no -resampling is performed. Unsupported headers, stereo, non-16-bit PCM, -truncated headers, empty audio and incomplete final samples return errors. -HTTP byte limits include the WAV header. Shared HTTP deadlines, cancellation -and request/response limits below apply. For Fish Speech, the idle timeout -`:receive_timeout_ms` defaults to the request `:timeout_ms` (30 seconds), rather -than the shared 10-second default. Increase both for slow or cold servers and -long passages; the server may pause between decoded text chunks. Also raise -the Session or graph turn deadline when needed. Telephony output needs explicit -resampling to its supported 8 or 16 kHz rate. Inline emotion/speaker tags in text -pass through unchanged. There are no `:model`, `:language`, `:voice_id`, or -`:sample_rate` options; use `:reference_id` for the voice. - -The graph/UI catalog includes `fish_audio.tts`, with optional `reference_id` -and `timeout_ms` / `receive_timeout_ms` options. A graph requires an explicit -trusted endpoint in server code (the localhost default is for direct use only): - -```elixir -# Merge with any existing provider endpoints. -Application.put_env(:audio_flow, :speech_provider_endpoints, %{ - "fish_audio.tts" => "http://127.0.0.1:8080/v1/tts" -}) -``` - -Set `FISH_SPEECH_API_KEY` in the server environment only if authentication is -required. Graph data cannot supply endpoints or credentials. Local servers -need no key. Missing endpoint configuration disables graph runs with a -prerequisite message. The server -must be reachable from the AudioFlow process (including its container). - -Wire behavior was checked against upstream -[request schema](https://github.com/fishaudio/fish-speech/blob/main/fish_speech/utils/schema.py), -[TTS route](https://github.com/fishaudio/fish-speech/blob/main/tools/server/views.py), and -[stream header](https://github.com/fishaudio/fish-speech/blob/main/fish_speech/inference_engine/utils.py) -on 2026-11-15. Tests use local HTTP fixtures; no live Fish Speech model inference -has been run. - -## Native Fish Speech on Nx - -Fish Speech is not currently a native Nx backend in AudioFlow. The two HTTP -adapters above run inference in Fish Audio's hosted service or in your Python -server. Neither is presented as native inference or wrapped in `Nx.Serving`. -For native TTS available today, use `AudioFlow.Kokoro` or VITS with -`AUDIOFLOW_ML=1`. - -A native S2-Pro implementation is feasible in principle, but needs a dedicated -model integration. The official checkpoint was inspected at revision -`1de9996b6be38b745688de084d87a5633f714e4e`: it contains sharded transformer -safetensors, tokenizer/config files, and `codec.pth`, with no ONNX files. -See the [checkpoint files](https://huggingface.co/fishaudio/s2-pro/tree/1de9996b6be38b745688de084d87a5633f714e4e). -The [configuration](https://huggingface.co/fishaudio/s2-pro/blob/1de9996b6be38b745688de084d87a5633f714e4e/config.json) -identifies `fish_qwen3_omni`, with a 36-layer text model, a four-layer audio -decoder, and ten audio codebooks. A generic Qwen3 text generator cannot run the -complete speech pipeline. - -The implementation path would require: - -1. Pin a model revision and preserve Fish's prompt/speaker formatting and - [semantic-token mapping](https://github.com/fishaudio/fish-speech/blob/main/fish_speech/tokenizer.py). -2. Implement/export the slow transformer and fast codebook decoder, including - their separate KV caches, generation loop and sampling. Validate token - logits and generated codebooks against the - [upstream implementation](https://github.com/fishaudio/fish-speech/blob/main/fish_speech/models/text2semantic/llama.py). -3. Implement/export the - [ModifiedDAC codec](https://github.com/fishaudio/fish-speech/blob/main/fish_speech/models/dac/modded_dac.py) - decoder, plus the encoder for reference-voice conditioning. Verify waveform - shape, sample rate, reconstruction quality and chunk boundaries against Python. -4. Integrate proven inference with a shared `Nx.Serving` and AudioFlow's PCM - adapter. Check memory use, compile cost, cancellation and generation latency - on the actual target backend before registering a runnable graph node. - -The existing Transmuter dependency consumes ONNX graphs, so it would need exports -of those components and operator/parity validation; it cannot load the supplied -safetensors and codec checkpoint as a complete Fish model. An Axon implementation -would instead need model definitions and weight mapping. Neither path has been -implemented or validated here. The assessment does not establish that every -required export/operator works. Drama 3 needs its own architecture assessment. - -## Direct speech-to-speech calls - -These calls send one committed utterance per connection. For an always-on -OpenAI conversation with the microphone open, use -[`AudioFlow.Duplex.OpenAIRealtime`](#continuous-openai-realtime-conversation). - -`AudioFlow.Adapters.OpenAIRealtime.run/3` and -`AudioFlow.Adapters.GeminiLive.run/3` accept a committed `AudioFlow.Audio` and -invoke an arity-one callback with `{:transcript, text}`, `{:text, delta}` and -`{:audio, %AudioFlow.Audio{}}` values. The callback must return `:ok`. Return is -`:ok` or `{:error, reason}`. Input transcription can arrive after generated -speech. Gemini transcripts and assistant text are deltas; concatenate in order. -OpenAI emits one completed input transcript and assistant text deltas. - -```elixir -AudioFlow.Adapters.OpenAIRealtime.run(audio_24khz, - [model: System.fetch_env!("OPENAI_REALTIME_MODEL"), - api_key: fn -> System.fetch_env!("OPENAI_API_KEY") end, - instructions: "Answer briefly.", voice: "marin"], - fn event -> send(output_process, event); :ok end) - -AudioFlow.Adapters.GeminiLive.run(audio_16khz, - [model: System.fetch_env!("GEMINI_LIVE_MODEL"), # include models/ prefix - api_key: fn -> System.fetch_env!("GEMINI_API_KEY") end], - fn event -> send(output_process, event); :ok end) -``` - -OpenAI uses the GA Realtime WebSocket protocol, waits for `session.updated`, -disables VAD, appends and commits the input, then requests a response. Input and -output PCM must be 24 kHz. Input transcription defaults to -`gpt-4o-mini-transcribe` (`:transcription_model` overrides it). Success waits for -both a completed response and input transcription. Failed or cancelled -responses, transcription failures and tool calls return errors. - -Gemini uses Live v1beta, waits for `setupComplete`, disables automatic activity -detection and wraps the audio in `activityStart` / `activityEnd`. Input is -16 kHz PCM, output is 24 kHz PCM. It requests input/output transcription. -`turnComplete` ends the run; interruptions, tool calls and `goAway` fail the -run. Both adapters support optional `:instructions`. - -## Session speech-to-speech mode - -Start a dedicated Session without dummy STT/LLM/TTS adapters: - -```elixir -{:ok, session} = AudioFlow.start_session( - speech_to_speech: {AudioFlow.Adapters.OpenAIRealtime, - [model: System.fetch_env!("OPENAI_REALTIME_MODEL"), - api_key: fn -> System.fetch_env!("OPENAI_API_KEY") end, - instructions: "Answer briefly."]}, - timeout_ms: 30_000, max_input_bytes: 960_000, - max_events: 1024, max_output_bytes: 16_777_216) -{:ok, turn} = AudioFlow.submit(session, audio_24khz) -# Receive {AudioFlow, session, turn, {:transcript | :text | :audio, value}} -# followed by {:done, metrics} or {:error, reason, metrics}. -AudioFlow.cancel(session) -AudioFlow.stop_session(session) -``` - -GeminiLive uses the same option with 16 kHz input. Only committed PCM inputs -are accepted. One active turn is allowed; busy input is rejected. The optional -Output transport receives start/push/finish and flush on cancellation or failure. -Cancellation, timeout, owner exit and stop terminate the socket-owning task. -Late callbacks for an old turn are rejected. The byte budget counts cumulative -text/transcript UTF-8 and PCM payload bytes, separately from event count. The -owner must still consume its mailbox across turns. Provider limits also apply. - -This mode explicitly rejects `:history`, stage adapters, graph plans and -conversation flows. Each turn opens a fresh connection; no prior transcript is -silently substituted for native provider context. Instructions are supported as -provider options, but replaying prior text/audio, native item truncation, session -resumption and provider history are not implemented. No heard-text checkpoints -are inferred from mixed deltas: their ordering and boundaries do not establish -text/audio alignment. Acknowledgements can track PCM progress but cannot prove -which transcript prefix was heard. The official [OpenAI conversation guide](https://developers.openai.com/api/docs/guides/realtime-conversations#interruption-and-truncation) -also distinguishes native audio truncation from a precisely truncated transcript. -[Gemini session management](https://aistudio.google.com/docs/live-api/session-management) -describes persistent connections and explicit resumption handles; this adapter -does not retain or replay those handles. - -Graph/UI registration remains deferred: the current catalog and edge validator -expose one typed output per stage. A useful mixed-output speech node needs -explicit typed event ports (transcript, text and audio), routing/validation for -each, and a dedicated history capability contract. Registering either adapter -as an existing STT/LLM/TTS node would misrepresent its contract. Use the explicit -Session mode or direct API today. There is no continuous duplex input, tool -execution, automatic reconnect, resampling or WebRTC in this mode. For -continuous input, see `AudioFlow.Duplex` below. - -## Local Moshi speech-to-speech - -`AudioFlow.Adapters.Moshi` runs one committed turn against a local -[Kyutai Moshi](https://github.com/kyutai-labs/moshi) server. Moshi is a 7B -full-duplex model. The 4-bit MLX build needs approximately 5 GB of weights and -runs on an Apple Silicon laptop. The adapter needs `AUDIOFLOW_MEDIA=1`, because -it uses `membrane_opus_plugin` for Opus and `membrane_ogg_plugin` for Ogg pages. - -Start the server (Python 3.12, approximately 5 GB download on first start): - -```sh -uvx --python 3.12 --from moshi_mlx python -m moshi_mlx.local_web \ - -q 4 --hf-repo kyutai/moshika-mlx-q4 --no-browser --port 8998 -``` - -Use the adapter with 24 kHz input: - -```elixir -{:ok, session} = AudioFlow.start_session( - speech_to_speech: {AudioFlow.Adapters.Moshi, [endpoint: "ws://127.0.0.1:8998/api/chat"]}, - timeout_ms: 60_000) -``` - -The wire protocol is binary WebSocket messages with a one-byte kind: `0` -handshake, `1` Ogg Opus audio (24 kHz mono), `2` UTF-8 text tokens. The adapter -sends the input as 80 ms Ogg pages of four 20 ms Opus packets, then silence. It -sends one silent frame for each output frame, so the model sets the pace, not -the wall clock. Output for the input period is dropped. - -Moshi has no end-of-turn signal. The reply ends after `:end_silence_ms` (1,600) -of model output without a text token. The turn fails with `:no_reply` if -`:max_reply_ms` (20,000) passes without text. The default `:timeout_ms` is -60,000. Moshi does not transcribe the user, so there is no `:transcript` event. - -Limits: - -- The server serves one connection at a time. A second turn waits for the lock. -- Model state continues across connections. The server does not reset context - between turns, and the adapter cannot clear it. -- The first turn after server start is slow (approximately 13 s on an M5) while - MLX warms up. Later turns gave the first reply audio approximately 2 s after - submit for a 3.2 s question. -- Moshi speaks English only. -- The adapter calls the Opus `Native` modules and the Ogg `Page`, `Parser` and - `Opus` modules directly, not through Membrane pipeline elements. The - `Membrane.Ogg.Muxer` element holds packets until a page has 255 segments - (approximately 5 s), which is too slow for a duplex model. These modules are - internal to the plugins, so the dependencies are pinned to `~> 0.21.0` and - `~> 0.5.2`. - -To check a running server, convert a question to raw 24 kHz PCM and run: - -```sh -AUDIOFLOW_MEDIA=1 AUDIOFLOW_HTTP_MODEL_TESTS=1 \ -AUDIOFLOW_MOSHI_PCM=question.s16le mix test test/moshi_test.exs -``` - -`AUDIOFLOW_MOSHI_ENDPOINT` overrides the default endpoint. - -### Continuous full-duplex Moshi - -`AudioFlow.Duplex` keeps one Moshi connection open. Microphone input and model -output flow at the same time. There is no committed turn, no end-of-turn -detection, no silence gate, and no output drop while the user speaks. Use it -for a live conversation. Use `AudioFlow.Adapters.Moshi` for one committed turn. - -```elixir -{:ok, duplex} = - AudioFlow.Duplex.start_link( - owner: self(), - adapter: {AudioFlow.Duplex.Moshi, endpoint: "ws://127.0.0.1:8998/api/chat"}) - -# Wait for {AudioFlow.Duplex, ^duplex, :ready}, then push 80 ms chunks: -:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm_3840_bytes, sample_rate: 24_000}) -:ok = AudioFlow.Duplex.stop(duplex) -``` - -`start_link/1` returns before the connection opens. The owner receives -`{AudioFlow.Duplex, pid, event}`, where `event` is `:ready` (after the Moshi -handshake), `{:audio, %AudioFlow.Audio{}}`, `{:text, token}`, -`{:error, reason}` or `:closed`. `:closed` comes last, also after an error. -`push/2` returns `{:error, :not_ready}` before `:ready` and `{:error, :closed}` -after the session stops. Keep the endpoint in server configuration; the browser -does not need it. - -`start/1` starts an unlinked session with the same API. Use it when the owner -must also survive an unexpected adapter crash, as the chat UI does. Monitor -the returned process to detect these crashes. Both start functions monitor -the owner and close the connection when it exits. - -The adapter sends each complete 80 ms frame (3,840 bytes at 24 kHz) as one Ogg -page at once. A shorter remainder waits for the next push. Moshi answers each -input frame with one output frame, so the client must push continuous audio, -silence included, to get continuous output. - -Bounds (defaults): - -- `:connect_timeout_ms` (15,000) from start to the Moshi handshake. -- `:idle_timeout_ms` (30,000) without an accepted push. -- `:max_session_ms` (1,800,000) in total. -- `:max_chunk_bytes` (48,000) for each push, else `{:error, :too_large}`. -- `:max_response_bytes` (67,108,864) for all incoming WebSocket bytes in a - session, including fragments. The session fails with `:response_too_large` - at this bound. Incomplete Ogg packets are limited to 256 KiB. -- `:max_input_lead_ms` (2,000). For Moshi (adapter input flow `:answered`): - pushed audio that model audio has not answered. For OpenAI (`:realtime`): - pushed audio ahead of the wall clock since `:ready`, so continuous silence - never fills it. A push past it returns `{:error, :overloaded}` and is not - sent, for example while MLX warms up. -- `:max_owner_queue` (250): when the owner mailbox has this many messages, the - session fails with `:owner_overloaded`. Output is not buffered or dropped. -- `:send_timeout_ms` (5,000) for each TCP write. - -The session monitors the owner and closes the connection when the owner exits. -On failure, timeout and `stop/1` it exits with reason `:normal`, so the link -from `start_link/1` does not stop the owner. The owner must be a local process. -The Moshi server limits above also apply: one connection at a time, and model -state continues across connections. - -`mix test test/duplex_test.exs` (with `AUDIOFLOW_MEDIA=1`) checks simultaneous -input and output, frame sizes, the handshake gate, the input and owner bounds, -timeouts and connection cleanup against a local fixture. With -`AUDIOFLOW_HTTP_MODEL_TESTS=1` and `AUDIOFLOW_MOSHI_PCM`, it also streams the -question and then silence in real time to a running server. - -### Continuous OpenAI Realtime conversation - -`AudioFlow.Duplex.OpenAIRealtime` keeps one authenticated OpenAI Realtime GA -WebSocket open for a whole conversation. It needs no media build. - -```elixir -{:ok, duplex} = - AudioFlow.Duplex.start( - owner: self(), - adapter: - {AudioFlow.Duplex.OpenAIRealtime, - model: System.fetch_env!("OPENAI_REALTIME_MODEL"), - api_key: fn -> System.fetch_env!("OPENAI_API_KEY") end, - voice: "marin"}) - -# After {AudioFlow.Duplex, ^duplex, :ready}, push 24 kHz PCM continuously, -# silence included: -:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm, sample_rate: 24_000}) -``` - -The adapter sends `session.update` (type `realtime`, `output_modalities` -`["audio"]`, PCM 24 kHz in and out, the voice, input transcription and -`server_vad` with `create_response` and `interrupt_response`) after -`session.created`, and emits `:ready` after `session.updated`. Each push is one -`input_audio_buffer.append`. The adapter never commits input and never sends -`response.create`: OpenAI detects each utterance, replies to it and cancels the -reply when new speech starts. All utterances of one connection share the -provider conversation; a new connection starts a new one. The API key function -runs only to connect, so the key is not kept in the session state. Options: -`:model`, `:api_key`, `:voice` (`"marin"`), `:instructions` (`""`), -`:transcription_model` (`"gpt-4o-mini-transcribe"`) and `:endpoint`. - -The owner also receives: - -| Event | Meaning | -| --- | --- | -| `{:speech_started, item}` | User speech started. Flush queued reply audio; keep the microphone open. Late audio and text of the interrupted reply are dropped. | -| `{:transcript, item, text \| :failed}` | Final transcript of the user utterance `item`. | -| `{:response, id, status}` | Reply `id` was `:created`, or ended `:completed`, `:cancelled`, `:incomplete` or `:failed`. | -| `{:output, item}` | The next `{:audio, _}` events belong to reply audio `item`. | - -After a flush, report the played part of the cut reply with -`AudioFlow.Duplex.control(duplex, {:played, item, ms})`. If `ms` is less than -the audio received for `item`, the adapter sends `conversation.item.truncate` -(`audio_end_ms` capped to the received audio), so the provider history keeps -only the played audio and its transcript. Only the last interrupted reply is -accepted, once; other reports return `{:error, :stale}` and leave the call -open. A rejected truncation also leaves the call open. The played time is -client playback time: it does not prove acoustic delivery. Without a report, -the provider history keeps the full reply. - -Provider `error` events fail the session with `{:remote_error, code}` (only -the code or type, never the message). Tool calls fail it with -`:unsupported_tool_call`, because no tools are configured. All -`AudioFlow.Duplex` bounds apply; `:max_response_bytes` (64 MiB) is about 17 -minutes of base64 reply audio per session. -The chat example sets this bound to 256 MiB for OpenAI calls, to allow the -30-minute call limit to apply before the response byte limit in ordinary use. - -`mix test test/duplex_openai_test.exs` checks the handshake order, server VAD -configuration, several utterances on one socket, continuous silence, -interruption drops, truncation bounds, provider errors and cleanup against a -local WebSocket peer, not OpenAI. - -## Bounds, cancellation and errors - -All providers accept `:endpoint` overrides for proxies and local tests. Use -HTTPS/WSS for credentials on external networks. Requests are not redirected or -retried. Provider errors are normalized without returning credential-bearing -URLs or provider message contents. Partial output may have been emitted before -an error; callers must decide whether to discard it. - -WebSocket operations have a total `:timeout_ms` budget (30,000 default, including -time spent in the callback) and `:max_response_bytes` (16,777,216, before -WebSocket decoding). Input must be nonempty valid PCM, at most 2 MB, at the -provider's exact rate for Realtime/Gemini. Pings get pongs. Premature socket -closure fails the run. The calling turn process owns the socket; terminating -it closes the connection and stops remote generation on that connection. There -is no separate cancel handle or in-connection `response.cancel` command. - -HTTP TTS accepts `:timeout_ms` (30,000), `:receive_timeout_ms` (10,000), -`:max_request_bytes` (65,536), and `:max_response_bytes` (16,777,216). -The Finch read budget excludes callback backpressure; use a Session/worker -deadline to bound the complete operation. Killing the turn releases the HTTP -connection. Empty responses, unsupported content types, and incomplete final -samples fail. Limits and timeout options must be positive integers. - -## Protocol references and verification - -Wire shapes were checked against official documentation on 2026-11-03 -(OpenAI Realtime events again on 2026-11-06): - -- [OpenAI Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations) -- [OpenAI Realtime WebSocket](https://developers.openai.com/api/docs/guides/voice-websockets), - [voice activity detection](https://developers.openai.com/api/docs/guides/realtime-vad), - [client events](https://developers.openai.com/api/reference/resources/realtime/client-events) and - [server events](https://developers.openai.com/api/reference/resources/realtime/server-events) -- [Gemini Live WebSocket reference](https://ai.google.dev/api/live) -- [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) - -`mix test test/remote_providers_test.exs` exercises local protocol fixtures, -setup ordering, authentication/request shapes, final/delta event mapping, -streaming before EOF, odd PCM chunk boundaries, errors, limits, timeouts and -connection cleanup on caller cancellation. It performs no model inference. diff --git a/docs/recording-and-privacy.md b/docs/recording-and-privacy.md deleted file mode 100644 index 0b5ce49..0000000 --- a/docs/recording-and-privacy.md +++ /dev/null @@ -1,98 +0,0 @@ -# Optional recordings and transcript privacy - -`AudioFlow.Recording` consumes the existing owner messages. Nothing is recorded -unless the owner explicitly creates and feeds a recorder. No Session changes, -provider integrations, or native media dependencies are required. - -```elixir -alias AudioFlow.{Privacy, Recording} -alias AudioFlow.Recording.Store - -{:ok, store} = Store.new("/var/lib/my_app/recordings", - max_age_ms: 86_400_000, max_records: 1000, max_bytes: 8_000_000) -{:ok, session} = AudioFlow.start_session(my_adapter_options) - -# Example rule only: supply your own policy/detector for the data you handle. -redactor = Privacy.rules([{~r/customer-[0-9]+/, "[CUSTOMER]"}]) -recorder = Recording.new(session, store, redactor: redactor, - audio: false, max_events: 1024, max_bytes: 4_000_000) - -# In the owner's receive loop / GenServer.handle_info: -# Always keep `next`, including after an error. -receive do - {AudioFlow, ^session, _turn, _event} = message -> - case Recording.consume(recorder, message) do - {:ok, next, nil} -> {:continue, next} - {:ok, next, id} -> {:artifact, id, next} - {:error, reason, next} -> {:recording_error, reason, next} - end -end -``` - -Feed **every** runtime event in mailbox order, including terminal events; keep -one recorder per session. Calls are synchronous and can delay the owner, so use -a dedicated owner process when disk latency matters. This limits recorder state, -not the owner's mailbox; runtime producers need their own flow control. The -session already stops when its owner exits. Monitor the session and call -`Recording.discard/1` on shutdown: unfinished turns are discarded, never falsely -marked successful. Recording errors do not change runtime inference or playback. - -## Artifact contract - -Each terminal `:done`, `:cancelled`, or `:error` writes one versioned JSON file. -Failed/cancelled turns retain their partial outputs and explicit status. Error -reasons and metrics are excluded because they can contain sensitive data. Limits -or redactor failures discard the entire turn, with no partial plaintext file. -Byte limits bound buffered payload plus descriptor overhead; the store separately -limits final JSON bytes, including redactor expansion and base64 PCM. - -`streams` holds full redacted text for each `{kind, node}` pair (`transcript`, -`description`, `text`). Joining all chunks in a stream before redaction covers -matches split across chunks, even with interleaved audio. `events` preserves -arrival order with zero-based sequence numbers and kind/node references. Text -chunk contents and offsets are deliberately absent: redaction can change length. -Identifiers spanning *different* streams require an application-specific policy. -Node IDs are application configuration and must not contain personal data. - -Set `audio: true` to save genuine **output** mono PCM as base64 `pcm_s16le` with -its sample rate in ordered events. These are PCM chunks, not WAV containers. -There is no audio redaction: voice recordings can contain all spoken PII. -Images/vectors are excluded. Original submitted input, including text-only user -input and microphone PCM, is not an owner output event and is not captured. -This records STT transcript/description and generated text/audio, not a full call -capture. No synthetic inference or acoustic quality claims are implied. - -## Privacy and lifecycle - -A redactor is required and runs before *any* artifact (including a temporary -file) is written. Supply `fn text -> {:ok, sanitized_text} end`, or return an -error to suppress the turn. Exceptions, throws and invalid return values fail -closed with `:redaction_failed`; callback error details are not returned/logged. -Regex rules are only explicit pattern transformations, not a generic PII detector, -compliance certification, or protection for runtime history, providers, live -owner messages or audio. Plaintext remains in bounded process memory until turn -completion; a redactor must be trusted, fast and memory bounded. For intentional -plaintext persistence only, pass `redactor: &{:ok, &1}`. - -`Store.list/1` and `Store.read/2` enforce finite retention as well as writes. -`Store.cleanup/1` must be scheduled by your application during idle periods -(e.g. a supervised periodic job); no background timer is silently installed. -`Store.delete/2` deletes one generated artifact ID; use `list/1` for discovery. -The directory is private (0700); artifacts are 0600, written via a synced temporary -file and rename. Use a dedicated directory: retention manages only generated -artifact names, never recursively deletes directories, and leaves unrelated files -alone. Age uses wall-clock milliseconds in generated IDs; clock corrections can -affect expiration. Count retention keeps the newest timestamps (ties by ID). - -Symlink directory components and non-regular artifact files are rejected or -ignored. IDs are strictly validated before joining paths. The directory must be -controlled by the application OS user; pathname checks do not prevent races by -another process with the same filesystem privileges. Serialize store operations -if multiple owners share a root. This is local disk storage with no encryption, -authentication, backup management or secure erasure: enforce those at deployment. -Deletion does not remove external backups or already-read copies. I/O failures -are returned to the owner, which should alert without logging sensitive content. - -Interrupted writes can leave sanitized `.tmp` files. Cleanup expires matching -regular temporary files by the same age policy, while leaving fresh temporary -files alone. Final artifact count limits apply to completed JSON files. diff --git a/docs/refactoring/test-audit.md b/docs/refactoring/test-audit.md deleted file mode 100644 index 227ae2d..0000000 --- a/docs/refactoring/test-audit.md +++ /dev/null @@ -1,59 +0,0 @@ -# Test review - -## Baseline - -The first full core run had 15 failures. Each failure occurred before the -recording behavior ran: `Store.new/1` returned `{:error, :unsafe_path}`. -The setup used `System.tmp_dir!/0`. On macOS this path can contain a symlink. -The store rejects symlinks in all path segments. This is its security contract. - -## Changes - -- Repair temporary directory setup in `recording_test.exs`, - `recording_runtime_test.exs`, `cross_feature_acceptance_test.exs`, and - `remote_providers_test.exs`. Use ExUnit's `:tmp_dir` context. It gives each test - a directory under the project `tmp/` path. Keep all persistence, privacy, - retention, lifecycle, permission, and symlink checks. -- In `input_processing_test.exs`, remove checks of `speaking?`, - `semantic_checked_at`, and `reference_pending`. The returned events and PCM - check the behavior. Check the exact utterance and detector input on both - semantic completion cycles. A reset failure must prevent the second cycle - from completing and thus fail the test. -- In `graph_checkpoint_test.exs`, use the audio fixture duration for playback - acknowledgements. Do not read the session's private playout state. Branches - emit four two-sample chunks at 16 kHz: 500,000 ns. A joined node emits no - audio while its source is blocked. Silent and partial cases each emit one - two-sample chunk: 125,000 ns. -- In `conversation_test.exs`, let the controlled adapter send its task PID to - the test. Resume and failure commands go to that fixture PID. The tests no - longer read the session's private `active.task.pid` fields. The checks still - prove successful handoff, stale tool rejection, and rollback after failure. - -No test was deleted. The reviewed negative recording checks protect current -privacy, persistence, or path security requirements. Graph catalog checks -protect public metadata. Codec reference values and dependency compatibility -checks have independent contracts. Similar tests at session and transport -levels protect different lifecycle behavior. - -## Evidence - -The recording owner and store, all four repaired test files, their recent -history, CI routing, input processing, voice input, graph checkpoint, playout, -conversation, graph options, retrieval, and telephony tests were read. -The test tree was searched for source checks, constant assertions, private -state access, and skip tags. No deletion candidate had enough evidence to -remove its contract. - -The fixture changes add no production code or test-only production interface. -The store security rules are unchanged. - -## Checks - -- Recording and provider tests: 25 passed. -- Input processing and graph checkpoint tests: 8 passed. -- Conversation tests: 5 passed. -- Focused tests require local TCP access for the Mix build lock. Provider tests - also use local sockets. -- Final core and avatar server suite: 224 passed, 3 skipped, 5 excluded. -- UI: 28 passed. Chat: 12 passed. WebRTC: 12 passed. -- Final independent review found no further issue worth fixing. diff --git a/docs/refactoring/untangle.md b/docs/refactoring/untangle.md deleted file mode 100644 index a202c3e..0000000 --- a/docs/refactoring/untangle.md +++ /dev/null @@ -1,68 +0,0 @@ -# Code structure decisions - -Scope: the core library, optional libraries, UI, examples, scripts, and documentation. -The initial working tree was clean. The user selected comment and test cleanup. Remove implementation comments and review tests after structural changes. - -## Problems and changes - -- Put session connection state and domain events in a shared transport module. Keep JSON encoding in each WebSocket endpoint. - - RTVI and telephony call the raw PCM WebSocket handler and decode its JSON to recover events. - - RTVI encodes commands to JSON to call the raw PCM handler. - - Telephony intercepts private PCM output messages to enforce its output limits. -- Put PCMU conversion and packet completion in one packetizer. - - Telephony and WebRTC copy the rate conversion, 160-byte packets, filter tail, and silence padding. -- Let adapters merge execution context through an optional adapter callback. - - The graph runner names ReqLLM and ChatHTTP and knows their option layouts. -- Put linear PCM conversion in the resampler module, and retain its existing algorithm. - - The graph node module owns a general audio conversion algorithm. Other callers must import graph code to use it. -- Use the core WAV encoder in the UI and chat application. - - Three modules copy the same WAV header construction. -- Record the chat build profile in application configuration. - - Build configuration and runtime code independently select native mode from the environment. -- Keep chat choices and defaults with their owners. - - Chat setup validation and LiveView markup copy the mode, language, voice, and TTS choices. - - The demo engine and native engine copy model and voice defaults. -- Let graph node families report configuration requirements. - - UI prerequisite checks inspect the provider registry and name the RAG node and its configuration. -- Build the UI conversation example through a node catalog. - - The example edits nested compiled conversation plans to replace adapters. -- Store each graph node family and the model adapter in its own file. - - `graph/nodes.ex` contains four unrelated families; `graph/models.ex` contains a second module. - -## Cases to retain - -- PCM conversion algorithms serve different contracts: complete audio uses a sinc filter; graph linear conversion keeps its existing output; streaming telephony keeps filter state. -- Provider protocol differences, credential checks, frame bounds, reorder deadlines, playback pacing, stale message checks, and optional dependency profiles are current requirements. -- Model, distributed-node, and native pipeline tests need external resources. Their opt-in tags are required. -- Adapter and transport exception conversion keeps failures inside the documented error contract. -- Site documentation and repository guides have different navigation and context. Similar text alone does not justify removing either published entry point. - -## Verification - -- Initial `mix test` could not start because dependencies were absent. Locked dependencies were then installed. -- Full core and avatar server suite: 224 passed, 3 skipped, 5 excluded. -- UI suite: 28 passed. Chat suite: 12 passed. -- WebRTC suites: 12 passed. Core transport checks: 25 passed. -- Browser audio checks: 4 passed. Python report checks: 5 passed. -- Core type checks, changed-code lint, formatting, and whitespace checks passed. -- Native WebRTC first failed before media handling. The downloaded SRTP library - could not find OpenSSL 3. A link in the ignored native build cache repaired - the local library path. No dependency source or lockfile changed. -- Native model inference and hardware media tests remain opt-in. No model - weights or device sessions were started for this refactor. - -## Final review - -Independent agents checked graph execution, audio conversion, application -settings, transport events, packet completion, and test value. All accepted -findings are resolved. No further structural issue worth fixing was found in -those reviews. - -The review removed unused legacy WebSocket message forwarding. Public output -callbacks still work. Tests now use current transport messages. The filter -owns its own completion length, so the packetizer does not copy that constant. -The workflow graph names its reply type without relying on node order. - -The test review is recorded in [test-audit.md](test-audit.md). No tests were -deleted. Tests use observable events and audio where private state was not -needed. Required protocol and resource limits remain in place. diff --git a/docs/transports.md b/docs/transports.md deleted file mode 100644 index 7d4c52b..0000000 --- a/docs/transports.md +++ /dev/null @@ -1,170 +0,0 @@ -# Network transport integration - -The existing `AudioFlow.WebSocket` endpoint remains the raw mono s16le PCM -transport introduced in PR #24. Its wire protocol is unchanged. The telephony -and RTVI endpoints reuse its session ownership, output acknowledgements, -stale-turn rejection and VAD path. Optional WebRTC uses a -separate PCM Session bridge; see [the WebRTC guide](webrtc-avatars.md). - -## Telephony WebSockets - -Mount `AudioFlow.Telephony.WebSocket` in an application-owned Plug: - -```elixir -# Authenticate the HTTP upgrade before this point. -WebSockAdapter.upgrade(conn, AudioFlow.Telephony.WebSocket, - [provider: :twilio, session: session_options, - vad: {Your16kHzDetector, detector_options}], - max_frame_size: 100_000) -``` - -Use real STT/LLM/TTS adapters in `session_options`. The tests use the existing -Demo adapters to test transport behavior, not speech recognition or synthesis. -Install WebSockAdapter and a WebSock-capable server as runtime dependencies in -the host application (this library currently includes them for dev/test only). -Require WSS in deployment. Validate the provider's upgrade signature against the -externally visible URL in the host Plug, before allocating a session; the -WebSock handler cannot authenticate HTTP headers after upgrade. Configure proxy -idle timeouts and application connection limits there as well. - -For Twilio, use a bidirectional ``, not a -unidirectional ``. The handler accepts only mono `audio/x-mulaw` -at 8 kHz, binds `start.streamSid`, and emits `media`/`clear` with that SID. -See [Twilio's message reference](https://www.twilio.com/docs/voice/media-streams/websocket-messages). - -For Telnyx, select `provider: :telnyx`, `stream_track: "inbound_track"`, -`stream_bidirectional_mode: "rtp"`, and `stream_bidirectional_codec: "PCMU"` -in the Answer/Dial/streaming_start request. The handler accepts mono PCMU at -8 kHz and binds the top-level `stream_id`. Outgoing messages use Telnyx's -`media` and `clear` envelopes, without a Twilio SID. MP3 playback mode and other -codecs are unsupported. See [Telnyx's streaming guide](https://developers.telnyx.com/docs/voice/programmable-voice/media-streaming). - -Both paths decode Base64 headerless μ-law, interpolate to 16 kHz PCM, and feed -the configured VAD. Endpoint detection submits an utterance; confirmed speech -cancels an active reply and clears remote playback. TTS must emit 8 or 16 kHz -mono s16le PCM. Other rates fail the turn and close the stream with code 1011; -configure TTS output or an upstream resampler explicitly. Downsampling uses a -stateful 31-tap FIR, with 15 input samples of delay. On completion the filter -tail is drained and the last 20 ms packet is padded with μ-law silence. No -wideband recovery or production acoustic-quality claim is made. - -Input messages are capped at 100 KB and decoded media at 16 KB. Inbound media -must carry positive media.chunk values (strings or integers). Twilio remains -strictly sequential. Telnyx starts at chunk 1 and reorders within a configurable -window (":reorder_window", default 32), with a 64 KB aggregate byte cap -(":reorder_max_bytes"). First buffered copy wins; duplicates and already delivered -chunks are discarded. A missing chunk starts a non-extending 200 ms deadline -(":reorder_timeout_ms"). On timeout or overflow the connection closes with 1008 -and discards the buffer; it does not invent silence or splice across a gap. -Malformed payloads and wrong stream IDs also close. Timer tokens prevent stale -timeouts from affecting a recovered stream. Termination cancels timers. - -Outgoing PCMU is packetized into 160-byte (20 ms) messages, emitted at most once -per 20 ms timer tick. The local queue defaults to 500 packets (10 seconds), -configurable with :max_playout_packets; overflow closes rather than growing -without bound. Barge-in clears the local queue/filter tail, invalidates its timer, -and sends provider clear immediately. Timers never burst to catch up after delays. -Twilio permits arbitrary payload sizes and buffers media in arrival order; -Telnyx RTP mode permits 20 ms–30 s chunks. The once-per-second submission limit -in Telnyx's guide belongs to MP3 mode, which this transport does not use. - -Acknowledging a chunk means local acceptance, not playback at the handset. -Mark-based playout accounting, SIP, call creation/transfers and webhook handlers -remain application work. No live provider call has been tested. - -## RTVI control subset - -`AudioFlow.RTVI.WebSocket` can be mounted with the same `:session` options. It -accepts JSON control messages with `label: "rtvi-ai"`, a string `id`, and a -`type`. It negotiates RTVI major version 2 and advertises version `2.0.0`. - -```json -{"label":"rtvi-ai","id":"ready-1","type":"client-ready","data":{"version":"2.0.0","about":{"library":"my-client"}}} -{"label":"rtvi-ai","id":"text-1","type":"send-text","data":{"content":"Hello"}} -``` - -`client-ready` receives a `bot-ready` carrying the same ID. `send-text` runs an -immediate turn with audio, interrupting an active reply. Explicit -`run_immediately: false`, `audio_response: false`, unknown options and unsupported -messages receive an `error-response`; they are not silently treated as supported. -Generated text uses `llm-raw-text`. PCM is sent as Base64 `bot-tts-audio` with -`sample_rate` and `num_channels`. Interruption uses `bot-interrupted`; runtime -turn errors use `error` with `fatal: false`. These shapes follow the official -[RTVI message models](https://github.com/pipecat-ai/pipecat/blob/main/src/pipecat/processors/frameworks/rtvi/models.py) -inspected on 2026-11-03. The loopback tests contain request/response fixtures. - -A usable [Pipecat JavaScript client sample](../examples/rtvi-client/README.md) -now supplies an AudioFlow custom Transport subclass against the pinned official -SDK 1.16.0. Its executable test connects the real SDK to this real endpoint, -checks SDK-generated handshake/text, callback dispatch, PCM wire output, errors -and reconnect. Browser playback uses Web Audio with cancellation cleanup. -This does not make Daily/LiveKit/WebRTC or protobuf WebSocket transports work -unmodified. Microphone input, context mutation, tools, other client SDKs and -media-track UI components remain unsupported. Local Demo tests validate wire -behavior, not live inference, browser audio devices or acoustic quality. - -## Issue scope and remaining prerequisites - -- #5: raw PCM streaming WebSocket and optional ExWebRTC PCMU/VP8 publishing - plus a PCM Session bridge are implemented. This uses ExWebRTC directly rather - than the suggested Membrane Live.Capture/Live.Player wrapper. Local peer tests - cover negotiation and media; browser interoperability, TURN/NAT and production - loss/congestion handling remain unverified. See the WebRTC guide and - `examples/network` for setup and limits. -- #6: the requested Twilio/Telnyx PCMU serializer scope is implemented with - resampling, bounded input reordering, paced output and loopback tests. Live - carrier validation requires configured accounts/calls and a deployed endpoint. - SIP and call control were explicitly deferred in the original suggestion; - they need not block closure of the serializer request. -- #13: official JavaScript SDK works through the supplied custom transport for - text input and audio output. Rejected ready handshakes propagate the correlated - server error immediately; unrelated request errors do not reject negotiation. - Other SDKs, unmodified provider transports and full media/input coverage remain - outstanding, so broad SDK interoperability is not established. - -Avatar publication scope is documented separately in the -[WebRTC and LiveAvatar guide](webrtc-avatars.md). - -## Validation - -```sh -mix format --check-formatted -mix test -npm --prefix examples/rtvi-client ci -npm --prefix examples/rtvi-client run typecheck -npm --prefix examples/rtvi-client test -``` - -Core tests require no native media/ML libraries or provider credentials. Tests -exercise G.711 codewords, resampling chunk continuity and stop-band attenuation, -real loopback WebSocket upgrades for both provider envelopes, PCM session -input/output, barge-in clear, malformed input and stream lifecycle, plus the -RTVI handshake, text/audio events and correlated unsupported-message errors. -They do not establish live carrier interoperability, full SDK conformance or -perceived speech quality. - -## Standalone examples and application integration contract - -Run `MIX_ENV=test mix run examples/telephony-loopback.exs` from the repository -root for an executable Twilio/Telnyx start/media/stop demonstration. Telnyx sends -chunks 2, 2, 1 to exercise initial reordering and duplicate suppression. Both -paths verify six 160-byte outgoing packets over real loopback WebSockets. This -uses an explicitly test-only always-speech detector and silent Demo adapters. -It must not be used as a live-call speech detector. - -Applications integrating telephony must mount `AudioFlow.Telephony.WebSocket` -with a provider, real session adapters and a real 16 kHz detector. Authenticate -upgrades in the host Plug, choose the documented bidirectional provider settings, -and configure reorder/playout limits. Call creation, provider secrets and -signature validation belong to the host. The library owns one session per socket; -disconnect releases it. Provider mark acknowledgements are not handset latency -measurements in the current implementation. - -For application client views, import `AudioFlowTransport` from the standalone -sample and pass it to official `PipecatClient` with mic/camera disabled. Connect -from a user gesture, call `sendText`, display `onLlmRawText` and message errors, -and disconnect when leaving the view. Audio playback and interruption are -owned by the custom transport; do not attach SDK media-track components. -See the sample README for commands, authentication and unsupported capabilities. -These changes deliberately leave `examples/chat/**` and `ui/**` to their owning -app sessions. diff --git a/docs/webrtc-avatars.md b/docs/webrtc-avatars.md deleted file mode 100644 index 3fb4aff..0000000 --- a/docs/webrtc-avatars.md +++ /dev/null @@ -1,212 +0,0 @@ -# Optional encoded WebRTC and LiveAvatar publishing - -This adds partial implementations for #5 and #20. Neither issue is claimed fully -resolved. The raw PCM WebSocket transport and optional WebRTC Session bridge are separate paths. - -## Encoded WebRTC audio/video output prerequisite - -Set `AUDIOFLOW_WEBRTC=1` for both dependency resolution and execution: - -```sh -AUDIOFLOW_WEBRTC=1 mix deps.get -AUDIOFLOW_WEBRTC=1 mix test test/webrtc_test.exs -``` - -ExWebRTC 0.18 requires OpenSSL development headers, a C compiler and pkg-config. -Its SRTP dependency can download a native precompiled library. These are absent -from the default core dependency graph; `AUDIOFLOW_MEDIA` and `AUDIOFLOW_ML` are -independent. OpenSSL must match the major/minor ABI already loaded by Erlang. -This host uses OpenSSL 3.5.9 in Erlang; a temporary shell with OpenSSL 3.6.5 -compiled successfully but could not load the DTLS NIF. The successful local -build used the already installed matching development package: - -```sh -PKG_CONFIG_PATH=/nix/store/wps4g7kaj73d2zs53a5cfimw1bnb3c99-openssl-3.5.9-dev/lib/pkgconfig \ - AUDIOFLOW_WEBRTC=1 MIX_ENV=test mix deps.compile ex_dtls --force -AUDIOFLOW_WEBRTC=1 mix test test/webrtc_test.exs test/live_avatar_test.exs -``` - -The current Membrane dependencies implement file/camera decoding and PortAudio; -they do not include WebRTC. We inspected -[Membrane WebRTC 0.26.8](https://hexdocs.pm/membrane_webrtc_plugin/readme.html), -which wraps ExWebRTC, and use -[ExWebRTC 0.18](https://hexdocs.pm/ex_webrtc/ExWebRTC.PeerConnection.html) -directly to avoid pulling file/camera/PortAudio native plugins into a network -peer. This is not a `Membrane.WebRTC.Live.Player` or `Live.Capture` wrapper. - -```elixir -{:ok, peer} = AudioFlow.WebRTC.start_link(owner: self(), - ice_servers: [%{urls: "turn:turn.example.org", username: user, credential: secret}]) -{:ok, offer} = AudioFlow.WebRTC.offer(peer) -# Send offer over your authenticated signaling connection. -# Pass remote {"type":"answer","sdp":"..."} maps to signal/2. -# Relay {AudioFlow.WebRTC, peer, {:signal, message}} to the remote peer. -# Candidates use {"type":"candidate","candidate": browserCandidate.toJSON()}. -# Incoming offers automatically emit an answer through the same owner event. - -key = make_ref() -:ok = AudioFlow.WebRTC.start_turn(peer, key) -:ok = AudioFlow.WebRTC.publish(peer, key, :audio, encoded_pcmu_160_bytes, 20_000) -:ok = AudioFlow.WebRTC.publish(peer, key, :video, encoded_vp8_frame, 20_000) -:ok = AudioFlow.WebRTC.flush(peer, key) -AudioFlow.WebRTC.stop(peer) -``` - -Both outgoing tracks are created before negotiation. Audio is PCMU mono at -8 kHz, exactly 160 encoded bytes per 20 ms call. Video is VP8 at 90 kHz; frames -are fragmented into <=1200 byte RTP payloads with RFC 7741 start and last-packet -marker bits. Sequence numbers and 32-bit clock wrapping are maintained. PTS is -in microseconds on a shared epoch for the entire peer lifetime, monotonic per -track even across turns. The producer must pace frames; a timestamp is not a -scheduler. ExWebRTC handles ICE/DTLS/SRTP and RTCP, and forwards received track, -RTP and RTCP notifications to the owner as `{:media, event}`. An application must -consume these notifications promptly. A peer closes after a 15-second negotiation -deadline, failed connection, owner death or explicit stop. - -Local tests negotiate two real peers over host ICE and DTLS/SRTP and check -received packet payloads, clocks, fragmentation, cancellation keys and cleanup. -The VP8 fixture is a generated FFmpeg test pattern, and the test reassembles -its first encoded keyframe byte-for-byte after RTP reception. FFmpeg independently -decodes all three fixture frames locally; this is not browser interoperability. -For the encoded peer alone, scheduling and PCM conversion belong to its caller. -The optional Session bridge below supplies these plus bounded RTP reordering. -Remaining: browser signaling route/authentication, adaptive jitter buffering, congestion -adaptation, acoustic tests, browser interoperability and TURN/NAT deployment -validation. Flush rejects future stale-key calls; it cannot remove RTP already -accepted by ExWebRTC or rendered remotely. RTP acceptance is not playout ack. - -## LiveAvatar finite-utterance publication - -The [standalone server-backed browser viewer](../examples/avatar/README.md) -invokes this publisher with supplied 24 kHz PCM and subscribes to both provider -tracks using `livekit-client`. It defaults to no paid calls, keeps provider -secrets server-side, checks room-scoped subscription-only grants, and demonstrates -explicit start/cancel/disconnect and repeated finite sessions. Its opt-in viewer -readiness gate waits at most 15 seconds for both track subscriptions before PCM. -See its fixture-backed tests and live verification limits; live generation, -lip-sync, acoustics, account permissions and TURN are unverified. - -The adapter uses maintained LiveAvatar LITE, not the sunset HeyGen Streaming -Avatar API. Protocol references checked on 2026-11-03: - -- [Create session token](https://docs.liveavatar.com/api-reference/sessions/create-session-token) -- [Start session](https://docs.liveavatar.com/api-reference/sessions/start-session) -- [LITE events](https://docs.liveavatar.com/docs/lite-mode/events) -- [Stop session](https://docs.liveavatar.com/api-reference/sessions/stop-session) - -```elixir -{:ok, publisher} = AudioFlow.Avatars.LiveAvatar.start_link( - owner: self(), api_key: fn -> System.fetch_env!("LIVEAVATAR_API_KEY") end, - avatar_id: avatar_id, - audio: %AudioFlow.Audio{data: pcm, sample_rate: 24_000}) -# Receives {LiveAvatar, publisher, {:published, %{url: livekit_url, token: token}}} -# Subscribe an authorized LiveKit client to the room's audio AND video tracks. -# The provider generates and publishes the synchronized tracks; do not also play PCM. -# Receives {:done, :ok | {:error, reason}} then {:cleanup, result} in that envelope. -AudioFlow.Avatars.LiveAvatar.cancel(publisher) -``` - -One publisher creates one session for one finite utterance of at most ten seconds -of mono PCM16LE at 24 kHz. It waits for the media socket's connected event before -sending <=one-second base64 chunks, then seals the utterance with `speak_end`. -The UUID correlates completion events; unrelated completion cannot end the turn. -A 60-second deadline bounds media work. Cancellation kills the caller-owned -socket worker and requests remote session stop. Owner exit and provider errors -also clean up. Cleanup failures are reported; remote termination cannot be -promised when the service is unavailable. Tokens are never logged by the module; -keep owner events private. `:endpoint` exists for local HTTP fixtures. - -The local fixture verifies real HTTP and WebSocket exchange, PCM chunking, -readiness, correlation, completion and cancellation cleanup. **No credentials -were available:** actual avatar availability, account billing/permissions, -LiveKit subscription, generated A/V, lip-sync, end-to-end latency and live remote -cleanup remain unverified. This implementation requests actual provider A/V -publication; it does not implement a LiveKit receiver/relay into the separate -ExWebRTC peer, continuous multi-turn Session output or local avatar rendering. -Use the standalone viewer above or a LiveKit client in the host application to receive the provider tracks. - -For example, a host application's JavaScript client with the optional -`livekit-client` package can subscribe to the returned publication: - -```javascript -import {Room, RoomEvent} from "livekit-client"; -const room = new Room(); -room.on(RoomEvent.TrackSubscribed, (track) => { - // Attach both audio and video, preserving LiveKit's synchronized playout. - document.querySelector("#avatar").append(track.attach()); -}); -await room.connect(publication.url, publication.token); -await room.startAudio(); // call from a user gesture if autoplay is blocked -// On leaving the view: await room.disconnect(); cancel the server publisher too. -``` - -## PCM Session bridge (optional WebRTC feature) - -`AudioFlow.WebRTC.Session` now connects real Session PCM output and VoiceInput -utterances to the encoded peer. The core feature flags/dependency graph remain -unchanged. Run a credential-free standalone exercise: - -```sh -AUDIOFLOW_WEBRTC=1 mix run examples/network/voice_agent.exs -AUDIOFLOW_WEBRTC=1 mix test test/webrtc_session_test.exs test/webrtc_test.exs -``` - -The example explicitly labels **SYNTHETIC DEMO** output: its energy gate detects -an injected tone, while `Adapters.Demo` returns fixed text and silent PCM, not -speech recognition or synthesized speech. It negotiates two real local peers, -submits the decoded utterance to Session and receives six PCMU reply packets. -`publish.exs` continues to exercise independent encoded audio/video publishing. - -For a host integration, supply real adapters and a 16 kHz VoiceDetector: - -```elixir -alias AudioFlow.WebRTC.Session, as: VoicePeer -{:ok, bridge} = VoicePeer.start_link(owner: self(), session: session_options, - vad: {MyVoiceDetector, detector_options}, - voice_input: [min_speech_ms: 96, min_silence_ms: 320], - max_queue_packets: 100, reorder_window: 32, gap_timeout_ms: 200) -{:ok, offer} = VoicePeer.offer(bridge) -# Send offer through your signaling channel. Route remote JSON maps explicitly: -:ok = VoicePeer.signal(bridge, remote_answer_or_candidate) -# Relay {VoicePeer, bridge, {:signal, message}} back to this same remote endpoint. -# Incoming offers are also supported; the answer is emitted through that event. -# Receive {VoicePeer, bridge, {:session, turn, event}} for text/transcript/PCM. -# Audio events are generated PCM, not a second playback path or played audio. -VoicePeer.cancel(bridge) -VoicePeer.stop(bridge) -``` - -The owner must authenticate/authorize its signaling route. There is no implicit -peer discovery or globally registered signaling destination. The bridge accepts -one audio track negotiated as PCMU/8000 mono, RTP payload type 0, 160 bytes per -20 ms, no RID. Other audio formats/packet durations are unsupported. Sequence -and timestamp wrap are supported; up to 32 future packets wait at most 200 ms -for gaps. Stale/duplicate sequence numbers are discarded; persistent loss, -changed SSRC, unexpected tracks, invalid packet length, timestamp discontinuity -or excessive reordering closes the bridge and its Session/output/peer. No loss -concealment or adaptive jitter buffering is claimed. Video is not a Session input. - -Ingress uses the telephony μ-law codec and stateful 8→16 kHz interpolation, then -VoiceInput emits actual submitted utterances. Confirmed speech cancels the -previous turn/output before endpoint submission. Egress accepts mono PCM16LE -at 8 or 16 kHz (the latter uses the telephony low-pass decimator), preserving -filter state across chunks. Other rates and mid-turn format changes fail the -turn. Final filter tail and partial packets are padded with silence. Queue size -is bounded (100 packets by default, configurable 1–1500); overflow fails rather -than accumulating unbounded delay. Producers should stream small PCM chunks. - -Output is sent one packet per 20 ms without catch-up bursts. `finish` seals and -asynchronously drains the queue, allowing Session to remain responsive to cancel. -A Session `done` event means generation finished, not delivery or remote playout. -Cancel/timeout/stale keys clear unsent media, resampler/pending bytes and timers; -RTP already accepted by the peer cannot be recalled. The RTP clock remains -monotonic across turns. No Output acknowledgement is emitted, so playback-aware -history cannot claim unheard replies were heard. Session owner, peer, Session -or transport exit tears down the complete bridge. - -Tests cover local two-peer host ICE/DTLS/SRTP, transcript/text/audio routing, -byte-exact codec/rate conversion, RTP clocks, reordering/wrap, gap deadlines, -queue limits, barge-in/stale output, Session timeout and owner cleanup. Remaining: -browser signaling/client UI and interoperability, production signaling auth, -acoustic/AEC quality, congestion adaptation, packet-loss concealment, NAT/TURN -validation and live inference. These are not claimed by the local tests. diff --git a/examples/chat/README.md b/examples/chat/README.md index 668f0f0..708927c 100644 --- a/examples/chat/README.md +++ b/examples/chat/README.md @@ -284,7 +284,7 @@ Export credentials in the server shell before `mix phx.server`: Missing variables produce a visible error and keep the existing chat active. Provider account/model/voice availability must be checked with your account. -See [provider contracts](../../docs/providers.md). The chained pipeline supports +See [provider contracts](https://flowcopilot.github.io/audioflow/docs/features/providers/). The chained pipeline supports text and microphone messages with text history. Gemini speech-to-speech accepts only committed microphone utterances, opens a fresh provider connection each turn, and has **no history replay**. OpenAI live conversation is described above. The language control applies only to the remote diff --git a/examples/network/README.md b/examples/network/README.md index 9bcef71..daae4fd 100644 --- a/examples/network/README.md +++ b/examples/network/README.md @@ -15,7 +15,7 @@ completes DTLS, and sends paced PCMU silence plus encoded VP8 frames over SRTP. The receiver counts audio packets and completed video frames, then both peers close. Expected bundled-fixture result: **21 PCMU packets, 3 VP8 frames**. This is a terminal loopback example; it does not display video or open a server. -OpenSSL headers/ABI setup is covered in [the integration guide](../../docs/webrtc-avatars.md). +OpenSSL headers/ABI setup is covered in [the integration guide](https://flowcopilot.github.io/audioflow/docs/features/webrtc-avatars/). The included test pattern is generated without user media: diff --git a/examples/rtvi-client/README.md b/examples/rtvi-client/README.md index 08d8575..1b18971 100644 --- a/examples/rtvi-client/README.md +++ b/examples/rtvi-client/README.md @@ -19,7 +19,7 @@ control event. No speech quality or live inference claim follows from Demo PCM. ## Run From this directory: `npm ci`, then `npm run sample`. Enter the WSS URL of a -host-mounted `AudioFlow.RTVI.WebSocket` endpoint (see `docs/transports.md`). Use +host-mounted `AudioFlow.RTVI.WebSocket` endpoint (see [network transports](https://flowcopilot.github.io/audioflow/docs/features/transports/)). Use host-owned session adapters and authenticate the HTTP upgrade before allocating a session. Browser WebSocket uses cookies or another host-authorized mechanism; it cannot set arbitrary authentication headers. The Vite page is a development diff --git a/lib/audio_flow/adapters/cartesia.ex b/lib/audio_flow/adapters/cartesia.ex index 3e4fc0a..a858c93 100644 --- a/lib/audio_flow/adapters/cartesia.ex +++ b/lib/audio_flow/adapters/cartesia.ex @@ -1,5 +1,8 @@ defmodule AudioFlow.Adapters.Cartesia do - @moduledoc "Cartesia streaming HTTP bytes TTS (raw s16le PCM). See docs/providers.md." + @moduledoc """ + Cartesia streaming HTTP bytes TTS (raw s16le PCM). See + https://flowcopilot.github.io/audioflow/docs/features/providers/. + """ @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.PCMHTTP alias AudioFlow.Adapters.Providers.Socket diff --git a/lib/audio_flow/adapters/chat_http.ex b/lib/audio_flow/adapters/chat_http.ex deleted file mode 100644 index b032d0e..0000000 --- a/lib/audio_flow/adapters/chat_http.ex +++ /dev/null @@ -1,65 +0,0 @@ -defmodule AudioFlow.Adapters.ChatHTTP do - @moduledoc """ - Deprecated chat-completions configuration shim. Use `AudioFlow.Adapters.ReqLLM` - with ReqLLM model/context/options directly. No HTTP protocol is implemented here. - """ - @behaviour AudioFlow.Adapter - - alias AudioFlow.Adapters.ReqLLM - - @impl AudioFlow.Adapter - def with_context(options, context) do - context = Map.merge(Keyword.get(options, :tool_context, %{}), context) - Keyword.put(options, :tool_context, context) - end - - @impl true - def run(input, options, emit) do - endpoint = Keyword.fetch!(options, :endpoint) - uri = URI.parse(endpoint) - - if uri.scheme not in ["http", "https"] or uri.host == nil or uri.userinfo != nil, - do: raise(ArgumentError, "endpoint must be an HTTP or HTTPS URL without user information") - - parameters = - Keyword.get(options, :parameters, %{}) |> Map.new(fn {k, v} -> {to_string(k), v} end) - - parameters = Map.drop(parameters, ["stream", "n"]) - - unsupported = - Map.keys(Map.drop(parameters, ["max_tokens", "max_completion_tokens", "temperature"])) - - if unsupported != [], - do: - raise( - ArgumentError, - "unsupported legacy parameters #{Enum.join(Enum.sort(unsupported), ", ")}; " <> - "use AudioFlow.Adapters.ReqLLM generation options directly" - ) - - key = - case options[:api_key] do - fun when is_function(fun, 0) -> fun.() - key -> key || "local" - end - - opts = [ - model: %{provider: :openai, id: Keyword.fetch!(options, :model)}, - base_url: String.replace_suffix(endpoint, "/chat/completions", ""), - api_key: key, - system_prompt: Keyword.get(options, :system, AudioFlow.Prompt.default_system()), - max_tokens: - Map.get(parameters, "max_completion_tokens", Map.get(parameters, "max_tokens", 128)), - req_http_options: [headers: Keyword.get(options, :headers, [])], - audio_flow: - Keyword.drop(options, [:endpoint, :model, :api_key, :system, :parameters, :headers]) - ] - - opts = - if parameters["temperature"], - do: Keyword.put(opts, :temperature, parameters["temperature"] * 1.0), - else: opts - - ReqLLM.run(input, opts, emit) - end -end diff --git a/lib/audio_flow/adapters/eleven_labs.ex b/lib/audio_flow/adapters/eleven_labs.ex index eee70da..859dbf6 100644 --- a/lib/audio_flow/adapters/eleven_labs.ex +++ b/lib/audio_flow/adapters/eleven_labs.ex @@ -1,5 +1,8 @@ defmodule AudioFlow.Adapters.ElevenLabs do - @moduledoc "ElevenLabs streaming HTTP TTS (raw s16le PCM). See docs/providers.md." + @moduledoc """ + ElevenLabs streaming HTTP TTS (raw s16le PCM). See + https://flowcopilot.github.io/audioflow/docs/features/providers/. + """ @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.PCMHTTP alias AudioFlow.Adapters.Providers.Socket diff --git a/lib/audio_flow/adapters/fish_audio.ex b/lib/audio_flow/adapters/fish_audio.ex index bd75ae9..49d01b2 100644 --- a/lib/audio_flow/adapters/fish_audio.ex +++ b/lib/audio_flow/adapters/fish_audio.ex @@ -8,7 +8,9 @@ defmodule AudioFlow.Adapters.FishAudio do (a string or zero-argument function), for servers started with `--api-key`. Blank reference IDs are omitted. `:receive_timeout_ms` defaults to `:timeout_ms` (30 seconds), and can be set independently for slow or cold servers. - See `docs/providers.md` for setup and shared HTTP limits. + See + https://flowcopilot.github.io/audioflow/docs/features/providers/ + for setup and shared HTTP limits. """ @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.PCMHTTP diff --git a/lib/audio_flow/adapters/fish_audio_api.ex b/lib/audio_flow/adapters/fish_audio_api.ex index b4df8ba..027cdd9 100644 --- a/lib/audio_flow/adapters/fish_audio_api.ex +++ b/lib/audio_flow/adapters/fish_audio_api.ex @@ -10,7 +10,9 @@ defmodule AudioFlow.Adapters.FishAudioAPI do `:receive_timeout_ms` defaults to `:timeout_ms` (30 seconds). For a self-hosted Fish Speech server, use `AudioFlow.Adapters.FishAudio`. - See `docs/providers.md` for configuration and shared HTTP bounds. + See + https://flowcopilot.github.io/audioflow/docs/features/providers/ + for configuration and shared HTTP bounds. """ @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.PCMHTTP diff --git a/lib/audio_flow/adapters/gemini_live.ex b/lib/audio_flow/adapters/gemini_live.ex index c480ae4..a4469c8 100644 --- a/lib/audio_flow/adapters/gemini_live.ex +++ b/lib/audio_flow/adapters/gemini_live.ex @@ -2,7 +2,8 @@ defmodule AudioFlow.Adapters.GeminiLive do @moduledoc """ One committed audio turn over Gemini Live v1beta WebSocket. Direct callers receive transcript/text deltas and Audio tuples, like OpenAIRealtime. - Use directly or in Session `:speech_to_speech`; see docs/providers.md. + Use directly or in Session `:speech_to_speech`; see + https://flowcopilot.github.io/audioflow/docs/features/providers/. """ @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.Socket diff --git a/lib/audio_flow/adapters/openai_realtime.ex b/lib/audio_flow/adapters/openai_realtime.ex index ca3e126..f7ff742 100644 --- a/lib/audio_flow/adapters/openai_realtime.ex +++ b/lib/audio_flow/adapters/openai_realtime.ex @@ -3,7 +3,9 @@ defmodule AudioFlow.Adapters.OpenAIRealtime do One committed audio turn over OpenAI's GA Realtime WebSocket protocol. `run/3` emits `{:transcript, text}`, `{:text, delta}`, `{:audio, Audio}`. Use directly or in Session `:speech_to_speech`, never an STT/LLM/TTS slot. - See docs/providers.md for options and integration limits. + See + https://flowcopilot.github.io/audioflow/docs/features/providers/ + for options and integration limits. """ @behaviour AudioFlow.Adapter alias AudioFlow.Adapters.Providers.Socket diff --git a/lib/audio_flow/application.ex b/lib/audio_flow/application.ex index 9101652..b837b36 100644 --- a/lib/audio_flow/application.ex +++ b/lib/audio_flow/application.ex @@ -13,7 +13,6 @@ defmodule AudioFlow.Application do name: AudioFlow.HTTPClient, pools: %{default: [protocols: [:http1], conn_opts: [transport_opts: [timeout: 5_000]]]}}, {Task.Supervisor, name: AudioFlow.Tasks}, - AudioFlow.Jido, {DynamicSupervisor, name: AudioFlow.Sessions, strategy: :one_for_one} ] ++ Application.get_env(:audio_flow, :inference_children, []) diff --git a/lib/audio_flow/graph.ex b/lib/audio_flow/graph.ex index f0707dc..b75902c 100644 --- a/lib/audio_flow/graph.ex +++ b/lib/audio_flow/graph.ex @@ -8,9 +8,9 @@ defmodule AudioFlow.Graph do "nodes" => [ %{"id" => "mic", "type" => "input.audio"}, %{"id" => "stt", "type" => "demo.stt"}, - %{"id" => "llm", "type" => "llm.chat_http", - "options" => %{"endpoint" => "http://localhost:8080/v1/chat/completions", - "model" => "qwen3"}}, + %{"id" => "llm", "type" => "llm.req_llm", + "options" => %{"model" => "openai:qwen3", + "base_url" => "http://localhost:8080/v1"}}, %{"id" => "tts", "type" => "demo.tts"} ], "edges" => [ @@ -37,7 +37,7 @@ defmodule AudioFlow.Graph do alias AudioFlow.Graph.Nodes alias AudioFlow.Graph.OptionSchema - @default_nodes [Nodes.Input, Nodes.Audio, Nodes.Demo, Nodes.ChatHTTP, Nodes.RAG] + @default_nodes [Nodes.Input, Nodes.Audio, Nodes.Demo, Nodes.ReqLLM, Nodes.RAG] @kinds [:audio, :image, :text, :vector] @events [:transcript, :description, :text, :audio, :image, :vector] @settings %{ diff --git a/lib/audio_flow/graph/nodes/chat_http.ex b/lib/audio_flow/graph/nodes/chat_http.ex deleted file mode 100644 index 2381385..0000000 --- a/lib/audio_flow/graph/nodes/chat_http.ex +++ /dev/null @@ -1,101 +0,0 @@ -defmodule AudioFlow.Graph.Nodes.ChatHTTP do - @moduledoc "ReqLLM inference nodes, including the deprecated chat-completions configuration node." - @behaviour AudioFlow.Graph.Node - - @impl true - def nodes do - [ - %{ - type: "llm.chat_http", - title: "Chat completions LLM (deprecated)", - description: "A compatible local server or cloud endpoint.", - input: :text, - output: :text, - history: true, - options: [ - %{name: :endpoint, type: :string, required: true, description: "Chat-completions URL."}, - %{name: :model, type: :string, required: true, description: "Model name."}, - %{name: :system, type: :string, description: "System instruction."}, - %{ - name: :tools_profile, - type: :string, - description: "Trusted chat tool profile in application configuration." - }, - %{ - name: :api_key_env, - type: :string, - description: "Name of the environment variable with the API key." - }, - %{name: :timeout_ms, type: :integer, default: 30_000, description: "Request deadline."} - ] - } - ] ++ - [ - %{ - type: "llm.req_llm", - title: "ReqLLM", - description: "HTTP LLM inference using ReqLLM models and options.", - input: :text, - output: :text, - history: true, - options: [ - %{ - name: :model, - type: :string, - required: true, - description: "ReqLLM provider:model specification." - }, - %{ - name: :base_url, - type: :string, - description: "Provider base URL, for example http://localhost:8080/v1." - }, - %{name: :system_prompt, type: :string, description: "System instruction."}, - %{name: :api_key_env, type: :string, description: "API key environment variable."}, - %{name: :tools_profile, type: :string, description: "Trusted Jido tool profile."}, - %{ - name: :timeout_ms, - type: :integer, - default: 30_000, - description: "Request deadline." - } - ] - } - ] - end - - def adapter("llm.req_llm", options) do - tools = - if profile = options[:tools_profile], - do: Map.fetch!(Application.get_env(:audio_flow, :chat_tool_profiles, %{}), profile), - else: [] - - key = if env = options[:api_key_env], do: System.get_env(env), else: nil - opts = [model: options.model, audio_flow: [tools: tools, timeout_ms: options.timeout_ms]] - - opts = - Enum.reduce([:base_url, :system_prompt], opts, fn name, opts -> - if value = options[name], do: Keyword.put(opts, name, value), else: opts - end) - - {AudioFlow.Adapters.ReqLLM, if(key, do: Keyword.put(opts, :api_key, key), else: opts)} - end - - @impl true - def adapter("llm.chat_http", options) do - # The graph stores the variable name, never the key. - api_key = if env = options[:api_key_env], do: fn -> System.get_env(env) end - - adapter_options = - [endpoint: options.endpoint, model: options.model, timeout_ms: options.timeout_ms] ++ - if(options[:system], do: [system: options.system], else: []) ++ - if(api_key, do: [api_key: api_key], else: []) - - tools = - if profile = options[:tools_profile], - do: Map.fetch!(Application.get_env(:audio_flow, :chat_tool_profiles, %{}), profile), - else: [] - - {AudioFlow.Adapters.ChatHTTP, Keyword.put(adapter_options, :tools, tools)} - end -end diff --git a/lib/audio_flow/graph/nodes/req_llm.ex b/lib/audio_flow/graph/nodes/req_llm.ex new file mode 100644 index 0000000..e815c9d --- /dev/null +++ b/lib/audio_flow/graph/nodes/req_llm.ex @@ -0,0 +1,56 @@ +defmodule AudioFlow.Graph.Nodes.ReqLLM do + @moduledoc "ReqLLM inference nodes: the `llm.req_llm` node, run by `AudioFlow.Adapters.ReqLLM`." + @behaviour AudioFlow.Graph.Node + + @impl true + def nodes do + [ + %{ + type: "llm.req_llm", + title: "ReqLLM", + description: "HTTP LLM inference using ReqLLM models and options.", + input: :text, + output: :text, + history: true, + options: [ + %{ + name: :model, + type: :string, + required: true, + description: "ReqLLM provider:model specification." + }, + %{ + name: :base_url, + type: :string, + description: "Provider base URL, for example http://localhost:8080/v1." + }, + %{name: :system_prompt, type: :string, description: "System instruction."}, + %{name: :api_key_env, type: :string, description: "API key environment variable."}, + %{name: :tools_profile, type: :string, description: "Trusted Jido tool profile."}, + %{name: :timeout_ms, type: :integer, default: 30_000, description: "Request deadline."} + ] + } + ] + end + + @impl true + def adapter("llm.req_llm", options) do + key = if env = options[:api_key_env], do: System.get_env(env), else: nil + tools = if profile = options[:tools_profile], do: profile_tools(profile), else: [] + + opts = [ + model: options.model, + audio_flow: [tools: tools, timeout_ms: options.timeout_ms] + ] + + opts = + Enum.reduce([:base_url, :system_prompt], opts, fn name, opts -> + if value = options[name], do: Keyword.put(opts, name, value), else: opts + end) + + {AudioFlow.Adapters.ReqLLM, if(key, do: Keyword.put(opts, :api_key, key), else: opts)} + end + + defp profile_tools(profile), + do: Map.fetch!(Application.get_env(:audio_flow, :chat_tool_profiles, %{}), profile) +end diff --git a/lib/audio_flow/jido.ex b/lib/audio_flow/jido.ex deleted file mode 100644 index 379e9e9..0000000 --- a/lib/audio_flow/jido.ex +++ /dev/null @@ -1,7 +0,0 @@ -defmodule AudioFlow.Jido do - @moduledoc """ - Runs Jido agents under the AudioFlow supervision tree. - """ - - use Jido, otp_app: :audio_flow -end diff --git a/lib/audio_flow/rtvi/web_socket.ex b/lib/audio_flow/rtvi/web_socket.ex index 49d8369..216bc72 100644 --- a/lib/audio_flow/rtvi/web_socket.ex +++ b/lib/audio_flow/rtvi/web_socket.ex @@ -3,7 +3,8 @@ defmodule AudioFlow.RTVI.WebSocket do RTVI 2.x control-message subset over WebSock: client-ready, send-text, llm-raw-text, bot-tts-audio, bot-interrupted, and errors. This endpoint is for custom transports; it does not implement Daily/LiveKit signaling or - Pipecat's protobuf WebSocket media framing. See `docs/transports.md`. + Pipecat's protobuf WebSocket media framing. See + https://flowcopilot.github.io/audioflow/docs/features/transports/. """ @behaviour WebSock alias AudioFlow.Transport.Connection diff --git a/lib/audio_flow/smart_turn.ex b/lib/audio_flow/smart_turn.ex index cefc373..634f6c6 100644 --- a/lib/audio_flow/smart_turn.ex +++ b/lib/audio_flow/smart_turn.ex @@ -5,7 +5,8 @@ defmodule AudioFlow.SmartTurn do No downloads occur at runtime. Pass `{AudioFlow.SmartTurn, worker: pid}` as VoiceInput's `:turn_detector`. Inference receives only the last eight seconds at 16 kHz and returns the model's completion probability. See the pinned - model and dependency installation instructions in `docs/input-processing.md`. + model and dependency installation instructions in + https://flowcopilot.github.io/audioflow/docs/features/input-processing/. """ alias AudioFlow.Audio alias AudioFlow.PacketWorker diff --git a/lib/audio_flow/speex_dsp.ex b/lib/audio_flow/speex_dsp.ex index c2b2ec9..73961cc 100644 --- a/lib/audio_flow/speex_dsp.ex +++ b/lib/audio_flow/speex_dsp.ex @@ -7,7 +7,8 @@ defmodule AudioFlow.SpeexDSP do Pass `{AudioFlow.SpeexDSP, worker: pid}` as VoiceInput's `:preprocessor`. A missing reference means silence; cancellation requires synchronized reference samples via `VoiceInput.push/3`. Native failure raises rather than silently - passing unfiltered audio to VAD. See `docs/input-processing.md`. + passing unfiltered audio to VAD. See + https://flowcopilot.github.io/audioflow/docs/features/input-processing/. """ alias AudioFlow.Audio alias AudioFlow.PacketWorker diff --git a/lib/audio_flow/telemetry.ex b/lib/audio_flow/telemetry.ex index e15bee1..fe05513 100644 --- a/lib/audio_flow/telemetry.ex +++ b/lib/audio_flow/telemetry.ex @@ -33,7 +33,7 @@ defmodule AudioFlow.Telemetry do `[:audio_flow, :stage, :start | :stop | :exception]` is a `:telemetry.span/3` around each adapter call, in the turn task. Metadata is `%{session, turn, stage, adapter}`. `stage` is `:stt`, `:vision`, `:llm`, or `:tts`. In a graph - session it is the node type, such as `"llm.chat_http"`, and `:node` is the + session it is the node type, such as `"llm.req_llm"`, and `:node` is the node id. TTS runs once per text chunk, inside the LLM stage. An adapter error, an exception, or a downstream failure emits `:exception` with `:kind` and diff --git a/lib/audio_flow/telephony/web_socket.ex b/lib/audio_flow/telephony/web_socket.ex index cdaf078..83c4401 100644 --- a/lib/audio_flow/telephony/web_socket.ex +++ b/lib/audio_flow/telephony/web_socket.ex @@ -3,7 +3,9 @@ defmodule AudioFlow.Telephony.WebSocket do Twilio Media Streams and Telnyx PCMU WebSock endpoint. Requires `:provider` (`:twilio` or `:telnyx`), `:session` options and a 16 kHz `:vad` detector. Authenticate the upgrade in the host Plug before calling WebSockAdapter. - See `docs/transports.md` for provider configuration and limits. + See + https://flowcopilot.github.io/audioflow/docs/features/transports/ + for provider configuration and limits. """ @behaviour WebSock alias AudioFlow.Telephony.MuLaw diff --git a/lib_media/audio_flow/adapters/moshi.ex b/lib_media/audio_flow/adapters/moshi.ex index 4b50f34..7d3d21e 100644 --- a/lib_media/audio_flow/adapters/moshi.ex +++ b/lib_media/audio_flow/adapters/moshi.ex @@ -6,7 +6,8 @@ defmodule AudioFlow.Adapters.Moshi do `run/3` emits `{:text, delta}` and `{:audio, Audio}` like `OpenAIRealtime`. Moshi does not transcribe the user, so there is no `:transcript` event. - Use directly or in Session `:speech_to_speech`; see docs/providers.md. + Use directly or in Session `:speech_to_speech`; see + https://flowcopilot.github.io/audioflow/docs/features/providers/. Moshi is full duplex and has no end-of-turn signal. For continuous microphone input with simultaneous output, use `AudioFlow.Duplex` with diff --git a/priv/audio_flow/smart_turn.py b/priv/audio_flow/smart_turn.py index 04c023a..8a3e42a 100644 --- a/priv/audio_flow/smart_turn.py +++ b/priv/audio_flow/smart_turn.py @@ -33,7 +33,7 @@ def main(): digest = hashlib.file_digest(model_file, "sha256").hexdigest() if digest != "fb68d55c2d542ce79e44b12013bfd571e90df8594ab096d757198e851b0c6594": raise ValueError( - "expected pinned smart-turn-v3.1-cpu.onnx; see docs/input-processing.md" + "expected pinned smart-turn-v3.1-cpu.onnx; see https://flowcopilot.github.io/audioflow/docs/features/input-processing/" ) options = ort.SessionOptions() options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL diff --git a/site/src/content/docs/docs/chat-example.md b/site/src/content/docs/docs/chat-example.md index 7e1b89e..2befefc 100644 --- a/site/src/content/docs/docs/chat-example.md +++ b/site/src/content/docs/docs/chat-example.md @@ -8,6 +8,16 @@ tab. Type a message, or record one with the microphone. While you record, the user message shows a live transcript. The reply text streams into the conversation, and the reply audio plays as it arrives. +The app also exposes server-configured speech providers, languages, redacted +recordings, playback progress, and provisional pause/resume. Its Linux demo needs +no model download. + +Its always-on modes use `AudioFlow.Duplex` with OpenAI Realtime or a local Moshi +server. The microphone stays open from Start to Stop, and the model audio plays at +the same time. OpenAI detects each utterance, replies by voice, and stops the reply +when you speak. See [Remote speech providers](../features/providers/#continuous-openai-realtime-conversation) +for the duplex adapters. + The models run on the Apple Silicon GPU through MLX. This example needs an Apple Silicon Mac with macOS 26.2 or later. diff --git a/site/src/content/docs/docs/features/providers.md b/site/src/content/docs/docs/features/providers.md index 7098acc..f6edbc3 100644 --- a/site/src/content/docs/docs/features/providers.md +++ b/site/src/content/docs/docs/features/providers.md @@ -200,6 +200,10 @@ required export/operator works. Drama 3 needs its own architecture assessment. ## Direct speech-to-speech calls +These calls send one committed utterance per connection. For an always-on +OpenAI conversation with the microphone open, use +[`AudioFlow.Duplex.OpenAIRealtime`](#continuous-openai-realtime-conversation). + `AudioFlow.Adapters.OpenAIRealtime.run/3` and `AudioFlow.Adapters.GeminiLive.run/3` accept a committed `AudioFlow.Audio` and invoke an arity-one callback with `{:transcript, text}`, `{:text, delta}` and @@ -280,7 +284,197 @@ explicit typed event ports (transcript, text and audio), routing/validation for each, and a dedicated history capability contract. Registering either adapter as an existing STT/LLM/TTS node would misrepresent its contract. Use the explicit Session mode or direct API today. There is no continuous duplex input, tool -execution, automatic reconnect, resampling or WebRTC in this mode. +execution, automatic reconnect, resampling or WebRTC in this mode. For +continuous input, see `AudioFlow.Duplex` below. + +## Local Moshi speech-to-speech + +`AudioFlow.Adapters.Moshi` runs one committed turn against a local +[Kyutai Moshi](https://github.com/kyutai-labs/moshi) server. Moshi is a 7B +full-duplex model. The 4-bit MLX build needs approximately 5 GB of weights and +runs on an Apple Silicon laptop. The adapter needs `AUDIOFLOW_MEDIA=1`, because +it uses `membrane_opus_plugin` for Opus and `membrane_ogg_plugin` for Ogg pages. + +Start the server (Python 3.12, approximately 5 GB download on first start): + +```sh +uvx --python 3.12 --from moshi_mlx python -m moshi_mlx.local_web \ + -q 4 --hf-repo kyutai/moshika-mlx-q4 --no-browser --port 8998 +``` + +Use the adapter with 24 kHz input: + +```elixir +{:ok, session} = AudioFlow.start_session( + speech_to_speech: {AudioFlow.Adapters.Moshi, [endpoint: "ws://127.0.0.1:8998/api/chat"]}, + timeout_ms: 60_000) +``` + +The wire protocol is binary WebSocket messages with a one-byte kind: `0` +handshake, `1` Ogg Opus audio (24 kHz mono), `2` UTF-8 text tokens. The adapter +sends the input as 80 ms Ogg pages of four 20 ms Opus packets, then silence. It +sends one silent frame for each output frame, so the model sets the pace, not +the wall clock. Output for the input period is dropped. + +Moshi has no end-of-turn signal. The reply ends after `:end_silence_ms` (1,600) +of model output without a text token. The turn fails with `:no_reply` if +`:max_reply_ms` (20,000) passes without text. The default `:timeout_ms` is +60,000. Moshi does not transcribe the user, so there is no `:transcript` event. + +Limits: + +- The server serves one connection at a time. A second turn waits for the lock. +- Model state continues across connections. The server does not reset context + between turns, and the adapter cannot clear it. +- The first turn after server start is slow (approximately 13 s on an M5) while + MLX warms up. Later turns gave the first reply audio approximately 2 s after + submit for a 3.2 s question. +- Moshi speaks English only. +- The adapter calls the Opus `Native` modules and the Ogg `Page`, `Parser` and + `Opus` modules directly, not through Membrane pipeline elements. The + `Membrane.Ogg.Muxer` element holds packets until a page has 255 segments + (approximately 5 s), which is too slow for a duplex model. These modules are + internal to the plugins, so the dependencies are pinned to `~> 0.21.0` and + `~> 0.5.2`. + +To check a running server, convert a question to raw 24 kHz PCM and run: + +```sh +AUDIOFLOW_MEDIA=1 AUDIOFLOW_HTTP_MODEL_TESTS=1 \ +AUDIOFLOW_MOSHI_PCM=question.s16le mix test test/moshi_test.exs +``` + +`AUDIOFLOW_MOSHI_ENDPOINT` overrides the default endpoint. + +### Continuous full-duplex Moshi + +`AudioFlow.Duplex` keeps one Moshi connection open. Microphone input and model +output flow at the same time. There is no committed turn, no end-of-turn +detection, no silence gate, and no output drop while the user speaks. Use it +for a live conversation. Use `AudioFlow.Adapters.Moshi` for one committed turn. + +```elixir +{:ok, duplex} = + AudioFlow.Duplex.start_link( + owner: self(), + adapter: {AudioFlow.Duplex.Moshi, endpoint: "ws://127.0.0.1:8998/api/chat"}) + +# Wait for {AudioFlow.Duplex, ^duplex, :ready}, then push 80 ms chunks: +:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm_3840_bytes, sample_rate: 24_000}) +:ok = AudioFlow.Duplex.stop(duplex) +``` + +`start_link/1` returns before the connection opens. The owner receives +`{AudioFlow.Duplex, pid, event}`, where `event` is `:ready` (after the Moshi +handshake), `{:audio, %AudioFlow.Audio{}}`, `{:text, token}`, +`{:error, reason}` or `:closed`. `:closed` comes last, also after an error. +`push/2` returns `{:error, :not_ready}` before `:ready` and `{:error, :closed}` +after the session stops. Keep the endpoint in server configuration; the browser +does not need it. + +`start/1` starts an unlinked session with the same API. Use it when the owner +must also survive an unexpected adapter crash, as the chat UI does. Monitor +the returned process to detect these crashes. Both start functions monitor +the owner and close the connection when it exits. + +The adapter sends each complete 80 ms frame (3,840 bytes at 24 kHz) as one Ogg +page at once. A shorter remainder waits for the next push. Moshi answers each +input frame with one output frame, so the client must push continuous audio, +silence included, to get continuous output. + +Bounds (defaults): + +- `:connect_timeout_ms` (15,000) from start to the Moshi handshake. +- `:idle_timeout_ms` (30,000) without an accepted push. +- `:max_session_ms` (1,800,000) in total. +- `:max_chunk_bytes` (48,000) for each push, else `{:error, :too_large}`. +- `:max_response_bytes` (67,108,864) for all incoming WebSocket bytes in a + session, including fragments. The session fails with `:response_too_large` + at this bound. Incomplete Ogg packets are limited to 256 KiB. +- `:max_input_lead_ms` (2,000). For Moshi (adapter input flow `:answered`): + pushed audio that model audio has not answered. For OpenAI (`:realtime`): + pushed audio ahead of the wall clock since `:ready`, so continuous silence + never fills it. A push past it returns `{:error, :overloaded}` and is not + sent, for example while MLX warms up. +- `:max_owner_queue` (250): when the owner mailbox has this many messages, the + session fails with `:owner_overloaded`. Output is not buffered or dropped. +- `:send_timeout_ms` (5,000) for each TCP write. + +The session monitors the owner and closes the connection when the owner exits. +On failure, timeout and `stop/1` it exits with reason `:normal`, so the link +from `start_link/1` does not stop the owner. The owner must be a local process. +The Moshi server limits above also apply: one connection at a time, and model +state continues across connections. + +`mix test test/duplex_test.exs` (with `AUDIOFLOW_MEDIA=1`) checks simultaneous +input and output, frame sizes, the handshake gate, the input and owner bounds, +timeouts and connection cleanup against a local fixture. With +`AUDIOFLOW_HTTP_MODEL_TESTS=1` and `AUDIOFLOW_MOSHI_PCM`, it also streams the +question and then silence in real time to a running server. + +### Continuous OpenAI Realtime conversation + +`AudioFlow.Duplex.OpenAIRealtime` keeps one authenticated OpenAI Realtime GA +WebSocket open for a whole conversation. It needs no media build. + +```elixir +{:ok, duplex} = + AudioFlow.Duplex.start( + owner: self(), + adapter: + {AudioFlow.Duplex.OpenAIRealtime, + model: System.fetch_env!("OPENAI_REALTIME_MODEL"), + api_key: fn -> System.fetch_env!("OPENAI_API_KEY") end, + voice: "marin"}) + +# After {AudioFlow.Duplex, ^duplex, :ready}, push 24 kHz PCM continuously, +# silence included: +:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm, sample_rate: 24_000}) +``` + +The adapter sends `session.update` (type `realtime`, `output_modalities` +`["audio"]`, PCM 24 kHz in and out, the voice, input transcription and +`server_vad` with `create_response` and `interrupt_response`) after +`session.created`, and emits `:ready` after `session.updated`. Each push is one +`input_audio_buffer.append`. The adapter never commits input and never sends +`response.create`: OpenAI detects each utterance, replies to it and cancels the +reply when new speech starts. All utterances of one connection share the +provider conversation; a new connection starts a new one. The API key function +runs only to connect, so the key is not kept in the session state. Options: +`:model`, `:api_key`, `:voice` (`"marin"`), `:instructions` (`""`), +`:transcription_model` (`"gpt-4o-mini-transcribe"`) and `:endpoint`. + +The owner also receives: + +| Event | Meaning | +| --- | --- | +| `{:speech_started, item}` | User speech started. Flush queued reply audio; keep the microphone open. Late audio and text of the interrupted reply are dropped. | +| `{:transcript, item, text \| :failed}` | Final transcript of the user utterance `item`. | +| `{:response, id, status}` | Reply `id` was `:created`, or ended `:completed`, `:cancelled`, `:incomplete` or `:failed`. | +| `{:output, item}` | The next `{:audio, _}` events belong to reply audio `item`. | + +After a flush, report the played part of the cut reply with +`AudioFlow.Duplex.control(duplex, {:played, item, ms})`. If `ms` is less than +the audio received for `item`, the adapter sends `conversation.item.truncate` +(`audio_end_ms` capped to the received audio), so the provider history keeps +only the played audio and its transcript. Only the last interrupted reply is +accepted, once; other reports return `{:error, :stale}` and leave the call +open. A rejected truncation also leaves the call open. The played time is +client playback time: it does not prove acoustic delivery. Without a report, +the provider history keeps the full reply. + +Provider `error` events fail the session with `{:remote_error, code}` (only +the code or type, never the message). Tool calls fail it with +`:unsupported_tool_call`, because no tools are configured. All +`AudioFlow.Duplex` bounds apply; `:max_response_bytes` (64 MiB) is about 17 +minutes of base64 reply audio per session. +The chat example sets this bound to 256 MiB for OpenAI calls, to allow the +30-minute call limit to apply before the response byte limit in ordinary use. + +`mix test test/duplex_openai_test.exs` checks the handshake order, server VAD +configuration, several utterances on one socket, continuous silence, +interruption drops, truncation bounds, provider errors and cleanup against a +local WebSocket peer, not OpenAI. ## Bounds, cancellation and errors @@ -307,9 +501,14 @@ samples fail. Limits and timeout options must be positive integers. ## Protocol references and verification -Wire shapes were checked against official documentation on 2026-11-03: +Wire shapes were checked against official documentation on 2026-11-03 (OpenAI +Realtime events again on 2026-11-06): - [OpenAI Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations) +- [OpenAI Realtime WebSocket](https://developers.openai.com/api/docs/guides/voice-websockets), + [voice activity detection](https://developers.openai.com/api/docs/guides/realtime-vad), + [client events](https://developers.openai.com/api/reference/resources/realtime/client-events) and + [server events](https://developers.openai.com/api/reference/resources/realtime/server-events) - [Gemini Live WebSocket reference](https://ai.google.dev/api/live) - [Deepgram pre-recorded utterances](https://developers.deepgram.com/docs/utterances) - [Cartesia bytes TTS](https://docs.cartesia.ai/api-reference/tts/bytes) diff --git a/site/src/content/docs/docs/features/webrtc-avatars.md b/site/src/content/docs/docs/features/webrtc-avatars.md index a231a7f..8996c31 100644 --- a/site/src/content/docs/docs/features/webrtc-avatars.md +++ b/site/src/content/docs/docs/features/webrtc-avatars.md @@ -82,7 +82,8 @@ accepted by ExWebRTC or rendered remotely. RTP acceptance is not playout ack. The [standalone server-backed browser viewer](https://github.com/flowcopilot/audioflow/blob/main/examples/avatar/README.md) invokes this publisher with supplied 24 kHz PCM and subscribes to both provider -tracks using `livekit-client`. It defaults to no paid calls, keeps provider +tracks using `livekit-client`. It subscribes only when explicitly configured with +an account. It defaults to no paid calls, keeps provider secrets server-side, checks room-scoped subscription-only grants, and demonstrates explicit start/cancel/disconnect and repeated finite sessions. Its opt-in viewer readiness gate waits at most 15 seconds for both track subscriptions before PCM. diff --git a/site/src/content/docs/docs/guides/history.md b/site/src/content/docs/docs/guides/history.md index 1c81075..032ca2d 100644 --- a/site/src/content/docs/docs/guides/history.md +++ b/site/src/content/docs/docs/guides/history.md @@ -31,7 +31,8 @@ The runtime removes the oldest complete pairs to fit the new prompt. It also removes old pairs when a successful reply makes saved history exceed a limit. Current input and reply text must fit as one pair. Excess text ends the turn -with `{:error, :context_limit, metrics}`. The budget excludes role fields, +with `{:error, :context_limit, metrics}`. The input limit also applies while +transcript or description chunks arrive. The budget excludes role fields, prompt delimiters, and system instructions. It is a byte limit, not a model token limit. Set model sequence limits for the chosen workload. @@ -39,7 +40,8 @@ token limit. Set model sequence limits for the chosen workload. Only nonempty user and assistant text becomes a saved pair. The session saves it after successful inference and acknowledgement from `Output.finish/2`. -Failed or cancelled turns leave the previous saved pairs intact. A cancellation +Failed or cancelled turns leave the previous saved pairs intact. Transport +completion can precede physical playback. A cancellation after `:done` flushes output and keeps that completed pair. Each session owns its history, also when sessions share the same inference worker. @@ -54,7 +56,8 @@ Clear the saved text while the session is idle: :ok = AudioFlow.clear_history(session) ``` -An active turn returns `{:error, :busy}`. History lasts for the session +An active turn returns `{:error, :busy}`. Clearing a session with history +disabled is an idempotent operation. History lasts for the session process; owner exit or a session crash ends it. ## Try it @@ -65,4 +68,12 @@ AUDIOFLOW_ML=1 AUDIOFLOW_HISTORY=1 AUDIOFLOW_LLM=Qwen/Qwen3-0.6B \ ``` Inputs are mono 16 kHz s16le PCM. The example loads shared models once and -writes one PCM file plus JSON metadata per turn. +writes one PCM file plus JSON metadata per turn. It does not open a sound device. + +Set `AUDIOFLOW_HISTORY=1` for `examples/models.exs`, `examples/media.exs`, and +`examples/local.exs`. The supplied history prompt supports native Qwen3 or an +HTTP chat engine. Other native models need their own message formatter. +Benchmark attempts use new sessions, so their history starts empty. + +The native conversation model check and the saved speech conversation checks are +described in [Model checks](../../validation/model-checks/#conversation-checks). diff --git a/site/src/content/docs/docs/guides/http-inference.md b/site/src/content/docs/docs/guides/http-inference.md index c6d789d..bfd5bb1 100644 --- a/site/src/content/docs/docs/guides/http-inference.md +++ b/site/src/content/docs/docs/guides/http-inference.md @@ -9,7 +9,8 @@ sidebar: [ReqLLM](https://hexdocs.pm/req_llm). It takes ReqLLM's model, context, and generation options directly. It groups the generated text into sentences, with whitespace preserved, and runs tools in the turn. It uses the same adapter -interface as the native models, and needs no native model dependencies. +interface as the native models, and needs no native model dependencies. Local Nx +adapters do not depend on ReqLLM. ```elixir llm = {AudioFlow.Adapters.ReqLLM, @@ -46,7 +47,8 @@ tool limits, and the byte and time limits below. The adapter reads the HTTP stream in the turn process. It uses ReqLLM's request builders, SSE parser, provider decoders, and chunk accumulator, but not ReqLLM's stream server. The shared Finch pool uses HTTP/1, so the output callback applies -back pressure to socket reads. Cancellation closes the active connection. +back pressure to socket reads. Cancellation closes the active connection. A +failed output callback also releases the connection. Each request runs once. The adapter does not follow redirects, retry, use ReqLLM's cache, or replay fixtures. Only HTTP SSE transports are supported, not @@ -65,7 +67,9 @@ These limits go under `:audio_flow`: | `pool_timeout_ms` | 5,000 | Wait for a connection | ReqLLM's `request_timeout`, `receive_timeout`, and `pool_timeout` options are -also accepted; the `:audio_flow` values take precedence. Use the session +also accepted; the `:audio_flow` values take precedence. Connections have a +five-second connection timeout. The response-read budget excludes pool checkout, +connection setup, and time blocked in the output callback. Use the session deadline to bound the complete turn, including tools and a blocked callback. Refusals, truncation, incomplete streams, invalid events, and empty replies @@ -78,7 +82,8 @@ the last text is emitted. Put Jido actions and `AudioFlow.Tool` maps under `audio_flow: [tools: ...]`. A tool map has `:name`, `:description`, `:parameters` (JSON Schema), and a one-argument `:run` function. Native `ReqLLM.Tool` structs go in the top-level -`:tools` option. Tool names must be unique. +`:tools` option. Tool names must be unique. Both kinds run in linked tasks with +bounded results and deadlines, and cancellation stops them. ```elixir llm = {AudioFlow.Adapters.ReqLLM, @@ -105,24 +110,6 @@ In graphs, use the `llm.req_llm` node. Its options are `model` (a of the environment variable, never the key), `tools_profile`, and `timeout_ms`. The graph runner passes the session and turn to the tools as `tool_context`. -## Migrate from ChatHTTP - -`AudioFlow.Adapters.ChatHTTP` and the `llm.chat_http` node are deprecated. The -adapter now only maps its old options to `AudioFlow.Adapters.ReqLLM`: - -| ChatHTTP | ReqLLM | -| --- | --- | -| `endpoint: ".../v1/chat/completions"` | `base_url: ".../v1"` | -| `model: "id"` | `model: %{provider: :openai, id: "id"}` | -| `system:` | `system_prompt:` | -| `parameters: %{temperature:, max_tokens:}` | `temperature:`, `max_tokens:` | -| `headers:` | `req_http_options: [headers: ...]` | -| `tools:`, `tool_filler:`, limits | the same keys under `:audio_flow` | - -Other `:parameters` entries raise an error; set them as ReqLLM generation or -provider options. ReqLLM now chooses the token field name, enables usage -streaming, omits `n: 1`, and normalizes tool argument JSON. - ## Run ```sh @@ -133,4 +120,17 @@ AUDIOFLOW_CHAT_ENDPOINT=http://127.0.0.1:18082/v1/chat/completions \ Set `AUDIOFLOW_CHAT_API_KEY` when the server needs authentication. To use HTTP language inference with native Whisper and Kokoro, set `AUDIOFLOW_LLM_ENGINE=http` and `AUDIOFLOW_CHAT_ENDPOINT` for -`examples/local.exs` or `examples/media.exs`. +`examples/local.exs` or `examples/media.exs`. `AUDIOFLOW_LLM` becomes the server's +model ID. This mode does not load a native language model. The benchmark +metadata uses `mode=hybrid_inference` and records the language engine as HTTP. +Optional `AUDIOFLOW_LLM_SOURCE` and `AUDIOFLOW_LLM_REVISION` identify the deployed +weights. The metadata does not contain the API key or endpoint query string. + +The real HTTP check, and the llama.cpp server it was last run against, are +described in [Model checks](../../validation/model-checks/#http-inference-check). + +## References + +- [Chat completion stream protocol](https://developers.openai.com/api/reference/resources/chat/subresources/completions/streaming-events) +- [llama.cpp server](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md) +- [Finch streaming](https://hexdocs.pm/finch/Finch.html#stream_while/5) diff --git a/site/src/content/docs/docs/guides/images.md b/site/src/content/docs/docs/guides/images.md index 8187b4c..90ebaef 100644 --- a/site/src/content/docs/docs/guides/images.md +++ b/site/src/content/docs/docs/guides/images.md @@ -13,9 +13,21 @@ sidebar: | `Models.clip_image_embedding/2` | CLIP vision with projection | Normalized vector, 512 values | | `Models.image_captioning/2` | BLIP and other caption models | Caption text | -BERT and CLIP vectors use different spaces; do not compare them directly. All -three builders accept `:load_options` and `:model_options`. Captioning also -accepts `:generation_options`. Set `:compile` to bound input shapes. +The text embedding defaults use attention-masked mean pooling and L2 +normalization. These defaults match `sentence-transformers/all-MiniLM-L6-v2`, a +BERT model with 384 output values. Other models can need different pooling, +output attributes, or input prefixes. Set these through the serving options and +the adapter input mapper. The library does not infer a retrieval task or add a +query prefix. Text embedding sequence lengths can truncate long input; set the +length for the chosen model and workload. + +CLIP emits normalized vectors in the joint CLIP text-image space. BERT and CLIP +vectors use different spaces; do not compare them directly. The captioning +builder generates a complete caption before returning it. All three builders +accept `:load_options` and `:model_options`. Captioning also accepts +`:generation_options`. Set `:compile` to bound input shapes. Load the models once +and use `Models.child_spec/3` to start their shared servings. The same +`NxAdapter`, `Worker`, and `Router` interfaces apply to these models. Use `NxAdapter.embedding/1` to emit one list of numbers, or supply an output mapper that keeps the tensor on the device. `NxAdapter.captions/1` emits caption @@ -27,7 +39,8 @@ AUDIOFLOW_ML=1 mix run examples/multimodal.exs image-embedding image.png AUDIOFLOW_ML=1 mix run examples/multimodal.exs describe image.png ``` -Image modes need the FFmpeg and ffprobe CLIs. +Image modes need the FFmpeg and ffprobe CLIs. They decode the first frame to RGB. +The models run through Bumblebee, Nx, and EXLA. ## Image turns @@ -48,8 +61,11 @@ Image data must use packed RGB, with three unsigned 8-bit channels per pixel in row order. Its byte count must equal `width * height * 3`. The session rejects images above `:max_image_bytes` (6,291,456 by default). -Image turns emit `{:description, text}` events. The description becomes the -prompt for the language model, and the reply follows the normal speech path. +Image turns emit `{:description, text}` events. All description chunks form one +prompt for the language model, and the reply follows the normal speech path. The +`:description` event keeps the original model text. The terminal metrics include +`first_description_us`. Audio and image turns share one active-turn limit. Both +support cancellation, deadlines, and output limits. Image-only sessions can omit `:stt`. Submission without the required adapter returns `{:error, {:unsupported_input, stage}}`. diff --git a/site/src/content/docs/docs/guides/local-models.md b/site/src/content/docs/docs/guides/local-models.md index 9e14111..7036a21 100644 --- a/site/src/content/docs/docs/guides/local-models.md +++ b/site/src/content/docs/docs/guides/local-models.md @@ -23,27 +23,32 @@ batch timeout is 5 ms. Tune these values with real workload measurements. See `AudioFlow.NxAdapter` calls `Nx.Serving.batched_run/2`. Input and output functions translate model-specific values. It consumes streaming results in the -calling process. `AudioFlow.Adapters.Function` can call a remote API or another -local engine. +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. ## Speech recognition and text `AudioFlow.Models.whisper/2` builds a Whisper serving with Bumblebee and EXLA. `AudioFlow.Models.language_model/2` builds a streaming text serving. The repository must have a model architecture and tokenizer that Bumblebee supports. +No support is claimed for every model; check each repository before use. Both builders accept `:load_options` for repository revisions and caches, and `:model_options` for parameter type and backend. The language builder also -accepts `:generation_options` for token limits and decoding strategy. +accepts `:generation_options` for token limits and decoding strategy. Serving +options remain separate. The examples load parameters onto `EXLA.Backend`. The Qwen3 example uses `AudioFlow.Prompt.qwen3/2`, with thinking disabled and a short spoken-reply instruction. Its format is checked against the pinned model's original Jinja template. Other language models need their own prompt -format. +format. Streamed text retains its whitespace. Common English titles and initials +stay with the following word. Empty text chunks do not cause a TTS request. Use `AudioFlow.STT.Bumblebee` for Whisper. It converts the input to 16 kHz. Whisper output is read after utterance transcription. Language model output is streamed and -grouped into sentences before synthesis. +grouped into sentences before synthesis. This is not yet a continuous streaming +speech recognizer. ## Kokoro @@ -66,25 +71,51 @@ stream = Nx.Serving.batched_run(AudioFlow.TTS, pcm_chunks = AudioFlow.Kokoro.audio(stream) |> Enum.to_list() ``` -Speed must be between 0.5 and 2.0. Only loaded voices are accepted. Inputs -longer than 510 phoneme symbols are split at spaces. Each section emits PCM -after it is generated; Kokoro is not a continuous streaming vocoder. +Consume the result stream in the calling process. Set the adapter output mapper +to `&AudioFlow.Kokoro.audio/1`. Speed must be between 0.5 and 2.0. Only loaded +voices are accepted. Inputs longer than 510 phoneme symbols are split at spaces, +or at the limit when no space exists. No symbols are silently removed. Each +section runs as one batch because its waveform length depends on the text. Each +section emits PCM after it is generated; Kokoro is not a continuous streaming +vocoder. A section's new token and waveform lengths can cause compilation. `:cache_size` bounds the compiled shapes that Transmuter keeps (default 64). :::note Install espeak-ng for text input: `brew install espeak-ng` on macOS, or the `espeak-ng` package on Linux. The tested version is 1.52.0. It only converts -text to phonemes; Kokoro inference runs through Nx, Transmuter, and EXLA. +text to phonemes; Kokoro inference runs through Nx, Transmuter, and EXLA. Direct +phoneme input does not need this executable. ::: -The default phonemizer supports `en-us` and `en-gb`. It does not provide +The default phonemizer supports `en-us` and `en-gb`. It preserves punctuation +and converts the English diphthongs and affricates to Kokoro symbols. It does not provide Misaki's dictionary and text normalization, so numbers, abbreviations, and names can sound different. Supply a custom phonemizer tuple or `%{phonemes: phonemes}` for another front end. +The pinned ONNX graph has a phase error at DC and Nyquist. The builder applies +the Transmuter phase correction before compilation. Voice style row selection +uses `phoneme_count - 1`, as in the original Kokoro inference code. + ## VITS and SpeechT5 `AudioFlow.Models.text_to_speech/2` builds a VITS or SpeechT5 serving through Transmuter. `AudioFlow.NxAdapter.speech_audio/1` converts the float waveform to -mono s16le PCM in 20 ms chunks. Set `AUDIOFLOW_TTS=vits` in -`examples/local.exs` for the pinned `Xenova/mms-tts-eng` model. +mono s16le PCM in 20 ms chunks. Values outside the PCM range are clamped. Set `AUDIOFLOW_TTS=vits` in +`examples/local.exs` for the pinned `Xenova/mms-tts-eng` model. The model first +generates a full sentence waveform. Splitting it into PCM chunks does not make +model inference incremental. + +Transmuter is pinned to a Git revision in `mix.exs` and `mix.lock`. Its current +source API differs from the older Hex release. `examples/local.exs` uses Kokoro +by default. A custom TTS config is optional. + +## References + +- [Bumblebee audio](https://bumblebee.hexdocs.pm/Bumblebee.Audio.html) +- [Bumblebee text generation](https://bumblebee.hexdocs.pm/Bumblebee.Text.html) +- [Nx.Serving](https://nx.hexdocs.pm/Nx.Serving.html) +- [Transmuter package](https://hex.pm/packages/transmuter) +- [Pinned Transmuter speech guide](https://github.com/georgeguimaraes/transmuter/blob/231028d9ff6f53bd58fa15d9f24d632258369805/guides/speech_and_audio.md) +- [Kokoro voice style selection](https://github.com/hexgrad/kokoro/blob/main/kokoro/pipeline.py) +- [Misaki phoneme mapping](https://github.com/hexgrad/misaki/blob/main/misaki/espeak.py) diff --git a/site/src/content/docs/docs/guides/membrane-input.md b/site/src/content/docs/docs/guides/membrane-input.md index 9697a91..a26ecc5 100644 --- a/site/src/content/docs/docs/guides/membrane-input.md +++ b/site/src/content/docs/docs/guides/membrane-input.md @@ -26,20 +26,25 @@ submits utterances after endpoint detection: Start `AudioFlow.VAD` once with `AudioFlow.Silero.serving/2` and `AudioFlow.Models.child_spec/3`. The Silero source can be a local ONNX file or `{:hf, "onnx-community/silero-vad", "onnx/model.onnx"}`. Each sink keeps its -own recurrent state; only the weights are shared. Input must be 16 kHz. +own recurrent state; only the weights are shared. Input must be 16 kHz. Pin the +model with `load_options: [revision: "e71cae966052b992a7eca6b17738916ce0eca4ec"]`. +Put a resampler before the sink for other rates. ## Barge-in After speech confirmation, the sink cancels the active reply and sends `{:audio_flow_speech_started, session}` to its parent. A configured output -transport is flushed by the session. After endpoint detection, the sink sends -`{:audio_flow_input, result}`. The parent must handle busy input. +transport is flushed by the session. Otherwise, the parent must flush playback. +After endpoint detection, the sink sends `{:audio_flow_input, result}`. The parent +must handle busy input. At end of stream, the sink flushes the final utterance. +Without `vad`, each input buffer must be one complete utterance. ## Without Membrane `AudioFlow.VoiceInput` supplies the same frame processing without Membrane. It keeps pre-roll, confirms speech, uses separate start and stop thresholds, and -limits utterance length. +limits utterance length. It pads a partial final frame with silence. Endpoint +options are documented in the module. ```sh AUDIOFLOW_ML=1 AUDIOFLOW_PCM=recording.s16le mix run examples/vad.exs @@ -51,8 +56,17 @@ AUDIOFLOW_ML=1 AUDIOFLOW_PCM=recording.s16le mix run examples/vad.exs Membrane source chain. It converts mono or stereo input to mono s16le at the selected rate (16 kHz by default). `AudioFlow.InputPipeline` supplies this chain as a complete pipeline. The source can be `AudioFlow.PCMFileSource` or -`Membrane.PortAudio.Source`. +`Membrane.PortAudio.Source`. The file source reads bounded chunks and preserves +sample timestamps. It rejects incomplete PCM frames. Set the source format to match +the actual file or device. :::caution Echo cancellation is not included. Speaker audio can trigger the detector. ::: + +`AudioFlow.Input.attach/3` requires a voice detector tuple. + +## References + +- [Silero frame and context protocol](https://github.com/snakers4/silero-vad/blob/master/src/silero_vad/utils_vad.py) +- [FFmpeg resampler](https://membrane-ffmpeg-swresample-plugin.hexdocs.pm/Membrane.FFmpeg.SWResample.Converter.html) diff --git a/site/src/content/docs/docs/guides/output.md b/site/src/content/docs/docs/guides/output.md index dbf606c..ad1cf57 100644 --- a/site/src/content/docs/docs/guides/output.md +++ b/site/src/content/docs/docs/guides/output.md @@ -17,22 +17,30 @@ sink = %Membrane.PortAudio.Sink{latency: :low, The application selects the sink. A sound device opens only when PCM arrives. Each turn gets its own output pipeline. The queue is limited by `:max_bytes` -(96,000 by default). A full queue blocks the turn worker, while cancellation -stays available in the session. +(96,000 by default). One further chunk can wait for capacity. Each chunk must fit +within that limit. A full queue blocks the turn worker, while cancellation stays +available in the session. Membrane input prefetch is limited to one buffer; the +device has its own ring buffer. PCM chunks must keep the same sample rate +throughout a turn. ## Drain and flush Normal completion drains queued output. The playback process sends `:drained` after pipeline cleanup. Inference `:done` can arrive before playback finishes. +PortAudio output is padded to a whole device block and has a final ring-buffer +drain interval before close. Cancellation drops the queue and closes the old pipeline before it -acknowledges. Old turn references are rejected. +acknowledges. Old turn references are rejected. A completed inference turn can +still be cancelled while its audio is queued. Session exit also closes its output +pipeline. ## Events The observer receives `{AudioFlow.Playback, pid, turn_key, event}`. Events include `:drained`, `{:first_buffer, %{elapsed_us: us}}`, -`{:flushed, %{control_us: us}}`, back pressure, and failure. These are not -microphone-to-speaker measurements. Acoustic interruption latency needs a +`{:flushed, %{control_us: us}}`, back pressure, and failure. First-buffer time ends at the Membrane source, and flush time ends after pipeline +cleanup. Neither is a microphone-to-speaker measurement. A device close can drain +a short native buffer. Acoustic interruption latency needs a loopback recording and a common clock. ## Custom transports @@ -49,5 +57,17 @@ AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 AUDIOFLOW_PCM=recording.s16le \ AUDIOFLOW_LLM=Qwen/Qwen3-0.6B mix run examples/media.exs ``` -This connects a PCM file, resampling, Silero, the session, and PortAudio -output. It plays sound when run. +`examples/models.exs` starts shared models, and `examples/local.exs` adds a single +utterance for inference benchmarks. `examples/media.exs` connects a PCM file, +resampling, Silero, the session, and PortAudio output. It plays sound when run. + +Set `AUDIOFLOW_INPUT_RATE` and `AUDIOFLOW_INPUT_CHANNELS` for other input formats. +The file example reads at processing speed, so use one utterance for this check. +A live PortAudio source follows the device clock. The media tests use a controlled +sink. They verify back pressure, drain, cancellation, pipeline failure, and cleanup +without opening a sound device. + +## References + +- [PortAudio plugin](https://hexdocs.pm/membrane_portaudio_plugin/) +- [Membrane sinks](https://membrane-core.hexdocs.pm/Membrane.Sink.html) diff --git a/site/src/content/docs/docs/guides/routing.md b/site/src/content/docs/docs/guides/routing.md index 06bd140..cd0b4d0 100644 --- a/site/src/content/docs/docs/guides/routing.md +++ b/site/src/content/docs/docs/guides/routing.md @@ -32,11 +32,16 @@ options = Keyword.put(session_options, :llm, ## Remote workers -The remote node must run AudioFlow and a worker named `MyApp.RemoteLLM`. Erlang +The remote node must run AudioFlow and a worker named `MyApp.RemoteLLM`. Its +adapter uses model services on that node. Erlang distribution must already connect the nodes. Use compatible code on trusted nodes. Inputs and outputs cross the connection; model weights stay in their shared services. A worker can use `NxAdapter` or an application adapter for -ONNX, llama.cpp, or a cloud API. +ONNX, llama.cpp, or a cloud API. Cloud clients must set their own connection and +request timeouts. Only connected remote nodes are eligible. Reconnect a node +before routing to it again. If a node fails while admission is in progress, the +request ends with an error. Its admission status is unknown, so the router does +not retry it. All engines use the same adapter interface. ## Route selection @@ -54,13 +59,18 @@ AudioFlow.Router.put_route(MyApp.Routes, :voice, [{MyApp.RemoteLLM, :"ml@worker" The change applies to later adapter calls. Active requests keep their worker. An empty worker list disables the route. `:route` can also be a function that selects a route key from the adapter input, for example by text length or -language. +language. A policy like this can select a model without changing the session +pipeline. ## Cancellation Each output chunk waits for its caller's acknowledgement. Caller exit and session cancellation stop the worker task, also on a remote node. Worker exit or -node loss ends the active request with an error. +node loss ends the active request with an error. Each worker has a request +deadline, and the router has a deadline for the complete call. Cleanup can take up +to one additional second. A hardware batch already submitted to a shared serving +can still run to completion. Set worker limits and deadlines to match measured +model capacity and the session timeout. ## Try it @@ -70,4 +80,5 @@ AUDIOFLOW_DISTRIBUTED_TESTS=1 elixir --sname audioflow_test -S mix test ``` The distributed checks start a second local Erlang node. They check remote -output, cancellation, and node loss. +output, cancellation, and node loss. These checks use controlled adapters. They do +not measure network latency or model capacity across machines. diff --git a/site/src/content/docs/docs/guides/sessions.md b/site/src/content/docs/docs/guides/sessions.md index 1b25273..4045330 100644 --- a/site/src/content/docs/docs/guides/sessions.md +++ b/site/src/content/docs/docs/guides/sessions.md @@ -54,6 +54,24 @@ An empty transcript ends the turn without generation. Speech recognition chunks form one prompt. Language model chunks go to speech synthesis in sequence. Use complete sentences for language model output when possible. +## Remote and speech-to-speech adapters + +For hosted Fish Audio TTS, use `AudioFlow.Adapters.FishAudioAPI` with an API +key, model and hosted voice ID. For self-hosted Fish Speech, use +`AudioFlow.Adapters.FishAudio` with a server endpoint and optional voice +reference. See [Fish Audio backends](../../features/providers/#fish-audio-hosted-api). +Native Fish inference on Nx needs a separate model/codec integration; see the +[Nx feasibility assessment](../../features/providers/#native-fish-speech-on-nx). + +For OpenAI Realtime, Gemini Live or a local +[Moshi](../../features/providers/#local-moshi-speech-to-speech) server without +chained stages, use the explicit +[Session speech-to-speech mode](../../features/providers/#session-speech-to-speech-mode). +It accepts committed PCM and does not replay cross-turn history. For a +continuous conversation with the microphone open, use `AudioFlow.Duplex` with +[OpenAI Realtime](../../features/providers/#continuous-openai-realtime-conversation) +or [Moshi](../../features/providers/#continuous-full-duplex-moshi). + ## Lifetime The session stops when its owner exits. Turn failures do not stop the session. diff --git a/site/src/content/docs/docs/guides/telemetry.md b/site/src/content/docs/docs/guides/telemetry.md index 3694992..ccac418 100644 --- a/site/src/content/docs/docs/guides/telemetry.md +++ b/site/src/content/docs/docs/guides/telemetry.md @@ -96,3 +96,7 @@ end A turn produces a `audio_flow.turn` span with `audio_flow.stt` and `audio_flow.llm` children. Each `audio_flow.tts` span is a child of `audio_flow.llm`. Stage spans left open by a cancelled turn are not exported. + +## References + +- [telemetry span](https://hexdocs.pm/telemetry/telemetry.html#span/3) diff --git a/site/src/content/docs/docs/guides/video.md b/site/src/content/docs/docs/guides/video.md index ce5d3ea..342f4df 100644 --- a/site/src/content/docs/docs/guides/video.md +++ b/site/src/content/docs/docs/guides/video.md @@ -21,24 +21,31 @@ end The interval is the minimum time between selected frames. The reader uses presentation timestamps, not frame counts. By default, time starts at the first -decoded frame. Set `normalize_timestamps?: false` to keep decoder timestamps. +decoded frame. Set `normalize_timestamps?: false` to keep decoder timestamps, including MP4 composition offsets. These times do not account +for MP4 edit lists or provide audio and video synchronization. The default track is the H.264 track with the lowest ID. Use `:track_id` to -select another track. Other tracks, including audio, are discarded. +select another track. Other tracks, including audio, are discarded. Files with +metadata at either end are supported. Unsupported tracks and decode errors +produce errors; they do not end the calling process when you use the manual API. ## Limits -The default frame limit is 6,291,456 bytes. Set `:max_frame_bytes` to change it. -Optional `:width` and `:height` must be positive even integers. Scaling keeps the -aspect ratio and adds padding. Decoding follows demand; the reader does not pace -frames against a clock. +The reader allows one pending read and uses small RGB queues. The default frame +limit is 6,291,456 bytes. Set `:max_frame_bytes` to change it. Optional `:width` +and `:height` must be positive even integers. Scaling keeps the aspect ratio and +adds padding. The frame limit applies after scaling. Decoder working memory and +MP4 indexes are separate from this limit. Decoding follows demand; the reader +does not pace frames against a clock. ## Manual control `frames/2` closes the reader at the end of the file, on an early halt, or after -a consumer error. For manual control, use `Video.start_link(location: path)` or -`Video.start_link(source: source)`, then `Video.next_frame(reader, timeout_ms)` -and `Video.close(reader)`. +a consumer error. It raises on a read error. Its `:timeout_ms` option sets the +limit for each read (30 seconds by default). For manual control, use +`Video.start_link(location: path)` or `Video.start_link(source: source)`, then +`Video.next_frame(reader, timeout_ms)` and `Video.close(reader)`. A reader also +stops when its owner exits. ## Example @@ -46,7 +53,11 @@ and `Video.close(reader)`. AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 mix run examples/video.exs input.mp4 output ``` -The example uses shared BLIP, Qwen3, and Kokoro services. History supplies the -previous description for comparison. `AUDIOFLOW_VIDEO_INTERVAL_MS` sets the +The example uses shared BLIP, Qwen3, and Kokoro services. It waits for one frame +turn before it reads another. History supplies the previous description for +comparison. It saves descriptions, replies, timings, and speech PCM. `AUDIOFLOW_VIDEO_INTERVAL_MS` sets the interval, and `AUDIOFLOW_VIDEO_FRAMES` sets the frame limit. This is sampled -frame analysis; it does not track objects or motion between frames. +frame analysis; it does not track objects or motion between frames. A two-scene +model check produced correct individual descriptions, but Qwen3-0.6B added an +unsupported action during comparison. Model output needs assessment for the +intended use. diff --git a/site/src/content/docs/docs/index.md b/site/src/content/docs/docs/index.md index c8d15af..2ef78fa 100644 --- a/site/src/content/docs/docs/index.md +++ b/site/src/content/docs/docs/index.md @@ -49,7 +49,8 @@ know which one it calls. ## Build profiles The core needs no model downloads. Environment variables add the optional -parts. Each combination uses its own `_build` directory. +parts. Each combination uses its own `_build` directory. Changing a feature +flag does not remove modules used by another build profile. | Variable | Adds | Source directory | | --- | --- | --- | @@ -58,6 +59,18 @@ parts. Each combination uses its own `_build` directory. | `AUDIOFLOW_MEDIA=1` | Membrane audio and video | `lib_media` | | `AUDIOFLOW_WEBRTC=1` | ExWebRTC media output and the PCM bridge | `lib_webrtc` | +## Status + +This implements the session runtime, model routing, distributed inference +workers, native Silero voice detection, Whisper and text-generation adapters, +Kokoro and VITS speech synthesis, and Membrane audio and video input. The native +media path has a recorded-speech integration check and a controlled Pipecat +comparison. Output interruption is measured at the software transport. Acoustic +interruption needs a device loopback check. HTTP language inference can use a +compatible local server or cloud endpoint. Text embeddings, CLIP image +embeddings, and BLIP image captions use shared native model services. Their model +checks use independent PyTorch references. + ## Next steps - [Quickstart](quickstart/): run the demo and your first session. diff --git a/site/src/content/docs/docs/quickstart.md b/site/src/content/docs/docs/quickstart.md index 8d4f8c7..a394200 100644 --- a/site/src/content/docs/docs/quickstart.md +++ b/site/src/content/docs/docs/quickstart.md @@ -79,4 +79,7 @@ See [Local models](../guides/local-models/). | `examples/conversation.exs` | Sequential turns with history | | `examples/multimodal.exs` | Embeddings and image captions | | `examples/video.exs` | Descriptions of sampled video frames | +| `examples/models.exs` | Shared model services for the other examples | +| `examples/transcribe.exs` | Captions for a WAV file through any STT adapter | +| `examples/websocket.exs` | The browser WebSocket demo | | `examples/chat` | A LiveView voice and text chat | diff --git a/site/src/content/docs/docs/validation/benchmarks.md b/site/src/content/docs/docs/validation/benchmarks.md index babdfc1..df86527 100644 --- a/site/src/content/docs/docs/validation/benchmarks.md +++ b/site/src/content/docs/docs/validation/benchmarks.md @@ -25,21 +25,58 @@ AUDIOFLOW_ML=1 mix audio_flow.bench --config examples/local.exs \ --runs 100 --warmup 4 --concurrency 4 --output benchmarks/native.csv ``` -`--warmup` rows use `phase=warmup`; other rows use `phase=measured`. -`--timeout-ms` sets the attempt deadline. `--output` writes a CSV and a -`.meta.json` file with input hashes, model revisions, and runtime versions. +`--warmup` rows use `phase=warmup`; other rows use `phase=measured`. Both phases +run at the selected concurrency. Use measured rows for reported latency, and count +all measured failures in the error rate. `--timeout-ms` sets the attempt deadline. +Its default is the session timeout plus five seconds. Cleanup follows the deadline. +A final worker limit also prevents a stalled runner from waiting without an end. + +`--output` writes a CSV and a `.meta.json` file with input hashes, model revisions, +and runtime versions. Model logs remain on the console. The sidecar records +warmup settings, runtime and library versions, and loaded AudioFlow module +fingerprints. `setup_us` covers config evaluation and model setup, separately from +turn timings. Without `--output`, stdout also contains any model logs. :::note Errors stay in the CSV, so failed runs cannot improve the latency result. A completed turn with no audio counts as an error. ::: +Rejected input, session exit, cancellation, and benchmark deadlines also produce +rows. Error rows use elapsed attempt time where available. Unobserved timings +remain blank. Blank fields mean that the event did not occur. + +`first_text_us` measures the first sentence-sized text chunk from the language +model adapter. + +The local example requires `AUDIOFLOW_PCM` and `AUDIOFLOW_LLM`. It uses local +Kokoro by default. Set `AUDIOFLOW_VOICE` to select its voice, or +`AUDIOFLOW_TTS=vits` to use VITS. Set `AUDIOFLOW_TTS_CONFIG` for another adapter. +The example pins Whisper tiny, Qwen3-0.6B, and the selected TTS model. Set +`AUDIOFLOW_LLM_REVISION` to pin another language model and `AUDIOFLOW_HARDWARE` to +add a hardware label to its metadata. The metadata leaves unpinned revisions +empty. The default example uses greedy decoding with at most 64 new tokens, batch +size 1, and a 5 ms batch timeout. Repeat with concurrency 1, 2, 4, and higher. + ## Reporting Record hardware, model revisions, precision, batch settings, and warmup count. Keep cold runs separate. Report p50 and p95 latency and the error rate. Set the -latency and error limits before you select a maximum session count. +latency and error limits before you select a maximum session count. Use the same +recordings, endpoint rules, and models for a Pipecat comparison. The CPU run below +does not include a Pipecat comparison or establish real-time performance. + +The saved [CPU run data](https://github.com/flowcopilot/audioflow/blob/main/validation/native-cpu.csv), +[metadata](https://github.com/flowcopilot/audioflow/blob/main/validation/native-cpu.csv.meta.json), and +[chart](https://github.com/flowcopilot/audioflow/blob/main/validation/native-cpu.html) have one warmup turn and +three measured turns. They use one recording and one active session. This small +check confirms that the inference path runs. It does not establish session +capacity. Capture, VAD, transport, and playback device delays are excluded from +these measurements. + +## Open measurements -The saved [CPU run data](https://github.com/flowcopilot/audioflow/blob/main/validation/native-cpu.csv) has one warmup turn and -three measured turns with one session. It confirms that the inference path -runs. It does not establish session capacity. +- Add echo cancellation for microphone use. +- Measure interruption through a real playback device with loopback audio. +- Use sustained loads, more speakers, noise, and real-time input pacing. +- Compare independent Pipecat model engines with equivalent precision and decoding. diff --git a/site/src/content/docs/docs/validation/model-checks.md b/site/src/content/docs/docs/validation/model-checks.md index e2af15a..55633c6 100644 --- a/site/src/content/docs/docs/validation/model-checks.md +++ b/site/src/content/docs/docs/validation/model-checks.md @@ -29,34 +29,77 @@ AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 AUDIOFLOW_MODEL_TESTS=1 mix test | BLIP | Complete reference caption | `scripts/multimodal_reference.py` | | Qwen3 prompt | Original pinned Jinja template | `scripts/qwen3_prompt_reference.py` | +Silero probabilities are compared with independent ONNX Runtime values in +`test/fixtures/silero_reference.json`, for two concurrent streams. Set +`AUDIOFLOW_SILERO_MODEL` to use a local Silero file. The VITS test also checks PCM +size and non-silent output. The Kokoro checks also cover finite samples, PCM +output, and use through a session; they require espeak-ng. + +The multimodal checks compare BERT and projected CLIP vectors against independent +PyTorch outputs. The text model has two concurrent callers on one shared serving. +The pinned cat image comes from the Transmuter test fixtures. FFmpeg RGB output +must have the same SHA-256 as the reference image bytes. CLIP comparison allows +small differences between image resize implementations; BLIP checks the complete +reference text. These checks need FFmpeg, but no microphone or sound device. + +```sh +AUDIOFLOW_ML=1 AUDIOFLOW_MODEL_TESTS=1 mix test test/multimodal_model_test.exs +``` + +The image session check uses real BLIP with controlled LLM and TTS adapters. It +checks delivery through the session, rather than spoken audio quality. + These checks verify the inference path. They do not measure speech quality. ## Full native pipeline -The full media test uses a public LibriSpeech sample with real Silero, Whisper, -Qwen3, and Kokoro models and a Membrane test sink. It checks transcript content, -reply text, non-silent PCM, and complete delivery. It needs FFmpeg and espeak-ng. +The full media test uses the public LibriSpeech sample in the pinned Transmuter +repository, with real Silero, Whisper, Qwen3, and Kokoro models and a Membrane test +sink. It checks transcript content, reply text, non-silent PCM, and complete +delivery through the output pipeline. It needs FFmpeg and espeak-ng. It does not +open a sound device. ```sh AUDIOFLOW_ML=1 AUDIOFLOW_MEDIA=1 AUDIOFLOW_PIPELINE_TESTS=1 \ mix test test/native_pipeline_test.exs ``` +Set `AUDIOFLOW_PIPELINE_ARTIFACT_DIR` to retain the transcript, reply, PCM, and +timings in a selected directory. Model loading and compilation can take time. + ## Conversation checks The saved [speech conversation checks](https://github.com/flowcopilot/audioflow/blob/main/validation/conversation-smoke.json) use two utterances with eSpeak NG and Kokoro input voices. With Kokoro inputs, Whisper transcribed both utterances correctly, and the second spoken reply -recalled the codeword from the first turn. Whisper tiny misread the eSpeak -inputs. Both results are kept with model revisions and PCM hashes. +recalled the codeword `banana`. Whisper tiny misread the eSpeak inputs. Both +results are retained with model revisions and PCM hashes. These are small checks +of transcription and context use; model quality needs a broader workload. The +native conversation model check uses one Qwen3 serving for two turns and checks +recall of a codeword from the first turn. Its STT and TTS adapters are controlled +test adapters. Qwen3 message prompts are also compared with the original pinned +Jinja template. ## HTTP inference check ```sh AUDIOFLOW_HTTP_MODEL_TESTS=1 \ AUDIOFLOW_CHAT_ENDPOINT=http://127.0.0.1:18082/v1/chat/completions \ - AUDIOFLOW_LLM=audioflow-qwen mix test test/chat_http_model_test.exs + AUDIOFLOW_LLM=audioflow-qwen mix test test/req_llm_model_test.exs ``` This compares streamed session output with an independent request to the same -deterministic llama.cpp server. +deterministic llama.cpp server. This check uses controlled STT and TTS adapters. +It validates transport output. Model answer accuracy requires a separate +evaluation. The checked local server was llama.cpp 0.8.0, build 11960 +(`8642541b2`), with zero GPU layers. It used `Qwen/Qwen3-0.6B-GGUF`, revision +`23749fefcc72300e3a2ad315e1317431b06b590a`, file `Qwen3-0.6B-Q8_0.gguf`. The file +SHA-256 was +`9465e63a22add5354d9bb4b99e90117043c7124007664907259bd16d043bb031`. The server +used four threads, two slots, a 4,096-token context, and reasoning disabled. +Hybrid voice inference also passed with real Whisper and Kokoro. No hosted cloud +account was used for these checks. + +## References + +- [Silero frame and context protocol](https://github.com/snakers4/silero-vad/blob/master/src/silero_vad/utils_vad.py) diff --git a/site/src/content/docs/docs/validation/pipecat-comparison.md b/site/src/content/docs/docs/validation/pipecat-comparison.md index f1f5dd8..f9164e2 100644 --- a/site/src/content/docs/docs/validation/pipecat-comparison.md +++ b/site/src/content/docs/docs/validation/pipecat-comparison.md @@ -8,7 +8,9 @@ sidebar: `scripts/compare_pipecat.py` measures AudioFlow and Pipecat over the same shared Nx model services. One Elixir process loads Silero, Whisper tiny, Qwen3-0.6B, and Kokoro. Pipecat calls these services through private local -pipes; AudioFlow calls them in the same process. +pipes, so its result includes that transfer cost; AudioFlow calls them in the +same process. This does not compare Nx against Python inference engines. The run includes Membrane file +input, resampling, endpoint detection, model queues, and software output delivery. :::caution This compares orchestration over one inference engine. Pipe transfer, JSON, @@ -49,5 +51,13 @@ python3 scripts/comparison_report.py \ benchmarks/comparison.json benchmarks/comparison.html ``` +The runner retains failed attempts, input hashes, detected-utterance hashes, output +PCM hashes, model revisions, and source fingerprints. It separates warmup, measured +turns, and serial interruption checks. Choose `--max-first-output-ms` before the +run. The default rule allows no measured errors and requires p95 first output +within 10 seconds. The report checks input agreement and all lower tested levels +before it assigns a highest passing tested concurrency. This threshold is a test +rule; it does not establish conversational quality. + Each input must be mono 16 kHz s16le PCM with one detected utterance. See [`scripts/COMPARISON.md`](https://github.com/flowcopilot/audioflow/blob/main/scripts/COMPARISON.md) for the full method. diff --git a/test/audio_flow/application_test.exs b/test/audio_flow/application_test.exs deleted file mode 100644 index a95e24d..0000000 --- a/test/audio_flow/application_test.exs +++ /dev/null @@ -1,15 +0,0 @@ -defmodule AudioFlow.ApplicationTest do - use ExUnit.Case, async: true - - defmodule TestAgent do - use Jido.Agent, name: "bootstrap_test", schema: [] - end - - test "the application can start and locate a Jido agent" do - id = "bootstrap-#{System.unique_integer([:positive])}" - assert {:ok, pid} = AudioFlow.Jido.start_agent(TestAgent, id: id) - on_exit(fn -> AudioFlow.Jido.stop_agent(pid) end) - - assert AudioFlow.Jido.whereis(id) == pid - end -end diff --git a/test/conversation_evaluation_test.exs b/test/conversation_evaluation_test.exs index 8a4fe99..917fa3b 100644 --- a/test/conversation_evaluation_test.exs +++ b/test/conversation_evaluation_test.exs @@ -1,8 +1,8 @@ defmodule AudioFlow.ConversationEvaluationTest do use ExUnit.Case, async: true - alias AudioFlow.Adapters.ChatHTTP alias AudioFlow.Adapters.Demo alias AudioFlow.Adapters.Function + alias AudioFlow.Adapters.ReqLLM alias AudioFlow.Evaluation.Conversation, as: Conversation alias AudioFlow.Test.HTTPFixture, as: HTTP @@ -65,8 +65,11 @@ defmodule AudioFlow.ConversationEvaluationTest do session = start( - {ChatHTTP, - endpoint: endpoint, model: "fixture", tools: tools, tool_context: %{forecast: "sun"}} + {ReqLLM, + base_url: String.replace_suffix(endpoint, "/chat/completions", ""), + model: %{provider: :openai, id: "fixture"}, + api_key: "local", + audio_flow: [tools: tools, tool_context: %{forecast: "sun"}]} ) [first, second] = diff --git a/test/conversation_http_test.exs b/test/conversation_http_test.exs index d9588d4..edf2147 100644 --- a/test/conversation_http_test.exs +++ b/test/conversation_http_test.exs @@ -13,117 +13,109 @@ defmodule AudioFlow.ConversationHTTPTest do end) end - for adapter <- [:chat_http, :req_llm] do - @adapter adapter - test "#{adapter}: a Jido tool call swaps the actual HTTP prompt and tools while preserving history" do - previous = Application.get_env(:audio_flow, :chat_tool_profiles) + test "a Jido tool call swaps the actual HTTP prompt and tools while preserving history" do + previous = Application.get_env(:audio_flow, :chat_tool_profiles) - Application.put_env(:audio_flow, :chat_tool_profiles, %{ - "triage" => [AudioFlow.Graph.Handoff], - "billing" => [] - }) + Application.put_env(:audio_flow, :chat_tool_profiles, %{ + "triage" => [AudioFlow.Graph.Handoff], + "billing" => [] + }) - on_exit(fn -> - if previous, - do: Application.put_env(:audio_flow, :chat_tool_profiles, previous), - else: Application.delete_env(:audio_flow, :chat_tool_profiles) - end) + on_exit(fn -> + if previous, + do: Application.put_env(:audio_flow, :chat_tool_profiles, previous), + else: Application.delete_env(:audio_flow, :chat_tool_profiles) + end) - {child, listener, endpoint} = - HTTP.start(self(), fn socket, request -> - messages = request.body["messages"] + {child, listener, endpoint} = + HTTP.start(self(), fn socket, request -> + messages = request.body["messages"] - body = - if hd(messages)["content"] == "Triage" and - not Enum.any?(messages, &(&1["role"] == "tool")) do - "data: " <> - JSON.encode!(%{ - choices: [ - %{ - index: 0, - delta: %{ - tool_calls: [ - %{ - index: 0, - id: "transfer", - type: "function", - function: %{ - name: "handoff", - arguments: JSON.encode!(%{intent: "billing"}) - } + body = + if hd(messages)["content"] == "Triage" and + not Enum.any?(messages, &(&1["role"] == "tool")) do + "data: " <> + JSON.encode!(%{ + choices: [ + %{ + index: 0, + delta: %{ + tool_calls: [ + %{ + index: 0, + id: "transfer", + type: "function", + function: %{ + name: "handoff", + arguments: JSON.encode!(%{intent: "billing"}) } - ] - }, - finish_reason: "tool_calls" - } - ] - }) <> "\n\n" <> HTTP.done() - else - HTTP.event("Ready.", "stop") <> HTTP.done() - end + } + ] + }, + finish_reason: "tool_calls" + } + ] + }) <> "\n\n" <> HTTP.done() + else + HTTP.event("Ready.", "stop") <> HTTP.done() + end - HTTP.headers(socket) - HTTP.chunk(socket, body) - HTTP.finish(socket) - end) + HTTP.headers(socket) + HTTP.chunk(socket, body) + HTTP.finish(socket) + end) - start_supervised!(child) - on_exit(fn -> :gen_tcp.close(listener) end) + start_supervised!(child) + on_exit(fn -> :gen_tcp.close(listener) end) - graph = fn name, profile -> - %{ - nodes: [ - %{id: "in", type: "input.text"}, - %{ - id: "llm", - type: "llm.#{@adapter}", - options: - if @adapter == :req_llm do - %{ - base_url: String.replace_suffix(endpoint, "/chat/completions", ""), - model: "openai:fixture", - api_key_env: "AUDIOFLOW_HANDOFF_TEST_KEY", - system_prompt: name, - tools_profile: profile - } - else - %{endpoint: endpoint, model: "fixture", system: name, tools_profile: profile} - end + graph = fn name, profile -> + %{ + nodes: [ + %{id: "in", type: "input.text"}, + %{ + id: "llm", + type: "llm.req_llm", + options: %{ + base_url: String.replace_suffix(endpoint, "/chat/completions", ""), + model: "openai:fixture", + api_key_env: "AUDIOFLOW_HANDOFF_TEST_KEY", + system_prompt: name, + tools_profile: profile } - ], - edges: [%{from: "in", to: "llm"}], - settings: %{history: true} - } - end + } + ], + edges: [%{from: "in", to: "llm"}], + settings: %{history: true} + } + end - flow = - Conversation.new( - %{"a" => graph.("Triage", "triage"), "b" => graph.("Billing", "billing")}, - "a", - %{{"a", {:intent, "billing"}} => "b"} - ) + flow = + Conversation.new( + %{"a" => graph.("Triage", "triage"), "b" => graph.("Billing", "billing")}, + "a", + %{{"a", {:intent, "billing"}} => "b"} + ) - {:ok, session} = Conversation.start_session(flow) - on_exit(fn -> if Process.alive?(session), do: AudioFlow.stop_session(session) end) - {:ok, turn} = AudioFlow.submit(session, %AudioFlow.Text{data: "invoice"}) - assert_receive {AudioFlow, ^session, ^turn, {:done, _}}, 10_000 - assert {:ok, "b"} = Conversation.state(session) - assert_receive {:http_request, _, first} - assert hd(first.body["messages"])["content"] == "Triage" - assert [%{"function" => %{"name" => "handoff"}}] = first.body["tools"] - assert_receive {:http_request, _, tool_result} - assert List.last(tool_result.body["messages"])["content"] =~ "billing" - {:ok, next} = AudioFlow.submit(session, %AudioFlow.Text{data: "follow up"}) - assert_receive {AudioFlow, ^session, ^next, {:done, _}} - assert_receive {:http_request, _, final} - refute Map.has_key?(final.body, "tools") + {:ok, session} = Conversation.start_session(flow) + on_exit(fn -> if Process.alive?(session), do: AudioFlow.stop_session(session) end) + {:ok, turn} = AudioFlow.submit(session, %AudioFlow.Text{data: "invoice"}) + assert_receive {AudioFlow, ^session, ^turn, {:done, _}}, 10_000 + assert {:ok, "b"} = Conversation.state(session) + assert_receive {:http_request, _, first} + assert hd(first.body["messages"])["content"] == "Triage" + assert [%{"function" => %{"name" => "handoff"}}] = first.body["tools"] + assert_receive {:http_request, _, tool_result} + assert List.last(tool_result.body["messages"])["content"] =~ "billing" + {:ok, next} = AudioFlow.submit(session, %AudioFlow.Text{data: "follow up"}) + assert_receive {AudioFlow, ^session, ^next, {:done, _}} + assert_receive {:http_request, _, final} + refute Map.has_key?(final.body, "tools") - assert Enum.map(final.body["messages"], & &1["content"]) == [ - "Billing", - "invoice", - "Ready.", - "follow up" - ] - end + assert Enum.map(final.body["messages"], & &1["content"]) == [ + "Billing", + "invoice", + "Ready.", + "follow up" + ] end end diff --git a/test/cross_feature_acceptance_test.exs b/test/cross_feature_acceptance_test.exs index 48aec1b..af410d5 100644 --- a/test/cross_feature_acceptance_test.exs +++ b/test/cross_feature_acceptance_test.exs @@ -93,8 +93,11 @@ defmodule AudioFlow.CrossFeatureAcceptanceTest do |> Keyword.put(:history, true) |> Keyword.put( :llm, - {AudioFlow.Adapters.ChatHTTP, - endpoint: endpoint, model: "protocol-fixture", tools: [tool]} + {AudioFlow.Adapters.ReqLLM, + base_url: String.replace_suffix(endpoint, "/chat/completions", ""), + model: %{provider: :openai, id: "protocol-fixture"}, + api_key: "local", + audio_flow: [tools: [tool]]} ) {:ok, session} = AudioFlow.start_session(options) diff --git a/test/graph_test.exs b/test/graph_test.exs index 13e9780..42d3bd9 100644 --- a/test/graph_test.exs +++ b/test/graph_test.exs @@ -181,17 +181,22 @@ defmodule AudioFlow.GraphTest do end test "node options are checked, and defaults and secrets reach the adapter" do - options = %{"endpoint" => "http://localhost:1/v1/chat/completions", "model" => 1} - graph = update_node(voice(), "llm", &%{&1 | "type" => "llm.chat_http"}) + options = %{"base_url" => "http://localhost:1/v1", "model" => 1} + graph = update_node(voice(), "llm", &%{&1 | "type" => "llm.req_llm"}) graph = update_node(graph, "llm", &Map.put(&1, "options", options)) assert errors(graph) == [~s(node "llm": option model must be a string)] - options = %{options | "model" => "qwen3"} |> Map.put("api_key_env", "KEY") + env = "AUDIOFLOW_GRAPH_TEST_KEY_#{System.unique_integer([:positive])}" + System.put_env(env, "fixture-key") + on_exit(fn -> System.delete_env(env) end) + + options = %{options | "model" => "openai:qwen3"} |> Map.put("api_key_env", env) graph = update_node(graph, "llm", &Map.put(&1, "options", options)) assert {:ok, session} = Graph.session_options(graph, Graph.catalog()) - assert {AudioFlow.Adapters.ChatHTTP, adapter} = session[:graph].steps["llm"].adapter - assert adapter[:timeout_ms] == 30_000 - assert is_function(adapter[:api_key], 0) + assert {AudioFlow.Adapters.ReqLLM, adapter} = session[:graph].steps["llm"].adapter + assert adapter[:base_url] == "http://localhost:1/v1" + assert adapter[:api_key] == "fixture-key" + assert adapter[:audio_flow][:timeout_ms] == 30_000 assert session[:timeout_ms] == 5_000 graph = update_node(graph, "llm", &put_in(&1, ["options", "token"], "x")) diff --git a/test/chat_http_test.exs b/test/req_llm_http_test.exs similarity index 78% rename from test/chat_http_test.exs rename to test/req_llm_http_test.exs index 45b2f91..a9f8dcf 100644 --- a/test/chat_http_test.exs +++ b/test/req_llm_http_test.exs @@ -1,28 +1,19 @@ -defmodule AudioFlow.ChatHTTPTest do +defmodule AudioFlow.ReqLLMHTTPTest do use ExUnit.Case, async: true - alias AudioFlow.Adapters.ChatHTTP alias AudioFlow.Adapters.Demo + alias AudioFlow.Adapters.ReqLLM, as: Bridge alias AudioFlow.Test.HTTPFixture, as: HTTP - test "unsupported legacy parameters require explicit migration rather than being ignored" do - assert_raise ArgumentError, ~r/unsupported legacy parameters top_p.*ReqLLM/, fn -> - ChatHTTP.run( - "Hi", - [ - endpoint: "http://127.0.0.1:1/v1/chat/completions", - model: "fixture", - parameters: %{top_p: 0.8} - ], - fn _ -> :ok end - ) - end - end - defp server(handler) do {child, listener, endpoint} = HTTP.start(self(), handler) start_supervised!(child) on_exit(fn -> :gen_tcp.close(listener) end) - [endpoint: endpoint, model: "fixture-model"] + + [ + model: %{provider: :openai, id: "fixture-model"}, + base_url: String.replace_suffix(endpoint, "/chat/completions", ""), + api_key: "local" + ] end test "text is emitted before EOF and chat roles and credentials reach the endpoint" do @@ -42,27 +33,26 @@ defmodule AudioFlow.ChatHTTPTest do owner = self() options = - options ++ - [ - system: "Be brief.", - api_key: fn -> "fixture-key" end, - parameters: %{temperature: 0, max_completion_tokens: 64, stream: false, n: 9} - ] + Keyword.merge(options, + system_prompt: "Be brief.", + api_key: "fixture-key", + temperature: 0.0, + max_tokens: 64 + ) + + context = + ReqLLM.Context.new([ + ReqLLM.Context.user("First"), + ReqLLM.Context.assistant("Answer"), + ReqLLM.Context.user("Next") + ]) task = Task.async(fn -> - ChatHTTP.run( - [ - %{role: :user, content: "First"}, - %{role: :assistant, content: "Answer"}, - %{role: :user, content: "Next"} - ], - options, - fn text -> - send(owner, {:text, text}) - :ok - end - ) + Bridge.run(context, options, fn text -> + send(owner, {:text, text}) + :ok + end) end) assert_receive {:http_request, server, request} @@ -101,7 +91,7 @@ defmodule AudioFlow.ChatHTTPTest do HTTP.finish(socket) end) - assert {:error, {:http_status, ^status}} = ChatHTTP.run("Hello", options, fn _ -> :ok end) + assert {:error, {:http_status, ^status}} = Bridge.run("Hello", options, fn _ -> :ok end) assert_receive {:http_request, _, _} refute_receive {:http_request, _, _}, 20 end @@ -129,7 +119,7 @@ defmodule AudioFlow.ChatHTTPTest do end) assert {:error, ^expected} = - ChatHTTP.run("Hello", options, fn text -> + Bridge.run("Hello", options, fn text -> send(owner, {:unverified_tail, text}) :ok end) @@ -152,7 +142,9 @@ defmodule AudioFlow.ChatHTTPTest do HTTP.finish(socket) end) - assert {:error, ^expected} = ChatHTTP.run("Hello", options ++ limit, fn _ -> :ok end) + assert {:error, ^expected} = + Bridge.run("Hello", options ++ [audio_flow: limit], fn _ -> :ok end) + assert_receive {:http_request, _, _} end end @@ -161,7 +153,7 @@ defmodule AudioFlow.ChatHTTPTest do options = server(fn socket, _ -> HTTP.headers(socket) end) assert {:error, :request_too_large} = - ChatHTTP.run("Hello", options ++ [max_request_bytes: 2], fn _ -> :ok end) + Bridge.run("Hello", options ++ [audio_flow: [max_request_bytes: 2]], fn _ -> :ok end) refute_receive {:http_request, _, _}, 20 end @@ -180,7 +172,7 @@ defmodule AudioFlow.ChatHTTPTest do end end) - session_options = Keyword.put(Demo.options(), :llm, {ChatHTTP, options}) + session_options = Keyword.put(Demo.options(), :llm, {Bridge, options}) {:ok, session} = AudioFlow.start_session(session_options) on_exit(fn -> if Process.alive?(session), do: AudioFlow.stop_session(session) end) audio = %AudioFlow.Audio{data: <<0, 0>>, sample_rate: 16_000} @@ -211,7 +203,9 @@ defmodule AudioFlow.ChatHTTPTest do end) assert {:error, {:http, _}} = - ChatHTTP.run("Hello", options ++ [receive_timeout_ms: 100], fn _ -> :ok end) + Bridge.run("Hello", options ++ [audio_flow: [receive_timeout_ms: 100]], fn _ -> + :ok + end) assert_receive :connection_closed end @@ -226,7 +220,7 @@ defmodule AudioFlow.ChatHTTPTest do send(owner, {:socket_result, :gen_tcp.recv(socket, 0, 5_000)}) end) - assert catch_throw(ChatHTTP.run("Hello", options, fn _ -> throw(:stop_consuming) end)) == + assert catch_throw(Bridge.run("Hello", options, fn _ -> throw(:stop_consuming) end)) == :stop_consuming assert_receive {:socket_result, {:error, :closed}} @@ -241,6 +235,6 @@ defmodule AudioFlow.ChatHTTPTest do ) end) - assert {:error, :invalid_content_type} = ChatHTTP.run("Hello", options, fn _ -> :ok end) + assert {:error, :invalid_content_type} = Bridge.run("Hello", options, fn _ -> :ok end) end end diff --git a/test/chat_http_model_test.exs b/test/req_llm_model_test.exs similarity index 77% rename from test/chat_http_model_test.exs rename to test/req_llm_model_test.exs index d7d1912..e7019e6 100644 --- a/test/chat_http_model_test.exs +++ b/test/req_llm_model_test.exs @@ -1,4 +1,4 @@ -defmodule AudioFlow.ChatHTTPModelTest do +defmodule AudioFlow.ReqLLMModelTest do use ExUnit.Case, async: false alias AudioFlow.Adapters.Demo @@ -8,18 +8,22 @@ defmodule AudioFlow.ChatHTTPModelTest do test "streamed model output matches an independent nonstreamed response through a session" do input = "What is 2 + 2? Reply with only the number." system = "You are a voice assistant. Reply in one short sentence. Use plain text." + endpoint = System.fetch_env!("AUDIOFLOW_CHAT_ENDPOINT") + model = System.fetch_env!("AUDIOFLOW_LLM") chat_options = [ - endpoint: System.fetch_env!("AUDIOFLOW_CHAT_ENDPOINT"), - model: System.fetch_env!("AUDIOFLOW_LLM"), - system: system, - timeout_ms: 60_000, - parameters: %{temperature: 0, max_tokens: 64} + base_url: String.replace_suffix(endpoint, "/chat/completions", ""), + model: %{provider: :openai, id: model}, + api_key: "local", + system_prompt: system, + temperature: 0.0, + max_tokens: 64, + audio_flow: [timeout_ms: 60_000] ] body = JSON.encode!(%{ - model: chat_options[:model], + model: model, stream: false, temperature: 0, max_tokens: 64, @@ -27,7 +31,7 @@ defmodule AudioFlow.ChatHTTPModelTest do }) request = - Finch.build(:post, chat_options[:endpoint], [{"content-type", "application/json"}], body) + Finch.build(:post, endpoint, [{"content-type", "application/json"}], body) assert {:ok, %Finch.Response{status: 200, body: response}} = Finch.request(request, AudioFlow.HTTPClient, receive_timeout: 60_000) @@ -41,7 +45,7 @@ defmodule AudioFlow.ChatHTTPModelTest do :stt, {AudioFlow.Adapters.Function, run: fn _, emit -> emit.(input) end} ) - |> Keyword.put(:llm, {AudioFlow.Adapters.ChatHTTP, chat_options}) + |> Keyword.put(:llm, {AudioFlow.Adapters.ReqLLM, chat_options}) |> Keyword.put(:timeout_ms, 60_000) {:ok, session} = AudioFlow.start_session(options) diff --git a/test/chat_http_tools_test.exs b/test/req_llm_tools_test.exs similarity index 88% rename from test/chat_http_tools_test.exs rename to test/req_llm_tools_test.exs index 535030d..25a308d 100644 --- a/test/chat_http_tools_test.exs +++ b/test/req_llm_tools_test.exs @@ -1,7 +1,7 @@ -defmodule AudioFlow.ChatHTTPToolsTest do +defmodule AudioFlow.ReqLLMToolsTest do use ExUnit.Case, async: true - alias AudioFlow.Adapters.ChatHTTP alias AudioFlow.Adapters.Demo + alias AudioFlow.Adapters.ReqLLM, as: Bridge alias AudioFlow.Test.HTTPFixture, as: HTTP defmodule Weather do @@ -18,7 +18,14 @@ defmodule AudioFlow.ChatHTTPToolsTest do {child, listener, endpoint} = HTTP.start(self(), handler) start_supervised!(child) on_exit(fn -> :gen_tcp.close(listener) end) - [endpoint: endpoint, model: "fixture-model"] + + [ + model: %{provider: :openai, id: "fixture-model"}, + base_url: String.replace_suffix(endpoint, "/chat/completions", ""), + api_key: "local", + # The default system prompt keeps the message layout these tests assert. + system_prompt: AudioFlow.Prompt.default_system() + ] end defp data(delta, finish \\ nil), @@ -39,7 +46,7 @@ defmodule AudioFlow.ChatHTTPToolsTest do owner = self() result = - ChatHTTP.run(input, options, fn text -> + Bridge.run(input, options, fn text -> send(owner, {:text, text}) :ok end) @@ -85,7 +92,13 @@ defmodule AudioFlow.ChatHTTPToolsTest do options = options ++ - [tools: [Weather, clock], tool_context: %{unit: "C"}, tool_filler: "One moment."] + [ + audio_flow: [ + tools: [Weather, clock], + tool_context: %{unit: "C"}, + tool_filler: "One moment." + ] + ] assert {:ok, ["One moment.", "It is sunny."]} = collect("Weather?", options) @@ -141,7 +154,7 @@ defmodule AudioFlow.ChatHTTPToolsTest do ) end) - options = options ++ [tools: [Weather], tool_filler: "One moment."] + options = options ++ [audio_flow: [tools: [Weather], tool_filler: "One moment."]] assert {:ok, ["Let me check. ", "Done."]} = collect("Hi", options) assert_receive {:http_request, _, _} assert_receive {:http_request, _, second} @@ -160,7 +173,7 @@ defmodule AudioFlow.ChatHTTPToolsTest do ) end) - options = options ++ [tools: [Weather], max_tool_rounds: 2] + options = options ++ [audio_flow: [tools: [Weather], max_tool_rounds: 2]] assert {{:error, :tool_round_limit}, []} = collect("Hi", options) assert_receive {:http_request, _, _} assert_receive {:http_request, _, _} @@ -182,7 +195,10 @@ defmodule AudioFlow.ChatHTTPToolsTest do {data(%{function_call: %{name: "weather"}}), [], :unsupported_tool_call} ] do options = server(fn socket, _ -> reply(socket, body) end) - assert {{:error, ^expected}, []} = collect("Hi", options ++ [tools: [Weather]] ++ extra) + + assert {{:error, ^expected}, []} = + collect("Hi", options ++ [audio_flow: [tools: [Weather]] ++ extra]) + assert_receive {:http_request, _, _} end end @@ -207,7 +223,7 @@ defmodule AudioFlow.ChatHTTPToolsTest do end } - llm = {ChatHTTP, options ++ [tools: [wait]]} + llm = {Bridge, options ++ [audio_flow: [tools: [wait]]]} {:ok, session} = AudioFlow.start_session(Keyword.put(Demo.options(), :llm, llm)) diff --git a/ui/README.md b/ui/README.md index ce49715..91928fb 100644 --- a/ui/README.md +++ b/ui/README.md @@ -70,8 +70,7 @@ claude mcp add --transport http audioflow http://localhost:4100/mcp \ ## Node types The default catalog has the input nodes, `audio.resample`, the demo STT, -LLM, and TTS nodes, `llm.req_llm` for ReqLLM models and endpoints, and the -deprecated `llm.chat_http` chat-completions node. +LLM, and TTS nodes, and `llm.req_llm` for ReqLLM models and endpoints. To add the native model nodes, build with `AUDIOFLOW_ML=1`: @@ -103,7 +102,7 @@ To add node types, write an `AudioFlow.Graph.Node` module and set the list: config :audio_flow_ui, :nodes, [ AudioFlow.Graph.Nodes.Input, AudioFlow.Graph.Nodes.Demo, - AudioFlow.Graph.Nodes.ChatHTTP, + AudioFlow.Graph.Nodes.ReqLLM, MyApp.WhisperNodes ] ``` @@ -129,13 +128,13 @@ These checks do not grade audio or classify intents with a model. Remote speech nodes are deepgram.stt, mistral.stt (Voxtral), elevenlabs.tts and cartesia.tts. Self-hosted Fish Speech is available as fish_audio.tts with an optional reference_id; configure its trusted server endpoint and optional -FISH_SPEECH_API_KEY as described in [providers](../docs/providers.md#fish-audio--self-hosted-fish-speech). +FISH_SPEECH_API_KEY as described in [providers](https://flowcopilot.github.io/audioflow/docs/features/providers/#fish-audio--self-hosted-fish-speech). The hosted Fish Audio node is fish_audio_api.tts; set FISH_AUDIO_API_KEY and select its model and hosted reference_id. It supports configurable PCM rates, including 8 and 16 kHz for telephony. Native Fish on Nx is not currently available. For the hosted providers, create a starter, select its node, and save model, language code and voice options. Cartesia also requires an explicit API version; see -[contracts](../docs/providers.md). Set only the selected provider's +[contracts](https://flowcopilot.github.io/audioflow/docs/features/providers/). Set only the selected provider's DEEPGRAM_API_KEY, MISTRAL_API_KEY, ELEVENLABS_API_KEY or CARTESIA_API_KEY in the **server environment**, using your secret manager. Never paste credentials into graphs, scripts or browser/MCP payloads. Speech @@ -157,7 +156,7 @@ Speech-to-text nodes receive an already committed utterance, not continuous mic ingress. Remote STT nodes use ReqLLM, and whisper.stt uses Bumblebee. OpenAI Realtime and Gemini Live emit mixed transcript/text/audio and cannot occupy single-output graph nodes. Use their dedicated Session examples in -[providers.md](../docs/providers.md). +[providers](https://flowcopilot.github.io/audioflow/docs/features/providers/). ### RAG diff --git a/ui/lib/audio_flow_ui.ex b/ui/lib/audio_flow_ui.ex index 6b76c9c..8a587cb 100644 --- a/ui/lib/audio_flow_ui.ex +++ b/ui/lib/audio_flow_ui.ex @@ -17,7 +17,7 @@ defmodule AudioFlowUI do Graph.Nodes.Input, Graph.Nodes.Audio, Graph.Nodes.Demo, - Graph.Nodes.ChatHTTP, + Graph.Nodes.ReqLLM, Graph.Nodes.Providers, Graph.Nodes.RAG ] diff --git a/ui/lib/audio_flow_ui_web/live/examples_live.ex b/ui/lib/audio_flow_ui_web/live/examples_live.ex index b002480..c5a729e 100644 --- a/ui/lib/audio_flow_ui_web/live/examples_live.ex +++ b/ui/lib/audio_flow_ui_web/live/examples_live.ex @@ -75,7 +75,7 @@ defmodule AudioFlowUIWeb.ExamplesLive do

- RAG retrieves documents; the starter reply is a synthetic echo. Replace demo.llm with llm.chat_http for generated answers. + RAG retrieves documents; the starter reply is a synthetic echo. Replace demo.llm with llm.req_llm for generated answers.

@@ -112,7 +112,7 @@ defmodule AudioFlowUIWeb.ExamplesLive do

Speech-to-speech and standalone transports

OpenAI Realtime and Gemini Live emit transcript, text and audio together. Use the dedicated Session example or chat app; these are not single-output graph nodes.

- Speech-to-speech Session setup + Speech-to-speech Session setup Chat app Official Pipecat SDK RTVI client (typed input/audio output) Telephony loopback diff --git a/ui/test/mcp_test.exs b/ui/test/mcp_test.exs index 4212c0d..4dca87b 100644 --- a/ui/test/mcp_test.exs +++ b/ui/test/mcp_test.exs @@ -12,11 +12,11 @@ defmodule AudioFlowUI.MCPTest do test "an agent builds a graph in steps, then runs it", %{client: client} do assert {:ok, %{structured: %{"node_types" => types}}} = call_tool(client, "list_node_types") - llm = Enum.find(types, &(&1["type"] == "llm.chat_http")) + llm = Enum.find(types, &(&1["type"] == "llm.req_llm")) assert %{"input" => "text", "output" => "text"} = llm assert %{"type" => "string", "required" => true} = - Enum.find(llm["options"], &(&1["name"] == "endpoint")) + Enum.find(llm["options"], &(&1["name"] == "model")) partial = Map.update!(voice(), "edges", &Enum.drop(&1, -1))