Skip to content

Distribute and run LLMs with a single file.

Make default system prompt configurable on web

Justine Tunney35bc08814670
diff --git a/llama.cpp/common.cpp b/llama.cpp/common.cpp
index 9d0b185c..6dfb1386 100644
--- a/llama.cpp/common.cpp
+++ b/llama.cpp/common.cpp
@@ -276,6 +276,7 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
// TODO: this is temporary, in the future the sampling state will be moved fully to llama_sampling_context.
params.seed = std::stoul(argv[i]);
sparams.seed = std::stoul(argv[i]);
+ FLAG_seed = sparams.seed; // [jart]
return true;
}
if (arg == "-t" || arg == "--threads") {
@@ -490,6 +491,7 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
if (arg == "--top-p") {
CHECK_ARG
sparams.top_p = std::stof(argv[i]);
+ FLAG_top_p = sparams.top_p; // [jart]
return true;
}
if (arg == "--min-p") {
@@ -497,10 +499,12 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
sparams.min_p = std::stof(argv[i]);
return true;
}
- if (arg == "--temp") {
+ if (arg == "--temp" || //
+ arg == "--temperature") { // [jart]
CHECK_ARG
sparams.temp = std::stof(argv[i]);
sparams.temp = std::max(sparams.temp, 0.0f);
+ FLAG_temperature = sparams.temp; // [jart]
return true;
}
if (arg == "--tfs") {
@@ -527,11 +531,13 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
if (arg == "--frequency-penalty") {
CHECK_ARG
sparams.penalty_freq = std::stof(argv[i]);
+ FLAG_frequency_penalty = sparams.penalty_freq; // [jart]
return true;
}
if (arg == "--presence-penalty") {
CHECK_ARG
sparams.penalty_present = std::stof(argv[i]);
+ FLAG_presence_penalty = sparams.penalty_present; // [jart]
return true;
}
if (arg == "--dynatemp-range") {
@@ -903,8 +909,15 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_pa
params.verbose_prompt = true;
return true;
}
- if (arg == "--no-display-prompt" || arg == "--silent-prompt") {
+ if (arg == "--no-display-prompt" || //
+ arg == "--silent-prompt") { // [jart]
params.display_prompt = false;
+ FLAG_no_display_prompt = true; // [jart]
+ return true;
+ }
+ if (arg == "--display-prompt") { // [jart]
+ params.display_prompt = true;
+ FLAG_no_display_prompt = false;
return true;
}
if (arg == "-r" || arg == "--reverse-prompt") {
diff --git a/llama.cpp/server/server.cpp b/llama.cpp/server/server.cpp
index 88dd6689..76978305 100644
--- a/llama.cpp/server/server.cpp
+++ b/llama.cpp/server/server.cpp
@@ -2593,6 +2593,15 @@ static void server_params_parse(int argc, char **argv, server_params &sparams,
{
FLAG_nologo = true;
}
+ else if (arg == "--no-display-prompt" || //
+ arg == "--silent-prompt")
+ {
+ FLAG_no_display_prompt = true;
+ }
+ else if (arg == "--display-prompt")
+ {
+ FLAG_no_display_prompt = false;
+ }
else if (arg == "--trap")
{
FLAG_trap = true;
diff --git a/llamafile/flags.cpp b/llamafile/flags.cpp
index 55b1ff4b..de1770d5 100644
--- a/llamafile/flags.cpp
+++ b/llamafile/flags.cpp
@@ -43,6 +43,7 @@ bool FLAG_iq = false;
bool FLAG_log_disable = false;
bool FLAG_mlock = false;
bool FLAG_mmap = true;
+bool FLAG_no_display_prompt = false;
bool FLAG_nocompile = false;
bool FLAG_nologo = false;
bool FLAG_precise = false;
@@ -59,7 +60,10 @@ const char *FLAG_prompt = nullptr;
const char *FLAG_url_prefix = "";
const char *FLAG_www_root = "/zip/www";
double FLAG_token_rate = 1;
-float FLAG_temp = 0.8;
+float FLAG_frequency_penalty = 0;
+float FLAG_presence_penalty = 0;
+float FLAG_temperature = .8;
+float FLAG_top_p = .95;
int FLAG_batch = 2048;
int FLAG_ctx_size = 8192;
int FLAG_flash_attn = false;
@@ -69,7 +73,6 @@ int FLAG_http_obuf_size = 1024 * 1024;
int FLAG_keepalive = 5;
int FLAG_main_gpu = 0;
int FLAG_n_gpu_layers = -1;
-int FLAG_seed = LLAMA_DEFAULT_SEED;
int FLAG_slots = 1;
int FLAG_split_mode = LLAMA_SPLIT_MODE_LAYER;
int FLAG_threads = MIN(cpu_get_num_math(), 20);
@@ -80,6 +83,7 @@ int FLAG_ubatch = 512;
int FLAG_verbose = 0;
int FLAG_warmup = true;
int FLAG_workers;
+unsigned FLAG_seed = LLAMA_DEFAULT_SEED;
std::vector<std::string> FLAG_headers;
@@ -153,6 +157,17 @@ void llamafile_get_flags(int argc, char **argv) {
continue;
}
+ if (!strcmp(flag, "--no-display-prompt") || //
+ !strcmp(flag, "--silent-prompt")) {
+ FLAG_no_display_prompt = true;
+ continue;
+ }
+
+ if (!strcmp(flag, "--display-prompt")) {
+ FLAG_no_display_prompt = false;
+ continue;
+ }
+
//////////////////////////////////////////////////////////////////////
// server flags
@@ -278,6 +293,45 @@ void llamafile_get_flags(int argc, char **argv) {
continue;
}
+ //////////////////////////////////////////////////////////////////////
+ // sampling flags
+
+ if (!strcmp(flag, "--seed")) {
+ if (i == argc)
+ missing("--seed");
+ FLAG_seed = strtol(argv[i++], 0, 0);
+ continue;
+ }
+
+ if (!strcmp(flag, "--temp") || //
+ !strcmp(flag, "--temperature")) {
+ if (i == argc)
+ missing("--temp");
+ FLAG_temperature = atof(argv[i++]);
+ continue;
+ }
+
+ if (!strcmp(flag, "--top-p")) {
+ if (i == argc)
+ missing("--top-p");
+ FLAG_top_p = atof(argv[i++]);
+ continue;
+ }
+
+ if (!strcmp(flag, "--frequency-penalty")) {
+ if (i == argc)
+ missing("--frequency-penalty");
+ FLAG_frequency_penalty = atof(argv[i++]);
+ continue;
+ }
+
+ if (!strcmp(flag, "--presence-penalty")) {
+ if (i == argc)
+ missing("--presence-penalty");
+ FLAG_presence_penalty = atof(argv[i++]);
+ continue;
+ }
+
//////////////////////////////////////////////////////////////////////
// model flags
@@ -319,20 +373,6 @@ void llamafile_get_flags(int argc, char **argv) {
continue;
}
- if (!strcmp(flag, "--seed")) {
- if (i == argc)
- missing("--seed");
- FLAG_seed = atoi(argv[i++]);
- continue;
- }
-
- if (!strcmp(flag, "--temp")) {
- if (i == argc)
- missing("--temp");
- FLAG_temp = atof(argv[i++]);
- continue;
- }
-
if (!strcmp(flag, "-t") || !strcmp(flag, "--threads")) {
if (i == argc)
missing("--threads");
diff --git a/llamafile/llamafile.h b/llamafile/llamafile.h
index 7370fb9b..93e7aac8 100644
--- a/llamafile/llamafile.h
+++ b/llamafile/llamafile.h
@@ -13,6 +13,7 @@ extern bool FLAG_iq;
extern bool FLAG_log_disable;
extern bool FLAG_mlock;
extern bool FLAG_mmap;
+extern bool FLAG_no_display_prompt;
extern bool FLAG_nocompile;
extern bool FLAG_nologo;
extern bool FLAG_precise;
@@ -30,7 +31,10 @@ 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 float FLAG_frequency_penalty;
+extern float FLAG_presence_penalty;
+extern float FLAG_temperature;
+extern float FLAG_top_p;
extern int FLAG_batch;
extern int FLAG_ctx_size;
extern int FLAG_flash_attn;
@@ -41,7 +45,6 @@ extern int FLAG_http_obuf_size;
extern int FLAG_keepalive;
extern int FLAG_main_gpu;
extern int FLAG_n_gpu_layers;
-extern int FLAG_seed;
extern int FLAG_slots;
extern int FLAG_split_mode;
extern int FLAG_threads;
@@ -52,6 +55,7 @@ extern int FLAG_ubatch;
extern int FLAG_verbose;
extern int FLAG_warmup;
extern int FLAG_workers;
+extern unsigned FLAG_seed;
struct llamafile;
struct llamafile *llamafile_open_gguf(const char *, const char *);
diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cpp
index c6abeb6b..6ee0fd08 100644
--- a/llamafile/server/client.cpp
+++ b/llamafile/server/client.cpp
@@ -654,6 +654,8 @@ Client::dispatcher()
return v1_chat_completions();
if (p1 == "slotz")
return slotz();
+ if (p1 == "flagz")
+ return flagz();
// serve static endpoints
int infd;
diff --git a/llamafile/server/client.h b/llamafile/server/client.h
index 1df06dbc..64ea43ed 100644
--- a/llamafile/server/client.h
+++ b/llamafile/server/client.h
@@ -66,6 +66,7 @@ struct Client
char* params_memory_ = nullptr;
std::string_view payload_;
std::string resolved_;
+ std::string dump_;
Cleanup* cleanups_;
Buffer ibuf_;
Buffer obuf_;
@@ -112,6 +113,7 @@ struct Client
bool get_v1_chat_completions_params(V1ChatCompletionParams*) __wur;
bool slotz() __wur;
+ bool flagz() __wur;
};
} // namespace server
diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cpp
index fa986694..e3ce26da 100644
--- a/llamafile/server/embedding.cpp
+++ b/llamafile/server/embedding.cpp
@@ -27,6 +27,8 @@
#include <sys/resource.h>
#include <vector>
+using jt::Json;
+
namespace lf {
namespace server {
diff --git a/llamafile/server/flagz.cpp b/llamafile/server/flagz.cpp
new file mode 100644
index 00000000..1e81039f
--- /dev/null
+++ b/llamafile/server/flagz.cpp
@@ -0,0 +1,49 @@
+// -*- 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 "llama.cpp/llama.h"
+#include "llamafile/llamafile.h"
+#include "llamafile/server/json.h"
+
+namespace lf {
+namespace server {
+
+bool
+Client::flagz()
+{
+ jt::Json json;
+ json["prompt"] = FLAG_prompt;
+ json["no_display_prompt"] = FLAG_no_display_prompt;
+ json["nologo"] = FLAG_nologo;
+ json["temperature"] = FLAG_temperature;
+ json["presence_penalty"] = FLAG_presence_penalty;
+ json["frequency_penalty"] = FLAG_frequency_penalty;
+ if (FLAG_seed == LLAMA_DEFAULT_SEED) {
+ json["seed"] = nullptr;
+ } else {
+ json["seed"] = FLAG_seed;
+ }
+ dump_ = json.toStringPretty();
+ dump_ += '\n';
+ char* p = append_http_response_message(obuf_.p, 200);
+ p = stpcpy(p, "Content-Type: application/json\r\n");
+ return send_response(obuf_.p, p, dump_);
+}
+
+} // namespace server
+} // namespace lf
diff --git a/llamafile/server/json.cpp b/llamafile/server/json.cpp
index 6a78bf24..55ae5d0c 100644
--- a/llamafile/server/json.cpp
+++ b/llamafile/server/json.cpp
@@ -16,12 +16,12 @@
// limitations under the License.
#include "json.h"
-#include <stdckdint.h>
#include <cctype>
#include <climits>
#include <cstdint>
#include <cstdlib>
+#include <stdckdint.h>
#include "double-conversion/double-to-string.h"
#include "double-conversion/string-to-double.h"
@@ -75,6 +75,8 @@
(unsigned)((((wc) - 0x10000) & 1023) + 0xDC00) << 16) \
: 0xFFFD)
+namespace jt {
+
static const char kJsonStr[256] = {
1, 1, 1, 1, 1, 1, 1, 1, // 0000 ascii (0)
1, 1, 1, 1, 1, 1, 1, 1, // 0010
@@ -243,6 +245,20 @@ Json::Json(unsigned long long value)
}
}
+Json::Json(const char* value)
+{
+ if (value) {
+ type_ = String;
+ new (&string_value) std::string(value);
+ } else {
+ type_ = Null;
+ }
+}
+
+Json::Json(const JTJSON_STRING_VIEW& value) : type_(String), string_value(value)
+{
+}
+
Json::~Json()
{
clear();
@@ -540,7 +556,7 @@ Json::setString(std::string&& value)
}
void
-Json::setString(const JSON_STRING_VIEW_& value)
+Json::setString(const JTJSON_STRING_VIEW& value)
{
clear();
type_ = String;
@@ -690,7 +706,7 @@ Json::marshal(std::string& b, bool pretty, int indent) const
}
void
-Json::stringify(std::string& b, const JSON_STRING_VIEW_& s)
+Json::stringify(std::string& b, const JTJSON_STRING_VIEW& s)
{
b += '"';
serialize(b, s);
@@ -698,7 +714,7 @@ Json::stringify(std::string& b, const JSON_STRING_VIEW_& s)
}
void
-Json::serialize(std::string& sb, const JSON_STRING_VIEW_& s)
+Json::serialize(std::string& sb, const JTJSON_STRING_VIEW& s)
{
size_t i, j, m;
wint_t x, a, b;
@@ -1213,7 +1229,7 @@ Json::parse(Json& json, const char*& p, const char* e, int context, int depth)
}
std::pair<Json::Status, Json>
-Json::parse(const JSON_STRING_VIEW_& s)
+Json::parse(const JTJSON_STRING_VIEW& s)
{
Json::Status s2;
std::pair<Json::Status, Json> res;
@@ -1302,3 +1318,5 @@ Json::StatusToString(Json::Status status)
abort();
}
}
+
+} // namespace jt
diff --git a/llamafile/server/json.h b/llamafile/server/json.h
index b77e5097..30dc4db7 100644
--- a/llamafile/server/json.h
+++ b/llamafile/server/json.h
@@ -21,11 +21,13 @@
#include <vector>
#if __cplusplus >= 201703L
-#define JSON_STRING_VIEW_ std::string_view
+#define JTJSON_STRING_VIEW std::string_view
#else
-#define JSON_STRING_VIEW_ std::string
+#define JTJSON_STRING_VIEW std::string
#endif
+namespace jt {
+
class Json
{
public:
@@ -93,11 +95,13 @@ class Json
public:
static const char* StatusToString(Status);
- static std::pair<Status, Json> parse(const JSON_STRING_VIEW_&);
+ static std::pair<Status, Json> parse(const JTJSON_STRING_VIEW&);
Json(const Json&);
Json(Json&&) noexcept;
Json(unsigned long long);
+ Json(const char*);
+ Json(const JTJSON_STRING_VIEW&);
~Json();
Json(const std::nullptr_t = nullptr) : type_(Null)
@@ -128,18 +132,10 @@ class Json
{
}
- Json(const char* value) : type_(String), string_value(value)
- {
- }
-
Json(std::string&& value) : type_(String), string_value(std::move(value))
{
}
- Json(const JSON_STRING_VIEW_& value) : type_(String), string_value(value)
- {
- }
-
Type getType() const
{
return type_;
@@ -206,7 +202,7 @@ class Json
void setLong(long long);
void setString(const char*);
void setString(std::string&&);
- void setString(const JSON_STRING_VIEW_&);
+ void setString(const JTJSON_STRING_VIEW&);
void setArray();
void setObject();
@@ -227,7 +223,9 @@ class Json
private:
void clear();
void marshal(std::string&, bool, int) const;
- static void stringify(std::string&, const JSON_STRING_VIEW_&);
- static void serialize(std::string&, const JSON_STRING_VIEW_&);
+ static void stringify(std::string&, const JTJSON_STRING_VIEW&);
+ static void serialize(std::string&, const JTJSON_STRING_VIEW&);
static Status parse(Json&, const char*&, const char*, int, int);
};
+
+} // namespace jt
diff --git a/llamafile/server/json_test.cpp b/llamafile/server/json_test.cpp
index 22a46305..5ea78028 100644
--- a/llamafile/server/json_test.cpp
+++ b/llamafile/server/json_test.cpp
@@ -26,6 +26,8 @@
#define STRING(sl) std::string(sl, sizeof(sl) - 1)
+using jt::Json;
+
static const char kHuge[] = R"([
"JSON Test Pattern pass1",
{"object with 1 member":["array with 1 element"]},
@@ -406,6 +408,60 @@ json_test_suite()
}
}
+void
+afl_regression()
+{
+ Json::parse("[{\"\":1,3:14,]\n");
+ Json::parse("[\n"
+ "\n"
+ "3E14,\n"
+ "{\"!\":4,733:4,[\n"
+ "\n"
+ "3EL%,3E14,\n"
+ "{][1][1,,]");
+ Json::parse("[\n"
+ "null,\n"
+ "1,\n"
+ "3.14,\n"
+ "{\"a\": \"b\",\n"
+ "3:14,ull}\n"
+ "]");
+ Json::parse("[\n"
+ "\n"
+ "3E14,\n"
+ "{\"a!!!!!!!!!!!!!!!!!!\":4, \n"
+ "\n"
+ "3:1,,\n"
+ "3[\n"
+ "\n"
+ "]");
+ Json::parse("[\n"
+ "\n"
+ "3E14,\n"
+ "{\"a!!:!!!!!!!!!!!!!!!\":4, \n"
+ "\n"
+ "3E1:4, \n"
+ "\n"
+ "3E1,,\n"
+ ",,\n"
+ "3[\n"
+ "\n"
+ "]");
+ Json::parse("[\n"
+ "\n"
+ "3E14,\n"
+ "{\"!\":4,733:4,[\n"
+ "\n"
+ "3E1%,][1,,]");
+ Json::parse("[\n"
+ "\n"
+ "3E14,\n"
+ "{\"!\":4,733:4,[\n"
+ "\n"
+ "3EL%,3E14,\n"
+ "{][1][1,,]");
+}
+
int
main()
{
@@ -413,6 +469,7 @@ main()
deep_test();
parse_test();
round_trip_test();
+ afl_regression();
BENCH(2000, 1, object_test());
BENCH(2000, 1, deep_test());
diff --git a/llamafile/server/slot.cpp b/llamafile/server/slot.cpp
index 82d57109..9628a81a 100644
--- a/llamafile/server/slot.cpp
+++ b/llamafile/server/slot.cpp
@@ -80,6 +80,7 @@ Slot::describe_error(int err)
Slot::Slot(llama_model* model) : model_(model)
{
+ dll_init(&elem_);
}
Slot::~Slot()
@@ -175,7 +176,6 @@ Slot::eval_tokens(const std::vector<int>& tokens)
history_.emplace_back(toks[i + j]);
used += n_eval;
}
- last_used_ = timespec_real();
return N;
}
@@ -216,7 +216,6 @@ Slot::eval_image(const std::string_view& bytes)
}
llava_image_embed_free(image_embed);
history_.emplace_back(new Image(bytes, N));
- last_used_ = timespec_real();
return N;
}
diff --git a/llamafile/server/slot.h b/llamafile/server/slot.h
index 593f7a3c..c6d3d172 100644
--- a/llamafile/server/slot.h
+++ b/llamafile/server/slot.h
@@ -16,10 +16,12 @@
// limitations under the License.
#pragma once
-#include <ctime>
+#include <cosmo.h>
#include <string>
#include <vector>
+#define SLOT(e) DLL_CONTAINER(Slot, elem_, e)
+
struct llama_context;
struct llama_model;
struct clip_ctx;
@@ -44,10 +46,10 @@ struct Slot
static const char* describe_error(int);
+ Dll elem_;
llama_model* model_;
clip_ctx* clip_ctx_ = nullptr;
llama_context* ctx_ = nullptr;
- timespec last_used_ = timespec_zero;
std::vector<Atom> history_;
std::string system_fingerprint_;
diff --git a/llamafile/server/slots.cpp b/llamafile/server/slots.cpp
index c0db2279..1bc275c4 100644
--- a/llamafile/server/slots.cpp
+++ b/llamafile/server/slots.cpp
@@ -28,17 +28,20 @@ namespace server {
Slots::Slots(llama_model* model) : model_(model)
{
- pthread_mutex_init(&lock_, 0);
pthread_cond_init(&cond_, 0);
+ pthread_mutex_init(&lock_, 0);
}
Slots::~Slots()
{
- for (const auto& e : slots_)
- if (e.slot())
- delete e.slot();
- pthread_cond_destroy(&cond_);
pthread_mutex_destroy(&lock_);
+ pthread_cond_destroy(&cond_);
+}
+
+size_t
+Slots::size()
+{
+ return slots_.size();
}
int
@@ -50,8 +53,8 @@ Slots::start(int count)
Slot* slot = new Slot(model_);
if (slot->start()) {
++made;
- slots_.emplace(slot);
- all_slots_.push_back(slot);
+ slots_.emplace_back(slot);
+ dll_make_last(&free_slots_, &slot->elem_);
} else {
delete slot;
}
@@ -71,41 +74,22 @@ Slots::take(const std::vector<Atom>& prefix)
for (;;) {
// find slot with longest matching prefix
- SlotEntry search_key{ &prefix };
- auto i = slots_.upper_bound(search_key);
-
- // handle special case
- if (i == slots_.end() && i != slots_.begin()) {
- --i;
- Slot* slot = i->slot();
- unassert(slot);
- slots_.erase(i);
- pthread_mutex_unlock(&lock_);
- return slot;
- }
-
- // avoid slots with non-matching suffix
- // they probably belong to another client
- if (i != slots_.begin()) {
- --i;
- Slot* slot = i->slot();
- unassert(slot);
- int cpl = vector_common_prefix_length(slot->history_, prefix);
- if (cpl == slot->history_.size()) {
- slots_.erase(i);
- pthread_mutex_unlock(&lock_);
- return slot;
+ // favoring least recently used if multiple ones
+ int best_cpl = 0;
+ Dll* best_slot = nullptr;
+ for (Dll* e = dll_first(free_slots_); e; e = dll_next(free_slots_, e)) {
+ int cpl = vector_common_prefix_length(SLOT(e)->history_, prefix);
+ if (cpl >= best_cpl) {
+ best_cpl = cpl;
+ best_slot = e;
}
- ++i;
}
- // otherwise return result of search
- if (i != slots_.end()) {
- Slot* slot = i->slot();
- unassert(slot);
- slots_.erase(i);
+ // return borrowed pointer to best slot
+ if (best_slot) {
+ dll_remove(&free_slots_, best_slot);
pthread_mutex_unlock(&lock_);
- return slot;
+ return SLOT(best_slot);
}
// all slots are being used
@@ -120,7 +104,7 @@ Slots::give(Slot* slot)
SLOG("relinquishing slot");
unassert(slot);
pthread_mutex_lock(&lock_);
- slots_.emplace(slot);
+ dll_make_first(&free_slots_, &slot->elem_);
pthread_cond_signal(&cond_);
pthread_mutex_unlock(&lock_);
}
diff --git a/llamafile/server/slots.h b/llamafile/server/slots.h
index de5a2bd2..64e6b775 100644
--- a/llamafile/server/slots.h
+++ b/llamafile/server/slots.h
@@ -16,29 +16,34 @@
// limitations under the License.
#pragma once
+#include <memory>
#include <pthread.h>
-#include <set>
#include <vector>
struct llama_model;
+struct Dll;
namespace lf {
namespace server {
class Atom;
-struct Slot;
class SlotEntry;
+struct Slot;
struct Slots
{
llama_model* model_;
- std::multiset<SlotEntry> slots_;
- std::vector<Slot*> all_slots_;
- pthread_mutex_t lock_;
pthread_cond_t cond_;
+ pthread_mutex_t lock_;
+ std::vector<std::unique_ptr<Slot>> slots_;
+
+ // first elements are most recently used
+ // last elements are least recently used
+ Dll* free_slots_;
explicit Slots(llama_model*);
~Slots();
+ size_t size();
int start(int);
void tokenize(std::vector<Atom>*, std::string_view, bool);
Slot* take(const std::vector<Atom>&);
diff --git a/llamafile/server/slotz.cpp b/llamafile/server/slotz.cpp
index 97ad0f90..2b618292 100644
--- a/llamafile/server/slotz.cpp
+++ b/llamafile/server/slotz.cpp
@@ -32,9 +32,9 @@ Client::slotz()
int id = atoi(s.c_str());
if (id < 0)
return send_error(400);
- if (id >= worker_->server_->slots_->all_slots_.size())
+ if (id >= worker_->server_->slots_->size())
return send_error(404);
- Slot* slot = worker_->server_->slots_->all_slots_[id];
+ Slot* slot = worker_->server_->slots_->slots_[id].get();
std::string dump;
slot->dump(&dump);
char* p = append_http_response_message(obuf_.p, 200);
diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cpp
index cc20e829..8ef3cf37 100644
--- a/llamafile/server/tokenize.cpp
+++ b/llamafile/server/tokenize.cpp
@@ -28,6 +28,8 @@
#include <utility>
#include <vector>
+using jt::Json;
+
namespace lf {
namespace server {
diff --git a/llamafile/server/v1_chat_completions.cpp b/llamafile/server/v1_chat_completions.cpp
index c517ee4a..567b729a 100644
--- a/llamafile/server/v1_chat_completions.cpp
+++ b/llamafile/server/v1_chat_completions.cpp
@@ -37,6 +37,8 @@
#include <sys/resource.h>
#include <vector>
+using jt::Json;
+
namespace lf {
namespace server {
diff --git a/llamafile/server/www/chatbot.js b/llamafile/server/www/chatbot.js
index 7a534498..f0fc3699 100644
--- a/llamafile/server/www/chatbot.js
+++ b/llamafile/server/www/chatbot.js
@@ -15,6 +15,20 @@
const API_ENDPOINT = "/v1/chat/completions";
const API_KEY = "your-api-key-here";
+const DEFAULT_SYSTEM_PROMPT =
+ "A chat between a curious human and an artificial " +
+ "intelligence assistant. The assistant gives helpful, " +
+ "detailed, and polite answers to the human's questions.";
+
+const DEFAULT_FLAGZ = {
+ "prompt": null,
+ "no_display_prompt": false,
+ "frequency_penalty": 0,
+ "presence_penalty": 0,
+ "temperature": 0.8,
+ "seed": null
+};
+
const chatMessages = document.getElementById("chat-messages");
const chatInput = document.getElementById("chat-input");
const sendButton = document.getElementById("send-button");
@@ -24,15 +38,8 @@ let abortController = null;
let disableAutoScroll = false;
let streamingMessageContent = [];
let uploadedFiles = [];
-
-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.")
- },
-];
+let chatHistory = [];
+let flagz = null;
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substring(2);
@@ -189,10 +196,9 @@ async function sendMessage() {
} catch (error) {
if (error.name !== "AbortError") {
console.error("sendMessage() failed due to unexpected exception", error);
- const errorMessage = createMessageElement(
+ chatMessages.appendChild(createMessageElement(
"There was an error processing your request.",
- "system");
- chatMessages.appendChild(errorMessage);
+ "system"));
}
cleanupAfterMessage();
}
@@ -201,13 +207,13 @@ async function sendMessage() {
function onDragBegin(e) {
e.preventDefault();
e.stopPropagation();
- chatInput.classList.add('drag-over');
+ chatInput.classList.add("drag-over");
}
function onDragEnd(e) {
e.preventDefault();
e.stopPropagation();
- chatInput.classList.remove('drag-over');
+ chatInput.classList.remove("drag-over");
}
function onDrop(e) {
@@ -218,7 +224,7 @@ function onDrop(e) {
function onPaste(e) {
const items = e.clipboardData.items;
for (let item of items) {
- if (item.type.startsWith('image/')) {
+ if (item.type.startsWith("image/")) {
e.preventDefault();
onFile(item.getAsFile());
return;
@@ -232,22 +238,22 @@ function onPaste(e) {
async function fixImageDataUri(dataUri, maxLength = 1024 * 1024) {
const mimeMatch = dataUri.match(/^data:([^;,]+)/);
if (!mimeMatch)
- throw new Error('bad image data uri');
+ throw new Error("bad image data uri");
const mimeType = mimeMatch[1].toLowerCase();
- const supported = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
+ const supported = ["image/jpeg", "image/jpg", "image/png", "image/gif"];
if (supported.includes(mimeType))
if (dataUri.length <= maxLength)
return dataUri;
- const lossless = ['image/png', 'image/gif'];
+ const lossless = ["image/png", "image/gif"];
const quality = lossless.includes(mimeType) ? 0.92 : 0.8;
function createScaledCanvas(img, scale) {
- const canvas = document.createElement('canvas');
+ const canvas = document.createElement("canvas");
canvas.width = Math.floor(img.width * scale);
canvas.height = Math.floor(img.height * scale);
- const ctx = canvas.getContext('2d');
+ const ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = true;
- ctx.imageSmoothingQuality = 'high';
- ctx.fillStyle = 'white'; // in case of transparency
+ ctx.imageSmoothingQuality = "high";
+ ctx.fillStyle = "white"; // in case of transparency
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
return canvas;
@@ -259,12 +265,12 @@ async function fixImageDataUri(dataUri, maxLength = 1024 * 1024) {
let attempts = 0;
const maxAttempts = 5;
const initialCanvas = createScaledCanvas(img, scale);
- let result = initialCanvas.toDataURL('image/jpeg', quality);
+ let result = initialCanvas.toDataURL("image/jpeg", quality);
while (result.length > maxLength && attempts < maxAttempts) {
attempts++;
scale *= 0.7071;
const scaledCanvas = createScaledCanvas(img, scale);
- result = scaledCanvas.toDataURL('image/jpeg', quality);
+ result = scaledCanvas.toDataURL("image/jpeg", quality);
result.length = result.length;
}
if (result.length <= maxLength) {
@@ -302,7 +308,7 @@ function insertText(elem, text) {
const newPos = pos + text.length;
elem.setSelectionRange(newPos, newPos);
elem.focus();
- elem.dispatchEvent(new Event('input'));
+ elem.dispatchEvent(new Event("input"));
}
function onKeyDown(e) {
@@ -312,24 +318,56 @@ function onKeyDown(e) {
}
}
-function chatbot() {
+async function fetchFlagz() {
+ try {
+ const response = await fetch("/flagz");
+ return await response.json();
+ } catch (error) {
+ console.error("Could not fetch /flagz so using defaults", error);
+ return DEFAULT_FLAGZ;
+ }
+}
+
+function getSystemPrompt() {
+ let defaultPrompt = flagz.prompt;
+ if (!defaultPrompt)
+ defaultPrompt = DEFAULT_SYSTEM_PROMPT;
+ let promptsText = localStorage.getItem("v1.prompts");
+ if (!promptsText)
+ return defaultPrompt;
+ let prompts = JSON.parse(promptsText);
+ let prompt = prompts[defaultPrompt];
+ if (!prompt)
+ return defaultPrompt;
+ return prompt;
+}
+
+function startChat(history) {
+ chatHistory = history;
chatMessages.innerHTML = "";
for (let i = 0; i < chatHistory.length; i++) {
+ if (flagz.no_display_prompt && chatHistory[i].role == "system")
+ continue;
chatMessages.appendChild(createMessageElement(chatHistory[i].content,
chatHistory[i].role));
- scrollToBottom();
}
+ scrollToBottom();
+}
+
+async function chatbot() {
+ flagz = await fetchFlagz();
+ startChat([{ role: "system", content: getSystemPrompt() }]);
sendButton.addEventListener("click", sendMessage);
stopButton.addEventListener("click", stopMessage);
chatInput.addEventListener("input", onChatInput);
chatInput.addEventListener("keydown", onKeyDown);
- document.addEventListener('wheel', onWheel);
- document.addEventListener('dragenter', onDragBegin);
- document.addEventListener('dragover', onDragBegin);
- document.addEventListener('dragleave', onDragEnd);
- document.addEventListener('drop', onDragEnd);
- document.addEventListener('drop', onDrop);
- document.addEventListener('paste', onPaste);
+ document.addEventListener("wheel", onWheel);
+ document.addEventListener("dragenter", onDragBegin);
+ document.addEventListener("dragover", onDragBegin);
+ document.addEventListener("dragleave", onDragEnd);
+ document.addEventListener("drop", onDragEnd);
+ document.addEventListener("drop", onDrop);
+ document.addEventListener("paste", onPaste);
chatInput.focus();
}