Skip to content

Commit a28a4be

Browse files
new: make sure get_tkn_length avoids recomputing document tokens
Signed-off-by: thiswillbeyourgithub <26625900+thiswillbeyourgithub@users.noreply.github.com>
1 parent 6caa011 commit a28a4be

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

wdoc/utils/misc.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -708,13 +708,23 @@ def get_model_max_tokens(modelname: ModelName) -> int:
708708

709709

710710
def get_tkn_length(
711-
tosplit: str,
711+
tosplit: Union[str, Document],
712712
modelname: Union[str, ModelName] = "gpt-4o-mini",
713713
) -> int:
714714
if isinstance(modelname, ModelName):
715715
modelname = modelname.original
716716
modelname = modelname.replace("openrouter/", "")
717-
return litellm.token_counter(model=modelname, text=tosplit)
717+
if isinstance(tosplit, str):
718+
return litellm.token_counter(model=modelname, text=tosplit)
719+
720+
# avoid recomputing token length for documents
721+
tl = tosplit.metadata.get("tkn_length", None)
722+
if tl and isinstance(tl, int):
723+
return tl
724+
else:
725+
tl = litellm.token_counter(model=modelname, text=tosplit.page_content)
726+
tosplit.metadata["tkn_length"] = tl
727+
return tl
718728

719729

720730
class ChonkieSemanticSplitter(TextSplitter):

0 commit comments

Comments
 (0)