Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

index.js 14 KB

You have to be logged in to leave a comment. Sign In
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
  1. var util = require('util');
  2. var _ = require('lodash');
  3. var builder = require('botbuilder');
  4. const defaultSettings = {
  5. pageSize: 5,
  6. multipleSelection: true,
  7. refiners: [],
  8. refineFormatter: (arr) => _.zipObject(arr, arr)
  9. };
  10. const CancelOption = 'Cancel';
  11. // Create the BotBuilder library for Search with the specified Id
  12. function create(settings) {
  13. settings = Object.assign({}, defaultSettings, settings);
  14. if (typeof settings.search !== 'function') {
  15. throw new Error('options.search is required');
  16. }
  17. if (settings.refineFormatter && typeof settings.refineFormatter !== 'function') {
  18. throw new Error('options.refineFormatter should be a function');
  19. }
  20. const library = new builder.Library('search');
  21. // Entry point. Closure that handlers these states
  22. // - A. Completing after search result selection without multipleSelection
  23. // - B. Cancelling after search result selection with multipleSelection
  24. // - C. Typing 'done'
  25. // - D. Selecting a refine value. Will trigger search
  26. // - E. Typing 'list'
  27. // - F. Entering search text. Will trigger search
  28. // - G. No input. Will trigger search prompt
  29. library.dialog('/',
  30. new builder.SimpleDialog((session, args) => {
  31. args = args || {};
  32. var query = args.query || session.dialogData.query || emptyQuery();
  33. var selection = args.selection || session.dialogData.selection || [];
  34. session.dialogData.selection = selection;
  35. session.dialogData.query = query;
  36. var done = args.done;
  37. if (done) {
  38. // A/B/C returning from search results or cancelling
  39. return session.endDialogWithResult({
  40. selection,
  41. query
  42. });
  43. }
  44. var refining = !!args.refining;
  45. if (refining) {
  46. // D. returning from refine dialog
  47. if (args.refiner && args.refiner.key) {
  48. session.send('Filtering by %s: %s', args.refiner.key, args.refiner.value);
  49. }
  50. return performSearch(session, query, selection);
  51. }
  52. var input = args.response;
  53. var hasInput = typeof input === 'string';
  54. if (hasInput) {
  55. // Process input
  56. if (settings.multipleSelection && input.trim().toLowerCase() === 'list') {
  57. // E. List items
  58. listAddedItems(session);
  59. searchPrompt(session);
  60. } else {
  61. // F. Perform search
  62. var newQuery = Object.assign({}, query, { searchText: input });
  63. performSearch(session, newQuery, selection);
  64. }
  65. } else {
  66. // G. Prompt
  67. searchPrompt(session);
  68. }
  69. }));
  70. // Handle display results & selection
  71. library.dialog('results',
  72. new builder.IntentDialog()
  73. .onBegin((session, args) => {
  74. // Save previous state
  75. session.dialogData.selection = args.selection;
  76. session.dialogData.searchResponse = args.searchResponse;
  77. session.dialogData.query = args.query;
  78. // Display results
  79. var results = args.searchResponse.results;
  80. var reply = new builder.Message(session)
  81. .text('Here are a few good options I found:')
  82. .attachmentLayout(builder.AttachmentLayout.carousel)
  83. .attachments(results.map(searchHitAsCard.bind(null, true)));
  84. session.send(reply);
  85. session.send(settings.multipleSelection ?
  86. 'You can select one or more to add to your list, *list* what you\'ve selected so far, *refine* these results, see *more* or search *again*.' :
  87. 'You can select one, *refine* these results, see *more* or search *again*.');
  88. })
  89. .matches(/again|reset/i, (session) => {
  90. // Restart
  91. session.replaceDialog('/');
  92. })
  93. .matches(/more/i, (session) => {
  94. // Next Page
  95. session.dialogData.query.pageNumber++;
  96. performSearch(session, session.dialogData.query, session.dialogData.selection);
  97. })
  98. .matches(/refine/i, (session) => {
  99. // Refine
  100. session.beginDialog('refine', {
  101. query: session.dialogData.query,
  102. selection: session.dialogData.selection
  103. });
  104. })
  105. .matches(/list/i, (session) => listAddedItems(session))
  106. .matches(/done/i, (session) => session.endDialogWithResult({ selection: session.dialogData.selection, done: true }))
  107. .onDefault((session, args) => {
  108. var selectedKey = session.message.text;
  109. var hit = _.find(session.dialogData.searchResponse.results, ['key', selectedKey]);
  110. if (!hit) {
  111. // Un-recognized selection
  112. return session.send('Not sure what you mean. You can search *again*, *refine*, *list* or select one of the items above. Or are you *done*?');
  113. } else {
  114. // Add selection
  115. var selection = session.dialogData.selection || [];
  116. if (!_.find(selection, ['key', hit.key])) {
  117. selection.push(hit);
  118. session.dialogData.selection = selection;
  119. session.save();
  120. }
  121. var query = session.dialogData.query;
  122. if (settings.multipleSelection) {
  123. // Multi-select -> Continue?
  124. session.send('%s was added to your list!', hit.title);
  125. session.beginDialog('confirm-continue', { selection: selection, query: query });
  126. } else {
  127. // Single-select -> done!
  128. session.endDialogWithResult({ selection: selection, query: query });
  129. }
  130. }
  131. }));
  132. // Handle refine search
  133. library.dialog('refine', [
  134. (session, args, next) => {
  135. // args: query, selection, refiner(optional), prompt(optional)
  136. var query = args.query || emptyQuery();
  137. var selection = args.selection || [];
  138. var refiner = args.refiner;
  139. var prompt = args.prompt;
  140. session.dialogData.query = query;
  141. session.dialogData.selection = selection;
  142. // Manual call
  143. if (refiner) {
  144. return next({
  145. response: { entity: refiner },
  146. prompt: prompt
  147. });
  148. }
  149. // 1. Display choices from usable refiners
  150. var usedRefiners = query.filters.map(s => s.key);
  151. var usableRefiners = _.filter(settings.refiners, (r) => usedRefiners.indexOf(r) === -1);
  152. if (usableRefiners.length === 0) {
  153. // no more refiners
  154. session.send('Oops! You used all the available refiners and you cannot refine the results anymore.');
  155. session.endDialogWithResult({ query, selection });
  156. } else {
  157. // format them as { 'Label #1': 'value_1', 'Label #2'... }
  158. var options = settings.refineFormatter(usableRefiners);
  159. // add cancel option
  160. options = Object.assign(_.zipObject([CancelOption], [CancelOption]), options);
  161. builder.Prompts.choice(session, 'What do you want to refine by?', options);
  162. }
  163. },
  164. (session, args, next) => {
  165. // format refiners again and get value based on response
  166. var selectedOption = args.response.entity;
  167. if(selectedOption === CancelOption) {
  168. // continue and cancel
  169. return next();
  170. }
  171. var options = settings.refineFormatter(settings.refiners);
  172. var refiner = options[selectedOption];
  173. session.dialogData.refiner = refiner;
  174. // 2. Search using current query and new refiner
  175. var newQuery = Object.assign(
  176. { facets: [refiner] },
  177. session.dialogData.query);
  178. settings.search(newQuery).then((response) => {
  179. // 3. Display choices with refiner values
  180. var facet = _.find(response.facets, ['key', refiner]);
  181. if (facet) {
  182. var options = [CancelOption].concat(facet.options.map(formatRefinerOption));
  183. var prompt = args.prompt || 'Here\'s what I found for ' + refiner + ' (select \'cancel\' if you don\'t want to select any of these):';
  184. builder.Prompts.choice(session, prompt, options);
  185. } else {
  186. // No results for selected facet, continue and cancel
  187. next();
  188. }
  189. });
  190. },
  191. (session, args, next) => {
  192. // 4. Process refiner value selection
  193. var query = session.dialogData.query;
  194. var selection = session.dialogData.selection;
  195. var refiner = session.dialogData.refiner;
  196. args = args || {};
  197. args.response = args.response || { entity: CancelOption };
  198. var selectedValue = args.response.entity;
  199. if (selectedValue === CancelOption) {
  200. // Cancel
  201. session.endDialogWithResult({ query, selection });
  202. } else {
  203. var refinerValue = parseRefinerValue(selectedValue);
  204. // Returning dialog handles searching with current SearchTerm and new filters
  205. var newQuery = applyRefiner(query, refiner, refinerValue);
  206. session.endDialogWithResult({
  207. query: newQuery,
  208. selection,
  209. refining: true,
  210. refiner: { key: refiner, value: refinerValue }
  211. });
  212. }
  213. }
  214. ]);
  215. // Helpers
  216. library.dialog('confirm-continue', new builder.SimpleDialog((session, args) => {
  217. args = args || {};
  218. if (args.response === undefined) {
  219. session.dialogData.selection = args.selection;
  220. session.dialogData.query = args.query;
  221. builder.Prompts.confirm(session, args.message || 'Do you want to continue searching and adding more items?');
  222. } else {
  223. return session.endDialogWithResult({
  224. done: !args.response,
  225. selection: session.dialogData.selection,
  226. query: session.dialogData.query
  227. });
  228. }
  229. }));
  230. function performSearch(session, query, selection) {
  231. settings.search(query).then((response) => {
  232. if (response.results.length === 0) {
  233. // No Results - Prompt retry
  234. session.beginDialog('confirm-continue', {
  235. message: 'Sorry, I didn\'t find any matches. Do you want to retry your search?',
  236. selection: selection,
  237. query: query
  238. });
  239. } else {
  240. // Handle results selection
  241. session.beginDialog('results', {
  242. searchResponse: response,
  243. selection: selection,
  244. query: query
  245. });
  246. }
  247. });
  248. }
  249. function searchHitAsCard(showSave, searchHit) {
  250. var buttons = showSave
  251. ? [new builder.CardAction().type('imBack').title('Save').value(searchHit.key)]
  252. : [];
  253. var card = new builder.HeroCard()
  254. .title(searchHit.title)
  255. .buttons(buttons);
  256. if (searchHit.description) {
  257. card.subtitle(searchHit.description);
  258. }
  259. if (searchHit.imageUrl) {
  260. card.images([new builder.CardImage().url(searchHit.imageUrl)]);
  261. }
  262. return card;
  263. }
  264. function applyRefiner(query, refiner, refinerValue) {
  265. query.filters.push({ key: refiner, value: refinerValue });
  266. query.pageNumber = 1;
  267. return query;
  268. }
  269. function formatRefinerOption(facet) {
  270. return util.format('%s (%d)', facet.value, facet.count);
  271. }
  272. function parseRefinerValue(s) {
  273. return s.split('(')[0].trim();
  274. }
  275. function searchPrompt(session) {
  276. var prompt = 'What would you like to search for?';
  277. if (session.dialogData.firstTimeDone) {
  278. prompt = 'What else would you like to search for?';
  279. if (settings.multipleSelection) {
  280. prompt += ' You can also *list* all items you\'ve added so far.';
  281. }
  282. }
  283. session.dialogData.firstTimeDone = true;
  284. builder.Prompts.text(session, prompt);
  285. }
  286. function listAddedItems(session) {
  287. var selection = session.dialogData.selection || [];
  288. if (selection.length === 0) {
  289. session.send('You have not added anything yet.');
  290. } else {
  291. var actions = selection.map((hit) => builder.CardAction.imBack(session, hit.title));
  292. var message = new builder.Message(session)
  293. .text('Here\'s what you\'ve added to your list so far:')
  294. .attachments(selection.map(searchHitAsCard.bind(null, false)))
  295. .attachmentLayout(builder.AttachmentLayout.list);
  296. session.send(message);
  297. }
  298. }
  299. function emptyQuery() {
  300. return { pageNumber: 1, pageSize: settings.pageSize, filters: [] };
  301. }
  302. return library.clone();
  303. }
  304. function begin(session, args) {
  305. session.beginDialog('search:/', args);
  306. }
  307. function refine(session, args) {
  308. session.beginDialog('search:refine', args);
  309. }
  310. // This helper transforms each of the AzureSearch result items using the mapping function provided (itemMap)
  311. function defaultResultsMapper(itemMap) {
  312. return function (providerResults) {
  313. return {
  314. results: providerResults.results.map(itemMap),
  315. facets: providerResults.facets
  316. };
  317. };
  318. }
  319. // Exports
  320. module.exports = {
  321. create: create,
  322. begin: begin,
  323. refine: refine,
  324. defaultResultsMapper: defaultResultsMapper
  325. };
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...