Skip to main content

Factuality Detection for Generative AI

Project description

Factuality Detection in Generative AI

This repository contains the source code and plugin configuration for our paper Factuality Detection in Generative AI: A Tool Augmented Framework for Multi-Task and Multi-Domain Scenarios.

Factool is a tool augmented framework for detecting factual errors of texts generated by large language models (e.g., ChatGPT).

Factool now supports 4 tasks:

  • knowledge-based QA: Factool detects factual errors in knowledge-based QA.
  • code generation: Factool detects execution errors in code generation.
  • mathematical reasoning: Factool detects calculation errors in mathematical reasoning.
  • scientific literature review: Factool detects hallucinated scientific literatures.

Installation

  • For General User

pip install factool
  • For Developer

git clone git@github.com:GAIR-NLP/factool.git
cd factool
pip install -e .

Quick Start:

Knowledge-based QA

Click to toggle contents of `code`
export OPENAI_API_KEY=...
export SERPER_API_KEY=...

where you can

  • get your OpenAI API key from here.
  • get your Serper API key from here.
from factool  import Factool

factool_instance = Factool("gpt-3.5-turbo")

inputs = [
            {
                "prompt": "Introduce Graham Neubig",
                "response": "Graham Neubig is a professor at MIT",
                "category": "kbqa",
                "entry_point": "answer_question",
            },
]
response_list = factool_instance.run(inputs)

print(response_list)

where

  • prompt: the prompt for the model to generate the response.
  • response: the response generated by the model.
  • category: the category of the task. it could be:
    • kbqa
    • code
    • math
    • sci
  • entry_point: The function name of the code snippet to be fact-checked in the response. Could be "null" if the response doesn't contain any code snippet.

The response_list should following the following format:

[
    {
        'prompt': prompt_1, 
        'response': response_1, 
        'category': 'kbqa', 
        'claims': [claim_11, claim_12, ..., claims_1n], 
        'queries': [[query_111, query_112], [query_121, query_122], ..[query_1n1, query_1n2]], 
        'evidences': [[evidences_11], [evidences_12], ..., [evidences_1n]], 
        'claim_level_factuality': [{claim_11, reasoning_11, error_11, correction_11, factuality_11}, {claim_12, reasoning_12, error_12, correction_12, factuality_12}, ..., {claim_1n, reasoning_1n, error_1n, correction_1n, factuality_1n}], 
        'response_level_factuality': factuality_1
    },
    {
        'prompt': prompt_2, 
        'response': response_2, 
        'category': 'kbqa',
        'claims': [claim_21, claim_22, ..., claims_2n], 
        'queries': [[query_211, query_212], [query_221, query_222], ..., [query_2n1, query_2n2]], 
        'evidences': [[evidences_21], [evidences_22], ..., [evidences_2n]], 
        'claim_level_factuality': [{claim_21, reasoning_21, error_21, correction_21, factuality_21}, {claim_22, reasoning_22, error_22, correction_22, factuality_22}, ..., {claim_2n, reasoning_2n, error_2n, correction_2n, factuality_2n}],
        'response_level_factuality': factuality_2,
    },
    ...
]

In this case, you will get:

