From c1ac54b77aaba10d029084d152be786102010eb2 Mon Sep 17 00:00:00 2001 From: Bruce MacDonald Date: Sat, 26 Aug 2023 16:11:45 -0700 Subject: [PATCH] server : add `/detokenize` endpoint (#2802) * Add a /detokenize endpoint to the example server * remove trailing white-space --- examples/server/README.md | 6 ++++++ examples/server/server.cpp | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/examples/server/README.md b/examples/server/README.md index 7105e9020..517608046 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -164,6 +164,12 @@ node index.js Note that the special `BOS` token is not added in front of the text and also a space character is not inserted automatically as it is for `/completion`. +- **POST** `/detokenize`: Convert tokens to text. + + *Options:* + + `tokens`: Set the tokens to detokenize. + - **POST** `/embedding`: Generate embedding of a given text just as [the embedding example](../embedding) does. *Options:* diff --git a/examples/server/server.cpp b/examples/server/server.cpp index 3300553f9..a4b4d6418 100644 --- a/examples/server/server.cpp +++ b/examples/server/server.cpp @@ -1104,6 +1104,12 @@ static json format_tokenizer_response(const std::vector &tokens) {"tokens", tokens}}; } +static json format_detokenized_response(std::string content) +{ + return json{ + {"content", content}}; +} + template static T json_value(const json &body, const std::string &key, const T &default_value) { @@ -1501,6 +1507,21 @@ int main(int argc, char **argv) const json data = format_tokenizer_response(tokens); return res.set_content(data.dump(), "application/json"); }); + svr.Post("/detokenize", [&llama](const Request &req, Response &res) + { + auto lock = llama.lock(); + + const json body = json::parse(req.body); + std::string content; + if (body.count("tokens") != 0) + { + const std::vector tokens = body["tokens"]; + content = tokens_to_str(llama.ctx, tokens.cbegin(), tokens.cend()); + } + + const json data = format_detokenized_response(content); + return res.set_content(data.dump(), "application/json"); }); + svr.Post("/embedding", [&llama](const Request &req, Response &res) { auto lock = llama.lock();