Skip to content

About

RAG-powered Q&A bot for football rules using IFAB Laws of the Game, FAISS vector search, and Groq's Llama 3.1 with citation tracking

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

RefBot — Football Laws of the Game Q&A

RefBot uses the bundled English IFAB Laws of the Game 2024/25 PDF to answer football rules questions. It uses pdfplumber, all-MiniLM-L6-v2, FAISS and Groq's qwen/qwen3.8-27b.

Try the React web app locally

The web app covers IFAB 2024/25. Explicit requests for current or different seasons receive an edition notice. Sample Q&A uses checked passages from the bundled rulebook and works without a Groq key. Enter a question and select Ask RefBot to use the live path. An answer includes expandable page excerpts and links to physical PDF pages.

Build and preview

Use Python 3.11 and Node.js 24 or later. From the repository root:

python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
npm --prefix frontend ci
npm --prefix frontend run build
python -m uvicorn api:app --host 127.0.0.1 --port 8000

Open the local web app. The checked-in indexes support the sample flow immediately. Add GROQ_API_KEY to .env and restart Uvicorn for live answers. During frontend development, run npm --prefix frontend run dev with Uvicorn still listening on port 8000. Vite proxies the API and PDF endpoints.

Browser / React → FastAPI
    ├── Sample Q&A → checked passages in the local FAISS metadata
    ├── Live question → dense FAISS → Groq → server-side citation validation
    └── Source link → bundled IFAB PDF at its physical page

The API exposes display numbers, physical pages and excerpts. Internal source IDs stay on the server. Insufficient evidence, invalid citations and upstream failures produce distinct API outcomes. The UI shows insufficient evidence separately from service errors.

Container hosting

The root Dockerfile builds React and starts FastAPI on the hosting provider's PORT (default 10000). The container needs no Groq key for checked sample answers. For the retained Streamlit interface, override the container command with streamlit run app.py --server.address=0.0.0.0 --server.port=10000.

Test

python -m unittest discover -s tests -v
npm --prefix frontend run build

In a browser, open the offside sample and expand its source. Confirm that pages 99 and 100 have separate excerpts and PDF links. Try the unrelated question and ask a current-season question through the live form. With the key unset, a normal live question should show a service error while samples still load.

The original Streamlit interface remains available with streamlit run app.py. The evaluation below retains the original 30 cases and adds 16 out-of-scope questions. Retrieval and live answer metrics use separate rubrics.

How a question is answered

  1. src/pdf_loader.py extracts text in PDF reading order and records each page's one-based position in the file. The tighter line tolerance keeps offset headings from merging with nearby bullets. The parser is designed for the bundled edition.
  2. src/chunking.py builds overlapping fixed windows or groups text by law, section and subheading. Structure-aware chunks carry governing headings and list lead-ins across splits. Both strategies keep the text from each physical PDF page and derive stable source IDs from the passage content and provenance.
  3. src/embeddings.py builds normalized FAISS vectors and checks that the index and its citation metadata match when loading. src/retriever.py ranks passages by cosine similarity. The evaluation also supports reciprocal rank fusion of FAISS and a TF-IDF unigram/bigram ranking.
  4. src/generator.py asks Groq to return claims with retrieved IDs and short verbatim supporting excerpts. Code checks the response structure, IDs and excerpts before resolving the citations to physical PDF pages. The sources drawer shows the cited passages, grouped by page. When evidence is insufficient or validation fails, the app says “I couldn't verify this in the rulebook.” Printed page numbers are omitted. Excerpt validation verifies that the words occur in the source. Whether the excerpt supports the claim still requires judgment.

Setup and index rebuild

Run from the repository root with Python 3.10 or newer.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python build_index.py
python -m unittest discover -s tests -v

The builder uses data/laws_of_the_game.pdf and writes both FAISS indexes under data/index/. Rebuild if the app reports old or mismatched citation metadata. If native embedding threads crash on macOS, set OMP_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 TOKENIZERS_PARALLELISM=false in the shell before building, evaluating or starting the app.

For live answers, copy .env.example to .env, set GROQ_API_KEY, and run streamlit run app.py. Set GROQ_MODEL in .env if your Groq account needs a different chat model that supports JSON mode.

Evaluation

The structure change regressed dense hit rate from 20/26 to 19/26. The live dense run still improved from 14/26 to 17/26 correct answers. Running each ranking against both indexes shows that the updated index also lost one hybrid hit, while gaining one case with all expected evidence. Hybrid improved both retrieval measures on each index. Each cell used the same five-passage and 1,500-token source-context limits.

  • Original index, dense. Hit at 5 was 20/26. All evidence at 5 was 17/26.
  • Original index, hybrid. Hit at 5 was 22/26. All evidence at 5 was 19/26.
  • Updated index, dense. Hit at 5 was 19/26. All evidence at 5 was 17/26.
  • Updated index, hybrid. Hit at 5 was 21/26. All evidence at 5 was 20/26.

