Notebooks
A
Arize AI
Evaluate Hallucination Classifications

Evaluate Hallucination Classifications

agentsllmsLlamaIndexarize-phoenixopenaitutorialsevalsllmopsai-monitoringaiengineeringprompt-engineeringdatasetsllm-evalai-observabilityllm-evaluationsmolagentslegacyanthropiclangchain

Open In Colab

phoenix logo
Docs | GitHub | Community

Hallucination Classification Evals

The purpose of this notebook is:

  • to evaluate the performance of an LLM-assisted approach to detecting hallucinations,
  • to provide an experimental framework for users to iterate and improve on the default classification template.

Install Dependencies and Import Libraries

[1]
[1]

ℹ️ To enable async request submission in notebook environments like Jupyter or Google Colab, optionally use nest_asyncio. nest_asyncio globally patches asyncio to enable event loops to be re-entrant. This is not required for non-notebook environments.

Without nest_asyncio, eval submission can be much slower, depending on your organization's rate limits. Speed increases of about 5x are typical.

[2]
[3]

Download Benchmark Dataset

We'll evaluate the evaluation system consisting of an LLM model and settings in addition to an evaluation prompt template against benchmark datasets of queries and retrieved documents with ground-truth relevance labels. Currently supported datasets include "halueval_qa_data" from the HaluEval benchmark:

[4]

Display Binary Hallucination Classification Template

View the default template used to classify hallucinations. You can tweak this template and evaluate its performance relative to the default.

[5]

In this task, you will be presented with a query, a reference text and an answer. The answer is
generated to the question based on the reference text. The answer may contain false information. You
must use the reference text to determine if the answer to the question contains false information,
if the answer is a hallucination of facts. Your objective is to determine whether the answer text
contains factual information and is not a hallucination. A 'hallucination' refers to
an answer that is not based on the reference text or assumes information that is not available in
the reference text. Your response should be a single word: either "factual" or "hallucinated", and
it should not include any other text or characters. "hallucinated" indicates that the answer
provides factually inaccurate information to the query based on the reference text. "factual"
indicates that the answer to the question is correct relative to the reference text, and does not
contain made up information. Please read the query and reference text carefully before determining
your response.

    [BEGIN DATA]
    ************
    [Query]: {input}
    ************
    [Reference text]: {reference}
    ************
    [Answer]: {output}
    ************
    [END DATA]

    Is the answer above factual or hallucinated based on the query and reference text?

Template variables:

  • input : The question or prompt asked on the context data.
  • reference : The context data used to answer the question
  • output : The answer generated from the context data, we are checking this answer for halluciations relative to the reference context

Configure the LLM

Configure your OpenAI API key.

[6]

Benchmark Dataset Sample

Sample size determines run time Recommend iterating small: 100 samples Then increasing to large test set

[7]

LLM Evals: hallucination Classifications GPT-4

Run hallucination against a subset of the data.

Instantiate the LLM and set parameters.

[8]
The `model_name` field is deprecated. Use `model` instead.                 This will be removed in a future release.
[9]
"Hello! I'm working perfectly. How can I assist you today?"
[10]
llm_classify |          | 0/100 (0.0%) | ⏳ 00:00<? | ?it/s

Evaluate the predictions against human-labeled ground-truth hallucination labels.

[11]
              precision    recall  f1-score   support

hallucinated       0.95      0.78      0.86        50
     factual       0.81      0.96      0.88        50

    accuracy                           0.87       100
   macro avg       0.88      0.87      0.87       100
weighted avg       0.88      0.87      0.87       100

<Axes: title={'center': 'Confusion Matrix (Normalized)'}, xlabel='Predicted Classes', ylabel='Actual Classes'>
Output

Classifications with explanations

When evaluating a dataset for hallucinations, it can be useful to know why the LLM classified a response as a hallucination or not. The following code block runs llm_classify with explanations turned on so that we can inspect why the LLM made the classification it did. There is speed tradeoff since more tokens is being generated but it can be highly informative when troubleshooting.

[12]
Using prompt:


In this task, you will be presented with a query, a reference text and an answer. The answer is
generated to the question based on the reference text. The answer may contain false information. You
must use the reference text to determine if the answer to the question contains false information,
if the answer is a hallucination of facts. Your objective is to determine whether the answer text
contains factual information and is not a hallucination. A 'hallucination' refers to
an answer that is not based on the reference text or assumes information that is not available in
the reference text.

    [BEGIN DATA]
    ************
    [Query]: {input}
    ************
    [Reference text]: {reference}
    ************
    [Answer]: {output}
    ************
    [END DATA]

    Is the answer above factual or hallucinated based on the query and reference text?

Please read the query, reference text and answer carefully, then write out in a step by step manner
an EXPLANATION to show how to determine if the answer is "factual" or "hallucinated". Avoid simply
stating the correct answer at the outset. Your response LABEL should be a single word: either
"factual" or "hallucinated", and it should not include any other text or characters. "hallucinated"
indicates that the answer provides factually inaccurate information to the query based on the
reference text. "factual" indicates that the answer to the question is correct relative to the
reference text, and does not contain made up information.

Example response:
************
EXPLANATION: An explanation of your reasoning for why the label is "factual" or "hallucinated"
LABEL: "factual" or "hallucinated"
************

EXPLANATION:
OpenAI invocation parameters: {'model': 'gpt-4', 'temperature': 0.0, 'max_tokens': 256, 'frequency_penalty': 0, 'presence_penalty': 0, 'top_p': 1, 'n': 1, 'timeout': None}
llm_classify |          | 0/5 (0.0%) | ⏳ 00:00<? | ?it/s
- Snapped 'hallucinated' to rail: hallucinated
- Snapped 'factual' to rail: factual
- Snapped 'factual' to rail: factual
- Snapped 'hallucinated' to rail: hallucinated
- Snapped 'hallucinated' to rail: hallucinated
[13]

LLM Evals: hallucination Classifications GPT-3.5

Run hallucination against a subset of the data.

[14]
The `model_name` field is deprecated. Use `model` instead.                 This will be removed in a future release.
[15]
llm_classify |          | 0/100 (0.0%) | ⏳ 00:00<? | ?it/s
[16]
              precision    recall  f1-score   support

hallucinated       0.84      0.72      0.77        50
     factual       0.75      0.86      0.80        50

    accuracy                           0.79       100
   macro avg       0.80      0.79      0.79       100
weighted avg       0.80      0.79      0.79       100

<Axes: title={'center': 'Confusion Matrix (Normalized)'}, xlabel='Predicted Classes', ylabel='Actual Classes'>
Output

Preview: GPT-4 Turbo

[17]
The `model_name` field is deprecated. Use `model` instead.                 This will be removed in a future release.
llm_classify |          | 0/100 (0.0%) | ⏳ 00:00<? | ?it/s
[18]
              precision    recall  f1-score   support

hallucinated       0.90      0.74      0.81        50
     factual       0.78      0.92      0.84        50

    accuracy                           0.83       100
   macro avg       0.84      0.83      0.83       100
weighted avg       0.84      0.83      0.83       100

<Axes: title={'center': 'Confusion Matrix (Normalized)'}, xlabel='Predicted Classes', ylabel='Actual Classes'>
Output