quipugraph 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
quipu/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """quipu: a GraphRAG engine that lives inside Postgres."""
2
+
3
+ from .client import Answer, Graph, Hit, Quipu, chunk_text
4
+ from .embed import OpenAIEmbedder, SentenceTransformerEmbedder
5
+ from .install import install, sql_script
6
+ from .llm import AnthropicLLM, ClaudeCodeLLM, OpenAILLM
7
+
8
+ __version__ = "0.1.0"
9
+ __all__ = ["Quipu", "Graph", "Hit", "Answer", "chunk_text", "install", "sql_script",
10
+ "SentenceTransformerEmbedder", "OpenAIEmbedder", "AnthropicLLM", "OpenAILLM",
11
+ "ClaudeCodeLLM"]
quipu/cli.py ADDED
@@ -0,0 +1,89 @@
1
+ """quipu command line.
2
+
3
+ quipu install $DATABASE_URL [--app-role app] create/upgrade the schema (as the DB owner)
4
+ quipu sql > quipu.sql print the install script (for migration tools)
5
+ quipu tenant create create the tenant in QUIPU_TENANT
6
+ quipu graph create NAME [--ontology o.json] [--strict]
7
+ quipu graph list | ontology NAME | stats NAME
8
+ quipu add NAME FILE... [--no-extract] ingest text/markdown files
9
+ quipu query NAME "question" [-k 5] [--mode graph] [--json]
10
+ quipu ask NAME "question"
11
+ quipu mcp run the MCP server (stdio)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ from .install import install, sql_script
21
+
22
+
23
+ def main(argv=None):
24
+ ap = argparse.ArgumentParser(prog="quipu", description="GraphRAG inside Postgres")
25
+ ap.add_argument("--tenant")
26
+ sub = ap.add_subparsers(dest="cmd", required=True)
27
+ p = sub.add_parser("install"); p.add_argument("dsn"); p.add_argument("--app-role")
28
+ sub.add_parser("sql")
29
+ p = sub.add_parser("tenant"); p.add_argument("action", choices=["create"]); p.add_argument("--name")
30
+ p = sub.add_parser("graph"); p.add_argument("action", choices=["create", "list", "ontology", "stats", "drop"])
31
+ p.add_argument("name", nargs="?"); p.add_argument("--ontology"); p.add_argument("--strict", action="store_true")
32
+ p.add_argument("--dim", type=int)
33
+ p = sub.add_parser("add"); p.add_argument("graph"); p.add_argument("files", nargs="+")
34
+ p.add_argument("--no-extract", action="store_true")
35
+ p = sub.add_parser("query"); p.add_argument("graph"); p.add_argument("question"); p.add_argument("-k", type=int, default=5)
36
+ p.add_argument("--mode", default="graph"); p.add_argument("--json", action="store_true")
37
+ p = sub.add_parser("ask"); p.add_argument("graph"); p.add_argument("question"); p.add_argument("-k", type=int, default=5)
38
+ sub.add_parser("mcp")
39
+ a = ap.parse_args(argv)
40
+
41
+ if a.cmd == "install":
42
+ print("quipu", install(a.dsn, a.app_role), "installed")
43
+ return
44
+ if a.cmd == "sql":
45
+ sys.stdout.write(sql_script())
46
+ return
47
+ if a.cmd == "mcp":
48
+ from .mcp_server import main as mcp_main
49
+ mcp_main()
50
+ return
51
+
52
+ from .config import from_env
53
+ light = a.cmd in ("tenant",) or (a.cmd == "graph" and a.action != "create")
54
+ q = from_env(a.tenant, need_models=not light)
55
+ if a.cmd == "tenant":
56
+ q.create_tenant(a.name); print("tenant", q.tenant, "ready")
57
+ elif a.cmd == "graph":
58
+ if a.action == "list":
59
+ for g in q.graphs():
60
+ print(f"{g['name']}\t{g['embedding_dim']}d\t{g['ontology_mode']}")
61
+ elif a.action == "create":
62
+ onto = json.loads(Path(a.ontology).read_text()) if a.ontology else None
63
+ q.create_graph(a.name, ontology=onto, mode="strict" if a.strict else "open", embedding_dim=a.dim)
64
+ print("graph", a.name, "created")
65
+ elif a.action == "ontology":
66
+ print(json.dumps(q.graph(a.name).ontology(), indent=2))
67
+ elif a.action == "stats":
68
+ print(json.dumps(q.graph(a.name).stats(), indent=2))
69
+ elif a.action == "drop":
70
+ q.graph(a.name).drop(); print("dropped", a.name)
71
+ elif a.cmd == "add":
72
+ docs = [{"external_id": str(Path(f)), "title": Path(f).stem, "text": Path(f).read_text()} for f in a.files]
73
+ for d, r in zip(docs, q.graph(a.graph).add_many(docs, extract_graph=not a.no_extract)):
74
+ print(d["external_id"], json.dumps(r))
75
+ elif a.cmd == "query":
76
+ hits = q.graph(a.graph).retrieve(a.question, k=a.k, mode=a.mode)
77
+ if a.json:
78
+ print(json.dumps([h.__dict__ for h in hits], default=str, indent=1))
79
+ else:
80
+ for h in hits:
81
+ print(f"#{h.rank} {h.score:.4f} [{h.external_id}] {h.content[:160].replace(chr(10), ' ')}")
82
+ elif a.cmd == "ask":
83
+ ans = q.graph(a.graph).ask(a.question, k=a.k)
84
+ print(ans.text)
85
+ print("\nsources:", ", ".join(h.external_id for h in ans.hits))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
quipu/client.py ADDED
@@ -0,0 +1,441 @@
1
+ """Python client: tenant-scoped connections, graphs, ingestion and retrieval."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from contextlib import contextmanager
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Iterable, Sequence
11
+
12
+ import psycopg
13
+ from psycopg.rows import dict_row
14
+
15
+ from .embed import CrossEncoderReranker, Embedder, to_pgvector # noqa: F401
16
+ from .extract import Extraction, extract
17
+ from .install import install as _install
18
+ from .llm import LLM, parse_json
19
+
20
+
21
+ @dataclass
22
+ class Hit:
23
+ chunk_id: int
24
+ document_id: int
25
+ external_id: str
26
+ title: str | None
27
+ content: str
28
+ score: float
29
+ rank: int
30
+ signals: dict = field(default_factory=dict)
31
+
32
+
33
+ @dataclass
34
+ class Answer:
35
+ text: str
36
+ hits: list[Hit]
37
+ facts: list[dict]
38
+
39
+
40
+ def chunk_text(text: str, max_chars: int = 1500, overlap: int = 150) -> list[str]:
41
+ """Paragraph-aware chunking: packs paragraphs up to max_chars, splits long ones on sentences."""
42
+ paras = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
43
+ pieces: list[str] = []
44
+ for p in paras:
45
+ if len(p) <= max_chars:
46
+ pieces.append(p)
47
+ continue
48
+ sents = re.split(r"(?<=[.!?])\s+", p)
49
+ buf = ""
50
+ for s in sents:
51
+ if buf and len(buf) + len(s) + 1 > max_chars:
52
+ pieces.append(buf)
53
+ buf = buf[-overlap:] if overlap else ""
54
+ buf = (buf + " " + s).strip()
55
+ if buf:
56
+ pieces.append(buf)
57
+ chunks, buf = [], ""
58
+ for p in pieces:
59
+ if buf and len(buf) + len(p) + 2 > max_chars:
60
+ chunks.append(buf)
61
+ buf = ""
62
+ buf = (buf + "\n\n" + p).strip()
63
+ if buf:
64
+ chunks.append(buf)
65
+ return chunks
66
+
67
+
68
+ class Quipu:
69
+ """Entry point. One instance per (database, tenant).
70
+
71
+ >>> q = Quipu("postgresql://app@db/kb", tenant="acme", embedder=..., llm=...)
72
+ >>> g = q.create_graph("support", ontology={...})
73
+ >>> g.add("Ada Lovelace worked with Charles Babbage ...", external_id="ada")
74
+ >>> g.retrieve("Who did Ada work with?")
75
+ """
76
+
77
+ def __init__(self, dsn: str, tenant: str, embedder: Embedder | None = None,
78
+ llm: LLM | None = None, extraction_llm: LLM | None = None):
79
+ self.dsn = dsn
80
+ self.tenant = tenant
81
+ self.embedder = embedder
82
+ self.llm = llm
83
+ self.extraction_llm = extraction_llm or llm
84
+ self._conn: psycopg.Connection | None = None
85
+
86
+ # -- connections ---------------------------------------------------------
87
+ @property
88
+ def conn(self) -> psycopg.Connection:
89
+ if self._conn is None or self._conn.closed:
90
+ self._conn = psycopg.connect(self.dsn, row_factory=dict_row, autocommit=True)
91
+ self._conn.execute("SET client_min_messages = warning")
92
+ return self._conn
93
+
94
+ @contextmanager
95
+ def tx(self, conn: psycopg.Connection | None = None):
96
+ """A transaction pinned to this client's tenant."""
97
+ c = conn or self.conn
98
+ with c.transaction():
99
+ c.execute("SELECT quipu.use_tenant(%s)", (self.tenant,))
100
+ yield c
101
+
102
+ def close(self):
103
+ if self._conn is not None:
104
+ self._conn.close()
105
+
106
+ # -- admin -------------------------------------------------------------
107
+ def install(self, app_role: str | None = None) -> str:
108
+ return _install(self.conn, app_role)
109
+
110
+ def create_tenant(self, name: str | None = None) -> None:
111
+ with self.conn.transaction():
112
+ self.conn.execute("SELECT quipu.create_tenant(%s, %s)", (self.tenant, name))
113
+
114
+ def create_graph(self, name: str, ontology: dict | None = None, mode: str = "open",
115
+ text_config: str = "english", embedding_dim: int | None = None,
116
+ exist_ok: bool = False) -> "Graph":
117
+ dim = embedding_dim or (self.embedder.dim if self.embedder else None)
118
+ if not dim:
119
+ raise ValueError("embedding_dim is required when no embedder is configured")
120
+ with self.tx() as c:
121
+ exists = c.execute("SELECT 1 FROM quipu.graphs WHERE name = %s", (name,)).fetchone()
122
+ if exists and not exist_ok:
123
+ raise ValueError(f"graph {name!r} already exists")
124
+ if not exists:
125
+ c.execute("SELECT quipu.create_graph(%s, %s, %s, %s, %s)",
126
+ (name, dim, json.dumps(ontology) if ontology else None, mode, text_config))
127
+ elif ontology:
128
+ c.execute("SELECT quipu.set_ontology(%s, %s, %s)", (name, json.dumps(ontology), mode))
129
+ return Graph(self, name)
130
+
131
+ def graph(self, name: str) -> "Graph":
132
+ return Graph(self, name)
133
+
134
+ def graphs(self) -> list[dict]:
135
+ with self.tx() as c:
136
+ return c.execute("SELECT name, embedding_dim, ontology_mode, created_at FROM quipu.graphs "
137
+ "ORDER BY name").fetchall()
138
+
139
+
140
+ class Graph:
141
+ def __init__(self, client: Quipu, name: str):
142
+ self.q = client
143
+ self.name = name
144
+
145
+ # -- schema ------------------------------------------------------------
146
+ def ontology(self) -> dict:
147
+ with self.q.tx() as c:
148
+ return c.execute("SELECT quipu.get_ontology(%s) AS o", (self.name,)).fetchone()["o"]
149
+
150
+ def set_ontology(self, ontology: dict, mode: str | None = None) -> dict:
151
+ with self.q.tx() as c:
152
+ return c.execute("SELECT quipu.set_ontology(%s, %s, %s) AS o",
153
+ (self.name, json.dumps(ontology), mode)).fetchone()["o"]
154
+
155
+ def drop(self) -> None:
156
+ with self.q.tx() as c:
157
+ c.execute("SELECT quipu.drop_graph(%s)", (self.name,))
158
+
159
+ # -- ingestion -----------------------------------------------------------
160
+ def ingest_payload(self, payload: dict) -> dict:
161
+ """Low-level: write a pre-built payload (see quipu.ingest in SQL)."""
162
+ with self.q.tx() as c:
163
+ return c.execute("SELECT quipu.ingest(%s, %s) AS r",
164
+ (self.name, json.dumps(payload))).fetchone()["r"]
165
+
166
+ def _conform(self, ex: Extraction, onto: dict) -> Extraction:
167
+ """Make an extraction safe to write: strict graphs drop off-ontology items; open graphs
168
+ declare relation endpoints the model forgot to list."""
169
+ ents = {e["name"].lower(): e for e in ex.entities}
170
+ if onto.get("mode") == "strict":
171
+ etypes = {e["name"] for e in onto.get("entities", [])}
172
+ rtypes = {r["name"]: r for r in onto.get("relations", [])}
173
+ ents = {k: e for k, e in ents.items() if e["type"] in etypes}
174
+ rels = []
175
+ for r in ex.relations:
176
+ rt = rtypes.get(r["type"])
177
+ s, t = ents.get(r["source"].lower()), ents.get(r["target"].lower())
178
+ if not rt or not s or not t:
179
+ continue
180
+ if rt.get("source") and s["type"] not in rt["source"]:
181
+ continue
182
+ if rt.get("target") and t["type"] not in rt["target"]:
183
+ continue
184
+ rels.append(r)
185
+ return Extraction(list(ents.values()), rels)
186
+ for r in ex.relations:
187
+ for side in ("source", "target"):
188
+ if r[side].lower() not in ents:
189
+ ents[r[side].lower()] = {"name": r[side], "type": r.get(f"{side}_type", "Entity"),
190
+ "description": ""}
191
+ r[f"{side}_type"] = ents[r[side].lower()]["type"]
192
+ return Extraction(list(ents.values()), ex.relations)
193
+
194
+ def build_payloads(self, docs: Sequence[dict], extract_graph: bool = True,
195
+ batch_size: int = 4, workers: int = 4, max_chars: int = 1500,
196
+ known: dict[str, Extraction] | None = None) -> list[dict]:
197
+ """docs: [{"text" | "chunks", "external_id", "title", "metadata"}] -> ingest payloads.
198
+ Runs chunking, LLM extraction (batched, parallel) and embedding."""
199
+ emb = self.q.embedder
200
+ if emb is None:
201
+ raise ValueError("an embedder is required to add documents")
202
+ onto = self.ontology() if extract_graph else {}
203
+ flat: list[tuple[int, str]] = []
204
+ for di, d in enumerate(docs):
205
+ chunks = d.get("chunks") or chunk_text(d["text"], max_chars=max_chars)
206
+ flat.extend((di, ch) for ch in chunks)
207
+ texts = [t for _, t in flat]
208
+ known = known or {}
209
+ extractions: list[Extraction] = [known.get(t, Extraction()) for t in texts]
210
+ todo = [i for i, t in enumerate(texts) if t not in known]
211
+ if extract_graph and todo:
212
+ llm = self.q.extraction_llm
213
+ if llm is None:
214
+ raise ValueError("an LLM is required for graph extraction (or pass extract_graph=False)")
215
+ batches = [todo[i:i + batch_size] for i in range(0, len(todo), batch_size)]
216
+ with ThreadPoolExecutor(max_workers=workers) as pool:
217
+ for idxs, res in zip(batches, pool.map(
218
+ lambda b: extract(llm, [texts[i] for i in b], onto), batches)):
219
+ for i, ex in zip(idxs, res):
220
+ extractions[i] = self._conform(ex, onto)
221
+ chunk_vecs = emb.embed(texts, "passage")
222
+ names = sorted({e["name"] for ex in extractions for e in ex.entities})
223
+ facts = sorted({r["fact"] for ex in extractions for r in ex.relations})
224
+ name_vec = dict(zip(names, emb.embed(names, "entity"))) if names else {}
225
+ fact_vec = dict(zip(facts, emb.embed(facts, "fact"))) if facts else {}
226
+
227
+ payloads = [{"external_id": d.get("external_id") or d.get("id"), "title": d.get("title"),
228
+ "metadata": d.get("metadata") or {}, "chunks": []} for d in docs]
229
+ for (di, text), vec, ex in zip(flat, chunk_vecs, extractions):
230
+ payloads[di]["chunks"].append({
231
+ "content": text, "embedding": vec,
232
+ "entities": [{**e, "embedding": name_vec.get(e["name"])} for e in ex.entities],
233
+ "relations": [{**r, "embedding": fact_vec.get(r["fact"])} for r in ex.relations],
234
+ })
235
+ return payloads
236
+
237
+ def add(self, text: str, external_id: str | None = None, title: str | None = None,
238
+ metadata: dict | None = None, **kw) -> dict:
239
+ return self.add_many([{"text": text, "external_id": external_id, "title": title,
240
+ "metadata": metadata}], **kw)[0]
241
+
242
+ def add_many(self, docs: Sequence[dict], link_synonyms: bool = True, bulk: bool = False,
243
+ **kw) -> list[dict]:
244
+ """bulk=True drops the graph's vector indexes during the load and rebuilds them once at
245
+ the end: much faster for large initial loads, but dense search is slow meanwhile."""
246
+ payloads = self.build_payloads(docs, **kw)
247
+ if bulk:
248
+ with self.q.tx() as c:
249
+ c.execute("SELECT quipu.begin_bulk_load(%s)", (self.name,))
250
+ try:
251
+ results = [self.ingest_payload(p) for p in payloads]
252
+ finally:
253
+ if bulk:
254
+ with self.q.tx() as c:
255
+ c.execute("SET LOCAL maintenance_work_mem = '1GB'")
256
+ c.execute("SELECT quipu.end_bulk_load(%s)", (self.name,))
257
+ if link_synonyms:
258
+ self.link_synonyms()
259
+ self.refresh_stats()
260
+ return results
261
+
262
+ def delete(self, external_id: str) -> bool:
263
+ with self.q.tx() as c:
264
+ return c.execute("SELECT quipu.delete_document(%s, %s) AS ok",
265
+ (self.name, external_id)).fetchone()["ok"]
266
+
267
+ # -- versioned documents (system of record) ----------------------------------
268
+ def put(self, external_id: str, text: str, title: str | None = None,
269
+ metadata: dict | None = None, author: str | None = None,
270
+ chunks: Sequence[str] | None = None, **kw) -> dict:
271
+ """Create or replace a document as a new version; the full text is kept in its revision.
272
+ Facts the new text no longer supports are expired, not deleted."""
273
+ payload = self.build_payloads([{"text": text, "chunks": chunks, "external_id": external_id,
274
+ "title": title, "metadata": metadata}],
275
+ known=self._known(external_id), **kw)[0]
276
+ payload["text"] = text
277
+ with self.q.tx() as c:
278
+ r = c.execute("SELECT quipu.put_document(%s, %s, %s) AS r",
279
+ (self.name, json.dumps(payload), author)).fetchone()["r"]
280
+ self.link_synonyms()
281
+ self.refresh_stats()
282
+ return r
283
+
284
+ def _known(self, external_id: str) -> dict[str, Extraction]:
285
+ """What the graph already extracted from each current chunk of a document, keyed by the
286
+ chunk text: unchanged passages keep their facts instead of being re-extracted (LLM
287
+ output varies run to run, which would churn facts on every edit)."""
288
+ out: dict[str, Extraction] = {}
289
+ with self.q.tx() as c:
290
+ chunks = c.execute(
291
+ "SELECT c.id, c.content FROM quipu.chunks c JOIN quipu.documents d ON d.id = c.document_id "
292
+ "WHERE d.graph_id = quipu.graph_id(%s) AND d.external_id = %s", (self.name, external_id)).fetchall()
293
+ for ch in chunks:
294
+ ents = c.execute(
295
+ "SELECT e.name, e.type, coalesce(e.description, '') AS description FROM quipu.mentions m "
296
+ "JOIN quipu.entities e ON e.id = m.entity_id WHERE m.chunk_id = %s", (ch["id"],)).fetchall()
297
+ rels = c.execute(
298
+ "SELECT s.name AS source, s.type AS source_type, r.type, o.name AS target, "
299
+ "o.type AS target_type, r.fact FROM quipu.relation_sources rs "
300
+ "JOIN quipu.relations r ON r.id = rs.relation_id AND r.expired_at IS NULL "
301
+ "JOIN quipu.entities s ON s.id = r.source_id JOIN quipu.entities o ON o.id = r.target_id "
302
+ "WHERE rs.chunk_id = %s", (ch["id"],)).fetchall()
303
+ out[ch["content"]] = Extraction([dict(e) for e in ents], [dict(r) for r in rels])
304
+ return out
305
+
306
+ def remove(self, external_id: str, author: str | None = None) -> bool:
307
+ """Delete a document but keep its history (revision 'delete', facts expired)."""
308
+ with self.q.tx() as c:
309
+ return c.execute("SELECT quipu.remove_document(%s, %s, %s) AS ok",
310
+ (self.name, external_id, author)).fetchone()["ok"]
311
+
312
+ def get(self, external_id: str, as_of=None) -> dict | None:
313
+ """The document's text and metadata, now or as of a timestamp."""
314
+ with self.q.tx() as c:
315
+ return c.execute("SELECT * FROM quipu.get_document(%s, %s, %s)",
316
+ (self.name, external_id, as_of)).fetchone()
317
+
318
+ def history(self, external_id: str) -> list[dict]:
319
+ with self.q.tx() as c:
320
+ return c.execute("SELECT * FROM quipu.document_history(%s, %s)",
321
+ (self.name, external_id)).fetchall()
322
+
323
+ def documents(self, where: dict | None = None, since=None, until=None) -> list[dict]:
324
+ with self.q.tx() as c:
325
+ return c.execute("SELECT * FROM quipu.list_documents(%s, %s, %s, %s)",
326
+ (self.name, json.dumps(where) if where else None, since, until)).fetchall()
327
+
328
+ def changes(self, since, until=None) -> list[dict]:
329
+ """Document revisions and facts added/expired in [since, until)."""
330
+ with self.q.tx() as c:
331
+ return c.execute("SELECT * FROM quipu.changes(%s, %s, %s)",
332
+ (self.name, since, until)).fetchall()
333
+
334
+ def link_synonyms(self, threshold: float = 0.85, k: int = 10, only_new: bool = True) -> int:
335
+ with self.q.tx() as c:
336
+ return c.execute("SELECT quipu.link_synonyms(%s, %s, %s, %s) AS n",
337
+ (self.name, threshold, k, only_new)).fetchone()["n"]
338
+
339
+ def refresh_stats(self) -> dict:
340
+ with self.q.tx() as c:
341
+ return c.execute("SELECT quipu.refresh_stats(%s) AS s", (self.name,)).fetchone()["s"]
342
+
343
+ def stats(self) -> dict:
344
+ with self.q.tx() as c:
345
+ return c.execute("SELECT quipu.stats(%s) AS s", (self.name,)).fetchone()["s"]
346
+
347
+ # -- retrieval -----------------------------------------------------------
348
+ def _qvec(self, query: str):
349
+ return to_pgvector(self.q.embedder.embed([query], "query")[0]) if self.q.embedder else None
350
+
351
+ def retrieve(self, query: str, k: int = 10, mode: str = "graph", rerank_facts: bool = False,
352
+ query_entities: bool = False, embedding: Sequence[float] | None = None,
353
+ reranker=None, rerank_depth: int = 30, **options: Any) -> list[Hit]:
354
+ """mode: graph (default) | hybrid | dense | lexical.
355
+
356
+ rerank_facts: ask the LLM which retrieved facts matter before seeding PageRank
357
+ (HippoRAG 2's "recognition memory"; one extra LLM call).
358
+ query_entities: ask the LLM for the entities named in the query (one extra call).
359
+ Other options go straight to quipu.retrieve() (fact_k, link_k, damping, fuse, as_of...).
360
+ """
361
+ qv = to_pgvector(embedding) if embedding is not None else self._qvec(query)
362
+ opts = {"mode": mode, "k": max(k, rerank_depth) if reranker else k, **options}
363
+ if mode == "graph" and rerank_facts and self.q.llm is not None:
364
+ facts = self.facts(query, k=options.get("fact_k", 20), embedding=qv)
365
+ keep = self._filter_facts(query, facts)
366
+ if keep:
367
+ opts["fact_ids"] = keep
368
+ if mode == "graph" and query_entities and self.q.llm is not None:
369
+ opts["entities"] = self._query_entities(query)
370
+ with self.q.tx() as c:
371
+ rows = c.execute("SELECT * FROM quipu.retrieve(%s, %s, %s::vector, %s)",
372
+ (self.name, query, qv, json.dumps(opts))).fetchall()
373
+ hits = [Hit(**r) for r in rows]
374
+ if reranker is not None and hits:
375
+ scores = reranker.scores(query, [h.content for h in hits])
376
+ hits = [h for _, h in sorted(zip(scores, hits), key=lambda x: -x[0])][:k]
377
+ for i, (h, s) in enumerate(zip(hits, sorted(scores, reverse=True))):
378
+ h.rank, h.signals = i + 1, {**h.signals, "rerank": s, "first_stage_score": h.score}
379
+ h.score = s
380
+ return hits
381
+
382
+ def facts(self, query: str, k: int = 10, mode: str = "hybrid", embedding=None) -> list[dict]:
383
+ qv = embedding if isinstance(embedding, str) else (
384
+ to_pgvector(embedding) if embedding is not None else self._qvec(query))
385
+ with self.q.tx() as c:
386
+ return c.execute("SELECT * FROM quipu.search_facts(%s, %s, %s::vector, %s, %s)",
387
+ (self.name, query, qv, k, mode)).fetchall()
388
+
389
+ def entities(self, query: str, k: int = 10, mode: str = "hybrid") -> list[dict]:
390
+ with self.q.tx() as c:
391
+ return c.execute("SELECT * FROM quipu.search_entities(%s, %s, %s::vector, %s, %s)",
392
+ (self.name, query, self._qvec(query), k, mode)).fetchall()
393
+
394
+ def neighbors(self, entity: str, limit: int = 50) -> list[dict]:
395
+ with self.q.tx() as c:
396
+ return c.execute("SELECT * FROM quipu.neighbors(%s, %s, %s)",
397
+ (self.name, entity, limit)).fetchall()
398
+
399
+ def context(self, chunk_ids: Iterable[int], max_facts: int = 50) -> dict:
400
+ with self.q.tx() as c:
401
+ return c.execute("SELECT quipu.context(%s, %s, %s) AS c",
402
+ (self.name, list(chunk_ids), max_facts)).fetchone()["c"]
403
+
404
+ def ask(self, question: str, k: int = 5, **kw) -> Answer:
405
+ """Retrieve, then answer with the configured LLM, citing passages."""
406
+ if self.q.llm is None:
407
+ raise ValueError("an LLM is required to answer")
408
+ hits = self.retrieve(question, k=k, **kw)
409
+ facts = self.context([h.chunk_id for h in hits]).get("facts", [])
410
+ passages = "\n\n".join(f"[{i + 1}] {(h.title + ': ') if h.title else ''}{h.content}"
411
+ for i, h in enumerate(hits))
412
+ fact_lines = "\n".join(f"- {f['fact'] or (f['source'] + ' ' + f['type'] + ' ' + f['target'])}"
413
+ for f in facts[:30])
414
+ prompt = (f"Answer the question using only the passages and facts below. Cite passages "
415
+ f"as [n]. If they do not contain the answer, say so.\n\nPassages:\n{passages}\n\n"
416
+ f"Facts:\n{fact_lines}\n\nQuestion: {question}")
417
+ return Answer(self.q.llm.complete(prompt, max_tokens=1024).strip(), hits, facts)
418
+
419
+ # -- LLM helpers ---------------------------------------------------------
420
+ def _filter_facts(self, query: str, facts: list[dict]) -> list[int]:
421
+ if not facts:
422
+ return []
423
+ listing = "\n".join(f"{i}. ({f['source']}, {f['type']}, {f['target']}) {f['fact'] or ''}"
424
+ for i, f in enumerate(facts))
425
+ prompt = (f"Question: {query}\n\nCandidate facts:\n{listing}\n\nWhich facts could help "
426
+ f"answer the question, directly or as one step of a multi-step chain? Reply with "
427
+ f'JSON only: {{"keep": [indices]}}, at most 5, most useful first.')
428
+ try:
429
+ keep = parse_json(self.q.llm.complete(prompt, max_tokens=200)).get("keep", [])
430
+ return [facts[i]["relation_id"] for i in keep if isinstance(i, int) and 0 <= i < len(facts)]
431
+ except Exception:
432
+ return []
433
+
434
+ def _query_entities(self, query: str) -> list[str]:
435
+ prompt = (f'List the named entities in this question. Reply with JSON only: {{"entities": [..]}}\n\n'
436
+ f"Question: {query}")
437
+ try:
438
+ ents = parse_json(self.q.llm.complete(prompt, max_tokens=200)).get("entities", [])
439
+ return [str(e) for e in ents if e]
440
+ except Exception:
441
+ return []
quipu/config.py ADDED
@@ -0,0 +1,53 @@
1
+ """Build clients from environment variables (used by the CLI and the MCP server).
2
+
3
+ QUIPU_DATABASE_URL postgres connection string (app role)
4
+ QUIPU_TENANT tenant id
5
+ QUIPU_GRAPH default graph name
6
+ QUIPU_EMBEDDER "openai:<model>[:dim]" | "local:<model>" (default local:BAAI/bge-base-en-v1.5)
7
+ QUIPU_LLM "anthropic:<model>" | "openai:<model>" | "claude-code:<model>" (default anthropic:claude-haiku-5-5)
8
+ OPENAI_BASE_URL / OPENAI_API_KEY / ANTHROPIC_API_KEY as usual.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+
14
+ from .client import Quipu
15
+
16
+
17
+ def make_embedder(spec: str | None = None):
18
+ spec = spec or os.environ.get("QUIPU_EMBEDDER", "local:BAAI/bge-base-en-v1.5")
19
+ kind, _, rest = spec.partition(":")
20
+ if kind == "openai":
21
+ model, _, dim = rest.partition(":")
22
+ from .embed import OpenAIEmbedder
23
+ return OpenAIEmbedder(model or "text-embedding-3-small", dim=int(dim) if dim else None)
24
+ if kind == "local":
25
+ from .embed import SentenceTransformerEmbedder
26
+ return SentenceTransformerEmbedder(rest or "BAAI/bge-base-en-v1.5")
27
+ raise ValueError(f"unknown embedder spec {spec!r}")
28
+
29
+
30
+ def make_llm(spec: str | None = None):
31
+ spec = spec or os.environ.get("QUIPU_LLM", "anthropic:claude-haiku-5-5")
32
+ kind, _, model = spec.partition(":")
33
+ from . import llm
34
+ if kind == "anthropic":
35
+ return llm.AnthropicLLM(model or "claude-haiku-5-5")
36
+ if kind == "openai":
37
+ return llm.OpenAILLM(model or "gpt-4o-mini")
38
+ if kind == "claude-code":
39
+ return llm.ClaudeCodeLLM(model or "haiku")
40
+ if kind == "none":
41
+ return None
42
+ raise ValueError(f"unknown llm spec {spec!r}")
43
+
44
+
45
+ def from_env(tenant: str | None = None, dsn: str | None = None, need_models: bool = True) -> Quipu:
46
+ dsn = dsn or os.environ.get("QUIPU_DATABASE_URL") or os.environ.get("DATABASE_URL")
47
+ tenant = tenant or os.environ.get("QUIPU_TENANT")
48
+ if not dsn:
49
+ raise SystemExit("set QUIPU_DATABASE_URL (or DATABASE_URL)")
50
+ if not tenant:
51
+ raise SystemExit("set QUIPU_TENANT or pass --tenant")
52
+ return Quipu(dsn, tenant, embedder=make_embedder() if need_models else None,
53
+ llm=make_llm() if need_models else None)