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

# WebSocket

> Real-time bidirectional communication via WebSocket.

The WebSocket interface provides real-time bidirectional communication between clients and agents using JSON messages.

## Quick Start

```python theme={null}
from definable.agent import Agent
from definable.agent.interface.websocket import WebSocketInterface

agent = Agent(model="gpt-4o", instructions="You are a helpful assistant.")

ws = WebSocketInterface(
    path="/ws",
    auth_on_connect=True,  # Require auth on connection
)

agent.serve(ws, port=8000)
```

Clients connect to `ws://localhost:8000/ws` and exchange JSON messages.

## Wire Protocol

### Client to Server

```json theme={null}
{
  "type": "message",
  "content": "Hello, agent!",
  "session_id": "optional-session-id"
}
```

### Server to Client

```json theme={null}
{
  "type": "response",
  "content": "Hello! How can I help?",
  "run_id": "abc123"
}
```

## Heartbeat

The interface sends periodic heartbeat pings. Clients should respond with pong messages to keep the connection alive.

## Constructor Reference

<ParamField path="path" type="str" default="/ws">
  WebSocket endpoint path.
</ParamField>

<ParamField path="auth_on_connect" type="bool" default="false">
  Require authentication during the WebSocket handshake.
</ParamField>

## FastAPI Integration

Use `create_router()` to mount the WebSocket endpoint on an existing FastAPI app:

```python theme={null}
from fastapi import FastAPI

app = FastAPI()
router = ws.create_router(agent)
app.include_router(router)
```

## Imports

```python theme={null}
from definable.agent.interface.websocket import WebSocketInterface
```
