cacheverifier 0.8.0__tar.gz → 0.9.1__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.
Files changed (31) hide show
  1. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/CHANGELOG.md +38 -0
  2. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/PKG-INFO +90 -35
  3. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/README.md +89 -34
  4. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/__init__.py +1 -1
  5. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/client.py +9 -0
  6. cacheverifier-0.9.1/cacheverifier/integrations/_reporting.py +115 -0
  7. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/integrations/gptcache.py +26 -0
  8. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/integrations/langchain.py +44 -6
  9. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/local.py +2 -0
  10. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/pyproject.toml +2 -2
  11. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/tests/test_client.py +17 -0
  12. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/tests/test_gptcache_integration.py +23 -0
  13. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/tests/test_langchain_integration.py +78 -0
  14. cacheverifier-0.9.1/tests/test_reporting.py +50 -0
  15. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/.github/workflows/ci.yml +0 -0
  16. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/.github/workflows/publish.yml +0 -0
  17. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/.gitignore +0 -0
  18. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/LICENSE +0 -0
  19. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/__main__.py +0 -0
  20. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/_healthcheck/__init__.py +0 -0
  21. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/_healthcheck/_base_models.py +0 -0
  22. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/_healthcheck/_finetune.py +0 -0
  23. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/_healthcheck/cli.py +0 -0
  24. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/_inference.py +0 -0
  25. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/integrations/__init__.py +0 -0
  26. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/integrations/_cold_start.py +0 -0
  27. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/cacheverifier/py.typed +0 -0
  28. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/examples/gptcache_example.py +0 -0
  29. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/examples/quickstart.py +0 -0
  30. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/tests/test_healthcheck.py +0 -0
  31. {cacheverifier-0.8.0 → cacheverifier-0.9.1}/tests/test_local.py +0 -0
@@ -1,5 +1,43 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.1
4
+
5
+ Documentation only; no code changes.
6
+
7
+ - README opens with what the verifier checks and how it decides: a fine-tuned
8
+ cross-encoder scores each (question, cached answer) pair against a
9
+ threshold, with no LLM call. An LLM is involved only if you pass one as
10
+ `judge=`.
11
+ - Quickstart: the free tier's monthly verify calls are stated, and the
12
+ example no longer labels the same `verification_id` twice (the second label
13
+ gets a 409).
14
+ - Fine-tuning: the 20-row minimum and the ~1,000-row caveat no longer read as
15
+ contradicting each other.
16
+ - The package description says the same.
17
+
18
+ ## 0.9.0
19
+
20
+ The integrations can report the hits they didn't serve. Until now they never
21
+ sent feedback, so audited and rejected hits made through them produced no
22
+ labels.
23
+
24
+ - `VerifiedCache` (LangChain) takes `judge=`, a function
25
+ `judge(question, cached_answer, fresh_answer) -> bool | None`. When a hit is
26
+ rejected or audited and your model answers instead, the fresh answer is
27
+ judged when LangChain stores it, and the verdict is sent as feedback linked
28
+ to that verdict (`verification_id`, or the result itself for a
29
+ `LocalVerifier`). It runs in a background thread; judge and report errors
30
+ are logged, not raised. `close()` waits for queued reports. These reports
31
+ are sent with `label_method="judge"`: they train fine-tunes, but the
32
+ service leaves them out of the audit risk bound, the audited CRC threshold
33
+ and ACI.
34
+ - `feedback()` (`CacheVerifier` and `LocalVerifier`) takes
35
+ `label_method="human"|"judge"`. It is sent only when `"judge"`, so
36
+ existing calls send the same request as before.
37
+ - `CacheVerifierEvaluation.report_feedback` attaches the `verification_id` of
38
+ the matching unserved hit (same query and cached answer) on its own, and
39
+ takes an explicit `verification_id=`.
40
+
3
41
  ## 0.8.0
4
42
 
5
43
  The integrations no longer switch your cache off during cold start. While a
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cacheverifier
3
- Version: 0.8.0
4
- Summary: Python client for the CacheVerifier semantic-cache verification API, hosted or scored locally
3
+ Version: 0.9.1
4
+ Summary: Check whether a semantic-cache hit is right for the question before serving it: a fine-tuned cross-encoder, no LLM call. Hosted API or local scoring; LangChain and GPTCache integrations.
5
5
  Project-URL: Homepage, https://www.cacheverifier.com
6
6
  Project-URL: Documentation, https://www.cacheverifier.com/docs
7
7
  Project-URL: Source, https://github.com/imxinchengyou/cacheverifier-python
@@ -43,32 +43,40 @@ Description-Content-Type: text/markdown
43
43
  [![PyPI](https://img.shields.io/pypi/v/cacheverifier)](https://pypi.org/project/cacheverifier/)
44
44
  [![Python](https://img.shields.io/pypi/pyversions/cacheverifier)](https://pypi.org/project/cacheverifier/)
45
45
 
46
- Python client for **[CacheVerifier](https://www.cacheverifier.com)**: verification and
47
- operations for semantic caches. It checks the cache hits a similarity threshold can't call,
48
- then keeps your cache right after launch.
46
+ Python client for **[CacheVerifier](https://www.cacheverifier.com)**, which checks whether
47
+ a semantic-cache hit is actually right for the new question before you serve it.
49
48
 
50
- - **Verify the uncertain hits.** Given a query and a candidate cached answer, approve or
51
- reject serving it in tens of milliseconds, so a match that is *close but wrong* doesn't
52
- become a silent error. Fine-tuned on your own feedback.
49
+ A semantic cache matches on how *similar* two questions look, so "can I cancel my order?"
50
+ can get the cached answer to "can I change my order?". CacheVerifier looks at the new
51
+ question and the cached answer together and returns approve or reject, in tens of
52
+ milliseconds. It sits on top of the cache you already run.
53
+
54
+ **How it decides.** A small cross-encoder model, fine-tuned on your own feedback, scores
55
+ each (question, cached answer) pair. There is **no LLM call** and nothing is generated: the
56
+ verdict is a score compared with a threshold. An LLM only enters the picture if *you* choose
57
+ one, for example as the optional `judge=` that labels hits your cache didn't serve (see
58
+ [LangChain](#reporting-hits-that-werent-served)).
59
+
60
+ - **Verify the uncertain hits.** Call `verify()` on the candidates in the similarity "gray
61
+ zone", where a plain threshold match might be wrong, so a match that is *close but wrong*
62
+ doesn't become a silent error.
53
63
  - **Know your real error rate.** Randomized audits of approved hits give a conservative
54
- (Clopper-Pearson) upper bound on how often a served answer is wrong, measured on your
55
- traffic, not a benchmark.
56
- - **Certified thresholds.** At fine-tune time, Conformal Risk Control can report a threshold
57
- that keeps false reuses under a target you set. It is informational (`verify()` doesn't
58
- apply it), holds only while traffic resembles the calibration data, and covers only the
59
- hits you send to `verify()`, not the ones your cache serves on similarity alone. An
60
- optional online (ACI) threshold does change decisions, following what the audits find.
61
- - **Catch drift and recalibrate.** When traffic moves away from what the verifier learned,
62
- the dashboard flags it; on Team and Scale you also get a webhook alert and it is
63
- retrained on your feedback automatically.
64
+ (Clopper-Pearson) upper bound on how often a served answer is wrong, measured on your traffic, not a benchmark.
65
+ - **Set a risk target.** Conformal Risk Control can report a threshold that keeps wrong
66
+ reuses under a target you set, and the audits can check it on later traffic. It is a
67
+ report (`verify()` doesn't apply it), holds only while traffic resembles the calibration
68
+ data, and covers only the hits you send to `verify()`. An optional online (ACI) threshold
69
+ does change decisions, following what the audits find.
70
+ - **Catch drift.** When traffic moves away from what the verifier learned, the dashboard
71
+ flags it; on Team and Scale you also get a webhook alert and it is retrained on your
72
+ feedback automatically.
64
73
  - **Know which entries to fix.** `entries_to_refresh()` lists the cache entries your
65
74
  feedback reported stale, or wrong more often than right, with your own cache keys.
66
75
  - **Run it in your stack.** On Managed plans, `LocalVerifier` scores with your fine-tuned
67
- model locally: no network hop, your texts stay with you, nothing metered.
76
+ model on your own machines: no network hop, your texts stay with you, nothing metered.
68
77
 
69
- CacheVerifier does **not** run your cache or do similarity search. Your cache backend does
70
- its own lookup first; you call `verify()` only on the candidates in the similarity "gray
71
- zone", where a plain threshold match might be wrong.
78
+ CacheVerifier does **not** run your cache or do similarity search: your cache backend does
79
+ its own lookup first.
72
80
 
73
81
  | | answers | examples |
74
82
  |---|---|---|
@@ -99,8 +107,8 @@ are opt-in.
99
107
 
100
108
  ## Quickstart
101
109
 
102
- Get a free API key at <https://www.cacheverifier.com> (verify, fine-tuning, audits and
103
- entries to refresh are free, no card).
110
+ Get a free API key at <https://www.cacheverifier.com>: 20,000 verify calls a month,
111
+ fine-tuning, audits and entries to refresh, no card.
104
112
 
105
113
  ```python
106
114
  from cacheverifier import CacheVerifier
@@ -110,19 +118,24 @@ cv = CacheVerifier(api_key="cv_...")
110
118
  query = "can I change the delivery address after my parcel ships"
111
119
  candidate = "You can change the delivery address any time before the parcel ships." # from your cache
112
120
 
113
- result = cv.verify(query, candidate)
121
+ result = cv.verify(query, candidate, similarity_score=0.86)
114
122
  if result.approved:
115
- answer = candidate # verified hit — skip the LLM call
123
+ answer = candidate # verified hit: skip the LLM call
116
124
  else:
117
- answer = call_your_llm(query) # not trustworthy — fall through
118
- if result.audit: # a randomized audit of an approval: report whether
119
- cv.feedback(query, candidate, # the cached answer matched the fresh one
125
+ answer = call_your_llm(query) # not trustworthy: fall through
126
+ if result.audit: # a randomized audit of an approval: report
127
+ cv.feedback(query, candidate, # whether the cached answer was right
120
128
  was_correct=same_answer(answer, candidate),
121
129
  verification_id=result.verification_id)
130
+ ```
131
+
132
+ Every other label you have is worth sending too, whenever you learn it (a thumbs-down, a
133
+ reopened ticket, a reviewer's call). Label the cached candidate, not the fresh LLM answer:
134
+ was it right for this query? Each `verification_id` takes one label (a second one gets a
135
+ 409), so an audit you already reported is done.
122
136
 
123
- # Later, label the cached candidate (not the fresh LLM answer): was it right for this
124
- # query? (a thumbs-down, a reopened ticket, a reviewer's call)
125
- cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score=0.86,
137
+ ```python
138
+ cv.feedback(query, candidate, was_correct=False, similarity_score=0.86,
126
139
  verification_id=result.verification_id)
127
140
  ```
128
141
 
@@ -214,6 +227,37 @@ first time. Pass `cold_start="reject"` to fall through to your model instead,
214
227
  for example if you loosened the wrapped cache's similarity threshold because
215
228
  a verifier would be checking its hits.
216
229
 
230
+ ### Reporting hits that weren't served
231
+
232
+ When a hit is rejected or picked for a randomized audit, your model answers
233
+ anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when
234
+ LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides
235
+ whether the cached answer would have been right (`True` / `False`, or `None`
236
+ to skip), and the verdict is sent as feedback, linked to the verdict it is
237
+ about. It gives fine-tuning labels on audited and rejected hits, which are
238
+ otherwise rare. It runs in a background thread, off your request path, and a
239
+ failing judge or report is logged, never raised.
240
+
241
+ These reports are sent as `label_method="judge"`. Judge labels train your
242
+ fine-tunes, but the service leaves them out of every number it certifies
243
+ (the audit risk bound, the audited CRC threshold, ACI) until a judge can be
244
+ checked: a judge that calls wrong answers right would make those numbers look
245
+ better than they are. An audit answered only by the judge still counts as
246
+ unreported there; to complete audits, report them yourself with
247
+ `feedback(..., verification_id=...)`.
248
+
249
+ ```python
250
+ def same_answer(question, cached, fresh): # -> True, False, or None to skip
251
+ ... # your own check, e.g. an LLM call or a rule for your domain
252
+
253
+ set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer))
254
+ ```
255
+
256
+ The judge is yours because "the same answer" depends on your domain: the
257
+ cheap automatic checks we measured (answer embeddings, an NLI model) did no
258
+ better than the query similarity your cache already has. Without `judge`,
259
+ nothing is reported.
260
+
217
261
  ## GPTCache
218
262
 
219
263
  Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
@@ -244,6 +288,12 @@ so replacing your evaluator also drops the similarity check it did. With
244
288
  - `direct_hit` serves hits whose fallback score is at least that high without
245
289
  a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
246
290
 
291
+ When the evaluator doesn't let a hit through (a rejection, or a randomized
292
+ audit), GPTCache calls your LLM. Compare its answer with the cached one and
293
+ call `report_feedback(query, cached_answer, was_correct=...)` with the same
294
+ query and cached answer: the evaluator attaches that verdict's
295
+ `verification_id` for you, which is what completes an audit.
296
+
247
297
  See [`examples/gptcache_example.py`](examples/gptcache_example.py).
248
298
 
249
299
  ## Entries to refresh
@@ -261,9 +311,10 @@ for e in cv.entries_to_refresh():
261
311
 
262
312
  ## Fine-tuning
263
313
 
264
- Once you have ~20+ feedback rows (the service found fine-tuning is often a net negative
265
- below ~1,000 on the hardest data — see the [research](https://github.com/imxinchengyou/CacheVerifier)),
266
- train a verifier on your own gray-zone labels:
314
+ Train a verifier on your own gray-zone labels. The service accepts a job from 20 feedback
315
+ rows, but on the hardest data fine-tuning was often a net negative below ~1,000 (see the
316
+ [research](https://github.com/imxinchengyou/CacheVerifier)); `dry_run()` and the Health
317
+ Check tell you whether it helps on yours before anything is deployed.
267
318
 
268
319
  ```python
269
320
  job = cv.finetune() # or cv.finetune(target_risk=0.01, cost_ratio=5.0)
@@ -414,6 +465,10 @@ verdict
414
465
 
415
466
  Non-2xx responses raise `CacheVerifierError` (`.status_code`, `.detail`).
416
467
 
468
+ Monitoring endpoints without a client method yet (`GET /v1/monitor/risk`,
469
+ `/v1/monitor/audited-crc-threshold`, `/v1/monitor/judge-agreement`) are in the
470
+ [API reference](https://www.cacheverifier.com/docs).
471
+
417
472
  ## License
418
473
 
419
474
  MIT — see [`LICENSE`](LICENSE). (The [research repository](https://github.com/imxinchengyou/CacheVerifier)
@@ -4,32 +4,40 @@
4
4
  [![PyPI](https://img.shields.io/pypi/v/cacheverifier)](https://pypi.org/project/cacheverifier/)
5
5
  [![Python](https://img.shields.io/pypi/pyversions/cacheverifier)](https://pypi.org/project/cacheverifier/)
6
6
 
7
- Python client for **[CacheVerifier](https://www.cacheverifier.com)**: verification and
8
- operations for semantic caches. It checks the cache hits a similarity threshold can't call,
9
- then keeps your cache right after launch.
10
-
11
- - **Verify the uncertain hits.** Given a query and a candidate cached answer, approve or
12
- reject serving it in tens of milliseconds, so a match that is *close but wrong* doesn't
13
- become a silent error. Fine-tuned on your own feedback.
7
+ Python client for **[CacheVerifier](https://www.cacheverifier.com)**, which checks whether
8
+ a semantic-cache hit is actually right for the new question before you serve it.
9
+
10
+ A semantic cache matches on how *similar* two questions look, so "can I cancel my order?"
11
+ can get the cached answer to "can I change my order?". CacheVerifier looks at the new
12
+ question and the cached answer together and returns approve or reject, in tens of
13
+ milliseconds. It sits on top of the cache you already run.
14
+
15
+ **How it decides.** A small cross-encoder model, fine-tuned on your own feedback, scores
16
+ each (question, cached answer) pair. There is **no LLM call** and nothing is generated: the
17
+ verdict is a score compared with a threshold. An LLM only enters the picture if *you* choose
18
+ one, for example as the optional `judge=` that labels hits your cache didn't serve (see
19
+ [LangChain](#reporting-hits-that-werent-served)).
20
+
21
+ - **Verify the uncertain hits.** Call `verify()` on the candidates in the similarity "gray
22
+ zone", where a plain threshold match might be wrong, so a match that is *close but wrong*
23
+ doesn't become a silent error.
14
24
  - **Know your real error rate.** Randomized audits of approved hits give a conservative
15
- (Clopper-Pearson) upper bound on how often a served answer is wrong, measured on your
16
- traffic, not a benchmark.
17
- - **Certified thresholds.** At fine-tune time, Conformal Risk Control can report a threshold
18
- that keeps false reuses under a target you set. It is informational (`verify()` doesn't
19
- apply it), holds only while traffic resembles the calibration data, and covers only the
20
- hits you send to `verify()`, not the ones your cache serves on similarity alone. An
21
- optional online (ACI) threshold does change decisions, following what the audits find.
22
- - **Catch drift and recalibrate.** When traffic moves away from what the verifier learned,
23
- the dashboard flags it; on Team and Scale you also get a webhook alert and it is
24
- retrained on your feedback automatically.
25
+ (Clopper-Pearson) upper bound on how often a served answer is wrong, measured on your traffic, not a benchmark.
26
+ - **Set a risk target.** Conformal Risk Control can report a threshold that keeps wrong
27
+ reuses under a target you set, and the audits can check it on later traffic. It is a
28
+ report (`verify()` doesn't apply it), holds only while traffic resembles the calibration
29
+ data, and covers only the hits you send to `verify()`. An optional online (ACI) threshold
30
+ does change decisions, following what the audits find.
31
+ - **Catch drift.** When traffic moves away from what the verifier learned, the dashboard
32
+ flags it; on Team and Scale you also get a webhook alert and it is retrained on your
33
+ feedback automatically.
25
34
  - **Know which entries to fix.** `entries_to_refresh()` lists the cache entries your
26
35
  feedback reported stale, or wrong more often than right, with your own cache keys.
27
36
  - **Run it in your stack.** On Managed plans, `LocalVerifier` scores with your fine-tuned
28
- model locally: no network hop, your texts stay with you, nothing metered.
37
+ model on your own machines: no network hop, your texts stay with you, nothing metered.
29
38
 
30
- CacheVerifier does **not** run your cache or do similarity search. Your cache backend does
31
- its own lookup first; you call `verify()` only on the candidates in the similarity "gray
32
- zone", where a plain threshold match might be wrong.
39
+ CacheVerifier does **not** run your cache or do similarity search: your cache backend does
40
+ its own lookup first.
33
41
 
34
42
  | | answers | examples |
35
43
  |---|---|---|
@@ -60,8 +68,8 @@ are opt-in.
60
68
 
61
69
  ## Quickstart
62
70
 
63
- Get a free API key at <https://www.cacheverifier.com> (verify, fine-tuning, audits and
64
- entries to refresh are free, no card).
71
+ Get a free API key at <https://www.cacheverifier.com>: 20,000 verify calls a month,
72
+ fine-tuning, audits and entries to refresh, no card.
65
73
 
66
74
  ```python
67
75
  from cacheverifier import CacheVerifier
@@ -71,19 +79,24 @@ cv = CacheVerifier(api_key="cv_...")
71
79
  query = "can I change the delivery address after my parcel ships"
72
80
  candidate = "You can change the delivery address any time before the parcel ships." # from your cache
73
81
 
74
- result = cv.verify(query, candidate)
82
+ result = cv.verify(query, candidate, similarity_score=0.86)
75
83
  if result.approved:
76
- answer = candidate # verified hit — skip the LLM call
84
+ answer = candidate # verified hit: skip the LLM call
77
85
  else:
78
- answer = call_your_llm(query) # not trustworthy — fall through
79
- if result.audit: # a randomized audit of an approval: report whether
80
- cv.feedback(query, candidate, # the cached answer matched the fresh one
86
+ answer = call_your_llm(query) # not trustworthy: fall through
87
+ if result.audit: # a randomized audit of an approval: report
88
+ cv.feedback(query, candidate, # whether the cached answer was right
81
89
  was_correct=same_answer(answer, candidate),
82
90
  verification_id=result.verification_id)
91
+ ```
92
+
93
+ Every other label you have is worth sending too, whenever you learn it (a thumbs-down, a
94
+ reopened ticket, a reviewer's call). Label the cached candidate, not the fresh LLM answer:
95
+ was it right for this query? Each `verification_id` takes one label (a second one gets a
96
+ 409), so an audit you already reported is done.
83
97
 
84
- # Later, label the cached candidate (not the fresh LLM answer): was it right for this
85
- # query? (a thumbs-down, a reopened ticket, a reviewer's call)
86
- cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score=0.86,
98
+ ```python
99
+ cv.feedback(query, candidate, was_correct=False, similarity_score=0.86,
87
100
  verification_id=result.verification_id)
88
101
  ```
89
102
 
@@ -175,6 +188,37 @@ first time. Pass `cold_start="reject"` to fall through to your model instead,
175
188
  for example if you loosened the wrapped cache's similarity threshold because
176
189
  a verifier would be checking its hits.
177
190
 
191
+ ### Reporting hits that weren't served
192
+
193
+ When a hit is rejected or picked for a randomized audit, your model answers
194
+ anyway. Pass `judge=` and `VerifiedCache` uses that fresh answer: when
195
+ LangChain stores it, `judge(question, cached_answer, fresh_answer)` decides
196
+ whether the cached answer would have been right (`True` / `False`, or `None`
197
+ to skip), and the verdict is sent as feedback, linked to the verdict it is
198
+ about. It gives fine-tuning labels on audited and rejected hits, which are
199
+ otherwise rare. It runs in a background thread, off your request path, and a
200
+ failing judge or report is logged, never raised.
201
+
202
+ These reports are sent as `label_method="judge"`. Judge labels train your
203
+ fine-tunes, but the service leaves them out of every number it certifies
204
+ (the audit risk bound, the audited CRC threshold, ACI) until a judge can be
205
+ checked: a judge that calls wrong answers right would make those numbers look
206
+ better than they are. An audit answered only by the judge still counts as
207
+ unreported there; to complete audits, report them yourself with
208
+ `feedback(..., verification_id=...)`.
209
+
210
+ ```python
211
+ def same_answer(question, cached, fresh): # -> True, False, or None to skip
212
+ ... # your own check, e.g. an LLM call or a rule for your domain
213
+
214
+ set_llm_cache(VerifiedCache(cache, api_key="cv_...", judge=same_answer))
215
+ ```
216
+
217
+ The judge is yours because "the same answer" depends on your domain: the
218
+ cheap automatic checks we measured (answer embeddings, an NLI model) did no
219
+ better than the query similarity your cache already has. Without `judge`,
220
+ nothing is reported.
221
+
178
222
  ## GPTCache
179
223
 
180
224
  Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
@@ -205,6 +249,12 @@ so replacing your evaluator also drops the similarity check it did. With
205
249
  - `direct_hit` serves hits whose fallback score is at least that high without
206
250
  a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
207
251
 
252
+ When the evaluator doesn't let a hit through (a rejection, or a randomized
253
+ audit), GPTCache calls your LLM. Compare its answer with the cached one and
254
+ call `report_feedback(query, cached_answer, was_correct=...)` with the same
255
+ query and cached answer: the evaluator attaches that verdict's
256
+ `verification_id` for you, which is what completes an audit.
257
+
208
258
  See [`examples/gptcache_example.py`](examples/gptcache_example.py).
209
259
 
210
260
  ## Entries to refresh
@@ -222,9 +272,10 @@ for e in cv.entries_to_refresh():
222
272
 
223
273
  ## Fine-tuning
224
274
 
225
- Once you have ~20+ feedback rows (the service found fine-tuning is often a net negative
226
- below ~1,000 on the hardest data — see the [research](https://github.com/imxinchengyou/CacheVerifier)),
227
- train a verifier on your own gray-zone labels:
275
+ Train a verifier on your own gray-zone labels. The service accepts a job from 20 feedback
276
+ rows, but on the hardest data fine-tuning was often a net negative below ~1,000 (see the
277
+ [research](https://github.com/imxinchengyou/CacheVerifier)); `dry_run()` and the Health
278
+ Check tell you whether it helps on yours before anything is deployed.
228
279
 
229
280
  ```python
230
281
  job = cv.finetune() # or cv.finetune(target_risk=0.01, cost_ratio=5.0)
@@ -375,6 +426,10 @@ verdict
375
426
 
376
427
  Non-2xx responses raise `CacheVerifierError` (`.status_code`, `.detail`).
377
428
 
429
+ Monitoring endpoints without a client method yet (`GET /v1/monitor/risk`,
430
+ `/v1/monitor/audited-crc-threshold`, `/v1/monitor/judge-agreement`) are in the
431
+ [API reference](https://www.cacheverifier.com/docs).
432
+
378
433
  ## License
379
434
 
380
435
  MIT — see [`LICENSE`](LICENSE). (The [research repository](https://github.com/imxinchengyou/CacheVerifier)
@@ -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.8.0"
22
+ __version__ = "0.9.1"
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
- def _approved(self, prompt: str, hit: RETURN_VAL_TYPE) -> bool:
126
- answer = "\n".join(generation.text for generation in hit)
127
- result = self.client.verify(user_question(prompt), answer)
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,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cacheverifier"
7
- version = "0.8.0"
8
- description = "Python client for the CacheVerifier semantic-cache verification API, hosted or scored locally"
7
+ version = "0.9.1"
8
+ description = "Check whether a semantic-cache hit is right for the question before serving it: a fine-tuned cross-encoder, no LLM call. Hosted API or local scoring; LangChain and GPTCache integrations."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
11
  license = { text = "MIT" }
@@ -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