The fixture has 26 in-scope questions with expected answers, rule references and page-specific excerpts. The harness checks that each expected excerpt is present on the specified physical page in each index. The additional 20 out-of-scope questions cover unrelated topics, football facts outside the Laws, and requests that need a different rulebook, competition rules, or incident evidence. A hit at 5 requires at least one expected excerpt on the right page. All-evidence at 5 requires every expected excerpt.

Live results

All configurations used the hardened answer generator with Groq's qwen/qwen3.8-27b. The original-index runs use the old passage text and boundaries with the new citation metadata. Codex reviewed the generated answers against the fixture using the rubric below.

  • Original index, dense. Correct answers 14/26. Citation accuracy 12/26. Out-of-scope refusals 20/20. Zero API errors, two response-validation errors and six in-scope refusals.
  • Original index, hybrid. Correct answers 16/26. Citation accuracy 13/26. Out-of-scope refusals 20/20. Zero API errors, three response-validation errors and three in-scope refusals.
  • Updated index, dense. Correct answers 17/26. Citation accuracy 14/26. Out-of-scope refusals 20/20. Zero API errors, two response-validation errors and six in-scope refusals.
  • Updated index, hybrid. Live scores pending. Groq reached its 200,000-token daily limit after 18 case outcomes, including one response-validation error. Eleven additional cases hit the API limit and 17 were unattempted. The checkpoint keeps those categories separate.

The refusal result applies to this 20-question set. One failure across the complete runs was the cross-page penalty question. The answers omitted either the decision to retake after a goalkeeper's save or the warning for a first offence. Full case verdicts and recorded answers are in eval/live-results.json.

Reproduce the benchmark

The baseline rebuild preserves the original PDF extraction and structure chunk texts while adding physical-page provenance. Rebuild both indexes from the bundled PDF.

mkdir -p .venv/eval
python build_index.py
python build_index.py --baseline-dir .venv/eval/baseline-index

With GROQ_API_KEY configured, run the four live evaluations. Set the request interval to fit your Groq limits. These are sequential runs.

python test_questions.py --live --request-interval 12 --index-dir .venv/eval/baseline-index --retrieval dense --output .venv/eval/live-old-dense.json
python test_questions.py --live --request-interval 12 --index-dir .venv/eval/baseline-index --retrieval hybrid --output .venv/eval/live-old-hybrid.json
python test_questions.py --live --request-interval 12 --retrieval dense --output .venv/eval/live-new-dense.json
python test_questions.py --live --request-interval 12 --retrieval hybrid --output .venv/eval/live-new-hybrid.json

Omit --live to measure retrieval with local embeddings and FAISS.

Live runs write a checkpoint after each case when --output is set. For a four-way run that exceeds your daily quota, continue from the checkpoint after quota is available. The runner preserves prior valid and parsing-error outcomes, retries API failures, and keeps their original attempt log.

python test_questions.py --live --resume --request-interval 12 --retrieval hybrid --output .venv/eval/live-new-hybrid.json

Grading rubric

  • Answer correctness (26 in-scope questions). Compare the answer with the fixture's expected answer and its indexed evidence. Award one point only for the correct decision, restart, or rule and all conditions or exceptions needed by the question. Equivalent wording and units count. An omission that changes the decision, an incorrect condition, or a materially false addition earns zero. Review each in-scope answer and set its report row's answer_correct to true or false.
  • Citation accuracy (26 in-scope questions). The harness checks that the cited passages collectively contain every expected excerpt on the correct physical pages, and that each cited passage contributes expected evidence. This measures evidence coverage against the fixed excerpts. It can miss equivalent evidence. Claim-level entailment requires separate review.
  • Refusal accuracy (20 out-of-scope questions). An explicit unsupported response earns one point. An answer or a failed request earns zero, even if the UI would display the same fallback after validation failure.
  • Failures. API errors, response parsing and validation errors, and in-scope refusals are reported separately. They earn zero for the applicable accuracy metrics and remain in their denominators.

After reviewing the answers in each live report, rescore it with this command.

python test_questions.py --score-report .venv/eval/live-new-hybrid.json

About

RAG-powered Q&A bot for football rules using IFAB Laws of the Game, FAISS vector search, and Groq's Llama 3.1 with citation tracking

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages