This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
/
CLRunner.ts
1617 lines (1368 loc) · 69.7 KB
/
CLRunner.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import * as BB from 'botbuilder'
import { CLMemory } from './CLMemory'
import { BotMemory } from './Memory/BotMemory'
import { CLDebug } from './CLDebug'
import { CLClient } from './CLClient'
import { TemplateProvider } from './TemplateProvider'
import * as CLM from '@conversationlearner/models'
import { ReadOnlyClientMemoryManager, ClientMemoryManager } from './Memory/ClientMemoryManager'
import { addEntitiesById, CL_DEVELOPER, UI_RUNNER_APPID } from './Utils'
import { CLRecognizerResult } from './CLRecognizeResult'
import { ConversationLearner } from './ConversationLearner'
import { InputQueue } from './Memory/InputQueue'
import * as util from 'util'
interface RunnerLookup {
[appId: string] : CLRunner
}
export enum SessionStartFlags {
NONE = 0,
/* Start a teaching session */
IN_TEACH = 1 << 0,
/* Session is an edit and continue with existing turns */
IS_EDIT_CONTINUE = 1 << 1,
/* Session created by manual timeout by user in UI */
IS_MANUAL_TIMEOUT = 1 << 2
}
export interface InternalCallback<T> extends CLM.Callback, ICallback<T> {
}
/**
* Processes messages received from the user. Called by the dialog system.
*/
export type EntityDetectionCallback = (text: string, memoryManager: ClientMemoryManager) => Promise<void>
/**
* Called at session start.
* Allows bot to set initial entities before conversation begins
*/
export type OnSessionStartCallback = (context: BB.TurnContext, memoryManager: ClientMemoryManager) => Promise<void>
/**
* Called when Session ends.
* If not implemented all entity values will be cleared.
* If implemented, developer may return a list of entities to preserve for the next session
* as well as store them in the Bot State
*/
export type OnSessionEndCallback = (context: BB.TurnContext, memoryManager: ClientMemoryManager, sessionEndState: CLM.SessionEndState, data: string | undefined) => Promise<string[] | void>
/**
* Called when the associated action in your bot is sent.
* Common use cases are to call external APIs to gather data and save into entities for usage later.
*/
export type LogicCallback<T> = (memoryManager: ClientMemoryManager, ...args: string[]) => Promise<T | void>
// tslint:disable-next-line:no-empty
export const defaultLogicCallback = async () => {}
/**
* Called when the associated action in your bot is sent AND during dialog replay.
* Common use cases are to construct text or card messages based on current entity values.
*/
export type RenderCallback<T> = (logicResult: T, memoryManager: ReadOnlyClientMemoryManager, ...args: string[]) => Promise<Partial<BB.Activity> | string>
export const defaultRenderCallback = async (x: Partial<BB.Activity> | string) => x
export interface ICallbackInput<T> {
name: string
logic?: LogicCallback<T>
render?: RenderCallback<T>
}
interface ICallback<T> {
name: string
logic: LogicCallback<T>
render: RenderCallback<T>
}
enum ActionInputType {
LOGIC_ONLY,
RENDER_ONLY,
LOGIC_AND_RENDER
}
interface IActionInputLogic {
type: ActionInputType.RENDER_ONLY
value: string | undefined
}
interface IActionInputRenderOnly {
type: ActionInputType
}
type IActionInput = IActionInputRenderOnly | IActionInputLogic
export interface IActionResult {
logicResult: object | void
response: Partial<BB.Activity> | string | null
}
export type CallbackMap = { [name: string]: InternalCallback<any> }
export class CLRunner {
/* Lookup table for CLRunners. One CLRunner per CL Model */
private static Runners: RunnerLookup = {}
private static UIRunner: CLRunner;
public clClient: CLClient
public adapter: BB.BotAdapter | undefined
/* Model Id passed in from configuration. Used when not running in Conversation Learner UI */
private configModelId: string | undefined;
private maxTimeout: number | undefined; // TODO: Move timeout to app settings
/* Mapping between user defined API names and functions */
public callbacks: CallbackMap = {}
public static Create(configModelId: string | undefined, maxTimeout: number | undefined, client: CLClient): CLRunner {
// Ok to not provide modelId when just running in training UI.
// If not, Use UI_RUNNER_APPID const as lookup value
let newRunner = new CLRunner(configModelId, maxTimeout, client);
CLRunner.Runners[configModelId || UI_RUNNER_APPID] = newRunner;
// Bot can define multiple CLs. Always run UI on first CL defined in the bot
if (!CLRunner.UIRunner) {
CLRunner.UIRunner = newRunner;
}
return newRunner;
}
// Get CLRunner for the UI
public static GetRunnerForUI(appId?: string) : CLRunner {
// Runner with the appId may not exist if running training UI, if so use the UI Runner
if (!appId || !CLRunner.Runners[appId]) {
if (CLRunner.UIRunner) {
return CLRunner.UIRunner;
} else {
throw new Error(`Not in UI and requested CLRunner that doesn't exist: ${appId}`)
}
}
return CLRunner.Runners[appId];
}
private constructor(configModelId: string | undefined, maxTimeout: number | undefined, client: CLClient) {
this.configModelId = configModelId
this.maxTimeout = maxTimeout
this.clClient = client
}
public onTurn(turnContext: BB.TurnContext, next: () => Promise<void>): Promise<void> {
return this.recognize(turnContext, true)
.then(next);
}
public recognize(turnContext: BB.TurnContext, force?: boolean): Promise<CLRecognizerResult | null> {
// Add input to queue
return this.AddInput(turnContext).then(res => {
return res;
})
}
public async InTrainingUI(turnContext: BB.TurnContext): Promise<boolean> {
if (turnContext.activity.from && turnContext.activity.from.name === CL_DEVELOPER) {
let clMemory = CLMemory.GetMemory(turnContext.activity.from.id)
let app = await clMemory.BotState.GetApp()
// If no app selected in UI or no app set in config, or they don't match return true
if (!app || !this.configModelId || app.appId !== this.configModelId) {
return true
}
}
return false
}
// Allows Bot developer to start a new Session with initial parameters (never in Teach)
public async BotStartSession(turnContext: BB.TurnContext): Promise<void> {
// Set adapter / conversation reference even if from field not set
let conversationReference = BB.TurnContext.getConversationReference(turnContext.activity);
this.SetAdapter(turnContext.adapter, conversationReference);
const activity = turnContext.activity
if (activity.from === undefined || activity.id == undefined) {
return;
}
try {
let app = await this.GetRunningApp(activity.from.id, false);
let clMemory = await CLMemory.InitMemory(activity.from, conversationReference)
if (app) {
let packageId = (app.livePackageId || app.devPackageId)
if (packageId) {
const sessionCreateParams: CLM.SessionCreateParams = {
saveToLog: app.metadata.isLoggingOn !== false,
packageId: packageId,
initialFilledEntities: [] // LARS TODO put inti entities in here
}
await this.StartSessionAsync(clMemory, activity.conversation.id, app.appId, SessionStartFlags.NONE, sessionCreateParams)
}
}
}
catch (error) {
CLDebug.Error(error)
}
}
public SetAdapter(adapter: BB.BotAdapter, conversationReference: Partial<BB.ConversationReference>) {
this.adapter = adapter
CLDebug.InitLogger(adapter, conversationReference)
}
// Add input to queue. Allows CL to handle out-of-order messages
private async AddInput(turnContext: BB.TurnContext) : Promise<CLRecognizerResult | null> {
// Set adapter / conversation reference even if from field not set
let conversationReference = BB.TurnContext.getConversationReference(turnContext.activity);
this.SetAdapter(turnContext.adapter, conversationReference);
// ConversationUpdate messages are not processed by ConversationLearner
// They should be handled in the general bot code
if (turnContext.activity.type == "conversationUpdate") {
CLDebug.Verbose(`Ignoring Conversation update... +${JSON.stringify(turnContext.activity.membersAdded)} -${JSON.stringify(turnContext.activity.membersRemoved)}`);
return null
}
if (turnContext.activity.from === undefined || turnContext.activity.id == undefined) {
return null;
}
let clMemory = await CLMemory.InitMemory(turnContext.activity.from, conversationReference)
let botState = clMemory.BotState;
// If I'm in teach mode process message right away
let inTeach = await botState.GetInTeach();
if (inTeach) {
return await this.ProcessInput(turnContext.activity, conversationReference);
}
// Otherwise I have to queue up messages as user may input them faster than bot responds
else {
let addInputPromise = util.promisify(InputQueue.AddInput);
let isReady = await addInputPromise(botState, turnContext.activity, conversationReference);
if (isReady)
{
let intents = await this.ProcessInput(turnContext.activity, conversationReference);
return intents;
}
// Message has expired
return null;
}
}
public async StartSessionAsync(clMemory: CLMemory, conversationId: string | null, appId: string, sessionStartFlags: SessionStartFlags, createParams: CLM.SessionCreateParams | CLM.CreateTeachParams): Promise<CLM.Teach | CLM.Session> {
const inTeach = ((sessionStartFlags & SessionStartFlags.IN_TEACH) > 0)
let entityList = await this.clClient.GetEntities(appId) // LARS can this be passed in?
// If not continuing an edited session, call endSession
if (!(sessionStartFlags && SessionStartFlags.IS_EDIT_CONTINUE)) {
// Default callback will clear the bot memory.
// END_SESSION action was never triggered, so SessionEndState.OPEN
await this.CheckSessionEndCallback(clMemory, entityList.entities, CLM.SessionEndState.OPEN);
}
// LARS - may need to clear memory here? check
// LARS check that this works = should it be inside loop above
// Check if StartSession call is required
await this.CheckSessionStartCallback(clMemory, entityList.entities);
const startSessionEntities = await clMemory.BotMemory.FilledEntitiesAsync()
createParams.initialFilledEntities = [...createParams.initialFilledEntities || [], ...startSessionEntities]
const filledEntityMap = CLM.FilledEntityMap.FromFilledEntities(createParams.initialFilledEntities, entityList.entities)
clMemory.BotMemory.RestoreFromMapAsync(filledEntityMap)
// Start the new session
let sessionId: string
let logDialogId: string | null
let startResponse: CLM.Teach | CLM.Session
if (inTeach) {
const teachResponse = await this.clClient.StartTeach(appId, createParams as CLM.CreateTeachParams)
startResponse = CLM.ModelUtils.ToTeach(teachResponse)
sessionId = teachResponse.teachId
logDialogId = null
}
else {
startResponse = await this.clClient.StartSession(appId, createParams as CLM.SessionCreateParams)
sessionId = startResponse.sessionId
logDialogId = startResponse.logDialogId
}
// Initizize Bot State
await clMemory.BotState.InitSessionAsync(sessionId, logDialogId, conversationId, sessionStartFlags)
CLDebug.Verbose(`Started Session: ${sessionId} - ${conversationId}`)
return startResponse
}
// Get the currently running app
private async GetRunningApp(key: string, inEditingUI: boolean) : Promise<CLM.AppBase | null> {
let clMemory = CLMemory.GetMemory(key)
let app = await clMemory.BotState.GetApp()
if (app) {
// If I'm not in the editing UI, always use app specified by options
if (!inEditingUI && this.configModelId && this.configModelId != app.appId)
{
// Use config value
CLDebug.Log(`Switching to app specified in config: ${this.configModelId}`)
app = await this.clClient.GetApp(this.configModelId)
await clMemory.SetAppAsync(app)
}
}
// If I don't have an app, attempt to use one set in config
else if (this.configModelId) {
CLDebug.Log(`Selecting app specified in config: ${this.configModelId}`)
app = await this.clClient.GetApp(this.configModelId)
await clMemory.SetAppAsync(app)
}
return app;
}
// End a teach or log session
// originalSessionId is sent when session terminated from EndSession action or expiration
public async EndSessionAsync(key: string, sessionEndState: CLM.SessionEndState, originalSessionId: string | null = null, data?: string): Promise<void> {
let memory = CLMemory.GetMemory(key)
let app = await memory.BotState.GetApp()
if (app) {
let entityList = await this.clClient.GetEntities(app.appId)
// Default callback will clear the bot memory
await this.CheckSessionEndCallback(memory, entityList.entities, sessionEndState, data);
await memory.BotState.EndSessionAsync(originalSessionId);
}
}
// Process user input
private async ProcessInput(activity: BB.Activity, conversationReference: Partial<BB.ConversationReference>): Promise<CLRecognizerResult | null> {
let errComponent = 'ProcessInput'
// Validate request
if (!activity.from || !activity.from.id) {
throw new Error(`Attempted to get current session for user, but user was not defined on bot request.`)
}
try {
let inEditingUI =
conversationReference.user &&
conversationReference.user.name === CL_DEVELOPER || false;
// Validate setup
if (!inEditingUI && !this.configModelId) {
let msg = 'Must specify modelId in ConversationLearner constructor when not running bot in Editing UI\n\n'
CLDebug.Error(msg)
return null
}
if (!ConversationLearner.options || !ConversationLearner.options.LUIS_AUTHORING_KEY) {
let msg = 'Options must specify luisAuthoringKey. Set the LUIS_AUTHORING_KEY.\n\n'
CLDebug.Error(msg)
return null
}
let app = await this.GetRunningApp(activity.from.id, inEditingUI);
let clMemory = await CLMemory.InitMemory(activity.from, conversationReference)
let inTeach = await clMemory.BotState.GetInTeach()
if (!app) {
let error = "ERROR: AppId not specified. When running in a channel (i.e. Skype) or the Bot Framework Emulator, CONVERSATION_LEARNER_MODEL_ID must be specified in your Bot's .env file or Application Settings on the server"
await this.SendMessage(clMemory, error, activity.id)
return null;
}
let sessionId = await clMemory.BotState.GetSessionIdAndSetConversationId(activity.conversation.id)
// If I'm not in teach mode and have a session
if (!inTeach && sessionId) {
const currentTicks = new Date().getTime();
let lastActive = await clMemory.BotState.GetLastActive()
let passedTicks = currentTicks - lastActive;
if (passedTicks > this.maxTimeout!) {
// End the current session, clear the memory
await this.clClient.EndSession(app.appId, sessionId)
// Send original session Id. Used for continuing sessions
await this.EndSessionAsync(activity.from.id, CLM.SessionEndState.OPEN, sessionId)
// If I'm not in the UI, reload the App to get any changes (live package version may have been updated)
if (!inEditingUI) {
if (!this.configModelId) {
let error = "ERROR: ModelId not specified. When running in a channel (i.e. Skype) or the Bot Framework Emulator, CONVERSATION_LEARNER_MODEL_ID must be specified in your Bot's .env file or Application Settings on the server"
await this.SendMessage(clMemory, error, activity.id)
return null
}
app = await this.clClient.GetApp(this.configModelId)
await clMemory.SetAppAsync(app)
if (!app) {
let error = "ERROR: Failed to find Model specified by CONVERSATION_LEARNER_MODEL_ID"
await this.SendMessage(clMemory, error, activity.id)
return null
}
}
let conversationId = await clMemory.BotState.GetConversationId()
// Start a new session
const sessionCreateParams: CLM.SessionCreateParams = {
saveToLog: app.metadata.isLoggingOn,
initialFilledEntities: []
}
let session = await this.StartSessionAsync(clMemory, conversationId, app.appId, SessionStartFlags.IS_MANUAL_TIMEOUT, sessionCreateParams) as CLM.Session
sessionId = session.sessionId
}
// Otherwise update last access time
else {
await clMemory.BotState.SetLastActive(currentTicks);
}
}
// Handle any other non-message input
if (activity.type !== "message") {
await InputQueue.MessageHandled(clMemory.BotState, activity.id);
return null;
}
// PackageId: Use live package id if not in editing UI, default to devPackage if no active package set
let packageId = (inEditingUI ? await clMemory.BotState.GetEditingPackageForApp(app.appId) : app.livePackageId) || app.devPackageId
if (!packageId) {
await this.SendMessage(clMemory, "ERROR: No PackageId has been set", activity.id)
return null;
}
// If no session for this conversation, create a new one
if (!sessionId) {
const sessionCreateParams: CLM.SessionCreateParams = {
saveToLog: app.metadata.isLoggingOn !== false,
packageId: packageId,
initialFilledEntities: []
}
let session = await this.StartSessionAsync(clMemory, activity.conversation.id, app.appId, SessionStartFlags.NONE, sessionCreateParams) as CLM.Session
sessionId = session.sessionId
}
// Process any form data
let buttonResponse = await this.ProcessFormData(activity, clMemory, app.appId)
// Teach inputs are handled via API calls from the Conversation Learner UI
if (!inTeach) {
let entities: CLM.EntityBase[] = []
errComponent = 'SessionExtract'
let userInput: CLM.UserInput = { text: buttonResponse || activity.text || ' ' }
let extractResponse = await this.clClient.SessionExtract(app.appId, sessionId, userInput)
entities = extractResponse.definitions.entities
errComponent = 'ProcessExtraction'
const scoredAction = await this.Score(
app.appId,
sessionId,
clMemory,
extractResponse.text,
extractResponse.predictedEntities,
entities,
inTeach
)
return {
scoredAction: scoredAction,
clEntities: entities,
memory: clMemory,
inTeach: false,
activity: activity
} as CLRecognizerResult
}
return null
} catch (error) {
// Try to end the session, so use can potentially recover
try {
await this.EndSessionAsync(activity.from.id, CLM.SessionEndState.OPEN)
} catch {
CLDebug.Log(`Failed to End Session`)
}
CLDebug.Error(error, errComponent)
return null
}
}
private async ProcessFormData(request: BB.Activity, clMemory: CLMemory, appId: string): Promise<string | null> {
const data = request.value as FormData
if (data) {
// Get list of all entities
let entityList = await this.clClient.GetEntities(appId)
// For each form entry
for (let entityName of Object.keys(data)) {
// Reserved parameter
if (entityName == 'submit') {
continue
}
// Find the entity
let entity = entityList.entities.find((e: CLM.EntityBase) => e.entityName == entityName)
if (!entity) {
CLDebug.Error(`Form - Can't find Entity named: ${entityName}`)
return null
}
// Set it
await clMemory.BotMemory.RememberEntity(entity.entityName, entity.entityId, data[entityName], entity.isMultivalue)
}
// If submit type return as a response
if (data['submit']) {
return data['submit']
} else {
CLDebug.Error(`Adaptive Card has no Submit data`)
return null
}
}
return null
}
public async Score(
appId: string,
sessionId: string,
memory: CLMemory,
text: string,
predictedEntities: CLM.PredictedEntity[],
allEntities: CLM.EntityBase[],
inTeach: boolean
): Promise<CLM.ScoredAction> {
// Call LUIS callback
let scoreInput = await this.CallEntityDetectionCallback(text, predictedEntities, memory, allEntities)
// Call the scorer
let scoreResponse = null
if (inTeach) {
scoreResponse = await this.clClient.TeachScore(appId, sessionId, scoreInput)
} else {
scoreResponse = await this.clClient.SessionScore(appId, sessionId, scoreInput)
}
// Get best action
let bestAction = scoreResponse.scoredActions[0]
// Return the action
return bestAction
}
//-------------------------------------------
// Optional callback than runs after LUIS but before Conversation Learner. Allows Bot to substitute entities
public entityDetectionCallback: EntityDetectionCallback | undefined
// Optional callback than runs before a new chat session starts. Allows Bot to set initial entities
public onSessionStartCallback: OnSessionStartCallback | undefined
// Optional callback than runs when a session ends. Allows Bot set and/or preserve memories after session end
public onSessionEndCallback: OnSessionEndCallback | undefined
public AddCallback<T>(
callback: ICallbackInput<T>
) {
if (typeof callback.name !== "string" || callback.name.trim().length === 0) {
throw new Error(`You attempted to add callback but did not provide a valid name. Name must be non-empty string.`)
}
if (!callback.logic && !callback.render) {
throw new Error(`You attempted to add callback by name: ${callback.name} but did not provide a logic or render function. You must provide at least one of them.`)
}
if (!callback.logic) {
callback.logic = defaultLogicCallback
}
if (!callback.render) {
callback.render = defaultRenderCallback
}
this.callbacks[callback.name] = {
...callback as ICallback<T>,
logicArguments: this.GetArguments(callback.logic, 1),
renderArguments: this.GetArguments(callback.render, 2),
}
}
private GetArguments(func: Function, skip: number = 0): string[] {
const STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/gm
const ARGUMENT_NAMES = /([^\s,]+)/g
const fnStr = func.toString().replace(STRIP_COMMENTS, '')
const argumentNames = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES) || []
return argumentNames.filter((_, i) => i >= skip)
}
private async ProcessPredictedEntities(text: string, memory: BotMemory, predictedEntities: CLM.PredictedEntity[], allEntities: CLM.EntityBase[]): Promise<void> {
// Update entities in my memory
for (let predictedEntity of predictedEntities) {
let entity = allEntities.find(e => e.entityId == predictedEntity.entityId)
if (!entity) {
CLDebug.Error(`Could not find entity by id: ${predictedEntity.entityId}`)
return;
}
// If negative entity will have a positive counter entity
if (entity.positiveId) {
await memory.ForgetEntity(entity.entityName, predictedEntity.entityText, entity.isMultivalue)
} else {
await memory.RememberEntity(
entity.entityName,
entity.entityId,
predictedEntity.entityText,
entity.isMultivalue,
predictedEntity.builtinType,
predictedEntity.resolution
)
}
}
}
public async CallEntityDetectionCallback(text: string, predictedEntities: CLM.PredictedEntity[], clMemory: CLMemory, allEntities: CLM.EntityBase[]): Promise<CLM.ScoreInput> {
// Entities before processing
let prevMemories = new CLM.FilledEntityMap(await clMemory.BotMemory.FilledEntityMap());
// Update memory with predicted entities
await this.ProcessPredictedEntities(text, clMemory.BotMemory, predictedEntities, allEntities)
let memoryManager = await this.CreateMemoryManagerAsync(clMemory, allEntities, prevMemories)
// If bot has callback, call it
if (this.entityDetectionCallback) {
try {
await this.entityDetectionCallback(text, memoryManager)
// Update Memory
await clMemory.BotMemory.RestoreFromMemoryManagerAsync(memoryManager)
}
catch (err) {
await this.SendMessage(clMemory, "Exception hit in Bot's EntityDetectionCallback")
let errMsg = CLDebug.Error(err);
this.SendMessage(clMemory, errMsg);
}
}
// Get entities from my memory
const filledEntities = await clMemory.BotMemory.FilledEntitiesAsync()
let scoreInput: CLM.ScoreInput = {
filledEntities,
context: {},
maskedActions: []
}
return scoreInput
}
private async CreateMemoryManagerAsync(clMemory: CLMemory, allEntities: CLM.EntityBase[], prevMemories?: CLM.FilledEntityMap): Promise<ClientMemoryManager> {
let sessionInfo = await clMemory.BotState.SessionInfoAsync()
let curMemories = new CLM.FilledEntityMap(await clMemory.BotMemory.FilledEntityMap());
if (!prevMemories) {
prevMemories = curMemories;
}
return new ClientMemoryManager(prevMemories, curMemories, allEntities, sessionInfo);
}
// Call session start callback, set memory and return list of filled entities coming from callback
public async CheckSessionStartCallback(clMemory: CLMemory, entities: CLM.EntityBase[]): Promise<void> {
// If onStartSession hasn't been called yet, call it
// LARS let needStartSession = await clMemory.BotState.GetNeedSessionStartCall();
// if (needStartSession) {
// If bot has callback, call it
if (this.onSessionStartCallback && this.adapter) {
let memoryManager = await this.CreateMemoryManagerAsync(clMemory, entities)
// Get conversation ref, so I can generate context and send it back to bot dev
let conversationReference = await clMemory.BotState.GetConversationReverence()
if (!conversationReference) {
CLDebug.Error('Missing ConversationReference')
return
}
await this.adapter.continueConversation(conversationReference, async (context) => {
if (this.onSessionStartCallback) {
try {
await this.onSessionStartCallback(context, memoryManager)
await clMemory.BotMemory.RestoreFromMemoryManagerAsync(memoryManager)
}
catch (err) {
await this.SendMessage(clMemory, "Exception hit in Bot's OnSessionStartCallback")
let errMsg = CLDebug.Error(err);
this.SendMessage(clMemory, errMsg);
}
}
})
// }
// LARS await clMemory.BotState.SetNeedSessionStartCall(false);
}
}
public async CheckSessionEndCallback(clMemory: CLMemory, entities: CLM.EntityBase[], sessionEndState: CLM.SessionEndState, data?: string): Promise<void> {
// If onEndSession hasn't been called yet, call it
let needEndSession = await clMemory.BotState.GetNeedSessionEndCall();
if (needEndSession) {
// If bot has callback, call it to determine which entities to clear / edit
if (this.onSessionEndCallback && this.adapter) {
let memoryManager = await this.CreateMemoryManagerAsync(clMemory, entities)
// Get conversation ref, so I can generate context and send it back to bot dev
let conversationReference = await clMemory.BotState.GetConversationReverence()
if (!conversationReference) {
CLDebug.Error('Missing ConversationReference')
return
}
await this.adapter.continueConversation(conversationReference, async (context) => {
try {
let saveEntities = this.onSessionEndCallback
? await this.onSessionEndCallback(context, memoryManager, sessionEndState, data)
: undefined
await clMemory.BotMemory.ClearAsync(saveEntities)
}
catch (err) {
await this.SendMessage(clMemory, "Exception hit in Bot's OnSessionEndCallback")
let errMsg = CLDebug.Error(err);
this.SendMessage(clMemory, errMsg);
}
})
}
// Otherwise just clear the memory
else {
await clMemory.BotMemory.ClearAsync()
}
await clMemory.BotState.SetNeedSessionEndCall(false);
}
}
public async RenderTemplateAsync(conversationReference: Partial<BB.ConversationReference>, clRecognizeResult: CLRecognizerResult, channelData: {} | null): Promise<IActionResult> {
// Get filled entities from memory
let filledEntityMap = await clRecognizeResult.memory.BotMemory.FilledEntityMap()
filledEntityMap = addEntitiesById(filledEntityMap)
// If the action was terminal, free up the mutex allowing queued messages to be processed
// Activity won't be present if running in training as messages aren't queued
if (clRecognizeResult.scoredAction.isTerminal && clRecognizeResult.activity) {
await InputQueue.MessageHandled(clRecognizeResult.memory.BotState, clRecognizeResult.activity.id);
}
if (!conversationReference.conversation) {
throw new Error(`ConversationReference contains no conversation`)
}
let actionResult: IActionResult
const inTeach = channelData !== null
switch (clRecognizeResult.scoredAction.actionType) {
case CLM.ActionTypes.TEXT: {
// This is hack to allow ScoredAction to be accepted as ActionBase
// TODO: Remove extra properties from ScoredAction so it only had actionId and up service to return actions definitions of scored/unscored actions
// so UI can link the two together instead of having "partial" actions being incorrectly treated as full actions
const textAction = new CLM.TextAction(clRecognizeResult.scoredAction as any)
const response = await this.TakeTextAction(textAction, filledEntityMap)
actionResult = {
logicResult: undefined,
response
}
break
}
case CLM.ActionTypes.API_LOCAL: {
const apiAction = new CLM.ApiAction(clRecognizeResult.scoredAction as any)
actionResult = await this.TakeAPIAction(
apiAction,
filledEntityMap,
clRecognizeResult.memory,
clRecognizeResult.clEntities,
inTeach,
{
type: ActionInputType.LOGIC_AND_RENDER
}
)
break
}
case CLM.ActionTypes.CARD: {
const cardAction = new CLM.CardAction(clRecognizeResult.scoredAction as any)
const response = await this.TakeCardAction(cardAction, filledEntityMap)
actionResult = {
logicResult: undefined,
response
}
break
}
case CLM.ActionTypes.END_SESSION: {
const sessionAction = new CLM.SessionAction(clRecognizeResult.scoredAction as any)
let sessionInfo = await clRecognizeResult.memory.BotState.SessionInfoAsync()
let sessionId = await clRecognizeResult.memory.BotState.GetSessionIdAndSetConversationId(conversationReference.conversation.id)
const response = await this.TakeSessionAction(sessionAction, filledEntityMap, inTeach, sessionInfo.userId, sessionId);
actionResult = {
logicResult: undefined,
response
}
break
}
default:
throw new Error(`Could not find matching renderer for action type: ${clRecognizeResult.scoredAction.actionType}`)
}
// Convert string actions to activities
if (typeof actionResult.response === 'string' ) {
actionResult.response = BB.MessageFactory.text(actionResult.response)
}
if (actionResult.response && channelData) {
actionResult.response.channelData = channelData
}
// If action wasn't terminal loop through Conversation Learner again after a short delay
if (!clRecognizeResult.scoredAction.isTerminal) {
setTimeout(async () => {
let app = await clRecognizeResult.memory.BotState.GetApp()
if (!app) {
throw new Error(`Attempted to get current app before app was set.`)
}
if(!conversationReference.conversation) {
throw new Error(`Attempted to get session by conversation id, but user was not defined on current conversation`)
}
let sessionId = await clRecognizeResult.memory.BotState.GetSessionIdAndSetConversationId(conversationReference.conversation.id)
if (!sessionId) {
throw new Error(`Attempted to get session by conversation id: ${conversationReference.conversation.id} but session was not found`)
}
// If not inTeach, send message to user
if (!clRecognizeResult.inTeach) {
let bestAction = await this.Score(
app.appId,
sessionId,
clRecognizeResult.memory,
'',
[],
clRecognizeResult.clEntities,
clRecognizeResult.inTeach
)
clRecognizeResult.scoredAction = bestAction
// LARS - need to increment scorere step in channel data
actionResult = await this.RenderTemplateAsync(conversationReference, clRecognizeResult, channelData)
if (actionResult.response != null) {
this.SendMessage(clRecognizeResult.memory, actionResult.response)
}
}
}, 100)
}
return actionResult
}
public async SendIntent(intent: CLRecognizerResult, channelData: {} | null = null): Promise<IActionResult | undefined> {
let conversationReference = await intent.memory.BotState.GetConversationReverence();
if (!conversationReference) {
CLDebug.Error('Missing ConversationReference')
return
}
if (!this.adapter) {
CLDebug.Error('Missing Adapter')
return
}
const actionResult = await this.RenderTemplateAsync(conversationReference, intent, channelData)
if (actionResult.response != null) {
await this.adapter.continueConversation(conversationReference, async (context) => {
// Need to repeat null check as compiler is catching one above for explicit null
if (actionResult.response != null) {
await context.sendActivity(actionResult.response)
}
});
}
return actionResult
}
public async SendMessage(memory: CLMemory, message: string | Partial<BB.Activity>, incomingActivityId?: string | undefined): Promise<void> {
// If requested, pop incoming activity from message queue
if (incomingActivityId) {
await InputQueue.MessageHandled(memory.BotState, incomingActivityId);
}
let conversationReference = await memory.BotState.GetConversationReverence()
if (!conversationReference) {
CLDebug.Error('Missing ConversationReference')
return
}
if (!this.adapter) {
CLDebug.Error(`Attempted to send message before adapter was assigned`)
return
}
await this.adapter.continueConversation(conversationReference, async (context) => {
await context.sendActivity(message)
});
}
// TODO: This issue arises because we only save non-null non-empty argument values on the actions
// which means callback may accept more arguments than is actually available on the action.arguments
// To me, it seems it would make more sense to always have these be same length, but perhaps there is
// dependency on action not being defined somewhere else in the application like ActionCreatorEditor
private GetRenderedArguments(fnArgs: string[], actionArgs: CLM.ActionArgument[], filledEntityMap: CLM.FilledEntityMap): string[] {
const missingEntityNames: string[] = []
const renderedArgumentValues = fnArgs.map(param => {
const argument = actionArgs.find(arg => arg.parameter === param)
if (!argument) {
return ''
}
try {
return argument.renderValue(CLM.getEntityDisplayValueMap(filledEntityMap))
}
catch (error) {
missingEntityNames.push(param)
return ''
}
}, missingEntityNames)
if (missingEntityNames.length > 0) {
throw new Error(`Missing Entity value(s) for ${missingEntityNames.join(', ')}`)
}
return renderedArgumentValues
}
public async TakeAPIAction(apiAction: CLM.ApiAction, filledEntityMap: CLM.FilledEntityMap, clMemory: CLMemory, allEntities: CLM.EntityBase[], inTeach: boolean, actionInput: IActionInput): Promise<IActionResult> {
// Extract API name and args
const callback = this.callbacks[apiAction.name]
if (!callback) {
return {
logicResult: undefined,
response: CLDebug.Error(`API callback with name "${apiAction.name}" is not defined`)
}
}
try {
try {
// Invoke Logic part of callback
const renderedLogicArgumentValues = this.GetRenderedArguments(callback.logicArguments, apiAction.logicArguments, filledEntityMap)
const memoryManager = await this.CreateMemoryManagerAsync(clMemory, allEntities)
// If we're only doing the render part, used stored input value
// This happens when replaying dialog to recreated action outputs
let logicResult : any
if (actionInput.type === ActionInputType.RENDER_ONLY) {
const value = (actionInput as IActionInputLogic).value
logicResult = value ? JSON.parse(value) : undefined
}
else {
logicResult = await callback.logic(memoryManager, ...renderedLogicArgumentValues)
}
await clMemory.BotMemory.RestoreFromMemoryManagerAsync(memoryManager)
// Render the action unless only doing logic part
if (actionInput.type === ActionInputType.LOGIC_ONLY) {
return {
logicResult,
response: null
}
}
else {
// Invoke Render part of callback
const renderedRenderArgumentValues = this.GetRenderedArguments(callback.renderArguments, apiAction.renderArguments, filledEntityMap)
let response = await callback.render(logicResult, memoryManager.AsReadOnly(), ...renderedRenderArgumentValues)