問題
LLMには有限のコンテキストウィンドウがあります。128Kトークンモデルは寛容に聞こえますが、出力予算、システムプロンプト、ツール説明、マルチターン会話の蓄積された履歴を差し引くと話は別です。長い会話、大きなツール結果、マルチステップエージェントループはすべてこの制限に対して圧力をかけます。多くの場合、単一のセッション内でです。 素朴なソリューションは切り詰めです。ウィンドウが満杯になったら古いメッセージを削除します。これは高速で予測可能ですが、コンテキストを無差別に破壊します。ユーザーの元々の意図、以前のターンからの重要な決定、重要なデータポイントはすべて、単純な文字切り詰めが当たると消えてしまいます。反対の極端 — すべてのターンでLLM駆動の要約 — は意味的なコンテンツを保持しますが、高コストで遅く、独自の障害モード(幻覚的な要約、数値精度の喪失)を導入します。 真の課題は「ウィンドウに収まる」ことではありません。それは:重要な情報を失わずに段階的に劣化し、不要な圧縮にトークンを浪費せず、ユーザーが感じることができるレイテンシを追加しない。 FIM Oneはこれを5層の多層防御アーキテクチャで解決します。各層は問題の異なるスケールに対処し、きれいに構成されます — 単一の層が完璧である必要はありません。次の層がそれが見落とすものをキャッチするからです。Five layers of defense
Context management is not a single mechanism. It is a stack, where each layer handles a specific concern at a specific granularity:
The layers are numbered bottom-up because higher layers depend on lower ones. Layer 5 sets the budget. Layer 4 does the initial load-time compaction. Layer 3 enforces the budget on every iteration. Layers 2 and 1 provide the primitives that layers 3 and 4 use.
Layer 5 — Budget Configuration
The budget is computed from two values of the model in use:(128,000 - 64,000) × 0.92 = 58,880 tokens. The 8% margin absorbs the error of heuristic token estimation, so compaction triggers before the provider’s hard limit.
No static system prompt reserve is subtracted. The system prompt (agent instructions, tool descriptions, formatting overhead) is included in the message list that ContextGuard estimates dynamically — subtracting a fixed reserve on top would double-count it and waste budget. A typical system prompt consumes 3K-5K tokens; agents with many tools or long instructions may use more. ContextGuard accounts for the actual size automatically.
The values come from the models a chat turn resolved: the agent’s own model and fast model when it sets them, otherwise the active model group, otherwise the system default. Each resolved model reports its own context_size and max_output_tokens, so two agents on different models get different budgets in the same deployment.
A model with no context size configured (the field left empty in its model configuration) falls back to the system budget for its role, resolved in priority order:
- System ModelConfig for the role —
context_sizeandmax_output_tokensof the systemgeneralorfastmodel set by the admin. - Environment variables —
LLM_CONTEXT_SIZE/FAST_LLM_CONTEXT_SIZEandLLM_MAX_OUTPUT_TOKENS. - Hardcoded defaults — 128K context, 64K output.
- ReAct mode sends one message list to both models: the fast model decides tool calls, the main model writes the final answer (and the fast model stands in when the main model is unavailable). The list is budgeted against the smaller of the two budgets, so any mix of windows stays within both. When a legal, medical or similar domain query escalates the turn to the reasoning model, that model’s window replaces the main model’s in the comparison.
- DAG mode budgets history loading and planning against the main model, and each step against the model that runs it (the general model by default, or the one the step’s
model_hintselects).
Layer 4 — DbMemory
DbMemory is the production memory implementation. It loads persisted conversation history from the database and compacts it to fit the token budget before the agent sees it.
The design is read-only by intention. Persistence is handled by chat.py — the API layer that owns the full message lifecycle (including metadata, usage tracking, and image attachments). DbMemory does not persist conversation turns: its add_message() and clear() methods are no-ops, and its only write is a synthetic tool result row for a tool call left dangling by an interrupted turn. This separation prevents double-writes and keeps the persistence logic in one place.
On load, DbMemory:
- Queries all
user,assistantandtoolmessages for the conversation, ordered by creation time. - Drops the trailing user message (the current query, which the agent will re-append).
- Reconstructs image attachments — user messages that included images store metadata (
file_id,mime_type) in the database, andDbMemoryrebuilds the base64 data-URLs from disk so the LLM can “see” images from earlier turns. - Compacts: if a
compact_llmwas provided, usesCompactUtils.llm_compact(). Otherwise, falls back toCompactUtils.smart_truncate(). The whole stored conversation is the input here, so this is where the history most often exceeds the summarising model’s window; it is then summarised in parts (see Chunked compaction input).
DbMemory sets tracking flags (was_compacted, _original_count, _compacted_count) that the SSE layer uses to emit a compact event to the frontend.
Layer 3 — ContextGuard
ContextGuard is the per-iteration budget enforcer. It is called at the top of every ReAct iteration — both in standalone ReAct mode and inside each DAG step’s agent. This is the last line of defense before the messages hit the LLM API.
The enforcement follows a three-step process:
-
Truncate oversized individual messages. Any single message exceeding 50K characters is hard-truncated with a
[Truncated]suffix. This catches runaway tool outputs — a web scrape that returns an entire webpage, a file read that dumps a large dataset. - Estimate total tokens. If the total fits within budget, return immediately. Most iterations pass here — compaction is the exception, not the norm.
-
Compact if over budget. If a
compact_llmis available, use LLM-powered compaction with a hint-specific prompt. Otherwise, fall back tosmart_truncate.
Each hint maps to a carefully worded system prompt that tells the compaction LLM what to keep and what to discard. Each prompt instructs the LLM to write in the same language as the conversation — a detail that matters for CJK users whose summaries would otherwise default to English.
If LLM compaction fails (network error, empty response, any exception), ContextGuard falls back to
smart_truncate silently. The agent never sees the failure. This is a deliberate reliability choice: better to lose some context via heuristic truncation than to crash the iteration.
Chunked compaction input
The summariser is the fast model, and its window can be smaller than the history it is asked to condense: a large main model paired with a small fast one, or a long stored conversation loaded byDbMemory. Sending that history as one request overflows the summariser, and compaction degrades to truncation exactly when it is needed.
CompactUtils.summarize_history() is the single summarising step behind ContextGuard, DbMemory and the DAG planner-input summary. It takes the summariser’s own input budget (from the window that model declares) and guarantees no request exceeds it:
- History that fits goes out as one request, as before.
- Longer history is cut into consecutive parts. A tool call and its results always land in the same part; only a single exchange larger than a whole part is split, and an over-long message is cut rather than dropped.
- The parts are folded in order: the first is summarised on its own, and each later request carries the summary so far (capped at 10K tokens, or a quarter of the summariser’s budget if smaller) plus the next part, and asks for one updated summary in the same format.
CONTEXT_GUARD_MAX_COMPACT_CHUNKS(default 8) bounds the number of requests. History needing more parts keeps the first part and the most recent ones, and the summariser is told there is a gap.
smart_truncate fallback. The split only concerns the text the summariser reads: the message list kept for the main model still never starts with tool results whose tool call was summarised away.
Layer 2 — CompactUtils
CompactUtils is a stateless utility class — no instances, no state, just pure functions. It provides three capabilities that layers 3 and 4 build on.
Token estimation converts text to an approximate token count without importing a tokenizer library. The heuristic:
- ASCII characters: ~4 characters per token
- CJK / non-ASCII characters: ~1.5 characters per token
- Images: 765 tokens per image (flat cost)
- Per-message overhead: 4 tokens (role marker, delimiters)
smart_truncate is the heuristic fallback. It keeps pinned messages unconditionally, then walks backward through non-pinned messages, accumulating until the budget is exhausted. The result is a suffix of the conversation that fits. It also ensures the result never starts with an assistant message — an orphaned assistant turn with no preceding user message confuses LLMs.
llm_compact is the LLM-powered path. It splits messages into three groups — system messages (always kept), pinned messages (always kept), and compactable messages. The oldest compactable messages are summarized into a single [Conversation summary] system message (in parts when they exceed the summariser’s window); the most recent 4 messages are kept verbatim, more when the cut would otherwise separate a tool call from its results. If the compacted result is still too long, it falls back to smart_truncate on the compacted output — belt and suspenders.
レイヤー 1 — メモリ実装
メモリレイヤーはBaseMemory インターフェースを定義します: add_message()、get_messages()、clear()。3 つの実装が存在します:
- WindowMemory — カウントベースのスライディングウィンドウ。最後の N 個の非システムメッセージを保持します。シンプルで予測可能、LLM 呼び出しなし。本番環境では使用されていません。テストとステートレスシナリオに役立ちます。
-
SummaryMemory — メッセージカウントがしきい値を超えたときに LLM 要約をトリガーします。古いメッセージを
[Conversation summary]システムメッセージに圧縮します。本番環境では使用されていません。より洗練された ContextGuard アプローチより前のものです。 - DbMemory — 本番実装 (レイヤー 4 で説明)。データベースバック、読み取り専用、ロード時に LLM またはヒューリスティック圧縮を使用します。
How context flows through ReAct
The ReAct agent uses context management at two distinct phases: load time and iteration time. Tool iterations run on the fast model when one is configured (non-streamingchat() in JSON mode, stream_chat() in native mode); the answer is streamed through stream_answer(). This two-phase split — tool loop followed by a streamed answer — optimizes both latency and user experience. For full ReAct engine architecture including dual-mode execution and tool selection, see ReAct Engine.
The key insight: DbMemory handles the historical context problem (turns from previous requests), while ContextGuard handles the within-request growth problem (tool results accumulating during an agent loop). They operate at different timescales and catch different failure modes.
The user’s current query is always marked as pinned=True. This ensures it survives all compaction — both smart_truncate and llm_compact preserve pinned messages unconditionally. No matter how aggressively the history is compressed, the user’s actual question is never lost.
How context flows through DAG
DAG mode has a fundamentally different context shape than ReAct. Instead of one long conversation thread, it has a tree: a planning phase, multiple parallel execution steps, and an analysis phase. Each phase has its own context management strategy. Phase 1 — History loading. DbMemory loads and compacts conversation history, same as ReAct. The compacted history is formatted into a text block prefixed with"Previous conversation:".
Phase 2 — Enriched query construction. The history text and current query are combined into an enriched_query. If this exceeds 16K tokens, it is LLM-summarized using the planner_input hint prompt, in parts when the history exceeds the fast model’s window. The 16K threshold is chosen because the planner needs to read the entire query in a single pass — unlike ReAct, there is no iterative compaction during planning.
Phase 3 — Planning. The planner receives a 2-message prompt: system prompt plus enriched query. No ContextGuard here — the enriched query is already size-controlled by the 16K check.
Phase 4 — Step execution. Each DAG step runs as an independent ReAct agent with its own ContextGuard. Critically, these step agents have no memory — they start fresh with only their task description and dependency context. This is by design: DAG steps should be self-contained units of work. Dependency results are injected via _build_step_context, which character-truncates at 50K (the ContextGuard’s max_message_chars limit).
Phase 5 — Analysis. Step results are formatted for the analyzer LLM with per-step truncation at 10K characters. This prevents a single step’s verbose output from dominating the analysis context.
Phase 6 — Replanning. When the analyzer determines the goal was not achieved and does not judge it unreachable, step results are truncated to 500 characters each for the latest round (200 for older rounds) in the replanning context. Replanning needs to know what happened and what went wrong, not the full detail of every step’s output. This aggressive truncation keeps the replan prompt compact enough for the planner to process efficiently.
For the full DAG pipeline architecture including the LLM Call Map and re-planning logic, see DAG Engine.
ピン留めされたメッセージ
ピン留めメカニズムは、圧縮によって破棄されてはならないメッセージを保護します。2つのカテゴリのメッセージがピン留めされます:- 現在のユーザークエリ — 常にピン留めされます。ユーザーが質問をして履歴が長すぎる場合、システムは履歴を圧縮し、質問は圧縮しません。
- ストリーム中に注入されたメッセージ — ユーザーがエージェント実行中にフォローアップを送信すると、注入されたメッセージはピン留めされ、エージェントは次の反復でそれを認識します。
Token estimation
FIM One uses heuristic token estimation rather than a real tokenizer. This is a deliberate choice with clear trade-offs. Why not a real tokenizer? Three reasons:-
Dependency cost.
tiktoken(OpenAI’s tokenizer) is 15MB of compiled Rust bindings.sentencepiece(used by some open-source models) has its own build requirements. For a framework that targets multiple LLM providers, there is no single correct tokenizer — each model family uses a different one. - Speed. Heuristic estimation is a single pass over the string. Real tokenization involves vocabulary lookup, BPE merge operations, and special token handling. ContextGuard calls estimation on every iteration, sometimes multiple times — the speed difference matters.
- Good enough. The heuristic is tuned for mixed-language text (the ASCII/CJK split covers the two major cases). It can be 1.5-2x off for edge cases (heavily punctuated code, unusual Unicode), but context management is inherently approximate. Being 30% off on a ~59K budget still leaves a comfortable margin.
The estimation always returns at least 1 token for non-empty content. This prevents division-by-zero edge cases in budget arithmetic.
What the user sees
Context management is designed to be invisible in the common case and minimally intrusive when it activates. The user-facing signals are: CompactDivider. WhenDbMemory compacts history on load, the frontend renders a dashed divider with the text “Earlier context (N messages) was summarized by AI.” This appears between the summary and the preserved recent messages, giving the user a visual cue that older context has been compressed without interrupting the conversation flow.
Token usage display. The done card at the end of each response shows “X.Xk in / X.Xk out” — the total input and output tokens consumed. Tokens the fast LLM spends on compaction are not included in this figure.
Graceful error handling. If context management fails entirely — a scenario that should not happen given the fallback chain, but could in theory — the error surfaces as agent error text in the response, not as a system crash. The conversation continues; the user can retry or rephrase.
The goal is that most users never think about context management. They have long conversations, the system handles the budget transparently, and the only visible artifact is an occasional compact divider. For power users and operators who care about token efficiency, the usage display and the configurable budget parameters provide the control they need.