Skip to content

Add BaseDetector.detect and adetect with min_score and support flags #141

Closed

Description

@hslev

Parent: #140 · Epic: #126 · Blocked by: #135, #139
Work on branch 140-implement-a-detector-against-detect-and-check-it-with-a-contract-suite; commit the changes and close the ticket.

Problem

BaseDetector has only the three predict* methods, whose result shape depends on an argument. There is no typed detect, no async variant, and min_confidence validation raises a bare ValueError.

Current behavior

  • lettucedetect/detectors/base.py:12 predict, :33 predict_prompt, :47 predict_prompt_batch are abstract.
  • base.py:65 _validate_min_confidence raises ValueError; :75 _filter_spans_by_confidence keeps spans that have no confidence key.

Steps

  1. Add detect(request, *, min_score=0.0, include_tokens=False, include_detail=False) -> Detection to BaseDetector. It validates arguments, then calls a protected hook (_detect) that detectors implement.
  2. min_score outside [0, 1] raises InvalidInputError (invalid_min_score, param min_score) before the hook runs. Spans below min_score are dropped; tokens are not.
  3. Add class attributes supports_tokens = False and supports_detail = False. include_tokens / include_detail on an unsupported detector raise InvalidInputError (tokens_not_supported, detail_not_supported) before the hook runs.
  4. Add async def adetect(request, *, min_score=0.0, include_tokens=False, include_detail=False) -> Detection to BaseDetector. It runs detect in a worker thread (asyncio.to_thread), so it never blocks the event loop and every detector gets it without writing it. Detectors implement only _detect; none overrides adetect. The docstring says three things: adetect uses the event loop's default executor, which has min(32, cpu+4) workers (a service with many concurrent calls should size it); that executor is shared with the rest of the service (loop.getaddrinfo uses it too), so a burst of long LLM calls can delay DNS lookups and other to_thread users; and cancelling adetect stops the wait but not the thread. There is no executor argument.
  5. adetect goes through detect, so argument validation, min_score filtering and the support-flag checks apply unchanged. The errors from step 2 and 3 are raised from the awaited call (not at call time), as the same classes with the same code and param; an error raised in the hook propagates unwrapped, with __cause__ intact.
  6. Add a model_id attribute (default None).
  7. The async tests here need asyncio_mode = "auto" under [tool.pytest.ini_options] in pyproject.toml (pytest-asyncio is already in the dev extra). Add the ResponseCache protocol, make_cache_key and InMemoryCache #145 adds that line. Whichever of this ticket and Add the ResponseCache protocol, make_cache_key and InMemoryCache #145 lands first adds it, and the other finds it present.

Acceptance criteria

  • detect and adetect exist with the signature above; adetect returns an equal result.
  • adetect is a coroutine function; the hook runs on a thread other than the event loop's (test: the hook records threading.get_ident()), and a loop ticker keeps running while a slow hook sleeps.
  • Concurrent adetect calls via asyncio.gather return results in call order, each equal to its detect result.
  • The docstring of adetect states the three points of step 4 (default executor and its size; shared with the rest of the service; cancelling stops the wait, not the thread) and says there is no executor argument.
  • The same error cases as detect (out-of-range min_score, unsupported include_tokens / include_detail) raise the same class, code and param from await adetect(...), with the hook not called.
  • An exception raised in the hook propagates from await adetect(...) as the same exception object.
  • Out-of-range min_score and unsupported flags raise the listed errors before the hook is called (test with a hook that fails if called).
  • Spans are filtered by score; tokens are not.
  • Existing subclasses are not yet affected; existing tests pass; follows CONTRIBUTING "Errors and logging".

Start here

uv run --extra dev pytest tests/test_benchmark_detectors_pytest.py tests/test_factory_pytest.py -q

Metadata

Metadata

Assignees

No one assigned

    Labels

    ready-for-agent

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions