Skip to content

One typed detect interface for the detectors package #126

Done
15 of 15 issues completed
Done

Description

@hslev

Problem Statement

A service that runs LettuceDetect detectors behind an API has to serve many concurrent requests, with models loaded once at startup, results it can type and validate, and a record of what each call used. Today's detectors can't be called that way.

  • The result shape depends on an argument. predict returns a list of token dicts or a list of span dicts depending on output_format, and RAGFactCheckerDetector.predict returns a dict for "detailed". The three predict* methods have no typed result, no usage and no place for a warning. predict_prompt_batch takes a batch_size on TransformerDetector and not on the others.
  • Spans don't always carry a score. LLMDetector spans have no confidence unless include_reasoning is set, and native generative spans never have one. min_confidence keeps every span without a confidence key, so a threshold of 0.9 silently keeps them. RAGFactCheckerDetector spans carry the constants 0.9 and 0.7, and its tokens (and the LLM detector's tokens without reasoning) carry the constants 0.9 and 0.1. A caller can't tell a model probability from a constant.
  • RAGFactCheckerDetector can return a span whose text is not the text at its offsets. Merging overlapping spans extends end and keeps the first span's text.
  • Constructors build things from names. TransformerDetector downloads the tokenizer, the model and (with taxonomy_head) the TaxonomyTyper encoder inside the constructor. LLMDetector builds an LLMClient from provider when none is passed, and OpenAIClient reads OPENAI_API_KEY and OPENAI_API_BASE and falls back to the key "EMPTY". RAGFactCheckerDetector builds a RAGFactChecker, which reads OPENAI_API_KEY, and ignores unknown keyword arguments, so a misspelt option has no effect. The caller can't decide when a download happens or which credentials are used.
  • Detectors are chosen by name. make_detector takes a method string and passes **kwargs through. LLMDetector decides between the judge prompt and the fine-tuned generative prompt by looking for substrings in the model name, and takes fourteen keyword arguments (plus **client_kwargs) whose conflicts are checked at runtime, for example native with zero_shot.
  • Failures are silent. An unparseable judge reply logs an error and returns no spans, which reads as "no hallucination found". A native reply without JSON, or without the hallucinated_spans key, returns no spans. BedrockClient returns "" when the reply has no tool call. The native path writes a reply to the cache before parsing it, so an empty or garbage reply is replayed on every later call. A malformed verification reply keeps all first-pass spans without a trace. An LLM item that can't be located in the answer is dropped with a debug line. A truncated input is only logged, in two of the three paths, and not at all when a passage group still exceeds max_length. A fewshot_path that doesn't exist logs a warning and runs without examples.
  • Customer text is logged on module loggers: a malformed LLM item at WARNING, a dropped span text and the raw LLM reply at DEBUG.
  • Detectors write to disk. LLMDetector builds a CacheManager in its constructor, and with no cache_file the file is cache_<model>_<lang>.json inside the installed package directory. The CacheManager constructor creates that directory, every set rewrites the whole file with a plain write_text (a crash mid-write leaves a corrupt file), and the lock only covers one process. The cache key holds the model name but not the model version, so a redeployed model serves stale replies.
  • Nothing reports which models ran or how much work a call did, adetect doesn't exist, and LLMDetector.predict_prompt_batch runs a hard-coded pool of 30 threads and raises on the first failure, dropping the results of the requests that succeeded.

Existing users need all of it to keep working. HallucinationDetector (outside this package) calls make_detector and predict, predict_prompt and predict_prompt_batch, and must keep returning today's output. Code that builds TransformerDetector(model_path=...), LLMDetector(...) and RAGFactCheckerDetector(...) directly, subclasses BaseDetector, or reads a cache file written by CacheManager must keep working. One evaluation script builds a TransformerDetector with __new__ and sets model, tokenizer, device, max_length, lang and typer by hand, and the existing tests patch private methods such as _predict_single. None of them may break.

Solution

The detectors package gets one typed interface. A request is a SourcesInput (a question or None, the sources as Chunk items, and the answer) or a PromptInput (a full prompt and the answer). BaseDetector gains detect and adetect, which take a DetectRequest plus min_score, include_tokens and include_detail, and return one Detection: the spans (each with offsets into the answer and a score), optional tokens, optional detail, the usage per model that took part, and the warnings. Batch methods detect_batch and adetect_batch follow once the batch result decision is made.

Four detector classes implement the interface. EncoderDetector takes a loaded model, tokenizer and optional TaxonomyTyper, and from_pretrained is the one place a model name becomes a model. LLMJudgeDetector and GenerativeDetector take an LLM client and a model id, and RAGFactCheckerDetector gains detect. Options move into frozen pydantic config models (EncoderConfig, LLMJudgeConfig, GenerativeConfig) that never read the environment. A ResponseCache protocol with FileCache and InMemoryCache replaces CacheManager, and detectors cache only when the caller passes one. load_detector(model_id, ...) replaces the factory for the KR Labs models the library knows.

Failures are visible. A detector returns a correct Detection or raises InvalidInputError, ConfigurationError or UpstreamError, and a result that is degraded but correct says so in warnings.

Today's API keeps working through adapters. TransformerDetector, LLMDetector, make_detector, CacheManager, the three predict* methods and the min_confidence and output_format arguments warn with LettuceDetectDeprecationWarning, name their replacement and the removal version, and delegate to the new classes, so each step has one implementation. A deprecated name called from inside the lettucedetect package does not warn, which keeps the unchanged HallucinationDetector facade silent until a follow-up moves it.

User Stories

