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

Add tokenize detokenize compatibility #383

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ python3 examples/<example>.py
- [structured-outputs-image.py](structured-outputs-image.py)


### Tokenization - Tokenize and detokenize text with a model
- [tokenization.py](tokenization.py)


### Ollama List - List all downloaded models and their properties
- [list.py](list.py)

Expand Down
10 changes: 10 additions & 0 deletions examples/tokenization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import ollama

# Get tokens from a model
response = ollama.tokenize(model='llama3.2', text='Why the sky is blue?')
tokens = response.tokens
print('Tokens from model', tokens)

# Convert tokens back to text
response = ollama.detokenize(model='llama3.2', tokens=tokens)
print('Text from tokens', response.text) # Prints: Why the sky is blue?
6 changes: 6 additions & 0 deletions ollama/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
ListResponse,
ShowResponse,
ProcessResponse,
TokenizeResponse,
DetokenizeResponse,
RequestError,
ResponseError,
)
Expand All @@ -31,6 +33,8 @@
'ListResponse',
'ShowResponse',
'ProcessResponse',
'TokenizeResponse',
'DetokenizeResponse',
'RequestError',
'ResponseError',
]
Expand All @@ -49,3 +53,5 @@
copy = _client.copy
show = _client.show
ps = _client.ps
tokenize = _client.tokenize
detokenize = _client.detokenize
48 changes: 48 additions & 0 deletions ollama/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
CreateRequest,
CopyRequest,
DeleteRequest,
DetokenizeRequest,
DetokenizeResponse,
EmbedRequest,
EmbedResponse,
EmbeddingsRequest,
Expand All @@ -67,6 +69,8 @@
ShowRequest,
ShowResponse,
StatusResponse,
TokenizeRequest,
TokenizeResponse,
Tool,
)

Expand Down Expand Up @@ -611,6 +615,28 @@ def ps(self) -> ProcessResponse:
'/api/ps',
)

def tokenize(self, model: str, text: str) -> TokenizeResponse:
return self._request(
TokenizeResponse,
'POST',
'/api/tokenize',
json=TokenizeRequest(
model=model,
text=text,
).model_dump(exclude_none=True),
)

def detokenize(self, model: str, tokens: Sequence[int]) -> DetokenizeResponse:
return self._request(
DetokenizeResponse,
'POST',
'/api/detokenize',
json=DetokenizeRequest(
model=model,
tokens=tokens,
).model_dump(exclude_none=True),
)


class AsyncClient(BaseClient):
def __init__(self, host: Optional[str] = None, **kwargs) -> None:
Expand Down Expand Up @@ -1120,6 +1146,28 @@ async def ps(self) -> ProcessResponse:
'/api/ps',
)

async def tokenize(self, model: str, text: str) -> TokenizeResponse:
return await self._request(
TokenizeResponse,
'POST',
'/api/tokenize',
json=TokenizeRequest(
model=model,
text=text,
).model_dump(exclude_none=True),
)

async def detokenize(self, model: str, tokens: Sequence[int]) -> DetokenizeResponse:
return await self._request(
DetokenizeResponse,
'POST',
'/api/detokenize',
json=DetokenizeRequest(
model=model,
tokens=tokens,
).model_dump(exclude_none=True),
)


def _copy_messages(messages: Optional[Sequence[Union[Mapping[str, Any], Message]]]) -> Iterator[Message]:
for message in messages or []:
Expand Down
18 changes: 18 additions & 0 deletions ollama/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,24 @@ class Model(SubscriptableBaseModel):
models: Sequence[Model]


class TokenizeRequest(BaseRequest):
model: str
text: str


class TokenizeResponse(BaseGenerateResponse):
tokens: Sequence[int]


class DetokenizeRequest(BaseRequest):
model: str
tokens: Sequence[int]


class DetokenizeResponse(BaseGenerateResponse):
text: str


class RequestError(Exception):
"""
Common class for request errors.
Expand Down
24 changes: 24 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1260,3 +1260,27 @@ def test_tool_validation():
with pytest.raises(ValidationError):
invalid_tool = {'type': 'invalid_type', 'function': {'name': 'test'}}
list(_copy_tools([invalid_tool]))


def test_client_tokenize(httpserver: HTTPServer):
httpserver.expect_ordered_request(
'/api/tokenize',
method='POST',
json={'model': 'dummy', 'text': 'Hello world!'},
).respond_with_json({'tokens': [1, 2, 3]})

client = Client(httpserver.url_for('/'))
response = client.tokenize('dummy', 'Hello world!')
assert response.tokens == [1, 2, 3]


def test_client_detokenize(httpserver: HTTPServer):
httpserver.expect_ordered_request(
'/api/detokenize',
method='POST',
json={'model': 'dummy', 'tokens': [1, 2, 3]},
).respond_with_json({'text': 'Hello world!'})

client = Client(httpserver.url_for('/'))
response = client.detokenize('dummy', [1, 2, 3])
assert response.text == 'Hello world!'
Loading