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

Environment:24kchengYe MemoMind tiktoken

From Leeroopedia
Knowledge Sources
Domains Infrastructure, Tokenization
Last Updated 2026-10-28 14:45 GMT

Overview

tiktoken Python library with the `cl100k_base` encoding for token counting in budget filtering and context window management.

Description

This environment provides the `tiktoken` library used to count tokens for the token budget filtering phase of recall. The `cl100k_base` encoding (used by GPT-4/3.5) is cached as a module-level singleton for performance. Token counts are used to pack search results into the LLM context window up to a specified `max_tokens` limit, stopping before including a fact that would exceed the budget.

Usage

Use this environment for token budget filtering — the final step in recall that truncates search results to fit within an LLM context window. Also used internally for retain chunk sizing and consolidation source fact budgeting.

System Requirements

Category Requirement Notes
OS Any (pure Python + Rust extension) Linux, macOS, Windows
Hardware Minimal No GPU needed; fast BPE tokenization
Disk ~2MB for encoding file Cached automatically on first use

Dependencies

Python Packages

  • `tiktoken` >= 0.5 — OpenAI BPE tokenizer

Encodings

  • `cl100k_base` — GPT-4, GPT-3.5-turbo encoding (the only encoding used by MemoMind)

Credentials

No credentials required. The `tiktoken` library downloads the encoding file on first use (or uses a pre-cached copy).

Optional:

  • `TIKTOKEN_CACHE_DIR` — Directory for cached encoding files (production Docker copies `tiktoken_cache/` into the image)

Quick Install

pip install tiktoken

# Verify encoding loads
python -c "import tiktoken; enc = tiktoken.get_encoding('cl100k_base'); print(len(enc.encode('hello world')))"

Code Evidence

Module-level singleton cache from `memory_engine.py:209-218`:

# Cache tiktoken encoding for token budget filtering (module-level singleton)
_TIKTOKEN_ENCODING = None

def _get_tiktoken_encoding():
    """Get cached tiktoken encoding (cl100k_base for GPT-4/3.5)."""
    global _TIKTOKEN_ENCODING
    if _TIKTOKEN_ENCODING is None:
        _TIKTOKEN_ENCODING = tiktoken.get_encoding("cl100k_base")
    return _TIKTOKEN_ENCODING

Token budget filtering from `memory_engine.py:3353-3386`:

def _filter_by_token_budget(self, results, max_tokens):
    """Filter results to fit within token budget.
    Counts tokens only for the 'text' field using tiktoken (cl100k_base encoding).
    Stops before including a fact that would exceed the budget.
    """
    encoding = _get_tiktoken_encoding()
    filtered_results = []
    total_tokens = 0
    for result in results:
        text = result.get("text", "")
        text_tokens = len(encoding.encode(text))
        if total_tokens + text_tokens <= max_tokens:
            filtered_results.append(result)
            total_tokens += text_tokens
        else:
            break  # Stop before exceeding limit
    return filtered_results, total_tokens

Docker cache copy from `deploy/server/Dockerfile:18`:

COPY tiktoken_cache /app/tiktoken_cache

Common Errors

Error Message Cause Solution
`ImportError: tiktoken` Package not installed `pip install tiktoken`
No internet to download `cl100k_base` file | Pre-cache: copy `tiktoken_cache/` directory; set `TIKTOKEN_CACHE_DIR`
Using `cl100k_base` for a non-GPT-4 model | MemoMind hardcodes `cl100k_base`; results are approximate for other models

Compatibility Notes

  • cl100k_base only: MemoMind hardcodes `cl100k_base` (GPT-4/3.5). Token counts for other model families (e.g., Claude, Gemini) are approximate.
  • Offline production: The Docker image copies a `tiktoken_cache/` directory to avoid runtime downloads.
  • Singleton pattern: The encoding is cached at module level — created once, reused across all calls.
  • Text field only: Token counting applies only to the `text` field of search results, not metadata or context.

Related Pages

Page Connections

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