OneLLM 0.0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # Unified interface for LLM providers using OpenAI format
5
+ # https://github.com/muxi-ai/onellm
6
+ #
7
+ # Copyright (C) 2025 Ran Aroussi
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """
22
+ Token counting utilities for various models.
23
+
24
+ This module provides utilities for counting tokens in text
25
+ for different language models. It supports both tiktoken-based
26
+ counting for OpenAI models and fallback approximations for other models.
27
+ """
28
+
29
+ import re
30
+ from typing import Dict, List, Optional, Union
31
+
32
+ # Note: tiktoken is an optional dependency
33
+ try:
34
+ import tiktoken
35
+
36
+ TIKTOKEN_AVAILABLE = True
37
+ except ImportError:
38
+ TIKTOKEN_AVAILABLE = False
39
+
40
+
41
+ # Regex pattern for tokenizing text when tiktoken is not available
42
+ # This is a simple approximation and not accurate for all languages/models
43
+ SIMPLE_TOKEN_PATTERN = re.compile(r"\w+|[^\w\s]")
44
+
45
+
46
+ # Map of OpenAI model names to tiktoken encodings
47
+ OPENAI_MODEL_ENCODINGS = {
48
+ # GPT-4 models
49
+ "gpt-4": "cl100k_base",
50
+ "gpt-4-0613": "cl100k_base",
51
+ "gpt-4-32k": "cl100k_base",
52
+ "gpt-4-32k-0613": "cl100k_base",
53
+ "gpt-4-turbo": "cl100k_base",
54
+ "gpt-4-turbo-2024-04-09": "cl100k_base",
55
+ "gpt-4-1106-preview": "cl100k_base",
56
+ "gpt-4-0125-preview": "cl100k_base",
57
+ "gpt-4-vision-preview": "cl100k_base",
58
+ # GPT-3.5 models
59
+ "gpt-3.5-turbo": "cl100k_base",
60
+ "gpt-3.5-turbo-0613": "cl100k_base",
61
+ "gpt-3.5-turbo-1106": "cl100k_base",
62
+ "gpt-3.5-turbo-0125": "cl100k_base",
63
+ "gpt-3.5-turbo-16k": "cl100k_base",
64
+ "gpt-3.5-turbo-16k-0613": "cl100k_base",
65
+ # Base GPT-3 models
66
+ "text-davinci-003": "p50k_base",
67
+ "text-davinci-002": "p50k_base",
68
+ "text-davinci-001": "r50k_base",
69
+ "davinci": "r50k_base",
70
+ "curie": "r50k_base",
71
+ "babbage": "r50k_base",
72
+ "ada": "r50k_base",
73
+ # Embedding models
74
+ "text-embedding-ada-002": "cl100k_base",
75
+ "text-embedding-3-small": "cl100k_base",
76
+ "text-embedding-3-large": "cl100k_base",
77
+ }
78
+
79
+
80
+ def get_encoder(model: str) -> Optional["tiktoken.Encoding"]:
81
+ """
82
+ Get the tiktoken encoder for the specified model.
83
+
84
+ This function attempts to find the appropriate tiktoken encoder for a given model.
85
+ It first checks if the model has a known encoding in our mapping, then tries to get
86
+ the encoder directly from tiktoken, and finally falls back to cl100k_base as a default.
87
+
88
+ Args:
89
+ model: Name of the model to get the encoder for
90
+
91
+ Returns:
92
+ Encoding object if available, None otherwise if tiktoken is not installed
93
+ or if no appropriate encoder can be found
94
+ """
95
+ # Return None immediately if tiktoken is not available
96
+ if not TIKTOKEN_AVAILABLE:
97
+ return None
98
+
99
+ # Extract base model name if using provider prefix (e.g., "openai/gpt-4")
100
+ if "/" in model:
101
+ _, model = model.split("/", 1)
102
+
103
+ try:
104
+ # First check if we have a predefined encoding for this model
105
+ if model in OPENAI_MODEL_ENCODINGS:
106
+ encoding_name = OPENAI_MODEL_ENCODINGS[model]
107
+ return tiktoken.get_encoding(encoding_name)
108
+
109
+ # If not in our mapping, try to get encoder directly from tiktoken
110
+ return tiktoken.encoding_for_model(model)
111
+ except (KeyError, ImportError, ValueError):
112
+ # If both methods fail, fall back to cl100k_base which works for most newer models
113
+ try:
114
+ return tiktoken.get_encoding("cl100k_base")
115
+ except Exception:
116
+ # If all attempts fail, return None
117
+ return None
118
+
119
+
120
+ def num_tokens_from_string(text: str, model: Optional[str] = None) -> int:
121
+ """
122
+ Count the number of tokens in a string.
123
+
124
+ This function counts tokens in a text string using either tiktoken (if available
125
+ and a model is specified) or a simple regex-based approximation as fallback.
126
+
127
+ Args:
128
+ text: Text to count tokens for
129
+ model: Optional model name to use for counting with tiktoken
130
+
131
+ Returns:
132
+ Number of tokens in the text
133
+ """
134
+ # Handle empty text case
135
+ if not text:
136
+ return 0
137
+
138
+ # Try to use tiktoken for accurate counting if available and model is specified
139
+ if TIKTOKEN_AVAILABLE and model:
140
+ encoder = get_encoder(model)
141
+ if encoder:
142
+ return len(encoder.encode(text))
143
+
144
+ # Fallback to simple approximation using regex
145
+ # This splits text into words and punctuation as a rough token estimate
146
+ return len(SIMPLE_TOKEN_PATTERN.findall(text))
147
+
148
+
149
+ def num_tokens_from_messages(
150
+ messages: List[Dict[str, Union[str, List]]], model: Optional[str] = None
151
+ ) -> int:
152
+ """
153
+ Count the number of tokens in a list of chat messages.
154
+
155
+ This function handles token counting for chat message formats used by LLMs.
156
+ It accounts for message formatting overhead and handles nested content structures
157
+ like those used in multi-modal conversations.
158
+
159
+ Args:
160
+ messages: List of chat messages in the format expected by LLM APIs
161
+ model: Optional model name to use for counting
162
+
163
+ Returns:
164
+ Total number of tokens in the messages, including formatting overhead
165
+ """
166
+ # Handle empty messages case
167
+ if not messages:
168
+ return 0
169
+
170
+ # Extract base model name if using provider prefix
171
+ if model and "/" in model:
172
+ _, model = model.split("/", 1)
173
+
174
+ # Special handling for OpenAI chat models with tiktoken
175
+ # This follows OpenAI's specific token counting methodology for chat formats
176
+ if TIKTOKEN_AVAILABLE and model and model.startswith(("gpt-3.5", "gpt-4")):
177
+ encoder = get_encoder(model)
178
+ if encoder:
179
+ # Constants based on OpenAI's token counting methodology
180
+ tokens_per_message = (
181
+ 3 # Every message follows <|start|>{role/name}\n{content}<|end|>\n
182
+ )
183
+ tokens_per_name = 1 # If there's a name, the role is omitted
184
+
185
+ token_count = 0
186
+ for message in messages:
187
+ # Add base tokens for each message
188
+ token_count += tokens_per_message
189
+
190
+ # Process each field in the message
191
+ for key, value in message.items():
192
+ if isinstance(value, str):
193
+ # For string values, encode and count directly
194
+ token_count += len(encoder.encode(value))
195
+ elif isinstance(value, list):
196
+ # Handle content list (for multi-modal inputs)
197
+ for item in value:
198
+ # Check if this is a content item with text
199
+ is_dict = isinstance(item, dict)
200
+ has_text = is_dict and "text" in item
201
+ is_text_str = has_text and isinstance(item["text"], str)
202
+
203
+ # Only count tokens for text content
204
+ if is_dict and has_text and is_text_str:
205
+ token_count += len(encoder.encode(item["text"]))
206
+
207
+ # Add extra token for name field if present
208
+ if key == "name":
209
+ token_count += tokens_per_name
210
+
211
+ # Add 3 tokens for assistant message formatting (final reply format)
212
+ token_count += 3
213
+ return token_count
214
+
215
+ # Fallback to simple approximation for non-OpenAI models or when tiktoken is unavailable
216
+ token_count = 0
217
+ for message in messages:
218
+ # Count tokens in each field that's a string
219
+ for value in message.values():
220
+ if isinstance(value, str):
221
+ # Count tokens in string values
222
+ token_count += num_tokens_from_string(value, model)
223
+ elif isinstance(value, list):
224
+ # Handle content list (for multi-modal inputs)
225
+ for item in value:
226
+ # Check if this is a content item with text
227
+ is_dict = isinstance(item, dict)
228
+ has_text = is_dict and "text" in item
229
+ is_text_str = has_text and isinstance(item["text"], str)
230
+
231
+ # Only count tokens for text content
232
+ if is_dict and has_text and is_text_str:
233
+ token_count += num_tokens_from_string(item["text"], model)
234
+
235
+ # Add approximation of formatting overhead (4 tokens per message)
236
+ # This is a rough estimate of the tokens used for message formatting
237
+ token_count += len(messages) * 4
238
+ return token_count