Categories:
Conversational context utils
Conversational context utils is an utility found in Aura Bot common library in charge of managing BotFramework TurnContext
Introduction
Conversational context utils utility allows managing BotFramework TurnContext.
Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-common/utils
It contains different methods, described in the following sections.
getAuraUser
It gets the AuraUser with the minimum BaseModel attributes and, optionally, more specific attributes of the authenticator.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Minimum BaseModel attributes:
export interface AuraUserBaseModel<T> {
auraId: string;
auraIdGlobal: string;
type: AuraUserType;
userId: string;
authData: T;
channel: ChannelConfiguration;
timestamp: number;
deviceId?: string;
accountNumber?: string;
phoneNumber?: string;
authorizationId?: string;
redirectIntent?: string;
originalAddress?: MessageUserInfo;
sessionId?: string;
idTokenHint?: string;
}
Example of use:
const auraUser = ContextUtils.getAuraUser(context);
getAuraPersistentData
It gets persistent data including information about: conversationData, userData and dialogData.
export interface AuraPersistentData {
conversationData: any;
userData: any;
dialogData: any;
}
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
const persistentData = await ContextUtils.getAuraPersistentData(stepContext.context);
if (persistentData.conversationData.orderPizza) {
orderPizza = persistentData.conversationData.orderPizza;
}
...
getCorrelator
It gets the correlator (identifier to track the request).
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channelData will be taken from |
yes |
const corr: string = ContextUtils.getCorrelator(stepContext.context);
this.logger.info({ msg: 'App GenericFaq Closed', corr });
getRecognitionResult
It gets the result of the recognition process.
⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
export interface RecognizerResult {
/**
* Utterance sent to recognizer
*/
readonly text: string;
/**
* If original text is changed by things like spelling, the altered version.
*/
readonly alteredText?: string;
/**
* Intents recognized for the utterance.
*
* @remarks
* A map of intent names to an object with score is returned.
*/
readonly intents: {
[name: string]: {
score: number;
};
};
/**
* (Optional) entities recognized.
*/
readonly entities?: any;
/**
* (Optional) other properties
*/
[propName: string]: any;
}
Example of use:
const recognitionResult: RecognizerResult = ContextUtils.getRecognitionResult(stepContext.context);
const entities = recognitionResult.entities;
getTopIntentResult
Among all the recognized intents, it gets the topIntent with the highest score and the utm information.
⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
export interface AuraIntentResult extends RecognizerResult {
topIntent: Intent;
utm: Utm;
}
Example of use:
const auraIntentResult: AuraIntentResult = ContextUtils.getAuraIntentResult(stepContext.context);
const utmInfo: Utm = auraIntentResult.utm;
getTopIntent
Among all the recognized intents, it gets the topIntent with the highest score directly.
⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
export interface Intent {
intent: string;
entities?: IEntity[];
score?: number;
type?: IntentType;
}
Example of use:
const auraIntentResult: Intent = ContextUtils.getTopIntent(stepContext.context);
getTopIntentValue
Among all the recognized intents, it gets the topIntent value in string format. For example: intent.balance.check.
⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
const intent : string = ContextUtils.getTopIntentValue(stepContext.context);
getUserChannel
It gets the user’s channel.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
export interface ChannelConfigurationPartial {
auraBotCacheTTL?: number;
id: string;
brand?: string;
dialogLibraries?: DialogLibraryConfiguration[];
name?: string;
nlp?: NlpConfig;
actions?: ChannelActions;
prefix?: string;
requestOptions?: RequestOptionsModel;
responseOptions?: ResponseOptions;
security?: Security;
whatsapp?: WhatsAppModel;
type?: BridgeType;
metadata?: DocumentMetadata;
}
export interface ChannelConfiguration extends ChannelConfigurationPartial {
brand: string;
name: string;
prefix: string;
nlp: NlpConfig;
}
Example of use:
const userChannel: ChannelConfiguration = ContextUtils.getUserChannel(stepContext.context);
getPromptRecognizedResult
It gets the recognizerResult from turnState to retrieve the value in the validator function.
This function is currently used in getRetriesValidatorAndOverwriteRecognizerResult function, used for overwrite the default recognizerResult with the result got in the prompt recognizer.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
const userChannel: PromptRecognizerResult<any> = ContextUtils.getPromptRecognizedResult(context);
setPromptRecognizedResult
It saves the recognizerResult in the turnState to retrieve the value later in the validator function.
This function is currently used in the prompt recognizer where a custom recognizeChoices is performed (including number and ordinal recognition).
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
| promptRecognizedResult | PromptRecognizerResult | Result of prompt recognition | yes |
Example of use:
const result: PromptRecognizerResult<FoundChoice> = { succeeded: false };
if (matched.length > 0) {
result.succeeded = true;
result.value = matched[0].resolution;
}
// Save personalized recognizer result
ContextUtils.setPromptRecognizedResult(context, result);
existError
It checks if an error exist and returns a boolean. (Mainly, it is designed for middlewares)
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
if (!ContextUtils.existError(context)) {
...
}
setError
It sets an error without warning the user at that time, allowing the execution of remaining middlewares. (Mainly designed for middlewares)
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
| error | Error | Error got from catch (for example) | yes |
| localMessage | string | Specific error message for logger | no |
| activityMessage | string | Specific error message for activity show to user | no |
Example of use:
try {
} catch (error) {
await ContextUtils.setError(context, error);
}
setErrorAndSendActivity
It sets an error and immediately sends a message to the user. (Mainly designed for dialogs).
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
| error | Error | Error got from catch (for example) | yes |
| localMessage | string | Specific error message for logger | no |
| activityMessage | string | Specific error message for activity show to user | no |
Example of use:
try {
} catch (error) {
await ContextUtils.setErrorAndSendActivity(context, error);
}
setHistoryConversation
It stores in Conversation Data the request and response messages. This method is deprecated.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
| activity | Partial |
Activity requested to the channel | yes |
| maxHistorySize | number | Maximum number of messages in the history | yes |
Example of use:
await ContextUtils.setHistoryConversation(
context,
activity,
ConfigurationManager.instance.environmentConfiguration.AURA_MAX_HISTORY_CHAT_ITERATIONS
);
addToHistoryConversation
It stores in Conversation Data the request and response messages.
⚠️ This method is deprecated.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
| activity | Partial |
Activity requested to the channel | yes |
| maxHistorySize | number | Maximum number of messages in the history | yes |
| isRequest | boolean | If is request | no |
Example of use:
this.addToHistoryConversation(context, activity, maxHistorySize, false);
getHistoryConversation
It returns the history conversation stored in Conversation Data.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
| loadFromRemote | boolean | Force to load the history from remote storage | yes |
| formatter | (DialogChatHistory) => string | Formatter function | no |
Example of use:
const history = await ContextUtils.getHistoryConversation(context, true,
(item: DialogChatHistory) =>
`(${getLocalFormattedIsoTime(item.date)})` +
`[${(item.type === 'request') ? User : AURA}]:${item.message}`
)
Result:
2021-3-15 15:55:02 User: Que ponen en la cuatro
2021-3-15 15:55:04 AURA: Ok, estarei aqui sempre que você precisar.
2021-3-15 15:55:08 User: Hola?
2021-3-15 15:55:09 AURA: Ok, estarei aqui sempre que você precisar.
2021-3-15 15:55:15 User: Bye
2021-3-15 15:55:16 AURA: Ok, estarei aqui sempre que você precisar.
setConversationState
It stores the conversation state in turnState.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
| conversationState | ConversationState | Conversation state to store | yes |
Example of use:
ContextUtils.setConversationState(context, this.conversationState);
saveConversationState
It saves the cached state object if it has been changed. If the force flag is passed in the cached state, the object will be saved regardless of whether it has been changed or not. If no object has been cached, an empty object will be created and then saved.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context for current turn of conversation with the user | yes |
| force | boolean | If true, the state will always be written, out regardless of its change state. By default, false. |
no |
Example of use:
await ContextUtils.saveConversationState(context, true);
loadConversationState
It reads and caches the backing state object for a turn. Subsequent readings will return the cached object, unless the force flag is passed, in which the state object to be re-read will be forced.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context for current turn of conversation with the user | yes |
| force | boolean | If true, the cache will be bypassed and the state will always be read directly from storage. By default, false. |
no |
Example of use:
await ContextUtils.loadConversationState(context, loadFromRemote);
getInternalSuggestions
It gets Aura suggestions.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context | yes |
Example of use:
const internalSuggestions: InternalSuggestions = ContextUtils.getInternalSuggestions(stepContext.context);
setInternalSuggestions
It sets Aura suggestions.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context | yes |
| internalSuggestions | InternalSuggestions | Suggestions to store | yes |
Example of use:
getUserAuthPersistentData
It gets the user’s authentication state for login/logout.
export interface IUserAuthState {
refreshCache?: boolean; // Deprecated in Vortex release
accountRemovalTimestamp?: number;
}
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
const userAuthState = await ContextUtils.getUserAuthPersistentData(stepContext.context);
getCorrelatorFromChannelData
It gets the correlator from channelData, if exists there, or creates a new one.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
const correlator = ContextUtils.getCorrelatorFromChannelData(context);
setStatus
It sets status to the response channelData object.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Current Context | yes |
| status | AuraResponseStatus | Aura Response object with the error status | yes |
| errorInfo | Error | Extra info of error. Used when the error has been triggered by another component | no |
| logAsError | boolean | Force to log the error info as logger.error. By default, false. It logs only in debug level mode |
no |
Example of use:
ContextUtils.setStatus(context, new AuraResponseStatus(AURA_STATUS.ERROR.OTHER.GENERAL));
getError
It gets the error from context.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
const error = ContextUtils.getError(context);
getRecognizer
It gets the recognizer.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the channel data will be taken from | yes |
Example of use:
const error = ContextUtils.getRecognizer(context);
setRecognizer
It sets the recognizer.
| param | type | description | mandatory |
|---|---|---|---|
| context | TurnContext | Context where the | |
channelData will set |
yes | ||
| recognizer | string | Recognizer | yes |
Example of use:
const error = ContextUtils.getSecognizer(context, recognizer);