# Realtime Model API

> The Realtime API is a type of AI model API that streams audio and text in both directions over a persistent connection.

## What is a realtime AI API?

The type of model API that keeps a persistent WebSocket or WebRTC session and streams audio, text and tool calls both ways. Used to build voice agents with low latency instead of sending separate HTTP requests.

- Topic: Voice AI
- Type: technology

## Example

Wrong:

```js
const pc = new RTCPeerConnection();
const answer = await fetch(REALTIME_URL, {
  method: 'POST',
  headers: { Authorization: 'Bearer ' + API_KEY },
  body: offer.sdp,
});
```

Right:

```js
const { token } = await fetch('/api/realtime-token').then((r) => r.json());
const answer = await fetch(REALTIME_URL, {
  method: 'POST',
  headers: { Authorization: 'Bearer ' + token },
  body: offer.sdp,
});
```

The browser gets a short-lived token from your server, so the main API key never ships in frontend code.

## Common mistakes

- Putting the provider API key in frontend code to open the session.

## Key points

- Browsers connect with short-lived tokens issued by the server, never with the main API key.
- The session handles reconnects and closes when the conversation ends.

## Interview questions

### WebRTC vs WebSocket for a realtime AI API?

WebRTC is usually better from the browser, as it handles audio, jitter and echo cancellation. WebSocket is simpler for server-side connections.

### Can I use a realtime API for text only?

Yes, most realtime APIs accept and return text as well as audio, but a regular streaming HTTP API is usually simpler for text-only chat.

### Why does my realtime session disconnect?

Sessions often have a maximum duration and drop on network changes. Handle the close event, reconnect with a new token and restore the conversation state.

## Related cards

- [Voice Agent](https://wonderium.dev/ai/voice-agent.md)
- [WebRTC](https://wonderium.dev/web/webrtc.md)
- [WebSocket](https://wonderium.dev/js/web-socket.md)
- [LLM API](https://wonderium.dev/ai/llm-api.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/realtime-api
- Last updated: 2026-11-25
