Instance methods
Instance methods enable your code to interact with or modify an active chat instance at run time.
Contents
Overview
List of methods and properties
Instance method and property details
Instance elements
Instance writeable elements
Custom panels
Overview
When your AI chat loads, it returns an instance
object for runtime interaction with the chat. The initialized AI chat instance supports runtime utility methods your code uses to render the AI chat widget, send a message, or subscribe to events.
List of methods and properties
The following list shows all the available instance methods and properties.
Method or Property | Description |
---|---|
Server Customization | |
addMessage | Adds a new incoming/received message to the chat. |
addMessageChunk | Adds a new incoming/received message chunk to the chat for a streaming message. |
clearConversation | Removes all messages from the chat. |
insertHistory | Inserts the historical messages into the chat. |
removeMessages | Removes the messages from the chat. |
Messages | |
doAutoScroll | Scrolls to the most recent message in the list. |
restartConversation | Restarts the conversation with the assistant. |
scrollToMessage | Scrolls the AI chat messages list to the message. |
send | Sends the specified message to the assistant. |
updateHistoryUserDefined | Updates the value of a user_defined property in the history of a message. |
Events | |
off | Removes a subscription to an event type. |
on | Subscribes to a type of event. |
once | Subscribes an event handler as a listener for only one occurrence of the specified event type. |
Human agent | |
serviceDesk.endConversation | Ends the conversation with a human agent. |
Security and identity | |
destroy | Destroys the AI chat and removes it from the page. |
destroySession | This method removes all browser storage related to the current AI chat session. |
Tours | |
tours.endTour Beta | Clears all tour data, closes the tour, and switches to the launcher. |
tours.goToNextStep Beta | Moves forward one step in the tour. |
tours.goToStep Beta | Moves to the step in the tour that has a matching step_id. |
tours.startTour Beta | Sends a message request then switches to the tour view after receiving the new tour data from the request. |
User interface | |
changeView | Changes the current view state. |
customPanels | Returns an object that can be used to control custom panels. |
elements | A list of elements that the AI chat provides limited access to. |
render | Renders the AI chat widget on your page. |
requestFocus | When the application is open, an appropriate focusable and visible element has focus. |
showLauncherGreetingMessage | Sets the time for the greeting message to appear from the launcher. |
updateAssistantInputFieldVisibility | Allows you to hide or show the input field when conversing with the assistant. |
updateBotUnreadIndicatorVisibility | Updates the visibility of the custom unread indicator that appears on the launcher. |
updateCSSVariables | Overrides the configurable CSS variables used to render the AI chat. |
updateCustomMenuOptions | Updates the display of custom menu options that appear in the header. |
updateHomeScreenConfig | Updates the configuration for the home screen. |
updateIsTypingCounter | Changes the internal counter that determines whether to show the "is typing" indicator. |
updateLanguagePack | Updates the language pack used for displaying message strings. |
updateLocale | Changes the current locale that the widget uses. |
updateMainHeaderAvatar | Changes the avatar image in the chat header. |
updateMainHeaderTitle | Changes the name of the assistant in the header. |
updateLauncherAvatarURL | Updates the launcher avatar image. |
updateLauncherGreetingMessage | Sets the greeting message for the launcher. |
writeableElements | A list of container elements where you can attach custom elements. |
AI chat state | |
getIntl | Returns the object that the AI chat uses for displaying static translated strings. |
getLocale | Returns the current locale that the widget uses. |
getState | Returns properties representing the current state of the AI chat. |
getWidgetVersion | Returns the version number of the widget code. |
Instance method and property details
instance.messaging.addMessage(message)
This method adds a new incoming/received message to the chat. Use this method when a new message has been constructed and should be displayed to the user. It can only be used to display messages "received" by the user. It cannot be used to display user created or "sent" messages. It should not be used to add old historical messages into the chat; insertHistory should be used for that.
When you call this method, it fires the pre:receive and receive events as well as the userDefinedResponse event for any user_defined
items in the message.
The message expected here is a MessageResponse. If an id
is not included in the message, the AI chat generates one.
This method returns a Promise which resolves after the message has been added and the receive events have been completed.
Parameter | Type |
---|---|
message | MessageResponse |
Example
await instance.messaging.addMessage({
output: {
generic: [
{
response_type: 'text',
text: 'This is a message to the user',
},
],
},
});
instance.messaging.addMessageChunk(chunk)
This method adds a new incoming/received message chunk to the chat for a streaming message. A message has a response_id
. This message can contain individual message items, which also have their own unique IDs.
The instance.messaging.addMessageChunk
method takes chunks of the following three different types:
partial_item
The partial_item
type is an individual message item chunk. It is the latest chunk of an individual message item and the AI chat handles joining with previous chunks. The chunk is a PartialItemChunk with a partial GenericItem inside it. For more information, see FinalResponseChunk.
complete_item
The complete_item
type is the final complete message item. This does not have to match the total values of the partial_item
chunks that have been sent. For more information, see CompleteItemChunk.
final_response
The final_response
type is the full message with all individual completed message items. The content of this response does not have to match the original stream. For more information, see FinalResponseChunk.
The AI chat expects an additional streaming_metadata: { response_id: 'xyz' }
object at the root of the chunk for partial_item
and complete_item
chunks which contain the unique ID assigned to the final completed response. This is different from the IDs assigned to each individual item in the response that each chunk represents. The final_response
chunk provides the ID as the id
property on the final response object.
If the chunk is a final_response
, it also fires the same events that fire when the AI chat receives a message response in the case of addMessage.
This method returns a Promise which resolves after the AI chat adds the chunk. If the chunk is a final_response
, the Promise resolves after the pre:receive
and receive
events complete.
Parameter | Type | Description |
---|---|---|
chunk | Object |
PartialChunkItem or CompleteItemChunk or FinalResponseChunk |
Canceling a stream
If you include streaming_metadata.cancellable
on the PartialItemChunk it will enable the button to stop streaming. If the button is pressed, the stopStreaming event will be thrown.
When the stream is cancelled, streaming_metadata.stream_stopped
should be set to true on the CompleteItemChunk and FinalResponseChunk.
For more information, see ItemStreamingMetadata.
Example
// Add the first partial_item chunk when streaming starts.
await instance.messaging.addMessageChunk({
partial_item: {
response_type: 'text',
text: 'Streaming',
streaming_metadata: {
id: '1',
cancellable: true, // marks it able to be cancelled which turns on the stop streaming button.
},
},
streaming_metadata: {
response_id,
},
});
// Add a second partial_item chunk that adds more content to the message item.
await instance.messaging.addMessageChunk({
partial_item: {
response_type: 'text',
text: ' is cool!',
streaming_metadata: {
id: '1',
cancellable: true,
},
},
streaming_metadata: {
response_id,
},
});
// When the item is complete, add a complete_item chunk to show a full version
// of the item. Note that this allows the item content to be changed.
await instance.messaging.addMessageChunk({
complete_item: {
response_type: 'text',
text: 'Streaming is cool! (complete)',
streaming_metadata: {
id: '1',
stream_stopped: false,
},
},
streaming_metadata: {
response_id,
},
});
// When the entire stream is done, use a final_response chunk to display the
// final complete response that has all the items in it. Note that this allows
// the item content to be changed again.
await instance.messaging.addMessageChunk({
final_response: {
id: response_id,
output: {
generic: [
{
response_type: 'text',
text: 'Streaming is cool! (final)',
streaming_metadata: {
id: '1',
stream_stopped: false,
},
},
],
}
},
});
instance.messaging.clearConversation()
This method removes all messages from the chat. It performs the same operations as restartConversation except that it does not attempt to reload any initial state for the chat; in particular, it does not display the home screen or make a request for the welcome message and leaves the chat empty.
Example
await instance.messaging.clearConversation();
instance.messaging.insertHistory(historyItems[])
This method inserts the historical messages into the chat. It fires the history:begin and history:end events. Any existing messages in the chat are inserted before them.
The array of messages contains messages following the format:
interface HistoryItem {
/**
* The v2 message request or response object.
*/
message: MessageRequest | MessageResponse;
/**
* Time this interaction occurred in ISO Format (e.g 2020-03-15T08:59:56.952Z).
*/
time: string;
}
Parameter | Type | Description |
---|---|---|
historyItems[] | Array of HistoryItem |
An array of HistoryItem objects to insert into the chat. |
Example
await instance.messaging.insertHistory([
{
message: {
id: crypto.randomUUID(),
input: {
text: 'Message from user',
}
},
time: new Date().toISOString(),
},
{
message: {
id: crypto.randomUUID(),
output: {
generic: [
{
response_type: 'text',
text: 'Response from the server',
},
],
},
},
time: new Date().toISOString(),
},
]);
instance.messaging.removeMessages(ids[])
This instance removes the messages from the chat. The array passed to this method contains the string IDs associated with messages that the AI chat removes from the chat. The IDs are full message responses or requests, not the individual message items in (streaming_metadata.id).
No events fire from this method.
Example
Parameter | Type | Description |
---|---|---|
ids[] | Array of String |
An array of the IDs of messages to remove. |
await instance.messaging.removeMessages(['aefbe9c7-72ec-443e-ad3d-3666dc57f039']);
instance.agentEndConversation()
This method ends the conversation with a human agent. It does not request confirmation from the user first. This function has no effect, if the user does not connect or is not connecting to a human agent. You can determine if the user connects or is connecting by calling getState. Note that this function returns a Promise that only resolves when the conversation has ended; this includes after the agent:pre:endChat and agent:endChat events have been fired and resolved.
Example
const state = instance.getState();
if (state.serviceDesk.isConnected || state.serviceDesk.isConnecting) {
await instance.agentEndConversation();
}
instance.serviceDesk.endConversation()
This method ends the conversation with a human agent. It does not request confirmation from the user first. This function has no effect, if the user does not connect or is not connecting to a human agent. You can determine if the user connects or is connecting by calling getState. Note that this function returns a Promise that only resolves when the conversation has ended; this includes after the agent:pre:endChat and agent:endChat events have been fired and resolved.
Example
const state = instance.getState();
if (state.serviceDesk.isConnected || state.serviceDesk.isConnecting) {
await instance.serviceDesk.endConversation();
}
instance.changeView()
Changes the current view state. You can use it to open or close the main window or to open or close a tour.
This function has the following two forms:
-
First form: Passes the name of the view as a string to open. The view opens and all other views close.
-
Second form: Passes an object with the names of the views to change. The state of each included view changes to the state, while others views stay the same. Any views that do not pass don't change.
The current view names:
launcher
: The button at the bottom of the screen that opens the main window.mainWindow
: The main window of AI chat that displays messages with the user.tour
: The window that displays the contents of an active tour.
This method fires the view:pre:change and view:change events.
Example
// Opens the main window and closes all the other views.
instance.changeView('mainWindow');
// Opens the main window and closes the launcher. The tour view remains unchanged.
instance.changeView({ mainWindow: true, launcher: false });
instance.closeWindow()
This method closes the chat window if it is currently open, and fires the window:close event.
Example
instance.closeWindow();
instance.destroy()
This method destroys the AI chat widget, including the chat window and chat launcher. It removes all event subscriptions and all methods on the instance.
Also, to keep a subsequently created AI chat from trying to continue the previous session, you should also call instance.destroySession before calling this method.
Example
instance.destroy();
instance.destroySession()
AI chat stores information about the current session in the browser. This method removes all browser storage related to the current AI chat session. It also issues a call to the server to remove the session from the server. You can call this method as part of your logout sequence to avoid a user's AI chat from trying to reconnect to the previous user's session.
Stop using the AI chat instance after making the call if the call does not occur during the window unload process. Call instance.destroy to destroy the AI chat instance and remove it from the page.
Example
instance.destroySession();
instance.doAutoScroll()
This method automatically scrolls to the most recent message in the list. It helps when you render a user_defined
response type after the AI chat has already completed its autoscroll behavior, and you need the AI chat to correct itself.
Example
instance.doAutoScroll();
instance.getIntl()
This method returns the object that the AI chat uses for displaying static translated strings. It is an instance of a IntlShape
that the Format.JS library provides. You can find the out-of-the-box strings that the AI chat uses in the languages folder. Make sure to access the files for the version of the AI chat that you use.
Note: A new IntlShape
object generates every time the locale or language pack updates.
Example
const placeholderText = instance.getIntl().formatMessage({ id: 'input_placeholder' });
instance.getLocale()
This method returns the current locale in use by the widget. It returns a string containing the language code or the language and region codes (for example, ja
or en-gb
).
Example
console.log(instance.getLocale());
instance.getState()
Returns properties representing the current state of the AI chat.
Parameter | Type | Description |
---|---|---|
isAssistantInputFieldVisible | Boolean |
Indicates whether the input field is visible when the user is talking to assistant. |
isDebugEnabled | Boolean |
Indicates if the debug flag for the AI chat is set to true . |
isHomeScreenOpen | Boolean |
Indicates if the home screen is open. |
isTourActive Beta | Boolean |
Indicates whether there currently is an active tour. This can be true even if a tour isn't visible. If there is an active tour but the launcher or main chat window are visible then the tour appears upon launcher click or minimize of the main chat window. |
isWebChatOpen | Boolean |
Indicates whether the AI chat is currently in an open state. |
hasUserSentMessage | Boolean |
Indicates whether the user sends a message. |
serviceDesk.isConnected | Boolean |
Indicates whether the AI chat is currently connected with a human agent. |
serviceDesk.isConnecting | Boolean |
Indicates if the AI chat has requests to be connected to a human agent but an agent has not yet joined the conversation. |
viewState | Object |
Indicates the current state of all the views. See changeView for a list of the possible view. |
Example
instance.getState();
instance.getWidgetVersion()
This method returns the version number of the widget code.
Example
instance.getWidgetVersion();
instance.off()
This method removes a subscription to an event type. After you remove a subscription, the callback handler does not call for the event type. It returns the instance itself, for chaining purposes.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
options | Object |
Required | The method options. | |
options.type | string |
Required | The event type you no longer want to listen for (for example, * or send ). For more information, see Events. |
|
options.handler | function |
Optional | The reference to the callback you want to unsubscribe. Specify this parameter to indicate which callback you want to unsubscribe, if you have subscribed multiple callbacks to the same event type. By default, it removes all subscriptions registered to the event type. |
Example
// Your handler
function handler(event) {
console.log(event);
}
instance.on({ type: 'receive', handler: handler });
instance.on({ type: 'send', handler: handler });
instance.off({ type: 'receive', handler: handler });
instance.off({ type: 'send', handler: handler });
// You can also pass AN ARRAY of objects to the method
instance.on([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
instance.off([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
// You can also just "unsubscribe from all" by not passing a handler
instance.on({ type: 'send', handler: handler });
instance.off({ type: 'send' });
instance.on()
This method subscribes to a type of event using a callback that calls whenever it fires a specified event type. You can register as many subscriptions to an event type as you want. Subscriptions are called in order, starting with the first registered.
This method returns the instance itself, for chaining purposes.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
options | Object |
Required | Method options. | |
options.type | string |
Required | The event to listen to (for example, * or send ). For more information, see Events. |
|
options.handler | function |
Required | The callback that handles the event. |
Example
// Your handler
function handler(event) {
console.log(event);
}
instance.on({ type: 'receive', handler: handler });
instance.on({ type: 'send', handler: handler });
// You can also pass AN ARRAY of objects to the method
instance.on([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
instance.once()
This method subscribes an event handler as a listener for only one occurrence of the specified event type. After handling one event of the specified type, this handler automatically unsubscribes.
This method returns the instance itself, for chaining purposes.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
options | Object |
Required | The method options. | |
options.type | string |
Required | The event type to listen for (for example, * or send ). For more information, see Events. |
|
options.handler | function |
Required | The callback that handles the event. See Events. |
Example
function handler(event) {
console.log(event);
}
const mockSendObject = {
input: {
message_type: 'text',
text: 'get human agent'
}
};;
instance.once({ type: 'send', handler: handler });
instance.send(mockSendObject);
// The subscription is now removed.
// You can also pass AN ARRAY of objects to the method
instance.once([
{ type: 'receive', handler: handler },
{ type: 'send', handler: handler }
]);
instance.openWindow()
This method opens the chat window if it is currently closed, and fires the window:open event.
Example
instance.openWindow();
instance.requestFocus()
When the application is open, an appropriate focusable and visible element gets focus.
Example
instance.requestFocus();
instance.render()
This method renders the AI chat widget on your page. It returns a Promise that succeeds if the widget successfully renders.
Example
instance.render().then(function() {
console.log('It worked!')
}).catch(function(e) {
console.error(e);
});
instance.restartConversation()
This method restarts the conversation with the assistant and ends any conversation with a human agent. It clears all of the current assistant messages from the main bot view and cancel any outstanding messages. This also deletes the current assistant session which forces a new session to start on the next message.
This method also fires the pre:restartConversation and restartConversation events.
Once the restart is complete, the AI chat switches to the home screen or request the welcome message to be displayed again.
Example
instance.restartConversation();
instance.scrollToMessage()
This method scrolls the AI chat messages list to the message. The top of the message scrolls to the top of the message list. The ID of the message can be obtained using one of the receive
, pre:receive
, send
, pre:send
, history:begin
or history:end
events depending on where the message came from.
Parameter | Type | Description |
---|---|---|
messageID | String |
Indicates the message ID |
animate (optional) | boolean |
Indicates if the scrolling is animated. |
Example
instance.scrollToMessage('8cf22fcd-f3d1-4eee-9aea-26d14e87e481');
instance.send()
This method sends the specified message to the assistant. This results in pre:send and send events being fired.
This method returns a Promise that resolves successfully when the message is successfully sent.
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object or String |
Required | Indicates a v2 message request object or a string. If you provide a string, it automatically creates a v2 message object that uses the string as the text of the message. (For more information, see the API Reference.) | |
options | Object |
Method options. | ||
options.silent | Boolean |
Indicates whether the message hides from the UI. If this option is set to true , the message is sent to the assistant, but does not appear in the AI chat UI. |
||
options.skipPause | Boolean |
Indicates if the forced pause displayed with the response skips. By default, the AI chat inserts a pause to produce a delay of 1 second after it receives the response. This gives the bot a more natural, conversational feeling. This value defaults to true if you call this function while the AI chat is closed. |
Examples
A simple text message.
instance.send('get a human agent');
A message request using the message request object format and with a silent option so the message request is not visible to the user. Note, send always returns a Promise but it's particularly important when a silent message is sent to catch any errors from the Promise and notify the user about them since it may not be obvious in the chat that the message has failed.
const sendObject = {
input: {
message_type: 'text',
text: 'get a human agent'
}
};
const sendOptions = {
silent: true
}
instance.send(sendObject, sendOptions).catch(console.error);
A message that sets a context variable. Replace ['main skill'].user_defined
with ['actions skill'].skill_variables
if you are using Actions instead of Dialog.
const sendObject = {
input: {
message_type: 'text',
text: 'get a human agent'
},
context: {
skills: {
['main skill']: {
user_defined: {
custom_var: 'My custom variable',
}
}
}
}
};
instance.send(sendObject);
instance.showLauncherGreetingMessage()
This method controls the timing of when the greeting message appears. The default behavior is that the greeting message appears after 15 seconds. If the greeting message is already visible, then it ignores any new set times. If the greeting message is visible to the user when the page changes or reloads, the greeting message remains visible when reloading. The updated timing does not save in the session storage, if the user changes pages or reloads the page before the greeting message appears. The updated timing needs to be set again. This can not be used to change the greeting text of the launcher. If you want to change the text use instance.updateLauncherGreetingMessage()
Parameter | Type | Required | Description |
---|---|---|---|
time | Number |
Optional | The number of milliseconds until the launcher should display the greeting message. For example passing 4000 would imply that the greeting message should be shown four seconds from now. If no time passes, then the greeting message appears immediately. |
launcherType | String |
Optional | There are two different launchers that appear depending on the end users device type, a desktop and a mobile launcher. launcherType can be used to specify which launcher the new timing should be set for, valid options are either mobile or desktop . If no launcherType passes then the timing sets for both. |
Example
// To show the desktop launcher in 4s (the mobile launcher shows at the original 15s interval).
instance.showLauncherGreetingMessage(4000, 'desktop')
// To show the mobile launcher in 6s (the desktop launcher would still plan to show in 4s).
instance.showLauncherGreetingMessage(6000, 'mobile')
// To show both the desktop and mobile launcher 8s from now (the previous timers would be cleared).
instance.showLauncherGreetingMessage(8000)
instance.toggleOpen()
This method toggles the current open or closed state of the window.
Example
instance.toggleOpen();
instance.tours.endTour() Beta
This method clears all tour data, closes the tour, and switches to the launcher. When the user clicks the launcher, the main chat window opens. The user can start the tour again with the tour card from the chat window.
instance.tours.goToNextStep() Beta
This method moves to the next step in the tour. When the next step is switched to the tour:step event fires.
instance.tours.goToStep() Beta
This method accepts a string for the stepId
that the tour goes to. This tour json defines the step_id
as a step_id
string. When the tour switches to the new step, the tour:step event fires.
Example
// Switch to the step in the tour that is labeled as step_id: "welcome_3" in the tour json.
instance.tours.goToStep('welcome_3');
instance.tours.startTour() Beta
This method accepts a message
string that sends data to the back end to get a new tour. Once the tour data returns, the tour view switches automatically. When the tour switches, the tour:start event fires.
Example
// Send a message that corresponds to a "welcome tour" action and returns to show the tour data.
instance.tours.startTour('welcome tour');
instance.updateAssistantInputFieldVisibility()
This method allows you to hide or show the input field when conversing with the assistant. It applies when your assistant requires input via buttons or other constrained input. This does not apply to the input field for conversing with a human agent.
Parameter | Type | Description |
---|---|---|
shouldBeVisible | Boolean |
If the input fields to write to the assistant should be visible. |
Example
instance.updateAssistantInputFieldVisibility(true); // Shows input field.
instance.updateAssistantInputFieldVisibility(false); // Hides input field.
instance.updateBotUnreadIndicatorVisibility()
This method updates the visibility of the custom unread indicator that appears on the launcher. It appears as an empty circle on the launcher and remains visible until the AI chat opens.
This indicator is in addition to the indicator for unread messages from a human agent. If there are any unread agent messages, a circle appears with the unread count inside of it and it appears regardless if you call this method.
You can adjust the colors of this indicator by using the updateCSSVariables method.
Parameter | Type | Required | Description |
---|---|---|---|
isVisible | boolean |
Required | A value of true shows the indicator and false hides it (unless unread agent messages exist). |
Example
// Show the indicator.
instance.updateBotUnreadIndicatorVisibility(true);
// Hide the indicator.
instance.updateBotUnreadIndicatorVisibility(false);
instance.updateCSSVariables()
This method overrides the configurable CSS variables used to render the AI chat. You can pass in as many variables as you want to override. The values you specify merge with the existing settings. You can also visit the section on Theming for more information.
Warning: The AI chat provides many hooks to amend and change content, and the AI chat uses HTML, CSS, and JavaScript for its build. Avoid manipulating content outside the default configuration to prevent unintended issues when the AI chat deploys new releases.
Example
instance.updateCSSVariables({
'BASE-z-index': '8000',
'BASE-font-family': '"Times New Roman", Times, serif',
'$focus': '#ff0000'
});
Customizable variables
Parameter | Type | Default | Description |
---|---|---|---|
BASE-font-family | String |
'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serif | The font family the AI chat uses. |
BASE-header-font-family | String |
'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serif | The font family the AI chat uses in the header. |
BASE-height | CSS height value |
640px | The default value the AI chat sets its height to. AI chat also has a default max-height of 640px on desktop devices. If you want a height greater than this, you need to change BASE-max-height as well. |
BASE-max-height | CSS height value |
640px | The default max value the AI chat sets its height to on desktop devices. On mobile devices, the AI chat resizes to fill the screen. |
BASE-width | CSS width value |
380px | The default value the AI chat sets its width to. On mobile screens, or if you use a custom element, the AI chat grows to the size of the respective container instead of this width. |
BASE-z-index | Number |
99999 | The z-index on your website that the AI chat is assigned to. |
HOME_SCREEN-greeting-font-family | String |
'IBM Plex Sans', 'Helvetica Neue', Arial, sans-serif | The font family used by the main greeting message on the home screen. |
UNREAD-INDICATOR-color-background | Hex color code |
#da1e28 | The background color of the launcher unread indicator. |
UNREAD-INDICATOR-color-text | Hex color code |
#ffffff | The color of the text that appears on the launcher unread indicator. |
$chat-button | Hex color code |
#000000 in white and g10 themes, #ffffff in g90 and g100 themes | The border and text color of the rounded buttons with transparent backgrounds that are used throughout the home screen and main chat window. These chat buttons are in beta within carbon so these properties aren't currently documented within their docs. |
$chat-button-hover | Hex color code |
#8c8c8c1f in white and g10 themes, #8c8c8c29 in g90 and g100 themes | The background color of the rounded buttons with transparent backgrounds when you hover. |
$chat-button-text-hover | Hex color code |
#525252 in white and g10 themes, #f4f4f4 in g90 and g100 themes | The text color of the rounded buttons with transparent backgrounds when you hover. |
$chat-button-selected | Hex color code |
#8c8c8c33 in white and g10 themes, #8c8c8c3d in g90 and g100 themes | The background color when one of the rounded buttons with transparent backgrounds is selected. |
$chat-button-active | Hex color code |
#8c8c8c80 in white and g10 themes, #8c8c8c66 in g90 and g100 themes | The background color when one of the rounded buttons with transparent backgrounds is active. |
$chat-button-text-selected | Hex color code |
#525252 in white and g10 themes, #c6c6c6 in g90 and g100 themes | The text color when one of the rounded buttons with transparent backgrounds is selected. |
Customizable launcher variables
You can override the pre-configured color variables for the AI chat launcher and desktop launcher expanded message.
Parameter | Type | Description |
---|---|---|
LAUNCHER-color-avatar | Hex color code |
The color of the default launcher avatar. |
LAUNCHER-color-background | Hex color code |
The background color of the default launcher. |
LAUNCHER-color-background-active | Hex color code |
The background color of the default launcher in the active state. |
LAUNCHER-color-background-hover | Hex color code |
The background color of the default launcher in the hover state. |
LAUNCHER-color-focus-border | Hex color code |
The border color of the launcher in the focus state. |
LAUNCHER-EXPANDED-MESSAGE-color-background | Hex color code |
The background color of the desktop launcher expanded message. |
LAUNCHER-EXPANDED-MESSAGE-color-background-active | Hex color code |
The background color of the desktop launcher expanded message in the active state. |
LAUNCHER-EXPANDED-MESSAGE-color-background-hover | Hex color code |
The background color of the desktop launcher expanded message in the hover state. |
LAUNCHER-EXPANDED-MESSAGE-color-text | Hex color code |
The text color of the desktop launcher expanded message. |
LAUNCHER-EXPANDED-MESSAGE-color-focus-border | Hex color code |
The border color of the desktop launcher expanded message in the focus state. |
LAUNCHER-MOBILE-color-text | Hex color code |
The text color of the mobile launcher message. |
Example
instance.updateCSSVariables({
'LAUNCHER-color-background': '#525252',
'LAUNCHER-color-background-hover': '#3d3d3d',
'LAUNCHER-color-background-active': '#1f1f1f',
'LAUNCHER-color-focus-border': '#ffffff',
'LAUNCHER-color-avatar': '#ffffff',
'LAUNCHER-EXPANDED-MESSAGE-color-background': '#ffffff',
'LAUNCHER-EXPANDED-MESSAGE-color-background-hover': '#ebebeb',
'LAUNCHER-EXPANDED-MESSAGE-color-background-active': '#cccccc',
'LAUNCHER-EXPANDED-MESSAGE-color-focus-border': '#000000',
'LAUNCHER-EXPANDED-MESSAGE-color-text': '#000000',
'LAUNCHER-MOBILE-color-text': '#000000',
});
await instance.render();
Customizable theming variables
For a complete list of theming variables and their default values, see the Carbon Design System documentation. To customize the appearance of your AI chat, use the instance.updateCSSVariables() method to override the theming variables you want to change. Color values must be in hexadecimal format.
Example
instance.updateCSSVariables({ '$focus': '#ff0000' });
await instance.render();
instance.updateCustomMenuOptions()
This method updates the display of custom menu options that appear in the header. These options display in a hamburger menu that appears in the top left corner of the header. You can call this method anytime to change the current set of options. Each option is configurable with a custom callback function that calls when the option is selected.
Parameter | Type | Required | Description |
---|---|---|---|
options | array |
Required | An array of options to display. Each value of the array is an object that has the text to display for the menu option label as well as a function that is the click handler to be called when the option is selected. |
options[n].text | string |
Required | The text to display for this option. |
options[n].handler | function |
Required | A function that calls when you select the option. |
Example
instance.updateCustomMenuOptions([
{ text: 'Bot option 1', handler: () => console.log(`Selected Bot option 1`) },
{ text: 'Bot option 2', handler: () => console.log(`Selected Bot option 2`) },
]);
instance.updateHistoryUserDefined()
This method provides a way to save state for any message response. This saved state is available in the history.user_defined section of the message response on reload. The data is only saved for the duration of the user's session; once the session expires, the data deletes.
Parameter | Type | Description |
---|---|---|
messageID | String |
The messageID of the message response the data is being saved for. Depending on the event this method is being used within the messageID may come from different sources. For example in receive the id is available in event.data.id , however in userDefinedResponse the id can be found at event.data.fullMessage.id . |
data | Anything |
The data to be saved. Once it's been passed to the AI chat the data is frozen and can't be updated. However you can call this method again to save more state related to a message response. If this method is called multiple times for the same message then the data is merged in with any existing data if it's an object. It doesn't replace the entire object. |
For an example of this method in action look at the "Example with session history" in the userDefinedResponse section.
instance.addNotification() Deprecated
This method provides a way to notify the user in a way consistent with the AI chat of the results of actions that have been taken.
Parameter | Type | Description | Required |
---|---|---|---|
notification.groupId | String | The group id to associate with one or more notifications. You can use this to group notifications and remove them at once. See instance.notifications.removeNotifications()) for more information. | Optional |
notification.kind | 'error', 'info', 'success', or 'warning' | The type of notification to show. | Required |
notification.title | String |
The title that displays in the notification. | Required |
notification.message | String |
The message that displays in the system. | Required |
notification.actionButtonLabel | String |
The text displayed on an optional action button . |
Optional |
notification.onActionButtonClick | Function |
A function to call when the user clicks the action button . The notification dismisses when the user clicks the button. |
Optional |
notification.onCloseButtonClick | Function |
A function to call when the user clicks the close button . |
Optional |
Example
instance.addNotification({
kind: 'success',
title: 'Success',
message: 'You have successfully paid your bill.'
});
instance.addNotification({
kind: 'error',
title: 'Error',
message: 'Your bill was unable to be paid.',
actionButtonLabel: 'Contact us',
onActionButtonClick: () => { // Do something, notification closes on click. }
});
instance.updateHomeScreenConfig
This method turns the home screen feature on and off, and dynamically updates the home screen content. It applies when you want to have different conversation starters or welcome text on different pages of your website.
You can also control the home screen background. The home screen currently supports two options for background gradients; either a top corner out gradient, or a gradient that goes from the bottom up. You can choose between these two options, and whether or not to enable the background gradient, by editing the background_gradient
object within the homeScreenConfig.
Example
instance.updateHomeScreenConfig({
is_on: true,
greeting: 'Welcome! Please ask us a question.',
starters: {
is_on: true,
buttons: [
{
label: 'Open a new brokerage account',
},
{
label: 'Open a new savings account',
},
{
label: 'Open a new checking account',
}
]
},
background_gradient: {
is_on: true,
gradient_direction: 'bottom_up'
}
});
Parameter | Type | Required | Description |
---|---|---|---|
homeScreenConfig | Object |
Required | Defines the configuration object for a home screen. |
homeScreenConfig.is_on | boolean |
Optional | Shows a home screen when set to true . |
homeScreenConfig.greeting | text |
Optional | Provides text to introduce your assistant. |
homeScreenConfig.starters | Object |
Optional | Configures the conversation starter buttons. |
homeScreenConfig.starters.is_on | boolean |
Optional | Shows the conversation starter buttons when set to true. |
homeScreenConfig.starters.buttons[] | Object[] |
Optional | Contains an array of conversation starter button configurations. |
homeScreenConfig.starters.buttons[].label | string |
Optional | Displays text to the user in the button. It sends this text to your assistant when the user presses the button. |
homeScreenConfig.bot_avatar_url | string |
Optional | Loads the image url as the bot avatar on home screen. |
homeScreenConfig.custom_content_only | boolean |
Optional | Hides the avatar, greeting message, and starters so you can provide you own custom home screen. |
homeScreenConfig.background | 'none', 'solid', 'top_corner_out', 'bottom_up' | Optional | Configures the background. 'none' keeps the home screen background the same color as the chat background. 'solid' uses the accent color for the home screen background. 'top_corner_out' and 'bottom_up' are both gradient backgrounds for the home screen that fade from the accent color to the chat background color. These fades start from either the top corner, or the bottom of the home screen, depending on the selected gradient option. |
instance.updateIsTypingCounter()
This method changes the internal counter that controls the visibility of the "is typing" indicator. This indicator displays an animated "..." that lets the user know the assistant is "typing" a message. Based on an internal counter, this indicator increases when an action qualifies as "is typing" and decreases when the action completes. The indicator remains visible as long as this counter is greater than zero. Use this function to increase or decrease this counter (but not below zero).
To increase the counter, pass the argument increase
to the method. To decrease the counter, pass the argument decrease
to the method.
Ensure that if you increase the counter, you always decrease it, even in the event of an error. If you fail to decrease the counter, the indicator becomes stuck permanently.
Example
// Show the indicator.
instance.updateIsTypingCounter('increase');
// Hide the indicator.
instance.updateIsTypingCounter('decrease');
instance.updateMainHeaderAvatar()
This method lets you updates the avatar image displayed in the header of the main bot panel. By default there is no avatar image in the main header.
Parameter | Type | Required | Description |
---|---|---|---|
headerAvatarConfig | Object |
The configuration object to set the chat header image. | |
headerAvatarConfig.url | String |
Required | The image url to display in the chat header. |
headerAvatarConfig.corners | String |
Optional | The type of corner style to give the image. The possible values are: 'square' , 'round' |
Example - Adding a new chat header avatar
instance.updateMainHeaderAvatar({
source: 'CUSTOM_AVATAR_URL',
corners: 'round',
});
Example - Setting an empty chat header avatar
instance.updateMainHeaderAvatar();
instance.updateMainHeaderTitle()
This method updates the string shown in the header of the chat to signify the name of the assistant.
Example - Adding a new title
instance.updateMainHeaderTitle('Larry the Assistant');
Example - Setting an empty title
instance.updateMainHeaderTitle();
instance.updateLanguagePack()
Updates the current language pack with the values from the provided language pack. This language pack does not need to be complete; only the strings it contains update, and all other strings remain unchanged. Variables used within a value string of the current language pack can be used in your updated strings. If you need to make an update based on the user's locale (e.g. British English vs US English), use getLocale to identify the current locale.
See Languages for more information.
Example
const customLanguagePack = {
errors_communicating: 'Oops, something went wrong. Refresh to try again.'
};
instance.updateLanguagePack(customLanguagePack);
instance.updateLauncherAvatarURL()
This method allows you to modify the default the AI chat launcher avatar with a custom image. The avatar renders in 32 x 32 pixels.
Example
instance.updateLauncherAvatarURL('CUSTOM_AVATAR_URL');
instance.updateLauncherGreetingMessage()
This method provides a way to update the greeting text of the launcher. We recommend limiting the number of characters to 65 on desktop, and 45 on mobile, in order to avoid truncation. The updated text does not save in session storage, if the user changes pages or reloads the page then the updated text needs to be set again. This does not cause the greeting message to be displayed. If you want to show the greeting message, use instance.showLauncherGreetingMessage()
Parameter | Type | Required | Description |
---|---|---|---|
greetingMessage | String |
Required | The new greeting text for the launcher. |
launcherType | String |
Optional | The two different launchers that appear depending on the end users device type, a desktop and a mobile launcher. launcherType can be used to specify which launcher the new greeting text should be set for, valid options are either mobile or desktop . If you do not pass a launcherType, then the greeting text sets for both. |
Example
// To update desktop text only.
instance.updateLauncherGreetingMessage('launcher text desktop', 'desktop')
// To update mobile text only.
instance.updateLauncherGreetingMessage('launcher text mobile', 'mobile')
// To update both desktop and mobile text.
instance.updateLauncherGreetingMessage('launcher text')
instance.updateLocale()
This method changes the current language and locale in use by the AI chat. See Languages for more information. By default, the locale is US English (en-us
).
The locale controls the default language strings and the format of any dates shown by the AI chat that it generated on its own (not dates you generate in your dialog skill, for instance). If you simply want to change the AI chat to use spanish, you can update the locale to es
. If you want more fine-grained control over individual strings, see instance.updateLanguagePack. If you change the locale after updating individual language strings, you lose your changes to the individual strings. It is recommended you call the updateLocale
method before you call instance.render()
.
This method returns a Promise that succeeds if the widget successfully updates the locale.
Note: After you call this function, the context.global.system.locale
context variable is set to this value on the next message that sends to the assistant.
Example
await instance.updateLocale('fr');
Instance elements
instance.elements.getMainWindow()
This method provides access to the main window of the AI chat. If you use a custom element to contain the AI chat, these functions require to show or hide the main window or to apply animations.
addClassName()
Adds the classname to the main window element.
Argument | Type | Description |
---|---|---|
className | String |
The name of the class to add to the main window element. |
removeClassName()
Removes the classname from the main window element. Only classnames added with addClassName
can be removed.
Argument | Type | Description |
---|---|---|
className | String |
The name of the class to remove from the main window element. |
Example
instance.elements.getMainWindow().addClassName('HideWebChat');
instance.elements.getMessageInput()
This method provides access to the input field that appears at the bottom of the main messages area of the main window. This field is a different object than the field that appears on the home screen.
getHTMLElement()
Returns the raw DOM element (text area) that is the input field. You can attach listeners to this element to provide custom behavior to the field. For example, you can add a keydown
listener that could navigate through a type-ahead popup using the arrow keys. You can also access the value
property of the element to get the current value in the field.
While you can add input
and change
listeners to this field, the listeners do not fire in some cases. For example, if the AI chat internally changes the value of the field (which happens when it clears the field after the user sends a message), these events do not fire. In order to ensure that you always get any change to the value of the field, use the addChangeListener function instead.
Setting the value
property of the element directly does not work. It does not trigger the internal events that the AI chat needs to respond to the change (such as enabling the send button). You should instead use the setValue elements function instead.
Also note that you cannot access the input field before it has been rendered by the AI chat. This does not occur until after chat:ready has fired. You should wait for this event using once before attempting to access the element.
setValue()
Sets the value of the input field. You should use this instead of setting the value
property directly on the HTML DOM element.
Argument | Type | Description |
---|---|---|
value | String |
The value to set in the input field. |
setEnableEnterKey()
This method changes whether the enter key is handled by the AI chat. By default, pressing enter in the input field sends the field's contents to the assistant or an agent. Setting this value to false disables this behavior. This allows you to add custom logic when the user presses this key (for example, if the user selects a highlighted value from a type-ahead popup).
Argument | Type | Description |
---|---|---|
isEnabled | boolean |
With a value of true , the AI chat sends the message when the user presses enter. With a value of false , the AI chat does not send the message. |
addChangeListener()
Adds a change listener to the input field that fires whenever the value in the field changes. This fires even in cases where a change
or input
DOM event would not.
Argument | Type | Description |
---|---|---|
listener | Function |
The listener to add. The listener passes a single argument which is the new value of the input field. |
removeChangeListener()
Removes a change listener from the input field.
Argument | Type | Description |
---|---|---|
listener | Function |
The listener to remove. |
Example
instance.once({ type: 'chat:ready', handler: () => {
const messageInput = instance.elements.getMessageInput();
messageInput.setValue('Default value');
messageInput.getHTMLElement().addEventListener('keydown', event => console.log('Got keydown', event));
messageInput.addChangeListener(value => console.log('You typed', value));
}});
instance.elements.getHomeScreenInput()
This method provides access to the input field that appears at the bottom of the home screen. This field is a different object than the field that appears on the main message area. This function returns an object that has the same functions as getMessageInput.
Instance writeable elements
AI chat provides elements available in different parts of the AI chat for you to provide custom HTML content. You can directly write to these elements or, if you use advanced frameworks like React or Angular, you can write to these elements as portals from your own application.
Example
instance.writeableElements.welcomeNodeBeforeElement.innerHTML = '<div class="my-awesome-class">Disclaimer text...</div>';
All writeable elements inject into slots within the AI chat's ShadowRoot. This means that they can be styled from global CSS and only have a very small piece part of the CSS inherited from the AI chat (font styling, etc) styles.
Element name | Description |
---|---|
headerBottomElement | Add content to the bottom of the main header when talking with the Assistant. Useful for adding dismissible banners or other content you want to remain visible even when a user scrolls. |
welcomeNodeBeforeElement | Add content above the welcome node. Useful for further introductions of your assistant or disclaimers. |
homeScreenHeaderBottomElement | Add content to the home screen below the header and above the rest of the homescreen content. Useful for replacing the avatar with custom content and leaving the rest of the homescreen as configured. |
homeScreenAfterStartersElement | Add content to the home screen below any conversation starters. Useful for additional non-text content to introduce your assistant, advertisements, or alternate forms of customer support. You can use this inconjuction with the custom_content_only option in the homescreen configuration object to take complete control of the homescreen. |
beforeInputElement | Add content that appears after the messages area when talking with the Assistant and before the input field. |
aiTooltipAfterDescriptionElement | If using the Carbon for AI theme, this element appears below the title and description in the AI tooltip in the header of the AI chat. Useful for adding additional non-text content to explain how your assistant works. |
Custom panels
AI chat provides access to panels that can take up the whole AI chat window and that can contain fully custom content. To get a custom panel, use the instance.customPanels.getPanel()
instance method.
instance.customPanels
This method returns an object that can be used to control custom panels.
Method | Description |
---|---|
instance.customPanels.getPanel() | Returns a custom panel instance. |
Custom Panel Instance
The following list shows all the available custom panel instance methods:
Method | Description |
---|---|
open |
Opens the custom panel with basic config options that change the look and feel of the panel. |
close |
Closes the custom panel if it is open. |
The following list shows all the available custom panel instance properties.
Property | Description |
---|---|
hostElement |
Returns the element that hosts your content and display it in the panel. |
customPanel.open()
This method opens the custom panel and accepts configuration options for the custom panel. It also fires a customPanel:pre:open event when its opening animation has started. Once the opening animation has ended it fires a customPanel:open event.
Example
const customPanel = instance.customPanels.getPanel();
const panelOptions = {
title: 'My custom panel',
};
customPanel.open(panelOptions);
Optional properties for the options
object:
Parameter | Type | Default | Description |
---|---|---|---|
disableAnimation | Boolean |
false | Disables the panel's opening/closing animations. |
disableDefaultCloseAction | Boolean |
false | Disables the default action, when the user clicks the close or close-and-restart buttons. The default action closes the AI chat and disabling this causes the button to not do anything. You can then override the button behavior by using the onClickClose or onClickCloseAndRestart callback. |
hideBackButton | boolean |
false | Indicates if the back button in the panel header should be hidden. This button closes the custom panel and sends the user back to the previous panel. |
hideCloseAndRestartButton | Boolean |
false | Indicates if the close-and-restart button in the panel header should be hidden. This value only applies if you enable the showCloseAndRestartButton flag in the top level AI chat config. |
hideCloseButton | Boolean |
false | Indicates if the close/minimize button in the panel header hides. This button closes and minimizes all of the AI chat window. This value is ignored if the top-levelhideCloseButton value for all of the AI chat is true . |
hidePanelHeader | Boolean |
false | Indicates if the entire panel header hides. |
onClickBack | Function |
Calls the callback when the user clicks the back button. | |
onClickClose | Function |
Calls the callback when the user clicks the close button. This calls even if disableDefaultCloseAction is set to true. |
|
onClickCloseAndRestart | Function |
Calls the callback when the user clicks the close-and-restart button. This calls even if disableDefaultCloseAction is set to true. It only calls after the user clicks the button and then confirms they wish to end the conversation. |
|
title | String |
Displays the title in the custom panel header. |
customPanel.close()
This method closes the custom panel and fires a customPanel:pre:close event when its closing animation starts. Once the closing animation has ended it fires a customPanel:close event.
Example
const customPanel = instance.customPanels.getPanel();
customPanel.close();
customPanel.hostElement
This method is the host element where you can place your content to display within the custom panel.
Example
const customPanel = instance.customPanels.getPanel();
customPanel.hostElement.innerHTML = '<div class="content-class">My awesome content!</div>';