Run this model with HF Jobs
Run nsr51324/CortexRAG on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/nsr51324/CortexRAG. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/nsr51324/CortexRAG on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use nsr51324/CortexRAG with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use nsr51324/CortexRAG with sentence-transformers:
from sentence_transformers import CrossEncoder model = CrossEncoder("nsr51324/CortexRAG") query = "Which planet is known as the Red Planet?" passages = [ "Venus is often called Earth's twin because of its similar size and proximity.", "Mars, known for its reddish appearance, is often referred to as the Red Planet.", "Jupiter, the largest planet in our solar system, has a prominent red spot.", "Saturn, famous for its rings, is sometimes mistaken for the Red Planet." ] scores = model.predict([(query, passage) for passage in passages]) print(scores) - Notebooks
- Google Colab
- Kaggle
Update README.md
Browse files18 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203212 unmodified lines3243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119618 unmodified linesA retrieval-augmented generation (RAG) system for answering medical questions using a curated English medical Question-Answer knowledge base.The system combines:- Semantic retrieval using Sentence Transformers- FAISS vector search- Medical query expansion- Cross-Encoder reranking- Evidence deduplication- Confidence gating- LLM-based answer generation- Retrieval evaluation- Confidence-gate evaluation- Latency measurement> **Important:** This system is intended for research and educational purposes. It is not a medical diagnostic system and should not be used as a substitute for professional medical advice.---# 1. OverviewThis project implements a complete Retrieval-Augmented Generation pipeline for medical Question-Answer data.Instead of asking an LLM to answer directly from its internal knowledge, the system first retrieves relevant medical evidence from a local knowledge base.The pipeline is:```textUser QuestionββΌQuery ExpansionββΌSentence Transformer EmbeddingββΌFAISS Vector SearchββΌTop-N Candidate DocumentsββΌCross-Encoder RerankingββΌTop-K EvidenceββΌNear-Duplicate RemovalββΌConfidence Gateββββ Reject β Insufficient EvidenceββΌLLM GenerationββΌEvidence-Based Answer```---# 2. Knowledge BaseThe knowledge base contains approximately:```text16,384 medical Question-Answer records```The dataset contains medical questions and corresponding answers, together with categorical information.Main columns used by the system:```textQuestionAnswerCategorydoc_id```A unique `doc_id` is assigned to every document:```pythondf = df.reset_index(drop=True)df["doc_id"] = df.index```The `doc_id` is later used to identify evidence sources.---# 3. Embedding ModelThe system uses:```textsentence-transformers/all-MiniLM-L6-v2```The model converts every medical question into a dense vector representation.Embeddings are normalized:```pythonquestion_embeddings = embedder.encode(questions,batch_size=64,show_progress_bar=True,convert_to_numpy=True,normalize_embeddings=True,)```Normalization allows the FAISS Inner Product index to behave as cosine similarity search.The resulting embedding matrix is stored as:```textquestion_embeddings.npy```---# 4. FAISS RetrievalFAISS is used for efficient vector similarity search.The index is created using:```pythonfaiss.IndexFlatIP(embedding_dim)```Because the embeddings are normalized, Inner Product corresponds to cosine similarity.The FAISS index contains:```text16,384 vectors```The index is saved as:```textquestions.index```Retrieval works by:1. Embedding the user query2. Searching the FAISS index3. Returning the top-N most similar questionsDefault retrieval configuration:```pythonRETRIEVE_TOP_N = 20```---# 5. Query ExpansionThe system includes a lightweight medical query expansion layer.This helps bridge the gap between everyday language and medical terminology.Examples:```textunderactive thyroidβhypothyroidismoveractive thyroidβhyperthyroidismhigh blood sugarβhyperglycemialow blood sugarβhypoglycemiasugar diseaseβdiabetes```For example:```textI suffer from an underactive thyroid gland```becomes:```textI suffer from an underactive thyroid gland(hypothyroidism)```The original query is not replaced.The medical term is simply appended before generating the embedding.---# 6. Cross-Encoder RerankingAfter FAISS retrieves the initial candidates, a Cross-Encoder is used to rerank them.Model:```textcross-encoder/ms-marco-MiniLM-L-6-v2```The system retrieves:```textTop 20```candidates and reranks them to keep:```textTop 6```Configuration:```pythonRETRIEVE_TOP_N = 20RERANK_TOP_K = 6```The reranker scores:```text(query, Answer)```rather than:```text(query, Question)```This is important because the dataset contains multiple records with the same Question but different medical answers.Reranking the Answer therefore helps determine which evidence is actually useful for answering the user's question.---# 7. Evidence DeduplicationMedical datasets can contain multiple answers that are almost identical.The system removes near-duplicate answers using:```pythondifflib.SequenceMatcher```with:```pythonthreshold = 0.92```This prevents the LLM from receiving multiple copies of essentially the same evidence.Each evidence item contains:```textdoc_idquestionanswercategorysimilarityrerank_score```---# 8. Confidence GateThe system does not automatically answer every question.Before sending evidence to the LLM, a confidence gate checks whether the retrieved evidence is strong enough.Current configuration:```pythonMIN_RERANK_SCORE = -82 unmodified linesSUPPORT_SCORE = -5.0```The system accepts the evidence only if:1. At least one result exists.2. The highest rerank score is above the minimum threshold.3. The similarity score is above the minimum similarity floor.4. At least two retrieved documents provide sufficient support.Otherwise, the system refuses to generate an evidence-based answer.Example:```textQuestion:Why do I feel short of breath and tired when I climb stairs?Result:No sufficiently relevant evidence.System:I couldn't find sufficiently relevant medical evidencein the knowledge base to answer this question.```This behavior is important for reducing unsupported answers.---# 9. LLM GenerationThe generation stage uses a Groq-hosted LLM.Current model used during development:```textopenai/gpt-oss-20b```The LLM is explicitly instructed to operate in RAG mode.Main generation rules:```text1. Use only retrieved evidence.2. Do not add outside medical knowledge.3. Do not guess.4. Cite evidence using [doc_id].5. Mention when evidence is insufficient.6. Do not diagnose users.7. Do not prescribe personalized treatment or dosages.8. Mention disagreements between sources.9. Keep answers concise and organized.10. Include a medical-information disclaimer.```The API key is NOT stored in this repository.It should be provided through an environment variable:```pythonimport osGROQ_API_KEY = os.environ["GROQ_API_KEY"]```---# 10. Example## Input```textWhat signs might suggest that my thyroid is not producing enough hormones?```## Retrieved Evidence```text[15967] Thyroid symptoms[13504] Thyroid symptoms[10676] Thyroid symptoms[13989] What are the symptoms of thyroid disease?[13559] Symptoms that indicate a disorder in the thyroid gland[12173] How do I know that I have a thyroid problem?```## Generated AnswerThe system generated an evidence-based response describing symptoms associated with low thyroid hormone production, including:- Fatigue- Feeling cold- Weight gain- Constipation- Menstrual changes- Hair lossThe final response also included the required medical disclaimer.---# 11. Example of Out-of-Domain Query## Input```textWhat is the best treatment for a broken leg?```The retriever returned some medically related documents, mostly concerning diabetic foot injuries.However, those documents did not contain appropriate evidence about treating fractures.The final system response therefore stated that the available evidence did not contain information about treating a broken leg.This demonstrates an important property of the system:> Retrieval similarity alone does not guarantee that the retrieved evidence is appropriate for the question.---# 12. EvaluationThe system was evaluated using multiple complementary evaluation methods.These include:- Self-retrieval accuracy- Recall@K- Precision@K- F1@K- MRR- NDCG@K- Category sanity check- Confidence-gate accuracy- Cross-validation threshold tuning- Latency evaluation---# 13. Self-Retrieval EvaluationA sample of 50 questions was tested.Result:```textSelf-retrieval Top-1 Accuracy:50 / 50= 100%```However, this metric should NOT be interpreted as proof that the system has 100% real-world retrieval accuracy.It mainly verifies that the embedding/index pipeline can retrieve the original record when the exact same question is used.---# 14. Retrieval EvaluationThe retrieval evaluation used questions that have duplicate Question entries in the dataset.This provides multiple possible relevant answers for the same question.```textQuestions with duplicate entries usable for evaluation:67```## Retrieval Only```textRecall@1 = 0.690Precision@1 = 1.000F1@1 = 0.745Recall@3 = 0.851Precision@3 = 0.560F1@3 = 0.563Recall@5 = 0.899Precision@5 = 0.423F1@5 = 0.462Recall@10 = 0.959Precision@10 = 0.286F1@10 = 0.349MRR = 1.000```Number of evaluated queries:```text150```---# 15. Retrieval + Cross-Encoder EvaluationThe same evaluation was also performed after Cross-Encoder reranking.Results:```textRecall@1 = 0.083Precision@1 = 0.113F1@1 = 0.093Recall@3 = 0.157Precision@3 = 0.087F1@3 = 0.100Recall@5 = 0.222Precision@5 = 0.121F1@5 = 0.120Recall@10 = 0.388Precision@10 = 0.135F1@10 = 0.153MRR = 0.237```Number of evaluated queries:```text150```---# 16. Important Evaluation ObservationThe evaluation shows that the Cross-Encoder performed significantly worse under this particular retrieval benchmark.This is an important finding rather than something to hide.The current reranker was trained for general passage relevance using:```textcross-encoder/ms-marco-MiniLM-L-6-v2```while this evaluation is based on medical Question-Answer records.Therefore, the Cross-Encoder may not rank the medical answers in the same way as the manually defined relevance criteria.This suggests that the reranking component requires further investigation before being considered production-ready.Possible future improvements include:- Medical-domain reranker- Fine-tuning a Cross-Encoder on medical relevance pairs- Using a manually reviewed gold set- Better relevance labeling- Evaluating reranking separately from retrieval- Testing alternative reranking models---# 17. Category Sanity CheckA category-based sanity check was also performed.The goal is to determine whether retrieved documents contain at least one document belonging to the same category as the query's source document.## Retrieval + Reranker```textCategory Recall = 0.98n = 100```## Retrieval Only```textCategory Recall = 0.97n = 100```This indicates that the retrieval system generally retrieves documents from the expected medical category.However:> Category matching is only a supporting diagnostic metric and is NOT treated as the final ground truth for relevance.---# 18. Confidence Gate EvaluationA manually constructed evaluation set contained:```text25 in-domain questions25 out-of-domain questions```Total:```text50 questions```The system achieved:```textGate Decision Accuracy = 88%```The system correctly accepted most in-domain questions and rejected most out-of-domain questions.However, several false positives were observed.Examples included questions about:```textbroken legskidney stonessprained anklesbroken armsfood poisoning```These questions sometimes retrieved medically related evidence even though the knowledge base did not contain appropriate evidence.This demonstrates why confidence gating and stronger relevance evaluation are necessary.---# 19. Confidence Score DistributionFor the confidence-gate evaluation:### Expected answer = True```textMean score = 5.539Minimum = -8.938Maximum = 9.321```### Expected answer = False```textMean score = -6.167Minimum = -11.062Maximum = 1.532```There is overlap between the two distributions.Therefore, a single rerank-score threshold cannot perfectly separate valid and invalid questions.---# 20. Threshold TuningThe confidence threshold was evaluated using 5-fold cross-validation.Instead of selecting a threshold from one train/test split, the data is divided into five different folds.For every fold:1. A threshold is optimized on the training portion.2. The threshold is evaluated on the held-out fold.3. The threshold and test accuracy are recorded.4. Mean and standard deviation are calculated.This helps determine whether the selected threshold is stable or highly dependent on a small evaluation sample.A large threshold standard deviation indicates that the evaluation set is too small or unstable and should be expanded before selecting a production threshold.---# 21. Gold SetA semi-automatic gold-set construction process was implemented.The process:```text100 sampled questionsββΌExact duplicate questionsββΌSemantic candidates with similarity >= 0.90ββΌManual reviewββΌRelevant = 1Not relevant = 0ββΌFinal Gold Set```The initial run generated:```text100 questions16 candidate pairs3 questions with semantic candidates```The generated file:```textgold_set_for_manual_review.xlsx```contains candidate pairs that should be manually reviewed.For each candidate, the reviewer should enter:```text1 = relevant0 = not relevant```Only manually approved candidates should be added to the final relevant evidence set.---# 22. Gold Set Evaluation MetricsOnce the manually reviewed gold set is completed, the system evaluates:```textRecall@5MRRNDCG@5```The evaluation compares:```textRetriever only```against:```textRetriever + Cross-Encoder Reranker```The manually reviewed gold set is preferred over category-based evaluation because it provides explicit relevance judgments.---# 23. Latency EvaluationThe complete RAG pipeline was also measured for response latency.Example result:```textRetrieval = 0.016 secReranking = 0.094 secEvidence build = 0.025 secLLM generation = 0.858 secTotal = 0.993 sec```Approximate breakdown:```textRetrieval βReranking βββββEvidence ββLLM βββββββββββββββββοΏ½οΏ½βββββββββββββββββββ```The LLM generation stage is the largest contributor to total latency.The measured end-to-end latency in this test was approximately:```text0.99 seconds```This should not be interpreted as a guaranteed production latency because API/network conditions, hardware, load, and model availability can change.---# 24. Saved ArtifactsThe system uses the following main artifacts:```textquestions.indexquestion_embeddings.npyREADME.mdgold_set_for_manual_review.xlsx```## questions.indexFAISS vector index containing the question embeddings.## question_embeddings.npyNumPy array containing the normalized question embeddings.## gold_set_for_manual_review.xlsxHuman-review file used to create the manually verified relevance set.---# 25. Local DeploymentThe RAG system can be deployed locally as a Python service.Recommended architecture:```textFrontendββΌBackend APIββΌMedical RAG Pipelineββββ FAISSβββ Sentence Transformerβββ Cross Encoderβββ LLM API```The application should load the embedding model and FAISS index once when the service starts.They should NOT be reloaded for every user request.Example:```pythonfrom sentence_transformers import SentenceTransformer, CrossEncoderimport faissimport numpy as npembedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")faiss_index = faiss.read_index("questions.index")question_embeddings = np.load("question_embeddings.npy")```---# 26. Example API ArchitectureA backend can expose an endpoint such as:```httpPOST /api/rag/query```Request:```json{"question": "What are the symptoms of diabetes?"}```Response:```json{"answer": "...","evidence": [{"doc_id": 4793,"similarity": 0.91,"rerank_score": 8.21}]}```This makes the RAG pipeline independent from the frontend.---# 27. Recommended Project Structure```textmedical-rag/ββββ README.mdββββ artifacts/β βββ questions.indexβ βββ question_embeddings.npyββββ src/β βββ retrieval.pyβ βββ reranker.pyβ βββ query_expansion.pyβ βββ evidence.pyβ βββ confidence_gate.pyβ βββ generation.pyβ βββ rag_pipeline.pyββββ api/β βββ app.pyββββ evaluation/β βββ retrieval_evaluation.pyβ βββ gate_evaluation.pyβ βββ gold_set_evaluation.pyββββ data/β βββ gold_set_for_manual_review.xlsxββββ requirements.txt```---# 28. InstallationInstall the main dependencies:```bashpip install sentence-transformers faiss-cpu numpy pandas openpyxl```For Groq-based generation:```bashpip install groq```---# 29. Environment VariablesNever hard-code API keys inside source code.Set:```bashGROQ_API_KEY=your_api_key_here```Python:```pythonimport osapi_key = os.environ["GROQ_API_KEY"]```---# 30. SecurityThe API key used during development must not be committed to GitHub or Hugging Face.Recommended practice:```text.env```and:```text.gitignore```Example `.gitignore`:```text.env__pycache__/*.pyc.ipynb_checkpoints/```If an API key has already been exposed publicly, revoke it and generate a new one.---# 31. LimitationsThis system has several important limitations.### 1. Medical domain limitationsThe knowledge base does not necessarily cover every medical condition or clinical scenario.### 2. Retrieval limitationsA semantically similar document is not necessarily an appropriate answer.### 3. Reranker limitationsThe current Cross-Encoder was not specifically trained on this medical dataset.### 4. Gold-set limitationsThe manually reviewed gold set is still small.### 5. Evaluation limitationsSome evaluation metrics rely on duplicate Question entries rather than a fully manually annotated relevance dataset.### 6. LLM limitationsThe generated answer depends on the quality of the retrieved evidence.### 7. Clinical safetyThe system should not be used for diagnosis, emergency decisions, prescribing medication, or personalized treatment.---# 32. Future ImprovementsRecommended next steps:```text1. Complete the manual gold-set annotation.2. Increase the number of manually reviewed questions.3. Train or evaluate a medical-domain reranker.4. Re-evaluate the Cross-Encoder using the manual gold set.5. Tune the confidence gate using a larger validation set.6. Add citation/source metadata.7. Add automated regression tests.8. Add monitoring for retrieval failures.9. Add API-level authentication and rate limiting.10. Deploy the RAG pipeline behind a REST API.11. Add a frontend chat interface.12. Evaluate hallucination/faithfulness separately from retrieval quality.```---# 33. Evaluation Summary| Metric | Result ||---|---:|| Knowledge Base Size | 16,384 records || Self-Retrieval Top-1 | 100% || Retrieval Recall@1 | 69.0% || Retrieval Recall@3 | 85.1% || Retrieval Recall@5 | 89.9% || Retrieval Recall@10 | 95.9% || Retrieval Precision@1 | 100% || Retrieval F1@1 | 74.5% || Retrieval MRR | 1.000 || Category Recall + Reranker | 98% || Category Recall Retrieval Only | 97% || Confidence Gate Accuracy | 88% || Example End-to-End Latency | 0.993 sec |> The evaluation numbers above are specific to the current experimental setup and should not be interpreted as general medical accuracy.---# 34. Responsible UseThis project provides general medical information retrieval and generation.It is not:- A diagnostic tool- A clinical decision-support system- A replacement for a physician- A prescription system- An emergency medical serviceUsers should consult qualified healthcare professionals for medical decisions.---# 35. Citation and References### Sentence Transformershttps://www.sbert.net/### FAISShttps://github.com/facebookresearch/faiss### Cross-Encoderhttps://www.sbert.net/examples/applications/cross-encoder/README.html### Hugging Face Model Cardshttps://huggingface.co/docs/hub/en/model-cards### Hugging Face Model Release Checklisthttps://huggingface.co/docs/hub/en/model-release-checklist---# 36. Project Status```textStatus: Research / PrototypeRetrieval: ImplementedFAISS: ImplementedQuery Expansion: ImplementedCross-Encoder Reranking: ImplementedEvidence Deduplication: ImplementedConfidence Gate: ImplementedLLM Generation: ImplementedEvaluation: ImplementedLatency Measurement: ImplementedManual Gold Set: In ProgressProduction Deployment: Future Work```---# 37. Final NoteThe main objective of this project is not simply to generate medical answers.The goal is to build a RAG system that:```textRetrieves evidenceβRanks evidenceβChecks confidenceβGenerates from evidenceβProvides traceable document IDs```This design allows the system to be evaluated as a retrieval pipeline independently from the LLM generation layer.18 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273742 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814918 unmodified linesA retrieval-augmented generation (RAG) system for answering medical questions using a curated English medical Question-Answer knowledge base.The system combines semantic retrieval (Sentence Transformers + FAISS), medical query expansion, Cross-Encoder reranking, evidence deduplication, confidence gating, and LLM-based answer generation.> **Important:** This system is for research and educational purposes only. It is not a medical diagnostic system and should not replace professional medical advice.---## 1. Pipeline```textUser QuestionββΌQuery Expansion (lay terms β medical terms)ββΌSentence Transformer EmbeddingββΌFAISS Vector Search (Top 20 candidates)ββΌCross-Encoder Reranking (Top 6 evidence)ββΌNear-Duplicate RemovalββΌConfidence Gate ββrejectβββΆ "Insufficient evidence"β passβΌLLM GenerationββΌEvidence-Based Answer (with doc_id citations)```## 2. Knowledge Base~16,384 medical Question-Answer records with columns `Question`, `Answer`, `Category`, `doc_id`.## 3. Retrieval- **Embedding model:** `sentence-transformers/all-MiniLM-L6-v2`, embeddings normalized so FAISS `IndexFlatIP` behaves as cosine similarity.- **Query Expansion:** a small lay-term β medical-term dictionary is appended to the query before embedding (e.g. `underactive thyroid β hypothyroidism`, `high blood sugar β hyperglycemia`). The original query is never replaced, only extended.- **Reranking:** `cross-encoder/ms-marco-MiniLM-L-6-v2` scores `(query, Answer)` β not `(query, Question)` β since many records share the same question with different answers; this identifies which *evidence* is actually useful.- **Evidence deduplication:** near-identical answers are collapsed via `difflib.SequenceMatcher` (threshold 0.92).## 4. Confidence GateEvidence is only sent to the LLM if **all** conditions hold:```pythonMIN_RERANK_SCORE = -82 unmodified linesSUPPORT_SCORE = -5.0```1. At least one result exists.2. Top rerank score β₯ `MIN_RERANK_SCORE`.3. Top similarity β₯ `MIN_SIMILARITY_FLOOR`.4. At least `MIN_SUPPORT_COUNT` results score β₯ `SUPPORT_SCORE`.Otherwise, the system explicitly refuses to answer rather than guessing.## 5. GenerationLLM: Groq-hosted `openai/gpt-oss-20b`, instructed to answer **only** from retrieved evidence, cite sources by `[doc_id]`, flag disagreement between sources, avoid diagnosis/prescriptions, and include a medical disclaimer. API key is read from `GROQ_API_KEY` (never hard-coded).## 6. Example**Q:** *What signs might suggest that my thyroid is not producing enough hormones?***Evidence:** 6 thyroid-related records retrieved and reranked.**Answer:** Evidence-based summary (fatigue, feeling cold, weight gain, constipation, menstrual changes, hair loss) + disclaimer.**Out-of-domain example β Q:** *What is the best treatment for a broken leg?*Retrieval returned diabetic-foot documents (lexically similar), but the gate/LLM correctly identified them as inappropriate evidence and refused to answer β demonstrating that similarity alone doesn't guarantee relevance.## 7. Evaluation Summary| Metric | Result ||---|---:|| Knowledge Base Size | 16,384 records || Self-Retrieval Top-1 | 100% || Retrieval Recall@1 / @5 / @10 | 69.0% / 89.9% / 95.9% || Retrieval MRR | 1.000 || Retrieval + Reranker Recall@1 / @5 / @10 | 8.3% / 22.2% / 38.8% || Retrieval + Reranker MRR | 0.237 || Category Recall (retrieval / +reranker) | 97% / 98% || Confidence Gate Accuracy | 88% (n=50) || Example End-to-End Latency | 0.99 sec |**Key finding:** the general-purpose Cross-Encoder scores notably *worse* than plain retrieval on this duplicate-question-based benchmark. This isn't hidden β it indicates the reranker (trained for general passage relevance) doesn't align well with medical relevance judgments, and needs validation against a manually reviewed gold set before being trusted in production. A semi-automatic gold-set workflow (exact duplicates + semantic candidates β₯0.90 similarity, human-reviewed 1/0 labels) is included for this purpose; Category-match is used only as a secondary sanity check, not ground truth.The confidence-gate threshold was tuned via 5-fold cross-validation rather than a single split, to check stability rather than overfit to one small sample.## 8. Limitations- Knowledge base doesn't cover every condition/scenario.- Semantic similarity β appropriate evidence (see broken-leg example).- Reranker not fine-tuned on this medical domain yet.- Manual gold set is still small β evaluation should be treated as preliminary.- Not for diagnosis, emergencies, prescriptions, or personalized treatment.## 9. Installation```bashpip install sentence-transformers faiss-cpu numpy pandas openpyxl groq``````pythonimport osGROQ_API_KEY = os.environ["GROQ_API_KEY"] # never hard-code keys```## 10. Future WorkComplete manual gold-set annotation β re-evaluate reranker against it β consider a medical-domain reranker β expand confidence-gate validation set β add citations/monitoring/auth β deploy behind a REST API β evaluate faithfulness/hallucination separately from retrieval quality.## 11. Responsible UseNot a diagnostic tool, clinical decision-support system, prescription system, or emergency service. Consult a qualified healthcare professional for medical decisions.## References- [Sentence Transformers](https://www.sbert.net/)- [FAISS](https://github.com/facebookresearch/faiss)- [Cross-Encoder](https://www.sbert.net/examples/applications/cross-encoder/README.html)
README.md+62-1109