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

Filter by extension

Filter by extension


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

## 0.8.0

The integrations no longer switch your cache off during cold start. While a
workspace has no model of its own, `/v1/verify` rejects every call; an
integration sends every hit, so that rejected all of them, silently.

- `VerifiedCache` (LangChain) now serves cold-start hits exactly as the
wrapped cache returned them, and logs the service's notice once. Pass
`cold_start="reject"` for the old behavior.
- `CacheVerifierEvaluation` (GPTCache) takes `fallback=`, the evaluator it
replaces (e.g. `SearchDistanceEvaluation()`): during cold start GPTCache
decides with it exactly as before. Without a fallback, cold-start hits stay
misses, now with a warning saying how to keep them. `direct_hit=` serves
hits whose fallback score is at least that high without a verify call.
- `VerifyResult.cold_start`: True when no model decided the call.

## 0.7.1

README only, no code change, so the PyPI page matches the docs: the
Expand Down
30 changes: 28 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,13 @@ cv.feedback(query, candidate, was_correct=candidate_was_right, similarity_score=
| `latency_ms` | server-side inference time |
| `degraded` | `True` when the call failed and this result was synthesized client-side |
| `notice` | why no model decided the call (cold start); `None` otherwise |
| `cold_start` | property: `True` when no model decided the call (`model_version` is `"cold_start_..."`) |
| `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 |

A new account starts in cold start: every call returns `approved=False` until a
Health Check shows the shared model is accurate enough on your data. Look at
Health Check shows the shared model is accurate enough on your data. (The
LangChain and GPTCache integrations hand cold-start hits back to your cache's
own decision instead, see below.) Look at
`result.shadow` to see what it would have decided in the meantime:

```python
Expand Down Expand Up @@ -164,21 +167,44 @@ set_llm_cache(
)
```

Until your workspace has a model of its own (cold start), the service
decides nothing and would reject every hit, which would switch your cache
off. So during cold start `VerifiedCache` serves each hit exactly as the
wrapped cache returned it, the same as without it, and logs a warning the
first time. Pass `cold_start="reject"` to fall through to your model instead,
for example if you loosened the wrapped cache's similarity threshold because
a verifier would be checking its hits.

## GPTCache

Drop the verifier into a GPTCache pipeline as its similarity evaluator — no fork required:

```python
from gptcache import cache
from gptcache.similarity_evaluation import SearchDistanceEvaluation
from cacheverifier.integrations.gptcache import CacheVerifierEvaluation

evaluator = CacheVerifierEvaluation(api_key="cv_...")
evaluator = CacheVerifierEvaluation(
api_key="cv_...",
fallback=SearchDistanceEvaluation(), # the evaluator you used before
direct_hit=0.95, # optional: trust hits this close without verifying
)
cache.init(similarity_evaluation=evaluator, ...)

# when you learn a served hit's real outcome:
evaluator.report_feedback(query, answer, was_correct=False, similarity_score=0.9)
```

GPTCache applies its `similarity_threshold` to whatever the evaluator returns,
so replacing your evaluator also drops the similarity check it did. With
`fallback` set:

- during cold start, hits are decided by the fallback exactly as before (the
first one logs a warning); `cold_start="reject"` makes them misses instead.
Without a fallback, cold-start hits are always misses.
- `direct_hit` serves hits whose fallback score is at least that high without
a verify call. It uses the same 0–1 scale as GPTCache's `similarity_threshold`.

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

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

__version__ = "0.7.1"
__version__ = "0.8.0"
__all__ = [
"CacheVerifier",
"CacheVerifierError",
Expand Down
15 changes: 15 additions & 0 deletions cacheverifier/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,14 @@
#: failed (timeout / connection error / 5xx) and the client fell back.
VERIFY_UNAVAILABLE = "verify_unavailable"

#: model_version prefix the API uses when no model ran because the workspace
#: is still in cold start ("cold_start_fail_closed" / "cold_start_auto_pending").
COLD_START_PREFIX = "cold_start_"

_log = logging.getLogger(__name__)

__all__ = [
"COLD_START_PREFIX",
"DEFAULT_BASE_URL",
"DEFAULT_TIMEOUT",
"DEFAULT_VERIFY_TIMEOUT",
Expand Down Expand Up @@ -102,6 +107,8 @@ class VerifyResult:
(default `False` -> `approved=False`, i.e. fall through to your LLM).
- `notice`: a plain-language reason when no model decided the call (cold
start); None otherwise.
- `cold_start` (property): True when no model decided the call, i.e.
`model_version` is `"cold_start_..."`.
- `shadow`: on a cold-start call, what the shared stock model would have
decided (a `ShadowVerdict`); None otherwise, and on servers that don't
send it.
Expand Down Expand Up @@ -129,6 +136,14 @@ class VerifyResult:
local_decision: str | None = None
"""`LocalVerifier` only: its handle for this decision until upload."""

@property
def cold_start(self) -> bool:
"""True when no model decided this call: the workspace has no model
of its own yet and runs fail-closed, so `approved` is always False
and `notice` says what to do next. A verdict from the shared stock
model is not a cold start in this sense: a model did run."""
return self.model_version.startswith(COLD_START_PREFIX)

@classmethod
def _from_json(cls, d: dict[str, Any]) -> VerifyResult:
shadow = d.get("shadow")
Expand Down
52 changes: 52 additions & 0 deletions cacheverifier/integrations/_cold_start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""What an integration does with a cold-start verdict.

While a workspace has no model of its own, `/v1/verify` runs fail-closed and
rejects every call. Rejecting a call the caller only sends in its gray zone
is cheap. An integration, though, sends every hit its cache backend
returns, and rejecting all of them switches the cache off: the hit rate
drops to zero, LLM spend goes up, and nothing is protected that wasn't
already being served before CacheVerifier was added. So by default an
integration hands a cold-start call back to the cache's own decision, and
says so once in the log.
"""

from __future__ import annotations

import logging
import threading

from cacheverifier.client import VerifyResult

COLD_START_MODES = ("serve", "reject")

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


def check_mode(cold_start: str) -> str:
if cold_start not in COLD_START_MODES:
raise ValueError(f"cold_start must be one of {COLD_START_MODES}, got {cold_start!r}")
return cold_start


class ColdStartNotice:
"""Logs the first cold-start verdict an integration instance sees, once."""

def __init__(self, integration: str) -> None:
self._integration = integration
self._lock = threading.Lock()
self._logged = False

def seen(self, result: VerifyResult, action: str) -> None:
"""`action`: what the integration does with cold-start hits, in a
phrase ("serving ... unchanged until a model is ready")."""
with self._lock:
if self._logged:
return
self._logged = True
_log.warning(
"cacheverifier %s: no model decides your calls yet (%s) -- %s. %s",
self._integration,
result.model_version,
action,
result.notice or "Run a Health Check at https://www.cacheverifier.com to get one.",
)
86 changes: 79 additions & 7 deletions cacheverifier/integrations/gptcache.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,22 @@
required.

from gptcache import cache
from gptcache.similarity_evaluation import SearchDistanceEvaluation
from cacheverifier.integrations.gptcache import CacheVerifierEvaluation

cache.init(
similarity_evaluation=CacheVerifierEvaluation(api_key="cv_..."),
similarity_evaluation=CacheVerifierEvaluation(
api_key="cv_...",
fallback=SearchDistanceEvaluation(), # the evaluator you used before
),
...
)

`fallback` is the evaluator this one replaces. With it, GPTCache keeps
deciding exactly as before while your workspace has no model of its own
(cold start), and `direct_hit` can skip the verify call for hits that are
close enough on their own. Without it, every cold-start hit is a miss.

`gptcache` is an optional dependency -- `pip install "cacheverifier[gptcache]"`.
"""

Expand All @@ -28,6 +37,7 @@
DEFAULT_VERIFY_TIMEOUT,
CacheVerifier,
)
from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode

try:
from gptcache.similarity_evaluation import SimilarityEvaluation as _GPTCacheBase
Expand All @@ -38,10 +48,28 @@
class CacheVerifierEvaluation(_GPTCacheBase):
"""Drop-in replacement for GPTCache's built-in similarity evaluators.

`evaluation()` returns 1.0 (reuse) or 0.0 (don't) -- binary, because the
hosted verifier already makes a binary approve/reject call per gray-zone
hit rather than a softened similarity score. Callers who want GPTCache's
own threshold logic on top can wrap this rather than replace it.
`evaluation()` returns 1.0 (reuse) or 0.0 (don't) for a verified hit --
binary, because the hosted verifier already makes a binary approve/reject
call per gray-zone hit rather than a softened similarity score.

`fallback` (optional, recommended): the GPTCache evaluator you ran before,
e.g. `SearchDistanceEvaluation()`. GPTCache applies its
`similarity_threshold` to whatever `evaluation()` returns, so replacing
your evaluator also drops the similarity check it did. `fallback` puts it
back where it is needed:

- cold start (no model of your own yet, so the service decides nothing):
with `cold_start="serve"` (the default) `evaluation()` returns the
fallback's own score, rescaled so GPTCache's `similarity_threshold`
accepts exactly the hits it accepted before. The first such call is
logged as a warning. `cold_start="reject"` makes every cold-start hit a
miss instead: do that if you loosened your similarity setup because a
verifier would be checking the hits. Without a fallback there is no
earlier decision to keep, so cold-start hits are misses either way.
- `direct_hit` (needs `fallback`): a hit whose rescaled fallback score is
at least this is served without calling `/v1/verify`, the way a
gray-zone setup trusts hits above its upper bound. Same 0-1 scale as
GPTCache's `similarity_threshold`.

If the verify call times out or the service is unreachable, `evaluation()`
returns 0.0 (don't reuse) by default -- a verifier outage falls through to
Expand All @@ -57,7 +85,21 @@ def __init__(
timeout: float = DEFAULT_TIMEOUT,
verify_timeout: float = DEFAULT_VERIFY_TIMEOUT,
fail_open: bool = False,
fallback: Any = None,
cold_start: str = "serve",
direct_hit: float | None = None,
) -> None:
if direct_hit is not None and fallback is None:
raise ValueError("direct_hit needs fallback: it is measured on the fallback evaluator's score")
if fallback is not None:
low, high = fallback.range()
if not high > low:
raise ValueError(f"fallback.range() must be increasing, got {(low, high)!r}")
self._fallback_span = float(high - low)
self.fallback = fallback
self.cold_start = check_mode(cold_start)
self.direct_hit = direct_hit
self._cold_start_notice = ColdStartNotice("CacheVerifierEvaluation")
self._cv = CacheVerifier(
api_key=api_key,
base_url=base_url,
Expand All @@ -66,10 +108,40 @@ def __init__(
fail_open=fail_open,
)

def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **_kwargs: Any) -> float:
def _fallback_score(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwargs: Any) -> float:
"""The fallback's score divided by the width of its range: GPTCache
accepts a hit when rank >= (max - min) * similarity_threshold, so on
this evaluator's (0, 1) range the rescaled score passes exactly when
the raw one passed on the fallback's own range. Exact for any range
that starts at 0, which every built-in GPTCache evaluator's does."""
return float(self.fallback.evaluation(src_dict, cache_dict, **kwargs)) / self._fallback_span

def evaluation(self, src_dict: dict[str, Any], cache_dict: dict[str, Any], **kwargs: Any) -> float:
fallback_score = None
if self.fallback is not None:
fallback_score = self._fallback_score(src_dict, cache_dict, **kwargs)
if self.direct_hit is not None and fallback_score >= self.direct_hit:
return 1.0
query = src_dict.get("question") or src_dict.get("query", "")
candidate_answer = cache_dict.get("answer", "")
return 1.0 if self._cv.verify(query, candidate_answer).approved else 0.0
result = self._cv.verify(query, candidate_answer)
if result.cold_start:
serve = self.cold_start == "serve" and fallback_score is not None
if serve:
action = (
"deciding hits with your fallback evaluator, as before, until a model is ready "
"(cold_start='reject' makes them misses instead)"
)
elif self.cold_start == "serve":
action = (
"every hit is a miss until a model is ready; pass fallback=<the evaluator you "
"used before> to keep its decisions meanwhile"
)
else:
action = "every hit is a miss until a model is ready (cold_start='reject')"
self._cold_start_notice.seen(result, action)
return fallback_score if serve and fallback_score is not None else 0.0
return 1.0 if result.approved else 0.0

def range(self) -> tuple[float, float]:
return 0.0, 1.0
Expand Down
25 changes: 24 additions & 1 deletion cacheverifier/integrations/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@
default (a verifier outage becomes a normal cache miss); pass
`fail_open=True` to serve it instead.

Until your workspace has a model of its own, the service decides nothing
(cold start) and would reject every hit, which switches your cache off. So
by default a cold-start hit is served exactly as the wrapped cache returned
it, the same as without `VerifiedCache`, and the first one is logged as a
warning. Pass `cold_start="reject"` to fall through to your model instead:
do that if you loosened the wrapped cache's similarity threshold because a
verifier would be checking its hits.

`langchain-core` is an optional dependency -- `pip install "cacheverifier[langchain]"`.
"""

Expand All @@ -39,6 +47,7 @@
DEFAULT_VERIFY_TIMEOUT,
CacheVerifier,
)
from cacheverifier.integrations._cold_start import ColdStartNotice, check_mode

try:
from langchain_core.caches import RETURN_VAL_TYPE, BaseCache
Expand Down Expand Up @@ -96,7 +105,10 @@ def __init__(
timeout: float = DEFAULT_TIMEOUT,
verify_timeout: float = DEFAULT_VERIFY_TIMEOUT,
fail_open: bool = False,
cold_start: str = "serve",
) -> None:
self.cold_start = check_mode(cold_start)
self._cold_start_notice = ColdStartNotice("VerifiedCache")
if client is None:
if not api_key:
raise ValueError("pass api_key or client")
Expand All @@ -112,7 +124,18 @@ def __init__(

def _approved(self, prompt: str, hit: RETURN_VAL_TYPE) -> bool:
answer = "\n".join(generation.text for generation in hit)
return self.client.verify(user_question(prompt), answer).approved
result = self.client.verify(user_question(prompt), answer)
if result.cold_start:
serve = self.cold_start == "serve"
self._cold_start_notice.seen(
result,
"serving the wrapped cache's hits unchanged until a model is ready "
"(cold_start='reject' falls through to your model instead)"
if serve
else "every hit falls through to your model until one is ready (cold_start='reject')",
)
return serve
return result.approved

def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None:
hit = self.cache.lookup(prompt, llm_string)
Expand Down
8 changes: 7 additions & 1 deletion examples/gptcache_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from gptcache.adapter.api import get, put
from gptcache.embedding import Onnx
from gptcache.manager import CacheBase, VectorBase, get_data_manager
from gptcache.similarity_evaluation import SearchDistanceEvaluation

from cacheverifier.integrations.gptcache import CacheVerifierEvaluation

Expand All @@ -23,7 +24,12 @@
VectorBase("faiss", dimension=embedding.dimension),
)

evaluator = CacheVerifierEvaluation(api_key=os.environ["CACHEVERIFIER_API_KEY"])
# fallback: the evaluator this replaces. It keeps deciding hits while your workspace
# has no model of its own yet (cold start), instead of every hit becoming a miss.
evaluator = CacheVerifierEvaluation(
api_key=os.environ["CACHEVERIFIER_API_KEY"],
fallback=SearchDistanceEvaluation(),
)

cache.init(
embedding_func=embedding.to_embeddings,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "cacheverifier"
version = "0.7.1"
version = "0.8.0"
description = "Python client for the CacheVerifier semantic-cache verification API, hosted or scored locally"
readme = "README.md"
requires-python = ">=3.9"
Expand Down
Loading
Loading