WebSocket
Real-time bidirectional communication for chat-like applications with streaming responses and session persistence.
Setup Instructions
Create the connector
Open your agent, click Add inbound connector in the Connector Flow, then Create New Connector and select WebSocket.
Copy the WebSocket URL and Secret
After clicking Create, the connector detail drawer opens automatically with your credentials in the Configuration section. Authentication is enabled by default; disable Require Authentication only when middleware authenticates clients before they reach Connic. To access credentials later, hover over the connector in the Connector Flow and click the Eye icon.
Connect from your client
Use the URL and pass the secret via the X-Connic-Secret query parameter or header unless connector authentication is disabled because middleware validates the connection first.
How WebSocket Works
WebSocket connectors provide full-duplex communication for real-time chat. Unlike HTTP webhooks, they hold persistent connections for bidirectional messaging. Best for chat apps, streaming responses, multi-turn conversations, and interactive agents.
- Streaming: Send partial responses as generated (default: enabled)
- Require Auth: Secret key authentication (default: enabled)
- Session Timeout: Inactive expiry time (default: 1 hour)
- Max Messages: Per session limit (default: 100)
Connecting
// Connect to WebSocket
const ws = new WebSocket('<websocket-url>');
// Authenticate (required by default)
ws.onopen = () => {
ws.send(JSON.stringify({ secret: '<your-secret-key>' }));
};
// Handle connection confirmation
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'connected') {
console.log('Connector run ID:', data.connector_run_id);
console.log('Agents:', data.agents);
}
};The connector_run_id returned on connection identifies the persisted connector session.
Sending Messages
// Send a message
ws.send(JSON.stringify({
type: 'message',
id: 'msg-001',
payload: {
message: 'What is the weather like today?',
context: { location: 'New York' }
}
}));The id field is optional but useful for correlating responses.
Streaming Responses
// Streaming response events
{ "type": "ack", "id": "msg-001", "message_number": 1 }
{ "type": "stream_start", "id": "msg-001", "agent": "assistant" }
{ "type": "stream_chunk", "id": "msg-001", "agent": "assistant", "chunk": "The weather in " }
{ "type": "stream_chunk", "id": "msg-001", "agent": "assistant", "chunk": "New York is sunny." }
{
"type": "stream_end",
"id": "msg-001",
"agent": "assistant",
"full_response": "The weather in New York is sunny.",
"token_usage": { "prompt_tokens": 45, "candidates_tokens": 15 }
}Event types: ack (received),stream_start,stream_chunk (partial text),stream_end (complete with token usage)
Non-Streaming Mode
When streaming is disabled, you receive the complete response in a single message:
// Non-streaming response (when streaming disabled)
{ "type": "ack", "id": "msg-001", "message_number": 1 }
{
"type": "response",
"id": "msg-001",
"agent": "assistant",
"response": "The weather in New York is sunny.",
"token_usage": { "prompt_tokens": 45, "candidates_tokens": 15 }
}Session Persistence
Each connection creates a unique session for conversation history. Send multiple messages in the same session and the agent remembers context. Closing the connection ends the session.
Python Example
import asyncio
import websockets
import json
async def chat():
uri = "<websocket-url>"
async with websockets.connect(uri) as ws:
# Authenticate
await ws.send(json.dumps({"secret": "<your-secret-key>"}))
response = await ws.recv()
print(f"Connected: {json.loads(response)}")
# Send message
await ws.send(json.dumps({"message": "Hello!"}))
# Receive streaming response
while True:
msg = await ws.recv()
data = json.loads(msg)
if data["type"] == "stream_chunk":
print(data["chunk"], end="", flush=True)
elif data["type"] == "stream_end":
print(f"\nDone! Tokens: {data['token_usage']}")
break
asyncio.run(chat())Install with pip install websockets
Connection Features
- Ping/Pong keepalive, graceful close, session timeout, message limits