![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
# How to Detect Hallucinations in LLMs
Teaching Chatbots to Say "I Don't Know"
[Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)
December 31, 202310 min read
![Photo by visuals on Unsplash](../images/000.jpg)
Photo by [visuals](https://unsplash.com/@visuals?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)
> **Who is Evelyn Hartwell?**
> Evelyn Hartwell is an American author, speaker, and life coach...
> Evelyn Hartwell is a Canadian ballerina and the founding Artistic Director...
> Evelyn Hartwell is an American actress known for her roles in the...
No, Evelyn Hartwell is not a con artist with multiple false identities, living a deceptive triple life with various professions. In fact, she doesn't exist at all, but the model, instead of telling me that it doesn't know, starts making facts up. We are dealing with an LLM Hallucination.
Long, detailed outputs can seem really convincing, even if fictional. Does it mean that we cannot trust chatbots and have to manually fact-check the outputs every time? Fortunately, there could be ways to make chatbots less likely to say fabricated things with the right safeguards.
![text-davinci-003 prompt completion on a fictional person. Image by the author.](../images/001.png)
text-davinci-003 prompt completion on a fictional person. Image by the author.
For the outputs above, I set a higher temperature of 0.7. I am allowing the LLM to change the structure of its sentences in order not to have identical text for each generation. The differences between outputs should be just semantic, not factual.
Learn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer), [Prompt Engineering](https://roadmap.sh/prompt-engineering) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.
This simple idea allowed for introducing a new sample-based hallucination detection mechanism. If the LLM's outputs to the same prompt contradict each other, they will likely be hallucinations. If they are entailing each other, it implies the information is factual. [2]
For this type of evaluation, we only require the text outputs of the LLMs. This is known as black-box evaluation. Also, because we don't need any external knowledge, is called zero-resource. [5]
## Sentence embeddings cosine distance
Let's start with a very basic way of measuring similarity. We will compute the pairwise cosine similarity between corresponding pairs of embedded sentences. We normalize them because we need to focus only on the vector's direction, not magnitude. The function below takes as input the originally generated sentence called _output_ and a list of 3 sample outputs called _sampled _passages_. All the completions are found in the image at the beginning of the article.
For generating the embeddings, I am using the _all-MiniLM-L6-v2_ lightweight model. Embedding a sentence turns it into its vectorial representation.
python

```
output = "Evelyn Hartwell is a Canadian dancer, actor, and choreographer." 
output_embeddings= model.encode(output)

array([ 6.09108340e-03, -8.73148292e-02, -5.30637987e-02, -4.41815751e-03,
 1.45469820e-02, 4.20340300e-02, 1.99541822e-02, -7.29453489e-02,
...
 -4.08893749e-02, -5.41420840e-02, 2.05906332e-02, 9.94611382e-02,
 -2.24501686e-03, 2.29083393e-02, 7.80007839e-02, -9.53456461e-02],
 dtype=float32)
```

We generate embeddings for every output of the LLM; then, we compute the pairwise cos similarity using the _pairwise_cos _sim_ function from sentence_transformers. We'll compare the original response to each new sample response and then do the average.
python

```
from sentence_transformers.util import pairwise_cos_sim
from sentence_transformers import SentenceTransformer

def get_cos_sim(output,sampled_passages):
    model = SentenceTransformer('all-MiniLM-L6-v2')
    sentence_embeddings = model.encode(output).reshape(1, -1)
    sample1_embeddings = model.encode(sampled_passages[0]).reshape(1, -1)
    sample2_embeddings = model.encode(sampled_passages[1]).reshape(1, -1)
    sample3_embeddings = model.encode(sampled_passages[2]).reshape(1, -1)
    cos_sim_with_sample1 = pairwise_cos_sim(
    sentence_embeddings, sample1_embeddings
    )
    cos_sim_with_sample2  = pairwise_cos_sim(
    sentence_embeddings, sample2_embeddings
    )
    cos_sim_with_sample3  = pairwise_cos_sim(
    sentence_embeddings, sample3_embeddings
    )
    cos_sim_mean = (cos_sim_with_sample1 + cos_sim_with_sample2 + cos_sim_with_sample3) / 3
    cos_sim_mean = cos_sim_mean.item()
    return round(cos_sim_mean,2)
```

This is the intuition behind how the function works with a very simple pair of vectors in a 2D cartesian space. A and B are the original vectors, and Â and B̂ are the normalized ones.
![Pairwise cos similarity computation. Image by author.](../images/002.png)
Pairwise cos similarity computation. Image by author.
From the image above, we can see that the angle between the vectors is approximately 30⁰, so they are close to each other. The cosine is approximately 0.87. The closer the cosine is to 1, the closer the vectors are to each other.
ini

```
cos_sim_score = get_cos_sim(output, [sample1,sample2,sample3])
```

The _cos_sim _score_ for our embedded outputs has an average value of 0.52.
To understand how to interpret this number, let's compare it to the cosine similarity score for some valid outputs where we ask for information about an existing person.
![Image by the author - text-davinci-003 prompt completion on Nicolas Cage](../images/003.png)
Image by the author - text-davinci-003 prompt completion on Nicolas Cage
The pairwise cosine similarity score, in this case, is 0.93. Looks promising, especially as it's a very fast method of assessing the similarity between outputs.
![Duration of cosine similarity computation. Image by author.](../images/004.png)
Duration of cosine similarity computation. Image by author.
## SelfCheckGPT- BERTScore
The BERTScore builds on the pairwise cosine similarity idea we implemented previously.
![\[1\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1zvmykW-RtIYUN78u3UFmDw.png)
[1]
The default tokenizer for computing the contextual embeddings is RobertaTokenizer. Contextual embeddings differ from static embeddings because they take into account the context around the word. For example, the word "bat" would correspond to different token values depending on whether the context refers to a "flying mammal" or a "baseball bat".
python

```
def get_bertscore(output, sampled_passages):
    # spacy sentence tokenization
    sentences = [sent.text.strip() for sent in nlp(output).sents] 
    selfcheck_bertscore = SelfCheckBERTScore(rescale_with_baseline=True)
    sent_scores_bertscore = selfcheck_bertscore.predict(
        sentences = sentences, # list of sentences
        sampled_passages = sampled_passages, # list of sampled passages
    )
    df = pd.DataFrame({
    'Sentence Number': range(1, len(sent_scores_bertscore) + 1),
    'Hallucination Score': sent_scores_bertscore
    })
    return df
```

Let's take an inside look at the _selfcheck _bertscore.predict_ function. Instead of passing the full original output as an argument, we split it into individual sentences.
vbnet

```
['Evelyn Hartwell is an American author, speaker, and life coach.', 'She is best known for her book, The Miracle of You: How to Live an Extraordinary Life, which was published in 2007.', 'She is a motivational speaker and has been featured on TV, radio, and in many magazines.', 'She has authored several books, including How to Make an Impact and The Power of Choice.']
```

This step is important because the s_elfcheck _bertscore.predict_ function computes the BERTScore for each sentence into the original response matched to each sentence from the samples. First, it creates an array with the number of rows equal to the number of sentences in the original output and the number of columns equal to the number of samples.
lua

```
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
```

The model used for computing the BERTScore between the candidate and reference sentences is RoBERTa large with 17 layers. Our original output has 4 sentences, which I will call r1,r2,r3, and r4. The first sample has two sentences: c1 and c2. We compute the F1 BERTScore for each sentence from the original output matched to each sentence from the first sample. Then we do base rescaling with respect to the baseline tensor b = **tensor([0.8315, 0.8315, 0.8312]).** The baseline _b_ was computed using 1 million randomly paired sentences from the Common Crawl monolingual datasets. They computed the BERTScore for each pair and averaged it. This represents a lower bound since random pairs have little semantic overlap. [1]
![F1 BERTScore. Image by author.](../images/006.png)
F1 BERTScore. Image by author.
We keep the BERTScore of each sentence from the original response with the most similar sentence from each drawn sample. The logic is that if a piece of information appears across multiple samples generated from the same prompt, there is a good chance that the information is factual. If a statement only appears in one sample and not in any other samples from the same prompt, it is more likely to be a fabrication.
Let's add the maximum similarities in the array for the first sample:
python

```
bertscore_array
array([[0.43343216, 0.        , 0.        ],
       [0.12838356, 0.        , 0.        ],
       [0.2571277 , 0.        , 0.        ],
       [0.21805632, 0.        , 0.        ]])
```

Now we repeat the process for the other two samples:
python

```
array([[0.43343216, 0.34562832, 0.65371764],
       [0.12838356, 0.28202596, 0.2576825 ],
       [0.2571277 , 0.48610589, 0.2253703 ],
       [0.21805632, 0.34698656, 0.28309497]])
```

Then we compute the mean for each row, giving us the similarity score between each sentence from the original response and each subsequent sample.
python

```
array([0.47759271, 0.22269734, 0.32286796, 0.28271262])
```

The hallucination score for each sentence is obtained by subtracting from 1 each of the values above.
![Hallucination Score for Evelyn Hartwell. Image by author.](../images/007.png)
Hallucination Score for **Evelyn Hartwell.** Image by author.
Comparing the results with the answers for Nicolas Cage.
![Hallucination Score for Nicolas Cage. Image by author.](../images/008.png)
Hallucination Score for **Nicolas Cage.** Image by author.
Seems reasonable; the hallucination score for the valid outputs is low, and the one for the made-up outputs is high. Unfortunately, the process of computing the BERTScore is very time-consuming, which makes it a bad candidate for real-time hallucination detection.
![Duration of BERTScore computation. Image by author.](../images/009.png)
Duration of BERTScore computation. Image by author.
## SelfCheckGPT-NLI
Natural language inference (NLI) involves determining whether a hypothesis logically follows from or contradicts a given premise. The relationship is classified as entailment, contradiction, or neutral. For SelfCheck-NLI, we utilize the DeBERTa-v3-large model that has been fine-tuned on the MNLI dataset to perform NLI.
![NLI flowchart \[5\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1TOEao7YVaPZmLav2d1nvFA.png)
NLI flowchart [5]
Below are some examples of premise-hypothesis pairs and their labels.
![Examples of context - hypothesis pairs \[4\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1aKX-qf2TmWMkri3o8zEumg.png)
Examples of context - hypothesis pairs [4]
python

```
def get_self_check_nli(output, sampled_passages):
    # spacy sentence tokenization
    sentences = [sent.text.strip() for sent in nlp(output).sents] 
    selfcheck_nli = SelfCheckNLI(device=mps_device) # set device to 'cuda' if GPU is available
    sent_scores_nli = selfcheck_nli.predict(
        sentences = sentences, # list of sentences
        sampled_passages = sampled_passages, # list of sampled passages
    )
    df = pd.DataFrame({
    'Sentence Number': range(1, len(sent_scores_nli) + 1),
    'Probability of Contradiction': sent_scores_nli
    })
    return df
```

In the _selfcheck _nli.predict_ function, each sentence from the original response is paired with each of the three samples.
python

```
logits = model(**inputs).logits # neutral is already removed
probs = torch.softmax(logits, dim=-1)
prob_ = probs[0][1].item() # prob(contradiction)
```

![Probability of contradiction w.r.t the first sentence and each sample. Image by the author.](../images/012.png)
Probability of contradiction w.r.t the first sentence and each sample. Image by the author.
Now we repeat the process for each of the four sentences.
![SelfCheck-NLI for Evelyn Hartwell. Image by author.](../images/013.png)
SelfCheck-NLI for **Evelyn Hartwell**. Image by author.
We can see that the model is outputting an extremely high probability of contradiction. Now we compare with the factual outputs.
![SelfCheck-NLI for Nicolas Cage. Image by author.](../images/014.png)
SelfCheck-NLI for **Nicolas Cage**. Image by author.
The model is doing a great job! Unfortunately, the NLI check is a bit too long.
![Duration of NLI computation. Image by author.](../images/015.png)
Duration of NLI computation. Image by author.
## SelfCheckGPT-Prompt
Newer methods have started using LLMs themselves to evaluate generated text. Instead of using a formula to calculate a score, we will send the output along with the three samples to gpt-3.5-turbo. The model will decide how consistent the original output is with respect to the other three samples generated. [3]
python

```
def llm_evaluate(sentences,sampled_passages):
    prompt = f"""You will be provided with a text passage 
                and your task is to rate the consistency of that text to 
                that of the provided context. Your answer must be only 
                a number between 0.0 and 1.0 rounded to the nearest two 
                decimal places where 0.0 represents no consistency and 
                1.0 represents perfect consistency and similarity. nn 
                Text passage: {sentences}. nn 
                Context: {sampled_passages[0]} nn 
                {sampled_passages[1]} nn 
                {sampled_passages[2]}."""

    completion = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": ""},
        {"role": "user", "content": prompt}
    ]
    )

    return completion.choices[0].message.content
```

The self-similarity score returned for Evelyn Hartwell is **0**. Meanwhile, the score for the outputs related to Nicolas Cage is **0.95**. The time needed for getting the score is also pretty low.
![Duration of LLM self-similarity score computation. Image by author.](../images/body-e5f561d2bcb2e2ede743.png)
Duration of LLM self-similarity score computation. Image by author.
This seems to be the best solution for our case, as we were also expecting from the comparative analysis of the source paper [2]. SelfCheckGPTPrompt significantly outperformed all other methods, with NLI being the second-best performing method.
![Hallucination detection evaluation results \[6\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1MHVR6KrTBfXdnZ_JU5-EFw.png)
Hallucination detection evaluation results [6]
The evaluation dataset was created by generating synthetic Wikipedia articles using the WikiBio dataset and GPT-3. To avoid obscure concepts, 238 article topics were randomly sampled from the top 20% of the longest articles. GPT-3 was prompted to generate the first paragraphs in a Wikipedia style for each concept.
![Evaluation dataset creation \[5\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/172f_HotR8gx1fcWwXVfLwQ.png)
Evaluation dataset creation [5]
Next, these generated passages were manually annotated for factuality at the sentence level. Each sentence was labeled as major inaccurate, minor inaccurate, or accurate based on predefined guidelines. In total, 1908 sentences were annotated, with around 40% major inaccurate, 33% minor inaccurate, and 27% accurate.
To assess annotator agreement, 201 sentences had dual annotations. If the annotators agreed, that label was used; otherwise, the worst-case label was chosen. Inter-annotator agreement measured by Cohen's kappa was 0.595 when selecting between accurate, minor inaccurate, and major inaccurate and 0.748 when minor/major inaccuracies were combined into one label.
The evaluation metric, AUC-PR, refers to the area under the precision-recall curve, which is a metric used to evaluate classification models.
## Real-time hallucination detection
As a final application, let's build a Streamlit app for real-time hallucination detection. As mentioned before, the best metric is the LLM self-similarity score. We will use a threshold of 0.5 to decide whether to display the generated output or a disclaimer.
python

```
import streamlit as st
import utils
import pandas as pd

# Streamlit app layout
st.title('Anti-Hallucination Chatbot')

# Text input
user_input = st.text_input("Enter your text:")

if user_input:

    prompt = user_input

    output, sampled_passages = utils.get_output_and_samples(prompt)

    # LLM score
    self_similarity_score = utils.llm_evaluate(output,sampled_passages)

    # Display the output
    st.write("**LLM output:**")
    if float(self_similarity_score) > 0.5:
        st.write(output)
    else:
        st.write("I'm sorry, but I don't have the specific information required to answer your question accurately. ")
```

Now, we can visualize the final result.
![Streamlit app demo. Image by author.](../images/body-78fe77971d47707b639c.gif)
Streamlit app demo. Image by author.
## Conclusion
The results are very promising! Hallucination detection in chatbots has been a long-discussed quality problem.
What makes the techniques outlined here so exciting is the novel approach of using an LLM to evaluate the outputs of other LLMs. Specifically done by generating multiple responses to the same prompt and comparing their consistency.
There is still more work to be done, but rather than relying on human evaluation or hand-crafted rules, it seems to be a good direction to let the models themselves catch the inconsistencies.
. . .
_If you enjoyed this article, join_[ _**Text Generation**_](https://textgeneration.substack.com/) _- our newsletter has two weekly posts with the latest insights on Generative AI and Large Language Models._
_You can find the full code for this project on_[ _GitHub_](https://github.com/partycia/real-time-hallucination-detection.git) _._
_You can also find me on_[ _LinkedIn_](https://www.linkedin.com/in/ibrezeanu/) _._
. . .
## References:
  1. [A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference](https://aclanthology.org/N18-1101)


## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-f993dd42b2e293ffbc34.png)
Written By
## [Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)
[See all from Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)
[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[ChatGPT](https://towardsdatascience.com/tag/chatgpt/)[Generative Ai Tools](https://towardsdatascience.com/tag/generative-ai-tools/)[Llm](https://towardsdatascience.com/tag/llm/)[NLP](https://towardsdatascience.com/tag/nlp/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F&title=How%20to%20Detect%20Hallucinations%20in%20LLMs)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F&title=How%20to%20Detect%20Hallucinations%20in%20LLMs)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F&text=How%20to%20Detect%20Hallucinations%20in%20LLMs)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/016.png)](https://towardsdatascience.com/ai-ml-model-validation-framework-13dd3f10e824/)
## [AI/ML Model Validation Framework](https://towardsdatascience.com/ai-ml-model-validation-framework-13dd3f10e824/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
It's more than a simple MRM issue
[Prasun Biswas](https://towardsdatascience.com/author/prasunbiswas90/)
June 7, 20216 min read
  * [![](../images/017.jpg)](https://towardsdatascience.com/the-power-and-pitfalls-of-vector-based-image-search/)
## [The Power and Pitfalls of Vector-Based Image Search](https://towardsdatascience.com/the-power-and-pitfalls-of-vector-based-image-search/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
A hands-on guide to setting up image similarity search in Milvus, and why visual replication isn't always enough.
[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)
June 18, 20267 min read
  * [![](../images/018.jpeg)](https://towardsdatascience.com/exercise-classification-with-machine-learning-part-i-7cc336ef2e01/)
## [Exercise Classification with Machine Learning (Part I)](https://towardsdatascience.com/exercise-classification-with-machine-learning-part-i-7cc336ef2e01/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
In this two-part post we're taking a deep dive into a specific problem: classifying videos of people performing various exercises.
[Trevor Phillips](https://towardsdatascience.com/author/trevor.j.phillips/)
July 29, 20198 min read
  * [![](../images/019.png)](https://towardsdatascience.com/developing-a-company-specific-chatgpt-is-one-third-technology-and-two-thirds-process-improvements-2c6b4adf637f/)
## [Developing a Company-Specific ChatGPT is One-Third Technology and Two-Thirds Process Improvements](https://towardsdatascience.com/developing-a-company-specific-chatgpt-is-one-third-technology-and-two-thirds-process-improvements-2c6b4adf637f/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
A practical overview of the processes, roles, and complexities involved in the development of a GPT-based virtual assistant
[Kristjan Eljand](https://towardsdatascience.com/author/eljand/)
November 18, 20235 min read
  * [![](../images/020.png)](https://towardsdatascience.com/most-common-text-processing-tasks-in-natural-language-processing-d8cd7a076b79/)
## [Most Common Text Processing Tasks In Natural Language Processing](https://towardsdatascience.com/most-common-text-processing-tasks-in-natural-language-processing-d8cd7a076b79/)
[NLP](https://towardsdatascience.com/category/artificial-intelligence/nlp/)
Computers haven't human capability, text data need processing for better understanding and interpretation
[Zoumana Keita](https://towardsdatascience.com/author/zoumanakeita/)
December 13, 20229 min read
  * [![](../images/021.png)](https://towardsdatascience.com/a-derivation-and-application-of-restricted-boltzmann-machines-2024-nobel-prize-ead5fe66908c/)
## [A Derivation and Application of Restricted Boltzmann Machines (2024 Nobel Prize)](https://towardsdatascience.com/a-derivation-and-application-of-restricted-boltzmann-machines-2024-nobel-prize-ead5fe66908c/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Investigating Geoffrey Hinton's Nobel Prize-winning work and building it from scratch using PyTorch
[Ryan D'Cunha](https://towardsdatascience.com/author/rtdcunha/)
January 23, 20257 min read
  * [![](../images/022.png)](https://towardsdatascience.com/how-linear-regression-actually-works-theory-and-implementation-8d8dcae3222c/)
## [How linear regression actually works - theory and implementation](https://towardsdatascience.com/how-linear-regression-actually-works-theory-and-implementation-8d8dcae3222c/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
We derive the maximum likelihood estimate and implement it
[Stefan Hrouda-Rasmussen](https://towardsdatascience.com/author/cookieblues/)
March 22, 20217 min read
  * [![](../images/023.jpeg)](https://towardsdatascience.com/learn-how-neural-networks-learn-d920fab3f72e/)
## [Learn How Neural Networks Learn](https://towardsdatascience.com/learn-how-neural-networks-learn-d920fab3f72e/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
It's not so different from humans...
[Anna Shi](https://towardsdatascience.com/author/anna-shi/)
November 28, 20208 min read
  * [![](../images/024.png)](https://towardsdatascience.com/explainable-graph-neural-networks-cb009c2bc8ea/)
## [Explainable Graph Neural Networks](https://towardsdatascience.com/explainable-graph-neural-networks-cb009c2bc8ea/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
A step forward in explainable AI, and why it is hard to adapt existing explanation methods to GNNs
[Remy Lau](https://towardsdatascience.com/author/remylau961/)
June 13, 20214 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ "Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ "The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ "Does Your Company Have a Data Strategy?")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ "Productivity Tips, Data Career Insights, and Other Recent Must-Reads")


