Winnex ← back to documentation

Examples

Seventeen working examples covering every package in the stack. Four are sector-specific tracer scenarios — medicine, government, law and finance — with the data structures those systems actually use. Every example was executed locally before publication, and every one starts with the pip install line it needs.

Start with 00 — and no, you do not need to install anything

Every script installs its own dependencies on the first run. Paste it into a Colab cell and execute; the pip install happens inside the cell, before the imports.

This matters because a !pip install line written inside a comment never executes — which is the most common reason a Colab example fails with ModuleNotFoundError. All seventeen scripts here were verified in a clean virtual environment with none of the packages installed.

Which example to read

#ExamplePackageDomain
00Hello worldmadhava—
01E-discovery with provable completenessmadhavalegal
02Clinical record for a denied claimmadhavahealth
03Credit decision reconstructionmadhavafinance
04Reproduce the benchmarkmadhava—
05Quality gate on a broken corpusmadhava + normalize—
06Auditable agent memorymadhavaagents
07SQL to search (minimal)madhava—
08RAG agent (minimal)madhava—
09Tracer-MED — hospital audit trailmadhava + tracerhealth
10Tracer-GOV — procurement auditmadhava + tracergovernment
11Tracer-JUS — contract due diligencemadhava + tracerlegal
12Tracer-GAP — financial reconciliationmadhava + tracerfinance
13X-Factor — manifold projectionxfactor—
14Nano — tokenizer and weight blendingnano—
15Normalize — providers, L2, driftnormalize—
16Build speed across corpus sizesmadhava—

00 — Hello world

Fifteen lines, no data, no API key

The smallest working example. A corpus of five vectors, one query, and the proof that the four non-returned vectors could not belong.

import numpy as np
import winnex_madhava as mad

corpus = np.array([...], dtype=np.float32)      # 5 vectors, dim 16
engine = mad.build_engine(corpus, dim=16, k=2,
                          k1_fraction=1.0, postfilter=True,
                          audit_exhaustive=True)
result = mad.retrieve(engine, corpus[0], k=2)

Output from the actual run:

indices: [0, 4]
bound violations: 0
latency: 0.016 ms
proof: every excluded document carries a Cauchy-Schwarz proof...  
getting started ~40 lines
Download .py

01 — Law firm: e-discovery with provable completeness

The problem: you must certify the production is complete

A litigation support database holds custodial documents. Counsel must produce the responsive set and certify nothing was missed — under penalty of sanctions for spoliation. Every platform returns documents; none can show that the withheld set was correctly excluded.

The example loads seven custodial documents into SQLite (the shape Relativity, Everlaw and Concordance all use), withholds the privileged one before indexing, and produces a certificate listing both the production set and the withheld set with proof.

CREATE TABLE documents (
    doc_id     TEXT PRIMARY KEY,
    custodian  TEXT,
    doc_date   TEXT,
    file_type  TEXT,
    subject    TEXT,
    body       TEXT,
    privilege  INTEGER DEFAULT 0
)

Output from the actual run:

documents in database : 7
privileged withheld   : 1
indexed for search    : 6

responsive documents:
  1. [0.742] DOC-0001  Re: Contrato de Fornecimento - Cláusula 7
  2. [0.577] DOC-0004  Conciliação de multas Q1 2024
  3. [0.477] DOC-0002  Re: Contrato de Fornecimento - prazo

─── production certificate ───
  production set         : ['DOC-0001', 'DOC-0004', 'DOC-0002']
  withheld as irrelevant : ['DOC-0003', 'DOC-0005', 'DOC-0007']
  bound violations       : 0  (must be 0)

What the certificate asserts. For each withheld document, the engine computed a Cauchy–Schwarz upper bound below the score of the third responsive document — so it could not belong in the responsive set, and an opposing expert can re-run the arithmetic. An approximate index gives the same three documents and no way to make that statement.

legal · e-discovery realistic ~130 lines
Download .py

02 — Hospital: finding the record that justifies a bill

The problem: a denied claim needs the note that supports it

An insurer denies a claim. The revenue cycle team has 30 days to produce the clinical documentation proving the procedure was justified, or the revenue is written off. The documentation exists in the EHR — the question is whether the search finds it, and whether anyone can tell the difference between "no record found" and "no record exists".

The example loads clinical notes in the table layout Cerner, Epic, MV and Tasy all use, indexes the notes for one patient under dispute, and produces the statement the hospital sends to the payer.

CREATE TABLE notas_clinicas (
    id                INTEGER PRIMARY KEY,
    paciente_id       TEXT,
    data_atendimento  TEXT,
    tipo              TEXT,      -- evolução, descrição cirúrgica, sumário
    profissional      TEXT,
    texto             TEXT
)

