cacheverifier 0.8.0__tar.gz → 0.9.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/CHANGELOG.md +23 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/PKG-INFO +38 -1
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/README.md +37 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/__init__.py +1 -1
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/client.py +9 -0
- cacheverifier-0.9.0/cacheverifier/integrations/_reporting.py +115 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/integrations/gptcache.py +26 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/integrations/langchain.py +44 -6
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/local.py +2 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/pyproject.toml +1 -1
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/tests/test_client.py +17 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/tests/test_gptcache_integration.py +23 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/tests/test_langchain_integration.py +78 -0
- cacheverifier-0.9.0/tests/test_reporting.py +50 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/.github/workflows/ci.yml +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/.github/workflows/publish.yml +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/.gitignore +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/LICENSE +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/__main__.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/__init__.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/_base_models.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/_finetune.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/_healthcheck/cli.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/_inference.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/integrations/__init__.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/integrations/_cold_start.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/cacheverifier/py.typed +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/examples/gptcache_example.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/examples/quickstart.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/tests/test_healthcheck.py +0 -0
- {cacheverifier-0.8.0 → cacheverifier-0.9.0}/tests/test_local.py +0 -0
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
The integrations can report the hits they didn't serve. Until now they never
|
|
6
|
+
sent feedback, so audited and rejected hits made through them produced no
|
|
7
|
+
labels.
|
|
8
|
+
|
|
9
|
+
- `VerifiedCache` (LangChain) takes `judge=`, a function
|
|
10
|
+
`judge(question, cached_answer, fresh_answer) -> bool | None`. When a hit is
|
|
11
|
+
rejected or audited and your model answers instead, the fresh answer is
|
|
12
|
+
judged when LangChain stores it, and the verdict is sent as feedback linked
|
|
13
|
+
to that verdict (`verification_id`, or the result itself for a
|
|
14
|
+
`LocalVerifier`). It runs in a background thread; judge and report errors
|
|
15
|
+
are logged, not raised. `close()` waits for queued reports. These reports
|
|
16
|
+
are sent with `label_method="judge"`: they train fine-tunes, but the
|
|
17
|
+
service leaves them out of the audit risk bound, the audited CRC threshold
|
|
18
|
+
and ACI.
|
|
19
|
+
- `feedback()` (`CacheVerifier` and `LocalVerifier`) takes
|
|
20
|
+
`label_method="human"|"judge"`. It is sent only when `"judge"`, so
|
|
21
|
+
existing calls send the same request as before.
|
|
22
|
+
- `CacheVerifierEvaluation.report_feedback` attaches the `verification_id` of
|
|
23
|
+
the matching unserved hit (same query and cached answer) on its own, and
|
|
24
|
+
takes an explicit `verification_id=`.
|
|
25
|
+
|
|
3
26
|
## 0.8.0
|
|
4
27
|
|
|
5
28
|
The integrations no longer switch your cache off during cold start. While a
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: cacheverifier
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.0
|
|
4
4
|
Summary: Python client for the CacheVerifier semantic-cache verification API, hosted or scored locally
|
|
5
5
|
Project-URL: Homepage, https://www.cacheverifier.com
|
|
6
6
|
Project-URL: Documentation, https://www.cacheverifier.com/docs
|
|
@@ -214,6 +214,37 @@ first time. Pass `cold_start="reject"` to fall through to your model instead,
|
|
|
214
214
|
for example if you loosened the wrapped cache's similarity threshold because
|
|
215
215
|
a verifier would be checking its hits.
|
|
216
216
|
|
|
217
|
+
### Reporting hits that weren't served
|
|
218
|
+
|
|
219
|
+
When a hit is rejected or picked for a randomized audit, your model answers
|
|
220
|
+
anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when
|
|
221
|
+
LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides
|
|
222
|
+
whether the cached answer would have been right (`True` / `False`, or `None`
|
|
223
|
+
to skip), and the verdict is sent as feedback, linked to the verdict it is
|
|
224
|
+
about. It gives fine-tuning labels on audited and rejected hits, which are
|
|
225
|
+
otherwise rare. It runs in a background thread, off your request path, and a
|
|
226
|
+
failing judge or report is logged, never raised.
|
|
227
|
+
|
|
228
|
+
These reports are sent as `label_method="judge"`. Judge labels train your
|
|
229
|
+
fine-tunes, but the service leaves them out of every number it certifies
|
|
230
|
+
(the audit risk bound, the audited CRC threshold, ACI) until a judge can be
|
|
231
|
+
checked: a judge that calls wrong answers right would make those numbers look
|
|
232
|
+
better than they are. An audit answered only by the judge still counts as
|
|
233
|
+
unreported there; to complete audits, report them yourself with
|
|
234
|
+
`feedback(..., verification_id=...)`.
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
def same_answer(question, cached, fresh): # -> True, False, or None to skip
|
|
238
|
+
... # your own check, e.g. an LLM call or a rule for your domain
|
|
239
|
+
|
|
240
|
+
set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer))
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
The judge is yours because "the same answer" depends on your domain: the
|
|
244
|
+
cheap automatic checks we measured (answer embeddings, an NLI model) did no
|
|
245
|
+
better than the query similarity your cache already has. Without `judge`,
|
|
246
|
+
nothing is reported.
|
|
247
|
+
|
|
217
248
|
## GPTCache
|
|
218
249
|
|
|
219
250
|
Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
|
|
@@ -244,6 +275,12 @@ so replacing your evaluator also drops the similarity check it did. With
|
|
|
244
275
|
- `direct_hit` serves hits whose fallback score is at least that high without
|
|
245
276
|
a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
|
|
246
277
|
|
|
278
|
+
When the evaluator doesn't let a hit through (a rejection, or a randomized
|
|
279
|
+
audit), GPTCache calls your LLM. Compare its answer with the cached one and
|
|
280
|
+
call `report_feedback(query, cached_answer, was_correct=...)` with the same
|
|
281
|
+
query and cached answer: the evaluator attaches that verdict's
|
|
282
|
+
`verification_id` for you, which is what completes an audit.
|
|
283
|
+
|
|
247
284
|
See [`examples/gptcache_example.py`](examples/gptcache_example.py).
|
|
248
285
|
|
|
249
286
|
## Entries to refresh
|
|
@@ -175,6 +175,37 @@ first time. Pass `cold_start="reject"` to fall through to your model instead,
|
|
|
175
175
|
for example if you loosened the wrapped cache's similarity threshold because
|
|
176
176
|
a verifier would be checking its hits.
|
|
177
177
|
|
|
178
|
+
### Reporting hits that weren't served
|
|
179
|
+
|
|
180
|
+
When a hit is rejected or picked for a randomized audit, your model answers
|
|
181
|
+
anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when
|
|
182
|
+
LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides
|
|
183
|
+
whether the cached answer would have been right (`True` / `False`, or `None`
|
|
184
|
+
to skip), and the verdict is sent as feedback, linked to the verdict it is
|
|
185
|
+
about. It gives fine-tuning labels on audited and rejected hits, which are
|
|
186
|
+
otherwise rare. It runs in a background thread, off your request path, and a
|
|
187
|
+
failing judge or report is logged, never raised.
|
|
188
|
+
|
|
189
|
+
These reports are sent as `label_method="judge"`. Judge labels train your
|
|
190
|
+
fine-tunes, but the service leaves them out of every number it certifies
|
|
191
|
+
(the audit risk bound, the audited CRC threshold, ACI) until a judge can be
|
|
192
|
+
checked: a judge that calls wrong answers right would make those numbers look
|
|
193
|
+
better than they are. An audit answered only by the judge still counts as
|
|
194
|
+
unreported there; to complete audits, report them yourself with
|
|
195
|
+
`feedback(..., verification_id=...)`.
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
def same_answer(question, cached, fresh): # -> True, False, or None to skip
|
|
199
|
+
... # your own check, e.g. an LLM call or a rule for your domain
|
|
200
|
+
|
|
201
|
+
set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer))
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
The judge is yours because "the same answer" depends on your domain: the
|
|
205
|
+
cheap automatic checks we measured (answer embeddings, an NLI model) did no
|
|
206
|
+
better than the query similarity your cache already has. Without `judge`,
|
|
207
|
+
nothing is reported.
|
|
208
|
+
|
|
178
209
|
## GPTCache
|
|
179
210
|
|
|
180
211
|
Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
|
|
@@ -205,6 +236,12 @@ so replacing your evaluator also drops the similarity check it did. With
|
|
|
205
236
|
- `direct_hit` serves hits whose fallback score is at least that high without
|
|
206
237
|
a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
|
|
207
238
|
|
|
239
|
+
When the evaluator doesn't let a hit through (a rejection, or a randomized
|
|
240
|
+
audit), GPTCache calls your LLM. Compare its answer with the cached one and
|
|
241
|
+
call `report_feedback(query, cached_answer, was_correct=...)` with the same
|
|
242
|
+
query and cached answer: the evaluator attaches that verdict's
|
|
243
|
+
`verification_id` for you, which is what completes an audit.
|
|
244
|
+
|
|
208
245
|
See [`examples/gptcache_example.py`](examples/gptcache_example.py).
|
|
209
246
|
|
|
210
247
|
## Entries to refresh
|
|
@@ -19,7 +19,7 @@ Research behind it: https://github.com/imxinchengyou/CacheVerifier
|
|
|
19
19
|
from cacheverifier.client import CacheVerifier, CacheVerifierError, ShadowVerdict, VerifyResult
|
|
20
20
|
from cacheverifier.local import LocalVerifier, ModelCheckFailed
|
|
21
21
|
|
|
22
|
-
__version__ = "0.
|
|
22
|
+
__version__ = "0.9.0"
|
|
23
23
|
__all__ = [
|
|
24
24
|
"CacheVerifier",
|
|
25
25
|
"CacheVerifierError",
|
|
@@ -329,6 +329,7 @@ class CacheVerifier:
|
|
|
329
329
|
verification_id: int | None = None,
|
|
330
330
|
cache_entry_id: str | None = None,
|
|
331
331
|
stale: bool = False,
|
|
332
|
+
label_method: str = "human",
|
|
332
333
|
idempotency_key: str | None = None,
|
|
333
334
|
) -> int:
|
|
334
335
|
"""Record whether a served (or considered) hit was actually correct.
|
|
@@ -349,14 +350,22 @@ class CacheVerifier:
|
|
|
349
350
|
- `stale`: set instead of a bare `was_correct=False` when the answer
|
|
350
351
|
is wrong ONLY because a fact changed (price, date, ...), not a
|
|
351
352
|
semantic mismatch. Stale rows are excluded from training and drift.
|
|
353
|
+
- `label_method`: `"human"` (default: a person, or a signal you vouch
|
|
354
|
+
for) or `"judge"` (an automatic check decided `was_correct`). Judge
|
|
355
|
+
labels train fine-tunes but are left out of the certified numbers
|
|
356
|
+
(audit risk bound, audited CRC threshold, ACI).
|
|
352
357
|
- `idempotency_key`: pass a stable key to make retries safe.
|
|
353
358
|
"""
|
|
359
|
+
if label_method not in ("human", "judge"):
|
|
360
|
+
raise ValueError(f'label_method must be "human" or "judge", got {label_method!r}')
|
|
354
361
|
payload: dict[str, Any] = {
|
|
355
362
|
"query": query,
|
|
356
363
|
"candidate_answer": candidate_answer,
|
|
357
364
|
"was_correct": was_correct,
|
|
358
365
|
"stale": stale,
|
|
359
366
|
}
|
|
367
|
+
if label_method != "human":
|
|
368
|
+
payload["label_method"] = label_method
|
|
360
369
|
payload.update(
|
|
361
370
|
_drop_none(
|
|
362
371
|
similarity_score=similarity_score,
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Closing the loop on hits an integration didn't serve.
|
|
2
|
+
|
|
3
|
+
When a verified hit is rejected or picked for an audit, the caller's model
|
|
4
|
+
answers the question anyway. That fresh answer is what tells you whether the
|
|
5
|
+
cached one would have been fine: the label an audit needs to complete, and
|
|
6
|
+
the rejected-side label fine-tuning otherwise rarely gets. An integration
|
|
7
|
+
that sees the fresh answer (LangChain's `update()` after a miss) can hand
|
|
8
|
+
both answers to a caller-supplied judge and report its verdict.
|
|
9
|
+
|
|
10
|
+
The judge is yours on purpose. Whether two answers are "the same" depends on
|
|
11
|
+
your domain, and the cheap automatic checks we measured (answer embeddings,
|
|
12
|
+
an NLI model) did no better than the query similarity you already have.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
import threading
|
|
19
|
+
from collections import OrderedDict
|
|
20
|
+
from collections.abc import Callable, Hashable
|
|
21
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from cacheverifier.client import VerifyResult
|
|
26
|
+
from cacheverifier.local import LocalVerifier
|
|
27
|
+
|
|
28
|
+
Judge = Callable[[str, str, str], "bool | None"]
|
|
29
|
+
"""`judge(question, cached_answer, fresh_answer)`: True if the cached answer
|
|
30
|
+
would have been right for this question, False if not, None to skip."""
|
|
31
|
+
|
|
32
|
+
MAX_PENDING = 1024
|
|
33
|
+
"""Unserved hits remembered while waiting for the fresh answer. Oldest are
|
|
34
|
+
dropped first: a fresh answer that never arrives (the model call failed)
|
|
35
|
+
must not grow memory without bound."""
|
|
36
|
+
|
|
37
|
+
_log = logging.getLogger("cacheverifier.integrations")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class _Pending:
|
|
42
|
+
question: str
|
|
43
|
+
cached_answer: str
|
|
44
|
+
result: VerifyResult
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class RejectedHitReporter:
|
|
48
|
+
"""Remembers unserved hits by key and, when the fresh answer for the same
|
|
49
|
+
key arrives, reports the judge's verdict as feedback. Never raises into
|
|
50
|
+
the caller's request path: judge and report errors are logged."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, client: Any, judge: Judge, *, background: bool = True) -> None:
|
|
53
|
+
self._client = client
|
|
54
|
+
self._judge = judge
|
|
55
|
+
self._lock = threading.Lock()
|
|
56
|
+
self._pending: OrderedDict[Hashable, _Pending] = OrderedDict()
|
|
57
|
+
self._executor = (
|
|
58
|
+
ThreadPoolExecutor(max_workers=1, thread_name_prefix="cacheverifier-report") if background else None
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def remember(self, key: Hashable, question: str, cached_answer: str, result: VerifyResult) -> None:
|
|
62
|
+
"""Call for a hit that was not served: rejected by a model, an audit,
|
|
63
|
+
or a cold-start rejection. Outages (`degraded`) carry no verdict and
|
|
64
|
+
are not reported."""
|
|
65
|
+
if result.degraded or result.approved:
|
|
66
|
+
return
|
|
67
|
+
with self._lock:
|
|
68
|
+
self._pending[key] = _Pending(question, cached_answer, result)
|
|
69
|
+
self._pending.move_to_end(key)
|
|
70
|
+
while len(self._pending) > MAX_PENDING:
|
|
71
|
+
self._pending.popitem(last=False)
|
|
72
|
+
|
|
73
|
+
def fresh_answer(self, key: Hashable, fresh: str) -> Future[None] | None:
|
|
74
|
+
"""Call with the answer the model just produced for `key`."""
|
|
75
|
+
with self._lock:
|
|
76
|
+
pending = self._pending.pop(key, None)
|
|
77
|
+
if pending is None:
|
|
78
|
+
return None
|
|
79
|
+
if self._executor is None:
|
|
80
|
+
self._report(pending, fresh)
|
|
81
|
+
return None
|
|
82
|
+
return self._executor.submit(self._report, pending, fresh)
|
|
83
|
+
|
|
84
|
+
def _report(self, pending: _Pending, fresh: str) -> None:
|
|
85
|
+
try:
|
|
86
|
+
verdict = self._judge(pending.question, pending.cached_answer, fresh)
|
|
87
|
+
except Exception as exc: # noqa: BLE001 -- the judge is caller code; never raise into the request path
|
|
88
|
+
_log.warning("cacheverifier: judge raised %r; hit not reported", exc)
|
|
89
|
+
return
|
|
90
|
+
if verdict is None:
|
|
91
|
+
return
|
|
92
|
+
try:
|
|
93
|
+
if isinstance(self._client, LocalVerifier): # links by result, not by id
|
|
94
|
+
self._client.feedback(
|
|
95
|
+
pending.question,
|
|
96
|
+
pending.cached_answer,
|
|
97
|
+
bool(verdict),
|
|
98
|
+
result=pending.result,
|
|
99
|
+
label_method="judge",
|
|
100
|
+
)
|
|
101
|
+
else:
|
|
102
|
+
self._client.feedback(
|
|
103
|
+
pending.question,
|
|
104
|
+
pending.cached_answer,
|
|
105
|
+
bool(verdict),
|
|
106
|
+
verification_id=pending.result.verification_id,
|
|
107
|
+
label_method="judge",
|
|
108
|
+
)
|
|
109
|
+
except Exception as exc: # noqa: BLE001 -- a failed report must not break the caller
|
|
110
|
+
_log.warning("cacheverifier: reporting an unserved hit failed: %s", exc)
|
|
111
|
+
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
"""Wait for queued reports to finish."""
|
|
114
|
+
if self._executor is not None:
|
|
115
|
+
self._executor.shutdown(wait=True)
|
|
@@ -29,6 +29,8 @@ close enough on their own. Without it, every cold-start hit is a miss.
|
|
|
29
29
|
|
|
30
30
|
from __future__ import annotations
|
|
31
31
|
|
|
32
|
+
import threading
|
|
33
|
+
from collections import OrderedDict
|
|
32
34
|
from typing import Any
|
|
33
35
|
|
|
34
36
|
from cacheverifier.client import (
|
|
@@ -38,6 +40,7 @@ from cacheverifier.client import (
|
|
|
38
40
|
CacheVerifier,
|
|
39
41
|
)
|
|
40
42
|
from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode
|
|
43
|
+
from cacheverifier.integrations._reporting import MAX_PENDING
|
|
41
44
|
|
|
42
45
|
try:
|
|
43
46
|
from gptcache.similarity_evaluation import SimilarityEvaluation as _GPTCacheBase
|
|
@@ -100,6 +103,8 @@ class CacheVerifierEvaluation(_GPTCacheBase):
|
|
|
100
103
|
self.cold_start = check_mode(cold_start)
|
|
101
104
|
self.direct_hit = direct_hit
|
|
102
105
|
self._cold_start_notice = ColdStartNotice("CacheVerifierEvaluation")
|
|
106
|
+
self._unserved_lock = threading.Lock()
|
|
107
|
+
self._unserved: OrderedDict[tuple[str, str], int] = OrderedDict()
|
|
103
108
|
self._cv = CacheVerifier(
|
|
104
109
|
api_key=api_key,
|
|
105
110
|
base_url=base_url,
|
|
@@ -125,6 +130,8 @@ class CacheVerifierEvaluation(_GPTCacheBase):
|
|
|
125
130
|
query = src_dict.get("question") or src_dict.get("query", "")
|
|
126
131
|
candidate_answer = cache_dict.get("answer", "")
|
|
127
132
|
result = self._cv.verify(query, candidate_answer)
|
|
133
|
+
if not result.approved and result.verification_id is not None:
|
|
134
|
+
self._remember_unserved(query, candidate_answer, result.verification_id)
|
|
128
135
|
if result.cold_start:
|
|
129
136
|
serve = self.cold_start == "serve" and fallback_score is not None
|
|
130
137
|
if serve:
|
|
@@ -143,6 +150,13 @@ class CacheVerifierEvaluation(_GPTCacheBase):
|
|
|
143
150
|
return fallback_score if serve and fallback_score is not None else 0.0
|
|
144
151
|
return 1.0 if result.approved else 0.0
|
|
145
152
|
|
|
153
|
+
def _remember_unserved(self, query: str, candidate_answer: str, verification_id: int) -> None:
|
|
154
|
+
with self._unserved_lock:
|
|
155
|
+
self._unserved[(query, candidate_answer)] = verification_id
|
|
156
|
+
self._unserved.move_to_end((query, candidate_answer))
|
|
157
|
+
while len(self._unserved) > MAX_PENDING:
|
|
158
|
+
self._unserved.popitem(last=False)
|
|
159
|
+
|
|
146
160
|
def range(self) -> tuple[float, float]:
|
|
147
161
|
return 0.0, 1.0
|
|
148
162
|
|
|
@@ -152,6 +166,7 @@ class CacheVerifierEvaluation(_GPTCacheBase):
|
|
|
152
166
|
candidate_answer: str,
|
|
153
167
|
was_correct: bool,
|
|
154
168
|
similarity_score: float | None = None,
|
|
169
|
+
verification_id: int | None = None,
|
|
155
170
|
) -> None:
|
|
156
171
|
"""Not part of GPTCache's interface -- call it once you know whether
|
|
157
172
|
a served hit was actually correct (a thumbs-down, a reopened
|
|
@@ -162,12 +177,23 @@ class CacheVerifierEvaluation(_GPTCacheBase):
|
|
|
162
177
|
score for this candidate if you still have it when you learn
|
|
163
178
|
`was_correct` -- that is what lets the service later recommend a
|
|
164
179
|
tau_high for your GPTCache config (`gray_zone_threshold()`).
|
|
180
|
+
|
|
181
|
+
Audits and rejections: when this evaluator didn't let a hit through
|
|
182
|
+
(a rejection or a randomized audit), GPTCache calls your LLM. Compare
|
|
183
|
+
its answer with the cached one and report the result here with the
|
|
184
|
+
same `query` and `candidate_answer`: the `verification_id` of that
|
|
185
|
+
verdict is attached for you (it is what completes an audit), unless
|
|
186
|
+
you pass one yourself.
|
|
165
187
|
"""
|
|
188
|
+
if verification_id is None:
|
|
189
|
+
with self._unserved_lock:
|
|
190
|
+
verification_id = self._unserved.pop((query, candidate_answer), None)
|
|
166
191
|
self._cv.feedback(
|
|
167
192
|
query,
|
|
168
193
|
candidate_answer,
|
|
169
194
|
was_correct,
|
|
170
195
|
similarity_score=similarity_score,
|
|
196
|
+
verification_id=verification_id,
|
|
171
197
|
)
|
|
172
198
|
|
|
173
199
|
def close(self) -> None:
|
|
@@ -32,6 +32,21 @@ warning. Pass `cold_start="reject"` to fall through to your model instead:
|
|
|
32
32
|
do that if you loosened the wrapped cache's similarity threshold because a
|
|
33
33
|
verifier would be checking its hits.
|
|
34
34
|
|
|
35
|
+
Pass `judge=` to close the loop on hits that weren't served. When a hit is
|
|
36
|
+
rejected or picked for an audit, your model answers anyway; `VerifiedCache`
|
|
37
|
+
sees that answer when LangChain stores it, calls
|
|
38
|
+
`judge(question, cached_answer, fresh_answer)` and reports the verdict as
|
|
39
|
+
feedback (True: the cached answer would have been right, False: it would
|
|
40
|
+
not, None: skip), as `label_method="judge"`. Those labels train fine-tunes;
|
|
41
|
+
the service keeps them out of its certified numbers (an audit answered only
|
|
42
|
+
by the judge still counts as unreported there). It runs in a background
|
|
43
|
+
thread, off your request path.
|
|
44
|
+
|
|
45
|
+
def same_answer(question, cached, fresh):
|
|
46
|
+
return my_llm_judge(question, cached, fresh) # your own check
|
|
47
|
+
|
|
48
|
+
VerifiedCache(cache, api_key="cv_...", judge=same_answer)
|
|
49
|
+
|
|
35
50
|
`langchain-core` is an optional dependency -- `pip install "cacheverifier[langchain]"`.
|
|
36
51
|
"""
|
|
37
52
|
|
|
@@ -48,6 +63,7 @@ from cacheverifier.client import (
|
|
|
48
63
|
CacheVerifier,
|
|
49
64
|
)
|
|
50
65
|
from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode
|
|
66
|
+
from cacheverifier.integrations._reporting import Judge, RejectedHitReporter
|
|
51
67
|
|
|
52
68
|
try:
|
|
53
69
|
from langchain_core.caches import RETURN_VAL_TYPE, BaseCache
|
|
@@ -92,6 +108,10 @@ def user_question(prompt: str) -> str:
|
|
|
92
108
|
return prompt
|
|
93
109
|
|
|
94
110
|
|
|
111
|
+
def _text(generations: RETURN_VAL_TYPE) -> str:
|
|
112
|
+
return "\n".join(generation.text for generation in generations)
|
|
113
|
+
|
|
114
|
+
|
|
95
115
|
class VerifiedCache(BaseCache):
|
|
96
116
|
"""A LangChain cache that verifies another cache's hits before serving them."""
|
|
97
117
|
|
|
@@ -106,6 +126,7 @@ class VerifiedCache(BaseCache):
|
|
|
106
126
|
verify_timeout: float = DEFAULT_VERIFY_TIMEOUT,
|
|
107
127
|
fail_open: bool = False,
|
|
108
128
|
cold_start: str = "serve",
|
|
129
|
+
judge: Judge | None = None,
|
|
109
130
|
) -> None:
|
|
110
131
|
self.cold_start = check_mode(cold_start)
|
|
111
132
|
self._cold_start_notice = ColdStartNotice("VerifiedCache")
|
|
@@ -121,10 +142,18 @@ class VerifiedCache(BaseCache):
|
|
|
121
142
|
)
|
|
122
143
|
self.cache = cache
|
|
123
144
|
self.client = client
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
145
|
+
self._reporter = RejectedHitReporter(client, judge) if judge is not None else None
|
|
146
|
+
|
|
147
|
+
def _approved(self, prompt: str, llm_string: str, hit: RETURN_VAL_TYPE) -> bool:
|
|
148
|
+
answer = _text(hit)
|
|
149
|
+
question = user_question(prompt)
|
|
150
|
+
result = self.client.verify(question, answer)
|
|
151
|
+
served = self._served(result)
|
|
152
|
+
if not served and self._reporter is not None:
|
|
153
|
+
self._reporter.remember((prompt, llm_string), question, answer, result)
|
|
154
|
+
return served
|
|
155
|
+
|
|
156
|
+
def _served(self, result: Any) -> bool:
|
|
128
157
|
if result.cold_start:
|
|
129
158
|
serve = self.cold_start == "serve"
|
|
130
159
|
self._cold_start_notice.seen(
|
|
@@ -141,20 +170,29 @@ class VerifiedCache(BaseCache):
|
|
|
141
170
|
hit = self.cache.lookup(prompt, llm_string)
|
|
142
171
|
if not hit:
|
|
143
172
|
return hit
|
|
144
|
-
return hit if self._approved(prompt, hit) else None
|
|
173
|
+
return hit if self._approved(prompt, llm_string, hit) else None
|
|
145
174
|
|
|
146
175
|
async def alookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
|
|
147
176
|
hit = await self.cache.alookup(prompt, llm_string)
|
|
148
177
|
if not hit:
|
|
149
178
|
return hit
|
|
150
|
-
approved = await asyncio.get_running_loop().run_in_executor(None, self._approved, prompt, hit)
|
|
179
|
+
approved = await asyncio.get_running_loop().run_in_executor(None, self._approved, prompt, llm_string, hit)
|
|
151
180
|
return hit if approved else None
|
|
152
181
|
|
|
153
182
|
def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
|
|
154
183
|
self.cache.update(prompt, llm_string, return_val)
|
|
184
|
+
if self._reporter is not None:
|
|
185
|
+
self._reporter.fresh_answer((prompt, llm_string), _text(return_val))
|
|
155
186
|
|
|
156
187
|
async def aupdate(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
|
|
157
188
|
await self.cache.aupdate(prompt, llm_string, return_val)
|
|
189
|
+
if self._reporter is not None:
|
|
190
|
+
self._reporter.fresh_answer((prompt, llm_string), _text(return_val))
|
|
191
|
+
|
|
192
|
+
def close(self) -> None:
|
|
193
|
+
"""Wait for queued `judge` reports to finish (only needed with `judge=`)."""
|
|
194
|
+
if self._reporter is not None:
|
|
195
|
+
self._reporter.close()
|
|
158
196
|
|
|
159
197
|
def clear(self, **kwargs: Any) -> None:
|
|
160
198
|
self.cache.clear(**kwargs)
|
|
@@ -477,6 +477,7 @@ class LocalVerifier:
|
|
|
477
477
|
cached_query: str | None = None,
|
|
478
478
|
cache_entry_id: str | None = None,
|
|
479
479
|
stale: bool = False,
|
|
480
|
+
label_method: str = "human",
|
|
480
481
|
idempotency_key: str | None = None,
|
|
481
482
|
) -> int:
|
|
482
483
|
"""`CacheVerifier.feedback`, linked to `result` when given (always
|
|
@@ -491,6 +492,7 @@ class LocalVerifier:
|
|
|
491
492
|
verification_id=verification_id,
|
|
492
493
|
cache_entry_id=cache_entry_id,
|
|
493
494
|
stale=stale,
|
|
495
|
+
label_method=label_method,
|
|
494
496
|
idempotency_key=idempotency_key,
|
|
495
497
|
)
|
|
496
498
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "cacheverifier"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.9.0"
|
|
8
8
|
description = "Python client for the CacheVerifier semantic-cache verification API, hosted or scored locally"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -308,3 +308,20 @@ def test_control_plane_call_still_uses_the_10s_default_and_raises():
|
|
|
308
308
|
cv.usage()
|
|
309
309
|
|
|
310
310
|
assert set(seen["timeout"].values()) == {10.0}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def test_feedback_sends_label_method_only_for_a_judge():
|
|
314
|
+
bodies = []
|
|
315
|
+
|
|
316
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
317
|
+
bodies.append(json.loads(request.content))
|
|
318
|
+
return httpx.Response(200, json={"id": 1})
|
|
319
|
+
|
|
320
|
+
with make_client(handler) as cv:
|
|
321
|
+
cv.feedback("q", "a", was_correct=True)
|
|
322
|
+
cv.feedback("q", "a", was_correct=False, label_method="judge")
|
|
323
|
+
with pytest.raises(ValueError):
|
|
324
|
+
cv.feedback("q", "a", was_correct=True, label_method="robot")
|
|
325
|
+
assert "label_method" not in bodies[0]
|
|
326
|
+
assert bodies[1]["label_method"] == "judge"
|
|
327
|
+
assert len(bodies) == 2
|
|
@@ -147,3 +147,26 @@ def test_a_model_verdict_still_decides_when_a_fallback_is_set():
|
|
|
147
147
|
def test_direct_hit_needs_a_fallback():
|
|
148
148
|
with pytest.raises(ValueError):
|
|
149
149
|
CacheVerifierEvaluation(api_key="cv_test", direct_hit=0.9)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_report_feedback_attaches_the_verification_id_of_an_unserved_hit():
|
|
153
|
+
import json
|
|
154
|
+
|
|
155
|
+
posted: list = []
|
|
156
|
+
|
|
157
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
158
|
+
if request.url.path == "/v1/feedback":
|
|
159
|
+
posted.append(json.loads(request.content))
|
|
160
|
+
return httpx.Response(200, json={"id": 1})
|
|
161
|
+
return httpx.Response(
|
|
162
|
+
200,
|
|
163
|
+
json={"approved": False, "audit": True, "verification_id": 41, "score": 2.0, "latency_ms": 5.0,
|
|
164
|
+
"model_version": "v3", "threshold": 0.0},
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
ev, _ = _eval_with(handler)
|
|
168
|
+
assert ev.evaluation({"question": "q"}, {"answer": "a"}) == 0.0
|
|
169
|
+
ev.report_feedback("q", "a", was_correct=True)
|
|
170
|
+
ev.report_feedback("q", "a", was_correct=True) # already linked: no id the second time
|
|
171
|
+
ev.report_feedback("other", "a", was_correct=False, verification_id=5)
|
|
172
|
+
assert [p.get("verification_id") for p in posted] == [41, None, 5]
|
|
@@ -150,3 +150,81 @@ def test_an_audited_call_still_falls_through_during_serve_mode():
|
|
|
150
150
|
def test_bad_cold_start_mode_is_rejected():
|
|
151
151
|
with pytest.raises(ValueError):
|
|
152
152
|
VerifiedCache(InMemoryCache(), api_key="cv_test", cold_start="open")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _judged(verdict_json: dict, judge, posted: list) -> VerifiedCache:
|
|
156
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
157
|
+
body = json.loads(request.content)
|
|
158
|
+
if request.url.path == "/v1/feedback":
|
|
159
|
+
posted.append(body)
|
|
160
|
+
return httpx.Response(200, json={"id": 1})
|
|
161
|
+
return httpx.Response(200, json=verdict_json)
|
|
162
|
+
|
|
163
|
+
client = CacheVerifier(api_key="cv_test", transport=httpx.MockTransport(handler))
|
|
164
|
+
return VerifiedCache(InMemoryCache(), client=client, judge=judge)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
_AUDIT = {"approved": False, "audit": True, "verification_id": 7, "score": 3.0, "latency_ms": 5.0,
|
|
168
|
+
"model_version": "v12", "threshold": 0.0}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_judge_reports_an_audited_hit_with_its_verification_id():
|
|
172
|
+
posted: list = []
|
|
173
|
+
seen: list = []
|
|
174
|
+
|
|
175
|
+
def judge(question, cached, fresh):
|
|
176
|
+
seen.append((question, cached, fresh))
|
|
177
|
+
return cached.split(".")[0] == fresh.split(".")[0]
|
|
178
|
+
|
|
179
|
+
cache = _judged(_AUDIT, judge, posted)
|
|
180
|
+
model = FakeListChatModel(responses=["Gate B12.", "Gate B12. Boarding 9:20."], cache=cache)
|
|
181
|
+
assert model.invoke("which gate is my flight").content == "Gate B12." # miss, cached
|
|
182
|
+
assert model.invoke("which gate is my flight").content == "Gate B12. Boarding 9:20." # audited -> model
|
|
183
|
+
cache.close()
|
|
184
|
+
assert seen == [("which gate is my flight", "Gate B12.", "Gate B12. Boarding 9:20.")]
|
|
185
|
+
assert posted == [{"query": "which gate is my flight", "candidate_answer": "Gate B12.", "was_correct": True,
|
|
186
|
+
"stale": False, "label_method": "judge", "verification_id": 7}]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def test_judge_reports_a_rejected_hit_in_the_async_path_too():
|
|
190
|
+
posted: list = []
|
|
191
|
+
rejected = {**_AUDIT, "audit": False, "score": -2.0}
|
|
192
|
+
cache = _judged(rejected, lambda q, c, f: False, posted)
|
|
193
|
+
asyncio.run(cache.aupdate("q", "llm", [Generation(text="old")]))
|
|
194
|
+
assert asyncio.run(cache.alookup("q", "llm")) is None
|
|
195
|
+
asyncio.run(cache.aupdate("q", "llm", [Generation(text="new")]))
|
|
196
|
+
cache.close()
|
|
197
|
+
assert [(p["candidate_answer"], p["was_correct"], p["verification_id"]) for p in posted] == [("old", False, 7)]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def test_served_hits_and_skipped_verdicts_are_not_reported():
|
|
201
|
+
posted: list = []
|
|
202
|
+
approved = {**_AUDIT, "approved": True, "audit": False}
|
|
203
|
+
cache = _judged(approved, lambda q, c, f: True, posted)
|
|
204
|
+
cache.update("q", "llm", [Generation(text="a")])
|
|
205
|
+
assert cache.lookup("q", "llm") is not None
|
|
206
|
+
cache.update("q", "llm", [Generation(text="b")])
|
|
207
|
+
|
|
208
|
+
skipping = _judged(_AUDIT, lambda q, c, f: None, posted)
|
|
209
|
+
skipping.update("q", "llm", [Generation(text="a")])
|
|
210
|
+
assert skipping.lookup("q", "llm") is None
|
|
211
|
+
skipping.update("q", "llm", [Generation(text="b")])
|
|
212
|
+
cache.close()
|
|
213
|
+
skipping.close()
|
|
214
|
+
assert posted == []
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def test_a_failing_judge_is_logged_not_raised(caplog):
|
|
218
|
+
posted: list = []
|
|
219
|
+
|
|
220
|
+
def judge(q, c, f):
|
|
221
|
+
raise RuntimeError("judge down")
|
|
222
|
+
|
|
223
|
+
cache = _judged(_AUDIT, judge, posted)
|
|
224
|
+
cache.update("q", "llm", [Generation(text="a")])
|
|
225
|
+
assert cache.lookup("q", "llm") is None
|
|
226
|
+
with caplog.at_level("WARNING", logger="cacheverifier.integrations"):
|
|
227
|
+
cache.update("q", "llm", [Generation(text="b")]) # must not raise
|
|
228
|
+
cache.close()
|
|
229
|
+
assert posted == []
|
|
230
|
+
assert "judge down" in caplog.text
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""RejectedHitReporter: which client call it makes, and the pending bound."""
|
|
2
|
+
|
|
3
|
+
from cacheverifier import LocalVerifier, VerifyResult
|
|
4
|
+
from cacheverifier.integrations import _reporting
|
|
5
|
+
from cacheverifier.integrations._reporting import RejectedHitReporter
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _result(**kw) -> VerifyResult:
|
|
9
|
+
base = {"approved": False, "score": -1.0, "threshold": 0.0, "model_version": "v9", "latency_ms": 1.0}
|
|
10
|
+
base.update(kw)
|
|
11
|
+
return VerifyResult(**base)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _FakeLocal(LocalVerifier):
|
|
15
|
+
def __init__(self) -> None: # no model download
|
|
16
|
+
self.calls: list = []
|
|
17
|
+
|
|
18
|
+
def feedback(self, query, candidate_answer, was_correct, **kwargs):
|
|
19
|
+
self.calls.append((query, candidate_answer, was_correct, kwargs))
|
|
20
|
+
return 1
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_local_verifier_is_reported_by_result_not_by_id():
|
|
24
|
+
client = _FakeLocal()
|
|
25
|
+
r = _result(local_decision="tok-1")
|
|
26
|
+
reporter = RejectedHitReporter(client, lambda q, c, f: True, background=False)
|
|
27
|
+
reporter.remember("k", "q", "cached", r)
|
|
28
|
+
reporter.fresh_answer("k", "fresh")
|
|
29
|
+
assert client.calls == [("q", "cached", True, {"result": r, "label_method": "judge"})]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_degraded_and_approved_results_are_not_remembered():
|
|
33
|
+
client = _FakeLocal()
|
|
34
|
+
reporter = RejectedHitReporter(client, lambda q, c, f: True, background=False)
|
|
35
|
+
reporter.remember("a", "q", "c", _result(degraded=True, model_version="verify_unavailable"))
|
|
36
|
+
reporter.remember("b", "q", "c", _result(approved=True))
|
|
37
|
+
reporter.fresh_answer("a", "f")
|
|
38
|
+
reporter.fresh_answer("b", "f")
|
|
39
|
+
assert client.calls == []
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_pending_hits_are_bounded(monkeypatch):
|
|
43
|
+
monkeypatch.setattr(_reporting, "MAX_PENDING", 2)
|
|
44
|
+
client = _FakeLocal()
|
|
45
|
+
reporter = RejectedHitReporter(client, lambda q, c, f: True, background=False)
|
|
46
|
+
for key in ("a", "b", "c"):
|
|
47
|
+
reporter.remember(key, key, "c", _result())
|
|
48
|
+
for key in ("a", "b", "c"):
|
|
49
|
+
reporter.fresh_answer(key, "f")
|
|
50
|
+
assert [call[0] for call in client.calls] == ["b", "c"] # oldest dropped
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|