basal-engine 3.0.3__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.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/navigate.py ADDED
@@ -0,0 +1,646 @@
1
+ """basal-navigate (experimental, 2.5): retrieval by navigating a document tree with typed decisions, no index.
2
+
3
+ The corpus is a tree: topics, pages (and sections) down to passages. At each level the candidates are judged together:
4
+ one shared state holds the query and every candidate's description, and one yes / no question per candidate asks
5
+ whether its branch is worth opening (a `rank` question, basal/rank.py: one request to basal-serve per level, split into
6
+ requests of about 50 candidates when a level is larger). The best branches within the level's budget are opened, the
7
+ others pruned. The passages reached are judged the same way in one shared context, grouped under their pages in reading
8
+ order, and a final choice question reorders the top 20. Every request reads its state once, and the final choice
9
+ reads the same state again, which basal-serve --state-cache-gb keeps.
10
+
11
+ basal-navigate build docs/ -o tree.jsonl (basal/navtree.py; Markdown, HTML, text or JSONL documents)
12
+ basal-navigate search tree.jsonl "How do I renew my licence?" --url http://127.0.0.1:8000
13
+ basal-navigate calibrate tree.jsonl labels.jsonl -o cutoff.json (basal/navcut.py: how many pages to open, from your
14
+ labelled queries; then search --levels @cutoff.json)
15
+
16
+ from basal_sdk import Basal
17
+ from basal.navigate import Navigator, Tree
18
+ nav = Navigator(Basal("http://127.0.0.1:8000", timeout=600), Tree.load("tree.jsonl"), levels=[{"keep": 10}])
19
+ hits = nav.search("How do I renew my licence?")["passages"] # [{"id", "score", "choice"?, "text"}, ...]
20
+
21
+ Tree file (JSONL, one node per line, children in reading order): {"id", "parent" (null at the top), "kind" ("topic",
22
+ "page", "section", "passage" or your own), "text" (what the model reads: a description, a title, the passage itself),
23
+ "title" (optional: the heading its children are listed under), "path" (optional: a passage's heading path)}.
24
+ A node without children is a passage.
25
+
26
+ Budgets (`levels`, one per depth, the last one repeats): "keep" (at most this many branches), "min_p" (only those
27
+ with at least this probability, always at least one), "sure" (only the top branch when its probability is at least
28
+ this), "chunk" (candidates per request). `pin`: node ids always kept at their level, also when a branch above them
29
+ was pruned (a conversation's recently used pages, or its help center); `extra`: passage ids added to the last stage
30
+ (e.g. a dense retriever's top passages). `final`: "top" (the choice shortlist, 0 = none), "chunk" (0 = one shared context when its
31
+ state has at most rank.SHARED_TOKENS tokens and it fits the model's context and --max-prompt-mb), "multiply" (a passage's score times its page's), "choice_context" (basal/rank.py), "per_page"
32
+ (passages per page by the page's rank, e.g. [[3, 0], [10, 10], [30, 3]]: every passage of the top 3 pages, the first
33
+ 10 of pages 4-10, the first 3 of pages 11-30).
34
+
35
+ Very large collections (experimental, off by default): a level goes out as one request, which basal-serve refuses
36
+ above its --rank-max-candidates (10,000 by default). `split_at` (CLI --split-at N) sends a level with more than N
37
+ candidates as several requests of at most N, cut where the server's requests of `chunk` end, so every candidate reads
38
+ the same prompt as in one request; the engine batches the requests differently, so scores can differ slightly from a
39
+ one-request run. The last stage with a choice (top > 0) or one shared context (chunk 0) must still fit one request.
40
+ """
41
+ import argparse
42
+ import json
43
+ import sys
44
+ import time
45
+
46
+ from .jsonl import JSONLError, records, write
47
+ from .prompt import lang_of
48
+ from .rank import chunks
49
+
50
+ LABELS = {
51
+ "en": {"topic": ("Topic", "Topics"), "page": ("Page", "Pages"), "section": ("Section", "Sections"),
52
+ "passage": ("Passage", "Passages"), None: ("Item", "Items")},
53
+ "pl": {"topic": ("Temat", "Tematy"), "page": ("Strona", "Strony"), "section": ("Sekcja", "Sekcje"),
54
+ "passage": ("Fragment", "Fragmenty"), None: ("Pozycja", "Pozycje")},
55
+ }
56
+ WORDS = { # the questions of each kind; "dialog": the query is a conversation and the agent replies next
57
+ "en": {
58
+ "question": {
59
+ "topic": "Is the page with the information needed to answer the user's question likely in {candidate}?",
60
+ "page": "Is the information needed to answer the user's question on {candidate}?",
61
+ "section": "Is the information needed to answer the user's question in {candidate}?",
62
+ "passage": "Does {candidate} contain information needed to answer the user's question?",
63
+ "choice": "Which passage contains the information needed to answer the user's question?"},
64
+ "dialog": {
65
+ "topic": "Is the page with the information the agent needs for its next reply likely in {candidate}?",
66
+ "page": "Is the information the agent needs for its next reply on {candidate}?",
67
+ "section": "Is the information the agent needs for its next reply in {candidate}?",
68
+ "passage": "Should the agent's next reply be based on {candidate}?",
69
+ "choice": "Which passage should the agent's next reply be based on?"}},
70
+ "pl": {
71
+ "question": {
72
+ "topic": "Czy {candidate} obejmuje stronę z informacją potrzebną do odpowiedzi na pytanie użytkownika?",
73
+ "page": "Czy {candidate} zawiera informację potrzebną do odpowiedzi na pytanie użytkownika?",
74
+ "section": "Czy {candidate} zawiera informację potrzebną do odpowiedzi na pytanie użytkownika?",
75
+ "passage": "Czy {candidate} zawiera informację potrzebną do odpowiedzi na pytanie użytkownika?",
76
+ "choice": "Który fragment zawiera informację potrzebną do odpowiedzi na pytanie użytkownika?"},
77
+ "dialog": {
78
+ "topic": "Czy {candidate} obejmuje stronę z informacją, której agent potrzebuje do następnej odpowiedzi?",
79
+ "page": "Czy {candidate} zawiera informację, której agent potrzebuje do następnej odpowiedzi?",
80
+ "section": "Czy {candidate} zawiera informację, której agent potrzebuje do następnej odpowiedzi?",
81
+ "passage": "Czy {candidate} powinien być podstawą następnej odpowiedzi agenta?",
82
+ "choice": "Na którym fragmencie powinna się opierać następna odpowiedź agenta?"}},
83
+ }
84
+ QUERY = {"en": ("User's question", "Dialogue (the latest turn last)", {"user": "User", "agent": "Agent"}),
85
+ "pl": ("Pytanie użytkownika", "Rozmowa (ostatnia wypowiedź na końcu)", {"user": "Użytkownik", "agent": "Agent"})}
86
+ LEVEL = {"keep": 10}
87
+ FINAL = {"top": 20, "chunk": 0, "multiply": False, "choice_context": "auto"}
88
+ TITLE_CHARS = 200
89
+
90
+
91
+ class Tree:
92
+ """The corpus tree: nodes by id, children in reading order."""
93
+
94
+ def __init__(self, nodes):
95
+ self.nodes, self.children, self.pos = {}, {None: []}, {}
96
+ nodes = list(nodes)
97
+ for n, x in enumerate(nodes):
98
+ if not isinstance(x, dict) or not isinstance(x.get("id"), str) or not isinstance(x.get("text"), str):
99
+ raise ValueError(f"node {n}: needs a string id and a string text")
100
+ if not isinstance(x.get("parent"), (str, type(None))): # ([] or {} cannot be looked up as an id)
101
+ raise ValueError(f"node {n}: parent must be a node id (a string) or null, not "
102
+ f"{type(x['parent']).__name__}")
103
+ if x["id"] in self.nodes:
104
+ raise ValueError(f"node {n}: duplicate id {x['id']!r}")
105
+ self.nodes[x["id"]] = x
106
+ for x in nodes:
107
+ p = x.get("parent")
108
+ if p is not None and p not in self.nodes:
109
+ raise ValueError(f"node {x['id']!r}: unknown parent {p!r}")
110
+ self.children.setdefault(p, []).append(x["id"])
111
+ seen, stack = 0, [(i, 0) for i in reversed(self.children[None])]
112
+ while stack: # reading order: depth first, children in file order
113
+ i, _ = stack.pop()
114
+ self.pos[i] = seen
115
+ seen += 1
116
+ stack += [(c, 0) for c in reversed(self.children.get(i, ()))]
117
+ if seen != len(self.nodes):
118
+ raise ValueError("the tree has a cycle (a node is its own ancestor)")
119
+
120
+ @classmethod
121
+ def load(cls, path):
122
+ """A BOM (Notepad) or UTF-16 (PowerShell 5) too; a line that is not JSON: a JSONLError with its place."""
123
+ return cls(rec for _, rec in records(path))
124
+
125
+ def save(self, path):
126
+ """The nodes in reading order, the file whole or not at all (an interrupted build leaves the old tree)."""
127
+ write(path, (self.nodes[i] for i in sorted(self.nodes, key=self.pos.get)))
128
+
129
+ @property
130
+ def roots(self):
131
+ return self.children[None]
132
+
133
+ def leaf(self, i):
134
+ return not self.children.get(i)
135
+
136
+ def leaves(self, i):
137
+ """The passages under node i (or i itself), in reading order."""
138
+ return list(self.iter_leaves(i))
139
+
140
+ def iter_leaves(self, i):
141
+ """leaves(i) one at a time: a reader that stops early does not walk the rest of the subtree."""
142
+ stack = [i]
143
+ while stack:
144
+ j = stack.pop()
145
+ kids = self.children.get(j)
146
+ if kids:
147
+ stack += reversed(kids)
148
+ else:
149
+ yield j
150
+
151
+ def title(self, i):
152
+ x = self.nodes[i]
153
+ return (x.get("title") or x["text"])[:TITLE_CHARS]
154
+
155
+ def group(self, i):
156
+ """The heading a node is listed under: its parent's title, from the nearest page down (None at the top)."""
157
+ parts, p = [], self.nodes[i].get("parent")
158
+ while p is not None:
159
+ parts.append(self.title(p))
160
+ if self.nodes[p].get("kind") == "page":
161
+ break
162
+ p = self.nodes[p].get("parent")
163
+ return " > ".join(reversed(parts)) or None
164
+
165
+ def shown(self, i):
166
+ x = self.nodes[i]
167
+ return f"[{x['path']}] {x['text']}" if x.get("path") else x["text"]
168
+
169
+
170
+ def check_level(n, b):
171
+ """Level n's budget, before a search uses it: keep a whole number of at least 1, min_p and sure numbers from 0 to 1
172
+ (or null), chunk a whole number of at least 0; ValueError naming the level and the field (other keys are left)."""
173
+ def whole(v):
174
+ return isinstance(v, int) and not isinstance(v, bool)
175
+ if "keep" in b and not (whole(b["keep"]) and b["keep"] >= 1):
176
+ raise ValueError(f"level {n}: keep must be a whole number of at least 1, not {b['keep']!r}")
177
+ for k in ("min_p", "sure"):
178
+ v = b.get(k)
179
+ if v is not None and not (isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v <= 1):
180
+ raise ValueError(f"level {n}: {k} must be a number from 0 to 1 (or null), not {v!r}")
181
+ if "chunk" in b and not (whole(b["chunk"]) and b["chunk"] >= 0):
182
+ raise ValueError(f"level {n}: chunk must be a whole number of at least 0, not {b['chunk']!r}")
183
+
184
+
185
+ def select(ranking, budget):
186
+ """The kept (id, score) of a level's ranking (best first) under a budget {"keep", "min_p", "sure"}."""
187
+ out = ranking[: budget.get("keep", LEVEL["keep"])]
188
+ if budget.get("min_p") is not None:
189
+ out = [x for x in out if x[1] >= budget["min_p"]] or ranking[:1]
190
+ if budget.get("sure") is not None and ranking and ranking[0][1] >= budget["sure"]:
191
+ out = ranking[:1]
192
+ return out
193
+
194
+
195
+ def query_state(query, lang, turns=6):
196
+ """The query as the state's head: a question, or the last `turns` turns of a conversation."""
197
+ head, conv, roles = QUERY[lang]
198
+ if isinstance(query, str):
199
+ return f"{head}: {query}"
200
+ lines = []
201
+ for t in list(query)[-turns:]:
202
+ if isinstance(t, str):
203
+ lines.append(t)
204
+ else:
205
+ role = roles.get(t.get("role"), roles["agent"] if t.get("role") == "assistant" else t.get("role", ""))
206
+ lines.append(f"{role}: {t['text']}")
207
+ return conv + ":\n" + "\n".join(lines)
208
+
209
+
210
+ def _text_of(query):
211
+ return query if isinstance(query, str) else " ".join(t if isinstance(t, str) else t.get("text", "") for t in query)
212
+
213
+
214
+ class Navigator:
215
+ """Search a Tree through a basal-serve (client: basal_sdk.Basal, or any object with request(body) -> the
216
+ response). levels: budgets per depth (the last one repeats); final: the last stage's settings; style "question" or
217
+ "dialog" (default: dialog for a list of turns); lang "en" / "pl" (default: from the query); wording: your own
218
+ question templates {kind: "... {candidate} ...", "choice": "..."}; order: "state_first" or "candidates_first";
219
+ split_at (experimental, 0 = off): a level with more candidates goes out as several requests (set it to basal-serve's
220
+ --rank-max-candidates)."""
221
+
222
+ def __init__(self, client, tree, levels=None, final=None, style=None, lang=None, wording=None, chunk=50,
223
+ order="state_first", turns=6, split_at=0):
224
+ self.client, self.tree, self.split_at = client, tree, split_at
225
+ self.levels = [dict(b) for b in (levels or [LEVEL])]
226
+ for n, b in enumerate(self.levels):
227
+ check_level(n, b)
228
+ self.final = {**FINAL, **(final or {})}
229
+ self.style, self.lang, self.wording, self.chunk, self.order, self.turns = style, lang, wording or {}, chunk, \
230
+ order, turns
231
+
232
+ def words(self, lang, style, kind):
233
+ return self.wording.get(kind) or WORDS[lang][style].get(kind) or WORDS[lang][style]["section"]
234
+
235
+ def label(self, lang, kind):
236
+ return LABELS[lang].get(kind) or LABELS[lang][None]
237
+
238
+ def ask(self, state, lang, style, groups, chunk, top=0, prior=None, context="auto"):
239
+ """A rank question per kind of candidate, in one request (or several with split_at) -> ([(id, score, choice)]
240
+ best first, the server's requests)."""
241
+ qs = {}
242
+ for kind, ids in groups.items():
243
+ lab, title = self.label(lang, kind)
244
+ cands = []
245
+ for i in ids:
246
+ g = self.tree.group(i)
247
+ cands.append({"key": i, "text": self.tree.shown(i) if self.tree.leaf(i) else self.tree.nodes[i]["text"],
248
+ **({"group": g} if g else {})})
249
+ q = {"type": "rank", "instructions": self.words(lang, style, kind), "candidates": cands, "label": lab,
250
+ "list_title": title, "chunk": chunk, "top": top, "order": self.order, "choice_context": context}
251
+ if top:
252
+ q["choice_instructions"] = self.words(lang, style, "choice")
253
+ if prior:
254
+ q["prior"] = {i: prior[i] for i in ids if i in prior}
255
+ qs[kind or "item"] = q
256
+ parts = self.parts(qs, chunk, top) if self.split_at else [qs]
257
+ if len(parts) == 1: # one request per level (the default)
258
+ out = self.client.request({"state": state, "questions": qs, "lang": lang})
259
+ ranks = [[(e["key"], e["score"], e.get("choice")) for e in a["ranking"]]
260
+ for a in out["answers"].values()]
261
+ # Compare the current head of each group so the server's within-group choice order survives.
262
+ import heapq
263
+ ranking = list(heapq.merge(*ranks, key=lambda e: -e[1]))
264
+ return ranking, out["usage"].get("requests", 1)
265
+ rankings, n_req = {name: [] for name in qs}, 0
266
+ for part in parts:
267
+ out = self.client.request({"state": state, "questions": part, "lang": lang})
268
+ n_req += out["usage"].get("requests", 1)
269
+ for name, a in out["answers"].items():
270
+ rankings[name] += [(e["key"], e["score"], e.get("choice")) for e in a["ranking"]]
271
+ # stable: equal scores keep the candidates' order, as in one request
272
+ rankings = {name: sorted(r, key=lambda x: -x[1]) for name, r in rankings.items()}
273
+ ranking = [x for r in rankings.values() for x in r]
274
+ return (sorted(ranking, key=lambda x: -x[1]) if len(qs) > 1 else ranking), n_req
275
+
276
+ def parts(self, qs, chunk, top):
277
+ """split_at: the rank questions of a level as requests of at most split_at candidates in all: whole requests
278
+ of `chunk` (rank.chunks) per part, so each candidate is judged in the same request as without parts. A last
279
+ stage (a choice, or one shared context) must fit one request."""
280
+ n = sum(len(q["candidates"]) for q in qs.values())
281
+ if n <= self.split_at:
282
+ return [qs]
283
+ if top or not chunk:
284
+ raise ValueError(f"the last stage has {n} passages, more than split_at ({self.split_at}): lower keep or "
285
+ "per_page, or raise --split-at and basal-serve --rank-max-candidates")
286
+ out, cur, size = [], {}, 0
287
+ for name, q in qs.items():
288
+ cands = q["candidates"]
289
+ for idx in chunks([(c["key"], c["text"], c.get("group")) for c in cands], chunk):
290
+ if size and size + len(idx) > self.split_at:
291
+ out.append(cur)
292
+ cur, size = {}, 0
293
+ cur.setdefault(name, dict(q, candidates=[]))["candidates"] += [cands[i] for i in idx]
294
+ size += len(idx)
295
+ out.append(cur)
296
+ for part in out: # each part's prior names only its own candidates
297
+ for q in part.values():
298
+ if "prior" in q:
299
+ q["prior"] = {c["key"]: q["prior"][c["key"]] for c in q["candidates"] if c["key"] in q["prior"]}
300
+ return out
301
+
302
+ def depth(self, i):
303
+ d, p = 0, self.tree.nodes[i].get("parent")
304
+ while p is not None:
305
+ d, p = d + 1, self.tree.nodes[p].get("parent")
306
+ return d
307
+
308
+ def cap(self, pool, rank_of, keep=()):
309
+ """The passages of each judged page within its rank's allowance (final "per_page"); a page ranked beyond the
310
+ last bound adds none; passages without a judged ancestor and pinned passages (keep) are kept."""
311
+ keep = {leaf for pinned in keep for leaf in self.tree.iter_leaves(pinned)}
312
+ out, used = [], {}
313
+ for x in pool:
314
+ if x in keep:
315
+ out.append(x)
316
+ continue
317
+ p = self.tree.nodes[x].get("parent")
318
+ while p is not None and p not in rank_of:
319
+ p = self.tree.nodes[p].get("parent")
320
+ if p is None:
321
+ out.append(x)
322
+ continue
323
+ n = next((m for upto, m in self.final["per_page"] if rank_of[p] < upto), -1)
324
+ if n == 0 or used.get(p, 0) < n:
325
+ out.append(x)
326
+ used[p] = used.get(p, 0) + 1
327
+ return out
328
+
329
+ def search(self, query, k=10, pin=(), extra=(), trace=None, depth_limit=None):
330
+ """The best passages for a query (a question, or a conversation: a list of turns {"role", "text"} or strings)
331
+ -> {"passages": [{"id", "score", "choice"?, "text"}], "stages": [...], "latency_ms"}. trace: a list that gets
332
+ each level's {"depth", "ranking": [(id, score)] best first (None when the level fitted its budget, unasked),
333
+ "kept"}; depth_limit: stop after that depth's level, with no last stage (no passages): basal/navcut.py's
334
+ calibration reads the levels as a search makes them."""
335
+ t0 = time.perf_counter()
336
+ tree = self.tree
337
+ lang = self.lang or lang_of(_text_of(query))
338
+ style = self.style or ("question" if isinstance(query, str) else "dialog")
339
+ state = query_state(query, lang, self.turns)
340
+ pin = [p for p in pin if p in tree.nodes]
341
+ pin_depth = {p: self.depth(p) for p in pin}
342
+ frontier, pool, score, rank_of, stages, depth = list(tree.roots), [], {}, {}, [], 0
343
+ seen = set()
344
+ while True:
345
+ pruned = [p for p in pin if pin_depth[p] == depth and p not in set(frontier)] # a pruned branch's pin
346
+ frontier = sorted(frontier + pruned, key=tree.pos.get) if pruned else frontier
347
+ seen.update(frontier)
348
+ pool += [i for i in frontier if tree.leaf(i)]
349
+ inner = [i for i in frontier if not tree.leaf(i)]
350
+ if not inner:
351
+ break
352
+ b = self.levels[min(depth, len(self.levels) - 1)]
353
+ t1, n_req = time.perf_counter(), 0
354
+ ranking = None
355
+ if len(inner) <= b.get("keep", LEVEL["keep"]) and b.get("min_p") is None and b.get("sure") is None:
356
+ kept = inner # the whole level fits the budget: no request
357
+ else:
358
+ groups = {}
359
+ for i in inner:
360
+ groups.setdefault(tree.nodes[i].get("kind"), []).append(i)
361
+ ranking, n_req = self.ask(state, lang, style, groups, b.get("chunk", self.chunk))
362
+ score.update((i, s) for i, s, _ in ranking)
363
+ rank_of.update((i, r) for r, (i, _, _) in enumerate(ranking))
364
+ kept = [i for i, _ in select([(i, s) for i, s, _ in ranking], b)]
365
+ kept = sorted(set(kept) | (set(pin) & set(inner)), key=tree.pos.get)
366
+ stages.append({"depth": depth, "candidates": len(inner), "kept": kept, "requests": n_req,
367
+ "ms": round((time.perf_counter() - t1) * 1000, 2)})
368
+ if trace is not None:
369
+ trace.append({"depth": depth, "ranking": None if ranking is None else [(i, s) for i, s, _ in ranking],
370
+ "kept": kept})
371
+ if depth_limit is not None and depth >= depth_limit:
372
+ return {"passages": [], "stages": stages, "latency_ms": round((time.perf_counter() - t0) * 1000, 2)}
373
+ frontier = [c for i in kept for c in tree.children[i]]
374
+ depth += 1
375
+ if self.final.get("per_page"): # passages per page by the page's rank: [[up to rank, at most n (0 = all)]]
376
+ pool = self.cap(pool, rank_of, set(pin))
377
+ reached = set(pool)
378
+ for p in pin: # a pin deeper than the search went: its passages join the last stage
379
+ if p not in seen:
380
+ pool += [x for x in tree.leaves(p) if x not in reached and not reached.add(x)]
381
+ pool += [x for x in dict.fromkeys(extra) if x in tree.nodes and tree.leaf(x) and x not in reached
382
+ and not reached.add(x)]
383
+ pool.sort(key=tree.pos.get)
384
+ if not pool:
385
+ return {"passages": [], "stages": stages, "latency_ms": round((time.perf_counter() - t0) * 1000, 2)}
386
+ f, prior = self.final, None
387
+ if f["multiply"]:
388
+ prior = {}
389
+ for x in pool:
390
+ p = tree.nodes[x].get("parent")
391
+ while p is not None and p not in score:
392
+ p = tree.nodes[p].get("parent")
393
+ prior[x] = score.get(p, 1.0)
394
+ t1 = time.perf_counter()
395
+ groups = {}
396
+ for x in pool:
397
+ groups.setdefault("passage", []).append(x)
398
+ ranking, n_req = self.ask(state, lang, style, groups, f["chunk"], f["top"], prior, f["choice_context"])
399
+ stages.append({"depth": depth, "candidates": len(pool), "kept": [], "requests": n_req,
400
+ "ms": round((time.perf_counter() - t1) * 1000, 2)})
401
+ hits = []
402
+ for i, s, c in ranking[:k]:
403
+ hits.append({"id": i, "score": s, **({"choice": c} if c is not None else {}), "text": tree.nodes[i]["text"]})
404
+ return {"passages": hits, "stages": stages, "latency_ms": round((time.perf_counter() - t0) * 1000, 2)}
405
+
406
+
407
+ def parser():
408
+ ap = argparse.ArgumentParser(prog="basal-navigate", description="Retrieval by navigating a document tree with "
409
+ "typed decisions (experimental): build a tree, then search it through basal-serve")
410
+ sub = ap.add_subparsers(dest="cmd", required=True)
411
+ b = sub.add_parser("build", help="a tree (JSONL) from Markdown, HTML, text, JSONL or PDF documents "
412
+ "(basal/navtree.py)")
413
+ b.add_argument("inputs", nargs="+", help="files or folders (.md, .markdown, .html, .htm, .txt, .jsonl, .pdf: "
414
+ "needs basal-engine[pdf])")
415
+ b.add_argument("-o", "--out", required=True, help="the tree file to write (JSONL)")
416
+ b.add_argument("--split-long", type=int, default=0, metavar="N",
417
+ help="a section level under pages with more than N passages (default: none)")
418
+ b.add_argument("--group-dirs", action="store_true",
419
+ help="folders become topics above their pages (a PDF: a topic above its pages)")
420
+ from .pdf import LIMITS
421
+ b.add_argument("--pdf-max-mb", dest="pdf_max_mb", type=float, default=LIMITS["max_mb"], metavar="MB",
422
+ help="a larger PDF is refused before it is read (default %(default)s)")
423
+ b.add_argument("--pdf-max-pages", dest="pdf_max_pages", type=int, default=LIMITS["max_pages"], metavar="N",
424
+ help="a PDF with more pages is refused (default %(default)s)")
425
+ b.add_argument("--pdf-seconds", dest="pdf_seconds", type=float, default=LIMITS["seconds"], metavar="S",
426
+ help="the time a PDF may take to read, else it is refused (default %(default)s)")
427
+ b.add_argument("--clusters", type=int, default=0, metavar="K",
428
+ help="topics by k-means over the pages (needs basal-engine[navigate]); 0 = none")
429
+ b.add_argument("--max-children", type=int, default=0, metavar="M",
430
+ help="with --clusters: split a topic of more than M pages again (recursive k-means)")
431
+ b.add_argument("--max-chars", type=int, default=2000, help="split longer passages (default 2000 characters)")
432
+ b.add_argument("--min-chars", type=int, default=0, help="merge shorter passages under one heading (default off)")
433
+ b.add_argument("--lang", choices=["en", "pl"], default=None, help="the language of generated descriptions")
434
+ s = sub.add_parser("search", help="the best passages for a query (or a JSONL file of queries)")
435
+ s.add_argument("tree", help="the tree file (JSONL)")
436
+ s.add_argument("query", nargs="?", help="the question (or give --queries)")
437
+ s.add_argument("--queries", help='JSONL: {"id", "query" | "turns", "pin"?, "extra"?} per line; writes JSONL')
438
+ s.add_argument("--url", default="http://127.0.0.1:8000", help="basal-serve (default %(default)s)")
439
+ s.add_argument("--api-key", default=None)
440
+ s.add_argument("--timeout", type=float, default=600)
441
+ s.add_argument("--k", type=int, default=10, help="passages returned (default 10)")
442
+ s.add_argument("--keep", type=int, default=None, help="branches kept at every level (default 10)")
443
+ s.add_argument("--levels", default=None, help='budgets per depth as JSON, e.g. \'[{"keep": 2, "sure": 0.8}, '
444
+ '{"keep": 10}]\', or @FILE: such a list, or the cut-off of basal-navigate calibrate')
445
+ s.add_argument("--force", action="store_true",
446
+ help="use a --levels @FILE cut-off fitted on another model (its scores are that model's)")
447
+ s.add_argument("--top", type=int, default=FINAL["top"], help="the final choice shortlist (0 = none)")
448
+ s.add_argument("--final-chunk", type=int, default=FINAL["chunk"],
449
+ help="passages per request in the last stage (0 = one shared context when it fits)")
450
+ s.add_argument("--chunk", type=int, default=50, help="candidates per request at the other levels")
451
+ s.add_argument("--split-at", type=int, default=0, metavar="N",
452
+ help="experimental: send a level with more than N candidates as several requests of at most N (set N "
453
+ "to basal-serve's --rank-max-candidates, 10000 by default); scores can differ slightly from one "
454
+ "request. Default: off (one request per level)")
455
+ s.add_argument("--multiply", action="store_true", help="a passage's score times its page's")
456
+ s.add_argument("--per-page", default=None, help="passages per page by the page's rank as JSON, e.g. "
457
+ "'[[3, 0], [10, 10], [30, 3]]' (every passage of the top 3 pages, 10 of pages 4-10, 3 of 11-30)")
458
+ s.add_argument("--choice-context", choices=["auto", "screen", "shortlist"], default="auto")
459
+ s.add_argument("--order", choices=["state_first", "candidates_first"], default="state_first")
460
+ s.add_argument("--style", choices=["question", "dialog"], default=None)
461
+ s.add_argument("--lang", choices=["en", "pl"], default=None)
462
+ s.add_argument("--json", action="store_true", help="print the whole result as JSON")
463
+ c = sub.add_parser("calibrate", help="a cut-off for how many pages a search opens, fitted on labelled queries so "
464
+ "that the answer's page is opened with a stated probability (basal/navcut.py)")
465
+ c.add_argument("tree", help="the tree file (JSONL)")
466
+ c.add_argument("labels", help='JSONL: {"id"?, "query" | "turns", "pages": [page ids] | "passages": [ids]} per line')
467
+ c.add_argument("-o", "--out", required=True, help="the cut-off file to write (for search --levels @FILE)")
468
+ c.add_argument("--coverage", type=float, default=0.9,
469
+ help="the probability that a query's answer page is opened (default %(default)s)")
470
+ c.add_argument("--max-keep", dest="max_keep", type=int, default=50,
471
+ help="at most this many branches opened at a calibrated level (default %(default)s)")
472
+ c.add_argument("--cert-share", dest="cert_share", type=float, default=0.5,
473
+ help="the share of the labelled queries kept out of the fit to measure it (default %(default)s)")
474
+ c.add_argument("--seed", type=int, default=0, help="of the FIT / CERT split")
475
+ c.add_argument("--levels", default=None,
476
+ help="the levels below the answer pages, and the budget the report compares with, as JSON "
477
+ "(default: keep 10)")
478
+ for p in (c,):
479
+ p.add_argument("--url", default="http://127.0.0.1:8000", help="basal-serve (default %(default)s)")
480
+ p.add_argument("--api-key", default=None)
481
+ p.add_argument("--timeout", type=float, default=600)
482
+ p.add_argument("--chunk", type=int, default=50, help="candidates per request at the levels")
483
+ p.add_argument("--order", choices=["state_first", "candidates_first"], default="state_first")
484
+ p.add_argument("--style", choices=["question", "dialog"], default=None)
485
+ p.add_argument("--lang", choices=["en", "pl"], default=None)
486
+ return ap
487
+
488
+
489
+ def _tree(path):
490
+ """The tree file, or SystemExit with what is wrong in it."""
491
+ try:
492
+ return Tree.load(path)
493
+ except JSONLError as e:
494
+ raise SystemExit(f"basal-navigate: {e}") from None
495
+ except ValueError as e: # a node without an id or a text, a duplicate id, a cycle
496
+ raise SystemExit(f"basal-navigate: {path}: {e}") from None
497
+
498
+
499
+ ORDER_WARNING = ("basal-navigate: the server keeps its states on disk (--state-cache-dir), but --order state_first "
500
+ "puts the query before each list, so no list is shared between queries or read back for a later "
501
+ "one; --order candidates_first shares them (docs/NAVIGATE.md)")
502
+
503
+
504
+ def _warn_order(client):
505
+ """search --order state_first against a server with a disk tier (GET /v1/capabilities, 3.0): one line on stderr.
506
+ A server that does not say (before 3.0), or a client without capabilities(), is not warned about."""
507
+ import httpx
508
+
509
+ from basal_sdk.client import BasalError
510
+ ask = getattr(client, "capabilities", None)
511
+ if ask is None:
512
+ return
513
+ try:
514
+ caps = ask()
515
+ except (BasalError, httpx.HTTPError, ValueError):
516
+ return
517
+ if ((caps.get("state_cache") if isinstance(caps, dict) else None) or {}).get("disk"):
518
+ print(ORDER_WARNING, file=sys.stderr)
519
+
520
+
521
+ def _per_page(text):
522
+ """--per-page: [[up to rank, at most n passages (0: all)], ...], or SystemExit saying what is wrong."""
523
+ try:
524
+ pp = json.loads(text)
525
+ except json.JSONDecodeError as e:
526
+ raise SystemExit(f"basal-navigate: --per-page: not JSON: {e}") from None
527
+ if not isinstance(pp, list) or not all(
528
+ isinstance(x, list) and len(x) == 2 and all(isinstance(v, int) and not isinstance(v, bool) and v >= 0
529
+ for v in x) for x in pp):
530
+ raise SystemExit(f"basal-navigate: --per-page: a list of [up to rank, at most n] pairs of whole numbers "
531
+ f"([[3, 0], [10, 10]]), not {text}")
532
+ return pp
533
+
534
+
535
+ def _query_line(q, where):
536
+ """A --queries line -> (its query or turns, pin, extra), or SystemExit naming the line and what is wrong: "query"
537
+ a text or "turns" a list of texts or {"role", "text"}; "pin" and "extra" lists of node ids (null: none)."""
538
+ query = q.get("turns") or q.get("query")
539
+ if isinstance(query, list):
540
+ if not all(isinstance(t, str) or isinstance(t, dict) and isinstance(t.get("text"), str) for t in query):
541
+ raise SystemExit(f'basal-navigate: {where}: "turns" must be a list of texts or {{"role", "text"}} objects')
542
+ elif not isinstance(query, str) or not query:
543
+ raise SystemExit(f'basal-navigate: {where}: needs a "query" (a text) or "turns" (a list)')
544
+ ids = []
545
+ for k in ("pin", "extra"):
546
+ v = q.get(k) or []
547
+ if not isinstance(v, list) or not all(isinstance(i, str) for i in v):
548
+ raise SystemExit(f'basal-navigate: {where}: "{k}" must be a list of node ids')
549
+ ids.append(v)
550
+ return query, *ids
551
+
552
+
553
+ def _calibrate(a):
554
+ from basal_sdk.client import Basal
555
+ from .navcut import CutoffError, calibrate, load_levels, model_entry, read_labels, write_file
556
+ tree = _tree(a.tree)
557
+ settings = {"style": a.style, "lang": a.lang, "chunk": a.chunk, "order": a.order}
558
+ try:
559
+ labels = read_labels(a.labels, tree)
560
+ base = load_levels(a.levels) if a.levels else None
561
+ with Basal(a.url, timeout=a.timeout, api_key=a.api_key) as client:
562
+ model = model_entry(client)
563
+ result = calibrate(client, tree, labels, a.coverage, a.max_keep, base, settings, a.cert_share, a.seed)
564
+ except (CutoffError, ValueError) as e:
565
+ raise SystemExit(f"basal-navigate calibrate: {e}") from None
566
+ write_file(a.out, result, a.coverage, a.labels, a.tree, model, settings, a.seed, a.cert_share)
567
+ for f in result["fitted"]:
568
+ lost = (f"; {f['lost']} lost at the levels above, the server's scores having moved since the last pass"
569
+ if f.get("lost") else "")
570
+ print(f"depth {f['depth']}: {f['n']} FIT queries, cut-off {f['threshold']:.4f} (the {f['k']}-th smallest "
571
+ f"answer score, miscoverage {f['alpha']:.4g}{lost})", file=sys.stderr)
572
+ r = result["report"]
573
+ for name in ("cert_cutoff", "cert_given_levels"):
574
+ if name in r:
575
+ x = r[name]
576
+ print(f"{'CERT, cut-off' if name == 'cert_cutoff' else 'CERT, the given levels'}: coverage "
577
+ f"{x['coverage']:.3f} over {x['queries']} queries, pages opened mean {x['pages_mean']}, p90 "
578
+ f"{x['pages_p90']}, max {x['pages_max']}", file=sys.stderr)
579
+ print(f"{a.out}: levels {json.dumps(result['levels'])}", file=sys.stderr)
580
+
581
+
582
+ def main(argv=None):
583
+ a = parser().parse_args(argv)
584
+ if a.cmd == "build":
585
+ from .navtree import build
586
+ try: # a document that cannot be read (its file and line); nothing is written then
587
+ nodes = build(a.inputs, split_long=a.split_long, group_dirs=a.group_dirs, clusters=a.clusters,
588
+ max_children=a.max_children, max_chars=a.max_chars, min_chars=a.min_chars, lang=a.lang,
589
+ skip=[a.out], pdf={"max_mb": a.pdf_max_mb, "max_pages": a.pdf_max_pages,
590
+ "seconds": a.pdf_seconds})
591
+ except ValueError as e:
592
+ raise SystemExit(f"basal-navigate build: {e}") from None
593
+ tree = Tree(nodes)
594
+ try: # (a text the file cannot hold, such as a lone surrogate from a JSONL document's "\ud800")
595
+ tree.save(a.out)
596
+ except ValueError as e:
597
+ raise SystemExit(f"basal-navigate build: {e}") from None
598
+ kinds = {}
599
+ for x in tree.nodes.values():
600
+ kinds[x.get("kind")] = kinds.get(x.get("kind"), 0) + 1
601
+ print(f"{a.out}: " + ", ".join(f"{n} {k}" for k, n in kinds.items()), file=sys.stderr)
602
+ return
603
+ if a.cmd == "calibrate":
604
+ return _calibrate(a)
605
+ from basal_sdk.client import Basal
606
+ from .navcut import CutoffError, load_levels
607
+ if (a.query is None) == (a.queries is None):
608
+ raise SystemExit("give a query or --queries")
609
+ final = {"top": a.top, "chunk": a.final_chunk, "multiply": a.multiply, "choice_context": a.choice_context,
610
+ **({"per_page": _per_page(a.per_page)} if a.per_page else {})}
611
+ tree = _tree(a.tree)
612
+ with Basal(a.url, timeout=a.timeout, api_key=a.api_key) as client:
613
+ if a.order == "state_first":
614
+ _warn_order(client)
615
+ try: # (a cut-off file is checked against the served model, the tree and these settings)
616
+ levels = load_levels(a.levels, client, a.tree, {"style": a.style, "lang": a.lang, "chunk": a.chunk,
617
+ "order": a.order}, a.force,
618
+ warn=lambda m: print(m, file=sys.stderr)) if a.levels else \
619
+ [{"keep": a.keep or LEVEL["keep"]}]
620
+ except (CutoffError, ValueError) as e:
621
+ raise SystemExit(f"basal-navigate: {e}") from None
622
+ nav = Navigator(client, tree, levels, final, a.style, a.lang, chunk=a.chunk, order=a.order,
623
+ split_at=a.split_at)
624
+ if a.query is not None:
625
+ r = nav.search(a.query, k=a.k)
626
+ if a.json:
627
+ print(json.dumps(r, ensure_ascii=False, indent=1))
628
+ return
629
+ for n, h in enumerate(r["passages"], 1):
630
+ print(f"{n:>3} {h['score']:.3f} {h['id']} {h['text'][:100]}")
631
+ print(f"{r['latency_ms']:.0f} ms, {sum(s['requests'] for s in r['stages'])} requests", file=sys.stderr)
632
+ return
633
+ try: # read as they go (a pipe too); a line that is not a JSON object stops it with its place
634
+ for n, q in records(a.queries, objects=True):
635
+ query, pin, extra = _query_line(q, f"--queries {a.queries}:{n}")
636
+ r = nav.search(query, k=a.k, pin=pin, extra=extra)
637
+ print(json.dumps({"id": q.get("id"), "passages": [h["id"] for h in r["passages"]],
638
+ "scores": [h["score"] for h in r["passages"]], "latency_ms": r["latency_ms"],
639
+ "stages": [{k: v for k, v in s.items() if k != "kept"} for s in r["stages"]]},
640
+ ensure_ascii=False), flush=True)
641
+ except JSONLError as e:
642
+ raise SystemExit(f"basal-navigate: --queries {e}") from None
643
+
644
+
645
+ if __name__ == "__main__":
646
+ main()