From f5df794a4d5948224993e8aa3b205cc2d57416b7 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 15:47:52 +0200 Subject: [PATCH 1/6] refactor(graph): keep node behavior and adapter context with owners --- lib/audio_flow/adapter.ex | 12 ++ lib/audio_flow/adapters/chat_http.ex | 6 + lib/audio_flow/adapters/req_llm.ex | 7 ++ lib/audio_flow/graph.ex | 3 - lib/audio_flow/graph/node.ex | 4 +- lib/audio_flow/graph/nodes/audio.ex | 34 +++++ .../graph/{nodes.ex => nodes/chat_http.ex} | 116 ------------------ lib/audio_flow/graph/nodes/demo.ex | 37 ++++++ lib/audio_flow/graph/nodes/input.ex | 22 ++++ lib/audio_flow/graph/prerequisites.ex | 23 ++++ lib/audio_flow/graph/providers.ex | 6 + lib/audio_flow/graph/rag.ex | 12 ++ lib/audio_flow/graph/runner.ex | 19 +-- lib/audio_flow/resampler.ex | 24 +++- lib_ml/audio_flow/graph/model_adapter.ex | 24 ++++ lib_ml/audio_flow/graph/models.ex | 26 ---- 16 files changed, 209 insertions(+), 166 deletions(-) create mode 100644 lib/audio_flow/graph/nodes/audio.ex rename lib/audio_flow/graph/{nodes.ex => nodes/chat_http.ex} (52%) create mode 100644 lib/audio_flow/graph/nodes/demo.ex create mode 100644 lib/audio_flow/graph/nodes/input.ex create mode 100644 lib/audio_flow/graph/prerequisites.ex create mode 100644 lib_ml/audio_flow/graph/model_adapter.ex diff --git a/lib/audio_flow/adapter.ex b/lib/audio_flow/adapter.ex index 42557d2..b39869e 100644 --- a/lib/audio_flow/adapter.ex +++ b/lib/audio_flow/adapter.ex @@ -15,6 +15,18 @@ defmodule AudioFlow.Adapter do @callback run(input :: term(), options :: keyword(), emit :: (term() -> :ok)) :: :ok | {:error, term()} + @doc "Merges per-run context into adapter options when the adapter supports it." + @callback with_context(options :: keyword(), context :: map()) :: keyword() + @optional_callbacks with_context: 2 + + def with_context({module, options}, context) do + Code.ensure_loaded!(module) + + if function_exported?(module, :with_context, 2), + do: {module, module.with_context(options, context)}, + else: {module, options} + end + def run({module, options}, input, emit) do case module.run(input, options, emit) do :ok -> :ok diff --git a/lib/audio_flow/adapters/chat_http.ex b/lib/audio_flow/adapters/chat_http.ex index b1e6ee9..b032d0e 100644 --- a/lib/audio_flow/adapters/chat_http.ex +++ b/lib/audio_flow/adapters/chat_http.ex @@ -7,6 +7,12 @@ defmodule AudioFlow.Adapters.ChatHTTP do 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) diff --git a/lib/audio_flow/adapters/req_llm.ex b/lib/audio_flow/adapters/req_llm.ex index 28e851c..49a82c3 100644 --- a/lib/audio_flow/adapters/req_llm.ex +++ b/lib/audio_flow/adapters/req_llm.ex @@ -29,6 +29,13 @@ defmodule AudioFlow.Adapters.ReqLLM do alias ReqLLM.Streaming.SSE alias ReqLLM.ToolCall + @impl AudioFlow.Adapter + def with_context(options, context) do + execution = Keyword.get(options, :audio_flow, []) + context = Map.merge(Keyword.get(execution, :tool_context, %{}), context) + Keyword.put(options, :audio_flow, Keyword.put(execution, :tool_context, context)) + end + @impl true def run(input, options, emit) do {execution, opts} = Keyword.pop(options, :audio_flow, []) diff --git a/lib/audio_flow/graph.ex b/lib/audio_flow/graph.ex index a85056c..f0707dc 100644 --- a/lib/audio_flow/graph.ex +++ b/lib/audio_flow/graph.ex @@ -59,7 +59,6 @@ defmodule AudioFlow.Graph do defp add_type(catalog, module, spec), do: Map.put(catalog, spec.type, {module, complete_spec(spec)}) - # Defaults for the optional spec keys. See `AudioFlow.Graph.Node`. defp complete_spec(spec) do spec = Map.merge( @@ -304,7 +303,6 @@ defmodule AudioFlow.Graph do defp fetch_node(nodes, declared, id) do cond do Map.has_key?(nodes, id) -> {:ok, nodes[id]} - # An invalid node is reported once, as a node error. MapSet.member?(declared, id) -> :skip true -> {:error, "edge refers to unknown node #{inspect(id)}"} end @@ -364,7 +362,6 @@ defmodule AudioFlow.Graph do else: reach(Map.get(targets, id, []) ++ rest, targets, MapSet.put(reached, id)) end - # Depth-first search. A node on the current path that is seen again closes a cycle. defp cycles(ids, targets) do {_, errors} = Enum.reduce(Enum.sort(ids), {MapSet.new(), []}, fn id, {done, errors} -> diff --git a/lib/audio_flow/graph/node.ex b/lib/audio_flow/graph/node.ex index b807fc6..74a6a67 100644 --- a/lib/audio_flow/graph/node.ex +++ b/lib/audio_flow/graph/node.ex @@ -45,5 +45,7 @@ defmodule AudioFlow.Graph.Node do @callback nodes() :: [spec()] @callback adapter(type :: String.t(), options :: map()) :: {module(), keyword()} - @optional_callbacks adapter: 2 + @doc "Server configuration errors for a type and its unvalidated, string-keyed options." + @callback prerequisites(type :: String.t(), options :: map()) :: [String.t()] + @optional_callbacks adapter: 2, prerequisites: 2 end diff --git a/lib/audio_flow/graph/nodes/audio.ex b/lib/audio_flow/graph/nodes/audio.ex new file mode 100644 index 0000000..1942817 --- /dev/null +++ b/lib/audio_flow/graph/nodes/audio.ex @@ -0,0 +1,34 @@ +defmodule AudioFlow.Graph.Nodes.Audio do + @moduledoc "Audio conversion nodes." + @behaviour AudioFlow.Graph.Node + + @rates [8_000, 16_000, 22_050, 24_000, 44_100, 48_000] + + @impl true + def nodes do + [ + %{ + type: "audio.resample", + title: "Resample", + description: "Converts the complete PCM input to another sample rate.", + input: :audio, + output: :audio, + options: [ + %{ + name: :sample_rate, + type: {:enum, @rates}, + default: 16_000, + description: "Output sample rate in Hz. Whisper needs 16000." + } + ] + } + ] + end + + @impl true + def adapter("audio.resample", %{sample_rate: rate}), + do: {AudioFlow.Adapters.Function, [run: fn audio, emit -> emit.(resample(audio, rate)) end]} + + @doc "Linear interpolation of mono signed 16-bit PCM." + defdelegate resample(audio, rate), to: AudioFlow.Resampler, as: :linear +end diff --git a/lib/audio_flow/graph/nodes.ex b/lib/audio_flow/graph/nodes/chat_http.ex similarity index 52% rename from lib/audio_flow/graph/nodes.ex rename to lib/audio_flow/graph/nodes/chat_http.ex index c13ce60..2381385 100644 --- a/lib/audio_flow/graph/nodes.ex +++ b/lib/audio_flow/graph/nodes/chat_http.ex @@ -1,64 +1,3 @@ -defmodule AudioFlow.Graph.Nodes.Input do - @moduledoc "Input nodes. Each one marks an input type that the agent accepts." - @behaviour AudioFlow.Graph.Node - - @impl true - def nodes do - for {kind, title, description} <- [ - {:audio, "Audio input", "Mono 16-bit PCM from a microphone or a file."}, - {:image, "Image input", "RGB images or video frames."}, - {:text, "Text input", "Typed messages. They go directly to the LLM."} - ] do - %{ - type: "input.#{kind}", - title: title, - description: description, - input: nil, - output: kind, - options: [] - } - end - end -end - -defmodule AudioFlow.Graph.Nodes.Demo do - @moduledoc "Synthetic nodes for setup checks. See `AudioFlow.Adapters.Demo`." - @behaviour AudioFlow.Graph.Node - - @impl true - def nodes do - [ - spec("demo.stt", "Demo STT", "Emits a fixed transcript.", :audio, :text, - event: :transcript - ), - spec("demo.llm", "Demo LLM", "Repeats the prompt.", :text, :text, history: true), - spec("demo.tts", "Demo TTS", "Emits 50 ms of silent PCM.", :text, :audio, - input_mode: :stream - ) - ] - end - - @impl true - def adapter(type, _options) do - stage = Map.fetch!(%{"demo.stt" => :stt, "demo.llm" => :llm, "demo.tts" => :tts}, type) - {AudioFlow.Adapters.Demo, [stage: stage]} - end - - defp spec(type, title, description, input, output, extra) do - Map.merge( - %{ - type: type, - title: title, - description: description, - input: input, - output: output, - options: [] - }, - Map.new(extra) - ) - end -end - defmodule AudioFlow.Graph.Nodes.ChatHTTP do @moduledoc "ReqLLM inference nodes, including the deprecated chat-completions configuration node." @behaviour AudioFlow.Graph.Node @@ -160,58 +99,3 @@ defmodule AudioFlow.Graph.Nodes.ChatHTTP do {AudioFlow.Adapters.ChatHTTP, Keyword.put(adapter_options, :tools, tools)} end end - -defmodule AudioFlow.Graph.Nodes.Audio do - @moduledoc "Audio conversion nodes." - @behaviour AudioFlow.Graph.Node - alias AudioFlow.Audio - - @rates [8_000, 16_000, 22_050, 24_000, 44_100, 48_000] - - @impl true - def nodes do - [ - %{ - type: "audio.resample", - title: "Resample", - description: "Converts the complete PCM input to another sample rate.", - input: :audio, - output: :audio, - options: [ - %{ - name: :sample_rate, - type: {:enum, @rates}, - default: 16_000, - description: "Output sample rate in Hz. Whisper needs 16000." - } - ] - } - ] - end - - @impl true - def adapter("audio.resample", %{sample_rate: rate}), - do: {AudioFlow.Adapters.Function, [run: fn audio, emit -> emit.(resample(audio, rate)) end]} - - @doc "Linear interpolation of mono signed 16-bit PCM." - def resample(%Audio{sample_rate: rate} = audio, rate), do: audio - - def resample(%Audio{data: data, sample_rate: from}, to) do - samples = for <>, do: sample - input = List.to_tuple(samples) - count = tuple_size(input) - length = if count == 0, do: 0, else: max(1, div(count * to, from)) - - pcm = - for index <- 0..(length - 1)//1, into: <<>> do - position = index * from / to - left = min(trunc(position), count - 1) - right = min(left + 1, count - 1) - weight = position - left - sample = round(elem(input, left) * (1 - weight) + elem(input, right) * weight) - <> - end - - %Audio{data: pcm, sample_rate: to} - end -end diff --git a/lib/audio_flow/graph/nodes/demo.ex b/lib/audio_flow/graph/nodes/demo.ex new file mode 100644 index 0000000..452a1aa --- /dev/null +++ b/lib/audio_flow/graph/nodes/demo.ex @@ -0,0 +1,37 @@ +defmodule AudioFlow.Graph.Nodes.Demo do + @moduledoc "Synthetic nodes for setup checks. See `AudioFlow.Adapters.Demo`." + @behaviour AudioFlow.Graph.Node + + @impl true + def nodes do + [ + spec("demo.stt", "Demo STT", "Emits a fixed transcript.", :audio, :text, + event: :transcript + ), + spec("demo.llm", "Demo LLM", "Repeats the prompt.", :text, :text, history: true), + spec("demo.tts", "Demo TTS", "Emits 50 ms of silent PCM.", :text, :audio, + input_mode: :stream + ) + ] + end + + @impl true + def adapter(type, _options) do + stage = Map.fetch!(%{"demo.stt" => :stt, "demo.llm" => :llm, "demo.tts" => :tts}, type) + {AudioFlow.Adapters.Demo, [stage: stage]} + end + + defp spec(type, title, description, input, output, extra) do + Map.merge( + %{ + type: type, + title: title, + description: description, + input: input, + output: output, + options: [] + }, + Map.new(extra) + ) + end +end diff --git a/lib/audio_flow/graph/nodes/input.ex b/lib/audio_flow/graph/nodes/input.ex new file mode 100644 index 0000000..44ebeaf --- /dev/null +++ b/lib/audio_flow/graph/nodes/input.ex @@ -0,0 +1,22 @@ +defmodule AudioFlow.Graph.Nodes.Input do + @moduledoc "Input nodes. Each one marks an input type that the agent accepts." + @behaviour AudioFlow.Graph.Node + + @impl true + def nodes do + for {kind, title, description} <- [ + {:audio, "Audio input", "Mono 16-bit PCM from a microphone or a file."}, + {:image, "Image input", "RGB images or video frames."}, + {:text, "Text input", "Typed messages. They go directly to the LLM."} + ] do + %{ + type: "input.#{kind}", + title: title, + description: description, + input: nil, + output: kind, + options: [] + } + end + end +end diff --git a/lib/audio_flow/graph/prerequisites.ex b/lib/audio_flow/graph/prerequisites.ex new file mode 100644 index 0000000..b4d3e93 --- /dev/null +++ b/lib/audio_flow/graph/prerequisites.ex @@ -0,0 +1,23 @@ +defmodule AudioFlow.Graph.Prerequisites do + @moduledoc "Checks node configuration through the catalog; does not verify external connectivity." + alias AudioFlow.Graph + + def errors(graph, catalog) do + for node <- Graph.normalize(graph)["nodes"] || [], + is_map(node), + message <- node_errors(node, catalog), + do: "#{node["id"]}: #{message}" + end + + defp node_errors(node, catalog) do + case Map.fetch(catalog, node["type"]) do + {:ok, {module, _spec}} -> + if function_exported?(module, :prerequisites, 2), + do: module.prerequisites(node["type"], node["options"] || %{}), + else: [] + + :error -> + [] + end + end +end diff --git a/lib/audio_flow/graph/providers.ex b/lib/audio_flow/graph/providers.ex index 83f69ed..9c0d208 100644 --- a/lib/audio_flow/graph/providers.ex +++ b/lib/audio_flow/graph/providers.ex @@ -16,6 +16,12 @@ defmodule AudioFlow.Graph.Nodes.Providers do def providers, do: @providers + @impl true + 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 diff --git a/lib/audio_flow/graph/rag.ex b/lib/audio_flow/graph/rag.ex index 68ae531..2a8cd4a 100644 --- a/lib/audio_flow/graph/rag.ex +++ b/lib/audio_flow/graph/rag.ex @@ -2,6 +2,7 @@ defmodule AudioFlow.Graph.Nodes.RAG do @moduledoc "Vector-to-document retrieval. Profiles are trusted application configuration." @behaviour AudioFlow.Graph.Node + @impl true def nodes do [ %{ @@ -24,6 +25,17 @@ defmodule AudioFlow.Graph.Nodes.RAG do ] end + @impl true + def prerequisites("rag.retrieve", options) do + if Map.has_key?( + Application.get_env(:audio_flow, :retrieval_profiles, %{}), + options["profile"] + ), + do: [], + else: ["retrieval profile is not configured on the server (database/backend required)"] + end + + @impl true def adapter("rag.retrieve", options) do profiles = Application.get_env(:audio_flow, :retrieval_profiles, %{}) config = Map.fetch!(profiles, options.profile) diff --git a/lib/audio_flow/graph/runner.ex b/lib/audio_flow/graph/runner.ex index 42525d1..e4a8875 100644 --- a/lib/audio_flow/graph/runner.ex +++ b/lib/audio_flow/graph/runner.ex @@ -99,7 +99,6 @@ defmodule AudioFlow.Graph.Runner do end end - # All sources of `target` finished: run a joined step, then continue past it. defp ready(run, target) do step = run.plan.steps[target] if step.input_mode == :join, do: run_join(run, target, step) @@ -125,7 +124,7 @@ defmodule AudioFlow.Graph.Runner do value = if step.history, do: run.callbacks.context.(value), else: value {module, _} = step.adapter - adapter = with_tool_context(step.adapter, Map.get(run.callbacks, :telemetry, %{})) + adapter = Adapter.with_context(step.adapter, Map.get(run.callbacks, :telemetry, %{})) metadata = run.callbacks @@ -137,20 +136,6 @@ defmodule AudioFlow.Graph.Runner do end) end - defp with_tool_context({AudioFlow.Adapters.ReqLLM, options}, telemetry) do - execution = Keyword.get(options, :audio_flow, []) - context = Map.merge(Keyword.get(execution, :tool_context, %{}), telemetry) - execution = Keyword.put(execution, :tool_context, context) - {AudioFlow.Adapters.ReqLLM, Keyword.put(options, :audio_flow, execution)} - end - - defp with_tool_context({AudioFlow.Adapters.ChatHTTP, options}, telemetry) do - context = Map.merge(Keyword.get(options, :tool_context, %{}), telemetry) - {AudioFlow.Adapters.ChatHTTP, Keyword.put(options, :tool_context, context)} - end - - defp with_tool_context(adapter, _telemetry), do: adapter - defp emit_output(run, step, output) do :ok = run.callbacks.emit.(step, output) Enum.each(step.targets, &deliver(run, step.id, &1, output)) @@ -180,7 +165,6 @@ defmodule AudioFlow.Graph.Runner do Enum.count(step.sources, &MapSet.member?(active, &1)) <= 1 end - # A history text node whose only target is the one terminal streaming audio node. defp aligned_node(plan, active, id) do with %{history: true, event: :text, targets: [target]} <- plan.steps[id], %{input_mode: :stream, event: :audio, targets: [], sources: [^id]} <- @@ -198,7 +182,6 @@ defmodule AudioFlow.Graph.Runner do end) end - # `groups` has the values of each source, in edge order. defp join([]), do: nil defp join([[value | _] | _] = groups) when is_binary(value) do diff --git a/lib/audio_flow/resampler.ex b/lib/audio_flow/resampler.ex index 6be2fc7..9d39073 100644 --- a/lib/audio_flow/resampler.ex +++ b/lib/audio_flow/resampler.ex @@ -24,7 +24,6 @@ defmodule AudioFlow.Resampler do count = div(byte_size(audio.data), 2) output_count = div(count * up, down) {table, half} = table(up, down) - # Zero padding keeps every filter window inside the input. padding = :binary.copy(<<0, 0>>, half) input = padding <> audio.data <> padding width = 4 * half @@ -32,7 +31,6 @@ defmodule AudioFlow.Resampler do data = for k <- 0..(output_count - 1)//1, into: <<>> do position = k * down - # Window start: input sample center - half + 1, shifted by the padding. start = div(position, up) + 1 window = binary_part(input, 2 * start, width) value = dot(window, elem(table, rem(position, up)), 0.0) @@ -76,4 +74,26 @@ defmodule AudioFlow.Resampler do sinc = if abs(x) < 1.0e-9, do: 1.0, else: :math.sin(x) / x if abs(distance) >= half, do: 0.0, else: cutoff * sinc * window end + + @doc "Linear interpolation of mono signed 16-bit PCM." + def linear(%Audio{sample_rate: rate} = audio, rate), do: audio + + def linear(%Audio{data: data, sample_rate: from}, to) do + samples = for <>, do: sample + input = List.to_tuple(samples) + count = tuple_size(input) + length = if count == 0, do: 0, else: max(1, div(count * to, from)) + + pcm = + for index <- 0..(length - 1)//1, into: <<>> do + position = index * from / to + left = min(trunc(position), count - 1) + right = min(left + 1, count - 1) + weight = position - left + sample = round(elem(input, left) * (1 - weight) + elem(input, right) * weight) + <> + end + + %Audio{data: pcm, sample_rate: to} + end end diff --git a/lib_ml/audio_flow/graph/model_adapter.ex b/lib_ml/audio_flow/graph/model_adapter.ex new file mode 100644 index 0000000..1d5d775 --- /dev/null +++ b/lib_ml/audio_flow/graph/model_adapter.ex @@ -0,0 +1,24 @@ +defmodule AudioFlow.Graph.ModelAdapter do + @moduledoc """ + Runs `AudioFlow.NxAdapter` on a shared serving from `AudioFlow.Servings`. + + Options: `:key` and `:build` for `AudioFlow.Servings.fetch/2`, and the + `:input` and `:output` mappers of `AudioFlow.NxAdapter`. + """ + @behaviour AudioFlow.Adapter + + @impl true + def run(input, options, emit) do + case AudioFlow.Servings.fetch(Keyword.fetch!(options, :key), Keyword.fetch!(options, :build)) do + {:ok, name} -> + AudioFlow.NxAdapter.run( + input, + [serving: name] ++ Keyword.take(options, [:input, :output]), + emit + ) + + {:error, reason} -> + {:error, {:model_load, reason}} + end + end +end diff --git a/lib_ml/audio_flow/graph/models.ex b/lib_ml/audio_flow/graph/models.ex index aae8a52..0ba85ac 100644 --- a/lib_ml/audio_flow/graph/models.ex +++ b/lib_ml/audio_flow/graph/models.ex @@ -163,7 +163,6 @@ defmodule AudioFlow.Graph.Nodes.Models do @impl true def adapter("whisper.stt", %{model: model} = options) do language = Map.get(options, :language, "auto") - # Validate when the graph is built, not on the first turn. ModelLanguages.whisper_options!(model, language) {AudioFlow.STT.Bumblebee, @@ -293,28 +292,3 @@ defmodule AudioFlow.Graph.Nodes.Models do defp exla, do: [backend: EXLA.Backend] end - -defmodule AudioFlow.Graph.ModelAdapter do - @moduledoc """ - Runs `AudioFlow.NxAdapter` on a shared serving from `AudioFlow.Servings`. - - Options: `:key` and `:build` for `AudioFlow.Servings.fetch/2`, and the - `:input` and `:output` mappers of `AudioFlow.NxAdapter`. - """ - @behaviour AudioFlow.Adapter - - @impl true - def run(input, options, emit) do - case AudioFlow.Servings.fetch(Keyword.fetch!(options, :key), Keyword.fetch!(options, :build)) do - {:ok, name} -> - AudioFlow.NxAdapter.run( - input, - [serving: name] ++ Keyword.take(options, [:input, :output]), - emit - ) - - {:error, reason} -> - {:error, {:model_load, reason}} - end - end -end From b8057a4380838baba118f06bdecb034001e6474b Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 15:48:06 +0200 Subject: [PATCH 2/6] refactor(transports): share session events and PCMU packetization --- lib/audio_flow/rtvi/web_socket.ex | 37 ++- lib/audio_flow/telephony/packetizer.ex | 42 +++ lib/audio_flow/telephony/rate_converter.ex | 12 +- lib/audio_flow/telephony/web_socket.ex | 139 +++++----- lib/audio_flow/transport/connection.ex | 285 +++++++++++++++++++++ lib/audio_flow/web_socket.ex | 281 ++------------------ lib_webrtc/audio_flow/webrtc/transport.ex | 50 +--- test/network_protocol_test.exs | 3 +- test/telephony_reorder_test.exs | 11 +- 9 files changed, 459 insertions(+), 401 deletions(-) create mode 100644 lib/audio_flow/telephony/packetizer.ex create mode 100644 lib/audio_flow/transport/connection.ex diff --git a/lib/audio_flow/rtvi/web_socket.ex b/lib/audio_flow/rtvi/web_socket.ex index b977c23..49d8369 100644 --- a/lib/audio_flow/rtvi/web_socket.ex +++ b/lib/audio_flow/rtvi/web_socket.ex @@ -6,12 +6,12 @@ defmodule AudioFlow.RTVI.WebSocket do Pipecat's protobuf WebSocket media framing. See `docs/transports.md`. """ @behaviour WebSock - alias AudioFlow.WebSocket, as: PCM + alias AudioFlow.Transport.Connection @impl true def init(options) do - case PCM.init(options) do - {:push, _ready, pcm} -> {:ok, %{pcm: pcm, ready: false, rate: nil, request: nil}} + case Connection.init(options) do + {:events, _ready, pcm} -> {:ok, %{pcm: pcm, ready: false, rate: nil, request: nil}} other -> other end end @@ -62,7 +62,7 @@ defmodule AudioFlow.RTVI.WebSocket do Map.get(options, "audio_response", true) == true and Map.keys(options) -- ["run_immediately", "audio_response"] == [] do # RTVI run_immediately interrupts the current response before submitting. - case PCM.handle_in({JSON.encode!(%{type: "cancel"}), opcode: :text}, state.pcm) + case Connection.command(:cancel, state.pcm) |> translate(state) do {:ok, state} -> submit(content, id, state, []) {:push, frames, state} -> submit(content, id, state, frames) @@ -77,10 +77,7 @@ defmodule AudioFlow.RTVI.WebSocket do defp submit(content, id, state, frames) do case translate( - PCM.handle_in( - {JSON.encode!(%{type: "text", text: content}), opcode: :text}, - state.pcm - ), + Connection.command({:text, content}, state.pcm), %{state | request: id} ) do {:ok, state} -> reply(frames, state) @@ -89,16 +86,18 @@ defmodule AudioFlow.RTVI.WebSocket do end @impl true - def handle_info(message, state), do: translate(PCM.handle_info(message, state.pcm), state) + def handle_info(message, state), + do: translate(Connection.handle_info(message, state.pcm), state) + @impl true - def terminate(reason, state), do: PCM.terminate(reason, state.pcm) + def terminate(reason, state), do: Connection.terminate(reason, state.pcm) defp translate({:ok, pcm}, state), do: {:ok, %{state | pcm: pcm}} defp translate({:stop, reason, close, pcm}, state), do: {:stop, reason, close, %{state | pcm: pcm}} - defp translate({:push, frames, pcm}, state) do + defp translate({:events, frames, pcm}, state) do {frames, state} = Enum.reduce(frames, {[], %{state | pcm: pcm}}, fn frame, {frames, state} -> {new, state} = outgoing(frame, state) @@ -109,7 +108,7 @@ defmodule AudioFlow.RTVI.WebSocket do end # Keep custom media events below the SDK transport's 64 KB message bound. - defp outgoing({:binary, data}, state) do + defp outgoing({:audio, data}, state) do frames = for chunk <- audio_chunks(data), do: @@ -122,21 +121,21 @@ defmodule AudioFlow.RTVI.WebSocket do {frames, state} end - defp outgoing({:text, data}, state) do - case JSON.decode!(data) do - %{"type" => "output_format", "sample_rate" => rate} -> + defp outgoing({:event, message}, state) do + case message do + %{type: :output_format, sample_rate: rate} -> {[], %{state | rate: rate}} - %{"type" => "text", "text" => text} -> + %{type: :text, text: text} -> {[json("llm-raw-text", %{text: text})], state} - %{"type" => "flush"} -> + %{type: :flush} -> {[json("bot-interrupted", nil)], state} - %{"type" => "error", "reason" => reason} = message when not is_map_key(message, "turn") -> + %{type: :error, reason: reason} = message when not is_map_key(message, :turn) -> {[json("error-response", %{error: reason}, state.request || "")], state} - %{"type" => "error", "reason" => reason} -> + %{type: :error, reason: reason} -> {[json("error", %{error: reason, fatal: false})], state} _ -> diff --git a/lib/audio_flow/telephony/packetizer.ex b/lib/audio_flow/telephony/packetizer.ex new file mode 100644 index 0000000..d36b7a3 --- /dev/null +++ b/lib/audio_flow/telephony/packetizer.ex @@ -0,0 +1,42 @@ +defmodule AudioFlow.Telephony.Packetizer do + @moduledoc "Stateful PCM conversion to 20 ms G.711 μ-law packets, with a padded final packet." + alias AudioFlow.Audio + alias AudioFlow.Telephony.MuLaw + alias AudioFlow.Telephony.RateConverter + + defstruct rate: nil, converter: %RateConverter{}, pending: <<>>, active?: false + + def format(state, rate), do: %{state | rate: rate, converter: %RateConverter{}} + + def push(%Audio{data: data, sample_rate: rate}, state) do + {data, converter} = + if rate == 16_000, + do: RateConverter.down(data, state.converter), + else: {data, state.converter} + + split(state.pending <> MuLaw.encode(data), %{ + state + | rate: rate, + converter: converter, + active?: true + }) + end + + def finish(state) do + {tail, _} = + if state.active? and state.rate == 16_000, + do: RateConverter.finish_down(state.converter), + else: {<<>>, state.converter} + + data = state.pending <> MuLaw.encode(tail) + padding = rem(160 - rem(byte_size(data), 160), 160) + split(data <> :binary.copy(<<255>>, padding), %__MODULE__{rate: state.rate}) + end + + defp split(data, state) do + packets = for <>, do: packet + size = byte_size(data) + remaining = rem(size, 160) + {packets, %{state | pending: binary_part(data, size - remaining, remaining)}} + end +end diff --git a/lib/audio_flow/telephony/rate_converter.ex b/lib/audio_flow/telephony/rate_converter.ex index da4d5a1..8f3ee44 100644 --- a/lib/audio_flow/telephony/rate_converter.ex +++ b/lib/audio_flow/telephony/rate_converter.ex @@ -4,14 +4,16 @@ defmodule AudioFlow.Telephony.RateConverter do interpolation; downsampling uses a 31-tap windowed-sinc low-pass FIR at 3.4 kHz. Filter delay is 15 input samples. This is not wideband audio restoration. """ - @taps (for n <- -15..15 do + @half_width 15 + @history_size @half_width * 2 + @taps (for n <- -@half_width..@half_width do sinc = if n == 0, do: 0.425, else: :math.sin(2 * :math.pi() * 0.2125 * n) / (:math.pi() * n) - sinc * (0.54 + 0.46 * :math.cos(:math.pi() * n / 15)) + sinc * (0.54 + 0.46 * :math.cos(:math.pi() * n / @half_width)) end) @gain Enum.sum(@taps) - defstruct previous: 0, history: List.duplicate(0, 30), phase: 0 + defstruct previous: 0, history: List.duplicate(0, @history_size), phase: 0 def up(data, state) when rem(byte_size(data), 2) == 0 do {samples, previous} = @@ -22,6 +24,8 @@ defmodule AudioFlow.Telephony.RateConverter do {IO.iodata_to_binary(samples), %{state | previous: previous}} end + def finish_down(state), do: down(:binary.copy(<<0, 0>>, @history_size), state) + def down(data, state) when rem(byte_size(data), 2) == 0 do {samples, state} = Enum.map_reduce(for(<>, do: s), state, fn s, state -> @@ -29,7 +33,7 @@ defmodule AudioFlow.Telephony.RateConverter do value = Enum.zip_with(history, @taps, &(&1 * &2)) |> Enum.sum() value = (value / @gain) |> round() |> max(-32_768) |> min(32_767) output = if state.phase == 1, do: <>, else: <<>> - {output, %{state | history: Enum.take(history, 30), phase: 1 - state.phase}} + {output, %{state | history: Enum.take(history, @history_size), phase: 1 - state.phase}} end) {IO.iodata_to_binary(samples), state} diff --git a/lib/audio_flow/telephony/web_socket.ex b/lib/audio_flow/telephony/web_socket.ex index d0f6758..cdaf078 100644 --- a/lib/audio_flow/telephony/web_socket.ex +++ b/lib/audio_flow/telephony/web_socket.ex @@ -7,8 +7,9 @@ defmodule AudioFlow.Telephony.WebSocket do """ @behaviour WebSock alias AudioFlow.Telephony.MuLaw + alias AudioFlow.Telephony.Packetizer alias AudioFlow.Telephony.RateConverter - alias AudioFlow.WebSocket, as: PCM + alias AudioFlow.Transport.Connection @limits_schema [ max_playout_packets: [type: :pos_integer, default: 500], @@ -37,9 +38,7 @@ defmodule AudioFlow.Telephony.WebSocket do pcm: nil, stream: nil, up: %RateConverter{}, - down: %RateConverter{}, - pending: <<>>, - output_rate: nil, + packetizer: %Packetizer{}, last_chunk: nil, playout: :queue.new(), playout_timer: nil, @@ -49,8 +48,7 @@ defmodule AudioFlow.Telephony.WebSocket do gap_timer: nil, reorder_window: limits[:reorder_window], reorder_max_bytes: limits[:reorder_max_bytes], - reorder_timeout_ms: limits[:reorder_timeout_ms], - output?: false + reorder_timeout_ms: limits[:reorder_timeout_ms] }} end @@ -80,7 +78,12 @@ defmodule AudioFlow.Telephony.WebSocket do end if format == expected and is_binary(id) and id != "" do - translate(PCM.init(state.options), %{state | stream: id}) + translate( + Connection.init( + Keyword.put(state.options, :output_check, &output_check(&1, state.max_playout_packets)) + ), + %{state | stream: id} + ) else fail(:unsupported_start, state) end @@ -146,8 +149,6 @@ defmodule AudioFlow.Telephony.WebSocket do else: fail(:unordered_media, state) end - # Start at chunk 1 even if the first packet received is chunk 2. - # First copy wins; stale/duplicate packets never enter the resampler twice. defp reorder(chunk, bytes, state) do expected = (state.last_chunk || 0) + 1 @@ -194,7 +195,7 @@ defmodule AudioFlow.Telephony.WebSocket do {data, up} = RateConverter.up(MuLaw.decode(bytes), state.up) translate( - PCM.handle_in({data, opcode: :binary}, state.pcm), + Connection.audio(data, state.pcm), %{state | up: up, last_chunk: chunk} ) end @@ -237,36 +238,40 @@ defmodule AudioFlow.Telephony.WebSocket do def handle_info({__MODULE__, :gap_timeout, _}, state), do: {:ok, state} - def handle_info({PCM, :push, _key, audio, {from, tag}}, state) - when audio.sample_rate not in [8000, 16_000] do - send(from, {tag, {:error, :unsupported_telephony_output_rate}}) - {:ok, state} - end - - def handle_info({PCM, :push, _key, audio, {from, tag}}, state) - when byte_size(audio.data) > state.max_playout_packets * 640 do - send(from, {tag, {:error, :telephony_output_too_large}}) - fail(:playout_limit, state) - end - def handle_info(_, %{pcm: nil} = state), do: {:ok, state} - def handle_info(message, state), do: translate(PCM.handle_info(message, state.pcm), state) + + def handle_info(message, state), + do: translate(Connection.handle_info(message, state.pcm), state) @impl true def terminate(reason, state) do cancel_timer(state.gap_timer) cancel_timer(state.playout_timer) - if state.pcm, do: PCM.terminate(reason, state.pcm), else: :ok + if state.pcm, do: Connection.terminate(reason, state.pcm), else: :ok end + defp output_check(audio, limit) do + cond do + audio.sample_rate not in [8000, 16_000] -> {:error, :unsupported_telephony_output_rate} + byte_size(audio.data) > limit * 640 -> {:error, :telephony_output_too_large} + true -> :ok + end + end + + defp translate({:output_rejected, :unsupported_telephony_output_rate, pcm}, state), + do: {:ok, %{state | pcm: pcm}} + + defp translate({:output_rejected, :telephony_output_too_large, pcm}, state), + do: fail(:playout_limit, %{state | pcm: pcm}) + defp translate({:ok, pcm}, state), do: {:ok, %{state | pcm: pcm}} defp translate({:stop, reason, close, pcm}, state), do: {:stop, reason, close, %{state | pcm: pcm}} - defp translate({:push, [{:text, data}] = frames, pcm}, state) do - case JSON.decode!(data) do - %{"type" => "error", "reason" => reason} -> + defp translate({:events, [{:event, message}] = frames, pcm}, state) do + case message do + %{type: :error, reason: reason} -> {:stop, {:session_error, reason}, {1011, "audio session failed"}, %{state | pcm: pcm}} _ -> @@ -274,7 +279,7 @@ defmodule AudioFlow.Telephony.WebSocket do end end - defp translate({:push, frames, pcm}, state), do: translate_frames(frames, pcm, state) + defp translate({:events, frames, pcm}, state), do: translate_frames(frames, pcm, state) defp translate_frames(frames, pcm, state) do {frames, state} = @@ -294,17 +299,14 @@ defmodule AudioFlow.Telephony.WebSocket do end end - defp queue_frame({:text, data} = frame, {now, state}) do - case JSON.decode!(data)["event"] do - "clear" -> - cancel_timer(state.playout_timer) - {now ++ [frame], %{state | playout: :queue.new(), playout_timer: nil}} - - "media" -> - {now, %{state | playout: :queue.in(frame, state.playout)}} - end + defp queue_frame({:clear, frame}, {now, state}) do + cancel_timer(state.playout_timer) + {now ++ [frame], %{state | playout: :queue.new(), playout_timer: nil}} end + defp queue_frame({:media, frame}, {now, state}), + do: {now, %{state | playout: :queue.in(frame, state.playout)}} + defp schedule_playout(%{playout_timer: nil} = state) do if :queue.is_empty(state.playout) do state @@ -317,54 +319,37 @@ defmodule AudioFlow.Telephony.WebSocket do defp schedule_playout(state), do: state - defp outgoing({:binary, data}, state) do - {data, down} = - if state.output_rate == 16_000, - do: RateConverter.down(data, state.down), - else: {data, state.down} + defp outgoing({:audio, data}, state) do + {packets, packetizer} = + Packetizer.push( + %AudioFlow.Audio{data: data, sample_rate: state.packetizer.rate}, + state.packetizer + ) - packetize(state.pending <> MuLaw.encode(data), %{state | down: down, output?: true}) + packet_frames(packets, %{state | packetizer: packetizer}) end - defp outgoing({:text, data}, state) do - case JSON.decode!(data) do - %{"type" => "output_format", "sample_rate" => rate} -> - {[], %{state | output_rate: rate, down: %RateConverter{}}} - - %{"type" => "flush"} -> - {[wire(state, %{event: "clear"})], - %{state | pending: <<>>, down: %RateConverter{}, output?: false}} + defp outgoing({:event, %{type: :output_format, sample_rate: rate}}, state), + do: {[], %{state | packetizer: Packetizer.format(state.packetizer, rate)}} - %{"type" => "done"} -> - {tail, _} = - if state.output? and state.output_rate == 16_000, - do: RateConverter.down(:binary.copy(<<0>>, 60), state.down), - else: {<<>>, state.down} + defp outgoing({:event, %{type: :flush}}, state), + do: + {[{:clear, wire(state, %{event: "clear"})}], + %{state | packetizer: %Packetizer{rate: state.packetizer.rate}}} - data = state.pending <> MuLaw.encode(tail) - padding = rem(160 - rem(byte_size(data), 160), 160) - - packetize(data <> :binary.copy(<<255>>, padding), %{ - state - | pending: <<>>, - down: %RateConverter{}, - output?: false - }) - - %{"type" => "error"} -> - {[], state} - - _ -> - {[], state} - end + defp outgoing({:event, %{type: :done}}, state) do + {packets, packetizer} = Packetizer.finish(state.packetizer) + packet_frames(packets, %{state | packetizer: packetizer}) end - defp packetize(data, state) when byte_size(data) < 160, do: {[], %{state | pending: data}} + defp outgoing({:event, _message}, state), do: {[], state} - defp packetize(<>, state) do - {frames, state} = packetize(rest, state) - {[wire(state, %{event: "media", media: %{payload: Base.encode64(packet)}}) | frames], state} - end + defp packet_frames(packets, state), + do: + {Enum.map( + packets, + &{:media, wire(state, %{event: "media", media: %{payload: Base.encode64(&1)}})} + ), state} defp wire(%{provider: :twilio, stream: id}, message), do: {:text, JSON.encode!(Map.put(message, :streamSid, id))} diff --git a/lib/audio_flow/transport/connection.ex b/lib/audio_flow/transport/connection.ex new file mode 100644 index 0000000..c85ee29 --- /dev/null +++ b/lib/audio_flow/transport/connection.ex @@ -0,0 +1,285 @@ +defmodule AudioFlow.Transport.Connection do + @moduledoc """ + Session lifecycle and commands shared by connection transports. + + Results contain structured `{:event, map}` and `{:audio, pcm}` events. + Endpoints encode those events in their own wire format. An output check can + reject PCM before the producer receives its acceptance acknowledgement. + """ + @behaviour AudioFlow.Output + alias AudioFlow.Audio + alias AudioFlow.Text + alias AudioFlow.VoiceInput + + @impl AudioFlow.Output + def start_turn(_connection, _key), do: :ok + + @impl AudioFlow.Output + def push(connection, key, audio) do + ref = Process.monitor(connection) + send(connection, {__MODULE__, :push, key, audio, {self(), ref}}) + + receive do + {^ref, result} -> + Process.demonitor(ref, [:flush]) + result + + {:DOWN, ^ref, :process, _, reason} -> + {:error, {:connection_exit, reason}} + end + end + + @impl AudioFlow.Output + def finish(_connection, _key), do: :ok + + @impl AudioFlow.Output + def flush(connection, key) do + send(connection, {__MODULE__, :flush, key}) + :ok + end + + @limits_schema [ + sample_rate: [type: :pos_integer, default: 16_000], + max_chunk_bytes: [type: :pos_integer, default: 64_000], + max_buffer_bytes: [type: :pos_integer, default: 960_000] + ] + + def init(options) do + limits = + AudioFlow.RuntimeOptions.known!( + options, + @limits_schema, + Enum.map(@limits_schema, fn {key, _} -> {key, "#{key} must be a positive integer"} end) + ) + + rate = limits[:sample_rate] + vad = Keyword.get(options, :vad) + + input = if vad, do: VoiceInput.new(vad, Keyword.get(options, :endpoint_options, [])) + + if input && input.rate != rate, + do: raise(ArgumentError, "sample_rate must match the detector rate #{input.rate}") + + state = %{ + session: nil, + session_ref: nil, + input: input, + rate: rate, + max_chunk_bytes: limits[:max_chunk_bytes], + max_buffer_bytes: limits[:max_buffer_bytes], + buffer: [], + buffer_bytes: 0, + turn: nil, + next_turn: 1, + output_check: Keyword.get(options, :output_check, fn _ -> :ok end), + output_rate: nil + } + + session_options = + options + |> Keyword.fetch!(:session) + |> Keyword.merge(owner: self(), output: {__MODULE__, self()}) + + case AudioFlow.start_session(session_options) do + {:ok, session} -> + ready = %{ + type: :ready, + mode: if(input, do: :vad, else: :commit), + input: %{encoding: :pcm_s16le, sample_rate: rate, channels: 1} + } + + state = %{state | session: session, session_ref: Process.monitor(session)} + {:events, [event(ready)], state} + + {:error, reason} -> + {:stop, {:session_start, reason}, {1011, "session start failed"}, state} + end + end + + def audio(data, state) do + cond do + byte_size(data) > state.max_chunk_bytes -> + reply([error(nil, :chunk_too_large)], state) + + not Audio.valid?(%Audio{data: data, sample_rate: state.rate}) -> + reply([error(nil, :invalid_audio)], state) + + state.input -> + audio = %Audio{data: data, sample_rate: state.rate} + {events, input} = VoiceInput.push(state.input, audio) + voice_events(events, %{state | input: input}) + + state.buffer_bytes + byte_size(data) > state.max_buffer_bytes -> + reply([error(nil, :input_too_large)], %{state | buffer: [], buffer_bytes: 0}) + + true -> + {:ok, + %{ + state + | buffer: [state.buffer, :binary.copy(data)], + buffer_bytes: state.buffer_bytes + byte_size(data) + }} + end + end + + def command(command, state), do: reply(run_command(command, state)) + + def handle_info({__MODULE__, :push, {session, ref}, audio, {from, tag}}, state) do + if state.session == session and match?({^ref, _}, state.turn) do + case state.output_check.(audio) do + :ok -> + send(from, {tag, :ok}) + {format, state} = output_format(audio.sample_rate, state) + reply(format ++ [{:audio, audio.data}], state) + + {:error, reason} -> + send(from, {tag, {:error, reason}}) + {:output_rejected, reason, state} + end + else + send(from, {tag, {:error, :stale_turn}}) + {:ok, state} + end + end + + def handle_info({__MODULE__, :flush, {session, _ref}}, %{session: session} = state), + do: reply([event(%{type: :flush})], state) + + def handle_info({AudioFlow, session, ref, event}, %{session: session, turn: {ref, id}} = state) do + case event do + {:done, metrics} -> + reply([event(%{type: :done, turn: id, metrics: metrics})], %{state | turn: nil}) + + {:cancelled, _metrics} -> + reply([event(%{type: :cancelled, turn: id})], %{state | turn: nil}) + + {:error, reason, _metrics} -> + reply([error(id, reason)], %{state | turn: nil}) + + {kind, text} when kind in [:transcript, :description, :text] -> + reply([event(%{type: kind, turn: id, text: text})], state) + + {kind, value} when kind in [:segment, :partial_transcript] -> + reply([event(transcript_message(id, kind, value))], state) + + {kind, text, node} when kind in [:transcript, :description, :text] and is_binary(text) -> + reply([event(%{type: kind, turn: id, text: text, node: node})], state) + + _ -> + {:ok, state} + end + end + + def handle_info({:DOWN, ref, :process, _, reason}, %{session_ref: ref} = state), + do: {:stop, {:session_exit, reason}, {1011, "session stopped"}, %{state | session: nil}} + + def handle_info(_message, state), do: {:ok, state} + + def terminate(_reason, %{session: session}) when is_pid(session) do + AudioFlow.stop_session(session) + :ok + end + + def terminate(_reason, _state), do: :ok + + defp run_command({:text, text}, state) when is_binary(text), + do: submit(%Text{data: text}, state) + + defp run_command(:commit, %{input: nil} = state) do + audio = %Audio{data: IO.iodata_to_binary(state.buffer), sample_rate: state.rate} + state = %{state | buffer: [], buffer_bytes: 0} + + if audio.data == <<>>, + do: {[error(nil, :empty_input)], state}, + else: submit(audio, state) + end + + defp run_command(:commit, state) do + {events, input} = VoiceInput.flush(state.input) + voice_frames(events, %{state | input: input}) + end + + defp run_command(:cancel, state), do: cancel(state) + + defp run_command(:clear_history, state) do + case AudioFlow.clear_history(state.session) do + :ok -> {[event(%{type: :history_cleared})], state} + {:error, reason} -> {[error(nil, reason)], state} + end + end + + defp run_command(_command, state), do: {[error(nil, :invalid_message)], state} + + defp voice_events(events, state), do: reply(voice_frames(events, state)) + + defp voice_frames(events, state) do + Enum.reduce(events, {[], state}, fn event, {frames, state} -> + {new, state} = + case event do + :speech_started -> + {cancelled, state} = cancel(state) + {[event(%{type: :speech_started}) | cancelled], state} + + {:utterance, audio, _reason} -> + submit(audio, state) + end + + {frames ++ new, state} + end) + end + + defp submit(input, state) do + case AudioFlow.submit(state.session, input) do + {:ok, ref} -> + id = state.next_turn + {[event(%{type: :turn_started, turn: id})], %{state | turn: {ref, id}, next_turn: id + 1}} + + {:error, reason} -> + {[error(nil, reason)], state} + end + end + + defp cancel(state) do + frames = + case {AudioFlow.cancel(state.session), state.turn} do + {:ok, nil} -> [] + {:ok, {_ref, id}} -> [event(%{type: :cancelled, turn: id})] + {{:error, reason}, turn} -> [error(turn && elem(turn, 1), reason)] + end + + {frames, %{state | turn: nil}} + end + + defp output_format(rate, %{output_rate: rate} = state), do: {[], state} + + defp output_format(rate, state), + do: {[event(%{type: :output_format, sample_rate: rate})], %{state | output_rate: rate}} + + defp error(turn, reason) do + message = %{type: :error, reason: reason_text(reason)} + event(if turn, do: Map.put(message, :turn, turn), else: message) + end + + defp reason_text(reason) when is_atom(reason), do: Atom.to_string(reason) + defp reason_text(reason), do: inspect(reason) + + defp event(message), do: {:event, message} + + defp transcript_message(id, :partial_transcript, text), + do: %{type: :partial_transcript, turn: id, text: text} + + defp transcript_message(id, :segment, segment) do + %{ + type: :transcript, + turn: id, + text: segment.text, + start_ms: segment.start_ms, + end_ms: segment.end_ms, + words: segment.words + } + end + + defp reply({frames, state}), do: reply(frames, state) + defp reply([], state), do: {:ok, state} + defp reply(frames, state), do: {:events, frames, state} +end diff --git a/lib/audio_flow/web_socket.ex b/lib/audio_flow/web_socket.ex index 19e63be..a8d4f52 100644 --- a/lib/audio_flow/web_socket.ex +++ b/lib/audio_flow/web_socket.ex @@ -62,284 +62,49 @@ defmodule AudioFlow.WebSocket do """ @behaviour WebSock @behaviour AudioFlow.Output - alias AudioFlow.Audio - alias AudioFlow.Text - alias AudioFlow.VoiceInput + alias AudioFlow.Transport.Connection @impl AudioFlow.Output - def start_turn(_connection, _key), do: :ok - - # The connection can call the session while the session calls these - # functions, so only `push/3` waits for the connection. + defdelegate start_turn(connection, key), to: Connection @impl AudioFlow.Output - def push(connection, key, audio) do - ref = Process.monitor(connection) - send(connection, {__MODULE__, :push, key, audio, {self(), ref}}) - - receive do - {^ref, result} -> - Process.demonitor(ref, [:flush]) - result - - {:DOWN, ^ref, :process, _, reason} -> - {:error, {:connection_exit, reason}} - end - end - + defdelegate push(connection, key, audio), to: Connection @impl AudioFlow.Output - def finish(_connection, _key), do: :ok - + defdelegate finish(connection, key), to: Connection @impl AudioFlow.Output - def flush(connection, key) do - send(connection, {__MODULE__, :flush, key}) - :ok - end - - @limits_schema [ - sample_rate: [type: :pos_integer, default: 16_000], - max_chunk_bytes: [type: :pos_integer, default: 64_000], - max_buffer_bytes: [type: :pos_integer, default: 960_000] - ] + defdelegate flush(connection, key), to: Connection @impl WebSock - def init(options) do - limits = - AudioFlow.RuntimeOptions.known!( - options, - @limits_schema, - Enum.map(@limits_schema, fn {key, _} -> {key, "#{key} must be a positive integer"} end) - ) - - rate = limits[:sample_rate] - vad = Keyword.get(options, :vad) - - input = if vad, do: VoiceInput.new(vad, Keyword.get(options, :endpoint_options, [])) - - if input && input.rate != rate, - do: raise(ArgumentError, "sample_rate must match the detector rate #{input.rate}") - - state = %{ - session: nil, - session_ref: nil, - input: input, - rate: rate, - max_chunk_bytes: limits[:max_chunk_bytes], - max_buffer_bytes: limits[:max_buffer_bytes], - buffer: [], - buffer_bytes: 0, - turn: nil, - next_turn: 1, - output_rate: nil - } - - session_options = - options - |> Keyword.fetch!(:session) - |> Keyword.merge(owner: self(), output: {__MODULE__, self()}) - - case AudioFlow.start_session(session_options) do - {:ok, session} -> - ready = %{ - type: :ready, - mode: if(input, do: :vad, else: :commit), - input: %{encoding: :pcm_s16le, sample_rate: rate, channels: 1} - } - - state = %{state | session: session, session_ref: Process.monitor(session)} - {:push, [json(ready)], state} - - {:error, reason} -> - {:stop, {:session_start, reason}, {1011, "session start failed"}, state} - end - end + def init(options), do: encode(Connection.init(options)) @impl WebSock - def handle_in({data, opcode: :binary}, state) do - cond do - byte_size(data) > state.max_chunk_bytes -> - reply([error(nil, :chunk_too_large)], state) - - not Audio.valid?(%Audio{data: data, sample_rate: state.rate}) -> - reply([error(nil, :invalid_audio)], state) - - state.input -> - audio = %Audio{data: data, sample_rate: state.rate} - {events, input} = VoiceInput.push(state.input, audio) - voice_events(events, %{state | input: input}) - - state.buffer_bytes + byte_size(data) > state.max_buffer_bytes -> - reply([error(nil, :input_too_large)], %{state | buffer: [], buffer_bytes: 0}) - - true -> - {:ok, - %{ - state - | buffer: [state.buffer, :binary.copy(data)], - buffer_bytes: state.buffer_bytes + byte_size(data) - }} - end - end + def handle_in({data, opcode: :binary}, state), do: encode(Connection.audio(data, state)) def handle_in({data, opcode: :text}, state) do case JSON.decode(data) do - {:ok, %{"type" => type} = message} -> reply(command(type, message, state)) - _ -> reply([error(nil, :invalid_message)], state) - end - end - - @impl WebSock - def handle_info({__MODULE__, :push, {session, ref}, audio, {from, tag}}, state) do - if state.session == session and match?({^ref, _}, state.turn) do - send(from, {tag, :ok}) - {format, state} = output_format(audio.sample_rate, state) - reply(format ++ [{:binary, audio.data}], state) - else - send(from, {tag, {:error, :stale_turn}}) - {:ok, state} - end - end - - def handle_info({__MODULE__, :flush, {session, _ref}}, %{session: session} = state), - do: reply([json(%{type: :flush})], state) - - def handle_info({AudioFlow, session, ref, event}, %{session: session, turn: {ref, id}} = state) do - case event do - {:done, metrics} -> - reply([json(%{type: :done, turn: id, metrics: metrics})], %{state | turn: nil}) - - {:cancelled, _metrics} -> - reply([json(%{type: :cancelled, turn: id})], %{state | turn: nil}) - - {:error, reason, _metrics} -> - reply([error(id, reason)], %{state | turn: nil}) - - {kind, text} when kind in [:transcript, :description, :text] -> - reply([json(%{type: kind, turn: id, text: text})], state) + {:ok, %{"type" => type} = message} -> + encode(Connection.command(command(type, message), state)) - {kind, value} when kind in [:segment, :partial_transcript] -> - reply([json(transcript_message(id, kind, value))], state) - - {kind, text, node} when kind in [:transcript, :description, :text] and is_binary(text) -> - reply([json(%{type: kind, turn: id, text: text, node: node})], state) - - # Audio arrives through push/3. _ -> - {:ok, state} + encode(Connection.command(:invalid, state)) end end - def handle_info({:DOWN, ref, :process, _, reason}, %{session_ref: ref} = state), - do: {:stop, {:session_exit, reason}, {1011, "session stopped"}, %{state | session: nil}} - - # Events from a cancelled or finished turn, and unrelated messages. - def handle_info(_message, state), do: {:ok, state} - @impl WebSock - def terminate(_reason, %{session: session}) when is_pid(session) do - AudioFlow.stop_session(session) - :ok - end - - def terminate(_reason, _state), do: :ok - - defp command("text", %{"text" => text}, state) when is_binary(text), - do: submit(%Text{data: text}, state) - - defp command("commit", _message, %{input: nil} = state) do - audio = %Audio{data: IO.iodata_to_binary(state.buffer), sample_rate: state.rate} - state = %{state | buffer: [], buffer_bytes: 0} - - if audio.data == <<>>, - do: {[error(nil, :empty_input)], state}, - else: submit(audio, state) - end - - defp command("commit", _message, state) do - {events, input} = VoiceInput.flush(state.input) - voice_frames(events, %{state | input: input}) - end - - defp command("cancel", _message, state), do: cancel(state) - - defp command("clear_history", _message, state) do - case AudioFlow.clear_history(state.session) do - :ok -> {[json(%{type: :history_cleared})], state} - {:error, reason} -> {[error(nil, reason)], state} - end - end - - defp command(_type, _message, state), do: {[error(nil, :invalid_message)], state} - - defp voice_events(events, state), do: reply(voice_frames(events, state)) + def handle_info(message, state), do: encode(Connection.handle_info(message, state)) - defp voice_frames(events, state) do - Enum.reduce(events, {[], state}, fn event, {frames, state} -> - {new, state} = - case event do - :speech_started -> - {cancelled, state} = cancel(state) - {[json(%{type: :speech_started}) | cancelled], state} - - {:utterance, audio, _reason} -> - submit(audio, state) - end - - {frames ++ new, state} - end) - end - - defp submit(input, state) do - case AudioFlow.submit(state.session, input) do - {:ok, ref} -> - id = state.next_turn - {[json(%{type: :turn_started, turn: id})], %{state | turn: {ref, id}, next_turn: id + 1}} - - {:error, reason} -> - {[error(nil, reason)], state} - end - end - - defp cancel(state) do - frames = - case {AudioFlow.cancel(state.session), state.turn} do - {:ok, nil} -> [] - {:ok, {_ref, id}} -> [json(%{type: :cancelled, turn: id})] - {{:error, reason}, turn} -> [error(turn && elem(turn, 1), reason)] - end - - {frames, %{state | turn: nil}} - end - - defp output_format(rate, %{output_rate: rate} = state), do: {[], state} - - defp output_format(rate, state), - do: {[json(%{type: :output_format, sample_rate: rate})], %{state | output_rate: rate}} - - defp error(turn, reason) do - message = %{type: :error, reason: reason_text(reason)} - json(if turn, do: Map.put(message, :turn, turn), else: message) - end - - defp reason_text(reason) when is_atom(reason), do: Atom.to_string(reason) - defp reason_text(reason), do: inspect(reason) - - defp json(message), do: {:text, JSON.encode!(message)} + @impl WebSock + def terminate(reason, state), do: Connection.terminate(reason, state) - defp transcript_message(id, :partial_transcript, text), - do: %{type: :partial_transcript, turn: id, text: text} + defp command("text", %{"text" => text}), do: {:text, text} + defp command("commit", _), do: :commit + defp command("cancel", _), do: :cancel + defp command("clear_history", _), do: :clear_history + defp command(_, _), do: :invalid - defp transcript_message(id, :segment, segment) do - %{ - type: :transcript, - turn: id, - text: segment.text, - start_ms: segment.start_ms, - end_ms: segment.end_ms, - words: segment.words - } - end + defp encode({:events, events, state}), + do: {:push, Enum.map(events, &encode_event/1), state} - defp reply({frames, state}), do: reply(frames, state) - defp reply([], state), do: {:ok, state} - defp reply(frames, state), do: {:push, frames, state} + defp encode(result), do: result + defp encode_event({:event, message}), do: {:text, JSON.encode!(message)} + defp encode_event({:audio, data}), do: {:binary, data} end diff --git a/lib_webrtc/audio_flow/webrtc/transport.ex b/lib_webrtc/audio_flow/webrtc/transport.ex index 62bb8f4..0677115 100644 --- a/lib_webrtc/audio_flow/webrtc/transport.ex +++ b/lib_webrtc/audio_flow/webrtc/transport.ex @@ -9,8 +9,7 @@ defmodule AudioFlow.WebRTC.Transport do use GenServer @behaviour AudioFlow.Output alias AudioFlow.Audio - alias AudioFlow.Telephony.MuLaw - alias AudioFlow.Telephony.RateConverter + alias AudioFlow.Telephony.Packetizer alias AudioFlow.WebRTC def start_link(opts), do: GenServer.start_link(__MODULE__, opts) @@ -37,9 +36,7 @@ defmodule AudioFlow.WebRTC.Transport do limit: limit, key: nil, queue: :queue.new(), - pending: <<>>, - rate: nil, - converter: %RateConverter{}, + packetizer: %Packetizer{}, timer: nil, sealed: false, pts: 0, @@ -84,15 +81,9 @@ defmodule AudioFlow.WebRTC.Transport do end def handle_call({:finish, _}, _from, s) do - {tail, _} = - if s.rate == 16_000, - do: RateConverter.down(:binary.copy(<<0>>, 60), s.converter), - else: {<<>>, s.converter} + {packets, packetizer} = Packetizer.finish(s.packetizer) - data = s.pending <> MuLaw.encode(tail) - padding = rem(160 - rem(byte_size(data), 160), 160) - - case enqueue(data <> :binary.copy(<<255>>, padding), s) do + case enqueue(packets, packetizer, s) do {:ok, s} -> # Session invokes finish inside its server. Keep draining asynchronously # so that server can still accept cancellation and deadline messages. @@ -138,7 +129,7 @@ defmodule AudioFlow.WebRTC.Transport do not Audio.valid?(audio) or audio.sample_rate not in [8000, 16_000] -> :unsupported_pcm - s.sealed or (s.rate != nil and s.rate != audio.sample_rate) -> + s.sealed or (s.packetizer.rate != nil and s.packetizer.rate != audio.sample_rate) -> :output_format_changed byte_size(audio.data) > s.limit * if(audio.sample_rate == 8000, do: 320, else: 640) -> @@ -150,36 +141,21 @@ defmodule AudioFlow.WebRTC.Transport do end defp push_audio(audio, s) do - {data, converter} = - if audio.sample_rate == 16_000, - do: RateConverter.down(audio.data, s.converter), - else: {audio.data, s.converter} - - case enqueue(s.pending <> MuLaw.encode(data), %{ - s - | converter: converter, - rate: audio.sample_rate - }) do + {packets, packetizer} = Packetizer.push(audio, s.packetizer) + + case enqueue(packets, packetizer, s) do {:ok, s} -> {:reply, :ok, schedule(s)} {:error, reason} -> {:reply, {:error, reason}, s} end end - defp enqueue(data, s) do - count = div(byte_size(data) + 159, 160) + defp enqueue(packets, packetizer, s) do + count = length(packets) + if(packetizer.pending == <<>>, do: 0, else: 1) if :queue.len(s.queue) + count > s.limit do {:error, :queue_limit} else - packets = for <>, do: packet - rest = rem(byte_size(data), 160) - - {:ok, - %{ - s - | queue: Enum.reduce(packets, s.queue, &:queue.in/2), - pending: binary_part(data, byte_size(data) - rest, rest) - }} + {:ok, %{s | queue: Enum.reduce(packets, s.queue, &:queue.in/2), packetizer: packetizer}} end end @@ -202,11 +178,9 @@ defmodule AudioFlow.WebRTC.Transport do %{ s | queue: :queue.new(), - pending: <<>>, - converter: %RateConverter{}, + packetizer: %Packetizer{}, timer: nil, sealed: false, - rate: nil, error: nil } end diff --git a/test/network_protocol_test.exs b/test/network_protocol_test.exs index fb1b482..7d6e5d4 100644 --- a/test/network_protocol_test.exs +++ b/test/network_protocol_test.exs @@ -244,7 +244,8 @@ defmodule AudioFlow.NetworkProtocolTest do assert {:push, frames, _state} = handler.handle_info( - {AudioFlow.WebSocket, :push, {state.pcm.session, ref}, audio, {self(), tag}}, + {AudioFlow.Transport.Connection, :push, {state.pcm.session, ref}, audio, + {self(), tag}}, state ) diff --git a/test/telephony_reorder_test.exs b/test/telephony_reorder_test.exs index 152f35d..4c18c7e 100644 --- a/test/telephony_reorder_test.exs +++ b/test/telephony_reorder_test.exs @@ -105,7 +105,10 @@ defmodule AudioFlow.TelephonyReorderTest do audio = %AudioFlow.Audio{sample_rate: 8000, data: :binary.copy(<<0>>, 960)} assert {:ok, state} = - Handler.handle_info({AudioFlow.WebSocket, :push, key, audio, {self(), tag}}, state) + Handler.handle_info( + {AudioFlow.Transport.Connection, :push, key, audio, {self(), tag}}, + state + ) assert_receive {^tag, :ok} assert :queue.len(state.playout) == 3 @@ -121,11 +124,11 @@ defmodule AudioFlow.TelephonyReorderTest do {timer, old_token} = state.playout_timer assert {:push, [{:text, clear}], state} = - Handler.handle_info({AudioFlow.WebSocket, :flush, key}, state) + Handler.handle_info({AudioFlow.Transport.Connection, :flush, key}, state) assert JSON.decode!(clear) == %{"event" => "clear"} assert :queue.is_empty(state.playout) - assert state.pending == <<>> and state.playout_timer == nil + assert state.playout_timer == nil assert Process.read_timer(timer) == false assert {:ok, ^state} = Handler.handle_info({Handler, :playout, old_token}, state) end @@ -138,7 +141,7 @@ defmodule AudioFlow.TelephonyReorderTest do assert {:stop, {:protocol_error, :playout_limit}, _, state} = Handler.handle_info( - {AudioFlow.WebSocket, :push, {state.pcm.session, ref}, audio, + {AudioFlow.Transport.Connection, :push, {state.pcm.session, ref}, audio, {self(), make_ref()}}, state ) From 1addf5f23dfbe9303db284a5956c615b37096181 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Fri, 6 Nov 2026 15:48:22 +0200 Subject: [PATCH 3/6] refactor(apps): centralize chat settings and graph requirements --- examples/chat/assets/js/audio.js | 3 - examples/chat/lib/chat/catalog.ex | 4 ++ examples/chat/lib/chat/engine.ex | 9 +-- examples/chat/lib/chat/setup.ex | 22 ++++++- examples/chat/lib/chat/wav.ex | 12 ---- examples/chat/lib/chat_web/live/chat_live.ex | 30 ++++------ examples/chat/mix.exs | 18 +++--- examples/chat/native/engine.ex | 12 ++-- examples/chat/test/chat_test.exs | 13 +++++ ui/lib/audio_flow_ui/examples.ex | 60 +++++++++++++------- ui/lib/audio_flow_ui/graphs.ex | 1 - ui/lib/audio_flow_ui/prerequisites.ex | 27 +-------- ui/lib/audio_flow_ui/runs.ex | 1 - ui/lib/audio_flow_ui/wave.ex | 7 +-- ui/lib/audio_flow_ui_web/live/graph_live.ex | 2 - ui/test/examples_test.exs | 6 +- 16 files changed, 110 insertions(+), 117 deletions(-) delete mode 100644 examples/chat/lib/chat/wav.ex diff --git a/examples/chat/assets/js/audio.js b/examples/chat/assets/js/audio.js index 54f5a63..0b0b79d 100644 --- a/examples/chat/assets/js/audio.js +++ b/examples/chat/assets/js/audio.js @@ -83,7 +83,6 @@ export const Recorder = { window.dispatchEvent(new CustomEvent("chat:flush")); try { - // Load the worklet while the browser opens the microphone. const context = new AudioContext(); this.targetRate = Number(this.el.dataset.rate || INPUT_RATE); if (context.sampleRate < this.targetRate) { await context.close(); throw new Error("Capture sample rate is below required PCM rate"); } @@ -111,7 +110,6 @@ export const Recorder = { } }, - // Conversion is deterministic per sample, so earlier samples do not change. send(event) { const capture = this.capture; if (!capture) return; @@ -199,7 +197,6 @@ export const Player = { this.handleEvent("output_control", (command) => { const epoch = this.epoch; - // Serialize actual Web Audio operations. A resume never overtakes suspend. this.commands = this.commands.then(async () => { if (epoch !== this.epoch || command.token !== this.token) return; try { diff --git a/examples/chat/lib/chat/catalog.ex b/examples/chat/lib/chat/catalog.ex index b5c166b..b549638 100644 --- a/examples/chat/lib/chat/catalog.ex +++ b/examples/chat/lib/chat/catalog.ex @@ -7,6 +7,10 @@ defmodule Chat.Catalog do about twice its f16 download. Compiled kernels and caches add to this. """ + @defaults %{stt: "whisper-small", llm: "qwen3-1.7b", voice: "af_heart"} + + def defaults, do: @defaults + @stt [ %{ id: "whisper-tiny", diff --git a/examples/chat/lib/chat/engine.ex b/examples/chat/lib/chat/engine.ex index 1e62149..88f90b0 100644 --- a/examples/chat/lib/chat/engine.ex +++ b/examples/chat/lib/chat/engine.ex @@ -1,12 +1,7 @@ defmodule Chat.Engine do @moduledoc "Profile boundary: only native builds start model processes." @compile {:no_warn_undefined, Chat.LocalEngine} - def native?, - do: - System.get_env( - "CHAT_PROFILE", - if(:os.type() == {:unix, :darwin}, do: "native", else: "demo") - ) == "native" + def native?, do: Application.fetch_env!(:chat, :native_profile) def child_spec(_) do if native?(), @@ -25,7 +20,7 @@ defmodule Chat.Engine do if native?(), do: Chat.LocalEngine.status(), else: %{ - selection: %{stt: "whisper-small", llm: "qwen3-1.7b", voice: "af_heart"}, + selection: Chat.Catalog.defaults(), status: %{}, memory_gb: 0 } diff --git a/examples/chat/lib/chat/setup.ex b/examples/chat/lib/chat/setup.ex index 7b4b634..d740a7e 100644 --- a/examples/chat/lib/chat/setup.ex +++ b/examples/chat/lib/chat/setup.ex @@ -2,6 +2,22 @@ defmodule Chat.Setup do @moduledoc "Validated per-tab settings. Credentials are resolved only on the server." alias AudioFlow.Adapters + @modes [ + {"demo", "Synthetic demo"}, + {"local", "Local Apple MLX"}, + {"remote", "Deepgram → Chat HTTP → TTS"}, + {"openai", "OpenAI speech-to-speech"}, + {"gemini", "Gemini speech-to-speech"} + ] + @languages ~w(en es fr de ro) + @voices ~w(marin cedar) + @tts_providers ~w(elevenlabs cartesia) + + def modes, do: @modes + def languages, do: @languages + def voices, do: @voices + def tts_providers, do: @tts_providers + def defaults, do: %{ "mode" => if(Chat.Engine.native?(), do: "local", else: "demo"), @@ -23,7 +39,7 @@ defmodule Chat.Setup do missing = Enum.filter(required(s), &(env.(&1) in [nil, ""])) cond do - mode not in ["local", "demo", "remote", "openai", "gemini"] -> + not Enum.any?(@modes, &(elem(&1, 0) == mode)) -> {:error, "Unknown mode"} not supported?(s) -> @@ -50,8 +66,8 @@ defmodule Chat.Setup do defp required(s), do: requirements(s["mode"]) defp supported?(s) do - s["language"] in ["en", "es", "fr", "de", "ro"] and s["voice"] in ["marin", "cedar"] and - s["tts"] in ["elevenlabs", "cartesia"] + s["language"] in @languages and s["voice"] in @voices and + s["tts"] in @tts_providers end defp key(env, name), do: fn -> env.(name) end diff --git a/examples/chat/lib/chat/wav.ex b/examples/chat/lib/chat/wav.ex deleted file mode 100644 index b3139f8..0000000 --- a/examples/chat/lib/chat/wav.ex +++ /dev/null @@ -1,12 +0,0 @@ -defmodule Chat.Wav do - @moduledoc "Wraps mono s16le PCM in a WAV header for the browser audio player." - - def encode(pcm, rate) do - data = IO.iodata_to_binary(pcm) - size = byte_size(data) - - <<"RIFF", size + 36::little-32, "WAVE", "fmt ", 16::little-32, 1::little-16, 1::little-16, - rate::little-32, rate * 2::little-32, 2::little-16, 16::little-16, "data", size::little-32, - data::binary>> - end -end diff --git a/examples/chat/lib/chat_web/live/chat_live.ex b/examples/chat/lib/chat_web/live/chat_live.ex index 0ac90ab..f6dcdf3 100644 --- a/examples/chat/lib/chat_web/live/chat_live.ex +++ b/examples/chat/lib/chat_web/live/chat_live.ex @@ -16,7 +16,6 @@ defmodule ChatWeb.ChatLive do alias AudioFlow.Text alias Chat.Catalog alias Chat.Setup - alias Chat.Wav alias ChatWeb.Components.UI.Badge alias ChatWeb.Components.UI.Button alias ChatWeb.Components.UI.NativeSelect @@ -82,7 +81,6 @@ defmodule ChatWeb.ChatLive do end end - # A new recording interrupts the current reply. def handle_event("recording", _params, socket) do socket = cancel(socket) |> add_message("user", "", pending: true, live: true) id = List.last(socket.assigns.messages).id @@ -336,7 +334,6 @@ defmodule ChatWeb.ChatLive do def handle_info({AudioFlow, _, _, _}, socket), do: {:noreply, socket} def handle_info({:models, models}, socket), do: {:noreply, assign(socket, models: models)} - # A partial transcription finished. def handle_info({ref, result}, %{assigns: %{recording: %{task: ref} = recording}} = socket) do Process.demonitor(ref, [:flush]) @@ -355,7 +352,6 @@ defmodule ChatWeb.ChatLive do ), do: {:noreply, assign(socket, recording: %{r | task: nil})} - # Results of partial transcriptions for a recording that already ended. def handle_info({ref, _}, socket) when is_reference(ref) do Process.demonitor(ref, [:flush]) {:noreply, socket} @@ -404,7 +400,13 @@ defmodule ChatWeb.ChatLive do if socket.assigns.rate, do: %{ media_type: "audio/wav", - base64: Base.encode64(Wav.encode(socket.assigns.pcm, socket.assigns.rate)) + base64: + Base.encode64( + AudioFlow.Wav.encode(%AudioFlow.Audio{ + data: IO.iodata_to_binary(socket.assigns.pcm), + sample_rate: socket.assigns.rate + }) + ) } note = @@ -479,7 +481,6 @@ defmodule ChatWeb.ChatLive do ) end - # One partial transcription runs at a time, over the complete recording so far. defp maybe_transcribe(%{assigns: %{recording: %{invalid: true}}} = socket), do: socket defp maybe_transcribe(%{assigns: %{settings: %{"mode" => mode}}} = socket) when mode != "local", @@ -543,7 +544,6 @@ defmodule ChatWeb.ChatLive do assign(socket, messages: messages) end - # The newest user message that is not the live recording. defp update_last(socket, role, fun) do live = socket.assigns.recording && socket.assigns.recording.id @@ -606,15 +606,7 @@ defmodule ChatWeb.ChatLive do