Skip to main content

medeval-framework

PyPI version License: Apache 2.0 Python Support CI Pipeline

A rigorous, open-source Python evaluation framework designed to benchmark medical Large Language Models (LLMs) and PEFT/LoRA adapters for clinical accuracy, hallucination rates, model calibration, and safety.


📖 Table of Contents


🌟 Key Features

  • Multi-Dataset Benchmarks: Out-of-the-box loaders for standard medical datasets (MedQA, PubMedQA, MedMCQA, MMLU-Medical).
  • Custom Proprietary Data: Effortlessly evaluate your own internal datasets via Generic JSONL Loading (air-gapped PHI-safe) or dynamic HuggingFace Dataset ingestion.
  • Dynamic Topic Filtering: Filter any benchmark dataset by medical domain or disease keyword on the fly (e.g. --topic "sickle", --topic "cardiac", --topic "renal").
  • Universal SOTA Connectors: Query local PyTorch weights, PEFT/LoRA adapters (with automatic base-model merging), local RAG architectures (llama_cpp / ChromaDB), OpenAI APIs (gpt-4o), or SOTA routers (OpenRouter) driving Claude 3.5 Sonnet, Llama 3.1 70B/405B, DeepSeek, and Gemini.
  • Dual Clinical Safety Audit:
    • Deterministic Checker: Pure-Python regex engine detecting explicit contraindications in Sickle Cell Disease and Cardiology.
    • Semantic Safety Net: Cross-encoder NLI hazard verification (SemanticSafetyChecker) flagging context-dependent medical risks.
  • Context-Injected Hallucination Detection: Cross-encoder Natural Language Inference (NLIHallucinationDetector) evaluating prediction hypotheses against ground-truth clinical facts with full context injection to minimize false positives.
  • Advanced Calibration & Metrics Suite:
    • Vectorized Expected Calibration Error (ECE), Maximum Calibration Error (MCE), and Brier Score.
    • Generative Sequence Mean: Calculates robust confidence (y_prob) by averaging generated token probabilities, natively supporting OpenAI logprobs.
    • Zero-Shot CoT Uncertainty Extraction: Calculates probabilities directly from <think> reasoning traces for models that do not output logprobs (e.g. DeepSeek R1, OpenAI o1).
    • Dynamic Bootstrap Resampling: Automatically calculates rigorous 95% Confidence Intervals for Accuracy and Hallucination Rates.
  • Incremental Checkpointing: Instantly saves results to a .jsonl stream, allowing you to resume interrupted evaluations flawlessly without re-running API calls.
  • Robust Answer Extraction: High-fidelity regex strategies that flawlessly strip markdown and extract multi-choice keys from verbose clinical reasoning.
  • Multi-Format Export & Comparison: Export structured reports to JSON, Markdown tables (.md), or interactive HTML dashboards (.html), with built-in side-by-side model comparison tools (compare_reports).

📊 Public SOTA Evaluation Benchmarks

The following side-by-side evaluation metrics were generated directly by the medeval-framework against 60 highly-filtered clinical queries from MedQA and PubMedQA.

Metric claude-opus-4-8 deepseek-v4-flash glm-5.3 gpt-5.6-sol
Accuracy 0.8966 0.7500 0.9286 0.8929
Accuracy Ci Lower 0.7361 0.5664 0.7735 0.7280
Accuracy Ci Upper 0.9642 0.8732 0.9802 0.9629
Brier Score 0.1111 0.1758 0.4365 0.4008
Ece 0.1264 0.2016 0.6190 0.5833
Hallucination Rate 0.5862 0.2857 0.6071 0.4643
Hallucination Rate Ci Upper 0.7449 0.4706 0.7643 0.6419
Safety Violations Count 3 1 3 2

Note: High Accuracy combined with high Hallucination Rates points towards memorization of open-source datasets over true clinical reasoning.


⚙️ Installation

medeval-framework is available on PyPI:

# Core lightweight installation (NumPy & pure-Python engines)
pip install medeval-framework

# Full ML & NLP stack (Transformers, PyTorch, Datasets, PEFT, BERTScore)
pip install medeval-framework[nlp]

# Complete installation including development and test suites
pip install medeval-framework[all]

2. Install from Source

For development or contributing:

git clone https://github.com/TeslaInch/medeval-framework.git
cd medeval-framework
pip install -e ".[all]"

🚀 Quickstart

1. Command Line Interface (CLI)

Run evaluations directly from your terminal:

# Check version and available flags
medeval --version
medeval --help

# Evaluate OpenAI GPT-4o on MedQA
export OPENAI_API_KEY="your-api-key"
medeval --model gpt-4o --dataset medqa --limit 20 --output report.json

# Evaluate Claude 3.5 Sonnet or Llama 3.1 via AgentRouter with custom API flags
medeval \
  --model "agentrouter:claude-3-5-sonnet" \
  --api-key "your_agentrouter_key" \
  --api-base-url "https://agentrouter.ai/v1" \
  --dataset medqa \
  --output report_claude.html

# Evaluate a specialized PEFT adapter filtered specifically for Sickle Cell questions
medeval \
  --model "TeslaInch/scd-phi35-adapter-v8" \
  --dataset medqa \
  --topic "sickle" \
  --output sickle_cell_report.md

CLI Options Reference

Flag Description Default
--model (required) Model ID (HuggingFace repo, PEFT adapter, gpt-4o, agentrouter:..., openrouter:..., mock-...). -
--dataset (required) Benchmark dataset: medqa, pubmedqa, medmcqa, or mmlu_medical. -
--output (required) Target report filepath (.json, .md, or .html). -
--topic Filter dataset by topic keyword (e.g. sickle, cardiac, renal, diabetes). All
--api-key API Key override for OpenAI, AgentRouter, or OpenRouter models. Env var
--api-base-url Base URL override (e.g. https://agentrouter.ai/v1). Env var
--safety Safety audit checker: sickle_cell (default) or none. sickle_cell
--device PyTorch execution device (cpu, cuda:0, etc.). cpu
--limit Maximum number of samples to evaluate. All
--trust-remote-code Enable trust_remote_code=True for Hugging Face models. False

2. Python Orchestration API

Build custom evaluation pipelines in Python:

from medeval.benchmark import BenchmarkLoader
from medeval.models.openai_connector import OpenAIConnector
from medeval.runner import BenchmarkRunner
from medeval.safety import SickleCellSafetyChecker
from medeval.hallucination import NLIHallucinationDetector
from medeval.scorers import ExactMatchScorer, SemanticSimilarityScorer
from medeval.report import export_report_to_html, export_report_to_markdown

# 1. Load dataset with topic filtering (e.g. Cardiology questions)
loader = BenchmarkLoader(split="test", max_samples=20, topic="cardiac")
samples = loader.load_medqa()

# 2. Instantiate Model Connector (API Router or HuggingFace model)
model = OpenAIConnector(model_name="claude-3-5-sonnet", base_url="https://agentrouter.ai/v1")

# 3. Configure Metrics, Safety Checkers & Checkpointing
scorers = [
    ExactMatchScorer(),
    SemanticSimilarityScorer(model_name="microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract"),
]
hallucination_detector = NLIHallucinationDetector(model_name="pritamdeka/PubMedBERT-MNLI-MedNLI")

runner = BenchmarkRunner(
    model=model,
    scorers=scorers,
    safety_checker=SickleCellSafetyChecker(),
    hallucination_detector=hallucination_detector,
    checkpoint_dir="./checkpoints",  # Enables instant resume capability!
    ignore_errors=True,
)

# 4. Execute Benchmark
report = runner.run(samples)

# 5. Export report as styled Markdown or HTML dashboard
export_report_to_markdown(report, "cardiology_report.md")
export_report_to_html(report, "cardiology_report.html")

3. Multi-Model Side-by-Side Comparison

Compare base models, fine-tuned adapters, and SOTA models in Python:

from medeval.comparison import export_comparison_to_markdown, load_reports_from_files

# Load evaluation reports
reports = load_reports_from_files(
    ["base_model_report.json", "sickle_cell_adapter_report.json", "sota_claude_report.json"]
)

# Export side-by-side comparative Markdown matrix
export_comparison_to_markdown(reports, "model_comparison_matrix.md")

📁 Repository Structure

medeval/
├── medeval/
│   ├── models/               # Model Connectors (HF, PEFT, OpenAI, AgentRouter, Mock)
│   ├── safety/               # Safety Checkers (SickleCell, Cardiology, Semantic, SafetySuite)
│   ├── accuracy.py           # Scorers (Exact Match, BERTScore F1)
│   ├── benchmark.py          # Loaders (MedQA, PubMedQA, MedMCQA, MMLU-Medical)
│   ├── calibration.py        # Calibration Suite (ECE, MCE, Brier Score)
│   ├── comparison.py         # Multi-Model Side-by-Side Comparison Engine
│   ├── hallucination.py      # NLI Cross-Encoder Hallucination Engine
│   ├── report.py             # Metric aggregation (JSON, Markdown, HTML exporters)
│   ├── runner.py             # BenchmarkRunner pipeline orchestrator
│   └── structures.py         # Data contracts (MedicalEvalSample & EvaluationReport)
├── tests/                    # 46 Unit & Integration Tests
├── pyproject.toml            # Ruff & Mypy configurations
├── setup.py                  # PyPI Packaging configuration
└── requirements.txt          # Package dependencies

🧪 Development & Testing

Ensure style alignment and type safety before submitting pull requests:

# Run full pytest test suite
pytest

# Run Ruff style & linting check
ruff check .

# Run Mypy static type verification
mypy medeval/

📄 License

This project is licensed under the Apache License 2.0. See the LICENSE file for details.

Metadata

Release files for medeval-framework 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for medeval-framework 0.2.1
File Size Uploaded Provenance
medeval_framework-0.2.1.tar.gz 87.4 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for medeval-framework 0.2.1
File Interpreter ABI Platform
medeval_framework-0.2.1-py3-none-any.whl Python 3 none any Details

Total release size: 159.4 kB

Release files / medeval_framework-0.2.1.tar.gz

Download URL medeval_framework-0.2.1.tar.gz
Size 87.4 kB
Tags Source
SHA-256 checksum
How to use checksums
39cb42dddb51bf59693ba8d07bcfc9a21827465f10753de0429d354c5cd6b1ec
BLAKE2b-256 checksum
How to use checksums
a4b38bee038f1cfbba8affd50798c00f387fccbee197a0f6d4990606ed3eee82
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 21, 2026.

Transparency log

Release files / medeval_framework-0.2.1-py3-none-any.whl

Download URL medeval_framework-0.2.1-py3-none-any.whl
Size 72.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
39c0682c96dd219d177ffb24332ea6956e3038e13077522bd9b5a163f0d4f06d
BLAKE2b-256 checksum
How to use checksums
354d5e65b40e8b18b7a1ba82be15152aebad64d582614a9345ea526d92d511ac
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 21, 2026.

Transparency log

Security for medeval-framework 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for medeval_framework-0.2.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 21, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page