Skip to content

Interview question · Model API Foundations

Your harness keeps the last ten messages to save tokens, and the provider sometimes returns 400. Debug it.

A debugging question that tests whether you know what a message list has to look like. The strong answer finds the cut through a call-and-result pair, explains why it is intermittent, and replaces slicing with trimming in whole units.

mediumEssentialNewUpdated Nov 2026

TL;DR: Slicing by message count cuts through call-and-result pairs. When the window happens to start on a tool result whose assistant call fell off the front, the result is an orphan: some providers reject the request with 400, others accept it and the model misreads it. The fix is to trim in whole units (a user turn, or an assistant turn plus every result that answers it), pin the system message, count in tokens, and validate the list before every send.

How to approach it

Treat it as the debugging round it is: reproduce, explain the intermittency, fix the mechanism, add the check that prevents a recurrence. Ask what the 400 body says, because providers usually name the problem ("tool result without a preceding tool call"). Then explain what the model actually receives from a list of messages, so the interviewer hears that you know why the structure matters and not just that you found a bug.

A strong answer

Reproduce it with the shape of the history. An agent that calls tools produces runs of messages like user, assistant with tool calls, tool result, tool result, assistant text, user, and so on. A fixed-size slice of that list starts wherever the arithmetic lands. When it lands on a tool result, the assistant turn that requested it is gone:

a(c1,c2) = assistant turn calling c1 and c2;  t(c1) = result for c1

full history:   sys u1 a(c1,c2) t(c1) t(c2) a u2 a(c3) t(c3) a u3
last ten:           u1 a(c1,c2) t(c1) t(c2) a u2 a(c3) t(c3) a u3    valid, by luck
one turn later:     a(c1,c2) t(c1) t(c2) a u2 a(c3) t(c3) a u3 a(c4) valid
two turns later:    t(c1) t(c2) a u2 a(c3) t(c3) a u3 a(c4) t(c4)    orphans t(c1) t(c2)

That is the intermittency. Whether the request is valid depends on where the window falls, so the bug appears and disappears as the conversation grows. The system message has also been sliced off in every case, which is a second bug hiding behind the first: the agent is running without its instructions whenever the history is longer than ten messages.

Explain the rule the list has to obey. Every tool result names the call id it answers, and that call must be in the assistant turn immediately before. A call and its results are one unit, kept or dropped together. Providers differ in how strictly they enforce it: some return 400, which is the symptom here; others accept the list and the model reads an answer to a question nobody asked, which is worse because it fails silently.

Fix the mechanism rather than the symptom:

  1. Group the history into units: a user turn is a unit, an assistant turn with tool calls plus all its results is a unit, an assistant text turn is a unit.
  2. Pin the system message outside the trimming entirely.
  3. Trim from the oldest unit, and count in tokens rather than messages, because ten messages can be 400 tokens or 40,000.
  4. Validate before every send: no tool result without its call, no call without a result, system first.
def units(msgs):
    out, i = [], 0
    while i < len(msgs):
        m = msgs[i]
        if m["role"] == "tool":
            raise ValueError(f"orphan result {m['id']}")
        unit, i = [m], i + 1
        if m["role"] == "assistant" and m.get("calls"):
            while i < len(msgs) and msgs[i]["role"] == "tool":
                unit.append(msgs[i]); i += 1
            if {r["id"] for r in unit[1:]} != set(m["calls"]):
                raise ValueError("call without result")
        out.append(unit)
    return out

def trim(msgs, budget, size=lambda m: len(m.get("text", "")) // 4 + 8):
    system = [m for m in msgs if m["role"] == "system"]
    kept, used = [], sum(size(m) for m in system)
    for u in reversed(units([m for m in msgs if m["role"] != "system"])):
        cost = sum(size(m) for m in u)
        if used + cost > budget:
            break
        kept.insert(0, u); used += cost
    return system + [m for u in kept for m in u]

h = [{"role": "system", "text": "rules"}, {"role": "user", "text": "q1"},
     {"role": "assistant", "calls": ["c1"]}, {"role": "tool", "id": "c1", "text": "r1"},
     {"role": "assistant", "text": "a1"}, {"role": "user", "text": "q2"}]
print([m["role"] for m in trim(h, budget=30)])  # => ['system', 'assistant', 'user']
try:
    units(h[3:])
except ValueError as e:
    print(e)  # => orphan result c1

With a budget of thirty token-ish units, the trimmer keeps the system message and the two newest whole units; it never produces a list that starts on a result. The validator turns the production bug into a test failure.

Finish by saying what trimming cannot do. Dropping old units loses what was in them. For a long run the real design is clearing old tool results to placeholders, moving durable facts into notes, and compacting the conversation deliberately rather than by truncation (Clearing, Compaction and Notes).

What interviewers probe next

"The provider accepts the orphaned result instead of rejecting it. Is that better?" Worse. The request succeeds and the model reads a result with no request, which it may ignore, misattribute to a later call, or treat as user text. Validate on your side so the behaviour does not depend on how strict the provider is.

"Why count in tokens rather than messages?" Because messages are not a unit of size. One tool result can be 20,000 tokens of rows. A message count gives no control over the budget that matters.

"The model requested two tools and one failed. What goes in the list?" A result for both, including a structured error for the failure. One call without a result is the same malformed list from the other side.

What if?

What if · interview follow-ups

Hold your answer as the constraints change

Your support agent's requests fail with 400 about one time in twenty, and on other days the model answers as if a lookup never happened. The history is trimmed to the last ten messages.

  1. Start here

    Why is the failure intermittent?

How it's scored

Weak: Blames the provider or raises the message count, with no account of why the failure is intermittent.

Hire: Finds the cut through a call-and-result pair, explains the intermittency, trims in whole units and pins the system message.

Strong Hire: Also counts in tokens, adds a pre-send validator, names the silent variant where the provider accepts the orphan, and points to clearing, notes and compaction as the real long-run design.

Common mistakes

  • Slicing the list by count and treating "it worked in testing" as evidence.
  • Forgetting the system message is in the slice too.
  • Appending results only for successful calls, leaving a call unanswered.
  • Trusting a lenient provider: a request that succeeds with an orphaned result is a silent misread.
  • Using truncation as the long-run context strategy instead of clearing, notes and compaction.
You just read a free answer. Every topic opens its first 5 answers to anyone. Sign in and the count per topic goes to 6, and the site remembers where you stopped in each one.Google sign-in · free · no payment details
HOW DID IT GO?
0
READING SIGNED OUT

Signing in raises your free answers from 5 to 6 per topic, adds an applied lesson in every topic and easy practice tests, and the site starts remembering you: mastery per topic, bookmarks, and a next-focus recommendation. Free, no card.

Sign in free
UP NEXT ON YOUR JOURNEY
DISCUSSION · 0

Nobody has commented. Post a correction or another way to answer.