Service developer (running detectors behind an API)

  1. As a service developer, I want requests and results to be typed models that serialise to JSON and validate back unchanged, so that they cross a service boundary without conversion.
  2. As a service developer, I want every error to carry a stable code (and param for an invalid argument) and every result warning a stable code, so that I can handle and monitor them without parsing messages.
  3. As a service developer, I want to pass a question, sources and an answer to detect and get a Detection, so that I can serve detection from sources I hold.
  4. As a service developer, I want to pass a full prompt and an answer to detect and get the same Detection type, so that prompt-based callers use the same interface.
  5. As a service developer, I want each span to give its offsets into the answer, with the start inclusive and the end exclusive in Unicode code points, and its text to equal the answer between them, so that I can highlight it without searching.
  6. As a service developer, I want min_score to drop spans whose score is below it, and a value outside [0, 1] to raise InvalidInputError, so that a threshold means the same on every detector.
  7. As a service developer, I want every span of every detector to have a numeric score, so that min_score works on all of them.
  8. As a service developer, I want one synthetic_score warning on a Detection whose scores are constants and not model outputs, so that I can tell a certain flag from an unscored one.
  9. As a service developer, I want adetect to return the same result as detect without blocking the event loop, so that I can call detectors from async code.
  10. As a service developer, I want one detector instance to serve concurrent calls, and the same input to give the same result also after a call with other input, so that I build it once at startup.
  11. As a service developer, I want a call to write no files, read no environment variables, print nothing, and log customer text only on the lettucedetect.content logger, so that detectors are safe in a long-running server.
  12. As a service developer, I want include_tokens=True on an EncoderDetector to return TokenScore items with token text, offsets, score and flag, so that I can show token-level evidence.
  13. As a service developer, I want include_tokens=True and include_detail=True to raise InvalidInputError on detectors that can't provide them, so that I never get fabricated token scores.
  14. As a service developer, I want include_detail=True on RAGFactCheckerDetector to return the triplets and fact-check results, so that I keep the evidence the fact checker produced.
  15. As a service developer, I want to load encoder weights once with EncoderDetector.from_pretrained and to build an EncoderDetector from an already loaded model without any download, so that no request triggers a model load.
  16. As a service developer, I want from_pretrained to record the resolved Hugging Face commit as model_version, and to take my own model_version for weights from a local path, so that usage names the exact weights.
  17. As a service developer, I want to pass the LLM client into LLMJudgeDetector and GenerativeDetector, so that my service controls credentials, endpoints and connection reuse.
  18. As a service developer, I want an EncoderDetector result to report one Usage with the model id, the model version and the units sources, source_chars, answer_chars and input_tokens, so that I can see what the call used.
  19. As a service developer, I want an LLM-backed result to report one Usage with llm_calls (calls actually made), cache_hits, source_chars and answer_chars, so that a cache hit is not metered as an LLM call.
  20. As a service developer, I want an encoder with a TaxonomyTyper to type every span with category and subcategory and to report the typer as a second Usage, so that typed spans are metered like the rest.
  21. As a service developer, I want an unparseable LLM reply to raise UpstreamError, so that I never read "no hallucination found" from a failed call.
  22. As a service developer, I want OpenAI authentication and quota errors to raise ConfigurationError, and timeouts, connection errors, rate limits, server errors and an empty Bedrock reply to raise UpstreamError, so that I can tell my misconfiguration from a provider outage.
  23. As a service developer, I want a verification reply I can't parse to keep the first-pass spans and add the warning verification_skipped, so that a degraded result says so.
  24. As a service developer, I want an LLM item that can't be located in the answer to be dropped with the warning span_not_found, and a malformed item with item_malformed, so that I can monitor how often the LLM drifts.
  25. As a service developer, I want an input that exceeds the encoder's max_length to add the warning input_truncated, so that I know part of the input was not scored.
  26. As a service developer, I want to pass a ResponseCache to an LLM-backed detector, with no caching and no file written when I pass none, so that I choose where replies are kept.
  27. As a service developer, I want an entry stored with a TTL to expire, so that stale replies don't live forever.
  28. As a service developer, I want the cache key to include the model version when one is given, and to equal today's key when it isn't, so that a redeployed model doesn't serve stale replies and existing cache files keep hitting.
  29. As a service developer, I want a reply that can't be parsed never to be written to the cache, and an unparseable cached entry to be deleted, so that a bad reply is not replayed.
  30. As a service developer, I want every cache backend to pass one contract suite, with sync and async methods, an atomic FileCache, and the directory created on the first write, so that I can write a backend against the protocol.
  31. As a service developer, I want load_detector(model_id, ...) to build the right detector for every registered KR Labs model id, so that I don't choose classes by hand.
  32. As a service developer, I want an unknown model id to raise InvalidInputError that lists the known ids, so that a typo is not a silent fallback.
  33. As a service developer, I want a registered generative model id without a client to raise ConfigurationError, so that a missing client fails at startup.
  34. As a service developer, I want options to be validated config models, and an unknown or invalid option to raise ConfigurationError at construction, so that a misspelt option fails loudly.
  35. As a service developer, I want detect_batch and adetect_batch to return one result per request in input order, so that I can map results back to requests.
  36. As a service developer, I want the encoder's batch methods to score requests in padded groups of batch_size with the same results as single detect calls, so that batching is faster and not different.
  37. As a service developer, I want LLM-backed batch methods to run requests concurrently up to max_concurrency, so that I set the pool size instead of a hard-coded 30.
  38. As a service developer, I want one failed request in a batch not to discard the results of the others, reported the way the batch result decision defines, so that a batch is usable under partial failure.

