跳到正文
DEV Community· Yuya AI Lab·· 4 小時前AI 評分67

智能體忘記訂單編號:純 Python 上下文壓縮如何保留事實

Your Agent Forgot the Order Number: Compacting Context Without Losing Facts (Pure Python)

AI 導讀

Yuya AI Lab 以純 Python 實作智能體上下文壓縮方法,在每次呼叫前按預算保留對話事實,並記錄被省略的事實。在 400 組固定種子的合成客服對話測試中,具型別欄位在 10% 預算下令 95.8% 的對話仍可完整回答;只保留最近對話的策略為 1.0%。這是事實是否仍在提示詞中的代理指標,並非實際回答準確率;文章亦指出,截短條件值可能保留日期卻刪去行動要求。

正文

A support agent takes a 40-turn conversation, hits the context limit, and quietly drops the first half. The customer's order number was in turn 3. The closing question — "can you repeat the details I gave you?" — gets a confident, wrong answer, and nothing in the logs shows that the number was ever there.

I measured four ways to fit a conversation into a token budget, on 400 seeded synthetic transcripts, with no model calls and no dependencies. At the same total prompt size, keeping the newest turns recovered 30% of the facts a later turn needed. A small typed slot memory recovered 100%. At a 10% budget it still had 95.8% of sessions fully answerable, in 148 tokens out of 1,557.

This post is the implementation, the numbers, and — mostly — the two places where the obvious version of this idea breaks.

The failure is a budget decision, not a memory problem

Every agent framework has the same three lines somewhere:

if tokens(messages) > limit:
    messages = messages[-keep:]     # keep the newest

That is a policy choice disguised as housekeeping. It assumes that importance correlates with recency, which is true for small talk and false for exactly the facts people call back about: order numbers, dates, budgets, addresses, constraints, the one instruction that must never be broken.

The alternative — "summarise the old part with another model call" — costs money per turn, is non-deterministic, and can summarise away the digits. For a system handling bookings or refunds, a summary that turns "QX-48213" into "their order" has destroyed the only thing that mattered.

So the design goal here is narrower and duller than "memory": before each call, decide what fits, and be able to say precisely what you left out.

The corpus you can rerun

Synthetic, seeded, offline: 400 support conversations, 30–70 turns, a mean of 1,557 tokens each. Every session plants three facts the closing question depends on — an order number, a deadline, and one detail (dietary constraint, budget, shipping city, or a conditional instruction). 35% of sessions correct the order number halfway through, so a stale value exists in the transcript and must lose. The rest is realistic filler, which is most of what a real transcript is.

The metric is fact availability: after compaction, is the exact value still present in the prompt? It is a proxy for answer accuracy, not a substitute — if the value is absent the model cannot answer correctly, and if it is present the model usually can. Every number below uses the same seeded corpus and the same prompt budget, so the comparison holds even though the absolute token counts are estimates from a regex tokenizer rather than a BPE one.

Recency, salience, and one measured surprise

Four policies at the same budget fraction:

strategy budget mean fact recall fully answerable prompt tokens facts / 100 tokens stale order ids in prompt
tail 25% 0.300 6.0% 363 0.26 1%
tail 10% 0.088 1.0% 136 0.19 0%
extractive 25% 0.450 12.2% 374 0.38 47%
extractive 10% 0.274 1.5% 148 0.59 30%
slots 25% 1.000 100% 365 0.88 0%
slots 10% 0.986 95.8% 148 2.14 0%
slots-clipped 10% 0.924 77.2% 148 2.02 0%

Two things worth reading twice.

The stale column. "Extractive" here means keeping individual sentences scored by recency plus "looks like data" (IDs, money, digits) — the heuristic most teams write first, and it beats plain tail. It also puts the superseded order number into 47% of prompts at the 25% budget. The prompt then contains two order numbers and no indication which one won. That is worse than forgetting: a model that guesses between them produces a wrong answer that looks sourced.

Facts per 100 prompt tokens. At 10% the slot memory is 11× more efficient than tail (2.14 vs 0.19). You are not buying recall with tokens, you are buying it with structure.

Three parts, about 370 lines, standard library only

1. A token count you can trust to be deterministic

_TOKEN_RE = re.compile(r"[A-Za-z]+(?:'[A-Za-z]+)?|\d+(?:[.,:\-/]\d+)*|[^\sA-Za-z\d]")

def estimate_tokens(text: str) -> int:
    if not text:
        return 0
    return len(_TOKEN_RE.findall(text))

Word runs, number runs kept whole (QX-48213, 1,240.00), single punctuation marks. It is not a BPE tokenizer and I do not pretend it is: absolute counts will drift by roughly 10–20% against one. Every strategy is measured in the same units, so the comparisons stand, and the budget you pass in should be a fraction of your real window, not a hair under it.

2. Typed slots with conflict resolution

Rules are plain regexes per key, and the interesting part is not extraction but what happens when a value changes.

class SlotMemory:
    RULES = [
        ("order_id", re.compile(r"order(?:\s+number|\s+no\.?|\s*#)?\s*(?:is|:)?\s*#?([A-Z]{2}-\d{5})", re.I)),
        ("deadline", re.compile(r"(?:by|before)\s+(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|\d{4}-\d{2}-\d{2})", re.I)),
        ("budget",   re.compile(r"(?:under|budget is|budget of)\s*(\$[\d,]+)", re.I)),
        ("conditional", re.compile(r"(if (?:it|the item|the parcel) arrives before [A-Z][a-z]+,? leave it with the [a-z ]+?)(?=[.,;]|$)", re.I)),
        # dietary, address omitted here
    ]

    def _put(self, key, value, turn, span):
        existing = self.slots.get(key)
        if existing is None:
            self.slots[key] = Fact(key, value, turn, span)
        elif existing.value == value:
            return None                      # repeat: keep the earliest turn
        elif turn < existing.turn:
            return None                      # old turn arriving late: ignore
        else:
            existing.superseded.append(existing.value)   # a later turn wins
            existing.value, existing.turn, existing.span = value, turn, span

