Skip to content

Conversation

@nathan-gage
Copy link
Contributor

Closes #3429

AFAIK, bedrock client does not support count_tokens, so I have to raise a UserError in that case.

@nathan-gage nathan-gage force-pushed the anthropic-count-tokens branch from 338b3d1 to b9f3094 Compare November 17, 2025 22:38
nathan-gage and others added 2 commits November 17, 2025 17:46
Add comprehensive test coverage for the Anthropic `count_tokens` implementation:

- test_anthropic_model_usage_limit_exceeded: Verifies UsageLimitExceeded is raised when input_tokens_limit would be exceeded (18 < 19 tokens)
- test_anthropic_model_usage_limit_not_exceeded: Tests successful execution when within token limits (25 > 19 tokens)
- test_anthropic_count_tokens_error: Tests ModelHTTPError handling for invalid model names (404 response)

Tests follow the same pattern as Bedrock's count_tokens tests, using the standard "quick brown fox" prompt which tokenizes to 19 input tokens with Anthropic's tokenizer.

All tests include VCR cassettes for the `/v1/messages/count_tokens?beta=true` API endpoint.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@nathan-gage nathan-gage force-pushed the anthropic-count-tokens branch from b9f3094 to 8f47956 Compare November 17, 2025 22:46
@nathan-gage
Copy link
Contributor Author

nathan-gage commented Nov 17, 2025

It's my first time using the cassette/vcr for tests, so would love some feedback on if I got that part right.

@nathan-gage nathan-gage changed the title Anthropic token counting Implement AnthropicModel count_tokens Nov 17, 2025
@nathan-gage nathan-gage changed the title Implement AnthropicModel count_tokens Add AnthropicModel count_tokens Nov 17, 2025
@DouweM
Copy link
Collaborator

DouweM commented Nov 17, 2025

@nathan-gage Looks great, thanks Nathan!

@DouweM DouweM merged commit 80a1ce0 into pydantic:main Nov 17, 2025
30 checks passed
@nathan-gage nathan-gage deleted the anthropic-count-tokens branch November 17, 2025 23:37
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.

Add Anthropic token counting

2 participants