Application developer (open-source user of the detectors)

  1. As an application developer, I want HallucinationDetector to keep returning today's output for every method, so that my pipelines keep working.
  2. As an application developer, I want TransformerDetector(model_path=...), LLMDetector(...), RAGFactCheckerDetector(...), make_detector, CacheManager and the three predict* methods to keep returning today's output, so that I can migrate at my own pace.
  3. As an application developer, I want a deprecated name I use directly to warn with LettuceDetectDeprecationWarning and the message "X is deprecated since S and will be removed in R. Use U.", so that I know what to change and by when.
  4. As an application developer, I want importing lettucedetect.detectors never to warn, and a deprecated name called from inside the lettucedetect package not to warn, so that I only see warnings for code I wrote.
  5. As an application developer, I want the docstring of every deprecated name to carry a .. deprecated:: note with its replacement and removal version, so that the API reference warns me too.
  6. As an application developer, I want LLMDetector without a client to build today's client and warn that the client should be passed, so that my code keeps running and I learn the explicit form.
  7. As an application developer, I want LLMDetector to keep choosing between the judge and the generative detector by today's name rule or by native=, and native=True with zero_shot, fewshot_path or prompt_path to raise ConfigurationError, so that today's calls behave the same.
  8. As an application developer, I want LLMDetector to write a cache file only when I pass cache_file, so that nothing is written into the installed package.
  9. As an application developer, I want a constructor argument that can't work (an unknown language, a batch_size below 1, a missing fewshot_path, native with judge-only options) to raise ConfigurationError with a code and param, so that I see the mistake at construction.
  10. As an application developer, I want predict(output_format="tokens") on the LLM and fact-checker detectors to keep returning today's token dicts, so that my token-level code keeps working.
  11. As an application developer, I want the old predict* methods to raise InvalidInputError for an unsupported output_format or mismatched list lengths, so that errors are typed through the old API too.
  12. As an application developer, I want the custom taxonomy forms (True, a list of names, a flat {name: description} dict and the nested {"categories": ..., "subcategories": ...} dict) to keep working on the judge, the generative detector and the typer, so that my custom label sets keep working.
  13. As an application developer, I want the changelog to list every deprecated name and every behaviour that changes through the old API, and the roadmap to reflect the release, so that I can plan the upgrade.

Contributor with a custom detector

  1. As a contributor writing a detector, I want to implement only detect and get predict, predict_prompt and predict_prompt_batch from BaseDetector, so that old callers keep working with it.
  2. As a contributor with a subclass that implements only the old predict methods, I want it to keep working through detect, with one LettuceDetectDeprecationWarning per class, so that I can migrate later.
  3. As a contributor, I want a subclass that implements neither detect nor predict to fail with TypeError when the class is defined, so that I don't get infinite recursion at call time.
  4. As a contributor, I want a reusable detector contract suite that I can run against my detector, so that I know it keeps the span, score, usage and logging invariants.
  5. As a contributor, I want a TransformerDetector created with __new__ and the attributes model, tokenizer, device, max_length, lang and typer set by hand to keep answering predict, so that evaluation scripts that build one this way keep working.

Maintainer

  1. As a maintainer, I want each old entry point to only convert arguments and results around the new detector, so that the old and new API can't drift apart.
  2. As a maintainer, I want pytest to turn LettuceDetectDeprecationWarning into an error, with the five existing test modules that use old names marked to ignore it, so that new code can't call deprecated names.
  3. As a maintainer, I want today's detector output recorded as golden fixtures before any change, so that every adapter can prove it keeps today's shape.
  4. As a maintainer, I want the team's errors-and-logging convention in this repository's CONTRIBUTING.md, so that every change follows the same rules.

Implementation Decisions

