Skip to content

NameError: name 'estimated' is not defined in estimate_prompt_tokens_chain — tiktoken fallback broken #3581

@rdnot

Description

@rdnot

Bug Description

estimate_prompt_tokens_chain() in nanobot/utils/helpers.py crashes with NameError: name 'estimated' is not defined when the provider counter is unavailable or raises an exception.

The crash occurs in memory.py:603 → helpers.py:434 during token-based memory consolidation.

Root Cause

Commit d9800ec ("refactor: replace try-except blocks with contextlib.suppress") accidentally deleted the tiktoken fallback line when converting try/except to with suppress():

     provider_counter = getattr(provider, "estimate_prompt_tokens", None)
     if callable(provider_counter):
-        try:
+        with suppress(Exception):
             tokens, source = provider_counter(messages, tools, model)
             if isinstance(tokens, (int, float)) and tokens > 0:
                 return int(tokens), str(source or "provider_counter")
-        except Exception:
-            pass
-
-    estimated = estimate_prompt_tokens(messages, tools)
     if estimated > 0:
         return int(estimated), "tiktoken"
     return 0, "none"

Steps to Reproduce

  1. Run nanobot gateway with any provider that doesn't implement estimate_prompt_tokens
  2. Send a message that triggers memory consolidation
  3. Consolidator calls estimate_session_prompt_tokens() → estimate_prompt_tokens_chain()
  4. NameError at line 434

Expected Behavior

After provider counter fails, fall through to tiktoken estimation.

Relevant Logs

nanobot Version

nanobot v0.1.5.post3

Python Version

Other (specify below)

Operating System

Windows

Channel / Platform

WhatsApp

LLM Provider

Other (specify below)

Configuration (Optional)

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions