bitskitten 0.4.0__tar.gz → 0.6.0__tar.gz

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 (60) hide show
  1. bitskitten-0.6.0/NOTICE +7 -0
  2. {bitskitten-0.4.0 → bitskitten-0.6.0}/PKG-INFO +130 -20
  3. bitskitten-0.4.0/bitskitten.egg-info/PKG-INFO → bitskitten-0.6.0/README.md +113 -33
  4. bitskitten-0.6.0/__init__.py +60 -0
  5. bitskitten-0.6.0/_deps.py +20 -0
  6. bitskitten-0.6.0/_sink.py +14 -0
  7. {bitskitten-0.4.0 → bitskitten-0.6.0}/bandit.py +14 -10
  8. bitskitten-0.4.0/README.md → bitskitten-0.6.0/bitskitten.egg-info/PKG-INFO +143 -12
  9. {bitskitten-0.4.0 → bitskitten-0.6.0}/bitskitten.egg-info/SOURCES.txt +29 -1
  10. bitskitten-0.6.0/bitskitten.egg-info/requires.txt +21 -0
  11. bitskitten-0.6.0/codegraph.py +395 -0
  12. bitskitten-0.6.0/llm/__init__.py +12 -0
  13. bitskitten-0.6.0/llm/report.py +113 -0
  14. bitskitten-0.6.0/llm/tools.py +272 -0
  15. bitskitten-0.6.0/metrics.py +64 -0
  16. bitskitten-0.6.0/process/__init__.py +20 -0
  17. bitskitten-0.6.0/process/bpmn.py +881 -0
  18. bitskitten-0.6.0/process/examples/answer-from-memory.bpmn +64 -0
  19. bitskitten-0.6.0/process/examples/answer-from-memory.md +27 -0
  20. bitskitten-0.6.0/process/examples/bug-fix.bpmn +100 -0
  21. bitskitten-0.6.0/process/examples/bug-fix.md +36 -0
  22. bitskitten-0.6.0/pyproject.toml +49 -0
  23. {bitskitten-0.4.0 → bitskitten-0.6.0}/qa/__init__.py +2 -2
  24. {bitskitten-0.4.0 → bitskitten-0.6.0}/qa/judge.py +14 -6
  25. {bitskitten-0.4.0 → bitskitten-0.6.0}/qa/runner.py +8 -3
  26. bitskitten-0.6.0/search/__init__.py +16 -0
  27. bitskitten-0.6.0/search/bm25.py +55 -0
  28. bitskitten-0.6.0/search/chunk.py +161 -0
  29. bitskitten-0.6.0/search/encoder.py +55 -0
  30. bitskitten-0.6.0/search/index.py +184 -0
  31. bitskitten-0.6.0/search/model.py +43 -0
  32. {bitskitten-0.4.0 → bitskitten-0.6.0}/tests/test_bandit.py +12 -2
  33. bitskitten-0.6.0/tests/test_boundary.py +64 -0
  34. bitskitten-0.6.0/tests/test_chunk_graph.py +113 -0
  35. {bitskitten-0.4.0 → bitskitten-0.6.0}/tests/test_fit_time.py +12 -0
  36. bitskitten-0.6.0/tests/test_process.py +242 -0
  37. bitskitten-0.6.0/tests/test_process_review.py +337 -0
  38. {bitskitten-0.4.0 → bitskitten-0.6.0}/tests/test_qa_judge.py +10 -1
  39. {bitskitten-0.4.0 → bitskitten-0.6.0}/tests/test_qa_runner.py +5 -3
  40. bitskitten-0.6.0/tests/test_search.py +116 -0
  41. bitskitten-0.6.0/tests/test_tools.py +144 -0
  42. bitskitten-0.4.0/__init__.py +0 -35
  43. bitskitten-0.4.0/bitskitten.egg-info/requires.txt +0 -9
  44. bitskitten-0.4.0/metrics.py +0 -36
  45. bitskitten-0.4.0/pyproject.toml +0 -46
  46. {bitskitten-0.4.0 → bitskitten-0.6.0}/LICENSE +0 -0
  47. {bitskitten-0.4.0 → bitskitten-0.6.0}/bitskitten.egg-info/dependency_links.txt +0 -0
  48. {bitskitten-0.4.0 → bitskitten-0.6.0}/bitskitten.egg-info/top_level.txt +0 -0
  49. {bitskitten-0.4.0 → bitskitten-0.6.0}/classes.py +0 -0
  50. {bitskitten-0.4.0 → bitskitten-0.6.0}/input.py +0 -0
  51. {bitskitten-0.4.0 → bitskitten-0.6.0}/output.py +0 -0
  52. {bitskitten-0.4.0 → bitskitten-0.6.0}/qa/checks.py +0 -0
  53. {bitskitten-0.4.0 → bitskitten-0.6.0}/qa/failures.py +0 -0
  54. {bitskitten-0.4.0 → bitskitten-0.6.0}/qa/scenario.py +0 -0
  55. {bitskitten-0.4.0 → bitskitten-0.6.0}/qa/users.py +0 -0
  56. {bitskitten-0.4.0 → bitskitten-0.6.0}/setup.cfg +0 -0
  57. {bitskitten-0.4.0 → bitskitten-0.6.0}/tests/test_qa.py +0 -0
  58. {bitskitten-0.4.0 → bitskitten-0.6.0}/tests/test_qa_users.py +0 -0
  59. {bitskitten-0.4.0 → bitskitten-0.6.0}/tests/test_smoke.py +0 -0
  60. {bitskitten-0.4.0 → bitskitten-0.6.0}/text.py +0 -0
