Skip to chapter content
navan✳THE BUILD LABAI ENGINEERING / GUIDE
0/21 read
COOKBOOK 07 / 8

Measure cost and cache with context.

Estimate request cost and construct a cache key that includes prompt, document, and permission versions.

BY NAVAN SAMICOMPLETE EXAMPLEPYTHON 3
01 / THE PURPOSE

Why this workflow exists.

AI costs can grow through long prompts, repeated calls, and retries. A useful cost report distinguishes input and output quantities. Caching can avoid repeat work, but only when the answer's evidence and access rules are unchanged. A careless cache can serve stale or private answers to the wrong person.

This recipe uses a versioned key containing the user, task, prompt version, and corpus version. It does not claim that those fields are sufficient for every product; they illustrate the dimensions a cache designer must inspect.

Code context. Python 3 standard library only. Prices and token counts are fictional example inputs.

02 / COMPLETE PYTHON

The whole example.

cost-and-cache.py
import hashlib
import json


def estimated_cost(input_tokens, output_tokens, input_per_million, output_per_million):
    return (input_tokens * input_per_million + output_tokens * output_per_million) / 1_000_000


def cache_key(user_id, question, prompt_version, corpus_version):
    payload = [user_id, question, prompt_version, corpus_version]
    encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()

print(round(estimated_cost(1200, 300, 0.5, 2.0), 6))
print(cache_key("user-7", "How do I reset access?", "prompt-v3", "docs-v8")[:12])
03 / READ THE FLOW

What each stage does.

The cost function multiplies token counts by fictional prices per million tokens. Input and output rates are separate because real services often price them differently. The cache function serialises four key fields and hashes them into a stable identifier. Changing the prompt or document version changes the key, so an old answer is not silently reused after those changes.

The user ID prevents sharing this cache entry across users. For a real product, permissions may change independently of the user ID, and source document IDs, model version, language, or tenant may also affect the answer. Those factors must be included or the cache disabled for that workflow.

04 / THE RESULT

What the output means.

The script prints an estimated cost and a short prefix of a cache key. The numbers are illustrative and are not current prices for any provider.

05 / THE BOUNDARY

Where the example stops.

A cache key is one safeguard, not a complete privacy policy. Entries need expiry, access checks at read time, deletion behavior, and careful handling of sensitive question text. The cost function excludes infrastructure, retrieval, retries, and human review.

Built with curiosity. By Navan Sami. ↗AI engineering · From model calls to reliable systems.