Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
# Changelog

## 0.9.0

The integrations can report the hits they didn't serve. Until now they never
sent feedback, so audited and rejected hits made through them produced no
labels.

- `VerifiedCache` (LangChain) takes `judge=`, a function
`judge(question, cached_answer, fresh_answer) -> bool | None`. When a hit is
rejected or audited and your model answers instead, the fresh answer is
judged when LangChain stores it, and the verdict is sent as feedback linked
to that verdict (`verification_id`, or the result itself for a
`LocalVerifier`). It runs in a background thread; judge and report errors
are logged, not raised. `close()` waits for queued reports. These reports
are sent with `label_method="judge"`: they train fine-tunes, but the
service leaves them out of the audit risk bound, the audited CRC threshold
and ACI.
- `feedback()` (`CacheVerifier` and `LocalVerifier`) takes
`label_method="human"|"judge"`. It is sent only when `"judge"`, so
existing calls send the same request as before.
- `CacheVerifierEvaluation.report_feedback` attaches the `verification_id` of
the matching unserved hit (same query and cached answer) on its own, and
takes an explicit `verification_id=`.

## 0.8.0

The integrations no longer switch your cache off during cold start. While a
Expand Down
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,37 @@ first time. Pass `cold_start="reject"` to fall through to your model instead,
for example if you loosened the wrapped cache's similarity threshold because
a verifier would be checking its hits.

### Reporting hits that weren't served

When a hit is rejected or picked for a randomized audit, your model answers
anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when
LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides
whether the cached answer would have been right (`True` / `False`, or `None`
to skip), and the verdict is sent as feedback, linked to the verdict it is
about. It gives fine-tuning labels on audited and rejected hits, which are
otherwise rare. It runs in a background thread, off your request path, and a
failing judge or report is logged, never raised.

These reports are sent as `label_method="judge"`. Judge labels train your
fine-tunes, but the service leaves them out of every number it certifies
(the audit risk bound, the audited CRC threshold, ACI) until a judge can be
checked: a judge that calls wrong answers right would make those numbers look
better than they are. An audit answered only by the judge still counts as
unreported there; to complete audits, report them yourself with
`feedback(..., verification_id=...)`.

```python
def same_answer(question, cached, fresh): # -> True, False, or None to skip
... # your own check, e.g. an LLM call or a rule for your domain

set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer))
```

The judge is yours because "the same answer" depends on your domain: the
cheap automatic checks we measured (answer embeddings, an NLI model) did no
better than the query similarity your cache already has. Without `judge`,
nothing is reported.

## GPTCache

Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
Expand Down Expand Up @@ -205,6 +236,12 @@ so replacing your evaluator also drops the similarity check it did. With
- `direct_hit` serves hits whose fallback score is at least that high without
a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.

When the evaluator doesn't let a hit through (a rejection, or a randomized
audit), GPTCache calls your LLM. Compare its answer with the cached one and
call `report_feedback(query, cached_answer, was_correct=...)` with the same
query and cached answer: the evaluator attaches that verdict's
`verification_id` for you, which is what completes an audit.

See [`examples/gptcache_example.py`](examples/gptcache_example.py).

## Entries to refresh
Expand Down
2 changes: 1 addition & 1 deletion cacheverifier/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from cacheverifier.client import CacheVerifier, CacheVerifierError, ShadowVerdict, VerifyResult
from cacheverifier.local import LocalVerifier, ModelCheckFailed

