cacheverifier 0.7.1__tar.gz → 0.8.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.
Files changed (31) hide show
  1. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/CHANGELOG.md +16 -0
  2. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/PKG-INFO +29 -3
  3. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/README.md +28 -2
  4. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/__init__.py +1 -1
  5. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/client.py +15 -0
  6. cacheverifier-0.8.0/cacheverifier/integrations/_cold_start.py +52 -0
  7. cacheverifier-0.8.0/cacheverifier/integrations/gptcache.py +174 -0
  8. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/integrations/langchain.py +24 -1
  9. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/examples/gptcache_example.py +7 -1
  10. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/pyproject.toml +1 -1
  11. cacheverifier-0.8.0/tests/test_gptcache_integration.py +149 -0
  12. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/tests/test_langchain_integration.py +62 -0
  13. cacheverifier-0.7.1/cacheverifier/integrations/gptcache.py +0 -102
  14. cacheverifier-0.7.1/tests/test_gptcache_integration.py +0 -55
  15. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/.github/workflows/ci.yml +0 -0
  16. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/.github/workflows/publish.yml +0 -0
  17. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/.gitignore +0 -0
  18. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/LICENSE +0 -0
  19. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/__main__.py +0 -0
  20. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/_healthcheck/__init__.py +0 -0
  21. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/_healthcheck/_base_models.py +0 -0
  22. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/_healthcheck/_finetune.py +0 -0
  23. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/_healthcheck/cli.py +0 -0
  24. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/_inference.py +0 -0
  25. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/integrations/__init__.py +0 -0
  26. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/local.py +0 -0
  27. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/cacheverifier/py.typed +0 -0
  28. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/examples/quickstart.py +0 -0
  29. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/tests/test_client.py +0 -0
  30. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/tests/test_healthcheck.py +0 -0
  31. {cacheverifier-0.7.1 → cacheverifier-0.8.0}/tests/test_local.py +0 -0
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0
4
+
5
+ The integrations no longer switch your cache off during cold start. While a
6
+ workspace has no model of its own, `/v1/verify` rejects every call; an
7
+ integration sends every hit, so that rejected all of them, silently.
8
+
9
+ - `VerifiedCache` (LangChain) now serves cold-start hits exactly as the
10
+ wrapped cache returned them, and logs the service's notice once. Pass
11
+ `cold_start="reject"` for the old behavior.
12
+ - `CacheVerifierEvaluation` (GPTCache) takes `fallback=`, the evaluator it
13
+ replaces (e.g. `SearchDistanceEvaluation()`): during cold start GPTCache
14
+ decides with it exactly as before. Without a fallback, cold-start hits stay
15
+ misses, now with a warning saying how to keep them. `direct_hit=` serves
16
+ hits whose fallback score is at least that high without a verify call.
17
+ - `VerifyResult.cold_start`: True when no model decided the call.
18
+
3
19
  ## 0.7.1
4
20
 
5
21
  README only, no code change, so the PyPI page matches the docs: the
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cacheverifier
3
- Version: 0.7.1
3
+ Version: 0.8.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
@@ -139,10 +139,13 @@ cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score=
139
139
  | `latency_ms` | server-side inference time |
140
140
  | `degraded` | `True` when the call failed and this result was synthesized client-side |
141
141
  | `notice` | why no model decided the call (cold start); `None` otherwise |
142
+ | `cold_start` | property: `True` when no model decided the call (`model_version` is `"cold_start_..."`) |
142
143
  | `shadow` | cold start only: a `ShadowVerdict` with what the shared stock model would have decided. The call is still rejected, so treat it as a preview |
143
144
 
144
145
  A new account starts in cold start: every call returns `approved=False` until a
145
- Health Check shows the shared model is accurate enough on your data. Look at
146
+ Health Check shows the shared model is accurate enough on your data. (The
147
+ LangChain and GPTCache integrations hand cold-start hits back to your cache's
148
+ own decision instead, see below.) Look at
146
149
  `result.shadow` to see what it would have decided in the meantime:
147
150
 
148
151
  ```python
@@ -203,21 +206,44 @@ set_llm_cache(
203
206
  )
204
207
  ```
205
208
 
209
+ Until your workspace has a model of its own (cold start), the service
210
+ decides nothing and would reject every hit, which would switch your cache
211
+ off. So during cold start `VerifiedCache` serves each hit exactly as the
212
+ wrapped cache returned it, the same as without it, and logs a warning the
213
+ first time. Pass `cold_start="reject"` to fall through to your model instead,
214
+ for example if you loosened the wrapped cache's similarity threshold because
215
+ a verifier would be checking its hits.
216
+
206
217
  ## GPTCache
207
218
 
208
219
  Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
209
220
 
210
221
  ```python
211
222
  from gptcache import cache
223
+ from gptcache.similarity_evaluation import SearchDistanceEvaluation
212
224
  from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
213
225
 
214
- evaluator = CacheVerifierEvaluation(api_key="cv_...")
226
+ evaluator = CacheVerifierEvaluation(
227
+ api_key="cv_...",
228
+ fallback=SearchDistanceEvaluation(), # the evaluator you used before
229
+ direct_hit=0.95, # optional: trust hits this close without verifying
230
+ )
215
231
  cache.init(similarity_evaluation=evaluator, ...)
216
232
 
217
233
  # when you learn a served hit's real outcome:
218
234
  evaluator.report_feedback(query, answer, was_correct=False, similarity_score=0.9)
219
235
  ```
