Long Context Done Right: What to Send and What to Cut
Practical rules for long LLM contexts: what belongs in the prompt, trimming chat history, summarising old turns, and what big contexts cost in plan tokens.
Many models now accept very long inputs. On FreeModel, gpt-6-luna, claude-sonnet-5 and claude-opus-5-5 list a 1M-token context, and gpt-6.1-sol lists 500K. It is tempting to treat that window as free space and send everything.
A context window is a limit, not a budget. This post is a checklist for deciding what goes in, plus code for the two techniques that matter most: trimming history and summarising old turns.
What a big context really costs
The chat API is stateless. Every request carries everything the model should know, so a fixed block of context is paid again on every turn, and input and output tokens both count toward your plan.
Take a coding assistant that sends 50,000 tokens of project files with each message, on claude-sonnet-5 (a 3× model):
| Turns | Fixed context sent | Plan tokens (× 3) |
|---|---|---|
| 1 | 50,000 | 150,000 |
| 10 | 500,000 | 1,500,000 |
| 20 | 1,000,000 | 3,000,000 |
That is before the growing history and the answers themselves. Twenty turns use 10% of a Starter plan's 30M tokens on the file block alone. Cut the block to 10,000 relevant tokens and the same session uses a fifth of that.
The checklist
1. Instructions first, question last
Put the stable parts — system prompt, reference material — at the start, and the user's actual question at the end. Models tend to follow the most recent instruction best, and a stable prefix is also what provider-side prompt caching works with (see prompt caching and token costs).
2. Send excerpts, not whole files
The function being changed and its callers, not the whole repository. A table's schema, not its contents.
3. Keep recent turns verbatim
The last few exchanges carry the live details — variable names, the error just pasted. Keep them word for word.
4. Summarise older turns
Decisions and facts from an hour ago fit in a paragraph. Replace them with a summary (code below).
5. Truncate tool results
A 3,000-line log rarely needs to be resent in full. Keep the first and last lines and any matched errors.
6. Drop attachments once used
An image or PDF the model has already described can be replaced by that description in later turns.
7. Retrieve instead of stuffing
For large document sets, search first and send only the matching passages — retrieval keeps each request small even when the source material is huge.
8. Set max_tokens on purpose
Output counts too. Give reasoning models room to think, and keep short-answer calls tight.
Trimming history to a budget
This keeps the system message and as many of the newest messages as fit into a token budget. It uses the same rough estimate as FreeModel's own pre-checks (characters ÷ 3.8), which is fine for budgeting.
import json
def approx_tokens(m):
c = m.get("content") or ""
c = c if isinstance(c, str) else json.dumps(c)
return int(len(c) / 3.8) + 4
def trim_history(messages, budget=24_000):
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
used = sum(approx_tokens(m) for m in system)
kept = []
for m in reversed(rest): # newest first
cost = approx_tokens(m)
if used + cost > budget:
break
kept.append(m)
used += cost
kept.reverse()
while kept and kept[0]["role"] == "tool": # never start with an orphaned tool result
kept.pop(0)
return system + kept
Dropping a tool result whose matching assistant tool_calls message was cut would make the request invalid, which is what the last loop prevents.
Summarising older turns
Trimming forgets. Summarising keeps the gist. Run it when the history passes a threshold, using a cheap model — here the free gpt-6-luna:
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["FREEMODEL_API_KEY"],
base_url="https://freemodel.in/v1")
def compact(messages, keep_last=6):
"""messages[0] is the system message."""
system, rest = messages[:1], messages[1:]
if len(rest) <= keep_last:
return messages
old, recent = rest[:-keep_last], rest[-keep_last:]
transcript = "\n".join(f"{m['role']}: {m['content']}"
for m in old if isinstance(m.get("content"), str))
r = client.chat.completions.create(
model="gpt-6-luna",
messages=[
{"role": "system", "content": "Summarise this conversation in under 200 "
"words. Keep decisions, names, numbers and open questions."},
{"role": "user", "content": transcript},
],
max_tokens=2048,
)
summary = r.choices[0].message.content
while recent and recent[0]["role"] == "tool":
recent.pop(0)
return system + [{"role": "user",
"content": f"Summary of the earlier conversation:\n{summary}"}] + recent
The summary call costs tokens once. Every later turn saves the difference between the old history and the summary — usually far more.
Limits to know on FreeModel
- On the free plan, one request can carry about 128,000 tokens; larger requests get
413 context_length_exceeded. The free plan has no daily cap; a free account is limited to 400K tokens per minute. - A prompt larger than your remaining plan tokens (after the multiplier) is rejected with
402 prompt_exceeds_quotabefore the model runs, and nothing is charged. - Context sizes are listed per model on the models page where the vendor has published them.
Quality, not just cost
More context is not automatically better context. Models can overlook a detail buried in the middle of a very long prompt, and unrelated material gives them more to be distracted by. A focused 10,000-token prompt often beats a 200,000-token dump on accuracy as well as cost. Test both on your own task before deciding.
FAQ
If a model has a 1M context window, should I use it?
Only when the task needs it. Every token you send counts on every request, and focused context usually gives better answers than a full window.
How large can a single request be on the free plan?
About 128,000 tokens per request. Larger requests get a 413 context_length_exceeded error. The free plan has no daily cap; a free account is limited to 400K tokens per minute.
Is summarising old turns worth the extra request?
Usually yes. One summary call on a cheap model replaces many thousands of tokens that would otherwise be resent on every later turn.
Does the API remember earlier messages?
No. The chat API is stateless. Whatever the model should know must be in the request, which is why history size drives cost.
Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.