# RefChecker

RefChecker provides a standardized assessment framework to identify subtle hallucinations present in the outputs of large language models (LLMs). 
<p align="center">
  <img src="imgs/framework.png" alt="RefChecker Framework" 
  style="width:800px">
  <br>
  <b>Figure</b>: RefChecker Framework
</p>

## 🌟 Highlighted Features

- **Finer granularity** - RefChecker breakdowns the claims in the LLM’s response into [knowledge triplets](#granularity), as opposed to paragraph, sentence or sub-sentence. Detecting at knowledge triplets will test the truthfulness of facts. Importantly, this finer granularity subsumes other coarse granularity and is therefore more informative and precise. One can arbitrarily roll up the granularity ladder to derive coarse level metrics if needed.
- **Wider Coverage** - RefChecker differentiates [three distinctive settings](#setting_definitions) based on the quality and quantity of context provided for LLM’s response:
    1. Zero Context: the prompt is a factual question without any context (eg. Open QA).
    2. Noisy Context: the prompt is a question as well as a list of retrieved document (eg. RAG).
    3. Accurate Context: the prompt is a question as well as one document (eg. Summarization).
- **Human Evaluation** - RefChecker includes 2.1k [human annotated LLM’s responses](#benchmark_dataset) consist of 300 test samples, each responded by 7 popular LLMs: GPT4, GPT-3.5-Turbo, InstructGPT, Falcon (Falcon-40B-Instruct), Alpaca (Alpaca-7B), LLaMA2(70B-Chat) and Claude 2. We will release the data and results upon approval.
- **Modular Architecture** — RefChecker is a 3-stage pipeline, consisting of a claim extractor $E$, a hallucination checker $C$, and [aggregation rules](#aggregation) $\tau$. They can be invoked and configured individually from command-line. Other than the 3 core stages, there are 3 auxiliary components:
    1. human labeling tool (coming soon) to label claims,
    2. call to search engine for Zero Context setting
    3. a [localization model](#localization) to map each knowledge triple back to the corresponding snippets of the reference.

You can explore RefChecker in the following ways:

- **[Demo Website](#demo_website)** - Setup a website and check your responses with user interfaces. 
- **[Quick Start](#quick_start)** - Setup the environment and check your responses in a console.
- **[Automatic Checker](#automatic-hallucination-checker)** - Check our automatic hallucination checker with strong performance and efficiency.


<a id='demo_website'></a>
## 🤖️ Demo Website
<img src="imgs/demo.gif" alter="Demo" style="width:800px">

You can first setup a [demo website](./demo/) and then use the web UI to try RefChecker as the animation shows above. There are four steps to perform hallucination detection in it:

1. **Extract Triplets**: You can start with typing what you want to check in the top-left box. Then click the `Next Step` button on the right side. The checker will extract triplets in your text and show them in the bottom-left area.
2. **Gather Reference**: You can then add reference text in the top-right box and click the `Next Step` button. If you don’t have reference text, leave the box empty and click the button anyway. We will retrieve some references with the text to be checked using search engines.
3. **Fact Checking**: With the text to be checked and the retrieved reference text, the checker will perform fact checking then. The checking results will be shown in the bottom-left area, with ✅/❌/❓ indicating factual/hallucinatory/neutral. An overall factuality score will be given aside.
4. **Localization**: You can then click the `Next Step` button and the checker will perform triplet localization. You can click the button on the left of each triplet to see the localization result.


<a id='quick_start'></a>

## 🚀 Quick Start

### Setup Environment
First create a python environment using conda or virtualenv. Clone this repo and change path into the root directory. Then install:
```bash
pip install -e .
python -m spacy download en_core_web_sm
```

### Usage
We provide a command-line interface to run RefChecker in a console:

```
usage: refchecker-cli [-h] --input_path INPUT_PATH --output_path OUTPUT_PATH
                     [--cache_dir CACHE_DIR]
                     [--extractor_name {gpt4,claude2,mixtral,mistral}]
                     [--extractor_max_new_tokens EXTRACTOR_MAX_NEW_TOKENS]
                     [--checker_name {gpt4,claude2,nli,alignscore,repc}]
                     [--repc_classifier_name {svm,svm_ensemble,nn,nn_ensemble}]
                     [--retriever_name {google}]
                     [--aggregator_name {strict,soft,major}]
                     [--openai_key OPENAI_KEY]
                     [--anthropic_key ANTHROPIC_KEY]
                     [--aws_bedrock_region AWS_BEDROCK_REGION]
                     [--use_retrieval]
                     [--serper_api_key SERPER_API_KEY]
                     [{extract,check,extract-check}]

positional arguments:
  {extract,check,extract-check}
     extract:       Extract triplets from provided responses.
     check:         Check whether the provided triplets are factual.
     extract-check: Extract triplets and check whether they are factual.

options:
  -h, --help  show this help message and exit
  --input_path INPUT_PATH
              Input path to the json file.
  --output_path OUTPUT_PATH
              Output path to the result json file.
  --cache_dir CACHE_DIR
              Path to the cache directory. Default: ./.cache.
  --extractor_name {gpt4,claude2,mixtral,mistral}
              Model used for extracting triplets. Default: claude2.
  --extractor_max_new_tokens EXTRACTOR_MAX_NEW_TOKENS
              Max generated tokens of the extractor, set a larger value for longer documents. Default: 500
  --checker_name {gpt4,claude2,nli,alignscore,repc}
              Model used for checking whether the triplets are factual. Default: claude2.
  --repc_classifier_name {svm,svm_ensemble,nn,nn_ensemble}
              Classifier Model used for RepC checker, only valid when RepC checker is used.
              Default: nn_ensemble, neural network classifier with layer ensemble.
  --retriever_name {google}
              Model used for retrieving reference (currently only google is supported).
              Default: google.
  --aggregator_name {strict,soft,major}
              Aggregator used for aggregating the results from multiple triplets.
              Default: soft.
              *  strict: If any of the triplets is Contradiction, the response is
              Contradiction. If all of the triplets are Entailment, the response is
              Entailment. Otherwise, the response is Neutral.
              *  soft:   The ratio of each category is calculated.
              *  major:  The category with the most votes is selected.
  --openai_key OPENAI_KEY
              Path to the openai api key file. Required if openAI models are used.
  --anthropic_key ANTHROPIC_KEY
              Path to the Anthropic api key file. Required if the Anthropic Claude2
              api is used.
  --aws_bedrock_region AWS_BEDROCK_REGION
              AWS region where the Amazon Bedrock api is deployed. Required if the 
              Amazon Bedrock api is used.
  --use_retriever  
              Whether to use retrieval to find the reference for checking. Required
              if the reference field in input data is not provided.
  --serper_api_key SERPER_API_KEY
              Path to the serper api key file. Required if the google retriever is
              used.
```

To extract claim triplets from LLM-generated responses, do:
```bash
refchecker-cli extract \
  --input_path {INPUT_PATH} \
  --output_path {OUTPUT_PATH} \
  --extractor_name {gpt4,claude2,mixtral}
```

The input json file contains a list of
```json
{
   "response": "",  # required, the response to be checked
   "question": "",  # optional if the question is not important (e.g., in summarization)
   ...
}
```

In the output json file, each item is added with a `triplets` field, containing a list of `[head, relation, tail]`.

To check hallucinations at triplet level, do:
```bash
refchecker-cli check \
  --input_path {INPUT_PATH} \
  --output_path {OUTPUT_PATH} \
  --checker_name {gpt4,claude2,nli,alignscore} \
  --aggregator_name {strict,soft,major}
```

The input json file contains a list of
```json
{
   "response": "",  # required, the response to be checked
   "triplets": [
       ["head1", "relation1", "tail1"],
       ["head2", "relation2", "tail2"],
       ...
   ]                # required, the corresponding triplets of the response
   "reference": "", # optional if a retriever is used to get reference
   ...
}
```

In the output json file, each item is added with the following fields:
```json
{
   "Y": Union[str, dict],  # aggregated predictions on the whole response
   "ys": [
       "Entailment",
       "Neutral",
       "Contradiction",
       ...
   ]                # checker predictions on each triplet
   "reference": "", # added if a retriever is used to get reference
   ...
}
```

The format of aggregated predictions `Y` depends on the selected aggregator. It is a `str` as “Entailment”, “Neutral”, or “Contradiction” if `strict` or `major` aggregators are used. It is a `dict` containing ratios of each category if the `soft` aggregator is used. We additionally include a special category “Abstain” introduced in [Evaluation Metric](#evaluation-metric).

Note that the retriever is required in the zero-context setting, where no reference is provided by users. You can activate it by adding the `--use_retriever` flag and specifying `--retriever_name`. Currently we only support a google-based retriever. Feel free to try your own retrieval system and welcome to contribute.

For using the google retriever and/or the OpenAI models, you should provide corresponding API keys by specifying `--serper_api_key` and/or `--openai_key`.

Finally, you can use the whole extraction and checking pipeline by:
```bash
refchecker-cli extract-check \
  --input_path {INPUT_PATH} \
  --output_path {OUTPUT_PATH} \
  --extractor_name {gpt4,claude2,mixtral} \
  --checker_name {gpt4,claude2,nli,alignscore} \
  --aggregator_name {strict,soft,major} \
  <other optional flags>
```

You can try the command-line with example scripts and example input data [here](./example/).

## 🪪 License

The code in this project is licensed under the Apache-2.0 License.
