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:
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:
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.
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.
When the user types a message into your chat UI, you’ll need to send a message on the websocket.