Count the tokens a call used and work out what it cost.
1# part1/tokens_cost.py
2import tiktoken
3from openai import OpenAI
4client = OpenAI()
5
6question = "Explain what a black hole is in 2 sentences."
7
8# Count tokens BEFORE sending. It's only an estimate:
9# the API adds a few tokens for formatting.
10enc = tiktoken.get_encoding("o200k_base")
11estimate = len(enc.encode(question))
12print(f"Estimated input tokens: {estimate}")
13
14# Send the question, just like in Basic API Call
15response = client.chat.completions.create(
16 model="gpt-4o-mini",
17 messages=[
18 {"role": "user", "content": question}
19 ],
20)
21print("Answer:", response.choices[0].message.content)
22
23# The exact counts come back on the receipt
24usage = response.usage
25print("Input tokens:", usage.prompt_tokens)
26print("Output tokens:", usage.completion_tokens)
27print("Total tokens:", usage.total_tokens)
28
29# Example gpt-4o-mini prices, in $ per 1M tokens
30# (prices change: check openai.com/api/pricing)
31IN_PRICE = 0.15 # tokens we send
32OUT_PRICE = 0.60 # tokens it writes
33
34# Cost = tokens ÷ 1,000,000 × price
35in_cost = usage.prompt_tokens / 1_000_000 * IN_PRICE
36out_cost = usage.completion_tokens / 1_000_000 * OUT_PRICE
37cost = in_cost + out_cost
38print(f"This call cost: ${cost:.6f}")
39print(f"1,000 calls like this: ${cost * 1000:.2f}")No output yet...