fleet-memory/hindsight-api/hindsight_api/engine/reflect
Nicolò Boschi 77defd96e9
fix(reflect): prevent context_length_exceeded on large memory banks (#462)
* fix(reflect): prevent context_length_exceeded on large memory banks (#457)

The reflect agent's agentic loop accumulated tool-call messages across
iterations with no upper bound on token count, causing
context_length_exceeded errors on banks with 19K+ nodes.

Changes:
- Add proactive token-budget guard: before each call_with_tools, count
  accumulated message tokens via tiktoken; if >= max_context_tokens and
  evidence has been gathered, immediately synthesize from what was found
- Detect context-overflow errors specifically (_is_context_overflow_error)
  and skip the retry path — retrying after overflow only makes it worse
- Truncate context_history in build_final_prompt to a 60K-token budget
  so the fallback synthesis prompt itself cannot overflow
- Add HINDSIGHT_API_REFLECT_MAX_CONTEXT_TOKENS config (default 100000)
  wired through config.py → main.py → memory_engine → run_reflect_agent
- Tests: unit tests for helpers + mock-LLM behavior tests + an
  end-to-end integration test using a real LLM with max_context_tokens=1

* fix(reflect): derive final prompt context budget from max_context_tokens

Replace the hardcoded _FINAL_PROMPT_CONTEXT_BUDGET (60K tokens) with
a fraction of max_context_tokens (80%), so the fallback synthesis prompt
automatically scales with whatever context window is configured.
2026-03-02 12:03:12 +01:00
..
__init__.py chore: drop dead code (#210) 2026-01-27 15:03:25 +01:00
agent.py fix(reflect): prevent context_length_exceeded on large memory banks (#462) 2026-03-02 12:03:12 +01:00
models.py feat: support markdown in reflect and mental models (#307) 2026-02-06 10:49:13 +01:00
observations.py feat: revisit mental models, directives and reflections (#179) 2026-01-22 17:13:16 +01:00
prompts.py fix(reflect): prevent context_length_exceeded on large memory banks (#462) 2026-03-02 12:03:12 +01:00
tools.py feat: add reflect mode to LoComo benchmark and improve reflect agent (#428) 2026-02-24 09:48:23 +01:00
tools_schema.py feat: add reflect mode to LoComo benchmark and improve reflect agent (#428) 2026-02-24 09:48:23 +01:00