Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Get basic chatbot web gui working in llamafiler
Justine Tunney14713b51d101
diff --git a/llamafile/flags.cpp b/llamafile/flags.cppindex d8ef693a..6d0581ff 100644--- a/llamafile/flags.cpp+++ b/llamafile/flags.cpp@@ -20,6 +20,7 @@#include "llamafile.h"#include "trust.h"+#include <cosmo.h>#include <errno.h>#include <fcntl.h>#include <limits.h>@@ -49,7 +50,8 @@ const char *FLAG_ip_header = nullptr;const char *FLAG_listen = "0.0.0.0:8080";const char *FLAG_model = nullptr;const char *FLAG_prompt = nullptr;-const char *FLAG_url_prefix = nullptr;+const char *FLAG_url_prefix = "";+const char *FLAG_www_root = "/zip/www";double FLAG_token_rate = 1;float FLAG_temp = 0.8;int FLAG_batch = 2048;@@ -140,13 +142,6 @@ void llamafile_get_flags(int argc, char **argv) {continue;}- if (!strcmp(flag, "--url-prefix")) {- if (i == argc)- missing("--url-prefix");- FLAG_url_prefix = argv[i++];- continue;- }-if (!strcmp(flag, "-k") || !strcmp(flag, "--keepalive")) {if (i == argc)missing("--keepalive");@@ -219,6 +214,28 @@ void llamafile_get_flags(int argc, char **argv) {//////////////////////////////////////////////////////////////////////// http server flags+ if (!strcmp(flag, "--www-root")) {+ if (i == argc)+ missing("--www-root");+ FLAG_www_root = argv[i++];+ continue;+ }++ if (!strcmp(flag, "--url-prefix")) {+ if (i == argc)+ missing("--url-prefix");+ FLAG_url_prefix = argv[i++];+ if (!IsAcceptablePath(FLAG_url_prefix, -1)) {+ tinyprint(2, "error: --url-prefix must not have // or /. or /./ or /../\n", NULL);+ exit(1);+ }+ if (endswith(FLAG_url_prefix, "/")) {+ tinyprint(2, "error: --url-prefix must not be slash or end with slash\n", NULL);+ exit(1);+ }+ continue;+ }+if (!strcmp(flag, "--http-ibuf-size")) {if (i == argc)missing("--http-ibuf-size");diff --git a/llamafile/llamafile.h b/llamafile/llamafile.hindex 2f853670..ade93ea4 100644--- a/llamafile/llamafile.h+++ b/llamafile/llamafile.h@@ -26,6 +26,7 @@ extern const char *FLAG_listen;extern const char *FLAG_model;extern const char *FLAG_prompt;extern const char *FLAG_url_prefix;+extern const char *FLAG_www_root;extern double FLAG_token_rate;extern float FLAG_temp;extern int FLAG_batch;diff --git a/llamafile/server/BUILD.mk b/llamafile/server/BUILD.mkindex 66019571..f170bd8b 100644--- a/llamafile/server/BUILD.mk+++ b/llamafile/server/BUILD.mk@@ -8,6 +8,7 @@ LLAMAFILE_SERVER_HDRS = $(filter %.h,$(LLAMAFILE_SERVER_FILES))LLAMAFILE_SERVER_INCS = $(filter %.inc,$(LLAMAFILE_SERVER_FILES))LLAMAFILE_SERVER_SRCS = $(filter %.cpp,$(LLAMAFILE_SERVER_FILES))LLAMAFILE_SERVER_OBJS = $(LLAMAFILE_SERVER_SRCS:%.cpp=o/$(MODE)/%.o)+LLAMAFILE_SERVER_ASSETS = $(wildcard llamafile/server/www/*)$(LLAMAFILE_SERVER_OBJS): private CCFLAGS += -g@@ -22,6 +23,11 @@ o/$(MODE)/llamafile/server/main: \o/$(MODE)/llama.cpp/llava/llava.a \o/$(MODE)/double-conversion/double-conversion.a \o/$(MODE)/stb/stb.a \+ $(LLAMAFILE_SERVER_ASSETS:%=o/$(MODE)/%.zip.o)++# turn /zip/llamafile/server/www/...+# into /zip/www/...+$(LLAMAFILE_SERVER_ASSETS:%=o/$(MODE)/%.zip.o): private ZIPOBJ_FLAGS += -C2$(LLAMAFILE_SERVER_OBJS): llamafile/server/BUILD.mkdiff --git a/llamafile/server/cleanup.cpp b/llamafile/server/cleanup.cppindex 1e25418c..6d2d7b02 100644--- a/llamafile/server/cleanup.cpp+++ b/llamafile/server/cleanup.cpp@@ -17,10 +17,17 @@#include "cleanup.h"+#include <unistd.h>#include <vector>#include "llama.cpp/llama.h"+void+cleanup_fildes(void* arg)+{+ close((intptr_t)arg);+}+voidcleanup_float_vector(void* arg){diff --git a/llamafile/server/cleanup.h b/llamafile/server/cleanup.hindex 7f9ecb7e..5fc0221a 100644--- a/llamafile/server/cleanup.h+++ b/llamafile/server/cleanup.h@@ -17,6 +17,9 @@#pragma once+void+cleanup_fildes(void*);+voidcleanup_float_vector(void*);diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cppindex 3d250174..b793bf3d 100644--- a/llamafile/server/client.cpp+++ b/llamafile/server/client.cpp@@ -21,16 +21,19 @@#include <fcntl.h>#include <limits.h>#include <string.h>+#include <sys/stat.h>#include <sys/uio.h>#include <time.h>#include <unistd.h>#include "llama.cpp/llama.h"#include "llamafile/llamafile.h"+#include "llamafile/string.h"#include "llamafile/threadlocal.h"#include "llamafile/trust.h"#include "llamafile/version.h"+#include "cleanup.h"#include "log.h"#include "server.h"#include "time.h"@@ -42,27 +45,34 @@"Referrer-Policy: origin\r\n" \"Cache-Control: private; max-age=0\r\n"-using namespace std;-static voidon_http_cancel(Client* client){- if (client->should_send_error_if_canceled) {- fcntl(client->fd, F_SETFL, fcntl(client->fd, F_GETFL) | O_NONBLOCK);+ if (client->should_send_error_if_canceled_) {+ fcntl(client->fd_, F_SETFL, fcntl(client->fd_, F_GETFL) | O_NONBLOCK);client->send_error(503);}}static ThreadLocal<Client> g_http_cancel(on_http_cancel);+static const char*+pick_content_type(const std::string_view& path)+{+ const char* ct = FindContentType(path.data(), path.size());+ if (!ct)+ ct = "application/octet-stream";+ return ct;+}+Client::Client(llama_model* model): model_(model)- , cleanups(nullptr)- , ibuf(FLAG_http_ibuf_size)- , obuf(FLAG_http_obuf_size)+ , cleanups_(nullptr)+ , ibuf_(FLAG_http_ibuf_size)+ , obuf_(FLAG_http_obuf_size){- InitHttpMessage(&msg, 0);- url.params.p = nullptr;+ InitHttpMessage(&msg_, 0);+ url_.params.p = nullptr;}int@@ -70,12 +80,12 @@ Client::close(){int rc = 0;clear();- DestroyHttpMessage(&msg);- if (fd != -1) {+ DestroyHttpMessage(&msg_);+ if (fd_ != -1) {if (FLAG_verbose >= 2)SLOG("close");- rc = ::close(fd);- fd = -1;+ rc = ::close(fd_);+ fd_ = -1;}return rc;}@@ -84,8 +94,8 @@ voidClient::cleanup(){Cleanup* clean;- while ((clean = cleanups)) {- cleanups = clean->next;+ while ((clean = cleanups_)) {+ cleanups_ = clean->next;clean->func(clean->arg);delete clean;}@@ -95,31 +105,31 @@ voidClient::clear(){cleanup();- free(url_memory);- url_memory = nullptr;- free(params_memory);- params_memory = nullptr;- free(url.params.p);- url.params.p = nullptr;- close_connection = false;- payload = "";- unread = 0;+ free(url_memory_);+ url_memory_ = nullptr;+ free(params_memory_);+ params_memory_ = nullptr;+ free(url_.params.p);+ url_.params.p = nullptr;+ close_connection_ = false;+ payload_ = "";+ unread_ = 0;}voidClient::defer_cleanup(void (*func)(void*), void* arg){Cleanup* clean = new Cleanup;- clean->next = cleanups;+ clean->next = cleanups_;clean->func = func;clean->arg = arg;- cleanups = clean;+ cleanups_ = clean;}voidClient::run(){- ibuf.n = 0;+ ibuf_.n = 0;for (;;) {// read headers@@ -132,17 +142,17 @@ Client::run()break;// synchronize message stream- if (close_connection)+ if (close_connection_)break;if (!read_payload())break;// move pipelined bytes back to beginning- if (ibuf.n == ibuf.i) {- ibuf.n = 0;+ if (ibuf_.n == ibuf_.i) {+ ibuf_.n = 0;} else {- memmove(ibuf.p, ibuf.p + ibuf.i, ibuf.n - ibuf.i);- ibuf.n -= ibuf.i;+ memmove(ibuf_.p, ibuf_.p + ibuf_.i, ibuf_.n - ibuf_.i);+ ibuf_.n -= ibuf_.i;}}}@@ -151,75 +161,75 @@ boolClient::read_request(){int inmsglen;- ResetHttpMessage(&msg, kHttpRequest);+ ResetHttpMessage(&msg_, kHttpRequest);for (;;) {- inmsglen = ParseHttpMessage(&msg, ibuf.p, ibuf.n, ibuf.c);+ inmsglen = ParseHttpMessage(&msg_, ibuf_.p, ibuf_.n, ibuf_.c);if (inmsglen > 0) {- message_started = timespec_real();- ibuf.i = inmsglen;+ message_started_ = timespec_real();+ ibuf_.i = inmsglen;return true;}if (inmsglen == -1) {SLOG("bad message %m");return false;}- if (ibuf.n)- SLOG("fragmented message with %zu bytes", ibuf.n);+ if (ibuf_.n)+ SLOG("fragmented message with %zu bytes", ibuf_.n);ssize_t got;- got = read(fd, ibuf.p + ibuf.n, ibuf.c - ibuf.n);- if (!got && ibuf.n)- SLOG("unexpected eof after %zu bytes", ibuf.n);- if (got == -1 && (ibuf.n || (errno != EAGAIN && errno != ECONNRESET)))+ got = read(fd_, ibuf_.p + ibuf_.n, ibuf_.c - ibuf_.n);+ if (!got && ibuf_.n)+ SLOG("unexpected eof after %zu bytes", ibuf_.n);+ if (got == -1 && (ibuf_.n || (errno != EAGAIN && errno != ECONNRESET)))SLOG("read failed %m");if (got <= 0)return false;- ibuf.n += got;+ ibuf_.n += got;}}boolClient::transport(){- if (msg.version > 11) {- close_connection = true;+ if (msg_.version > 11) {+ close_connection_ = true;return send_error(505);}- if (msg.method == kHttpConnect) {- close_connection = true;+ if (msg_.method == kHttpConnect) {+ close_connection_ = true;return send_error(501);}if (!has_at_most_this_element(kHttpExpect, "100-continue")) {- close_connection = true;+ close_connection_ = true;return send_error(417);}- effective_ip = client_ip;- effective_ip_trusted = client_ip_trusted;+ effective_ip_ = client_ip_;+ effective_ip_trusted_ = client_ip_trusted_;if (FLAG_ip_header) {- if (is_loopback_ip(client_ip) || client_ip_trusted) {+ if (is_loopback_ip(client_ip_) || client_ip_trusted_) {std::string_view ip_header = get_header(FLAG_ip_header);if (!ip_header.empty()) {long ip;if ((ip = parse_ip(ip_header)) == -1) {- effective_ip = ip;- effective_ip_trusted = is_trusted_ip(ip);+ effective_ip_ = ip;+ effective_ip_trusted_ = is_trusted_ip(ip);} else {SLOG("client's --ip-header wasn't a single ipv4 address");- effective_ip_trusted = false;+ effective_ip_trusted_ = false;}}} else {SLOG("received direct connect from untrusted ip");- effective_ip_trusted = false;+ effective_ip_trusted_ = false;}}if (get_header("X-Priority") == "batch") {worker_->deprioritize();- } else if (!effective_ip_trusted) {- if (tokenbucket_acquire(client_ip) > FLAG_token_burst) {+ } else if (!effective_ip_trusted_) {+ if (tokenbucket_acquire(client_ip_) > FLAG_token_burst) {SLOG("deprioritizing");worker_->deprioritize();}@@ -227,7 +237,7 @@ Client::transport()if (HasHeader(kHttpTransferEncoding))if (!HeaderEqualCase(kHttpTransferEncoding, "identity")) {- close_connection = true;+ close_connection_ = true;return send_error(501, "Transfer-Encoding Not Implemented");}@@ -236,30 +246,32 @@ Client::transport()cl = ParseContentLength(HeaderData(kHttpContentLength),HeaderLength(kHttpContentLength));if (cl == -1) {- close_connection = true;+ close_connection_ = true;return send_error(400, "Bad Content-Length");}- if (cl > ibuf.c - ibuf.i) {- close_connection = true;+ if (cl > ibuf_.c - ibuf_.i) {+ close_connection_ = true;return send_error(413);}- unread = cl;- } else if (msg.method == kHttpPost || msg.method == kHttpPut) {- close_connection = true;+ unread_ = cl;+ } else if (msg_.method == kHttpPost || msg_.method == kHttpPut) {+ close_connection_ = true;return send_error(411);}if (FLAG_verbose >= 1)- SLOG("get %#.*s", msg.uri.b - msg.uri.a, ibuf.p + msg.uri.a);+ SLOG("get %#.*s", msg_.uri.b - msg_.uri.a, ibuf_.p + msg_.uri.a);- if (msg.version >= 11)+ if (msg_.version >= 11)if (HeaderEqualCase(kHttpExpect, "100-continue"))if (!send("HTTP/1.1 100 Continue\r\n\r\n"))return false;- url_memory = ParseUrl(- ibuf.p + msg.uri.a, msg.uri.b - msg.uri.a, &url, kUrlPlus | kUrlLatin1);- if (!url_memory)+ url_memory_ = ParseUrl(ibuf_.p + msg_.uri.a,+ msg_.uri.b - msg_.uri.a,+ &url_,+ kUrlPlus | kUrlLatin1);+ if (!url_memory_)__builtin_trap();return dispatch();@@ -277,8 +289,8 @@ Client::send_error(int code, const char* reason)if (!reason)reason = GetHttpReason(code);SLOG("error %d %s", code, reason);- char* p = append_http_response_message(obuf.p, code, reason);- (void)!send_response(obuf.p, p, string(reason) + "\r\n");+ char* p = append_http_response_message(obuf_.p, code, reason);+ (void)!send_response(obuf_.p, p, std::string(reason) + "\r\n");return false;}@@ -303,7 +315,7 @@ Client::append_http_response_message(char* p, int code, const char* reason)*p++ = '/';*p++ = '1';*p++ = '.';- *p++ = '0' + (msg.version & 1);+ *p++ = '0' + (msg_.version & 1);*p++ = ' ';*p++ = '0' + code / 100;*p++ = '0' + code / 10 % 10;@@ -321,17 +333,17 @@ Client::append_http_response_message(char* p, int code, const char* reason)// append date headertm tm;p = stpcpy(p, "Date: ");- gmtime_lockless(message_started.tv_sec, &tm);+ gmtime_lockless(message_started_.tv_sec, &tm);p = FormatHttpDateTime(p, &tm);*p++ = '\r';*p++ = '\n';// inform client of close() intent- if (msg.version < 11)- close_connection = true;+ if (msg_.version < 11)+ close_connection_ = true;if (HeaderEqualCase(kHttpConnection, "close"))- close_connection = true;- if (close_connection)+ close_connection_ = true;+ if (close_connection_)p = stpcpy(p, "Connection: close\r\n");return p;@@ -345,11 +357,11 @@ Client::append_http_response_message(char* p, int code, const char* reason)// @param p points to end of http response message headers; we assume// that we can keep appending to `p` which must be page guardedbool-Client::send_response(char* p0, char* p, string_view content)+Client::send_response(char* p0, char* p, std::string_view content){cleanup();pthread_testcancel();- should_send_error_if_canceled = false;+ should_send_error_if_canceled_ = false;// append content lengthp = stpcpy(p, "Content-Length: ");@@ -361,7 +373,7 @@ Client::send_response(char* p0, char* p, string_view content)*p++ = '\r';*p++ = '\n';- return send2(string_view(p0, p - p0), content);+ return send2(std::string_view(p0, p - p0), content);}// sends http response message, but not its body.@@ -375,7 +387,7 @@ Client::send_response(char* p0, char* p, string_view content)// bool// Client::fun()// {-// char* message = obuf.p;+// char* message = obuf_.p;// char* p = append_http_response_message(message, 200);// if (!send_response_start(message, p))// return false;@@ -396,25 +408,26 @@ boolClient::send_response_start(char* p0, char* p){// use chunked transfer encoding if http/1.1- if (msg.version >= 11)+ if (msg_.version >= 11)p = stpcpy(p, "Transfer-Encoding: chunked\r\n");// finish message*p++ = '\r';*p++ = '\n';- return send(string_view(p0, p - p0));+ should_send_error_if_canceled_ = false;+ return send(std::string_view(p0, p - p0));}// finishes sending chunked http response body.//// once you are finished sending chunks, call send_response_finish().bool-Client::send_response_chunk(const string_view content)+Client::send_response_chunk(const std::string_view content){// don't encode chunk boundaries for simple http client// it will need to rely on read() doing the right thing- if (msg.version < 11)+ if (msg_.version < 11)return send(content);// sent in three pieces@@ -443,9 +456,10 @@ Client::send_response_chunk(const string_view content)// perform send system callssize_t sent;- if ((sent = writev(fd, iov, 3)) != bytes) {+ if ((sent = writev(fd_, iov, 3)) != bytes) {if (sent == -1 && errno != EAGAIN && errno != ECONNRESET)SLOG("writev failed %m");+ close_connection_ = true;return false;}return true;@@ -461,7 +475,7 @@ Client::send_response_finish()// don't encode chunk boundaries for simple http client// it will need to rely on read() doing the right thing- if (msg.version < 11)+ if (msg_.version < 11)return true;// send terminating chunk@@ -473,12 +487,13 @@ Client::send_response_finish()// consider using the higher level methods like send_error(),// send_response(), send_response_start(), etc.bool-Client::send(const string_view s)+Client::send(const std::string_view s){ssize_t sent;- if ((sent = write(fd, s.data(), s.size())) != s.size()) {+ if ((sent = write(fd_, s.data(), s.size())) != s.size()) {if (sent == -1 && errno != EAGAIN && errno != ECONNRESET)SLOG("write failed %m");+ close_connection_ = true;return false;}return true;@@ -489,7 +504,7 @@ Client::send(const string_view s)// consider using the higher level methods like send_error(),// send_response(), send_response_start(), etc.bool-Client::send2(const string_view s1, const string_view s2)+Client::send2(const std::string_view s1, const std::string_view s2){iovec iov[2];ssize_t sent;@@ -497,27 +512,28 @@ Client::send2(const string_view s1, const string_view s2)iov[0].iov_len = s1.size();iov[1].iov_base = (void*)s2.data();iov[1].iov_len = s2.size();- if ((sent = writev(fd, iov, 2)) != s1.size() + s2.size()) {+ if ((sent = writev(fd_, iov, 2)) != s1.size() + s2.size()) {if (sent == -1 && errno != EAGAIN && errno != ECONNRESET)SLOG("writev failed %m");+ close_connection_ = true;return false;}return true;}bool-Client::has_at_most_this_element(int h, const string_view s)+Client::has_at_most_this_element(int h, const std::string_view s){if (!HasHeader(h))return true;if (!SlicesEqualCase(s.data(), s.size(), HeaderData(h), HeaderLength(h)))return false;struct HttpHeader* x;- for (unsigned i = 0; i < msg.xheaders.n; ++i) {- x = msg.xheaders.p + i;- if (GetHttpHeader(ibuf.p + x->k.a, x->k.b - x->k.a) == h &&+ for (unsigned i = 0; i < msg_.xheaders.n; ++i) {+ x = msg_.xheaders.p + i;+ if (GetHttpHeader(ibuf_.p + x->k.a, x->k.b - x->k.a) == h &&!SlicesEqualCase(- ibuf.p + x->v.a, x->v.b - x->v.a, s.data(), s.size())) {+ ibuf_.p + x->v.a, x->v.b - x->v.a, s.data(), s.size())) {return false;}}@@ -530,18 +546,19 @@ 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 std::string_view(ibuf.p + msg.headers[h].a,- msg.headers[h].b - msg.headers[h].a);+ if (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)+ for (i = 0; i < msg_.xheaders.n; ++i)if (SlicesEqualCase(key.data(),key.size(),- ibuf.p + msg.xheaders.p[i].k.a,- msg.xheaders.p[i].k.b - msg.xheaders.p[i].k.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);+ ibuf_.p + msg_.xheaders.p[i].k.a,+ msg_.xheaders.p[i].k.b -+ msg_.xheaders.p[i].k.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 std::string_view();}@@ -549,27 +566,27 @@ Client::get_header(const std::string_view& key)boolClient::read_payload(){- while (ibuf.n - ibuf.i < unread) {+ while (ibuf_.n - ibuf_.i < unread_) {ssize_t got;- if ((got = read(fd, ibuf.p + ibuf.n, ibuf.c - ibuf.n)) <= 0) {+ if ((got = read(fd_, ibuf_.p + ibuf_.n, ibuf_.c - ibuf_.n)) <= 0) {if (!got)SLOG("unexpected eof");if (got == -1)SLOG("read failed %m");return false;}- ibuf.n += got;+ ibuf_.n += got;}- payload = string_view(ibuf.p + ibuf.i, unread);- ibuf.i += unread;- unread = 0;- if (msg.method == kHttpPost && //+ payload_ = std::string_view(ibuf_.p + ibuf_.i, unread_);+ ibuf_.i += unread_;+ unread_ = 0;+ if (msg_.method == kHttpPost && //HasHeader(kHttpContentType) &&IsMimeType(HeaderData(kHttpContentType),HeaderLength(kHttpContentType),"application/x-www-form-urlencoded")) {- params_memory =- ParseParams(payload.data(), payload.size(), &url.params);+ params_memory_ =+ ParseParams(payload_.data(), payload_.size(), &url_.params);}return true;}@@ -578,7 +595,7 @@ boolClient::dispatch(){bool res;- should_send_error_if_canceled = true;+ should_send_error_if_canceled_ = true;g_http_cancel.set(this);res = dispatcher();g_http_cancel.set(nullptr);@@ -588,52 +605,121 @@ Client::dispatch()boolClient::dispatcher(){- std::string_view p = path();-- if (!g_url_prefix.empty()) {- if (FLAG_verbose >= 2) {- SLOG("request path %.*s", (int)p.size(), p.data());- }-- size_t prefix_len = g_url_prefix.size();- if (p.size() < prefix_len ||- memcmp(p.data(), g_url_prefix.c_str(), prefix_len) != 0) {- SLOG("path prefix mismatch");- return send_error(404);- }-- // Adjust path view to exclude prefix- p = std::string_view(p.data() + prefix_len, p.size() - prefix_len);+ // get request-uri path+ std::string_view p1 = path();+ if (FLAG_verbose >= 2)+ SLOG("request path %.*s", (int)p1.size(), p1.data());+ if (!p1.starts_with(FLAG_url_prefix)) {+ SLOG("path prefix mismatch");+ return send_error(404);+ }+ p1 = p1.substr(strlen(FLAG_url_prefix));+ if (!p1.starts_with("/") || !IsAcceptablePath(p1.data(), p1.size())) {+ SLOG("unacceptable path");+ return send_error(400);}+ p1 = p1.substr(1);- if (p == "/tokenize")+ // look for dynamic endpoints+ if (p1 == "tokenize")return tokenize();- if (p == "/embedding")+ if (p1 == "embedding")return embedding();- if (p == "/v1/embeddings")+ if (p1 == "v1/embeddings")return embedding();- if (p == "/v1/chat/completions")+ if (p1 == "v1/chat/completions")return v1_chat_completions();- SLOG("path not found: %.*s", (int)p.size(), p.data());- return send_error(404);+ // serve static endpoints+ int infd;+ size_t size;+ resolved_ = lf::resolve(FLAG_www_root, p1);+ for (;;) {+ infd = open(resolved_.c_str(), O_RDONLY);+ if (infd == -1) {+ if (errno == ENOENT || errno == ENOTDIR) {+ SLOG("path not found: %s", resolved_.c_str());+ return send_error(404);+ } else if (errno == EPERM || errno == EACCES) {+ SLOG("path not authorized: %s", resolved_.c_str());+ return send_error(401);+ } else {+ SLOG("%s: %s", strerror(errno), resolved_.c_str());+ return send_error(500);+ }+ }+ struct stat st;+ if (fstat(infd, &st)) {+ SLOG("%s: %s", strerror(errno), resolved_.c_str());+ ::close(infd);+ return send_error(500);+ }+ size = st.st_size;+ if (S_ISREG(st.st_mode)) {+ break;+ } else if (S_ISDIR(st.st_mode)) {+ ::close(infd);+ resolved_ = lf::resolve(resolved_, "index.html");+ } else {+ ::close(infd);+ SLOG("won't serve special file: %s", resolved_.c_str());+ return send_error(500);+ }+ }+ defer_cleanup(cleanup_fildes, (void*)(intptr_t)infd);+ char* p = append_http_response_message(obuf_.p, 200, "OK");+ p = stpcpy(p, "Content-Type: ");+ p = stpcpy(p, pick_content_type(resolved_));+ p = stpcpy(p, "\r\n");+ p = stpcpy(p, "Content-Length: ");+ p = FormatInt64(p, size);+ p = stpcpy(p, "\r\n");+ p = stpcpy(p, "\r\n");+ should_send_error_if_canceled_ = false;+ if (!send(std::string_view(obuf_.p, p - obuf_.p)))+ return false;+ char buf[512];+ size_t i, chunk;+ for (i = 0; i < size; i += chunk) {+ chunk = size - i;+ if (chunk > sizeof(buf))+ chunk = sizeof(buf);+ ssize_t got = pread(infd, buf, chunk, i);+ if (got == -1) {+ SLOG("static asset pread failed: %s", strerror(errno));+ close_connection_ = true;+ return false;+ }+ if (got != chunk) {+ SLOG("couldn't read full amount reading static asset");+ close_connection_ = true;+ return false;+ }+ if (!send(std::string_view(buf, chunk))) {+ close_connection_ = true;+ return false;+ }+ }+ SLOG("served %s", resolved_.c_str());+ cleanup();+ return true;}-string_view+std::string_viewClient::path(){- if (!url.path.n)+ if (!url_.path.n)return "/";- return { url.path.p, url.path.n };+ return { url_.path.p, url_.path.n };}-optional<string_view>-Client::param(string_view key)+std::optional<std::string_view>+Client::param(std::string_view key){- for (size_t i = 0; i < url.params.n; ++i)- if (key.size() == url.params.p[i].key.n)- if (!memcmp(key.data(), url.params.p[i].key.p, key.size()))- return optional(- string_view(url.params.p[i].val.p, url.params.p[i].val.n));+ for (size_t i = 0; i < url_.params.n; ++i)+ if (key.size() == url_.params.p[i].key.n)+ if (!memcmp(key.data(), url_.params.p[i].key.p, key.size()))+ return std::optional(std::string_view(url_.params.p[i].val.p,+ url_.params.p[i].val.n));return {};}diff --git a/llamafile/server/client.h b/llamafile/server/client.hindex c7d97495..de84b710 100644--- a/llamafile/server/client.h+++ b/llamafile/server/client.h@@ -28,9 +28,9 @@#include <sys/resource.h>#include <time.h>-#define HasHeader(H) (!!msg.headers[H].a)-#define HeaderData(H) (ibuf.p + msg.headers[H].a)-#define HeaderLength(H) (msg.headers[H].b - msg.headers[H].a)+#define HasHeader(H) (!!msg_.headers[H].a)+#define HeaderData(H) (ibuf_.p + msg_.headers[H].a)+#define HeaderLength(H) (msg_.headers[H].b - msg_.headers[H].a)#define HeaderEqual(H, S) \SlicesEqual(S, strlen(S), HeaderData(H), HeaderLength(H))#define HeaderEqualCase(H, S) \@@ -52,26 +52,27 @@ struct Cleanupstruct Client{- int fd = -1;- unsigned client_ip = 0;- unsigned effective_ip = 0;- bool client_ip_trusted = false;- bool effective_ip_trusted = false;- bool close_connection = false;- bool should_send_error_if_canceled;- size_t unread = 0;+ int fd_ = -1;+ unsigned client_ip_ = 0;+ unsigned effective_ip_ = 0;+ bool client_ip_trusted_ = false;+ bool effective_ip_trusted_ = false;+ bool close_connection_ = false;+ bool should_send_error_if_canceled_;+ size_t unread_ = 0;Worker* worker_; // borrowedSlot* slot_ = nullptr; // owned or nullllama_model* model_; // borrowed- timespec message_started;- HttpMessage msg;- Url url = {};- char* url_memory = nullptr;- char* params_memory = nullptr;- std::string_view payload;- Cleanup* cleanups;- Buffer ibuf;- Buffer obuf;+ timespec message_started_;+ HttpMessage msg_;+ Url url_ = {};+ char* url_memory_ = nullptr;+ char* params_memory_ = nullptr;+ std::string_view payload_;+ std::string resolved_;+ Cleanup* cleanups_;+ Buffer ibuf_;+ Buffer obuf_;explicit Client(llama_model*);diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cppindex 53008303..8ac915fc 100644--- a/llamafile/server/embedding.cpp+++ b/llamafile/server/embedding.cpp@@ -104,11 +104,11 @@ Client::get_embedding_params(EmbeddingParams* params)if (IsMimeType(HeaderData(kHttpContentType),HeaderLength(kHttpContentType),"text/plain")) {- params->prompt = payload;+ params->prompt = payload_;} else if (IsMimeType(HeaderData(kHttpContentType),HeaderLength(kHttpContentType),"application/json")) {- std::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())@@ -132,7 +132,7 @@ Client::get_embedding_params(EmbeddingParams* params)return send_error(501, "Content Type Not Implemented");}} else {- params->prompt = payload;+ params->prompt = payload_;}return true;}@@ -140,7 +140,7 @@ Client::get_embedding_params(EmbeddingParams* params)boolClient::embedding(){- if (msg.method != kHttpGet && msg.method != kHttpPost)+ if (msg_.method != kHttpGet && msg_.method != kHttpPost)return send_error(405);if (!read_payload())@@ -237,7 +237,7 @@ Client::embedding()bool in_openai_mode = path() == "/v1/embeddings";// serialize tokens to json- char* p = obuf.p;+ char* p = obuf_.p;p = stpcpy(p, "{\n");// Here's what an OpenAI /v1/embedding response looks like:@@ -307,7 +307,7 @@ Client::embedding()if (in_openai_mode)p = stpcpy(p, " }]\n");p = stpcpy(p, "}\n");- std::string_view content(obuf.p, p - obuf.p);+ std::string_view content(obuf_.p, p - obuf_.p);// collect statisticsrusage ruend = {};diff --git a/llamafile/server/listen.cpp b/llamafile/server/listen.cppindex 86b8df00..1c50ec08 100644--- a/llamafile/server/listen.cpp+++ b/llamafile/server/listen.cpp@@ -25,15 +25,20 @@#include <string.h>#include <sys/socket.h>-#include "log.h"-#include "server.h"+#include "llamafile/llamafile.h"+#include "llamafile/server/log.h"+#include "llamafile/server/server.h"voidprint_listening_url(unsigned ip, int port){SLOG("listen http://%hhu.%hhu.%hhu.%hhu:%hu%s",- ip >> 24, ip >> 16, ip >> 8, ip, port,- g_url_prefix.c_str());+ ip >> 24,+ ip >> 16,+ ip >> 8,+ ip,+ port,+ FLAG_url_prefix);}intdiff --git a/llamafile/server/main.cpp b/llamafile/server/main.cppindex df0d102b..7dd5f925 100644--- a/llamafile/server/main.cpp+++ b/llamafile/server/main.cpp@@ -32,7 +32,6 @@#include "utils.h"Server* g_server;-std::string g_url_prefix;intmain(int argc, char* argv[])@@ -59,10 +58,6 @@ main(int argc, char* argv[])LoadZipArgs(&argc, &argv);llamafile_get_flags(argc, argv);- // normalize URL prefix- if (FLAG_url_prefix)- g_url_prefix = normalize_url_prefix(FLAG_url_prefix);-// initialize subsystemstime_init();tokenbucket_init();diff --git a/llamafile/server/normalize_url_prefix.cpp b/llamafile/server/normalize_url_prefix.cppdeleted file mode 100644index 38c07ae7..00000000--- a/llamafile/server/normalize_url_prefix.cpp+++ /dev/null@@ -1,40 +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 "utils.h"--#include <cosmo.h>--std::string-normalize_url_prefix(std::string url_prefix)-{- // Rule 1: Replace multiple slashes with single slash- while (url_prefix.find("//") != std::string::npos) {- url_prefix.replace(url_prefix.find("//"), 2, "/");- }-- // Rule 2: Remove trailing slash- if (!url_prefix.empty() && url_prefix.back() == '/') {- url_prefix.pop_back();- }-- // Rule 3: Convert single slash to empty string- if (url_prefix == "/") {- url_prefix.clear();- }- return url_prefix;-}diff --git a/llamafile/server/server.h b/llamafile/server/server.hindex b877f710..da7038e2 100644--- a/llamafile/server/server.h+++ b/llamafile/server/server.h@@ -52,7 +52,6 @@ struct Server};extern Server* g_server;-extern std::string g_url_prefix;intcreate_listening_socket(const char*);diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cppindex 8f9f71c2..175d4615 100644--- a/llamafile/server/tokenize.cpp+++ b/llamafile/server/tokenize.cpp@@ -57,11 +57,11 @@ Client::get_tokenize_params(TokenizeParams* params)if (IsMimeType(HeaderData(kHttpContentType),HeaderLength(kHttpContentType),"text/plain")) {- params->prompt = payload;+ params->prompt = payload_;} else if (IsMimeType(HeaderData(kHttpContentType),HeaderLength(kHttpContentType),"application/json")) {- std::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())@@ -78,7 +78,7 @@ Client::get_tokenize_params(TokenizeParams* params)return send_error(501, "Content Type Not Implemented");}} else {- params->prompt = payload;+ params->prompt = payload_;}return true;}@@ -86,7 +86,7 @@ Client::get_tokenize_params(TokenizeParams* params)boolClient::tokenize(){- if (msg.method != kHttpGet && msg.method != kHttpPost)+ if (msg_.method != kHttpGet && msg_.method != kHttpPost)return send_error(405);if (!read_payload())@@ -124,7 +124,7 @@ Client::tokenize()toks->resize(count);// serialize tokens to json- char* p = obuf.p;+ char* p = obuf_.p;p = stpcpy(p, "{\n");p = stpcpy(p, " \"add_special\": ");p = encode_bool(p, add_special);@@ -148,7 +148,7 @@ Client::tokenize()}p = stpcpy(p, "\n ]\n");p = stpcpy(p, "}\n");- std::string_view content(obuf.p, p - obuf.p);+ std::string_view content(obuf_.p, p - obuf_.p);// collect statisticsrusage ruend = {};diff --git a/llamafile/server/utils.h b/llamafile/server/utils.hindex 495f3c84..9295a4f7 100644--- a/llamafile/server/utils.h+++ b/llamafile/server/utils.h@@ -27,6 +27,3 @@ atob(std::string_view, bool);std::string_viewor_empty(std::optional<std::string_view> x);--std::string-normalize_url_prefix(std::string url_prefix);diff --git a/llamafile/server/v1_chat_completions.cpp b/llamafile/server/v1_chat_completions.cppindex 7ab7b33b..a9657fcf 100644--- a/llamafile/server/v1_chat_completions.cpp+++ b/llamafile/server/v1_chat_completions.cpp@@ -164,7 +164,7 @@ boolClient::get_v1_chat_completions_params(V1ChatCompletionParams* params){// must be json post request- if (msg.method != kHttpPost)+ if (msg_.method != kHttpPost)return send_error(405);if (!HasHeader(kHttpContentType) ||!IsMimeType(HeaderData(kHttpContentType),@@ -176,7 +176,7 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)return false;// object<model, messages, ...>- std::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())@@ -499,9 +499,9 @@ Client::v1_chat_completions()// initialize responseif (params->stream) {- char* p = append_http_response_message(obuf.p, 200);+ 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))+ if (!send_response_start(obuf_.p, p))return false;choice["delta"].setObject();choice["delta"]["role"].setString("assistant");@@ -542,7 +542,7 @@ Client::v1_chat_completions()llama_token_to_piece(slot_->ctx_, id, DONT_RENDER_SPECIAL_TOKENS);if (!state->piece.empty()) {if (params->stream) {- char* p = append_http_response_message(obuf.p, 200);+ char* p = append_http_response_message(obuf_.p, 200);choice["delta"].setObject();choice["delta"]["content"].setString(state->piece);response->json["created"].setLong(timespec_real().tv_sec);@@ -578,10 +578,10 @@ Client::v1_chat_completions()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);+ char* p = append_http_response_message(obuf_.p, 200);p = stpcpy(p, "Content-Type: application/json\r\n");response->content = response->json.toStringPretty();response->content += '\n';- return send_response(obuf.p, p, response->content);+ return send_response(obuf_.p, p, response->content);}}diff --git a/llamafile/server/worker.cpp b/llamafile/server/worker.cppindex ce327969..bf73e381 100644--- a/llamafile/server/worker.cpp+++ b/llamafile/server/worker.cpp@@ -48,10 +48,10 @@ Worker::begin(){npassert(!working_);client_.worker_ = this;- client_.client_ip_trusted = is_trusted_ip(client_.client_ip);+ client_.client_ip_trusted_ = is_trusted_ip(client_.client_ip_);int tokens = 0;- if (!client_.client_ip_trusted)- tokens = tokenbucket_acquire(client_.client_ip);+ if (!client_.client_ip_trusted_)+ tokens = tokenbucket_acquire(client_.client_ip_);server_->lock();dll_remove(&server_->idle_workers, &elem_);if (dll_is_empty(server_->idle_workers)) {@@ -108,7 +108,7 @@ Worker::retire()voidWorker::handle(){- if ((client_.fd = server_->accept(&client_.client_ip)) == -1) {+ if ((client_.fd_ = server_->accept(&client_.client_ip_)) == -1) {SLOG("accept returned %m");return;}diff --git a/llamafile/server/www/chatbot.css b/llamafile/server/www/chatbot.cssnew file mode 100644index 00000000..744388dc--- /dev/null+++ b/llamafile/server/www/chatbot.css@@ -0,0 +1,143 @@+* {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}++body {+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ line-height: 1.6;+ color: #333;+ background: #f5f5f5;+}++.chat-container {+ max-width: 800px;+ margin: 2rem auto;+ background: white;+ border-radius: 12px;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);+ display: flex;+ flex-direction: column;+ height: calc(100vh - 4rem);+}++.chat-header {+ padding: 1rem;+ background: #f8f9fa;+ border-bottom: 1px solid #e9ecef;+ border-radius: 12px 12px 0 0;+}++.chat-header h1 {+ font-size: 1.25rem;+ color: #212529;+ vertical-align: center;+}++.chat-messages {+ flex: 1;+ overflow-y: auto;+ padding: 1rem;+}++.message {+ margin-bottom: 1rem;+ padding: 0.75rem;+ border-radius: 8px;+ max-width: 80%;+ word-wrap: break-word;+}++.message.user {+ background: #e9ecef;+ margin-left: auto;+}++.message.assistant {+ background: #f8f9fa;+ margin-right: auto;+}++.message.system {+ background: #f8e3fa;+ margin-right: auto;+}++.chat-input-container {+ padding: 1rem;+ border-top: 1px solid #e9ecef;+ display: flex;+ gap: 0.5rem;+}++.chat-input {+ flex: 1;+ padding: 0.75rem;+ border: 1px solid #dee2e6;+ border-radius: 6px;+ font-size: 1rem;+ outline: none;+}++.chat-input:focus {+ border-color: #86b7fe;+ box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);+}++.send-button {+ padding: 0.75rem 1.5rem;+ background: #0d6efd;+ color: white;+ border: none;+ border-radius: 6px;+ cursor: pointer;+ font-size: 1rem;+ transition: background-color 0.2s;+}++.send-button:hover {+ background: #0b5ed7;+}++.send-button:disabled {+ background: #6c757d;+ cursor: not-allowed;+}++.message pre {+ background: #f8f9fa;+ padding: 0.5rem;+ border-radius: 4px;+ overflow-x: auto;+}++.typing-indicator {+ display: none;+ align-items: center;+ gap: 0.25rem;+ padding: 0.5rem;+ color: #6c757d;+}++.typing-indicator span {+ width: 4px;+ height: 4px;+ background: #6c757d;+ border-radius: 50%;+ display: inline-block;+ animation: typing 1s infinite ease-in-out;+}++.typing-indicator span:nth-child(2) {+ animation-delay: 0.2s;+}++.typing-indicator span:nth-child(3) {+ animation-delay: 0.4s;+}++@keyframes typing {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-4px); }+}diff --git a/llamafile/server/www/chatbot.js b/llamafile/server/www/chatbot.jsnew file mode 100644index 00000000..e05c9765--- /dev/null+++ b/llamafile/server/www/chatbot.js@@ -0,0 +1,166 @@+// 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.++const API_ENDPOINT = "/v1/chat/completions";+const API_KEY = "your-api-key-here";++const chatMessages = document.getElementById("chat-messages");+const chatInput = document.getElementById("chat-input");+const sendButton = document.getElementById("send-button");+const typingIndicator = document.getElementById("typing-indicator");++let chatHistory = [+ {+ role: "system",+ content: ("A chat between a curious human and an artificial " ++ "intelligence assistant. The assistant gives helpful, " ++ "detailed, and polite answers to the human's questions.")+ },+];++function createMessageElement(content, role) {+ const messageDiv = document.createElement("div");+ messageDiv.classList.add("message", role);+ messageDiv.textContent = content;+ return messageDiv;+}++function scrollToBottom() {+ chatMessages.scrollTop = chatMessages.scrollHeight;+}++function setTypingIndicatorVisibility(visible) {+ typingIndicator.style.display = visible ? "flex" : "none";+}++async function handleChatStream(response) {+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ let currentMessageElement = createMessageElement("", "assistant");+ chatMessages.appendChild(currentMessageElement);++ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split("\n");++ // process all complete lines+ for (let i = 0; i < lines.length - 1; i++) {+ const line = lines[i].trim();+ if (line.startsWith("data: ")) {+ const data = line.slice(6);+ if (data === "[DONE]") continue;++ try {+ const parsed = JSON.parse(data);+ const content = parsed.choices[0]?.delta?.content || "";+ currentMessageElement.textContent += content;+ scrollToBottom();+ } catch (e) {+ console.error("Error parsing JSON:", e);+ }+ }+ }++ // keep the last incomplete line in the buffer+ buffer = lines[lines.length - 1];+ }+ } catch (error) {+ console.error("Error reading stream:", error);+ } finally {+ setTypingIndicatorVisibility(false);+ sendButton.disabled = false;+ chatInput.disabled = false;+ chatInput.focus();+ }+}++async function sendMessage() {+ const message = chatInput.value.trim();+ if (!message) return;++ // disable input while processing+ chatInput.value = "";+ chatInput.disabled = true;+ sendButton.disabled = true;++ // add user message to chat+ const userMessageElement = createMessageElement(message, "user");+ chatMessages.appendChild(userMessageElement);+ scrollToBottom();++ // update chat history+ chatHistory.push({ role: "user", content: message });++ // show typing indicator+ setTypingIndicatorVisibility(true);++ try {+ const response = await fetch(API_ENDPOINT, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Authorization": `Bearer ${API_KEY}`+ },+ body: JSON.stringify({+ model: "gpt-3.5-turbo",+ messages: chatHistory,+ stream: true+ })+ });++ if (!response.ok)+ throw new Error(`HTTP error! status: ${response.status}`);++ // handle the stream+ await handleChatStream(response);++ // update chat history with response+ const lastMessage = chatMessages.lastElementChild.textContent;+ chatHistory.push({ role: "assistant", content: lastMessage });++ } catch (error) {+ console.error("Error:", error);+ const errorMessage = createMessageElement(+ "Sorry, there was an error processing your request.",+ "system");+ chatMessages.appendChild(errorMessage);+ setTypingIndicatorVisibility(false);+ sendButton.disabled = false;+ chatInput.disabled = false;+ }+}++// setup chat window+chatMessages.innerHTML = "";+for (let i = 0; i < chatHistory.length; i++) {+ chatMessages.appendChild(createMessageElement(chatHistory[i].content,+ chatHistory[i].role));+}++// setup events+sendButton.addEventListener("click", sendMessage);+chatInput.addEventListener("keypress", (e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ sendMessage();+ }+});++// focus input+chatInput.focus();diff --git a/llamafile/server/www/chatbot.png b/llamafile/server/www/chatbot.pngnew file mode 100644index 00000000..20557f4fBinary files /dev/null and b/llamafile/server/www/chatbot.png differdiff --git a/llamafile/server/www/favicon.ico b/llamafile/server/www/favicon.iconew file mode 100644index 00000000..28252cdcBinary files /dev/null and b/llamafile/server/www/favicon.ico differdiff --git a/llamafile/server/www/index.html b/llamafile/server/www/index.htmlnew file mode 100644index 00000000..f531ab11--- /dev/null+++ b/llamafile/server/www/index.html@@ -0,0 +1,30 @@+<!DOCTYPE html>+<html lang="en">+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0">+<title>llamafile</title>+<link rel="stylesheet" href="chatbot.css">++<div class="chat-container">+ <div class="chat-header">+ <h1>+ <img src="chatbot.png" alt="[logo]">+ llamafile+ </h1>+ </div>+ <div class="chat-messages" id="chat-messages">+ <div class="message system">+ Loading...+ </div>+ </div>+ <div class="typing-indicator" id="typing-indicator">+ <span></span>+ <span></span>+ <span></span>+ </div>+ <div class="chat-input-container">+ <input type="text" class="chat-input" id="chat-input" placeholder="Type your message..." autocomplete="off">+ <button class="send-button" id="send-button">Send</button>+ </div>+</div>+<script src="chatbot.js"></script>diff --git a/llamafile/string.cpp b/llamafile/string.cppindex 04cacb57..3f98af5e 100644--- a/llamafile/string.cpp+++ b/llamafile/string.cpp@@ -80,12 +80,12 @@ std::string basename(const std::string_view path) {}}-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_view extname(const std::string_view &path) {+ size_t i = path.size();+ while (i--)+ if (path[i] == '.' || path[i] == '/')+ return path.substr(i + 1);+ return path;}std::string dirname(const std::string_view path) {diff --git a/llamafile/string.h b/llamafile/string.hindex 0aaf9a65..89a4e935 100644--- a/llamafile/string.h+++ b/llamafile/string.h@@ -24,11 +24,11 @@ namespace lf {std::string basename(const std::string_view);std::string collapse(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 join(const std::vector<std::string> &, const std::string_view &);std::string resolve(const std::string_view, const std::string_view);std::string tolower(const std::string_view);+std::string_view extname(const std::string_view &);void append_wchar(std::string *, wchar_t);} // namespace lf