Spaces:
Paused

File size: 31,501 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
"""
agent_memory.py β€” Shared multi-turn memory helpers for every smolagents
CodeAgent in the app (General Chat agentic mode, RAG Chat agentic mode,
Data Analysis), following the official smolagents memory guide exactly:
https://huggingface.co/docs/smolagents/tutorials/memory

Standard smolagents memory model
---------------------------------
smolagents keeps an agent's own history in `agent.memory.steps` β€” a plain
Python list of TaskStep / ActionStep / PlanningStep objects. Two rules
from the official tutorial cover everything this app needs:

  1. `agent.run(task, reset=False)` keeps `agent.memory.steps` across
     calls, instead of the `reset=True` default that wipes it at the
     start of every single call β€” this is what lets a follow-up like
     "and what about last year?" refer back to what was already asked.
     Every chat handler (chat.py / data_analysis.py) already does this
     correctly: `agent.run(task, reset=not use_memory)`.
  2. Memory can be edited directly, as a plain list. The tutorial's own
     "Dynamically change the agent's memory" section does exactly this
     (`agent.memory.steps = previous_agent.memory.steps`, or trimming via
     a step_callback) β€” cap_agent_memory() below does the same thing
     (trim old turns by reassigning `agent.memory.steps`), and
     reset_memory() below calls smolagents' own `agent.memory.reset()`
     for the same effect when the whole conversation should be dropped.

This module is intentionally just those two small helpers now. It used
to also serialize `agent.memory.steps` to JSON on disk so memory would
survive an app restart, not just a model swap within the same run β€” that
was NEVER part of smolagents' own memory model (smolagents doesn't ship
save/load for `agent.memory` at all β€” see the still-open
https://github.com/huggingface/smolagents/issues/1216), and hand-rolling
it was the source of several real bugs:

  - Reconstructing ToolCall / ChatMessage / Timing objects from a
    flattened dict is version-sensitive; a smolagents upgrade can
    silently rename/drop a field, which needed several defensive
    "filter down to whatever kwargs this version's constructor accepts"
    layers just to avoid crashing on load β€” a lot of fragility for a
    feature smolagents itself doesn't officially support.
  - Memory was persisted GLOBALLY per tab (shared across every model used
    in that tab), so replaying a step written by one model's tool-call
    format into a DIFFERENT model's chat template could produce a
    genuinely confused answer β€” a real quality/correctness bug, not just
    a theoretical risk.
  - Worse, it actively defeated Data Analysis's "a new dataset was
    uploaded, so old memory about the previous one shouldn't carry over"
    logic: that code correctly detected the dataset had changed and reset
    the agent β€” but building a replacement agent right afterward then
    reloaded the *exact same stale, pre-reset memory straight back off
    disk*, silently undoing the reset it was supposed to perform.

This file now sticks to the plain, official, RAM-only workflow instead:
an agent's memory lives exactly as long as its Python object does. It's
gone the moment the model is switched, "Clear" is clicked, or the app
restarts β€” matching smolagents' own tutorial exactly, and matching the
"🧠 Conversation Memory (Experimental)" checkbox's own label: this trades
"memory survives a restart / model switch" for "memory behaves correctly
and predictably", which is the right trade given the bugs above.

Compaction (the third helper, added later)
-------------------------------------------
`compact_agent_memory()` upgrades the plain drop-oldest cap: instead of
throwing the oldest turns away when the conversation grows, it FIRST
measures the agent memory's token footprint against the model's context
window, and β€” only when it's about to overflow β€” asks the model itself to
condense the older turns into a short rolling summary that is prepended
to the system prompt (the most recent turns stay verbatim). This is the
"true" compaction approach (approach #4 in the standard context-window
playbook, with the token-usage trigger of #3), and it deliberately keeps
the exact same RAM-only lifecycle as everything else here: the summary
lives on the agent object (`agent._rolling_summary`), dies with it, and
is cleared by reset_memory() together with the steps. On any failure it
degrades to dropping the oldest turns β€” the old behaviour β€” so the chat
loop is never worse off than before.
"""

