Sub topic 1
How Tokens Turn into Cost
Prerequisites
Assume you know basic Python, JSON, HTTP APIs, prompts, and common LLM settings such as temperature.
How tokens turn into cost
A token is a small piece of text that a model reads or generates. Pricing usually separates input tokens from output tokens:
\[ \text{cost} = \frac{\text{input tokens} \times \text{input price} + \text{output tokens} \times \text{output price}}{1{,}000{,}000} \]
The input includes system instructions, conversation history, and retrieved documents. Output tokens are the generated answer. A long prompt can therefore cost more even when the answer is short.
import tiktoken
PRICE_PER_MTOK = {"input": 1.00, "output": 4.00}
def estimate_cost(prompt: str, expected_output_tokens: int) -> float:
enc = tiktoken.get_encoding("cl100k_base")
input_tokens = len(enc.encode(prompt))
return (
input_tokens * PRICE_PER_MTOK["input"]
+ expected_output_tokens * PRICE_PER_MTOK["output"]
) / 1_000_000
print(estimate_cost("Summarize this paragraph in two sentences.", 120))| Quantity | Meaning |
|---|---|
| Input tokens | Text sent to the model |
| Output tokens | Text generated by the model |
| Price per million tokens | Provider price for one million tokens |
Where latency comes from: queueing, prefill, and decoding
Latency is the time a request takes. Queueing delays occur when your request waits for available capacity. Prefill processes the input prompt. Longer prompts usually increase time to first token (TTFT), the delay before generated text begins.
Decoding generates output one token at a time. Longer answers increase total generation time. Streaming sends tokens as they are decoded, reducing perceived waiting time without necessarily reducing total time.
flowchart TD
A[Request] --> B[Queue]
B --> C[Prefill input]
C --> D[First token]
D --> E[Decode remaining tokens]
E --> F[Complete response]Measure first: build a cost and latency baseline
Record input tokens, output tokens, TTFT, total latency, model, and request status. Measure representative traffic before optimizing. Averages alone hide slow requests, so also inspect percentiles such as p95.
Protect quality with a small evaluation set
A quality evaluation set is a fixed collection of representative inputs with expected properties or reference answers. Run it before and after an optimization. Check factual accuracy, required fields, refusal behavior, and formatting. A cheaper model or shorter prompt is useful only if it still meets the quality threshold.
Exercise
A request uses 2,000 input tokens at $1 per million and 500 output tokens at $4 per million. What is its estimated cost?
Show answer
(2,000 × 1 + 500 × 4) / 1,000,000 = $0.004.