Skip to content

Commit c49ecfd

Browse files
igardevigardev
andauthored
core : remove repeating suffix of a suggestion + fix speculative FIM (#18)
* Remove repeating suffix of a suggestion * If linesuffix is empty - cut the repeating suffix of the suggestion. * If there is a linesuffix, suggest only one line, don't make hidden second request * Fix the caching of the future suggestion in case of max inputPrefix length. --------- Co-authored-by: igardev <[email protected]>
1 parent 01cf5c8 commit c49ecfd

File tree

1 file changed

+50
-7
lines changed

1 file changed

+50
-7
lines changed

src/architect.ts

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
// TODO
2-
// По подразбиране порта по подразбиране да е друг (сървера и екстеншъна) - примерно 8012 (за да няма конфликти)
3-
// Да не премигва при избор само на ред или дума (върни частично проверката за съвпадение с последния рекуест?)
2+
// Ако има linesuffix да се остави от suggestion само първия ред (намаляване на дължината на отговора при заявката?)
3+
// При кеширане на следваща заявка да се отрязват от префикса първите няколко реда ако е необходимо
44
// Profiling - провери кое колко време отнема, за да оптимизираш (примерно пускай паралелно информацията в статус бара..., по-малко търсене в кеша...)
55
// - Търсенето в кеша при 250 елемента и 49 символа отнема 1/5 милисекунда => може по-голям кеш, може търсене до началото на реда
66
// - ShowInfo < 1/10 мс
7+
// Да не премигва при избор само на ред или дума (върни частично проверката за съвпадение с последния рекуест?)
78
// (Нисък приоритет) Прозорец на майкософт интелисенс - да не се показва или нещо друго по-красиво
89
import * as vscode from 'vscode';
910
import { LRUCache } from './lru-cache';
@@ -391,24 +392,26 @@ export class Architect {
391392

392393
let suggestionLines = completion.split(/\r?\n/)
393394
this.removeTrailingNewLines(suggestionLines);
394-
completion = suggestionLines.join('\n')
395395

396396
if (this.shouldDiscardSuggestion(suggestionLines, document, position, linePrefix, lineSuffix)) {
397397
this.showInfo(undefined);
398398
this.isRequestInProgress = false
399399
this.addEventLog(group, "DISCARD_SUGGESTION_RETURN", "")
400400
return [];
401401
}
402+
completion = this.updateSuggestion( suggestionLines, document, position, linePrefix, lineSuffix);
402403
if (!isCachedResponse) this.lruResultCache.put(hashKey, completion)
403404
this.lastCompletion = this.getCompletionDetails(completion, position, inputPrefix, inputSuffix, prompt);
404405

405406
// Run async as not needed for the suggestion
406407
setTimeout(async () => {
407408
if (isCachedResponse) this.showCachedInfo()
408409
else this.showInfo(data);
409-
if (!(token.isCancellationRequested)){
410+
if (!token.isCancellationRequested && lineSuffix.trim() === ""){
410411
await this.cacheFutureSuggestion(inputPrefix, inputSuffix, prompt, suggestionLines);
411412
await this.cacheFutureAcceptLineSuggestion(inputPrefix, inputSuffix, prompt, suggestionLines);
413+
}
414+
if (!token.isCancellationRequested){
412415
this.extraContext.addFimContextChunks(position, context, document);
413416
}
414417
}, 0);
@@ -506,11 +509,11 @@ export class Architect {
506509
const isLanguageEnabled = currentLanguage ? this.isCompletionEnabled(editor.document) : true;
507510

508511
if (!isEnabled) {
509-
this.myStatusBarItem.text = "$(x) Llama";
512+
this.myStatusBarItem.text = "$(x) llama.vscode";
510513
} else if (currentLanguage && !isLanguageEnabled) {
511-
this.myStatusBarItem.text = `$(x) Llama (${currentLanguage})`;
514+
this.myStatusBarItem.text = `$(x) llama.vscode (${currentLanguage})`;
512515
} else {
513-
this.myStatusBarItem.text = "$(check) Llama";
516+
this.myStatusBarItem.text = "$(check) llama.vscode";
514517
}
515518
}
516519

@@ -534,6 +537,10 @@ export class Architect {
534537
if (suggestionLines.length > 1) {
535538
futureInputPrefix = inputPrefix + prompt + suggestionLines.slice(0, -1).join('\n') + '\n';
536539
futurePrompt = suggestionLines[suggestionLines.length - 1];
540+
let futureInputPrefixLines = futureInputPrefix.slice(0,-1).split(/\r?\n/)
541+
if (futureInputPrefixLines.length > this.extConfig.n_prefix){
542+
futureInputPrefix = futureInputPrefixLines.slice(futureInputPrefixLines.length - this.extConfig.n_prefix).join('\n')+ '\n';
543+
}
537544
}
538545
let futureHashKey = this.lruResultCache.getHash(futureInputPrefix + "|" + futureInputSuffix + "|" + futurePrompt)
539546
let cached_completion = this.lruResultCache.get(futureHashKey)
@@ -662,6 +669,42 @@ export class Architect {
662669
return discardSuggestion;
663670
}
664671

672+
// returns suggestion with removed trailing part, which is the same as the existing code
673+
updateSuggestion = (suggestionLines: string[], document: vscode.TextDocument, position: vscode.Position, linePrefix: string, lineSuffix: string) => {
674+
let updatedSuggestion = suggestionLines.join("\n");
675+
if (suggestionLines.length == 1 && lineSuffix.trim() === "") return updatedSuggestion
676+
// if suggestion is one line and the line suffix is a suffix of the line - remove the line suffix
677+
if (suggestionLines.length == 1 && suggestionLines[0].endsWith(lineSuffix)) return suggestionLines[0].slice(0, -lineSuffix.length);
678+
679+
// if cursor on the last line just return the suggestion
680+
if (position.line == document.lineCount - 1) return updatedSuggestion;
681+
682+
// if the following lines repeat the suggestion and the line suffix is empty - update suggestion
683+
if (suggestionLines.length > 1
684+
&& (lineSuffix.trim() === "")) {
685+
let linesToCompareCount = suggestionLines.length - 1
686+
// if cursor on the last line don't discard
687+
if (position.line + linesToCompareCount > document.lineCount - 1) return updatedSuggestion;
688+
let indLastSuggestionLine = suggestionLines.slice(1).reverse().findIndex((value, index) => value != document.lineAt((position.line + linesToCompareCount) - index).text)
689+
return suggestionLines.slice(0, indLastSuggestionLine + 2).join("\n"); // if indLastSuggestionLine is -1 then all following lines are the same as the suggestion
690+
}
691+
692+
// if the following lines repeat the suggestion and the first line ends with the line suffix update suggestion
693+
if (suggestionLines.length > 1
694+
&& suggestionLines[0].endsWith(lineSuffix)
695+
&& suggestionLines.slice(1).every((value, index) => value === document.lineAt((position.line + 1) + index).text)){
696+
return suggestionLines[0].slice(0, -lineSuffix.length);
697+
}
698+
699+
// if there is a line suffix suggest only one line
700+
if (suggestionLines.length > 1
701+
&& lineSuffix.trim() != ""){
702+
return suggestionLines[0];
703+
}
704+
705+
return updatedSuggestion;
706+
}
707+
665708
private getCompletionDetails = (completion: string, position: vscode.Position, inputPrefix: string, inputSuffix: string, prompt: string) => {
666709
return { suggestion: completion, position: position, inputPrefix: inputPrefix, inputSuffix: inputSuffix, prompt: prompt };
667710
}

0 commit comments

Comments
 (0)