- Type a message, or record one with the microphone.
+ {if @duplex,
+ do: "Start a conversation and talk. You and Moshi can speak at the same time.",
+ else: "Type a message, or record one with the microphone."}
New chat
@@ -636,7 +873,7 @@ defmodule ChatWeb.ChatLive do
>
{voice}
-
+
{@setup_error}
@@ -645,13 +882,16 @@ defmodule ChatWeb.ChatLive do
Synthetic demo: fixed transcript, echoed text, silent PCM. No inference.
+
+ Full duplex: the microphone stays open and Moshi audio plays at the same time. Input is sent in 80 ms chunks. Moshi speaks English only and does not transcribe you. Use headphones to prevent echo. The server connects to AUDIOFLOW_MOSHI_ENDPOINT.
+
Microphone only; fresh provider connection each turn, no history replay. No text/audio alignment or native history truncation is claimed. Language and Gemini voice use provider defaults.
Remote chain requires DEEPGRAM_API_KEY, CHAT_HTTP_ENDPOINT, CHAT_HTTP_MODEL and ELEVENLABS_API_KEY / ELEVENLABS_VOICE_ID or CARTESIA_API_KEY / CARTESIA_VOICE_ID. Optional CHAT_HTTP_API_KEY. Speech-to-speech requires OPENAI_API_KEY / OPENAI_REALTIME_MODEL or GEMINI_API_KEY / GEMINI_LIVE_MODEL. Configure these on the server.
Synthetic demo: fixed transcript, echoed text, silent PCM. No inference.
- Full duplex: the microphone stays open and Moshi audio plays at the same time. Input is sent in 80 ms chunks. Moshi speaks English only and does not transcribe you. Use headphones to prevent echo. The server connects to AUDIOFLOW_MOSHI_ENDPOINT.
+ AudioFlow sends your microphone audio to local Moshi and plays its reply at the same time. Moshi speaks English. The text below is its speech, not a transcript of your voice.
Microphone only; fresh provider connection each turn, no history replay. No text/audio alignment or native history truncation is claimed. Language and Gemini voice use provider defaults.
-
+
Remote chain requires DEEPGRAM_API_KEY, CHAT_HTTP_ENDPOINT, CHAT_HTTP_MODEL and ELEVENLABS_API_KEY / ELEVENLABS_VOICE_ID or CARTESIA_API_KEY / CARTESIA_VOICE_ID. Optional CHAT_HTTP_API_KEY. Speech-to-speech requires OPENAI_API_KEY / OPENAI_REALTIME_MODEL or GEMINI_API_KEY / GEMINI_LIVE_MODEL. Configure these on the server.
Opt-in text-only JSON: all content replaced with [REDACTED], no PCM. Limit 20 turns, 1 hour, 128 KB buffered per turn. Deleted on disconnect; retention checked every minute and on access.
@@ -902,7 +904,7 @@ defmodule ChatWeb.ChatLive do
Delete
-
+
+
+
+ Start conversation
+
+
+ Stop
+
+
+
+ {call_label(@call_status)}
+
+
+
+ Use headphones. Clear text does not reset Moshi. Its context stays until the model service restarts.
+
+
+ {@call_error}
+
+
No messages yet.
@@ -998,27 +1024,6 @@ defmodule ChatWeb.ChatLive do
Confirm / Stop{if @paused, do: "Web Audio suspended", else: "Playback running or awaiting endpoint"}
-
-
- Start conversation
-
-
- Stop
-
-
-
- {call_label(@call_status)}
-
-
-
- {@call_error}
-
-
element("#configuration") |> render_submit(%{"mode" => "demo"})
assert render(view) =~ "Stop the current turn, recording or conversation"
- assert render(view) =~ "Active: moshi"
+ assert has_element?(view, "select[name=mode] option[value=moshi][selected]")
end
test "microphone denial and an unreachable model stop the conversation with an error" do
From ebbb9c65dc173cc70ebb2d55a0fa22dff7b12dbd Mon Sep 17 00:00:00 2001
From: TudorAndrei
Date: Fri, 6 Nov 2026 22:48:03 +0200
Subject: [PATCH 09/12] fix(chat): bound microphone startup and allow
cancellation
---
examples/chat/assets/js/duplex.js | 19 +++++++++++++++-
examples/chat/assets/test/duplex.test.js | 29 +++++++++++++++++++++---
2 files changed, 44 insertions(+), 4 deletions(-)
diff --git a/examples/chat/assets/js/duplex.js b/examples/chat/assets/js/duplex.js
index d7166fe..c09425d 100644
--- a/examples/chat/assets/js/duplex.js
+++ b/examples/chat/assets/js/duplex.js
@@ -89,7 +89,10 @@ export const Duplex = {
this.handleEvent("call_ready", ({ generation }) => {
this.readyGeneration = generation;
const call = this.current(generation);
- if (call) call.ready = true;
+ if (call) {
+ call.ready = true;
+ clearTimeout(call.startupTimer);
+ }
});
this.handleEvent("call_play", ({ generation, pcm, rate }) => {
const call = this.current(generation);
@@ -134,6 +137,13 @@ export const Duplex = {
};
this.call = call;
this.draw("Requesting microphone…");
+ call.startupTimer = setTimeout(() => {
+ this.fail(call, new Error(
+ call.generation === null
+ ? "Microphone or audio setup did not finish. Allow microphone access and try again."
+ : "The model connection did not become ready. Try again.",
+ ));
+ }, 20_000);
try {
// Created during the click, so the browser allows playback.
@@ -167,6 +177,7 @@ export const Duplex = {
track.onended = () => this.fail(call, new Error("Microphone disconnected"));
}
+ this.draw("Connecting to Moshi…");
this.pushEvent("call_start", {}, (reply) => {
if (this.call !== call) {
// Stopped while the server started it.
@@ -176,6 +187,7 @@ export const Duplex = {
if (!reply?.ok) return this.release(call);
call.generation = reply.generation;
call.ready = this.readyGeneration === reply.generation;
+ if (call.ready) clearTimeout(call.startupTimer);
this.ticker = setInterval(() => this.draw(), 500);
this.draw();
});
@@ -248,6 +260,7 @@ export const Duplex = {
release(call) {
if (!call) return;
+ clearTimeout(call.startupTimer);
call.released = true;
if (this.call === call) {
this.call = null;
@@ -272,6 +285,10 @@ export const Duplex = {
},
draw(text) {
+ const start = this.controls.querySelector('[data-call="start"]');
+ const stop = this.controls.querySelector('[data-call="stop"]');
+ if (start) start.disabled = Boolean(this.call);
+ if (stop) stop.disabled = !this.call;
const stats = this.controls.querySelector("#duplex-stats");
if (!stats) return;
const call = this.call;
diff --git a/examples/chat/assets/test/duplex.test.js b/examples/chat/assets/test/duplex.test.js
index 4f83c60..ac70614 100644
--- a/examples/chat/assets/test/duplex.test.js
+++ b/examples/chat/assets/test/duplex.test.js
@@ -83,12 +83,17 @@ function mount() {
const pushes = [];
const listeners = {};
const stats = { textContent: "" };
+ const buttons = {
+ start: { disabled: false, dataset: { call: "start" } },
+ stop: { disabled: true, dataset: { call: "stop" } },
+ };
const el = {
addEventListener(type, fn) {
listeners[type] = fn;
},
removeEventListener() {},
- querySelector: () => stats,
+ querySelector: (selector) => selector.includes('"start"') ? buttons.start :
+ selector.includes('"stop"') ? buttons.stop : stats,
};
const hook = {
...Duplex,
@@ -103,9 +108,9 @@ function mount() {
hook.mounted();
mounted.push(hook);
const click = (action) =>
- listeners.click({ target: { closest: () => ({ dataset: { call: action }, disabled: false }) } });
+ listeners.click({ target: { closest: () => buttons[action] } });
const sent = (name) => pushes.filter((push) => push.name === name);
- return { hook, handlers, pushes, click, sent, stats };
+ return { hook, handlers, pushes, click, sent, stats, buttons };
}
// Starts a conversation: click, microphone grant, server reply, model handshake.
@@ -248,8 +253,10 @@ test("server stop, disconnect and a stop during startup all release the call", a
const early = mount();
grantMicrophone();
early.click("start");
+ assert.equal(early.buttons.stop.disabled, false);
await tick();
early.click("stop");
+ assert.equal(early.buttons.start.disabled, false);
assert.ok(microphone.track.stopped);
early.sent("call_start")[0].reply({ ok: true, generation: 8 });
assert.deepEqual(early.sent("call_stop").at(-1).payload, { generation: 8 });
@@ -273,3 +280,19 @@ test("microphone denial and device loss report a failure and release capture", a
assert.deepEqual(lost.sent("call_failed").at(-1).payload, { message: "Microphone disconnected" });
assert.ok(microphone.track.stopped);
});
+
+test("a microphone request that does not finish times out and releases a late grant", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const view = mount();
+ const mic = grantMicrophone();
+ let grant;
+ mic.grant = () => new Promise((resolve) => { grant = resolve; });
+ view.click("start");
+ t.mock.timers.tick(20_000);
+ assert.equal(view.hook.call, null);
+ assert.match(view.sent("call_failed").at(-1).payload.message, /microphone/i);
+ grant({ getTracks: () => [mic.track] });
+ await tick();
+ assert.ok(mic.track.stopped);
+ assert.equal(view.sent("call_start").length, 0);
+});
From ca48791908073c04ed2441e6f5f7fdb0b789465e Mon Sep 17 00:00:00 2001
From: TudorAndrei
Date: Fri, 6 Nov 2026 23:12:44 +0200
Subject: [PATCH 10/12] feat(duplex): add continuous OpenAI Realtime adapter
AudioFlow.Duplex.OpenAIRealtime keeps one server-owned OpenAI Realtime GA
WebSocket open per call. It configures server VAD with create_response and
interrupt_response, emits :ready only after session.updated, appends input
without commits or response.create, and keeps the provider conversation
for the whole connection.
Duplex core additions:
- adapter input_flow :realtime bounds input against the wall clock, so
continuous silence never fills the input lead (Moshi keeps :answered)
- adapter headers can be a function, resolved only to connect
- events {:speech_started, item}, {:transcript, item, text | :failed},
{:response, id, status} and {:output, item}
- Duplex.control/2 with optional handle_control/2; OpenAI uses
{:played, item, ms} to send conversation.item.truncate, capped to the
received audio, once, for the last interrupted reply only
---
README.md | 13 +-
docs/providers.md | 84 +++++-
lib/audio_flow/duplex.ex | 89 +++++-
lib/audio_flow/duplex/adapter.ex | 48 +++-
lib/audio_flow/duplex/openai_realtime.ex | 279 ++++++++++++++++++
test/duplex_openai_test.exs | 348 +++++++++++++++++++++++
6 files changed, 837 insertions(+), 24 deletions(-)
create mode 100644 lib/audio_flow/duplex/openai_realtime.ex
create mode 100644 test/duplex_openai_test.exs
diff --git a/README.md b/README.md
index fd45bae..bf4f532 100644
--- a/README.md
+++ b/README.md
@@ -30,9 +30,11 @@ mix audio_flow.bench --runs 20 --concurrency 4
For a browser chat with typed and spoken messages, see
[examples/chat](examples/chat/README.md). Its Linux demo needs no model download;
the app also exposes server-configured speech providers, languages, redacted
-recordings, playback progress and provisional pause/resume. Its full duplex
-mode talks to a local Moshi server through `AudioFlow.Duplex`: the microphone
-stays open and the model audio plays at the same time.
+recordings, playback progress and provisional pause/resume. Its always-on
+modes use `AudioFlow.Duplex` with OpenAI Realtime or a local Moshi server: the
+microphone stays open from Start to Stop and the model audio plays at the same
+time. OpenAI detects each utterance, replies by voice and stops the reply when
+you speak.
To build agents as node graphs, see [ui](ui/README.md). It is a local dashboard
with a canvas editor and an MCP endpoint for coding agents. A session runs an
@@ -68,7 +70,10 @@ For OpenAI Realtime, Gemini Live or a local
[Moshi](docs/providers.md#local-moshi-speech-to-speech) server without chained
stages, use the explicit
[Session speech-to-speech mode](docs/providers.md#session-speech-to-speech-mode).
-It accepts committed PCM and does not replay cross-turn history.
+It accepts committed PCM and does not replay cross-turn history. For a
+continuous conversation with the microphone open, use `AudioFlow.Duplex` with
+[OpenAI Realtime](docs/providers.md#continuous-openai-realtime-conversation) or
+[Moshi](docs/providers.md#continuous-full-duplex-moshi).
The owner receives transcript, text, audio, and terminal events. See
`AudioFlow` for the event format. Each turn has a unique reference. A session
diff --git a/docs/providers.md b/docs/providers.md
index 57d0525..bf497e8 100644
--- a/docs/providers.md
+++ b/docs/providers.md
@@ -49,6 +49,10 @@ not decoded and are not requested.
## Direct speech-to-speech calls
+These calls send one committed utterance per connection. For an always-on
+OpenAI conversation with the microphone open, use
+[`AudioFlow.Duplex.OpenAIRealtime`](#continuous-openai-realtime-conversation).
+
`AudioFlow.Adapters.OpenAIRealtime.run/3` and
`AudioFlow.Adapters.GeminiLive.run/3` accept a committed `AudioFlow.Audio` and
invoke an arity-one callback with `{:transcript, text}`, `{:text, delta}` and
@@ -129,7 +133,8 @@ explicit typed event ports (transcript, text and audio), routing/validation for
each, and a dedicated history capability contract. Registering either adapter
as an existing STT/LLM/TTS node would misrepresent its contract. Use the explicit
Session mode or direct API today. There is no continuous duplex input, tool
-execution, automatic reconnect, resampling or WebRTC in this mode.
+execution, automatic reconnect, resampling or WebRTC in this mode. For
+continuous input, see `AudioFlow.Duplex` below.
## Local Moshi speech-to-speech
@@ -235,9 +240,11 @@ Bounds (defaults):
- `:max_response_bytes` (67,108,864) for all incoming WebSocket bytes in a
session, including fragments. The session fails with `:response_too_large`
at this bound. Incomplete Ogg packets are limited to 256 KiB.
-- `:max_input_lead_ms` (2,000) of pushed audio that model audio has not
- answered. A push past it returns `{:error, :overloaded}` and is not sent, for
- example while MLX warms up.
+- `:max_input_lead_ms` (2,000). For Moshi (adapter input flow `:answered`):
+ pushed audio that model audio has not answered. For OpenAI (`:realtime`):
+ pushed audio ahead of the wall clock since `:ready`, so continuous silence
+ never fills it. A push past it returns `{:error, :overloaded}` and is not
+ sent, for example while MLX warms up.
- `:max_owner_queue` (250): when the owner mailbox has this many messages, the
session fails with `:owner_overloaded`. Output is not buffered or dropped.
- `:send_timeout_ms` (5,000) for each TCP write.
@@ -254,6 +261,68 @@ timeouts and connection cleanup against a local fixture. With
`AUDIOFLOW_HTTP_MODEL_TESTS=1` and `AUDIOFLOW_MOSHI_PCM`, it also streams the
question and then silence in real time to a running server.
+### Continuous OpenAI Realtime conversation
+
+`AudioFlow.Duplex.OpenAIRealtime` keeps one authenticated OpenAI Realtime GA
+WebSocket open for a whole conversation. It needs no media build.
+
+```elixir
+{:ok, duplex} =
+ AudioFlow.Duplex.start(
+ owner: self(),
+ adapter:
+ {AudioFlow.Duplex.OpenAIRealtime,
+ model: System.fetch_env!("OPENAI_REALTIME_MODEL"),
+ api_key: fn -> System.fetch_env!("OPENAI_API_KEY") end,
+ voice: "marin"})
+
+# After {AudioFlow.Duplex, ^duplex, :ready}, push 24 kHz PCM continuously,
+# silence included:
+:ok = AudioFlow.Duplex.push(duplex, %AudioFlow.Audio{data: pcm, sample_rate: 24_000})
+```
+
+The adapter sends `session.update` (type `realtime`, `output_modalities`
+`["audio"]`, PCM 24 kHz in and out, the voice, input transcription and
+`server_vad` with `create_response` and `interrupt_response`) after
+`session.created`, and emits `:ready` after `session.updated`. Each push is one
+`input_audio_buffer.append`. The adapter never commits input and never sends
+`response.create`: OpenAI detects each utterance, replies to it and cancels the
+reply when new speech starts. All utterances of one connection share the
+provider conversation; a new connection starts a new one. The API key function
+runs only to connect, so the key is not kept in the session state. Options:
+`:model`, `:api_key`, `:voice` (`"marin"`), `:instructions` (`""`),
+`:transcription_model` (`"gpt-4o-mini-transcribe"`) and `:endpoint`.
+
+The owner also receives:
+
+| Event | Meaning |
+| --- | --- |
+| `{:speech_started, item}` | User speech started. Flush queued reply audio; keep the microphone open. Late audio and text of the interrupted reply are dropped. |
+| `{:transcript, item, text \| :failed}` | Final transcript of the user utterance `item`. |
+| `{:response, id, status}` | Reply `id` was `:created`, or ended `:completed`, `:cancelled`, `:incomplete` or `:failed`. |
+| `{:output, item}` | The next `{:audio, _}` events belong to reply audio `item`. |
+
+After a flush, report the played part of the cut reply with
+`AudioFlow.Duplex.control(duplex, {:played, item, ms})`. If `ms` is less than
+the audio received for `item`, the adapter sends `conversation.item.truncate`
+(`audio_end_ms` capped to the received audio), so the provider history keeps
+only the played audio and its transcript. Only the last interrupted reply is
+accepted, once; other reports return `{:error, :stale}` and leave the call
+open. A rejected truncation also leaves the call open. The played time is
+client playback time: it does not prove acoustic delivery. Without a report,
+the provider history keeps the full reply.
+
+Provider `error` events fail the session with `{:remote_error, code}` (only
+the code or type, never the message). Tool calls fail it with
+`:unsupported_tool_call`, because no tools are configured. All
+`AudioFlow.Duplex` bounds apply; `:max_response_bytes` (64 MiB) is about 17
+minutes of base64 reply audio per session.
+
+`mix test test/duplex_openai_test.exs` checks the handshake order, server VAD
+configuration, several utterances on one socket, continuous silence,
+interruption drops, truncation bounds, provider errors and cleanup against a
+local WebSocket peer, not OpenAI.
+
## Bounds, cancellation and errors
All providers accept `:endpoint` overrides for proxies and local tests. Use
@@ -279,9 +348,14 @@ samples fail. Limits and timeout options must be positive integers.
## Protocol references and verification
-Wire shapes were checked against official documentation on 2026-11-03:
+Wire shapes were checked against official documentation on 2026-11-03
+(OpenAI Realtime events again on 2026-11-06):
- [OpenAI Realtime conversations](https://developers.openai.com/api/docs/guides/realtime-conversations)
+- [OpenAI Realtime WebSocket](https://developers.openai.com/api/docs/guides/voice-websockets),
+ [voice activity detection](https://developers.openai.com/api/docs/guides/realtime-vad),
+ [client events](https://developers.openai.com/api/reference/resources/realtime/client-events) and
+ [server events](https://developers.openai.com/api/reference/resources/realtime/server-events)
- [Gemini Live WebSocket reference](https://ai.google.dev/api/live)
- [Deepgram pre-recorded utterances](https://developers.deepgram.com/docs/utterances)
- [Cartesia bytes TTS](https://docs.cartesia.ai/api-reference/tts/bytes)
diff --git a/lib/audio_flow/duplex.ex b/lib/audio_flow/duplex.ex
index 0c8e459..03c5e13 100644
--- a/lib/audio_flow/duplex.ex
+++ b/lib/audio_flow/duplex.ex
@@ -26,7 +26,8 @@ defmodule AudioFlow.Duplex do
max_input_lead_ms: [
type: :pos_integer,
default: 2_000,
- doc: "Pushed audio not yet answered by model audio."
+ doc:
+ "Input lead. With adapter input flow `:answered`: pushed audio not yet answered by model audio. With `:realtime`: pushed audio ahead of the wall clock since `:ready`."
],
max_owner_queue: [
type: :pos_integer,
@@ -58,6 +59,9 @@ defmodule AudioFlow.Duplex do
`{:error, :not_ready}` before it.
* `{:audio, %AudioFlow.Audio{}}` and `{:text, text}` with model output, in
wire order.
+ * Adapters with model turn detection also send `{:speech_started, item}`,
+ `{:transcript, item, text | :failed}`, `{:response, id, status}` and
+ `{:output, item}`. See `AudioFlow.Duplex.Adapter`.
* `{:error, reason}` when the session fails. `:closed` follows.
* `:closed` once, when the session stops for any reason except owner exit.
@@ -71,8 +75,12 @@ defmodule AudioFlow.Duplex do
## Bounds
- Input that the model has not answered is at most `:max_input_lead_ms`.
- A push past that bound returns `{:error, :overloaded}` and the chunk is not
+ The adapter selects the input flow. With `:answered` (Moshi, one output
+ frame for each input frame), input that the model has not answered is at
+ most `:max_input_lead_ms`. With `:realtime` (OpenAI, output only when the
+ model speaks), pushed audio is at most `:max_input_lead_ms` ahead of the
+ wall clock since `:ready`, so continuous silence never overloads. A push
+ past the bound returns `{:error, :overloaded}` and the chunk is not
sent. Output is sent to the owner at once and is not buffered. If the owner
mailbox has `:max_owner_queue` messages or more, the session fails with
`:owner_overloaded`. The owner must be a local process.
@@ -101,6 +109,10 @@ defmodule AudioFlow.Duplex do
Code.ensure_loaded!(module)
config = module.config(adapter_options)
Socket.endpoint!(config.url)
+
+ unless Map.get(config, :input_flow, :answered) in [:answered, :realtime],
+ do: raise(ArgumentError, "input_flow must be :answered or :realtime")
+
args = {options, module, config}
if link == :linked,
@@ -123,6 +135,19 @@ defmodule AudioFlow.Duplex do
:exit, _ -> {:error, :closed}
end
+ @doc """
+ Sends an adapter control command, for example playback progress. Returns
+ `:ok`, `{:error, :not_ready}`, `{:error, :unsupported}` (the adapter has no
+ controls), adapter errors such as `{:error, :stale}` (these leave the session
+ open), `{:error, :timeout}` or `{:error, :closed}`.
+ """
+ def control(pid, command) when is_pid(pid) do
+ GenServer.call(pid, {:control, command}, @call_timeout)
+ catch
+ :exit, {:timeout, _} -> {:error, :timeout}
+ :exit, _ -> {:error, :closed}
+ end
+
@doc "Stops the session and closes the connection. Returns `:ok` if it already stopped."
def stop(pid) when is_pid(pid) do
GenServer.stop(pid, :normal, @call_timeout)
@@ -154,6 +179,8 @@ defmodule AudioFlow.Duplex do
module: module,
adapter: module.init(config.options),
rate: config.sample_rate,
+ input_flow: Map.get(config, :input_flow, :answered),
+ ready_at: nil,
phase: :connecting,
connector: connector,
conn: nil,
@@ -174,9 +201,21 @@ defmodule AudioFlow.Duplex do
end
@impl true
- def handle_call({:push, _audio}, _from, %{phase: phase} = state) when phase != :ready,
+ def handle_call({_kind, _value}, _from, %{phase: phase} = state) when phase != :ready,
do: {:reply, {:error, :not_ready}, state}
+ def handle_call({:control, command}, _from, state) do
+ with true <- function_exported?(state.module, :handle_control, 2),
+ {:ok, frames, adapter} <- state.module.handle_control(command, state.adapter),
+ {:ok, state} <- send_frames(%{state | adapter: adapter}, frames) do
+ {:reply, :ok, state}
+ else
+ false -> {:reply, {:error, :unsupported}, state}
+ {:error, reason, state} -> fail({:error, reason}, state, reason)
+ {:error, reason} -> {:reply, {:error, reason}, state}
+ end
+ end
+
def handle_call({:push, audio}, _from, state) do
with :ok <- check_audio(audio, state),
{:ok, frames, adapter} <- state.module.handle_audio(audio, state.adapter),
@@ -203,7 +242,7 @@ defmodule AudioFlow.Duplex do
byte_size(audio.data) > state.max_chunk ->
{:error, :too_large}
- state.pushed + div(byte_size(audio.data), 2) - state.received > state.max_lead ->
+ state.pushed + div(byte_size(audio.data), 2) - allowance(state) > state.max_lead ->
{:error, :overloaded}
true ->
@@ -213,6 +252,12 @@ defmodule AudioFlow.Duplex do
defp check_audio(_audio, _state), do: {:error, :invalid_audio}
+ # Samples that the bound already counts as consumed.
+ defp allowance(%{input_flow: :answered} = state), do: state.received
+
+ defp allowance(%{input_flow: :realtime} = state),
+ do: div((System.monotonic_time(:millisecond) - state.ready_at) * state.rate, 1000)
+
defp fail(reply, state, reason) do
notify!(state, {:error, reason})
{:stop, :normal, reply, state}
@@ -342,7 +387,15 @@ defmodule AudioFlow.Duplex do
defp events(%{phase: :open} = state, [:ready | rest]) do
:erlang.cancel_timer(state.connect_timer)
- state = restart_idle(%{state | phase: :ready, connect_timer: nil})
+
+ state =
+ restart_idle(%{
+ state
+ | phase: :ready,
+ connect_timer: nil,
+ ready_at: System.monotonic_time(:millisecond)
+ })
+
with :ok <- notify(state, :ready), do: events(state, rest)
end
@@ -351,11 +404,25 @@ defmodule AudioFlow.Duplex do
with :ok <- notify(state, event), do: events(state, rest)
end
- defp events(state, [{:text, text} = event | rest]) when is_binary(text) do
- with :ok <- notify(state, event), do: events(state, rest)
+ defp events(state, [event | rest]) do
+ if valid_event?(event) do
+ with :ok <- notify(state, event), do: events(state, rest)
+ else
+ {:error, :invalid_event, state}
+ end
end
- defp events(state, _), do: {:error, :invalid_event, state}
+ @statuses [:created, :completed, :cancelled, :incomplete, :failed]
+
+ defp valid_event?({:text, text}), do: is_binary(text)
+ defp valid_event?({:speech_started, item}), do: is_binary(item)
+ defp valid_event?({:output, item}), do: is_binary(item)
+
+ defp valid_event?({:transcript, item, text}),
+ do: is_binary(item) and (is_binary(text) or text == :failed)
+
+ defp valid_event?({:response, id, status}), do: is_binary(id) and status in @statuses
+ defp valid_event?(_event), do: false
defp notify(state, event) do
case Process.info(state.owner, :message_queue_len) do
@@ -406,8 +473,10 @@ defmodule AudioFlow.Duplex do
defp connect(server, config, timeout, send_timeout) do
deadline = System.monotonic_time(:millisecond) + timeout
transport = [send_timeout: send_timeout, send_timeout_close: true]
+ # A header function keeps credentials out of the session state.
+ headers = if is_function(config.headers, 0), do: config.headers.(), else: config.headers
- case Socket.open(config.url, config.headers, deadline,
+ case Socket.open(config.url, headers, deadline,
mode: :active,
transport_opts: transport
) do
diff --git a/lib/audio_flow/duplex/adapter.ex b/lib/audio_flow/duplex/adapter.ex
index 8795aa4..1261133 100644
--- a/lib/audio_flow/duplex/adapter.ex
+++ b/lib/audio_flow/duplex/adapter.ex
@@ -12,21 +12,50 @@ defmodule AudioFlow.Duplex.Adapter do
until then.
* `{:audio, %AudioFlow.Audio{}}` with model output at `:sample_rate`.
* `{:text, text}` with model text.
+
+ Adapters for models with their own turn detection also return:
+
+ * `{:speech_started, item}`: the model detected user speech. Audio of the
+ current reply is obsolete; the owner flushes queued playback. `item` is
+ the provider ID of the user input.
+ * `{:transcript, item, text}`: final transcript of the user input `item`,
+ or `{:transcript, item, :failed}`.
+ * `{:response, id, status}`: a model reply starts (`:created`) or ends
+ (`:completed`, `:cancelled`, `:incomplete` or `:failed`).
+ * `{:output, item}`: the next `{:audio, _}` events belong to the reply
+ audio `item`, until the next `{:output, _}` or `{:speech_started, _}`.
"""
alias AudioFlow.Audio
@type frame :: {:text | :binary, binary()}
- @type event :: :ready | {:audio, Audio.t()} | {:text, String.t()}
+ @type item :: String.t()
+ @type event ::
+ :ready
+ | {:audio, Audio.t()}
+ | {:text, String.t()}
+ | {:speech_started, item()}
+ | {:transcript, item(), String.t() | :failed}
+ | {:response, String.t(), :created | :completed | :cancelled | :incomplete | :failed}
+ | {:output, item()}
@doc """
Validates options in the caller of `AudioFlow.Duplex.start_link/1`. Raises
`ArgumentError` for invalid options. `:url` must be `ws` or `wss`.
+
+ `:headers` can be a function that returns the headers. The session calls it
+ only to connect, so credentials do not stay in the session state.
+
+ `:input_flow` (default `:answered`) selects the input bound. `:answered`
+ counts input that model audio has not answered; use it when the model sends
+ one output frame for each input frame. `:realtime` counts input ahead of the
+ wall clock; use it when the model is silent while the user speaks.
"""
@callback config(options :: keyword()) :: %{
- url: String.t(),
- headers: [{String.t(), String.t()}],
- sample_rate: pos_integer(),
- options: term()
+ required(:url) => String.t(),
+ required(:headers) => [{String.t(), String.t()}] | (-> [{String.t(), String.t()}]),
+ required(:sample_rate) => pos_integer(),
+ required(:options) => term(),
+ optional(:input_flow) => :answered | :realtime
}
@doc "Returns the initial protocol state from `config/1` `:options`."
@@ -38,4 +67,13 @@ defmodule AudioFlow.Duplex.Adapter do
@doc "Maps one accepted input chunk to frames. Partial model frames may stay buffered."
@callback handle_audio(Audio.t(), state :: term()) ::
{:ok, [frame()], state :: term()} | {:error, term()}
+
+ @doc """
+ Maps a command from `AudioFlow.Duplex.control/2` to frames. An error leaves
+ the session open.
+ """
+ @callback handle_control(command :: term(), state :: term()) ::
+ {:ok, [frame()], state :: term()} | {:error, term()}
+
+ @optional_callbacks handle_control: 2
end
diff --git a/lib/audio_flow/duplex/openai_realtime.ex b/lib/audio_flow/duplex/openai_realtime.ex
new file mode 100644
index 0000000..f023324
--- /dev/null
+++ b/lib/audio_flow/duplex/openai_realtime.ex
@@ -0,0 +1,279 @@
+defmodule AudioFlow.Duplex.OpenAIRealtime do
+ @moduledoc """
+ `AudioFlow.Duplex` adapter for one continuous OpenAI Realtime conversation
+ over the GA WebSocket protocol. Needs no media dependencies.
+
+ The adapter sends `session.update` after `session.created` and emits `:ready`
+ after `session.updated`. Input is mono s16le PCM at 24 kHz; each push becomes
+ one `input_audio_buffer.append`. OpenAI server VAD detects speech, commits each
+ utterance and creates the reply (`create_response`). New speech cancels the
+ current reply (`interrupt_response`). The adapter never commits input or
+ creates replies itself. The provider conversation keeps every utterance of
+ one connection; a new connection starts a new conversation.
+
+ Events: `{:speech_started, item}`, `{:transcript, item, text | :failed}`,
+ `{:response, id, status}`, `{:output, item}`, `{:audio, audio}` and
+ `{:text, delta}` (assistant audio transcript or text). After
+ `{:speech_started, _}`, late audio and text of the interrupted reply are
+ dropped.
+
+ Control `{:played, item, ms}` reports how much audio of the interrupted reply
+ `item` played before the owner flushed it. If that is less than the audio
+ received for `item`, the adapter sends `conversation.item.truncate` with
+ `audio_end_ms` capped to the received audio, so the provider history keeps
+ only the played part. Only the last interrupted reply is accepted, once;
+ anything else returns `{:error, :stale}`.
+
+ Fatal reasons: `{:remote_error, code}` (provider `error` event, except for a
+ rejected truncation), `:unsupported_tool_call` (no tools are configured),
+ `:invalid_audio` and `:invalid_event`.
+
+ Options: `:model` (required), `:api_key` (required; a function is resolved
+ only to connect), `:voice` (`"marin"`), `:instructions` (`""`),
+ `:transcription_model` (`"gpt-4o-mini-transcribe"`) and `:endpoint`
+ (`"wss://api.openai.com/v1/realtime"`).
+ """
+ @behaviour AudioFlow.Duplex.Adapter
+ alias AudioFlow.Adapters.Providers.Socket
+ alias AudioFlow.Audio
+
+ @rate 24_000
+ @truncate "audioflow_truncate_"
+ @statuses %{
+ "completed" => :completed,
+ "cancelled" => :cancelled,
+ "incomplete" => :incomplete,
+ "failed" => :failed
+ }
+
+ @impl true
+ def config(options) do
+ options =
+ Keyword.validate!(options, [
+ :model,
+ :api_key,
+ voice: "marin",
+ instructions: "",
+ transcription_model: "gpt-4o-mini-transcribe",
+ endpoint: "wss://api.openai.com/v1/realtime"
+ ])
+
+ for key <- [:model, :voice, :transcription_model, :endpoint] do
+ unless is_binary(options[key]) and options[key] != "",
+ do: raise(ArgumentError, "#{key} must be a nonempty string")
+ end
+
+ unless is_binary(options[:instructions]),
+ do: raise(ArgumentError, "instructions must be a string")
+
+ api_key = options[:api_key]
+
+ unless is_function(api_key, 0) or (is_binary(api_key) and api_key != ""),
+ do: raise(ArgumentError, "api_key must be a nonempty string or a function")
+
+ %{
+ url: Socket.url(options[:endpoint], %{"model" => options[:model]}),
+ headers: fn -> [{"authorization", "Bearer " <> Socket.key(api_key: api_key)}] end,
+ sample_rate: @rate,
+ input_flow: :realtime,
+ options: Keyword.take(options, [:model, :voice, :instructions, :transcription_model])
+ }
+ end
+
+ @impl true
+ def init(options) do
+ %{
+ session: options,
+ phase: :connecting,
+ response: nil,
+ dropped: nil,
+ output: nil,
+ cut: nil,
+ truncates: 0
+ }
+ end
+
+ @impl true
+ def handle_frame({:text, data}, state) do
+ case JSON.decode(data) do
+ {:ok, %{"type" => type} = event} when is_binary(type) -> event(type, event, state)
+ _ -> {:error, :invalid_event}
+ end
+ end
+
+ def handle_frame(_frame, _state), do: {:error, :invalid_event}
+
+ @impl true
+ def handle_audio(%Audio{data: data}, state),
+ do: {:ok, [json(%{type: "input_audio_buffer.append", audio: Base.encode64(data)})], state}
+
+ @impl true
+ def handle_control({:played, item, ms}, %{cut: %{item: item} = cut} = state)
+ when is_binary(item) and is_integer(ms) and ms >= 0 do
+ received = div(cut.samples * 1000, @rate)
+ state = %{state | cut: nil}
+
+ if ms < received do
+ count = state.truncates + 1
+
+ truncate = %{
+ type: "conversation.item.truncate",
+ event_id: @truncate <> Integer.to_string(count),
+ item_id: item,
+ content_index: cut.content_index,
+ audio_end_ms: ms
+ }
+
+ {:ok, [json(truncate)], %{state | truncates: count}}
+ else
+ {:ok, [], state}
+ end
+ end
+
+ def handle_control({:played, item, ms}, _state)
+ when is_binary(item) and is_integer(ms) and ms >= 0,
+ do: {:error, :stale}
+
+ def handle_control(_command, _state), do: {:error, :invalid_command}
+
+ defp event("session.created", _event, %{phase: :connecting} = state),
+ do:
+ {:ok, [], [json(%{type: "session.update", session: session(state.session)})],
+ %{state | phase: :updating}}
+
+ defp event("session.updated", _event, %{phase: :updating} = state),
+ do: {:ok, [:ready], [], %{state | phase: :ready}}
+
+ defp event("error", event, state) do
+ error = if is_map(event["error"]), do: event["error"], else: %{}
+
+ # A rejected truncation only leaves the provider history longer.
+ if is_binary(error["event_id"]) and String.starts_with?(error["event_id"], @truncate),
+ do: {:ok, [], [], state},
+ else: {:error, {:remote_error, code(error)}}
+ end
+
+ defp event(_type, _event, %{phase: phase} = state) when phase != :ready,
+ do: {:ok, [], [], state}
+
+ defp event("input_audio_buffer.speech_started", %{"item_id" => item}, state)
+ when is_binary(item) do
+ state = %{state | dropped: state.response, cut: state.output || state.cut, output: nil}
+ {:ok, [{:speech_started, item}], [], state}
+ end
+
+ defp event(
+ "conversation.item.input_audio_transcription.completed",
+ %{"item_id" => item, "transcript" => text},
+ state
+ )
+ when is_binary(item) and is_binary(text),
+ do: {:ok, [{:transcript, item, text}], [], state}
+
+ defp event("conversation.item.input_audio_transcription.failed", %{"item_id" => item}, state)
+ when is_binary(item),
+ do: {:ok, [{:transcript, item, :failed}], [], state}
+
+ defp event("response.created", %{"response" => %{"id" => id}}, state) when is_binary(id),
+ do: {:ok, [{:response, id, :created}], [], %{state | response: id}}
+
+ defp event("response.output_audio.delta", %{"response_id" => id}, %{dropped: id} = state),
+ do: {:ok, [], [], state}
+
+ defp event(
+ "response.output_audio.delta",
+ %{"item_id" => item, "delta" => delta} = event,
+ state
+ )
+ when is_binary(item) and is_binary(delta) do
+ case Base.decode64(delta) do
+ {:ok, pcm} when rem(byte_size(pcm), 2) == 0 -> audio(pcm, item, event, state)
+ _ -> {:error, :invalid_audio}
+ end
+ end
+
+ defp event(type, %{"response_id" => id}, %{dropped: id} = state)
+ when type in ["response.output_audio_transcript.delta", "response.output_text.delta"],
+ do: {:ok, [], [], state}
+
+ defp event(type, %{"delta" => text}, state)
+ when type in ["response.output_audio_transcript.delta", "response.output_text.delta"] and
+ is_binary(text),
+ do: {:ok, [{:text, text}], [], state}
+
+ defp event("response.done", %{"response" => %{"id" => id} = response}, state)
+ when is_binary(id) do
+ output = if is_list(response["output"]), do: response["output"], else: []
+
+ cond do
+ Enum.any?(output, &(is_map(&1) and &1["type"] == "function_call")) ->
+ {:error, :unsupported_tool_call}
+
+ status = @statuses[response["status"]] ->
+ state = %{
+ state
+ | response: if(state.response == id, do: nil, else: state.response),
+ dropped: if(state.dropped == id, do: nil, else: state.dropped)
+ }
+
+ {:ok, [{:response, id, status}], [], state}
+
+ true ->
+ {:error, :invalid_event}
+ end
+ end
+
+ defp event(type, _event, _state)
+ when type in [
+ "input_audio_buffer.speech_started",
+ "response.created",
+ "response.output_audio.delta",
+ "response.output_audio_transcript.delta",
+ "response.output_text.delta",
+ "response.done",
+ "conversation.item.input_audio_transcription.completed",
+ "conversation.item.input_audio_transcription.failed"
+ ],
+ do: {:error, :invalid_event}
+
+ defp event(_type, _event, state), do: {:ok, [], [], state}
+
+ defp audio(pcm, item, event, state) do
+ {started, output} =
+ case state.output do
+ %{item: ^item} = output -> {[], output}
+ _ -> {[{:output, item}], %{item: item, content_index: index(event), samples: 0}}
+ end
+
+ output = %{output | samples: output.samples + div(byte_size(pcm), 2)}
+ audio = {:audio, %Audio{data: pcm, sample_rate: @rate}}
+ {:ok, started ++ [audio], [], %{state | output: output}}
+ end
+
+ defp session(options) do
+ %{
+ type: "realtime",
+ model: options[:model],
+ output_modalities: ["audio"],
+ instructions: options[:instructions],
+ audio: %{
+ input: %{
+ format: %{type: "audio/pcm", rate: @rate},
+ transcription: %{model: options[:transcription_model]},
+ turn_detection: %{type: "server_vad", create_response: true, interrupt_response: true}
+ },
+ output: %{format: %{type: "audio/pcm", rate: @rate}, voice: options[:voice]}
+ }
+ }
+ end
+
+ defp index(%{"content_index" => index}) when is_integer(index) and index >= 0, do: index
+ defp index(_event), do: 0
+
+ # Only the short code or type: provider messages can quote request data.
+ defp code(%{"code" => code}) when is_binary(code), do: String.slice(code, 0, 64)
+ defp code(%{"type" => type}) when is_binary(type), do: String.slice(type, 0, 64)
+ defp code(_error), do: "unknown"
+
+ defp json(value), do: {:text, JSON.encode!(value)}
+end
diff --git a/test/duplex_openai_test.exs b/test/duplex_openai_test.exs
new file mode 100644
index 0000000..f440e4e
--- /dev/null
+++ b/test/duplex_openai_test.exs
@@ -0,0 +1,348 @@
+defmodule AudioFlow.DuplexOpenAITest do
+ use ExUnit.Case, async: true
+ alias AudioFlow.Audio
+ alias AudioFlow.Duplex
+ alias AudioFlow.Duplex.OpenAIRealtime
+
+ # Local peer with the OpenAI Realtime GA event framing. It reports the
+ # upgrade request and every client event to the test, and pushes the events
+ # that the test sends to it. It never acts on its own.
+ defmodule Peer do
+ @behaviour WebSock
+
+ def init(owner) do
+ send(owner, {:peer, self()})
+ {:ok, owner}
+ end
+
+ def handle_in({data, opcode: :text}, owner) do
+ send(owner, {:client, JSON.decode!(data)})
+ {:ok, owner}
+ end
+
+ def handle_info({:events, events}, owner),
+ do: {:push, Enum.map(events, &{:text, JSON.encode!(&1)}), owner}
+
+ def handle_info(:close, owner), do: {:stop, :normal, owner}
+
+ def terminate(_reason, owner) do
+ send(owner, :peer_closed)
+ :ok
+ end
+ end
+
+ defmodule Endpoint do
+ def init(owner), do: owner
+
+ def call(conn, owner) do
+ send(owner, {:upgrade, conn.query_string, conn.req_headers})
+ conn |> WebSockAdapter.upgrade(Peer, owner, []) |> Plug.Conn.halt()
+ end
+ end
+
+ # 80 ms of 24 kHz mono s16le.
+ @chunk 3_840
+
+ defp endpoint do
+ server =
+ start_supervised!(
+ {Bandit, plug: {Endpoint, self()}, port: 0, ip: {127, 0, 0, 1}, startup_log: false}
+ )
+
+ {:ok, {_, port}} = ThousandIsland.listener_info(server)
+ "ws://127.0.0.1:#{port}/v1/realtime"
+ end
+
+ defp start(options \\ []) do
+ adapter =
+ {OpenAIRealtime,
+ endpoint: endpoint(),
+ model: "fixture-model",
+ api_key: fn -> "fixture-key" end,
+ voice: "cedar"}
+
+ {:ok, duplex} = Duplex.start_link([owner: self(), adapter: adapter] ++ options)
+ assert_receive {:peer, peer}
+ {duplex, peer}
+ end
+
+ defp ready(options \\ []) do
+ {duplex, peer} = start(options)
+ send(peer, {:events, [%{type: "session.created", session: %{}}]})
+ assert_receive {:client, %{"type" => "session.update"}}
+ send(peer, {:events, [%{type: "session.updated", session: %{}}]})
+ assert_receive {Duplex, ^duplex, :ready}
+ {duplex, peer}
+ end
+
+ defp silence(bytes \\ @chunk), do: %Audio{data: :binary.copy(<<0>>, bytes), sample_rate: 24_000}
+ defp pcm(samples), do: Base.encode64(:binary.copy(<<1, 0>>, samples))
+
+ defp delta(response, item, samples) do
+ %{
+ type: "response.output_audio.delta",
+ response_id: response,
+ item_id: item,
+ output_index: 0,
+ content_index: 0,
+ delta: pcm(samples)
+ }
+ end
+
+ defp reply(peer, response, item, text, samples) do
+ send(
+ peer,
+ {:events,
+ [
+ %{type: "response.created", response: %{id: response, status: "in_progress"}},
+ delta(response, item, samples),
+ %{type: "response.output_audio_transcript.delta", response_id: response, delta: text}
+ ]}
+ )
+ end
+
+ defp done(peer, response, status, output \\ []),
+ do:
+ send(
+ peer,
+ {:events,
+ [%{type: "response.done", response: %{id: response, status: status, output: output}}]}
+ )
+
+ defp speech(peer, item, transcript) do
+ send(
+ peer,
+ {:events,
+ [
+ %{type: "input_audio_buffer.speech_started", item_id: item, audio_start_ms: 0},
+ %{type: "input_audio_buffer.speech_stopped", item_id: item, audio_end_ms: 900},
+ %{type: "input_audio_buffer.committed", item_id: item},
+ %{
+ type: "conversation.item.input_audio_transcription.completed",
+ item_id: item,
+ content_index: 0,
+ transcript: transcript
+ }
+ ]}
+ )
+ end
+
+ test "configures server VAD replies, then is ready only after session.updated" do
+ {duplex, peer} = start()
+
+ assert_received {:upgrade, "model=fixture-model", headers}
+ assert {"authorization", "Bearer fixture-key"} in headers
+ assert {:error, :not_ready} = Duplex.push(duplex, silence())
+
+ send(peer, {:events, [%{type: "session.created", session: %{}}]})
+ assert_receive {:client, %{"type" => "session.update", "session" => session}}
+
+ assert %{
+ "type" => "realtime",
+ "model" => "fixture-model",
+ "output_modalities" => ["audio"],
+ "audio" => %{
+ "input" => %{
+ "format" => %{"type" => "audio/pcm", "rate" => 24_000},
+ "transcription" => %{"model" => "gpt-4o-mini-transcribe"},
+ "turn_detection" => %{
+ "type" => "server_vad",
+ "create_response" => true,
+ "interrupt_response" => true
+ }
+ },
+ "output" => %{
+ "format" => %{"type" => "audio/pcm", "rate" => 24_000},
+ "voice" => "cedar"
+ }
+ }
+ } = session
+
+ refute_receive {Duplex, ^duplex, :ready}, 100
+ assert {:error, :not_ready} = Duplex.push(duplex, silence())
+
+ send(peer, {:events, [%{type: "session.updated", session: session}]})
+ assert_receive {Duplex, ^duplex, :ready}
+ assert :ok = Duplex.push(duplex, silence())
+ assert_receive {:client, %{"type" => "input_audio_buffer.append", "audio" => audio}}
+ assert Base.decode64!(audio) == silence().data
+ end
+
+ test "several utterances share one connection; input is only appended, never committed" do
+ {duplex, peer} = ready()
+
+ for {user, response, item, text} <- [
+ {"user_1", "resp_1", "item_1", "Hello."},
+ {"user_2", "resp_2", "item_2", "Again."}
+ ] do
+ assert :ok = Duplex.push(duplex, silence())
+ speech(peer, user, "Question #{user}")
+ reply(peer, response, item, text, 480)
+ done(peer, response, "completed")
+
+ assert_receive {Duplex, ^duplex, {:speech_started, ^user}}
+ assert_receive {Duplex, ^duplex, {:transcript, ^user, "Question " <> ^user}}
+ assert_receive {Duplex, ^duplex, {:response, ^response, :created}}
+ assert_receive {Duplex, ^duplex, {:output, ^item}}
+ assert_receive {Duplex, ^duplex, {:audio, %Audio{data: data, sample_rate: 24_000}}}
+ assert byte_size(data) == 960
+ assert_receive {Duplex, ^duplex, {:text, ^text}}
+ assert_receive {Duplex, ^duplex, {:response, ^response, :completed}}
+ end
+
+ for _ <- 1..2, do: assert_receive({:client, %{"type" => "input_audio_buffer.append"}})
+ refute_received {:client, _}
+ refute_received {:peer, _}
+ end
+
+ test "continuous silence well past the input lead is accepted at the real-time rate" do
+ {duplex, _peer} = ready(max_input_lead_ms: 400)
+
+ # 2.4 s of silence at the browser rate, with no model output at all.
+ for _ <- 1..30 do
+ assert :ok = Duplex.push(duplex, silence())
+ Process.sleep(80)
+ end
+
+ # A burst far ahead of the clock is refused, and the call stays open.
+ results = for _ <- 1..40, do: Duplex.push(duplex, silence())
+ assert {:error, :overloaded} in results
+ assert Process.alive?(duplex)
+ refute_received {Duplex, ^duplex, {:error, _}}
+ end
+
+ test "speech during a reply drops its late audio and text, and the next reply plays" do
+ {duplex, peer} = ready()
+ reply(peer, "resp_1", "item_1", "Long answer", 2_400)
+ assert_receive {Duplex, ^duplex, {:audio, _}}
+ assert_receive {Duplex, ^duplex, {:text, "Long answer"}}
+
+ send(
+ peer,
+ {:events,
+ [
+ %{type: "input_audio_buffer.speech_started", item_id: "user_2", audio_start_ms: 10},
+ delta("resp_1", "item_1", 2_400),
+ %{type: "response.output_audio_transcript.delta", response_id: "resp_1", delta: " late"}
+ ]}
+ )
+
+ assert_receive {Duplex, ^duplex, {:speech_started, "user_2"}}
+ done(peer, "resp_1", "cancelled")
+ assert_receive {Duplex, ^duplex, {:response, "resp_1", :cancelled}}
+ refute_received {Duplex, ^duplex, {:audio, _}}
+ refute_received {Duplex, ^duplex, {:text, " late"}}
+
+ # Input continues during and after the interruption.
+ assert :ok = Duplex.push(duplex, silence())
+ reply(peer, "resp_2", "item_2", "Short", 480)
+ assert_receive {Duplex, ^duplex, {:output, "item_2"}}
+ assert_receive {Duplex, ^duplex, {:audio, _}}
+ assert_receive {Duplex, ^duplex, {:text, "Short"}}
+ end
+
+ test "played audio of the interrupted reply truncates the provider item, capped and once" do
+ {duplex, peer} = ready()
+ # 200 ms of reply audio in two deltas.
+ reply(peer, "resp_1", "item_1", "Hi", 2_400)
+ send(peer, {:events, [delta("resp_1", "item_1", 2_400)]})
+ for _ <- 1..2, do: assert_receive({Duplex, ^duplex, {:audio, _}})
+
+ assert {:error, :stale} = Duplex.control(duplex, {:played, "item_1", 50})
+
+ speech(peer, "user_2", "Wait")
+ assert_receive {Duplex, ^duplex, {:speech_started, "user_2"}}
+
+ assert {:error, :stale} = Duplex.control(duplex, {:played, "other", 50})
+ assert {:error, :invalid_command} = Duplex.control(duplex, {:played, "item_1", -1})
+ assert :ok = Duplex.control(duplex, {:played, "item_1", 120})
+
+ assert_receive {:client,
+ %{
+ "type" => "conversation.item.truncate",
+ "item_id" => "item_1",
+ "content_index" => 0,
+ "audio_end_ms" => 120,
+ "event_id" => event_id
+ }}
+
+ assert {:error, :stale} = Duplex.control(duplex, {:played, "item_1", 100})
+
+ # A rejected truncation does not end the call.
+ send(
+ peer,
+ {:events, [%{type: "error", error: %{type: "invalid_request_error", event_id: event_id}}]}
+ )
+
+ assert :ok = Duplex.push(duplex, silence())
+
+ # A report at or past the received audio needs no truncation.
+ reply(peer, "resp_2", "item_2", "Ok", 2_400)
+ assert_receive {Duplex, ^duplex, {:output, "item_2"}}
+ speech(peer, "user_3", "More")
+ assert_receive {Duplex, ^duplex, {:speech_started, "user_3"}}
+ assert :ok = Duplex.control(duplex, {:played, "item_2", 5_000})
+ refute_receive {:client, %{"type" => "conversation.item.truncate"}}, 100
+ refute_received {Duplex, ^duplex, {:error, _}}
+ end
+
+ test "provider errors, tool calls and invalid audio fail the call with a reason" do
+ for {events, reason} <- [
+ {[%{type: "error", error: %{type: "server_error", code: "boom", message: "detail"}}],
+ {:remote_error, "boom"}},
+ {[
+ %{
+ type: "response.done",
+ response: %{id: "r", status: "completed", output: [%{type: "function_call"}]}
+ }
+ ], :unsupported_tool_call},
+ {[%{type: "response.output_audio.delta", response_id: "r", item_id: "i", delta: "%%"}],
+ :invalid_audio}
+ ] do
+ {duplex, peer} = ready()
+ ref = Process.monitor(duplex)
+ send(peer, {:events, events})
+ assert_receive {Duplex, ^duplex, {:error, ^reason}}
+ assert_receive {Duplex, ^duplex, :closed}
+ assert_receive {:DOWN, ^ref, :process, ^duplex, :normal}
+ assert_receive :peer_closed
+ end
+ end
+
+ test "an error before session.updated fails the start" do
+ {duplex, peer} = start()
+
+ send(
+ peer,
+ {:events, [%{type: "error", error: %{type: "invalid_request_error", code: "bad_model"}}]}
+ )
+
+ assert_receive {Duplex, ^duplex, {:error, {:remote_error, "bad_model"}}}
+ assert_receive {Duplex, ^duplex, :closed}
+ refute_received {Duplex, ^duplex, :ready}
+ end
+
+ test "stop closes the connection; a new call starts a new provider session" do
+ {duplex, _peer} = ready()
+ assert :ok = Duplex.stop(duplex)
+ assert_receive {Duplex, ^duplex, :closed}
+ assert_receive :peer_closed
+ assert {:error, :closed} = Duplex.control(duplex, {:played, "item", 0})
+
+ {second, _peer} = ready()
+ assert second != duplex
+ end
+
+ test "rejects invalid options in the caller" do
+ for options <- [
+ [api_key: "k"],
+ [model: "m"],
+ [model: "", api_key: "k"],
+ [model: "m", api_key: "k", endpoint: "https://api.openai.com/v1/realtime"]
+ ] do
+ assert_raise ArgumentError, fn ->
+ Duplex.start_link(owner: self(), adapter: {OpenAIRealtime, options})
+ end
+ end
+ end
+end
From e86eec7edac2f9ee628e6b4065b8892415debf6c Mon Sep 17 00:00:00 2001
From: TudorAndrei
Date: Fri, 6 Nov 2026 23:13:28 +0200
Subject: [PATCH 11/12] feat(chat): run OpenAI mode as an always-on
conversation
The OpenAI mode ("OpenAI live conversation") now uses AudioFlow.Duplex
with AudioFlow.Duplex.OpenAIRealtime: Start once, the microphone stays
open and streams until Stop, and the model replies by voice. On user
speech the browser flushes queued reply audio without releasing capture,
drops late audio of the cut reply, and reports heard time so the server
truncates the provider history. Utterances show as transcript messages,
replies as assistant messages. OPENAI_REALTIME_ENDPOINT optionally
replaces the endpoint from the server environment.
The main view for all modes now has the title, the provider and voice
selectors, the conversation controls, a short status and the
conversation. Standalone transport links, prerequisite lists, timing
notes and disclaimers move to the README. Transcript saving and
playback diagnostics go to collapsed Settings and Diagnostics sections.
---
examples/chat/README.md | 107 ++++--
examples/chat/assets/js/duplex.js | 91 ++++-
examples/chat/assets/test/duplex.test.js | 58 ++-
examples/chat/lib/chat/setup.ex | 63 ++--
examples/chat/lib/chat_web/live/chat_live.ex | 368 ++++++++++++-------
examples/chat/test/chat_test.exs | 47 ++-
examples/chat/test/duplex_test.exs | 5 +-
examples/chat/test/openai_live_test.exs | 235 ++++++++++++
8 files changed, 767 insertions(+), 207 deletions(-)
create mode 100644 examples/chat/test/openai_live_test.exs
diff --git a/examples/chat/README.md b/examples/chat/README.md
index 6302035..fb98d5e 100644
--- a/examples/chat/README.md
+++ b/examples/chat/README.md
@@ -4,8 +4,16 @@ A local LiveView chat over one AudioFlow session per browser tab. Type a
message, or record one with the microphone. While you record, the user message
shows a live transcript. The reply text streams into the conversation, the
reply audio plays as it arrives, and each reply keeps an audio player for
-replay. A full duplex mode talks to a local Moshi model without turns. The UI uses [live_shadcn](https://live-shadcn-storybook.fly.dev/) and
-its AI Elements components.
+replay. Two always-on modes keep the microphone open from **Start
+conversation** to **Stop**: **OpenAI live conversation** (OpenAI Realtime) and
+**Local Moshi full duplex**. The UI uses
+[live_shadcn](https://live-shadcn-storybook.fly.dev/) and its AI Elements
+components.
+
+The page shows only the provider, its voice, the conversation controls, a short
+status and the conversation. Setup, limits and privacy details are in this
+README. Turn-based modes keep transcript saving and playback diagnostics in
+collapsed **Settings** and **Diagnostics** sections.
The native profile runs models on Apple Silicon through MLX (macOS 26.2+).
Linux defaults to a credential-free synthetic demo. Remote providers work in
@@ -27,6 +35,52 @@ Demo STT returns a fixed “Hello”, replies echo the input and output PCM is s
It tests session wiring, not recognition or synthesis. No EMLX, EXLA, Bumblebee
or model downloads are needed. Use the same profile for all Mix commands.
+## Always-on OpenAI live conversation
+
+This mode uses `AudioFlow.Duplex` with `AudioFlow.Duplex.OpenAIRealtime` over
+one server-side WebSocket to OpenAI Realtime. It needs no media build and no
+model download.
+
+```sh
+cd examples/chat
+export CHAT_PROFILE=demo CHAT_MODE=openai
+export OPENAI_API_KEY=... OPENAI_REALTIME_MODEL=gpt-realtime
+mix setup
+mix phx.server
+```
+
+Open , select the voice, click **Start conversation**
+once and allow the microphone. Talk normally. The microphone stays open until
+you click **Stop**:
+
+- The browser streams 80 ms chunks of 24 kHz PCM all the time, also silence and
+ also while the reply plays.
+- OpenAI server VAD detects each utterance and starts the spoken reply. The
+ client never commits input or requests a reply.
+- When you start to speak during a reply, OpenAI cancels the reply, and the
+ browser stops the queued reply audio at once. The microphone stays open.
+ The browser reports how much of the reply it played (audio clock minus the
+ output latency), and the server truncates the reply in the OpenAI history to
+ that part (`conversation.item.truncate`), capped to the audio it received.
+- All utterances of one call share one OpenAI conversation. A new call starts
+ a new conversation. **Clear text** clears the page only.
+- Your speech shows as a transcript message (`gpt-4o-mini-transcribe`), and
+ each reply as one assistant message.
+
+The key stays on the server: the adapter reads it only to connect, and the
+browser never sends or receives it. `OPENAI_REALTIME_ENDPOINT` (optional,
+`ws://` or `wss://` without user information) replaces the OpenAI endpoint,
+for example for a proxy.
+
+Limits (in addition to the shared limits below): the browser queues at most
+60 s of reply audio; if a reply is longer, the rest of that reply is dropped.
+Provider errors stop the call and show the provider error code only. Tool
+calls are not supported and stop the call. The truncation uses browser
+playback time, not acoustic delivery: it does not prove that you heard the
+audio, and the transcript text of a truncated reply on the page is not cut.
+Use headphones; the browser requests echo cancellation, and without it the
+model can hear its own voice.
+
## Full duplex conversation with local Moshi
This mode has no turns. The microphone stays open, and Moshi audio plays at
@@ -61,7 +115,7 @@ download. The demo profile starts no native model.
Use the same three variables for all Mix commands of this profile. The build
goes to `_build/demo_media`, so it does not reuse modules from another profile
(`_build` native, `_build/demo` demo, `_build/native_media` native with media).
-Without `CHAT_MODE=moshi`, select **Local Moshi full duplex** in the Pipeline
+Without `CHAT_MODE=moshi`, select **Local Moshi full duplex** in the Provider
list and click **Apply**.
The server reads the model endpoint only from `AUDIOFLOW_MOSHI_ENDPOINT`
@@ -69,7 +123,7 @@ The server reads the model endpoint only from `AUDIOFLOW_MOSHI_ENDPOINT`
`wss://` URL without user information. Browser events never select the
endpoint.
-Status and errors show next to the controls: **Connecting to Moshi…**, **Live**,
+Status and errors show next to the controls: **Connecting…**, **Live**,
**Conversation ended** or **Stopped by an error** with the reason (for
example `connect_failed` when the Moshi server does not run, or the microphone
error). The text input, the record button, the pause controls and the
@@ -86,13 +140,14 @@ Limits:
| Input before the model handshake | dropped |
| Input that waits for a server acknowledgement | 4 chunks (320 ms) |
| Input that waits to be sent | 12 chunks (960 ms); the oldest chunk is dropped first |
-| Input that the model has not answered | 2 s (`AudioFlow.Duplex` `:max_input_lead_ms`); more is refused with `overloaded` and dropped |
-| Queued model audio in the browser | 1 s ahead of the playback clock; later chunks are dropped |
+| Input lead (`AudioFlow.Duplex` `:max_input_lead_ms`) | 2 s. Moshi: input that the model has not answered. OpenAI: input ahead of the wall clock since the call started, so silence never fills it. More is refused with `overloaded` and dropped. |
+| Queued model audio in the browser | Moshi 1 s, OpenAI 60 s ahead of the playback clock; later chunks are dropped |
| Time | 15 s to the model handshake; 30 s without accepted input ends the conversation; 30 min in total |
| Conversation messages | the latest 200, 4,000 bytes each |
-The status line shows the sent and dropped input chunks, the queued playback
-and the dropped model audio. Each conversation has a generation number; the
+**Diagnostics** (collapsed) shows the sent and dropped input chunks, the
+queued playback, the dropped model audio and the interruptions. These limits
+apply to both always-on modes. Each conversation has a generation number; the
browser and the server ignore events of an earlier generation. Stop, an
error, a microphone failure or disconnection, a LiveView disconnect and a
server stop release the microphone, the queued playback and the model
@@ -212,7 +267,7 @@ pinned to the commit in live_shadcn's `registry/UPSTREAM.json`.
## Remote providers and per-tab controls
-The pipeline form applies settings by starting a **new chat**; it never silently
+The provider form applies settings by starting a **new chat**; it never silently
replays or discards history during a turn. Stop recording/generation first.
Native model selections remain shared across tabs, as before. Remote pipeline
settings are per tab. Browser events contain selection IDs and PCM, never keys.
@@ -223,15 +278,15 @@ Export credentials in the server shell before `mix phx.server`:
| Remote chain | `DEEPGRAM_API_KEY`, `CHAT_HTTP_ENDPOINT` (full chat-completions URL), `CHAT_HTTP_MODEL` | `DEEPGRAM_MODEL` (default nova-3), `CHAT_HTTP_API_KEY`; language en/es/fr/de/ro applies to STT and TTS |
| ElevenLabs TTS in chain | `ELEVENLABS_API_KEY`, `ELEVENLABS_VOICE_ID` | `ELEVENLABS_MODEL` (default eleven_multilingual_v2) |
| Cartesia TTS in chain | `CARTESIA_API_KEY`, `CARTESIA_VOICE_ID` | `CARTESIA_MODEL` (default sonic-3.6); API version 2026-08-14 |
-| OpenAI speech-to-speech | `OPENAI_API_KEY`, `OPENAI_REALTIME_MODEL` | Page voice marin/cedar; input/output 24 kHz |
-| Gemini speech-to-speech | `GEMINI_API_KEY`, `GEMINI_LIVE_MODEL` (include models/ prefix) | Provider default voice/language; input 16 kHz, output 24 kHz |
+| OpenAI live conversation (always on) | `OPENAI_API_KEY`, `OPENAI_REALTIME_MODEL` | `OPENAI_REALTIME_ENDPOINT`; page voice marin/cedar; input/output 24 kHz |
+| Gemini speech-to-speech (turn-based) | `GEMINI_API_KEY`, `GEMINI_LIVE_MODEL` (include models/ prefix) | Provider default voice/language; input 16 kHz, output 24 kHz |
Missing variables produce a visible error and keep the existing chat active.
Provider account/model/voice availability must be checked with your account.
See [provider contracts](../../docs/providers.md). The chained pipeline supports
-text and microphone messages with text history. Speech-to-speech accepts only
-committed microphone utterances, opens a fresh provider connection each turn,
-and has **no history replay**. The language control applies only to the remote
+text and microphone messages with text history. Gemini speech-to-speech accepts
+only committed microphone utterances, opens a fresh provider connection each
+turn, and has **no history replay**. OpenAI live conversation is described above. The language control applies only to the remote
chain; the OpenAI voice control only to OpenAI. Local voices use Kokoro's control.
The browser actually converts microphone samples to the selected rate using a
box filter; it rejects capture below that rate. This is basic speech conversion,
@@ -247,13 +302,14 @@ and on flush. Suspended contexts do not advance; queued buffers are not counted.
A token rejects acknowledgements from earlier turns. Stop/new input flushes
playback even after generation has finished. Cancellation conservatively keeps
only complete aligned chained speech chunks covered by acknowledgements;
-it can undercount by one reporting interval. Speech-to-speech deltas have no
-proven text/audio alignment; no heard-text history or native provider truncation
-is claimed. Replay players do not modify conversation history. First-text,
+it can undercount by one reporting interval. Gemini speech-to-speech deltas have
+no proven text/audio alignment; no heard-text history or native provider
+truncation is claimed. Replay players do not modify conversation history. First-text,
first-audio, total generation time and acknowledged playback are separate values;
they do not measure acoustic latency.
-Recording is off by default. Enable between turns to persist bounded JSON event
+Recording is off by default and not available in the always-on modes. In
+**Settings**, click **Save redacted transcripts** between turns to persist bounded JSON event
metadata with **all text replaced by `[REDACTED]`** and no audio. It deliberately
does not attempt selective PII detection. Controls list, download and delete the
current tab's artifacts. Disable deletes that tab's store. Bounds: 1,024 events,
@@ -275,8 +331,7 @@ server command, npm setup and client connection. Use
[`telephony-loopback.exs`](../telephony-loopback.exs) for the credential-free paced
telephony/Telnyx reordering exercise (`MIX_ENV=test mix run examples/telephony-loopback.exs`
from the repository root). These transports are separate runnable examples,
-not modes of this microphone chat. They arrive on the parent integration branch
-via PR #35. Navigation in the chat links to that branch's source/setup.
+not modes of this microphone chat, and the chat page does not link to them.
The [standalone network publisher](../network/README.md) runs actual encoded
PCMU/VP8 two-peer negotiation with `AUDIOFLOW_WEBRTC=1 mix run
@@ -307,8 +362,10 @@ CHAT_PROFILE=demo mix assets.build
```
The JS tests use a simulated AudioContext clock and microphone, not a browser
-speaker. With `AUDIOFLOW_MEDIA=1`, the duplex LiveView tests use a local
-WebSocket peer with the Moshi wire format, not the Moshi model.
+speaker. The OpenAI LiveView tests use a local WebSocket peer with the OpenAI
+Realtime event format, not OpenAI. With `AUDIOFLOW_MEDIA=1`, the Moshi LiveView
+tests use a local WebSocket peer with the Moshi wire format, not the Moshi
+model.
Implementation validation on Linux (synthetic/local fixtures only): 7 chat
ExUnit tests, 1 simulated AudioContext test, and 51 relevant core tests passed;
@@ -330,9 +387,9 @@ no breaking dependency upgrades were made as part of this feature.
### Provisional interruption / real browser pause
-The chat's **Pause / test interruption (10 s)** control requests a provisional
-interruption. **Resume false interruption** continues the same turn, worker,
-queued speech and speech checkpoints. **Confirm / Stop**, the 10-second candidate
+In the collapsed **Diagnostics** section of the turn-based modes, **Pause
+playback** requests a provisional interruption (10 s). **Resume** continues the
+same turn, worker, queued speech and speech checkpoints. **Confirm stop**, the 10-second candidate
deadline, the original turn timeout, or an endpoint failure cancels and flushes.
Resume must be acknowledged before the candidate deadline too. This is an
explicit manual test control, not an automatic microphone/VAD classifier.
diff --git a/examples/chat/assets/js/duplex.js b/examples/chat/assets/js/duplex.js
index c09425d..7a13ead 100644
--- a/examples/chat/assets/js/duplex.js
+++ b/examples/chat/assets/js/duplex.js
@@ -1,14 +1,21 @@
-// Full duplex conversation with a local Moshi model through AudioFlow.Duplex.
+// Always-on conversation through AudioFlow.Duplex (local Moshi or OpenAI).
//
-// The microphone stays open for the whole conversation. Its samples are
-// resampled continuously to 24 kHz and sent as 80 ms s16le chunks. Model audio
-// plays at the same time; microphone input never stops or flushes playback.
+// The microphone stays open from Start to Stop. Its samples are resampled
+// continuously to 24 kHz and sent as 80 ms s16le chunks. Model audio plays at
+// the same time; microphone input never stops playback.
+//
+// When the server reports user speech ("call_flush"), queued model audio is
+// stopped and the microphone stays open. The hook then reports how much of
+// the cut reply audio the browser rendered ("call_played"), and drops later
+// audio of that reply.
//
// Flow limits:
// - Before the server reports the model handshake, microphone input is dropped.
// - At most MAX_IN_FLIGHT chunks wait for a server acknowledgement.
// - At most MAX_PENDING chunks wait to be sent; the oldest is dropped first.
-// - Model audio more than MAX_PLAYBACK_AHEAD seconds ahead of the clock is dropped.
+// - Model audio more than data-playback-ahead seconds (default
+// MAX_PLAYBACK_AHEAD) ahead of the clock is dropped, and so is the rest of
+// that reply, so the rendered time maps to a prefix of the reply.
// - Each conversation has a server generation. Events of another generation
// are ignored.
@@ -94,9 +101,13 @@ export const Duplex = {
clearTimeout(call.startupTimer);
}
});
- this.handleEvent("call_play", ({ generation, pcm, rate }) => {
+ this.handleEvent("call_play", ({ generation, output, pcm, rate }) => {
+ const call = this.current(generation);
+ if (call) this.play(call, pcm, rate, output ?? null);
+ });
+ this.handleEvent("call_flush", ({ generation }) => {
const call = this.current(generation);
- if (call) this.play(call, pcm, rate);
+ if (call) this.flush(call);
});
this.handleEvent("call_stopped", ({ generation }) => {
const call = this.current(generation);
@@ -133,6 +144,11 @@ export const Duplex = {
sources: new Set(),
next: 0,
late: 0,
+ flushed: 0,
+ // Read at start: the server sets it per provider.
+ ahead: Number(this.el.dataset?.playbackAhead) || MAX_PLAYBACK_AHEAD,
+ output: null,
+ cut: null,
released: false,
};
this.call = call;
@@ -177,7 +193,7 @@ export const Duplex = {
track.onended = () => this.fail(call, new Error("Microphone disconnected"));
}
- this.draw("Connecting to Moshi…");
+ this.draw("Connecting…");
this.pushEvent("call_start", {}, (reply) => {
if (this.call !== call) {
// Stopped while the server started it.
@@ -232,16 +248,22 @@ export const Duplex = {
}
},
- play(call, pcm, rate) {
+ play(call, pcm, rate, output) {
+ if (output !== null && output === call.cut) return;
const bytes = fromBase64(pcm);
const samples = new Int16Array(bytes.buffer, 0, bytes.length >> 1);
if (samples.length === 0) return;
+ if (output !== null && call.output?.id !== output) {
+ call.output = { id: output, spans: [], rendered: 0, dropping: false };
+ }
+ const reply = output === null ? null : call.output;
const context = call.context;
const now = context.currentTime;
const start = Math.max(call.next, now + PLAYBACK_LEAD);
- if (start - now > MAX_PLAYBACK_AHEAD) {
+ if (reply?.dropping || start - now > call.ahead) {
call.late++;
+ if (reply) reply.dropping = true;
return;
}
@@ -256,6 +278,52 @@ export const Duplex = {
source.start(start);
call.sources.add(source);
call.next = start + buffer.duration;
+ if (reply) {
+ this.fold(call, reply);
+ reply.spans.push([start, call.next]);
+ }
+ },
+
+ // Audio-clock time that the listener has heard: output latency is
+ // subtracted, so progress never counts audio still in the output buffer.
+ heard(call) {
+ const context = call.context;
+ return context.currentTime - (context.outputLatency || context.baseLatency || 0);
+ },
+
+ // Moves fully heard spans into a sum, so the span list stays short.
+ fold(call, reply) {
+ const heard = this.heard(call);
+ reply.spans = reply.spans.filter(([start, end]) => {
+ if (end > heard) return true;
+ reply.rendered += end - start;
+ return false;
+ });
+ },
+
+ // Seconds of this reply that were heard.
+ rendered(call, reply) {
+ const heard = this.heard(call);
+ let sum = reply.rendered;
+ for (const [start, end] of reply.spans) sum += Math.max(0, Math.min(heard, end) - start);
+ return sum;
+ },
+
+ // User speech: stop queued model audio, keep the microphone, report progress.
+ flush(call) {
+ const reply = call.output;
+ const ms = reply ? Math.max(0, Math.floor(this.rendered(call, reply) * 1000)) : 0;
+ for (const source of call.sources) {
+ source.onended = null;
+ source.stop();
+ }
+ call.sources.clear();
+ call.next = 0;
+ call.flushed++;
+ if (!reply) return;
+ call.cut = reply.id;
+ call.output = null;
+ this.pushEvent("call_played", { generation: call.generation, output: reply.id, ms });
},
release(call) {
@@ -299,6 +367,7 @@ export const Duplex = {
const queued = Math.max(0, call.next - call.context.currentTime);
stats.textContent =
`Sent ${call.sent} · dropped ${call.dropped} input chunks · ` +
- `${Math.round(queued * 1000)} ms queued playback · ${call.late} late output chunks`;
+ `${Math.round(queued * 1000)} ms queued playback · ${call.late} late output chunks · ` +
+ `${call.flushed} interruptions`;
},
};
diff --git a/examples/chat/assets/test/duplex.test.js b/examples/chat/assets/test/duplex.test.js
index ac70614..6301dec 100644
--- a/examples/chat/assets/test/duplex.test.js
+++ b/examples/chat/assets/test/duplex.test.js
@@ -78,7 +78,7 @@ function grantMicrophone() {
return microphone;
}
-function mount() {
+function mount(dataset = {}) {
const handlers = {};
const pushes = [];
const listeners = {};
@@ -97,7 +97,7 @@ function mount() {
};
const hook = {
...Duplex,
- el: { parentElement: el },
+ el: { parentElement: el, dataset },
handleEvent(name, fn) {
handlers[name] = fn;
},
@@ -114,8 +114,8 @@ function mount() {
}
// Starts a conversation: click, microphone grant, server reply, model handshake.
-async function connect(generation = 1) {
- const view = mount();
+async function connect(generation = 1, dataset = {}) {
+ const view = mount(dataset);
grantMicrophone();
view.click("start");
await tick();
@@ -296,3 +296,53 @@ test("a microphone request that does not finish times out and releases a late gr
assert.ok(mic.track.stopped);
assert.equal(view.sent("call_start").length, 0);
});
+
+test("user speech flushes queued reply audio, reports heard time and keeps the microphone", async () => {
+ const view = await connect(5, { playbackAhead: "60" });
+ const [context] = contexts.slice(-1);
+ context.outputLatency = 0.02;
+ for (let i = 0; i < 3; i++) {
+ view.handlers.call_play({ generation: 5, output: "item_1", pcm: pcm(1_920), rate: 24_000 });
+ }
+ // Chunks at 0.04, 0.12 and 0.2 s. At 0.1 s minus 20 ms latency, 40 ms were heard.
+ context.currentTime = 0.1;
+ view.handlers.call_flush({ generation: 4 });
+ assert.equal(view.sent("call_played").length, 0);
+ view.handlers.call_flush({ generation: 5 });
+
+ assert.ok(context.sources.every((source) => source.stopped));
+ assert.deepEqual(view.sent("call_played").at(-1).payload, {
+ generation: 5,
+ output: "item_1",
+ ms: 40,
+ });
+ assert.ok(!microphone.track.stopped);
+ assert.ok(!microphone.node.disconnected);
+ speak(30);
+ assert.equal(view.sent("call_audio").length, 1);
+
+ // Late audio of the cut reply is dropped; the next reply plays at once.
+ view.handlers.call_play({ generation: 5, output: "item_1", pcm: pcm(1_920), rate: 24_000 });
+ assert.equal(context.sources.length, 3);
+ view.handlers.call_play({ generation: 5, output: "item_2", pcm: pcm(1_920), rate: 24_000 });
+ assert.equal(context.sources.length, 4);
+ assert.equal(Number(context.sources[3].at.toFixed(2)), 0.14);
+});
+
+test("reply audio past the playback limit drops the rest of that reply", async () => {
+ const view = await connect(6, { playbackAhead: "0.2" });
+ const [context] = contexts.slice(-1);
+ for (let i = 0; i < 4; i++) {
+ view.handlers.call_play({ generation: 6, output: "item_1", pcm: pcm(1_920), rate: 24_000 });
+ }
+ // Chunks start at 0.04, 0.12 and 0.2 s; the fourth would start past 0.2 s.
+ assert.equal(context.sources.length, 3);
+ // Room is free again, but the reply has a gap; its heard time must stay a prefix.
+ context.currentTime = 0.5;
+ view.handlers.call_play({ generation: 6, output: "item_1", pcm: pcm(1_920), rate: 24_000 });
+ assert.equal(context.sources.length, 3);
+ view.handlers.call_flush({ generation: 6 });
+ assert.equal(view.sent("call_played").at(-1).payload.ms, 240);
+ view.handlers.call_play({ generation: 6, output: "item_2", pcm: pcm(1_920), rate: 24_000 });
+ assert.equal(context.sources.length, 4);
+});
diff --git a/examples/chat/lib/chat/setup.ex b/examples/chat/lib/chat/setup.ex
index 5e6fd3b..f53f077 100644
--- a/examples/chat/lib/chat/setup.ex
+++ b/examples/chat/lib/chat/setup.ex
@@ -6,7 +6,7 @@ defmodule Chat.Setup do
{"demo", "Synthetic demo"},
{"local", "Local Apple MLX"},
{"remote", "Deepgram → Chat HTTP → TTS"},
- {"openai", "OpenAI speech-to-speech"},
+ {"openai", "OpenAI live conversation"},
{"gemini", "Gemini speech-to-speech"},
{"moshi", "Local Moshi full duplex"}
]
@@ -43,10 +43,14 @@ defmodule Chat.Setup do
def requirements(_), do: []
def rate(%{"mode" => mode}) when mode in ["openai", "moshi"], do: 24_000
def rate(_), do: 16_000
- def speech?(settings), do: settings["mode"] in ["openai", "gemini"]
+ @doc "Turn-based speech-to-speech: one recorded utterance per turn."
+ def speech?(settings), do: settings["mode"] == "gemini"
- @doc "Full duplex modes use `AudioFlow.Duplex` instead of a turn-based session."
- def duplex?(settings), do: settings["mode"] == "moshi"
+ @doc """
+ Always-on modes use `AudioFlow.Duplex` instead of a turn-based session: the
+ microphone stays open from Start to Stop.
+ """
+ def duplex?(settings), do: settings["mode"] in ["moshi", "openai"]
def options(s, env \\ &System.get_env/1) do
mode = s["mode"]
@@ -68,6 +72,9 @@ defmodule Chat.Setup do
mode == "moshi" ->
moshi(env.("AUDIOFLOW_MOSHI_ENDPOINT"))
+ mode == "openai" ->
+ openai(s, env)
+
true ->
{:ok,
build(s, env) ++ [timeout_ms: 120_000, max_events: 4096, max_input_bytes: 1_440_000]}
@@ -102,17 +109,42 @@ defmodule Chat.Setup do
defp moshi(endpoint) when endpoint in [nil, ""], do: moshi(@moshi_endpoint)
defp moshi(endpoint) do
- case URI.parse(endpoint) do
- %URI{scheme: scheme, host: host, userinfo: nil}
- when scheme in ["ws", "wss"] and host not in [nil, ""] ->
- {:ok, [duplex: {AudioFlow.Duplex.Moshi, [endpoint: endpoint]}]}
-
- _ ->
+ if websocket?(endpoint),
+ do: {:ok, [duplex: {AudioFlow.Duplex.Moshi, [endpoint: endpoint]}]},
+ else:
{:error,
"AUDIOFLOW_MOSHI_ENDPOINT must be a ws:// or wss:// URL without user information"}
+ end
+
+ # The optional endpoint (a proxy, for example) comes only from the server environment.
+ defp openai(s, env) do
+ options = [
+ model: env.("OPENAI_REALTIME_MODEL"),
+ api_key: key(env, "OPENAI_API_KEY"),
+ voice: s["voice"]
+ ]
+
+ case env.("OPENAI_REALTIME_ENDPOINT") do
+ endpoint when endpoint in [nil, ""] ->
+ {:ok, [duplex: {AudioFlow.Duplex.OpenAIRealtime, options}]}
+
+ endpoint ->
+ if websocket?(endpoint),
+ do: {:ok, [duplex: {AudioFlow.Duplex.OpenAIRealtime, options ++ [endpoint: endpoint]}]},
+ else:
+ {:error,
+ "OPENAI_REALTIME_ENDPOINT must be a ws:// or wss:// URL without user information"}
end
end
+ defp websocket?(endpoint) do
+ match?(
+ %URI{scheme: scheme, host: host, userinfo: nil}
+ when scheme in ["ws", "wss"] and host not in [nil, ""],
+ URI.parse(endpoint)
+ )
+ end
+
defp key(env, name), do: fn -> env.(name) end
defp build(%{"mode" => "demo"}, _), do: Adapters.Demo.options() ++ [history: true]
defp build(%{"mode" => "local"}, _), do: Chat.Stage.session_options()
@@ -160,17 +192,6 @@ defmodule Chat.Setup do
]
end
- defp build(%{"mode" => "openai"} = s, env),
- do: [
- speech_to_speech:
- {Adapters.OpenAIRealtime,
- [
- model: env.("OPENAI_REALTIME_MODEL"),
- api_key: key(env, "OPENAI_API_KEY"),
- voice: s["voice"]
- ]}
- ]
-
defp build(%{"mode" => "gemini"}, env),
do: [
speech_to_speech:
diff --git a/examples/chat/lib/chat_web/live/chat_live.ex b/examples/chat/lib/chat_web/live/chat_live.ex
index 24c7d45..964e4fe 100644
--- a/examples/chat/lib/chat_web/live/chat_live.ex
+++ b/examples/chat/lib/chat_web/live/chat_live.ex
@@ -9,10 +9,14 @@ defmodule ChatWeb.ChatLive do
one session turn. Reply audio is pushed to the browser as it arrives, and the
complete reply is kept as a WAV file for replay.
- The full duplex mode (local Moshi) has no turns. It uses `AudioFlow.Duplex`:
- the browser sends 80 ms chunks of 24 kHz PCM continuously, and the model
- audio and text come back at the same time. Each conversation has a
- generation number; events from an earlier generation are ignored.
+ The always-on modes (local Moshi and OpenAI live conversation) use
+ `AudioFlow.Duplex`. From Start to Stop the browser sends 80 ms chunks of
+ 24 kHz PCM continuously, and the model audio and text come back at the same
+ time. Moshi has no turns. OpenAI detects speech itself: when the user starts
+ to speak, the browser flushes queued reply audio (the microphone stays open)
+ and reports how much of the reply played, so the provider history keeps only
+ that part. Each conversation has a generation number; events from an earlier
+ generation are ignored.
"""
use Phoenix.LiveView
@@ -40,6 +44,10 @@ defmodule ChatWeb.ChatLive do
@call_segment_ms 1_500
@call_max_messages 200
@call_max_message_bytes 4_000
+ # User utterances that wait for their transcript.
+ @call_max_pending 16
+ # Seconds of model audio that the browser queues ahead of playback.
+ @playback_ahead %{"moshi" => 1, "openai" => 60}
@impl true
def mount(_params, _session, socket) do
@@ -192,8 +200,11 @@ defmodule ChatWeb.ChatLive do
true ->
# The adapter and endpoint come from the server settings, not from params.
case Setup.options(socket.assigns.settings) do
- {:ok, [duplex: adapter]} -> start_call(socket, adapter)
- {:error, message} -> {:reply, %{ok: false, error: message}, call_error(socket, message)}
+ {:ok, [duplex: adapter]} ->
+ start_call(socket, adapter, socket.assigns.settings["mode"] == "openai")
+
+ {:error, message} ->
+ {:reply, %{ok: false, error: message}, call_error(socket, message)}
end
end
end
@@ -224,6 +235,20 @@ defmodule ChatWeb.ChatLive do
end
end
+ # Playback progress of the reply audio that a flush cut. The adapter caps it
+ # to the received audio and ignores reports for any other reply.
+ def handle_event(
+ "call_played",
+ %{"generation" => generation, "output" => output, "ms" => ms},
+ %{assigns: %{call: %{generation: generation, ready: true} = call}} = socket
+ )
+ when is_binary(output) and byte_size(output) <= 256 and is_integer(ms) and ms >= 0 do
+ _ = Duplex.control(call.pid, {:played, output, ms})
+ {:noreply, socket}
+ end
+
+ def handle_event("call_played", _params, socket), do: {:noreply, socket}
+
def handle_event("call_failed", %{"message" => message}, socket) when is_binary(message),
do: {:noreply, call_error(socket, "Microphone error: " <> String.slice(message, 0, 200))}
@@ -354,7 +379,9 @@ defmodule ChatWeb.ChatLive do
end
end
- defp start_call(socket, adapter) do
+ # `turns`: the model marks user speech and replies (OpenAI). Without turns
+ # (Moshi), a pause in the model text starts a new message.
+ defp start_call(socket, adapter, turns) do
generation = socket.assigns.generation + 1
socket = assign(socket, generation: generation)
@@ -365,8 +392,11 @@ defmodule ChatWeb.ChatLive do
monitor: Process.monitor(pid),
generation: generation,
ready: false,
+ turns: turns,
reply_id: nil,
- text_at: nil
+ text_at: nil,
+ output: nil,
+ users: []
}
{:reply, %{ok: true, generation: generation},
@@ -385,6 +415,12 @@ defmodule ChatWeb.ChatLive do
error in ArgumentError -> {:error, Exception.message(error)}
end
+ defp call_event(%{assigns: %{call: %{turns: true} = call}} = socket, :ready) do
+ socket
+ |> assign(call: %{call | ready: true}, call_status: "live")
+ |> push_event("call_ready", %{generation: call.generation})
+ end
+
defp call_event(socket, :ready) do
%{call: call} = socket.assigns
socket = add_message(socket, "assistant", "", pending: true, live: true)
@@ -398,8 +434,11 @@ defmodule ChatWeb.ChatLive do
end
defp call_event(socket, {:audio, %Audio{data: data, sample_rate: rate}}) do
+ %{call: call} = socket.assigns
+
push_event(socket, "call_play", %{
- generation: socket.assigns.call.generation,
+ generation: call.generation,
+ output: call.output,
pcm: Base.encode64(data),
rate: rate
})
@@ -407,12 +446,81 @@ defmodule ChatWeb.ChatLive do
defp call_event(socket, {:text, text}), do: call_text(socket, text)
+ # The user starts to speak: queued reply audio is obsolete. The browser
+ # flushes it and keeps the microphone open.
+ defp call_event(socket, {:speech_started, item}) do
+ %{call: call} = socket.assigns
+ socket = add_message(socket, "user", "", pending: true, live: true)
+
+ users =
+ Enum.take(call.users ++ [{item, List.last(socket.assigns.messages).id}], -@call_max_pending)
+
+ socket
+ |> assign(call: %{call | output: nil, users: users})
+ |> push_event("call_flush", %{generation: call.generation})
+ |> trim_messages()
+ end
+
+ defp call_event(socket, {:transcript, item, text}) do
+ %{call: call} = socket.assigns
+
+ case List.keytake(call.users, item, 0) do
+ {{_, id}, users} -> socket |> assign(call: %{call | users: users}) |> transcript(id, text)
+ nil -> socket
+ end
+ end
+
+ defp call_event(socket, {:response, _id, :created}) do
+ %{call: call} = socket.assigns
+ socket = if call.reply_id, do: settle(socket, call.reply_id), else: socket
+ socket = add_message(socket, "assistant", "", pending: true)
+
+ assign(socket, call: %{call | reply_id: List.last(socket.assigns.messages).id})
+ |> trim_messages()
+ end
+
+ defp call_event(%{assigns: %{call: %{reply_id: nil}}} = socket, {:response, _id, _status}),
+ do: socket
+
+ defp call_event(socket, {:response, _id, status}) do
+ %{call: call} = socket.assigns
+
+ socket
+ |> update_message(call.reply_id, &%{&1 | note: reply_note(status, &1.text)})
+ |> settle(call.reply_id)
+ |> assign(call: %{call | reply_id: nil})
+ end
+
+ defp call_event(socket, {:output, item}),
+ do: assign(socket, call: %{socket.assigns.call | output: item})
+
defp call_event(socket, {:error, reason}),
do: call_error(socket, "Conversation error: " <> describe(reason))
defp call_event(socket, :closed), do: stop_call(socket, "closed")
defp call_event(socket, _event), do: socket
+ defp transcript(socket, id, :failed),
+ do: update_message(socket, id, &%{&1 | pending: false, live: false, note: "Not transcribed."})
+
+ defp transcript(socket, id, text) do
+ case String.trim(text) do
+ "" -> remove_message(socket, id)
+ text -> update_message(socket, id, &%{&1 | text: text, pending: false, live: false})
+ end
+ end
+
+ # A reply cancelled before any text gets no note, so `settle/2` removes it.
+ defp reply_note(:cancelled, ""), do: nil
+ defp reply_note(:cancelled, _text), do: "Interrupted."
+ defp reply_note(:incomplete, _text), do: "Reply incomplete."
+ defp reply_note(:failed, _text), do: "Reply failed."
+ defp reply_note(:completed, _text), do: nil
+
+ defp call_text(%{assigns: %{call: %{turns: true, reply_id: id}}} = socket, text)
+ when id != nil,
+ do: update_message(socket, id, &%{&1 | text: &1.text <> text, pending: false})
+
# Moshi does not mark turns. A pause in the model text starts a new message,
# and the conversation keeps only the latest messages.
defp call_text(socket, text) do
@@ -437,14 +545,17 @@ defmodule ChatWeb.ChatLive do
text = if message.text == "", do: String.trim_leading(text), else: text
%{message | text: message.text <> text, pending: false, live: false}
end)
- |> then(&assign(&1, messages: Enum.take(&1.assigns.messages, -@call_max_messages)))
+ |> trim_messages()
|> assign(call: %{call | text_at: now})
end
- # A message without model text is removed; otherwise it stops waiting.
+ defp trim_messages(socket),
+ do: assign(socket, messages: Enum.take(socket.assigns.messages, -@call_max_messages))
+
+ # A message without text or note is removed; otherwise it stops waiting.
defp settle(socket, id) do
case Enum.find(socket.assigns.messages, &(&1.id == id)) do
- %{text: ""} -> remove_message(socket, id)
+ %{text: "", note: nil} -> remove_message(socket, id)
%{} -> update_message(socket, id, &%{&1 | pending: false, live: false})
nil -> socket
end
@@ -469,14 +580,17 @@ defmodule ChatWeb.ChatLive do
:exit, _ -> :ok
end
- socket
- |> settle(call.reply_id)
+ call.users
+ |> Enum.reduce(settle(socket, call.reply_id), fn {_, id}, socket ->
+ settle(socket, id)
+ end)
|> push_event("call_stopped", %{generation: call.generation})
end
assign(socket, call: nil, call_status: status, call_error: error)
end
+ defp describe({:remote_error, code}) when is_binary(code), do: "provider error " <> code
defp describe(reason) when is_binary(reason), do: reason
defp describe(reason) when is_atom(reason), do: Atom.to_string(reason)
defp describe(reason), do: inspect(reason)
@@ -633,16 +747,9 @@ defmodule ChatWeb.ChatLive do
)
}
- note =
- if metrics.first_text_us,
- do: "First text #{ms(metrics.first_text_us)}, first audio #{ms(metrics.first_audio_us)}",
- else: "No speech was recognized."
-
finish(socket,
audio: audio,
- note:
- note <>
- " · Transcript #{ms(metrics[:first_transcript_us])} · Total #{ms(metrics[:duration_us])} · #{metrics[:events]} events · played #{socket.assigns.played_ms} ms"
+ note: if(metrics.first_text_us, do: nil, else: "No speech was recognized.")
)
end
@@ -725,8 +832,7 @@ defmodule ChatWeb.ChatLive do
socket =
if socket.assigns.turn,
- do:
- finish(socket, note: "Stopped; history keeps only acknowledged complete speech chunks."),
+ do: finish(socket, note: "Stopped."),
else: socket
socket |> assign(candidate: nil, control: nil, paused: false) |> push_event("flush", %{})
@@ -778,9 +884,6 @@ defmodule ChatWeb.ChatLive do
end
end
- defp ms(nil), do: "none"
- defp ms(us), do: "#{div(us, 1000)} ms"
-
defp system_memory_gb do
case System.cmd("sysctl", ["-n", "hw.memsize"], stderr_to_stdout: true) do
{bytes, 0} -> String.to_integer(String.trim(bytes)) / 1_073_741_824
@@ -803,8 +906,8 @@ defmodule ChatWeb.ChatLive do
else: "The largest combinations may not fit in memory."
end
- defp call_label("connecting"), do: "Connecting to Moshi…"
- defp call_label("live"), do: "Live: microphone and playback on"
+ defp call_label("connecting"), do: "Connecting…"
+ defp call_label("live"), do: "Live · microphone on"
defp call_label("closed"), do: "Conversation ended"
defp call_label("error"), do: "Stopped by an error"
defp call_label(_), do: "Not connected"
@@ -822,98 +925,73 @@ defmodule ChatWeb.ChatLive do
stt_models: Catalog.stt(),
llm_models: Catalog.llm(),
voices: Catalog.voices(),
- duplex: Setup.duplex?(assigns.settings)
+ duplex: Setup.duplex?(assigns.settings),
+ playback_ahead: @playback_ahead
)
~H"""
-
-
AudioFlow chat
-
- {if @duplex,
- do: "Start a conversation and talk. You and Moshi can speak at the same time.",
- else: "Type a message, or record one with the microphone."}
-
- AudioFlow sends your microphone audio to local Moshi and plays its reply at the same time. Moshi speaks English. The text below is its speech, not a transcript of your voice.
-
-
- Microphone only; fresh provider connection each turn, no history replay. No text/audio alignment or native history truncation is claimed. Language and Gemini voice use provider defaults.
-
-
- Remote chain requires DEEPGRAM_API_KEY, CHAT_HTTP_ENDPOINT, CHAT_HTTP_MODEL and ELEVENLABS_API_KEY / ELEVENLABS_VOICE_ID or CARTESIA_API_KEY / CARTESIA_VOICE_ID. Optional CHAT_HTTP_API_KEY. Speech-to-speech requires OPENAI_API_KEY / OPENAI_REALTIME_MODEL or GEMINI_API_KEY / GEMINI_LIVE_MODEL. Configure these on the server.
-
- Opt-in text-only JSON: all content replaced with [REDACTED], no PCM. Limit 20 turns, 1 hour, 128 KB buffered per turn. Deleted on disconnect; retention checked every minute and on access.
-
- Standalone encoded WebRTC needs AUDIOFLOW_WEBRTC=1 and OpenSSL; it negotiates local peers, not a Session PCM bridge. LiveAvatar LITE requires LIVEAVATAR_API_KEY, LIVEAVATAR_AVATAR_ID and finite 24 kHz PCM; no provider verification is claimed.
-
-
+
+
{@setup_error}
-
-
- ≈ {gb(@models.memory_gb)} GB of model weights{if @system_memory_gb,
- do: " · #{gb(@system_memory_gb)} GB memory"}
-
- {fit_text(@system_memory_gb)}
-
-
+
+
Start conversation
@@ -977,15 +1054,41 @@ defmodule ChatWeb.ChatLive do
{call_label(@call_status)}
-
-
- Use headphones. Clear text does not reset Moshi. Its context stays until the model service restarts.
-
{@call_error}
+
+ Diagnostics
+
+
+
+ Settings
+
+
+ ≈ {gb(@models.memory_gb)} GB of model weights{if @system_memory_gb,
+ do: " · #{gb(@system_memory_gb)} GB memory"}. {fit_text(@system_memory_gb)}
+
+
+
+ {if @capture, do: "Delete saved transcripts", else: "Save redacted transcripts"}
+
+
+ Text only, with all words replaced by [REDACTED]. Deleted when you leave.
+
+
+
+ {id}
+
+ Download
+
+
+ Delete
+
+
+
+
No messages yet.
@@ -1018,12 +1121,19 @@ defmodule ChatWeb.ChatLive do