220
236
 
237
+ GPTCache applies its `similarity_threshold` to whatever the evaluator returns,
238
+ so replacing your evaluator also drops the similarity check it did. With
239
+ `fallback` set:
240
+
241
+ - during cold start, hits are decided by the fallback exactly as before (the
242
+ first one logs a warning); `cold_start="reject"` makes them misses instead.
243
+ Without a fallback, cold-start hits are always misses.
244
+ - `direct_hit` serves hits whose fallback score is at least that high without
245
+ a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
246
+
221
247
  See [`examples/gptcache_example.py`](examples/gptcache_example.py).
222
248
 
223
249
  ## Entries to refresh
@@ -100,10 +100,13 @@ cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score=
100
100
  | `latency_ms` | server-side inference time |
101
101
  | `degraded` | `True` when the call failed and this result was synthesized client-side |
102
102
  | `notice` | why no model decided the call (cold start); `None` otherwise |
103
+ | `cold_start` | property: `True` when no model decided the call (`model_version` is `"cold_start_..."`) |
103
104
  | `shadow` | cold start only: a `ShadowVerdict` with what the shared stock model would have decided. The call is still rejected, so treat it as a preview |
104
105
 
105
106
  A new account starts in cold start: every call returns `approved=False` until a
106
- Health Check shows the shared model is accurate enough on your data. Look at
107
+ Health Check shows the shared model is accurate enough on your data. (The
108
+ LangChain and GPTCache integrations hand cold-start hits back to your cache's
109
+ own decision instead, see below.) Look at
107
110
  `result.shadow` to see what it would have decided in the meantime:
108
111
 
109
112
  ```python
@@ -164,21 +167,44 @@ set_llm_cache(
164
167
  )
165
168
  ```
166
169
 
170
+ Until your workspace has a model of its own (cold start), the service
171
+ decides nothing and would reject every hit, which would switch your cache
172
+ off. So during cold start `VerifiedCache` serves each hit exactly as the
173
+ wrapped cache returned it, the same as without it, and logs a warning the
174
+ first time. Pass `cold_start="reject"` to fall through to your model instead,
175
+ for example if you loosened the wrapped cache's similarity threshold because
176
+ a verifier would be checking its hits.
177
+
167
178
  ## GPTCache
168
179
 
169
180
  Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:
170
181
 
171
182
  ```python
172
183
  from gptcache import cache
184
+ from gptcache.similarity_evaluation import SearchDistanceEvaluation
173
185
  from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
174
186
 
175
- evaluator = CacheVerifierEvaluation(api_key="cv_...")
187
+ evaluator = CacheVerifierEvaluation(
188
+ api_key="cv_...",
189
+ fallback=SearchDistanceEvaluation(), # the evaluator you used before
190
+ direct_hit=0.95, # optional: trust hits this close without verifying
191
+ )
176
192
  cache.init(similarity_evaluation=evaluator, ...)
177
193
 
178
194
  # when you learn a served hit's real outcome:
179
195
  evaluator.report_feedback(query, answer, was_correct=False, similarity_score=0.9)
180
196
  ```
181
197
 
198
+ GPTCache applies its `similarity_threshold` to whatever the evaluator returns,
199
+ so replacing your evaluator also drops the similarity check it did. With
200
+ `fallback` set:
201
+
202
+ - during cold start, hits are decided by the fallback exactly as before (the
203
+ first one logs a warning); `cold_start="reject"` makes them misses instead.
204
+ Without a fallback, cold-start hits are always misses.
205
+ - `direct_hit` serves hits whose fallback score is at least that high without
206
+ a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.
207
+
182
208
  See [`examples/gptcache_example.py`](examples/gptcache_example.py).
183
209
 
184
210
  ## 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.7.1"
