-
Notifications
You must be signed in to change notification settings - Fork 315
/
SimpleNodeParser.ts
72 lines (67 loc) · 2.05 KB
/
SimpleNodeParser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { BaseNode } from "../Node.js";
import { SentenceSplitter } from "../TextSplitter.js";
import { DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE } from "../constants.js";
import type { NodeParser } from "./types.js";
import { getNodesFromDocument } from "./utils.js";
/**
* SimpleNodeParser is the default NodeParser. It splits documents into TextNodes using a splitter, by default SentenceSplitter
*/
export class SimpleNodeParser implements NodeParser {
/**
* The text splitter to use.
*/
textSplitter: SentenceSplitter;
/**
* Whether to include metadata in the nodes.
*/
includeMetadata: boolean;
/**
* Whether to include previous and next relationships in the nodes.
*/
includePrevNextRel: boolean;
constructor(init?: {
textSplitter?: SentenceSplitter;
includeMetadata?: boolean;
includePrevNextRel?: boolean;
chunkSize?: number;
chunkOverlap?: number;
splitLongSentences?: boolean;
}) {
this.textSplitter =
init?.textSplitter ??
new SentenceSplitter({
chunkSize: init?.chunkSize ?? DEFAULT_CHUNK_SIZE,
chunkOverlap: init?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP,
splitLongSentences: init?.splitLongSentences ?? false,
});
this.includeMetadata = init?.includeMetadata ?? true;
this.includePrevNextRel = init?.includePrevNextRel ?? true;
}
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
return this.getNodesFromDocuments(nodes);
}
static fromDefaults(init?: {
chunkSize?: number;
chunkOverlap?: number;
includeMetadata?: boolean;
includePrevNextRel?: boolean;
}): SimpleNodeParser {
return new SimpleNodeParser(init);
}
/**
* Generate Node objects from documents
* @param documents
*/
getNodesFromDocuments(documents: BaseNode[]) {
return documents
.map((document) =>
getNodesFromDocument(
document,
this.textSplitter.splitText.bind(this.textSplitter),
this.includeMetadata,
this.includePrevNextRel,
),
)
.flat();
}
}