Repository navigation
Description
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.
predictreturns a list of token dicts or a list of span dicts depending onoutput_format, andRAGFactCheckerDetector.predictreturns a dict for"detailed". The threepredict*methods have no typed result, nousageand no place for a warning.predict_prompt_batchtakes abatch_sizeonTransformerDetectorand not on the others. - Spans don't always carry a score.
LLMDetectorspans have noconfidenceunlessinclude_reasoningis set, and native generative spans never have one.min_confidencekeeps every span without aconfidencekey, so a threshold of 0.9 silently keeps them.RAGFactCheckerDetectorspans 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. RAGFactCheckerDetectorcan return a span whosetextis not the text at its offsets. Merging overlapping spans extendsendand keeps the first span'stext.- Constructors build things from names.
TransformerDetectordownloads the tokenizer, the model and (withtaxonomy_head) theTaxonomyTyperencoder inside the constructor.LLMDetectorbuilds anLLMClientfromproviderwhen none is passed, andOpenAIClientreadsOPENAI_API_KEYandOPENAI_API_BASEand falls back to the key"EMPTY".RAGFactCheckerDetectorbuilds aRAGFactChecker, which readsOPENAI_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_detectortakes a method string and passes**kwargsthrough.LLMDetectordecides 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 examplenativewithzero_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_spanskey, returns no spans.BedrockClientreturns""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 exceedsmax_length. Afewshot_paththat 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.
LLMDetectorbuilds aCacheManagerin its constructor, and with nocache_filethe file iscache_<model>_<lang>.jsoninside the installed package directory. TheCacheManagerconstructor creates that directory, everysetrewrites the whole file with a plainwrite_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,
adetectdoesn't exist, andLLMDetector.predict_prompt_batchruns 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)
- 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.
- As a service developer, I want every error to carry a stable
code(andparamfor an invalid argument) and every result warning a stablecode, so that I can handle and monitor them without parsing messages. - As a service developer, I want to pass a question, sources and an answer to
detectand get aDetection, so that I can serve detection from sources I hold. - As a service developer, I want to pass a full prompt and an answer to
detectand get the sameDetectiontype, so that prompt-based callers use the same interface. - 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
textto equal the answer between them, so that I can highlight it without searching. - As a service developer, I want
min_scoreto drop spans whosescoreis below it, and a value outside [0, 1] to raiseInvalidInputError, so that a threshold means the same on every detector. - As a service developer, I want every span of every detector to have a numeric
score, so thatmin_scoreworks on all of them. - As a service developer, I want one
synthetic_scorewarning on aDetectionwhose scores are constants and not model outputs, so that I can tell a certain flag from an unscored one. - As a service developer, I want
adetectto return the same result asdetectwithout blocking the event loop, so that I can call detectors from async code. - 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.
- 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.contentlogger, so that detectors are safe in a long-running server. - As a service developer, I want
include_tokens=Trueon anEncoderDetectorto returnTokenScoreitems with token text, offsets, score and flag, so that I can show token-level evidence. - As a service developer, I want
include_tokens=Trueandinclude_detail=Trueto raiseInvalidInputErroron detectors that can't provide them, so that I never get fabricated token scores. - As a service developer, I want
include_detail=TrueonRAGFactCheckerDetectorto return the triplets and fact-check results, so that I keep the evidence the fact checker produced. - As a service developer, I want to load encoder weights once with
EncoderDetector.from_pretrainedand to build anEncoderDetectorfrom an already loaded model without any download, so that no request triggers a model load. - As a service developer, I want
from_pretrainedto record the resolved Hugging Face commit asmodel_version, and to take my ownmodel_versionfor weights from a local path, so thatusagenames the exact weights. - As a service developer, I want to pass the LLM client into
LLMJudgeDetectorandGenerativeDetector, so that my service controls credentials, endpoints and connection reuse. - As a service developer, I want an
EncoderDetectorresult to report oneUsagewith the model id, the model version and the unitssources,source_chars,answer_charsandinput_tokens, so that I can see what the call used. - As a service developer, I want an LLM-backed result to report one
Usagewithllm_calls(calls actually made),cache_hits,source_charsandanswer_chars, so that a cache hit is not metered as an LLM call. - As a service developer, I want an encoder with a
TaxonomyTyperto type every span withcategoryandsubcategoryand to report the typer as a secondUsage, so that typed spans are metered like the rest. - 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. - 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 raiseUpstreamError, so that I can tell my misconfiguration from a provider outage. - 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. - 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 withitem_malformed, so that I can monitor how often the LLM drifts. - As a service developer, I want an input that exceeds the encoder's
max_lengthto add the warninginput_truncated, so that I know part of the input was not scored. - As a service developer, I want to pass a
ResponseCacheto an LLM-backed detector, with no caching and no file written when I pass none, so that I choose where replies are kept. - As a service developer, I want an entry stored with a TTL to expire, so that stale replies don't live forever.
- 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.
- 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.
- 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. - 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. - As a service developer, I want an unknown model id to raise
InvalidInputErrorthat lists the known ids, so that a typo is not a silent fallback. - 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. - As a service developer, I want options to be validated config models, and an unknown or invalid option to raise
ConfigurationErrorat construction, so that a misspelt option fails loudly. - As a service developer, I want
detect_batchandadetect_batchto return one result per request in input order, so that I can map results back to requests. - As a service developer, I want the encoder's batch methods to score requests in padded groups of
batch_sizewith the same results as singledetectcalls, so that batching is faster and not different. - 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. - 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)
- As an application developer, I want
HallucinationDetectorto keep returning today's output for every method, so that my pipelines keep working. - As an application developer, I want
TransformerDetector(model_path=...),LLMDetector(...),RAGFactCheckerDetector(...),make_detector,CacheManagerand the threepredict*methods to keep returning today's output, so that I can migrate at my own pace. - As an application developer, I want a deprecated name I use directly to warn with
LettuceDetectDeprecationWarningand 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. - As an application developer, I want importing
lettucedetect.detectorsnever to warn, and a deprecated name called from inside thelettucedetectpackage not to warn, so that I only see warnings for code I wrote. - 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. - As an application developer, I want
LLMDetectorwithout aclientto build today's client and warn that the client should be passed, so that my code keeps running and I learn the explicit form. - As an application developer, I want
LLMDetectorto keep choosing between the judge and the generative detector by today's name rule or bynative=, andnative=Truewithzero_shot,fewshot_pathorprompt_pathto raiseConfigurationError, so that today's calls behave the same. - As an application developer, I want
LLMDetectorto write a cache file only when I passcache_file, so that nothing is written into the installed package. - As an application developer, I want a constructor argument that can't work (an unknown language, a
batch_sizebelow 1, a missingfewshot_path,nativewith judge-only options) to raiseConfigurationErrorwith acodeandparam, so that I see the mistake at construction. - 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. - As an application developer, I want the old
predict*methods to raiseInvalidInputErrorfor an unsupportedoutput_formator mismatched list lengths, so that errors are typed through the old API too. - 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. - 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
- As a contributor writing a detector, I want to implement only
detectand getpredict,predict_promptandpredict_prompt_batchfromBaseDetector, so that old callers keep working with it. - As a contributor with a subclass that implements only the old
predictmethods, I want it to keep working throughdetect, with oneLettuceDetectDeprecationWarningper class, so that I can migrate later. - As a contributor, I want a subclass that implements neither
detectnorpredictto fail withTypeErrorwhen the class is defined, so that I don't get infinite recursion at call time. - 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.
- As a contributor, I want a
TransformerDetectorcreated with__new__and the attributesmodel,tokenizer,device,max_length,langandtyperset by hand to keep answeringpredict, so that evaluation scripts that build one this way keep working.
Maintainer
- 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.
- As a maintainer, I want pytest to turn
LettuceDetectDeprecationWarninginto 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. - 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.
- 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,SpanandUsagelive, whether the error classes areValueErrorsubclasses, 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.textalways equals the answer between the offsets.DetectedSpanextendsSpanwithcategory,subcategoryandreasoning, eachNonewhen not produced.TokenScore:token,start,end,score,flagged.scoreis the model's probability that the token is hallucinated.flaggedis today'spred.DetailedResult:kind="detailed",triplets(answer,context,hallucinated, each a list of triplets),fact_check_results, andspan_triplets, a list parallel toDetection.spansthat holds each span's source triplet orNone.Usage:model_id,model_version,units.SourcesInput:kind="sources",sources(list ofChunk),answer,question(Nonefor summarisation).PromptInput:kind="prompt",prompt,answer.DetectRequestis the union discriminated onkind.Detection:spans,tokens(Noneunless requested),detail(Noneunless requested),usage,warnings.usageandwarningsare 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) -> Detectionandadetectwith the same arguments. Every detector has amodel_id. Per-call arguments are only these three; there is no per-call config.adetectrunsdetectin a worker thread on every detector, becauseLLMClientis synchronous. It uses the event loop's default executor, which hasmin(32, cpu+4)workers, so a service running many concurrent LLM-backed calls should size that executor; there is noexecutorargument. Cancelling anadetectstops the wait but not the thread; the detector and any cache stay valid afterwards (a late cache write holds a parsed reply or nothing, aFileCachefile is never partial), and tests check this. The default executor is also shared with the rest of the service (loop.getaddrinforuns on it too), so a burst of long LLM calls can delay DNS lookups and otherto_threadusers. These points go in theadetectdocstring and the changelog.- Concurrency limits.
LLMJudgeDetectorandGenerativeDetectoreach hold onethreading.BoundedSemaphore(config.max_concurrency)per instance (max_concurrencybelow 1 raisesConfigurationError,invalid_config, paramconfig.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_batchandadetect_batchall go through it, so at mostmax_concurrencyclient calls are in flight on one instance however they were started, and a batch can't deadlock on it.RAGFactCheckerDetectorgains amax_concurrency=30keyword and bounds concurrentdetectcalls the same way, because its LLM calls happen insideRAGFactChecker.EncoderDetectorholds one privatethreading.RLockaround its whole scoring path (tokenize, forward pass, aggregate), so concurrent calls on one instance run one at a time. The reason:transformersrewrites the fast tokenizer's truncation and padding settings on every call, so concurrent calls on one tokenizer can return wrong tokens or raiseValueError(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 aTransformerDetectorbuilt 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_scorekeeps a span when itsscoreis not below it. A value outside [0, 1] raisesInvalidInputError(invalid_min_score, parammin_score) before any model or client call. Tokens are not filtered bymin_score.include_tokens=Trueis supported only byEncoderDetector, andinclude_detail=Trueonly byRAGFactCheckerDetector. Elsewhere they raiseInvalidInputError(tokens_not_supported,detail_not_supported, paraminclude_tokensorinclude_detail) before any model or client call.detect_batchandadetect_batchtake a sequence ofDetectRequestand 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. BaseDetectorkeeps both interfaces. A subclass that implements onlypredict,predict_promptandpredict_prompt_batchgetsdetectfrom the base class:SourcesInputgoes topredict,PromptInputtopredict_prompt,confidencebecomesscore, a span withoutconfidencegets score 1.0 plus thesynthetic_scorewarning, and the base class warns once per subclass. Such a detector'susagehas one entry with itsmodel_idattribute (Nonewhen absent), andinclude_tokensandinclude_detailraise. A subclass that implements onlydetectgets the threepredict*methods from the base class. A subclass that implements neither raisesTypeErrorwhen defined.BaseDetectoritself is never marked deprecated.
Scores, tokens and detail
- Encoder:
scoreis the maximum token probability of the span. LLM judge: the model's ownconfidencewithinclude_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
Detectiongets exactly onesynthetic_scorewarning when any span's score is a constant: the 1.0 paths, the RAGFactChecker constants and the old-subclass conversion. A model's ownconfidenceis not synthetic. - Token scoring (
include_tokens) is the encoder's own, over its answer tokens, aggregated across passage groups withmax()as today. The oldpredict(output_format="tokens")onLLMDetectorandRAGFactCheckerDetectorkeeps returningtoken,predandprobdicts: the adapter projects spans onto tokens with today's rule for each class.
Usage
- A detection reports one
Usageper model that ran.model_versionis the resolved Hugging Face commit forfrom_pretrained, the caller'smodel_versionfor weights from a local path, andNonefor an LLM unless the constructor was givenmodel_version.LLMClient.completekeeps returningstr, so provider model names and token counts are not available and wait for the LLM-call layer. - Encoder units:
sources(omitted for aPromptInput),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 unitspans. - 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 outsideRAGFactChecker.
Configs
- Options move from constructor keywords into frozen pydantic models with
extra="forbid", passed asconfig=. None reads the environment. An unknown or invalid option raisesConfigurationError(invalid_config, orinvalid_language,invalid_batch_size, withparam) 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_scoreis applied before the verify pass, asmin_confidenceis today, and the call'smin_scoreis applied to the final spans. Afewshot_paththat doesn't exist raisesConfigurationError(fewshot_not_found, paramconfig.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-settingsclasses that fill these configs from the environment or.envfiles 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 logsmodel_loaded. Scoring, passage grouping andmax()aggregation are today's. When the tokenized input exceedsmax_length, the result has the warninginput_truncated.TaxonomyTyper(encoder, tokenizer, *, categories=None, subcategories=None, max_length=1024, model_id=None, model_version=None): takes loaded objects, with afrom_pretrainedfor the head. With a typer, every span hascategoryandsubcategory.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 withspan_not_found, and an item that is neither a string nor an object withtextis dropped withitem_malformed. An item the model rejected itself (is_hallucinationfalse) 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 (explanationbecomesreasoning) and the custom taxonomy forms. Locating, dropping and verifying follow the judge's rules.RAGFactCheckerDetector: the constructor is unchanged and gainsfact_checker=None, an injectedRAGFactChecker, andmax_concurrency=30, the bound on concurrentdetectcalls (below 1 raisesConfigurationError,invalid_config, parammax_concurrency). Without it the detector builds one from its old arguments, which is a documented exception to "no client built from a name" becauseRAGFactCheckersits outside this package.detectandadetectare added,include_detail=Truereturns aDetailedResult, and a merged span'stextis the answer between its offsets.- A reply that is not JSON, or lacks
hallucination_list(judge) orhallucinated_spans(generative), or has the wrong type, raisesUpstreamError(unparseable_response). A verify reply that can't be parsed keeps the first-pass spans and addsverification_skipped. OpenAIClientraisesConfigurationError(authentication_failed,quota_exceeded) for authentication and quota errors, andUpstreamError(upstream_unavailable) for timeouts, connection errors, rate limits and server errors.BedrockClientraisesUpstreamError(empty_response) when the reply has no tool call. Foreign errors are chained withraise ... from. Errors raised by a caller's ownLLMClientpropagate unwrapped.
Caching
ResponseCacheis a protocol withget(key),set(key, value, *, ttl_seconds=None),delete(key)andaget,aset,adelete. Keys are opaque strings, values are the raw reply string, a missing or expired key returnsNone. Detectors takecache=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), withkindone of"judge","native"and"verify". Withmodel_version=Noneit returns exactly today's key (SHA-256 of the parts joined by||, withnativeorverifyas 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 byCacheManager. An entry without a TTL is stored as key to string, as today. An entry with a TTL is stored as an object withvalueandexpires_atand isNoneon 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.FileCacheis for one process and the documentation says so.InMemoryCachehas 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). CacheManagerbecomes a deprecated subclass ofFileCachethat keepsget,set,delete,_hashandpath.- 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 callEncoderDetector.from_pretrained; generative entries build aGenerativeDetectorand requireclient.optionsgo to the entry's config orfrom_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-v1andKRLabsOrg/tinylettuce-ettin-17m-enas encoders, andKRLabsOrg/lettucedect-v2-qwen-2bas the generative model. The task confirms each id against the Hugging Face Hub before merging. - An unknown id raises
InvalidInputError(unknown_model_id, parammodel_id) listing the known ids. A generative id withoutclientraisesConfigurationError(client_required). An argument the entry's class doesn't accept raisesConfigurationError(invalid_config). There is no public registration function, andRAGFactCheckerDetectoris 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
LettuceDetectDeprecationWarningsubclassesDeprecationWarningand is exported fromlettucedetect.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
lettucedetectdoes not warn. This is temporary: theHallucinationDetectorfacade callsmake_detectorandpredict*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, calldetectordetect_batch, and convert theDetectioninto today's dicts withconfidenceandprobtaken fromscore."detailed"is built fromdetail. They raise typed errors:InvalidInputError(unsupported_output_format,length_mismatch,invalid_min_scorewith parammin_confidence).min_confidenceandoutput_format: map tomin_score, and toinclude_tokensandinclude_detail.TransformerDetector(model_path=...): a subclass ofEncoderDetectorthat callsfrom_pretrained, keeps its attributes and its private methods' names, and keeps accepting**tok_kwargs.LLMDetector: builds aLLMJudgeDetectoror aGenerativeDetector, choosing by today's name rule or bynative=. Withoutclientit builds one fromproviderand**client_kwargsas today and warns.cache_filebuilds aFileCacheand warns. With nocache_fileit writes nothing.make_detector: builds through the adapters.CacheManager: as above.
- No caller outside the package is changed. The names
HallucinationDetectorand 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'sCONTRIBUTING.mdwith these names: content loggerlettucedetect.content, warning classLettuceDetectDeprecationWarning. - Error classes:
InvalidInputErrorfor an argument of a call,ConfigurationErrorfor a constructor argument, a setting or a missing package,UpstreamErrorfor 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 onlettucedetect.content, at DEBUG, including the raw LLM reply. - Steps of a call log at DEBUG. Loading a model logs
model_loadedat INFO. A fallback logsfallback_usedwith its warning code at WARNING, and the other degraded results log their warning code and counts at WARNING.synthetic_scoreis informational and logs at DEBUG. - The verify fallback is the only fallback. It catches only
UpstreamError. AConfigurationErrororInvalidInputErrornever triggers it.
Release
- Changelog "Deprecated":
TransformerDetector,LLMDetector(and itsprovider,client_kwargsandcache_filearguments and the omittedclient),make_detector,CacheManager,predict,predict_prompt,predict_prompt_batch, and themin_confidenceandoutput_formatarguments. - Changelog "Changed", through the old API:
- Spans without
confidencetoday (judge without reasoning, generative) carryconfidence1.0. LLMDetectorwrites a cache file only whencache_fileis passed.- An unparseable LLM reply, a native reply without
hallucinated_spansand an empty Bedrock reply raiseUpstreamErrorinstead of returning no spans. - OpenAI authentication and quota errors raise
ConfigurationError, and timeouts, connection errors, rate limits and server errors raiseUpstreamError, instead of OpenAI's own exceptions. - Invalid arguments raise
InvalidInputErrorandConfigurationErrorinstead ofValueError(subject to the error-class decision). - A
fewshot_paththat doesn't exist raises. - A merged
RAGFactCheckerDetectorspan'stextequals its offsets. - Customer text is no longer logged on module loggers.
CacheManagerno longer creates its directory in the constructor.- The cache key includes the model version when one is passed.
- Spans without
- 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
detectandadetect. It checks that:- every span's text equals the answer between its offsets
adetectequalsdetect- a call run in an empty temporary directory set as working directory and
HOMEleaves it empty - a second call with the same input returns the same result, also after a call with other input
usagehas an entry with the detector'smodel_idand amodel_versionfield- every span has a numeric
scoreandmin_scorefilters on it include_tokensandinclude_detailraiseInvalidInputErrorwhere 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
FileCacheandInMemoryCacheand 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
FileCachewrite leaves the previous file intact - a file written by
CacheManagerreads back - construction touches no disk
- a set value reads back, and a missing key returns
- Seam 3: the encoder. Stub model, the
local_wordpiece_tokenizerfixture and a stub typer: spans and tokens, passage groups,input_truncated,usage, a constructor that downloads nothing, typed spans. Gatheredadetectcalls 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
FakeClientandCountingClient): scoring,synthetic_score, dropped items, unparseable replies, the verify fallback, caching and the cache key,llm_callsandcache_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_concurrencyclient 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 pytestruns everything and installs.[dev], which includes torch and transformers, so all tests gate merges. Tests are network-free (CI setsHF_HUB_OFFLINE) and need no API key. Only tests that needboto3, an optional extra, skip themselves withpytest.importorskip.pytest-asyncio(already indev) runs the async tests inautomode, set inpyproject.tomlby 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.pyandtests/test_llm_client_pytest.py(fake clients, thecache_filefixture),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.pyandtests/test_cli_pytest.py.
Out of Scope
- Decisions made elsewhere, which this feature waits for or works around:
- where
Chunk,SpanandUsageand the error classes live, whether the error classes areValueErrorsubclasses, the shape of a result warning, and whether source ids must be unique - the result type and failure reporting of
detect_batchandadetect_batch; one candidate is a generic result model with aget_or_raisemethod - 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 forusageandLLMClient's reading of environment variables
- where
- Native async LLM calls: an
acompleteonLLMClient(defaulting toto_thread(complete), withAsyncOpenAIcreated lazily inOpenAIClient) and async drivers forLLMJudgeDetectorandGenerativeDetector, which would remove the executor ceiling and make cancellation real. It is additive, so it changes no signature or result in this epic.acompletekeepsto_thread(complete)as its permanent default:BedrockClient(boto3 has no native async),RAGFactCheckerand the encoder can't go native, so the thread path and the executor note stay.AsyncOpenAIis 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
adetectwould really cancel, the OpenAI path would stop using worker threads, and the per-instance semaphore would become anasyncio.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_detectthin so the async driver can reuse its pure steps.
- The
HallucinationDetectorfacade and the rest ofmodels/, the CLI, the integrations, the evaluator,lettucedetect_api/(the HTTP server and client, a/v1/detectroute, 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
lettucedetectroot. - The documentation site: a migration page and new API pages. Docstring notes cover the deprecations.
RAGFactCheckeritself (lettucedetect/ragfactchecker.py), including its reading ofOPENAI_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'smax()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-settingsclasses that read configs from the environment, and settings for local weight paths.- Removing the adapters after the deprecation window.
Further Notes
- Prerequisites:
- The errors-and-logging convention in task Read the errors-and-logging convention in CONTRIBUTING.md #132 is copied from the team's VerbatimRAG
CONTRIBUTING.md(branchstateless_core).
- The errors-and-logging convention in task Read the errors-and-logging convention in CONTRIBUTING.md #132 is copied from the team's VerbatimRAG
- Blocked by decisions made elsewhere:
- Task Build detect requests and read typed results and errors #137 and every task after it wait for the shared-types and error-class decision.
- Task Run many requests with detect_batch and adetect_batch #175 waits for the batch result decision.
- Task Read the changelog and roadmap for the release #179, and the values of the two constants in task See one consistent warning for every deprecated name #134, wait for the version and window decision.
- Tasks Record golden fixtures for today's detector API #127, Read the errors-and-logging convention in CONTRIBUTING.md #132, See one consistent warning for every deprecated name #134 and Pass a ResponseCache to a detector #144 can start immediately (task Pass a ResponseCache to a detector #144 needs only task See one consistent warning for every deprecated name #134).
- Where the design documents and today's code differ (the code is followed for "today"):
- The design says the LLM detector reports a fixed 0.9 or 0.1 per token. With
include_reasoningit reports the span'sconfidence, andRAGFactCheckerDetectoralso emits fixed tokens, so "only the encoder scores tokens" is a decision of this feature and not a description of today. - The design says usage's
model_versionis the model name the provider returned.LLMClient.completereturns only a string, so that value is not available. - The design lists no per-call
config, and this feature follows it, although the shared document says per-call settings are call arguments. - The design says "no cache in the core"; this feature adds a
ResponseCachethat detectors use only when the caller passes one.
- The design says the LLM detector reports a fixed 0.9 or 0.1 per token. With
- Suggested order of the tasks:
- Record golden fixtures for today's detector API #127, Read the errors-and-logging convention in CONTRIBUTING.md #132 and See one consistent warning for every deprecated name #134, in parallel
- Build detect requests and read typed results and errors #137 (after the shared-types decision) and Pass a ResponseCache to a detector #144
- Implement a detector against detect and check it with a contract suite #140
- Load an EncoderDetector explicitly and call detect #148, Run the LLM judge through LLMJudgeDetector #156 and Get triplets and fact-check results from RAGFactCheckerDetector.detect #169, in parallel
- Get typed spans from the encoder #153 and Run the fine-tuned generative models through GenerativeDetector #162
- Keep LLMDetector working as a warning adapter #166 and Build a detector from a model id with load_detector #172
- Run many requests with detect_batch and adetect_batch #175 (after the batch decision)
- Read the changelog and roadmap for the release #179
@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:
-
EncoderDetector(model, tokenizer, typer):typeris positional.EncoderDetec…
Activity
adaamko commentedon Nov 9, 2026
@hslev Thanks a lot, i like the direction. I write here a few suggestions and issues i found going forward. (
stateless_coreat d0a7d5c (tickets 01–08), focused on the public interfaces.)Overall the PRs have been great.
Chunk,SpanandUsagematch verbatim-core field for field, the error classes behave the same way, andEncoderConfigfails at construction with aConfigurationError. The full suite passes (689 tests), and 300 concurrentdetectandadetectcalls on oneEncoderDetectorgave the same results as single calls.These are the bugs I found. The first three are worth fixing before more tickets build on them:
EncoderDetector(model, tokenizer, typer):typeris positional.EncoderDetector(model, tok, EncoderConfig(max_length=512))constructs fine with the config taken as the typer andmax_lengthleft at 4096. It fails only at the first span, withAttributeError: 'EncoderConfig' object has no attribute 'type_spans'(encoder.py:240-249). Making everything aftertokenizerkeyword-only fixes it.TransformerDetectorsubclass that overridespredictis bypassed bydetect(). With a subclass whosepredictpost-filters spans,predict()returns['short']anddetect()returns['word', 'short']. Nothing visible breaks today, but oncepredict_prompt_batchandHallucinationDetectorroute throughdetect, such subclasses silently change behaviour.BaseDetectoralready bridges detect-less subclasses throughpredict; the same bridge could apply whenpredictorpredict_promptis overridden.make_cache_key(kind=...)rejects every kind exceptjudge,nativeandverify(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.Detection.tokensincludes the trailing[SEP]as a flagged token. For a 30-character answer the last entry isTokenScore(token='[SEP]', start=30, end=30, score=0.99, flagged=True)(encoder.py:521-522). The deprecatedpredictpath has to keep this for the golden fixtures, but the new output should drop zero-width tokens.TokenScorealso acceptsend < start, whileSpanrejects it.detect()with a dict request raisesAttributeError('dict' object has no attribute 'answer') instead ofInvalidInputError.predict()whose default fails. The defaultoutput_format="tokens"raisestokens_not_supportedfor any detector without token support.tests/test_deprecation.py, but the file istests/test_deprecation_pytest.py. TheEncoderConfig.batch_sizedocstring describes padded batches, whichdetectdoesn't do until Run many requests with detect_batch and adetect_batch #175.adaamko commentedon Nov 9, 2026
A second list: some design suggestions worth thinking about. Most are cheaper to change now than after tickets 09–14.
adetect. Todayadetectisto_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 ofdetect, and it would fail those tests by design. One option:async def _adetect(...)defaulting toawait asyncio.to_thread(self._detect, ...), withadetectdoing validation and filtering. The contract would keep the "loop keeps running" check, drop the thread-identity assertion and make the cancellation checks conditional.modelormodel_id? The tickets planLLMJudgeDetector(client, model)andGenerativeDetector(client, model_id). Ismodeldeliberate for the judge because it is a provider model name? If not,model_ideverywhere reads better.min_scores.LLMJudgeConfig.min_scorefilters before the verify pass, anddetect(min_score=)filters the final result. A different name for the config one, e.g.verify_min_score, would avoid mixing them up.load_detector(model_id, **options)routes**optionsby name to either the config or the loader, so a typo can end up as a loader kwarg.config=plus**loader_kwargs, as inEncoderDetector.from_pretrained, is stricter.Detectionhas 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 aBatchResultmodel.typer. It isAnytoday, and the real contract istype_spans(answer, context, spans: list[dict])on the legacy dict shape. A smallSpanTyperprotocol overDetectedSpanwould let the generative detector share it.TaxonomyTyperis named in theEncoderDetectordocstring but not exported.scoreand the unit names.Span.scoreonly says "score in [0, 1]". It is detector-specific and not calibrated, and a caller should checkwarningsforsynthetic_score. TheUsage.unitskeys (sources,source_chars,answer_chars,input_tokens,llm_calls,cache_hits) could be listed in the docstring, so operators can meter against stable names.errors.pydocstring. Today they are spread over the epic and two module docstrings.ResultWarning.messageisstr | Nonehere andstrthere.SourcesInputaccepts duplicate chunk ids, which verbatim-core rejects; this starts to matter once spans point to sources.encoder.py(:677-954) is used only byTransformerDetector. Moving it totransformer.pywould make the later removal one file.adaamko commentedon Nov 16, 2026
@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:
LLMDetectoradapter: 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).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).VelaDetectorcan be registered here.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).adaamko commentedon Dec 2, 2026
Merged into
mainwith #204. Every ticket of the epic is done.