22
+ __version__ = "0.8.0"
23
23
  __all__ = [
24
24
  "CacheVerifier",
25
25
  "CacheVerifierError",
@@ -29,9 +29,14 @@ DEFAULT_VERIFY_TIMEOUT = 1.0
29
29
  #: failed (timeout / connection error / 5xx) and the client fell back.
30
30
  VERIFY_UNAVAILABLE = "verify_unavailable"
31
31
 
32
+ #: model_version prefix the API uses when no model ran because the workspace
33
+ #: is still in cold start ("cold_start_fail_closed" / "cold_start_auto_pending").
34
+ COLD_START_PREFIX = "cold_start_"
35
+
32
36
  _log = logging.getLogger(__name__)
33
37
 
34
38
  __all__ = [
39
+ "COLD_START_PREFIX",
35
40
  "DEFAULT_BASE_URL",
36
41
  "DEFAULT_TIMEOUT",
37
42
  "DEFAULT_VERIFY_TIMEOUT",
@@ -102,6 +107,8 @@ class VerifyResult:
102
107
  (default `False` -> `approved=False`, i.e. fall through to your LLM).
103
108
  - `notice`: a plain-language reason when no model decided the call (cold
104
109
  start); None otherwise.
110
+ - `cold_start` (property): True when no model decided the call, i.e.
111
+ `model_version` is `"cold_start_..."`.
105
112
  - `shadow`: on a cold-start call, what the shared stock model would have
106
113
  decided (a `ShadowVerdict`); None otherwise, and on servers that don't
107
114
  send it.
@@ -129,6 +136,14 @@ class VerifyResult:
129
136
  local_decision: str | None = None
130
137
  """`LocalVerifier` only: its handle for this decision until upload."""
131
138
 
139
+ @property
140
+ def cold_start(self) -> bool:
141
+ """True when no model decided this call: the workspace has no model
142
+ of its own yet and runs fail-closed, so `approved` is always False
143
+ and `notice` says what to do next. A verdict from the shared stock
144
+ model is not a cold start in this sense: a model did run."""
145
+ return self.model_version.startswith(COLD_START_PREFIX)
146
+
132
147
  @classmethod
133
148
  def _from_json(cls, d: dict[str, Any]) -> VerifyResult:
134
149
  shadow = d.get("shadow")
@@ -0,0 +1,52 @@
1
+ """What an integration does with a cold-start verdict.
2
+
3
+ While a workspace has no model of its own, `/v1/verify` runs fail-closed and
4
+ rejects every call. Rejecting a call the caller only sends in its gray zone
5
+ is cheap. An integration, though, sends every hit its cache backend
6
+ returns, and rejecting all of them switches the cache off: the hit rate
7
+ drops to zero, LLM spend goes up, and nothing is protected that wasn't
8
+ already being served before CacheVerifier was added. So by default an
9
+ integration hands a cold-start call back to the cache's own decision, and
10
+ says so once in the log.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import threading
17
+
18
+ from cacheverifier.client import VerifyResult
19
+
20
+ COLD_START_MODES = ("serve", "reject")
21
+
22
+ _log = logging.getLogger("cacheverifier.integrations")
23
+
24
+
25
+ def check_mode(cold_start: str) -> str:
26
+ if cold_start not in COLD_START_MODES:
27
+ raise ValueError(f"cold_start must be one of {COLD_START_MODES}, got {cold_start!r}")
28
+ return cold_start
29
+
30
+
31
+ class ColdStartNotice:
32
+ """Logs the first cold-start verdict an integration instance sees, once."""
33
+
34
+ def __init__(self, integration: str) -> None:
35
+ self._integration = integration
36
+ self._lock = threading.Lock()
37
+ self._logged = False
38
+
39
+ def seen(self, result: VerifyResult, action: str) -> None:
40
+ """`action`: what the integration does with cold-start hits, in a
41
+ phrase ("serving ... unchanged until a model is ready")."""
42
+ with self._lock:
43
+ if self._logged:
44
+ return
45
+ self._logged = True
46
+ _log.warning(
47
+ "cacheverifier %s: no model decides your calls yet (%s) -- %s. %s",
48
+ self._integration,
49
+ result.model_version,
50
+ action,
51
+ result.notice or "Run a Health Check at https://www.cacheverifier.com to get one.",
52
+ )
@@ -0,0 +1,174 @@
1
+ """GPTCache integration: a `SimilarityEvaluation` that calls the hosted
2
+ CacheVerifier `/v1/verify` endpoint instead of relying on cosine/dot-product
3
+ similarity alone.
4
+
5
+ GPTCache's `SimilarityEvaluation` interface (`evaluation()` + `range()`) is
6
+ a zero-friction integration point: any subclass drops straight into a
7
+ GPTCache pipeline's `similarity_evaluation=` argument, no upstream PR
8
+ required.
9
+
10
+ from gptcache import cache
11
+ from gptcache.similarity_evaluation import SearchDistanceEvaluation
12
+ from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
13
+
14
+ cache.init(
15
+ similarity_evaluation=CacheVerifierEvaluation(
16
+ api_key="cv_...",
17
+ fallback=SearchDistanceEvaluation(), # the evaluator you used before
18
+ ),
19
+ ...
20
+ )
21
+
22
+ `fallback` is the evaluator this one replaces. With it, GPTCache keeps
23
+ deciding exactly as before while your workspace has no model of its own
24
+ (cold start), and `direct_hit` can skip the verify call for hits that are
25
+ close enough on their own. Without it, every cold-start hit is a miss.
26
+
27
+ `gptcache` is an optional dependency -- `pip install "cacheverifier[gptcache]"`.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ from typing import Any
33
+
34
+ from cacheverifier.client import (
35
+ DEFAULT_BASE_URL,
36
+ DEFAULT_TIMEOUT,
37
+ DEFAULT_VERIFY_TIMEOUT,
38
+ CacheVerifier,
39
+ )
40
+ from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode
41
+
42
+ try:
43
+ from gptcache.similarity_evaluation import SimilarityEvaluation as _GPTCacheBase
44
+ except ImportError: # keep importable without gptcache installed
45
+ _GPTCacheBase = object
46
+
47
+
48
+ class CacheVerifierEvaluation(_GPTCacheBase):
49
+ """Drop-in replacement for GPTCache's built-in similarity evaluators.
50
+
51
+ `evaluation()` returns 1.0 (reuse) or 0.0 (don't) for a verified hit --
52
+ binary, because the hosted verifier already makes a binary approve/reject
53
+ call per gray-zone hit rather than a softened similarity score.
54
+
55
+ `fallback` (optional, recommended): the GPTCache evaluator you ran before,
56
+ e.g. `SearchDistanceEvaluation()`. GPTCache applies its
57
+ `similarity_threshold` to whatever `evaluation()` returns, so replacing
58
+ your evaluator also drops the similarity check it did. `fallback` puts it
59
+ back where it is needed:
60
+
61
+ - cold start (no model of your own yet, so the service decides nothing):
62
+ with `cold_start="serve"` (the default) `evaluation()` returns the
63
+ fallback's own score, rescaled so GPTCache's `similarity_threshold`
64
+ accepts exactly the hits it accepted before. The first such call is
65
+ logged as a warning. `cold_start="reject"` makes every cold-start hit a
66
+ miss instead: do that if you loosened your similarity setup because a
67
+ verifier would be checking the hits. Without a fallback there is no
68
+ earlier decision to keep, so cold-start hits are misses either way.
69
+ - `direct_hit` (needs `fallback`): a hit whose rescaled fallback score is
70
+ at least this is served without calling `/v1/verify`, the way a
71
+ gray-zone setup trusts hits above its upper bound. Same 0-1 scale as
72
+ GPTCache's `similarity_threshold`.
73
+
74
+ If the verify call times out or the service is unreachable, `evaluation()`
75
+ returns 0.0 (don't reuse) by default -- a verifier outage falls through to
76
+ a normal GPTCache miss. Pass `fail_open=True` to reuse the cached answer
77
+ instead in that case.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ api_key: str,
83
+ *,
84
+ base_url: str = DEFAULT_BASE_URL,
85
+ timeout: float = DEFAULT_TIMEOUT,
86
+ verify_timeout: float = DEFAULT_VERIFY_TIMEOUT,
87
+ fail_open: bool = False,
88
+ fallback: Any = None,
89
+ cold_start: str = "serve",
90
+ direct_hit: float | None = None,
91
+ ) -> None:
92
+ if direct_hit is not None and fallback is None:
93
+ raise ValueError("direct_hit needs fallback: it is measured on the fallback evaluator's score")
94
+ if fallback is not None:
95
+ low, high = fallback.range()
96
+ if not high > low:
97
+ raise ValueError(f"fallback.range() must be increasing, got {(low, high)!r}")
98
+ self._fallback_span = float(high - low)
99
+ self.fallback = fallback
100
+ self.cold_start = check_mode(cold_start)
101
+ self.direct_hit = direct_hit
102
+ self._cold_start_notice = ColdStartNotice("CacheVerifierEvaluation")
103
+ self._cv = CacheVerifier(
104
+ api_key=api_key,
105
+ base_url=base_url,
106
+ timeout=timeout,
107
+ verify_timeout=verify_timeout,
108
+ fail_open=fail_open,
109
+ )
110
+
111
+ def _fallback_score(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwargs: Any) -> float:
112
+ """The fallback's score divided by the width of its range: GPTCache
113
+ accepts a hit when rank >= (max - min) * similarity_threshold, so on
114
+ this evaluator's (0, 1) range the rescaled score passes exactly when
115
+ the raw one passed on the fallback's own range. Exact for any range
116
+ that starts at 0, which every built-in GPTCache evaluator's does."""
117
+ return float(self.fallback.evaluation(src_dict, cache_dict, **kwargs)) / self._fallback_span
118
+
119
+ def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwargs: Any) -> float:
120
+ fallback_score = None
121
+ if self.fallback is not None:
122
+ fallback_score = self._fallback_score(src_dict, cache_dict, **kwargs)
123
+ if self.direct_hit is not None and fallback_score >= self.direct_hit:
124
+ return 1.0
125
+ query = src_dict.get("question") or src_dict.get("query", "")
126
+ candidate_answer = cache_dict.get("answer", "")
127
+ result = self._cv.verify(query, candidate_answer)
128
+ if result.cold_start:
129
+ serve = self.cold_start == "serve" and fallback_score is not None
130
+ if serve:
131
+ action = (
132
+ "deciding hits with your fallback evaluator, as before, until a model is ready "
133
+ "(cold_start='reject' makes them misses instead)"
134
+ )
135
+ elif self.cold_start == "serve":
136
+ action = (
137
+ "every hit is a miss until a model is ready; pass fallback=<the evaluator you "
138
+ "used before> to keep its decisions meanwhile"
139
+ )
140
+ else:
141
+ action = "every hit is a miss until a model is ready (cold_start='reject')"
142
+ self._cold_start_notice.seen(result, action)
143
+ return fallback_score if serve and fallback_score is not None else 0.0
144
+ return 1.0 if result.approved else 0.0
145
+
146
+ def range(self) -> tuple[float, float]:
147
+ return 0.0, 1.0
148
+
149
+ def report_feedback(
150
+ self,
151
+ query: str,
152
+ candidate_answer: str,
153
+ was_correct: bool,
154
+ similarity_score: float | None = None,
155
+ ) -> None:
156
+ """Not part of GPTCache's interface -- call it once you know whether
157
+ a served hit was actually correct (a thumbs-down, a reopened
158
+ ticket, ...). Feeds `POST /v1/feedback`, which fine-tuning and drift
159
+ monitoring both consume.
160
+
161
+ `similarity_score` is optional: pass GPTCache's own vector-search
162
+ score for this candidate if you still have it when you learn
163
+ `was_correct` -- that is what lets the service later recommend a
164
+ tau_high for your GPTCache config (`gray_zone_threshold()`).
165
+ """
166
+ self._cv.feedback(
167
+ query,
168
+ candidate_answer,
169
+ was_correct,
170
+ similarity_score=similarity_score,
171
+ )
172
+
173
+ def close(self) -> None:
174
+ self._cv.close()
@@ -24,6 +24,14 @@ call times out or the service is unreachable, the hit is rejected by
24
24
  default (a verifier outage becomes a normal cache miss); pass
25
25
  `fail_open=True` to serve it instead.
26
26
 
27
+ Until your workspace has a model of its own, the service decides nothing
28
+ (cold start) and would reject every hit, which switches your cache off. So
29
+ by default a cold-start hit is served exactly as the wrapped cache returned
30
+ it, the same as without `VerifiedCache`, and the first one is logged as a
31
+ warning. Pass `cold_start="reject"` to fall through to your model instead:
32
+ do that if you loosened the wrapped cache's similarity threshold because a
33
+ verifier would be checking its hits.
34
+
27
35
  `langchain-core` is an optional dependency -- `pip install "cacheverifier[langchain]"`.
28
36
  """
29
37
 
@@ -39,6 +47,7 @@ from cacheverifier.client import (
39
47
  DEFAULT_VERIFY_TIMEOUT,
40
48
  CacheVerifier,
41
49
  )
50
+ from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode
42
51
 
43
52
  try:
44
53
  from langchain_core.caches import RETURN_VAL_TYPE, BaseCache
@@ -96,7 +105,10 @@ class VerifiedCache(BaseCache):
96
105
  timeout: float = DEFAULT_TIMEOUT,
97
106
  verify_timeout: float = DEFAULT_VERIFY_TIMEOUT,
98
107
  fail_open: bool = False,
108
+ cold_start: str = "serve",
99
109
  ) -> None:
110
+ self.cold_start = check_mode(cold_start)
111
+ self._cold_start_notice = ColdStartNotice("VerifiedCache")
100
112
  if client is None:
101
113
  if not api_key:
102
114
  raise ValueError("pass api_key or client")
@@ -112,7 +124,18 @@ class VerifiedCache(BaseCache):
112
124
 
113
125
  def _approved(self, prompt: str, hit: RETURN_VAL_TYPE) -> bool:
114
126
  answer = "\n".join(generation.text for generation in hit)
115
- return self.client.verify(user_question(prompt), answer).approved
127
+ result = self.client.verify(user_question(prompt), answer)
128
+ if result.cold_start:
129
+ serve = self.cold_start == "serve"
130
+ self._cold_start_notice.seen(
131
+ result,
132
+ "serving the wrapped cache's hits unchanged until a model is ready "
133
+ "(cold_start='reject' falls through to your model instead)"
134
+ if serve
135
+ else "every hit falls through to your model until one is ready (cold_start='reject')",
136
+ )
137
+ return serve
138
+ return result.approved
116
139
 
117
140
  def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
118
141
  hit = self.cache.lookup(prompt, llm_string)
@@ -14,6 +14,7 @@ from gptcache import cache
14
14
  from gptcache.adapter.api import get, put
15
15
  from gptcache.embedding import Onnx
16
16
  from gptcache.manager import CacheBase, VectorBase, get_data_manager
17
+ from gptcache.similarity_evaluation import SearchDistanceEvaluation
17
18
 
18
19
  from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
19
20
 
@@ -23,7 +24,12 @@ data_manager = get_data_manager(
23
24
  VectorBase("faiss", dimension=embedding.dimension),
24
25
  )
25
26
 
26
- evaluator = CacheVerifierEvaluation(api_key=os.environ["CACHEVERIFIER_API_KEY"])
27
+ # fallback: the evaluator this replaces. It keeps deciding hits while your workspace
28
+ # has no model of its own yet (cold start), instead of every hit becoming a miss.
29
+ evaluator = CacheVerifierEvaluation(
30
+ api_key=os.environ["CACHEVERIFIER_API_KEY"],
31
+ fallback=SearchDistanceEvaluation(),
32
+ )
27
33
 
28
34
  cache.init(
29
35
  embedding_func=embedding.to_embeddings,
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cacheverifier"
7
- version = "0.7.1"
7
+ version = "0.8.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"
@@ -0,0 +1,149 @@
1
+ """The GPTCache adapter must stay importable and usable even when gptcache
2
+ itself isn't installed (it's an optional dependency)."""
3
+
4
+ import httpx
5
+
6
+ from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
7
+
8
+
9
+ def _eval(handler) -> CacheVerifierEvaluation:
10
+ ev = CacheVerifierEvaluation(api_key="cv_test")
11
+ ev._cv._client = httpx.Client( # swap in a mock transport
12
+ base_url="https://www.cacheverifier.com",
13
+ headers={"X-API-Key": "cv_test"},
14
+ transport=httpx.MockTransport(handler),
15
+ )
16
+ return ev
17
+
18
+
19
+ def test_evaluation_maps_approved_to_binary_score():
20
+ def handler(request: httpx.Request) -> httpx.Response:
21
+ assert request.url.path == "/v1/verify"
22
+ return httpx.Response(
23
+ 200,
24
+ json={"approved": True, "score": 2.0, "latency_ms": 5.0, "model_version": "stock", "threshold": 0.0},
25
+ )
26
+
27
+ ev = _eval(handler)
28
+ assert ev.evaluation({"question": "q"}, {"answer": "a"}) == 1.0
29
+ assert ev.range() == (0.0, 1.0)
30
+
31
+
32
+ def test_evaluation_rejects_to_zero():
33
+ def handler(request: httpx.Request) -> httpx.Response:
34
+ return httpx.Response(
35
+ 200,
36
+ json={"approved": False, "score": -1.0, "latency_ms": 5.0, "model_version": "stock", "threshold": 0.0},
37
+ )
38
+
39
+ assert _eval(handler).evaluation({"query": "q"}, {"answer": "a"}) == 0.0
40
+
41
+
42
+ def test_report_feedback_posts_similarity_score():
43
+ seen = {}
44
+
45
+ def handler(request: httpx.Request) -> httpx.Response:
46
+ import json
47
+
48
+ seen["path"] = request.url.path
49
+ seen["body"] = json.loads(request.content)
50
+ return httpx.Response(200, json={"id": 9})
51
+
52
+ _eval(handler).report_feedback("q", "a", was_correct=False, similarity_score=0.9)
53
+ assert seen["path"] == "/v1/feedback"
54
+ assert seen["body"]["similarity_score"] == 0.9
55
+ assert seen["body"]["was_correct"] is False
56
+
57
+
58
+ import logging
59
+
60
+ import pytest
61
+
62
+ _COLD_START = {
63
+ "approved": False,
64
+ "score": 0.0,
65
+ "threshold": 0.0,
66
+ "model_version": "cold_start_fail_closed",
67
+ "latency_ms": 0.0,
68
+ "decision_rule": "cold_start",
69
+ "notice": "No model of your own yet.",
70
+ }
71
+
72
+
73
+ class _Distance:
74
+ """Stands in for GPTCache's SearchDistanceEvaluation(max_distance=4.0)."""
75
+
76
+ def evaluation(self, src_dict, cache_dict, **_kwargs):
77
+ distance, _ = cache_dict["search_result"]
78
+ return 4.0 - min(distance, 4.0)
79
+
80
+ def range(self):
81
+ return 0.0, 4.0
82
+
83
+
84
+ def _eval_with(handler, **kwargs) -> tuple[CacheVerifierEvaluation, list]:
85
+ calls: list = []
86
+
87
+ def counting(request: httpx.Request) -> httpx.Response:
88
+ calls.append(request)
89
+ return handler(request)
90
+
91
+ ev = CacheVerifierEvaluation(api_key="cv_test", **kwargs)
92
+ ev._cv._client = httpx.Client(
93
+ base_url="https://www.cacheverifier.com",
94
+ headers={"X-API-Key": "cv_test"},
95
+ transport=httpx.MockTransport(counting),
96
+ )
97
+ return ev, calls
98
+
99
+
100
+ def _cold(request: httpx.Request) -> httpx.Response:
101
+ return httpx.Response(200, json=_COLD_START)
102
+
103
+
104
+ def test_cold_start_with_fallback_returns_the_fallbacks_rescaled_score(caplog):
105
+ ev, _ = _eval_with(_cold, fallback=_Distance())
106
+ with caplog.at_level(logging.WARNING, logger="cacheverifier.integrations"):
107
+ # distance 0.8 -> fallback 3.2 of 4.0 -> 0.8; GPTCache's default similarity_threshold 0.8
108
+ # accepted it before (3.2 >= 4.0 * 0.8) and accepts it now (0.8 >= 1.0 * 0.8)
109
+ assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.8, 1)}) == pytest.approx(0.8)
110
+ assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (2.0, 1)}) == pytest.approx(0.5)
111
+ warnings = [r for r in caplog.records if r.name == "cacheverifier.integrations"]
112
+ assert len(warnings) == 1
113
+ assert "fallback evaluator" in warnings[0].getMessage()
114
+
115
+
116
+ def test_cold_start_without_fallback_is_a_miss_and_says_how_to_keep_hits(caplog):
117
+ ev, _ = _eval_with(_cold)
118
+ with caplog.at_level(logging.WARNING, logger="cacheverifier.integrations"):
119
+ assert ev.evaluation({"question": "q"}, {"answer": "a"}) == 0.0
120
+ assert "pass fallback=" in caplog.records[-1].getMessage()
121
+
122
+
123
+ def test_cold_start_reject_ignores_the_fallback():
124
+ ev, _ = _eval_with(_cold, fallback=_Distance(), cold_start="reject")
125
+ assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.0, 1)}) == 0.0
126
+
127
+
128
+ def test_direct_hit_skips_the_verify_call():
129
+ ev, calls = _eval_with(_cold, fallback=_Distance(), direct_hit=0.95)
130
+ assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.1, 1)}) == 1.0 # 3.9/4 = 0.975
131
+ assert calls == []
132
+ ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (1.0, 1)}) # 0.75: verified
133
+ assert len(calls) == 1
134
+
135
+
136
+ def test_a_model_verdict_still_decides_when_a_fallback_is_set():
137
+ def rejecting(request: httpx.Request) -> httpx.Response:
138
+ return httpx.Response(
139
+ 200,
140
+ json={"approved": False, "score": -1.0, "latency_ms": 5.0, "model_version": "v3", "threshold": 0.0},
141
+ )
142
+
143
+ ev, _ = _eval_with(rejecting, fallback=_Distance())
144
+ assert ev.evaluation({"question": "q"}, {"answer": "a", "search_result": (0.0, 1)}) == 0.0
145
+
146
+
147
+ def test_direct_hit_needs_a_fallback():
148
+ with pytest.raises(ValueError):
149
+ CacheVerifierEvaluation(api_key="cv_test", direct_hit=0.9)
@@ -88,3 +88,65 @@ def test_user_question_falls_back_to_the_raw_prompt():
88
88
  def test_needs_a_key_or_a_client():