[
  {
    'prompt': 'Introduce Graham Neubig',
    'response': 'Graham Neubig is a professor at MIT',
    'category': 'kbqa',
    'entry_point': 'answer_question',
    'claims': [{'claim': 'Graham Neubig is a professor at MIT'}],
    'queries': [['Is Graham Neubig a professor at MIT?', 'Graham Neubig MIT']],
    'evidences': [['I am an Associate Professor of Computer Science at Carnegie Mellon University and CEO of Inspired Cognition. My research and development focuses on AI and ...', 'Graham Neubig. I am an Associate Professor at the Carnegie Mellon University Language Technology Institute in the School of Computer Science, and work with ...', 'Missing: MIT? | Must include:MIT?.', 'Associate Professor, Language Technology Institute, Carnegie Mellon University Affiliated Faculty, Machine Learning Department, Carnegie Mellon University', 'Missing: MIT? | Must include:MIT?.', 'I am an Associate Professor at the Carnegie Mellon University Language Technology Institute in the School of Computer Science, and work with a bunch of great ...', 'Missing: MIT | Must include:MIT.', 'I am an Associate Professor of Computer Science at Carnegie Mellon University and CEO of Inspired Cognition. My research and development focuses on AI and ...', 'was heavily inspired by an MIT PhD thesis finished 16 years earlier in 1996! ... Episode 22 of The Thesis Review: Graham Neubig (@gneubig), ...', 'Graham Neubig,. Graham Neubig. Graduate School of Information Science Nara Institute of Science and Technology. Search for other works by this author on:.']],
    'claim_level_factuality': [{'reasoning': 'The given text states that Graham Neubig is a professor at MIT. However, the provided evidences consistently mention that Graham Neubig is an Associate Professor at Carnegie Mellon University. There is no mention of Graham Neubig being affiliated with MIT in any of the provided evidences.', 'error': 'The given text Falsely states that Graham Neubig is a professor at MIT.', 'correction': 'Graham Neubig is an Associate Professor at Carnegie Mellon University.', 'factuality': False, 'claim': 'Graham Neubig is a professor at MIT'}],
    'response_level_factuality': False
  }
]

Code

Click to toggle contents of `code`
export OPENAI_API_KEY=...
from factool  import Factool

factool_instance = Factool("gpt-3.5-turbo")

inputs = [
        {
            "prompt": "def get_max_triples(n): \"\"\" You are given a positive integer n. You have to create an integer array a of length n. For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : Input: n = 5 Output: 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). \"\"\" Now implement the function get_max_triples using Python",
            "category": "code",
            "response": "def get_max_triples(n):\n    a = [i * i - i + 1 for i in range(1, n+1)]\n    count = 0\n    for i in range(n-2):\n        for j in range(i+1, n-1):\n            for k in range(j+1, n):\n                if (a[i] + a[j] + a[k]) % 3 == 0:\n                    count += 1\n    return count\n\nprint(get_max_triples(5)) # Output: 1",
            "entry_point": "get_max_triples"
        }
]

response_list = factool_instance.run(inputs)
print(response_list)

Output:

[
  {
    'prompt': 'def get_max_triples(n): """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : Input: n = 5 Output: 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ Now implement the function get_max_triples using Python',
    'category': 'code',
    'response': 'def get_max_triples(n):\n    a = [i * i - i + 1 for i in range(1, n+1)]\n    count = 0\n    for i in range(n-2):\n        for j in range(i+1, n-1):\n            for k in range(j+1, n):\n                if (a[i] + a[j] + a[k]) % 3 == 0:\n                    count += 1\n    return count\n\nprint(get_max_triples(5)) # Output: 1', 'entry_point': 'get_max_triples', 'claim': 'def get_max_triples(n):\n    a = [i * i - i + 1 for i in range(1, n+1)]\n    count = 0\n    for i in range(n-2):\n        for j in range(i+1, n-1):\n            for k in range(j+1, n):\n                if (a[i] + a[j] + a[k]) % 3 == 0:\n                    count += 1\n    return count\n\nprint(get_max_triples(5)) # Output: 1', 'testcases_queries': ['get_max_triples(5)', 'get_max_triples(10)', 'get_max_triples(3)'], 'potential_solutions_queries': ['def get_max_triples(n):\n    a = [i * i - i + 1 for i in range(1, n+1)]\n    count = 0\n    for i in range(n-2):\n        for j in range(i+1, n-1):\n            for k in range(j+1, n):\n                if (a[i] + a[j] + a[k]) % 3 == 0:\n                    count += 1\n    return count', 'def get_max_triples(n):\n    a = [i * i - i + 1 for i in range(1, n + 1)]\n    count = 0\n    for i in range(n):\n        for j in range(i + 1, n):\n            for k in range(j + 1, n):\n                if (a[i] + a[j] + a[k]) % 3 == 0:\n                    count += 1\n    return count', 'def get_max_triples(n):\n    a = [i * i - i + 1 for i in range(1, n+1)]\n    count = 0\n    for i in range(n):\n        for j in range(i+1, n):\n            for k in range(j+1, n):\n                if (a[i] + a[j] + a[k]) % 3 == 0:\n                    count += 1\n    return count', 'def get_max_triples(n):\n    a = [i * i - i + 1 for i in range(1, n+1)]\n    count = 0\n    for i in range(n-2):\n        for j in range(i+1, n-1):\n            for k in range(j+1, n):\n                if (a[i] + a[j] + a[k]) % 3 == 0:\n                    count += 1\n    return count\n\nprint(get_max_triples(5)) # Output: 1'], 'exec_results': [[1, 1, 1, 1], [36, 36, 36, 36], [0, 0, 0, 0]],
    'claim_level_factuality': True,
    'response_level_factuality': True
  }
]

