Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Add Scala syntax highlighting
Justine Tunneye67522e705b2
diff --git a/llamafile/highlight.cpp b/llamafile/highlight.cppindex cf266800..ffe21176 100644--- a/llamafile/highlight.cpp+++ b/llamafile/highlight.cpp@@ -123,6 +123,11 @@ Highlight *Highlight::create(const std::string_view &lang) {lang == "kotlin")return new HighlightKotlin;+ if (lang == "sc" || //+ lang == "sbt" || //+ lang == "scala")+ return new HighlightScala;+if (lang == "lua")return new HighlightLua;diff --git a/llamafile/highlight.h b/llamafile/highlight.hindex 35957808..2086fe2c 100644--- a/llamafile/highlight.h+++ b/llamafile/highlight.h@@ -136,6 +136,7 @@ is_keyword_f is_keyword_matlab_constant;is_keyword_f is_keyword_r;is_keyword_f is_keyword_r_builtin;is_keyword_f is_keyword_r_constant;+is_keyword_f is_keyword_scala;}class Highlight {@@ -698,3 +699,17 @@ class HighlightSwift : public Highlight {unsigned char nest_[16];unsigned char hash_[16];};++class HighlightScala : public Highlight {+ public:+ HighlightScala();+ ~HighlightScala() override;+ void feed(std::string *result, std::string_view input) override;+ void flush(std::string *result) override;++ private:+ int t_ = 0;+ int nesti_ = 0;+ std::string word_;+ unsigned char nest_[16];+};diff --git a/llamafile/highlight_scala.cpp b/llamafile/highlight_scala.cppnew file mode 100644index 00000000..e0032289--- /dev/null+++ b/llamafile/highlight_scala.cpp@@ -0,0 +1,387 @@+// -*- 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 "highlight.h"++#include <ctype.h>++enum {+ NORMAL,+ WORD,+ QUOTE,+ QUOTE_BACKSLASH,+ ANNOTATION,+ ANNOTATION2,+ SLASH,+ SLASH_SLASH,+ SLASH_STAR,+ SLASH_STAR_STAR,+ DQUOTE, // "+ DQUOTE_DOLLAR, // "+ DQUOTE_VAR, // "+ DQUOTESTR, // "...+ DQUOTESTR_BACKSLASH, // "...+ DQUOTESTR_DOLLAR, // "...+ DQUOTESTR_VAR, // "...+ DQUOTE2, // ""+ DQUOTE3, // """...+ DQUOTE3_BACKSLASH,+ DQUOTE3_DOLLAR, // """...+ DQUOTE3_VAR, // """...+ DQUOTE31, // """..."+ DQUOTE32, // """...""+};++HighlightScala::HighlightScala() {+}++HighlightScala::~HighlightScala() {+}++void HighlightScala::feed(std::string *r, std::string_view input) {+ int c;+ for (size_t i = 0; i < input.size(); ++i) {+ c = input[i] & 255;+ switch (t_) {++ Normal:+ case NORMAL:+ if (!isascii(c) || isalpha(c) || c == '_') {+ t_ = WORD;+ word_ += c;+ } else if (c == '/') {+ t_ = SLASH;+ } else if (c == '\'') {+ t_ = QUOTE;+ *r += HI_STRING;+ *r += '\'';+ } else if (c == '"') {+ t_ = DQUOTE;+ *r += HI_STRING;+ *r += '"';+ } else if (c == '@') {+ t_ = ANNOTATION;+ } else if (c == '{' && nesti_ && nesti_ < sizeof(nest_)) {+ nest_[nesti_++] = NORMAL;+ *r += '{';+ } else if (c == '}' && nesti_) {+ if ((t_ = nest_[--nesti_]) != NORMAL)+ *r += HI_STRING;+ *r += '}';+ } else {+ *r += c;+ }+ break;++ case WORD:+ if (!isascii(c) || isalnum(c) || c == '_') {+ word_ += c;+ } else {+ if (is_keyword_scala(word_.data(), word_.size())) {+ *r += HI_KEYWORD;+ *r += word_;+ *r += HI_RESET;+ } else if (is_keyword_java_constant(word_.data(), word_.size())) {+ *r += HI_CONSTANT;+ *r += word_;+ *r += HI_RESET;+ } else if (!word_.empty() && isupper(word_[0])) {+ *r += HI_TYPE;+ *r += word_;+ *r += HI_RESET;+ } else {+ *r += word_;+ }+ word_.clear();+ t_ = NORMAL;+ goto Normal;+ }+ break;++ case SLASH:+ if (c == '/') {+ *r += HI_COMMENT;+ *r += "//";+ t_ = SLASH_SLASH;+ } else if (c == '*') {+ *r += HI_COMMENT;+ *r += "/*";+ t_ = SLASH_STAR;+ } else {+ *r += '/';+ t_ = NORMAL;+ goto Normal;+ }+ break;++ case SLASH_SLASH:+ *r += c;+ if (c == '\n') {+ *r += HI_RESET;+ t_ = NORMAL;+ }+ break;++ case SLASH_STAR:+ *r += c;+ if (c == '*')+ t_ = SLASH_STAR_STAR;+ break;++ case SLASH_STAR_STAR:+ *r += c;+ if (c == '/') {+ *r += HI_RESET;+ t_ = NORMAL;+ } else if (c != '*') {+ t_ = SLASH_STAR;+ }+ break;++ case QUOTE:+ *r += c;+ if (c == '\'') {+ *r += HI_RESET;+ t_ = NORMAL;+ } else if (c == '\\') {+ t_ = QUOTE_BACKSLASH;+ }+ break;++ case QUOTE_BACKSLASH:+ *r += c;+ t_ = QUOTE;+ break;++ case DQUOTE:+ *r += c;+ if (c == '"') {+ t_ = DQUOTE2;+ } else if (c == '\\') {+ t_ = DQUOTESTR_BACKSLASH;+ } else if (c == '$') {+ t_ = DQUOTESTR_DOLLAR;+ } else {+ t_ = DQUOTESTR;+ }+ break;++ Dquotestr:+ case DQUOTESTR:+ *r += c;+ if (c == '"') {+ *r += HI_RESET;+ t_ = NORMAL;+ } else if (c == '\\') {+ t_ = DQUOTESTR_BACKSLASH;+ } else if (c == '$') {+ t_ = DQUOTESTR_DOLLAR;+ }+ break;++ case DQUOTESTR_BACKSLASH:+ *r += c;+ t_ = DQUOTESTR;+ break;++ case DQUOTESTR_DOLLAR:+ if (c == '{' && nesti_ < sizeof(nest_)) {+ *r += c;+ *r += HI_RESET;+ nest_[nesti_++] = DQUOTESTR;+ t_ = NORMAL;+ } else if (!isascii(c) || isalpha(c) || c == '_') {+ *r += HI_BOLD;+ *r += c;+ t_ = DQUOTESTR_VAR;+ } else {+ t_ = DQUOTESTR;+ goto Dquotestr;+ }+ break;++ case DQUOTESTR_VAR:+ if (!isascii(c) || isalpha(c) || c == '_') {+ *r += c;+ } else {+ *r += HI_UNBOLD;+ t_ = DQUOTESTR;+ goto Dquotestr;+ }+ break;++ case DQUOTE2:+ if (c == '"') {+ *r += '"';+ t_ = DQUOTE3;+ } else {+ *r += HI_RESET;+ t_ = NORMAL;+ goto Normal;+ }+ break;++ Dquote3:+ case DQUOTE3:+ *r += c;+ if (c == '"') {+ t_ = DQUOTE31;+ } else if (c == '$') {+ t_ = DQUOTE3_DOLLAR;+ } else if (c == '\\') {+ t_ = DQUOTE3_BACKSLASH;+ }+ break;++ case DQUOTE31:+ *r += c;+ if (c == '"') {+ t_ = DQUOTE32;+ } else if (c == '$') {+ t_ = DQUOTE3_DOLLAR;+ } else if (c == '\\') {+ t_ = DQUOTE3_BACKSLASH;+ } else {+ t_ = DQUOTE3;+ }+ break;++ case DQUOTE32:+ *r += c;+ if (c == '"') {+ *r += HI_RESET;+ t_ = NORMAL;+ } else if (c == '$') {+ t_ = DQUOTE3_DOLLAR;+ } else if (c == '\\') {+ t_ = DQUOTE3_BACKSLASH;+ } else {+ t_ = DQUOTE3;+ }+ break;++ case DQUOTE3_BACKSLASH:+ *r += c;+ t_ = DQUOTE3;+ break;++ case DQUOTE3_DOLLAR:+ if (c == '{' && nesti_ < sizeof(nest_)) {+ *r += c;+ *r += HI_RESET;+ nest_[nesti_++] = DQUOTE3;+ t_ = NORMAL;+ } else if (!isascii(c) || isalpha(c) || c == '_') {+ *r += HI_BOLD;+ *r += c;+ t_ = DQUOTE3_VAR;+ } else {+ *r += c;+ t_ = DQUOTE3;+ }+ break;++ case DQUOTE3_VAR:+ if (!isascii(c) || isalpha(c) || c == '_') {+ *r += c;+ } else {+ *r += HI_UNBOLD;+ t_ = DQUOTE3;+ goto Dquote3;+ }+ break;++ case ANNOTATION:+ if (!isascii(c) || isalpha(c) || c == '_') {+ *r += HI_ATTRIB;+ *r += '@';+ *r += c;+ t_ = ANNOTATION2;+ } else {+ *r += '@';+ t_ = NORMAL;+ goto Normal;+ }+ break;++ case ANNOTATION2:+ if (!isascii(c) || isalnum(c) || c == '_') {+ *r += c;+ } else {+ *r += HI_RESET;+ t_ = NORMAL;+ goto Normal;+ }+ break;++ default:+ __builtin_unreachable();+ }+ }+}++void HighlightScala::flush(std::string *r) {+ switch (t_) {+ case WORD:+ if (is_keyword_scala(word_.data(), word_.size())) {+ *r += HI_KEYWORD;+ *r += word_;+ *r += HI_RESET;+ } else if (is_keyword_java_constant(word_.data(), word_.size())) {+ *r += HI_CONSTANT;+ *r += word_;+ *r += HI_RESET;+ } else if (!word_.empty() && isupper(word_[0])) {+ *r += HI_TYPE;+ *r += word_;+ *r += HI_RESET;+ } else {+ *r += word_;+ }+ word_.clear();+ break;+ case SLASH:+ *r += '/';+ break;+ case ANNOTATION:+ *r += '@';+ break;+ case QUOTE:+ case QUOTE_BACKSLASH:+ case SLASH_SLASH:+ case SLASH_STAR:+ case SLASH_STAR_STAR:+ case DQUOTE:+ case DQUOTESTR:+ case DQUOTESTR_BACKSLASH:+ case DQUOTESTR_DOLLAR:+ case DQUOTESTR_VAR:+ case DQUOTE2:+ case DQUOTE3:+ case DQUOTE3_BACKSLASH:+ case DQUOTE31:+ case DQUOTE32:+ case ANNOTATION2:+ case DQUOTE3_DOLLAR:+ case DQUOTE3_VAR:+ *r += HI_RESET;+ break;+ default:+ break;+ }+ t_ = NORMAL;+}diff --git a/llamafile/highlight_test.cpp b/llamafile/highlight_test.cppindex 602ad203..3439ae13 100644--- a/llamafile/highlight_test.cpp+++ b/llamafile/highlight_test.cpp@@ -60,6 +60,7 @@ const char *const kLanguages[] = {"r", //"ruby", //"rust", //+ "scala", //"shell", //"sql", //"swift", //diff --git a/llamafile/is_keyword_scala.gperf b/llamafile/is_keyword_scala.gperfnew file mode 100644index 00000000..8da2c2bb--- /dev/null+++ b/llamafile/is_keyword_scala.gperf@@ -0,0 +1,46 @@+%{+#include <string.h>+%}+%pic+%compare-strncmp+%language=ANSI-C+%readonly-tables+%define lookup-function-name is_keyword_scala+%%+abstract+case+catch+class+def+do+else+extends+final+finally+for+forSome+if+implicit+import+lazy+macro+match+new+object+override+package+private+protected+return+sealed+super+this+throw+trait+try+type+val+var+while+with+yielddiff --git a/llamafile/server/doc/endpoints.md b/llamafile/server/doc/endpoints.mdindex 72da38b2..e01cd1df 100644--- a/llamafile/server/doc/endpoints.md+++ b/llamafile/server/doc/endpoints.md@@ -2,3 +2,4 @@- [`/tokenize`](tokenize.md)- [`/embedding`](embedding.md)+- [`/v1/chat/completions`](v1_chat_completions.md)diff --git a/llamafile/server/doc/v1_chat_completions.md b/llamafile/server/doc/v1_chat_completions.mdnew file mode 100644index 00000000..fce4af08--- /dev/null+++ b/llamafile/server/doc/v1_chat_completions.md@@ -0,0 +1,167 @@+# LLaMAfiler Chat Completions Endpoint++The `/v1/chat/completions` endpoint lets you build a chatbot.++## Request URIs++- `/v1/chat/completions` (OpenAI API compatible)++## Request Methods++- `POST`++## Request Content Types++- `application/json` must be used.++## Request Parameters++- `model`: `string`++ Specifies name of model to run.++ Only a single model is currently supported, so this field is simply+ copied along to the response. In the future, this will matter.++ This field is required in the request.++- `messages`: `array<object<role:string, content:string>>`++ Specifies chat messages.++ This is your prompt, except structured as JSON that indicates who's+ saying what. It's a required array containing objects. Each object has+ two mandatory fields:++ - `role`: `string`++ The role may be any of the following:++ - `system`: Used for system prompts.+ - `user`: Used when the user is speaking.+ - `assistant`: Used when the model is speaking.++ - `content`: `string`++ The content field holds text the system, user, or assistant said.++ The completion endpoint will then generate at least one additional+ chat message. If the client wishes to request another completion, then+ the client should append the server-provided message to the messages+ field, and then start a new chat completions request over. The server+ will then look at the full conversation history, notice that it's+ cached, and then re-use the same context if it hasn't expired.+ Otherwise, it'll prefill the entire provided messages history into a+ new context to resume a fresh conversation where you left off.++- `stream`: `boolean|null`++ If this field is optionally set to true, then this endpoint will+ return a text/event-stream using HTTP chunked transfer encoding. This+ allows your chatbot to rapidly show text as it's being genearted. The+ standard JSON response is slightly modified so that its message field+ will be named delta instead. It's assumed the client will reconstruct+ the full conversation.++- `max_tokens`: `integer|null`++ Specifies an upper bound for the number of tokens that can be+ generated for this completion. This can be used to control compute+ and/or latency costs.++- `max_completion_tokens`: `integer|null`++ This currently means the same thing as `max_tokens`.++- `top_p`: `number|null`++ May optionally be used to set the `top_p` sampling parameter. This+ should be a floating point number. Setting this to 1.0 (the default)+ will disable this feature. Setting this to, for example, 0.1, would+ mean that only the top 10% probability tokens are considered.++ We generally recommend altering this or temperature but not both.++- `temperature`: `number|null`++ Configures the randomness level of generated text.++ This field may be set to a value between 0.0 and 2.0 inclusive. It+ defaults to 1.0. Lower numbers are more deterministic. Higher numbers+ mean more randomness.++ We generally recommend altering this or top_p but not both.++- `seed`: `integer|null`++ If specified, llamafiler will make its best effort to sample+ deterministically, even when temperature is non-zero. This means that+ repeated requests with the same seed and parameters should return the+ same result.++- `seed`: `integer|null`++ If specified, llamafiler will make its best effort to sample+ deterministically, even when temperature is non-zero. This means that+ repeated requests with the same seed and parameters should return the+ same result.++- `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.++- `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.++- `user`: `string|null`++ A unique identifier representing your end-user, which can help+ llamafiler to monitor and detect abuse.++- `stop`: `string|array<string>|null`++ Up to 4 sequences where the API will stop generating further tokens.++- `response_format`: `string|object|null`++ Specifies the format that the model must output.++ The default value is `"auto"` which means to just output arbitrary+ text without any kind of grammar constraint. No other string values+ are currently supported.++ This field may be set to `{ "type": "json_object" }` to indicate that+ the response must be a valid JSON object, e.g. `{}`, `{"hi": 123}`. If+ you use this feature, then you must have your user in the last chat+ message instruct the LLM to generate JSON, otherwise you might get a+ strange response that never ends.++ It's also possible to further constrain the JSON, by specifying a JSON+ schema, by using `{ "type": "json_schema", "json_schema": {...} }`. In+ this case, you're able to specify things like mandatory fields and+ their types.++The following OpenAI Chat Completions request parameters are currently+unsupported:++- `n`+- `tools`+- `audio`+- `logprobs`+- `functions`+- `modalities`+- `tool_choice`+- `top_logprobs`+- `function_call`+- `parallel_tool_calls`++## See Also++- [LLaMAfiler Documentation Index](index.md)+- [LLaMAfiler Endpoints Reference](endpoints.md)+- [LLaMAfiler Technical Details](technical_details.md)diff --git a/llamafile/server/json.cpp b/llamafile/server/json.cppindex 621fa6e6..715ad70d 100644--- a/llamafile/server/json.cpp+++ b/llamafile/server/json.cpp@@ -125,6 +125,11 @@ StringToDouble(const char* s, size_t n, int* out_processed)return res;}+Json::~Json()+{+ clear();+}+voidJson::clear(){diff --git a/llamafile/server/json.h b/llamafile/server/json.hindex b8d0574a..4a0bbd0c 100644--- a/llamafile/server/json.h+++ b/llamafile/server/json.h@@ -92,11 +92,7 @@ class JsonJson(const Json&);Json(Json&&) noexcept;-- ~Json()- {- clear();- }+ ~Json();Json(const nullptr_t = nullptr) : type_(Null){diff --git a/llamafile/server/v1_chat_completions.cpp b/llamafile/server/v1_chat_completions.cppindex 933c96b7..70bf83fc 100644--- a/llamafile/server/v1_chat_completions.cpp+++ b/llamafile/server/v1_chat_completions.cpp@@ -216,7 +216,7 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)// 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.+ // a completion. This can be used to control compute costs.Json& max_tokens = json.second["max_tokens"];if (!max_tokens.isNull()) {if (!max_tokens.isLong())@@ -307,7 +307,7 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)// user: string|null//// A unique identifier representing your end-user, which can help- // llamafile to monitor and detect abuse. Learn more.+ // llamafiler to monitor and detect abuse.Json& user = json.second["user"];if (!user.isNull()) {if (!user.isString())