89
89
  with pytest.raises(ValueError):
90
90
  VerifiedCache(InMemoryCache())
91
+
92
+
93
+ _COLD_START = {
94
+ "approved": False,
95
+ "score": 0.0,
96
+ "threshold": 0.0,
97
+ "model_version": "cold_start_auto_pending",
98
+ "latency_ms": 0.0,
99
+ "decision_rule": "cold_start",
100
+ "notice": "Run a Health Check to let the stock model decide.",
101
+ }
102
+
103
+
104
+ def _cold(cold_start: str | None = None) -> VerifiedCache:
105
+ def handler(request: httpx.Request) -> httpx.Response:
106
+ return httpx.Response(200, json=_COLD_START)
107
+
108
+ client = CacheVerifier(api_key="cv_test", transport=httpx.MockTransport(handler))
109
+ kwargs = {} if cold_start is None else {"cold_start": cold_start}
110
+ return VerifiedCache(InMemoryCache(), client=client, **kwargs)
111
+
112
+
113
+ def test_cold_start_serves_the_wrapped_caches_hit_by_default_and_warns_once(caplog):
114
+ cache = _cold()
115
+ cache.update("when does my flight board", "llm", [Generation(text="40 minutes before departure.")])
116
+ with caplog.at_level("WARNING", logger="cacheverifier.integrations"):
117
+ assert cache.lookup("when does my flight board", "llm")[0].text == "40 minutes before departure."
118
+ assert asyncio.run(cache.alookup("when does my flight board", "llm"))[0].text == "40 minutes before departure."
119
+ warnings = [r for r in caplog.records if r.name == "cacheverifier.integrations"]
120
+ assert len(warnings) == 1
121
+ assert "cold_start_auto_pending" in warnings[0].getMessage()
122
+ assert "Run a Health Check" in warnings[0].getMessage()
123
+
124
+
125
+ def test_cold_start_reject_makes_every_hit_a_miss():
126
+ cache = _cold("reject")
127
+ cache.update("q", "llm", [Generation(text="a")])
128
+ assert cache.lookup("q", "llm") is None
129
+
130
+
131
+ def test_a_stock_model_rejection_is_not_a_cold_start():
132
+ cache = _verified(False) # model_version "stock": a model ran and said no
133
+ cache.update("q", "llm", [Generation(text="a")])
134
+ assert cache.lookup("q", "llm") is None
135
+
136
+
137
+ def test_an_audited_call_still_falls_through_during_serve_mode():
138
+ def handler(request: httpx.Request) -> httpx.Response:
139
+ return httpx.Response(
140
+ 200,
141
+ json={"approved": False, "audit": True, "verification_id": 7, "score": 3.0, "latency_ms": 5.0,
142
+ "model_version": "v12", "threshold": 0.0},
143
+ )
144
+
145
+ cache = VerifiedCache(InMemoryCache(), client=CacheVerifier(api_key="cv_test", transport=httpx.MockTransport(handler)))
146
+ cache.update("q", "llm", [Generation(text="a")])
147
+ assert cache.lookup("q", "llm") is None
148
+
149
+
150
+ def test_bad_cold_start_mode_is_rejected():
151
+ with pytest.raises(ValueError):
152
+ VerifiedCache(InMemoryCache(), api_key="cv_test", cold_start="open")
@@ -1,102 +0,0 @@
1
- """GPTCache integration: a `SimilarityEvaluation` that calls the hosted
2
- CacheVerifier `/v1/verify` endpoint instead of relying on cosine/dot-product
3
- similarity alone.
4
-
5
- GPTCache's `SimilarityEvaluation` interface (`evaluation()` + `range()`) is
6
- a zero-friction integration point: any subclass drops straight into a
7
- GPTCache pipeline's `similarity_evaluation=` argument, no upstream PR
8
- required.
9
-
10
- from gptcache import cache
11
- from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
12
-
13
- cache.init(
14
- similarity_evaluation=CacheVerifierEvaluation(api_key="cv_..."),
15
- ...
16
- )
17
-
18
- `gptcache` is an optional dependency -- `pip install "cacheverifier[gptcache]"`.
19
- """
20
-
21
- from __future__ import annotations
22
-
23
- from typing import Any
24
-
25
- from cacheverifier.client import (
26
- DEFAULT_BASE_URL,
27
- DEFAULT_TIMEOUT,
28
- DEFAULT_VERIFY_TIMEOUT,
29
- CacheVerifier,
30
- )
31
-
32
- try:
33
- from gptcache.similarity_evaluation import SimilarityEvaluation as _GPTCacheBase
34
- except ImportError: # keep importable without gptcache installed
35
- _GPTCacheBase = object
36
-
37
-
38
- class CacheVerifierEvaluation(_GPTCacheBase):
39
- """Drop-in replacement for GPTCache's built-in similarity evaluators.
40
-
41
- `evaluation()` returns 1.0 (reuse) or 0.0 (don't) -- binary, because the
42
- hosted verifier already makes a binary approve/reject call per gray-zone
43
- hit rather than a softened similarity score. Callers who want GPTCache's
44
- own threshold logic on top can wrap this rather than replace it.
45
-
46
- If the verify call times out or the service is unreachable, `evaluation()`
47
- returns 0.0 (don't reuse) by default -- a verifier outage falls through to
48
- a normal GPTCache miss. Pass `fail_open=True` to reuse the cached answer
49
- instead in that case.
50
- """
51
-
52
- def __init__(
53
- self,
54
- api_key: str,
55
- *,
56
- base_url: str = DEFAULT_BASE_URL,
57
- timeout: float = DEFAULT_TIMEOUT,
58
- verify_timeout: float = DEFAULT_VERIFY_TIMEOUT,
59
- fail_open: bool = False,
60
- ) -> None:
61
- self._cv = CacheVerifier(
62
- api_key=api_key,
63
- base_url=base_url,
64
- timeout=timeout,
65
- verify_timeout=verify_timeout,
66
- fail_open=fail_open,
67
- )
68
-
69
- def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **_kwargs: Any) -> float:
70
- query = src_dict.get("question") or src_dict.get("query", "")
71
- candidate_answer = cache_dict.get("answer", "")
72
- return 1.0 if self._cv.verify(query, candidate_answer).approved else 0.0
73
-
74
- def range(self) -> tuple[float, float]:
75
- return 0.0, 1.0
76
-
77
- def report_feedback(
78
- self,
79
- query: str,
80
- candidate_answer: str,
81
- was_correct: bool,
82
- similarity_score: float | None = None,
83
- ) -> None:
84
- """Not part of GPTCache's interface -- call it once you know whether
85
- a served hit was actually correct (a thumbs-down, a reopened
86
- ticket, ...). Feeds `POST /v1/feedback`, which fine-tuning and drift
87
- monitoring both consume.
88
-
89
- `similarity_score` is optional: pass GPTCache's own vector-search
90
- score for this candidate if you still have it when you learn
91
- `was_correct` -- that is what lets the service later recommend a
92
- tau_high for your GPTCache config (`gray_zone_threshold()`).
93
- """
94
- self._cv.feedback(
95
- query,
96
- candidate_answer,
97
- was_correct,
98
- similarity_score=similarity_score,
99
- )
100
-
101
- def close(self) -> None:
102
- self._cv.close()
@@ -1,55 +0,0 @@
1
- """The GPTCache adapter must stay importable and usable even when gptcache
2
- itself isn't installed (it's an optional dependency)."""
3
-
4
- import httpx
5
-
6
- from cacheverifier.integrations.gptcache import CacheVerifierEvaluation
7
-
8
-
9
- def _eval(handler) -> CacheVerifierEvaluation:
10
- ev = CacheVerifierEvaluation(api_key="cv_test")
11
- ev._cv._client = httpx.Client( # swap in a mock transport
12
- base_url="https://www.cacheverifier.com",
13
- headers={"X-API-Key": "cv_test"},
14
- transport=httpx.MockTransport(handler),
15
- )
16
- return ev
17
-
18
-
19
- def test_evaluation_maps_approved_to_binary_score():
20
- def handler(request: httpx.Request) -> httpx.Response:
21
- assert request.url.path == "/v1/verify"
22
- return httpx.Response(
23
- 200,
24
- json={"approved": True, "score": 2.0, "latency_ms": 5.0, "model_version": "stock", "threshold": 0.0},
25
- )
26
-
27
- ev = _eval(handler)
28
- assert ev.evaluation({"question": "q"}, {"answer": "a"}) == 1.0
29
- assert ev.range() == (0.0, 1.0)
30
-
31
-
32
- def test_evaluation_rejects_to_zero():
33
- def handler(request: httpx.Request) -> httpx.Response:
34
- return httpx.Response(
35
- 200,
36
- json={"approved": False, "score": -1.0, "latency_ms": 5.0, "model_version": "stock", "threshold": 0.0},
37
- )
38
-
39
- assert _eval(handler).evaluation({"query": "q"}, {"answer": "a"}) == 0.0
40
-
41
-
42
- def test_report_feedback_posts_similarity_score():
43
- seen = {}
44
-
45
- def handler(request: httpx.Request) -> httpx.Response:
46
- import json
47
-
48
- seen["path"] = request.url.path
49
- seen["body"] = json.loads(request.content)
50
- return httpx.Response(200, json={"id": 9})
51
-
52
- _eval(handler).report_feedback("q", "a", was_correct=False, similarity_score=0.9)
53
- assert seen["path"] == "/v1/feedback"
54
- assert seen["body"]["similarity_score"] == 0.9
55
- assert seen["body"]["was_correct"] is False
File without changes
File without changes