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(tokens): incorrect caching of async tokenizer #47

Merged
merged 2 commits into from
Jun 29, 2023
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
32 changes: 26 additions & 6 deletions examples/tokens.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
#!/usr/bin/env poetry run python

from anthropic import Anthropic
import asyncio

client = Anthropic()
from anthropic import Anthropic, AsyncAnthropic

text = "hello world!"

tokens = client.count_tokens(text)
print(f"'{text}' is {tokens} tokens")
def sync_tokens() -> None:
client = Anthropic()

assert tokens == 3
text = "hello world!"

tokens = client.count_tokens(text)
print(f"'{text}' is {tokens} tokens")

assert tokens == 3


async def async_tokens() -> None:
anthropic = AsyncAnthropic()

text = "fist message"
tokens = await anthropic.count_tokens(text)
print(f"'{text}' is {tokens} tokens")

text = "second message"
tokens = await anthropic.count_tokens(text)
print(f"'{text}' is {tokens} tokens")


sync_tokens()
asyncio.run(async_tokens())
26 changes: 21 additions & 5 deletions src/anthropic/_tokenizers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from typing import cast
from pathlib import Path
from functools import lru_cache

from anyio import Path as AsyncPath

Expand All @@ -13,15 +15,29 @@ def _get_tokenizer_cache_path() -> Path:
return Path(__file__).parent / "tokenizer.json"


@lru_cache(maxsize=None)
_tokenizer: Tokenizer | None = None


def _load_tokenizer(raw: str) -> Tokenizer:
global _tokenizer

_tokenizer = cast(Tokenizer, Tokenizer.from_str(raw))
return _tokenizer


def sync_get_tokenizer() -> Tokenizer:
if _tokenizer is not None:
return _tokenizer

tokenizer_path = _get_tokenizer_cache_path()
text = tokenizer_path.read_text()
return Tokenizer.from_str(text)
return _load_tokenizer(text)


@lru_cache(maxsize=None)
async def async_get_tokenizer() -> Tokenizer:
if _tokenizer is not None:
return _tokenizer

tokenizer_path = AsyncPath(_get_tokenizer_cache_path())
text = await tokenizer_path.read_text()
return Tokenizer.from_str(text)
return _load_tokenizer(text)