Skip to content

About

Cited, abstaining RAG over Brazilian tax-reform law (LC 214/2025) and NF-e technical docs, with a reproducible evaluation: BM25 vs bge-m3 vs hybrid vs rerank, golden set, CI without API keys.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

fiscal-rag-br

CI Python License

A retrieval-augmented QA system for Brazilian tax-reform questions where every answer cites its source (an answer without a valid citation is discarded) and questions the corpus cannot answer should get an abstention, plus the evaluation that measures how often both hold.

The corpus is a deliberately narrow slice of official, public documents:

Source What it covers Unit of retrieval
Lei Complementar 214/2025 (Planalto, compiled text) IBS, CBS and Imposto Seletivo: incidence, base, rates, credits, special regimes, transition article (long ones split by paragraph; every part repeats the caput and the §, inciso and alínea that govern it) and annex
NT 2025.002-RTC v1.53 (Portal NF-e) NF-e/NFC-e layout changes for IBS/CBS/IS: fields, validation rules, new events layout field (UB18), validation rule (UB13-30), numbered section (8.6)
MOC 7.0 Visão Geral (Portal NF-e) NF-e web services, access key, events, contingency numbered section
MOC 7.0 Anexo I (Portal NF-e) full NF-e layout and validation rules layout field (B22), validation rule (N12-70)

Every answer comes with a citation a person can check in the original: document, article/field/rule/section, version and page, e.g. NT 2025.002-RTC, regra UB13-30 (v1.53 (October 2026), p. 41).

PT-BR: RAG sobre a reforma tributária do consumo (LC 214/2025, NT 2025.002-RTC) e o manual da NF-e (MOC 7.0). Toda resposta cita documento, artigo/campo/regra e versão; perguntas fora do corpus recebem abstenção explícita. Inclui golden set anotado, comparação BM25 × vetorial × híbrido × reranking e avaliação no CI sem chave de API.

How a question is answered

flowchart LR
    subgraph Build["Corpus build (offline)"]
        S[sources.toml<br/>official URLs] --> D[download<br/>SHA-256 pinned in<br/>corpus/manifest.json]
        D --> C[structural chunking<br/>article / field / rule / section]
        C --> J[(corpus/chunks.jsonl<br/>doc, locator, version, page)]
    end
    Q[question] --> B[BM25<br/>accent-folded, code-aware]
    Q --> V[dense<br/>bge-m3, local]
    J --> B
    J --> V
    B --> F[hybrid<br/>reciprocal rank fusion]
    V --> F
    F --> R[rerank<br/>bge-reranker-v2-m3<br/>experiment]
    R --> G{confidence &ge;<br/>threshold tuned<br/>on dev split?}
    F --> G
    G -- no --> X[abstain:<br/>no basis in corpus]
    G -- yes --> A[answer<br/>extractive passage, or<br/>local LLM citing n]
    A --> O[answer + citations<br/>doc, locator, version, page]
Loading

Results

Golden set: 69 questions (55 answerable, 14 unanswerable), split into 19 dev and 50 test. Corpus: 3,351 chunks from 4 documents. One run on one machine; every row is reproducible with the command under Try it.

Retriever Recall@5 MRR@10 Hit@1 Citation correct* Abstains on unanswerable* False abstentions* p95 latency Cost / question
bm25 (extractive) 83.6% 0.641 50.9% 60.0% 90.0% 25.0% 0.2 ms $0
dense (extractive) 90.9% 0.713 58.2% 52.8% 40.0% 10.0% 19.3 ms $0
hybrid (extractive) 89.1% 0.752 61.8% 67.7% 90.0% 22.5% 11.2 ms $0
hybrid+rerank (extractive) 96.4% 0.87 81.8% 80.6% 100.0% 10.0% 979.1 ms $0
hybrid+rerank + Qwen3-4B-Instruct-2507 (gated) 91.2% 100.0% 15.0% 8737.7 ms $0 (local GPU, ~2150 in / 78 out tokens)
hybrid+rerank + Qwen3-4B-Instruct-2507 (no gate, model decides) 92.1% 100.0% 5.0% 8910 ms $0 (local GPU, ~2184 in / 66 out tokens)

* Answer metrics are on the test split only; the abstention threshold of each row was chosen on the dev split. Recall@5, MRR@10 and Hit@1 are on all answerable questions and count chunks, not articles: a hit is a chunk of a gold passage that contains the annotated evidence quote, and Recall@5 asks whether one is among the 5 chunks the answerer reads. "Citation correct" = the cited chunk is an annotated gold passage that contains the evidence quote (a part of a long article that lacks it does not count), over the answerable questions the system chose to answer. Latency is per question on one machine (RTX 3090 for the model rows); BM25 runs on CPU. Cost is $0 because nothing calls a paid API; the token counts let you price the LLM row on any provider.