Output from the actual run:

patient under dispute : PAC-4471
clinical notes on file: 4

insurer's question: justificativa clínica para videolaparoscopia

documentation produced:
  1. [0.558] descrição cirúrgica de 2026-03-02
  2. [0.467] evolução de 2026-03-02
  3. [0.466] sumário de alta de 2026-03-05

notes supporting the procedure : 3
notes excluded with proof      : 1
bound violations               : 0

Why the revenue cycle team cares. A denied claim that is not appealed is revenue the hospital already earned and will never collect. The work of appealing is searching the record for justification — and every search returning "nothing found" is a claim written off. What matters is knowing whether nothing was found or nothing was proven absent.

health · revenue cycle realistic ~140 lines
Download .py

03 — Bank: reconstructing a credit decision for the regulator

The problem: explain the denial, and prove the reading was complete

A credit application is denied. The applicant invokes their right to review under LGPD art. 20 / GDPR art. 22, and the regulator asks the bank to reconstruct the grounds. The bank must show which policies applied — and that no policy was missed.

This is the case where approximate search becomes a liability: if the retrieval misses the exception clause that would have approved the application, the bank denied credit on incomplete grounds and cannot demonstrate otherwise.

CREATE TABLE politicas_credito (
    codigo        TEXT PRIMARY KEY,
    vigencia      TEXT,
    categoria     TEXT,     -- limite, garantia, exceção, restrição
    titulo        TEXT,
    texto         TEXT,
    aprovado_por  TEXT
)

Output from the actual run — a denial at 33% income commitment, 7-year relationship, no active restriction:

application  : PROP-2026-03-4471
commitment   : 33.0%
relationship : 7 years
decision     : NEGADO

policy that governs this decision:
  1. [0.818] POL-0187 (garantia)
  2. [0.813] PRE-0088 (precedente)
  3. [0.801] POL-0203 (exceção)
  4. [0.713] POL-0142 (limite)

policies excluded with proof : ['POL-0115', 'POL-0264']
bound violations             : 0

What the reconstruction reveals. POL-0203 allows up to 35% commitment for clients with more than five years of relationship and no active restriction. The applicant has seven years, no restriction, and 33% commitment. The retrieval surfaces it — and proves no other policy in the repository is responsive. Whether the denial was correct is a credit judgement; whether it was made on a complete reading of policy is now on the record.

finance · regulatory realistic ~150 lines
Download .py
These three use demo embeddings

The sector examples use a deterministic hash embedding so they run with no API key. Swap embed() for a domain encoder before measuring anything — the retrieval logic does not change, but the quality of the result will.

04 — Reproduce the benchmark yourself

Verify exact recall on data you generate

Do not trust our numbers. This generates its own corpus, computes brute-force ground truth, and compares. If it cannot reproduce exact scan on synthetic data, it will not on BIGANN either.

Output from the actual run (20,000 vectors × 384 dims, 50 queries):

top-1 agreement   1.0000
setR@10 overlap   1.0000
bound violations  0
------------------------------------------------
build time        177.0 ms
search time       107.5 ms (2.15 ms per query)
brute force time  36.4 ms
verification ~100 lines
Download .py

05 — Catch a corrupted corpus before it breaks the proofs

The quality gate that fails loudly

A bound proof is only as strong as the vectors it was computed on. The engine will index a corpus full of NaN and return bound_violations = 0, because the arithmetic is correct — the inputs were garbage. This example feeds it a broken corpus and shows the thirteen-flag audit catching it.

Output from the actual run — NaN, zeros and inf mixed in:

has_fail      : True
fail flags    : 1
warn flags    : 3

FAIL [dataset.nan]
     150 of 32000 values are NaN/inf (0.4687%) — the engine would
     silently produce garbage scores with 0 bound violations.

WARN [dataset.recall_not_guaranteed]
     seed recall@K = 0.375 vs the motor's own search_exact...
     the returned top-K is the best WITHIN the pool, NOT proven
     the global top-K.

The second warning is the important one: a query can report zero bound violations and still not be globally guaranteed, because the count only covers the candidate pool. The gate tells you which case you are in. See the flag system in the main documentation for all thirteen codes.

data quality critical ~110 lines
Download .py

06 — Agent memory that can be audited

Append-only memory where every recall carries proof

An agent that remembers past interactions is only as trustworthy as its ability to recall them. If memory silently drops a past instruction, the agent behaves unpredictably and nobody can explain why.

class AuditableMemory:
    def remember(self, texto, **meta): ...   # append + rebuild
    def recall(self, consulta, k=3): ...   # memories + proof
    def explain(self, consulta, alvo): ...  # why not recalled?

Output from the actual run:

consulta: quando posso contatar o cliente

  [0.909] (contexto) O cliente atua no setor hospitalar, em Portugal.
  [0.899] (preferencia) O cliente pediu para não ser contatado às sextas.

total de memórias      : 5
recuperadas            : 2
excluídas COM PROVA    : 3
violações de bound     : 0

Every remember() rebuilds the index — viable because a 1M-vector index builds in 1.69 s against 33.6 s for HNSW on the same corpus. Agent memory can grow in real time without the guarantee degrading.

agents · memory intermediate ~140 lines
Download .py

07 and 08 — The minimal generic paths

07 · SQL to search (generic)

The shortest path from a database to a provably complete answer, with no domain framing. Use this when you want the mechanics without the scenario.

SQL~40 lines
Download .py

08 · RAG agent (generic)

How to wire the engine into an existing RAG pipeline, including the system prompt that lets the model state the retrieval was proven complete.

RAG · LLM~90 lines
Download .py

What none of these examples do

Stated plainly, because documentation is only useful when the limits are visible:

09–12 — The tracer family

Four examples, one per vertical. Each loads a realistic corpus for its domain, instruments the engine so every search produces a signed record, and reads back the exclusion evidence.

09 · Tracer-MED — hospital audit trail

A medical audit service holds 400 reports. The query "apendicite" returns two, and the engine reports how many were excluded with proof.

laudos no corpus    : 400
laudos encontrados  : 2
excluídos com prova : 17
garantia            : exact_global
bound violations    : 0

registro de exclusão (amostra):
  doc 13: bound=0.3854 excluído=True
health~85 lines
Download .py

10 · Tracer-GOV — procurement audit

A court of accounts scans 600 procurement processes for emergency dispensations lacking justification.

processos analisados : 600
processos retornados : 5
garantia             : exact_global
bound violations     : 0
government~75 lines
Download .py

11 · Tracer-JUS — contract due diligence

500 contract clauses searched for early-termination risk. The point is proving no risky clause was omitted.

cláusulas no repositório : 500
cláusulas de risco       : 4
garantia                 : exact_global
bound violations         : 0
legal~75 lines
Download .py

12 · Tracer-GAP — financial reconciliation

800 accounting entries in a period with a discrepancy. Internal audit asks which entries lack supporting documentation.

lançamentos no período : 800
lançamentos suspeitos  : 5
garantia               : exact_global
bound violations       : 0
finance~75 lines
Download .py

13–16 — X-Factor, Nano, Normalize and build speed

13 · X-Factor — manifold projection from weights

Derives the subspace where a model's token embeddings live, without training and without running the model. The example is honest about a subtlety: synthetic noise has no low-dimensional structure, so the projection does not reduce anything. Real weights do.

embedding table : 4,000 tokens x 256 dims
manifold basis  : (256, 256)  (rank efetivo 236)
residual        : 0.9521
embedding see the honesty note~80 lines
Download .py

14 · Nano — tokenizer and weight blending

Two components that run with no model download: the deterministic spectral tokenizer (perfect round-trip across five languages, including accents and Japanese) and the weight balancer that fuses two models without gradients.

[OK] 'Winnex AI' -> 'Winnex AI'
[OK] 'Ñoño café — acentuação preservada' -> idêntico
[OK] '日本語のテスト' -> idêntico

modelo A (70%) + modelo B (30%)
fundido: [3.70, 7.40, 11.10, 14.80]
inference~105 lines
Download .py

15 · Normalize — providers, L2 contract and drift

Applies the L2 unit-norm contract by hand, shows validation rejecting NaN and wrong dimensions, and demonstrates drift detection with an embedding fingerprint.

norma antes  : min=87.74 max=105.67
norma depois : min=1.0000 max=1.0000

[aceito]   vetores válidos
[recusado] com NaN — ValueError
[recusado] dimensão errada — ValueError

[embedding.provider_drift] espaço deslocado:
  batch-centroid cosine 0.061 (< 0.8)
data quality~110 lines
Download .py

16 · Build speed across corpus sizes

Measures build time from 1,000 to 200,000 vectors and compares query latency against brute force. Ends with the honest crossover: Madhava is competitive in query time up to roughly 50,000 vectors, and always far ahead on build.

    corpus       build   per 1k docs
     1,000       9.1 ms        9.07 ms
    50,000      93.2 ms        1.86 ms
   200,000     269.3 ms        1.35 ms

vs HNSW on 99,800 vectors: 1.45 s vs 33.60 s (23.1x)
performance~110 lines
Download .py