Lesson 3 of 5 · 2 min
Cost per answer
Prices are listed per token, but you care about the cost of one useful answer. Count input and output separately, and remember that a reused prompt prefix can often be cached at a much lower price.
PRICE_IN, PRICE_OUT, CACHED = 3.0, 15.0, 0.3 # example prices per million tokens
def cost(prefix, fresh, out, cached=False):
rate = CACHED if cached else PRICE_IN
return (prefix * rate + fresh * PRICE_IN + out * PRICE_OUT) / 1_000_000
plain = cost(20_000, 500, 400)
reused = cost(20_000, 500, 400, cached=True)
print(f"without caching ${plain:.4f} with caching ${reused:.4f} saving {1 - reused / plain:.0%}")
