Elffuss BraidHub

kikocis/continue public

ed46f5b1432f · 1017 BRawPermalink
1import { ChunkWithoutID } from "../../index.js";
2import { countTokensAsync } from "../../llm/countTokens.js";
3
4export async function* basicChunker(
5 contents: string,
6 maxChunkSize: number,
7): AsyncGenerator<ChunkWithoutID> {
8 if (contents.trim().length === 0) {
9 return;
10 }
11
12 let chunkContent = "";
13 let chunkTokens = 0;
14 let startLine = 0;
15 let currLine = 0;
16
17 const lineTokens = await Promise.all(contents.split("\n").map(async l => {
18 return {
19 line: l,
20 tokenCount: await countTokensAsync(l),
21 };
22 }));
23
24 for (const lt of lineTokens) {
25 if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {
26 yield { content: chunkContent, startLine, endLine: currLine - 1 };
27 chunkContent = "";
28 chunkTokens = 0;
29 startLine = currLine;
30 }
31
32 if (lt.tokenCount < maxChunkSize) {
33 chunkContent += `${lt.line}\n`;
34 chunkTokens += lt.tokenCount + 1;
35 }
36
37 currLine++;
38 }
39
40 yield {
41 content: chunkContent,
42 startLine,
43 endLine: currLine - 1,
44 };
45}