Elffuss BraidHub

kikocis/continue public

main · 1.0 KiBRawPermalink
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(
18 contents.split("\n").map(async (l) => {
19 return {
20 line: l,
21 tokenCount: await countTokensAsync(l),
22 };
23 }),
24 );
25
26 for (const lt of lineTokens) {
27 if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {
28 yield { content: chunkContent, startLine, endLine: currLine - 1 };
29 chunkContent = "";
30 chunkTokens = 0;
31 startLine = currLine;
32 }
33
34 if (lt.tokenCount < maxChunkSize) {
35 chunkContent += `${lt.line}\n`;
36 chunkTokens += lt.tokenCount + 1;
37 }
38
39 currLine++;
40 }
41
42 yield {
43 content: chunkContent,
44 startLine,
45 endLine: currLine - 1,
46 };
47}