ChatGPT API Conversation History Token Cost Explained
ChatGPT API conversation history token cost is real: the API is stateless, so every request bills all tokens in the messages array as input, plus the reply as output. Only sending fewer tokens lowers the bill.
- Every call bills the full messages array (system, user and assistant turns) as input tokens, so old messages are paid for again on each turn.
- Cumulative input tokens grow roughly quadratically with turn count, while the reply cost grows linearly.
- The usage object in each response, including prompt_tokens_details.cached_tokens, is the source of truth for billing, not your tiktoken estimate.
- Prompt caching discounts a repeated prefix of 1024+ tokens on supported models, so keep the system prompt and older history byte-stable at the start.
- Stateful options like the Responses API with previous_response_id save you resending text but still bill the whole context as input.
Does the API charge again for previous messages?
Yes. The Chat Completions API keeps no memory between calls. The model only sees what is in the messages array of the current request, so to continue a conversation you resend the system prompt, every earlier user message and every earlier assistant reply.
All of those tokens are counted as input (prompt) tokens on every call. The text the model generates is counted as output (completion) tokens. Nothing you sent last turn is waived this turn, except for a prompt caching discount described below.
This is why a chat that feels cheap at turn 3 can feel expensive at turn 30: the new message is small, but the history riding along with it keeps growing.
How fast does cost grow as a conversation gets longer?
Take a system prompt plus first question of 100 tokens, a 150 token reply, and an 80 token follow-up each turn. Turn 2 sends 100 + 150 + 80 = 330 input tokens, turn 3 sends 560, and so on, adding 230 tokens per turn.
Input per turn grows linearly, so the running total grows roughly with the square of the number of turns. Output grows only linearly.
| Turn | Input tokens this call | Output tokens | Cumulative input | Cumulative output |
|---|---|---|---|---|
| 1 | 100 | 150 | 100 | 150 |
| 2 | 330 | 150 | 430 | 300 |
| 3 | 560 | 150 | 990 | 450 |
| 4 | 790 | 150 | 1,780 | 600 |
| 5 | 1,020 | 150 | 2,800 | 750 |
| 6 | 1,250 | 150 | 4,050 | 900 |
| 7 | 1,480 | 150 | 5,530 | 1,050 |
| 8 | 1,710 | 150 | 7,240 | 1,200 |
| 9 | 1,940 | 150 | 9,180 | 1,350 |
| 10 | 2,170 | 150 | 11,350 | 1,500 |
How do I calculate ChatGPT API conversation history token cost?
Input and output are priced separately, per million tokens, and output is priced higher than input. Look up the current rates for your model on the official OpenAI pricing page rather than copying numbers from old tutorials. The gpt-3.5-turbo prices that appear in many posts are legacy.
The formula for one call is: cost = (input_tokens x input_price + output_tokens x output_price) / 1,000,000. For a conversation, sum it over every call.
Worked example with purely illustrative prices of $2 per million input and $8 per million output: the 10 turn chat above costs 11,350 x 2 / 1M = $0.0227 for input plus 1,500 x 8 / 1M = $0.012 for output, about $0.035 in total. Input is already the larger share, and it gets worse the longer chats run.
For a monthly estimate: monthly cost = conversations per month x [(avg input tokens per call x calls per conversation x input price) + (avg output tokens x calls x output price)]. Use the cumulative input column from a real conversation, not the first turn size, as your average.
How do I see what I was actually billed?
Read the usage object on every response. It is the source of truth for billing. It reports prompt_tokens, completion_tokens and total_tokens, plus detail objects such as prompt_tokens_details.cached_tokens and, on reasoning models, completion_tokens_details.reasoning_tokens.
Reasoning tokens are generated and billed as output even though you never see them in the reply, so a short visible answer can still carry a large completion count. Field names differ slightly in the Responses API (input_tokens, output_tokens, input_tokens_details), so check which API you call.
The snippet below logs usage per call and trims history to a token budget before sending. It estimates with tiktoken, which uses roughly 3 extra tokens per message for role and formatting plus about 3 to prime the reply. Treat that as an estimate: results differ slightly from usage, especially with tools or images.
The trim function always keeps the newest message. It drops the oldest turns first, but never the last one. If that single message still exceeds the budget, it raises an error instead of silently sending only the system prompt. Catch that error and ask the user to shorten the text, or truncate it before calling chat().
import tiktoken
from openai import OpenAI
client = OpenAI()
MODEL = "gpt-4o-mini" # use your model
try:
enc = tiktoken.encoding_for_model(MODEL)
except KeyError:
enc = tiktoken.get_encoding("o200k_base")
def count(messages):
n = 3 # reply priming
for m in messages:
n += 3 + len(enc.encode(m["content"]))
return n
def trim(messages, budget=3000):
system, rest = messages[0], messages[1:]
# drop oldest turns first, but always keep the newest message
while len(rest) > 1 and count([system] + rest) > budget:
rest.pop(0)
if count([system] + rest) > budget:
# the latest message alone is too large: never send it silently dropped
raise ValueError(
"Latest message plus system prompt exceeds the token budget; "
"shorten or truncate the user's text.")
return [system] + rest
total_in = total_out = 0
def chat(history, user_text):
global total_in, total_out
msg = {"role": "user", "content": user_text}
sent = trim(history + [msg]) # may raise before history is changed
history.append(msg)
r = client.chat.completions.create(
model=MODEL, messages=sent, max_tokens=400)
u = r.usage
cached = u.prompt_tokens_details.cached_tokens if u.prompt_tokens_details else 0
total_in += u.prompt_tokens
total_out += u.completion_tokens
print(f"est={count(sent)} in={u.prompt_tokens} cached={cached} out={u.completion_tokens}")
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return replyDoes prompt caching reduce the cost of repeated history?
On newer models, caching is automatic. When a request starts with a prefix of at least 1024 tokens that was recently seen, the matching part of the prompt is billed at a discounted cached-input rate. You see the savings in cached_tokens. Older legacy models do not get this discount, and no code changes are needed to enable it.
Caching matches the exact prefix, so order matters. Put the system prompt, fixed instructions and older history first, and put changing content last. Anything that changes early, such as a timestamp in the system prompt or a re-summarised history, breaks the match for everything after it.
Caching lowers the price of resent tokens but does not remove them. They still count against the context window, and the cache is short lived, so a user who pauses for a while may miss it.
What is the best way to cut token usage in a chatbot?
Each technique trades some fidelity for fewer input tokens. Combine them: a short system prompt, a window or summary for history, and a max_tokens cap.
Also cap reply length. Long assistant replies are resent on every later turn, so a verbose answer costs once as output and then again on every following call as input. Asking for concise answers or setting max_tokens pays off twice.
| Approach | How it works | Saves | Downside |
|---|---|---|---|
| Sliding window | Send the system prompt plus the last N messages or a token budget | Large, predictable cap on input per call | Model forgets older facts entirely |
| Summarise older turns | Replace old turns with a short summary message, refresh every few turns | Large on long chats | Extra summarisation call, lossy, can break cache prefix when rewritten |
| Prompt caching | Keep a stable prefix of 1024+ tokens first | Discount on repeated prefix, no quality loss | Needs supported model, only helps with identical prefix |
| Retrieval or memory (RAG) | Store past facts or messages as embeddings, fetch only relevant ones | Keeps input small regardless of chat length | More infrastructure, retrieval can miss things |
| Cheaper model | Use a smaller model for simple turns, route hard ones up | Lower price per token | Lower quality on hard tasks |
What about the Responses API, context limits and spend limits?
The Responses API can hold state for you through previous_response_id or Conversations, so you stop resending the messages yourself. That is a convenience, not a discount: the stored context is still fed to the model and billed as input tokens on every call. Caching and trimming still apply to your cost.
Every model has a context window, and history plus the reply must fit inside it. If not, the request fails with a context_length_exceeded error ("maximum context length exceeded"). Fix it by trimming or summarising before sending and by leaving headroom for max_tokens, rather than catching the error afterwards.
Common mistakes cause most surprise bills:
- Assuming only the latest message is billed, when the entire array is.
- Forgetting the system prompt and any tool definitions are resent and billed on every call.
- Ignoring hidden reasoning tokens on reasoning models, which count as output.
- Never setting a limit. Configure a monthly budget and usage alerts in the billing and limits settings of the OpenAI dashboard, and review the usage page by model and key.
- Using one API key for everything, which makes it hard to find the app that is spending.
Common questions
Is the ChatGPT website subscription billed the same way as the API?
No. A ChatGPT subscription is a flat monthly fee, while the API is pay as you go per token. A chat in the ChatGPT app has no effect on your API bill, and API usage does not count toward a subscription.
Why is my tiktoken count different from prompt_tokens?
The library counts raw text, while the API adds tokens for message roles, formatting, tool definitions and sometimes images. Differences of a few tokens per message are normal. Use tiktoken for budgeting and the usage object for the real figure.
Does a failed or truncated request still cost tokens?
A request rejected before processing, such as a context length error, is generally not billed for output. A reply cut off by max_tokens is billed for what was generated, and you pay for the full input either way.
How many messages should I keep in a sliding window?
Use a token budget rather than a message count, since message sizes vary widely. Pick a budget such as 2,000 to 4,000 tokens for history, keep the system prompt fixed, and raise it only if users report the bot forgetting needed context.
Do embeddings or vector memory remove the history cost?
They reduce it, because only the few retrieved snippets are added to the prompt instead of the entire past conversation. You still pay input tokens for those snippets and a small fee for the embedding calls.