Sub topic 6
Pinning the system prompt and important messages
Truncation drops the oldest messages first. Some messages must never be dropped. This chapter covers how to protect them and what protecting them costs.
This chapter assumes you can read Python and know the system, user and assistant roles. It also assumes you have read the earlier chapters on token estimates and the input budget. It reuses the estimate_tokens heuristic (about 4 characters per token plus 4 tokens of overhead per message).
Why a plain sliding window is not enough
A sliding window keeps the newest messages that fit. That rule treats every message as equally disposable, but messages differ in value:
- The system prompt defines the assistant's role, tone, and rules. If it falls out of the window, the assistant forgets who it is.
- Early user messages sometimes hold facts the whole conversation depends on, such as an order number, a deadline, or a constraint like "never suggest paid tools".
- The newest messages usually matter most for the next reply, but they are not the only ones that matter.
Pinning means marking content as exempt from truncation. Pinned content is always sent, and the sliding window applies only to what is left over.
Pin the system prompt first
Most chat APIs accept the system prompt in a separate field or as the first message with role system. Either way, the code in the earlier chapter already pins it: it splits system messages out, subtracts their cost from the budget, and truncates only the rest.
Two details are easy to get wrong.
- Subtract the system prompt before filling the window. If you fill the window first and add the system prompt afterward, the request can exceed the limit.
- Keep it first and keep it stable. Put the system prompt at the start of every request and avoid editing it between turns. Some providers cache a repeated prompt prefix, and a changed prefix defeats the cache. Models also treat leading instructions as more authoritative than text buried in the middle.
The system prompt's cost is fixed overhead on every request. A 2,000-token system prompt in a 8,000-token input budget leaves 6,000 tokens for conversation. Long prompts shrink the window directly, so measure yours.
Pinning individual messages
You can extend the idea to ordinary messages. The simplest design is a flag on the message dictionary:
{"role": "user", "content": "My order number is 48213.", "pinned": True}Decide who sets the flag. Three approaches are common:
| Approach | How it works | Trade-off |
|---|---|---|
| Application rule | Code pins messages that match a rule, such as the first user message or any message containing an order number | Predictable, but misses facts you did not anticipate |
| User action | The user clicks a "remember this" control | Accurate, but needs interface work and user effort |
| Model decision | A model call labels messages as important | Flexible, but adds cost and can mislabel |
Start with application rules. They are easy to test, and a later chapter covers testing that important facts survive compaction.
A truncation function with pins
The function below pins every system message and every message with "pinned": True. It spends the budget on pinned content first, then fills the remainder with the newest unpinned messages. It raises an error if the pinned content alone does not fit.
def estimate_tokens(message):
# About 4 characters per token, plus a small per-message overhead.
return len(message["content"]) // 4 + 4
def truncate_with_pins(messages, max_input_tokens):
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
pinned = {i for i, m in enumerate(rest) if m.get("pinned")}
fixed_cost = sum(estimate_tokens(m) for m in system)
fixed_cost += sum(estimate_tokens(rest[i]) for i in pinned)
if fixed_cost > max_input_tokens:
raise ValueError(
f"Pinned content needs {fixed_cost} tokens, "
f"but the budget is {max_input_tokens}."
)
budget = max_input_tokens - fixed_cost
keep = set(pinned)
for i in range(len(rest) - 1, -1, -1):
if i in pinned:
continue
cost = estimate_tokens(rest[i])
if cost > budget:
break
keep.add(i)
budget -= cost
kept = [rest[i] for i in sorted(keep)]
# Do not start with an orphaned assistant reply, unless it is pinned.
while kept and kept[0]["role"] != "user" and not kept[0].get("pinned"):
kept.pop(0)
# Remove the private "pinned" flag before sending to the API.
return [{"role": m["role"], "content": m["content"]} for m in system + kept]The last line matters. Chat APIs often reject unknown fields, so the pinned flag stays inside your application and is stripped from the outgoing request.
Running it
Each fake message below is padded to 36 characters, so every message costs exactly 13 tokens (36 // 4 + 4). The budget is 65 tokens: 13 for the system message, 13 for the pinned message, and 39 for three more.
def msg(role, label, pinned=False):
m = {"role": role, "content": label.ljust(36, ".")}
if pinned:
m["pinned"] = True
return m
history = [
msg("system", "S"),
msg("user", "u0", pinned=True),
msg("assistant", "a0"),
msg("user", "u1"),
msg("assistant", "a1"),
msg("user", "u2"),
msg("assistant", "a2"),
msg("user", "u3"),
]
result = truncate_with_pins(history, 65)
print([m["content"].rstrip(".") for m in result])Output:
['S', 'u0', 'u2', 'a2', 'u3']The window kept the three newest unpinned messages (u2, a2, u3). The pinned u0 survived even though it is the oldest, and a0, u1, and a1 were dropped.
What the request looks like
The assembled request has three zones, always in this order.
The recent window is the only zone that shrinks. If it shrinks to nothing and the request still does not fit, the pinned content is too large, which is the failure the function reports with ValueError.
Edge cases and failure modes
Pinned content crowds out the window
Every pin permanently reduces the space for recent messages. If pins use 70% of the budget, the model sees little of the current exchange and replies lose coherence. Set a pin budget, such as a maximum of 25% of the input budget, and refuse or evict pins beyond it.
Pins accumulate
An automatic rule that pins on every match will eventually pin most of the conversation. Give pins a lifetime. Options include a maximum count, evicting the oldest pin when a new one arrives, or letting the user unpin.
Pinned messages create gaps
In the example above, the model sees u0 and then jumps to u2. The assistant replies to those messages are gone, so the transcript has a hole. Models usually cope, but a pinned user message without its answer can look unresolved, and the model may try to answer it again. Two mitigations help:
- Pin the whole exchange (the user message and the assistant reply) together.
- Instead of pinning raw messages, copy the fact into a short note in a system message, such as "The user's order number is 48213." This is shorter and has no gap. The summary chapters build on this idea.
Orphaned pins
If you pin an assistant message that contains a tool call, you must also keep the matching tool result, and the reverse. Most APIs reject a tool result with no matching call. The next chapter covers keeping these pairs intact. Until then, avoid pinning tool messages individually.
Pins that conflict
A pinned message from the start of the conversation can contradict a later one, for example "use metric units" followed by "actually, use miles". Both stay in the prompt. The model usually follows the later message, but the stale pin wastes tokens and can confuse it. Provide a way to remove or replace a pin when the user changes their mind.
Ordering
Keep pinned messages in their original relative order, which the function does by sorting indices. Reordering them, for example by moving all pins to the top, changes the meaning of any pin that refers to "the above".
Pinning checklist
- Count the system prompt in the budget before anything else.
- Cap the total pinned size and decide what happens at the cap.
- Pin whole exchanges, or write facts as a short system note.
- Strip private flags such as
pinnedbefore the API call. - Never split tool call pairs.
- Log the token count of each zone (system, pinned, window) so you can see which one is growing.
Exercise
A request has a 6,000-token input budget. The system prompt costs 1,500 tokens and pinned messages cost 3,000 tokens. How many tokens remain for the recent window? What should the application do if the system prompt grows to 3,500 tokens?
Show answer
6,000 - 1,500 - 3,000 = 1,500 tokens remain for the recent window. If the system prompt grows to 3,500 tokens, the fixed cost is 6,500 tokens, which exceeds the budget, so no window fits. The application should not send the request as is. It should fail with a clear error (as truncate_with_pins does), or shrink the pins by evicting the oldest or converting them to a short note.
Exercise
Why does truncate_with_pins remove the pinned key from each message before returning, and why does it skip the orphan check for pinned messages?
Show answer
Chat APIs often reject fields they do not recognize, so the private flag must not leave the application. The orphan check drops a leading non-user message to avoid starting on a stray assistant reply, but a pinned message was chosen deliberately, so dropping it would break the promise that pinned content is always sent.