-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathai-query-reducer.ts
More file actions
523 lines (473 loc) · 13.6 KB
/
ai-query-reducer.ts
File metadata and controls
523 lines (473 loc) · 13.6 KB
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
import type { Action, Reducer } from 'redux';
import { getSimplifiedSchema } from 'mongodb-schema';
import toNS from 'mongodb-ns';
import { UUID } from 'bson';
import type { QueryBarThunkAction } from './query-bar-store';
import { isAction } from '../utils';
import {
mapQueryToFormFields,
parseQueryAttributesToFormFields,
} from '../utils/query';
import type { QueryFormFields } from '../constants/query-properties';
import { DEFAULT_FIELD_VALUES } from '../constants/query-bar-store';
import { openToast } from '@mongodb-js/compass-components';
import type { AtlasServiceError } from '@mongodb-js/atlas-service/renderer';
import type { Logger } from '@mongodb-js/compass-logging/provider';
import { mongoLogId } from '@mongodb-js/compass-logging/provider';
import type { TrackFunction } from '@mongodb-js/compass-telemetry';
import type { ConnectionInfo } from '@mongodb-js/compass-connections/provider';
type AIQueryStatus = 'ready' | 'fetching' | 'success';
export type AIQueryState = {
errorMessage: string | undefined;
errorCode: string | undefined;
isInputVisible: boolean;
aiPromptText: string;
status: AIQueryStatus;
aiQueryRequestId: string | null; // Maps to the AbortController of the current fetch (or null).
lastAIQueryRequestId: string | null; // We store the last request id so we can pass it when a user provides feedback.
};
export const initialState: AIQueryState = {
status: 'ready',
aiPromptText: '',
errorMessage: undefined,
errorCode: undefined,
isInputVisible: false,
aiQueryRequestId: null,
lastAIQueryRequestId: null,
};
export const AIQueryActionTypes = {
AIQueryStarted: 'compass-query-bar/ai-query/AIQueryStarted',
AIQueryCancelled: 'compass-query-bar/ai-query/AIQueryCancelled',
AIQueryFailed: 'compass-query-bar/ai-query/AIQueryFailed',
AIQuerySucceeded: 'compass-query-bar/ai-query/AIQuerySucceeded',
CancelAIQuery: 'compass-query-bar/ai-query/CancelAIQuery',
ShowInput: 'compass-query-bar/ai-query/ShowInput',
HideInput: 'compass-query-bar/ai-query/HideInput',
ChangeAIPromptText: 'compass-query-bar/ai-query/ChangeAIPromptText',
} as const;
const NUM_DOCUMENTS_TO_SAMPLE = 4;
const AIQueryAbortControllerMap = new Map<string, AbortController>();
function getAbortSignal() {
const id = new UUID().toString();
const controller = new AbortController();
AIQueryAbortControllerMap.set(id, controller);
return { id, signal: controller.signal };
}
function abort(id: string) {
const controller = AIQueryAbortControllerMap.get(id);
controller?.abort();
return AIQueryAbortControllerMap.delete(id);
}
function cleanupAbortSignal(id: string) {
return AIQueryAbortControllerMap.delete(id);
}
type ShowInputAction = {
type: typeof AIQueryActionTypes.ShowInput;
};
type HideInputAction = {
type: typeof AIQueryActionTypes.HideInput;
};
type ChangeAIPromptTextAction = {
type: typeof AIQueryActionTypes.ChangeAIPromptText;
text: string;
};
export const changeAIPromptText = (text: string): ChangeAIPromptTextAction => ({
type: AIQueryActionTypes.ChangeAIPromptText,
text,
});
type AIQueryStartedAction = {
type: typeof AIQueryActionTypes.AIQueryStarted;
requestId: string;
};
type AIQueryFailedAction = {
type: typeof AIQueryActionTypes.AIQueryFailed;
errorMessage: string;
statusCode?: number;
errorCode?: string;
};
export type AIQuerySucceededAction = {
type: typeof AIQueryActionTypes.AIQuerySucceeded;
fields: QueryFormFields;
requestId: string;
};
type FailedResponseTrackMessage = {
statusCode?: number;
errorCode?: string;
errorName: string;
errorMessage: string;
log: Logger['log'];
track: TrackFunction;
requestId: string;
connectionInfo: ConnectionInfo;
};
function trackAndLogFailed({
statusCode,
errorCode,
errorName,
errorMessage,
log,
track,
requestId,
connectionInfo,
}: FailedResponseTrackMessage) {
log.warn(mongoLogId(1_001_000_198), 'AIQuery', 'AI query request failed', {
statusCode,
errorMessage,
errorName,
errorCode,
requestId,
});
track(
'AI Response Failed',
() => ({
editor_view_type: 'find' as const,
error_name: errorName,
status_code: statusCode,
error_code: errorCode ?? '',
request_id: requestId,
}),
connectionInfo
);
}
export const runAIQuery = (
userInput: string
): QueryBarThunkAction<
Promise<void>,
AIQueryStartedAction | AIQueryFailedAction | AIQuerySucceededAction
> => {
return async (
dispatch,
getState,
{
dataService,
localAppRegistry,
preferences,
atlasAiService,
logger: { log },
connectionInfoRef,
track,
collection,
}
) => {
const provideSampleDocuments =
preferences.getPreferences().enableGenAISampleDocumentPassing;
const abortController = new AbortController();
const { id: requestId, signal } = getAbortSignal();
const connectionInfo = connectionInfoRef.current;
track(
'AI Prompt Submitted',
() => ({
editor_view_type: 'find' as const,
user_input_length: userInput.length,
has_sample_documents: provideSampleDocuments,
request_id: requestId,
}),
connectionInfo
);
const {
aiQuery: { aiQueryRequestId: existingRequestId },
queryBar: { namespace },
} = getState();
if (existingRequestId !== null) {
// Cancel the active request as this one will override.
abort(existingRequestId);
}
dispatch({
type: AIQueryActionTypes.AIQueryStarted,
requestId,
});
let jsonResponse;
try {
const sampleDocuments = await dataService.sample(
namespace,
{
query: {},
size: NUM_DOCUMENTS_TO_SAMPLE,
},
{
maxTimeMS: preferences.getPreferences().maxTimeMS,
promoteValues: false,
},
{
abortSignal: signal,
}
);
const schema = await getSimplifiedSchema(sampleDocuments);
const { isFLE } = await collection.fetchMetadata({ dataService });
const { collection: collectionName, database: databaseName } =
toNS(namespace);
jsonResponse = await atlasAiService.getQueryFromUserInput(
{
signal: abortController.signal,
userInput,
collectionName,
databaseName,
schema,
// Provide sample documents when the user has opted in in their settings.
...(provideSampleDocuments
? {
sampleDocuments,
}
: undefined),
requestId,
enableStorage: !isFLE,
},
connectionInfo
);
} catch (err: any) {
if (signal.aborted) {
// If we already aborted so we ignore the error.
return;
}
trackAndLogFailed({
errorName: 'request_error',
statusCode: (err as AtlasServiceError).statusCode || err?.code,
errorCode: (err as AtlasServiceError).errorCode || err?.name,
errorMessage: (err as AtlasServiceError).message,
log,
track,
requestId,
connectionInfo,
});
// We're going to reset input state with this error, show the error in the
// toast instead
if ((err as AtlasServiceError).statusCode === 401) {
openToast('ai-unauthorized', {
variant: 'important',
title: 'Network Error',
description: 'Unauthorized',
timeout: 5000,
});
}
dispatch({
type: AIQueryActionTypes.AIQueryFailed,
errorMessage: (err as AtlasServiceError).message,
statusCode: (err as AtlasServiceError).statusCode ?? -1,
errorCode: (err as AtlasServiceError).errorCode,
});
return;
} finally {
// Remove the AbortController from the Map as we either finished
// waiting for the fetch or cancelled at this point.
cleanupAbortSignal(requestId);
}
if (signal.aborted) {
log.info(
mongoLogId(1_001_000_197),
'AIQuery',
'Cancelled ai query request',
{
requestId,
}
);
return;
}
let query;
let generatedFields: QueryFormFields;
try {
query = jsonResponse?.content?.query;
generatedFields = parseQueryAttributesToFormFields(
query,
preferences.getPreferences()
);
} catch (err: any) {
trackAndLogFailed({
errorName: 'could_not_parse_fields',
statusCode: (err as AtlasServiceError).statusCode,
errorMessage: err?.message,
log,
track,
requestId,
connectionInfo,
});
dispatch({
type: AIQueryActionTypes.AIQueryFailed,
errorMessage: err?.message,
});
return;
}
// Error when the response is empty or there is nothing to map.
if (!generatedFields || Object.keys(generatedFields).length === 0) {
const aggregation = jsonResponse?.content?.aggregation;
// The query endpoint may return the aggregation property in addition to filter, project, etc..
// It happens when the AI model couldn't generate a query and tried to fulfill a task with the aggregation.
if (aggregation) {
localAppRegistry?.emit('generate-aggregation-from-query', {
userInput,
aggregation,
requestId,
});
const msg =
'Query requires stages from aggregation framework therefore an aggregation was generated.';
trackAndLogFailed({
errorName: 'ai_generated_aggregation_instead_of_query',
errorMessage: msg,
log,
track,
requestId,
connectionInfo,
});
return;
}
const msg =
'No query was returned from the ai. Consider re-wording your prompt.';
trackAndLogFailed({
errorName: 'no_usable_query_from_ai',
errorMessage: msg,
log,
track,
requestId,
connectionInfo,
});
dispatch({
type: AIQueryActionTypes.AIQueryFailed,
errorMessage: msg,
});
return;
}
const queryFields = {
...mapQueryToFormFields(
preferences.getPreferences(),
DEFAULT_FIELD_VALUES
),
...generatedFields,
};
log.info(
mongoLogId(1_001_000_199),
'AIQuery',
'AI query request succeeded',
{
requestId,
shape: Object.keys(generatedFields),
}
);
track(
'AI Response Generated',
() => ({
editor_view_type: 'find' as const,
query_shape: Object.keys(generatedFields),
request_id: requestId,
}),
connectionInfo
);
dispatch({
type: AIQueryActionTypes.AIQuerySucceeded,
fields: queryFields,
requestId,
});
};
};
type CancelAIQueryAction = {
type: typeof AIQueryActionTypes.CancelAIQuery;
};
export const cancelAIQuery = (): QueryBarThunkAction<
void,
CancelAIQueryAction
> => {
return (dispatch, getState) => {
// Abort any ongoing op.
const existingRequestId = getState().aiQuery.aiQueryRequestId;
if (existingRequestId !== null) {
abort(existingRequestId);
}
dispatch({
type: AIQueryActionTypes.CancelAIQuery,
});
};
};
export const showInput = (): QueryBarThunkAction<Promise<void>> => {
return async (dispatch, _getState, { atlasAiService }) => {
try {
if (process.env.COMPASS_E2E_SKIP_AI_OPT_IN !== 'true') {
await atlasAiService.ensureAiFeatureAccess();
}
dispatch({ type: AIQueryActionTypes.ShowInput });
} catch {
// if sign in failed / user canceled we just don't show the input
}
};
};
export const hideInput = (): QueryBarThunkAction<void, HideInputAction> => {
return (dispatch) => {
// Cancel any ongoing op when we hide.
dispatch(cancelAIQuery());
dispatch({ type: AIQueryActionTypes.HideInput });
};
};
const aiQueryReducer: Reducer<AIQueryState, Action> = (
state = initialState,
action
) => {
if (
isAction<AIQueryStartedAction>(action, AIQueryActionTypes.AIQueryStarted)
) {
return {
...state,
status: 'fetching',
errorMessage: undefined,
aiQueryRequestId: action.requestId,
};
}
if (isAction<AIQueryFailedAction>(action, AIQueryActionTypes.AIQueryFailed)) {
// If fetching query failed due to authentication error, reset the state to
// hide the input and show the "Generate query" button again: this should start
// the sign in flow for the user when clicked
if (action.statusCode === 401) {
return { ...initialState };
}
return {
...state,
status: 'ready',
aiQueryRequestId: null,
errorMessage: action.errorMessage,
errorCode: action.errorCode,
};
}
if (
isAction<AIQuerySucceededAction>(
action,
AIQueryActionTypes.AIQuerySucceeded
)
) {
return {
...state,
status: 'success',
aiQueryRequestId: null,
lastAIQueryRequestId: action.requestId,
};
}
if (isAction<CancelAIQueryAction>(action, AIQueryActionTypes.CancelAIQuery)) {
return {
...state,
status: 'ready',
aiQueryRequestId: null,
};
}
if (isAction<ShowInputAction>(action, AIQueryActionTypes.ShowInput)) {
return {
...state,
isInputVisible: true,
};
}
if (isAction<HideInputAction>(action, AIQueryActionTypes.HideInput)) {
return {
...state,
isInputVisible: false,
};
}
if (
isAction<ChangeAIPromptTextAction>(
action,
AIQueryActionTypes.ChangeAIPromptText
)
) {
return {
...state,
// Reset the status after a successful run when the user change's the text.
status: state.status === 'success' ? 'ready' : state.status,
aiPromptText: action.text,
};
}
return state;
};
export { aiQueryReducer };