Three behaviours are load-bearing. A repeated fact does not churn. A late-arriving old turn cannot overwrite a newer value. And the superseded value is remembered, not discarded — the fill step in part 3 uses it to keep the stale sentence out of the prompt, which is where the extractive policy above went wrong.

The weird-looking conditional rule exists because a value can be a value and an action. Storing "Friday" is not enough: "if it arrives before Friday, leave it with the concierge" becomes useless the moment the action is dropped. So that slot's value is the whole clause.

3. Assembly with a receipt

def compact(messages, budget, strategy="tail", keep_recent=2, pin_instructions=True):
    memory = SlotMemory()
    for m in messages:
        memory.observe(m)

    total = sum(m.tokens for m in messages)
    if total <= budget:
        text = "\n\n".join(m.text for m in messages)
        return CompactionResult(text, strategy, budget, estimate_tokens(text), [], [], 0, untouched=True)

    pinned = [m for m in messages if m.is_instruction] if pin_instructions else []
    remaining = budget - estimate_tokens("\n".join(m.text for m in pinned))

    # half the budget for facts, half for the live exchange; facts win ties
    slot_text, _ = memory.render(max_tokens=remaining // 2)
    ...
    result.dropped_facts = missing_facts(result.text, memory)
    return result

missing_facts() is nine lines and is the only part I would ship even if I shipped nothing else:

def missing_facts(compacted_text, memory):
    low = compacted_text.lower()
    return sorted(f"{key}={fact.value}" for key, fact in memory.slots.items()
                  if fact.value.lower() not in low)

Now the answer to "why did the agent forget the order number" is a log line: dropped_facts: ["order_id=TL-90217", "deadline=Monday", "dietary=dairy-free"] at a 34-token budget, with the prompt still carrying its pinned rules. In production that line is how you find out you set the budget to 34.

The knob that quietly breaks things

Compacting the slot block itself looks harmless: keep values short, fit more of them. Clipping long values to eight words raised nothing suspicious in the aggregate — 94.8% recall at 25%, versus 100% unclipped.

Then the conditional facts:

action survives
tail / extractive, 25% 40.6%
slots, 25% 100%
slots, clipped to 8 words, 25% 34.4%

Clipping turned the best line of the block into the worst. The value was still there — conditional: If it arrives before Friday, leave it with — the instruction was not. Any budget knob that shortens values is also a knob that deletes verbs.

The same trap has a second face in the pinned lines. Two RULE: messages in every session:

variant both rules kept at 10% / 5% / 2%
tail, no pinning 0% / 0% / 0%
extractive, no pinning 0% / 0% / 0%
tail, pinned 100% / 100% / 100%

The naive policy loses both rules at every budget tested — 0 of 120 sessions — because they sit at turn 0 and policy keeps the tail. They are not "old context". They are the frame the rest of the answer must sit inside, and they cost about 23 tokens to keep.

What this does not measure

Being specific about the limits matters more than the numbers.

  • The probe asks only for facts the memory was designed to hold. Extraction is hand-written regex for a support domain. Recall of 1.000 means "the memory kept what it extracted", not "the memory extracted everything a careful human would". A free-text requirement in turn 5 that no rule recognises is invisible to both the slot block and the receipt.
  • Availability is not correctness. A present value can still be misused, and an agent that forgets can sometimes ask. The metric bounds the failure, it does not rule it out.
  • The corpus is synthetic. Seeded, reproducible, honest about its shape — but real transcripts have false facts, ambiguity and sarcasm, and the regexes will meet all three.
  • Compaction is not summarisation. This deliberately refuses to paraphrase. If your product needs narrative continuity ("the customer was frustrated, so soften the tone"), keep a short human-written running note alongside the slots; do not ask a summariser to preserve digits.

Production checklist

  1. Pin instructions and policy text outside the budget; account for their cost explicitly.
  2. Slot the facts your closing questions depend on — IDs, dates, money, constraints — and resolve conflicts by turn order, keeping the old value as superseded.
  3. Never clip a value that contains an action. Clip only display-only fields.
  4. Filter the fill step against superseded values, or you will mail the model two order numbers.
  5. Log dropped_facts per call. It is the difference between "the model is dumb" and "we set the limit wrong".
  6. Leave the transcript untouched when it already fits — no rewrites, no tax.
  7. Test the boundaries: empty conversation, budget below the pinned lines, keep_recent=0, unknown strategy.

The module is 373 lines, the experiments 367, and 39 unittest tests pass in 13 ms (python3 -m unittest discover -s tests). Compaction costs 2.4 ms on a 50-turn transcript and 28 ms on 600 turns (20,459 tokens) — cheap enough to run on every call, which is the point: a decision you can afford to make every time is a decision you can also log every time.

The whole thing is deterministic: same transcript and budget, same prompt, same hash. That means the failing prompt from yesterday is a fixture you can replay today.

Disclosure: I write about AI automation systems I build and run solo. If you want the working code, the seeded experiment harness, and the deploy notes in one place, they are here: Yuya AI Lab on Payhip.

來源:DEV Community · dev.to