This guide was prepared with AI assistance using the linked documentation. Code examples are illustrative; verify them against your environment and current API documentation before use.
Who this is for: developers adding a conversational voice interface to a web application. You should be comfortable with JavaScript, HTTP, and a small Node.js server. You do not need prior WebRTC experience.
What you will build: a browser page that asks for microphone access when the user starts a session, exchanges connection information through your server, plays the agent’s audio, and lets the user end the call. Then you will turn that prototype into a plan for testing, privacy, authorization, and operational reliability.
Before you begin: you need an OpenAI API key with access to a supported Realtime model, a recent Node.js runtime, and a browser with a working microphone and speaker. API usage can incur charges. Check the current model availability, limits, and pricing for your account before opening the endpoint to others. The browser example below is a learning prototype, not an authenticated public service.
Voice feels easy when it works: someone asks a question and hears a useful reply. Most of the engineering is in the gaps between those moments. What if the person pauses mid-sentence? What if the browser denies microphone permission? What happens when a booking tool says a slot is available but another user claims it before confirmation? A responsive demo needs answers to those questions before it becomes a dependable product.
This guide uses the Realtime API with WebRTC because the browser can send microphone audio and receive generated speech during an interactive session. We will use the documented unified connection: the browser sends a WebRTC offer to your server, the server creates the call with a standard API key, and the browser applies the answer. The standard key stays on your server. OpenAI also documents a client-secret flow, which we compare later.
The code is intentionally small enough to inspect. It has not been tested here against your account or browser; provider APIs and model availability change, so compare the request shape with the linked documentation before adapting it. Follow the testing section on your own environment, including failures and shutdown, before relying on it.
The short version
A browser voice agent needs five pieces:
- A deliberate user action that requests microphone access.
- A WebRTC peer connection that sends the microphone track and plays a remote audio track.
- A server endpoint that authenticates a Realtime call without exposing the standard API key to the browser.
- A data channel for connection events and, when needed, session configuration.
- A clear stop action that releases microphone tracks and closes the connection.
The smallest successful result is a conversation you can start and stop. A production result additionally needs authentication, abuse controls, accessible feedback, privacy decisions, reliable business tools, and measurements based on actual user tasks.
First, choose the voice architecture
Before writing a connection handler, decide whether your application needs a conversational voice model at all. A support assistant that listens to an open-ended question and responds aloud has different needs from a recorded meeting that needs captions. Start with the user’s task and what the application must know at each step.
| Approach | Useful when | Trade-off to investigate |
|---|---|---|
| Realtime speech-to-speech | A user speaks to an agent that can respond and use tools during a session. | Test interruptions, model behavior, and tool boundaries in the actual workflow. |
| Chained speech pipeline | You need to inspect or transform intermediate text between transcription, reasoning, and speech. | Separate stages give control but add integration work and potentially more latency. |
| Full-duplex voice with a delegated backend | Conversation and backend reasoning need separate responsibilities. | Review how delegation, backend ownership, and cost fit your product. |
| Realtime transcription | The product needs a live text representation of speech. | Partial text can change, and final results may arrive after other events. |
The provider’s voice architecture guide describes these choices. For a browser app, the Realtime getting-started guide recommends WebRTC for client connections; server-side integrations can use WebSockets. A telephone integration has different call-control and security concerns, so do not treat a browser demo as a complete phone system.
For the example, imagine a voice assistant that answers questions about a fictional coworking space. It can explain opening hours from a short instruction. It cannot charge a card, access a member account, or create a reservation. That narrow scope makes it easier to tell whether the audio path works before introducing real data and side effects.
Understand the connection before copying code
The browser does not put your server’s standard API key in JavaScript. Instead, it asks for an audio track and creates a WebRTC offer: a description of the media connection it wants to establish. The browser sends that offer to your own endpoint. Your server combines the offer with session settings and posts a multipart request to the Realtime calls endpoint. It returns the resulting answer to the browser, which completes the peer connection.
Loading diagram…
The offer and answer contain session descriptions, not your application’s user authorization. The connection does not make a caller entitled to access a customer record. It only establishes a media session. That distinction matters when you later attach tools.
The data channel carries structured events alongside audio. It can report that a session has been created or updated, and it can carry other supported client and server events. Your interface can use those messages to update its state, but avoid dumping complete event payloads into a shared browser console: events may contain conversation content or identifiers.
This flow follows the provider’s WebRTC connection guide. That documentation is the reference for supported configuration fields and event names. The Realtime API’s older beta session endpoint has been deprecated; a tutorial that relies on it or requires the old beta header may no longer reflect the current GA flow.
Prepare a minimal local project
Create a new directory outside a public document root. You will place a server file and a single HTML file in it. The server will read an API key from an environment variable at runtime. Never paste the key into the HTML file, commit it to source control, or print it in a public support request.
For a fresh Node project, install Express:
mkdir browser-voice-demo
cd browser-voice-demo
npm init -y
npm install expressUse a supported Node release with built-in fetch, FormData, and Blob. Set OPENAI_API_KEY in your shell or use your team’s approved secret management method. The exact command depends on your shell; avoid commands that save a secret permanently to a shared history or file. The example below names files server.mjs and public/index.html.
Microphone access requires a secure context in supported browsers. Localhost is commonly treated as a potentially trustworthy development origin, while a deployed site should use HTTPS. See MDN’s getUserMedia() documentation and test the actual target browser. An HTTPS page embedded in another site can also be affected by browser permissions and embedding policy.
Create the server endpoint
This server accepts an SDP offer, forwards it to the Realtime calls endpoint with a session configuration, and returns the answer. The use case is deliberately restricted: the assistant explains a fictional space and avoids making reservations. Substitute instructions for your own scenario after the connection works.
// server.mjs — local learning example
import express from "express";
const app = express();
const port = 3000;
app.use(express.static("public"));
app.use(express.text({ type: "application/sdp", limit: "64kb" }));
app.post("/session", async (req, res) => {
if (!process.env.OPENAI_API_KEY) {
return res.status(500).send("Server is missing its API key");
}
if (typeof req.body !== "string" || !req.body.trim()) {
return res.status(400).send("An SDP offer is required");
}
const session = {
type: "realtime",
model: "gpt-realtime-2.1",
instructions:
"You are a concise voice guide for a fictional coworking space. " +
"Explain that the space opens weekdays from 9 to 5. " +
"Do not claim to book anything or access real accounts.",
audio: { output: { voice: "marin" } },
};
const body = new FormData();
body.set("sdp", req.body);
body.set("session", JSON.stringify(session));
try {
const upstream = await fetch("https://api.openai.com/v1/realtime/calls", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
body,
signal: AbortSignal.timeout(20_000),
});
const answer = await upstream.text();
if (!upstream.ok) {
// Avoid forwarding an upstream error body to an untrusted client.
return res.status(502).send("Could not create a voice session");
}
res.set("Cache-Control", "no-store");
res.type("application/sdp").send(answer);
} catch {
res.status(502).send("Voice service unavailable; try again");
}
});
app.listen(port, "127.0.0.1", () => {
console.log(`Demo available at http://localhost:${port}`);
});Run node server.mjs after setting the environment variable. The model and voice are examples from the current connection documentation, not guarantees that every account has access. If the server responds with an upstream failure, check account access and the current model documentation; do not paste credentials into issue trackers when asking for help.
The local example deliberately binds to the loopback address and omits a public user system. For a deployed app, add authentication and authorization before creating a session, enforce request and concurrent-session limits outside a single server process, validate the request origin as appropriate for your authentication scheme, set timeouts, and make upstream errors observable without leaking secrets. CSRF defenses matter when a browser can send a credentialed request. Merely changing 127.0.0.1 to a public bind address does not add any of those protections.
Protect session creation even if the assistant performs no business action. A visitor who can create sessions can consume provider resources. Decide which users are entitled to start a session, how many concurrent sessions they can open, and what your app does when a limit is reached. A reverse proxy limit may reduce abuse, but it is not a replacement for user-level authorization or a shared limiter across application instances.
Connect the browser and play audio
Create public/index.html. This sample handles a basic start-and-stop lifecycle. It requests the microphone after the user clicks Start; if anything fails, it closes the peer connection and stops the local tracks it acquired.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voice session demo</title>
</head>
<body>
<main>
<h1>Talk to the demo guide</h1>
<p>This demo sends microphone audio to a voice service while connected.</p>
<button id="start">Start voice session</button>
<button id="stop" disabled>End session</button>
<p id="status" role="status" aria-live="polite">Not connected</p>
<audio id="remote" autoplay controls></audio>
</main>
<script type="module" src="/client.js"></script>
</body>
</html>Create public/client.js:
const start = document.querySelector("#start");
const stop = document.querySelector("#stop");
const status = document.querySelector("#status");
const remote = document.querySelector("#remote");
let peer;
let microphone;
let channel;
let starting = false;
function endSession(message = "Session ended") {
channel?.close();
peer?.close();
microphone?.getTracks().forEach((track) => track.stop());
remote.srcObject = null;
channel = undefined;
peer = undefined;
microphone = undefined;
starting = false;
start.disabled = false;
stop.disabled = true;
status.textContent = message;
}
start.addEventListener("click", async () => {
if (starting || peer) return;
starting = true;
start.disabled = true;
status.textContent = "Requesting microphone permission…";
try {
microphone = await navigator.mediaDevices.getUserMedia({ audio: true });
peer = new RTCPeerConnection();
peer.ontrack = (event) => {
remote.srcObject = event.streams[0];
remote.play().catch(() => {
status.textContent = "Use the audio control to enable playback.";
});
};
microphone.getTracks().forEach((track) => peer.addTrack(track, microphone));
channel = peer.createDataChannel("oai-events");
channel.onopen = () => {
status.textContent = "Connected. Speak when you are ready.";
};
peer.onconnectionstatechange = () => {
if (["failed", "closed"].includes(peer?.connectionState)) {
endSession("Connection ended. You can start again.");
}
};
status.textContent = "Connecting…";
const offer = await peer.createOffer();
await peer.setLocalDescription(offer);
const response = await fetch("/session", {
method: "POST",
headers: { "Content-Type": "application/sdp" },
body: offer.sdp,
signal: AbortSignal.timeout(25_000),
});
if (!response.ok) throw new Error("Session request failed");
await peer.setRemoteDescription({ type: "answer", sdp: await response.text() });
starting = false;
stop.disabled = false;
} catch (error) {
const message = error?.name === "NotAllowedError"
? "Microphone access was denied. Check browser permissions."
: "Could not start the session. Check your connection and try again.";
endSession(message);
}
});
stop.addEventListener("click", () => endSession());Open the local page, select Start, allow microphone access, and ask what time the fictional space opens. You should hear an answer if your account, browser, audio devices, and network support the flow. Press End and check the browser’s microphone indicator. The sample exposes the browser audio controls so a user can attempt playback if autoplay is blocked.
The prototype still has limitations. A browser permission prompt can remain unanswered, and network conditions can change while the session is starting. For production, use a connection-generation identifier or cancellation controller so a late permission or network result cannot resurrect a session after the user has navigated away. Expose a Cancel action while starting. Handle disconnected with a visible recovery state and a bounded timeout rather than treating every transient network change as a final failure. Test those races rather than assuming a successful happy path covers them.
Standard API key versus temporary client secret
The unified flow above has the browser send its offer to your server. Your server then authenticates the call to OpenAI. Another documented option is for the server to create a short-lived client secret through /v1/realtime/client_secrets; the browser uses that secret to send its offer directly to the Realtime calls endpoint. Both designs keep the standard API key server-side.
The choice changes what crosses your server and where you apply controls. A temporary secret is still a credential: do not log it, embed it in analytics URLs, cache it in a public CDN, or grant it to an unauthenticated client without an intentional abuse policy. Fetch it only when needed and return it with Cache-Control: no-store. A short lifetime narrows exposure but does not replace authentication, rate limits, or account monitoring.
The client-secret endpoint can attach session configuration; the API reference also explains that configuration may be overridden by the client connection. Therefore, do not treat a prompt or a browser-provided session setting as your security boundary. Authorization for customer data and business actions belongs in services under your control.
The current Realtime getting-started guide documents the GA endpoint and migration from beta. If an older article uses /v1/realtime/sessions, check whether it has been deprecated before copying the sample. Similarly, validate event names and session properties against the model and endpoint you actually use. Realtime interfaces evolve, and a confidently copied snippet can fail for reasons unrelated to WebRTC.
Design turn taking around actual conversations
An agent must decide when a person has finished speaking. Voice activity detection, often shortened to VAD, estimates the boundaries of speech. In a quiet room, a silence-based rule may work well. In a busy office, keyboard noise or a short hesitation can cause premature boundaries. A person speaking a second language might pause longer while searching for a word. Neither setting should be treated as universally correct.
OpenAI documents server_vad, which segments audio around silence, and semantic_vad, which uses the content of an utterance to estimate whether the speaker has finished. Where supported, a session.update event can configure session.audio.input.turn_detection. Check the VAD guide for current fields and model support.
The following event illustrates the shape for semantic turn detection. Send it through an open data channel only after verifying that the chosen model supports it:
channel.send(JSON.stringify({
type: "session.update",
session: {
type: "realtime",
audio: {
input: {
turn_detection: {
type: "semantic_vad",
eagerness: "low",
create_response: true,
interrupt_response: true,
},
},
},
},
}));This is a configuration example, not a tested universal setting. Lower eagerness may give someone more time to finish; it can also increase the wait before a response. Higher eagerness can make turn boundaries faster but may split a thought too early. Measure the trade-off with participants and scenarios representative of your users.
Consider offering push-to-talk where a deliberate control is more appropriate than automatic detection. It can help in noisy environments or when users do not want an always-listening interaction. Give the control a clear keyboard interaction, visible recording state, and an accessible name. If the action depends on holding a pointer, provide an equivalent for people who cannot hold the button continuously.
Interruptions are part of conversation. A useful assistant should stop or adapt when the user speaks over a long answer, but the application must not confuse interrupted playback with a completed business task. If a tool request is in flight, cancelling speech is not necessarily the same as cancelling the tool. Design the cancellation and confirmation rules explicitly on the server.
Make state visible and recoverable
A voice interface has several states that sound similar when described as “loading.” They need different user messages and different recovery actions.
| State | What the user should understand | Suggested action |
|---|---|---|
| Idle | The microphone is not being used by this feature. | Start a session. |
| Awaiting permission | The browser is waiting for a microphone decision. | Allow, deny, or cancel. |
| Connecting | Permission exists and the application is establishing a connection. | Wait briefly or cancel. |
| Connected | The session is active and the microphone may send audio. | Speak, mute if supported, or end. |
| Playback blocked | The session may be connected but the browser has not played audio. | Use an explicit playback control. |
| Interrupted or reconnecting | Network or device state has changed. | Retry or end, without suggesting a completed action. |
| Ended | Local capture has stopped and the connection is closed. | Start a new session. |
Use a live region for concise status changes, but avoid announcing every low-level event to assistive technology. Keyboard users need a reliable route to Start, Stop, and any mute control. People who cannot use audio need a text alternative that can complete the same essential task, not merely a note that voice is unavailable.
Do not use a color change as the only sign that the microphone is live. Combine text, iconography, and an obvious control. If the application stores audio or a transcript, say what is stored and how the user can obtain more information before capture. Browser permission tells the browser that the user allowed device access; it does not by itself settle every consent or retention requirement for your product.
Treat tool calls as untrusted requests
Voice is a convenient input method, not an authorization method. A caller saying “I am the account owner” does not authenticate them. The model proposing cancel_reservation does not prove that the customer owns the reservation. The tool implementation must authenticate the user, check their rights against current server data, validate arguments, and return a result that distinguishes success from failure.
For a booking workflow, separate lookup, confirmation, and commit. First query availability. Then repeat the exact date, time zone, and service to the user. Only after an explicit confirmation should the server attempt the booking. The final write must check availability again because the slot may have changed between lookup and commit. If a conflict occurs, the assistant should say the booking failed and offer another time instead of announcing success.
Use a durable idempotency strategy for writes where duplicate attempts could create duplicate bookings. Associate a server-generated operation key with the authenticated user and the confirmed request. A retry should retrieve the original result or safely report that the operation is still pending. A model-generated statement, a browser button click, or a speech interruption is not an idempotency guarantee.
For sensitive actions, define confirmation requirements outside the prompt and enforce them in the backend. The agent can help gather information and ask for confirmation, but the server decides whether the request is permitted and complete. If a user asks for a person, provide a real escalation path and describe what happens when nobody is available. Never imply that a transfer succeeded until your call or support system reports it.
Keep tool outputs minimal. A lookup tool may need to return appointment availability, but it rarely needs to send an entire customer profile into the session. Redact secrets and unnecessary personal data from logs. Treat retrieved page text, uploaded files, and tool responses as data that can contain misleading instructions, not as a new authority over your application rules.
Write instructions that help the conversation
A prompt works best when it defines the task, limits, and behavior the user can observe. For the coworking demo, the instruction says what the assistant can explain and what it cannot claim. A real support assistant needs the same clarity, plus a plan for uncertainty and escalation.
Try a compact structure:
Role: Help visitors understand the coworking space.
Scope: Explain the published opening hours and direct booking questions to a person.
Uncertainty: If the answer is not in the supplied information, say you do not know.
Speaking style: Use short sentences and allow the visitor to interrupt.
Action boundary: Do not claim that a reservation exists without a confirmed tool result.
Escalation: When the visitor asks for a person, offer the available contact channel.That wording is a starting point, not proof of compliance. Test contradictory requests, long descriptions, background voices, and situations where a tool fails. Confirm that the agent does not turn an unknown answer into a plausible invention. Refine instructions using examples that represent actual user needs; avoid adding pages of rules that conflict or duplicate one another.
Write the things that must be enforced as code or workflow checks. If a refund needs human review, implement the review boundary rather than relying on a single sentence in the prompt. If a tool is read-only, make the underlying credential read-only too. Defense should hold even when the model misunderstands a request or the user speaks an adversarial instruction.
Handle transcripts without overstating their accuracy
Speech-to-speech systems may expose transcript events, but a transcript is a representation of audio, not a perfect record of what a person meant. Proper names, addresses, product codes, and numbers deserve special care. A single mistaken digit can change an appointment date or a support ticket identifier.
For high-consequence fields, ask the user to confirm the value in a form they can inspect or hear. Read back dates with a time zone and month name rather than relying on an ambiguous numeric format. For an email address, provide a text field or a correction step instead of assuming a phonetic transcription is exact. If the user corrects a value, replace the candidate and re-confirm before using it in a write.
Live captions also need a distinction between provisional and completed text. A partial sentence may change, and different turns can complete at different times. Associate display text with the correct item identifier when the API provides one, preserve order deliberately, and avoid presenting a provisional fragment as an official record. The Realtime transcription guide covers event behavior for transcription workflows.
Decide whether you actually need to store transcripts. If you retain them, establish who can read them, how long they are kept, how deletion works, and whether vendors or internal systems process them. Avoid placing raw transcripts in general-purpose analytics events or application error messages. Review the provider’s data controls together with the terms and requirements that apply to your own product.
Measure latency at the moments users notice
A voice agent can say “one moment” quickly and still take too long to answer. Measure both the first acknowledgement and the first useful answer. When a tool is involved, measure tool duration separately so a slow database or external service does not get blamed on audio playback.
Define a test case before comparing numbers. For example: the user asks, “What time do you open on Friday?” Record the browser, device, network conditions, model configuration, speech sample, and expected answer. Repeat the same scenario across versions, then add a second case that uses a slow tool. Comparing unlike conversations produces a chart, not a useful diagnosis.
Useful measurements include time from session-start click to connected state; time from the end of the user’s utterance to first audible response; time from utterance end to a useful answer; tool execution duration; and the percentage of attempts that end in a recoverable error. Use a monotonic clock for durations and document how the endpoints are identified. A VAD event can help approximate an utterance boundary, but it is not a perfect ground truth for every speaker.
Report distributions such as a median and a high percentile alongside sample size, rather than presenting a single best-case number. Separate cold starts, permission delays, and an already-connected conversation. Do not promise a specific latency until you have measured your own traffic on representative devices and networks. Optimize the largest observed delay before changing settings based on intuition.
Build a small evaluation set before launch
Testing a voice agent by asking the same question twice is a good smoke test. It is not a release test. Create a repeatable set of tasks with expected outcomes, including ordinary conversations and failures. Keep any recorded participant audio only when you have the right permission and a retention plan.
| Scenario | Expected observable result |
|---|---|
| User asks about opening hours | The answer matches the supplied information. |
| User pauses mid-sentence | The assistant does not consistently cut the speaker off. |
| User interrupts a long answer | Playback and response behavior match your interruption design. |
| User asks an unsupported question | The assistant admits uncertainty or offers the intended fallback. |
| Microphone permission is denied | The interface explains the issue and offers a retry or alternative. |
| Speaker autoplay is blocked | The user sees a control or instruction to enable playback. |
| Network drops during connection | The UI leaves its loading state and offers recovery. |
| A booking slot becomes unavailable | The application does not claim a reservation succeeded. |
| A user requests account data without authorization | The backend denies the request, regardless of what was spoken. |
| User ends the session | The microphone track stops and the connection closes. |
For each scenario, record the expected result, the actual result, and the version under test. For tool actions, inspect the underlying system of record rather than relying on what the assistant said. A spoken “done” is not a receipt. A booking is complete only when the booking system confirms it and the user receives the appropriate confirmation.
Include a range of microphones, speakers, accents, speaking speeds, and background conditions that reflects your audience. Do not infer fairness from a handful of convenient recordings. Seek consent and review failures with people who understand the language and context. Accessibility testing should include keyboard navigation and screen-reader behavior as well as audio quality.
Troubleshoot common failures
The permission prompt never appears. Check whether the page runs in a secure context, whether the browser supports the API, and whether an existing site permission blocks access. The user may also have ignored a prompt; a pending promise does not always mean the code has crashed. Show a way to cancel and provide browser-specific help only after confirming the environment.
The session endpoint returns an error. Confirm that the server has an API key, the account can use the selected model, and the upstream endpoint and request shape match the current documentation. Inspect safe server-side status information. Do not print the full authorization header or return provider error bodies blindly to untrusted clients.
The connection starts but there is no sound. Check the selected output device, browser playback policy, remote track event, and audio element. Try headphones to reduce feedback while diagnosing. The session being connected does not guarantee that the output device is audible or that the browser permitted autoplay.
The assistant cuts users off. Reproduce the issue with representative speech and background noise. Compare supported VAD settings or a push-to-talk design. A longer wait may reduce premature turns but can make the interaction feel slower. Change one variable at a time and measure both completion and perceived responsiveness.
The agent gives an answer but the action did not occur. Check the tool result and your system of record. Make success language conditional on a confirmed server result, and distinguish pending, failed, and completed states. Add a test for retries and conflicts; do not repair the issue only by telling the model to be more careful.
The microphone indicator remains active after ending. Inspect every acquired track and stop it during normal shutdown, failed startup, navigation, and cancellation. A closed peer connection alone should not be your only cleanup strategy. Check the browser indicator and device permissions during the test.
Privacy and operational checklist
Before inviting real users, walk through the complete lifecycle:
- Explain when microphone capture begins, where the audio goes, and how to stop it.
- Ask for microphone access only after a clear user action, and provide a non-voice route for essential tasks.
- Authenticate session creation and apply shared rate, concurrency, and spending controls appropriate to your environment.
- Keep the standard API key on the server; avoid logging credentials, raw audio, and unnecessary transcripts.
- Define retention, access, deletion, and incident procedures for any stored conversation data.
- Validate tool arguments and enforce user permissions in the backend.
- Require an appropriate confirmation for consequential writes and verify the result in the system of record.
- Release media tracks and close the connection on stop, failure, cancellation, and navigation.
- Test permission denial, device changes, interruptions, playback failures, and unreliable networks.
- Review provider limits, pricing, model availability, and API changes before each significant release.
Some products may have additional legal, accessibility, security, or sector-specific obligations. This checklist is an engineering starting point; adapt it with the people responsible for those decisions in your organization.
Frequently asked questions
Can a browser call the Realtime API without exposing my standard API key?
Yes. In the unified flow, your backend makes the authenticated call after receiving the browser’s WebRTC offer. In the client-secret flow, your backend issues a short-lived secret for the browser. In either case, keep your standard API key off the client and protect the endpoint that creates access.
Is WebRTC the only way to build a voice agent?
No. It is a useful choice for browser audio. Server-side systems may use WebSockets, and telephony systems have their own integration path. A chained speech pipeline may also fit a product that needs explicit control over intermediate text. Choose based on the user experience, the deployment environment, and the operational controls you need.
Does a working microphone demo mean the agent is production ready?
No. The demo proves only that one connection and conversation worked under the conditions tested. Production readiness also depends on authentication, abuse prevention, safe business actions, reliable shutdown, privacy decisions, accessibility, and repeatable evaluation across realistic environments.
How do I prevent the agent from taking an unauthorized action?
Enforce permissions in the service that owns the action. Authenticate the user, validate arguments, check access to the specific record, require confirmation where appropriate, and make the operation idempotent. Instructions to the model can improve conversation flow but cannot substitute for a server-side authorization decision.
Should I automatically save every conversation?
Start by deciding what problem storage solves. If a transcript is needed for support, specify access, retention, deletion, and correction procedures, and explain the practice to users. If it is not needed, avoid collecting it. A live voice interface and a permanent recording are different product decisions.
What if I need captions as well as speech?
Design captions around provisional and final text, item identity, and corrections. Test them with representative speakers and assistive technology. Consult the current transcription event documentation for your chosen session type; do not assume every event has the same ordering or completeness.
Sources and further reading
- OpenAI: Realtime getting started — session flow and migration from beta.
- OpenAI: WebRTC connection guide — unified and client-secret connection patterns.
- OpenAI: Voice agents and architectures — selecting a speech architecture.
- OpenAI: Voice activity detection — supported turn detection modes and settings.
- OpenAI: Realtime transcription — live transcript events and lifecycle.
- OpenAI: Client secret API reference — short-lived credential behavior.
- OpenAI: Data controls — provider data handling options.
- MDN:
getUserMedia()— browser permission and secure-context requirements.
Documentation reviewed November 13, 2026. Check current provider documentation and account configuration when implementing; this article’s demo is an educational example and has not been verified against your environment.
