""" 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