We recommend WebRTC for GPT-Live audio connections in browser, mobile, and server applications. This guide walks through a browser example. Microphone input and generated speech travel on negotiated media tracks. A data channel carries JSON events for transcripts, session updates, and delegated work.
Your browser creates a Session Description Protocol (SDP) offer. Your application server exchanges it for an answer with POST /v1/live/sessions, using the project API key. Keep the key and session configuration on your trusted server.
You need:
- A project API key with access to GPT-Live.
- A server runtime for your chosen SDK example. The Node.js example requires Node.js 22.6 or later.
- A browser with microphone permission, running on HTTPS or localhost.
The example uses Responses delegation with gpt-5.6-terra and hosted web search. For backend instructions and application tools, see Delegation and tools. For voice and backend usage, see Cost optimization.
- Request microphone access from a user action and add its tracks to a peer connection.
- Create the data channel and register event listeners before creating the SDP offer.
- Set the local description, wait for ICE candidate gathering, and send the offer to your server.
- Have your server post JSON containing
session and transport: { type: "webrtc", sdp: ... } to OpenAI.
- Apply the returned SDP answer as the remote description. Wait for
session.started on the data channel before sending application commands.
The HTTP request starts the session. Do not send session.start on the data channel. The oai-events string in the example is the data-channel label. To wait for speech before starting inference, configure standby.
With the default startup behavior, creating a WebRTC session with POST /v1/live/sessions bills 15 seconds of voice duration during initialization. That amount is credited against duration charges once the session starts running; it is not an extra 15 seconds added to the running session. See WebRTC initialization charges for cost accounting.
Save the server example in a new directory and set OPENAI_API_KEY in its environment. For TypeScript, use Node.js 22.6 or later, save the example as server.ts, and run npm install openai express followed by npm pkg set type=module. For Python, install openai. This example binds to 127.0.0.1, accepts session requests from http://localhost:3000, and serves index.html from the directory where you run it.
For Go, save the example as main.go, initialize a module with go mod init live-demo, and install github.com/openai/openai-go/v3@v3.85.1 with go get. Run go run . with Go 1.26 or later. For Java, add the Maven dependency com.openai:openai-java:4.95.0 and run the LiveConnectionWebrtcExample class. For Ruby 3.3 or later, install openai 0.110.0 and webrick with gem install openai -v 0.110.0 and gem install webrick, save the example as server.rb, and run ruby server.rb.
Choose a server language below; each variant serves index.html and the same /api/session endpoint on port 3000. Use an SDK version with Live support. Run only one variant at a time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66import express from "express";
import OpenAI from "openai";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
const app = express();
const client = new OpenAI({ maxRetries: 0 });
const port = 3000;
const origin = `http://localhost:${port}`;
const indexPath = resolve("index.html");
app.use(express.json({ limit: "64kb" }));
app.get("/", async (_request, response) => {
response.type("html").send(await readFile(indexPath, "utf8"));
});
// Local-only demo. Add your application's authentication and authorization
// before exposing session creation to other users.
app.post("/api/session", async (request, response) => {
if (request.headers.origin !== origin) {
response.status(403).json({ error: "Unexpected request origin" });
return;
}
if (typeof request.body?.sdp !== "string" || !request.body.sdp.trim()) {
response.status(400).json({ error: "An SDP offer is required" });
return;
}
if (!process.env.OPENAI_API_KEY) {
response.status(503).json({ error: "Set OPENAI_API_KEY on the server" });
return;
}
try {
const result = await client.live.create({
session: {
model: "gpt-live-1.1",
instructions:
"Be concise. Delegate requests needing current information to the backend, which can search the web.",
delegation: {
type: "responses",
responses: {
model: "gpt-5.6-terra",
instructions:
"Use web search when current facts are needed. Return concise, grounded results for a spoken conversation.",
tools: [{ type: "web_search" }],
tool_choice: "auto",
},
},
},
transport: {
type: "webrtc",
sdp: request.body.sdp,
},
});
// Preserve the SDK's typed session ID and SDP answer.
response.status(201).json(result);
} catch (error) {
if (!(error instanceof OpenAI.APIError)) throw error;
console.error("Live session creation failed", error.status);
response
.status(error.status ?? 502)
.json({ error: "Live session creation failed" });
}
});
app.listen(port, "127.0.0.1", () => console.log(`Open ${origin}`));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from openai import APIError, OpenAI
from openai.types.live.media_session_config_param import MediaSessionConfigParam
from pydantic import BaseModel, Field, ValidationError
client = OpenAI(max_retries=0)
origin = "http://localhost:3000"
class SDPOffer(BaseModel):
sdp: str = Field(min_length=1)
class SessionHandler(BaseHTTPRequestHandler):
def reply(
self, status: int, body: bytes, content_type: str = "application/json"
) -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.end_headers()
self.wfile.write(body)
def do_GET(self) -> None:
if self.path != "/":
self.reply(404, b"{}")
return
self.reply(200, Path("index.html").read_bytes(), "text/html")
def do_POST(self) -> None:
# Local-only demo: add application authentication before exposing it.
if self.path != "/api/session":
self.reply(404, b"{}")
return
if self.headers.get("Origin") != origin:
self.reply(403, b'{"error":"Unexpected request origin"}')
return
length = int(self.headers.get("Content-Length", "0"))
if length > 65536:
self.reply(413, b'{"error":"SDP offer is too large"}')
return
if length <= 0:
self.reply(400, b'{"error":"An SDP offer is required"}')
return
try:
offer = SDPOffer.model_validate_json(self.rfile.read(length))
if not offer.sdp.strip():
self.reply(400, b'{"error":"An SDP offer is required"}')
return
except ValidationError:
self.reply(400, b'{"error":"An SDP offer is required"}')
return
session: MediaSessionConfigParam = {
"model": "gpt-live-1.1",
"instructions": "Be concise. Delegate requests needing current information to the backend, which can search the web.",
"delegation": {
"type": "responses",
"responses": {
"model": "gpt-5.6-terra",
"instructions": "Use web search when current facts are needed. Return concise, grounded results for a spoken conversation.",
"tools": [{"type": "web_search"}],
"tool_choice": "auto",
},
},
}
try:
result = client.live.create(
session=session, transport={"type": "webrtc", "sdp": offer.sdp}
)
except APIError as error:
self.reply(
getattr(error, "status_code", 502),
b'{"error":"Live session creation failed"}',
)
return
# Return the SDK's typed session ID and SDP answer unchanged.
self.reply(201, result.model_dump_json().encode())
if __name__ == "__main__":
print(f"Open {origin}")
ThreadingHTTPServer(("127.0.0.1", 3000), SessionHandler).serve_forever()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79package main
import (
"encoding/json"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/live"
"github.com/openai/openai-go/v3/option"
"io"
"log"
"net/http"
"os"
"strings"
"time"
)
func main() {
client := openai.NewClient(option.WithMaxRetries(0))
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" || r.Method != http.MethodGet {
http.NotFound(w, r)
return
}
http.ServeFile(w, r, "index.html")
})
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if r.Header.Get("Origin") != "http://localhost:3000" {
http.Error(w, "Forbidden", 403)
return
}
if os.Getenv("OPENAI_API_KEY") == "" {
http.Error(w, "Server API key is not configured", 503)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024))
if err != nil {
http.Error(w, "Invalid SDP offer", 413)
return
}
var offer struct {
SDP string `json:"sdp"`
}
if err := json.Unmarshal(body, &offer); err != nil || strings.TrimSpace(offer.SDP) == "" {
http.Error(w, "SDP offer is required", 400)
return
}
result, err := client.Live.New(r.Context(), live.LiveNewParams{
Session: live.MediaSessionConfigParam{
Model: "gpt-live-1.1",
Instructions: openai.String("Be concise. Delegate requests needing current information to the backend, which can search the web."),
Delegation: live.MediaSessionConfigDelegationUnionParam{OfResponses: &live.MediaSessionConfigDelegationResponsesParam{Responses: live.ResponsesDelegationConfigParam{
Model: "gpt-5.6-terra",
Instructions: openai.String("Use web search when current facts are needed. Return concise, grounded results for a spoken conversation."),
Tools: []live.ResponsesDelegationConfigToolUnionParam{{OfWebSearch: &live.ResponsesDelegationConfigToolWebSearchParam{}}},
ToolChoice: live.ResponsesDelegationConfigToolChoiceUnionParam{OfLiveToolChoiceEnum: openai.String("auto")},
}}},
},
Transport: live.LiveNewParamsTransport{Sdp: offer.SDP},
})
if err != nil {
log.Printf("Live session creation failed: %T", err)
http.Error(w, "Session creation failed", 502)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(result); err != nil {
log.Print("Could not write session response")
}
})
server := &http.Server{Addr: "127.0.0.1:3000", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
fmt.Println("Open http://localhost:3000")
log.Fatal(server.ListenAndServe())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.live.*;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public final class LiveConnectionWebrtcExample {
public static void main(String[] args) throws Exception {
var client = OpenAIOkHttpClient.builder().fromEnv().maxRetries(0).build();
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 3000), 0);
server.createContext(
"/",
exchange -> {
try (exchange) {
var path = exchange.getRequestURI().getPath();
int status;
byte[] body;
String contentType = "text/plain; charset=utf-8";
if (path.equals("/") && exchange.getRequestMethod().equals("GET")) {
status = 200;
body = Files.readAllBytes(Path.of("index.html"));
contentType = "text/html; charset=utf-8";
} else if (!path.equals("/api/session")) {
status = 404;
body = "Not found".getBytes(StandardCharsets.UTF_8);
} else if (!exchange.getRequestMethod().equals("POST")) {
status = 405;
body = "Method not allowed".getBytes(StandardCharsets.UTF_8);
} else if (!"http://localhost:3000"
.equals(exchange.getRequestHeaders().getFirst("Origin"))) {
status = 403;
body = "Forbidden".getBytes(StandardCharsets.UTF_8);
} else if (System.getenv("OPENAI_API_KEY") == null
|| System.getenv("OPENAI_API_KEY").isBlank()) {
status = 503;
body = "Server API key is not configured".getBytes(StandardCharsets.UTF_8);
} else {
var offer = exchange.getRequestBody().readNBytes(64 * 1024 + 1);
String sdp = "";
if (offer.length <= 64 * 1024) {
try {
var request = com.openai.core.ObjectMappers.jsonMapper().readTree(offer);
if (request != null && request.path("sdp").isTextual()) {
sdp = request.path("sdp").asText();
}
} catch (com.fasterxml.jackson.core.JsonProcessingException error) {
// Invalid browser JSON is rejected below without creating a session.
}
}
if (offer.length > 64 * 1024 || sdp.isBlank()) {
status = offer.length > 64 * 1024 ? 413 : 400;
body = "Invalid SDP offer".getBytes(StandardCharsets.UTF_8);
} else {
try {
var result =
client
.live()
.create(
LiveCreateParams.builder()
.session(
MediaSessionConfig.builder()
.model("gpt-live-1.1")
.instructions(
"Be concise. Delegate requests needing current information to the backend, which can search the web.")
.responsesDelegation(
ResponsesDelegationConfig.builder()
.model("gpt-5.6-terra")
.instructions(
"Use web search when current facts are needed. Return concise, grounded results for a spoken conversation.")
.addToolWebSearch()
.toolChoice(
ResponsesDelegationConfig.ToolChoice
.LiveToolChoiceEnum.AUTO)
.build())
.build())
.transport(LiveCreateParams.Transport.builder().sdp(sdp).build())
.build());
body = com.openai.core.ObjectMappers.jsonMapper().writeValueAsBytes(result);
status = 201;
contentType = "application/json";
} catch (RuntimeException error) {
System.err.println(
"Live session creation failed: " + error.getClass().getSimpleName());
status = 502;
body = "Session creation failed".getBytes(StandardCharsets.UTF_8);
}
}
}
exchange.getResponseHeaders().set("Content-Type", contentType);
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
}
});
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
server.stop(0);
client.close();
}));
server.start();
System.out.println("Open http://localhost:3000");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73require "openai"
require "webrick"
require "json"
client = OpenAI::Client.new(api_key: ENV["OPENAI_API_KEY"] || "", max_retries: 0)
server = WEBrick::HTTPServer.new(BindAddress: "127.0.0.1", Port: 3000)
server.mount_proc "/" do |request, response|
response["Content-Type"] = "text/plain; charset=utf-8"
if request.path == "/" && request.request_method == "GET"
response["Content-Type"] = "text/html; charset=utf-8"
response.body = File.read("index.html")
elsif request.path != "/api/session"
response.status = 404
response.body = "Not found"
elsif request.request_method != "POST"
response.status = 405
response.body = "Method not allowed"
elsif request["origin"] != "http://localhost:3000"
response.status = 403
response.body = "Forbidden"
elsif ENV["OPENAI_API_KEY"].to_s.empty?
response.status = 503
response.body = "Server API key is not configured"
else
raise WEBrick::HTTPStatus::LengthRequired if request.content_length.nil?
raise WEBrick::HTTPStatus::BadRequest if request["transfer-encoding"]
raise WEBrick::HTTPStatus::RequestEntityTooLarge if request.content_length.to_i > 64 * 1024
offer = request.body.to_s
raise WEBrick::HTTPStatus::RequestEntityTooLarge if offer.bytesize > 64 * 1024
begin
payload = JSON.parse(offer)
rescue JSON::ParserError
raise WEBrick::HTTPStatus::BadRequest
end
sdp = payload.is_a?(Hash) ? payload["sdp"] : nil
raise WEBrick::HTTPStatus::BadRequest unless sdp.is_a?(String) && !sdp.strip.empty?
begin
result = client.live.create(
session: {
model: "gpt-live-1.1",
instructions: "Be concise. Delegate requests needing current information to the backend, which can search the web.",
delegation: {
type: :responses,
responses: {
model: "gpt-5.6-terra",
instructions: "Use web search when current facts are needed. Return concise, grounded results for a spoken conversation.",
tools: [{ type: :web_search }],
tool_choice: :auto
}
}
},
transport: {
type: :webrtc,
sdp: sdp
}
)
response.status = 201
response["Content-Type"] = "application/json"
response.body = result.to_json
rescue OpenAI::Errors::Error => error
warn "Live session creation failed: #{error.class}"
response.status = 502
response.body = "Session creation failed"
end
end
end
trap("INT") { server.shutdown }
puts "Open http://localhost:3000"
server.start
Before making the server accessible to other users, protect /api/session with your application’s authentication, authorization, request limits, and HTTPS. The origin check in this local example does not authenticate users.
Create index.html in the directory where you run the server:
12345678910111213<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GPT-Live connection</title>
</head>
<body>
<script type="module">
// Paste the compiled contents of browser.js here.
</script>
</body>
</html>
Save the following TypeScript code as browser.ts. It adds start and end controls, connects the microphone and output audio, and handles session events. /api/session is a route on your application server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133const start = document.createElement("button");
start.textContent = "Start conversation";
const stop = document.createElement("button");
stop.textContent = "End conversation";
stop.disabled = true;
const status = document.createElement("p");
const audio = new Audio();
audio.autoplay = true;
audio.controls = true;
document.body.append(start, stop, status, audio);
let peer: RTCPeerConnection;
let events: RTCDataChannel | undefined;
let microphone: MediaStream;
let closeTimeout: ReturnType<typeof setTimeout> | undefined;
let ready = false;
let finalized = false;
function cleanup() {
clearTimeout(closeTimeout);
microphone?.getTracks().forEach((track) => track.stop());
const closingEvents = events;
events = undefined;
closingEvents?.close();
peer?.close();
audio.srcObject = null;
ready = false;
start.disabled = false;
stop.disabled = true;
}
start.addEventListener("click", async () => {
start.disabled = true;
finalized = false;
status.textContent = "Connecting…";
try {
const connection = new RTCPeerConnection();
peer = connection;
connection.addEventListener("track", (event) => {
audio.srcObject = new MediaStream([event.track]);
audio.play().catch(() => {
status.textContent =
"Select play on the audio controls to hear the assistant.";
});
});
microphone = await navigator.mediaDevices.getUserMedia({ audio: true });
for (const track of microphone.getAudioTracks()) {
connection.addTrack(track, microphone);
}
// Create the event channel before creating the SDP offer.
events = connection.createDataChannel("oai-events");
events.addEventListener("message", ({ data }) => {
const event = JSON.parse(data);
if (event.type === "session.started") {
ready = true;
stop.disabled = false;
status.textContent = "Connected: " + event.session.id;
} else if (event.type === "session.closed") {
finalized = true;
console.log("Final session usage", event.usage);
status.textContent = "Conversation ended.";
cleanup();
} else {
// Save transcript and nested Responses events as needed by your app.
console.log(event);
}
});
events.addEventListener("close", (event) => {
if (event.target !== events) return;
if (!finalized) {
status.textContent = "Disconnected without final session usage.";
cleanup();
}
});
const offer = await connection.createOffer();
await connection.setLocalDescription(offer);
if (connection.iceGatheringState !== "complete") {
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
connection.removeEventListener("icegatheringstatechange", onState);
reject(new Error("Timed out while gathering ICE candidates"));
}, 10_000);
function onState() {
if (connection.iceGatheringState !== "complete") return;
clearTimeout(timeout);
connection.removeEventListener("icegatheringstatechange", onState);
resolve(undefined);
}
connection.addEventListener("icegatheringstatechange", onState);
onState();
});
}
const sdp = connection.localDescription?.sdp;
if (!sdp) throw new Error("Missing local SDP offer");
const response = await fetch("/api/session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sdp }),
});
if (!response.ok) throw new Error(await response.text());
const result = await response.json();
console.log("Created session", result.session.id);
await connection.setRemoteDescription({
type: "answer",
sdp: result.transport.sdp,
});
// The HTTP request started this session. Do not send session.start here.
} catch (error) {
status.textContent =
error instanceof Error ? error.message : String(error);
cleanup();
}
});
stop.addEventListener("click", () => {
if (!ready || !events || events.readyState !== "open") return;
stop.disabled = true;
status.textContent = "Finishing the conversation…";
// The session.closed handler is already registered. Keep media and events
// alive while pending work drains; only clean up after the final event.
events.send(JSON.stringify({ type: "session.close" }));
closeTimeout = setTimeout(() => {
status.textContent = "Incomplete finalization: no session.closed event.";
cleanup();
}, 15_000);
});
Compile browser.ts, then replace the placeholder in the module script with the contents of the generated browser.js file:
npm install --save-dev esbuild
npx esbuild browser.ts --format=esm --outfile=browser.js
Run your chosen server (node --experimental-strip-types server.ts or python server.py), open http://localhost:3000, and select Start conversation. After the status changes to Connected, ask a question that needs current information to exercise hosted search. Use the audio controls if your browser blocks autoplay.
A successful request returns HTTP 201 with JSON containing the session ID and SDP answer:
1234{
"session": { "id": "live_123" },
"transport": { "type": "webrtc", "sdp": "<SDP answer>" }
}
Read result.session.id and pass result.transport.sdp to setRemoteDescription. Treat the session ID as opaque and preserve it unchanged, including its prefix.
To reduce connection startup latency, see WebRTC with WARP.
Send microphone audio and receive generated speech through the media tracks. WebRTC negotiates the audio format through SDP, so omit audio.format from session configuration. Do not send session.input_audio.append or expect session.output_audio.delta on the data channel.
Use the data channel for transcript deltas, session commands, and nested response.event messages. See Managing sessions for transcript handling and lifecycle events, and Server-side controls if your server needs its own event connection.
To end the conversation, send session.close and keep receiving until session.closed before closing the peer connection and microphone tracks. The example registers the final-event listener before sending the command. If the connection fails or times out first, final usage is unconfirmed. See Usage and graceful close for final usage handling.
WebRTC is a powerful set of standard interfaces for building real-time applications. The OpenAI Realtime API supports connecting to realtime models through a WebRTC peer connection.
For browser-based speech-to-speech voice applications, we recommend starting with Voice agents, which covers the Agents SDK’s higher-level helpers and APIs for managing Realtime sessions. The WebRTC interface is powerful and flexible, but lower level than the Agents SDK.
When connecting to a Realtime model from the client (like a web browser or
mobile device), we recommend using WebRTC rather than WebSockets for more
consistent performance.
For more guidance on building user interfaces on top of WebRTC, refer to the docs on MDN.
The Realtime API supports two mechanisms for connecting from the browser: the unified interface and ephemeral API keys (generated via the OpenAI REST API). Use the unified interface for simpler setup and faster connections. This approach puts your application server in the critical path for session initialization.
The process for initializing a WebRTC connection using the unified interface is as follows (assuming a web browser client):
- The browser makes a request to a developer-controlled server using the SDP data from its WebRTC peer connection.
- The server combines that SDP with its session configuration in a multipart form and sends that to the OpenAI Realtime API, authenticating it with its standard API key.
To create a realtime API session via the unified interface, you will need to build a small server-side application (or integrate with an existing one) to make a request to /v1/realtime/calls. You will use a standard API key to authenticate this request on your backend server.
Create a Realtime API session from your application server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44import express from "express";
const app = express();
// Parse raw SDP payloads posted from the browser
app.use(express.text({ type: ["application/sdp", "text/plain"] }));
const sessionConfig = JSON.stringify({
type: "realtime",
model: "gpt-realtime-2.1",
audio: { output: { voice: "marin" } },
});
// An endpoint which creates a Realtime API session.
app.post("/session", async (req, res) => {
const fd = new FormData();
fd.set("sdp", req.body);
fd.set("session", sessionConfig);
try {
const r = await fetch("https://api.openai.com/v1/realtime/calls", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"OpenAI-Safety-Identifier": "hashed-user-id",
},
body: fd,
});
// Send back the SDP we received from the OpenAI REST API
const sdp = await r.text();
res.set(
"Content-Type",
r.ok ? "application/sdp" : (r.headers.get("Content-Type") ?? "text/plain")
);
const location = r.headers.get("Location");
if (location) res.set("Location", location);
res.status(r.status).send(sdp);
} catch (error) {
console.error("Session creation error:", error);
res.status(500).json({ error: "Failed to create session" });
}
});
app.listen(3000);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
import requests
ORIGIN = "http://127.0.0.1:3000"
SESSION = {
"type": "realtime",
"model": "gpt-realtime-2.1",
"audio": {"output": {"voice": "marin"}},
}
def signaling_query(path: str) -> dict[str, str]:
target = urlsplit(path)
if target.path != "/session" or target.scheme or target.netloc or target.fragment:
raise ValueError("Invalid signaling path")
if target.query:
raise ValueError("Unexpected query parameters")
return {}
def main() -> None:
key = os.environ["OPENAI_API_KEY"]
if not key.strip():
raise ValueError("OPENAI_API_KEY must not be empty")
# This is an HTTP signaling example, not a browser media implementation.
# Authenticate application users before public deployment and derive their
# hashed safety IDs. Keep this credential server-side; use HTTPS publicly.
class SessionHandler(BaseHTTPRequestHandler):
def setup(self) -> None:
super().setup()
self.connection.settimeout(30)
def reply(
self,
status: int,
body: bytes,
content_type: str,
location: str | None = None,
) -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.send_header("Connection", "close")
if location:
self.send_header("Location", location)
if status == 405:
self.send_header("Allow", "POST")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
self.close_connection = True
def do_POST(self) -> None:
try:
path = urlsplit(self.path).path
except ValueError:
self.reply(
400, b'{"error":"Invalid signaling request"}', "application/json"
)
return
if path != "/session":
self.reply(404, b'{"error":"Not found"}', "application/json")
return
if self.headers.get("Origin", ORIGIN) != ORIGIN:
self.reply(403, b'{"error":"Origin not allowed"}', "application/json")
return
if self.headers.get_content_type() not in ("application/sdp", "text/plain"):
self.reply(415, b'{"error":"Expected SDP"}', "application/json")
return
try:
query = signaling_query(self.path)
lengths = self.headers.get_all("Content-Length", [])
if len(lengths) != 1 or self.headers.get("Transfer-Encoding"):
raise ValueError("A single Content-Length is required")
length = int(lengths[0])
if not 0 < length <= 1024 * 1024:
raise ValueError("Invalid SDP length")
self.connection.settimeout(30)
offer = self.rfile.read(length)
if (
len(offer) != length
or offer.decode("utf-8").splitlines()[0] != "v=0"
):
raise ValueError("Invalid SDP offer")
except (ValueError, OSError):
self.reply(
400, b'{"error":"Invalid signaling request"}', "application/json"
)
return
try:
# requests generates multipart boundaries; SDP bytes remain intact.
with requests.post(
"https://api.openai.com/v1/realtime/calls",
params=query,
headers={
"Authorization": f"Bearer {key}",
"OpenAI-Safety-Identifier": "hashed-user-id",
"Accept": "application/sdp",
},
files={
"sdp": (None, offer, "application/sdp"),
"session": (None, json.dumps(SESSION), "application/json"),
},
timeout=(10, 60),
allow_redirects=False,
) as upstream:
status = upstream.status_code
body = upstream.content
content_type = (
"application/sdp"
if 200 <= status < 300
else upstream.headers.get("Content-Type", "text/plain")
)
location = upstream.headers.get("Location")
except requests.RequestException:
self.reply(
502, b'{"error":"Failed to create session"}', "application/json"
)
return
self.reply(status, body, content_type, location)
def method_not_allowed(self) -> None:
self.reply(405, b'{"error":"Method not allowed"}', "application/json")
do_GET = method_not_allowed
do_PUT = method_not_allowed
do_PATCH = method_not_allowed
do_DELETE = method_not_allowed
do_HEAD = method_not_allowed
do_OPTIONS = method_not_allowed
def log_message(self, format: str, *args: object) -> None:
return # Do not log signaling bodies or upstream errors.
with ThreadingHTTPServer(("127.0.0.1", 3000), SessionHandler) as server:
server.daemon_threads = False
try:
server.serve_forever()
except KeyboardInterrupt:
return # Close the listening socket and wait for handler threads.
if __name__ == "__main__":
main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38func handler(client openai.Client) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /session", func(w http.ResponseWriter, r *http.Request) {
offer, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024))
if err != nil || strings.TrimSpace(string(offer)) == "" {
http.Error(w, "A valid SDP offer is required", http.StatusBadRequest)
return
}
opts := []option.RequestOption{
option.WithHeader("OpenAI-Safety-Identifier", "hashed-user-id"),
}
response, err := client.Realtime.Calls.New(r.Context(), realtime.CallNewParams{
Sdp: string(offer),
Session: realtime.RealtimeSessionCreateRequestParam{
Model: "gpt-realtime-2.1",
Audio: realtime.RealtimeAudioConfigParam{
Output: realtime.RealtimeAudioConfigOutputParam{
Voice: realtime.RealtimeAudioConfigOutputVoiceUnionParam{
OfString: openai.String("marin"),
},
},
},
},
}, opts...)
if err != nil {
http.Error(w, "Could not create Realtime call", http.StatusBadGateway)
return
}
defer response.Body.Close()
w.Header().Set("Content-Type", "application/sdp")
w.Header().Set("Location", response.Header.Get("Location"))
w.WriteHeader(response.StatusCode)
if _, err := io.Copy(w, response.Body); err != nil {
log.Print("Could not write SDP answer")
}
})
return mux
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.realtime.*;
import com.openai.models.realtime.calls.CallCreateParams;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
var client = OpenAIOkHttpClient.fromEnv();
// Authenticate your application's users before exposing this server publicly.
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 3000), 0);
server.createContext(
"/session",
exchange -> {
int status = 200;
byte[] body;
exchange.getResponseHeaders().set("Content-Type", "application/sdp");
try {
if (!exchange.getRequestMethod().equals("POST")) {
status = 405;
body = "Method not allowed".getBytes(StandardCharsets.UTF_8);
} else {
byte[] offer = exchange.getRequestBody().readNBytes(1024 * 1024 + 1);
if (offer.length > 1024 * 1024)
throw new IllegalArgumentException("SDP offer is too large");
try (var response =
client
.realtime()
.calls()
.withRawResponse()
.create(
CallCreateParams.builder()
.sdp(new String(offer, StandardCharsets.UTF_8))
.session(
RealtimeSessionCreateRequest.builder()
.model("gpt-realtime-2.1")
.audio(
RealtimeAudioConfig.builder()
.output(
RealtimeAudioConfigOutput.builder()
.voice("marin")
.build())
.build())
.build())
.putAdditionalHeader("OpenAI-Safety-Identifier", "hashed-user-id")
.build())) {
status = response.statusCode();
body = response.body().readAllBytes();
response.headers().values("Location").stream()
.findFirst()
.ifPresent(location -> exchange.getResponseHeaders().set("Location", location));
}
}
} catch (IllegalArgumentException error) {
status = 400;
body = "Invalid SDP offer".getBytes(StandardCharsets.UTF_8);
} catch (RuntimeException error) {
status = 502;
body = "Could not create session".getBytes(StandardCharsets.UTF_8);
}
if (status >= 400) exchange.getResponseHeaders().set("Content-Type", "text/plain");
exchange.sendResponseHeaders(status, body.length);
try (var output = exchange.getResponseBody()) {
output.write(body);
} finally {
exchange.close();
}
});
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
server.stop(0);
client.close();
}));
server.start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45require "openai"
require "webrick"
require "json"
require "uri"
client = OpenAI::Client.new(max_retries: 0)
server = WEBrick::HTTPServer.new(
BindAddress: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "3000")),
Logger: WEBrick::Log.new($stderr), AccessLog: []
)
server.mount_proc("/session") do |request, response|
unless request.request_method == "POST" && request.path == "/session"
response.status = 405
next
end
begin
options = { extra_headers: { "OpenAI-Safety-Identifier" => "hashed-user-id" } }
upstream = client.realtime.calls.create(
sdp: request.body.to_s,
session: {
type: :realtime,
model: "gpt-realtime-2.1",
audio: { output: { voice: :marin } }
},
request_options: options
)
response.status = upstream.status
response["Content-Type"] = "application/sdp"
# Resolve against the API origin before WEBrick normalizes Location headers.
location = upstream.headers["location"]
response["Location"] = URI.join(client.base_url.to_s, location).to_s if location
response.body = upstream.body.to_a.join
rescue OpenAI::Errors::APIError => error
response.status = error.status || 502
response["Content-Type"] = "application/json"
response.body = JSON.generate(error.body)
rescue
response.status = 500
response["Content-Type"] = "application/json"
response.body = JSON.generate(error: "Failed to create session")
end
end
trap("INT") { server.shutdown }
trap("TERM") { server.shutdown }
server.start
If your application assigns a safety identifier
for each end user, include it as the OpenAI-Safety-Identifier header in this
server-side request. Use a stable, privacy-preserving value, such as a hashed
internal user ID. Keep the identifier to 128 characters or fewer. The header
should be set by your trusted backend, not by the browser.
In the browser, you can use standard WebRTC APIs to connect to the Realtime API via your application server. The client sends its SDP data to your server in a POST request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34// Create a peer connection
const pc = new RTCPeerConnection();
// Set up to play remote audio from the model
audioElement.current = document.createElement("audio");
audioElement.current.autoplay = true;
pc.ontrack = (e) => (audioElement.current.srcObject = e.streams[0]);
// Add local audio track for microphone input in the browser
const ms = await navigator.mediaDevices.getUserMedia({
audio: true,
});
pc.addTrack(ms.getTracks()[0]);
// Set up data channel for sending and receiving events
const dc = pc.createDataChannel("oai-events");
// Start the session using the Session Description Protocol (SDP)
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const sdpResponse = await fetch("/session", {
method: "POST",
body: offer.sdp,
headers: {
"Content-Type": "application/sdp",
},
});
const answer = {
type: "answer",
sdp: await sdpResponse.text(),
};
await pc.setRemoteDescription(answer);
The process for initializing a WebRTC connection using an ephemeral API key is as follows (assuming a web browser client):
- The browser makes a request to a developer-controlled server to mint an ephemeral API key.
- The developer’s server uses a standard API key to request an ephemeral key from the OpenAI REST API, and returns that new key to the browser.
- The browser uses the ephemeral key to authenticate a session directly with the OpenAI Realtime API as a WebRTC peer connection.

