🎨 refactor to allow storing embeddings from multiple sources

This commit is contained in:
Nate Sesti 2024-01-10 12:23:00 -08:00
parent 2a2ce80577
commit 4fcb1d7ee4
17 changed files with 190 additions and 95 deletions

View file

@ -36,7 +36,8 @@ class CodebaseContextProvider extends BaseContextProvider {
const results = await new ExtensionIde().retrieveChunks(
v,
this.options.useReranking === false ? nFinal : nRetrieve,
[]
[],
extras.embeddingsProvider.id
);
// Re-ranking

View file

@ -108,13 +108,18 @@ class FileSystemIde implements IDE {
return "";
}
getFilesToEmbed(): Promise<[string, string, string][]> {
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
return Promise.resolve([]);
}
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {}
retrieveChunks(v: number[], n: number, tags: string[]): Promise<Chunk[]> {
retrieveChunks(
v: number[],
n: number,
tags: string[],
providerId: string
): Promise<Chunk[]> {
return Promise.resolve([]);
}
}

View file

@ -88,15 +88,20 @@ export class ExtensionIde implements IDE {
return r("getSearchResults", { query });
}
getFilesToEmbed(): Promise<[string, string, string][]> {
return r("getFilesToEmbed");
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
return r("getFilesToEmbed", { providerId });
}
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {
return r("sendChunkForFile", { chunk, embedding, tags });
}
retrieveChunks(v: number[], n: number, tags: string[]): Promise<Chunk[]> {
return r("retrieveChunks", { v, n, tags });
retrieveChunks(
v: number[],
n: number,
tags: string[],
providerId: string
): Promise<Chunk[]> {
return r("retrieveChunks", { v, n, tags, providerId });
}
}

10
core/index.d.ts vendored
View file

@ -279,13 +279,18 @@ export interface IDE {
/**
* Returns list of [tag, filepath, hash of contents] that need to be embedded
*/
getFilesToEmbed(): Promise<[string, string, string][]>;
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
sendEmbeddingForChunk(
chunk: Chunk,
embedding: number[],
tags: string[]
): void;
retrieveChunks(v: number[], n: number, tags: string[]): Promise<Chunk[]>;
retrieveChunks(
v: number[],
n: number,
tags: string[],
providerId: string
): Promise<Chunk[]>;
}
// Slash Commands
@ -470,6 +475,7 @@ export interface EmbeddingsProviderDescription extends EmbedOptions {
}
export interface EmbeddingsProvider {
id: string;
embed(chunks: string[]): Promise<number[][]>;
}

View file

@ -4,6 +4,10 @@ class BaseEmbeddingsProvider implements EmbeddingsProvider {
options: EmbedOptions;
static defaultOptions: Partial<EmbedOptions> | undefined = undefined;
get id(): string {
throw new Error("Method not implemented.");
}
constructor(options: EmbedOptions) {
this.options = {
...(this.constructor as typeof BaseEmbeddingsProvider).defaultOptions,

View file

@ -10,6 +10,10 @@ async function embedOne(chunk: string, options: EmbedOptions) {
}),
});
if (!resp.ok) {
throw new Error("Failed to embed chunk: " + (await resp.text()));
}
return (await resp.json()).embedding;
}
@ -18,6 +22,10 @@ class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
apiBase: "http://localhost:11434",
};
get id(): string {
return "ollama::" + this.options.model;
}
embed(chunks: string[]) {
return Promise.all(chunks.map((chunk) => embedOne(chunk, this.options)));
}

View file

@ -7,6 +7,10 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "text-embedding-ada-002",
};
get id(): string {
return "openai::" + this.options.model;
}
async embed(chunks: string[]) {
let apiBase = this.options.apiBase;
if (apiBase?.endsWith("/")) {

View file

@ -3,6 +3,10 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
providerName: string = "transformers.js";
get id(): string {
return "transformers.js";
}
constructor() {
super({ model: "all-MiniLM-L2-v6" });
}

View file

@ -333,7 +333,7 @@ export function getSidebarContent(
break;
}
case "getFilesToEmbed": {
let filesToEmbed = await ide.getFilesToEmbed();
let filesToEmbed = await ide.getFilesToEmbed(data.message.providerId);
respond(filesToEmbed);
break;
}
@ -352,7 +352,8 @@ export function getSidebarContent(
await ide.retrieveChunks(
data.message.v,
data.message.n,
data.message.tags
data.message.tags,
data.message.providerId
)
);
break;

View file

@ -301,13 +301,15 @@ class VsCodeIde implements IDE {
return results.join("\n\n");
}
async getFilesToEmbed(): Promise<[string, string, string][]> {
async getFilesToEmbed(
providerId: string
): Promise<[string, string, string][]> {
let results = [];
let branch = await ideProtocolClient.getBranch();
for (let dir of await this.getWorkspaceDirs()) {
let tag = `${dir}::${branch}`;
let sync_results = sync.sync_results(dir, branch);
results.push(...sync_results.map((r: any) => [tag, r.name, r.hash]));
let tag = `${dir}::${branch}::${providerId}`; // TODO (don't build the string here ideally)
let filesToEmbed = sync.sync_results(dir, branch, providerId);
results.push(...filesToEmbed.map((r: any) => [tag, r.name, r.hash]));
}
return results;
}
@ -323,14 +325,15 @@ class VsCodeIde implements IDE {
async retrieveChunks(
v: number[],
n: number,
tags: string[]
tags: string[],
providerId: string
): Promise<Chunk[]> {
// TODO: OR clause with tags
let branch = await ideProtocolClient.getBranch();
let dirs = await this.getWorkspaceDirs();
let branchTag = `${dirs[0] || "NONE"}::${branch}`;
let sync_results = sync.retrieve(n, [...tags, branchTag], v);
return sync_results;
let mainTag = `${dirs[0] || "NONE"}::${branch}::${providerId}`;
let chunks = sync.retrieve(n, [...tags, mainTag], v);
return chunks;
}
}

View file

@ -79,7 +79,7 @@ async function resolveEditorContent(
if (slashCommand) {
finalText = `${slashCommand} ${finalText}`;
}
console.log(finalText, editorState?.content);
return finalText;
}

View file

@ -23,7 +23,7 @@ function useLoadEmbeddings() {
const ide = new ExtensionIde();
const filesToEmbed = await ide.getFilesToEmbed();
const filesToEmbed = await ide.getFilesToEmbed(embeddingsProvider.id);
const total = filesToEmbed.length + 1;
let done = 1;

View file

@ -8,6 +8,10 @@ class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
super({ model: "all-MiniLM-L2-v6" });
}
get id(): string {
return "transformers-js";
}
embed(chunks: string[]) {
return new Promise<number[][]>(async (resolve) => {
if (!worker) {

View file

@ -4,7 +4,7 @@ This is a small Rust library for efficiently keeping a codebase index up to date
### How it works
> Important definition: a _tag_ is a (workspace, branch) pair that uniquely identifies an index. Since we use content-based addressing within the index, much of the data is shared for efficiency.
> Important definition: a _tag_ is a (workspace, branch, provider_id) pair that uniquely identifies an index. Since we use content-based addressing within the index, much of the data is shared for efficiency.
The output of the sync_results function is a list of 4 lists of tuples. Each tuple contains a file path and a hash of the file contents. The 4 lists are:
@ -37,11 +37,11 @@ Thereafter, the following steps are performed:
Several files are stored and updated on disk in the ~/.continue/index folder to keep track of indexed files:
- `~/.continue/index/tags/<dir>/<branch>/merkle_tree` - the last computed Merkle tree of the codebase for a given tag
- `~/.continue/index/tags/<dir>/<branch>/.last_sync` - the last time the tag was synced
- `~/.continue/index/tags/<dir>/<branch>/<provider_id>/merkle_tree` - the last computed Merkle tree of the codebase for a given tag
- `~/.continue/index/tags/<dir>/<branch>/<provider_id>/.last_sync` - the last time the tag was synced
- The index cache contains a list of hashes that have already been computed both in general and per tag. These are always kept in sync.
- `~/.continue/index/.index_cache` - contains the global cache (flat file of hashes)
- `~/.continue/index/tags/<dir>/<branch>/.index_cache` - contains the tag-specific cache (flat file of hashes)
- `~/.continue/index/tags/<dir>/<branch>/<provider_id>/.index_cache` - contains the tag-specific cache (flat file of hashes)
- `~/.continue/index/rev_tags` - contains a mapping from hash to tags that the hash is currently indexed for. This is a directory of files, where each file is prefixed with the first 2 characters of the hash. The file is a JSON mapping from hash to list of tags.
### Files

View file

@ -29,9 +29,15 @@ fn build_js_array<'a>(
fn sync_results(mut cx: FunctionContext) -> JsResult<JsArray> {
let dir = cx.argument::<JsString>(0)?.value(&mut cx);
let branch = cx.argument::<JsString>(1)?.value(&mut cx);
let tag = format!("{}::{}", dir, branch);
let provider_id = cx.argument::<JsString>(2)?.value(&mut cx);
let compute = sync_db::sync_db(Path::new(&dir), branch, tag);
let tag = sync::Tag {
dir: Path::new(&dir),
branch: &branch,
provider_id: &provider_id.to_string(),
};
let compute = sync_db::sync_db(&tag);
let compute_js_array = build_js_array(compute, &mut cx);
return Ok(compute_js_array);

View file

@ -11,6 +11,24 @@ use std::{
use self::merkle::{ObjDescription, Tree};
#[derive(Clone)]
pub struct Tag<'a> {
pub dir: &'a Path,
pub branch: &'a str,
pub provider_id: &'a str,
}
impl<'a> Tag<'a> {
pub fn to_string(&self) -> String {
return format!(
"{}::{}::{}",
self.dir.to_str().unwrap(),
self.branch,
self.provider_id
);
}
}
fn remove_seps_from_path(dir: &Path) -> String {
let mut path = String::new();
for component in dir.components() {
@ -24,22 +42,19 @@ fn remove_seps_from_path(dir: &Path) -> String {
return path;
}
fn path_for_tag(dir: &Path, branch: Option<&str>) -> PathBuf {
fn path_for_tag(tag: &Tag) -> PathBuf {
let mut path = get_my_home().unwrap().unwrap();
path.push(".continue/index/tags");
path.push(remove_seps_from_path(dir));
if let Some(branch) = branch {
path.push(branch);
} else {
path.push("main");
}
path.push(remove_seps_from_path(tag.dir));
path.push(tag.branch);
path.push(tag.provider_id);
return path;
}
/// Stored in ~/.continue/index/.last_sync
fn get_last_sync_time(dir: &Path, branch: Option<&str>) -> u64 {
fn get_last_sync_time(tag: &Tag) -> u64 {
// TODO: Error handle here
let path = path_for_tag(dir, branch).join(".last_sync");
let path = path_for_tag(tag).join(".last_sync");
let mut file = File::open(path).unwrap();
let mut contents = String::new();
@ -49,8 +64,8 @@ fn get_last_sync_time(dir: &Path, branch: Option<&str>) -> u64 {
return last_sync_time;
}
fn write_sync_time(dir: &Path, branch: Option<&str>) {
let path = path_for_tag(dir, branch).join(".last_sync");
fn write_sync_time(tag: &Tag) {
let path = path_for_tag(tag).join(".last_sync");
let mut file = File::create(path).unwrap();
let now = SystemTime::now()
@ -61,10 +76,10 @@ fn write_sync_time(dir: &Path, branch: Option<&str>) {
}
/// Use stat to find files since last sync time
pub fn get_modified_files(dir: &Path, branch: Option<&str>) -> Vec<PathBuf> {
let last_sync_time = get_last_sync_time(dir, branch);
pub fn get_modified_files(tag: &Tag) -> Vec<PathBuf> {
let last_sync_time = get_last_sync_time(tag);
let mut modified_files = Vec::new();
for entry in build_walk(dir) {
for entry in build_walk(tag.dir) {
let entry = entry.unwrap();
let path = entry.path();
let metadata = path.metadata().unwrap();
@ -154,53 +169,54 @@ impl DiskSet {
}
}
struct IndexCache {
dir: Box<Path>,
branch: Box<str>,
struct IndexCache<'a> {
tag: Box<Tag<'a>>,
global_cache: DiskSet,
tag_cache: DiskSet,
}
impl IndexCache {
fn index_cache_path_for_tag(dir: &Path, branch: &str) -> PathBuf {
let mut path = path_for_tag(dir, Some(branch));
impl<'a> IndexCache<'a> {
fn index_cache_path_for_tag(tag: &Tag) -> PathBuf {
let mut path = path_for_tag(tag);
path.push(".index_cache");
return path;
}
fn rev_tags_path(hash: [u8; ITEM_SIZE]) -> PathBuf {
fn rev_tags_dir(provider_id: &str) -> PathBuf {
let mut path = IndexCache::provider_dir(provider_id);
path.push("rev_tags");
return path;
}
fn rev_tags_path(hash: [u8; ITEM_SIZE], provider_id: &str) -> PathBuf {
let hash_str = hash_string(hash);
let mut path = get_my_home().unwrap().unwrap();
path.push(".continue/index/rev_tags");
let mut path = IndexCache::rev_tags_dir(provider_id);
// Branch by 1) first two chars of hash
path.push(&hash_str[0..2]);
return path;
}
fn tag_str(&self) -> String {
return format!("{}::{}", self.dir.to_str().unwrap(), self.branch);
return self.tag.to_string();
}
fn new(dir: &Path, branch: Option<&str>) -> IndexCache {
fn provider_dir(provider_id: &str) -> PathBuf {
let mut path = get_my_home().unwrap().unwrap();
path.push(".continue/index/providers");
path.push(provider_id);
return path;
}
fn new(tag: &'a Tag) -> IndexCache<'a> {
return IndexCache {
dir: Box::from(dir),
branch: match branch {
Some(branch) => Box::from(branch),
None => Box::from("main"),
},
tag: Box::new(tag.clone()),
global_cache: DiskSet::new(
get_my_home()
.unwrap()
.unwrap()
.join(".continue/index/.index_cache")
.to_str()
.unwrap(),
),
tag_cache: DiskSet::new(
IndexCache::index_cache_path_for_tag(dir, branch.unwrap_or("main"))
IndexCache::provider_dir(tag.provider_id)
.join(".index_cache")
.to_str()
.unwrap(),
),
tag_cache: DiskSet::new(IndexCache::index_cache_path_for_tag(tag).to_str().unwrap()),
};
}
@ -210,7 +226,7 @@ impl IndexCache {
// TODO: You could add_bulk, remove_bulk if this gets slow
fn read_rev_tags(&self, hash: [u8; ITEM_SIZE]) -> HashMap<String, Vec<String>> {
let rev_tags_path = IndexCache::rev_tags_path(hash);
let rev_tags_path = IndexCache::rev_tags_path(hash, self.tag.provider_id);
let mut rev_tags_file = OpenOptions::new()
.read(true)
.write(true)
@ -226,7 +242,7 @@ impl IndexCache {
}
fn write_rev_tags(&self, hash: [u8; ITEM_SIZE], rev_tags: HashMap<String, Vec<String>>) {
let rev_tags_path = IndexCache::rev_tags_path(hash);
let rev_tags_path = IndexCache::rev_tags_path(hash, self.tag.provider_id);
let mut rev_tags_file = OpenOptions::new()
.read(true)
.write(true)
@ -309,8 +325,7 @@ impl IndexCache {
}
pub fn sync(
dir: &Path,
branch: Option<&str>,
tag: &Tag,
) -> Result<
(
Vec<(String, String)>,
@ -322,12 +337,12 @@ pub fn sync(
> {
// Make sure that the tag directory exists
// Create the directory and all its parent directories if they don't exist
fs::create_dir_all(path_for_tag(dir, branch)).unwrap();
if let Some(parent) = IndexCache::rev_tags_path([0; ITEM_SIZE]).parent() {
fs::create_dir_all(path_for_tag(tag)).unwrap();
if let Some(parent) = IndexCache::rev_tags_path([0; ITEM_SIZE], tag.provider_id).parent() {
fs::create_dir_all(parent).unwrap();
}
let mut tree_path = path_for_tag(dir, branch);
let mut tree_path = path_for_tag(tag);
tree_path.push("merkle_tree");
let old_tree: Tree = match Tree::load(&tree_path) {
Ok(tree) => tree,
@ -337,10 +352,10 @@ pub fn sync(
// Calculate and save new tree
// TODO: Use modified files to speed up calculation
// let modified_files = get_modified_files(dir, branch);
let new_tree = compute_tree_for_dir(dir, None)?;
let new_tree = compute_tree_for_dir(tag.dir, None)?;
// Update last sync time
write_sync_time(dir, branch);
write_sync_time(tag);
// Save new tree
new_tree.persist(&tree_path);
@ -351,7 +366,7 @@ pub fn sync(
// Compute the four action types: compute, remove, add tag, remove tag,
// transform into desired format: [(path, hash), ...],
// and update .index_cache
let mut index_cache = IndexCache::new(dir, branch);
let mut index_cache = IndexCache::new(tag);
let mut compute: Vec<(String, String)> = Vec::new();
let mut delete: Vec<(String, String)> = Vec::new();
@ -459,26 +474,45 @@ mod tests {
#[test]
fn test_sync() {
let ti = std::time::Instant::now();
let results = sync(Path::new("../"), Some("nate/pyO3"));
let tag = Tag {
dir: Path::new("../"),
branch: "nate/pyO3",
provider_id: "default",
};
let results = sync(&tag);
println!("Sync took {:?}", ti.elapsed());
// Vast majority (90+%) of this time is spent in compute_tree_for_dir
}
#[test]
fn test_on_vscode_extension() {
let results = sync(Path::new("../extensions/vscode"), Some("nate/pyO3"));
let results = sync(&Tag {
dir: Path::new("../extensions/vscode"),
branch: "nate/pyO3",
provider_id: "default",
});
}
#[test]
fn test_double_sync() {
let ti = std::time::Instant::now();
let results = sync(Path::new("../"), Some("nate/pyO3")).expect("Sync failed.");
let results = sync(&Tag {
dir: Path::new("../"),
branch: "nate/pyO3",
provider_id: "default",
})
.expect("Sync failed.");
println!("First sync took {:?}", ti.elapsed());
assert!(results.0.len() > 0);
assert!(results.1.len() > 0);
let ti = std::time::Instant::now();
let results = sync(Path::new("../"), Some("nate/pyO3")).expect("Sync failed");
let results = sync(&Tag {
dir: Path::new("../"),
branch: "nate/pyO3",
provider_id: "default",
})
.expect("Sync failed");
println!("Second sync took {:?}", ti.elapsed());
assert_eq!(results.0.len(), 0);
assert_eq!(results.1.len(), 0);
@ -495,8 +529,13 @@ mod tests {
.add("__init__.py", "a = 5")
.create();
let tag = &Tag {
dir: temp_dir.path(),
branch: "BRANCH",
provider_id: "default",
};
// Sync once
sync(temp_dir.path(), Some("BRANCH")).expect("Sync failed.");
sync(&tag).expect("Sync failed.");
// Make changes
let mut file = File::create(temp_dir.path().join("dir1/file1.txt")).unwrap();
@ -505,7 +544,7 @@ mod tests {
file.write_all("File 3 changed".as_bytes()).unwrap();
// Sync again
let results = sync(temp_dir.path(), Some("BRANCH")).expect("Sync failed.");
let results = sync(tag).expect("Sync failed.");
// Check results
assert_eq!(results.0.len(), 2);
@ -515,8 +554,13 @@ mod tests {
// Start a new branch
let tag2 = &Tag {
dir: temp_dir.path(),
branch: "BRANCH2",
provider_id: "default",
};
// Sync again
let results = sync(temp_dir.path(), Some("BRANCH2")).expect("Sync failed.");
let results = sync(tag2).expect("Sync failed.");
// Check results
assert_eq!(results.0.len(), 0);
@ -528,7 +572,7 @@ mod tests {
remove_file(temp_dir.path().join("dir1/file2.txt")).unwrap();
// Sync again
let results = sync(temp_dir.path(), Some("BRANCH2")).expect("Sync failed.");
let results = sync(tag2).expect("Sync failed.");
// Check results
assert_eq!(results.0.len(), 0);

View file

@ -1,12 +1,10 @@
use std::path::Path;
use crate::db::{add_tag, create_database, remove_chunks_for_hash, remove_tag};
use crate::sync;
pub fn sync_db(dir: &Path, branch: String, tag: String) -> Vec<(String, String)> {
pub fn sync_db(tag: &sync::Tag) -> Vec<(String, String)> {
create_database();
let results = sync::sync(dir, Some(&branch)).unwrap();
let results = sync::sync(tag).unwrap();
// Send to IDE Extension to compute embeddings
let compute = results.0;
@ -18,12 +16,12 @@ pub fn sync_db(dir: &Path, branch: String, tag: String) -> Vec<(String, String)>
// Add tag from chunks
for (_, hash) in results.2 {
add_tag(hash, tag.clone());
add_tag(hash, tag.to_string());
}
// Remove tag from chunk_rows
for (_, hash) in results.3 {
remove_tag(hash, tag.clone());
remove_tag(hash, tag.to_string());
}
return compute;
@ -32,13 +30,15 @@ pub fn sync_db(dir: &Path, branch: String, tag: String) -> Vec<(String, String)>
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn test_nothing_fails() {
sync_db(
Path::new("../extensions/vscode"),
"main".to_string(),
"test::main".to_string(),
);
let tag = &sync::Tag {
dir: Path::new("../extensions/vscode"),
branch: "main",
provider_id: "test",
};
sync_db(tag);
}
}