-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
index.ts
707 lines (622 loc) · 18.8 KB
/
index.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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { errors } from '@elastic/elasticsearch';
import { serverUnavailable, gatewayTimeout } from '@hapi/boom';
import type { ElasticsearchClient, IUiSettingsClient } from '@kbn/core/server';
import type { Logger } from '@kbn/logging';
import type { TaskManagerStartContract } from '@kbn/task-manager-plugin/server';
import pLimit from 'p-limit';
import pRetry from 'p-retry';
import { isEmpty, map, orderBy } from 'lodash';
import { encode } from 'gpt-tokenizer';
import { MlTrainedModelDeploymentNodesStats } from '@elastic/elasticsearch/lib/api/types';
import { aiAssistantSearchConnectorIndexPattern } from '../../../common';
import { INDEX_QUEUED_DOCUMENTS_TASK_ID, INDEX_QUEUED_DOCUMENTS_TASK_TYPE } from '..';
import { KnowledgeBaseEntry, KnowledgeBaseEntryRole, UserInstruction } from '../../../common/types';
import type { ObservabilityAIAssistantResourceNames } from '../types';
import { getAccessQuery } from '../util/get_access_query';
import { getCategoryQuery } from '../util/get_category_query';
interface Dependencies {
esClient: ElasticsearchClient;
resources: ObservabilityAIAssistantResourceNames;
logger: Logger;
taskManagerStart: TaskManagerStartContract;
getModelId: () => Promise<string>;
}
export interface RecalledEntry {
id: string;
text: string;
score: number | null;
is_correction?: boolean;
labels?: Record<string, string>;
}
function isAlreadyExistsError(error: Error) {
return (
error instanceof errors.ResponseError &&
(error.body.error.type === 'resource_not_found_exception' ||
error.body.error.type === 'status_exception')
);
}
function throwKnowledgeBaseNotReady(body: any) {
throw serverUnavailable(`Knowledge base is not ready yet`, body);
}
export enum KnowledgeBaseEntryOperationType {
Index = 'index',
Delete = 'delete',
}
interface KnowledgeBaseDeleteOperation {
type: KnowledgeBaseEntryOperationType.Delete;
doc_id?: string;
labels?: Record<string, string>;
}
interface KnowledgeBaseIndexOperation {
type: KnowledgeBaseEntryOperationType.Index;
document: KnowledgeBaseEntry;
}
export type KnowledgeBaseEntryOperation =
| KnowledgeBaseDeleteOperation
| KnowledgeBaseIndexOperation;
export class KnowledgeBaseService {
private hasSetup: boolean = false;
private _queue: KnowledgeBaseEntryOperation[] = [];
constructor(private readonly dependencies: Dependencies) {
this.ensureTaskScheduled();
}
setup = async () => {
const elserModelId = await this.dependencies.getModelId();
const retryOptions = { factor: 1, minTimeout: 10000, retries: 12 };
const installModel = async () => {
this.dependencies.logger.info('Installing ELSER model');
await this.dependencies.esClient.ml.putTrainedModel(
{
model_id: elserModelId,
input: {
field_names: ['text_field'],
},
// @ts-expect-error
wait_for_completion: true,
},
{ requestTimeout: '20m' }
);
this.dependencies.logger.info('Finished installing ELSER model');
};
const getIsModelInstalled = async () => {
const getResponse = await this.dependencies.esClient.ml.getTrainedModels({
model_id: elserModelId,
include: 'definition_status',
});
this.dependencies.logger.debug(
'Model definition status:\n' + JSON.stringify(getResponse.trained_model_configs[0])
);
return Boolean(getResponse.trained_model_configs[0]?.fully_defined);
};
await pRetry(async () => {
let isModelInstalled: boolean = false;
try {
isModelInstalled = await getIsModelInstalled();
} catch (error) {
if (isAlreadyExistsError(error)) {
await installModel();
isModelInstalled = await getIsModelInstalled();
}
}
if (!isModelInstalled) {
throwKnowledgeBaseNotReady({
message: 'Model is not fully defined',
});
}
}, retryOptions);
try {
await this.dependencies.esClient.ml.startTrainedModelDeployment({
model_id: elserModelId,
wait_for: 'fully_allocated',
});
} catch (error) {
this.dependencies.logger.debug('Error starting model deployment');
this.dependencies.logger.debug(error);
if (!isAlreadyExistsError(error)) {
throw error;
}
}
await pRetry(async () => {
const response = await this.dependencies.esClient.ml.getTrainedModelsStats({
model_id: elserModelId,
});
const isReady = response.trained_model_stats.some((stats) =>
(stats.deployment_stats?.nodes as unknown as MlTrainedModelDeploymentNodesStats[]).some(
(node) => node.routing_state.routing_state === 'started'
)
);
if (isReady) {
return Promise.resolve();
}
this.dependencies.logger.debug('Model is not allocated yet');
this.dependencies.logger.debug(JSON.stringify(response));
throw gatewayTimeout();
}, retryOptions);
this.dependencies.logger.info('Model is ready');
this.ensureTaskScheduled();
};
private ensureTaskScheduled() {
this.dependencies.taskManagerStart
.ensureScheduled({
taskType: INDEX_QUEUED_DOCUMENTS_TASK_TYPE,
id: INDEX_QUEUED_DOCUMENTS_TASK_ID,
state: {},
params: {},
schedule: {
interval: '1h',
},
})
.then(() => {
this.dependencies.logger.debug('Scheduled queue task');
return this.dependencies.taskManagerStart.runSoon(INDEX_QUEUED_DOCUMENTS_TASK_ID);
})
.then(() => {
this.dependencies.logger.debug('Queue task ran');
})
.catch((err) => {
this.dependencies.logger.error(`Failed to schedule queue task`);
this.dependencies.logger.error(err);
});
}
private async processOperation(operation: KnowledgeBaseEntryOperation) {
if (operation.type === KnowledgeBaseEntryOperationType.Delete) {
await this.dependencies.esClient.deleteByQuery({
index: this.dependencies.resources.aliases.kb,
query: {
bool: {
filter: [
...(operation.doc_id ? [{ term: { _id: operation.doc_id } }] : []),
...(operation.labels
? map(operation.labels, (value, key) => {
return { term: { [key]: value } };
})
: []),
],
},
},
});
return;
}
await this.addEntry({
entry: operation.document,
});
}
async processQueue() {
if (!this._queue.length) {
return;
}
if (!(await this.status()).ready) {
this.dependencies.logger.debug(`Bailing on queue task: KB is not ready yet`);
return;
}
this.dependencies.logger.debug(`Processing queue`);
this.hasSetup = true;
this.dependencies.logger.info(`Processing ${this._queue.length} queue operations`);
const limiter = pLimit(5);
const operations = this._queue.concat();
await Promise.all(
operations.map((operation) =>
limiter(async () => {
this._queue.splice(operations.indexOf(operation), 1);
await this.processOperation(operation);
})
)
);
this.dependencies.logger.info('Processed all queued operations');
}
queue(operations: KnowledgeBaseEntryOperation[]): void {
if (!operations.length) {
return;
}
if (!this.hasSetup) {
this._queue.push(...operations);
return;
}
const limiter = pLimit(5);
const limitedFunctions = this._queue.map((operation) =>
limiter(() => this.processOperation(operation))
);
Promise.all(limitedFunctions).catch((err) => {
this.dependencies.logger.error(`Failed to process all queued operations`);
this.dependencies.logger.error(err);
});
}
status = async () => {
const elserModelId = await this.dependencies.getModelId();
try {
const modelStats = await this.dependencies.esClient.ml.getTrainedModelsStats({
model_id: elserModelId,
});
const elserModelStats = modelStats.trained_model_stats[0];
const deploymentState = elserModelStats.deployment_stats?.state;
const allocationState = elserModelStats.deployment_stats?.allocation_status.state;
return {
ready: deploymentState === 'started' && allocationState === 'fully_allocated',
deployment_state: deploymentState,
allocation_state: allocationState,
model_name: elserModelId,
};
} catch (error) {
return {
error: error instanceof errors.ResponseError ? error.body.error : String(error),
ready: false,
model_name: elserModelId,
};
}
};
private async recallFromKnowledgeBase({
queries,
categories,
namespace,
user,
modelId,
}: {
queries: string[];
categories?: string[];
namespace: string;
user?: { name: string };
modelId: string;
}): Promise<RecalledEntry[]> {
const query = {
bool: {
should: queries.map((text) => ({
text_expansion: {
'ml.tokens': {
model_text: text,
model_id: modelId,
},
},
})),
filter: [
...getAccessQuery({
user,
namespace,
}),
...getCategoryQuery({ categories }),
],
},
};
const response = await this.dependencies.esClient.search<
Pick<KnowledgeBaseEntry, 'text' | 'is_correction' | 'labels'>
>({
index: [this.dependencies.resources.aliases.kb],
query,
size: 20,
_source: {
includes: ['text', 'is_correction', 'labels'],
},
});
return response.hits.hits.map((hit) => ({
...hit._source!,
score: hit._score!,
id: hit._id,
}));
}
private async getConnectorIndices(
client: ElasticsearchClient,
uiSettingsClient: IUiSettingsClient
) {
// improve performance by running this in parallel with the `uiSettingsClient` request
const responsePromise = client.transport.request({
method: 'GET',
path: '_connector',
querystring: {
filter_path: 'results.index_name',
},
});
const customSearchConnectorIndex = await uiSettingsClient.get<string>(
aiAssistantSearchConnectorIndexPattern
);
if (customSearchConnectorIndex) {
return customSearchConnectorIndex.split(',');
}
const response = (await responsePromise) as { results: Array<{ index_name: string }> };
const connectorIndices = response.results.map((result) => result.index_name);
// preserve backwards compatibility with 8.14 (may not be needed in the future)
if (isEmpty(connectorIndices)) {
return ['search-*'];
}
return connectorIndices;
}
private async recallFromConnectors({
queries,
asCurrentUser,
uiSettingsClient,
modelId,
}: {
queries: string[];
asCurrentUser: ElasticsearchClient;
uiSettingsClient: IUiSettingsClient;
modelId: string;
}): Promise<RecalledEntry[]> {
const ML_INFERENCE_PREFIX = 'ml.inference.';
const connectorIndices = await this.getConnectorIndices(asCurrentUser, uiSettingsClient);
const fieldCaps = await asCurrentUser.fieldCaps({
index: connectorIndices,
fields: `${ML_INFERENCE_PREFIX}*`,
allow_no_indices: true,
types: ['sparse_vector'],
filters: '-metadata,-parent',
});
const fieldsWithVectors = Object.keys(fieldCaps.fields).map((field) =>
field.replace('_expanded.predicted_value', '').replace(ML_INFERENCE_PREFIX, '')
);
if (!fieldsWithVectors.length) {
return [];
}
const esQueries = fieldsWithVectors.flatMap((field) => {
const vectorField = `${ML_INFERENCE_PREFIX}${field}_expanded.predicted_value`;
const modelField = `${ML_INFERENCE_PREFIX}${field}_expanded.model_id`;
return queries.map((query) => {
return {
bool: {
should: [
{
text_expansion: {
[vectorField]: {
model_text: query,
model_id: modelId,
},
},
},
],
filter: [
{
term: {
[modelField]: modelId,
},
},
],
},
};
});
});
const response = await asCurrentUser.search<unknown>({
index: connectorIndices,
query: {
bool: {
should: esQueries,
},
},
size: 20,
_source: {
exclude: ['_*', 'ml*'],
},
});
const results = response.hits.hits.map((hit) => ({
text: JSON.stringify(hit._source),
score: hit._score!,
is_correction: false,
id: hit._id,
}));
return results;
}
recall = async ({
user,
queries,
categories,
namespace,
asCurrentUser,
uiSettingsClient,
}: {
queries: string[];
categories?: string[];
user?: { name: string };
namespace: string;
asCurrentUser: ElasticsearchClient;
uiSettingsClient: IUiSettingsClient;
}): Promise<{
entries: RecalledEntry[];
}> => {
this.dependencies.logger.debug(`Recalling entries from KB for queries: "${queries}"`);
const modelId = await this.dependencies.getModelId();
const [documentsFromKb, documentsFromConnectors] = await Promise.all([
this.recallFromKnowledgeBase({
user,
queries,
categories,
namespace,
modelId,
}).catch((error) => {
if (isAlreadyExistsError(error)) {
throwKnowledgeBaseNotReady(error.body);
}
throw error;
}),
this.recallFromConnectors({
asCurrentUser,
uiSettingsClient,
queries,
modelId,
}).catch((error) => {
this.dependencies.logger.debug('Error getting data from search indices');
this.dependencies.logger.debug(error);
return [];
}),
]);
const sortedEntries = orderBy(
documentsFromKb.concat(documentsFromConnectors),
'score',
'desc'
).slice(0, 20);
const MAX_TOKENS = 4000;
let tokenCount = 0;
const returnedEntries: RecalledEntry[] = [];
for (const entry of sortedEntries) {
returnedEntries.push(entry);
tokenCount += encode(entry.text).length;
if (tokenCount >= MAX_TOKENS) {
break;
}
}
const droppedEntries = sortedEntries.length - returnedEntries.length;
if (droppedEntries > 0) {
this.dependencies.logger.info(`Dropped ${droppedEntries} entries because of token limit`);
}
return {
entries: returnedEntries,
};
};
getInstructions = async (
namespace: string,
user?: { name: string }
): Promise<UserInstruction[]> => {
try {
const response = await this.dependencies.esClient.search<KnowledgeBaseEntry>({
index: this.dependencies.resources.aliases.kb,
query: {
bool: {
must: [
{
term: {
'labels.category.keyword': {
value: 'instruction',
},
},
},
],
filter: getAccessQuery({
user,
namespace,
}),
},
},
size: 500,
_source: ['doc_id', 'text'],
});
return response.hits.hits.map((hit) => ({
doc_id: hit._source?.doc_id ?? '',
text: hit._source?.text ?? '',
}));
} catch (error) {
this.dependencies.logger.error('Failed to load instructions from knowledge base');
this.dependencies.logger.error(error);
return [];
}
};
getEntries = async ({
query,
sortBy,
sortDirection,
}: {
query?: string;
sortBy?: string;
sortDirection?: 'asc' | 'desc';
}): Promise<{ entries: KnowledgeBaseEntry[] }> => {
try {
const response = await this.dependencies.esClient.search<KnowledgeBaseEntry>({
index: this.dependencies.resources.aliases.kb,
...(query
? {
query: {
wildcard: {
doc_id: {
value: `${query}*`,
},
},
},
}
: {}),
sort: [
{
[String(sortBy)]: {
order: sortDirection,
},
},
],
size: 500,
_source: {
includes: [
'doc_id',
'text',
'is_correction',
'labels',
'confidence',
'public',
'@timestamp',
'role',
],
},
});
return {
entries: response.hits.hits.map((hit) => ({
...hit._source!,
role: hit._source!.role ?? KnowledgeBaseEntryRole.UserEntry,
score: hit._score,
id: hit._id,
})),
};
} catch (error) {
if (isAlreadyExistsError(error)) {
throwKnowledgeBaseNotReady(error.body);
}
throw error;
}
};
addEntry = async ({
entry: { id, ...document },
user,
namespace,
}: {
entry: Omit<KnowledgeBaseEntry, '@timestamp'>;
user?: { name: string; id?: string };
namespace?: string;
}): Promise<void> => {
try {
await this.dependencies.esClient.index({
index: this.dependencies.resources.aliases.kb,
id,
document: {
'@timestamp': new Date().toISOString(),
...document,
user,
namespace,
},
pipeline: this.dependencies.resources.pipelines.kb,
refresh: false,
});
} catch (error) {
if (error instanceof errors.ResponseError && error.body.error.type === 'status_exception') {
throwKnowledgeBaseNotReady(error.body);
}
throw error;
}
};
addEntries = async ({
operations,
}: {
operations: KnowledgeBaseEntryOperation[];
}): Promise<void> => {
this.dependencies.logger.info(`Starting import of ${operations.length} entries`);
const limiter = pLimit(5);
await Promise.all(
operations.map((operation) =>
limiter(async () => {
await this.processOperation(operation);
})
)
);
this.dependencies.logger.info(`Completed import of ${operations.length} entries`);
};
deleteEntry = async ({ id }: { id: string }): Promise<void> => {
try {
await this.dependencies.esClient.delete({
index: this.dependencies.resources.aliases.kb,
id,
refresh: 'wait_for',
});
return Promise.resolve();
} catch (error) {
if (isAlreadyExistsError(error)) {
throwKnowledgeBaseNotReady(error.body);
}
throw error;
}
};
}