@@ -0,0 +1,7 @@
1
+ bitskitten
2
+ Copyright 2022-2026 Caerno. Licensed under the Apache License, Version 2.0 (LICENSE).
3
+
4
+ bitskitten.search.fetch_model() downloads, at run time, the model
5
+ caerno/rubert-mini-retriever-onnx-int8 (Hugging Face): an ONNX int8 export of
6
+ rubert-mini-retriever by sergeyzh, distributed under the MIT License.
7
+ The model files are not part of this distribution.
@@ -1,38 +1,55 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bitskitten
3
- Version: 0.4.0
4
- Summary: EDA reports, plots and sklearn-compatible encoders
3
+ Version: 0.6.0
4
+ Summary: Small tools for data work (EDA, plots, sklearn-compatible encoders) and for LLM agents and bots: CPU memory search, tool loops, BPMN process walking, scenario suites with a checklist judge and Thompson-sampling scheduler; heavy dependencies only per extra
5
5
  Author: Caerno
6
6
  License-Expression: Apache-2.0
7
7
  Project-URL: Homepage, https://github.com/Caerno/bitskit
8
- Keywords: eda,pandas,sklearn,kaggle
8
+ Keywords: eda,pandas,sklearn,kaggle,llm,agents,memory,retrieval,bpmn,chatbot,testing,thompson-sampling
9
9
  Requires-Python: >=3.9
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE
12
+ License-File: NOTICE
12
13
  Requires-Dist: numpy>=1.21
13
- Requires-Dist: pandas>=1.3
14
- Requires-Dist: scikit-learn>=1.0
15
- Requires-Dist: matplotlib>=3.4
16
- Requires-Dist: seaborn>=0.11
17
- Requires-Dist: jinja2>=3
14
+ Provides-Extra: ml
15
+ Requires-Dist: pandas>=1.3; extra == "ml"
16
+ Requires-Dist: scikit-learn>=1.0; extra == "ml"
17
+ Provides-Extra: eda
18
+ Requires-Dist: pandas>=1.3; extra == "eda"
19
+ Requires-Dist: matplotlib>=3.4; extra == "eda"
20
+ Requires-Dist: seaborn>=0.11; extra == "eda"
21
+ Requires-Dist: jinja2>=3; extra == "eda"
22
+ Provides-Extra: search
23
+ Requires-Dist: onnxruntime>=1.16; extra == "search"
24
+ Requires-Dist: tokenizers>=0.15; extra == "search"
25
+ Provides-Extra: all
26
+ Requires-Dist: bitskitten[eda,ml,search]; extra == "all"
18
27
  Provides-Extra: test
19
28
  Requires-Dist: pytest>=7; extra == "test"
20
29
  Dynamic: license-file
21
30
 
22
31
  # bitskitten
23
32
 
24
- A small toolbox of things I kept re-typing in every EDA notebook:
25
- quick dataset reports, a few plots, and sklearn-compatible encoders that can be
26
- dropped straight into a `Pipeline` / `GridSearchCV`.
33
+ A small toolbox of things I kept re-typing: quick dataset reports, a few plots and
34
+ sklearn-compatible encoders for EDA notebooks; and for LLM agents and bots — memory search on CPU,
35
+ memory as tools, an agent walking a BPMN process, and a regression harness (scenario suites,
36
+ checklist judge, Thompson-sampling scheduler).
27
37
 
28
38
  Nothing here is a framework. Each helper is one function or one class you can read in a minute.
29
39
 
30
40
  ## Install
31
41
 
32
42
  ```bash
33
- pip install bitskitten
43
+ pip install bitskitten # numpy only: bot regression harness, test scheduler, LLM tools, BPMN agent, metric
44
+ pip install 'bitskitten[ml]' # + pandas, scikit-learn: encoders, NanFixer, harmonic_scorer
45
+ pip install 'bitskitten[eda]' # + pandas, matplotlib, seaborn: reports and plots
46
+ pip install 'bitskitten[search]' # + onnxruntime, tokenizers: memory search for agents
47
+ pip install 'bitskitten[all]' # everything
34
48
  ```
35
49
 
50
+ Each part loads its dependencies only when you use it: `import bitskitten` costs numpy,
51
+ not pandas and scikit-learn. A name whose extra is missing fails with the line to install.
52
+
36
53
  The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
37
54
  On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
38
55
  For a kernel with no internet, add
@@ -43,7 +60,7 @@ as a dataset and install it from disk:
43
60
  pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