from smolagents.memory import TaskStep


# ──────────────────────────────────────────────────────────────────
# Turn-count cap (approach #2 β€” drop oldest turns)
# ──────────────────────────────────────────────────────────────────
def cap_agent_memory(agent, max_turns: int = 6) -> None:
    """Keep only the most recent `max_turns` conversation turns in
    `agent.memory.steps` β€” the same "edit the list directly" pattern
    smolagents' own tutorial uses for trimming memory, just dropping
    whole old turns instead of individual fields/screenshots.

    Each turn starts with a `TaskStep` (the user's message, or in Data
    Analysis's case the full task prompt) and is followed by whatever
    `ActionStep`/`PlanningStep`s the agent took to answer it. This drops
    whole old turns rather than truncating mid-turn, so memory always
    stays structurally valid for smolagents to replay.

    The agent's system prompt lives separately in
    `agent.memory.system_prompt` and is never touched by this.
    """
    steps = agent.memory.steps
    task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)]
    if len(task_indices) > max_turns:
        cutoff = task_indices[-max_turns]
        agent.memory.steps = steps[cutoff:]


# ──────────────────────────────────────────────────────────────────
# Token-budget-aware rolling compaction (approaches #3 + #4)
# ──────────────────────────────────────────────────────────────────
# How much of the context window the memory may use before compaction
# fires, before the generation reserve is subtracted. Conservative by
# design: the upcoming answer shares the window with whatever memory we
# keep, and llama-server's native KV-cache shift remains the final safety
# net on the server backend.
COMPACTION_BUDGET_RATIO = 0.75

# Target size of the LLM-written rolling summary per compaction.
COMPACTION_MAX_SUMMARY_TOKENS = 512

# Longest single step fed to the summarizer (action steps carry full
# tool observations β€” a pasted webpage or a large DataFrame print must
# not flood the summary call).
_COMPACTION_STEP_TEXT_LIMIT = 2000

# Hard cap on the stored ROLLING summary (chars) β€” a very long
# conversation must never let the summary itself re-fill the window
# (which would otherwise trigger a compaction loop where the summary is
# the bulk of the prompt). ~1500 tokens at the 4-chars/token heuristic.
_COMPACTION_ROLLING_SUMMARY_MAX_CHARS = 6000


def estimate_text_tokens(text, tokenizer=None) -> int:
    """Approximate token count of `text` for context-window budgeting.

    Uses a real tokenizer when one is available (llama-cpp-python's
    `Llama.tokenize`, or a transformers tokenizer), falling back to a
    documented ~4-characters-per-token heuristic for every other backend
    (llama-server HTTP, HF Inference API, LiteLLM). Always wrapped in
    try/except so a tokenizer quirk can never break the chat loop β€” the
    heuristic is an estimate, and the compaction threshold has slack."""
    if not text:
        return 0
    if tokenizer is not None:
        try:
            return max(1, len(tokenizer(str(text))))
        except Exception:
            pass
    return max(1, int(len(str(text)) / 4))


def _get_model_tokenizer(llm):
    """Best-effort tokenizer callable for a smolagents Model object, or
    None when none is cheaply accessible (callers fall back to the char
    heuristic). Version-robust: every attribute is read defensively."""
    if llm is None:
        return None
    # In-process llama.cpp backend: LlamaCppModel wraps llama_cpp.Llama
    # as `.llm`, whose `.tokenize(text)` returns the token id list β€” the
    # most accurate count this app can get, since it is the exact same
    # tokenizer the KV-cache is sized against.
    inner = getattr(llm, "llm", None)
    if inner is not None and callable(getattr(inner, "tokenize", None)):
        return inner.tokenize
    # smolagents TransformersModel exposes `.tokenizer` in most versions.
    tok = getattr(llm, "tokenizer", None)
    if tok is not None:
        if callable(getattr(tok, "encode", None)):
            return lambda t: tok.encode(t, add_special_tokens=False)
        if callable(getattr(tok, "tokenize", None)):
            return tok.tokenize
    return None


