⚡️ increase cache hit rate for autocomplete

This commit is contained in:
Nate Sesti 2024-06-05 20:48:03 -07:00
parent 80557afb4f
commit 44d446f8ff
2 changed files with 23 additions and 14 deletions

View file

@ -29,36 +29,41 @@ export class AutocompleteLruCache {
return new AutocompleteLruCache(db);
}
async get(key: string): Promise<string | undefined> {
async get(prefix: string): Promise<string | undefined> {
// If the query is "co" and we have "c" -> "ontinue" in the cache,
// we should return "ntinue" as the completion.
// Have to make sure we take the key with shortest length
const result = await this.db.get(
"SELECT value FROM cache WHERE key = ?",
key,
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
prefix,
);
if (result) {
// Validate that the cached compeltion is a valid completion for the prefix
if (result && result.value.startsWith(prefix.slice(result.key.length))) {
await this.db.run(
"UPDATE cache SET timestamp = ? WHERE key = ?",
Date.now(),
key,
prefix,
);
return result.value;
// And then truncate so we aren't writing something that's already there
return result.value.slice(prefix.length - result.key.length);
}
return undefined;
}
async put(key: string, value: string) {
async put(prefix: string, completion: string) {
const result = await this.db.get(
"SELECT key FROM cache WHERE key = ?",
key,
prefix,
);
if (result) {
await this.db.run(
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
value,
completion,
Date.now(),
key,
prefix,
);
} else {
const count = await this.db.get("SELECT COUNT(*) as count FROM cache");
@ -71,8 +76,8 @@ export class AutocompleteLruCache {
await this.db.run(
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
key,
value,
prefix,
completion,
Date.now(),
);
}

View file

@ -69,6 +69,8 @@ export interface AutocompleteInput {
export interface AutocompleteOutcome extends TabAutocompleteOptions {
accepted?: boolean;
time: number;
prefix: string;
suffix: string;
prompt: string;
completion: string;
modelProvider: string;
@ -304,7 +306,7 @@ export async function getTabCompletion(
const cache = await autocompleteCache;
const cachedCompletion = options.useCache
? await cache.get(prompt)
? await cache.get(prefix)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
@ -409,6 +411,8 @@ export async function getTabCompletion(
return {
time,
completion,
prefix,
suffix,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
@ -623,7 +627,7 @@ export class CompletionProvider {
const completionToCache = outcome.completion;
setTimeout(async () => {
if (!outcome.cacheHit) {
(await this.autocompleteCache).put(outcome.prompt, completionToCache);
(await this.autocompleteCache).put(outcome.prefix, completionToCache);
}
}, 100);