44
61
  ```
45
62
 
46
- Requires Python ≥ 3.9, numpy, pandas, scikit-learn, matplotlib, seaborn.
63
+ Requires Python ≥ 3.9 and numpy; the rest comes with the extras above.
47
64
 
48
65
  ## Quick start
49
66
 
@@ -159,8 +176,9 @@ from bitskitten.bandit import ThompsonScheduler
159
176
 
160
177
  sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
161
178
  threshold=0.9, seed=0)
162
- report = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
163
- print(report) # runs, passes, mean, 95 % interval, pass^3, verdict per scenario
179
+ rows = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
180
+ # one dict per scenario, worst first: runs, passes, mean, 95 % interval, pass^3, verdict
181
+ print(sched.report()) # the same as a DataFrame, needs pandas
164
182
  ```
165
183
 
166
184
  For suites where one run of a scenario is a coin flip (LLM bots, anything
@@ -183,7 +201,8 @@ suite = Suite(scenarios, # Scenario.from_dict(
183
201
  gates={"collecting_states": {"collecting_date"}},
184
202
  judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
185
203
  result = suite.run(budget=80, threshold=0.9, max_runs=40)
186
- print(result.report) # per scenario: runs, mean, 95 % interval, pass^3, verdict
204
+ print(result.rows) # per scenario: runs, mean, 95 % interval, pass^3, verdict
205
+ # result.report: the same as a DataFrame, needs pandas
187
206
  print(format_report(result.failures)) # failed runs grouped by what failed
188
207
  ```
189
208
 
@@ -199,7 +218,8 @@ decided scenarios retire, the loop stops when nothing is left to learn.
199
218
  quietly answering them. `MarkovUsers` varies wording from real utterances at
200
219
  zero model cost. `CallableUser` wraps any model.
201
220
  - **Judge.** Repeated judging merges binary items by majority, not by mean.
202
- `item_agreement(judged, human)` gives per-item kappa against your own labels
221
+ `item_agreement_rows(judged, human)` gives per-item kappa against your own labels
222
+ (`item_agreement` — the same as a DataFrame)
203
223
  — check it before trusting an item; `pick_threshold` picks the score cut.
204
224
  - **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
205
225
  runs in a row; that is the threshold's price, not the scheduler's. A scenario
@@ -207,6 +227,95 @@ decided scenarios retire, the loop stops when nothing is left to learn.
207
227
  - `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
208
228
  absolute dates that will expire.
209
229
 
230
+ ## Memory search for agents
231
+
232
+ ```bash
233
+ pip install 'bitskitten[search]' # onnxruntime, tokenizers; no torch, no GPU
234
+ ```
235
+
236
+ ```python
237
+ from bitskitten.search import Index, fetch_model
238
+ ix = Index([{"id": "1", "text": "Deploys run on Tuesday and Friday"}], model_dir=fetch_model(), log="usage.jsonl")
239
+ page1 = ix.search("when do we deploy") # {"results", "abstain", "has_more", "page", "query_id", ...}
240
+ page2 = ix.search("when do we deploy", page=2, query_id=page1["query_id"])
241
+ ix.add([{"id": "2", "text": "...", "meta": {...}}]); ix.get("2"); ix.remove(["2"])
242
+ ```
243
+
244
+ - **Hybrid ranking**: ONNX sentence encoder + BM25 (word forms and 5-character prefixes), each min-max normalised over its
245
+ top-100, 0.4 / 0.6. `abstain` is set when the best match is too weak: the agent can say "not in memory".
246
+ - **Chunking** of long records by block form (prose, code fences, markdown tables as "Column: value" rows); a record is
247
+ ranked whole, a long one is shown by its best chunk with the record title.
248
+ - **Paging**: one ranking of 10 per query; page 1 = places 1–5, page 2 = 6–10 without re-searching.
249
+ - **Usage log**: one JSON line per call (query, ids shown, tokens returned, ms), `"v": 1`.
250
+ - **Model**: `fetch_model()` downloads [rubert-mini-retriever](https://huggingface.co/caerno/rubert-mini-retriever-onnx-int8)
251
+ (by sergeyzh, MIT; ONNX int8, 25 MB, Russian and English) once, at a pinned revision, each file checked by sha256;
252
+ `$BITSKITTEN_CACHE` or `~/.cache/bitskitten`. Any directory with `tokenizer.json` and an ONNX file with inputs
253
+ `ids`, `mask` works as `model_dir`.
254
+
255
+ ## Memory as LLM tools
256
+
257
+ ```python
258
+ from bitskitten.llm import MemoryTools, run_anthropic
259
+ import anthropic
260
+ client = anthropic.Anthropic()
261
+ send = lambda m, t: client.messages.create(model="claude-haiku-5-5", max_tokens=4000, messages=m, tools=t).to_dict()
262
+ answer, trace = run_anthropic(send, [{"role": "user", "content": "how do we deploy?"}], MemoryTools(ix, writable=True))
263
+ # OpenAI-compatible: send = lambda m, t: openai_client.chat.completions.create(model=..., messages=m, tools=t).model_dump()
264
+ # answer, trace = run_openai(send, messages, MemoryTools(ix))
265
+ ```
266
+
267
+ `memory_search` / `memory_get` / `memory_remember` are defined once and rendered for the Anthropic Messages API and for
268
+ OpenAI-compatible chat completions. `call(name, args)` never raises into the loop. The loops take your own
269
+ `send(messages, tools)`: no SDK, keys or network code in this package. One `MemoryTools` per conversation: a record
270
+ already shown there is not sent again. `MemoryTools.stats` counts calls, records shown and the provider's tokens; every
271
+ turn adds a `turn` line to the usage log:
272
+
273
+ ```bash
274
+ python -m bitskitten.llm.report usage.jsonl --by session --price 0.10 0.50
275
+ ```
276
+
277
+ Results are framed as data, not instructions. The frame is formatting of untrusted text, not a defence against prompt
278
+ injection.
279
+
280
+ ## Agent on a BPMN process
281
+
282
+ ```python
283
+ from bitskitten.process import load, Run, run_process, examples_dir
284
+ from bitskitten.llm import MemoryTools, run_anthropic
285
+ run = Run(load(f"{examples_dir()}/answer-from-memory.bpmn"), data={"question": "..."}, log="usage.jsonl")
286
+ human = lambda step, run: ("done", input(step["name"] + ": ")) if step["lane"] == "User" else None
287
+ tools = lambda step: [MemoryTools(ix)] if step["tools"] and "memory_search" in step["tools"] else []
288
+ run_process(send, run, run_anthropic, tools=tools, delegate=human) # -> "completed"
289
+ run.status, run.history, run.ended # "stuck" / "max_steps" leave it running: call run_process again
290
+ ```
291
+
292
+ The code walks a BPMN 2.0 process (Camunda Modeler, bpmn.io); the model only picks each step's outcome.
293
+ - **Outcomes** of a step = branches of the exclusive gateway(s) after it (flow name, or the value of a
294
+ `=var = "value"` condition) plus its boundary events. A chosen branch sets its variable, so later gateways on it
295
+ route by themselves.
296
+ - **Brief**: `run.brief(step)` = general and step instructions, outcomes with where each leads, what was done, the
297
+ route in short. Instructions: `documentation`, or extension property `instruction` = `file.md` / `file.md#Heading`.
298
+ Extension property `tools` says which tools a step gets.
299
+ - **State** is plain JSON (`run.state()`, `Run.from_state`, `"v": 1`) for LangGraph or any other host.
300
+ `delegate(step, run)` hands a step to a human or a service.
301
+ - **Scopes follow BPMN**: an error end leaves by an error boundary or error event subprocess, else goes up the call
302
+ stack (uncaught: `failed`); terminate ends its own scope; a parallel join waits for every incoming flow (stuck:
303
+ `deadlock`); call activities resolve across loaded files.
304
+ - **Supported profile**: all task types; exclusive and parallel gateways; start, end (incl. error and terminate),
305
+ intermediate, boundary and link events; embedded and event subprocesses, call activities; conditions only of the form
306
+ `=var = "value"`. Inclusive, complex and event-based gateways, multi-instance, compensation and transactions fail at
307
+ load. Timers do not tick: they are outcomes the agent or host reports. Checked on 1,131 Camunda 8 schemas.
308
+
309
+ ## Code graph
310
+
311
+ ```bash
312
+ python -m bitskitten.codegraph <src_root> <package> graph.json
313
+ ```
314
+
315
+ Modules, classes, functions, methods and the imports / defines / inherits / calls edges of a Python package via `ast`,
316
+ with calls resolved through import tables, re-exports, `self` / bases and annotations. `build(root, pkg)` returns
317
+ `{"defs", "edges", "report"}`.
318
+
210
319
  ## Plots
211
320
 
212
321
  ```python
@@ -263,8 +372,8 @@ and satisfies the condition.
263
372
  ## Development
264
373
 
265
374
  ```bash
266
- pip install -e .[test]
267
- pytest
375
+ pip install '.[all,test]'
376
+ pytest # BITSKITTEN_MODEL=<model dir> for the search tests, e.g. $(python -c "from bitskitten.search import fetch_model; print(fetch_model())")
268
377
  ```
269
378
 
270
379
  The repo root *is* the package (flat layout), so the clone has to be in a folder named
@@ -275,5 +384,6 @@ gets in:
275
384
 
276
385
  ```bash
277
386
  git archive --format=zip -o download/bitskitten.zip HEAD \
278
- __init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
387
+ __init__.py _deps.py _sink.py bandit.py classes.py codegraph.py input.py metrics.py output.py text.py \
388
+ qa search llm process/__init__.py process/bpmn.py process/examples/*.bpmn process/examples/*.md
279
389
  ```
@@ -1,38 +1,25 @@
1
- Metadata-Version: 2.4
2
- Name: bitskitten
3
- Version: 0.4.0
4
- Summary: EDA reports, plots and sklearn-compatible encoders
5
- Author: Caerno
6
- License-Expression: Apache-2.0
7
- Project-URL: Homepage, https://github.com/Caerno/bitskit
8
- Keywords: eda,pandas,sklearn,kaggle
9
- Requires-Python: >=3.9
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: numpy>=1.21
13
- Requires-Dist: pandas>=1.3
14
- Requires-Dist: scikit-learn>=1.0
15
- Requires-Dist: matplotlib>=3.4
16
- Requires-Dist: seaborn>=0.11
17
- Requires-Dist: jinja2>=3
18
- Provides-Extra: test
19
- Requires-Dist: pytest>=7; extra == "test"
20
- Dynamic: license-file
21
-
22
1
  # bitskitten
23
2
 
24
- A small toolbox of things I kept re-typing in every EDA notebook:
25
- quick dataset reports, a few plots, and sklearn-compatible encoders that can be
26
- dropped straight into a `Pipeline` / `GridSearchCV`.
3
+ A small toolbox of things I kept re-typing: quick dataset reports, a few plots and
4
+ sklearn-compatible encoders for EDA notebooks; and for LLM agents and bots — memory search on CPU,
5
+ memory as tools, an agent walking a BPMN process, and a regression harness (scenario suites,
6
+ checklist judge, Thompson-sampling scheduler).
27
7
 
28
8
  Nothing here is a framework. Each helper is one function or one class you can read in a minute.
29
9
 
30
10
  ## Install
31
11
 
32
12
  ```bash
33
- pip install bitskitten
13
+ pip install bitskitten # numpy only: bot regression harness, test scheduler, LLM tools, BPMN agent, metric
14
+ pip install 'bitskitten[ml]' # + pandas, scikit-learn: encoders, NanFixer, harmonic_scorer
15
+ pip install 'bitskitten[eda]' # + pandas, matplotlib, seaborn: reports and plots
16
+ pip install 'bitskitten[search]' # + onnxruntime, tokenizers: memory search for agents
17
+ pip install 'bitskitten[all]' # everything
34
18
  ```
35
19
 
20
+ Each part loads its dependencies only when you use it: `import bitskitten` costs numpy,
21
+ not pandas and scikit-learn. A name whose extra is missing fails with the line to install.
22
+
36
23
  The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
37
24
  On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
38
25
  For a kernel with no internet, add
@@ -43,7 +30,7 @@ as a dataset and install it from disk:
43
30
  pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
44
31
  ```
45
32
 
46
- Requires Python ≥ 3.9, numpy, pandas, scikit-learn, matplotlib, seaborn.
33
+ Requires Python ≥ 3.9 and numpy; the rest comes with the extras above.
47
34
 
48
35
  ## Quick start
49
36
 
@@ -159,8 +146,9 @@ from bitskitten.bandit import ThompsonScheduler
159
146
 
160
147
  sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
161
148
  threshold=0.9, seed=0)
162
- report = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
163
- print(report) # runs, passes, mean, 95 % interval, pass^3, verdict per scenario
149
+ rows = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
150
+ # one dict per scenario, worst first: runs, passes, mean, 95 % interval, pass^3, verdict
151
+ print(sched.report()) # the same as a DataFrame, needs pandas
164
152
  ```
165
153
 
166
154
  For suites where one run of a scenario is a coin flip (LLM bots, anything
@@ -183,7 +171,8 @@ suite = Suite(scenarios, # Scenario.from_dict(
183
171
  gates={"collecting_states": {"collecting_date"}},
184
172
  judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
185
173
  result = suite.run(budget=80, threshold=0.9, max_runs=40)
186
- print(result.report) # per scenario: runs, mean, 95 % interval, pass^3, verdict
174
+ print(result.rows) # per scenario: runs, mean, 95 % interval, pass^3, verdict
175
+ # result.report: the same as a DataFrame, needs pandas
187
176
  print(format_report(result.failures)) # failed runs grouped by what failed
188
177
  ```
189
178
 
@@ -199,7 +188,8 @@ decided scenarios retire, the loop stops when nothing is left to learn.
199
188
  quietly answering them. `MarkovUsers` varies wording from real utterances at
200
189
  zero model cost. `CallableUser` wraps any model.
201
190
  - **Judge.** Repeated judging merges binary items by majority, not by mean.
202
- `item_agreement(judged, human)` gives per-item kappa against your own labels
191
+ `item_agreement_rows(judged, human)` gives per-item kappa against your own labels
192
+ (`item_agreement` — the same as a DataFrame)
203
193
  — check it before trusting an item; `pick_threshold` picks the score cut.
204
194
  - **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
205
195
  runs in a row; that is the threshold's price, not the scheduler's. A scenario
@@ -207,6 +197,95 @@ decided scenarios retire, the loop stops when nothing is left to learn.
207
197
  - `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
208
198
  absolute dates that will expire.
209
199
 
200
+ ## Memory search for agents
201
+
202
+ ```bash
203
+ pip install 'bitskitten[search]' # onnxruntime, tokenizers; no torch, no GPU
204
+ ```
205
+
206
+ ```python
207
+ from bitskitten.search import Index, fetch_model
208
+ ix = Index([{"id": "1", "text": "Deploys run on Tuesday and Friday"}], model_dir=fetch_model(), log="usage.jsonl")
209
+ page1 = ix.search("when do we deploy") # {"results", "abstain", "has_more", "page", "query_id", ...}
210
+ page2 = ix.search("when do we deploy", page=2, query_id=page1["query_id"])
211
+ ix.add([{"id": "2", "text": "...", "meta": {...}}]); ix.get("2"); ix.remove(["2"])
212
+ ```
213
+
214
+ - **Hybrid ranking**: ONNX sentence encoder + BM25 (word forms and 5-character prefixes), each min-max normalised over its
215
+ top-100, 0.4 / 0.6. `abstain` is set when the best match is too weak: the agent can say "not in memory".
216
+ - **Chunking** of long records by block form (prose, code fences, markdown tables as "Column: value" rows); a record is
217
+ ranked whole, a long one is shown by its best chunk with the record title.
218
+ - **Paging**: one ranking of 10 per query; page 1 = places 1–5, page 2 = 6–10 without re-searching.
219
+ - **Usage log**: one JSON line per call (query, ids shown, tokens returned, ms), `"v": 1`.
220
+ - **Model**: `fetch_model()` downloads [rubert-mini-retriever](https://huggingface.co/caerno/rubert-mini-retriever-onnx-int8)
221
+ (by sergeyzh, MIT; ONNX int8, 25 MB, Russian and English) once, at a pinned revision, each file checked by sha256;
222
+ `$BITSKITTEN_CACHE` or `~/.cache/bitskitten`. Any directory with `tokenizer.json` and an ONNX file with inputs
223
+ `ids`, `mask` works as `model_dir`.
224
+
225
+ ## Memory as LLM tools
226
+
227
+ ```python
228
+ from bitskitten.llm import MemoryTools, run_anthropic
229
+ import anthropic
230
+ client = anthropic.Anthropic()
231
+ send = lambda m, t: client.messages.create(model="claude-haiku-5-5", max_tokens=4000, messages=m, tools=t).to_dict()
232
+ answer, trace = run_anthropic(send, [{"role": "user", "content": "how do we deploy?"}], MemoryTools(ix, writable=True))
233
+ # OpenAI-compatible: send = lambda m, t: openai_client.chat.completions.create(model=..., messages=m, tools=t).model_dump()
234
+ # answer, trace = run_openai(send, messages, MemoryTools(ix))
235
+ ```
236
+
237
+ `memory_search` / `memory_get` / `memory_remember` are defined once and rendered for the Anthropic Messages API and for
238
+ OpenAI-compatible chat completions. `call(name, args)` never raises into the loop. The loops take your own
239
+ `send(messages, tools)`: no SDK, keys or network code in this package. One `MemoryTools` per conversation: a record
240
+ already shown there is not sent again. `MemoryTools.stats` counts calls, records shown and the provider's tokens; every
241
+ turn adds a `turn` line to the usage log:
242
+
243
+ ```bash
244
+ python -m bitskitten.llm.report usage.jsonl --by session --price 0.10 0.50
245
+ ```
246
+
247
+ Results are framed as data, not instructions. The frame is formatting of untrusted text, not a defence against prompt
248
+ injection.
249
+
250
+ ## Agent on a BPMN process
251
+
252
+ ```python
253
+ from bitskitten.process import load, Run, run_process, examples_dir
254
+ from bitskitten.llm import MemoryTools, run_anthropic
255
+ run = Run(load(f"{examples_dir()}/answer-from-memory.bpmn"), data={"question": "..."}, log="usage.jsonl")
256
+ human = lambda step, run: ("done", input(step["name"] + ": ")) if step["lane"] == "User" else None
257
+ tools = lambda step: [MemoryTools(ix)] if step["tools"] and "memory_search" in step["tools"] else []
258
+ run_process(send, run, run_anthropic, tools=tools, delegate=human) # -> "completed"
259
+ run.status, run.history, run.ended # "stuck" / "max_steps" leave it running: call run_process again
260
+ ```
261
+
262
+ The code walks a BPMN 2.0 process (Camunda Modeler, bpmn.io); the model only picks each step's outcome.
263
+ - **Outcomes** of a step = branches of the exclusive gateway(s) after it (flow name, or the value of a
264
+ `=var = "value"` condition) plus its boundary events. A chosen branch sets its variable, so later gateways on it
265
+ route by themselves.
266
+ - **Brief**: `run.brief(step)` = general and step instructions, outcomes with where each leads, what was done, the
267
+ route in short. Instructions: `documentation`, or extension property `instruction` = `file.md` / `file.md#Heading`.
268
+ Extension property `tools` says which tools a step gets.
269
+ - **State** is plain JSON (`run.state()`, `Run.from_state`, `"v": 1`) for LangGraph or any other host.
270
+ `delegate(step, run)` hands a step to a human or a service.
271
+ - **Scopes follow BPMN**: an error end leaves by an error boundary or error event subprocess, else goes up the call
272
+ stack (uncaught: `failed`); terminate ends its own scope; a parallel join waits for every incoming flow (stuck:
273
+ `deadlock`); call activities resolve across loaded files.
274
+ - **Supported profile**: all task types; exclusive and parallel gateways; start, end (incl. error and terminate),
275
+ intermediate, boundary and link events; embedded and event subprocesses, call activities; conditions only of the form
276
+ `=var = "value"`. Inclusive, complex and event-based gateways, multi-instance, compensation and transactions fail at
277
+ load. Timers do not tick: they are outcomes the agent or host reports. Checked on 1,131 Camunda 8 schemas.
278
+
279
+ ## Code graph
280
+
281
+ ```bash
282
+ python -m bitskitten.codegraph <src_root> <package> graph.json
283
+ ```
284
+
285
+ Modules, classes, functions, methods and the imports / defines / inherits / calls edges of a Python package via `ast`,
286
+ with calls resolved through import tables, re-exports, `self` / bases and annotations. `build(root, pkg)` returns
287
+ `{"defs", "edges", "report"}`.
288
+
210
289
  ## Plots
211
290
 
212
291
  ```python
@@ -263,8 +342,8 @@ and satisfies the condition.
263
342
  ## Development
264
343
 
265
344
  ```bash
266
- pip install -e .[test]
267
- pytest
345
+ pip install '.[all,test]'
346
+ pytest # BITSKITTEN_MODEL=<model dir> for the search tests, e.g. $(python -c "from bitskitten.search import fetch_model; print(fetch_model())")
268
347
  ```
269
348
 
270
349
  The repo root *is* the package (flat layout), so the clone has to be in a folder named
@@ -275,5 +354,6 @@ gets in:
275
354
 
276
355
  ```bash
277
356
  git archive --format=zip -o download/bitskitten.zip HEAD \
278
- __init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
357
+ __init__.py _deps.py _sink.py bandit.py classes.py codegraph.py input.py metrics.py output.py text.py \
358
+ qa search llm process/__init__.py process/bpmn.py process/examples/*.bpmn process/examples/*.md
279
359
  ```
@@ -0,0 +1,60 @@
1
+ '''bitskitten - small tools for data work and for LLM bots and agents.
2
+
3
+ from bitskitten import imperfection, NanFixer, Digitalize # pip install 'bitskitten[eda,ml]'
4
+ from bitskitten import ThompsonScheduler # numpy only
5
+ from bitskitten.qa import Scenario, Suite # numpy only
6
+ from bitskitten.llm import MemoryTools, run_anthropic # numpy only: memory tools for LLM agents
7
+ from bitskitten.process import load, Run, run_process # numpy only: an agent walking a BPMN process
8
+ from bitskitten.search import Index, fetch_model # pip install 'bitskitten[search]'
9
+
10
+ One distribution, independent parts: a name is imported only when you use it, so `import bitskitten` and the
11
+ light parts (qa, bandit, metrics, input, llm, process, codegraph) do not load pandas, scikit-learn or matplotlib. A part whose extra is
12
+ not installed says which one to install. Submodules stay importable on their own (`from bitskitten import output`).
13
+ '''
14
+ import importlib
15
+
16
+ from ._deps import hint as _hint
17
+
18
+ __version__ = "0.6.0"
19
+
20
+ _EXPORTS = {
21
+ "ThompsonScheduler": "bandit", "pass_power": "bandit",
22
+ "Digitalize": "classes", "Encoder": "classes", "FeatureTrans": "classes", "NanFixer": "classes",
23
+ "SlowPolyLinearReg": "classes",
24
+ "number": "input",
25
+ "harmonic_from_confusion": "metrics", "harmonic_score": "metrics", "harmonic_scorer": "metrics",
26
+ "text_imperfection": "text",
27
+ "imperfection": "output", "informer": "output", "informer_print": "output", "multicolumn": "output",
28
+ "plot_conf_map": "output", "plot_some_scatters": "output", "img_squeeze": "output", "img_framaker": "output",
29
+ "Index": "search", "fetch_model": "search",
30
+ "MemoryTools": "llm", "run_anthropic": "llm", "run_openai": "llm",
31
+ "load_process": "process", "Run": "process", "run_process": "process",
32
+ }
33
+ _SUBMODULES = {"bandit", "classes", "input", "metrics", "text", "output", "qa", "search", "llm", "process", "codegraph"}
34
+
35
+ __all__ = list(_EXPORTS)
36
+
37
+
38
+ _MODULE_EXTRA = {"classes": "ml", "metrics": "ml", "output": "eda", "text": "eda", "search": "search"}
39
+
40
+
41
+ _ALIAS = {"load_process": "load"}
42
+
43
+
44
+ def __getattr__(name):
45
+ mod = _EXPORTS.get(name) or (name if name in _SUBMODULES else None)
46
+ if mod is None:
47
+ raise AttributeError(f"module 'bitskitten' has no attribute {name!r}")
48
+ try:
49
+ m = importlib.import_module(f".{mod}", __name__)
50
+ except ModuleNotFoundError as e:
51
+ if e.name and e.name.split(".")[0] != __name__:
52
+ raise ImportError(_hint(e.name, f"bitskitten.{name}", _MODULE_EXTRA.get(mod))) from e
53
+ raise
54
+ value = m if name == mod else getattr(m, _ALIAS.get(name, name))
55
+ globals()[name] = value
56
+ return value
57
+
58
+
59
+ def __dir__():
60
+ return sorted(set(globals()) | set(_EXPORTS) | _SUBMODULES)
@@ -0,0 +1,20 @@
1
+ """Optional dependencies: which extra brings which package, and a clear error when it is missing."""
2
+ import importlib
3
+
4
+ EXTRA = {"pandas": "ml", "sklearn": "ml", "matplotlib": "eda", "seaborn": "eda", "jinja2": "eda",
5
+ "onnxruntime": "search", "tokenizers": "search", "yaml": "nollm", "Stemmer": "nollm"}
6
+ PIP = {"sklearn": "scikit-learn", "yaml": "PyYAML", "Stemmer": "PyStemmer"}
7
+
8
+
9
+ def hint(missing, what="this", extra=None):
10
+ top = (missing or "").split(".")[0]
11
+ return (f"{what} needs {PIP.get(top, top)}: pip install 'bitskitten[{extra or EXTRA.get(top, 'all')}]' "
12
+ f"(or pip install {PIP.get(top, top)})")
13
+
14
+
15
+ def need(module, what="this"):
16
+ """import an optional module or raise ImportError naming the extra to install"""
17
+ try:
18
+ return importlib.import_module(module)
19
+ except ModuleNotFoundError as e:
20
+ raise ImportError(hint(e.name or module, what)) from e
@@ -0,0 +1,14 @@
1
+ """One JSON line to a usage log: a path (appended) or a callable taking the dict. Never raises: a failing log is a warning."""
2
+ import json, time, warnings
3
+
4
+ LOG_VERSION = 1 # format of a log line: search / turn / step
5
+
6
+
7
+ def emit(sink, rec):
8
+ if not sink: return
9
+ rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "v": LOG_VERSION, **rec}
10
+ try:
11
+ if callable(sink): sink(rec); return
12
+ with open(sink, "a", encoding="utf-8") as fh: fh.write(json.dumps(rec, ensure_ascii=False, default=str) + "\n")
13
+ except Exception as e:
14
+ warnings.warn(f"bitskitten usage log not written: {e}")
@@ -32,7 +32,6 @@ from dataclasses import dataclass, field
32
32
  from typing import Dict, Iterable, List, Optional, Tuple
33
33
 
34
34
  import numpy as np
35
- import pandas as pd
36
35
 
37
36
  __all__ = ["Arm", "ThompsonScheduler", "pass_power", "beta_interval"]
38
37
 
@@ -231,9 +230,10 @@ class ThompsonScheduler:
231
230
 
232
231
  # -- reporting ----------------------------------------------------------
233
232
 
234
- def report(self, *, k: int = 3) -> pd.DataFrame:
235
- """One row per scenario: runs, passes, posterior mean, interval,
236
- pass^k and the verdict against the threshold. Sorted worst first."""
233
+ def rows(self, *, k: int = 3) -> List[dict]:
234
+ """One dict per scenario: runs, passes, posterior mean, interval,
235
+ pass^k and the verdict against the threshold. Sorted worst first.
236
+ Plain Python: no pandas needed."""
237
237
  rows = []
238
238
  for name, arm in self.arms.items():
239
239
  lo, hi = self.interval(name)
@@ -247,15 +247,19 @@ class ThompsonScheduler:
247
247
  f"pass^{k}": pass_power(arm.alpha, arm.beta, k),
248
248
  "verdict": self.status(name),
249
249
  })
250
- return (pd.DataFrame(rows)
251
- .sort_values(["mean", "runs"])
252
- .reset_index(drop=True))
250
+ return sorted(rows, key=lambda r: (r["mean"], r["runs"]))
253
251
 
254
- def run(self, run_once, *, budget: int, k: int = 3) -> pd.DataFrame:
252
+ def report(self, *, k: int = 3):
253
+ """`rows()` as a pandas DataFrame (needs pandas)."""
254
+ from ._deps import need
255
+ return need("pandas", "ThompsonScheduler.report").DataFrame(self.rows(k=k))
256
+
257
+ def run(self, run_once, *, budget: int, k: int = 3):
255
258
  """Drive the loop: pick -> run_once(name) -> update, until `done()`.
256
259
 
257
260
  `run_once(name)` must return a truthy value for a pass. Returns the
258
- final report. Raising inside `run_once` aborts the loop; the state
261
+ final `rows(k)`, worst scenario first; `report(k)` gives the same as a
262
+ DataFrame. Raising inside `run_once` aborts the loop; the state
259
263
  collected so far stays on the scheduler.
260
264
  """
261
265
  if budget <= 0:
@@ -263,4 +267,4 @@ class ThompsonScheduler:
263
267
  while not self.done(budget=budget):
264
268
  name = self.pick()
265
269
  self.update(name, bool(run_once(name)))
266
- return self.report(k=k)
270
+ return self.rows(k=k)