Vocabulary: a source is one Chunk in a SourcesInput (today's code calls it a passage or context item); a passage group is what TransformerDetector calls a chunk (sources scored together under max_length); score replaces confidence and prob; detector, detection, span, usage and warning are used as in the design documents.

Shared types and results

  • Where Chunk, Span and Usage live, whether the error classes are ValueError subclasses, the shape of a result warning and whether source ids must be unique are decided elsewhere (see Out of Scope). This feature uses the names below and implements against them.
  • Chunk: id, text, metadata, source_start, source_end. Frozen.
  • Span: start, end, text, score. Offsets are Unicode code points into the answer, start inclusive, end exclusive. text always equals the answer between the offsets.
  • DetectedSpan extends Span with category, subcategory and reasoning, each None when not produced.
  • TokenScore: token, start, end, score, flagged. score is the model's probability that the token is hallucinated. flagged is today's pred.
  • DetailedResult: kind="detailed", triplets (answer, context, hallucinated, each a list of triplets), fact_check_results, and span_triplets, a list parallel to Detection.spans that holds each span's source triplet or None.
  • Usage: model_id, model_version, units.
  • SourcesInput: kind="sources", sources (list of Chunk), answer, question (None for summarisation). PromptInput: kind="prompt", prompt, answer. DetectRequest is the union discriminated on kind.
  • Detection: spans, tokens (None unless requested), detail (None unless requested), usage, warnings. usage and warnings are always present and default to empty lists.
  • All result and request types are pydantic models, and models that hold customer text hide the input in validation errors.

The detector interface

  • detect(request, *, min_score=0.0, include_tokens=False, include_detail=False) -> Detection and adetect with the same arguments. Every detector has a model_id. Per-call arguments are only these three; there is no per-call config.
  • adetect runs detect in a worker thread on every detector, because LLMClient is synchronous. It uses the event loop's default executor, which has min(32, cpu+4) workers, so a service running many concurrent LLM-backed calls should size that executor; there is no executor argument. Cancelling an adetect stops the wait but not the thread; the detector and any cache stay valid afterwards (a late cache write holds a parsed reply or nothing, a FileCache file is never partial), and tests check this. The default executor is also shared with the rest of the service (loop.getaddrinfo runs on it too), so a burst of long LLM calls can delay DNS lookups and other to_thread users. These points go in the adetect docstring and the changelog.
  • Concurrency limits. LLMJudgeDetector and GenerativeDetector each hold one threading.BoundedSemaphore(config.max_concurrency) per instance (max_concurrency below 1 raises ConfigurationError, invalid_config, param config.max_concurrency). It is taken only around a client call, the verify call included, and released when the call returns or fails. detect, adetect, detect_batch and adetect_batch all go through it, so at most max_concurrency client calls are in flight on one instance however they were started, and a batch can't deadlock on it. RAGFactCheckerDetector gains a max_concurrency=30 keyword and bounds concurrent detect calls the same way, because its LLM calls happen inside RAGFactChecker. EncoderDetector holds one private threading.RLock around its whole scoring path (tokenize, forward pass, aggregate), so concurrent calls on one instance run one at a time. The reason: transformers rewrites the fast tokenizer's truncation and padding settings on every call, so concurrent calls on one tokenizer can return wrong tokens or raise ValueError (reproduced by forcing thread switches; rare at default interpreter settings), and threads sharing one model gain little. The lock is created on first use, not in __init__, because a TransformerDetector built with __new__ never runs __init__; a module-level guard lock makes two racing first calls get the same lock. It has no config field and no argument.
  • min_score keeps a span when its score is not below it. A value outside [0, 1] raises InvalidInputError (invalid_min_score, param min_score) before any model or client call. Tokens are not filtered by min_score.
  • include_tokens=True is supported only by EncoderDetector, and include_detail=True only by RAGFactCheckerDetector. Elsewhere they raise InvalidInputError (tokens_not_supported, detail_not_supported, param include_tokens or include_detail) before any model or client call.
  • detect_batch and adetect_batch take a sequence of DetectRequest and the same three arguments. Their result type and failure reporting are decided elsewhere.
  • Spans come in the order today's predict(output_format="spans") returns them. Edge cases not listed here keep today's behaviour.
  • BaseDetector keeps both interfaces. A subclass that implements only predict, predict_prompt and predict_prompt_batch gets detect from the base class: SourcesInput goes to predict, PromptInput to predict_prompt, confidence becomes score, a span without confidence gets score 1.0 plus the synthetic_score warning, and the base class warns once per subclass. Such a detector's usage has one entry with its model_id attribute (None when absent), and include_tokens and include_detail raise. A subclass that implements only detect gets the three predict* methods from the base class. A subclass that implements neither raises TypeError when defined. BaseDetector itself is never marked deprecated.

Scores, tokens and detail

  • Encoder: score is the maximum token probability of the span. LLM judge: the model's own confidence with include_reasoning=True, else 1.0. Generative detector: 1.0. RAGFactChecker: today's 0.9 for a full match and 0.7 for a partial match. A score of 1.0 without a model output is documented as "flagged without a score".
  • A Detection gets exactly one synthetic_score warning when any span's score is a constant: the 1.0 paths, the RAGFactChecker constants and the old-subclass conversion. A model's own confidence is not synthetic.
  • Token scoring (include_tokens) is the encoder's own, over its answer tokens, aggregated across passage groups with max() as today. The old predict(output_format="tokens") on LLMDetector and RAGFactCheckerDetector keeps returning token, pred and prob dicts: the adapter projects spans onto tokens with today's rule for each class.

Usage

  • A detection reports one Usage per model that ran. model_version is the resolved Hugging Face commit for from_pretrained, the caller's model_version for weights from a local path, and None for an LLM unless the constructor was given model_version. LLMClient.complete keeps returning str, so provider model names and token counts are not available and wait for the LLM-call layer.
  • Encoder units: sources (omitted for a PromptInput), source_chars, answer_chars, input_tokens (tokens fed to the model, summed over passage groups). With a typer, a second entry for the typer with the unit spans.
  • LLM units: llm_calls (calls actually made, the verify pass included), cache_hits, source_chars, answer_chars.
  • RAGFactChecker units: sources, source_chars, answer_chars. Its LLM calls are not countable from outside RAGFactChecker.

Configs

  • Options move from constructor keywords into frozen pydantic models with extra="forbid", passed as config=. None reads the environment. An unknown or invalid option raises ConfigurationError (invalid_config, or invalid_language, invalid_batch_size, with param) at construction.
  • EncoderConfig: max_length=4096, batch_size=16, lang="en".
  • LLMJudgeConfig: temperature=0.0, lang="en", zero_shot=False, fewshot_path=None, prompt_path=None, include_reasoning=False, include_taxonomy=False (a bool, a list of names, a flat dict or the nested dict, as today), min_score=0.0, verify=False, max_concurrency=30. min_score is applied before the verify pass, as min_confidence is today, and the call's min_score is applied to the final spans. A fewshot_path that doesn't exist raises ConfigurationError (fewshot_not_found, param config.fewshot_path).
  • GenerativeConfig: temperature=0.0, lang="en" (used by the verify prompt), include_reasoning=False, include_taxonomy=False (same four forms), verify=False, max_concurrency=30.
  • pydantic-settings classes that fill these configs from the environment or .env files are out of scope.

The detectors

  • EncoderDetector(model, tokenizer, typer=None, *, config=None, model_id=None, model_version=None): takes loaded objects and downloads nothing. from_pretrained(model_id, *, device=None, taxonomy_head=None, include_taxonomy=True, model_version=None, config=None, **loader_kwargs) is the one place a name becomes a model; it logs model_loaded. Scoring, passage grouping and max() aggregation are today's. When the tokenized input exceeds max_length, the result has the warning input_truncated.
  • TaxonomyTyper(encoder, tokenizer, *, categories=None, subcategories=None, max_length=1024, model_id=None, model_version=None): takes loaded objects, with a from_pretrained for the head. With a typer, every span has category and subcategory.
  • LLMJudgeDetector(client, model, *, config=None, cache=None, model_version=None): the zero-shot and few-shot judge, reasoning, taxonomy and verify pass. Items are located in the answer as today (first unused verbatim match, no overlaps). An item that can't be located is dropped with span_not_found, and an item that is neither a string nor an object with text is dropped with item_malformed. An item the model rejected itself (is_hallucination false) is dropped as today.
  • GenerativeDetector(client, model_id, *, config=None, cache=None, model_version=None): the fine-tuned generative models with their frozen prompt, typed spans (explanation becomes reasoning) and the custom taxonomy forms. Locating, dropping and verifying follow the judge's rules.
  • RAGFactCheckerDetector: the constructor is unchanged and gains fact_checker=None, an injected RAGFactChecker, and max_concurrency=30, the bound on concurrent detect calls (below 1 raises ConfigurationError, invalid_config, param max_concurrency). Without it the detector builds one from its old arguments, which is a documented exception to "no client built from a name" because RAGFactChecker sits outside this package. detect and adetect are added, include_detail=True returns a DetailedResult, and a merged span's text is the answer between its offsets.
  • A reply that is not JSON, or lacks hallucination_list (judge) or hallucinated_spans (generative), or has the wrong type, raises UpstreamError (unparseable_response). A verify reply that can't be parsed keeps the first-pass spans and adds verification_skipped.
  • OpenAIClient raises ConfigurationError (authentication_failed, quota_exceeded) for authentication and quota errors, and UpstreamError (upstream_unavailable) for timeouts, connection errors, rate limits and server errors. BedrockClient raises UpstreamError (empty_response) when the reply has no tool call. Foreign errors are chained with raise ... from. Errors raised by a caller's own LLMClient propagate unwrapped.

Caching

  • ResponseCache is a protocol with get(key), set(key, value, *, ttl_seconds=None), delete(key) and aget, aset, adelete. Keys are opaque strings, values are the raw reply string, a missing or expired key returns None. Detectors take cache=None, which means no caching; a detector never builds a cache from a name or a path.
  • make_cache_key(prompt, model, model_version, temperature, kind), with kind one of "judge", "native" and "verify". With model_version=None it returns exactly today's key (SHA-256 of the parts joined by ||, with native or verify as an extra part for those kinds). With a version, the version is an extra part, so the key differs per version.
  • FileCache(path) keeps one JSON file and reads files written by CacheManager. An entry without a TTL is stored as key to string, as today. An entry with a TTL is stored as an object with value and expires_at and is None on read once expired. Writes go to a temporary file in the same directory and are renamed over the file. The constructor touches no disk and the directory is created on the first write. FileCache is for one process and the documentation says so. InMemoryCache has the same behaviour without a disk.
  • A reply is written to the cache only after it parses. A cached entry that doesn't parse is deleted and the call raises UpstreamError (unparseable_response).
  • CacheManager becomes a deprecated subclass of FileCache that keeps get, set, delete, _hash and path.
  • Redis and size eviction are out of scope.

The registry

  • load_detector(model_id, *, client=None, device=None, model_version=None, **options). A registry maps each known KR Labs model id to its detector class. Encoder entries call EncoderDetector.from_pretrained; generative entries build a GenerativeDetector and require client. options go to the entry's config or from_pretrained.
  • The registry holds the ids the README and docs name: KRLabsOrg/lettucedect-base-modernbert-en-v1, KRLabsOrg/lettucedect-large-modernbert-en-v1, KRLabsOrg/lettucedect-v2-mmbert-base, KRLabsOrg/lettucedect-mmbert-base-hu-v1, KRLabsOrg/lettucedect-210m-eurobert-{de,pl,it,fr,es,cn}-v1, KRLabsOrg/lettucedect-610m-eurobert-de-v1 and KRLabsOrg/tinylettuce-ettin-17m-en as encoders, and KRLabsOrg/lettucedect-v2-qwen-2b as the generative model. The task confirms each id against the Hugging Face Hub before merging.
  • An unknown id raises InvalidInputError (unknown_model_id, param model_id) listing the known ids. A generative id without client raises ConfigurationError (client_required). An argument the entry's class doesn't accept raises ConfigurationError (invalid_config). There is no public registration function, and RAGFactCheckerDetector is not in the registry because it has no model id.
  • The name rule that tells a generative model from a judge model survives only inside the deprecated LLMDetector.

Deprecation and adapters

  • LettuceDetectDeprecationWarning subclasses DeprecationWarning and is exported from lettucedetect.detectors. Every message is "X is deprecated since S and will be removed in R. Use U." with S and R taken from two module constants. Marking a class, function or method sets __deprecated__ (PEP 702) and appends a .. deprecated:: note to its docstring. A deprecated argument defaults to a sentinel and warns when the caller passed it. Importing never warns.
  • A deprecated name called from a module inside lettucedetect does not warn. This is temporary: the HallucinationDetector facade calls make_detector and predict* and is not migrated here, so its users must not see warnings for names they never used. The follow-up that migrates the facade removes the rule.
  • The adapters:
    • predict, predict_prompt, predict_prompt_batch: build a request, call detect or detect_batch, and convert the Detection into today's dicts with confidence and prob taken from score. "detailed" is built from detail. They raise typed errors: InvalidInputError (unsupported_output_format, length_mismatch, invalid_min_score with param min_confidence).
    • min_confidence and output_format: map to min_score, and to include_tokens and include_detail.
    • TransformerDetector(model_path=...): a subclass of EncoderDetector that calls from_pretrained, keeps its attributes and its private methods' names, and keeps accepting **tok_kwargs.
    • LLMDetector: builds a LLMJudgeDetector or a GenerativeDetector, choosing by today's name rule or by native=. Without client it builds one from provider and **client_kwargs as today and warns. cache_file builds a FileCache and warns. With no cache_file it writes nothing.
    • make_detector: builds through the adapters.
    • CacheManager: as above.
  • No caller outside the package is changed. The names HallucinationDetector and the scripts use keep working through the adapters.

Errors and logging

  • All new and changed code follows the team's Errors and logging convention (the "Errors and logging" section of the VerbatimRAG CONTRIBUTING.md), which task Read the errors-and-logging convention in CONTRIBUTING.md #132 adds to this repository's CONTRIBUTING.md with these names: content logger lettucedetect.content, warning class LettuceDetectDeprecationWarning.
  • Error classes: InvalidInputError for an argument of a call, ConfigurationError for a constructor argument, a setting or a missing package, UpstreamError for a failed or missing reply from a service.
  • Codes: invalid_min_score, tokens_not_supported, detail_not_supported, unsupported_output_format, length_mismatch, unknown_model_id (InvalidInputError); invalid_config, invalid_language, invalid_batch_size, fewshot_not_found, native_options_conflict, client_required, authentication_failed, quota_exceeded (ConfigurationError); unparseable_response, empty_response, upstream_unavailable (UpstreamError).
  • Warning codes: synthetic_score, span_not_found, item_malformed, verification_skipped, input_truncated.
  • Messages and warnings refer to items by position (requests[3], items[2]) and never contain the answer, a source, a prompt, a span text, a reply or a metadata value. Customer text is logged only on lettucedetect.content, at DEBUG, including the raw LLM reply.
  • Steps of a call log at DEBUG. Loading a model logs model_loaded at INFO. A fallback logs fallback_used with its warning code at WARNING, and the other degraded results log their warning code and counts at WARNING. synthetic_score is informational and logs at DEBUG.
  • The verify fallback is the only fallback. It catches only UpstreamError. A ConfigurationError or InvalidInputError never triggers it.

Release

  • Changelog "Deprecated": TransformerDetector, LLMDetector (and its provider, client_kwargs and cache_file arguments and the omitted client), make_detector, CacheManager, predict, predict_prompt, predict_prompt_batch, and the min_confidence and output_format arguments.
  • Changelog "Changed", through the old API:
    • Spans without confidence today (judge without reasoning, generative) carry confidence 1.0.
    • LLMDetector writes a cache file only when cache_file is passed.
    • An unparseable LLM reply, a native reply without hallucinated_spans and an empty Bedrock reply raise UpstreamError instead of returning no spans.
    • OpenAI authentication and quota errors raise ConfigurationError, and timeouts, connection errors, rate limits and server errors raise UpstreamError, instead of OpenAI's own exceptions.
    • Invalid arguments raise InvalidInputError and ConfigurationError instead of ValueError (subject to the error-class decision).
    • A fewshot_path that doesn't exist raises.
    • A merged RAGFactCheckerDetector span's text equals its offsets.
    • Customer text is no longer logged on module loggers.
    • CacheManager no longer creates its directory in the constructor.
    • The cache key includes the model version when one is passed.
  • The version and the deprecation window come from the decision made elsewhere. Documentation of the new API on the documentation site is a follow-up; the docstring notes reach the API reference through its generated pages.

Testing Decisions

  • A good test goes through a public interface and checks external behaviour: the spans, offsets, scores, warnings, usage and errors a caller sees. Fakes enter through constructor arguments: a fake LLMClient, a stub loaded model with the local test tokenizer, a fake fact checker, an in-memory cache. New tests don't patch module internals or call private helpers. The existing tests that do keep passing unchanged.
  • Seam 1: the detector contract. One reusable suite runs against every detector through detect and adetect. It checks that:
    • every span's text equals the answer between its offsets
    • adetect equals detect
    • a call run in an empty temporary directory set as working directory and HOME leaves it empty
    • a second call with the same input returns the same result, also after a call with other input
    • usage has an entry with the detector's model_id and a model_version field
    • every span has a numeric score and min_score filters on it
    • include_tokens and include_detail raise InvalidInputError where unsupported
    • a call prints nothing and logs no answer or source text on any logger other than lettucedetect.content
    • it runs against an in-test detector, an old-style subclass, and then each detector class as its task lands
  • Seam 2: the cache contract. One suite runs against FileCache and InMemoryCache and checks:
    • a set value reads back, and a missing key returns None
    • an expired entry returns None
    • delete removes an entry
    • sync and async agree
    • concurrent writers from threads lose no key
    • a failure during a FileCache write leaves the previous file intact
    • a file written by CacheManager reads back
    • construction touches no disk
  • Seam 3: the encoder. Stub model, the local_wordpiece_tokenizer fixture and a stub typer: spans and tokens, passage groups, input_truncated, usage, a constructor that downloads nothing, typed spans. Gathered adetect calls on one detector with the real offline tokenizer return each call's own result, and a stub model shows no two scoring calls overlapping.
  • Seam 4: the LLM-backed detectors. A fake client (copy FakeClient and CountingClient): scoring, synthetic_score, dropped items, unparseable replies, the verify fallback, caching and the cache key, llm_calls and cache_hits, and typed client errors.
  • Seam 5: the registry: every registered id resolves to the right class with fakes in place of loading, and the three error cases.
  • Seam 6: batch: order, concurrency limit, encoder padded groups equal to single calls, and the failure reporting once decided. At most max_concurrency client calls in flight across gathered batches and single calls on one instance, and gathered single and padded-batch encoder calls equal sequential results.
  • Seam 7: the old API. Golden fixtures recorded in the first task, compared by one deprecation test module per adapter: warning class and message, output equal to the fixtures, silence for calls from inside the package, and a fresh-interpreter import that emits no LettuceDetectDeprecationWarning.
  • CI: python -m pytest runs everything and installs .[dev], which includes torch and transformers, so all tests gate merges. Tests are network-free (CI sets HF_HUB_OFFLINE) and need no API key. Only tests that need boto3, an optional extra, skip themselves with pytest.importorskip. pytest-asyncio (already in dev) runs the async tests in auto mode, set in pyproject.toml by task Add the ResponseCache protocol, make_cache_key and InMemoryCache #145, or by Add BaseDetector.detect and adetect with min_score and support flags #141 if it lands first.
  • Prior art: tests/test_llm_detector_pytest.py and tests/test_llm_client_pytest.py (fake clients, the cache_file fixture), tests/test_inference_pytest.py (mock tokenizer and model fixtures; copy the fixtures, not the patching), tests/conftest.py (local_wordpiece_tokenizer), tests/test_factory_pytest.py, tests/test_custom_taxonomy_pytest.py and tests/test_cli_pytest.py.

Out of Scope

  • Decisions made elsewhere, which this feature waits for or works around:
    • where Chunk, Span and Usage and the error classes live, whether the error classes are ValueError subclasses, the shape of a result warning, and whether source ids must be unique
    • the result type and failure reporting of detect_batch and adetect_batch; one candidate is a generic result model with a get_or_raise method
    • the release version, the deprecation window and the removal version
    • the LLM-call layer that will replace LLMClient, including provider model names and token counts for usage and LLMClient's reading of environment variables
  • Native async LLM calls: an acomplete on LLMClient (defaulting to to_thread(complete), with AsyncOpenAI created lazily in OpenAIClient) and async drivers for LLMJudgeDetector and GenerativeDetector, which would remove the executor ceiling and make cancellation real. It is additive, so it changes no signature or result in this epic.
    • acomplete keeps to_thread(complete) as its permanent default: BedrockClient (boto3 has no native async), RAGFactChecker and the encoder can't go native, so the thread path and the executor note stay.
    • AsyncOpenAI is bound to the event loop that first uses it and needs closing, so the caller owns the async client, as story 17 already has the caller own the sync one.
    • Do it after the LLM-call layer decision, which is expected to replace LLMClient.
    • It is additive in signature and result, not in behaviour: cancelling adetect would really cancel, the OpenAI path would stop using worker threads, and the per-instance semaphore would become an asyncio.Semaphore. Both behaviour changes go in that release's changelog. Tasks Add LLMJudgeDetector with LLMJudgeConfig and visible failures #158 and Add GenerativeDetector with GenerativeConfig and typed spans #163 keep _detect thin so the async driver can reuse its pure steps.
  • The HallucinationDetector facade and the rest of models/, the CLI, the integrations, the evaluator, lettucedetect_api/ (the HTTP server and client, a /v1/detect route, deprecating the old routes), training, evaluation, datasets, preprocessing and the web demo. Moving them off deprecated names, and removing the rule that keeps in-package calls silent, are follow-ups.
  • Re-exporting the new names and the warning class from the lettucedetect root.
  • The documentation site: a migration page and new API pages. Docstring notes cover the deprecations.
  • RAGFactChecker itself (lettucedetect/ragfactchecker.py), including its reading of OPENAI_API_KEY.
  • lettuce.judge, safety spans and the decision-model detector backend (Add a VelaDetector on the typed detect interface (Vela 2.0): hallucination spans from a decision model #118, Safety spans with Vela 2.0: PII, prompt attacks, unsafe content #119), and evidence aggregation for chunked inference (Define and benchmark evidence aggregation for chunked transformer inference #74): the encoder keeps today's max() aggregation.
  • Lazy top-level imports so the LLM detector never touches torch (Avoid eagerly installing heavy deps for unused detector types #69).
  • A Redis or other network cache backend, and size eviction.
  • pydantic-settings classes that read configs from the environment, and settings for local weight paths.
  • Removing the adapters after the deprecation window.

Further Notes

Pinned by hslev

Sub-issues

Sub-issues

15 of 15 Issues completed
Loading 15 sub-issues

Activity

  1. added
    enhancement
    epic
    ready-for-agent
    on Nov 5, 2026
  2. adaamko commented on Nov 9, 2026

    @adaamko
    Collaborator

    @hslev Thanks a lot, i like the direction. I write here a few suggestions and issues i found going forward. (stateless_core at d0a7d5c (tickets 01–08), focused on the public interfaces.)

    Overall the PRs have been great.Chunk, Span and Usage match verbatim-core field for field, the error classes behave the same way, and EncoderConfig fails at construction with a ConfigurationError. The full suite passes (689 tests), and 300 concurrent detect and adetect calls on one EncoderDetector gave the same results as single calls.

    These are the bugs I found. The first three are worth fixing before more tickets build on them:

    1. EncoderDetector(model, tokenizer, typer): typer is positional. EncoderDetector(model, tok, EncoderConfig(max_length=512)) constructs fine with the config taken as the typer and max_length left at 4096. It fails only at the first span, with AttributeError: 'EncoderConfig' object has no attribute 'type_spans' (encoder.py:240-249). Making everything after tokenizer keyword-only fixes it.
    2. A TransformerDetector subclass that overrides predict is bypassed by detect(). With a subclass whose predict post-filters spans, predict() returns ['short'] and detect() returns ['word', 'short']. Nothing visible breaks today, but once predict_prompt_batch and HallucinationDetector route through detect, such subclasses silently change behaviour. BaseDetector already bridges detect-less subclasses through predict; the same bridge could apply when predict or predict_prompt is overridden.
    3. make_cache_key(kind=...) rejects every kind except judge, native and verify (response_cache.py:29-30). It is public, but the fact-checker (Get triplets and fact-check results from RAGFactCheckerDetector.detect #169) and third-party detectors can't use it with their own kind.
    4. Detection.tokens includes the trailing [SEP] as a flagged token. For a 30-character answer the last entry is TokenScore(token='[SEP]', start=30, end=30, score=0.99, flagged=True) (encoder.py:521-522). The deprecated predict path has to keep this for the golden fixtures, but the new output should drop zero-width tokens. TokenScore also accepts end < start, while Span rejects it.
    5. detect() with a dict request raises AttributeError ('dict' object has no attribute 'answer') instead of InvalidInputError.
    6. A detect-only detector inherits a predict() whose default fails. The default output_format="tokens" raises tokens_not_supported for any detector without token support.
    7. Two doc mismatches. CONTRIBUTING points to tests/test_deprecation.py, but the file is tests/test_deprecation_pytest.py. The EncoderConfig.batch_size docstring describes padded batches, which detect doesn't do until Run many requests with detect_batch and adetect_batch #175.
  3. adaamko commented on Nov 9, 2026

    @adaamko
    Collaborator

    A second list: some design suggestions worth thinking about. Most are cheaper to change now than after tickets 09–14.

    1. An async hook for adetect. Today adetect is to_thread(self.detect, ...), and the contract suite asserts that the call runs in a worker thread and that cancellation leaves it running (tests/detector_contract.py:269-293, :343-383). A native async judge would have to copy the validation and filtering out of detect, and it would fail those tests by design. One option: async def _adetect(...) defaulting to await asyncio.to_thread(self._detect, ...), with adetect doing validation and filtering. The contract would keep the "loop keeps running" check, drop the thread-identity assertion and make the cancellation checks conditional.
    2. model or model_id? The tickets plan LLMJudgeDetector(client, model) and GenerativeDetector(client, model_id). Is model deliberate for the judge because it is a provider model name? If not, model_id everywhere reads better.
    3. Two min_scores. LLMJudgeConfig.min_score filters before the verify pass, and detect(min_score=) filters the final result. A different name for the config one, e.g. verify_min_score, would avoid mixing them up.
    4. load_detector(model_id, **options) routes **options by name to either the config or the loader, so a typo can end up as a loader kwarg. config= plus **loader_kwargs, as in EncoderDetector.from_pretrained, is stricter.
    5. Batch result type. Detection has no error slot, so Run many requests with detect_batch and adetect_batch #175 needs a decision first: list[Detection | LettuceDetectError] (the errors pickle and round-trip fine) or a BatchResult model.
    6. A declared interface for typer. It is Any today, and the real contract is type_spans(answer, context, spans: list[dict]) on the legacy dict shape. A small SpanTyper protocol over DetectedSpan would let the generative detector share it. TaxonomyTyper is named in the EncoderDetector docstring but not exported.
    7. Document score and the unit names. Span.score only says "score in [0, 1]". It is detector-specific and not calibrated, and a caller should check warnings for synthetic_score. The Usage.units keys (sources, source_chars, answer_chars, input_tokens, llm_calls, cache_hits) could be listed in the docstring, so operators can meter against stable names.
    8. One table of error and warning codes (class, code, meaning), in CONTRIBUTING or the errors.py docstring. Today they are spread over the epic and two module docstrings.
    9. Small differences from verbatim-core. ResultWarning.message is str | None here and str there. SourcesInput accepts duplicate chunk ids, which verbatim-core rejects; this starts to matter once spans point to sources.
    10. Legacy-only scoring code in encoder.py (:677-954) is used only by TransformerDetector. Moving it to transformer.py would make the later removal one file.
  4. adaamko commented on Nov 16, 2026

    @adaamko
    Collaborator

    @FurkanAtass after the Vela pull requests, please start on this epic with ticket 12, the fact checker: #169 (#170, #171). It does not depend on the LLM detectors, so it is a good first one.

    The tickets after it, in the order I would take them:

    1. Ticket 09, the LLM judge: Run the LLM judge through LLMJudgeDetector #156 (Raise typed errors from OpenAIClient and BedrockClient #157 to Delegate the LLMDetector judge path to LLMJudgeDetector #161).
    2. Ticket 10, the generative detector: Run the fine-tuned generative models through GenerativeDetector #162 (Add GenerativeDetector with GenerativeConfig and typed spans #163 to Delegate the LLMDetector native path to GenerativeDetector #165). It builds on the typed client errors of Raise typed errors from OpenAIClient and BedrockClient #157.
    3. Ticket 11, the LLMDetector adapter: Keep LLMDetector working as a warning adapter #166 (Warn on deprecated LLMDetector use and stop writing a default cache file #167, Keep LLMDetector predict* output and token projection identical #168).
    4. Ticket 14, batch: Run many requests with detect_batch and adetect_batch #175 (Add detect_batch and adetect_batch with concurrent execution #176 to Route predict_prompt_batch through detect_batch #178). Bug 2 of Bugs: One typed detect interface for the detectors package #192 needs a decision before Route predict_prompt_batch through detect_batch #178.
    5. Ticket 13, load_detector: Build a detector from a model id with load_detector #172 (Add the model registry and load_detector #173, Deprecate make_detector as an adapter #174). VelaDetector can be registered here.
    6. Ticket 15, the changelog: Read the changelog and roadmap for the release #179 (Write the changelog and roadmap entries and set the deprecation constants #180, Update CONTRIBUTING for the new detector interface and test deprecation notes #181).

    One pull request per ticket against stateless_core, please, and request a review on each. The test workflow now runs on those pull requests (#195).

  5. adaamko commented on Dec 2, 2026

    @adaamko
    Collaborator

    Merged into main with #204. Every ticket of the epic is done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

enhancementepicready-for-agent

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions