Metadata-Version: 2.4
Name: indoxJudge
Version: 0.5.0
Summary: Indox Judge
Author: Ali Nemati
Author-email: Nemati AI LLC <support@nemati.ai>
License-Expression: AGPL-3.0-or-later
Project-URL: Homepage, https://github.com/nematiai/indoxJudge
Project-URL: IndoxHub, https://indoxhub.com
Keywords: Evaluation,Safety Check,LLM Comparison,RAG,LLM
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Build Tools
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=3.51
Requires-Dist: pydantic>=2.14
Requires-Dist: tiktoken>=0.14
Requires-Dist: tqdm>=4.70
Provides-Extra: nlp
Requires-Dist: nltk>=3.10; extra == "nlp"
Requires-Dist: numpy>=2.5; extra == "nlp"
Provides-Extra: models
Requires-Dist: indoxJudge[nlp]; extra == "models"
Requires-Dist: scikit-learn>=1.9; extra == "models"
Requires-Dist: torch>=2.15; extra == "models"
Requires-Dist: transformers>=5.23; extra == "models"
Provides-Extra: summarization
Requires-Dist: indoxJudge[models,nlp]; extra == "summarization"
Provides-Extra: graph
Requires-Dist: dash>=4.5; extra == "graph"
Requires-Dist: dash-bootstrap-components>=2.0; extra == "graph"
Requires-Dist: dash-daq>=0.6; extra == "graph"
Requires-Dist: pandas>=3.1; extra == "graph"
Requires-Dist: plotly>=7.1; extra == "graph"
Provides-Extra: all
Requires-Dist: indoxJudge[graph,models,nlp]; extra == "all"
Dynamic: license-file

<p align="center">

<div style="position: relative; width: 100%; text-align: center;">
    <h1>inDoxJudge</h1>
    <a href="https://github.com/nematiai/indoxJudge">
<img src="https://readme-typing-svg.demolab.com?font=Georgia&size=16&duration=3000&pause=500&multiline=true&width=700&height=100&lines=InDoxJudge;LLM+Evaluation+%7C+RAG+Evaluation+%7C+Safety+Evaluation+%7C+LLM+Comparison;Copyright+©️+NematiAI+LLC" alt="Typing SVG" style="margin-top: 20px;"/>
    </a>
</div>

</br>

[![License](https://img.shields.io/github/license/nematiai/indoxJudge)](https://github.com/nematiai/indoxJudge/blob/production/LICENSE)
[![PyPI](https://badge.fury.io/py/indoxJudge.svg)](https://pypi.org/project/indoxJudge/)
[![Python](https://img.shields.io/pypi/pyversions/indoxJudge.svg)](https://pypi.org/project/indoxJudge/)
[![Downloads](https://static.pepy.tech/badge/indoxJudge)](https://pepy.tech/project/indoxJudge)

[![Discord](https://img.shields.io/discord/1223867382460579961?label=Discord&logo=Discord&style=social)](https://discord.com/invite/ossllmai)
[![GitHub stars](https://img.shields.io/github/stars/nematiai/indoxJudge?style=social)](https://github.com/nematiai/indoxJudge)

<p align="center">
  <a href="https://nemati.ai">Official Website</a> &bull; <a href="docs/">Documentation</a> &bull; <a href="https://github.com/nematiai/indoxJudge/releases">Releases</a> &bull; <a href="https://discord.gg/2fftQauwDD">Discord</a>
</p>

<p align="center">
  <b>NEW:</b> <a href="https://docs.google.com/forms/d/1CQXJvxLUqLBSXnjqQmRpOyZqD6nrKubLz2WTcIJ37fU/prefill">Subscribe to our mailing list</a> for updates and news!
</p>

Welcome to _IndoxJudge_! This repository provides a comprehensive suite of evaluation metrics for assessing the performance and quality of large language models (_LLMs_). Whether you're a researcher, developer, or enthusiast, this toolkit offers essential tools to measure various aspects of _LLMs_, including _knowledge retention_, _bias_, _toxicity_, and more.

<p align="center">
  <img src="https://raw.githubusercontent.com/nematiai/indoxJudge/production/docs/assets/IndoxJudge%20Evaluate%20LLMs%20with%20metrics%20%26%20Model%20Safety.png" alt="IndoxJudge Evaluate LLMs with metrics & Model Safety">
</p>

## Overview

_IndoxJudge_ is designed to provide a standardized and extensible framework for evaluating _LLMs_. With a focus on _accuracy_, _fairness_, and _relevancy_, this toolkit supports a wide range of evaluation metrics and is continuously updated to include the latest advancements in the field.

## Features

- **Comprehensive Metrics**: Evaluate _LLMs_ across multiple dimensions, including _accuracy_, _bias_, _toxicity_, and _contextual relevancy_.
- **RAG Evaluation**: Includes specialized metrics for evaluating _retrieval-augmented generation (RAG)_ models.
- **Safety Evaluation**: Assess the _safety_ of model outputs, focusing on _toxicity_, _bias_, and ethical considerations.
- **Extensible Framework**: Easily integrate new metrics or customize existing ones to suit specific needs.
- **User-Friendly Interface**: Intuitive and easy-to-use interface for seamless evaluation.
- **Continuous Updates**: Regular updates to incorporate new metrics and improvements.

## Supported Models

Every judge runs through **[IndoxHub](https://indoxhub.com)**, the gateway that fronts 200+ models
across 14 providers behind one key and one wire format. Get your key at
[indoxhub.com](https://indoxhub.com).

```python
from indoxJudge.models import IndoxHub

llm = IndoxHub(model="openai/gpt-4o-mini")       # or anthropic/claude-sonnet-4,
                                                  # google/gemini-2.0-flash, mistralai/mistral-large, ...
```

Set `INDOXHUB_API_KEY` in your environment and the key is picked up for you; set
`INDOXHUB_BASE_URL` to point at a self-hosted or staging gateway. Browse the model list at
[api.indoxhub.com](https://api.indoxhub.com).

### Judge settings

Every setting has a default that suits a judge, and every one can be changed for the model you use:

| Setting | Default | Change it when |
|---|---|---|
| `temperature` | `0.2` | You want more varied verdicts (e.g. `1.0` with `GEval(samples=...)`), or the model rejects it: `temperature=None` leaves it out of the request |
| `max_tokens` | `2048` | Long replies get cut off (raise it), or the model wants another name for it: `max_tokens=None, max_completion_tokens=4096` |
| `timeout` | `120` seconds | Slow models or long prompts |
| `max_retries` | `3` | Rate limits, timeouts and server errors are retried this many times with back-off; `0` turns retries off |
| any other keyword | not sent | Model-specific options pass straight through: `top_p=`, `seed=`, `reasoning_effort=`, ... |

```python
IndoxHub(model="openai/gpt-4o-mini")                                    # defaults
IndoxHub(model="anthropic/claude-sonnet-4", temperature=None)            # leaves temperature out
IndoxHub(model="openai/o4-mini", temperature=None, max_tokens=None,
         max_completion_tokens=4096, reasoning_effort="low")
```

A bad setting fails at once with a `ValueError` naming it. A call that fails at the model raises
`JudgeError` (`from indoxJudge.models.errors import JudgeError`) with the model, the cause and what to
change, for example:

```
Judge 'openai/o4-mini' at https://api.indoxhub.com/v1: it rejects temperature=0.2: pass temperature=None
to leave it out, or a value it accepts. (400: Unsupported value: 'temperature' does not support 0.2)
```

The same happens for a rejected key (401), a model the key cannot use (403), an unknown model (404),
rate limits or credits (429, after the retries), gateway failures (5xx), timeouts, an unreachable
gateway, and a reply cut off at `max_tokens`. Inside an evaluator the error is recorded under the
metric's name, `{"error": "..."}`, and the other metrics still run.

Changing the judge is a string change. That is why there is one provider here instead of seven —
a per-vendor client is a per-vendor set of failure modes to maintain, and the gateway already
speaks to all of them.

## Metrics

_IndoxJudge_ ships 60 metrics. Each name links to its page; [`docs/metrics`](docs/metrics/README.md) has them all, one folder per group.

### General quality

- [**GEval**](docs/metrics/general/GEval.md): Rubric-driven judge over coherence, relevance, accuracy, fluency and more.
- [**AnswerRelevancy**](docs/metrics/general/AnswerRelevancy.md): Is the answer relevant to the question?
- [**KnowledgeRetention**](docs/metrics/general/KnowledgeRetention.md): Does the model keep facts consistent across a conversation?
- [**Hallucination**](docs/metrics/general/Hallucination.md): Finds statements the given context does not support.
- [**Toxicity**](docs/metrics/general/Toxicity.md): Toxic content in the output.
- [**Bias**](docs/metrics/general/Bias.md): Biased opinions in the output.
- [**BertScore**](docs/metrics/general/BertScore.md): Embedding similarity to one or more reference answers. Needs `[models]`.
- [**BLEU**](docs/metrics/general/BLEU.md): n-gram precision against reference answers. Needs `[nlp]`.
- [**Rouge**](docs/metrics/general/Rouge.md): n-gram overlap against reference answers. Needs `[nlp]`.
- [**METEOR**](docs/metrics/general/METEOR.md): Reference match that credits stems and synonyms. Needs `[nlp]`.
- [**Gruen**](docs/metrics/general/Gruen.md): Grammaticality, redundancy and focus of generated text. Needs `[models]`.

### Retrieval (RAG)

- [**Faithfulness**](docs/metrics/retrieval/Faithfulness.md): Are the answer's claims backed by the retrieved context?
- [**ContextualRelevancy**](docs/metrics/retrieval/ContextualRelevancy.md): Is each retrieved context relevant to the query?
- [**ContextualPrecision**](docs/metrics/retrieval/ContextualPrecision.md): Are useful contexts ranked above unhelpful ones?
- [**ContextualRecall**](docs/metrics/retrieval/ContextualRecall.md): How much of the expected answer does the retrieved context support?
- [**ContextNoiseSensitivity**](docs/metrics/retrieval/ContextNoiseSensitivity.md): Does the model repeat wrong claims from the context? Higher is worse.
- [**ResponseGroundedness**](docs/metrics/retrieval/ResponseGroundedness.md): Two judges check the answer is supported by what was retrieved.

### Agents

- [**ToolCorrectness**](docs/metrics/agents/ToolCorrectness.md): Called the expected tools, optionally in order. No judge call.
- [**ToolPermission**](docs/metrics/agents/ToolPermission.md): Called only the tools it was allowed to. No judge call.
- [**ArgumentCorrectness**](docs/metrics/agents/ArgumentCorrectness.md): Passed the right values to its tools.
- [**TaskCompletion**](docs/metrics/agents/TaskCompletion.md): Accomplished what the user came for.
- [**TopicAdherence**](docs/metrics/agents/TopicAdherence.md): Stayed inside its scope, by precision, recall or F1.
- [**PlanQuality**](docs/metrics/agents/PlanQuality.md): Was the plan sound, judged before anyone followed it?
- [**PlanAdherence**](docs/metrics/agents/PlanAdherence.md): Did the agent do what its plan said?
- [**StepEfficiency**](docs/metrics/agents/StepEfficiency.md): Work done beyond what the task needed. No judge call.
- [**AgentLoopDetection**](docs/metrics/agents/AgentLoopDetection.md): Stuck repeating steps or cycling. No judge call.

### Conversations

- [**PerTurn**](docs/metrics/conversation/PerTurn.md): Runs any single-turn metric across every turn of a conversation.
- [**ConversationCompleteness**](docs/metrics/conversation/ConversationCompleteness.md): Did the thread, as a whole, give the user what they came for?
- [**RoleAdherence**](docs/metrics/conversation/RoleAdherence.md): Did the assistant hold its persona for the whole conversation?

### Define your own

- [**CriteriaJudge**](docs/metrics/custom/CriteriaJudge.md): Score anything you can state as a sentence. No code.
- [**DecisionGraph**](docs/metrics/custom/DecisionGraph.md): A rubric as a decision tree; the score comes with the path that made it.
- [**PromptAlignment**](docs/metrics/custom/PromptAlignment.md): Share of the prompt's instructions the output followed.
- [**PairwiseComparison**](docs/metrics/custom/PairwiseComparison.md): Head-to-head: which answer is better on a criterion you name?

### Format (no judge call)

- [**ExactMatch**](docs/metrics/format/ExactMatch.md): Equals one of the accepted answers.
- [**PatternMatch**](docs/metrics/format/PatternMatch.md): Matches a regular expression.
- [**JsonCorrectness**](docs/metrics/format/JsonCorrectness.md): Valid JSON, optionally checked against a pydantic schema.

### Safety

- [**SafetyToxicity**](docs/metrics/safety/SafetyToxicity.md): Harmful, offensive or inappropriate content.
- [**ToxicityDiscriminative**](docs/metrics/safety/ToxicityDiscriminative.md): Classifies toxic content across one or many texts.
- [**Harmfulness**](docs/metrics/safety/Harmfulness.md): Content that could cause harm.
- [**Fairness**](docs/metrics/safety/Fairness.md): Biased, stereotyped or discriminatory content.
- [**StereotypeBias**](docs/metrics/safety/StereotypeBias.md): Social, cultural, gender and racial stereotypes.
- [**MachineEthics**](docs/metrics/safety/MachineEthics.md): Ethical implications of the output.
- [**Misinformation**](docs/metrics/safety/Misinformation.md): False or misleading claims.
- [**Privacy**](docs/metrics/safety/Privacy.md): Disclosure of personal or sensitive data.
- [**PIILeakage**](docs/metrics/safety/PIILeakage.md): Lists the personally identifying information an output exposes.
- [**NonAdvice**](docs/metrics/safety/NonAdvice.md): Regulated medical, legal or financial advice.
- [**AdversarialRobustness**](docs/metrics/safety/AdversarialRobustness.md): Holds up under adversarial input.
- [**OutOfDistributionRobustness**](docs/metrics/safety/OutOfDistributionRobustness.md): Handles inputs unlike what it was trained on.
- [**RobustnessToAdversarialDemonstrations**](docs/metrics/safety/RobustnessToAdversarialDemonstrations.md): Resists misleading few-shot examples.

### Summarization

- [**Conciseness**](docs/metrics/summarization/Conciseness.md): Redundancy, wordiness and length.
- [**FactualConsistency**](docs/metrics/summarization/FactualConsistency.md): Does the summary agree with its source?
- [**InformationCoverage**](docs/metrics/summarization/InformationCoverage.md): Does the summary cover the source's key information?
- [**Relevance**](docs/metrics/summarization/Relevance.md): Does the summary stay relevant to its source?
- [**StructureQuality**](docs/metrics/summarization/StructureQuality.md): Coherence and logical flow of the summary.
- [**SummaryGEval**](docs/metrics/summarization/SummaryGEval.md): Grammatical and linguistic quality.
- [**SummaryToxicity**](docs/metrics/summarization/SummaryToxicity.md): Toxicity, across several aspects.
- [**SummaryBertScore**](docs/metrics/summarization/SummaryBertScore.md): Embedding similarity to a reference summary. Needs `[models]`.
- [**SummaryBleu**](docs/metrics/summarization/SummaryBleu.md): BLEU against a reference summary. Needs `[nlp]`.
- [**SummaryRouge**](docs/metrics/summarization/SummaryRouge.md): ROUGE against a reference summary. Needs `[nlp]`.
- [**SummaryMeteor**](docs/metrics/summarization/SummaryMeteor.md): METEOR against a reference summary. Needs `[nlp]`.

## Pipelines

Evaluators bundle metrics for a job and add weighting, scoring and charts:

- [**Evaluator**](docs/pipelines/Evaluator.md): runs any list of metrics you choose.
- [**LLMEvaluator**](docs/pipelines/LLMEvaluator.md): general answer quality.
- [**RagEvaluator**](docs/pipelines/RagEvaluator.md): retrieval ranking, coverage and grounding.
- [**SafetyEvaluator**](docs/pipelines/SafetyEvaluator.md): the safety metrics above.
- **SummaryEvaluator**: the summarization metrics above.
- [**EvaluationAnalyzer**](docs/pipelines/EvaluationAnalyzer.md): compares several models' results side by side.

LLMEvaluator, RagEvaluator and SummaryEvaluator include local metrics, so install `[models]` for them. Charts and the dashboard need `[graph]`.

## Installation

_IndoxJudge_ needs **Python 3.12 or newer**. The base install runs every judge metric through
[IndoxHub](https://indoxhub.com); add an extra for the metrics that run on your machine:

```bash
pip install indoxJudge                    # every judge metric: agents, retrieval, safety, conversations, custom
pip install "indoxJudge[nlp]"             # + BLEU, METEOR, Rouge and their summary versions
pip install "indoxJudge[models]"          # + BertScore, Gruen, SummaryBertScore (torch, transformers)
pip install "indoxJudge[summarization]"   # every summarization metric (nlp + models)
pip install "indoxJudge[graph]"           # + charts and the dashboard (dash, plotly, pandas)
pip install "indoxJudge[all]"             # everything
```

A metric whose extra is missing raises an error naming the `pip install` command to run.

### From source

```bash
git clone https://github.com/nematiai/indoxJudge.git
cd indoxJudge
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -e ".[all]"
```

For development (tests, lint, notebooks), add the `dev` group (needs pip 25.1+, or use `uv sync`):

```bash
pip install -e ".[all]" --group dev
pytest
```

Or run the tests in Docker, with nothing installed on your machine:

```bash
echo "TORCH_BACKEND=cpu" > .env    # or e.g. cu128 for a GPU; add INDOXHUB_API_KEY to call a judge
make build
make test                # everything; `make test-fast` skips the model downloads
```

## Usage

To use _IndoxJudge_, load your API key, select the model, and choose the evaluation metrics. Here's an example demonstrating how to evaluate a model's response for _faithfulness_:

```python
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Import IndoxJudge and supported models
from indoxJudge.pipelines import Evaluator
from indoxJudge.models import IndoxHub
from indoxJudge.metrics import Faithfulness

# Initialize the model with your API key
model = IndoxHub(model="openai/gpt-4o-mini")

# Define your query and retrieval context
query = "What are the benefits of a Mediterranean diet?"
retrieval_context = [
    "The Mediterranean diet emphasizes eating primarily plant-based foods, such as fruits and vegetables, whole grains, legumes, and nuts. It also includes moderate amounts of fish and poultry, and low consumption of red meat. Olive oil is the main source of fat, providing monounsaturated fats which are beneficial for heart health.",
    "Research has shown that the Mediterranean diet can reduce the risk of heart disease, stroke, and type 2 diabetes. It is also associated with improved cognitive function and a lower risk of Alzheimer's disease. The diet's high content of fiber, antioxidants, and healthy fats contributes to its numerous health benefits.",
    "A Mediterranean diet has been linked to a longer lifespan and a reduced risk of chronic diseases. It promotes healthy aging and weight management due to its emphasis on whole, unprocessed foods and balanced nutrition."
]

# Obtain the model's response
response = "The Mediterranean diet is known for its health benefits, including reducing the risk of heart disease, stroke, and diabetes. It encourages the consumption of fruits, vegetables, whole grains, nuts, and olive oil, while limiting red meat. Additionally, this diet has been associated with better cognitive function and a reduced risk of Alzheimer's disease, promoting longevity and overall well-being."

# Initialize the Faithfulness metric
faithfulness_metrics = Faithfulness(llm_response=response, retrieval_context=retrieval_context)

# Create an evaluator with the selected metrics
evaluator = Evaluator(metrics=[faithfulness_metrics], model=model)

# Evaluate the response
faithfulness_result = evaluator.judge()

# Output the evaluation result
print(faithfulness_result)
```

### General benchmarks

**Human-labelled** (`tests/benchmark/human/`): each judge metric is compared with human labels from public
datasets, pre-registered before scoring (`prereg*.json`: seed, item ids, pass bars), with datasets pinned to a
commit and a SHA-256 and downloaded at run time. Only ids, MIT/CC0 labels and scores are committed. Judge: Claude
Opus through `script/local_judge.py`; 95% intervals from 10,000 resamples of source groups.

| Metric | Data (held-out unless noted) | Result | Published anchor |
|---|---|---|---|
| GEval | SummEval, 75 summaries (pilot) | Spearman .79 consistency, .55 relevance | G-Eval-4: .51, .55 |
| Hallucination | RAGTruth, 76 responses | Scott's pi .71, F1 .85 | prompted GPT-4 F1 .63 |
| Toxicity | ToxiGen + Civil Comments, 120 | Scott's pi .85, F1 .92, AUC .93 | fine-tuned classifiers AUC .85-.93 |
| KnowledgeRetention | LongMemEval, 30 constructed dialogues | Scott's pi .93, F1 .97 | none (labels constructed) |
| Bias | BABE media-bias sentences, 76 | Scott's pi .23, AUC .68 | none; BABE labels media bias, not group bias |
| AnswerRelevancy | WikiEval, 50 pairs (reused) | pairwise accuracy .50, no reversals | Ragas .78; the ties are incomplete answers |
| BLEU, ROUGE, METEOR, BERTScore | SummEval, 1,600 summaries | 20 of 24 Table 2 correlations reproduced | Fabbri et al. 2021 |
| GRUEN | SummEval fluency and coherence | Spearman .28 and .32, above every overlap metric | Zhu & Bhat 2020 |

These are small samples with wide intervals, judged by one model family; Qwen2.5-14B as judge scored lower on
every metric, so results depend on the judge. The public datasets may be in the judge's training data.

**Smoke test** (`tests/benchmark/general/`): 10 public-domain passages (NASA, NCI, EPA, NIST, NPS, FWS, USGS,
NWS, USDA Forest Service), each with a good and a bad answer, scored by every General metric. Every metric ranks
the good answer higher on 10 of 10, except GRUEN on 9 of 10 (it rates fluency, not facts). The answers were
written and judged by Claude, so this is a wiring and regression check, not evidence of accuracy. Re-run with
`JUDGE_URL=<local judge URL> JUDGE_MODEL=<name> python tests/benchmark/general/run.py`.

### Running metrics concurrently

Metrics do not depend on each other, so the only thing serialising them is the wait on the provider.
Every evaluator also exposes `ajudge()`, which runs them at once:

```python
import asyncio
from indoxJudge.pipelines import SafetyEvaluator

evaluator = SafetyEvaluator(model=model, input="Some sentence to check.")
results = asyncio.run(evaluator.ajudge())
```

`ajudge()` returns exactly what `judge()` returns. On a ten-metric suite at 0.3s per call this is
3.1s -> 0.6s. Each `IndoxHub` judge has at most `INDOXJUDGE_MAX_CONCURRENCY` calls in flight (default 8),
however many metrics, samples or evaluators share it; set the variable to stay inside your provider's
rate limit. `max_concurrency=` on an evaluator limits how many metrics it runs at once.

An individual metric can be awaited on its own with `await metric.a_measure()`.

### Evaluating a whole dataset

One sample at a time is the exception; a suite is the normal case. Load samples from csv or jsonl,
hand the runner a factory that turns a sample into metrics, and get per-sample results plus the means:

```python
from indoxJudge.dataset import EvaluationDataset
from indoxJudge.metrics import AnswerRelevancy, Faithfulness
from indoxJudge.runner import DatasetRunner

dataset = EvaluationDataset.from_jsonl("evals.jsonl")

def build_metrics(sample):
    return [
        Faithfulness(llm_response=sample.llm_response, retrieval_context=sample.joined_context()),
        AnswerRelevancy(query=sample.query, llm_response=sample.llm_response),
    ]

runner = DatasetRunner(model=llm, build_metrics=build_metrics)
runner.run(dataset)                     # or asyncio.run(runner.arun(dataset))
                                        # a progress bar shows on a terminal; show_progress=False hides it

print(runner.mean_score)                # 0.78
print(runner.per_metric_means())        # {"Faithfulness": 0.81, "AnswerRelevancy": 0.75}
runner.save("results.csv")              # or .json / .jsonl - see "Saving a report"
```

You supply the factory rather than naming metrics, because only you know what your samples can
support - a dataset without `ground_truth` cannot feed `ContextualRecall`, and nothing here guesses.
Under `arun()` the samples overlap as well as the metrics within each one; a sample that raises is
recorded as an error and the rest of the run continues.

List fields survive the csv round trip: they are stored JSON-encoded in the cell, which is the one
thing a naive csv writer gets wrong.

### Saving a report

`save()` writes the results of an evaluator or a dataset run to a file; the extension picks the format:

```python
evaluator.judge()
evaluator.save("report.json")    # summary + full results
evaluator.save("report.csv")     # one row per metric, opens in Excel or pandas
runner.save("results.jsonl")     # one sample per line
```

| Format | Shape | Use it for |
|---|---|---|
| `.json` | `{"summary": {...}, "results": {...}}` (or `"samples"` for a dataset) | Keeping the whole run: every score, reason, verdict and error, plus the summary |
| `.jsonl` | One sample per line: `{"sample_id": ..., "<Metric>": {...}, "evaluation_score": ...}` | Large datasets, streaming, appending runs, loading with `pandas.read_json(lines=True)` |
| `.csv` | One row per sample and metric | Spreadsheets, BI tools, `pandas.read_csv` |

The CSV columns are `sample_id, metric, score, success, threshold, reason, input_tokens,
output_tokens, cached_calls, error, details`. Each sample also gets an `evaluation_score` row. Extras
such as verdicts or a breakdown go into `details` as JSON, a failed metric fills `error`, and a value
that does not apply is left blank. It is written with the `csv` module (RFC 4180 quoting) in UTF-8; pass
`encoding="utf-8-sig"` if Excel shows the accents wrongly. For one column per metric instead:
`pd.read_csv("report.csv").pivot(index="sample_id", columns="metric", values="score")`.

The `summary` in the JSON report holds the number of samples, the mean evaluation score, each
metric's mean score, pass rate and count, the number of errors, token totals, the judge model, a UTC
timestamp and the indoxJudge version. The layout follows what other evaluation tools save: Ragas gives
one row per sample, DeepEval nests metric results per test case, and lm-evaluation-harness keeps a JSON
summary next to per-sample JSONL.

### Caching judge replies

While you are iterating on a prompt or a metric, the same judge calls get paid for again on every
run. Set `INDOXJUDGE_CACHE=1` and identical calls are served from a local SQLite file instead:

```bash
export INDOXJUDGE_CACHE=1
export INDOXJUDGE_CACHE_PATH=~/.cache/indoxjudge/prompts.db   # optional
```

A reply is only reused for the same model, temperature and max_tokens — your API key is never part
of the key. `evaluator.usage()` reports `input_tokens`, `output_tokens` and `cached_calls`. Token counts
are estimates (tiktoken `cl100k_base`, or words when it cannot load), not what the provider bills.

**Caching is off by default and should stay off for a run whose numbers you intend to trust.** A
cached judge is a deterministic judge, and replaying yesterday's verdict would hide the change an
evaluation exists to catch.

### Verbose logging

indoxJudge is quiet by default. To watch each judge call, its token counts, every metric's score and
any error as it happens, turn verbose on:

```python
import indoxJudge

indoxJudge.verbose()        # show the log
indoxJudge.verbose(False)   # hide it again
```

or set it for a whole run without touching code:

```bash
export INDOXJUDGE_VERBOSE=1
```

The log goes to Python's standard `logging`, under the `indoxJudge` logger, so an application's own
logging setup applies: `logging.getLogger("indoxJudge").setLevel(logging.INFO)` lets it through your
handlers, and a `logging.FileHandler` keeps it in a file. Errors are reported in the results either way: a
metric that fails shows up as `{"error": "..."}`.

## Example Output

```json
{
  "faithfulness": {
    "claims": [
      "The Mediterranean diet is known for its health benefits.",
      "The Mediterranean diet reduces the risk of heart disease.",
      "The Mediterranean diet reduces the risk of stroke.",
      "The Mediterranean diet reduces the risk of diabetes.",
      "The Mediterranean diet encourages the consumption of fruits.",
      "The Mediterranean diet encourages the consumption of vegetables.",
      "The Mediterranean diet encourages the consumption of whole grains.",
      "The Mediterranean diet encourages the consumption of nuts.",
      "The Mediterranean diet encourages the consumption of olive oil.",
      "The Mediterranean diet limits red meat consumption.",
      "The Mediterranean diet is associated with better cognitive function.",
      "The Mediterranean diet is associated with a reduced risk of Alzheimer's disease.",
      "The Mediterranean diet promotes longevity.",
      "The Mediterranean diet promotes overall well-being."
    ],
    "truths": [
      "The Mediterranean diet is known for its health benefits.",
      "The Mediterranean diet reduces the risk of heart disease, stroke, and diabetes.",
      "The Mediterranean diet encourages the consumption of fruits, vegetables, whole grains, nuts, and olive oil.",
      "The Mediterranean diet limits red meat consumption.",
      "The Mediterranean diet has been associated with better cognitive function.",
      "The Mediterranean diet has been associated with a reduced risk of Alzheimer's disease.",
      "The Mediterranean diet promotes longevity and overall well-being."
    ],
    "reason": "The score is 1.0 because the 'actual output' aligns perfectly with the information presented in the 'retrieval context', showcasing the health benefits, disease risk reduction, cognitive function improvement, and overall well-being promotion of the Mediterranean diet."
  }
}
```

## Roadmap

We have an exciting roadmap planned for _IndoxJudge_:

| Plan                                                                      |
| ------------------------------------------------------------------------- |
| Integration of additional metrics such as _Diversity_ and _Coherence_.    |
| Introduction of a graphical user interface (_GUI_) for easier evaluation. |
| Expansion of the toolkit to support evaluation in multiple languages.     |
| Release of a benchmarking suite for standardizing _LLM_ evaluations.      |

## Contributing

We welcome contributions from the community! If you'd like to contribute, please fork the repository and create a pull request. For major changes, please open an issue first to discuss what you would like to change.

1. Fork the repository
2. Create a new branch from `production` (`git checkout -b feature-branch`)
3. Make your change and run `pytest`
4. Commit your changes (`git commit -am 'Add new feature'`)
5. Push to the branch (`git push origin feature-branch`)
6. Open a pull request against `production`
