From 7a701d8dacaaf39a1e21a1eba8659c38cbc56fe1 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 7 Jan 2024 13:52:11 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20convert=20chunking=20code=20to?= =?UTF-8?q?=20Typescript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/ide/filesystem.ts | 5 +- core/ide/index.ts | 7 +- core/index.d.ts | 8 +- core/index/chunk/basic.ts | 32 +++++ core/index/chunk/chunk.ts | 46 +++++++ core/index/chunk/code.ts | 181 +++++++++++++++++++++++++++ core/index/chunk/index.d.ts | 12 ++ core/package-lock.json | 19 ++- core/package.json | 3 +- extensions/vscode/src/debugPanel.ts | 6 +- extensions/vscode/src/ideProtocol.ts | 16 ++- gui/src/hooks/useLoadEmbeddings.tsx | 18 ++- sync/src/lib.rs | 15 ++- 13 files changed, 331 insertions(+), 37 deletions(-) create mode 100644 core/index/chunk/basic.ts create mode 100644 core/index/chunk/chunk.ts create mode 100644 core/index/chunk/code.ts create mode 100644 core/index/chunk/index.d.ts diff --git a/core/ide/filesystem.ts b/core/ide/filesystem.ts index e85e5c6c7..c14143250 100644 --- a/core/ide/filesystem.ts +++ b/core/ide/filesystem.ts @@ -1,5 +1,6 @@ import * as fs from "fs"; import { DiffLine, IDE, SerializedContinueConfig } from ".."; +import { Chunk } from "../index/chunk"; import { getConfigJsonPath, getConfigTsPath, @@ -107,11 +108,11 @@ class FileSystemIde implements IDE { return ""; } - getFilesToEmbed(): Promise<[string, string][]> { + getFilesToEmbed(): Promise<[string, string, string][]> { return Promise.resolve([]); } - sendChunkForFile(hash: string, embedding: number[], index: number) {} + sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {} } export default FileSystemIde; diff --git a/core/ide/index.ts b/core/ide/index.ts index 94f7c9b9a..6c6a074fe 100644 --- a/core/ide/index.ts +++ b/core/ide/index.ts @@ -1,5 +1,6 @@ import { DiffLine } from ".."; import { IDE, SerializedContinueConfig } from "../index"; +import { Chunk } from "../index/chunk"; import { ideRequest } from "./messaging"; async function r(messageType: string, options: any = {}) { return await ideRequest(messageType, options); @@ -87,11 +88,11 @@ export class ExtensionIde implements IDE { return r("getSearchResults", { query }); } - getFilesToEmbed(): Promise<[string, string][]> { + getFilesToEmbed(): Promise<[string, string, string][]> { return r("getFilesToEmbed"); } - sendChunkForFile(hash: string, embedding: number[], index: number) { - return r("sendChunkForFile", { hash, embedding }); + sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) { + return r("sendChunkForFile", { chunk, embedding, tags }); } } diff --git a/core/index.d.ts b/core/index.d.ts index 60e0e20f2..d46dd0a34 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,3 +1,5 @@ +import { Chunk } from "./index/chunk"; + export interface ILLM extends LLMOptions { get providerName(): ModelProvider; @@ -264,10 +266,10 @@ export interface IDE { // Embeddings /** - * Returns list of [filepath, hash of contents] that need to be embedded + * Returns list of [tag, filepath, hash of contents] that need to be embedded */ - getFilesToEmbed(): Promise<[string, string][]>; - sendChunkForFile(hash: string, embedding: number[], index: number); + getFilesToEmbed(): Promise<[string, string, string][]>; + sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]); } // Slash Commands diff --git a/core/index/chunk/basic.ts b/core/index/chunk/basic.ts new file mode 100644 index 000000000..00a105504 --- /dev/null +++ b/core/index/chunk/basic.ts @@ -0,0 +1,32 @@ +import { ChunkWithoutID } from "."; +import { countTokens } from "../../llm/countTokens"; + +export function* basicChunker( + contents: string, + maxChunkSize: number +): Generator { + let chunkContent = ""; + let chunkTokens = 0; + let startLine = 0; + let currLine = 0; + + for (const line of contents.split("\n")) { + const lineTokens = countTokens(line, "gpt-4"); + if (chunkTokens + lineTokens > maxChunkSize) { + yield { content: chunkContent, startLine, endLine: currLine - 1 }; + chunkContent = ""; + chunkTokens = 0; + startLine = currLine; + } + + chunkContent += line + "\n"; + chunkTokens += lineTokens; + currLine++; + } + + yield { + content: chunkContent, + startLine, + endLine: currLine - 1, + }; +} diff --git a/core/index/chunk/chunk.ts b/core/index/chunk/chunk.ts new file mode 100644 index 000000000..fe209f705 --- /dev/null +++ b/core/index/chunk/chunk.ts @@ -0,0 +1,46 @@ +import { Chunk, ChunkWithoutID } from "."; +import { basicChunker } from "./basic"; +import { codeChunker, fileExtensionToLanguage } from "./code"; + +async function* chunkDocumentWithoutId( + filepath: string, + contents: string, + maxChunkSize: number +): AsyncGenerator { + if (contents.trim() === "") { + return; + } + + const segs = filepath.split("."); + const ext = segs[segs.length - 1]; + if (ext in fileExtensionToLanguage) { + for await (const chunk of codeChunker(filepath, contents, maxChunkSize)) { + yield chunk; + } + return; + } + + yield* basicChunker(contents, maxChunkSize); +} + +export async function* chunkDocument( + filepath: string, + contents: string, + maxChunkSize: number, + digest: string +): AsyncGenerator { + let index = 0; + for await (let chunkWithoutId of chunkDocumentWithoutId( + filepath, + contents, + maxChunkSize + )) { + yield { + ...chunkWithoutId, + digest, + index, + filepath, + }; + index++; + } +} diff --git a/core/index/chunk/code.ts b/core/index/chunk/code.ts new file mode 100644 index 000000000..8173041ec --- /dev/null +++ b/core/index/chunk/code.ts @@ -0,0 +1,181 @@ +import Parser, { SyntaxNode } from "web-tree-sitter"; +import { ChunkWithoutID } from "."; +import { countTokens } from "../../llm/countTokens"; + +export const fileExtensionToLanguage: { [key: string]: string } = { + py: "python", + js: "javascript", + ts: "typescript", + java: "java", + go: "go", + rb: "ruby", + rs: "rust", + c: "c", + cpp: "cpp", + cs: "c_sharp", + php: "php", + scala: "scala", + swift: "swift", + kt: "kotlin", +}; + +async function getParserForFile(filepath: string) { + const parser = new Parser(); + const segs = filepath.split("."); + const Language = await Parser.Language.load( + fileExtensionToLanguage[segs[segs.length - 1]] + ); + parser.setLanguage(Language); + return parser; +} + +function collapsedReplacement(node: SyntaxNode): string { + if (node.type === "statement_block") { + return "{ ... }"; + } else { + return "..."; + } +} + +function firstChild( + node: SyntaxNode, + grammarName: string | string[] +): SyntaxNode | null { + if (Array.isArray(grammarName)) { + return ( + node.children.find((child) => grammarName.includes(child.type)) || null + ); + } else { + return node.children.find((child) => child.type === grammarName) || null; + } +} + +function collapseChildren( + node: SyntaxNode, + code: string, + blockTypes: string[], + collapseTypes: string[], + collapseBlockTypes: string[] +): string { + code = code.slice(0, node.endIndex); + const block = firstChild(node, blockTypes); + if (block) { + const childrenToCollapse = block.children.filter((child) => + collapseTypes.includes(child.type) + ); + for (const child of childrenToCollapse.reverse()) { + const grandChild = firstChild(child, collapseBlockTypes); + if (grandChild) { + const start = grandChild.startIndex; + const end = grandChild.endIndex; + code = + code.slice(0, start) + + collapsedReplacement(grandChild) + + code.slice(end); + } + } + } + return code.slice(node.startIndex); +} + +function constructClassDefinitionChunk(node: SyntaxNode, code: string): string { + return collapseChildren( + node, + code, + ["block", "class_body", "declaration_list"], + ["method_definition", "function_definition", "function_item"], + ["block", "statement_block"] + ); +} + +function constructFunctionDefinitionChunk( + node: SyntaxNode, + code: string +): string { + const funcText = node.text; + if ( + node.parent && + ["block", "declaration_list"].includes(node.parent.type) && + node.parent.parent && + ["class_definition", "impl_item"].includes(node.parent.parent.type) + ) { + // If inside a class, include the class header + const classNode = node.parent.parent; + const classBlock = node.parent; + return ( + code.slice(classNode.startIndex, classBlock.startIndex) + + "...\n\n" + + " ".repeat(node.startPosition.column) + // ... + funcText + ); + } + return funcText; +} + +const collapsedNodeConstructors: { + [key: string]: (node: SyntaxNode, code: string) => string; +} = { + // Classes, structs, etc + class_definition: constructClassDefinitionChunk, + class_declaration: constructClassDefinitionChunk, + impl_item: constructClassDefinitionChunk, + // Functions + function_definition: constructFunctionDefinitionChunk, + function_declaration: constructFunctionDefinitionChunk, + function_item: constructFunctionDefinitionChunk, +}; + +function* getSmartCollapsedChunks( + node: SyntaxNode, + code: string, + maxChunkSize: number, + root = true +): Generator { + // Keep entire text if not over size + if ( + (root || node.type in collapsedNodeConstructors) && + countTokens(node.text, "gpt-4") < maxChunkSize + ) { + yield { + content: node.text, + startLine: node.startPosition.row, + endLine: node.endPosition.row, + }; + return; + } + + // If a collapsed form is defined, use that + if (node.type in collapsedNodeConstructors) { + yield { + content: collapsedNodeConstructors[node.type](node, code), + startLine: node.startPosition.row, + endLine: node.endPosition.row, + }; + } + + // Recurse (because even if collapsed version was shown, want to show the children in full somewhere) + for (const child of node.children) { + yield* getSmartCollapsedChunks(child, code, maxChunkSize, false); + } +} + +export async function* codeChunker( + filepath: string, + contents: string, + maxChunkSize: number +): AsyncGenerator { + if (contents.trim().length === 0) { + return; + } + let parser: Parser; + try { + parser = await getParserForFile(filepath); + } catch (e) { + console.warn(`Failed to load parser for file ${filepath}: `, e); + return; + } + + const tree = parser.parse(contents); + + yield* getSmartCollapsedChunks(tree.rootNode, contents, maxChunkSize); +} diff --git a/core/index/chunk/index.d.ts b/core/index/chunk/index.d.ts new file mode 100644 index 000000000..48162a617 --- /dev/null +++ b/core/index/chunk/index.d.ts @@ -0,0 +1,12 @@ +export interface ChunkWithoutID { + content: string; + startLine: number; + endLine: number; + otherMetadata?: { [key: string]: any }; +} + +export interface Chunk extends ChunkWithoutID { + digest: string; + filepath: string; + index: number; // Index of the chunk in the document at filepath +} diff --git a/core/package-lock.json b/core/package-lock.json index 37bf88b91..531fad802 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -7,7 +7,6 @@ "": { "name": "core", "version": "1.0.0", - "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { "@xenova/transformers": "^2.13.4", @@ -17,14 +16,14 @@ "js-tiktoken": "^1.0.8", "openai": "^4.20.1", "replicate": "^0.23.0", - "uuid": "^9.0.1" + "uuid": "^9.0.1", + "web-tree-sitter": "^0.20.8" }, "devDependencies": { "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/mustache": "^4.2.5", "@types/uuid": "^9.0.7", - "cargo-cp-artifact": "^0.1", "jest": "^29.7.0", "ts-jest": "^29.1.1" } @@ -1736,15 +1735,6 @@ } ] }, - "node_modules/cargo-cp-artifact": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/cargo-cp-artifact/-/cargo-cp-artifact-0.1.8.tgz", - "integrity": "sha512-3j4DaoTrsCD1MRkTF2Soacii0Nx7UHCce0EwUf4fHnggwiE4fbmF2AbnfzayR36DF8KGadfh7M/Yfy625kgPlA==", - "dev": true, - "bin": { - "cargo-cp-artifact": "bin/cargo-cp-artifact.js" - } - }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -4863,6 +4853,11 @@ "node": ">= 8" } }, + "node_modules/web-tree-sitter": { + "version": "0.20.8", + "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.20.8.tgz", + "integrity": "sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==" + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", diff --git a/core/package.json b/core/package.json index 05f3b403a..aee8af51e 100644 --- a/core/package.json +++ b/core/package.json @@ -23,6 +23,7 @@ "js-tiktoken": "^1.0.8", "openai": "^4.20.1", "replicate": "^0.23.0", - "uuid": "^9.0.1" + "uuid": "^9.0.1", + "web-tree-sitter": "^0.20.8" } } diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index d24276e31..af066d3f1 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -338,10 +338,10 @@ export function getSidebarContent( } case "sendChunkForFile": { respond( - await ide.sendChunkForFile( - data.message.hash, + await ide.sendEmbeddingForChunk( + data.message.chunk, data.message.embedding, - data.message.index + data.message.tags ) ); break; diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 696d90dbd..0770af1a6 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -17,6 +17,7 @@ import { intermediateToFinalConfig, serializedToIntermediateConfig, } from "core/config/load"; +import { Chunk } from "core/index/chunk"; import { verticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; import mergeJson from "./util/merge"; import { getExtensionUri } from "./util/vscode"; @@ -273,17 +274,24 @@ class VsCodeIde implements IDE { return results.join("\n\n"); } - async getFilesToEmbed(): Promise<[string, string][]> { + async getFilesToEmbed(): Promise<[string, string, string][]> { let results = []; let branch = await ideProtocolClient.getBranch(); for (let dir of await this.getWorkspaceDirs()) { - results.push(...sync.sync_results(dir, branch)); + let tag = `${dir}::${branch}`; + results.push( + ...sync.sync_results(dir, branch).map((r: any) => [tag, ...r]) + ); } return results; } - async sendChunkForFile(hash: string, embedding: number[], index: number) { - sync.sync_results(hash, embedding, index); + async sendEmbeddingForChunk( + chunk: Chunk, + embedding: number[], + tags: string[] + ) { + sync.add_chunk(chunk, tags, embedding); } } diff --git a/gui/src/hooks/useLoadEmbeddings.tsx b/gui/src/hooks/useLoadEmbeddings.tsx index 0698057df..ec5dd556b 100644 --- a/gui/src/hooks/useLoadEmbeddings.tsx +++ b/gui/src/hooks/useLoadEmbeddings.tsx @@ -1,8 +1,11 @@ import { ExtensionIde } from "core/ide"; +import { chunkDocument } from "core/index/chunk/chunk"; import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { RootStore } from "../redux/store"; +const MAX_CHUNK_SIZE = 512; + function useLoadEmbeddings() { const [progress, setProgress] = useState(0); const embeddingsProvider = useSelector( @@ -17,12 +20,17 @@ function useLoadEmbeddings() { const total = filesToEmbed.length; let done = 1; - for (let [filepath, hash] of filesToEmbed) { + for (let [tag, filepath, hash] of filesToEmbed) { const contents = await ide.readFile(filepath); - const chunks = await chunkFile(contents); - const embeddings = await embeddingsProvider.embed(chunks); - for (let i = 0; i < chunks.length; i++) { - await ide.sendChunkForFile(hash, embeddings[i], i); + const chunks = await chunkDocument( + filepath, + contents, + MAX_CHUNK_SIZE, + hash + ); + for await (let chunk of chunks) { + const [embedding] = await embeddingsProvider.embed([chunk.content]); + await ide.sendEmbeddingForChunk(chunk, embedding, [tag]); } done++; diff --git a/sync/src/lib.rs b/sync/src/lib.rs index 6993a5e46..8c9ac0191 100644 --- a/sync/src/lib.rs +++ b/sync/src/lib.rs @@ -48,10 +48,17 @@ fn sync_results(mut cx: FunctionContext) -> JsResult { } fn db_add_chunk(mut cx: FunctionContext) -> JsResult { - let hash = cx.argument::(0)?.value(&mut cx); - let content = cx.argument::(1)?.value(&mut cx); + let chunk_obj = cx.argument::(0)?; - let tags_vec = cx.argument::(2)?.to_vec(&mut cx).unwrap(); + let hash = chunk_obj + .get::(&mut cx, "digest")? + .value(&mut cx); + + let content = chunk_obj + .get::(&mut cx, "content")? + .value(&mut cx); + + let tags_vec = cx.argument::(1)?.to_vec(&mut cx).unwrap(); let mut tags: Vec = Vec::new(); for item in tags_vec { let tag = item @@ -61,7 +68,7 @@ fn db_add_chunk(mut cx: FunctionContext) -> JsResult { tags.push(tag); } - let embedding_vec = cx.argument::(3)?.to_vec(&mut cx).unwrap(); + let embedding_vec = cx.argument::(2)?.to_vec(&mut cx).unwrap(); let mut embedding: Vec = Vec::new(); for item in embedding_vec { let float = item