def _effective_n_ctx(llm, fallback_n_ctx: int) -> int:
    """Refine the context-window budget from the live model when
    possible. In-process llama.cpp reports its actual KV-cache size via
    `n_ctx()`; HF checkpoints report their trained context length via
    `config.max_position_embeddings`. Falls back to the value the caller
    passed (models._llm_n_ctx, or the persisted context-window setting)."""
    if llm is None:
        return fallback_n_ctx
    inner = getattr(llm, "llm", None)
    if inner is not None and callable(getattr(inner, "n_ctx", None)):
        try:
            return int(inner.n_ctx())
        except Exception:
            pass
    config = getattr(getattr(llm, "model", None), "config", None)
    mpe = getattr(config, "max_position_embeddings", None)
    if mpe:
        try:
            return int(mpe)
        except Exception:
            pass
    return fallback_n_ctx


def _step_to_text(step, limit: int = _COMPACTION_STEP_TEXT_LIMIT) -> str:
    """Version-robust plain-text rendition of one smolagents memory step
    (TaskStep / ActionStep / PlanningStep / ...). Prefers the step's own
    `to_string()`; falls back to repr. Truncated so a single huge
    observation (full webpage text, DataFrame print) can't flood the
    summarizer."""
    try:
        text = step.to_string()
    except Exception:
        try:
            text = str(step)
        except Exception:
            return ""
    text = str(text or "").strip()
    if not text:
        return ""
    if limit is not None and len(text) > limit:
        text = text[:limit] + "\n…(truncated)"
    return text


def _memory_to_text(agent, *, truncate: bool = True) -> str:
    """Flatten the agent's whole memory (system prompt + every step) into
    one text blob, for token estimation / summarization input.

    With `truncate=True` (the summarizer input) each step is capped so a
    single huge observation can't flood the summary call. With
    `truncate=False` (the token-budget estimate) the FULL step text is
    counted β€” the estimate must match what llama.cpp actually builds into
    the prompt, or a window overflow could slip past the budget check."""
    parts = []
    sp = getattr(agent.memory, "system_prompt", None)
    if sp is not None:
        parts.append(_step_to_text(sp, limit=4000 if truncate else None))
    for step in list(getattr(agent.memory, "steps", []) or []):
        parts.append(_step_to_text(step, limit=_COMPACTION_STEP_TEXT_LIMIT if truncate else None))
    return "\n\n".join(p for p in parts if p)


def _system_prompt_text(mem) -> str:
    """Read the agent memory's system prompt as a plain string β€” handles
    SystemPromptStep objects AND bare-string system prompts."""
    sp = getattr(mem, "system_prompt", None)
    if sp is None:
        return ""
    if isinstance(sp, str):
        return sp
    content = getattr(sp, "content", None)
    if isinstance(content, str):
        return content
    try:
        return str(sp.to_string())
    except Exception:
        return str(sp)


def _set_system_prompt_text(mem, text: str) -> None:
    """Replace the agent memory's system prompt in place. Version-robust:
    SystemPromptStep exposes a `.content` string in current smolagents;
    fall back to reassigning the slot for any older shape."""
    sp = getattr(mem, "system_prompt", None)
    if sp is None:
        return
    if isinstance(sp, str):
        mem.system_prompt = text
        return
    if hasattr(sp, "content"):
        try:
            sp.content = text
            return
        except Exception:
            pass
    try:
        mem.system_prompt = text
    except Exception:
        pass


def _inject_rolling_summary(agent, rolling: str) -> None:
    """Append the rolling conversation summary to the agent's system
    prompt, so it is included in every future run's prompt (smolagents
    always renders memory.system_prompt at the top of the next prompt).

    The ORIGINAL system prompt is captured on the agent object the first
    time, so reset_memory() can restore it (smolagents' memory.reset()
    clears `steps` but deliberately leaves `system_prompt` untouched)."""
    base = getattr(agent, "_base_system_prompt", None)
    if base is None:
        base = _system_prompt_text(agent.memory)
        agent._base_system_prompt = base
    block = (
        "\n\n---\n"
        "ROLLING CONVERSATION SUMMARY (the older turns of this conversation "
        "were compacted; treat the condensed history below as fact):\n"
        f"{rolling}"
    )
    _set_system_prompt_text(agent.memory, base + block)


