-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpromptCompletion.ts
229 lines (193 loc) · 5.56 KB
/
promptCompletion.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
import * as vscode from "vscode";
import path from "node:path";
import Logger from "../logger";
import { tokenizer } from "./tokenizer";
import { embeddings } from "../embedding/embedding";
const tokenize = async (text: string): Promise<number> => {
try {
const startLocal = performance.now();
const tokens = tokenizer.encode(text);
const endLocal = performance.now();
Logger.debug(
`Tokenized ${text.length} local: ${(endLocal - startLocal).toFixed(
2
)} CountTokens: ${tokens.length}`
);
return tokens.length + 1;
} catch (error) {
return 0;
}
};
const getTextNormalized = (text: string) => {
return text
.replaceAll("<|fim_prefix|>", "")
.replaceAll("<|fim_middle|>", "")
.replaceAll("<|fim_suffix|>", "")
.replaceAll("<|file_separator|>", "");
};
const spliteDocumentByPosition = (
document: vscode.TextDocument,
position: vscode.Position
): [string, string] => {
const textBefore = getTextNormalized(
document.getText(new vscode.Range(new vscode.Position(0, 0), position))
);
const textAfter = getTextNormalized(
document.getText(
new vscode.Range(
position,
new vscode.Position(
document.lineCount,
document.lineAt(document.lineCount - 1).text.length
)
)
)
);
return [textBefore, textAfter];
};
const processingDocumentWithPosition = async ({
document,
position,
maxToken,
}: {
document: vscode.TextDocument;
position: vscode.Position;
maxToken: number;
}) => {
const [textBefore, textAfter] = spliteDocumentByPosition(document, position);
let textLength = maxToken;
let textBeforeSlice: string;
let textAfterSlice: string;
let tokens = 0;
while (true) {
textBeforeSlice = textBefore.slice((textLength / 2) * 3 * -1);
textAfterSlice = textAfter.slice(0, (textLength / 2) * 3);
tokens = await tokenize(textBeforeSlice + textAfterSlice);
const tokenDifference = Math.abs(maxToken - tokens);
const maxDifference = Math.max(maxToken * 0.1, 50);
Logger.debug(`${document.fileName} document tokens: ${tokens}`);
if (
(tokens <= maxToken &&
textBeforeSlice.length >= textBefore.length &&
textAfterSlice.length >= textAfter.length) ||
tokenDifference <= maxDifference
) {
return {
documentText: `${textBeforeSlice}<|fim_suffix|>${textAfterSlice}`,
documentTokens: tokens,
};
}
if (tokens <= maxToken) {
textLength += 30;
} else {
textLength -= 60;
}
}
};
const processingDocument = async ({
document,
maxToken,
}: {
document: vscode.TextDocument;
maxToken: number;
}) => {
const text = getTextNormalized(document.getText());
let textLength = maxToken;
let textSlice: string;
let tokens = 0;
while (true) {
textSlice = text.slice(0, Number(textLength.toFixed(0)) * 3);
tokens = await tokenize(textSlice);
const tokenDifference = Math.abs(maxToken - tokens);
const maxDifference = Math.max(maxToken * 0.1, 50);
Logger.debug(`${document.fileName} document tokens: ${tokens}`);
if (
(tokens <= maxToken && textSlice.length >= text.length) ||
tokenDifference <= maxDifference
) {
return {
documentText: textSlice,
documentTokens: tokens,
};
}
if (tokens <= maxToken) {
textLength += 30;
} else {
textLength -= 60;
}
}
};
const getRelativePath = (uri: vscode.Uri) => {
const workspacePath = vscode.workspace.getWorkspaceFolder(uri)?.uri.fsPath;
const relativePath = path.relative(workspacePath ?? "", uri.fsPath);
return relativePath;
};
export const getPromptCompletion = async ({
activeDocument,
additionalDocuments,
position,
maxTokenExpect = 200,
}: {
activeDocument: vscode.TextDocument;
additionalDocuments: vscode.TextDocument[];
position: vscode.Position;
maxTokenExpect: number;
}) => {
const start = performance.now();
const maxTokenHardLimit = 4000;
const maxToken =
maxTokenExpect > maxTokenHardLimit ? maxTokenHardLimit : maxTokenExpect;
const {
documentTokens: activeDocumentTokens,
documentText: activeDocumentText,
} = await processingDocumentWithPosition({
document: activeDocument,
position,
maxToken,
});
let additionalDocumentsText = "";
const documentsFromEmbeddings = await embeddings.getRelativeDocuments(
activeDocument
);
if (
additionalDocuments.length !== 0 &&
maxToken - activeDocumentTokens > 100
) {
let restTokens = maxToken - activeDocumentTokens;
for (const document of additionalDocuments) {
if (restTokens <= 50) {
break;
}
const { documentText, documentTokens } = await processingDocument({
document,
maxToken: restTokens,
});
const documentName = document.fileName;
Logger.debug(
`${documentName} document tokens resualt: ${documentTokens}`
);
additionalDocumentsText +=
"/" +
getRelativePath(document.uri) +
"\n" +
"<|fim_prefix|>" +
documentText +
"<|fim_middle|>" +
"<|file_separator|>";
restTokens -= documentTokens;
}
}
const activeDocumentFileName =
additionalDocumentsText === ""
? "<|fim_prefix|>"
: "\n" +
"/" +
getRelativePath(activeDocument.uri) +
"\n" +
"<|fim_prefix|>";
const end = performance.now();
Logger.debug(`Full Time: ${(end - start).toFixed(2)}ms`);
const prompt = `${additionalDocumentsText}${activeDocumentFileName}${activeDocumentText}<|fim_middle|>`;
console.log(prompt);
return prompt;
};