Websocket Chat

You can chat with an agent using websockets. The most common use case is to host a chatbot on your website. These steps will walk you through the process of opening a websocket connection to an agent and then sending messages back and forth.

First, ensure that you have an agent provisioned. If you don’t have one, you can provision one using the POST /v1/agents endpoint.

Create a Channel

Each time a new user connects to your chatbot, you’ll need to create a channel for their chat. If your users are authenticated with the Flockx platform, you can re-use their existing channel when they connect later. If your users are not authenticated with Flockx, you’ll need to create a new channel every time.

To create a channel, you can use the POST /v1/channels endpoint. For example:

1POST /v1/channels HTTP/1.1
2Authorization: Bearer YOUR_API_KEY
3Content-Type: application/json
4
5{
6 "name": "My Chat Channel",
7 "type": "websocket",
8 "participants": [
9 {
10 "type": "agent",
11 "id": "78fb4a08-049f-4e5d-888b-f3a43b1be68a"
12 },
13 {
14 "type": "non_authenticated_user",
15 "user_metadata": { "browser": "chrome" }
16 }
17 ]
18}

Generate a Websocket Ticket

To prevent unauthorized access, you must provide a websocket ticket when opening a websocket connection that proves the user has access to the channel.

To generate a websocket ticket, you can use the POST /v1/channels/{channel_id}/websocket_tickets endpoint. For example:

1POST /v1/channels/123e4567-e89b-12d3-a456-426614174000/websocket_tickets HTTP/1.1
2Authorization: Bearer YOUR_API_KEY

The ticket will only be valid for 1 minute so you’ll need to generate a new one each time you open a new connection.

Open a Websocket Connection

Once you have a channel, you can open a websocket connection to it using the id from the channel creation response, and the ticket value from the websocket ticket creation response.

1const CHANNEL_ID = '123e4567-e89b-12d3-a456-426614174000';
2const TICKET = '35f80a1480bd4fe49dcf1cd07e5c9668';
3
4const ws = new WebSocket(`wss://api.flockx.com/v2/websockets/${CHANNEL_ID}?ticket=${TICKET}`);

If you provide an invalid channel ID, or an invalid/expired ticket, the server will close the connection with a 1008 error and a message indicating the issue.

Begin Chatting

You’ll need to register a message event listener that is responsible for rendering the messages in your chat UI. Note that user messages are echoed back on the websocket, so you’ll need to check the role_type to determine if the message is from the user or the AI agent.

1export enum RoleType {
2 HUMAN = 'human',
3 AI = 'ai'
4}
5
6ws.addEventListener('message', (event: MessageEvent) => {
7 const data = JSON.parse(event.data);
8 console.log('WebSocket message received:', data);
9
10 if (data.role_type === RoleType.HUMAN) {
11 console.log('Human message received:', data.text);
12 // Render human message in chat UI
13 }
14
15 if (data.role_type === RoleType.AI) {
16 console.log('AI message received:', data.text);
17 // Render AI agent response in chat UI
18 }
19});

When the user types a message into your chat UI, you’ll need to send a message on the websocket.

1import { v4 as uuid } from 'uuid';
2
3// This should be the ID of the agent for the channel
4const AGENT_ID = '123e4567-e89b-12d3-a456-426614174000';
5
6const sendMessage = (userMessage: string) => {
7 const messageId = uuid();
8 const timestamp = new Date().toISOString();
9
10 // Send messages from the user to the AI agent
11 const messageEvent = {
12 id: messageId,
13 source: 'websocket',
14 type: 'message',
15 role_type: RoleType.HUMAN,
16 text: userMessage,
17 twin_id: AGENT_ID,
18 session_id: CHANNEL_ID,
19 created_at: timestamp,
20 metadata: {},
21 };
22
23 ws.send(JSON.stringify(messageEvent));