Skip to content

Distribute and run LLMs with a single file.

Add /v1/chat/completions endpoint to llamafiler

Justine Tunney006f7437eedc
diff --git a/llama.cpp/common.cpp b/llama.cpp/common.cpp
index 80be6440..1cff40f8 100644
--- a/llama.cpp/common.cpp
+++ b/llama.cpp/common.cpp
@@ -383,7 +383,7 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
}
if (arg == "-c" || arg == "--ctx-size") {
CHECK_ARG
- params.n_ctx = std::stoi(argv[i]);
+ FLAG_ctx_size = params.n_ctx = std::stoi(argv[i]);
return true;
}
if (arg == "--grp-attn-n" || arg == "-gan") {
@@ -1060,7 +1060,7 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
}
if (arg == "-j" || arg == "--json-schema") {
CHECK_ARG
- sparams.grammar = json_schema_to_grammar(json::parse(argv[i]));
+ sparams.grammar = json_schema_string_to_grammar(argv[i]);
return true;
}
if (arg == "--override-kv") {
@@ -3256,3 +3256,7 @@ void yaml_dump_non_result_info(FILE * stream, const gpt_params & params, const l
fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
fprintf(stream, "display_prompt: %s # default: true\n", params.display_prompt ? "true" : "false");
}
+
+std::string json_schema_string_to_grammar(const std::string_view& schema) {
+ return json_schema_to_grammar(json::parse(schema));
+}
diff --git a/llama.cpp/common.h b/llama.cpp/common.h
index 118bd301..181ebaf2 100644
--- a/llama.cpp/common.h
+++ b/llama.cpp/common.h
@@ -466,3 +466,9 @@ void yaml_dump_string_multiline(FILE * stream, const char * prop_name, const cha
void yaml_dump_non_result_info(
FILE * stream, const gpt_params & params, const llama_context * lctx,
const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc);
+
+//
+// JSON utils
+//
+
+std::string json_schema_string_to_grammar(const std::string_view& schema); // [jart]
diff --git a/llamafile/ansiblas.h b/llamafile/ansiblas.h
index 38f5bf2b..6e935778 100644
--- a/llamafile/ansiblas.h
+++ b/llamafile/ansiblas.h
@@ -27,7 +27,7 @@ namespace ansiBLAS {
static constexpr int KN = 8;
-union alignas(64) Vector {
+union Vector {
double v[KN];
};
diff --git a/llamafile/chatbot.cpp b/llamafile/chatbot.cpp
index 0a03f07e..855d45f7 100644
--- a/llamafile/chatbot.cpp
+++ b/llamafile/chatbot.cpp
@@ -33,6 +33,7 @@
#include "llamafile/compute.h"
#include "llamafile/highlight.h"
#include "llamafile/llamafile.h"
+#include "llamafile/string.h"
#define RESET "\e[0m"
#define BOLD "\e[1m"
@@ -152,21 +153,6 @@ static std::string basename(const std::string_view path) {
}
}
-__attribute__((format(printf, 1, 2))) static std::string format(const char *fmt, ...) {
- va_list ap, ap2;
- va_start(ap, fmt);
- va_copy(ap2, ap);
- int size = 512;
- std::string res(size, '\0');
- int need = vsnprintf(res.data(), size, fmt, ap);
- res.resize(need + 1, '\0');
- if (need + 1 > size)
- vsnprintf(res.data(), need + 1, fmt, ap2);
- va_end(ap2);
- va_end(ap);
- return res;
-}
-
static std::string join(const std::vector<std::string> &vec, const std::string_view &delim) {
std::string result;
for (size_t i = 0; i < vec.size(); i++) {
@@ -462,7 +448,7 @@ static void eval_tokens(std::vector<llama_token> tokens, int n_batch) {
}
for (int i = 0; i < N; i += n_batch) {
if (N > n_batch)
- print_ephemeral(format("loading prompt %d%%...", (int)((double)i / N * 100)));
+ print_ephemeral(lf::format("loading prompt %d%%...", (int)((double)i / N * 100)));
int n_eval = (int)tokens.size() - i;
if (n_eval > n_batch)
n_eval = n_batch;
@@ -480,12 +466,12 @@ static void eval_id(int id) {
}
static void eval_string(const std::string &str, int n_batch, bool add_special, bool parse_special) {
- eval_tokens(llama_tokenize(g_ctx, str, add_special, parse_special), n_batch);
+ eval_tokens(llama_tokenize(g_model, str, add_special, parse_special), n_batch);
}
static void on_server_listening(const char *host, int port) {
pthread_mutex_lock(&g_lock);
- g_listen_url = format("http://%s:%d/", host, port);
+ g_listen_url = lf::format("http://%s:%d/", host, port);
pthread_cond_signal(&g_cond);
pthread_mutex_unlock(&g_lock);
}
diff --git a/llamafile/flags.cpp b/llamafile/flags.cpp
index a65af6f7..5efdb83f 100644
--- a/llamafile/flags.cpp
+++ b/llamafile/flags.cpp
@@ -47,13 +47,13 @@ bool FLAG_unsecure = false;
const char *FLAG_file = nullptr;
const char *FLAG_ip_header = nullptr;
const char *FLAG_listen = "0.0.0.0:8080";
-const char *FLAG_url_prefix = nullptr;
const char *FLAG_model = nullptr;
const char *FLAG_prompt = nullptr;
+const char *FLAG_url_prefix = nullptr;
double FLAG_token_rate = 1;
float FLAG_temp = 0.8;
int FLAG_batch = 2048;
-int FLAG_ctx = 512;
+int FLAG_ctx_size = 8192;
int FLAG_flash_attn = false;
int FLAG_gpu = 0;
int FLAG_http_ibuf_size = 1024 * 1024;
@@ -235,6 +235,13 @@ void llamafile_get_flags(int argc, char **argv) {
//////////////////////////////////////////////////////////////////////
// model flags
+ if (!strcmp(flag, "-c") || !strcmp(flag, "--ctx-size")) {
+ if (i == argc)
+ missing("--ctx-size");
+ FLAG_ctx_size = atoi(argv[i++]);
+ continue;
+ }
+
if (!strcmp(flag, "-m") || !strcmp(flag, "--model")) {
if (i == argc)
missing("--model");
diff --git a/llamafile/high.cpp b/llamafile/high.cpp
index 3fe1cd0c..a13d3fcd 100644
--- a/llamafile/high.cpp
+++ b/llamafile/high.cpp
@@ -26,28 +26,6 @@
// syntax highlighter demo
-static std::string basename(const std::string_view path) {
- size_t i, e;
- if ((e = path.size())) {
- while (e > 1 && path[e - 1] == '/')
- --e;
- i = e - 1;
- while (i && path[i - 1] != '/')
- --i;
- return std::string(path.substr(i, e - i));
- } else {
- return ".";
- }
-}
-
-static std::string extname(const std::string_view path) {
- std::string name = basename(path);
- size_t dot_pos = name.find_last_of('.');
- if (dot_pos == std::string::npos || dot_pos == name.length() - 1)
- return name;
- return std::string(name.substr(dot_pos + 1));
-}
-
static void highlight(int infd, int outfd, const char *lang, const char *inpath) {
// create syntax highlighter
Highlight *h;
@@ -55,7 +33,7 @@ static void highlight(int infd, int outfd, const char *lang, const char *inpath)
if (lang) {
h = Highlight::create(lang);
} else if (inpath) {
- if (!(h = Highlight::create(tolower(extname(inpath)))))
+ if (!(h = Highlight::create(lf::tolower(lf::extname(inpath)))))
h = new HighlightMarkdown;
} else {
h = Highlight::create("markdown");
diff --git a/llamafile/highlight_asm.cpp b/llamafile/highlight_asm.cpp
index be7482e5..ee520700 100644
--- a/llamafile/highlight_asm.cpp
+++ b/llamafile/highlight_asm.cpp
@@ -119,14 +119,14 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
c == '_' || //
(c == '#' && col_ == 0)) {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
break;
} else if (c == '#' && col_ && isspace(last_)) {
t_ = HASH;
} else if ((c == ';' || c == '!') && (!col_ || isspace(last_))) {
t_ = COMMENT;
*r += HI_COMMENT;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (c == '/' && col_ == 0) {
// bell system five allowed single slash comments
// anywhere on the line, but we limit that a bit.
@@ -163,7 +163,7 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
is_first_thing_on_line_ = false;
if (c == ':')
is_first_thing_on_line_ = true;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
@@ -180,9 +180,9 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
Immediate:
case IMMEDIATE:
if (is_immediate(c)) {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (c == '\'') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = IMMEDIATE_QUOTE;
} else {
*r += HI_RESET;
@@ -193,26 +193,26 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
case IMMEDIATE_QUOTE:
if (c == '\\') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = IMMEDIATE_QUOTE_BACKSLASH;
} else if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
goto Normal;
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = IMMEDIATE_QUOTE_FINISH;
}
break;
case IMMEDIATE_QUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = IMMEDIATE_QUOTE_FINISH;
break;
case IMMEDIATE_QUOTE_FINISH:
if (c == '\'') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = IMMEDIATE;
} else {
// yes '" means '"' in bell system five
@@ -222,7 +222,7 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
break;
case BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
break;
@@ -241,7 +241,7 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
case WORD:
if (!isascii(c) || isalnum(c) || c == '$' || c == '_' || c == '-' || c == '.') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_first_thing_on_line_) {
if (word_.size() > 1 && word_[0] == '#' &&
@@ -303,7 +303,7 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
case REG:
if (isalnum(c)) {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
*r += HI_RESET;
t_ = NORMAL;
@@ -368,13 +368,13 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
break;
case SLASH_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '*')
t_ = SLASH_STAR_STAR;
break;
case SLASH_STAR_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '/') {
*r += HI_RESET;
t_ = NORMAL;
@@ -386,7 +386,7 @@ void HighlightAsm::feed(std::string *r, std::string_view input) {
Comment:
case COMMENT:
case SLASH_SLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
diff --git a/llamafile/highlight_basic.cpp b/llamafile/highlight_basic.cpp
index 65fa2292..830ac824 100644
--- a/llamafile/highlight_basic.cpp
+++ b/llamafile/highlight_basic.cpp
@@ -81,7 +81,7 @@ void HighlightBasic::feed(std::string *r, std::string_view input) {
word_ += c;
} else {
if (is_keyword_basic(word_.data(), word_.size())) {
- if (tolower(word_) == "rem") {
+ if (lf::tolower(word_) == "rem") {
*r += HI_COMMENT;
*r += word_;
t_ = COMMENT;
@@ -159,7 +159,7 @@ void HighlightBasic::flush(std::string *r) {
switch (t_) {
case WORD:
if (is_keyword_basic(word_.data(), word_.size())) {
- if (tolower(word_) == "rem") {
+ if (lf::tolower(word_) == "rem") {
*r += HI_KEYWORD;
*r += word_;
*r += HI_RESET;
diff --git a/llamafile/highlight_js.cpp b/llamafile/highlight_js.cpp
index f9ce7a85..93661962 100644
--- a/llamafile/highlight_js.cpp
+++ b/llamafile/highlight_js.cpp
@@ -93,42 +93,42 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '/') {
t_ = SLASH;
} else if (c == '\'') {
t_ = QUOTE;
*r += HI_STRING;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
expect_ = EXPECT_OPERATOR;
} else if (c == '"') {
t_ = DQUOTE;
*r += HI_STRING;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
expect_ = EXPECT_OPERATOR;
} else if (c == '`') {
t_ = TICK;
*r += HI_STRING;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
expect_ = EXPECT_OPERATOR;
} else if (c == ')' || c == '}' || c == ']') {
expect_ = EXPECT_OPERATOR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (ispunct(c)) {
expect_ = EXPECT_VALUE;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (isdigit(c)) {
expect_ = EXPECT_OPERATOR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
Word:
case WORD:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_js(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -168,7 +168,7 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
expect_ = EXPECT_OPERATOR;
*r += HI_STRING;
*r += '/';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\\') {
t_ = REGEX_BACKSLASH;
} else if (c == '[') {
@@ -184,7 +184,7 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case SLASH_SLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (is_line_terminator(c)) {
*r += HI_RESET;
t_ = NORMAL;
@@ -192,13 +192,13 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case SLASH_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '*')
t_ = SLASH_STAR_STAR;
break;
case SLASH_STAR_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '/') {
*r += HI_RESET;
t_ = NORMAL;
@@ -208,7 +208,7 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case QUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'') {
*r += HI_RESET;
t_ = NORMAL;
@@ -218,12 +218,12 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case QUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = QUOTE;
break;
case DQUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
*r += HI_RESET;
t_ = NORMAL;
@@ -233,12 +233,12 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case DQUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE;
break;
case TICK:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '`') {
*r += HI_RESET;
t_ = NORMAL;
@@ -248,12 +248,12 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case TICK_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = TICK;
break;
case REGEX:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '/') {
*r += HI_RESET;
t_ = NORMAL;
@@ -265,13 +265,13 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case REGEX_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = REGEX;
break;
case REGEX_SQUARE:
// because /[/]/g is valid code
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\\') {
t_ = REGEX_SQUARE_BACKSLASH;
} else if (c == ']') {
@@ -280,7 +280,7 @@ void HighlightJs::feed(std::string *r, std::string_view input) {
break;
case REGEX_SQUARE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = REGEX_SQUARE;
break;
diff --git a/llamafile/highlight_make.cpp b/llamafile/highlight_make.cpp
index ecca27ae..8619b04c 100644
--- a/llamafile/highlight_make.cpp
+++ b/llamafile/highlight_make.cpp
@@ -80,7 +80,7 @@ void HighlightMake::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_' || c == '-' || c == '.') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
break;
} else if (c == '#') {
t_ = COMMENT;
@@ -94,19 +94,19 @@ void HighlightMake::feed(std::string *r, std::string_view input) {
*r += HI_ESCAPE;
*r += '\\';
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
break;
case WORD:
if (!isascii(c) || isalnum(c) || c == '_' || c == '-' || c == '.') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_make(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -124,7 +124,7 @@ void HighlightMake::feed(std::string *r, std::string_view input) {
case DOLLAR:
if (isdigit(c) || is_automatic_variable(c)) {
*r += HI_VAR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
} else if (c == '$') {
@@ -160,7 +160,7 @@ void HighlightMake::feed(std::string *r, std::string_view input) {
c == '?' || //
c == '@' || //
c == '_') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '$' && word_.empty()) {
t_ = DOLLAR;
*r += '$';
@@ -170,7 +170,7 @@ void HighlightMake::feed(std::string *r, std::string_view input) {
*r += word_;
*r += HI_RESET;
word_.clear();
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = NORMAL;
} else {
if (is_keyword_make_builtin(word_.data(), word_.size())) {
@@ -187,7 +187,7 @@ void HighlightMake::feed(std::string *r, std::string_view input) {
break;
case COMMENT:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
diff --git a/llamafile/highlight_markdown.cpp b/llamafile/highlight_markdown.cpp
index edcccd06..1b4928ba 100644
--- a/llamafile/highlight_markdown.cpp
+++ b/llamafile/highlight_markdown.cpp
@@ -82,7 +82,7 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
t_ = BACKSLASH;
*r += '\\';
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
if (c == '\n') {
bol_ = true;
@@ -95,7 +95,7 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
break;
case BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = NORMAL;
break;
@@ -107,14 +107,14 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
*r += "**";
} else if (bol_ && isblank(c)) {
*r += '*';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = NORMAL;
} else {
// handle *emphasized* text
// inverted because \e[3m has a poorly supported western bias
*r += '*';
*r += HI_ITALIC;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = EMPHASIS;
if (c == '\\')
t_ = EMPHASIS_BACKSLASH;
@@ -131,18 +131,18 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
t_ = EMPHASIS_BACKSLASH;
*r += '\\';
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case EMPHASIS_BACKSLASH:
// so we can say *unbroken \* italic* and have it work
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = EMPHASIS;
break;
case STRONG:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '*') {
t_ = STRONG_STAR;
} else if (c == '\\') {
@@ -152,12 +152,12 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
case STRONG_BACKSLASH:
// so we can say **unbroken \*\* bold** and have it work
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = STRONG;
break;
case STRONG_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '*' || // handle **bold** ending
(c == '\n' && !tail_)) { // handle *** line break
t_ = NORMAL;
@@ -175,7 +175,7 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
} else {
*r += HI_INCODE;
*r += '`';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = INCODE;
}
break;
@@ -183,7 +183,7 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
case INCODE:
// this is for `inline code` like that
// no backslash escapes are supported here
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '`') {
*r += HI_RESET;
t_ = NORMAL;
@@ -193,14 +193,14 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
case INCODE2:
// this is for ``inline ` code`` like that
// it lets you put backtick inside the code
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '`') {
t_ = INCODE2_TICK;
}
break;
case INCODE2_TICK:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '`') {
*r += HI_RESET;
t_ = NORMAL;
@@ -216,14 +216,14 @@ void HighlightMarkdown::feed(std::string *r, std::string_view input) {
} else {
*r += HI_INCODE;
*r += "``";
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = INCODE2;
}
break;
case LANG:
if (!isascii(c) || !isspace(c)) {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
lang_ += tolower(c);
} else {
if (!(highlighter_ = Highlight::create(lang_)))
diff --git a/llamafile/highlight_perl.cpp b/llamafile/highlight_perl.cpp
index 3c8a88c3..2bfbc4fd 100644
--- a/llamafile/highlight_perl.cpp
+++ b/llamafile/highlight_perl.cpp
@@ -176,7 +176,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '\'') {
t_ = QUOTE;
*r += HI_STRING;
@@ -203,7 +203,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
t_ = VAR;
expect_ = EXPECT_OPERATOR;
} else if (c == '@' || c == '%') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_VAR;
t_ = VAR2;
expect_ = EXPECT_OPERATOR;
@@ -220,7 +220,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
closer_ = '/';
expect_ = EXPECT_OPERATOR;
*r += HI_STRING;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = REGEX;
} else if (c == '\n') {
*r += '\n';
@@ -232,22 +232,22 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
}
} else if (c == ')' || c == '}' || c == ']') {
expect_ = EXPECT_OPERATOR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (ispunct(c)) {
expect_ = EXPECT_VALUE;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (isdigit(c)) {
expect_ = EXPECT_OPERATOR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
Word:
case WORD:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_perl(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -265,7 +265,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
opener_ = c;
closer_ = mirror(c);
*r += HI_STRING;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (is_double_regex(word_)) {
t_ = S_REGEX;
} else {
@@ -282,7 +282,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
break;
@@ -290,13 +290,13 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
case VAR:
if (isdigit(c) || is_magic_var(c)) {
*r += HI_VAR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
break;
} else if (c == '{') {
t_ = VAR2;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_VAR;
break;
} else {
@@ -307,7 +307,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
case VAR2:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
*r += HI_RESET;
t_ = NORMAL;
@@ -316,7 +316,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case COMMENT:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
@@ -324,7 +324,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case REGEX:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == closer_) {
*r += HI_RESET;
t_ = NORMAL;
@@ -334,12 +334,12 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case REGEX_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = REGEX;
break;
case S_REGEX:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == opener_) {
t_ = S_REGEX_S;
} else if (c == '\\') {
@@ -348,12 +348,12 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case S_REGEX_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = S_REGEX;
break;
case S_REGEX_S:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == closer_) {
*r += HI_RESET;
t_ = NORMAL;
@@ -363,12 +363,12 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case S_REGEX_S_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = S_REGEX_S;
break;
case QUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'') {
*r += HI_RESET;
t_ = NORMAL;
@@ -378,12 +378,12 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case QUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = QUOTE;
break;
case DQUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
*r += HI_RESET;
t_ = NORMAL;
@@ -393,12 +393,12 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case DQUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE;
break;
case TICK:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '`') {
*r += HI_RESET;
t_ = NORMAL;
@@ -408,7 +408,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case TICK_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = TICK;
break;
@@ -416,7 +416,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
if (isalpha(c)) {
*r += HI_COMMENT;
*r += '=';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
heredoc_ = "=cut";
t_ = HEREDOC;
i_ = 0;
@@ -429,7 +429,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
case LT:
if (c == '<') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = LT_LT;
heredoc_.clear();
pending_heredoc_ = false;
@@ -443,16 +443,16 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
case LT_LT:
if (c == '-') {
indented_heredoc_ = true;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (c == '"' || c == '\'') {
closer_ = c;
t_ = LT_LT_QNAME;
*r += HI_STRING;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (isalpha(c) || c == '_') {
t_ = LT_LT_NAME;
- append_wchar(&heredoc_, c);
- append_wchar(r, c);
+ lf::append_wchar(&heredoc_, c);
+ lf::append_wchar(r, c);
} else if (!isblank(c)) {
t_ = NORMAL;
goto Normal;
@@ -462,10 +462,10 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
case LT_LT_NAME:
if (isalnum(c) || c == '_') {
t_ = LT_LT_NAME;
- append_wchar(&heredoc_, c);
- append_wchar(r, c);
+ lf::append_wchar(&heredoc_, c);
+ lf::append_wchar(r, c);
} else if (c == '\n') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_STRING;
t_ = HEREDOC_BOL;
} else {
@@ -476,19 +476,19 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case LT_LT_QNAME:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == closer_) {
*r += HI_RESET;
t_ = HEREDOC_BOL;
pending_heredoc_ = true;
t_ = NORMAL;
} else {
- append_wchar(&heredoc_, c);
+ lf::append_wchar(&heredoc_, c);
}
break;
case HEREDOC_BOL:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
if (i_ == heredoc_.size()) {
t_ = NORMAL;
@@ -506,7 +506,7 @@ void HighlightPerl::feed(std::string *r, std::string_view input) {
break;
case HEREDOC:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
t_ = HEREDOC_BOL;
i_ = 0;
diff --git a/llamafile/highlight_shell.cpp b/llamafile/highlight_shell.cpp
index b86e13a1..01b6d3cf 100644
--- a/llamafile/highlight_shell.cpp
+++ b/llamafile/highlight_shell.cpp
@@ -85,7 +85,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '\'') {
t_ = QUOTE;
*r += HI_STRING;
@@ -121,19 +121,19 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
i_ = 0;
}
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
break;
case WORD:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_shell(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -163,7 +163,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
c == '\\' || //
c == '^') {
*r += HI_VAR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
break;
@@ -181,7 +181,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
case VAR2:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
*r += HI_RESET;
t_ = NORMAL;
@@ -208,20 +208,20 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
}
} else if (ispunct(c)) {
*r += HI_RESET;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case CURL_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = CURL;
break;
case COMMENT:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
@@ -229,7 +229,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
break;
case QUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'') {
*r += HI_RESET;
t_ = NORMAL;
@@ -239,21 +239,21 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
Dquote:
case DQUOTE:
if (c == '"') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
} else if (c == '\\') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE_BACKSLASH;
} else if (c == '$') {
t_ = DQUOTE_VAR;
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case DQUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE;
break;
@@ -269,7 +269,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
c == '^') {
*r += HI_BOLD;
*r += '$';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_UNBOLD;
t_ = DQUOTE;
break;
@@ -291,7 +291,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
case DQUOTE_VAR2:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
*r += HI_UNBOLD;
t_ = DQUOTE;
@@ -313,19 +313,19 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
t_ = DQUOTE;
}
} else if (ispunct(c)) {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case DQUOTE_CURL_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE_CURL;
break;
case TICK:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '`') {
*r += HI_RESET;
t_ = NORMAL;
@@ -335,13 +335,13 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
break;
case TICK_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = TICK;
break;
case LT:
if (c == '<') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = LT_LT;
heredoc_.clear();
pending_heredoc_ = false;
@@ -356,18 +356,18 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
case LT_LT:
if (c == '-') {
indented_heredoc_ = true;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (c == '\\') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (c == '\'') {
t_ = LT_LT_QNAME;
*r += HI_STRING;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
no_interpolation_ = true;
} else if (isalpha(c) || c == '_') {
t_ = LT_LT_NAME;
- append_wchar(&heredoc_, c);
- append_wchar(r, c);
+ lf::append_wchar(&heredoc_, c);
+ lf::append_wchar(r, c);
} else if (!isblank(c)) {
t_ = NORMAL;
goto Normal;
@@ -377,10 +377,10 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
case LT_LT_NAME:
if (isalnum(c) || c == '_') {
t_ = LT_LT_NAME;
- append_wchar(&heredoc_, c);
- append_wchar(r, c);
+ lf::append_wchar(&heredoc_, c);
+ lf::append_wchar(r, c);
} else if (c == '\n') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_STRING;
t_ = HEREDOC_BOL;
} else {
@@ -391,19 +391,19 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
break;
case LT_LT_QNAME:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'') {
*r += HI_RESET;
t_ = HEREDOC_BOL;
pending_heredoc_ = true;
t_ = NORMAL;
} else {
- append_wchar(&heredoc_, c);
+ lf::append_wchar(&heredoc_, c);
}
break;
case HEREDOC_BOL:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
if (i_ == heredoc_.size()) {
t_ = NORMAL;
@@ -428,7 +428,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
} else if (c == '$' && !no_interpolation_) {
t_ = HEREDOC_VAR;
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
@@ -444,7 +444,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
c == '^') {
*r += HI_BOLD;
*r += '$';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_UNBOLD;
t_ = HEREDOC;
break;
@@ -466,7 +466,7 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
case HEREDOC_VAR2:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
*r += HI_UNBOLD;
t_ = HEREDOC;
@@ -488,14 +488,14 @@ void HighlightShell::feed(std::string *r, std::string_view input) {
t_ = HEREDOC;
}
} else if (ispunct(c)) {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case HEREDOC_CURL_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = HEREDOC_CURL;
break;
diff --git a/llamafile/highlight_swift.cpp b/llamafile/highlight_swift.cpp
index 4eb5ee55..a100d6b4 100644
--- a/llamafile/highlight_swift.cpp
+++ b/llamafile/highlight_swift.cpp
@@ -92,7 +92,7 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '/') {
t_ = SLASH;
} else if (c == '"') {
@@ -116,14 +116,14 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
*r += HI_STRING;
*r += ')';
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
Word:
case WORD:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_swift(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -169,7 +169,7 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
break;
case SLASH_SLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
@@ -179,18 +179,18 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
break;
case SLASH_SLASH_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = SLASH_SLASH;
break;
case SLASH_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '*')
t_ = SLASH_STAR_STAR;
break;
case SLASH_STAR_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '/') {
*r += HI_RESET;
t_ = NORMAL;
@@ -224,7 +224,7 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
Dquote:
case DQUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
t_ = DQUOTE2;
hash2_ = 0;
@@ -238,7 +238,7 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
Dquotestr:
case DQUOTESTR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
t_ = DQUOTESTR_END;
hash2_ = 0;
@@ -298,7 +298,7 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
Dquote3:
case DQUOTE3:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
t_ = DQUOTE31;
} else if (c == '\\') {
@@ -361,7 +361,7 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
Regex:
case REGEX:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '/') {
t_ = REGEX_END;
hash2_ = 0;
@@ -386,7 +386,7 @@ void HighlightSwift::feed(std::string *r, std::string_view input) {
break;
case REGEX_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = REGEX;
break;
diff --git a/llamafile/highlight_tcl.cpp b/llamafile/highlight_tcl.cpp
index 642c9d9e..aca63db9 100644
--- a/llamafile/highlight_tcl.cpp
+++ b/llamafile/highlight_tcl.cpp
@@ -66,7 +66,7 @@ void HighlightTcl::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '"') {
t_ = DQUOTE;
*r += HI_STRING;
@@ -83,13 +83,13 @@ void HighlightTcl::feed(std::string *r, std::string_view input) {
*r += HI_ESCAPE;
*r += '\\';
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case WORD:
if (!(isspace(c) || c == ';')) {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_tcl(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -113,7 +113,7 @@ void HighlightTcl::feed(std::string *r, std::string_view input) {
break;
case BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
break;
@@ -132,7 +132,7 @@ void HighlightTcl::feed(std::string *r, std::string_view input) {
case VAR2:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
*r += HI_RESET;
t_ = NORMAL;
@@ -146,12 +146,12 @@ void HighlightTcl::feed(std::string *r, std::string_view input) {
*r += '}';
t_ = NORMAL;
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case COMMENT:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
@@ -159,7 +159,7 @@ void HighlightTcl::feed(std::string *r, std::string_view input) {
break;
case DQUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
*r += HI_RESET;
t_ = NORMAL;
@@ -169,7 +169,7 @@ void HighlightTcl::feed(std::string *r, std::string_view input) {
break;
case DQUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE;
break;
diff --git a/llamafile/highlight_tex.cpp b/llamafile/highlight_tex.cpp
index a7557d1f..55e6ae38 100644
--- a/llamafile/highlight_tex.cpp
+++ b/llamafile/highlight_tex.cpp
@@ -76,7 +76,7 @@ void HighlightTex::feed(std::string *r, std::string_view input) {
*r += HI_COMMENT;
*r += '%';
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
@@ -93,12 +93,12 @@ void HighlightTex::feed(std::string *r, std::string_view input) {
} else if (isalpha(c) || c == '@') {
*r += HI_KEYWORD;
*r += '\\';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = COMMAND;
} else {
*r += HI_ESCAPE;
*r += '\\';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
*r += HI_RESET;
t_ = NORMAL;
}
@@ -106,7 +106,7 @@ void HighlightTex::feed(std::string *r, std::string_view input) {
case COMMAND:
if (isalpha(c) || c == '@') {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
*r += HI_RESET;
t_ = NORMAL;
@@ -125,7 +125,7 @@ void HighlightTex::feed(std::string *r, std::string_view input) {
} else {
*r += HI_MATH;
*r += "$";
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = MATH;
}
break;
@@ -139,17 +139,17 @@ void HighlightTex::feed(std::string *r, std::string_view input) {
*r += '\\';
t_ = MATH_BACKSLASH;
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case MATH_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = MATH;
break;
case COMMENT:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
@@ -169,13 +169,13 @@ void HighlightTex::feed(std::string *r, std::string_view input) {
break;
case STRING:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'')
t_ = STRING_QUOTE;
break;
case STRING_QUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'') {
*r += HI_RESET;
t_ = NORMAL;
diff --git a/llamafile/highlight_typescript.cpp b/llamafile/highlight_typescript.cpp
index 0bdde0be..653cda2f 100644
--- a/llamafile/highlight_typescript.cpp
+++ b/llamafile/highlight_typescript.cpp
@@ -79,7 +79,7 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '/') {
t_ = SLASH;
} else if (c == '\'') {
@@ -107,22 +107,22 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
*r += '}';
} else if (c == ')' || c == '}' || c == ']') {
expect_ = EXPECT_OPERATOR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (ispunct(c)) {
expect_ = EXPECT_VALUE;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else if (isdigit(c)) {
expect_ = EXPECT_OPERATOR;
- append_wchar(r, c);
+ lf::append_wchar(r, c);
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
Word:
case WORD:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_typescript(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -167,7 +167,7 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
expect_ = EXPECT_OPERATOR;
*r += HI_STRING;
*r += '/';
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\\') {
t_ = REGEX_BACKSLASH;
} else if (c == '[') {
@@ -183,7 +183,7 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case SLASH_SLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
@@ -191,13 +191,13 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case SLASH_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '*')
t_ = SLASH_STAR_STAR;
break;
case SLASH_STAR_STAR:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '/') {
*r += HI_RESET;
t_ = NORMAL;
@@ -207,7 +207,7 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case QUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'') {
*r += HI_RESET;
t_ = NORMAL;
@@ -217,12 +217,12 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case QUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = QUOTE;
break;
case DQUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
*r += HI_RESET;
t_ = NORMAL;
@@ -232,7 +232,7 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case DQUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE;
break;
@@ -248,12 +248,12 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
*r += '\\';
t_ = TICK_BACKSLASH;
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case TICK_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = TICK;
break;
@@ -279,7 +279,7 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case REGEX:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '/') {
*r += HI_RESET;
t_ = NORMAL;
@@ -291,13 +291,13 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case REGEX_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = REGEX;
break;
case REGEX_SQUARE:
// because /[/]/g is valid code
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\\') {
t_ = REGEX_SQUARE_BACKSLASH;
} else if (c == ']') {
@@ -306,7 +306,7 @@ void HighlightTypescript::feed(std::string *r, std::string_view input) {
break;
case REGEX_SQUARE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = REGEX_SQUARE;
break;
diff --git a/llamafile/highlight_zig.cpp b/llamafile/highlight_zig.cpp
index db23815b..c251870a 100644
--- a/llamafile/highlight_zig.cpp
+++ b/llamafile/highlight_zig.cpp
@@ -67,7 +67,7 @@ void HighlightZig::feed(std::string *r, std::string_view input) {
case NORMAL:
if (!isascii(c) || isalpha(c) || c == '_' || c == '@') {
t_ = WORD;
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else if (c == '/') {
t_ = SLASH;
} else if (c == '\\') {
@@ -81,13 +81,13 @@ void HighlightZig::feed(std::string *r, std::string_view input) {
*r += HI_STRING;
*r += '"';
} else {
- append_wchar(r, c);
+ lf::append_wchar(r, c);
}
break;
case WORD:
if (!isascii(c) || isalnum(c) || c == '_') {
- append_wchar(&word_, c);
+ lf::append_wchar(&word_, c);
} else {
if (is_keyword_zig(word_.data(), word_.size())) {
*r += HI_KEYWORD;
@@ -128,7 +128,7 @@ void HighlightZig::feed(std::string *r, std::string_view input) {
case SLASH_SLASH:
case BACKSLASH_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\n') {
*r += HI_RESET;
t_ = NORMAL;
@@ -148,7 +148,7 @@ void HighlightZig::feed(std::string *r, std::string_view input) {
break;
case QUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '\'') {
*r += HI_RESET;
t_ = NORMAL;
@@ -158,12 +158,12 @@ void HighlightZig::feed(std::string *r, std::string_view input) {
break;
case QUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = QUOTE;
break;
case DQUOTE:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
if (c == '"') {
*r += HI_RESET;
t_ = NORMAL;
@@ -173,7 +173,7 @@ void HighlightZig::feed(std::string *r, std::string_view input) {
break;
case DQUOTE_BACKSLASH:
- append_wchar(r, c);
+ lf::append_wchar(r, c);
t_ = DQUOTE;
break;
diff --git a/llamafile/llamafile.h b/llamafile/llamafile.h
index dc817bd4..e74a210d 100644
--- a/llamafile/llamafile.h
+++ b/llamafile/llamafile.h
@@ -29,7 +29,7 @@ extern const char *FLAG_prompt;
extern double FLAG_token_rate;
extern float FLAG_temp;
extern int FLAG_batch;
-extern int FLAG_ctx;
+extern int FLAG_ctx_size;
extern int FLAG_flash_attn;
extern int FLAG_gpu;
extern int FLAG_gpu;
diff --git a/llamafile/parse_cidr.cpp b/llamafile/parse_cidr.cpp
index f2b08bf6..4b08d085 100644
--- a/llamafile/parse_cidr.cpp
+++ b/llamafile/parse_cidr.cpp
@@ -20,7 +20,7 @@
#include <ctype.h>
#include <string.h>
-bool parse_cidr(const ctl::string_view &str, cidr *out_cidr) noexcept {
+bool parse_cidr(const std::string_view &str, cidr *out_cidr) noexcept {
long ip;
int bits;
size_t i, n;
@@ -28,7 +28,7 @@ bool parse_cidr(const ctl::string_view &str, cidr *out_cidr) noexcept {
s = str.data();
n = str.size();
if ((p = (const char *)memchr(s, '/', n))) {
- if ((ip = parse_ip(ctl::string_view(s, (i = p - s)))) == -1)
+ if ((ip = parse_ip(std::string_view(s, (i = p - s)))) == -1)
return false;
bits = 0;
for (++i; i < n; ++i) {
diff --git a/llamafile/parse_ip.cpp b/llamafile/parse_ip.cpp
index da49db1e..65be09dd 100644
--- a/llamafile/parse_ip.cpp
+++ b/llamafile/parse_ip.cpp
@@ -21,7 +21,7 @@
#include <stdckdint.h>
#include <string.h>
-long parse_ip(const ctl::string_view &str) noexcept {
+long parse_ip(const std::string_view &str) noexcept {
int c, j;
size_t i, n;
unsigned b, x;
diff --git a/llamafile/server/atob.cpp b/llamafile/server/atob.cpp
index ee0dd3ee..5f02362e 100644
--- a/llamafile/server/atob.cpp
+++ b/llamafile/server/atob.cpp
@@ -18,7 +18,7 @@
#include "utils.h"
bool
-atob(ctl::string_view val, bool dflt)
+atob(std::string_view val, bool dflt)
{
if (val == "0")
return false;
diff --git a/llamafile/server/cleanup.cpp b/llamafile/server/cleanup.cpp
index a318aed6..5cbed976 100644
--- a/llamafile/server/cleanup.cpp
+++ b/llamafile/server/cleanup.cpp
@@ -17,20 +17,20 @@
#include "cleanup.h"
-#include <ctl/vector.h>
+#include <vector>
#include "llama.cpp/llama.h"
void
cleanup_float_vector(void* arg)
{
- delete (ctl::vector<float>*)arg;
+ delete (std::vector<float>*)arg;
}
void
cleanup_token_vector(void* arg)
{
- delete (ctl::vector<llama_token>*)arg;
+ delete (std::vector<llama_token>*)arg;
}
void
diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cpp
index 63617d44..de2685be 100644
--- a/llamafile/server/client.cpp
+++ b/llamafile/server/client.cpp
@@ -41,7 +41,7 @@
"Referrer-Policy: origin\r\n" \
"Cache-Control: private; max-age=0\r\n"
-using namespace ctl;
+using namespace std;
static void
on_http_cancel(Client* client)
@@ -195,7 +195,7 @@ Client::transport()
effective_ip_trusted = client_ip_trusted;
if (FLAG_ip_header) {
if (is_loopback_ip(client_ip) || client_ip_trusted) {
- ctl::string_view ip_header = get_header(FLAG_ip_header);
+ std::string_view ip_header = get_header(FLAG_ip_header);
if (!ip_header.empty()) {
long ip;
if ((ip = parse_ip(ip_header)) == -1) {
@@ -274,7 +274,8 @@ Client::send_error(int code, const char* reason)
reason = GetHttpReason(code);
SLOG("error %d %s", code, reason);
char* p = append_http_response_message(obuf.p, code, reason);
- return send_response(obuf.p, p, string(reason) + "\r\n");
+ (void)!send_response(obuf.p, p, string(reason) + "\r\n");
+ return false;
}
// appends start of http response message to `p`
@@ -519,14 +520,14 @@ Client::has_at_most_this_element(int h, const string_view s)
return true;
}
-ctl::string_view
-Client::get_header(const ctl::string_view& key)
+std::string_view
+Client::get_header(const std::string_view& key)
{
int h;
size_t i, keylen;
if ((h = GetHttpHeader(key.data(), key.size())) != -1) {
if (msg.headers[h].a)
- return ctl::string_view(ibuf.p + msg.headers[h].a,
+ return std::string_view(ibuf.p + msg.headers[h].a,
msg.headers[h].b - msg.headers[h].a);
} else {
for (i = 0; i < msg.xheaders.n; ++i)
@@ -534,11 +535,11 @@ Client::get_header(const ctl::string_view& key)
key.size(),
ibuf.p + msg.xheaders.p[i].k.a,
msg.xheaders.p[i].k.b - msg.xheaders.p[i].k.a))
- return ctl::string_view(ibuf.p + msg.xheaders.p[i].v.a,
+ return std::string_view(ibuf.p + msg.xheaders.p[i].v.a,
msg.xheaders.p[i].v.b -
msg.xheaders.p[i].v.a);
}
- return ctl::string_view();
+ return std::string_view();
}
bool
@@ -583,7 +584,7 @@ Client::dispatch()
bool
Client::dispatcher()
{
- ctl::string_view p = path();
+ std::string_view p = path();
if (!g_url_prefix.empty()) {
if (FLAG_verbose >= 2) {
@@ -598,7 +599,7 @@ Client::dispatcher()
}
// Adjust path view to exclude prefix
- p = ctl::string_view(p.data() + prefix_len, p.size() - prefix_len);
+ p = std::string_view(p.data() + prefix_len, p.size() - prefix_len);
}
if (p == "/tokenize")
@@ -607,8 +608,8 @@ Client::dispatcher()
return embedding();
if (p == "/v1/embeddings")
return embedding();
- if (p == "/completion")
- return completion();
+ if (p == "/v1/chat/completions")
+ return v1_chat_completions();
SLOG("path not found: %.*s", (int)p.size(), p.data());
return send_error(404);
diff --git a/llamafile/server/client.h b/llamafile/server/client.h
index baef96cb..cf9615ac 100644
--- a/llamafile/server/client.h
+++ b/llamafile/server/client.h
@@ -19,12 +19,12 @@
#include "buffer.h"
-#include <ctl/optional.h>
-#include <ctl/string.h>
#include <libc/fmt/itoa.h>
#include <libc/str/slice.h>
#include <net/http/http.h>
#include <net/http/url.h>
+#include <optional>
+#include <string>
#include <sys/resource.h>
#include <time.h>
@@ -39,7 +39,7 @@
struct Worker;
struct TokenizeParams;
struct EmbeddingParams;
-struct CompletionParams;
+struct V1ChatCompletionParams;
struct Cleanup
{
@@ -64,7 +64,7 @@ struct Client
Url url = {};
char* url_memory = nullptr;
char* params_memory = nullptr;
- ctl::string_view payload;
+ std::string_view payload;
Cleanup* cleanups;
Buffer ibuf;
Buffer obuf;
@@ -81,32 +81,32 @@ struct Client
bool read_request() __wur;
bool read_content() __wur;
bool send_continue() __wur;
- bool send(const ctl::string_view) __wur;
+ bool send(const std::string_view) __wur;
void defer_cleanup(void (*)(void*), void*);
bool send_error(int, const char* = nullptr);
char* append_http_response_message(char*, int, const char* = nullptr);
- bool send_response(char*, char*, const ctl::string_view) __wur;
+ bool send_response(char*, char*, const std::string_view) __wur;
bool send_response_start(char*, char*) __wur;
- bool send_response_chunk(const ctl::string_view) __wur;
+ bool send_response_chunk(const std::string_view) __wur;
bool send_response_finish() __wur;
- bool send2(const ctl::string_view, const ctl::string_view) __wur;
- char* append_header(const ctl::string_view, const ctl::string_view);
- bool has_at_most_this_element(int, const ctl::string_view);
- ctl::string_view get_header(const ctl::string_view&);
+ bool send2(const std::string_view, const std::string_view) __wur;
+ char* append_header(const std::string_view, const std::string_view);
+ bool has_at_most_this_element(int, const std::string_view);
+ std::string_view get_header(const std::string_view&);
bool fun() __wur;
- ctl::string_view path();
- ctl::optional<ctl::string_view> param(ctl::string_view);
+ std::string_view path();
+ std::optional<std::string_view> param(std::string_view);
bool dispatch() __wur;
bool dispatcher() __wur;
bool tokenize() __wur;
- bool get_tokenize_params(TokenizeParams*);
+ bool get_tokenize_params(TokenizeParams*) __wur;
bool embedding() __wur;
- bool get_embedding_params(EmbeddingParams*);
+ bool get_embedding_params(EmbeddingParams*) __wur;
- bool completion() __wur;
- bool get_completion_params(CompletionParams*);
+ bool v1_chat_completions() __wur;
+ bool get_v1_chat_completions_params(V1ChatCompletionParams*) __wur;
};
diff --git a/llamafile/server/completion.cpp b/llamafile/server/completion.cpp
deleted file mode 100644
index 5a98f1f8..00000000
--- a/llamafile/server/completion.cpp
+++ /dev/null
@@ -1,325 +0,0 @@
-// -*- 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.
-
-#include "client.h"
-
-#include <ctl/vector.h>
-#include <math.h>
-#include <string.h>
-#include <sys/resource.h>
-
-#include "llama.cpp/llama.h"
-#include "llama.cpp/sampling.h"
-#include "llamafile/macros.h"
-
-#include "cleanup.h"
-#include "fastjson.h"
-#include "json.h"
-#include "log.h"
-#include "model.h"
-#include "utils.h"
-
-struct CompletionParams
-{
- bool add_special;
- bool parse_special;
- bool display_special;
- ctl::string_view prompt;
- ctl::string content;
-};
-
-struct CompletionResponse
-{
- ctl::string prompt;
- ctl::string content;
- bool stop = false;
-};
-
-static void
-add_token_to_batch(llama_batch& batch,
- llama_token id,
- llama_pos pos,
- const ctl::vector<llama_seq_id>& seq_ids,
- bool logits)
-{
- batch.token[batch.n_tokens] = id;
- batch.pos[batch.n_tokens] = pos;
- batch.n_seq_id[batch.n_tokens] = seq_ids.size();
- for (size_t i = 0; i < seq_ids.size(); ++i)
- batch.seq_id[batch.n_tokens][i] = seq_ids[i];
- batch.logits[batch.n_tokens] = logits;
- batch.n_tokens++;
-}
-
-static ctl::string
-token_to_piece(const struct llama_context* ctx, llama_token token, bool special)
-{
- ctl::vector<char> result(8, 0);
- const int n_tokens = llama_token_to_piece(llama_get_model(ctx),
- token,
- result.data(),
- result.size(),
- false,
- special);
- if (n_tokens < 0) {
- result.resize(-n_tokens);
- int check = llama_token_to_piece(llama_get_model(ctx),
- token,
- result.data(),
- result.size(),
- false,
- special);
- GGML_ASSERT(check == -n_tokens);
- } else {
- result.resize(n_tokens);
- }
- return ctl::string(result.data(), result.size());
-}
-
-void
-cleanup_completion_params(void* arg)
-{
- delete (CompletionParams*)arg;
-}
-
-void
-cleanup_completion_response(void* arg)
-{
- delete (CompletionResponse*)arg;
-}
-
-void
-cleanup_llama_sampling_context(void* arg)
-{
- llama_sampling_free((llama_sampling_context*)arg);
-}
-
-bool
-Client::get_completion_params(CompletionParams* params)
-{
- params->add_special = atob(or_empty(param("add_special")), true);
- params->parse_special = atob(or_empty(param("parse_special")), false);
- params->display_special = atob(or_empty(param("display_special")), true);
- ctl::optional<ctl::string_view> prompt = param("prompt");
- if (prompt.has_value()) {
- params->prompt = prompt.value();
- } else if (HasHeader(kHttpContentType)) {
- if (IsMimeType(HeaderData(kHttpContentType),
- HeaderLength(kHttpContentType),
- "text/plain")) {
- 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();
- if (json.second["display_special"].isBool())
- params->display_special =
- json.second["display_special"].getBool();
- } else {
- return send_error(501, "Content Type Not Implemented");
- }
- } else {
- params->prompt = payload;
- }
- return true;
-}
-
-bool
-Client::completion()
-{
- if (msg.method != kHttpGet && msg.method != kHttpPost)
- return send_error(405);
-
- if (!read_payload())
- return false;
-
- // get parameters
- auto params = new CompletionParams;
- defer_cleanup(cleanup_completion_params, params);
- if (!get_completion_params(params))
- return false;
-
- // create response object
- auto response = new CompletionResponse;
- defer_cleanup(cleanup_completion_response, response);
-
- // setup statistics
- rusage rustart = {};
- getrusage(RUSAGE_THREAD, &rustart);
- timespec started = timespec_real();
-
- // turn text into tokens
- auto toks = new ctl::vector<llama_token>(params->prompt.size() + 16);
- defer_cleanup(cleanup_token_vector, toks);
- int count = llama_tokenize(g_model,
- params->prompt.data(),
- params->prompt.size(),
- &(*toks)[0],
- toks->size(),
- params->add_special,
- params->parse_special);
- if (count < 0) {
- SLOG("llama_tokenize failed");
- return send_error(405);
- }
- toks->resize(count);
-
- if (toks->empty())
- return send_error(400, "completely empty prompt disallowed");
-
- // fail if exceeds model context size
- const int n_ctx_train = llama_n_ctx_train(g_model);
- if (count + 1 > n_ctx_train)
- return send_error(400, "prompt too big for model context size");
-
- // initialize context
- llama_context_params cparams = {};
- cparams.embeddings = true;
- cparams.embeddings_only = false;
- cparams.logits_all = true;
- cparams.seed = _rand64();
- cparams.n_ctx = FLAG_ctx;
- if (cparams.n_ctx < count + 512)
- cparams.n_ctx = count + 512;
- if (cparams.n_ctx > n_ctx_train)
- cparams.n_ctx = n_ctx_train;
- cparams.n_batch = count;
- cparams.n_ubatch = count;
- cparams.n_seq_max = 1;
- cparams.n_threads = FLAG_threads;
- cparams.n_threads_batch = MIN(FLAG_threads, 20);
- cparams.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE;
- cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
- cparams.rope_freq_base = 0;
- cparams.yarn_ext_factor = -1;
- cparams.yarn_attn_factor = 1;
- cparams.yarn_beta_fast = 32;
- cparams.yarn_beta_slow = 1;
- cparams.yarn_orig_ctx = 0;
- cparams.defrag_thold = -1;
- cparams.type_k = GGML_TYPE_F16;
- cparams.type_v = GGML_TYPE_F16;
- cparams.flash_attn = FLAG_flash_attn;
-
- llama_context* ctx = llama_new_context_with_model(g_model, cparams);
- if (!ctx) {
- SLOG("llama_new_context_with_model failed");
- return send_error(500);
- }
- defer_cleanup(cleanup_llama_context, ctx);
-
- // turn prompt back into string
- for (auto tok : *toks)
- response->prompt += token_to_piece(ctx, tok, params->display_special);
-
- // prefill time
- if (llama_decode(ctx, llama_batch_get_one(&(*toks)[0], count, 0, 0))) {
- SLOG("llama_decode prefill failed");
- return send_error(500, "llama_decode prefill failed");
- }
-
- // init sampling
- llama_sampling_params sparams;
- sparams.temp = FLAG_temp;
- sparams.seed = cparams.seed;
- llama_sampling_context* ctx_sampling = llama_sampling_init(sparams);
- if (!ctx_sampling) {
- SLOG("llama_sampling_init() failed");
- return send_error(500, "llama_sampling_init() failed");
- }
- defer_cleanup(cleanup_llama_sampling_context, ctx_sampling);
-
- // prediction time
- for (;;) {
- llama_token id = llama_sampling_sample(ctx_sampling, ctx, NULL);
- llama_sampling_accept(ctx_sampling, ctx, id, true);
- if (llama_token_is_eog(g_model, id)) {
- response->stop = true;
- break;
- }
- response->content += token_to_piece(ctx, id, params->display_special);
- if (llama_decode(ctx, llama_batch_get_one(&id, 1, count, 0)))
- break;
- ++count;
- }
-
- // serialize tokens to json
- char* p = obuf.p;
- p = stpcpy(p, "{\n");
- p = stpcpy(p, " \"add_special\": ");
- p = encode_bool(p, params->add_special);
- p = stpcpy(p, ",\n");
- p = stpcpy(p, " \"parse_special\": ");
- p = encode_bool(p, params->parse_special);
- p = stpcpy(p, ",\n");
- p = stpcpy(p, " \"display_special\": ");
- p = encode_bool(p, params->display_special);
- p = stpcpy(p, ",\n");
- p = stpcpy(p, " \"tokens_provided\": ");
- p = encode_json(p, toks->size());
- p = stpcpy(p, ",\n");
- p = stpcpy(p, " \"tokens_used\": ");
- p = encode_json(p, count);
- p = stpcpy(p, ",\n");
- p = stpcpy(p, " \"prompt\": ");
- p = encode_json(p, response->prompt);
- p = stpcpy(p, ",\n");
- p = stpcpy(p, " \"content\": ");
- p = encode_json(p, response->content);
- p = stpcpy(p, ",\n");
- p = stpcpy(p, " \"stop\": ");
- p = encode_bool(p, response->stop);
- p = stpcpy(p, "\n");
- p = stpcpy(p, "}\n");
- ctl::string_view content(obuf.p, p - obuf.p);
-
- // collect statistics
- rusage ruend = {};
- getrusage(RUSAGE_THREAD, &ruend);
- timeval user = timeval_sub(ruend.ru_utime, rustart.ru_utime);
- timeval system = timeval_sub(ruend.ru_stime, rustart.ru_stime);
- timespec ended = timespec_real();
- timespec wall = timespec_sub(ended, started);
- long wall_us = timespec_tomicros(wall);
- long user_us = timeval_tomicros(user);
- long system_us = timeval_tomicros(system);
-
- // send response
- char* headers = p;
- p = append_http_response_message(p, 200);
- p = stpcpy(p, "Content-Type: application/json\r\n");
- p = stpcpy(p, "X-Wall-Micros: ");
- p = FormatInt64(p, wall_us);
- p = stpcpy(p, "\r\nX-User-Micros: ");
- p = FormatInt64(p, user_us);
- p = stpcpy(p, "\r\nX-System-Micros: ");
- p = FormatInt64(p, system_us);
- p = stpcpy(p, "\r\n");
- return send_response(headers, p, content);
-}
diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cpp
index b7412940..bc000cdf 100644
--- a/llamafile/server/embedding.cpp
+++ b/llamafile/server/embedding.cpp
@@ -17,10 +17,10 @@
#include "client.h"
-#include <ctl/vector.h>
#include <math.h>
#include <string.h>
#include <sys/resource.h>
+#include <vector>
#include "llama.cpp/llama.h"
@@ -35,9 +35,9 @@ struct EmbeddingParams
{
bool add_special;
bool parse_special;
- ctl::string_view prompt;
- ctl::string content;
- ctl::string model;
+ std::string_view prompt;
+ std::string content;
+ std::string model;
};
void
@@ -56,7 +56,7 @@ static void
add_token_to_batch(struct llama_batch& batch,
llama_token id,
llama_pos pos,
- const ctl::vector<llama_seq_id>& seq_ids,
+ const std::vector<llama_seq_id>& seq_ids,
bool logits)
{
batch.token[batch.n_tokens] = id;
@@ -81,15 +81,15 @@ Client::get_embedding_params(EmbeddingParams* params)
params->parse_special = atob(or_empty(param("parse_special")), false);
// try obtaining prompt (or its aliases) from request-uri
- ctl::optional<ctl::string_view> prompt = param("content");
+ std::optional<std::string_view> prompt = param("content");
if (!prompt.has_value()) {
- ctl::optional<ctl::string_view> prompt2 = param("prompt");
+ std::optional<std::string_view> prompt2 = param("prompt");
if (prompt2.has_value()) {
- prompt = ctl::move(prompt2);
+ prompt = std::move(prompt2);
} else {
- ctl::optional<ctl::string_view> prompt3 = param("input");
+ std::optional<std::string_view> prompt3 = param("input");
if (prompt3.has_value()) {
- prompt = ctl::move(prompt3);
+ prompt = std::move(prompt3);
}
}
}
@@ -109,17 +109,17 @@ Client::get_embedding_params(EmbeddingParams* params)
} else if (IsMimeType(HeaderData(kHttpContentType),
HeaderLength(kHttpContentType),
"application/json")) {
- ctl::pair<Json::Status, Json> json = Json::parse(payload);
+ std::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())
- params->content = ctl::move(json.second["content"].getString());
+ params->content = std::move(json.second["content"].getString());
else if (json.second["prompt"].isString())
- params->content = ctl::move(json.second["prompt"].getString());
+ params->content = std::move(json.second["prompt"].getString());
else if (json.second["input"].isString())
- params->content = ctl::move(json.second["input"].getString());
+ params->content = std::move(json.second["input"].getString());
else
return send_error(400, "JSON missing content/prompt/input key");
params->prompt = params->content;
@@ -128,7 +128,7 @@ Client::get_embedding_params(EmbeddingParams* params)
if (json.second["parse_special"].isBool())
params->parse_special = json.second["parse_special"].getBool();
if (json.second["model"].isString())
- params->model = ctl::move(json.second["model"].getString());
+ params->model = std::move(json.second["model"].getString());
} else {
return send_error(501, "Content Type Not Implemented");
}
@@ -159,7 +159,7 @@ Client::embedding()
timespec started = timespec_real();
// turn text into tokens
- auto toks = new ctl::vector<llama_token>(params->prompt.size() + 16);
+ auto toks = new std::vector<llama_token>(params->prompt.size() + 16);
defer_cleanup(cleanup_token_vector, toks);
int count = llama_tokenize(g_model,
params->prompt.data(),
@@ -220,7 +220,7 @@ Client::embedding()
SLOG("llama_decode failed");
return send_error(500);
}
- auto embeddings = new ctl::vector<float>(n_embd, 0);
+ auto embeddings = new std::vector<float>(n_embd, 0);
defer_cleanup(cleanup_float_vector, embeddings);
for (int i = 0; i < batch->n_tokens; i++) {
if (!batch->logits[i])
@@ -308,7 +308,7 @@ Client::embedding()
if (in_openai_mode)
p = stpcpy(p, " }]\n");
p = stpcpy(p, "}\n");
- ctl::string_view content(obuf.p, p - obuf.p);
+ std::string_view content(obuf.p, p - obuf.p);
// collect statistics
rusage ruend = {};
diff --git a/llamafile/server/fastjson.cpp b/llamafile/server/fastjson.cpp
index fd5603cb..2c2c21ff 100644
--- a/llamafile/server/fastjson.cpp
+++ b/llamafile/server/fastjson.cpp
@@ -18,8 +18,8 @@
#include "fastjson.h"
#include <cosmo.h>
-#include <ctl/string.h>
#include <net/http/escape.h>
+#include <string>
#include "double-conversion/double-to-string.h"
#include "double-conversion/utils.h"
@@ -95,7 +95,7 @@ encode_json(char* p, double x) noexcept
}
char*
-encode_json(char* p, const ctl::string_view s) noexcept
+encode_json(char* p, const std::string_view s) noexcept
{
*p++ = '"';
p = encode_js_string_literal(p, s);
@@ -105,7 +105,7 @@ encode_json(char* p, const ctl::string_view s) noexcept
}
char*
-encode_js_string_literal(char* p, const ctl::string_view s) noexcept
+encode_js_string_literal(char* p, const std::string_view s) noexcept
{
uint64_t w;
size_t i, j, m;
diff --git a/llamafile/server/fastjson.h b/llamafile/server/fastjson.h
index 0bee2b0c..5740df98 100644
--- a/llamafile/server/fastjson.h
+++ b/llamafile/server/fastjson.h
@@ -16,7 +16,7 @@
// limitations under the License.
#pragma once
-#include <ctl/string_view.h>
+#include <string_view>
char*
encode_bool(char*, bool) noexcept;
@@ -40,7 +40,7 @@ char*
encode_json(char*, unsigned long) noexcept;
char*
-encode_json(char*, const ctl::string_view) noexcept;
+encode_json(char*, const std::string_view) noexcept;
char*
-encode_js_string_literal(char*, const ctl::string_view) noexcept;
+encode_js_string_literal(char*, const std::string_view) noexcept;
diff --git a/llamafile/server/fastjson_test.cpp b/llamafile/server/fastjson_test.cpp
index ef99870b..5e01282e 100644
--- a/llamafile/server/fastjson_test.cpp
+++ b/llamafile/server/fastjson_test.cpp
@@ -17,10 +17,10 @@
#include "fastjson.h"
-#include <ctl/string.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
+#include <string>
using namespace ctl;
diff --git a/llamafile/server/json.cpp b/llamafile/server/json.cpp
index 53ca6e47..621fa6e6 100644
--- a/llamafile/server/json.cpp
+++ b/llamafile/server/json.cpp
@@ -130,7 +130,7 @@ Json::clear()
{
switch (type_) {
case String:
- string_value.~string();
+ string_value.~basic_string();
break;
case Array:
array_value.~vector();
@@ -155,9 +155,6 @@ Json::Json(const Json& other) : type_(other.type_)
case Long:
long_value = other.long_value;
break;
- case Ulong:
- ulong_value = other.ulong_value;
- break;
case Float:
float_value = other.float_value;
break;
@@ -165,13 +162,13 @@ Json::Json(const Json& other) : type_(other.type_)
double_value = other.double_value;
break;
case String:
- new (&string_value) ctl::string(other.string_value);
+ new (&string_value) std::string(other.string_value);
break;
case Array:
- new (&array_value) ctl::vector<Json>(other.array_value);
+ new (&array_value) std::vector<Json>(other.array_value);
break;
case Object:
- new (&object_value) ctl::map<ctl::string, Json>(other.object_value);
+ new (&object_value) std::map<std::string, Json>(other.object_value);
break;
default:
__builtin_trap();
@@ -193,9 +190,6 @@ Json::operator=(const Json& other)
case Long:
long_value = other.long_value;
break;
- case Ulong:
- ulong_value = other.ulong_value;
- break;
case Float:
float_value = other.float_value;
break;
@@ -203,14 +197,14 @@ Json::operator=(const Json& other)
double_value = other.double_value;
break;
case String:
- new (&string_value) ctl::string(other.string_value);
+ new (&string_value) std::string(other.string_value);
break;
case Array:
- new (&array_value) ctl::vector<Json>(other.array_value);
+ new (&array_value) std::vector<Json>(other.array_value);
break;
case Object:
new (&object_value)
- ctl::map<ctl::string, Json>(other.object_value);
+ std::map<std::string, Json>(other.object_value);
break;
default:
__builtin_trap();
@@ -230,9 +224,6 @@ Json::Json(Json&& other) noexcept : type_(other.type_)
case Long:
long_value = other.long_value;
break;
- case Ulong:
- ulong_value = other.ulong_value;
- break;
case Float:
float_value = other.float_value;
break;
@@ -240,14 +231,14 @@ Json::Json(Json&& other) noexcept : type_(other.type_)
double_value = other.double_value;
break;
case String:
- new (&string_value) ctl::string(ctl::move(other.string_value));
+ new (&string_value) std::string(std::move(other.string_value));
break;
case Array:
- new (&array_value) ctl::vector<Json>(ctl::move(other.array_value));
+ new (&array_value) std::vector<Json>(std::move(other.array_value));
break;
case Object:
new (&object_value)
- ctl::map<ctl::string, Json>(ctl::move(other.object_value));
+ std::map<std::string, Json>(std::move(other.object_value));
break;
default:
__builtin_trap();
@@ -270,9 +261,6 @@ Json::operator=(Json&& other) noexcept
case Long:
long_value = other.long_value;
break;
- case Ulong:
- ulong_value = other.ulong_value;
- break;
case Float:
float_value = other.float_value;
break;
@@ -280,15 +268,15 @@ Json::operator=(Json&& other) noexcept
double_value = other.double_value;
break;
case String:
- new (&string_value) ctl::string(ctl::move(other.string_value));
+ new (&string_value) std::string(std::move(other.string_value));
break;
case Array:
new (&array_value)
- ctl::vector<Json>(ctl::move(other.array_value));
+ std::vector<Json>(std::move(other.array_value));
break;
case Object:
new (&object_value)
- ctl::map<ctl::string, Json>(ctl::move(other.object_value));
+ std::map<std::string, Json>(std::move(other.object_value));
break;
default:
__builtin_trap();
@@ -308,8 +296,6 @@ Json::getNumber() const
return bool_value;
case Long:
return long_value;
- case Ulong:
- return ulong_value;
case Float:
return float_value;
case Double:
@@ -327,14 +313,6 @@ Json::getLong() const
return long_value;
}
-unsigned long
-Json::getUlong() const
-{
- if (!isUlong())
- __builtin_trap();
- return ulong_value;
-}
-
bool
Json::getBool() const
{
@@ -359,7 +337,7 @@ Json::getDouble() const
return double_value;
}
-ctl::string&
+std::string&
Json::getString()
{
if (!isString())
@@ -367,7 +345,7 @@ Json::getString()
return string_value;
}
-ctl::vector<Json>&
+std::vector<Json>&
Json::getArray()
{
if (!isArray())
@@ -375,7 +353,7 @@ Json::getArray()
return array_value;
}
-ctl::map<ctl::string, Json>&
+std::map<std::string, Json>&
Json::getObject()
{
if (!isObject())
@@ -414,14 +392,6 @@ Json::setLong(long value)
long_value = value;
}
-void
-Json::setUlong(unsigned long value)
-{
- clear();
- type_ = Ulong;
- ulong_value = value;
-}
-
void
Json::setDouble(double value)
{
@@ -435,31 +405,31 @@ Json::setString(const char* value)
{
clear();
type_ = String;
- new (&string_value) ctl::string(value);
+ new (&string_value) std::string(value);
}
void
-Json::setString(ctl::string&& value)
+Json::setString(std::string&& value)
{
clear();
type_ = String;
- new (&string_value) ctl::string(ctl::move(value));
+ new (&string_value) std::string(std::move(value));
}
void
-Json::setString(const ctl::string& value)
+Json::setString(const std::string& value)
{
clear();
type_ = String;
- new (&string_value) ctl::string(value);
+ new (&string_value) std::string(value);
}
void
-Json::setString(const ctl::string_view& value)
+Json::setString(const std::string_view& value)
{
clear();
type_ = String;
- new (&string_value) ctl::string_view(value);
+ new (&string_value) std::string_view(value);
}
void
@@ -467,7 +437,7 @@ Json::setArray()
{
clear();
type_ = Array;
- new (&array_value) ctl::vector<Json>();
+ new (&array_value) std::vector<Json>();
}
void
@@ -475,7 +445,7 @@ Json::setObject()
{
clear();
type_ = Object;
- new (&object_value) ctl::map<ctl::string, Json>();
+ new (&object_value) std::map<std::string, Json>();
}
Json&
@@ -492,7 +462,7 @@ Json::operator[](size_t index) noexcept
}
Json&
-Json::operator[](const ctl::string& key) noexcept
+Json::operator[](const std::string& key) noexcept
{
if (type_ != Object) {
clear();
@@ -501,16 +471,16 @@ Json::operator[](const ctl::string& key) noexcept
return object_value[key];
}
-ctl::string
+std::string
Json::toString(bool pretty) const noexcept
{
- ctl::string b;
+ std::string b;
marshal(b, pretty, 0);
return b;
}
void
-Json::marshal(ctl::string& b, bool pretty, int indent) const noexcept
+Json::marshal(std::string& b, bool pretty, int indent) const noexcept
{
switch (type_) {
case Null:
@@ -527,11 +497,6 @@ Json::marshal(ctl::string& b, bool pretty, int indent) const noexcept
b.append(buf, FormatInt64(buf, long_value) - buf);
break;
}
- case Ulong: {
- char buf[21];
- b.append(buf, FormatUint64(buf, ulong_value) - buf);
- break;
- }
case Float: {
char buf[128];
double_conversion::StringBuilder db(buf, 128);
@@ -602,7 +567,7 @@ Json::marshal(ctl::string& b, bool pretty, int indent) const noexcept
}
void
-Json::stringify(ctl::string& b, const ctl::string_view& s) noexcept
+Json::stringify(std::string& b, const std::string_view& s) noexcept
{
b += '"';
serialize(b, s);
@@ -610,7 +575,7 @@ Json::stringify(ctl::string& b, const ctl::string_view& s) noexcept
}
void
-Json::serialize(ctl::string& sb, const ctl::string_view& s) noexcept
+Json::serialize(std::string& sb, const std::string_view& s) noexcept
{
uint64_t w;
size_t i, j, m;
@@ -828,7 +793,7 @@ Json::parse(Json& json, const char*& p, const char* e, int context, int depth)
return success;
if (status != success)
return status;
- json.getArray().emplace_back(ctl::move(value));
+ json.getArray().emplace_back(std::move(value));
context = ARRAY | COMMA;
}
}
@@ -860,13 +825,13 @@ Json::parse(Json& json, const char*& p, const char* e, int context, int depth)
return object_missing_value;
if (status != success)
return status;
- json[key.getString()] = ctl::move(value);
+ json[key.getString()] = std::move(value);
context = KEY | COMMA | OBJECT;
}
}
case '"': { // string
- ctl::string b;
+ std::string b;
if (context & (COLON | COMMA))
goto OnColonComma;
for (;;) {
@@ -879,7 +844,7 @@ Json::parse(Json& json, const char*& p, const char* e, int context, int depth)
break;
case DQUOTE:
- json.setString(ctl::move(b));
+ json.setString(std::move(b));
return success;
case BACKSLASH:
@@ -1113,11 +1078,11 @@ Json::parse(Json& json, const char*& p, const char* e, int context, int depth)
return unexpected_eof;
}
-ctl::pair<Json::Status, Json>
-Json::parse(const ctl::string_view& s)
+std::pair<Json::Status, Json>
+Json::parse(const std::string_view& s)
{
Json::Status s2;
- ctl::pair<Json::Status, Json> res;
+ std::pair<Json::Status, Json> res;
const char* p = s.data();
const char* e = s.data() + s.size();
res.first = parse(res.second, p, e, 0, DEPTH);
diff --git a/llamafile/server/json.h b/llamafile/server/json.h
index 1f332bce..b8d0574a 100644
--- a/llamafile/server/json.h
+++ b/llamafile/server/json.h
@@ -16,9 +16,9 @@
// limitations under the License.
#pragma once
-#include <ctl/map.h>
-#include <ctl/string.h>
-#include <ctl/vector.h>
+#include <map>
+#include <string>
+#include <vector>
class Json
{
@@ -28,7 +28,6 @@ class Json
Null,
Bool,
Long,
- Ulong,
Float,
Double,
String,
@@ -82,15 +81,14 @@ class Json
long long_value;
float float_value;
double double_value;
- ctl::string string_value;
- unsigned long ulong_value;
- ctl::vector<Json> array_value;
- ctl::map<ctl::string, Json> object_value;
+ std::string string_value;
+ std::vector<Json> array_value;
+ std::map<std::string, Json> object_value;
};
public:
static const char* StatusToString(Status);
- static ctl::pair<Status, Json> parse(const ctl::string_view&);
+ static std::pair<Status, Json> parse(const std::string_view&);
Json(const Json&);
Json(Json&&) noexcept;
@@ -124,27 +122,34 @@ class Json
{
}
- Json(unsigned value) : type_(Ulong), ulong_value(value)
+ Json(unsigned value) : type_(Long), long_value(value)
{
}
- Json(unsigned long value) : type_(Ulong), ulong_value(value)
+ Json(unsigned long value)
{
+ if (value <= LONG_MAX) {
+ type_ = Long;
+ long_value = value;
+ } else {
+ type_ = Double;
+ double_value = value;
+ }
}
Json(const char* value) : type_(String), string_value(value)
{
}
- Json(ctl::string&& value) : type_(String), string_value(ctl::move(value))
+ Json(std::string&& value) : type_(String), string_value(std::move(value))
{
}
- Json(const ctl::string& value) : type_(String), string_value(value)
+ Json(const std::string& value) : type_(String), string_value(value)
{
}
- Json(const ctl::string_view& value) : type_(String), string_value(value)
+ Json(const std::string_view& value) : type_(String), string_value(value)
{
}
@@ -165,12 +170,7 @@ class Json
bool isNumber() const
{
- return isFloat() || isDouble() || isInteger();
- }
-
- bool isInteger() const
- {
- return isLong() || isUlong();
+ return isFloat() || isDouble() || isLong();
}
bool isLong() const
@@ -178,11 +178,6 @@ class Json
return type_ == Long;
}
- bool isUlong() const
- {
- return type_ == Ulong;
- }
-
bool isFloat() const
{
return type_ == Float;
@@ -213,10 +208,9 @@ class Json
float getFloat() const;
double getDouble() const;
double getNumber() const;
- unsigned long getUlong() const;
- ctl::string& getString();
- ctl::vector<Json>& getArray();
- ctl::map<ctl::string, Json>& getObject();
+ std::string& getString();
+ std::vector<Json>& getArray();
+ std::map<std::string, Json>& getObject();
void setNull();
void setBool(bool);
@@ -224,30 +218,29 @@ class Json
void setFloat(float);
void setDouble(double);
void setString(const char*);
- void setUlong(unsigned long);
- void setString(ctl::string&&);
- void setString(const ctl::string&);
- void setString(const ctl::string_view&);
+ void setString(std::string&&);
+ void setString(const std::string&);
+ void setString(const std::string_view&);
void setArray();
void setObject();
- ctl::string toString(bool pretty = false) const noexcept;
+ std::string toString(bool pretty = false) const noexcept;
Json& operator=(const Json&);
Json& operator=(Json&&) noexcept;
Json& operator[](size_t) noexcept;
- Json& operator[](const ctl::string&) noexcept;
+ Json& operator[](const std::string&) noexcept;
- operator ctl::string() const noexcept
+ operator std::string() const noexcept
{
return toString();
}
private:
void clear();
- void marshal(ctl::string&, bool, int) const noexcept;
- static void stringify(ctl::string&, const ctl::string_view&) noexcept;
- static void serialize(ctl::string&, const ctl::string_view&) noexcept;
+ void marshal(std::string&, bool, int) const noexcept;
+ static void stringify(std::string&, const std::string_view&) noexcept;
+ static void serialize(std::string&, const std::string_view&) noexcept;
static Status parse(Json&, const char*&, const char*, int, int);
};
diff --git a/llamafile/server/json_test.cpp b/llamafile/server/json_test.cpp
index c418b49d..de3ebbde 100644
--- a/llamafile/server/json_test.cpp
+++ b/llamafile/server/json_test.cpp
@@ -23,6 +23,8 @@
#include "llamafile/macros.h"
+using namespace std::string_literals;
+
static const char kHuge[] = R"([
"JSON Test Pattern pass1",
{"object with 1 member":["array with 1 element"]},
@@ -116,11 +118,11 @@ deep_test()
A1[3] = 3.14;
A1[4] = 40;
Json A2;
- A2[0] = ctl::move(A1);
+ A2[0] = std::move(A1);
Json A3;
- A3[0] = ctl::move(A2);
+ A3[0] = std::move(A2);
Json obj;
- obj["content"] = ctl::move(A3);
+ obj["content"] = std::move(A3);
if (obj.toString() != "{\"content\":[[[0,10,20,3.14,40]]]}")
exit(2);
}
@@ -128,7 +130,7 @@ deep_test()
void
parse_test()
{
- ctl::pair<Json::Status, Json> res =
+ std::pair<Json::Status, Json> res =
Json::parse("{ \"content\":[[[0,10,20,3.14,40]]]}");
if (res.first != Json::success)
exit(3);
@@ -150,8 +152,8 @@ parse_test()
static const struct
{
- ctl::string before;
- ctl::string after;
+ std::string before;
+ std::string after;
} kRoundTrip[] = {
// valid utf16 sequences
@@ -183,7 +185,7 @@ static const struct
static const struct
{
Json::Status error;
- ctl::string json;
+ std::string json;
} kJsonTestSuite[] = {
{ Json::absent_value, "" },
{ Json::json_payload_should_be_object_or_array, "null" },
@@ -348,7 +350,7 @@ void
round_trip_test()
{
for (size_t i = 0; i < ARRAYLEN(kRoundTrip); ++i) {
- ctl::pair<Json::Status, Json> res = Json::parse(kRoundTrip[i].before);
+ std::pair<Json::Status, Json> res = Json::parse(kRoundTrip[i].before);
if (res.first != Json::success) {
printf("error: Json::parse returned Json::%s but wanted Json::%s: "
"%`'s\n",
@@ -372,7 +374,7 @@ void
json_test_suite()
{
for (size_t i = 0; i < ARRAYLEN(kJsonTestSuite); ++i) {
- ctl::pair<Json::Status, Json> res = Json::parse(kJsonTestSuite[i].json);
+ std::pair<Json::Status, Json> res = Json::parse(kJsonTestSuite[i].json);
if (res.first != kJsonTestSuite[i].error) {
printf("error: Json::parse returned Json::%s but wanted Json::%s: "
"%`'s\n",
diff --git a/llamafile/server/main.cpp b/llamafile/server/main.cpp
index ffa5d6f5..8bdcdcf5 100644
--- a/llamafile/server/main.cpp
+++ b/llamafile/server/main.cpp
@@ -33,11 +33,12 @@
Server* g_server;
llama_model* g_model;
-ctl::string g_url_prefix;
+std::string g_url_prefix;
int
main(int argc, char* argv[])
{
+ signal(SIGPIPE, SIG_IGN);
mallopt(M_GRANULARITY, 2 * 1024 * 1024);
mallopt(M_MMAP_THRESHOLD, 16 * 1024 * 1024);
mallopt(M_TRIM_THRESHOLD, 128 * 1024 * 1024);
diff --git a/llamafile/server/normalize_url_prefix.cpp b/llamafile/server/normalize_url_prefix.cpp
index 6397d95e..38c07ae7 100644
--- a/llamafile/server/normalize_url_prefix.cpp
+++ b/llamafile/server/normalize_url_prefix.cpp
@@ -19,11 +19,11 @@
#include <cosmo.h>
-ctl::string
-normalize_url_prefix(ctl::string url_prefix)
+std::string
+normalize_url_prefix(std::string url_prefix)
{
// Rule 1: Replace multiple slashes with single slash
- while (url_prefix.find("//") != ctl::string::npos) {
+ while (url_prefix.find("//") != std::string::npos) {
url_prefix.replace(url_prefix.find("//"), 2, "/");
}
diff --git a/llamafile/server/or_empty.cpp b/llamafile/server/or_empty.cpp
index fbaa484d..7eb4e01a 100644
--- a/llamafile/server/or_empty.cpp
+++ b/llamafile/server/or_empty.cpp
@@ -17,8 +17,8 @@
#include "utils.h"
-ctl::string_view
-or_empty(ctl::optional<ctl::string_view> x)
+std::string_view
+or_empty(std::optional<std::string_view> x)
{
if (x.has_value())
return x.value();
diff --git a/llamafile/server/path.cpp b/llamafile/server/path.cpp
deleted file mode 100644
index c3aee5a8..00000000
--- a/llamafile/server/path.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-// -*- 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.
-
-#include "path.h"
-
-using namespace ctl;
-
-string
-basename(const string_view path) noexcept
-{
- size_t i, e;
- if ((e = path.size())) {
- while (e > 1 && path[e - 1] == '/')
- --e;
- i = e - 1;
- while (i && path[i - 1] != '/')
- --i;
- return path.substr(i, e - i);
- } else {
- return ".";
- }
-}
-
-string
-dirname(const string_view path) noexcept
-{
- size_t e = path.size();
- if (e--) {
- for (; path[e] == '/'; e--)
- if (!e)
- return "/";
- for (; path[e] != '/'; e--)
- if (!e)
- return ".";
- for (; path[e] == '/'; e--)
- if (!e)
- return "/";
- return path.substr(0, e + 1);
- }
- return ".";
-}
-
-string
-resolve(const string_view lhs, const string_view rhs) noexcept
-{
- if (lhs.empty())
- return rhs;
- if (!rhs.empty() && rhs[0] == '/')
- return rhs;
- if (!lhs.empty() && lhs[lhs.size() - 1] == '/')
- return string(lhs) + rhs;
- return string(lhs) + "/" + rhs;
-}
diff --git a/llamafile/server/server.h b/llamafile/server/server.h
index b5fe4a4d..2ef83455 100644
--- a/llamafile/server/server.h
+++ b/llamafile/server/server.h
@@ -19,7 +19,7 @@
#include <atomic>
#include <cosmo.h>
#include <pthread.h>
-#include <ctl/string.h>
+#include <string>
struct Server
{
@@ -47,7 +47,7 @@ struct Server
};
extern Server* g_server;
-extern ctl::string g_url_prefix;
+extern std::string g_url_prefix;
int
create_listening_socket(const char*);
diff --git a/llamafile/server/slot.cpp b/llamafile/server/slot.cpp
new file mode 100644
index 00000000..55d5040b
--- /dev/null
+++ b/llamafile/server/slot.cpp
@@ -0,0 +1,135 @@
+// -*- 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.
+
+#include "slot.h"
+#include "llamafile/llamafile.h"
+#include "llamafile/macros.h"
+#include "llamafile/server/log.h"
+#include "llamafile/server/model.h"
+#include <algorithm>
+#include <cassert>
+
+static bool
+vector_starts_with(const std::vector<llama_token>& sequence,
+ const std::vector<llama_token>& prefix)
+{
+ if (prefix.size() > sequence.size())
+ return false;
+ return std::equal(prefix.begin(), prefix.end(), sequence.begin());
+}
+
+static int
+ctx_size(void)
+{
+ int n_ctx_train = llama_n_ctx_train(g_model);
+ if (FLAG_ctx_size <= 0 || FLAG_ctx_size > n_ctx_train)
+ return n_ctx_train;
+ return FLAG_ctx_size;
+}
+
+Slot::Slot()
+{
+ dll_init(&elem_);
+}
+
+Slot::~Slot()
+{
+ if (ctx_)
+ llama_free(ctx_);
+}
+
+bool
+Slot::start()
+{
+ unassert(!ctx_);
+ llama_context_params cparams = {};
+ cparams.embeddings = false;
+ cparams.embeddings_only = false;
+ cparams.logits_all = false;
+ cparams.seed = _rand64();
+ cparams.n_ctx = ctx_size();
+ cparams.n_batch = FLAG_batch;
+ cparams.n_ubatch = FLAG_ubatch;
+ cparams.n_seq_max = 1;
+ cparams.n_threads = FLAG_threads;
+ cparams.n_threads_batch = MIN(FLAG_threads, 20);
+ cparams.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE;
+ cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
+ cparams.rope_freq_base = 0;
+ cparams.yarn_ext_factor = -1;
+ cparams.yarn_attn_factor = 1;
+ cparams.yarn_beta_fast = 32;
+ cparams.yarn_beta_slow = 1;
+ cparams.yarn_orig_ctx = 0;
+ cparams.defrag_thold = -1;
+ cparams.type_k = GGML_TYPE_F16;
+ cparams.type_v = GGML_TYPE_F16;
+ cparams.flash_attn = FLAG_flash_attn;
+ ctx_ = llama_new_context_with_model(g_model, cparams);
+ return ctx_ != nullptr;
+}
+
+int
+Slot::n_ctx()
+{
+ return llama_n_ctx(ctx_);
+}
+
+bool
+Slot::eval_token(llama_token id)
+{
+ std::vector<llama_token> tokens;
+ tokens.push_back(id);
+ return eval_tokens(tokens);
+}
+
+bool
+Slot::eval_tokens(std::vector<llama_token> tokens)
+{
+ unassert(ctx_);
+ if (history_.size() + tokens.size() > n_ctx())
+ return false;
+ for (int i = 0; i < tokens.size(); i += FLAG_batch) {
+ int n_eval = (int)tokens.size() - i;
+ if (n_eval > FLAG_batch)
+ n_eval = FLAG_batch;
+ if (llama_decode(
+ ctx_,
+ llama_batch_get_one(&tokens[i], n_eval, history_.size(), 0)))
+ return false;
+ history_.insert(
+ history_.end(), tokens.begin() + i, tokens.begin() + i + n_eval);
+ }
+ last_used_ = timespec_real();
+ return true;
+}
+
+bool
+Slot::can_use_slot(const std::vector<llama_token>& prompt)
+{
+ return ctx_ && vector_starts_with(prompt, history_);
+}
+
+bool
+Slot::prefill(const std::vector<llama_token>& tokens)
+{
+ unassert(can_use_slot(tokens));
+ if (history_.empty())
+ return eval_tokens(tokens);
+ return eval_tokens(
+ std::vector<llama_token>(tokens.begin() + history_.size(), tokens.end()));
+}
diff --git a/llamafile/server/slot.h b/llamafile/server/slot.h
new file mode 100644
index 00000000..a95546dd
--- /dev/null
+++ b/llamafile/server/slot.h
@@ -0,0 +1,43 @@
+// -*- 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"
+#include <cosmo.h>
+#include <stdatomic.h>
+#include <time.h>
+#include <vector>
+
+#define SLOT(e) DLL_CONTAINER(Slot, elem, e)
+
+struct Slot
+{
+ Dll elem_;
+ atomic_int refs_ = 0;
+ llama_context* ctx_ = nullptr;
+ timespec last_used_ = timespec_zero;
+ std::vector<llama_token> history_;
+
+ Slot();
+ ~Slot();
+ int n_ctx();
+ bool start();
+ bool eval_token(llama_token);
+ bool eval_tokens(std::vector<llama_token>);
+ bool can_use_slot(const std::vector<llama_token>&);
+ bool prefill(const std::vector<llama_token>&);
+};
diff --git a/llamafile/server/slots.cpp b/llamafile/server/slots.cpp
new file mode 100644
index 00000000..5966454a
--- /dev/null
+++ b/llamafile/server/slots.cpp
@@ -0,0 +1,26 @@
+// -*- 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.
+
+#include "slots.h"
+
+Slots::Slots()
+{
+}
+
+Slots::~Slots()
+{
+}
diff --git a/llamafile/server/path.h b/llamafile/server/slots.h
similarity index 77%
rename from llamafile/server/path.h
rename to llamafile/server/slots.h
index c24822f5..933dae7a 100644
--- a/llamafile/server/path.h
+++ b/llamafile/server/slots.h
@@ -16,13 +16,14 @@
// limitations under the License.
#pragma once
-#include <ctl/string.h>
+#include <cosmo.h>
+#include <pthread.h>
-ctl::string
-dirname(const ctl::string_view) noexcept;
+struct Slots
+{
+ Dll* slots_ = nullptr;
+ pthread_mutex_t lock_ = PTHREAD_MUTEX_INITIALIZER;
-ctl::string
-basename(const ctl::string_view) noexcept;
-
-ctl::string
-resolve(const ctl::string_view, const ctl::string_view) noexcept;
+ Slots();
+ ~Slots();
+};
diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cpp
index 38f0dd08..2742975b 100644
--- a/llamafile/server/tokenize.cpp
+++ b/llamafile/server/tokenize.cpp
@@ -17,10 +17,10 @@
#include "client.h"
-#include <ctl/pair.h>
-#include <ctl/vector.h>
#include <string.h>
#include <sys/resource.h>
+#include <utility>
+#include <vector>
#include "llama.cpp/llama.h"
@@ -36,8 +36,8 @@ struct TokenizeParams
{
bool add_special;
bool parse_special;
- ctl::string_view prompt;
- ctl::string content;
+ std::string_view prompt;
+ std::string content;
};
void
@@ -51,7 +51,7 @@ 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");
+ std::optional<std::string_view> prompt = param("prompt");
if (prompt.has_value()) {
params->prompt = prompt.value();
} else if (HasHeader(kHttpContentType)) {
@@ -62,14 +62,14 @@ Client::get_tokenize_params(TokenizeParams* params)
} else if (IsMimeType(HeaderData(kHttpContentType),
HeaderLength(kHttpContentType),
"application/json")) {
- ctl::pair<Json::Status, Json> json = Json::parse(payload);
+ std::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->content = std::move(json.second["prompt"].getString());
params->prompt = params->content;
if (json.second["add_special"].isBool())
params->add_special = json.second["add_special"].getBool();
@@ -109,7 +109,7 @@ Client::tokenize()
timespec started = timespec_real();
// turn text into tokens
- auto toks = new ctl::vector<llama_token>(params->prompt.size() + 16);
+ auto toks = new std::vector<llama_token>(params->prompt.size() + 16);
defer_cleanup(cleanup_token_vector, toks);
int count = llama_tokenize(g_model,
params->prompt.data(),
@@ -145,11 +145,11 @@ Client::tokenize()
SLOG("failed to turn token into string");
return send_error(405);
}
- p = encode_json(p, ctl::string_view(s, n));
+ p = encode_json(p, std::string_view(s, n));
}
p = stpcpy(p, "\n ]\n");
p = stpcpy(p, "}\n");
- ctl::string_view content(obuf.p, p - obuf.p);
+ std::string_view content(obuf.p, p - obuf.p);
// collect statistics
rusage ruend = {};
diff --git a/llamafile/server/utils.h b/llamafile/server/utils.h
index 9e1c3ae6..495f3c84 100644
--- a/llamafile/server/utils.h
+++ b/llamafile/server/utils.h
@@ -16,17 +16,17 @@
// limitations under the License.
#pragma once
-#include <ctl/optional.h>
-#include <ctl/string.h>
-#include <ctl/string_view.h>
+#include <optional>
+#include <string>
+#include <string_view>
extern const signed char kHexToInt[256];
bool
-atob(ctl::string_view, bool);
+atob(std::string_view, bool);
-ctl::string_view
-or_empty(ctl::optional<ctl::string_view> x);
+std::string_view
+or_empty(std::optional<std::string_view> x);
-ctl::string
-normalize_url_prefix(ctl::string url_prefix);
+std::string
+normalize_url_prefix(std::string url_prefix);
diff --git a/llamafile/server/v1_chat_completions.cpp b/llamafile/server/v1_chat_completions.cpp
new file mode 100644
index 00000000..933c96b7
--- /dev/null
+++ b/llamafile/server/v1_chat_completions.cpp
@@ -0,0 +1,526 @@
+// -*- 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.
+
+#include "client.h"
+
+#include <math.h>
+#include <string.h>
+#include <sys/resource.h>
+#include <vector>
+
+#include "llama.cpp/llama.h"
+#include "llama.cpp/sampling.h"
+#include "llamafile/macros.h"
+#include "llamafile/string.h"
+
+#include "cleanup.h"
+#include "fastjson.h"
+#include "json.h"
+#include "log.h"
+#include "model.h"
+#include "slot.h"
+#include "utils.h"
+
+struct V1ChatCompletionParams
+{
+ bool stream = false;
+ long max_tokens = -1;
+ long seed = _rand64();
+ double top_p = 1;
+ double temperature = 1;
+ double presence_penalty = 0;
+ double frequency_penalty = 0;
+ std::string user;
+ std::string model;
+ std::vector<llama_chat_msg> messages;
+ std::vector<std::vector<llama_token>> stop;
+ std::string grammar;
+
+ void add_stop(const std::string& text)
+ {
+ stop.emplace_back(llama_tokenize(g_model, text, false, false));
+ }
+};
+
+struct V1ChatCompletionResponse
+{
+ std::string prompt;
+ std::vector<llama_token> tokens;
+ std::string content;
+ Json json;
+};
+
+static bool
+is_legal_role(const std::string_view& role)
+{
+ return role == "system" || //
+ role == "user" || //
+ role == "assistant";
+}
+
+static void
+cleanup_params(void* arg)
+{
+ delete (V1ChatCompletionParams*)arg;
+}
+
+static void
+cleanup_response(void* arg)
+{
+ delete (V1ChatCompletionResponse*)arg;
+}
+
+static void
+cleanup_sampler(void* arg)
+{
+ llama_sampling_free((llama_sampling_context*)arg);
+}
+
+static void
+cleanup_slot(void* arg)
+{
+ delete (Slot*)arg;
+}
+
+static std::string
+generate_id()
+{
+ std::string b = "chatcmpl-";
+ for (int i = 0; i < 2; ++i) {
+ uint64_t w = _rand64();
+ for (int j = 0; j < 64 / 5; ++j) {
+ b += "abcdefghijklmnopqrstuvwxyz012345"[w & 31];
+ w >>= 5;
+ }
+ }
+ return b;
+}
+
+static llama_sampling_context*
+create_sampler(const V1ChatCompletionParams* params)
+{
+ llama_sampling_params sparams;
+ sparams.temp = params->temperature;
+ sparams.top_p = params->top_p;
+ sparams.penalty_freq = params->frequency_penalty;
+ sparams.penalty_present = params->presence_penalty;
+ sparams.seed = params->seed;
+ sparams.grammar = params->grammar;
+ return llama_sampling_init(sparams);
+}
+
+static std::string
+make_event(const Json& json)
+{
+ std::string s = "data: ";
+ s += json.toString();
+ s += "\n\n";
+ return s;
+}
+
+bool
+Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)
+{
+ // must be json post request
+ if (msg.method != kHttpPost)
+ return send_error(405);
+ if (!HasHeader(kHttpContentType) ||
+ !IsMimeType(HeaderData(kHttpContentType),
+ HeaderLength(kHttpContentType),
+ "application/json")) {
+ return send_error(501, "Content Type Not Implemented");
+ }
+ if (!read_payload())
+ return false;
+
+ // object<model, messages, ...>
+ std::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");
+
+ // fields openai documents that we don't support yet
+ if (!json.second["n"].isNull())
+ return send_error(400, "OpenAI n field not supported");
+ if (!json.second["tools"].isNull())
+ return send_error(400, "OpenAI tools field not supported");
+ if (!json.second["audio"].isNull())
+ return send_error(400, "OpenAI audio field not supported");
+ if (!json.second["logprobs"].isNull())
+ return send_error(400, "OpenAI logprobs field not supported");
+ if (!json.second["functions"].isNull())
+ return send_error(400, "OpenAI functions field not supported");
+ if (!json.second["modalities"].isNull())
+ return send_error(400, "OpenAI modalities field not supported");
+ if (!json.second["tool_choice"].isNull())
+ return send_error(400, "OpenAI tool_choice field not supported");
+ if (!json.second["top_logprobs"].isNull())
+ return send_error(400, "OpenAI top_logprobs field not supported");
+ if (!json.second["function_call"].isNull())
+ return send_error(400, "OpenAI function_call field not supported");
+ if (!json.second["parallel_tool_calls"].isNull())
+ return send_error(400, "parallel_tool_calls field not supported");
+
+ // model: string
+ Json& model = json.second["model"];
+ if (!model.isString())
+ return send_error(400, "JSON missing model string");
+ params->model = std::move(model.getString());
+
+ // messages: array<object<role:string, content:string>>
+ if (!json.second["messages"].isArray())
+ return send_error(400, "JSON missing messages array");
+ std::vector<Json>& messages = json.second["messages"].getArray();
+ for (Json& message : messages) {
+ if (!message.isObject())
+ return send_error(400, "messages array must hold objects");
+ if (!message["role"].isString())
+ return send_error(400, "message must have string role");
+ if (!is_legal_role(message["role"].getString()))
+ return send_error(400, "message role not system user assistant");
+ if (!message["content"].isString())
+ return send_error(400, "message must have string content");
+ params->messages.emplace_back(
+ std::move(message["role"].getString()),
+ std::move(message["content"].getString()));
+ }
+
+ // stream: bool|null
+ //
+ // If set, partial message deltas will be sent, like in ChatGPT.
+ // Tokens will be sent as data-only server-sent events as they
+ // become available, with the stream terminated by a data: [DONE]
+ // message.
+ Json& stream = json.second["stream"];
+ if (!stream.isNull()) {
+ if (!stream.isBool())
+ return send_error(400, "stream field must be boolean");
+ params->stream = stream.getBool();
+ }
+
+ // max_tokens: integer|null
+ //
+ // An upper bound for the number of tokens that can be generated for
+ // a completion. This can be used to control costs.
+ Json& max_tokens = json.second["max_tokens"];
+ if (!max_tokens.isNull()) {
+ if (!max_tokens.isLong())
+ return send_error(400, "max_tokens must be integer");
+ params->max_tokens = max_tokens.getLong();
+ }
+ Json& max_completion_tokens = json.second["max_completion_tokens"];
+ if (!max_completion_tokens.isNull()) {
+ if (!max_completion_tokens.isLong())
+ return send_error(400, "max_completion_tokens must be integer");
+ params->max_tokens = max_completion_tokens.getNumber();
+ }
+
+ // top_p: number|null
+ //
+ // An alternative to sampling with temperature, called nucleus
+ // sampling, where the model considers the results of the tokens
+ // with top_p probability mass. So 0.1 means only the tokens
+ // comprising the top 10% probability mass are considered.
+ //
+ // We generally recommend altering this or temperature but not both.
+ Json& top_p = json.second["top_p"];
+ if (!top_p.isNull()) {
+ if (!top_p.isNumber())
+ return send_error(400, "top_p must be number");
+ params->top_p = top_p.getNumber();
+ }
+
+ // temperature: number|null
+ //
+ // What sampling temperature to use, between 0 and 2. Higher values
+ // like 0.8 will make the output more random, while lower values
+ // like 0.2 will make it more focused and deterministic.
+ //
+ // We generally recommend altering this or top_p but not both.
+ Json& temperature = json.second["temperature"];
+ if (!temperature.isNull()) {
+ if (!temperature.isNumber())
+ return send_error(400, "temperature must be number");
+ params->temperature = temperature.getNumber();
+ if (!(0 <= params->temperature && params->temperature <= 2))
+ return send_error(400, "temperature must be between 0 and 2");
+ }
+
+ // seed: integer|null
+ //
+ // If specified, our system will make a best effort to sample
+ // deterministically, such that repeated requests with the same seed
+ // and parameters should return the same result. Determinism is not
+ // guaranteed, and you should refer to the system_fingerprint
+ // response parameter to monitor changes in the backend.
+ Json& seed = json.second["seed"];
+ if (!seed.isNull()) {
+ if (!seed.isLong())
+ return send_error(400, "seed must be integer");
+ params->seed = seed.getLong();
+ }
+
+ // presence_penalty: number|null
+ //
+ // Number between -2.0 and 2.0. Positive values penalize new tokens
+ // based on whether they appear in the text so far, increasing the
+ // model's likelihood to talk about new topics.
+ Json& presence_penalty = json.second["presence_penalty"];
+ if (!presence_penalty.isNull()) {
+ if (!presence_penalty.isNumber())
+ return send_error(400, "presence_penalty must be number");
+ params->presence_penalty = presence_penalty.getNumber();
+ if (!(-2 <= params->presence_penalty && params->presence_penalty <= 2))
+ return send_error(400, "presence_penalty must be between -2 and 2");
+ }
+
+ // frequency_penalty: number|null
+ //
+ // Number between -2.0 and 2.0. Positive values penalize new tokens
+ // based on their existing frequency in the text so far, decreasing
+ // the model's likelihood to repeat the same line verbatim.
+ Json& frequency_penalty = json.second["frequency_penalty"];
+ if (!frequency_penalty.isNull()) {
+ if (!frequency_penalty.isNumber())
+ return send_error(400, "frequency_penalty must be number");
+ params->frequency_penalty = frequency_penalty.getNumber();
+ if (!(-2 <= params->frequency_penalty &&
+ params->frequency_penalty <= 2))
+ return send_error(400, "frequency_penalty must be -2 through 2");
+ }
+
+ // user: string|null
+ //
+ // A unique identifier representing your end-user, which can help
+ // llamafile to monitor and detect abuse. Learn more.
+ Json& user = json.second["user"];
+ if (!user.isNull()) {
+ if (!user.isString())
+ return send_error(400, "JSON missing user string");
+ params->user = std::move(user.getString());
+ }
+
+ // stop: string|array<string>|null
+ //
+ // Up to 4 sequences where the API will stop generating further tokens.
+ Json& stop = json.second["stop"];
+ if (!stop.isNull()) {
+ if (stop.isString()) {
+ params->add_stop(stop.getString());
+ } else if (stop.isArray()) {
+ std::vector<Json>& stops = stop.getArray();
+ if (stops.size() > 4)
+ return send_error(400, "stop array must have 4 items or fewer");
+ for (Json& stop2 : stops) {
+ if (!stop2.isString())
+ return send_error(400, "stop array item must be string");
+ if (stop2.getString().size() > 50)
+ return send_error(400, "stop array string too long");
+ params->add_stop(stop2.getString());
+ }
+ } else {
+ return send_error(400, "stop field must be string or string array");
+ }
+ }
+
+ // response_format: "auto"
+ // response_format: { "type": "json_object" }
+ // response_format: { "type": "json_schema", "json_schema": {...} }
+ //
+ // An object specifying the format that the model must output.
+ //
+ // Setting to { "type": "json_schema", "json_schema": {...} }
+ // enables Structured Outputs which ensures the model will match
+ // your supplied JSON schema. Learn more in the Structured Outputs
+ // guide.
+ //
+ // Setting to { "type": "json_object" } enables JSON mode, which
+ // ensures the message the model generates is valid JSON.
+ //
+ // When using JSON mode, you must also instruct the model to produce
+ // JSON yourself via a system or user message. Without this, the
+ // model may generate an unending stream of whitespace until the
+ // generation reaches the token limit, resulting in a long-running
+ // and seemingly "stuck" request. Also note that the message content
+ // may be partially cut off if finish_reason = "length", which
+ // indicates the generation exceeded max_tokens or the conversation
+ // exceeded the max context length.
+ Json& response_format = json.second["response_format"];
+ if (!response_format.isNull()) {
+ if (response_format.isString()) {
+ if (response_format.getString() != "auto")
+ return send_error(400, "response_format not supported");
+ } else if (response_format.isObject()) {
+ Json& type = response_format.getObject()["type"];
+ if (!type.isString())
+ return send_error(400, "response_format.type must be string");
+ if (type.getString() == "json_object") {
+ params->grammar =
+ json_schema_string_to_grammar("{\"type\": \"object\"}");
+ } else if (type.getString() == "json_schema") {
+ Json& json_schema = response_format.getObject()["json_schema"];
+ if (!json_schema.isObject())
+ return send_error(
+ 400, "response_format.json_schema must be object");
+ try {
+ params->grammar =
+ json_schema_string_to_grammar(json_schema.toString());
+ } catch (const std::exception& e) {
+ SLOG("error: couldn't compile json schema: %s", e.what());
+ return send_error(400, "bad json schema");
+ }
+ } else {
+ return send_error(400, "response_format.type unsupported");
+ }
+ } else {
+ return send_error(400, "response_format must be string or object");
+ }
+ }
+
+ return true;
+}
+
+bool
+Client::v1_chat_completions()
+{
+ // get parameters
+ auto params = new V1ChatCompletionParams;
+ defer_cleanup(cleanup_params, params);
+ if (!get_v1_chat_completions_params(params))
+ return false;
+
+ // create response object
+ V1ChatCompletionResponse* response = new V1ChatCompletionResponse;
+ defer_cleanup(cleanup_response, response);
+
+ // turn text into tokens
+ response->prompt =
+ llama_chat_apply_template(g_model, "", params->messages, true);
+ response->tokens = llama_tokenize(g_model, response->prompt, true, false);
+
+ // find appropriate slot
+ Slot* slot;
+ slot = new Slot;
+ if (!slot->start()) {
+ delete slot;
+ SLOG("failed to create slot");
+ return send_error(500);
+ }
+ defer_cleanup(cleanup_slot, slot);
+
+ // sanity check
+ if (response->tokens.size() + 1 > slot->n_ctx())
+ return send_error(400, "prompt too big for model context size");
+
+ // init sampling
+ llama_sampling_context* sampler = create_sampler(params);
+ if (!sampler)
+ return send_error(500, "failed to create sampler");
+ defer_cleanup(cleanup_sampler, sampler);
+
+ // prefill time
+ if (!slot->prefill(response->tokens)) {
+ SLOG("slot prefill failed");
+ return send_error(500, "llama_decode prefill failed");
+ }
+
+ // setup response json
+ response->json["id"].setString(generate_id());
+ response->json["object"].setString("chat.completion");
+ response->json["model"].setString(params->model);
+ response->json["choices"].setArray();
+ Json& choice = response->json["choices"][0];
+ choice.setObject();
+ choice["index"].setLong(0);
+ choice["logprobs"].setNull();
+ choice["finish_reason"].setNull();
+
+ // initialize response
+ if (params->stream) {
+ char* p = append_http_response_message(obuf.p, 200);
+ p = stpcpy(p, "Content-Type: text/event-stream\r\n");
+ if (!send_response_start(obuf.p, p))
+ return false;
+ choice["delta"].setObject();
+ choice["delta"]["role"].setString("assistant");
+ choice["delta"]["content"].setString("");
+ response->json["created"].setLong(timespec_real().tv_sec);
+ response->content = make_event(response->json);
+ choice.getObject().erase("delta");
+ if (!send_response_chunk(response->content))
+ return false;
+ }
+
+ // prediction time
+ int completion_tokens = 0;
+ const char* finish_reason = "length";
+ while (params->max_tokens < 0 || completion_tokens < params->max_tokens) {
+ llama_token id = llama_sampling_sample(sampler, slot->ctx_, NULL);
+ llama_sampling_accept(sampler, slot->ctx_, id, true);
+ if (llama_token_is_eog(g_model, id)) {
+ finish_reason = "stop";
+ break;
+ }
+ ++completion_tokens;
+ std::string piece = llama_token_to_piece(slot->ctx_, id, false);
+ if (params->stream) {
+ char* p = append_http_response_message(obuf.p, 200);
+ choice["delta"].setObject();
+ choice["delta"]["content"].setString(piece);
+ response->json["created"].setLong(timespec_real().tv_sec);
+ response->content = make_event(response->json);
+ choice.getObject().erase("delta");
+ if (!send_response_chunk(response->content))
+ return false;
+ } else {
+ response->content += piece;
+ }
+ if (!slot->eval_token(id)) {
+ SLOG("ran out of context window");
+ break;
+ }
+ }
+ choice["finish_reason"].setString(finish_reason);
+
+ // finalize response
+ if (params->stream) {
+ choice["delta"].setObject();
+ choice["delta"]["content"].setString("");
+ response->json["created"].setLong(timespec_real().tv_sec);
+ response->content = make_event(response->json);
+ choice.getObject().erase("delta");
+ if (!send_response_chunk(response->content))
+ return false;
+ return send_response_finish();
+ } else {
+ Json& usage = response->json["usage"];
+ usage.setObject();
+ usage["prompt_tokens"].setLong(response->tokens.size());
+ usage["completion_tokens"].setLong(completion_tokens);
+ usage["total_tokens"].setLong(completion_tokens +
+ response->tokens.size());
+ choice["message"].setObject();
+ choice["message"]["role"].setString("assistant");
+ choice["message"]["content"].setString(std::move(response->content));
+ response->json["created"].setLong(timespec_real().tv_sec);
+ char* p = append_http_response_message(obuf.p, 200);
+ p = stpcpy(p, "Content-Type: application/json\r\n");
+ response->content = response->json.toString();
+ return send_response(obuf.p, p, response->content);
+ }
+}
diff --git a/llamafile/string.cpp b/llamafile/string.cpp
index b032094d..ee0da99a 100644
--- a/llamafile/string.cpp
+++ b/llamafile/string.cpp
@@ -18,11 +18,14 @@
#include "string.h"
#include <cosmo.h>
+#include <ctype.h>
+
+namespace lf {
std::string tolower(const std::string_view &s) {
std::string b;
for (char c : s)
- b += tolower(c);
+ b += std::tolower(c);
return b;
}
@@ -36,3 +39,77 @@ void append_wchar(std::string *r, wchar_t c) {
*r += s;
}
}
+
+std::string format(const char *fmt, ...) {
+ va_list ap, ap2;
+ va_start(ap, fmt);
+ va_copy(ap2, ap);
+ int size = 512;
+ std::string res(size, '\0');
+ int need = vsnprintf(res.data(), size, fmt, ap);
+ res.resize(need + 1, '\0');
+ if (need + 1 > size)
+ vsnprintf(res.data(), need + 1, fmt, ap2);
+ va_end(ap2);
+ va_end(ap);
+ return res;
+}
+
+std::string basename(const std::string_view path) {
+ size_t i, e;
+ if ((e = path.size())) {
+ while (e > 1 && path[e - 1] == '/')
+ --e;
+ i = e - 1;
+ while (i && path[i - 1] != '/')
+ --i;
+ return std::string(path.substr(i, e - i));
+ } else {
+ return ".";
+ }
+}
+
+std::string extname(const std::string_view path) {
+ std::string name = basename(path);
+ size_t dot_pos = name.find_last_of('.');
+ if (dot_pos == std::string::npos || dot_pos == name.length() - 1)
+ return name;
+ return std::string(name.substr(dot_pos + 1));
+}
+
+std::string dirname(const std::string_view path) {
+ size_t e = path.size();
+ if (e--) {
+ for (; path[e] == '/'; e--)
+ if (!e)
+ return "/";
+ for (; path[e] != '/'; e--)
+ if (!e)
+ return ".";
+ for (; path[e] == '/'; e--)
+ if (!e)
+ return "/";
+ return std::string(path.substr(0, e + 1));
+ }
+ return ".";
+}
+
+std::string resolve(const std::string_view lhs, const std::string_view rhs) {
+ if (lhs.empty())
+ return std::string(rhs);
+ if (!rhs.empty() && rhs[0] == '/')
+ return std::string(rhs);
+ if (!lhs.empty() && lhs[lhs.size() - 1] == '/') {
+ std::string res;
+ res += lhs;
+ res += rhs;
+ return res;
+ }
+ std::string res;
+ res += lhs;
+ res += '/';
+ res += rhs;
+ return res;
+}
+
+} // namespace lf
diff --git a/llamafile/string.h b/llamafile/string.h
index 1a6a46ca..cc99d4a4 100644
--- a/llamafile/string.h
+++ b/llamafile/string.h
@@ -18,5 +18,14 @@
#pragma once
#include <string>
+namespace lf {
+
+std::string basename(const std::string_view);
+std::string dirname(const std::string_view);
+std::string extname(const std::string_view);
+std::string format(const char *, ...) __attribute__((format(printf, 1, 2)));
+std::string resolve(const std::string_view, const std::string_view);
std::string tolower(const std::string_view &);
void append_wchar(std::string *, wchar_t);
+
+} // namespace lf
diff --git a/llamafile/trust.cpp b/llamafile/trust.cpp
index 7266d076..761ad0b6 100644
--- a/llamafile/trust.cpp
+++ b/llamafile/trust.cpp
@@ -17,7 +17,7 @@
#include "trust.h"
-ctl::vector<cidr> FLAG_trust;
+std::vector<cidr> FLAG_trust;
bool is_trusted_ip(unsigned ip) noexcept {
for (auto c : FLAG_trust)
diff --git a/llamafile/trust.h b/llamafile/trust.h
index 7443f40d..682621ab 100644
--- a/llamafile/trust.h
+++ b/llamafile/trust.h
@@ -16,8 +16,8 @@
// limitations under the License.
#pragma once
-#include <ctl/string.h>
-#include <ctl/vector.h>
+#include <string>
+#include <vector>
struct cidr {
unsigned ip;
@@ -29,9 +29,9 @@ struct cidr {
}
};
-extern ctl::vector<cidr> FLAG_trust;
+extern std::vector<cidr> FLAG_trust;
bool is_trusted_ip(unsigned) noexcept;
bool is_loopback_ip(unsigned) noexcept;
-long parse_ip(const ctl::string_view &) noexcept;
-bool parse_cidr(const ctl::string_view &, cidr *) noexcept;
+long parse_ip(const std::string_view &) noexcept;
+bool parse_cidr(const std::string_view &, cidr *) noexcept;