Conversation Control
Subscribing to Events
The ConversationHandler allows your application to listen and react to updates within the Touchpoint UI conversation, such as new messages from the bot or user inputs. This enables you to build dynamic experiences, trigger custom UI changes, integrate with analytics, or perform other actions based on the conversation flow.
- How to Subscribe to Conversation Updates
- Example Use Case: Reacting to Modalities
- Unsubscribing from Events
- Working with Response Objects
How to Subscribe to Conversation Updates
You use the
conversationHandler.subscribe()
method to register a callback function. This callback is invoked whenever the conversation history changes (e.g., a new message is added).
subscribe(callback)
The
subscribe
method takes a call function that will be called with (allResponses: Response[], newResponse?: Response)
Parameter | Type | Description |
---|---|---|
allResponses | Response[] | An array containing all Response objects in the conversation history up to this point. This reflects the complete current state of the conversation. |
newResponse | Response? | The most recent Response object that triggered this specific callback invocation. It is undefined during the initial call when the subscriber first registers. |
The
subscribe
method returns a function that you can call later to unsubscribe this specific callback.
JavaScript
1<script type="module"> 2 import { create, React, html } from "https://unpkg.com/@nlxai/touchpoint-ui@1.0.5-alpha.12/lib/index.js?module"; 3 4 // Assuming 'touchpoint' is initialized as per the setup guide 5 // const touchpoint = await create({ config: { /* ... */ } }); 6 const { conversationHandler } = touchpoint; 7 8 const myConversationListener = (allResponses, newResponse) => { 9 console.log("Total messages so far:", allResponses.length); 10 11 if (newResponse) { 12 console.log("A new response was received. Type:", newResponse.type); 13 // Further processing of newResponse... 14 } else { 15 console.log("Subscription initialized. Historical messages:", allResponses); 16 } 17 }; 18 19 // Start listening to conversation updates 20 const unsubscribeListener = conversationHandler.subscribe( 21 myConversationListener, 22 ); 23 24 // To stop this specific listener later: 25 // unsubscribeListener(); 26 27</script>
Example Use Case: Reacting to Modalities
A common use for
subscribe
is to detect and act upon custom modalities sent by NLX. This example looks for the Modalities to be defined in NLX: MapDisplay
, TrackOrder
1// Assuming 'conversationHandler' is obtained 2 3const handleConversationUpdate = (allResponses, newResponse) => { 4 if (newResponse && newResponse.type === "bot") { 5 const botPayload = newResponse.payload; 6 console.log("Bot says:", botPayload.messages.map((m) => m.text).join(" ")); 7 8 // Check for a specific custom modality, e.g., "MapDisplay" 9 if (botPayload.modalities?.MapDisplay) { 10 const mapData = botPayload.modalities.MapDisplay; 11 console.log("Received MapDisplay data:", mapData); 12 // Example: Call a function to render a map on your page 13 // renderMapOnPage(mapData.latitude, mapData.longitude, mapData.zoom); 14 } 15 16 // Check for another modality, e.g., "TrackOrder" 17 if (botPayload.modalities?.TrackOrder) { 18 const orderDetails = botPayload.modalities.TrackOrder; 19 // Example: Update UI with order status 20 // displayOrderStatus(orderDetails.status, orderDetails.estimatedDelivery); 21 } 22 } else if (newResponse && newResponse.type === "user") { 23 if (newResponse.payload.type === "text") { 24 console.log("User sent text:", newResponse.payload.text); 25 // Example: Send user messages to an analytics service 26 // analytics.track("UserMessageSent", { text: newResponse.payload.text }); 27 } 28 } 29}; 30 31const unsubscribe = conversationHandler.subscribe(handleConversationUpdate); 32 33// Later, if you need to clean up: 34// unsubscribe();
Unsubscribing from Events
It's important to clean up subscriptions when they are no longer needed to prevent memory leaks and unintended behavior, especially in single-page applications or when components are unmounted.
Unsubscribing a Specific Listener
The
subscribe
method returns a function. Call this function to remove that specific listener.
1const unsubscribeMe = conversationHandler.subscribe(mySpecificCallback); 2// ... later ... 3unsubscribeMe(); // This will stop mySpecificCallback from being called
Unsubscribing All Listeners
To remove all previously registered subscribers from the
conversationHandler
:
1conversationHandler.unsubscribeAll();
Working with Response Objects
The
Response
objects provided to your callback give you detailed information about each interaction. The callback receives allResponses
(an array of all historical Response
objects) and newResponse
(the most recent Response
object, if applicable).
A
Response
object (whether in allResponses
or as newResponse
) always has a type
property that indicates its origin:
Response.type Value | Description |
---|---|
"bot" | A message or set of messages from the NLX application. |
"user" | A message or action initiated by the user. |
"failure" | An error occurred in communication with the NLX application. |
For detailed structures of these objects, refer to the Headless API Reference.
NLX Response Object Details
If the
newResponse.type
is "bot"
, its payload
contains details from NLX:
newResponse.payload Property | Type / Structure | Description |
---|---|---|
messages | BotMessage[] | An array of message objects from the bot. See BotMessage structure below. |
modalities | Record<string, any> (Optional) | An object where keys are modality names (e.g., "MapDisplay" ) and values are their data payloads. This allows for custom UI rendering or client-side actions. |
Each
BotMessage
object within the payload.messages
array has the following key properties:
BotMessage Property | Type | Description |
---|---|---|
text | string | The text content of the message. |
choices | Choice[] | An array of choice objects offered to the user. |
nodeId | string? | Identifier for the flow node that generated this message. |
messageId | string? | Unique identifier for this specific message. |
Example Application Message (Choices)
1{ 2 "type": "bot", 3 "receivedAt": 1701234567890, 4 "payload": { 5 "conversationId": "conversationId", 6 "messages": [ 7 { 8 "messageId": "messageId", 9 "nodeId": "nodeId", 10 "text": "Hello! How can I help you today?", 11 "choices": [ 12 { 13 "choiceId": "choice_product_info", 14 "choiceText": "Learn about products" 15 }, 16 { 17 "choiceId": "choice_support", 18 "choiceText": "Get support" 19 } 20 } 21 ] 22 } 23}
Example Application Message (modalities)
1{ 2 "type": "bot", 3 "receivedAt": 1701234597890, 4 "payload": { 5 "messages": [ 6 { 7 "text": "Here's your order information:", 8 "choices": [] 9 } 10 ], 11 "modalities": { 12 "OrderDetails": { 13 "orderId": "ORD-12345", 14 "status": "Shipped", 15 "trackingNumber": "1Z999AA1234567890" 16 } 17 } 18 } 19}
User Response Object Details
If the
newResponse.type
is "user"
, its payload
provides information about the user's input:
newResponse.payload Property | Type | Description |
---|---|---|
type | "text" | "choice" | "structured" | Indicates the kind of user input. |
text | string | The text entered by the user. (Present if payload.type is "text" ) |
choiceId | string | The ID of the choice selected by the user. (Present if payload.type is "choice" ) |
(Other properties) | (Varies) | For payload.type "structured" , other properties relevant to the structured request will be present. |
Example User Response (text)
1{ 2 "type": "user", 3 "receivedAt": 1701234577890, 4 "payload": { 5 "type": "text", 6 "text": "I need help with my order", 7 "context": { 8 "pageUrl": "/orders" 9 } 10 } 11}
Example User Response (choice)
1{ 2 "type": "user", 3 "receivedAt": 1701234587890, 4 "payload": { 5 "type": "choice", 6 "choiceId": "choice_support", 7 "context": {} 8 } 9}
Failure Response Object Details
If the
newResponse.type
is "failure"
, its payload
contains error information:
newResponse.payload Property | Type | Description |
---|---|---|
text | string | A description of the error or failure encountered during communication with the NLX application. |
Example Failure Message
1{ 2 "type": "failure", 3 "receivedAt": 1701234607890, 4 "payload": { 5 "text": "We encountered an issue. Please try again soon." 6 } 7}