Math

Click to toggle contents of `code`
export OPENAI_API_KEY=...
from factool  import Factool


# Initialize a Factool instance with the specified keys. foundation_model could be either "gpt-3.5-turbo" or "gpt-4"
factool_instance = Factool("gpt-3.5-turbo")

inputs = [
        {
            "prompt": "Stephen placed an online order for groceries.  His final bill came to $7023116.  Because this was through a delivery vendor, they tacked on a 25% fee to his final total and charged him $3.00 in delivery fees.  Stephen also added a $4.00 tip.  After the extra fees, what was the final price of Stephen's groceries?",
            "category": "math",
            "response": "Okay, here are the steps to solve this:\n* Stephen's initial grocery bill was $7023116\n* The delivery vendor charged a 25% fee on top of that. 25% of $7023116 is 0.25 * $7023116 = $1755779\n* They also charged a flat $3 delivery fee\n* Stephen added a $4 tip\n* So the total charges were:\n    * Initial groceries: $7023116\n    * 25% fee: $1755779\n    * Delivery fee: $3 \n    * Tip: $4\n* Adding all that up, the total final price was $7023116 + $1755779 + $3 + $4 = $8779902\n\nSo the final price of Stephen's groceries was $8779902"
        },
]

response_list = factool_instance.run(inputs)

print(response_list)

You will get:

[
  {
    'prompt': "Stephen placed an online order for groceries.  His final bill came to $7023116.  Because this was through a delivery vendor, they tacked on a 25% fee to his final total and charged him $3.00 in delivery fees.  Stephen also added a $4.00 tip.  After the extra fees, what was the final price of Stephen's groceries?",
    'category': 'math',
    'response': "Okay, here are the steps to solve this:\n* Stephen's initial grocery bill was $7023116\n* The delivery vendor charged a 25% fee on top of that. 25% of $7023116 is 0.25 * $7023116 = $1755779\n* They also charged a flat $3 delivery fee\n* Stephen added a $4 tip\n* So the total charges were:\n    * Initial groceries: $7023116\n    * 25% fee: $1755779\n    * Delivery fee: $3 \n    * Tip: $4\n* Adding all that up, the total final price was $7023116 + $1755779 + $3 + $4 = $8779902\n\nSo the final price of Stephen's groceries was $8779902", 'claims': [{'math_calculation': '0.25 * 7023116', 'calculated_answer': '1755779'}, {'math_calculation': '7023116 + 1755779 + 3 + 4', 'calculated_answer': '8779902'}], 'queries': [{'python_snippet': 'print(0.25 * 7023116 == 1755779)'}, {'python_snippet': 'print(7023116 + 1755779 + 3 + 4 == 8779902)'}], 'execution_results': ['True', 'False'],
    'claim_level_factuality': [True, False],
    'response_level_factuality': False
  }
]

Scientific Literature Review

Click to toggle contents of `code`
export OPENAI_API_KEY=...
export SCRAPER_API_KEY=...
from factool  import Factool

factool_instance = Factool("gpt-3.5-turbo")

