🚧 convert chunking code to Typescript

This commit is contained in:
Nate Sesti 2024-01-07 13:52:11 -08:00
parent dde3bdbb5b
commit 7a701d8dac
13 changed files with 331 additions and 37 deletions

View file

@ -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;

View file

@ -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 });
}
}

8
core/index.d.ts vendored
View file

@ -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

32
core/index/chunk/basic.ts Normal file
View file

@ -0,0 +1,32 @@
import { ChunkWithoutID } from ".";
import { countTokens } from "../../llm/countTokens";
export function* basicChunker(
contents: string,
maxChunkSize: number
): Generator<ChunkWithoutID> {
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,
};
}

46
core/index/chunk/chunk.ts Normal file
View file

@ -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<ChunkWithoutID> {
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<Chunk> {
let index = 0;
for await (let chunkWithoutId of chunkDocumentWithoutId(
filepath,
contents,
maxChunkSize
)) {
yield {
...chunkWithoutId,
digest,
index,
filepath,
};
index++;
}
}

181
core/index/chunk/code.ts Normal file
View file

@ -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<ChunkWithoutID> {
// 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<ChunkWithoutID> {
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);
}

12
core/index/chunk/index.d.ts vendored Normal file
View file

@ -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
}

19
core/package-lock.json generated
View file

@ -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",

View file

@ -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"
}
}

View file

@ -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;

View file

@ -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);
}
}

View file

@ -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++;

View file

@ -48,10 +48,17 @@ fn sync_results(mut cx: FunctionContext) -> JsResult<JsObject> {
}
fn db_add_chunk(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let hash = cx.argument::<JsString>(0)?.value(&mut cx);
let content = cx.argument::<JsString>(1)?.value(&mut cx);
let chunk_obj = cx.argument::<JsObject>(0)?;
let tags_vec = cx.argument::<JsArray>(2)?.to_vec(&mut cx).unwrap();
let hash = chunk_obj
.get::<JsString, _, _>(&mut cx, "digest")?
.value(&mut cx);
let content = chunk_obj
.get::<JsString, _, _>(&mut cx, "content")?
.value(&mut cx);
let tags_vec = cx.argument::<JsArray>(1)?.to_vec(&mut cx).unwrap();
let mut tags: Vec<String> = Vec::new();
for item in tags_vec {
let tag = item
@ -61,7 +68,7 @@ fn db_add_chunk(mut cx: FunctionContext) -> JsResult<JsUndefined> {
tags.push(tag);
}
let embedding_vec = cx.argument::<JsArray>(3)?.to_vec(&mut cx).unwrap();
let embedding_vec = cx.argument::<JsArray>(2)?.to_vec(&mut cx).unwrap();
let mut embedding: Vec<f32> = Vec::new();
for item in embedding_vec {
let float = item