_SUMMARY_SYSTEM = (
    "You are the memory compactor of a local AI assistant. You will be "
    "given the OLDER turns of a conversation. Produce ONE compact rolling "
    "summary that preserves, in order of importance: "
    "(1) key facts, numbers and results, "
    "(2) the user's preferences, instructions and decisions, "
    "(3) any open questions or unfinished tasks. "
    "Be dense and factual β€” no pleasantries, no repetition, no markdown "
    "headers. Write in the same language as the conversation. "
    "Keep it under {max_tokens} tokens."
)


def _strip_old_observations(agent, keep_recent_turns: int = 1) -> bool:
    """Strip or truncate heavy tool observations from older ActionSteps
    before dropping entire turns, preserving tool call reasoning while
    reclaiming token budget."""
    changed = False
    try:
        steps = list(getattr(agent.memory, "steps", []) or [])
        task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)]
        if len(task_indices) <= keep_recent_turns:
            return False
        cutoff = task_indices[-keep_recent_turns]
        for step in steps[:cutoff]:
            if hasattr(step, "observations") and step.observations:
                obs = str(step.observations)
                if len(obs) > 200:
                    step.observations = obs[:200] + "… (observation summarized/truncated)"
                    changed = True
    except Exception:
        pass
    return changed


def _trim_memory_to_budget(agent, budget: int, tokenizer=None) -> bool:
    """Degraded fallback for compact_agent_memory(): when the LLM summary
    call fails β€” or when memory is already over budget before there are
    enough turns to summarize (a single heavy turn, e.g. a Deep Research
    turn whose sub-agent report lives in the manager's memory, can
    overflow the window on turn 2) β€” first strip heavy observations from
    older turns, then drop the OLDEST turns (never the newest) until the
    estimated memory size fits under `budget`, keeping at least one user
    turn's task + final answer. Returns True if anything was changed."""
    changed = False
    try:
        # Step 1: try stripping bulky observations from older turns first
        if _strip_old_observations(agent):
            changed = True
            if estimate_text_tokens(_memory_to_text(agent, truncate=False), tokenizer) <= budget:
                return True

        # Step 2: drop oldest turns as needed
        while True:
            steps = list(getattr(agent.memory, "steps", []) or [])
            task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)]
            if not steps:
                break
            if estimate_text_tokens(_memory_to_text(agent, truncate=False), tokenizer) <= budget:
                break
            if len(task_indices) >= 2:
                # Two or more turns β€” drop the oldest whole turn(s),
                # leaving the newest turn verbatim.
                agent.memory.steps = steps[task_indices[1]:]
                changed = True
                continue
            # Exactly one turn (a single heavy turn overflowed the window)
            # β€” keep the task and the final-answer step, dropping the
            # bloated middle (sub-agent reports / large tool observations)
            # which are the usual token hogs.
            if task_indices and len(steps) > 2:
                agent.memory.steps = [steps[task_indices[0]]] + steps[-1:]
                changed = True
                continue
            break  # task-only memory still over budget β€” nothing left to drop
    except Exception:
        pass
    return changed


