{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Iulia Brezeanu",
  "title_listed": "How to Detect Hallucinations in LLMs",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/real-time-llm-hallucination-detection-9a68bb292698/",
  "publish_date": "2023-12-31",
  "corpus_stage": "",
  "notes": "",
  "id": "ce373c7e7f74",
  "collected_at": "2026-10-02T09:52:06",
  "title": "How to Detect Hallucinations in LLMs | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# How to Detect Hallucinations in LLMs\nTeaching Chatbots to Say \"I Don't Know\"\n[Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\nDecember 31, 202310 min read\n![Photo by visuals on Unsplash](../images/000.jpg)\nPhoto by [visuals](https://unsplash.com/@visuals?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\n> **Who is Evelyn Hartwell?**\n> Evelyn Hartwell is an American author, speaker, and life coach...\n> Evelyn Hartwell is a Canadian ballerina and the founding Artistic Director...\n> Evelyn Hartwell is an American actress known for her roles in the...\nNo, 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.\nLong, 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.\n![text-davinci-003 prompt completion on a fictional person. Image by the author.](../images/001.png)\ntext-davinci-003 prompt completion on a fictional person. Image by the author.\nFor 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.\nLearn 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.\nThis 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]\nFor 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]\n## Sentence embeddings cosine distance\nLet'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.\nFor generating the embeddings, I am using the _all-MiniLM-L6-v2_ lightweight model. Embedding a sentence turns it into its vectorial representation.\npython\n\n```\noutput = \"Evelyn Hartwell is a Canadian dancer, actor, and choreographer.\" \noutput_embeddings= model.encode(output)\n\narray([ 6.09108340e-03, -8.73148292e-02, -5.30637987e-02, -4.41815751e-03,\n 1.45469820e-02, 4.20340300e-02, 1.99541822e-02, -7.29453489e-02,\n...\n -4.08893749e-02, -5.41420840e-02, 2.05906332e-02, 9.94611382e-02,\n -2.24501686e-03, 2.29083393e-02, 7.80007839e-02, -9.53456461e-02],\n dtype=float32)\n```\n\nWe 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.\npython\n\n```\nfrom sentence_transformers.util import pairwise_cos_sim\nfrom sentence_transformers import SentenceTransformer\n\ndef get_cos_sim(output,sampled_passages):\n    model = SentenceTransformer('all-MiniLM-L6-v2')\n    sentence_embeddings = model.encode(output).reshape(1, -1)\n    sample1_embeddings = model.encode(sampled_passages[0]).reshape(1, -1)\n    sample2_embeddings = model.encode(sampled_passages[1]).reshape(1, -1)\n    sample3_embeddings = model.encode(sampled_passages[2]).reshape(1, -1)\n    cos_sim_with_sample1 = pairwise_cos_sim(\n    sentence_embeddings, sample1_embeddings\n    )\n    cos_sim_with_sample2  = pairwise_cos_sim(\n    sentence_embeddings, sample2_embeddings\n    )\n    cos_sim_with_sample3  = pairwise_cos_sim(\n    sentence_embeddings, sample3_embeddings\n    )\n    cos_sim_mean = (cos_sim_with_sample1 + cos_sim_with_sample2 + cos_sim_with_sample3) / 3\n    cos_sim_mean = cos_sim_mean.item()\n    return round(cos_sim_mean,2)\n```\n\nThis 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.\n![Pairwise cos similarity computation. Image by author.](../images/002.png)\nPairwise cos similarity computation. Image by author.\nFrom 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.\nini\n\n```\ncos_sim_score = get_cos_sim(output, [sample1,sample2,sample3])\n```\n\nThe _cos_sim _score_ for our embedded outputs has an average value of 0.52.\nTo 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.\n![Image by the author - text-davinci-003 prompt completion on Nicolas Cage](../images/003.png)\nImage by the author - text-davinci-003 prompt completion on Nicolas Cage\nThe 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.\n![Duration of cosine similarity computation. Image by author.](../images/004.png)\nDuration of cosine similarity computation. Image by author.\n## SelfCheckGPT- BERTScore\nThe BERTScore builds on the pairwise cosine similarity idea we implemented previously.\n![\\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1zvmykW-RtIYUN78u3UFmDw.png)\n[1]\nThe 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\".\npython\n\n```\ndef get_bertscore(output, sampled_passages):\n    # spacy sentence tokenization\n    sentences = [sent.text.strip() for sent in nlp(output).sents] \n    selfcheck_bertscore = SelfCheckBERTScore(rescale_with_baseline=True)\n    sent_scores_bertscore = selfcheck_bertscore.predict(\n        sentences = sentences, # list of sentences\n        sampled_passages = sampled_passages, # list of sampled passages\n    )\n    df = pd.DataFrame({\n    'Sentence Number': range(1, len(sent_scores_bertscore) + 1),\n    'Hallucination Score': sent_scores_bertscore\n    })\n    return df\n```\n\nLet'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.\nvbnet\n\n```\n['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.']\n```\n\nThis 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.\nlua\n\n```\narray([[0., 0., 0.],\n       [0., 0., 0.],\n       [0., 0., 0.],\n       [0., 0., 0.]])\n```\n\nThe 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]\n![F1 BERTScore. Image by author.](../images/006.png)\nF1 BERTScore. Image by author.\nWe 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.\nLet's add the maximum similarities in the array for the first sample:\npython\n\n```\nbertscore_array\narray([[0.43343216, 0.        , 0.        ],\n       [0.12838356, 0.        , 0.        ],\n       [0.2571277 , 0.        , 0.        ],\n       [0.21805632, 0.        , 0.        ]])\n```\n\nNow we repeat the process for the other two samples:\npython\n\n```\narray([[0.43343216, 0.34562832, 0.65371764],\n       [0.12838356, 0.28202596, 0.2576825 ],\n       [0.2571277 , 0.48610589, 0.2253703 ],\n       [0.21805632, 0.34698656, 0.28309497]])\n```\n\nThen we compute the mean for each row, giving us the similarity score between each sentence from the original response and each subsequent sample.\npython\n\n```\narray([0.47759271, 0.22269734, 0.32286796, 0.28271262])\n```\n\nThe hallucination score for each sentence is obtained by subtracting from 1 each of the values above.\n![Hallucination Score for Evelyn Hartwell. Image by author.](../images/007.png)\nHallucination Score for **Evelyn Hartwell.** Image by author.\nComparing the results with the answers for Nicolas Cage.\n![Hallucination Score for Nicolas Cage. Image by author.](../images/008.png)\nHallucination Score for **Nicolas Cage.** Image by author.\nSeems 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.\n![Duration of BERTScore computation. Image by author.](../images/009.png)\nDuration of BERTScore computation. Image by author.\n## SelfCheckGPT-NLI\nNatural 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.\n![NLI flowchart \\[5\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1TOEao7YVaPZmLav2d1nvFA.png)\nNLI flowchart [5]\nBelow are some examples of premise-hypothesis pairs and their labels.\n![Examples of context - hypothesis pairs \\[4\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1aKX-qf2TmWMkri3o8zEumg.png)\nExamples of context - hypothesis pairs [4]\npython\n\n```\ndef get_self_check_nli(output, sampled_passages):\n    # spacy sentence tokenization\n    sentences = [sent.text.strip() for sent in nlp(output).sents] \n    selfcheck_nli = SelfCheckNLI(device=mps_device) # set device to 'cuda' if GPU is available\n    sent_scores_nli = selfcheck_nli.predict(\n        sentences = sentences, # list of sentences\n        sampled_passages = sampled_passages, # list of sampled passages\n    )\n    df = pd.DataFrame({\n    'Sentence Number': range(1, len(sent_scores_nli) + 1),\n    'Probability of Contradiction': sent_scores_nli\n    })\n    return df\n```\n\nIn the _selfcheck _nli.predict_ function, each sentence from the original response is paired with each of the three samples.\npython\n\n```\nlogits = model(**inputs).logits # neutral is already removed\nprobs = torch.softmax(logits, dim=-1)\nprob_ = probs[0][1].item() # prob(contradiction)\n```\n\n![Probability of contradiction w.r.t the first sentence and each sample. Image by the author.](../images/012.png)\nProbability of contradiction w.r.t the first sentence and each sample. Image by the author.\nNow we repeat the process for each of the four sentences.\n![SelfCheck-NLI for Evelyn Hartwell. Image by author.](../images/013.png)\nSelfCheck-NLI for **Evelyn Hartwell**. Image by author.\nWe can see that the model is outputting an extremely high probability of contradiction. Now we compare with the factual outputs.\n![SelfCheck-NLI for Nicolas Cage. Image by author.](../images/014.png)\nSelfCheck-NLI for **Nicolas Cage**. Image by author.\nThe model is doing a great job! Unfortunately, the NLI check is a bit too long.\n![Duration of NLI computation. Image by author.](../images/015.png)\nDuration of NLI computation. Image by author.\n## SelfCheckGPT-Prompt\nNewer 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]\npython\n\n```\ndef llm_evaluate(sentences,sampled_passages):\n    prompt = f\"\"\"You will be provided with a text passage \n                and your task is to rate the consistency of that text to \n                that of the provided context. Your answer must be only \n                a number between 0.0 and 1.0 rounded to the nearest two \n                decimal places where 0.0 represents no consistency and \n                1.0 represents perfect consistency and similarity. nn \n                Text passage: {sentences}. nn \n                Context: {sampled_passages[0]} nn \n                {sampled_passages[1]} nn \n                {sampled_passages[2]}.\"\"\"\n\n    completion = client.chat.completions.create(\n    model=\"gpt-3.5-turbo\",\n    messages=[\n        {\"role\": \"system\", \"content\": \"\"},\n        {\"role\": \"user\", \"content\": prompt}\n    ]\n    )\n\n    return completion.choices[0].message.content\n```\n\nThe 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.\n![Duration of LLM self-similarity score computation. Image by author.](../images/body-e5f561d2bcb2e2ede743.png)\nDuration of LLM self-similarity score computation. Image by author.\nThis 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.\n![Hallucination detection evaluation results \\[6\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1MHVR6KrTBfXdnZ_JU5-EFw.png)\nHallucination detection evaluation results [6]\nThe 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.\n![Evaluation dataset creation \\[5\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/172f_HotR8gx1fcWwXVfLwQ.png)\nEvaluation dataset creation [5]\nNext, 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.\nTo 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.\nThe evaluation metric, AUC-PR, refers to the area under the precision-recall curve, which is a metric used to evaluate classification models.\n## Real-time hallucination detection\nAs 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.\npython\n\n```\nimport streamlit as st\nimport utils\nimport pandas as pd\n\n# Streamlit app layout\nst.title('Anti-Hallucination Chatbot')\n\n# Text input\nuser_input = st.text_input(\"Enter your text:\")\n\nif user_input:\n\n    prompt = user_input\n\n    output, sampled_passages = utils.get_output_and_samples(prompt)\n\n    # LLM score\n    self_similarity_score = utils.llm_evaluate(output,sampled_passages)\n\n    # Display the output\n    st.write(\"**LLM output:**\")\n    if float(self_similarity_score) > 0.5:\n        st.write(output)\n    else:\n        st.write(\"I'm sorry, but I don't have the specific information required to answer your question accurately. \")\n```\n\nNow, we can visualize the final result.\n![Streamlit app demo. Image by author.](../images/body-78fe77971d47707b639c.gif)\nStreamlit app demo. Image by author.\n## Conclusion\nThe results are very promising! Hallucination detection in chatbots has been a long-discussed quality problem.\nWhat 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.\nThere 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.\n. . .\n_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._\n_You can find the full code for this project on_[ _GitHub_](https://github.com/partycia/real-time-hallucination-detection.git) _._\n_You can also find me on_[ _LinkedIn_](https://www.linkedin.com/in/ibrezeanu/) _._\n. . .\n## References:\n  1. [A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference](https://aclanthology.org/N18-1101)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-f993dd42b2e293ffbc34.png)\nWritten By\n## [Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[See all from Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F&text=How%20to%20Detect%20Hallucinations%20in%20LLMs)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/016.png)](https://towardsdatascience.com/ai-ml-model-validation-framework-13dd3f10e824/)\n## [AI/ML Model Validation Framework](https://towardsdatascience.com/ai-ml-model-validation-framework-13dd3f10e824/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIt's more than a simple MRM issue\n[Prasun Biswas](https://towardsdatascience.com/author/prasunbiswas90/)\nJune 7, 20216 min read\n  * [![](../images/017.jpg)](https://towardsdatascience.com/the-power-and-pitfalls-of-vector-based-image-search/)\n## [The Power and Pitfalls of Vector-Based Image Search](https://towardsdatascience.com/the-power-and-pitfalls-of-vector-based-image-search/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA hands-on guide to setting up image similarity search in Milvus, and why visual replication isn't always enough.\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJune 18, 20267 min read\n  * [![](../images/018.jpeg)](https://towardsdatascience.com/exercise-classification-with-machine-learning-part-i-7cc336ef2e01/)\n## [Exercise Classification with Machine Learning (Part I)](https://towardsdatascience.com/exercise-classification-with-machine-learning-part-i-7cc336ef2e01/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn this two-part post we're taking a deep dive into a specific problem: classifying videos of people performing various exercises.\n[Trevor Phillips](https://towardsdatascience.com/author/trevor.j.phillips/)\nJuly 29, 20198 min read\n  * [![](../images/019.png)](https://towardsdatascience.com/developing-a-company-specific-chatgpt-is-one-third-technology-and-two-thirds-process-improvements-2c6b4adf637f/)\n## [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/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA practical overview of the processes, roles, and complexities involved in the development of a GPT-based virtual assistant\n[Kristjan Eljand](https://towardsdatascience.com/author/eljand/)\nNovember 18, 20235 min read\n  * [![](../images/020.png)](https://towardsdatascience.com/most-common-text-processing-tasks-in-natural-language-processing-d8cd7a076b79/)\n## [Most Common Text Processing Tasks In Natural Language Processing](https://towardsdatascience.com/most-common-text-processing-tasks-in-natural-language-processing-d8cd7a076b79/)\n[NLP](https://towardsdatascience.com/category/artificial-intelligence/nlp/)\nComputers haven't human capability, text data need processing for better understanding and interpretation\n[Zoumana Keita](https://towardsdatascience.com/author/zoumanakeita/)\nDecember 13, 20229 min read\n  * [![](../images/021.png)](https://towardsdatascience.com/a-derivation-and-application-of-restricted-boltzmann-machines-2024-nobel-prize-ead5fe66908c/)\n## [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/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nInvestigating Geoffrey Hinton's Nobel Prize-winning work and building it from scratch using PyTorch\n[Ryan D'Cunha](https://towardsdatascience.com/author/rtdcunha/)\nJanuary 23, 20257 min read\n  * [![](../images/022.png)](https://towardsdatascience.com/how-linear-regression-actually-works-theory-and-implementation-8d8dcae3222c/)\n## [How linear regression actually works - theory and implementation](https://towardsdatascience.com/how-linear-regression-actually-works-theory-and-implementation-8d8dcae3222c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWe derive the maximum likelihood estimate and implement it\n[Stefan Hrouda-Rasmussen](https://towardsdatascience.com/author/cookieblues/)\nMarch 22, 20217 min read\n  * [![](../images/023.jpeg)](https://towardsdatascience.com/learn-how-neural-networks-learn-d920fab3f72e/)\n## [Learn How Neural Networks Learn](https://towardsdatascience.com/learn-how-neural-networks-learn-d920fab3f72e/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIt's not so different from humans...\n[Anna Shi](https://towardsdatascience.com/author/anna-shi/)\nNovember 28, 20208 min read\n  * [![](../images/024.png)](https://towardsdatascience.com/explainable-graph-neural-networks-cb009c2bc8ea/)\n## [Explainable Graph Neural Networks](https://towardsdatascience.com/explainable-graph-neural-networks-cb009c2bc8ea/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA step forward in explainable AI, and why it is hard to adapt existing explanation methods to GNNs\n[Remy Lau](https://towardsdatascience.com/author/remylau961/)\nJune 13, 20214 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n  * [ ![](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\")\n\n\n",
  "metadata": {
    "title": "How to Detect Hallucinations in LLMs | Towards Data Science",
    "description": "Teaching Chatbots to Say \"I Don't Know\"",
    "keywords": null,
    "author": "Iulia Brezeanu",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "How to Detect Hallucinations in LLMs",
    "og:description": "Teaching Chatbots to Say \"I Don't Know\"",
    "og:url": "https://towardsdatascience.com/real-time-llm-hallucination-detection-9a68bb292698/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/0_VgAtHvX7Irxlr2y-scaled.jpg",
    "og:image:width": "2560",
    "og:image:height": "1707",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Iulia Brezeanu",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "10 min read",
    "article:published_time": "2023-12-31T19:48:18.000Z",
    "article:modified_time": "2023-12-31T19:48:18.000Z",
    "article:author": "https://towardsdatascience.com/author/brezeanu.iulia/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_000.txt",
      "chars": 413
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_001.txt",
      "chars": 940
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_002.txt",
      "chars": 63
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_003.txt",
      "chars": 564
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_004.txt",
      "chars": 371
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_005.txt",
      "chars": 85
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_006.txt",
      "chars": 197
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_007.txt",
      "chars": 181
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_008.txt",
      "chars": 56
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_009.txt",
      "chars": 576
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_010.txt",
      "chars": 148
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_011.txt",
      "chars": 890
    },
    {
      "language": "txt",
      "file": "attachments/ce373c7e7f74/code/block_012.txt",
      "chars": 634
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:04:05Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:04:05Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:04:05Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:04:05Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/brezeanu.iulia/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/chatgpt/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/generative-ai-tools/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/llm/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/nlp/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/ai-ml-model-validation-framework-13dd3f10e824/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/prasunbiswas90/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/the-power-and-pitfalls-of-vector-based-image-search/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/sonery/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/exercise-classification-with-machine-learning-part-i-7cc336ef2e01/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/trevor.j.phillips/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/developing-a-company-specific-chatgpt-is-one-third-technology-and-two-thirds-process-improvements-2c6b4adf637f/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/@visuals"
    },
    {
      "type": "external",
      "href": "https://unsplash.com"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-engineer"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/prompt-engineering"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://textgeneration.substack.com/"
    },
    {
      "type": "external",
      "href": "https://github.com/partycia/real-time-hallucination-detection.git"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/ibrezeanu/"
    },
    {
      "type": "external",
      "href": "https://aclanthology.org/N18-1101"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=How+to+Detect+Hallucinations+in+LLMs&u=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=How+to+Detect+Hallucinations+in+LLMs&url=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=How+to+Detect+Hallucinations+in+LLMs&url=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:31:50Z",
  "source_url": "https://towardsdatascience.com/real-time-llm-hallucination-detection-9a68bb292698/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# How to Detect Hallucinations in LLMs\nTeaching Chatbots to Say \"I Don't Know\"\n[Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\nDecember 31, 202310 min read\n![Photo by visuals on Unsplash](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/0_VgAtHvX7Irxlr2y-scaled.jpg)\nPhoto by [visuals](https://unsplash.com/@visuals?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)\n> **Who is Evelyn Hartwell?**\n> Evelyn Hartwell is an American author, speaker, and life coach...\n> Evelyn Hartwell is a Canadian ballerina and the founding Artistic Director...\n> Evelyn Hartwell is an American actress known for her roles in the...\nNo, 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.\nLong, 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.\n![text-davinci-003 prompt completion on a fictional person. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/11Rk3_mxxXCg8ENKmY4i-DA.png)\ntext-davinci-003 prompt completion on a fictional person. Image by the author.\nFor 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.\nLearn 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.\nThis 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]\nFor 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]\n## Sentence embeddings cosine distance\nLet'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.\nFor generating the embeddings, I am using the _all-MiniLM-L6-v2_ lightweight model. Embedding a sentence turns it into its vectorial representation.\npython\n\n```\noutput = \"Evelyn Hartwell is a Canadian dancer, actor, and choreographer.\" \noutput_embeddings= model.encode(output)\n\narray([ 6.09108340e-03, -8.73148292e-02, -5.30637987e-02, -4.41815751e-03,\n 1.45469820e-02, 4.20340300e-02, 1.99541822e-02, -7.29453489e-02,\n...\n -4.08893749e-02, -5.41420840e-02, 2.05906332e-02, 9.94611382e-02,\n -2.24501686e-03, 2.29083393e-02, 7.80007839e-02, -9.53456461e-02],\n dtype=float32)\n```\n\nWe 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.\npython\n\n```\nfrom sentence_transformers.util import pairwise_cos_sim\nfrom sentence_transformers import SentenceTransformer\n\ndef get_cos_sim(output,sampled_passages):\n    model = SentenceTransformer('all-MiniLM-L6-v2')\n    sentence_embeddings = model.encode(output).reshape(1, -1)\n    sample1_embeddings = model.encode(sampled_passages[0]).reshape(1, -1)\n    sample2_embeddings = model.encode(sampled_passages[1]).reshape(1, -1)\n    sample3_embeddings = model.encode(sampled_passages[2]).reshape(1, -1)\n    cos_sim_with_sample1 = pairwise_cos_sim(\n    sentence_embeddings, sample1_embeddings\n    )\n    cos_sim_with_sample2  = pairwise_cos_sim(\n    sentence_embeddings, sample2_embeddings\n    )\n    cos_sim_with_sample3  = pairwise_cos_sim(\n    sentence_embeddings, sample3_embeddings\n    )\n    cos_sim_mean = (cos_sim_with_sample1 + cos_sim_with_sample2 + cos_sim_with_sample3) / 3\n    cos_sim_mean = cos_sim_mean.item()\n    return round(cos_sim_mean,2)\n```\n\nThis 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.\n![Pairwise cos similarity computation. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1vWF_y0ljfv-zictpzrJS8g.png)\nPairwise cos similarity computation. Image by author.\nFrom 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.\nini\n\n```\ncos_sim_score = get_cos_sim(output, [sample1,sample2,sample3])\n```\n\nThe _cos_sim _score_ for our embedded outputs has an average value of 0.52.\nTo 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.\n![Image by the author - text-davinci-003 prompt completion on Nicolas Cage](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1fibKeH-DCIRdqrpRs2m1zg.png)\nImage by the author - text-davinci-003 prompt completion on Nicolas Cage\nThe 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.\n![Duration of cosine similarity computation. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1Ox3gyluqHx5JMYy4ScLrZw.png)\nDuration of cosine similarity computation. Image by author.\n## SelfCheckGPT- BERTScore\nThe BERTScore builds on the pairwise cosine similarity idea we implemented previously.\n![\\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1zvmykW-RtIYUN78u3UFmDw.png)\n[1]\nThe 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\".\npython\n\n```\ndef get_bertscore(output, sampled_passages):\n    # spacy sentence tokenization\n    sentences = [sent.text.strip() for sent in nlp(output).sents] \n    selfcheck_bertscore = SelfCheckBERTScore(rescale_with_baseline=True)\n    sent_scores_bertscore = selfcheck_bertscore.predict(\n        sentences = sentences, # list of sentences\n        sampled_passages = sampled_passages, # list of sampled passages\n    )\n    df = pd.DataFrame({\n    'Sentence Number': range(1, len(sent_scores_bertscore) + 1),\n    'Hallucination Score': sent_scores_bertscore\n    })\n    return df\n```\n\nLet'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.\nvbnet\n\n```\n['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.']\n```\n\nThis 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.\nlua\n\n```\narray([[0., 0., 0.],\n       [0., 0., 0.],\n       [0., 0., 0.],\n       [0., 0., 0.]])\n```\n\nThe 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]\n![F1 BERTScore. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1qrKcKJeCn6MBsSawDHagig.png)\nF1 BERTScore. Image by author.\nWe 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.\nLet's add the maximum similarities in the array for the first sample:\npython\n\n```\nbertscore_array\narray([[0.43343216, 0.        , 0.        ],\n       [0.12838356, 0.        , 0.        ],\n       [0.2571277 , 0.        , 0.        ],\n       [0.21805632, 0.        , 0.        ]])\n```\n\nNow we repeat the process for the other two samples:\npython\n\n```\narray([[0.43343216, 0.34562832, 0.65371764],\n       [0.12838356, 0.28202596, 0.2576825 ],\n       [0.2571277 , 0.48610589, 0.2253703 ],\n       [0.21805632, 0.34698656, 0.28309497]])\n```\n\nThen we compute the mean for each row, giving us the similarity score between each sentence from the original response and each subsequent sample.\npython\n\n```\narray([0.47759271, 0.22269734, 0.32286796, 0.28271262])\n```\n\nThe hallucination score for each sentence is obtained by subtracting from 1 each of the values above.\n![Hallucination Score for Evelyn Hartwell. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1-8hzpYL3IWKRLzgb_XA6vQ.png)\nHallucination Score for **Evelyn Hartwell.** Image by author.\nComparing the results with the answers for Nicolas Cage.\n![Hallucination Score for Nicolas Cage. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1l9xdSoaQIruIfgb65yrZMQ.png)\nHallucination Score for **Nicolas Cage.** Image by author.\nSeems 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.\n![Duration of BERTScore computation. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1FWg9iPaOCibDX6v5q7XgGQ.png)\nDuration of BERTScore computation. Image by author.\n## SelfCheckGPT-NLI\nNatural 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.\n![NLI flowchart \\[5\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1TOEao7YVaPZmLav2d1nvFA.png)\nNLI flowchart [5]\nBelow are some examples of premise-hypothesis pairs and their labels.\n![Examples of context - hypothesis pairs \\[4\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1aKX-qf2TmWMkri3o8zEumg.png)\nExamples of context - hypothesis pairs [4]\npython\n\n```\ndef get_self_check_nli(output, sampled_passages):\n    # spacy sentence tokenization\n    sentences = [sent.text.strip() for sent in nlp(output).sents] \n    selfcheck_nli = SelfCheckNLI(device=mps_device) # set device to 'cuda' if GPU is available\n    sent_scores_nli = selfcheck_nli.predict(\n        sentences = sentences, # list of sentences\n        sampled_passages = sampled_passages, # list of sampled passages\n    )\n    df = pd.DataFrame({\n    'Sentence Number': range(1, len(sent_scores_nli) + 1),\n    'Probability of Contradiction': sent_scores_nli\n    })\n    return df\n```\n\nIn the _selfcheck _nli.predict_ function, each sentence from the original response is paired with each of the three samples.\npython\n\n```\nlogits = model(**inputs).logits # neutral is already removed\nprobs = torch.softmax(logits, dim=-1)\nprob_ = probs[0][1].item() # prob(contradiction)\n```\n\n![Probability of contradiction w.r.t the first sentence and each sample. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/10z8hzBmdCqOCvL4yePmEaA.png)\nProbability of contradiction w.r.t the first sentence and each sample. Image by the author.\nNow we repeat the process for each of the four sentences.\n![SelfCheck-NLI for Evelyn Hartwell. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1rFQ8ekWdgw4CEIB4-5jd6A.png)\nSelfCheck-NLI for **Evelyn Hartwell**. Image by author.\nWe can see that the model is outputting an extremely high probability of contradiction. Now we compare with the factual outputs.\n![SelfCheck-NLI for Nicolas Cage. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1yXF68X7hifUMNjtq-VPxHg.png)\nSelfCheck-NLI for **Nicolas Cage**. Image by author.\nThe model is doing a great job! Unfortunately, the NLI check is a bit too long.\n![Duration of NLI computation. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1_khaUIWAsyij0sTNN-o7lg.png)\nDuration of NLI computation. Image by author.\n## SelfCheckGPT-Prompt\nNewer 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]\npython\n\n```\ndef llm_evaluate(sentences,sampled_passages):\n    prompt = f\"\"\"You will be provided with a text passage \n                and your task is to rate the consistency of that text to \n                that of the provided context. Your answer must be only \n                a number between 0.0 and 1.0 rounded to the nearest two \n                decimal places where 0.0 represents no consistency and \n                1.0 represents perfect consistency and similarity. nn \n                Text passage: {sentences}. nn \n                Context: {sampled_passages[0]} nn \n                {sampled_passages[1]} nn \n                {sampled_passages[2]}.\"\"\"\n\n    completion = client.chat.completions.create(\n    model=\"gpt-3.5-turbo\",\n    messages=[\n        {\"role\": \"system\", \"content\": \"\"},\n        {\"role\": \"user\", \"content\": prompt}\n    ]\n    )\n\n    return completion.choices[0].message.content\n```\n\nThe 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.\n![Duration of LLM self-similarity score computation. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1joIlng5z9mGQaAgy6POELA.png)\nDuration of LLM self-similarity score computation. Image by author.\nThis 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.\n![Hallucination detection evaluation results \\[6\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1MHVR6KrTBfXdnZ_JU5-EFw.png)\nHallucination detection evaluation results [6]\nThe 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.\n![Evaluation dataset creation \\[5\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/172f_HotR8gx1fcWwXVfLwQ.png)\nEvaluation dataset creation [5]\nNext, 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.\nTo 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.\nThe evaluation metric, AUC-PR, refers to the area under the precision-recall curve, which is a metric used to evaluate classification models.\n## Real-time hallucination detection\nAs 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.\npython\n\n```\nimport streamlit as st\nimport utils\nimport pandas as pd\n\n# Streamlit app layout\nst.title('Anti-Hallucination Chatbot')\n\n# Text input\nuser_input = st.text_input(\"Enter your text:\")\n\nif user_input:\n\n    prompt = user_input\n\n    output, sampled_passages = utils.get_output_and_samples(prompt)\n\n    # LLM score\n    self_similarity_score = utils.llm_evaluate(output,sampled_passages)\n\n    # Display the output\n    st.write(\"**LLM output:**\")\n    if float(self_similarity_score) > 0.5:\n        st.write(output)\n    else:\n        st.write(\"I'm sorry, but I don't have the specific information required to answer your question accurately. \")\n```\n\nNow, we can visualize the final result.\n![Streamlit app demo. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1YG5aC7EKqvkQx31_9wi2KQ.gif)\nStreamlit app demo. Image by author.\n## Conclusion\nThe results are very promising! Hallucination detection in chatbots has been a long-discussed quality problem.\nWhat 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.\nThere 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.\n. . .\n_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._\n_You can find the full code for this project on_[ _GitHub_](https://github.com/partycia/real-time-hallucination-detection.git) _._\n_You can also find me on_[ _LinkedIn_](https://www.linkedin.com/in/ibrezeanu/) _._\n. . .\n## References:\n  1. [A Broad-Coverage Challenge Corpus for Sentence Understanding through Inference](https://aclanthology.org/N18-1101)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657516549_c8nzry.png)\nWritten By\n## [Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[See all from Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Freal-time-llm-hallucination-detection-9a68bb292698%2F&text=How%20to%20Detect%20Hallucinations%20in%20LLMs)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/1PPaRgIOgSeSvfAE4-sHdXg.png)](https://towardsdatascience.com/ai-ml-model-validation-framework-13dd3f10e824/)\n## [AI/ML Model Validation Framework](https://towardsdatascience.com/ai-ml-model-validation-framework-13dd3f10e824/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIt's more than a simple MRM issue\n[Prasun Biswas](https://towardsdatascience.com/author/prasunbiswas90/)\nJune 7, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/06/bohdan-stocek-8kCixqfgXjU-unsplash-scaled-1.jpg)](https://towardsdatascience.com/the-power-and-pitfalls-of-vector-based-image-search/)\n## [The Power and Pitfalls of Vector-Based Image Search](https://towardsdatascience.com/the-power-and-pitfalls-of-vector-based-image-search/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA hands-on guide to setting up image similarity search in Milvus, and why visual replication isn't always enough.\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJune 18, 20267 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/07/1sziFPGMLEtLTdBDNTNVfeg.jpeg)](https://towardsdatascience.com/exercise-classification-with-machine-learning-part-i-7cc336ef2e01/)\n## [Exercise Classification with Machine Learning (Part I)](https://towardsdatascience.com/exercise-classification-with-machine-learning-part-i-7cc336ef2e01/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn this two-part post we're taking a deep dive into a specific problem: classifying videos of people performing various exercises.\n[Trevor Phillips](https://towardsdatascience.com/author/trevor.j.phillips/)\nJuly 29, 20198 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/11/15sQz70PhUyM21U0hdI3Z0Q.png)](https://towardsdatascience.com/developing-a-company-specific-chatgpt-is-one-third-technology-and-two-thirds-process-improvements-2c6b4adf637f/)\n## [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/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA practical overview of the processes, roles, and complexities involved in the development of a GPT-based virtual assistant\n[Kristjan Eljand](https://towardsdatascience.com/author/eljand/)\nNovember 18, 20235 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/12/1fa7J0G4UCqCI5zrKujvGgw.png)](https://towardsdatascience.com/most-common-text-processing-tasks-in-natural-language-processing-d8cd7a076b79/)\n## [Most Common Text Processing Tasks In Natural Language Processing](https://towardsdatascience.com/most-common-text-processing-tasks-in-natural-language-processing-d8cd7a076b79/)\n[NLP](https://towardsdatascience.com/category/artificial-intelligence/nlp/)\nComputers haven't human capability, text data need processing for better understanding and interpretation\n[Zoumana Keita](https://towardsdatascience.com/author/zoumanakeita/)\nDecember 13, 20229 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/01/1uY3avHGG10Wt1twO6zJ70A.png)](https://towardsdatascience.com/a-derivation-and-application-of-restricted-boltzmann-machines-2024-nobel-prize-ead5fe66908c/)\n## [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/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nInvestigating Geoffrey Hinton's Nobel Prize-winning work and building it from scratch using PyTorch\n[Ryan D'Cunha](https://towardsdatascience.com/author/rtdcunha/)\nJanuary 23, 20257 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/03/1BUvr6JWkXScxc-OUbBBqjQ.png)](https://towardsdatascience.com/how-linear-regression-actually-works-theory-and-implementation-8d8dcae3222c/)\n## [How linear regression actually works - theory and implementation](https://towardsdatascience.com/how-linear-regression-actually-works-theory-and-implementation-8d8dcae3222c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWe derive the maximum likelihood estimate and implement it\n[Stefan Hrouda-Rasmussen](https://towardsdatascience.com/author/cookieblues/)\nMarch 22, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/0WFllWoFHxu5wNzj--scaled.jpeg)](https://towardsdatascience.com/learn-how-neural-networks-learn-d920fab3f72e/)\n## [Learn How Neural Networks Learn](https://towardsdatascience.com/learn-how-neural-networks-learn-d920fab3f72e/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIt's not so different from humans...\n[Anna Shi](https://towardsdatascience.com/author/anna-shi/)\nNovember 28, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/1dcKBPM4shLIksVThbbEtAw.png)](https://towardsdatascience.com/explainable-graph-neural-networks-cb009c2bc8ea/)\n## [Explainable Graph Neural Networks](https://towardsdatascience.com/explainable-graph-neural-networks-cb009c2bc8ea/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA step forward in explainable AI, and why it is hard to adapt existing explanation methods to GNNs\n[Remy Lau](https://towardsdatascience.com/author/remylau961/)\nJune 13, 20214 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n  * [ ![](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\")\n\n\n",
  "body_base_path": "attachments/ce373c7e7f74/pages/",
  "body_markdown_path": "attachments/ce373c7e7f74/pages/archived-body.md",
  "local_html": "attachments/ce373c7e7f74/pages/archived-body.html",
  "body_source": "prior_capture"
}