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

Quick Start

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

{
  "type": "message",
  "content": "Hello, agent!",
  "session_id": "optional-session-id"
}

Server to Client

{
  "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

path
str
default:"/ws"
WebSocket endpoint path.
auth_on_connect
bool
default:"false"
Require authentication during the WebSocket handshake.

FastAPI Integration

Use create_router() to mount the WebSocket endpoint on an existing FastAPI app:
from fastapi import FastAPI

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

Imports

from definable.agent.interface.websocket import WebSocketInterface