def guard_memory_within_run(agent, llm=None, n_ctx=None,
                            budget_ratio: float = COMPACTION_BUDGET_RATIO) -> bool:
    """Intra-run memory guard β€” the missing twin of compact_agent_memory().

    compact_agent_memory() only runs BETWEEN turns (before agent.run()),
    so a single long agentic run β€” a Deep Research manager that collects
    twelve web-search observations in ONE turn β€” could grow its memory
    far past the model's context window mid-run and die with llama-server's
    HTTP 400 exceed_context_size_error (observed: 62723 prompt tokens vs
    a 32768-token window at step ~12).

    This guard is called by stream_agent_steps() after EVERY completed
    step: when the estimated full-memory token cost crosses
    `n_ctx * budget_ratio`, _trim_memory_to_budget() strips heavy older
    observations / drops the bloated middle so the NEXT step's prompt fits.
    Only fires for LOCAL-backed models whose window this app can measure
    (is_local_backed_model) β€” remote backends are left untouched. Returns
    True when memory was trimmed."""
    try:
        if llm is None:
            llm = (getattr(agent, "llm", None)
                   or getattr(agent, "model", None))
        if not is_local_backed_model(llm):
            return False
        if n_ctx is None:
            try:
                from backend.model_registry import get_saved_context_window
                n_ctx = get_saved_context_window()
            except Exception:
                return False
        try:
            n_ctx = int(n_ctx)
        except Exception:
            return False
        if n_ctx <= 0:
            return False
        budget = int(n_ctx * budget_ratio)
        est = estimate_text_tokens(_memory_to_text(agent, truncate=False),
                                   _get_model_tokenizer(llm))
        if est <= budget:
            return False
        print(f"[MemoryGuard] Agent memory β‰ˆ{est} tokens exceeds the "
              f"{budget}-token budget ({n_ctx} ctx Γ— {budget_ratio:g}) β€” "
              f"trimming older steps …")
        return _trim_memory_to_budget(agent, budget,
                                      tokenizer=_get_model_tokenizer(llm))
    except Exception:
        return False


def is_local_backed_model(llm) -> bool:
    """True when `llm` is backed by LOCAL weights whose context window
    this app can measure: an in-process llama.cpp backend (`.llm`), the
    external llama-server backend (a `.gguf` model_path), or an
    in-process transformers model (`.model`). Remote backends (HF
    Inference API / LiteLLM) return False β€” their real context is
    unknowable here and typically far larger than the saved
    GGUF-oriented context-window fallback, so trimming against a
    guessed budget would fire every few turns for nothing. Shared by
    compact_agent_memory() and the direct chat paths' token-budget
    memory trimming (chat.py::_recent_memory_messages)."""
    if llm is None:
        return False
    return (bool(getattr(llm, "llm", None))
            or str(getattr(llm, "model_path", "") or "").lower().endswith(".gguf")
            or getattr(llm, "model", None) is not None)


def trim_messages_to_budget(messages: list, budget: int, tokenizer=None) -> list:
    """Keep the most recent `messages` β€” a list of plain
    {"role", "content"} dicts β€” whose estimated token footprint fits
    under `budget`, dropping whole OLD messages from the oldest end
    (never the newest) and always keeping at least one full exchange
    (two messages) when available. Same token-estimation machinery as
    compact_agent_memory(); used by the direct (non-agentic) chat
    paths' short-term memory so it is bounded by the context window
    instead of a fixed turn count. Returns `messages` unchanged when
    the budget is non-positive or an estimate hiccups."""
    if budget <= 0 or not messages:
        return messages
    try:
        costs = [estimate_text_tokens(str(m.get("content", "") or ""), tokenizer)
                 for m in messages]
        if sum(costs) <= budget:
            return messages
        n = len(messages)
        min_keep = min(n, 2)  # never trim below one full user+assistant exchange
        acc = sum(costs[n - min_keep:])
        best_start = n - min_keep
        for i in range(n - min_keep - 1, -1, -1):
            acc += costs[i]
            if acc <= budget:
                best_start = i
            else:
                break
        return messages[best_start:]
    except Exception:
        return messages


