-
Notifications
You must be signed in to change notification settings - Fork 8k
/
context.ts
308 lines (268 loc) · 9.26 KB
/
context.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
/*
* 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 { decodeOrThrow, jsonRt } from '@kbn/io-ts-utils';
import { Logger } from '@kbn/logging';
import type { Serializable } from '@kbn/utility-types';
import dedent from 'dedent';
import { encode } from 'gpt-tokenizer';
import * as t from 'io-ts';
import { compact, last, omit } from 'lodash';
import { lastValueFrom, Observable } from 'rxjs';
import { FunctionRegistrationParameters } from '.';
import { MessageAddEvent } from '../../common/conversation_complete';
import { FunctionVisibility, MessageRole, type Message } from '../../common/types';
import { concatenateChatCompletionChunks } from '../../common/utils/concatenate_chat_completion_chunks';
import type { ObservabilityAIAssistantClient } from '../service/client';
import { createFunctionResponseMessage } from '../service/util/create_function_response_message';
import { parseSuggestionScores } from './parse_suggestion_scores';
const MAX_TOKEN_COUNT_FOR_DATA_ON_SCREEN = 1000;
export function registerContextFunction({
client,
registerFunction,
resources,
isKnowledgeBaseAvailable,
}: FunctionRegistrationParameters & { isKnowledgeBaseAvailable: boolean }) {
registerFunction(
{
name: 'context',
contexts: ['core'],
description:
'This function provides context as to what the user is looking at on their screen, and recalled documents from the knowledge base that matches their query',
visibility: FunctionVisibility.AssistantOnly,
parameters: {
type: 'object',
additionalProperties: false,
properties: {
queries: {
type: 'array',
additionalItems: false,
additionalProperties: false,
description: 'The query for the semantic search',
items: {
type: 'string',
},
},
categories: {
type: 'array',
additionalItems: false,
additionalProperties: false,
description:
'Categories of internal documentation that you want to search for. By default internal documentation will be excluded. Use `apm` to get internal APM documentation, `lens` to get internal Lens documentation, or both.',
items: {
type: 'string',
enum: ['apm', 'lens'],
},
},
},
required: ['queries', 'categories'],
} as const,
},
async ({ arguments: args, messages, connectorId, screenContexts }, signal) => {
const { queries, categories } = args;
async function getContext() {
const systemMessage = messages.find(
(message) => message.message.role === MessageRole.System
);
const screenDescription = compact(
screenContexts.map((context) => context.screenDescription)
).join('\n\n');
// any data that falls within the token limit, send it automatically
const dataWithinTokenLimit = compact(
screenContexts.flatMap((context) => context.data)
).filter(
(data) => encode(JSON.stringify(data.value)).length <= MAX_TOKEN_COUNT_FOR_DATA_ON_SCREEN
);
const content = {
screen_description: screenDescription,
learnings: [],
...(dataWithinTokenLimit.length ? { data_on_screen: dataWithinTokenLimit } : {}),
};
if (!isKnowledgeBaseAvailable) {
return { content };
}
if (!systemMessage) {
throw new Error('No system message found');
}
const userMessage = last(
messages.filter((message) => message.message.role === MessageRole.User)
);
const nonEmptyQueries = compact(queries);
const queriesOrUserPrompt = nonEmptyQueries.length
? nonEmptyQueries
: compact([userMessage?.message.content]);
queriesOrUserPrompt.push(screenDescription);
const suggestions = await retrieveSuggestions({
userMessage,
client,
categories,
queries: queriesOrUserPrompt,
});
if (suggestions.length === 0) {
return {
content,
};
}
const { relevantDocuments, scores } = await scoreSuggestions({
suggestions,
queries: queriesOrUserPrompt,
messages,
client,
connectorId,
signal,
logger: resources.logger,
});
return {
content: { ...content, learnings: relevantDocuments as unknown as Serializable },
data: {
scores,
suggestions,
},
};
}
return new Observable<MessageAddEvent>((subscriber) => {
getContext()
.then(({ content, data }) => {
subscriber.next(
createFunctionResponseMessage({
name: 'context',
content,
data,
})
);
subscriber.complete();
})
.catch((error) => {
subscriber.error(error);
});
});
}
);
}
async function retrieveSuggestions({
queries,
client,
categories,
}: {
userMessage?: Message;
queries: string[];
client: ObservabilityAIAssistantClient;
categories: Array<'apm' | 'lens'>;
}) {
const recallResponse = await client.recall({
queries,
categories,
});
return recallResponse.entries.map((entry) => omit(entry, 'labels', 'is_correction', 'score'));
}
const scoreFunctionRequestRt = t.type({
message: t.type({
function_call: t.type({
name: t.literal('score'),
arguments: t.string,
}),
}),
});
const scoreFunctionArgumentsRt = t.type({
scores: t.string,
});
async function scoreSuggestions({
suggestions,
messages,
queries,
client,
connectorId,
signal,
logger,
}: {
suggestions: Awaited<ReturnType<typeof retrieveSuggestions>>;
messages: Message[];
queries: string[];
client: ObservabilityAIAssistantClient;
connectorId: string;
signal: AbortSignal;
logger: Logger;
}) {
const indexedSuggestions = suggestions.map((suggestion, index) => ({ ...suggestion, id: index }));
const newUserMessageContent =
dedent(`Given the following question, score the documents that are relevant to the question. on a scale from 0 to 7,
0 being completely irrelevant, and 7 being extremely relevant. Information is relevant to the question if it helps in
answering the question. Judge it according to the following criteria:
- The document is relevant to the question, and the rest of the conversation
- The document has information relevant to the question that is not mentioned,
or more detailed than what is available in the conversation
- The document has a high amount of information relevant to the question compared to other documents
- The document contains new information not mentioned before in the conversation
Question:
${queries.join('\n')}
Documents:
${JSON.stringify(indexedSuggestions, null, 2)}`);
const newUserMessage: Message = {
'@timestamp': new Date().toISOString(),
message: {
role: MessageRole.User,
content: newUserMessageContent,
},
};
const scoreFunction = {
name: 'score',
description:
'Use this function to score documents based on how relevant they are to the conversation.',
parameters: {
type: 'object',
additionalProperties: false,
properties: {
scores: {
description: `The document IDs and their scores, as CSV. Example:
my_id,7
my_other_id,3
my_third_id,4
`,
type: 'string',
},
},
required: ['score'],
} as const,
contexts: ['core'],
};
const response = await lastValueFrom(
(
await client.chat('score_suggestions', {
connectorId,
messages: [...messages.slice(0, -1), newUserMessage],
functions: [scoreFunction],
functionCall: 'score',
signal,
})
).pipe(concatenateChatCompletionChunks())
);
const scoreFunctionRequest = decodeOrThrow(scoreFunctionRequestRt)(response);
const { scores: scoresAsString } = decodeOrThrow(jsonRt.pipe(scoreFunctionArgumentsRt))(
scoreFunctionRequest.message.function_call.arguments
);
const scores = parseSuggestionScores(scoresAsString).map(({ index, score }) => {
return {
id: suggestions[index].id,
score,
};
});
if (scores.length === 0) {
// seemingly invalid or no scores, return all
return { relevantDocuments: suggestions, scores: [] };
}
const suggestionIds = suggestions.map((document) => document.id);
const relevantDocumentIds = scores
.filter((document) => suggestionIds.includes(document.id)) // Remove hallucinated documents
.filter((document) => document.score > 4)
.sort((a, b) => b.score - a.score)
.slice(0, 5)
.map((document) => document.id);
const relevantDocuments = suggestions.filter((suggestion) =>
relevantDocumentIds.includes(suggestion.id)
);
logger.debug(`Relevant documents: ${JSON.stringify(relevantDocuments, null, 2)}`);
return { relevantDocuments, scores };
}