inputs = [

        {
            "prompt": "Detail how machine learning algorithms are applied in data"
                      " analytics and the processes involved in training"
                      " these algorithms. Please cite relevant research papers"
                      " or textbooks to support your points, including the author's"
                      " name, the title of the work, and the year of publication.",
            "category": "scientific",
            "response": "Machine learning algorithms play a crucial role in data"
                        " analytics. They are used to extract insights and knowledge"
                        " from large datasets, which can be used to make informed"
                        " decisions and predictions. The following are the processes"
                        " involved in training machine learning algorithms:\n\n1. "
                        "Data Preprocessing: The first step in training a machine"
                        " learning algorithm is to preprocess the data. This involves"
                        " cleaning the data, handling missing values, "
                        "encoding categorical variables, and scaling the data. "
                        "The aim of preprocessing is to ensure that the data is in"
                        " a format that can be used by the machine learning algorithm.\n2. Feature Selection: Once the data has been preprocessed, the next step is to select the relevant features that will be used to train the machine learning algorithm. This involves identifying the features that are most important for predicting the target variable. Feature selection can be done using various techniques, such as filter methods, wrapper methods, and embedded methods.\n3. Model Selection: After feature selection, the next step is to select the appropriate machine learning algorithm to use. There are various types of machine learning algorithms, such as supervised learning, unsupervised learning, and reinforcement learning. The choice of algorithm depends on the nature of the problem and the type of data available.\n4. Training the Model: Once the model has been selected, the next step is to train the machine learning algorithm using the preprocessed data. This involves using a training set of data to optimize the parameters of the model so that it can accurately predict the target variable.\n5. Model Evaluation: After the model has been trained, the next step is to evaluate its performance. This involves testing the model on a separate test set of data and measuring its accuracy, precision, recall, and other performance metrics.\n6. Model Deployment: Once the model has been evaluated and fine-tuned, it can be deployed in a production environment. This involves integrating the model into a larger system or workflow, and monitoring its performance over time.\n\nResearch papers and textbooks that support the above points include:\n\n* \"An Introduction to Machine Learning\" by Alpaydin, B., (2010) which provides a comprehensive overview of machine learning algorithms and their applications.\n* \"Data Mining: Concepts and Techniques\" by Han, J., Kamber, B., & Pei, J., (2011) which provides a detailed introduction to data mining and its applications.\n* \"Machine Learning: Trends, Perspectives, and Prospects\" by Kamber, B., & Pei, J., (2012) which provides an overview of the current trends and future prospects of machine learning.\n* \"Machine Learning for Data Mining\" by He, C., & Wang, Y., (2015) which provides an in-depth introduction to machine learning algorithms and their applications in data mining."
        },
]

response_list = factool_instance.run(inputs)

print(response_list)

Steps for setting up FACTOOL ChatGPT Plugin:

  1. Install the package: Installation
  2. git clone the repo: git clone https://github.com/GAIR-NLP/factool.git
  3. cd ./factool/plugin_config
  4. Create your keys.yaml
  5. Run the API locally: uvicorn main:app --host 0.0.0.0 --port ${PORT:-5003}
  6. Enter plugin store of ChatGPT Website
  7. Click 'develop your own plugin' then enter the website domain localhost: 5003 under 'domain'.

Experiments:

  1. Experimental results:
  • Exp I: .results/knowledge_QA/RoSE/

  • Exp II: .results/knowledge_QA, .results/code, .results/math, .results/scientific

  • Exp III .results/chat

  1. Get the final results and statistics for fine-grained analysis:
  • Exp I: python ./results/knowledge_QA/RoSE/run_rose_claim_extraction.py

  • Exp II: bash ./results/evaluation.sh

  • Exp III: python ./results/chat/calc_stats.py

  1. Reimplement the experiments:
  • Exp II: bash run_experiments.sh

  • Exp III: bash run_chatbot.sh

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

factool-0.0.8.tar.gz (32.6 kB view hashes)

Uploaded Source

Built Distribution

factool-0.0.8-py2.py3-none-any.whl (37.6 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page