ARCHITECTURE · VOICE · OPENAI · 5 MIN READ
A realtime voice agent with OpenAI
Connect browser audio to a realtime session while keeping credentials and business actions on the server.
Jump to a section 12 sections
EXAMPLE USE CASE
Ask a returns-policy question through your microphone
A customer wants a spoken answer without typing, and the browser must not receive the permanent provider key.
- Input
- Microphone audio: “Can I return an item after twenty days?” A fixed demo policy allows returns within 30 days.
- Expected output
- A spoken answer using the supplied policy, with a browser session that can be stopped cleanly.
- Success check: Audio flows both ways; the server keeps the permanent key; Stop releases the microphone and peer connection.
- Try a failure: Deny microphone permission or stop during a reply. The UI must recover without leaving audio capture active.
Example scope: A real WebRTC FAQ session. It has fixed policy instructions and no order-changing tools; tool authorization and production authentication are later layers.
The user permits capture; the browser adds the microphone track to the peer connection.
audio inTo 03 · Realtime sessionThe backend signs the session request with the permanent provider key and returns the SDP answer.
signalingTo 03 · Realtime sessionThe configured model receives audio and the fixed demo policy; this FAQ lab exposes no business-action tools.
audio outTo 05 · SpeakerThe session instruction supplies the exact demonstration facts and requires uncertainty outside those facts.
The ontrack handler attaches the provider’s audio stream to the browser audio element.
Result or stopping pointStop closes the peer connection and every captured microphone track.
releaseBack to 01 · MicrophonecloseBack to 05 · Speaker
The configured model receives audio and the fixed demo policy; this FAQ lab exposes no business-action tools.
Components for this use case
- The browser owns media permission and playback. A backend authenticates session creation and retains the permanent key. OpenAI Realtime handles the media session.
- Add business operations behind a server-side tool policy only when the use case requires actions; test them separately from audio transport.
Establish the session
- The browser creates a WebRTC offer and posts its SDP to the local /session backend.
- The backend calls the provider’s realtime/calls endpoint using its permanent server-held key and returns the SDP answer. The browser applies that answer to the peer connection.
- This example uses backend-mediated signaling, rather than returning an ephemeral key to the browser.
- The loopback Origin check is a demo restriction. Add authenticated session creation and resource limits before exposing a production backend.
Handle an action during a conversation
- The model may request an appointment lookup or order status.
- Execute business logic in an authorized backend service.
- Return a compact result to the session so the agent can answer while preserving the conversational flow.
Design interruption and recovery
- Support user interruption, cancelled tool requests, reconnects, and expired session credentials.
- Separate the audio transport from business workflows so a dropped call does not duplicate a write.
- Use an idempotency key for committed actions.
Measure the experience
- Measure time to first audio, interruption recovery, tool latency, and task completion.
- Decide what audio or transcripts you retain and make the retention policy explicit.
Set up the lab
- Node.js 22+ and an OpenAI API key in the server environment. Requests may incur API usage charges.
- Choose an enabled Realtime model. This local transport lab establishes audio; add authenticated tools separately.
- Use localhost for the microphone permission prompt. Never put the permanent API key in browser JavaScript.
mkdir -p public
npm init -y
npm install express
export OPENAI_API_KEY="YOUR_SERVER_KEY"
export OPENAI_REALTIME_MODEL="YOUR_ENABLED_REALTIME_MODEL"Implement the example
Save as server.mjs
import express from 'express';
const app = express();
app.use(express.text({type:'application/sdp', limit:'64kb'}));
app.use(express.static('public'));
app.post('/session', async (req,res) => {
if (req.get('origin') !== 'http://localhost:3000') return res.sendStatus(403);
try {
const data = new FormData();
data.set('sdp', req.body);
data.set('session', JSON.stringify({type:'realtime', model:process.env.OPENAI_REALTIME_MODEL, instructions:"You are a concise voice FAQ assistant. Demo policy: returns are accepted within 30 days. Use only this policy; do not invent order statuses or dates. Ask a clarification when the request is outside it."}));
const upstream = await fetch('https://api.openai.com/v1/realtime/calls', {
method:'POST', body:data,
headers:{Authorization:'Bearer '+process.env.OPENAI_API_KEY},
signal:AbortSignal.timeout(15000)
});
if (!upstream.ok) { console.error('Session status',upstream.status); return res.sendStatus(502); }
res.type('application/sdp').set('Cache-Control','no-store').send(await upstream.text());
} catch { res.sendStatus(502); }
});
app.listen(3000,'127.0.0.1',()=>console.log('Open http://localhost:3000'));Save as public/index.html
<!doctype html>
<html lang="en"><meta charset="utf-8"><title>Local voice transport lab</title>
<button id="start">Start microphone</button><button id="stop" disabled>Stop</button>
<p id="status">Disconnected</p><audio id="audio" autoplay controls></audio>
<script type="module">
let pc, stream;
const status=document.querySelector('#status');
const stop=()=>{ stream?.getTracks().forEach(t=>t.stop()); pc?.close();
document.querySelector('#stop').disabled=true; document.querySelector('#start').disabled=false;
status.textContent='Disconnected'; };
document.querySelector('#stop').onclick=stop;
document.querySelector('#start').onclick=async()=>{
document.querySelector('#start').disabled=true;
try {
stream=await navigator.mediaDevices.getUserMedia({audio:true});
pc=new RTCPeerConnection();
pc.ontrack=e=>{document.querySelector('#audio').srcObject=e.streams[0];};
pc.onconnectionstatechange=()=>{status.textContent=pc.connectionState;};
pc.addTrack(stream.getAudioTracks()[0],stream);
const channel=pc.createDataChannel('events');
channel.onmessage=e=>{const event=JSON.parse(e.data); if(event.type==='error')status.textContent='Provider error';};
await pc.setLocalDescription(await pc.createOffer());
const response=await fetch('/session',{method:'POST',headers:{'Content-Type':'application/sdp'},body:pc.localDescription.sdp});
if(!response.ok)throw Error('Session failed');
await pc.setRemoteDescription({type:'answer',sdp:await response.text()});
document.querySelector('#stop').disabled=false;
} catch(error){stop();status.textContent=error.message;}
};
window.addEventListener('pagehide',stop);
</script></html>Run and verify
mkdir -p public
# Save the HTML file inside public/ before starting.
node server.mjs- Open http://localhost:3000 and start the microphone. Ask: Can I return an item after twenty days?
- The spoken answer uses the supplied 30-day policy. A question about a specific order must not produce an invented status.
- Stop releases media tracks and the peer connection. The browser receives an SDP answer; the permanent API key stays on the backend.
Troubleshooting and failure tests
- A 502 means the server could not establish the provider session. Inspect the upstream status without logging credentials or raw audio.
- No audio: check the browser permission, autoplay control, microphone device and network WebRTC support.
Before production
- Authenticate and rate-limit session creation, allow only approved models, and enforce usage and duration limits.
- Route business tool execution through an authorized server; confirm consequential operations using the exact spoken proposal.
- Handle interruption, reconnection, transcripts, accessibility, recording consent and explicit retention policies.