File size: 2,548 Bytes
ff376c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""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)