def compact_agent_memory(agent, model_id: str, n_ctx: int,
                         keep_recent_turns: int = 2,
                         budget_ratio: float = COMPACTION_BUDGET_RATIO,
                         max_summary_tokens: int = COMPACTION_MAX_SUMMARY_TOKENS,
                         lang_key: str = "kh") -> bool:
    """Token-budget-aware rolling compaction for an agentic CodeAgent β€”
    the meaningful upgrade over the plain turn-based cap.

    When the agent's memory would push the next prompt past the context
    window, the model condenses the OLDER turns into a short rolling
    summary that is prepended to the system prompt, while the most recent
    `keep_recent_turns` turns stay verbatim β€” preserving content the
    fixed turn-cap throws away, at the cost of one extra generation every
    time the window fills. Runs BEFORE the next agent.run() so the cost
    is only paid when a new message actually arrives.

    Returns True if memory was changed (summarized, or token-trimmed as a
    degraded fallback), so callers can surface a one-line status. Never
    raises: any failure degrades to dropping the oldest turns, and the
    existing post-run cap_agent_memory() call sites remain in place as
    the structural safety net. Returns False with zero changes when the
    "🧹 Memory Compaction" toggle (Settings) is off, when memory is
    still comfortably within budget, or when there aren't enough turns
    yet to make summarizing worthwhile AND memory is under budget (a
    single heavy turn that is already over budget β€” e.g. Deep Research,
    whose sub-agent report lives in the manager's memory β€” degrades to
    the token-budget trim instead, so the next run can't overflow).
    """
    from backend import model_registry as mr
    from backend import models

    if not mr.get_saved_memory_compaction_enabled():
        return False

    budget = 0
    tokenizer = None
    try:
        steps = list(getattr(agent.memory, "steps", []) or [])
        task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)]

        # Remote backends (HF Inference API / LiteLLM) have no in-process
        # tokenizer or model config, so their real context is unknowable
        # here β€” and it is typically far larger than the saved context-
        # window fallback (which is GGUF-oriented). Compacting those would
        # fire every few turns and burn unnecessary remote API calls for
        # nothing, so skip them; the fixed turn-caps still bound their
        # memory.
        model_obj = getattr(agent, "model", None)
        if not is_local_backed_model(model_obj):
            return False

        n_ctx = _effective_n_ctx(model_obj, n_ctx)
        # Generation reserve: the upcoming answer shares the window with
        # whatever memory we keep, so the budget must leave room for it.
        budget = int(n_ctx * budget_ratio) - mr.get_saved_max_new_tokens()
        if budget <= 0:
            return False

        tokenizer = _get_model_tokenizer(getattr(agent, "model", None))
        if estimate_text_tokens(_memory_to_text(agent, truncate=False), tokenizer) <= budget:
            return False

        # Too few turns to make summarizing worthwhile β€” BUT memory is
        # already over budget (a single heavy turn can overflow the
        # window, e.g. Deep Research, whose sub-agent report lives in the
        # manager's memory β€” the "Requested tokens (N) exceed context
        # window" failure on turn 2). Degrade to the token-budget trim so
        # the next run never crashes with a context overflow.
        if len(task_indices) <= keep_recent_turns + 1:
            return _trim_memory_to_budget(agent, budget, tokenizer)

        # Everything before the last `keep_recent_turns` user turns is
        # compacted; those recent turns stay verbatim.
        cutoff_idx = task_indices[-keep_recent_turns]
        old_text = "\n\n".join(
            _step_to_text(s) for s in steps[:cutoff_idx]
        ).strip()
        if not old_text:
            return False

        lang_note = "αžαŸ’αž˜αŸ‚αžš (Khmer)" if lang_key == "kh" else "English"
        # Cap the summary generation itself: the compaction call must NOT
        # inherit the model's full MAX_NEW_TOKENS budget β€” a slow local
        # model would stall behind the "Compacting…" status for minutes,
        # and a rambling model would permanently bloat the prompt. Passed
        # through _call_llm's optional max_tokens kwarg, which falls back
        # gracefully if a backend's Model wrapper rejects it.
        summary, _, _n_tok = models._call_llm(
            model_id,
            _SUMMARY_SYSTEM.format(max_tokens=max_summary_tokens)
            + f"\nLanguage: {lang_note}.",
            old_text,
            max_tokens=max_summary_tokens,
        )
        summary = (summary or "").strip()
        if not summary or summary.startswith("❌"):
            # Summarizer failed (network, template, budget…) β€” degrade to
            # token-aware trimming of the oldest turns rather than the
            # full compaction.
            return _trim_memory_to_budget(agent, budget, tokenizer)
        # Defensive truncation: even a capped generation can exceed the
        # requested size β€” never let a single summary bloat the prompt.
        max_chars = max(512, max_summary_tokens * 4)
        if len(summary) > max_chars:
            summary = summary[:max_chars].rstrip() + "…"

        prev = getattr(agent, "_rolling_summary", "") or ""
        rolling = (prev + "\n\n" + summary).strip() if prev else summary
        if len(rolling) > _COMPACTION_ROLLING_SUMMARY_MAX_CHARS:
            # Keep the NEWEST summary content and drop the oldest chunk,
            # so a long conversation can't let the summary itself re-fill
            # the window (which would trigger a compaction loop).
            rolling = "…" + rolling[-_COMPACTION_ROLLING_SUMMARY_MAX_CHARS:].lstrip("\n")
        _inject_rolling_summary(agent, rolling)
        agent.memory.steps = steps[cutoff_idx:]
        agent._rolling_summary = rolling
        # Counter surfaced in the chat response footer ("compacted NΓ—") so
        # users can see when the rolling summary is being used. Reset
        # together with the rest of memory in reset_memory().
        agent._compaction_count = (getattr(agent, "_compaction_count", 0) or 0) + 1
        print(f"[memory] Compaction: {len(task_indices)} turns -> rolling "
              f"summary + {len(steps[cutoff_idx:])} steps kept verbatim.")
        return True
    except Exception:
        import traceback
        traceback.print_exc()
        if budget > 0:
            try:
                return _trim_memory_to_budget(agent, budget, tokenizer)
            except Exception:
                pass
        return False


