Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Anthropic Tokenizer for Claude Models ✅ #71

Merged
merged 3 commits into from
Aug 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ classifiers = [
]
dependencies = [
"tiktoken>=0.7.0",
"aiohttp>=3.9.3"
"aiohttp>=3.9.3",
"anthropic>=0.34.0"
]

[project.optional-dependencies]
Expand Down
22 changes: 22 additions & 0 deletions tokencost/costs.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@

"""
Costs dictionary and utility tool for counting tokens
"""

import tiktoken
import anthropic
from typing import Union, List, Dict
from .constants import TOKEN_COSTS
from decimal import Decimal
Expand Down Expand Up @@ -39,6 +41,16 @@ def count_message_tokens(messages: List[Dict[str, str]], model: str) -> int:
"""
model = model.lower()
model = strip_ft_model_name(model)

if "claude-" in model:
"""
Note that this is only accurate for older models, e.g. `claude-2.1`.
For newer models this can only be used as a _very_ rough estimate,
instead you should rely on the `usage` property in the response for exact counts.
"""
prompt = "".join(message["content"] for message in messages)
return count_string_tokens(prompt,model)

try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
Expand Down Expand Up @@ -104,6 +116,16 @@ def count_string_tokens(prompt: str, model: str) -> int:
int: The number of tokens in the text string.
"""
model = model.lower()
if "claude-" in model:
"""
Note that this is only accurate for older models, e.g. `claude-2.1`.
For newer models this can only be used as a _very_ rough estimate,
instead you should rely on the `usage` property in the response for exact counts.
"""
client = anthropic.Client()
token_count = client.count_tokens(prompt)
return token_count

try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
Expand Down