diff --git a/README.md b/README.md index bf4f532..9a22ab1 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,13 @@ 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 diff --git a/docs/providers.md b/docs/providers.md index f3aed1f..a5912b9 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -47,6 +47,154 @@ 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 diff --git a/lib/audio_flow/adapters/fish_audio.ex b/lib/audio_flow/adapters/fish_audio.ex new file mode 100644 index 0000000..bd75ae9 --- /dev/null +++ b/lib/audio_flow/adapters/fish_audio.ex @@ -0,0 +1,53 @@ +defmodule AudioFlow.Adapters.FishAudio do + @moduledoc """ + Streaming TTS against a self-hosted Fish Speech `/v1/tts` server. + + Emits mono s16le `AudioFlow.Audio` using the rate from the streaming WAV header. + The model is loaded by the server; `:reference_id` selects a stored voice. + `:endpoint` defaults to `http://127.0.0.1:8080/v1/tts`. `:api_key` is optional + (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. + """ + @behaviour AudioFlow.Adapter + alias AudioFlow.Adapters.Providers.PCMHTTP + alias AudioFlow.Adapters.Providers.Socket + + @impl true + def run(text, options, emit) when is_binary(text) do + options = + Keyword.put_new(options, :receive_timeout_ms, Keyword.get(options, :timeout_ms, 30_000)) + + body = %{text: text, format: "wav", streaming: true} + + body = + case options[:reference_id] do + nil -> + body + + id when is_binary(id) -> + if String.trim(id) == "", do: body, else: Map.put(body, :reference_id, id) + end + + headers = + if options[:api_key] do + case Socket.key(options) do + key when key in [nil, ""] -> [] + key when is_binary(key) -> [{"authorization", "Bearer " <> key}] + end + else + [] + end + + PCMHTTP.run( + Keyword.get(options, :endpoint, "http://127.0.0.1:8080/v1/tts"), + headers, + body, + nil, + options, + emit, + :wav + ) + end +end diff --git a/lib/audio_flow/adapters/fish_audio_api.ex b/lib/audio_flow/adapters/fish_audio_api.ex new file mode 100644 index 0000000..b4df8ba --- /dev/null +++ b/lib/audio_flow/adapters/fish_audio_api.ex @@ -0,0 +1,64 @@ +defmodule AudioFlow.Adapters.FishAudioAPI do + @moduledoc """ + Fish Audio hosted HTTP TTS, emitting mono s16le PCM during the response. + + Requires `:model`, `:reference_id` (a hosted voice ID), and `:api_key` (a string + or zero-argument function). `:sample_rate` defaults to 44,100 Hz; supported + rates are 8,000, 16,000, 24,000, 32,000 and 44,100 Hz. Optional `:language` + controls text normalization, and `:latency` is `"normal"`, `"balanced"` or + `"low"`. The endpoint defaults to `https://api.fish.audio/v1/tts`. + + `: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. + """ + @behaviour AudioFlow.Adapter + alias AudioFlow.Adapters.Providers.PCMHTTP + alias AudioFlow.Adapters.Providers.Socket + + @impl true + def run(text, options, emit) when is_binary(text) do + rate = Keyword.get(options, :sample_rate, 44_100) + + unless rate in [8_000, 16_000, 24_000, 32_000, 44_100], + do: raise(ArgumentError, "unsupported Fish Audio PCM sample rate") + + key = Socket.key(options) + model = nonempty!(Keyword.fetch!(options, :model), :model) + reference = nonempty!(Keyword.fetch!(options, :reference_id), :reference_id) + key = nonempty!(key, :api_key) + latency = Keyword.get(options, :latency, "normal") + + unless latency in ["normal", "balanced", "low"], + do: raise(ArgumentError, "unsupported Fish Audio latency mode") + + body = %{ + text: text, + reference_id: reference, + format: "pcm", + sample_rate: rate, + latency: latency + } + + body = if options[:language], do: Map.put(body, :language, options[:language]), else: body + + options = + Keyword.put_new(options, :receive_timeout_ms, Keyword.get(options, :timeout_ms, 30_000)) + + PCMHTTP.run( + Keyword.get(options, :endpoint, "https://api.fish.audio/v1/tts"), + [{"authorization", "Bearer " <> key}, {"model", model}], + body, + rate, + options, + emit + ) + end + + defp nonempty!(value, name) do + unless is_binary(value) and String.trim(value) != "", + do: raise(ArgumentError, "#{name} must be a nonempty string") + + value + end +end diff --git a/lib/audio_flow/adapters/providers/pcm_http.ex b/lib/audio_flow/adapters/providers/pcm_http.ex index 6608302..1c1033c 100644 --- a/lib/audio_flow/adapters/providers/pcm_http.ex +++ b/lib/audio_flow/adapters/providers/pcm_http.ex @@ -2,7 +2,7 @@ defmodule AudioFlow.Adapters.Providers.PCMHTTP do @moduledoc false alias AudioFlow.Adapters.Providers.Socket - def run(endpoint, headers, body, rate, options, emit) do + def run(endpoint, headers, body, rate, options, emit, format \\ :pcm) do validate_endpoint!(endpoint) body = JSON.encode!(body) @@ -21,7 +21,9 @@ defmodule AudioFlow.Adapters.Providers.PCMHTTP do error: nil, limit: limit, rate: rate, - emit: emit + emit: emit, + format: format, + audio_bytes: 0 } request = @@ -45,10 +47,12 @@ defmodule AudioFlow.Adapters.Providers.PCMHTTP do defp stream_result({:ok, %{error: error}}) when error != nil, do: {:error, error} + defp stream_result({:ok, %{format: :wav}}), do: {:error, :invalid_wav} + defp stream_result({:ok, %{pending: pending}}) when pending != "", do: {:error, :incomplete_sample} - defp stream_result({:ok, %{bytes: 0}}), do: {:error, :empty_response} + defp stream_result({:ok, %{audio_bytes: 0}}), do: {:error, :empty_response} defp stream_result({:ok, _}), do: :ok defp stream_result({:error, _, _}), do: {:error, :http_stream_failed} @@ -63,7 +67,12 @@ defmodule AudioFlow.Adapters.Providers.PCMHTTP do type = type |> String.split(";") |> hd() |> String.trim() |> String.downcase() - if type in ["application/octet-stream", "audio/pcm", "audio/raw", "audio/x-raw"], + types = + if state.format == :wav, + do: ["audio/wav", "audio/x-wav", "audio/wave"], + else: ["application/octet-stream", "audio/pcm", "audio/raw", "audio/x-raw"] + + if type in types, do: {:cont, %{state | type: true}}, else: {:halt, %{state | error: :invalid_content_type}} end @@ -79,13 +88,35 @@ defmodule AudioFlow.Adapters.Providers.PCMHTTP do {:halt, %{state | error: :response_too_large}} true -> - data = state.pending <> chunk - size = byte_size(data) - rem(byte_size(data), 2) - <> = data - if size > 0, do: :ok = state.emit.(%AudioFlow.Audio{data: pcm, sample_rate: state.rate}) - {:cont, %{state | pending: pending, bytes: bytes}} + receive_audio(state.pending <> chunk, %{state | bytes: bytes, pending: ""}) end end defp receive_http({:trailers, _}, state), do: {:cont, state} + + # Fish Speech uses a canonical 44-byte streaming WAV header. Both older zero + # sizes and the current 0xFFFFFFFF sentinel mean PCM until HTTP EOF. + defp receive_audio(data, %{format: :wav} = state) when byte_size(data) < 44, + do: {:cont, %{state | pending: data}} + + defp receive_audio( + <<"RIFF", riff_size::little-32, "WAVEfmt ", 16::little-32, 1::little-16, 1::little-16, + rate::little-32, byte_rate::little-32, 2::little-16, 16::little-16, "data", + data_size::little-32, pcm::binary>>, + %{format: :wav} = state + ) + when rate > 0 and byte_rate == rate * 2 and riff_size in [36, 0xFFFFFFFF] and + data_size in [0, 0xFFFFFFFF] do + receive_audio(pcm, %{state | format: :pcm, rate: rate}) + end + + defp receive_audio(_, %{format: :wav} = state), + do: {:halt, %{state | error: :unsupported_wav}} + + defp receive_audio(data, state) do + size = byte_size(data) - rem(byte_size(data), 2) + <> = data + if size > 0, do: :ok = state.emit.(%AudioFlow.Audio{data: pcm, sample_rate: state.rate}) + {:cont, %{state | pending: pending, audio_bytes: state.audio_bytes + size}} + end end diff --git a/lib/audio_flow/graph/providers.ex b/lib/audio_flow/graph/providers.ex index 9c0d208..51ad8d7 100644 --- a/lib/audio_flow/graph/providers.ex +++ b/lib/audio_flow/graph/providers.ex @@ -9,7 +9,9 @@ defmodule AudioFlow.Graph.Nodes.Providers do "deepgram.stt" => {AudioFlow.STT.ReqLLM, "DEEPGRAM_API_KEY"}, "mistral.stt" => {AudioFlow.STT.ReqLLM, "MISTRAL_API_KEY"}, "elevenlabs.tts" => {AudioFlow.Adapters.ElevenLabs, "ELEVENLABS_API_KEY"}, - "cartesia.tts" => {AudioFlow.Adapters.Cartesia, "CARTESIA_API_KEY"} + "cartesia.tts" => {AudioFlow.Adapters.Cartesia, "CARTESIA_API_KEY"}, + "fish_audio.tts" => {AudioFlow.Adapters.FishAudio, "FISH_SPEECH_API_KEY"}, + "fish_audio_api.tts" => {AudioFlow.Adapters.FishAudioAPI, "FISH_AUDIO_API_KEY"} } @stt_providers %{"deepgram.stt" => :deepgram, "mistral.stt" => :mistral} @@ -17,14 +19,25 @@ defmodule AudioFlow.Graph.Nodes.Providers do def providers, do: @providers @impl true + def prerequisites("fish_audio.tts", _options) do + endpoint = Application.get_env(:audio_flow, :speech_provider_endpoints, %{})["fish_audio.tts"] + + if endpoint in [nil, ""], + do: ["configure speech_provider_endpoints for fish_audio.tts in the server application"], + else: [] + end + def prerequisites(type, _options) do {_module, env} = Map.fetch!(@providers, type) if System.get_env(env) in [nil, ""], do: ["set #{env} in the server environment"], else: [] end @impl true - def nodes do - for {type, {_adapter, env}} <- Enum.sort(@providers) do + def nodes, do: remote_nodes() ++ [fish_node(), fish_api_node()] + + defp remote_nodes do + for {type, {_adapter, env}} <- Enum.sort(@providers), + type not in ["fish_audio.tts", "fish_audio_api.tts"] do stt? = String.ends_with?(type, ".stt") %{ @@ -67,6 +80,69 @@ defmodule AudioFlow.Graph.Nodes.Providers do end end + defp fish_node do + %{ + type: "fish_audio.tts", + title: "Fish Speech (self-hosted)", + description: + "Self-hosted Fish Speech TTS; configure a trusted server endpoint. Optional server API key.", + input: :text, + output: :audio, + event: :audio, + input_mode: :stream, + options: [ + %{ + name: :reference_id, + type: :string, + description: "Stored voice reference ID; omit for the model default." + }, + %{name: :timeout_ms, type: :integer, default: 30_000}, + %{ + name: :receive_timeout_ms, + type: :integer, + description: + "Maximum idle wait for audio; defaults to timeout_ms. Increase for slow or cold servers." + } + ] + } + end + + defp fish_api_node do + %{ + fish_node() + | type: "fish_audio_api.tts", + title: "Fish Audio API", + description: + "Hosted Fish Audio TTS; requires server FISH_AUDIO_API_KEY and a hosted voice ID.", + options: + [ + %{ + name: :model, + type: :string, + required: true, + description: "Hosted TTS model, e.g. s2.1-pro." + }, + %{ + name: :reference_id, + type: :string, + required: true, + description: "Hosted voice model ID." + }, + %{ + name: :sample_rate, + type: {:enum, [8_000, 16_000, 24_000, 32_000, 44_100]}, + default: 44_100 + }, + %{ + name: :language, + type: :string, + description: "Optional text-normalization language, e.g. en or ro." + }, + %{name: :latency, type: {:enum, ["normal", "balanced", "low"]}, default: "normal"} + ] ++ Enum.reject(fish_node().options, &(&1.name == :reference_id)) + } + end + @impl true # STT nodes use ReqLLM with a fixed provider, so graph data cannot select another # one. ReqLLM reads the provider key at request time. A trusted endpoint is the @@ -85,6 +161,10 @@ defmodule AudioFlow.Graph.Nodes.Providers do def adapter(type, options) do {module, env} = Map.fetch!(@providers, type) endpoint = Application.get_env(:audio_flow, :speech_provider_endpoints, %{})[type] + + if type == "fish_audio.tts" and endpoint in [nil, ""], + do: raise(ArgumentError, "configure speech_provider_endpoints for fish_audio.tts") + trusted = if endpoint, do: [endpoint: endpoint], else: [] {module, Map.to_list(options) ++ trusted ++ [api_key: fn -> System.get_env(env) end]} end diff --git a/site/src/content/docs/docs/features/providers.md b/site/src/content/docs/docs/features/providers.md index a1dfe9a..7098acc 100644 --- a/site/src/content/docs/docs/features/providers.md +++ b/site/src/content/docs/docs/features/providers.md @@ -1,6 +1,6 @@ --- title: Remote speech providers -description: ReqLLM speech-to-text (Deepgram, Voxtral and others), Cartesia, ElevenLabs, OpenAI Realtime, and Gemini Live adapters. +description: ReqLLM speech-to-text (Deepgram, Voxtral and others), Cartesia, ElevenLabs, hosted Fish Audio and self-hosted Fish Speech, OpenAI Realtime, and Gemini Live adapters. --- These adapters make real network requests. The regression suite uses local HTTP @@ -50,6 +50,154 @@ 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 `AudioFlow.Adapters.OpenAIRealtime.run/3` and diff --git a/test/remote_providers_test.exs b/test/remote_providers_test.exs index 5f94b79..20d3cb8 100644 --- a/test/remote_providers_test.exs +++ b/test/remote_providers_test.exs @@ -2,6 +2,8 @@ defmodule AudioFlow.RemoteProvidersTest do use ExUnit.Case, async: true alias AudioFlow.Adapters.Cartesia alias AudioFlow.Adapters.ElevenLabs + alias AudioFlow.Adapters.FishAudio + alias AudioFlow.Adapters.FishAudioAPI alias AudioFlow.Adapters.GeminiLive alias AudioFlow.Adapters.OpenAIRealtime alias AudioFlow.Audio @@ -348,11 +350,23 @@ defmodule AudioFlow.RemoteProvidersTest do assert_receive {:peer_result, {:error, :closed}}, 3_000 end - test "both HTTP TTS providers request raw PCM and stream before EOF across odd byte boundaries" do - for provider <- [Cartesia, ElevenLabs] do + test "HTTP TTS providers stream before EOF across odd byte boundaries" do + for provider <- [Cartesia, ElevenLabs, FishAudio, FishAudioAPI] do options = http_options(fn socket, _ -> - pcm_headers(socket) + pcm_headers(socket, if(provider == FishAudio, do: "audio/wav", else: "audio/pcm")) + + if provider == FishAudio do + <> = fish_header() + HTTP.chunk(socket, first) + + receive do + :header_rest -> :ok + end + + HTTP.chunk(socket, rest) + end + HTTP.chunk(socket, <<1, 0, 2>>) receive do @@ -363,6 +377,20 @@ defmodule AudioFlow.RemoteProvidersTest do HTTP.finish(socket) end) + options = + if provider == FishAudioAPI do + Keyword.merge(options, + reference_id: "hosted-voice", + model: "s2.1-pro", + api_key: fn -> "api-key" end, + sample_rate: 16_000, + language: "ro", + latency: "balanced" + ) + else + options + end + owner = self() task = @@ -375,29 +403,240 @@ defmodule AudioFlow.RemoteProvidersTest do assert_receive {:http_request, server, request} - if provider == Cartesia do - assert request.headers["authorization"] == "Bearer key" - assert request.headers["cartesia-version"] == "2026-03-01" - assert request.body["voice"] == "voice" + if provider == FishAudio do + refute_receive {:pcm, _}, 20 + send(server, :header_rest) + end - assert request.body["output_format"] == %{ - "container" => "raw", - "encoding" => "pcm_s16le", - "sample_rate" => 24_000 - } - else - assert request.headers["xi-api-key"] == "key" - assert request.line =~ "output_format=pcm_24000" - assert request.body["text"] == "Hello" + case provider do + Cartesia -> + assert request.headers["authorization"] == "Bearer key" + assert request.headers["cartesia-version"] == "2026-03-01" + assert request.body["voice"] == "voice" + + assert request.body["output_format"] == %{ + "container" => "raw", + "encoding" => "pcm_s16le", + "sample_rate" => 24_000 + } + + FishAudio -> + assert request.headers["authorization"] == "Bearer key" + assert request.body == %{"text" => "Hello", "format" => "wav", "streaming" => true} + + FishAudioAPI -> + assert request.headers["authorization"] == "Bearer api-key" + assert request.headers["model"] == "s2.1-pro" + assert request.headers["content-type"] == "application/json" + + assert request.body == %{ + "text" => "Hello", + "format" => "pcm", + "reference_id" => "hosted-voice", + "sample_rate" => 16_000, + "language" => "ro", + "latency" => "balanced" + } + + ElevenLabs -> + assert request.headers["xi-api-key"] == "key" + assert request.line =~ "output_format=pcm_24000" + assert request.body["text"] == "Hello" end - assert_receive {:pcm, %Audio{data: <<1, 0>>, sample_rate: 24_000}} + rate = + case provider do + FishAudio -> 44_100 + FishAudioAPI -> 16_000 + _ -> 24_000 + end + + assert_receive {:pcm, %Audio{data: <<1, 0>>, sample_rate: ^rate}} send(server, :continue) assert :ok = Task.await(task) assert_receive {:pcm, %Audio{data: <<2, 0>>}} end end + test "hosted Fish Audio defaults to 44.1 kHz and rejects unusable configuration before HTTP" do + options = + http_options(fn socket, _ -> + pcm_headers(socket) + HTTP.chunk(socket, <<1, 0>>) + HTTP.finish(socket) + end) + |> Keyword.put(:reference_id, "hosted-voice") + + assert :ok = + FishAudioAPI.run("Hello", options, fn audio -> + send(self(), {:pcm, audio}) + :ok + end) + + assert_receive {:pcm, %Audio{data: <<1, 0>>, sample_rate: 44_100}} + + assert_receive {:http_request, _, + %{body: %{"format" => "pcm", "sample_rate" => 44_100, "latency" => "normal"}}} + + for extra <- [ + [sample_rate: 22_050], + [sample_rate: 48_000], + [latency: "invalid"], + [reference_id: ""], + [reference_id: " \t"], + [model: ""], + [api_key: fn -> nil end], + [api_key: fn -> "" end] + ] do + assert_raise ArgumentError, fn -> + FishAudioAPI.run("Hi", Keyword.merge(options, extra), fn _ -> flunk("unexpected PCM") end) + end + end + + refute_receive {:http_request, _, _} + end + + # Independent wire fixture matching Python wave's canonical streaming header. + defp fish_header(rate \\ 44_100, channels \\ 1, bits \\ 16, size \\ 0xFFFFFFFF) do + riff_size = if size == 0, do: 36, else: 0xFFFFFFFF + align = div(channels * bits, 8) + + <<"RIFF", riff_size::little-32, "WAVEfmt ", 16::little-32, 1::little-16, channels::little-16, + rate::little-32, rate * align::little-32, align::little-16, bits::little-16, "data", + size::little-32>> + end + + test "Fish Speech supports unauthenticated local servers, reference voices and legacy WAV headers" do + options = + http_options(fn socket, _ -> + pcm_headers(socket, "audio/wav") + HTTP.chunk(socket, fish_header(48_000, 1, 16, 0) <> <<3, 0>>) + HTTP.finish(socket) + end) + |> Keyword.delete(:api_key) + |> Keyword.put(:reference_id, "narrator") + + assert :ok = + FishAudio.run("[whisper] Hello", options, fn audio -> + send(self(), {:pcm, audio}) + :ok + end) + + assert_receive {:http_request, _, request} + refute Map.has_key?(request.headers, "authorization") + assert request.body["reference_id"] == "narrator" + assert request.body["text"] == "[whisper] Hello" + assert_receive {:pcm, %Audio{data: <<3, 0>>, sample_rate: 48_000}} + end + + test "Fish Speech rejects invalid WAV streams and enforces HTTP budgets" do + for {type, data, extra, expected} <- [ + {"audio/mpeg", <<1, 2>>, [], :invalid_content_type}, + {"audio/wav", "RIFF", [], :invalid_wav}, + {"audio/wav", fish_header(44_100, 2), [], :unsupported_wav}, + {"audio/wav", fish_header(44_100, 1, 32), [], :unsupported_wav}, + {"audio/wav", String.duplicate("x", 44), [], :unsupported_wav}, + {"audio/wav", fish_header(), [], :empty_response}, + {"audio/wav", fish_header() <> <<1>>, [], :incomplete_sample}, + {"audio/wav", fish_header() <> <<1, 0>>, [max_response_bytes: 45], :response_too_large} + ] do + options = + http_options(fn socket, _ -> + pcm_headers(socket, type) + HTTP.chunk(socket, data) + HTTP.finish(socket) + end) + + assert {:error, ^expected} = + FishAudio.run("Hi", options ++ extra, fn _ -> flunk("unexpected PCM") end) + end + + options = + http_options(fn socket, _ -> + HTTP.headers(socket, 401) + HTTP.finish(socket) + end) + + assert {:error, {:http_status, 401}} = FishAudio.run("Hi", options, fn _ -> :ok end) + + assert {:error, :request_too_large} = + FishAudio.run("Hi", options ++ [max_request_bytes: 1], fn _ -> :ok end) + end + + test "Fish Speech omits blank reference IDs and resolves optional API-key callbacks" do + for {reference, key} <- [{nil, nil}, {"", ""}, {" \t", "rotated-key"}] do + options = + http_options(fn socket, _ -> + pcm_headers(socket, "audio/wav") + HTTP.chunk(socket, fish_header() <> <<1, 0>>) + HTTP.finish(socket) + end) + + options = Keyword.merge(options, reference_id: reference, api_key: fn -> key end) + assert :ok = FishAudio.run("Hi", options, fn _ -> :ok end) + assert_receive {:http_request, _, request} + refute Map.has_key?(request.body, "reference_id") + expected = if key in [nil, ""], do: nil, else: "Bearer " <> key + assert request.headers["authorization"] == expected + end + end + + test "Fish Speech rejects premature HTTP EOF after headers or partial PCM" do + for pcm <- [<<>>, <<1, 0, 2>>] do + options = + http_options(fn socket, _ -> + pcm_headers(socket, "audio/wav") + HTTP.chunk(socket, fish_header() <> pcm) + # The fixture closes without the terminating HTTP chunk. + end) + + assert {:error, :http_stream_failed} = FishAudio.run("Hi", options, fn _ -> :ok end) + end + end + + test "Fish Speech idle timeout closes the connection before or during the WAV header" do + owner = self() + + for partial <- [<<>>, "RIFF"] do + options = + http_options(fn socket, _ -> + pcm_headers(socket, "audio/wav") + if partial != <<>>, do: HTTP.chunk(socket, partial) + send(owner, {:peer_result, :gen_tcp.recv(socket, 0, 2_000)}) + end) + + options = Keyword.merge(options, timeout_ms: 1_000, receive_timeout_ms: 40) + + assert {:error, :http_stream_failed} = + FishAudio.run("Hi", options, fn _ -> flunk("unexpected PCM") end) + + assert_receive {:peer_result, {:error, :closed}}, 3_000 + end + end + + test "Fish Speech cancellation closes the HTTP stream" do + owner = self() + + options = + http_options(fn socket, _ -> + pcm_headers(socket, "audio/wav") + HTTP.chunk(socket, fish_header() <> <<1, 0>>) + send(owner, {:peer_result, :gen_tcp.recv(socket, 0, 2_000)}) + end) + + task = + Task.async(fn -> + FishAudio.run("Hi", options, fn audio -> + send(owner, {:pcm, audio}) + :ok + end) + end) + + assert_receive {:pcm, _} + Task.shutdown(task, :brutal_kill) + assert_receive {:peer_result, {:error, :closed}}, 3_000 + end + test "TTS rejects status errors, compressed audio, incomplete samples, empty and oversized responses" do for {type, bytes, extra, expected} <- [ {"application/json", "{}", [], :invalid_content_type}, diff --git a/ui/README.md b/ui/README.md index ab8fa7a..ce49715 100644 --- a/ui/README.md +++ b/ui/README.md @@ -127,14 +127,20 @@ respect graph history settings. MCP offers evaluate_conversation with id/script. 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. Create a starter, select its node, and save model, language code +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). +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 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 nodes accept neither raw keys nor arbitrary environment-variable names or URLs. -A missing key disables dashboard runs and returns an MCP prerequisite error. +For hosted providers, a missing key disables dashboard runs and returns an MCP prerequisite error. Key presence is not evidence of account/model access. STT graphs accept committed mono signed 16-bit little-endian PCM uploads, diff --git a/ui/test/provider_graph_test.exs b/ui/test/provider_graph_test.exs index a5def09..354d03a 100644 --- a/ui/test/provider_graph_test.exs +++ b/ui/test/provider_graph_test.exs @@ -10,18 +10,37 @@ defmodule AudioFlowUI.ProviderGraphTest do {:ok, body, conn} = Conn.read_body(conn) send(owner, {:provider_request, conn.req_headers, Jason.decode!(body), conn.query_string}) - conn - |> Conn.put_resp_content_type("audio/pcm") - |> Conn.send_resp(status, <<1, 0, 2, 0>>) + if conn.request_path == "/fish" do + # Canonical zero-length streaming WAV header, followed by PCM. + header = AudioFlow.Wav.encode(%AudioFlow.Audio{data: <<>>, sample_rate: 44_100}) + + conn + |> Conn.put_resp_content_type("audio/wav") + |> Conn.send_resp(status, header <> <<1, 0, 2, 0>>) + else + conn |> Conn.put_resp_content_type("audio/pcm") |> Conn.send_resp(status, <<1, 0, 2, 0>>) + end end end setup do original = System.get_env("ELEVENLABS_API_KEY") + original_fish = System.get_env("FISH_AUDIO_API_KEY") + original_speech = System.get_env("FISH_SPEECH_API_KEY") + System.delete_env("FISH_SPEECH_API_KEY") + System.delete_env("FISH_AUDIO_API_KEY") endpoints = Application.get_env(:audio_flow, :speech_provider_endpoints) System.put_env("ELEVENLABS_API_KEY", "fixture-key") on_exit(fn -> + if original_speech, + do: System.put_env("FISH_SPEECH_API_KEY", original_speech), + else: System.delete_env("FISH_SPEECH_API_KEY") + + if original_fish, + do: System.put_env("FISH_AUDIO_API_KEY", original_fish), + else: System.delete_env("FISH_AUDIO_API_KEY") + if original, do: System.put_env("ELEVENLABS_API_KEY", original), else: System.delete_env("ELEVENLABS_API_KEY") @@ -72,6 +91,116 @@ defmodule AudioFlowUI.ProviderGraphTest do assert URI.decode_query(query)["output_format"] == "pcm_24000" end + test "Fish Speech graph uses the trusted server endpoint and resolves authentication per run" do + graph = graph(200) + endpoints = Application.fetch_env!(:audio_flow, :speech_provider_endpoints) + + Application.put_env(:audio_flow, :speech_provider_endpoints, %{ + "fish_audio.tts" => String.replace(endpoints["elevenlabs.tts"], "/tts", "/fish") + }) + + graph = + put_in(graph, ["nodes", Access.at(1)], %{ + "id" => graph["nodes"] |> Enum.at(1) |> Map.fetch!("id"), + "type" => "fish_audio.tts", + "options" => %{"reference_id" => "narrator"} + }) + + System.put_env("FISH_AUDIO_API_KEY", "hosted-only-key") + + for key <- [nil, "graph-key"] do + if key, do: System.put_env("FISH_SPEECH_API_KEY", key) + + assert {:ok, + %{ + "status" => "done", + "events" => [ + %{"type" => "audio", "bytes" => 4, "sample_rate" => 44_100} + ] + }} = AudioFlowUI.Runs.run_text(graph, "Salut") + + assert_receive {:provider_request, headers, + %{ + "text" => "Salut", + "reference_id" => "narrator", + "format" => "wav", + "streaming" => true + }, _} + + assert List.keyfind(headers, "authorization", 0) == + if(key, do: {"authorization", "Bearer " <> key}, else: nil) + end + + Application.delete_env(:audio_flow, :speech_provider_endpoints) + assert {:error, errors} = AudioFlowUI.Runs.run_text(graph, "Salut") + assert Enum.any?(errors, &String.contains?(&1, "speech_provider_endpoints")) + refute_receive {:provider_request, _, _, _} + end + + test "Fish Speech graph accepts an explicit idle timeout" do + graph = graph(200) + endpoints = Application.fetch_env!(:audio_flow, :speech_provider_endpoints) + + Application.put_env(:audio_flow, :speech_provider_endpoints, %{ + "fish_audio.tts" => String.replace(endpoints["elevenlabs.tts"], "/tts", "/fish") + }) + + graph = + put_in(graph, ["nodes", Access.at(1)], %{ + "id" => graph["nodes"] |> Enum.at(1) |> Map.fetch!("id"), + "type" => "fish_audio.tts", + "options" => %{"receive_timeout_ms" => 60_000, "timeout_ms" => 90_000} + }) + + assert {:ok, %{"status" => "done"}} = AudioFlowUI.Runs.run_text(graph, "Salut") + end + + test "hosted Fish Audio graph requires a key and selects its own PCM rate and model" do + System.put_env("FISH_SPEECH_API_KEY", "self-hosted-only-key") + graph = graph(200) + endpoints = Application.fetch_env!(:audio_flow, :speech_provider_endpoints) + + Application.put_env(:audio_flow, :speech_provider_endpoints, %{ + "fish_audio_api.tts" => endpoints["elevenlabs.tts"] + }) + + graph = + put_in(graph, ["nodes", Access.at(1)], %{ + "id" => graph["nodes"] |> Enum.at(1) |> Map.fetch!("id"), + "type" => "fish_audio_api.tts", + "options" => %{ + "model" => "s2.1-pro", + "reference_id" => "hosted-voice", + "sample_rate" => 16_000 + } + }) + + assert {:error, errors} = AudioFlowUI.Runs.run_text(graph, "Salut") + assert Enum.any?(errors, &String.contains?(&1, "FISH_AUDIO_API_KEY")) + refute_receive {:provider_request, _, _, _} + + System.put_env("FISH_AUDIO_API_KEY", "api-graph-key") + + assert {:ok, + %{ + "status" => "done", + "events" => [ + %{"type" => "audio", "bytes" => 4, "sample_rate" => 16_000} + ] + }} = AudioFlowUI.Runs.run_text(graph, "Salut") + + assert_receive {:provider_request, headers, + %{ + "text" => "Salut", + "reference_id" => "hosted-voice", + "format" => "pcm", + "sample_rate" => 16_000 + }, _} + + assert {"authorization", "Bearer api-graph-key"} in headers + assert {"model", "s2.1-pro"} in headers + end + test "remote failure produces a graph error without exposing provider key or body" do assert {:ok, %{"status" => "error"} = result} = AudioFlowUI.Runs.run_text(graph(401), "Salut") refute Jason.encode!(result) =~ "fixture-key"