__version__ = "0.8.0"
__version__ = "0.9.0"
__all__ = [
"CacheVerifier",
"CacheVerifierError",
Expand Down
9 changes: 9 additions & 0 deletions cacheverifier/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ def feedback(
verification_id: int | None = None,
cache_entry_id: str | None = None,
stale: bool = False,
label_method: str = "human",
idempotency_key: str | None = None,
) -> int:
"""Record whether a served (or considered) hit was actually correct.
Expand All @@ -349,14 +350,22 @@ def feedback(
- `stale`: set instead of a bare `was_correct=False` when the answer
is wrong ONLY because a fact changed (price, date, ...), not a
semantic mismatch. Stale rows are excluded from training and drift.
- `label_method`: `"human"` (default: a person, or a signal you vouch
for) or `"judge"` (an automatic check decided `was_correct`). Judge
labels train fine-tunes but are left out of the certified numbers
(audit risk bound, audited CRC threshold, ACI).
- `idempotency_key`: pass a stable key to make retries safe.
"""
if label_method not in ("human", "judge"):
raise ValueError(f'label_method must be "human" or "judge", got {label_method!r}')
payload: dict[str, Any] = {
"query": query,
"candidate_answer": candidate_answer,
"was_correct": was_correct,
"stale": stale,
}
if label_method != "human":
payload["label_method"] = label_method
payload.update(
_drop_none(
similarity_score=similarity_score,
Expand Down
115 changes: 115 additions & 0 deletions cacheverifier/integrations/_reporting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Closing the loop on hits an integration didn't serve.

When a verified hit is rejected or picked for an audit, the caller's model
answers the question anyway. That fresh answer is what tells you whether the
cached one would have been fine: the label an audit needs to complete, and
the rejected-side label fine-tuning otherwise rarely gets. An integration
that sees the fresh answer (LangChain's `update()` after a miss) can hand
both answers to a caller-supplied judge and report its verdict.

The judge is yours on purpose. Whether two answers are "the same" depends on
your domain, and the cheap automatic checks we measured (answer embeddings,
an NLI model) did no better than the query similarity you already have.
"""

from __future__ import annotations

import logging
import threading
from collections import OrderedDict
from collections.abc import Callable, Hashable
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any

from cacheverifier.client import VerifyResult
from cacheverifier.local import LocalVerifier

Judge = Callable[[str, str, str], "bool | None"]
"""`judge(question, cached_answer, fresh_answer)`: True if the cached answer
would have been right for this question, False if not, None to skip."""

MAX_PENDING = 1024
"""Unserved hits remembered while waiting for the fresh answer. Oldest are
dropped first: a fresh answer that never arrives (the model call failed)
must not grow memory without bound."""

_log = logging.getLogger("cacheverifier.integrations")


@dataclass(frozen=True)
class _Pending:
question: str
cached_answer: str
result: VerifyResult


class RejectedHitReporter:
"""Remembers unserved hits by key and, when the fresh answer for the same
key arrives, reports the judge's verdict as feedback. Never raises into
the caller's request path: judge and report errors are logged."""

def __init__(self, client: Any, judge: Judge, *, background: bool = True) -> None:
self._client = client
self._judge = judge
self._lock = threading.Lock()
self._pending: OrderedDict[Hashable, _Pending] = OrderedDict()
self._executor = (
ThreadPoolExecutor(max_workers=1, thread_name_prefix="cacheverifier-report") if background else None
)

def remember(self, key: Hashable, question: str, cached_answer: str, result: VerifyResult) -> None:
"""Call for a hit that was not served: rejected by a model, an audit,
or a cold-start rejection. Outages (`degraded`) carry no verdict and
are not reported."""
if result.degraded or result.approved:
return
with self._lock:
self._pending[key] = _Pending(question, cached_answer, result)
self._pending.move_to_end(key)
while len(self._pending) > MAX_PENDING:
self._pending.popitem(last=False)

def fresh_answer(self, key: Hashable, fresh: str) -> Future[None] | None:
"""Call with the answer the model just produced for `key`."""
with self._lock:
pending = self._pending.pop(key, None)
if pending is None:
return None
if self._executor is None:
self._report(pending, fresh)
return None
return self._executor.submit(self._report, pending, fresh)

def _report(self, pending: _Pending, fresh: str) -> None:
try:
verdict = self._judge(pending.question, pending.cached_answer, fresh)
except Exception as exc: # noqa: BLE001 -- the judge is caller code; never raise into the request path
_log.warning("cacheverifier: judge raised %r; hit not reported", exc)
return
if verdict is None:
return
try:
if isinstance(self._client, LocalVerifier): # links by result, not by id
self._client.feedback(
pending.question,
pending.cached_answer,
bool(verdict),
result=pending.result,
label_method="judge",
)
else:
self._client.feedback(
pending.question,
pending.cached_answer,
bool(verdict),
verification_id=pending.result.verification_id,
label_method="judge",
)
except Exception as exc: # noqa: BLE001 -- a failed report must not break the caller
_log.warning("cacheverifier: reporting an unserved hit failed: %s", exc)

def close(self) -> None:
"""Wait for queued reports to finish."""
if self._executor is not None:
self._executor.shutdown(wait=True)
26 changes: 26 additions & 0 deletions cacheverifier/integrations/gptcache.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@

from __future__ import annotations

import threading
from collections import OrderedDict
from typing import Any

from cacheverifier.client import (
Expand All @@ -38,6 +40,7 @@
CacheVerifier,
)
from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode
from cacheverifier.integrations._reporting import MAX_PENDING

try:
from gptcache.similarity_evaluation import SimilarityEvaluation as _GPTCacheBase
Expand Down Expand Up @@ -100,6 +103,8 @@ def __init__(
self.cold_start = check_mode(cold_start)
self.direct_hit = direct_hit
self._cold_start_notice = ColdStartNotice("CacheVerifierEvaluation")
self._unserved_lock = threading.Lock()
self._unserved: OrderedDict[tuple[str, str], int] = OrderedDict()
self._cv = CacheVerifier(
api_key=api_key,
base_url=base_url,
Expand All @@ -125,6 +130,8 @@ def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwa
query = src_dict.get("question") or src_dict.get("query", "")
candidate_answer = cache_dict.get("answer", "")
result = self._cv.verify(query, candidate_answer)
if not result.approved and result.verification_id is not None:
self._remember_unserved(query, candidate_answer, result.verification_id)
if result.cold_start:
serve = self.cold_start == "serve" and fallback_score is not None
if serve:
Expand All @@ -143,6 +150,13 @@ def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwa
return fallback_score if serve and fallback_score is not None else 0.0
return 1.0 if result.approved else 0.0

def _remember_unserved(self, query: str, candidate_answer: str, verification_id: int) -> None:
with self._unserved_lock:
self._unserved[(query, candidate_answer)] = verification_id
self._unserved.move_to_end((query, candidate_answer))
while len(self._unserved) > MAX_PENDING:
self._unserved.popitem(last=False)

def range(self) -> tuple[float, float]:
return 0.0, 1.0

Expand All @@ -152,6 +166,7 @@ def report_feedback(
candidate_answer: str,
was_correct: bool,
similarity_score: float | None = None,
verification_id: int | None = None,
) -> None:
"""Not part of GPTCache's interface -- call it once you know whether
a served hit was actually correct (a thumbs-down, a reopened
Expand All @@ -162,12 +177,23 @@ def report_feedback(
score for this candidate if you still have it when you learn
`was_correct` -- that is what lets the service later recommend a
tau_high for your GPTCache config (`gray_zone_threshold()`).

Audits and rejections: when this evaluator didn't let a hit through
(a rejection or a randomized audit), GPTCache calls your LLM. Compare
its answer with the cached one and report the result here with the
same `query` and `candidate_answer`: the `verification_id` of that
verdict is attached for you (it is what completes an audit), unless
you pass one yourself.
"""
if verification_id is None:
with self._unserved_lock:
verification_id = self._unserved.pop((query, candidate_answer), None)
self._cv.feedback(
query,
candidate_answer,
was_correct,
similarity_score=similarity_score,
verification_id=verification_id,
)

def close(self) -> None:
Expand Down
Loading
Loading