// The RAG API: put documents in, ask questions, get answers grounded in YOUR data.
// POST /documents {text, source} → split, embed, store
// POST /ask {question, k} → embed, search, answer with sources
// DELETE /documents/<id> → erase text AND vectors ("right to erasure")
// GET /healthz (process alive) GET /readyz (all dependencies up)
import http from "node:http";
import { randomUUID } from "node:crypto";
import { chat, config, db, dependencyHealth, embed, migrate, qdrant } from "./deps.js";
let ready = false;
/** Split long text into ~800-character chunks on paragraph boundaries. */
export function chunk(text, max = 800) {
const out = [];
let cur = "";
for (const para of text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean)) {
if (cur && cur.length + para.length + 2 > max) { out.push(cur); cur = ""; }
cur = cur ? `${cur}\n\n${para}` : para;
while (cur.length > max) { out.push(cur.slice(0, max)); cur = cur.slice(max); }
}
if (cur) out.push(cur);
return out;
}
async function addDocument({ text, source = "api" }) {
if (typeof text !== "string" || !text.trim()) throw Object.assign(new Error("text is required"), { status: 400 });
const pieces = chunk(text);
const vectors = await embed(pieces);
const documentId = randomUUID();
const chunkIds = pieces.map(() => randomUUID());
const client = await db.connect();
try {
await client.query("BEGIN");
await client.query("INSERT INTO documents (id, source) VALUES ($1, $2)", [documentId, String(source)]);
for (const [i, piece] of pieces.entries()) {
await client.query("INSERT INTO chunks (id, document_id, idx, text) VALUES ($1, $2, $3, $4)", [chunkIds[i], documentId, i, piece]);
}
// Vectors go to Qdrant; the text itself stays in Postgres (one source of truth).
await qdrant.upsert(pieces.map((_, i) => ({ id: chunkIds[i], vector: vectors[i], payload: { document_id: documentId, idx: i } })));
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
return { id: documentId, chunks: pieces.length };
}
async function ask({ question, k = 3 }) {
if (typeof question !== "string" || !question.trim()) throw Object.assign(new Error("question is required"), { status: 400 });
const started = Date.now();
const [vector] = await embed([question]);
const hits = await qdrant.search(vector, Math.min(Math.max(Number(k) || 3, 1), 10));
const ids = hits.map((h) => h.id);
const { rows } = await db.query("SELECT id, document_id, text FROM chunks WHERE id = ANY($1::uuid[])", [ids]);
const byId = new Map(rows.map((r) => [r.id, r]));
const sources = hits
.filter((h) => byId.has(h.id))
.map((h) => ({ documentId: byId.get(h.id).document_id, chunkId: h.id, score: h.score, text: byId.get(h.id).text }));
// Plain passages, no "[1]" labels: small models tend to answer with just the label.
const context = sources.map((s) => s.text).join("\n\n---\n\n");
const answer = await chat([
{
role: "system",
content: "You answer questions using only the provided context. Reply in one complete sentence. " +
"If the context does not contain the answer, reply exactly: I don't know.",
},
{ role: "user", content: `Context:\n${context || "(empty)"}\n\nQuestion: ${question}` },
]);
const latencyMs = Date.now() - started;
// Audit trail: regulated customers want to know who asked what, and what was used.
await db.query("INSERT INTO queries (question, answer, chunk_ids, latency_ms) VALUES ($1, $2, $3, $4)", [question, answer, ids, latencyMs]);
return { answer, sources, latencyMs };
}
/** Erase a document everywhere it lives: vectors in Qdrant, text in Postgres. */
async function deleteDocument(id) {
if (!/^[0-9a-f-]{36}$/i.test(id)) throw Object.assign(new Error("invalid id"), { status: 400 });
const { rows } = await db.query("SELECT id FROM chunks WHERE document_id = $1", [id]);
if (rows.length) await qdrant.remove(rows.map((r) => r.id));
const { rowCount } = await db.query("DELETE FROM documents WHERE id = $1", [id]); // chunks cascade
if (!rowCount) throw Object.assign(new Error("not found"), { status: 404 });
return { deleted: id, chunks: rows.length };
}
async function readBody(req, limit = 1_000_000) {
let size = 0;
const parts = [];
for await (const part of req) {
size += part.length;
if (size > limit) throw Object.assign(new Error("body too large"), { status: 413 });
parts.push(part);
}
try { return JSON.parse(Buffer.concat(parts).toString("utf8") || "{}"); }
catch { throw Object.assign(new Error("invalid JSON"), { status: 400 }); }
}
const server = http.createServer(async (req, res) => {
const send = (status, body) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(body));
};
try {
if (req.method === "GET" && req.url === "/healthz") return send(200, { ok: true });
if (req.method === "GET" && req.url === "/readyz") {
const deps = await dependencyHealth();
const ok = ready && Object.values(deps).every((v) => v === "ok");
return send(ok ? 200 : 503, { ready: ok, deps });
}
if (!ready) return send(503, { error: "starting up, models still loading" });
if (req.method === "POST" && req.url === "/documents") return send(201, await addDocument(await readBody(req)));
if (req.method === "POST" && req.url === "/ask") return send(200, await ask(await readBody(req)));
if (req.method === "DELETE" && req.url?.startsWith("/documents/")) return send(200, await deleteDocument(req.url.slice("/documents/".length)));
if (req.method === "GET" && req.url === "/documents") {
const { rows } = await db.query("SELECT d.id, d.source, d.created_at, count(c.id)::int AS chunks FROM documents d LEFT JOIN chunks c ON c.document_id = d.id GROUP BY d.id ORDER BY d.created_at DESC LIMIT 50");
return send(200, rows);
}
send(404, { error: "not found" });
} catch (e) {
console.error(JSON.stringify({ level: "error", path: req.url, error: e.message }));
send(e.status ?? 500, { error: e.status ? e.message : "internal error" });
}
});
/** Wait for every dependency, then create tables + the vector collection. */
async function init() {
for (let attempt = 1; ; attempt++) {
try {
await migrate();
const [probe] = await embed(["dimension probe"]); // learn the embedding size from the model itself
await qdrant.ensureCollection(probe.length);
ready = true;
console.log(JSON.stringify({ level: "info", msg: "ready", embeddingDimension: probe.length }));
return;
} catch (e) {
console.log(JSON.stringify({ level: "info", msg: "waiting for dependencies", attempt, error: e.message.slice(0, 120) }));
await new Promise((r) => setTimeout(r, Math.min(2_000 * attempt, 10_000)));
}
}
}
server.listen(config.port, () => {
console.log(JSON.stringify({ level: "info", msg: "listening", port: config.port }));
init();
});
// Kubernetes sends SIGTERM before killing a pod: finish in-flight requests, then exit.
process.on("SIGTERM", () => server.close(() => db.end().then(() => process.exit(0))));