dejahit 0.1.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.
- dejahit-0.1.0/.gitignore +11 -0
- dejahit-0.1.0/PKG-INFO +41 -0
- dejahit-0.1.0/README.md +28 -0
- dejahit-0.1.0/dejahit/__init__.py +9 -0
- dejahit-0.1.0/dejahit/client.py +452 -0
- dejahit-0.1.0/pyproject.toml +27 -0
dejahit-0.1.0/.gitignore
ADDED
dejahit-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: dejahit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Verified semantic cache for LLM apps: wrap your LLM call, repeated questions come from cache.
|
|
5
|
+
Project-URL: Homepage, https://dejahit.com
|
|
6
|
+
Project-URL: Documentation, https://dejahit.com/docs.html
|
|
7
|
+
Author-email: Hodolist <hello@dejahit.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: anthropic,cache,cost,latency,llm,openai,semantic-cache
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Requires-Dist: httpx>=0.25
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# dejahit (Python)
|
|
15
|
+
|
|
16
|
+
Stop paying for the same LLM answer twice. Wrap the call you already make; repeated questions come back from cache in milliseconds, and every reuse is verified before it is served.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install dejahit
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import os
|
|
24
|
+
from dejahit import Cache
|
|
25
|
+
|
|
26
|
+
cache = Cache(api_key=os.environ["DEJAHIT_KEY"])
|
|
27
|
+
|
|
28
|
+
answer = cache.ask(
|
|
29
|
+
question,
|
|
30
|
+
lambda: call_my_llm(question), # runs only on a miss
|
|
31
|
+
scope=["support-bot", "v3"], # who may reuse this answer (required)
|
|
32
|
+
ttl="24h",
|
|
33
|
+
)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
- Your LLM call, key and model stay in your code.
|
|
37
|
+
- Never breaks your app: short lookup budget, circuit breaker, your errors pass through unchanged.
|
|
38
|
+
- `AsyncCache` for asyncio, `ask_stream` for streaming, shadow mode to measure savings before serving from cache.
|
|
39
|
+
- Requires an API key. In tests use `mode="off"` (always calls your function, caches nothing).
|
|
40
|
+
|
|
41
|
+
Get an API key at [dejahit.com](https://dejahit.com) · Docs: [dejahit.com/docs.html](https://dejahit.com/docs.html)
|
dejahit-0.1.0/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# dejahit (Python)
|
|
2
|
+
|
|
3
|
+
Stop paying for the same LLM answer twice. Wrap the call you already make; repeated questions come back from cache in milliseconds, and every reuse is verified before it is served.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install dejahit
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import os
|
|
11
|
+
from dejahit import Cache
|
|
12
|
+
|
|
13
|
+
cache = Cache(api_key=os.environ["DEJAHIT_KEY"])
|
|
14
|
+
|
|
15
|
+
answer = cache.ask(
|
|
16
|
+
question,
|
|
17
|
+
lambda: call_my_llm(question), # runs only on a miss
|
|
18
|
+
scope=["support-bot", "v3"], # who may reuse this answer (required)
|
|
19
|
+
ttl="24h",
|
|
20
|
+
)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- Your LLM call, key and model stay in your code.
|
|
24
|
+
- Never breaks your app: short lookup budget, circuit breaker, your errors pass through unchanged.
|
|
25
|
+
- `AsyncCache` for asyncio, `ask_stream` for streaming, shadow mode to measure savings before serving from cache.
|
|
26
|
+
- Requires an API key. In tests use `mode="off"` (always calls your function, caches nothing).
|
|
27
|
+
|
|
28
|
+
Get an API key at [dejahit.com](https://dejahit.com) · Docs: [dejahit.com/docs.html](https://dejahit.com/docs.html)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Verified semantic cache for LLM apps. Your LLM call stays in your callback; we never see your LLM key.
|
|
2
|
+
|
|
3
|
+
from dejahit import Cache
|
|
4
|
+
cache = Cache(api_key=os.environ["DEJAHIT_KEY"])
|
|
5
|
+
answer = cache.ask(question, lambda: call_my_llm(question), scope=["support-bot", "v3"])
|
|
6
|
+
"""
|
|
7
|
+
from .client import AsyncCache, Cache, AskResult, Breaker, MemoryAdapter, DejahitHTTPError
|
|
8
|
+
|
|
9
|
+
__all__ = ["Cache", "AsyncCache", "AskResult", "Breaker", "MemoryAdapter", "DejahitHTTPError"]
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import inspect
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import random
|
|
8
|
+
import re
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, AsyncIterator, Awaitable, Callable, Iterator, Optional, Protocol, Union
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
DEFAULT_BASE_URL = os.environ.get("DEJAHIT_URL", "https://api.dejahit.com")
|
|
17
|
+
Scope = Union[str, list, dict]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# ------------------------------------------------------------------ helpers
|
|
21
|
+
def ttl_seconds(t) -> Optional[float]:
|
|
22
|
+
if t is None:
|
|
23
|
+
return None
|
|
24
|
+
if isinstance(t, (int, float)):
|
|
25
|
+
if t <= 0:
|
|
26
|
+
raise ValueError("ttl must be positive")
|
|
27
|
+
return float(t)
|
|
28
|
+
m = re.fullmatch(r"(\d+(?:\.\d+)?)([smhd])", str(t))
|
|
29
|
+
if not m:
|
|
30
|
+
raise ValueError(f'invalid ttl "{t}" (use 30s, 15m, 24h, 7d or seconds)')
|
|
31
|
+
return float(m.group(1)) * {"s": 1, "m": 60, "h": 3600, "d": 86400}[m.group(2)]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def canon(v) -> str:
|
|
35
|
+
return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def assert_scope(scope):
|
|
39
|
+
if scope is None or scope == "" or scope == [] or scope == {}:
|
|
40
|
+
raise TypeError('dejahit: `scope` is required (who may reuse this answer, e.g. ["support-bot", "v3"])')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class DejahitHTTPError(Exception):
|
|
44
|
+
def __init__(self, status: int, message: str):
|
|
45
|
+
super().__init__(message)
|
|
46
|
+
self.status = status
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Breaker:
|
|
50
|
+
"""closed -> (threshold consecutive failures) -> open for cooldown -> half-open: one trial call."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, threshold: int = 5, cooldown: float = 30.0, now: Callable[[], float] = time.monotonic):
|
|
53
|
+
self.threshold, self.cooldown, self.now = threshold, cooldown, now
|
|
54
|
+
self.fails, self.opened_at, self.trial = 0, 0.0, False
|
|
55
|
+
self._lock = threading.Lock()
|
|
56
|
+
|
|
57
|
+
def allow(self) -> bool:
|
|
58
|
+
with self._lock:
|
|
59
|
+
if self.fails < self.threshold:
|
|
60
|
+
return True
|
|
61
|
+
if self.now() - self.opened_at < self.cooldown or self.trial:
|
|
62
|
+
return False
|
|
63
|
+
self.trial = True
|
|
64
|
+
return True
|
|
65
|
+
|
|
66
|
+
def success(self):
|
|
67
|
+
with self._lock:
|
|
68
|
+
self.fails, self.trial = 0, False
|
|
69
|
+
|
|
70
|
+
def failure(self):
|
|
71
|
+
with self._lock:
|
|
72
|
+
self.fails += 1
|
|
73
|
+
self.trial = False
|
|
74
|
+
if self.fails >= self.threshold:
|
|
75
|
+
self.opened_at = self.now()
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def state(self) -> str:
|
|
79
|
+
if self.fails < self.threshold:
|
|
80
|
+
return "closed"
|
|
81
|
+
return "open" if self.now() - self.opened_at < self.cooldown else "half-open"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Adapter(Protocol):
|
|
85
|
+
def get(self, id: str) -> Optional[str]: ...
|
|
86
|
+
def set(self, id: str, answer: str, ttl_sec: Optional[float] = None) -> None: ...
|
|
87
|
+
def delete(self, id: str) -> None: ...
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class MemoryAdapter:
|
|
91
|
+
"""In-process adapter for store="prompt" (answers never leave your process)."""
|
|
92
|
+
|
|
93
|
+
def __init__(self):
|
|
94
|
+
self._d: dict = {}
|
|
95
|
+
|
|
96
|
+
def get(self, id):
|
|
97
|
+
v = self._d.get(id)
|
|
98
|
+
if not v:
|
|
99
|
+
return None
|
|
100
|
+
if v[1] and v[1] < time.time():
|
|
101
|
+
self._d.pop(id, None)
|
|
102
|
+
return None
|
|
103
|
+
return v[0]
|
|
104
|
+
|
|
105
|
+
def set(self, id, answer, ttl_sec=None):
|
|
106
|
+
self._d[id] = (answer, time.time() + ttl_sec if ttl_sec else 0)
|
|
107
|
+
|
|
108
|
+
def delete(self, id):
|
|
109
|
+
self._d.pop(id, None)
|
|
110
|
+
|
|
111
|
+
def __len__(self):
|
|
112
|
+
return len(self._d)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class AskResult:
|
|
117
|
+
answer: str
|
|
118
|
+
cached: bool
|
|
119
|
+
source: str # exact | verified | miss | bypass
|
|
120
|
+
score: Optional[float]
|
|
121
|
+
id: Optional[str]
|
|
122
|
+
reason: str
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _is_usage_error(e: Exception) -> bool:
|
|
126
|
+
return isinstance(e, DejahitHTTPError) and 400 <= e.status < 500 and e.status not in (402, 408, 429)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class _Base:
|
|
130
|
+
def __init__(self, api_key=None, base_url=None, timeout=0.8, mode="on", audit_rate=0.02, adapter=None,
|
|
131
|
+
strictness=None, breaker_threshold=5, breaker_cooldown=30.0, on_error=None):
|
|
132
|
+
self.api_key = api_key or os.environ.get("DEJAHIT_KEY")
|
|
133
|
+
if not self.api_key and mode != "off":
|
|
134
|
+
raise TypeError("dejahit: api_key missing (or DEJAHIT_KEY), or use mode='off'")
|
|
135
|
+
self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
136
|
+
self.timeout, self.mode, self.audit_rate, self.adapter, self.strictness = timeout, mode, audit_rate, adapter, strictness
|
|
137
|
+
self.breaker = Breaker(breaker_threshold, breaker_cooldown)
|
|
138
|
+
self.on_error = on_error or (lambda e, where: None)
|
|
139
|
+
self._headers = {"authorization": f"Bearer {self.api_key or ''}"}
|
|
140
|
+
|
|
141
|
+
def _prep(self, input, scope, key, store, mode, strictness):
|
|
142
|
+
assert_scope(scope)
|
|
143
|
+
text = key(input) if key else input
|
|
144
|
+
if not isinstance(text, str):
|
|
145
|
+
raise TypeError("dejahit: input must be a string, or pass key= to turn it into one")
|
|
146
|
+
if store == "prompt" and self.adapter is None:
|
|
147
|
+
raise TypeError('dejahit: store="prompt" needs an adapter=')
|
|
148
|
+
return text, (mode or self.mode), (strictness or self.strictness)
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def _raise(r: httpx.Response):
|
|
152
|
+
if r.status_code >= 400:
|
|
153
|
+
try:
|
|
154
|
+
msg = r.json().get("error", r.text)
|
|
155
|
+
except Exception:
|
|
156
|
+
msg = r.text
|
|
157
|
+
raise DejahitHTTPError(r.status_code, f"dejahit {r.status_code}: {msg}")
|
|
158
|
+
return r.json()
|
|
159
|
+
|
|
160
|
+
def _note_failure(self, e, where):
|
|
161
|
+
if not _is_usage_error(e):
|
|
162
|
+
self.breaker.failure()
|
|
163
|
+
self.on_error(e, where)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# ------------------------------------------------------------------ sync
|
|
167
|
+
class Cache(_Base):
|
|
168
|
+
def __init__(self, *a, http: Optional[httpx.Client] = None, **kw):
|
|
169
|
+
super().__init__(*a, **kw)
|
|
170
|
+
self._http = http or httpx.Client(base_url=self.base_url, headers=self._headers)
|
|
171
|
+
self._inflight: dict = {}
|
|
172
|
+
self._lock = threading.Lock()
|
|
173
|
+
|
|
174
|
+
def _call(self, method, path, body=None, timeout=None):
|
|
175
|
+
return self._raise(self._http.request(method, self.base_url + path, json=_clean(body), headers=self._headers,
|
|
176
|
+
timeout=timeout or self.timeout * 3))
|
|
177
|
+
|
|
178
|
+
def _lookup(self, text, scope, shadow, strictness, cacheable):
|
|
179
|
+
if not self.breaker.allow():
|
|
180
|
+
return None
|
|
181
|
+
try:
|
|
182
|
+
r = self._call("POST", "/v1/lookup", {"scope": scope, "text": text, "strictness": strictness,
|
|
183
|
+
"shadow": shadow, "cacheable": cacheable}, timeout=self.timeout)
|
|
184
|
+
self.breaker.success()
|
|
185
|
+
return r
|
|
186
|
+
except Exception as e: # noqa: BLE001 - never let the cache break the app
|
|
187
|
+
self._note_failure(e, "lookup")
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
def _save(self, ticket, answer, store, ttl, tags, cacheable, should_store):
|
|
191
|
+
if should_store and not should_store(answer):
|
|
192
|
+
return
|
|
193
|
+
if not self.breaker.allow():
|
|
194
|
+
return
|
|
195
|
+
try:
|
|
196
|
+
ttl_s = ttl_seconds(ttl)
|
|
197
|
+
r = self._call("POST", "/v1/store", {"ticket": ticket, "answer": answer if store == "all" else None, "store": store,
|
|
198
|
+
"ttlSec": ttl_s, "tags": tags, "cacheable": cacheable})
|
|
199
|
+
self.breaker.success()
|
|
200
|
+
if r.get("stored") and store == "prompt" and r.get("id"):
|
|
201
|
+
self.adapter.set(r["id"], answer, r.get("expiresInSec") or ttl_s)
|
|
202
|
+
except Exception as e: # noqa: BLE001
|
|
203
|
+
self._note_failure(e, "store")
|
|
204
|
+
|
|
205
|
+
def _resolve(self, r):
|
|
206
|
+
if r.get("answer") is not None:
|
|
207
|
+
return r["answer"]
|
|
208
|
+
if r.get("storeMode") == "prompt" and r.get("id") and self.adapter is not None:
|
|
209
|
+
try:
|
|
210
|
+
a = self.adapter.get(r["id"])
|
|
211
|
+
if a is not None:
|
|
212
|
+
return a
|
|
213
|
+
except Exception as e: # noqa: BLE001
|
|
214
|
+
self.on_error(e, "adapter")
|
|
215
|
+
try:
|
|
216
|
+
self.invalidate(id=r["id"])
|
|
217
|
+
except Exception as e: # noqa: BLE001
|
|
218
|
+
self.on_error(e, "invalidate")
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
def _audit(self, r, on_miss):
|
|
222
|
+
if not self.audit_rate or r.get("answer") is None or random.random() >= self.audit_rate:
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
def run():
|
|
226
|
+
try:
|
|
227
|
+
self._call("POST", "/v1/audit", {"id": r["id"], "fresh": on_miss()})
|
|
228
|
+
except Exception as e: # noqa: BLE001
|
|
229
|
+
self.on_error(e, "audit")
|
|
230
|
+
threading.Thread(target=run, daemon=True).start()
|
|
231
|
+
|
|
232
|
+
def ask_detailed(self, input, on_miss: Callable[[], str], *, scope: Scope, ttl=None, store="all", key=None,
|
|
233
|
+
should_store=None, cacheable=None, strictness=None, tags=None, mode=None) -> AskResult:
|
|
234
|
+
text, mode, strictness = self._prep(input, scope, key, store, mode, strictness)
|
|
235
|
+
if mode == "off":
|
|
236
|
+
return AskResult(on_miss(), False, "bypass", None, None, "mode off")
|
|
237
|
+
dkey = canon([scope, text, store, strictness, mode])
|
|
238
|
+
with self._lock:
|
|
239
|
+
ev = self._inflight.get(dkey)
|
|
240
|
+
leader = ev is None
|
|
241
|
+
if leader:
|
|
242
|
+
ev = self._inflight[dkey] = {"event": threading.Event(), "result": None, "error": None}
|
|
243
|
+
if not leader:
|
|
244
|
+
ev["event"].wait()
|
|
245
|
+
if ev["error"]:
|
|
246
|
+
raise ev["error"]
|
|
247
|
+
return ev["result"]
|
|
248
|
+
try:
|
|
249
|
+
res = self._ask(text, on_miss, scope, ttl, store, should_store, cacheable, strictness, tags, mode)
|
|
250
|
+
ev["result"] = res
|
|
251
|
+
return res
|
|
252
|
+
except BaseException as e:
|
|
253
|
+
ev["error"] = e
|
|
254
|
+
raise
|
|
255
|
+
finally:
|
|
256
|
+
with self._lock:
|
|
257
|
+
self._inflight.pop(dkey, None)
|
|
258
|
+
ev["event"].set()
|
|
259
|
+
|
|
260
|
+
def _ask(self, text, on_miss, scope, ttl, store, should_store, cacheable, strictness, tags, mode):
|
|
261
|
+
r = self._lookup(text, scope, mode == "shadow", strictness, cacheable)
|
|
262
|
+
if r and r.get("hit") and mode == "on":
|
|
263
|
+
a = self._resolve(r)
|
|
264
|
+
if a is not None:
|
|
265
|
+
self._audit(r, on_miss)
|
|
266
|
+
return AskResult(a, True, r["source"], r.get("score"), r.get("id"), r.get("reason", ""))
|
|
267
|
+
answer = on_miss() # callback errors propagate unchanged
|
|
268
|
+
if not isinstance(answer, str):
|
|
269
|
+
raise TypeError("dejahit: on_miss must return a str (use ask_stream for iterators)")
|
|
270
|
+
if r and r.get("ticket"):
|
|
271
|
+
self._save(r["ticket"], answer, store, ttl, tags, cacheable, should_store)
|
|
272
|
+
reason = "cache unavailable: callback used" if not r else (
|
|
273
|
+
f"shadow: {'would hit' if r.get('hit') else 'would miss'}" if mode == "shadow" else r.get("reason", "miss"))
|
|
274
|
+
return AskResult(answer, False, "miss" if r else "bypass", None, None, reason)
|
|
275
|
+
|
|
276
|
+
def ask(self, input, on_miss: Callable[[], str], **opts) -> str:
|
|
277
|
+
return self.ask_detailed(input, on_miss, **opts).answer
|
|
278
|
+
|
|
279
|
+
def ask_stream(self, input, on_miss: Callable[[], Iterator[str]], *, scope: Scope, ttl=None, store="all", key=None,
|
|
280
|
+
should_store=None, cacheable=None, strictness=None, tags=None, mode=None) -> Iterator[str]:
|
|
281
|
+
"""Yields chunks. Misses pass the callback's iterator through and store the full text if it completes."""
|
|
282
|
+
text, mode, strictness = self._prep(input, scope, key, store, mode, strictness)
|
|
283
|
+
r = None if mode == "off" else self._lookup(text, scope, mode == "shadow", strictness, cacheable)
|
|
284
|
+
if r and r.get("hit") and mode == "on":
|
|
285
|
+
a = self._resolve(r)
|
|
286
|
+
if a is not None:
|
|
287
|
+
yield from re.findall(r"\S+\s*|\s+", a) or [a]
|
|
288
|
+
return
|
|
289
|
+
parts = []
|
|
290
|
+
for chunk in on_miss():
|
|
291
|
+
parts.append(chunk)
|
|
292
|
+
yield chunk
|
|
293
|
+
if r and r.get("ticket"):
|
|
294
|
+
self._save(r["ticket"], "".join(parts), store, ttl, tags, cacheable, should_store)
|
|
295
|
+
|
|
296
|
+
def invalidate(self, *, id=None, tag=None, scope=None):
|
|
297
|
+
return self._call("POST", "/v1/invalidate", {k: v for k, v in {"id": id, "tag": tag, "scope": scope}.items() if v is not None})
|
|
298
|
+
|
|
299
|
+
def report(self, id, reason="wrong"):
|
|
300
|
+
self._call("POST", "/v1/report", {"id": id, "reason": reason})
|
|
301
|
+
if self.adapter is not None:
|
|
302
|
+
self.adapter.delete(id)
|
|
303
|
+
|
|
304
|
+
def delete_all(self):
|
|
305
|
+
return self._call("DELETE", "/v1/entries")
|
|
306
|
+
|
|
307
|
+
def stats(self):
|
|
308
|
+
return self._call("GET", "/v1/stats")
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
# ------------------------------------------------------------------ async
|
|
312
|
+
class AsyncCache(_Base):
|
|
313
|
+
def __init__(self, *a, http: Optional[httpx.AsyncClient] = None, **kw):
|
|
314
|
+
super().__init__(*a, **kw)
|
|
315
|
+
self._http = http or httpx.AsyncClient(headers=self._headers)
|
|
316
|
+
self._inflight: dict = {}
|
|
317
|
+
self._bg: set = set()
|
|
318
|
+
|
|
319
|
+
async def _call(self, method, path, body=None, timeout=None):
|
|
320
|
+
r = await self._http.request(method, self.base_url + path, json=_clean(body), headers=self._headers, timeout=timeout or self.timeout * 3)
|
|
321
|
+
return self._raise(r)
|
|
322
|
+
|
|
323
|
+
async def _lookup(self, text, scope, shadow, strictness, cacheable):
|
|
324
|
+
if not self.breaker.allow():
|
|
325
|
+
return None
|
|
326
|
+
try:
|
|
327
|
+
r = await asyncio.wait_for(self._call("POST", "/v1/lookup", {"scope": scope, "text": text, "strictness": strictness,
|
|
328
|
+
"shadow": shadow, "cacheable": cacheable}), self.timeout)
|
|
329
|
+
self.breaker.success()
|
|
330
|
+
return r
|
|
331
|
+
except Exception as e: # noqa: BLE001
|
|
332
|
+
self._note_failure(e, "lookup")
|
|
333
|
+
return None
|
|
334
|
+
|
|
335
|
+
async def _save(self, ticket, answer, store, ttl, tags, cacheable, should_store):
|
|
336
|
+
if should_store and not should_store(answer):
|
|
337
|
+
return
|
|
338
|
+
if not self.breaker.allow():
|
|
339
|
+
return
|
|
340
|
+
try:
|
|
341
|
+
ttl_s = ttl_seconds(ttl)
|
|
342
|
+
r = await self._call("POST", "/v1/store", {"ticket": ticket, "answer": answer if store == "all" else None, "store": store,
|
|
343
|
+
"ttlSec": ttl_s, "tags": tags, "cacheable": cacheable})
|
|
344
|
+
self.breaker.success()
|
|
345
|
+
if r.get("stored") and store == "prompt" and r.get("id"):
|
|
346
|
+
await _maybe_await(self.adapter.set(r["id"], answer, r.get("expiresInSec") or ttl_s))
|
|
347
|
+
except Exception as e: # noqa: BLE001
|
|
348
|
+
self._note_failure(e, "store")
|
|
349
|
+
|
|
350
|
+
async def _resolve(self, r):
|
|
351
|
+
if r.get("answer") is not None:
|
|
352
|
+
return r["answer"]
|
|
353
|
+
if r.get("storeMode") == "prompt" and r.get("id") and self.adapter is not None:
|
|
354
|
+
try:
|
|
355
|
+
a = await _maybe_await(self.adapter.get(r["id"]))
|
|
356
|
+
if a is not None:
|
|
357
|
+
return a
|
|
358
|
+
except Exception as e: # noqa: BLE001
|
|
359
|
+
self.on_error(e, "adapter")
|
|
360
|
+
self._spawn(self.invalidate(id=r["id"]))
|
|
361
|
+
return None
|
|
362
|
+
|
|
363
|
+
def _spawn(self, coro):
|
|
364
|
+
t = asyncio.ensure_future(coro)
|
|
365
|
+
self._bg.add(t)
|
|
366
|
+
t.add_done_callback(lambda x: (self._bg.discard(x), x.exception() and self.on_error(x.exception(), "background")))
|
|
367
|
+
return t
|
|
368
|
+
|
|
369
|
+
async def ask_detailed(self, input, on_miss: Callable[[], Awaitable[str]], *, scope: Scope, ttl=None, store="all", key=None,
|
|
370
|
+
should_store=None, cacheable=None, strictness=None, tags=None, mode=None, speculative=False) -> AskResult:
|
|
371
|
+
text, mode, strictness = self._prep(input, scope, key, store, mode, strictness)
|
|
372
|
+
if mode == "off":
|
|
373
|
+
return AskResult(await _maybe_await(on_miss()), False, "bypass", None, None, "mode off")
|
|
374
|
+
dkey = canon([scope, text, store, strictness, mode])
|
|
375
|
+
if dkey in self._inflight:
|
|
376
|
+
return await asyncio.shield(self._inflight[dkey])
|
|
377
|
+
fut = asyncio.ensure_future(self._ask(text, on_miss, scope, ttl, store, should_store, cacheable, strictness, tags, mode, speculative))
|
|
378
|
+
self._inflight[dkey] = fut
|
|
379
|
+
try:
|
|
380
|
+
return await fut
|
|
381
|
+
finally:
|
|
382
|
+
self._inflight.pop(dkey, None)
|
|
383
|
+
|
|
384
|
+
async def _ask(self, text, on_miss, scope, ttl, store, should_store, cacheable, strictness, tags, mode, speculative):
|
|
385
|
+
spec = asyncio.ensure_future(_maybe_await(on_miss())) if speculative and mode == "on" else None
|
|
386
|
+
r = await self._lookup(text, scope, mode == "shadow", strictness, cacheable)
|
|
387
|
+
if r and r.get("hit") and mode == "on":
|
|
388
|
+
a = await self._resolve(r)
|
|
389
|
+
if a is not None:
|
|
390
|
+
if spec:
|
|
391
|
+
spec.cancel()
|
|
392
|
+
if self.audit_rate and r.get("answer") is not None and random.random() < self.audit_rate:
|
|
393
|
+
async def audit():
|
|
394
|
+
await self._call("POST", "/v1/audit", {"id": r["id"], "fresh": await _maybe_await(on_miss())})
|
|
395
|
+
self._spawn(audit())
|
|
396
|
+
return AskResult(a, True, r["source"], r.get("score"), r.get("id"), r.get("reason", ""))
|
|
397
|
+
answer = await (spec if spec else _maybe_await(on_miss()))
|
|
398
|
+
if not isinstance(answer, str):
|
|
399
|
+
raise TypeError("dejahit: on_miss must return a str (use ask_stream for async iterators)")
|
|
400
|
+
if r and r.get("ticket"):
|
|
401
|
+
await self._save(r["ticket"], answer, store, ttl, tags, cacheable, should_store)
|
|
402
|
+
reason = "cache unavailable: callback used" if not r else (
|
|
403
|
+
f"shadow: {'would hit' if r.get('hit') else 'would miss'}" if mode == "shadow" else r.get("reason", "miss"))
|
|
404
|
+
return AskResult(answer, False, "miss" if r else "bypass", None, None, reason)
|
|
405
|
+
|
|
406
|
+
async def ask(self, input, on_miss, **opts) -> str:
|
|
407
|
+
return (await self.ask_detailed(input, on_miss, **opts)).answer
|
|
408
|
+
|
|
409
|
+
async def ask_stream(self, input, on_miss: Callable[[], AsyncIterator[str]], *, scope: Scope, ttl=None, store="all", key=None,
|
|
410
|
+
should_store=None, cacheable=None, strictness=None, tags=None, mode=None) -> AsyncIterator[str]:
|
|
411
|
+
text, mode, strictness = self._prep(input, scope, key, store, mode, strictness)
|
|
412
|
+
r = None if mode == "off" else await self._lookup(text, scope, mode == "shadow", strictness, cacheable)
|
|
413
|
+
if r and r.get("hit") and mode == "on":
|
|
414
|
+
a = await self._resolve(r)
|
|
415
|
+
if a is not None:
|
|
416
|
+
for p in re.findall(r"\S+\s*|\s+", a) or [a]:
|
|
417
|
+
yield p
|
|
418
|
+
return
|
|
419
|
+
parts = []
|
|
420
|
+
async for chunk in on_miss():
|
|
421
|
+
parts.append(chunk)
|
|
422
|
+
yield chunk
|
|
423
|
+
if r and r.get("ticket"):
|
|
424
|
+
await self._save(r["ticket"], "".join(parts), store, ttl, tags, cacheable, should_store)
|
|
425
|
+
|
|
426
|
+
async def invalidate(self, *, id=None, tag=None, scope=None):
|
|
427
|
+
return await self._call("POST", "/v1/invalidate", {k: v for k, v in {"id": id, "tag": tag, "scope": scope}.items() if v is not None})
|
|
428
|
+
|
|
429
|
+
async def report(self, id, reason="wrong"):
|
|
430
|
+
await self._call("POST", "/v1/report", {"id": id, "reason": reason})
|
|
431
|
+
if self.adapter is not None:
|
|
432
|
+
await _maybe_await(self.adapter.delete(id))
|
|
433
|
+
|
|
434
|
+
async def delete_all(self):
|
|
435
|
+
return await self._call("DELETE", "/v1/entries")
|
|
436
|
+
|
|
437
|
+
async def stats(self):
|
|
438
|
+
return await self._call("GET", "/v1/stats")
|
|
439
|
+
|
|
440
|
+
async def aclose(self):
|
|
441
|
+
await self._http.aclose()
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _clean(body):
|
|
445
|
+
"""Drop unset options (None), but keep answer=None, which means store="prompt"."""
|
|
446
|
+
if not isinstance(body, dict):
|
|
447
|
+
return body
|
|
448
|
+
return {k: v for k, v in body.items() if v is not None or k == "answer"}
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
async def _maybe_await(v):
|
|
452
|
+
return await v if inspect.isawaitable(v) else v
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "dejahit"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Verified semantic cache for LLM apps: wrap your LLM call, repeated questions come from cache."
|
|
5
|
+
requires-python = ">=3.9"
|
|
6
|
+
dependencies = ["httpx>=0.25"]
|
|
7
|
+
license = { text = "MIT" }
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
authors = [{ name = "Hodolist", email = "hello@dejahit.com" }]
|
|
10
|
+
keywords = ["llm", "cache", "semantic-cache", "openai", "anthropic", "cost", "latency"]
|
|
11
|
+
|
|
12
|
+
[project.urls]
|
|
13
|
+
Homepage = "https://dejahit.com"
|
|
14
|
+
Documentation = "https://dejahit.com/docs.html"
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["hatchling"]
|
|
18
|
+
build-backend = "hatchling.build"
|
|
19
|
+
|
|
20
|
+
[dependency-groups]
|
|
21
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.23"]
|
|
22
|
+
|
|
23
|
+
[tool.pytest.ini_options]
|
|
24
|
+
asyncio_mode = "auto"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.sdist]
|
|
27
|
+
include = ["dejahit", "README.md", "pyproject.toml"]
|