Download expander/generation_cache.py from mokner99/environmentexpander-20261118: direct link, hf CLI and curl.
- Browser
- Download file 2.55 kB
-
https://huggingface.co/datasets/mokner99/environmentexpander-20261118/resolve/main/expander/generation_cache.py
- Command line
-
hf download hf://datasets/mokner99/environmentexpander-20261118/expander/generation_cache.py
-
curl -L -o generation_cache.py https://huggingface.co/datasets/mokner99/environmentexpander-20261118/resolve/main/expander/generation_cache.py
2.55 kB
| """Explicit, content-addressed replay of validated generation responses.""" | |
| import hashlib | |
| import json | |
| import os | |
| import tempfile | |
| from pathlib import Path | |
| def digest(value): | |
| return hashlib.sha256( | |
| json.dumps(value, sort_keys=True, ensure_ascii=False).encode() | |
| ).hexdigest() | |
| class GenerationCache: | |
| def __init__(self, directory, prompt, schema, backend): | |
| settings = ( | |
| { | |
| key: os.environ.get(key) | |
| for key in ( | |
| "EXPANDER_GATEWAY_BASE_URL", | |
| "EXPANDER_GATEWAY_MODEL", | |
| "EXPANDER_GATEWAY_MAX_TOKENS", | |
| "EXPANDER_GATEWAY_THINKING", | |
| "EXPANDER_GATEWAY_STREAM", | |
| ) | |
| } | |
| if backend == "gateway" | |
| else {} | |
| ) | |
| self.key = digest( | |
| { | |
| "version": 1, | |
| "prompt": prompt, | |
| "schema": schema.model_json_schema(), | |
| "backend": backend, | |
| "settings": settings, | |
| } | |
| ) | |
| self.path = Path(directory) / f"{self.key}.json" | |
| def read(self, schema): | |
| if not self.path.exists(): | |
| return None | |
| entry = json.loads(self.path.read_text()) | |
| if entry["request_sha256"] != self.key or digest(entry["result"]) != entry["result_sha256"]: | |
| raise ValueError("Generation cache integrity check failed") | |
| result = schema.model_validate(entry["result"]) | |
| envelope = entry["envelope"] | |
| # Cache replay consumes no model tokens and must not duplicate recorded billing. | |
| replay = { | |
| **envelope, | |
| "usage": None, | |
| "total_cost_usd": 0, | |
| "modelUsage": {model: {"modelCalls": 0} for model in envelope.get("modelUsage", {})}, | |
| } | |
| return result, replay | |
| def write(self, result, envelope): | |
| self.path.parent.mkdir(parents=True, exist_ok=True) | |
| payload = result.model_dump(by_alias=True) | |
| entry = { | |
| "request_sha256": self.key, | |
| "result": payload, | |
| "result_sha256": digest(payload), | |
| "envelope": envelope, | |
| } | |
| # A unique temporary file also handles separate workers sharing one cache. | |
| with tempfile.NamedTemporaryFile(mode="w", dir=self.path.parent, delete=False) as stream: | |
| temporary = Path(stream.name) | |
| json.dump(entry, stream, ensure_ascii=False) | |
| stream.write("\n") | |
| temporary.replace(self.path) | |