Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:24kchengYe MemoMind filter by token budget

From Leeroopedia
Knowledge Sources
Domains Information_Retrieval, LLM_Engineering
Last Updated 2026-10-28 00:00 GMT

Overview

Concrete tool for filtering reranked search results to fit within a token budget using tiktoken's cl100k_base encoding, provided by the MemoMind MemoryEngine.

Description

The _filter_by_token_budget method of MemoryEngine takes reranked search results and greedily packs them into a token budget. It counts tokens for each result's 'text' field using the cl100k_base tiktoken encoding and stops before including a result that would exceed the budget.

The function uses a cached tiktoken encoding (initialized once via `_get_tiktoken_encoding` at memory_engine.py:L213). The greedy approach processes results in ranked order, ensuring the most relevant results are included first.

Usage

Use this method via MemoryEngine when you need to limit retrieved context to a token budget before feeding it to an LLM. It is called by the recall pipeline as the final stage before returning results.

Code Reference

Source Location

  • Repository: MemoMind
  • File: engine/hindsight_api/engine/memory_engine.py
  • Lines: L3353-3386 (uses count_tokens at L54-56, _get_tiktoken_encoding at L213)

Signature

def _filter_by_token_budget(
    self,
    results: list[dict[str, Any]],
    max_tokens: int,
) -> tuple[list[dict[str, Any]], int]:

Import

# Accessed as a MemoryEngine method:
# memory_engine._filter_by_token_budget(results, max_tokens)
# Or use the public recall_async API which calls this internally.

I/O Contract

Inputs

Name Type Required Description
results list[dict[str, Any]] Yes Reranked search results with 'text' field
max_tokens int Yes Maximum tokens allowed in output

Outputs

Name Type Description
filtered_results list[dict[str, Any]] Results fitting within token budget
total_tokens int Total tokens used by filtered results

Usage Examples

Token Budgeting in Recall

# Called internally by MemoryEngine.recall_async
# After reranking, results are filtered to fit the max_tokens budget

# Example: 20 reranked results, budget of 2048 tokens
filtered, tokens_used = memory_engine._filter_by_token_budget(
    results=reranked_results,
    max_tokens=2048,
)
print(f"Included {len(filtered)} results using {tokens_used} tokens")

Related Pages

Implements Principle

Requires Environment

Uses Heuristics

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment