Skip to content

Distribute and run LLMs with a single file.

Write documentation for new server

Justine Tunney73b183665b7c
diff --git a/llamafile/server/README.md b/llamafile/server/README.md
new file mode 100644
index 00000000..7bdac5b8
--- /dev/null
+++ b/llamafile/server/README.md
@@ -0,0 +1,7 @@
+# LLaMAfiler
+
+llamafiler is the fastest way to serve embeddings over HTTP. It's a
+brand new server intended to replace the server that came from the
+llama.cpp examples folder that's built into the `llamafile` command.
+
+Please see the [LLaMAfiler Documentation](doc/index.md) for details.
diff --git a/llamafile/server/client.h b/llamafile/server/client.h
index 3b8bc0a2..0b16f642 100644
--- a/llamafile/server/client.h
+++ b/llamafile/server/client.h
@@ -36,6 +36,7 @@
#define HeaderEqualCase(H, S) \
SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H))
+struct TokenizeParams;
struct EmbeddingParams;
struct CompletionParams;
@@ -88,9 +89,11 @@ struct Client
ctl::optional<ctl::string_view> param(ctl::string_view);
bool dispatch() __wur;
- bool tokenize() __wur;
bool dispatcher() __wur;
+ bool tokenize() __wur;
+ bool get_tokenize_params(TokenizeParams*);
+
bool embedding() __wur;
bool get_embedding_params(EmbeddingParams*);
diff --git a/llamafile/server/completion.cpp b/llamafile/server/completion.cpp
index 2086bf41..ad29e023 100644
--- a/llamafile/server/completion.cpp
+++ b/llamafile/server/completion.cpp
@@ -29,6 +29,7 @@
#include "fastjson.h"
#include "json.h"
#include "log.h"
+#include "model.h"
#include "utils.h"
struct CompletionParams
@@ -47,8 +48,6 @@ struct CompletionResponse
bool stop = false;
};
-extern llama_model* g_model;
-
static void
add_token_to_batch(llama_batch& batch,
llama_token id,
@@ -120,10 +119,19 @@ Client::get_completion_params(CompletionParams* params)
ctl::pair<Json::Status, Json> json = Json::parse(payload);
if (json.first != Json::success)
return send_error(400, Json::StatusToString(json.first));
+ if (!json.second.isObject())
+ return send_error(400, "JSON body must be an object");
if (!json.second["prompt"].isString())
return send_error(400, "JSON missing \"prompt\" key");
params->content = ctl::move(json.second["prompt"].getString());
params->prompt = params->content;
+ if (json.second["add_special"].isBool())
+ params->add_special = json.second["add_special"].getBool();
+ if (json.second["parse_special"].isBool())
+ params->parse_special = json.second["parse_special"].getBool();
+ if (json.second["display_special"].isBool())
+ params->display_special =
+ json.second["display_special"].getBool();
} else {
return send_error(501, "Content Type Not Implemented");
}
diff --git a/llamafile/server/doc/embedding.md b/llamafile/server/doc/embedding.md
new file mode 100644
index 00000000..25623be6
--- /dev/null
+++ b/llamafile/server/doc/embedding.md
@@ -0,0 +1,73 @@
+# LLaMAfiler Embedding Endpoint
+
+The `/embedding` endpoint of our HTTP server provides a powerful way to
+transform textual prompts into numerical representations. When you send
+a POST request to this endpoint with a prompt in the request body, it
+utilizes advanced natural language processing techniques to convert the
+text into a high-dimensional vector. This vector, represented as an
+array of floating-point numbers, captures the semantic essence of the
+input prompt. Each float in the array corresponds to a dimension in the
+embedding space, allowing for complex relationships between words and
+concepts to be mathematically represented. These embeddings can be used
+for various downstream tasks such as semantic search, text
+classification, or content recommendation systems.
+
+## Request URIs
+
+- `/embedding`
+
+## Request Methods
+
+- `POST` (recommended)
+- `GET`
+
+## Request Content Types
+
+- `application/x-www-form-urlencoded` may be used to send parameters
+ within the HTTP message body. This is useful for HTML forms.
+
+- `text/plain` in which case the prompt parameter is supplied in the
+ HTTP message body. It must be encoded using UTF-8. Please note the
+ message body is only consulted if the prompt wasn't supplied as an
+ HTTP GET or POST parameter.
+
+- `application/json` in which case the HTTP message body must hold a
+ JSON object, whose keys are the request parameters below. Please note
+ the message body is only consulted if the prompt wasn't supplied as an
+ HTTP GET or POST parameter.
+
+## Request Parameters
+
+- `content` (string) holds the prompt for which embeddings are
+ calculated.
+
+ This parameter may be passed as a GET parameter, e.g.
+ `/embedding?content=orange`. It may be passed as a POST parameter. It
+ may also be passed via a JSON object.
+
+ This prompt is tokenized automatically. Each model has its own context
+ window size that was used during training. The prompt is truncated if
+ it has more tokens than the model supports. Truncation can be detected
+ by checking if the `tokens_used` response parameter is less than
+ `tokens_provided`. The `/tokenize` endpoint may also be used to check
+ beforehand how the model chops up strings and into how many pieces.
+
+- `add_special` (bool; default: true) may be specified to indicate if
+ the tokenizer should insert special tokens automatically. What tokens
+ get inserted, depends on the model architecture. For example,
+ `all-MiniLM-L6-v2` likes to have a `[CLS]` at the beginning of the
+ prompt, and a `[SEP]` token at the end. As such, these token are
+ inserted implicitly by default.
+
+- `parse_special` (bool; default: false) may be specified to indicate
+ that the syntax for special tokens should be parsed in the prompt
+ `content` parameter. For example, `all-MiniLM-L6-v2` defines the
+ special token `[CLS]`. Under normal circumstances, this will be
+ tokenized as literal text, i.e. `[" [", " cl", "s", " ]"]`, but if
+ this parameter is true, then it'll be recognized as a single token.
+
+## See Also
+
+- [LLaMAfiler Documentation Index](index.md)
+- [LLaMAfiler Endpoints Reference](endpoints.md)
+- [LLaMAfiler Technical Details](technical_details.md)
diff --git a/llamafile/server/doc/endpoints.md b/llamafile/server/doc/endpoints.md
new file mode 100644
index 00000000..72da38b2
--- /dev/null
+++ b/llamafile/server/doc/endpoints.md
@@ -0,0 +1,4 @@
+# LLaMAfiler Endpoints Reference
+
+- [`/tokenize`](tokenize.md)
+- [`/embedding`](embedding.md)
diff --git a/llamafile/server/doc/getting_started.md b/llamafile/server/doc/getting_started.md
new file mode 100644
index 00000000..eba1514d
--- /dev/null
+++ b/llamafile/server/doc/getting_started.md
@@ -0,0 +1,77 @@
+# Getting Started with LLaMAfiler
+
+LLaMAfiler is a versatile tool that allows you to serve embeddings from
+a wide range of models. While it's compatible with various architectures
+like Mistral and TinyLLaMA, optimal performance is achieved with models
+specifically designed for embeddings. This guide will walk you through
+the process of setting up and using LLaMAfiler.
+
+## Step 1: Download an Embedding Model
+
+For this guide, we'll use the `all-MiniLM-L6-v2` model, which is
+optimized for embedding tasks. Download it using the following command:
+
+```bash
+wget https://huggingface.co/leliuga/all-MiniLM-L6-v2-GGUF/resolve/main/all-MiniLM-L6-v2.F16.gguf
+```
+
+## Step 2: Install LLaMAfiler
+
+Follow these steps to install the LLaMAfiler software:
+
+```bash
+git clone https://github.com/mozilla-ocho/llamafile
+cd llamafile
+make -j
+sudo make install
+```
+
+## Step 3: Verify Installation
+
+After installation, you can verify that LLaMAfiler is correctly installed by checking its version:
+
+```bash
+$ llamafiler --version
+llamafiler v0.8.9
+```
+
+## Step 4: Launch the Server
+
+To start the LLaMAfiler server on all IPv4 interfaces at port 8080, use the following command:
+
+```bash
+$ llamafiler -m all-MiniLM-L6-v2.F16.gguf -l 0.0.0.0:8080
+```
+
+You should see output similar to this:
+
+```
+2024-07-19T14:51:54.990853 llamafile/server/listen.cpp:33 server listen http://127.0.0.1:8080
+2024-07-19T14:51:54.990859 llamafile/server/listen.cpp:33 server listen http://10.10.10.129:8080
+```
+
+## Step 5: Send Requests
+
+You can now send requests to your LLaMAfiler server using curl. The API is compatible with the original llama.cpp server. Here's an example of how to generate an embedding for the word "orange":
+
+```bash
+curl -s -X POST -H "Content-Type: application/json" \
+ --data '{"content": "orange"}' \
+ http://localhost:8080/embedding
+```
+
+This command will return a JSON object containing the embedding vector for the word "orange".
+
+## Additional Notes
+
+- You can customize the port and interface by modifying the `-l` parameter in the server launch command.
+- LLaMAfiler supports various model architectures. Experiment with different models to find the best fit for your use case.
+- For production environments, consider setting up proper security measures, such as HTTPS and authentication.
+
+Happy embedding with LLaMAfiler!
+
+## See Also
+
+- [LLaMAfiler Documentation Index](index.md)
+- [LLaMAfiler Endpoints Reference](endpoints.md)
+- [LLaMAfiler Technical Details](technical_details.md)
diff --git a/llamafile/server/doc/index.md b/llamafile/server/doc/index.md
new file mode 100644
index 00000000..e86e68ee
--- /dev/null
+++ b/llamafile/server/doc/index.md
@@ -0,0 +1,10 @@
+# LLaMAfiler Documentation
+
+LLaMAfiler is an HTTP server for Large Language Models (LLMs).
+
+## Sections
+
+1. [Getting Started](getting_started.md)
+2. [Endpoints](endpoints.md)
+3. [Technical Details](technical_details.md)
+4. [Source Code](../)
diff --git a/llamafile/server/doc/technical_details.md b/llamafile/server/doc/technical_details.md
new file mode 100644
index 00000000..c8ca1a49
--- /dev/null
+++ b/llamafile/server/doc/technical_details.md
@@ -0,0 +1,133 @@
+# LLaMAfiler Technical Details
+
+LLaMAfiler is designed to be a high-performance server for generating
+embeddings from various language models. This document outlines key
+technical aspects of LLaMAfiler.
+
+## Performance
+
+This server can serve embeddings an order of a magnitude faster than the
+llama.cpp example server. We measured this on Threadripper PRO 7995WX w/
+all-MiniLM-L6-v2 Q6\_K. Using a prompt with 50 tokens this server served
+930 `/embedding` requests per second, whereas llama.cpp/build/bin/server
+built with glibc served 100 per second.
+
+The following wrk script was used:
+
+```lua
+wrk.method = "POST"
+wrk.body = "{\"content\": \"hello world how are you today what is up what is up what is up what is up is up what is up what is up is up what is up what is up is up what is up what is up is up what is up what is up\"}"
+wrk.headers["Content-Type"] = "application/json"
+```
+
+With the following commands:
+
+```
+llamafiler -m /weights/all-MiniLM-L6-v2.Q6_K.gguf
+wrk --latency -t 32 -c 32 -s embedding.lua 'http://127.0.0.1:8080/embedding'
+
+~/llama.cpp/build/bin/server -m /weights/all-MiniLM-L6-v2.Q6_K.gguf --embeddings
+wrk --latency -t 32 -c 32 -s embedding.lua 'http://127.0.0.1:8080/embedding'
+```
+
+The results for llamafiler were:
+
+```
+ Thread Stats Avg Stdev Max +/- Stdev
+ Latency 33.89ms 7.48ms 61.55ms 66.90%
+ Req/Sec 29.26 6.52 50.00 59.74%
+ Latency Distribution
+ 50% 33.31ms
+ 75% 38.76ms
+ 90% 43.76ms
+ 99% 53.31ms
+ 1592 requests in 1.70s, 8.26MB read
+Requests/sec: 934.80
+Transfer/sec: 4.85MB
+```
+
+The results for llama.cpp were:
+
+```
+ Thread Stats Avg Stdev Max +/- Stdev
+ Latency 262.34ms 75.10ms 322.91ms 82.80%
+ Req/Sec 3.73 1.88 10.00 93.55%
+ Latency Distribution
+ 50% 281.00ms
+ 75% 321.60ms
+ 90% 322.32ms
+ 99% 322.91ms
+ 93 requests in 901.53ms, 748.74KB read
+Requests/sec: 103.16
+Transfer/sec: 830.53KB
+```
+
+It's possible to make the llama.cpp server go faster, by passing the
+`-np 10` flag. This will preallocate ten server slots which allow
+requests to be handled in parallel. However doing this boosted the
+performance to no more than 200 requests per second. Specifying higher
+values, e.g. `-np 50` causes the llama.cpp to crash.
+
+For less computationally intensive endpoints, such as `/tokenize`,
+llamafiler on Threadripper PRO 7995WX is able to serve 3.3 million
+requests per second.
+
+```
+wrk --latency -t $(nproc) -c $(nproc) 'http://127.0.0.1:8080/tokenize?prompt=hello+world+how+are+you+today+what+is+up+what+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up'
+Running 10s test @ http://127.0.0.1:8080/tokenize?prompt=hello+world+how+are+you+today+what+is+up+what+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up+is+up+what+is+up+what+is+up
+ 192 threads and 192 connections
+ Thread Stats Avg Stdev Max +/- Stdev
+ Latency 56.46us 11.03us 3.69ms 97.53%
+ Req/Sec 17.36k 1.05k 25.48k 95.69%
+ Latency Distribution
+ 50% 56.00us
+ 75% 58.00us
+ 90% 59.00us
+ 99% 66.00us
+ 4971957 requests in 1.50s, 4.32GB read
+Requests/sec: 3316068.33
+Transfer/sec: 2.88GB
+```
+
+## Cancelation
+
+LLaMAfiler uses `pthread_cancel()` to asynchronously cancel requests
+when appropriate. The server is designed this way so that high-priority
+or latency-sensitive requests can preempt batch background jobs.
+
+For example, we intend to implement an HTTP header that will allow a
+client to elect the priority of its request. For low-priority requests,
+if a higher priority job happens to come in, the low-priority job can be
+canceled in less than a millisecond, even if it's inside a deep,
+long-running matrix multiplication operation. This will not leak memory.
+It ensures that resources are freed up immediately for the other job.
+
+Cancelation is also useful for DDoS mitigation. The `-w N` flag allows
+you to specify a fixed number of HTTP workers. By default, this will be
+set to the number of CPU cores multiplied by two. HTTP clients are
+permitted to idle (via the HTTP keep-alive mechanism) as long as they
+wish. However, if the number of available workers runs out when a new
+request comes in, the oldest worker will be canceled to make room.
+
+When a cancelation happens, HTTP connections in the idle state will
+simply be closed. If an HTTP connection is in the middle of serving a
+request, then a 503 Service Unavailable response will be sent to the
+client. In such cases, it is recommended that client software retry with
+exponential backoff. If multiple instances of LLaMAfiler are running on
+multiple servers, then failover strategies can also be used.
+
+## Crash Proofing
+
+LLaMAfiler is designed to be impossible to crash. Let's say there's a
+bug in llama.cpp or LLaMAfiler that causes a SIGSEGV to happen while
+processing a request. In that case, the worker thread will be canceled
+and a backtrace will be logged. A fresh new worker thread will then be
+spawned to take its place.
+
+Each thread is given a stack size of 81KB, which includes the guard
+page. Stack overflows are reported and recoverable with a backtrace,
+thanks to `sigaltstack()`.
+
+Recovering from a crash should not leak memory. For this reason, certain
+kinds of crashes aren't recoverable. If the heap becomes corrupted, then
+the entire process will crash.
diff --git a/llamafile/server/doc/tokenize.md b/llamafile/server/doc/tokenize.md
new file mode 100644
index 00000000..6f085632
--- /dev/null
+++ b/llamafile/server/doc/tokenize.md
@@ -0,0 +1,64 @@
+# LLaMAfiler Tokenization Endpoint
+
+The LLaMAfiler Tokenization Endpoint provides a robust interface for
+converting text prompts into tokens, a crucial preprocessing step for
+many natural language processing tasks. This endpoint supports flexible
+input methods, including GET and POST requests, with various content
+types to accommodate different integration needs. Users can customize
+the tokenization process through parameters such as `add_special` and
+`parse_special`, allowing for fine-tuned control over the output.
+Whether you're building a chatbot, developing a text analysis tool, or
+working on any NLP project, this endpoint offers a convenient and
+powerful way to tokenize your text data.
+
+## Request URIs
+
+- `/tokenize`
+
+## Request Methods
+
+- `GET`
+- `POST`
+
+## Request Content Types
+
+- `application/x-www-form-urlencoded` may be used to send parameters
+ within the HTTP message body. This is useful for HTML forms.
+
+- `text/plain` in which case the prompt parameter is supplied in the
+ HTTP message body. It must be encoded using UTF-8. Please note the
+ message body is only consulted if the prompt wasn't supplied as an
+ HTTP GET or POST parameter.
+
+- `application/json` in which case the HTTP message body must hold a
+ JSON object, whose keys are the request parameters below. Please note
+ the message body is only consulted if the prompt wasn't supplied as an
+ HTTP GET or POST parameter.
+
+## Request Parameters
+
+- `prompt` (string) holds the prompt which will be tokenized.
+
+ This parameter may be passed as a GET parameter, e.g.
+ `/tokenize?prompt=orange`. It may be passed as a POST parameter. It
+ may also be passed via a JSON object.
+
+- `add_special` (bool; default: true) may be specified to indicate if
+ the tokenizer should insert special tokens automatically. What tokens
+ get inserted, depends on the model architecture. For example,
+ `all-MiniLM-L6-v2` likes to have a `[CLS]` at the beginning of the
+ prompt, and a `[SEP]` token at the end. As such, these token are
+ inserted implicitly by default.
+
+- `parse_special` (bool; default: false) may be specified to indicate
+ that the syntax for special tokens should be parsed in the `prompt`
+ parameter. For example, `all-MiniLM-L6-v2` defines the special token
+ `[CLS]`. Under normal circumstances, this will be tokenized as literal
+ text, i.e. `[" [", " cl", "s", " ]"]`, but if this parameter is true,
+ then it'll be recognized as a single token.
+
+## See Also
+
+- [LLaMAfiler Documentation Index](index.md)
+- [LLaMAfiler Endpoints Reference](endpoints.md)
+- [LLaMAfiler Technical Details](technical_details.md)
diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cpp
index 311439c6..c2b42c8a 100644
--- a/llamafile/server/embedding.cpp
+++ b/llamafile/server/embedding.cpp
@@ -28,6 +28,7 @@
#include "fastjson.h"
#include "json.h"
#include "log.h"
+#include "model.h"
#include "utils.h"
struct EmbeddingParams
@@ -38,8 +39,6 @@ struct EmbeddingParams
ctl::string content;
};
-extern llama_model* g_model;
-
void
normalize_embeddings(const float* inp, float* out, int n)
{
@@ -79,15 +78,7 @@ Client::get_embedding_params(EmbeddingParams* params)
{
params->add_special = atob(or_empty(param("add_special")), true);
params->parse_special = atob(or_empty(param("parse_special")), false);
-
- // get prompt
- //
- // 1. Allow GET "/tokenize?prompt=foo"
- // 2. Allow POST {"content": "foo"} (application/json)
- // 3. Allow POST "prompt=foo" (application/x-www-form-urlencoded)
- // 3. Allow POST "foo" (text/plain)
- //
- ctl::optional<ctl::string_view> prompt = param("prompt");
+ ctl::optional<ctl::string_view> prompt = param("content");
if (prompt.has_value()) {
params->prompt = prompt.value();
} else if (HasHeader(kHttpContentType)) {
@@ -101,10 +92,16 @@ Client::get_embedding_params(EmbeddingParams* params)
ctl::pair<Json::Status, Json> json = Json::parse(payload);
if (json.first != Json::success)
return send_error(400, Json::StatusToString(json.first));
+ if (!json.second.isObject())
+ return send_error(400, "JSON body must be an object");
if (!json.second["content"].isString())
return send_error(400, "JSON missing \"content\" key");
params->content = ctl::move(json.second["content"].getString());
params->prompt = params->content;
+ if (json.second["add_special"].isBool())
+ params->add_special = json.second["add_special"].getBool();
+ if (json.second["parse_special"].isBool())
+ params->parse_special = json.second["parse_special"].getBool();
} else {
return send_error(501, "Content Type Not Implemented");
}
diff --git a/llamafile/server/main.cpp b/llamafile/server/main.cpp
index 7164ea0b..1740cb55 100644
--- a/llamafile/server/main.cpp
+++ b/llamafile/server/main.cpp
@@ -23,6 +23,7 @@
#include "llamafile/version.h"
#include "log.h"
+#include "model.h"
#include "server.h"
#include "signals.h"
#include "time.h"
diff --git a/llamafile/server/model.h b/llamafile/server/model.h
new file mode 100644
index 00000000..ee57c88d
--- /dev/null
+++ b/llamafile/server/model.h
@@ -0,0 +1,21 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// Copyright 2024 Mozilla Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+#include "llama.cpp/llama.h"
+
+extern llama_model* g_model;
diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cpp
index 71f5dd37..d6ee4da9 100644
--- a/llamafile/server/tokenize.cpp
+++ b/llamafile/server/tokenize.cpp
@@ -17,6 +17,7 @@
#include "client.h"
+#include <ctl/pair.h>
#include <ctl/vector.h>
#include <string.h>
#include <sys/resource.h>
@@ -25,40 +26,78 @@
#include "cleanup.h"
#include "fastjson.h"
+#include "json.h"
#include "log.h"
+#include "model.h"
#include "signals.h"
#include "utils.h"
-bool
-Client::tokenize()
+struct TokenizeParams
{
- if (msg.method != kHttpGet && msg.method != kHttpPost)
- return send_error(405);
+ bool add_special;
+ bool parse_special;
+ ctl::string_view prompt;
+ ctl::string content;
+};
- if (!read_payload())
- return false;
+void
+cleanup_tokenize_params(void* arg)
+{
+ delete (TokenizeParams*)arg;
+}
- // get prompt
- //
- // 1. Allow GET "/tokenize?prompt=foo"
- // 2. Allow POST "prompt=foo" (application/x-www-form-urlencoded)
- // 3. Allow POST "foo" (text/plain)
- //
- ctl::string_view input;
+bool
+Client::get_tokenize_params(TokenizeParams* params)
+{
+ params->add_special = atob(or_empty(param("add_special")), true);
+ params->parse_special = atob(or_empty(param("parse_special")), false);
ctl::optional<ctl::string_view> prompt = param("prompt");
if (prompt.has_value()) {
- input = prompt.value();
+ params->prompt = prompt.value();
} else if (HasHeader(kHttpContentType)) {
if (IsMimeType(HeaderData(kHttpContentType),
HeaderLength(kHttpContentType),
"text/plain")) {
- input = payload;
+ params->prompt = payload;
+ } else if (IsMimeType(HeaderData(kHttpContentType),
+ HeaderLength(kHttpContentType),
+ "application/json")) {
+ ctl::pair<Json::Status, Json> json = Json::parse(payload);
+ if (json.first != Json::success)
+ return send_error(400, Json::StatusToString(json.first));
+ if (!json.second.isObject())
+ return send_error(400, "JSON body must be an object");
+ if (!json.second["prompt"].isString())
+ return send_error(400, "JSON missing \"prompt\" key");
+ params->content = ctl::move(json.second["prompt"].getString());
+ params->prompt = params->content;
+ if (json.second["add_special"].isBool())
+ params->add_special = json.second["add_special"].getBool();
+ if (json.second["parse_special"].isBool())
+ params->parse_special = json.second["parse_special"].getBool();
} else {
return send_error(501, "Content Type Not Implemented");
}
} else {
- input = payload;
+ params->prompt = payload;
}
+ return true;
+}
+
+bool
+Client::tokenize()
+{
+ if (msg.method != kHttpGet && msg.method != kHttpPost)
+ return send_error(405);
+
+ if (!read_payload())
+ return false;
+
+ // get parameters
+ auto params = new TokenizeParams;
+ defer_cleanup(cleanup_tokenize_params, params);
+ if (!get_tokenize_params(params))
+ return false;
// get optional parameters
bool add_special = atob(or_empty(param("add_special")), true);
@@ -70,19 +109,17 @@ Client::tokenize()
timespec started = timespec_real();
// turn text into tokens
- extern llama_model* g_model;
- int maxcount = input.size() + 16;
- auto toks = new ctl::vector<llama_token>(maxcount);
+ auto toks = new ctl::vector<llama_token>(params->prompt.size() + 16);
defer_cleanup(cleanup_token_vector, toks);
int count = llama_tokenize(g_model,
- input.data(),
- input.size(),
+ params->prompt.data(),
+ params->prompt.size(),
&(*toks)[0],
- maxcount,
- add_special,
- parse_special);
+ toks->size(),
+ params->add_special,
+ params->parse_special);
if (count < 0) {
- SLOG("failed to tokenize");
+ SLOG("llama_tokenize failed");
return send_error(405);
}
toks->resize(count);