|
3 | 3 | from .core import Encoding
|
4 | 4 | from .registry import get_encoding
|
5 | 5 |
|
6 |
| -# TODO: this will likely be replaced by an API endpoint |
| 6 | +# TODO: these will likely be replaced by an API endpoint |
| 7 | +MODEL_PREFIX_TO_ENCODING: dict[str, str] = { |
| 8 | + # chat |
| 9 | + "gpt-3.5-turbo-": "cl100k_base" # e.g, gpt-3.5-turbo-0301, -0401, etc. |
| 10 | +} |
| 11 | + |
7 | 12 | MODEL_TO_ENCODING: dict[str, str] = {
|
| 13 | + # chat |
| 14 | + "gpt-3.5-turbo": "cl100k_base", |
8 | 15 | # text
|
9 | 16 | "text-davinci-003": "p50k_base",
|
10 | 17 | "text-davinci-002": "p50k_base",
|
|
45 | 52 |
|
46 | 53 |
|
47 | 54 | def encoding_for_model(model_name: str) -> Encoding:
|
48 |
| - try: |
| 55 | + """Returns the encoding used by a model.""" |
| 56 | + encoding_name = None |
| 57 | + if model_name in MODEL_TO_ENCODING: |
49 | 58 | encoding_name = MODEL_TO_ENCODING[model_name]
|
50 |
| - except KeyError: |
| 59 | + else: |
| 60 | + # Check if the model matches a known prefix |
| 61 | + # Prefix matching avoids needing library updates for every model version release |
| 62 | + # Note that this can match on non-existent models (e.g., gpt-3.5-turbo-FAKE) |
| 63 | + for model_prefix, model_encoding_name in MODEL_PREFIX_TO_ENCODING.items(): |
| 64 | + if model_name.startswith(model_prefix): |
| 65 | + return get_encoding(model_encoding_name) |
| 66 | + |
| 67 | + if encoding_name is None: |
51 | 68 | raise KeyError(
|
52 | 69 | f"Could not automatically map {model_name} to a tokeniser. "
|
53 | 70 | "Please use `tiktok.get_encoding` to explicitly get the tokeniser you expect."
|
54 | 71 | ) from None
|
| 72 | + |
55 | 73 | return get_encoding(encoding_name)
|
0 commit comments