def reset_memory(agent) -> None:
    """Wipe an agent's own conversation memory in place, WITHOUT rebuilding
    the agent object itself.

    Calls smolagents' own `agent.memory.reset()` β€” see smolagents/memory.py:
    `AgentMemory.reset()` sets `self.steps = []` and explicitly leaves
    `self.system_prompt` (a separate `SystemPromptStep`, not part of
    `steps`) untouched. Using the library's own method here rather than
    reassigning `agent.memory.steps = []` by hand keeps this in step with
    whatever AgentMemory.reset() does internally in a future smolagents
    version, instead of this file quietly re-implementing (and
    potentially drifting from) that logic.

    Also restores the ORIGINAL system prompt, drops any rolling
    compaction summary the agent carries, and zeroes the compaction
    counter (see compact_agent_memory()): a reset must never replay
    compacted history from the previous conversation, so the compacted
    system-prompt overlay is undone here.

    Used whenever something other than an explicit model switch should
    invalidate memory β€” e.g. Data Analysis's "a new dataset was uploaded"
    check (see reset_if_context_changed() below). Clearing memory in
    place like this β€” rather than tearing down and rebuilding the whole
    CodeAgent, as an earlier version of this file did β€” is both cheaper
    (no tool re-initialization) and avoids the stale-memory-reload bug
    described in this module's docstring.
    """
    agent.memory.reset()
    if hasattr(agent, "_base_system_prompt"):
        _set_system_prompt_text(agent.memory, agent._base_system_prompt)
    if hasattr(agent, "_rolling_summary"):
        agent._rolling_summary = None
    if hasattr(agent, "_compaction_count"):
        agent._compaction_count = 0


def reset_if_context_changed(agent, state: dict, new_key) -> bool:
    """Helper for tabs where a NEW context (e.g. a newly uploaded dataset)
    should invalidate old agent memory even though the underlying
    model/agent object hasn't changed β€” otherwise the agent would keep
    "remembering" a previous file's columns/stats while analyzing a
    different one.

    `state` is a small mutable dict (e.g. module-level `{"key": None}`)
    used to remember the last context key seen. Returns True if a reset
    was triggered.
    """
    if state.get("key") != new_key:
        reset_memory(agent)
        state["key"] = new_key
        return True
    return False