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

Fix Bedrock token count and IDs for Anthropic models #341

Merged
merged 10 commits into from
Feb 7, 2025

Conversation

michaelnchin
Copy link
Collaborator

@michaelnchin michaelnchin commented Jan 30, 2025

Fixes #314

The get_num_tokens() and get_token_ids() methods of BedrockLLM and ChatBedrock currently fail when used with Anthropic models and anthropic>=0.39.0 installed.

In such scenarios, this PR fixes get_num_tokens() and get_token_ids() by falling back to the base class implementations in BaseLanguageModel and in BaseChatModel, which use the HuggingFace GPT2 Tokenizer.

If anthropic<=0.38.0 (and other requirements) are present instead, the Anthropic SDK token methods will continue to be used as normal.

Note about tokenizer accuracy:

The GPT2 and Anthropic SDK tokenizers (see here) both may produce inaccurate token estimates for Claude 3 and 3.5 models. To obtain a more accurate estimate, Anthropic recommends using the new Count Message Tokens API. For example:

import os
import anthropic

os.environ["ANTHROPIC_API_KEY"] = "<your-api-key>"
anthropic.Anthropic().messages.count_tokens(
    model="claude-3-5-sonnet-20241022",
    messages=[
        {"role": "user", "content": "Hello, world"}
    ]
)

As another alternative, you can implement your own token counter method, and pass this using custom_get_token_ids when initializing the model. This will override both the GPT2 and Anthropic tokenizers.

Copy link
Collaborator

@3coins 3coins left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@michaelnchin
Thanks for submitting these changes. A question about the version checks, and a suggestion to use of warnings rather than logger statements.

libs/aws/langchain_aws/utils.py Outdated Show resolved Hide resolved
libs/aws/langchain_aws/utils.py Outdated Show resolved Hide resolved
libs/aws/langchain_aws/chat_models/bedrock.py Outdated Show resolved Hide resolved
@3coins 3coins merged commit 6355b0f into langchain-ai:main Feb 7, 2025
12 checks passed
@michaelnchin michaelnchin deleted the anthropic-tokens-tempfix branch February 7, 2025 21:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

AttributeError: 'Anthropic' object has no attribute 'count_tokens'
2 participants