---
title: "Talk to an agent in realtime"
description: "Open a voice conversation with a Qomni agent from your app over WebSocket, without exposing your key, in Python or TypeScript."
version: "en"
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.qomni.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Talk to an agent in realtime

A realtime conversation has two steps: your server creates a session
over REST with its key, and your client opens a WebSocket with that
session's `url`. **The key never travels over the socket.** In this guide one program
does both parts, so you can try it in one go. In production, the
server creates the session and the browser or the app only receives the `url`.

```mermaid
sequenceDiagram
  participant C as Client
  participant S as Your server
  participant A as Agents API
  S->>A: POST /agents/v1/realtime/sessions (secret key)
  A-->>S: { url }, valid for 60 s
  S-->>C: the url
  C->>A: opens the WebSocket
  A-->>C: session.started
  C->>A: input_text.send
  A-->>C: response.text.delta …
  A-->>C: response.done
  C->>A: session.end
  A-->>C: session.ended (billed minutes)
```

## Before you begin

You need:

- An Agents test key (`sk_agents_test_…`), stored in the
  `QOMNI_KEY` environment variable.
- Python 3.10 or later, or Node.js 22 or later (it ships with `fetch` and
  `WebSocket`).

1. ### Install what you need

   In Python we use `requests` for the REST call and `websockets` for the
   socket. In Node.js, `tsx` runs TypeScript without compiling it.

   ```bash
   export QOMNI_KEY="sk_agents_test_…"
   pip install requests websockets
   ```

   ```bash
   export QOMNI_KEY="sk_agents_test_…"
   npm install --save-dev tsx
   ```

2. ### Create a session

   To open a conversation, request a session with your key. `instructions`
   is optional and tells the agent what to do in this conversation:

   ```bash
   curl https://api.qomni.ai/agents/v1/realtime/sessions \
     -H "Authorization: Bearer $QOMNI_KEY" \
     -H "Content-Type: application/json" \
     -d '{ "instructions": "Responde en una frase" }'
   ```

   The response carries the socket's `url`. Open it within **60 seconds**:

   ```json title="201 Created"
   {
     "id": "rts_01k8x3d5n2p7q4r6s8t0v1w3y5",
     "url": "wss://api.qomni.ai/agents/v1/realtime?session=rts_co1_…",
     "client_secret": "rts_co1_…",
     "expires_at": "2026-10-21T15:05:05Z",
     "max_duration_seconds": 900,
     "livemode": false,
     "cell": "co1"
   }
   ```

3. ### Open the socket and talk

   The program creates the session, waits for `session.started`, sends a question,
   prints the reply as it arrives and hangs up. Save it as
   `realtime.py` or `realtime.mts`:

   ```python
   import asyncio
   import json
   import os

   import requests
   import websockets

   QUESTION = {
       "type": "input_text.send",
       "text": "¿Hacen domicilios al centro?",
   }
   HANG_UP = {"type": "session.end"}


   def create_session() -> str:
       key = os.environ["QOMNI_KEY"]
       response = requests.post(
           "https://api.qomni.ai/agents/v1/realtime/sessions",
           headers={"Authorization": f"Bearer {key}"},
           json={"instructions": "Responde en una frase"},
           timeout=10,
       )
       if not response.ok:
           error = response.json()["error"]
           raise SystemExit(f"{error['code']}: {error['message']}")
       return response.json()["url"]


   async def converse(url: str) -> None:
       async with websockets.connect(url) as socket:
           async for raw in socket:
               message = json.loads(raw)
               match message["type"]:
                   case "session.started":
                       await socket.send(json.dumps(QUESTION))
                   case "response.text.delta":
                       print(message["delta"], end="", flush=True)
                   case "response.done":
                       print()
                       await socket.send(json.dumps(HANG_UP))
                   case "session.ended":
                       print(message)
                   case "error":
                       raise SystemExit(message["error"]["code"])


   asyncio.run(converse(create_session()))
   ```

   ```typescript
   const url = "https://api.qomni.ai/agents/v1/realtime/sessions";
   const response = await fetch(url, {
     method: "POST",
     headers: {
       Authorization: `Bearer ${process.env.QOMNI_KEY}`,
       "Content-Type": "application/json",
     },
     body: JSON.stringify({ instructions: "Responde en una frase" }),
   });
   if (!response.ok) {
     const { error } = await response.json();
     throw new Error(`${error.code}: ${error.message}`);
   }
   const session = await response.json();

   const socket = new WebSocket(session.url);
   const send = (message: object) =>
     socket.send(JSON.stringify(message));

   socket.onmessage = ({ data }) => {
     const message = JSON.parse(data);
     switch (message.type) {
       case "session.started":
         send({
           type: "input_text.send",
           text: "¿Hacen domicilios al centro?",
         });
         break;
       case "response.text.delta":
         process.stdout.write(message.delta);
         break;
       case "response.done":
         console.log();
         send({ type: "session.end" });
         break;
       case "session.ended":
         console.log(message);
         break;
       case "error":
         throw new Error(message.error.code);
     }
   };
   ```

   Run it:

   ```bash
   python realtime.py
   ```

   ```bash
   npx tsx realtime.mts
   ```

## You should see

The agent's reply appears word by word, followed by the
`session.ended` message. In test mode, `billed_minutes` is always `0`:

```text
Sí, llevamos pedidos al centro de lunes a sábado.
{'type': 'session.ended', 'reason': 'client_ended', 'billed_minutes': 0, 'usage_record_id': None}
```

If you see `api_key_malformed` instead, the key was copied wrong: export
`QOMNI_KEY` again. If you see `realtime_session_invalid`, more than 60
seconds passed between creating the session and opening the socket.

## Hanging up

The program hangs up on its own when it receives `response.done`: it sends `session.end`, and the
server replies `session.ended` with the billed minutes and closes the
socket. If you do not hang up, the session ends by itself after `max_duration_seconds`
(900 seconds) with `reason: max_duration`.

## Next steps

You now have a complete conversation with an agent. To put it in your app,
split the two parts: your server creates the session and hands the `url` to the
client.

- [Realtime WebSocket](/agents/websocket/): every message on the channel, including audio.
- [API keys and authentication](/concepts/authentication/): why the key must never reach the browser.
- [Test mode](/concepts/test-mode/): what changes with a test key.

Source: https://docs.qomni.ai/agents/realtime/index.mdx
