Skip to content

Commit ad10405

Browse files
committed
Add token count message
1 parent b119e8e commit ad10405

File tree

3 files changed

+96
-8
lines changed

3 files changed

+96
-8
lines changed

llms_wrapper/llms.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from typing import Optional, Dict, List, Union, Tuple, Callable
1515
from copy import deepcopy
1616

17-
from litellm import completion, completion_cost
17+
from litellm import completion, completion_cost, token_counter
1818
from litellm.utils import get_model_info, get_supported_openai_params, supports_response_schema
1919
from litellm.utils import supports_function_calling, supports_parallel_function_calling
2020
from llms_wrapper.utils import dict_except
@@ -402,6 +402,15 @@ def supports_file_upload(self, llmalias: str) -> bool:
402402
"""
403403
return False
404404

405+
def count_tokens(self, llmalias: str, messages: List[Dict[str, str]]) -> int:
406+
"""
407+
Count the number of tokens in the given messages. If messages is a string, convert it to a
408+
single user message first.
409+
"""
410+
if isinstance(messages, str):
411+
messages = [{"role": "user", "content": messages}]
412+
return token_counter(model=self.llms[llmalias]["llm"], messages=messages)
413+
405414
def query(
406415
self,
407416
llmalias: str,
@@ -604,3 +613,8 @@ def supports_json_schema(self) -> bool:
604613
def supports_function_calling(self, parallel=False) -> bool:
605614
return self.llmsobject.supports_function_calling(self.config["alias"], parallel)
606615

616+
def supports_file_upload(self) -> bool:
617+
return self.llmsobject.supports_file_upload(self.config["alias"])
618+
619+
def count_tokens(self, messages: List[Dict[str, str]]) -> int:
620+
return self.llmsobject.count_tokens(self.config["alias"], messages)

llms_wrapper/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
import importlib.metadata
2-
__version__ = "0.1.30"
2+
__version__ = "0.1.31"
33

notebooks/test-api.ipynb

Lines changed: 80 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@
226226
" 'api_key_env': 'MY_GEMINI_API_KEY',\n",
227227
" 'alias': 'gemini/somemodel',\n",
228228
" '_cost': 0,\n",
229+
" '_last_request_time': 0,\n",
229230
" '_elapsed_time': 0}"
230231
]
231232
},
@@ -321,6 +322,79 @@
321322
"msg1 = llms.make_messages(\"What is a monoid?\")"
322323
]
323324
},
325+
{
326+
"cell_type": "code",
327+
"execution_count": 15,
328+
"id": "abac6cf6-7175-4cbb-8527-d24c8847a28b",
329+
"metadata": {},
330+
"outputs": [
331+
{
332+
"data": {
333+
"text/plain": [
334+
"13"
335+
]
336+
},
337+
"execution_count": 15,
338+
"metadata": {},
339+
"output_type": "execute_result"
340+
}
341+
],
342+
"source": [
343+
"llms.count_tokens(\"openai/gpt-4.5-preview\", msg1)"
344+
]
345+
},
346+
{
347+
"cell_type": "code",
348+
"execution_count": 16,
349+
"id": "a8e72aa6-c1be-4631-86cf-3b3f820c6059",
350+
"metadata": {},
351+
"outputs": [],
352+
"source": [
353+
"llm = llms[\"openai/gpt-4o\"]"
354+
]
355+
},
356+
{
357+
"cell_type": "code",
358+
"execution_count": 17,
359+
"id": "452600c9-ee93-48e3-bbf7-c3ab5eb51ade",
360+
"metadata": {},
361+
"outputs": [
362+
{
363+
"data": {
364+
"text/plain": [
365+
"13"
366+
]
367+
},
368+
"execution_count": 17,
369+
"metadata": {},
370+
"output_type": "execute_result"
371+
}
372+
],
373+
"source": [
374+
"llm.count_tokens(msg1)"
375+
]
376+
},
377+
{
378+
"cell_type": "code",
379+
"execution_count": 18,
380+
"id": "5a9a8a26-78a6-40ff-b104-24028b1c424c",
381+
"metadata": {},
382+
"outputs": [
383+
{
384+
"data": {
385+
"text/plain": [
386+
"13"
387+
]
388+
},
389+
"execution_count": 18,
390+
"metadata": {},
391+
"output_type": "execute_result"
392+
}
393+
],
394+
"source": [
395+
"llm.count_tokens(\"What is a monoid?\")"
396+
]
397+
},
324398
{
325399
"cell_type": "code",
326400
"execution_count": 15,
@@ -330,15 +404,15 @@
330404
{
331405
"data": {
332406
"text/plain": [
333-
"{'elapsed_time': 21.85033893585205,\n",
334-
" 'response': ModelResponse(id='chatcmpl-B84wXy8ULKMSfurBDArzoYPsLaElv', created=1741265325, model='gpt-4.5-preview-2025-02-27', object='chat.completion', system_fingerprint=None, choices=[Choices(finish_reason='stop', index=0, message=Message(content='In abstract algebra, a **monoid** is an algebraic structure consisting of:\\n\\n1. **A set \\\\(M\\\\)**,\\n2. **An associative binary operation**, usually denoted by multiplication (\\\\(\\\\cdot\\\\)), such that \\\\(a \\\\cdot (b \\\\cdot c) = (a \\\\cdot b) \\\\cdot c\\\\) for all \\\\(a, b, c \\\\in M\\\\),\\n3. **An identity element**, typically called unity or identity (often denoted by \\\\(e\\\\)), which satisfies:\\n\\\\[\\ne \\\\cdot a = a \\\\cdot e = a\\n\\\\]\\nfor all \\\\(a \\\\in M\\\\).\\n\\nSimply stated, a monoid is a set equipped with an associative binary operation and a neutral element.\\n\\n**Examples:**\\n\\n- **Natural numbers and addition**: The set \\\\(\\\\mathbb{N}_0 = \\\\{0, 1, 2, \\\\dots\\\\}\\\\) with addition is a monoid. Here, 0 acts as identity element.\\n- **Strings with concatenation**: The set of all strings over an alphabet, combined with concatenation (joining strings end-to-end), forms a monoid. The identity element here is the empty string.\\n- **Multiplication of integers**: The set of integers \\\\(\\\\mathbb{Z}\\\\) is a monoid under multiplication with identity element \\\\(1\\\\).\\n\\n**Why are monoids important?**\\n\\nMonoids appear naturally across many disciplines in mathematics and computer science. In particular:\\n\\n- **Formal language theory and computation**: Monoids arise naturally in studying automata, languages, and formal grammars.\\n- **Category theory**: Monoids can be seen as categories with a single object.\\n- **Parallel and distributed computing**: Monoids are useful for combining, aggregating, and reducing data in parallel computations.\\n\\nIn short, monoids provide an important algebraic abstraction capturing the concepts of \"composable processes\" and \"units of computation\".', role='assistant', tool_calls=None, function_call=None, provider_specific_fields={'refusal': None}))], usage=Usage(completion_tokens=406, prompt_tokens=13, total_tokens=419, completion_tokens_details=CompletionTokensDetailsWrapper(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0, text_tokens=None), prompt_tokens_details=PromptTokensDetailsWrapper(audio_tokens=0, cached_tokens=0, text_tokens=None, image_tokens=None)), service_tier='default'),\n",
407+
"{'elapsed_time': 39.25307822227478,\n",
408+
" 'response': ModelResponse(id='chatcmpl-BFI6FbX7BtguunCLPpOR1KqsexGuk', created=1742984195, model='gpt-4.5-preview-2025-02-27', object='chat.completion', system_fingerprint=None, choices=[Choices(finish_reason='stop', index=0, message=Message(content='A **monoid** is a fundamental algebraic structure in mathematics. Formally, it\\'s defined as a set equipped with an associative binary operation and an identity element.\\n\\nSpecifically, a monoid is a triple \\\\((M, \\\\cdot, e)\\\\), where:\\n\\n1. **\\\\(M\\\\)** is a set.\\n2. **\\\\(\\\\cdot\\\\)** is a binary operation: \\n \\\\[\\n \\\\cdot : M \\\\times M \\\\rightarrow M\\n \\\\]\\n satisfying the associativity property:\\n \\\\[\\n (a \\\\cdot b) \\\\cdot c = a \\\\cdot (b \\\\cdot c) \\\\quad \\\\text{for every } a, b, c \\\\in M.\\n \\\\]\\n3. **\\\\(e\\\\)** is a special element in \\\\(M\\\\), called the identity element, such that for every element \\\\(a\\\\) in \\\\(M\\\\):\\n \\\\[\\n e \\\\cdot a = a \\\\cdot e = a.\\n \\\\]\\n\\n**Examples of monoids:**\\n\\n- **Natural numbers or integers** under addition with identity element 0.\\n- **Natural numbers or positive reals** under multiplication with identity element 1.\\n- **Concatenation** of strings with empty string \"\" as identity.\\n- **Lists** with concatenation as the operation and the empty list as identity.\\n\\n**Relation to other algebraic structures:**\\n\\n- A **group** is a monoid in which every element has an inverse.\\n- A **semigroup** is a structure similar to a monoid but does not require an identity element.\\n\\nMonoids arise frequently in algebra, theoretical computer science, category theory, and functional programming, providing a simple yet versatile abstraction for combining or composing entities.', role='assistant', tool_calls=None, function_call=None, provider_specific_fields={'refusal': None, 'annotations': []}))], usage=Usage(completion_tokens=360, prompt_tokens=13, total_tokens=373, completion_tokens_details=CompletionTokensDetailsWrapper(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0, text_tokens=None), prompt_tokens_details=PromptTokensDetailsWrapper(audio_tokens=0, cached_tokens=0, text_tokens=None, image_tokens=None)), service_tier='default'),\n",
335409
" 'kwargs': {},\n",
336-
" 'cost': 0.06187499999999999,\n",
337-
" 'n_completion_tokens': 406,\n",
410+
" 'cost': 0.05497499999999999,\n",
411+
" 'n_completion_tokens': 360,\n",
338412
" 'n_prompt_tokens': 13,\n",
339-
" 'n_total_tokens': 419,\n",
413+
" 'n_total_tokens': 373,\n",
340414
" 'finish_reason': 'stop',\n",
341-
" 'answer': 'In abstract algebra, a **monoid** is an algebraic structure consisting of:\\n\\n1. **A set \\\\(M\\\\)**,\\n2. **An associative binary operation**, usually denoted by multiplication (\\\\(\\\\cdot\\\\)), such that \\\\(a \\\\cdot (b \\\\cdot c) = (a \\\\cdot b) \\\\cdot c\\\\) for all \\\\(a, b, c \\\\in M\\\\),\\n3. **An identity element**, typically called unity or identity (often denoted by \\\\(e\\\\)), which satisfies:\\n\\\\[\\ne \\\\cdot a = a \\\\cdot e = a\\n\\\\]\\nfor all \\\\(a \\\\in M\\\\).\\n\\nSimply stated, a monoid is a set equipped with an associative binary operation and a neutral element.\\n\\n**Examples:**\\n\\n- **Natural numbers and addition**: The set \\\\(\\\\mathbb{N}_0 = \\\\{0, 1, 2, \\\\dots\\\\}\\\\) with addition is a monoid. Here, 0 acts as identity element.\\n- **Strings with concatenation**: The set of all strings over an alphabet, combined with concatenation (joining strings end-to-end), forms a monoid. The identity element here is the empty string.\\n- **Multiplication of integers**: The set of integers \\\\(\\\\mathbb{Z}\\\\) is a monoid under multiplication with identity element \\\\(1\\\\).\\n\\n**Why are monoids important?**\\n\\nMonoids appear naturally across many disciplines in mathematics and computer science. In particular:\\n\\n- **Formal language theory and computation**: Monoids arise naturally in studying automata, languages, and formal grammars.\\n- **Category theory**: Monoids can be seen as categories with a single object.\\n- **Parallel and distributed computing**: Monoids are useful for combining, aggregating, and reducing data in parallel computations.\\n\\nIn short, monoids provide an important algebraic abstraction capturing the concepts of \"composable processes\" and \"units of computation\".',\n",
415+
" 'answer': 'A **monoid** is a fundamental algebraic structure in mathematics. Formally, it\\'s defined as a set equipped with an associative binary operation and an identity element.\\n\\nSpecifically, a monoid is a triple \\\\((M, \\\\cdot, e)\\\\), where:\\n\\n1. **\\\\(M\\\\)** is a set.\\n2. **\\\\(\\\\cdot\\\\)** is a binary operation: \\n \\\\[\\n \\\\cdot : M \\\\times M \\\\rightarrow M\\n \\\\]\\n satisfying the associativity property:\\n \\\\[\\n (a \\\\cdot b) \\\\cdot c = a \\\\cdot (b \\\\cdot c) \\\\quad \\\\text{for every } a, b, c \\\\in M.\\n \\\\]\\n3. **\\\\(e\\\\)** is a special element in \\\\(M\\\\), called the identity element, such that for every element \\\\(a\\\\) in \\\\(M\\\\):\\n \\\\[\\n e \\\\cdot a = a \\\\cdot e = a.\\n \\\\]\\n\\n**Examples of monoids:**\\n\\n- **Natural numbers or integers** under addition with identity element 0.\\n- **Natural numbers or positive reals** under multiplication with identity element 1.\\n- **Concatenation** of strings with empty string \"\" as identity.\\n- **Lists** with concatenation as the operation and the empty list as identity.\\n\\n**Relation to other algebraic structures:**\\n\\n- A **group** is a monoid in which every element has an inverse.\\n- A **semigroup** is a structure similar to a monoid but does not require an identity element.\\n\\nMonoids arise frequently in algebra, theoretical computer science, category theory, and functional programming, providing a simple yet versatile abstraction for combining or composing entities.',\n",
342416
" 'error': '',\n",
343417
" 'ok': True}"
344418
]

0 commit comments

Comments
 (0)