What the numbers say:

  • The reranker is the step that matters. BM25, dense and hybrid all put a chunk with the gold evidence in the top 5 for 84 to 91% of the questions, but rank it first only 51 to 62% of the time. The cross-encoder over the hybrid top 30 lifts Hit@1 to 81.8% and Recall@5 to 96.4%, at about 1 s per question on a GPU.
  • Dense retrieval alone abstains badly. Cosine similarity stays high for any question about taxes, so the threshold that keeps dense from refusing real questions also lets 6 of the 10 out-of-corpus test questions through (Protheus parameters, IRPJ presumption, IOF, ISS). BM25's "share of the best possible score" separates them much better; the hybrid confidence blends both.
  • Exact codes need the lexical side. On the 15 questions that name a field or rule code (UB13-30, cClassTrib), BM25 has the gold evidence in the top 5 more often than dense (93% vs 87%) and hybrid ranks it first most often (67%, against 47% for BM25 and 53% for dense). Fusion does not always help: over all questions hybrid's Recall@5 (89.1%) is below dense alone (90.9%), while its Hit@1 and MRR are higher.
  • The LLM improves the citations, not only the prose. Reading the top 5 passages, Qwen3-4B cites a gold passage in about 91% of the questions it answers, against 80.6% for "return the top passage" with the same retriever. With no gate it decides alone when to abstain and gets every unanswerable test question right while refusing only 2 answerable ones (5.0%); the retriever threshold on top makes it stricter without catching anything more (15.0% false abstentions). On this set, the model is the better abstention judge; on a larger or more adversarial set the gate is the cheap safety net.
  • Where it still fails (test split, ungated LLM): it abstains on q03 (IBS rates for 2027 and 2028) although the gold article was passage [1], and on q49 (NF-e file size limit), where the chunk with the answer was not among the 5 passages; it cites a neighbouring article on q18 (export immunity: cites art. 8, annotated art. 79) and q20; on q31 the annotated field UB54a was not retrieved and it cites the validation rule UB54a-10 that defines the same computation, which is right in substance and wrong for the metric. results/per_question-full.jsonl has every answer.
  • Latency. Gated LLM answers take 2.8 s at the median and 8.7 s at p95 on an RTX 3090, about 2,150 prompt and 80 output tokens; the abstentions decided by the gate cost only the retrieval.

Try it

uv sync                                   # base install: BM25 + evaluation, no models
uv run pytest -q                          # golden-set integrity, metric math, BM25 regression
uv run python -m fiscalrag.evaluate --retrievers bm25

# full run (GPU recommended): dense, hybrid, rerank and local generation
uv sync --extra models
uv run python -m fiscalrag.evaluate --retrievers bm25,dense,hybrid,hybrid+rerank --llm --readme
uv run python -m fiscalrag.ask "Qual o código do evento de imobilização de item na NF-e?"

# rebuild the corpus from the official sources
uv sync --extra corpus
uv run python -m fiscalrag.download       # fails loudly if an official file changed
uv run python -m fiscalrag.chunk

Golden set

eval/golden.jsonl: 69 questions in Portuguese, the way a tax analyst or ERP consultant would ask them. 55 are answerable (25 on LC 214, 18 on the NT, 12 on the MOC) and 14 are not. 19 form the dev split (15 answerable, 4 not), used only to pick thresholds and the retriever for the LLM; the other 50 are the test split. Each answerable question names its gold passage(s) by locator (lc214:art. 118, nt2025002:regra UB13-30) and carries verbatim evidence quotes, at least one for each gold location (an event code is quoted from both the event list and the event's own section); a test fails if any gold location holds none of them, so the annotations cannot silently drift when the corpus is rebuilt. Unanswerable questions say why they are out of scope; three of them are near misses (NFS-e and CT-e layouts, which LC 214 mentions but whose technical notes are not in the corpus; ERP parameters).

The questions were drafted with an LLM assistant and checked against the source text by me. 69 questions are enough to separate systems that differ a lot, not to rank systems a few points apart: one answerable question on the test split is worth 2.5 points, one unanswerable question 10 points.

CI

Two jobs, no API key and no model download:

  • bm25: unit tests (golden-set integrity, metric math, exact-code lookup) and a BM25 evaluation that must reproduce the committed numbers in results/metrics-bm25.json.
  • hybrid-from-cache: downloads the bge-m3 vectors of this exact corpus and golden-set version from a GitHub release and recomputes the dense and hybrid rows of the table above. The reranker and the LLM need a GPU and are run locally; their per-question outputs are committed in results/.

Design decisions and trade-offs

  • Chunk by the document's own structure, not by token windows. A tax question is about an article or a field, and the citation has to name one. LC 214 is split per article (long articles per paragraph group, each part repeating the caput and the §, inciso and alínea that govern its first line, so a condition is never cut off from its items); the NT and the MOC are split into layout fields, validation rules and numbered sections, read from the PDF tables with PyMuPDF. The cost: two custom parsers, and they break if Planalto or the Portal NF-e change their formatting. The download step pins SHA-256 hashes so that break is loud.
  • Revoked text is removed. Planalto's compiled text keeps revoked wording struck through; left in, it is retrieved and cited as if it were law. The chunker drops <strike> and line-through spans.
  • BM25 is kept, not replaced. Field and rule codes (UB13-30, N12-70, cClassTrib) are exact identifiers; dense retrieval blurs them, BM25 nails them. The tokenizer keeps a code whole and split, folds accents, and does no stemming (not tried; the misses below are not stemming problems).
  • Hybrid by reciprocal rank fusion, no score normalisation to tune. It improves ranking (MRR 0.713 to 0.752, Hit@1 58.2% to 61.8%) but not Recall@5; the reranker is what moves the numbers.
  • Abstention is a threshold on a confidence score, tuned on dev. Each retriever has its own score (BM25: share of the best possible score for the query terms; dense: cosine; hybrid: an average of both; rerank: the cross-encoder probability). The threshold maximises end-to-end correctness on dev, where "correct" means answering with a gold citation or abstaining on an unanswerable question.
  • Two answer modes. Extractive returns the top passage and its citation: deterministic, no hallucination possible, but the user reads a whole article. The LLM mode writes a short answer and must cite passage numbers; citations that do not point to a retrieved passage are dropped.
  • Everything local. bge-m3, bge-reranker-v2-m3 and Qwen3-4B run on one consumer GPU, so the cost per question is electricity and the evaluation needs no API key. Vectors are stored as fp16 (half the size; every run, cached or fresh, uses the same rounded vectors) and published as a release asset so CI can recompute the dense rows without the model.

Limitations

  • Four documents. No CT-e or NFS-e technical notes, no regulations, no Receita answers to frequently asked questions. Questions about them should abstain, and the near-miss unanswerable questions check that, but the system knows nothing beyond its corpus.
  • Versions move. The NT is at v1.53 and will change; download --accept-changes plus chunk rebuilds the corpus, but the golden set has to be re-checked (the evidence test flags quotes that disappeared).
  • The compiled law carries editorial notes ((Incluído pela Lei ...), (Vide ...)); they stay in the text and sometimes match a query term.
  • Small evaluation set. 50 test questions; differences under about 5 points between rows are within noise. The questions were written by the same person who built the system.
  • Citation correctness is checked against the annotated passage only. When the same rule is stated in two places (an NT rule and the article it implements) and the annotation names one, citing the other counts as wrong.
  • The 4B model's answers are graded by machine only: the citation check and a must_contain check (key numbers or terms), not by a human reading each answer. Each passage is clipped to 700 tokens before generation (80 of 3,351 chunks are longer; see answer.py for why).
  • Latency is one machine (RTX 3090, Windows) with the models already loaded.

What I would change next

  • Grow the golden set to a few hundred questions, with a second annotator, and report confidence intervals instead of point estimates.
  • Add the other technical notes of the reform (CT-e, NFS-e) and the regulations, with a version field per answer so an old answer can be traced to the NT it relied on.
  • Replace the single threshold with a small calibrated classifier over several signals (rerank score, score gap between the first and second hit, BM25 coverage of the query codes).
  • Grade the generated answers, not only their citations: an LLM judge checked against a human-graded sample.
  • Serve it: an HTTP endpoint with the reranker on a smaller model (or ONNX on CPU) to bring the 1.1 s rerank step down.

Data and licensing

The code is MIT. The corpus is downloaded from government sites (planalto.gov.br and nfe.fazenda.gov.br); Brazilian statutes and official acts are not protected by copyright (Lei 9.610/1998, art. 8º, IV), and the derived chunks are committed so CI does not depend on those sites being up. ERP vendor documentation (for example TOTVS/TDN) is deliberately excluded: its terms restrict reproduction. This is a retrieval experiment, not tax advice.

License

MIT

About

Cited, abstaining RAG over Brazilian tax-reform law (LC 214/2025) and NF-e technical docs, with a reproducible evaluation: BM25 vs bge-m3 vs hybrid vs rerank, golden set, CI without API keys.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages