Repository navigation
Expand file tree
/
Copy pathquery.js
More file actions
176 lines (137 loc) · 4.37 KB
/
Copy pathquery.js
File metadata and controls
176 lines (137 loc) · 4.37 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
* query.js — question → graph lookup → LLM answer
*
* Usage:
* node --env-file=.env query.js "Who handles the claim of Alice Chen?" [graph.jsonl]
*/
import fs from "fs";
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 MAX_HOPS = 1;
const MAX_TRIPLES = 30;
// --- Load graph ---
function loadGraph(file) {
if (!fs.existsSync(file)) {
console.error(`Graph file not found: ${file}`);
process.exit(1);
}
return fs.readFileSync(file, "utf-8")
.split("\n")
.filter(Boolean)
.map((line) => JSON.parse(line));
}
// --- Entity resolution ---
function normalize(str) {
return str.toLowerCase().replace(/[^a-z0-9äöüß]/g, " ").replace(/\s+/g, " ").trim();
}
function entityTokens(triples) {
const entities = new Set();
for (const t of triples) {
entities.add(normalize(t.subject));
entities.add(normalize(t.object));
}
return entities;
}
function findSeedEntities(question, triples) {
const qNorm = normalize(question);
const qWords = new Set(qNorm.split(" ").filter((w) => w.length > 2));
const entities = entityTokens(triples);
const matched = [];
for (const entity of entities) {
const eWords = entity.split(" ");
const overlap = eWords.filter((w) => qWords.has(w)).length;
if (overlap > 0) matched.push({ entity, overlap });
}
matched.sort((a, b) => b.overlap - a.overlap);
return matched.slice(0, 5).map((m) => m.entity);
}
// --- Graph traversal ---
function retrieveContext(seeds, triples, maxHops) {
const relevant = new Set();
let frontier = new Set(seeds);
for (let hop = 0; hop <= maxHops; hop++) {
const nextFrontier = new Set();
for (const t of triples) {
const s = normalize(t.subject);
const o = normalize(t.object);
const hit = [...frontier].some((e) => s.includes(e) || e.includes(s) || o.includes(e) || e.includes(o));
if (hit) {
relevant.add(JSON.stringify(t));
nextFrontier.add(s);
nextFrontier.add(o);
}
}
frontier = nextFrontier;
}
return [...relevant].slice(0, MAX_TRIPLES).map((r) => JSON.parse(r));
}
// --- LLM answer ---
function buildContext(triples) {
return triples.map((t) => `${t.subject} --[${t.relation}]--> ${t.object}`).join("\n");
}
async function answer(question, contextTriples) {
const context = buildContext(contextTriples);
return complete(
"You are an assistant that answers questions using a knowledge graph. Answer precisely and only based on the given facts. If the facts are not sufficient, say so clearly.",
`Knowledge graph:\n${context}\n\nQuestion: ${question}`,
1024,
);
}
// --- Main ---
async function main() {
const question = process.argv[2];
if (!question) {
console.error('Usage: node query.js "Your question?" [graph.jsonl]');
process.exit(1);
}
console.log();
// Step 1: question
box([
`${c.bold}${c.white}QUESTION${c.reset}`,
`${c.yellow}"${question}"${c.reset}`,
], c.yellow);
arrow();
// Step 2: load graph
const triples = loadGraph(GRAPH_FILE);
box([
`${c.bold}${c.white}${GRAPH_FILE}${c.reset}`,
`${c.dim}${triples.length} triples loaded${c.reset}`,
], c.cyan);
arrow();
// Step 3: Entity Matching
const seeds = findSeedEntities(question, triples);
box([
`${c.bold}${c.white}ENTITY MATCHING${c.reset}`,
...seeds.map((s) => `${c.green}▸ ${s}${c.reset}`),
...(seeds.length === 0 ? [`${c.gray}(none found)${c.reset}`] : []),
], c.blue);
arrow();
// Step 4: Graph Traversal
const context = retrieveContext(seeds, triples, MAX_HOPS);
box([
`${c.bold}${c.white}${MAX_HOPS}-HOP TRAVERSAL${c.reset}`,
`${c.dim}${context.length} relevant triples${c.reset}`,
], c.blue);
step(" Context triples:");
context.forEach((t) => triple(t));
arrow();
// Step 5: LLM
if (context.length === 0) {
box([`${c.gray}No relevant facts found.${c.reset}`], c.magenta);
console.log();
return;
}
box([
`${c.bold}${c.white}LLM ${MODEL_LABEL}${c.reset}`,
`${c.dim}generating answer…${c.reset}`,
], c.magenta);
const response = await answer(question, context);
arrow();
// Step 6: answer
box([`${c.bold}${c.white}ANSWER${c.reset}`], c.green);
console.log();
console.log(response);
console.log();
}
main().catch((e) => { console.error(e.message); process.exit(1); });