tiktoken icon indicating copy to clipboard operation
tiktoken copied to clipboard

decode() raises OverflowError instead of KeyError for negative/huge token IDs

Open mangeshraut712 opened this issue 1 month ago • 1 comments

Encoding.decode() raises different exception types for the same class of user error (out-of-range token ID), depending on the value:

import tiktoken
enc = tiktoken.get_encoding('cl100k_base')
enc.decode([99999999])  # KeyError: 'Invalid token for decoding: 99999999'
enc.decode([-1])        # OverflowError: number too small to fit in target type
enc.decode([2**64])     # OverflowError: Python int too large to convert to C long

The large invalid ID gets a clear KeyError from the Rust layer's token lookup, but negative and huge ints fail earlier in int conversion (OverflowError with Rust/C messages). Callers catching KeyError for invalid IDs will miss the OverflowError cases.

Repro output (tiktoken at 4e71bbe, release 0.14.0, Python 3.13.17, macOS arm64, installed with pip install -e .):

[99999999] KeyError 'Invalid token for decoding: 99999999'
[-1] OverflowError number too small to fit in target type
[18446744073709551616] OverflowError Python int too large to convert to C long

Expected: a single consistent error (e.g. KeyError/ValueError naming the bad ID) for all out-of-range inputs, or documented behavior that callers must catch both.

mangeshraut712 avatar Nov 03 '26 11:11 mangeshraut712

Opened #631 with a minimal fix that catches OverflowError in the decode helpers and raises a consistent KeyError for out-of-range negative/huge tokens.

mohmedmm avatar Nov 03 '26 13:11 mohmedmm