Tokenization endpoint
Is your feature request related to a problem? Please describe.
For generative models, many are limited by a maximum number of tokens. in some workflows, the prompts are generated dynamically to use as much context as possible by tokenizing the responses first to ensure that they will fit in the context.
Currently, this requires a local tokenization scheme which limits a complete API workflow.
Describe the solution you'd like
backends like transformers and llama.cpp both offer tokenization methods that just tokenize text without generating a response. Attaching these methods to a tokenization api endpoint would be helpful in removing local processing requirements.
Describe alternatives you've considered
Additional context
good point, it should be relatively easy indeed to expose
This is implemented on master:
- Route:
POST /v1/tokenizeregistered atcore/http/routes/localai.go:299 - Handler:
core/http/endpoints/localai/tokenize.go— takes aTokenizeRequestand dispatches tobackend.ModelTokenize - Backends like llama.cpp expose tokenization through the gRPC
Tokenizemethod
The endpoint accepts {"model": "...", "content": "..."} and returns the token IDs, which covers the workflow described in the issue. Probably safe to close. /cc @mudler
I wasn't clear in the OP, and maybe this should be a separate feature request, but a detokenization endpoint is also something I need and intended to be part of this request.
Thanks for the clarification @benniekiss — detokenization isn't there today (no Detokenize RPC in backend/backend.proto, no /v1/detokenize route). Happy to add it; it's a strict mirror of the existing tokenize path.
Proposed shape
- Proto — new RPC in
backend/backend.proto:rpc Detokenize(DetokenizeRequest) returns (DetokenizeResponse) {} message DetokenizeRequest { repeated int32 tokens = 1; } message DetokenizeResponse { string content = 1; } - llama.cpp backend — small handler that calls
common_token_to_pieceper token and concatenates. The existingTokenizeStringalready uses this primitive atbackend/cpp/llama-cpp/grpc-server.cpp:2762, so it's a few lines. - Other backends — default
Unimplemented(same pattern asDetect,Rerank, etc.) until they add support. - Endpoint —
POST /v1/detokenizeatcore/http/endpoints/localai/detokenize.gomirroring the existing tokenize handler. Request{"model": "...", "tokens": [...]}, response{"content": "..."}. - Schema + Go wrapper + route registration following the tokenize template.
@mudler — quick sanity check on the proto change before I sink time? If the shape above looks right I'll open a PR; happy to adjust if you'd prefer e.g. reusing an existing message or a different field name.