Repository navigation
Expand file tree
/
Copy pathextract.js
More file actions
121 lines (97 loc) · 3.49 KB
/
Copy pathextract.js
File metadata and controls
121 lines (97 loc) · 3.49 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* extract.js — Text → Triples → JSONL
*
* Usage:
* node --env-file=.env extract.js "input.txt" [graph.jsonl]
* echo "..." | node --env-file=.env extract.js - [graph.jsonl]
*/
import fs from "fs";
import readline from "readline";
import { c, box, arrow, triple, step } from "./ui.js";
import { complete, MODEL_LABEL } from "./llm.js";
const GRAPH_FILE = process.argv[3] ?? "graph.jsonl";
const SYSTEM_PROMPT = `You are a triple extractor. Read the text and extract all facts as a JSON array of triples.
Example input: "Acme Corp is based in Denver. Jane Doe founded Acme Corp."
Example output:
[{"subject": "Acme Corp", "relation": "BASED_IN", "object": "Denver"}, {"subject": "Jane Doe", "relation": "FOUNDED", "object": "Acme Corp"}]
Rules:
- Entities: nouns in canonical form (singular, no articles)
- Relations: UPPERCASE, underscores instead of spaces (e.g. IS_A, HEADQUARTERED_IN, HOLDS_POLICY)
- Objects: an entity or a concrete value (year, place, number)
- No duplicates
- Only facts stated in the text, no inferences
- Respond ONLY with the JSON array, no text before or after`;
async function extractTriples(text) {
const raw = await complete(SYSTEM_PROMPT, text, 2048);
// small local models like to add prose or code fences: keep only the outer [...]
return JSON.parse(raw.slice(raw.indexOf("["), raw.lastIndexOf("]") + 1));
}
function normalizeEntity(name) {
return name.trim().toLowerCase().replace(/\s+/g, " ");
}
function loadExisting(file) {
const seen = new Set();
if (!fs.existsSync(file)) return seen;
const lines = fs.readFileSync(file, "utf-8").split("\n").filter(Boolean);
for (const line of lines) {
try {
const t = JSON.parse(line);
seen.add(`${normalizeEntity(t.subject)}|${t.relation}|${normalizeEntity(t.object)}`);
} catch {}
}
return seen;
}
async function readInput(source) {
if (source === "-") {
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
for await (const line of rl) lines.push(line);
return lines.join("\n");
}
return fs.readFileSync(source, "utf-8");
}
async function main() {
const inputSource = process.argv[2];
if (!inputSource) {
console.error("Usage: node extract.js <file.txt | -> [graph.jsonl]");
process.exit(1);
}
const text = await readInput(inputSource);
console.log();
// Step 1: Input
box([
`${c.bold}${c.white}TEXT INPUT${c.reset}`,
`${c.gray}${text.slice(0, 38).trim()}${text.length > 38 ? "…" : ""}${c.reset}`,
`${c.dim}${text.length} characters${c.reset}`,
], c.cyan);
arrow();
// Step 2: LLM
box([
`${c.bold}${c.white}LLM ${MODEL_LABEL}${c.reset}`,
`${c.dim}extracting triples…${c.reset}`,
], c.magenta);
const triples = await extractTriples(text);
arrow();
// Step 3: Triples
step(" Extracted triples:");
triples.forEach((t) => triple(t));
arrow();
// Step 4: save JSONL
const existing = loadExisting(GRAPH_FILE);
let added = 0;
for (const t of triples) {
const key = `${normalizeEntity(t.subject)}|${t.relation}|${normalizeEntity(t.object)}`;
if (existing.has(key)) continue;
existing.add(key);
fs.appendFileSync(GRAPH_FILE, JSON.stringify(t) + "\n");
added++;
}
const total = loadExisting(GRAPH_FILE).size;
box([
`${c.bold}${c.white}${GRAPH_FILE}${c.reset}`,
`${c.green}+${added} new triples added${c.reset}`,
`${c.dim}${total} triples total${c.reset}`,
], c.green);
console.log();
}
main().catch((e) => { console.error(e.message); process.exit(1); });