DEV Community

Riley Zhang
Riley Zhang

Posted on

Your Context Trimmer Silently Drops the Rules: A One-Evening Fix

A conversation can grow until an application trims its oldest messages. If the output-format instruction lives in the same list as ordinary dialogue, the next request can retain the question and lose the rule the caller expects it to follow.

Make the request assembler accept two inputs. The first contains the trusted instructions the application promises to preserve. The second contains optional history. Keep the original roles and order; concatenating user text into an instruction block while shortening a request changes its meaning. Treat a tool call and the result messages required by the provider as a unit.

Budget the request the provider will see

Start with the model’s documented context limit and reserve space for output according to that API. Include tool definitions, message framing and any other fields that consume context. Counting the words in a prompt, or summing token counts for each message in isolation, does not guarantee that the fully assembled request fits. When the provider offers an applicable counting endpoint, use the whole serialized logical request. With an estimate, leave a margin and still handle a size rejection.

Preserve the pinned instructions or return an explicit assembly error. Then add recent complete history units within the available input budget. Decide whether the policy promises a contiguous recent suffix. If it does, stop when the next oldest unit does not fit, even if an earlier, smaller one could fit. Record which unit IDs were excluded in metadata that does not expose message text.

Try three fixtures. In the first there is room only for the pinned block and the current question. In the second, the latest optional tool exchange exceeds the remaining budget. In the third, the fixed content itself cannot fit. Inspect the outgoing request and the recorded omissions, not just the model’s answer. A model can coincidentally return valid JSON after the instruction was lost. Preserving the instruction is an assembly property; validating the returned JSON is a separate check.

Test the assembled request before inference

Give a fake transport three ordered history units with distinguishable IDs and make the newest optional tool exchange too large. Under the contiguous-suffix policy, verify that both halves of that exchange remain absent and the assembler records its omission. Separately, make the mandatory instructions plus the current request too large. Expect an assembly error and zero transport calls. Check the actual request envelope for the fitting case.

This article was created with AI assistance.

Top comments (0)