To create an ephemeral token to use on the client-side, you will need to build a small server-side application (or integrate with an existing one) to make an OpenAI REST API request for an ephemeral key. You will use a standard API key to authenticate this request on your backend server.
Create an ephemeral API key from your application server using the REST API:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43import express from "express";
const app = express();
const sessionConfig = JSON.stringify({
session: {
type: "realtime",
model: "gpt-realtime-2.1",
audio: {
output: {
voice: "marin",
},
},
},
});
// An endpoint which would work with the client code above - it returns
// the contents of a REST API request to this protected endpoint
app.get("/token", async (req, res) => {
res.set("Cache-Control", "no-store");
try {
const response = await fetch(
"https://api.openai.com/v1/realtime/client_secrets",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
"OpenAI-Safety-Identifier": "hashed-user-id",
},
body: sessionConfig,
}
);
const data = await response.json();
res.status(response.status).json(data);
} catch (error) {
console.error("Token generation error:", error);
res.status(500).json({ error: "Failed to generate token" });
}
});
app.listen(3000);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from openai import APIError, OpenAI
MODEL = "gpt-realtime-2.1"
ORIGIN = "http://127.0.0.1:3000"
def validate_credential(payload: dict) -> None:
session = payload.get("session", {})
if (
not isinstance(payload.get("value"), str)
or not payload["value"].strip()
or not isinstance(payload.get("expires_at"), int)
or payload["expires_at"] <= time.time()
or session.get("type") != "realtime"
or session.get("model") != MODEL
or session.get("audio", {}).get("output", {}).get("voice") != "marin"
):
raise ValueError("Invalid Realtime client credential")
def main() -> None:
# Local demonstration only. Before public deployment, authenticate the
# requesting application user and derive their stable hashed safety ID.
# Keep OPENAI_API_KEY on the server and serve the browser from ORIGIN.
with OpenAI(timeout=30.0, max_retries=0) as client:
class TokenHandler(BaseHTTPRequestHandler):
def setup(self) -> None:
super().setup()
self.connection.settimeout(30)
def reply(self, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.send_header("Connection", "close")
if status == 405:
self.send_header("Allow", "GET")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
self.close_connection = True
def do_GET(self) -> None:
if self.path != "/token":
self.reply(404, {"error": "Not found"})
return
if self.headers.get("Origin", ORIGIN) != ORIGIN:
self.reply(403, {"error": "Origin not allowed"})
return
try:
secret = client.realtime.client_secrets.create(
session={
"type": "realtime",
"model": MODEL,
"audio": {"output": {"voice": "marin"}},
},
extra_headers={"OpenAI-Safety-Identifier": "hashed-user-id"},
)
payload = secret.model_dump(mode="json", exclude_unset=True)
validate_credential(payload)
except (APIError, ValueError, TypeError, AttributeError):
self.reply(502, {"error": "Could not create client credential"})
return
self.reply(200, payload)
def method_not_allowed(self) -> None:
self.reply(405, {"error": "Method not allowed"})
do_POST = method_not_allowed
do_PUT = method_not_allowed
do_PATCH = method_not_allowed
do_DELETE = method_not_allowed
do_HEAD = method_not_allowed
do_OPTIONS = method_not_allowed
def log_message(self, format: str, *args: object) -> None:
# Avoid logging URLs, credentials, or upstream error details.
return
with ThreadingHTTPServer(("127.0.0.1", 3000), TokenHandler) as server:
server.daemon_threads = False
try:
server.serve_forever()
except KeyboardInterrupt:
return # The context managers close the listener and SDK client.
if __name__ == "__main__":
main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29func handler(client openai.Client) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /token", func(w http.ResponseWriter, r *http.Request) {
secret, err := client.Realtime.ClientSecrets.New(r.Context(), realtime.ClientSecretNewParams{
Session: realtime.ClientSecretNewParamsSessionUnion{
OfRealtime: &realtime.RealtimeSessionCreateRequestParam{
Model: "gpt-realtime-2.1",
Audio: realtime.RealtimeAudioConfigParam{
Output: realtime.RealtimeAudioConfigOutputParam{
Voice: realtime.RealtimeAudioConfigOutputVoiceUnionParam{
OfString: openai.String("marin"),
},
},
},
},
},
}, option.WithHeader("OpenAI-Safety-Identifier", "hashed-user-id"))
if err != nil {
http.Error(w, "Could not create client credential", http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
if _, err := io.WriteString(w, secret.RawJSON()); err != nil {
log.Print("Could not write client credential")
}
})
return mux
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.ObjectMappers;
import com.openai.models.realtime.*;
import com.openai.models.realtime.clientsecrets.ClientSecretCreateParams;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
var client = OpenAIOkHttpClient.fromEnv();
// Authenticate your application's users before exposing this server publicly.
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 3000), 0);
server.createContext(
"/token",
exchange -> {
int status = 200;
byte[] body;
try {
if (!exchange.getRequestMethod().equals("GET")) {
status = 405;
body = "{\"error\":\"Method not allowed\"}".getBytes(StandardCharsets.UTF_8);
} else {
var secret =
client
.realtime()
.clientSecrets()
.create(
ClientSecretCreateParams.builder()
.putAdditionalHeader("OpenAI-Safety-Identifier", "hashed-user-id")
.session(
RealtimeSessionCreateRequest.builder()
.model("gpt-realtime-2.1")
.audio(
RealtimeAudioConfig.builder()
.output(
RealtimeAudioConfigOutput.builder()
.voice("marin")
.build())
.build())
.build())
.build());
body = ObjectMappers.jsonMapper().writeValueAsBytes(secret);
}
} catch (RuntimeException error) {
status = 502;
body =
"{\"error\":\"Could not create client credential\"}"
.getBytes(StandardCharsets.UTF_8);
}
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.getResponseHeaders().set("Cache-Control", "no-store");
exchange.sendResponseHeaders(status, body.length);
try (var output = exchange.getResponseBody()) {
output.write(body);
} finally {
exchange.close();
}
});
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
server.stop(0);
client.close();
}));
server.start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43require "openai"
require "webrick"
require "json"
require "uri"
client = OpenAI::Client.new(max_retries: 0)
server = WEBrick::HTTPServer.new(
BindAddress: "127.0.0.1", Port: Integer(ENV.fetch("PORT", "3000")),
Logger: WEBrick::Log.new($stderr), AccessLog: []
)
server.mount_proc("/token") do |request, response|
response["Cache-Control"] = "no-store"
response["Content-Type"] = "application/json"
unless request.request_method == "GET" && request.path == "/token"
response.status = 405
next
end
begin
token = client.realtime.client_secrets.create(
session: {
type: :realtime,
model: "gpt-realtime-2.1",
audio: { output: { voice: :marin } }
},
request_options: {
include_raw_body: true,
extra_headers: { "OpenAI-Safety-Identifier" => "hashed-user-id" }
}
)
upstream = token.last_response or raise "Missing token response metadata"
response.status = upstream.status
response.body = upstream.body or raise "Missing token response body"
rescue OpenAI::Errors::APIError => error
response.status = error.status || 502
response.body = JSON.generate(error.body)
rescue
response.status = 500
response.body = JSON.generate(error: "Failed to generate token")
end
end
trap("INT") { server.shutdown }
trap("TERM") { server.shutdown }
server.start
You can create a server endpoint like this one on any platform that can send and receive HTTP requests. Just ensure that you only use standard OpenAI API keys on the server, not in the browser.
When using ephemeral tokens, set OpenAI-Safety-Identifier on the server-side
request that creates the client secret. Keep the identifier to 128 characters or
fewer. The Realtime API binds the identifier to the resulting ephemeral token,
so the browser does not need to send the safety identifier when it later
connects with that token.
In the browser, you can use standard WebRTC APIs to connect to the Realtime API with an ephemeral token. The client first fetches a token from your server endpoint, and then sends its SDP data (with the ephemeral token) to the Realtime API in a POST request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40// Get a session token for OpenAI Realtime API
const tokenResponse = await fetch("/token");
const data = await tokenResponse.json();
const EPHEMERAL_KEY = data.value;
// Create a peer connection
const pc = new RTCPeerConnection();
// Set up to play remote audio from the model
audioElement.current = document.createElement("audio");
audioElement.current.autoplay = true;
pc.ontrack = (e) => (audioElement.current.srcObject = e.streams[0]);
// Add local audio track for microphone input in the browser
const ms = await navigator.mediaDevices.getUserMedia({
audio: true,
});
pc.addTrack(ms.getTracks()[0]);
// Set up data channel for sending and receiving events
const dc = pc.createDataChannel("oai-events");
// Start the session using the Session Description Protocol (SDP)
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const sdpResponse = await fetch("https://api.openai.com/v1/realtime/calls", {
method: "POST",
body: offer.sdp,
headers: {
Authorization: `Bearer ${EPHEMERAL_KEY}`,
"Content-Type": "application/sdp",
},
});
const answer = {
type: "answer",
sdp: await sdpResponse.text(),
};
await pc.setRemoteDescription(answer);
WebRTC Abridged Roundtrip Protocol (WARP) reduces the time it takes to start a Realtime API voice session. You can enable its optimizations individually or combine them for the full WARP handshake.
See WebRTC with WARP for native client setup, browser support, origin-trial instructions, and the unified connection flow.
Realtime API sessions are managed using a combination of client-sent events emitted by you as the developer, and server-sent events created by the Realtime API to indicate session lifecycle events.
When connecting to a Realtime model via WebRTC, you don’t have to handle audio events from the model in the same granular way you must with WebSockets. The WebRTC peer connection object, if configured as above, will do all that work for you.
To send and receive other client and server events, you can use the WebRTC peer connection’s data channel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30// Reuse dc from the preceding browser connection example.
// Listen for server events
dc.addEventListener("message", (e) => {
const event = JSON.parse(e.data);
console.log(event);
});
// Send client events
const event = {
type: "conversation.item.create",
item: {
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "hello there!",
},
],
},
};
const sendGreeting = () => dc.send(JSON.stringify(event));
if (dc.readyState === "open") {
sendGreeting();
} else if (dc.readyState === "connecting") {
dc.addEventListener("open", sendGreeting, { once: true });
} else {
throw new Error("The data channel has closed before greeting was sent.");
}
To learn more about managing Realtime conversations, refer to the Realtime conversations guide.
Check out the WebRTC Realtime API in this light weight example app.