Skip to content

Commit 8abc5ce

Browse files
committed
Optionally use tiktoken - fallback on estimate of tokens
1 parent 1a4edae commit 8abc5ce

1 file changed

Lines changed: 18 additions & 4 deletions

File tree

plain2code_console.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import logging
22

3-
import tiktoken
43
from rich.console import Console
54
from rich.style import Style
65
from rich.tree import Tree
@@ -16,7 +15,13 @@ class Plain2CodeConsole(Console):
1615

1716
def __init__(self):
1817
super().__init__()
19-
self.llm_encoding = tiktoken.get_encoding("cl100k_base")
18+
try:
19+
import tiktoken
20+
21+
self.llm_encoding = tiktoken.get_encoding("cl100k_base")
22+
except Exception as e:
23+
logging.warning(f"Failed to import tiktoken: {e}. Using character count / 4 instead.")
24+
self.llm_encoding = None
2025

2126
def info(self, *args, **kwargs):
2227
logging.info(" ".join(map(str, args)))
@@ -86,7 +91,7 @@ def _create_tree_from_files(self, root_folder, files):
8691
current_level = current_level.add(f"{part} [red]deleted[/red]")
8792
else:
8893
file_lines = len(content.splitlines())
89-
file_tokens = len(self.llm_encoding.encode(content))
94+
file_tokens = self._count_tokens(content)
9095
current_level = current_level.add(f"{part} ({file_lines} lines, {file_tokens} tokens)")
9196
else:
9297
current_level = current_level.add(part)
@@ -95,6 +100,15 @@ def _create_tree_from_files(self, root_folder, files):
95100

96101
return tree
97102

103+
def _count_tokens(self, text):
104+
"""Count tokens using tiktoken if available, otherwise estimate from character count."""
105+
if self.llm_encoding is not None:
106+
try:
107+
return len(self.llm_encoding.encode(text))
108+
except Exception:
109+
pass
110+
return len(text) // 4
111+
98112
def print_resources(self, resources_list, linked_resources):
99113
if len(resources_list) == 0:
100114
self.input("Linked resources: None")
@@ -103,7 +117,7 @@ def print_resources(self, resources_list, linked_resources):
103117
self.input("Linked resources:")
104118
for resource_name in resources_list:
105119
if resource_name["target"] in linked_resources:
106-
file_tokens = len(self.llm_encoding.encode(linked_resources[resource_name["target"]]))
120+
file_tokens = self._count_tokens(linked_resources[resource_name["target"]])
107121
self.input(
108122
f"- {resource_name['text']} [#4169E1]({resource_name['target']}, {file_tokens} tokens)[/#4169E1]"
109123
)

0 commit comments

Comments
 (0)