# GPT-Live

> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

## 3. Build your first voice application with GPT-Live

In this lesson, we’re going to connect to GPT-Live and build our first voice application.

### Streaming audio

Let’s start with how our application exchanges audio with the model.



In a text-based application, we can wait until someone finishes typing their message before we send it. With live voice, we need to **send audio as the person speaks**, without waiting for a complete recording.





When GPT-Live replies, we also need to **play the audio as the model generates it**, rather than wait for the whole answer.



That means we need a connection that stays open for the whole conversation and lets audio flow in both directions at once.

Let’s look at two ways of doing that: WebSocket and WebRTC.

#### WebSocket

A WebSocket connection lets our application and GPT-Live send messages back and forth at any time. It can carry audio, but it wasn’t built specifically for audio streaming, so our application needs to handle more of the work.

For example, GPT-Live sends audio as it generates a reply, but network delays can make the pieces arrive at uneven intervals. Our application needs to buffer a little audio so a short delay doesn’t leave a gap in what the user hears.

#### WebRTC

WebRTC, on the other hand, was built for live audio and video. It handles much of that work for us, including compressing the audio and keeping playback smooth when pieces arrive unevenly.

That’s why we recommend WebRTC for GPT-Live audio connections in browser, mobile, and server applications. It’s what we’ll use throughout this training.

If you’re building an agent that people call over the phone, you can also connect through a phone provider using **SIP**, a standard used to set up internet phone calls. Although we won’t cover SIP in this training, you can find more details in the [SIP guide](https://developers.openai.com/api/docs/guides/voice-sip?api=live).

### WebRTC walkthrough

Let’s follow a browser app from the first microphone request to the end of a GPT-Live session. Select **Show code** to follow along in the browser and server files.



#### Browser and server

Let’s say we’re building a voice app that people use in their browser, with a server running behind it. We’ll use both to set up a WebRTC connection between the browser and OpenAI, where GPT-Live runs.







#### Request microphone access

First, the browser asks for permission to use the microphone so it can capture the user’s voice.







#### Prepare the microphone and speaker

Once we have that permission, we can add the microphone’s outgoing **audio track** to the WebRTC connection. We also set up the browser to play the track coming back from GPT-Live through the speaker.







#### Create a data channel for messages

Next, we add a **data channel** to the same connection. The browser can use it to receive transcripts and session updates from OpenAI. It can also send commands back over that channel, like a request to end the conversation.







#### Generate the browser’s SDP offer

WebRTC compresses audio, so the browser and OpenAI need a format they both support. They also need to know how to reach each other. The browser generates an **SDP offer** with its audio formats, support for the data channel, and the network addresses and ports OpenAI can try.







#### Send the offer to our application server

The browser asks our server to create a GPT-Live session and includes its SDP offer. The request to OpenAI needs our app’s API key, so the server makes that call on the user’s behalf.







#### Add the session settings

On the server, we put the offer into a request to OpenAI. We include the model name and the instructions we want GPT-Live to follow during the conversation.







#### Create a session with OpenAI

Our server sends the request with its API key. OpenAI creates a **session** for the conversation using those settings and prepares the connection details the browser needs to join it.







#### Pass OpenAI’s answer back to the browser

OpenAI returns those details in an **SDP answer**. It tells the browser which audio formats OpenAI accepts and where to reach it. Our server passes the answer back to the browser.







#### Use the answer to finish connecting

The browser uses the addresses in the answer to reach OpenAI and finish setting up the WebRTC connection. From here, audio and messages can travel directly between the browser and GPT-Live.







#### Wait for the session to start

Once the data channel opens, OpenAI uses it to confirm that the session is ready. The browser waits for that `session.started` message before sending any commands.







#### Send microphone audio and hear the reply

During the conversation, the user’s voice goes to GPT-Live on one audio track, and the model’s voice comes back on the other. Both tracks can be active at once, so GPT-Live can keep listening while it speaks.







#### Display the transcript as it arrives

As GPT-Live speaks, OpenAI sends transcript updates over the data channel. Your app can display the text in the browser as each update arrives.







#### Context compaction

GPT-Live automatically [**compacts the conversation history**](https://developers.openai.com/api/docs/guides/live-conversations#manage-longer-conversations) when the context window is over 90% full. The session continues with your instructions, recent messages, and any available summary. Store any key details you’ll need later in your application because the summary could omit them.







#### Disconnect from GPT-Live

The browser can ask OpenAI to close the session. For example, it might do this when the user ends the conversation or when your app ends it after a period of inactivity. Once OpenAI confirms the session is closed, the browser disconnects and releases the microphone.



### Connecting your server to the session

As you saw in the walkthrough, our server helps set up the WebRTC connection. But once it’s open, the browser and GPT-Live exchange audio and messages directly.

To let our server follow the conversation too, we can connect it to the same session over a WebSocket. That’s called a **sideband connection**. The server can receive transcripts and delegation requests while the browser handles the call audio. It can also send instructions back to GPT-Live.

### Try the application yourself



**Build a WebRTC voice app:**

```text
[@OpenAI Developers](plugin://openai-developers@openai-curated), build and run a browser voice app that connects to GPT-Live 1.1 over WebRTC. Show each step as it happens, from microphone access to the browser’s offer, the server’s session request, and the answer that comes back to the browser. Once I’m connected, let me talk to GPT-Live and watch the transcript arrive over the data channel.

Lesson 3: https://developers.openai.com/api/training/gpt-live/3-build-your-first-voice-application-with-gpt-live.md
```



You'll need Node.js 22.6 or later and an OpenAI project with GPT-Live access. In a new directory, install the server dependencies with `npm install openai@7.52.0 express@5.2.1` and set `OPENAI_API_KEY` in the server's environment.

<details>
<summary>Server code (server.ts)</summary>

This server serves `index.html` and handles the `/api/session` request. Its origin check is for local development. Before making the app available to other people, add your application's authentication, authorization, and request limits.

```typescript
import 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 friendly and concise. Help the user practice a voice conversation.",
      },
      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}`));
```


</details>

<details>
<summary>Browser code (index.html)</summary>

Create `index.html` alongside `server.ts` with this structure, then paste the browser code into its module script.

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>My first GPT-Live conversation</title>
  </head>
  <body>
    <script type="module">
      // Paste the browser code here.
    </script>
  </body>
</html>
```

</details>

Run `node --experimental-strip-types server.ts`, open `http://localhost:3000`, and select **Start conversation**. Allow microphone access and wait for Connected. Try asking for a lunch idea. You should hear the reply and see separate text for you and GPT-Live. If your browser blocks audio playback, use the audio controls on the page. Select **End conversation** when you're done. Running your own session uses your project's [GPT-Live credits or paid balance](https://developers.openai.com/api/docs/models/gpt-live-1.1).
