Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:ALwrity ALwrity HallucinationDetector

From Leeroopedia
Knowledge Sources
Domains Blog_Writer, Fact_Checking, LLM
Last Updated 2026-10-24 00:00 GMT

Overview

Concrete tool for detecting factual hallucinations in generated text via a three-step claim extraction, evidence search, and verification pipeline, provided by the ALwrity blog writer subsystem.

Description

The HallucinationDetector class implements a three-step fact-checking pipeline: (1) extract verifiable claims from the input text using the configured LLM provider, (2) search for evidence for each claim using Exa neural search, and (3) assess each claim against retrieved sources as supported, refuted, or insufficient_information. The result is a HallucinationResult dataclass containing a list of Claim objects (each with text, confidence, assessment, supporting/refuting sources, reasoning) and aggregate counts. A daily rate limit of 20 calls (reset per calendar day) gates access to control cost.

The provider is determined by the GPT_PROVIDER environment variable and the generation call delegates to llm_text_gen.

Usage

Import this class when:

  • The blog writer pipeline has generated content and must verify factual claims before publishing.
  • A daily rate-limited fact-check is acceptable (20 calls/day).
  • Claims must be classified as supported, refuted, or insufficient for downstream reporting.

Code Reference

Source Location

  • Repository: ALwrity
  • File: backend/services/hallucination_detector.py (L59-118)

Signature

@dataclass
class Claim:
    """Represents a single verifiable claim extracted from text."""
    text: str
    confidence: float
    assessment: str  # "supported", "refuted", "insufficient_information"
    supporting_sources: List[Dict[str, Any]]
    refuting_sources: List[Dict[str, Any]]
    reasoning: str = ""

@dataclass
class HallucinationResult:
    """Result of hallucination detection analysis."""
    claims: List[Claim]
    overall_confidence: float
    total_claims: int
    supported_claims: int
    refuted_claims: int
    insufficient_claims: int
    timestamp: str


class HallucinationDetector:
    """
    Hallucination detector using Exa.ai for evidence search
    and the configured LLM provider for claim extraction/assessment.
    """

    def __init__(self):
        self._llm_provider_info = _get_llm_provider_info()
        self._check_provider_keys()
        self.daily_api_calls = 0
        self.daily_limit = 20
        self.last_reset_date = None

    async def detect_hallucinations(
        self,
        text: str,
        user_id: str = None,
    ) -> HallucinationResult:
        """
        Main method to detect hallucinations in the given text.

        Args:
            text: The text to analyze for factual accuracy.
            user_id: Clerk user ID for LLM provider routing.

        Returns:
            HallucinationResult with claims analysis and confidence scores.
        """

Import

from services.hallucination_detector import HallucinationDetector, HallucinationResult, Claim

I/O Contract

Inputs

Name Type Required Description
text str Yes The text to fact-check
user_id str No Clerk user ID for LLM provider routing

Outputs

Name Type Description
return HallucinationResult claims list, overall_confidence, supported/refuted/insufficient counts, timestamp
side effect rate limit Increments daily call counter; returns empty result if limit exceeded

Usage Examples

Fact-checking generated blog content

from services.hallucination_detector import HallucinationDetector

detector = HallucinationDetector()
result = await detector.detect_hallucinations(
    text=blog_content,
    user_id="clerk_user_123",
)

print(f"Overall confidence: {result.overall_confidence}")
print(f"Supported: {result.supported_claims}, Refuted: {result.refuted_claims}")
for claim in result.claims:
    print(f"  [{claim.assessment}] {claim.text} (conf={claim.confidence})")

Handling rate-limit exhaustion

result = await detector.detect_hallucinations(text=blog_content, user_id="clerk_user_123")
if result.total_claims == 0 and result.overall_confidence == 0.0:
    print("Rate limit reached or no claims found — skipping fact-check.")

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment