/
token_counting.py
216 lines (181 loc) · 7.5 KB
/
token_counting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, cast
from llama_index.core.callbacks.base_handler import BaseCallbackHandler
from llama_index.core.callbacks.schema import CBEventType, EventPayload
from llama_index.core.utilities.token_counting import TokenCounter
from llama_index.core.utils import get_tokenizer
@dataclass
class TokenCountingEvent:
prompt: str
completion: str
completion_token_count: int
prompt_token_count: int
total_token_count: int = 0
event_id: str = ""
def __post_init__(self) -> None:
self.total_token_count = self.prompt_token_count + self.completion_token_count
def get_llm_token_counts(
token_counter: TokenCounter, payload: Dict[str, Any], event_id: str = ""
) -> TokenCountingEvent:
from llama_index.core.llms import ChatMessage
if EventPayload.PROMPT in payload:
prompt = str(payload.get(EventPayload.PROMPT))
completion = str(payload.get(EventPayload.COMPLETION))
return TokenCountingEvent(
event_id=event_id,
prompt=prompt,
prompt_token_count=token_counter.get_string_tokens(prompt),
completion=completion,
completion_token_count=token_counter.get_string_tokens(completion),
)
elif EventPayload.MESSAGES in payload:
messages = cast(List[ChatMessage], payload.get(EventPayload.MESSAGES, []))
messages_str = "\n".join([str(x) for x in messages])
response = payload.get(EventPayload.RESPONSE)
response_str = str(response)
# try getting attached token counts first
try:
messages_tokens = 0
response_tokens = 0
if response is not None and response.raw is not None:
usage = response.raw.get("usage", None)
if usage is not None:
if not isinstance(usage, dict):
usage = dict(usage)
messages_tokens = usage.get("prompt_tokens", 0)
response_tokens = usage.get("completion_tokens", 0)
if messages_tokens == 0 or response_tokens == 0:
raise ValueError("Invalid token counts!")
return TokenCountingEvent(
event_id=event_id,
prompt=messages_str,
prompt_token_count=messages_tokens,
completion=response_str,
completion_token_count=response_tokens,
)
except (ValueError, KeyError):
# Invalid token counts, or no token counts attached
pass
# Should count tokens ourselves
messages_tokens = token_counter.estimate_tokens_in_messages(messages)
response_tokens = token_counter.get_string_tokens(response_str)
return TokenCountingEvent(
event_id=event_id,
prompt=messages_str,
prompt_token_count=messages_tokens,
completion=response_str,
completion_token_count=response_tokens,
)
else:
raise ValueError(
"Invalid payload! Need prompt and completion or messages and response."
)
class TokenCountingHandler(BaseCallbackHandler):
"""Callback handler for counting tokens in LLM and Embedding events.
Args:
tokenizer:
Tokenizer to use. Defaults to the global tokenizer
(see llama_index.core.utils.globals_helper).
event_starts_to_ignore: List of event types to ignore at the start of a trace.
event_ends_to_ignore: List of event types to ignore at the end of a trace.
"""
def __init__(
self,
tokenizer: Optional[Callable[[str], List]] = None,
event_starts_to_ignore: Optional[List[CBEventType]] = None,
event_ends_to_ignore: Optional[List[CBEventType]] = None,
verbose: bool = False,
) -> None:
self.llm_token_counts: List[TokenCountingEvent] = []
self.embedding_token_counts: List[TokenCountingEvent] = []
self.tokenizer = tokenizer or get_tokenizer()
self._token_counter = TokenCounter(tokenizer=self.tokenizer)
self._verbose = verbose
super().__init__(
event_starts_to_ignore=event_starts_to_ignore or [],
event_ends_to_ignore=event_ends_to_ignore or [],
)
def start_trace(self, trace_id: Optional[str] = None) -> None:
return
def end_trace(
self,
trace_id: Optional[str] = None,
trace_map: Optional[Dict[str, List[str]]] = None,
) -> None:
return
def on_event_start(
self,
event_type: CBEventType,
payload: Optional[Dict[str, Any]] = None,
event_id: str = "",
parent_id: str = "",
**kwargs: Any,
) -> str:
return event_id
def on_event_end(
self,
event_type: CBEventType,
payload: Optional[Dict[str, Any]] = None,
event_id: str = "",
**kwargs: Any,
) -> None:
"""Count the LLM or Embedding tokens as needed."""
if (
event_type == CBEventType.LLM
and event_type not in self.event_ends_to_ignore
and payload is not None
):
self.llm_token_counts.append(
get_llm_token_counts(
token_counter=self._token_counter,
payload=payload,
event_id=event_id,
)
)
if self._verbose:
print(
"LLM Prompt Token Usage: "
f"{self.llm_token_counts[-1].prompt_token_count}\n"
"LLM Completion Token Usage: "
f"{self.llm_token_counts[-1].completion_token_count}",
flush=True,
)
elif (
event_type == CBEventType.EMBEDDING
and event_type not in self.event_ends_to_ignore
and payload is not None
):
total_chunk_tokens = 0
for chunk in payload.get(EventPayload.CHUNKS, []):
self.embedding_token_counts.append(
TokenCountingEvent(
event_id=event_id,
prompt=chunk,
prompt_token_count=self._token_counter.get_string_tokens(chunk),
completion="",
completion_token_count=0,
)
)
total_chunk_tokens += self.embedding_token_counts[-1].total_token_count
if self._verbose:
print(f"Embedding Token Usage: {total_chunk_tokens}", flush=True)
@property
def total_llm_token_count(self) -> int:
"""Get the current total LLM token count."""
return sum([x.total_token_count for x in self.llm_token_counts])
@property
def prompt_llm_token_count(self) -> int:
"""Get the current total LLM prompt token count."""
return sum([x.prompt_token_count for x in self.llm_token_counts])
@property
def completion_llm_token_count(self) -> int:
"""Get the current total LLM completion token count."""
return sum([x.completion_token_count for x in self.llm_token_counts])
@property
def total_embedding_token_count(self) -> int:
"""Get the current total Embedding token count."""
return sum([x.total_token_count for x in self.embedding_token_counts])
def reset_counts(self) -> None:
"""Reset the token counts."""
self.llm_token_counts = []
self.embedding_token_counts = []