Archived
radiance 1.3.0
- #47: llama-server's request fields, routes and sampler order, and /props (with baKon's model entry: max_model_len, root and capabilities on /v1/models, and /v1/models/:id) - new APIs: Anthropic's Messages API (/v1/messages), OpenAI's Responses API (/v1/responses), llama-server's /completion and /infill, logprobs (OpenAI's logprobs and top_logprobs, up to 20; llama-server's n_probs), OpenAI's legacy `functions`, and X-Api-Key beside the bearer key - #4: --model takes a Hugging Face repo id (owner/name), fetched before startup into ~/.cache/radiance/hf or --download-dir and checked for changes at every start (redxherring) - #46: --tp 3 --tp-wire wht6 serves -- a three-rank two-shot all-reduce with uneven shards and the tiered-int8 wire over it (baKon); scripts/cardclock.py names what holds each card's clock under load (baKon) - CPU-only serving works again; --kernels names the kernel libraries to load; a model the loaded libraries cannot fully serve refuses at startup instead of failing its first request; --vram-kv-mib and --vram-weights-mib are gone (the split is automatic) - --embedding-placement ram is the default, and `auto` is gone - #40: Swift 1.5 recipes; rad-convert reads which shard holds a tensor from the index - #53: the pinned host pool gets huge pages where shmem THP is off; #57: a crash on video with an odd frame width is fixed
This commit is contained in:
1 parent
6a2ee986d6
commit
89cee7ce41
107 files changed
+6849
-1091
No files matched your search
+26
-1
@@ -142,6 +142,7 @@ public:
|
||||
SessionStat o;
|
||||
o.id = s.id;
|
||||
o.model = s.model;
|
||||
o.label = s.label;
|
||||
o.n_tokens = s.n_tokens;
|
||||
o.bytes = s.bytes;
|
||||
o.idle_s = now > s.last_used_ns ? (double)(now - s.last_used_ns) / 1e9 : 0.0;
|
||||
@@ -319,6 +320,7 @@ public:
|
||||
std::string push(int32_t t) override { return d_.push(t); }
|
||||
std::string flush() override { return d_.flush(); }
|
||||
bool stopped() const override { return d_.stopped(); }
|
||||
std::string stop_hit() const override { return d_.stop_hit(); }
|
||||
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
|
||||
private:
|
||||
Detokenizer d_;
|
||||
@@ -376,6 +378,14 @@ public:
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return utf8_sanitize(vocab_->text(id));
|
||||
}
|
||||
std::string token_bytes(int32_t id) const override {
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return tok_.decode({ id }, /*render_special=*/true);
|
||||
}
|
||||
std::string reply_bytes(int32_t id) const override {
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return tok_.decode({ id }, /*render_special=*/false);
|
||||
}
|
||||
|
||||
std::unique_ptr<IDetokenizer> detokenizer(
|
||||
const std::vector<std::string>& stops,
|
||||
@@ -549,7 +559,21 @@ public:
|
||||
bool supports_tools() const override { return t_.caps().tools; }
|
||||
bool supports_reasoning() const override { return t_.caps().preserve_reasoning; }
|
||||
std::string tool_refusal() const override { return tool_refusal_; }
|
||||
const std::string& source() const { return t_.source(); }
|
||||
std::string source() const override { return t_.source(); }
|
||||
/* Under llama-server's names (its chat_template_caps), from the same probe. */
|
||||
std::string caps() const override {
|
||||
const ChatCaps& c = t_.caps();
|
||||
json o;
|
||||
o["supports_tools"] = c.tools;
|
||||
o["supports_tool_calls"] = c.tool_calls;
|
||||
o["supports_system_role"] = c.system_role;
|
||||
o["supports_parallel_tool_calls"] = c.parallel_tool_calls;
|
||||
o["supports_preserve_reasoning"] = c.preserve_reasoning;
|
||||
o["supports_string_content"] = c.string_content;
|
||||
o["supports_typed_content"] = c.typed_content;
|
||||
o["supports_object_arguments"] = c.object_arguments;
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
int apply(const json& messages, const json& tools, const ChatRenderOptions& opt,
|
||||
ChatRender* out, std::string* why) const override {
|
||||
@@ -559,6 +583,7 @@ public:
|
||||
o.parallel_tool_calls = opt.parallel_tool_calls;
|
||||
o.tool_choice = opt.tool_choice;
|
||||
o.reasoning_format = opt.reasoning_format;
|
||||
o.continue_final = opt.continue_final;
|
||||
o.grammar = opt.grammar;
|
||||
o.json_schema = opt.json_schema;
|
||||
o.template_kwargs = opt.template_kwargs;
|
||||
|
||||
+142
-28
@@ -1,6 +1,7 @@
|
||||
/* core/server/admin.cpp -- vLLM's non-generation endpoints.
|
||||
/* core/server/admin.cpp -- vLLM's and llama-server's non-generation endpoints.
|
||||
*
|
||||
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache.
|
||||
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache
|
||||
* /props.
|
||||
*
|
||||
* Separate from server.cpp because none of it touches the step path: no admission, no Sink, no
|
||||
* cancellation, nothing that outlives the handler. They are questions ABOUT the server, answered
|
||||
@@ -8,15 +9,17 @@
|
||||
* streaming lifetime would make that file harder to read for no shared code at all.
|
||||
*
|
||||
* WHAT IS DELIBERATELY NOT HERE. vLLM's surface also carries /pooling, /classify, /score and
|
||||
* /rerank (an embedding or cross-encoder model, which this engine does not load), /sleep, /wake_up
|
||||
* /rerank (a classifier or cross-encoder head, which this engine does not load), /sleep, /wake_up
|
||||
* and /is_sleeping (there is no sleep mode: weights are placed once, see spec §5), the LoRA
|
||||
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and
|
||||
* /v1/responses (a stateful conversation store, which is a component and not an endpoint). Each
|
||||
* would be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
|
||||
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and the
|
||||
* Responses API's stored responses (retrieved or deleted by id: a conversation store, which is a
|
||||
* component and not an endpoint); llama-server's carries /slots (its own slot state). Each would
|
||||
* be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
|
||||
*/
|
||||
#include "server.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -143,8 +146,61 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
|
||||
auto msgs = b.find("messages");
|
||||
auto prom = b.find("prompt");
|
||||
if (msgs != b.end() && prom != b.end())
|
||||
return error_response(err_bad("prompt", "send `prompt` or `messages`, not both"), req.peer);
|
||||
auto cont = b.find("content");
|
||||
if ((msgs != b.end()) + (prom != b.end()) + (cont != b.end()) > 1)
|
||||
return error_response(err_bad("prompt", "send one of `prompt`, `messages` or `content`"),
|
||||
req.peer);
|
||||
|
||||
/* THE THIRD SHAPE IS llama-server's: `content` -- a string, or strings and token ids mixed,
|
||||
* as its /completion takes a prompt -- with its own two flags and its own defaults (no BOS,
|
||||
* control tokens recognised), answered under its own key, `tokens`, as ids or with
|
||||
* `with_pieces` as {id, piece} objects. A piece that is not whole UTF-8 is its bytes, as
|
||||
* llama-server sends it. */
|
||||
if (cont != b.end()) {
|
||||
const bool add_special = get_bool_or(b, "add_special", false);
|
||||
const bool parse_special = get_bool_or(b, "parse_special", true);
|
||||
const bool with_pieces = get_bool_or(b, "with_pieces", false);
|
||||
auto take = [&](const json& v, bool first) -> bool {
|
||||
if (v.is_string()) {
|
||||
const std::vector<int32_t> t =
|
||||
deps_.tok->encode(v.get<std::string>(), first && add_special, parse_special);
|
||||
toks.insert(toks.end(), t.begin(), t.end());
|
||||
return true;
|
||||
}
|
||||
int32_t id = 0;
|
||||
if (!v.is_number_integer() || !token_id(v, &id)) return false;
|
||||
toks.push_back(id);
|
||||
return true;
|
||||
};
|
||||
bool ok = true;
|
||||
if (cont->is_array()) {
|
||||
bool first = true;
|
||||
for (const json& v : *cont) { ok = ok && take(v, first); first = false; }
|
||||
} else {
|
||||
ok = cont->is_string() && take(*cont, true);
|
||||
}
|
||||
if (!ok)
|
||||
return error_response(err_bad("content", "must be a string, or an array of strings "
|
||||
"and token ids"), req.peer);
|
||||
json arr = json::array();
|
||||
for (int32_t t : toks) {
|
||||
if (!with_pieces) { arr.push_back(t); continue; }
|
||||
const std::string piece = deps_.tok->token_bytes(t);
|
||||
json e;
|
||||
e["id"] = t;
|
||||
/* A piece that is not whole UTF-8 goes as its bytes, 0-255, as llama-server sends it. */
|
||||
if (utf8_valid_prefix(piece) == piece.size()) e["piece"] = piece;
|
||||
else e["piece"] = std::vector<int>((const unsigned char*)piece.data(),
|
||||
(const unsigned char*)piece.data() + piece.size());
|
||||
arr.push_back(std::move(e));
|
||||
}
|
||||
json o;
|
||||
o["tokens"] = std::move(arr);
|
||||
o["count"] = (int64_t)toks.size();
|
||||
o["max_model_len"] = opt_.max_ctx;
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
if (msgs != b.end()) {
|
||||
if (!deps_.chat)
|
||||
@@ -227,8 +283,10 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
|
||||
toks.push_back(id);
|
||||
}
|
||||
|
||||
/* `prompt` is vLLM's key and `content` llama-server's, for the same text. */
|
||||
json o;
|
||||
o["prompt"] = deps_.tok->decode(toks);
|
||||
o["content"] = o["prompt"];
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
@@ -239,29 +297,66 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
|
||||
* and reads what a request that sends no sampler fields inherits. /server_info says all of it and
|
||||
* more, but nothing written for llama-server knows to ask there.
|
||||
*
|
||||
* Only what this server can fill honestly, under llama-server's names: no chat template text
|
||||
* (the server holds a compiled template, not its source), no GGUF metadata, no per-slot state.
|
||||
* n_ctx is the context ONE request may use, which is what llama-server's per-slot n_ctx means to
|
||||
* the clients reading it; left out when the server does not know its length. */
|
||||
* Only what this server can fill honestly, under llama-server's names: no GGUF metadata, no
|
||||
* per-slot state. n_ctx is the context ONE request may use, which is what llama-server's per-slot
|
||||
* n_ctx means to the clients reading it; left out when the server does not know its length. */
|
||||
HttpResponse Server::handle_props(const HttpRequest&) {
|
||||
const SamplingParams& sp = opt_.default_sampling;
|
||||
/* EVERY FIELD llama-server's `params` CARRIES, so a client that reads one does not find it
|
||||
* missing. The samplers this server does not run are reported at their off values -- which
|
||||
* is what it serves -- and `samplers` is its own order, temperature first. */
|
||||
const int64_t n_predict = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
|
||||
json params;
|
||||
params["n_predict"] = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
|
||||
params["temperature"] = sp.temp;
|
||||
params["top_k"] = sp.top_k;
|
||||
params["top_p"] = sp.top_p;
|
||||
params["min_p"] = sp.min_p;
|
||||
params["typical_p"] = sp.typical_p;
|
||||
params["repeat_last_n"] = sp.penalty_last_n;
|
||||
params["repeat_penalty"] = sp.rep_penalty;
|
||||
params["presence_penalty"] = sp.pres_penalty;
|
||||
params["frequency_penalty"] = sp.freq_penalty;
|
||||
params["dry_multiplier"] = sp.dry_multiplier;
|
||||
params["dry_base"] = sp.dry_base;
|
||||
params["dry_allowed_length"] = sp.dry_allowed_length;
|
||||
params["dry_penalty_last_n"] = sp.dry_penalty_last_n;
|
||||
params["xtc_probability"] = sp.xtc_probability;
|
||||
params["xtc_threshold"] = sp.xtc_threshold;
|
||||
params["n_predict"] = n_predict;
|
||||
params["max_tokens"] = n_predict;
|
||||
params["seed"] = -1;
|
||||
params["temperature"] = sp.temp;
|
||||
params["dynatemp_range"] = 0.0;
|
||||
params["dynatemp_exponent"] = 1.0;
|
||||
params["top_k"] = sp.top_k;
|
||||
params["top_p"] = sp.top_p;
|
||||
params["min_p"] = sp.min_p;
|
||||
params["top_n_sigma"] = -1.0;
|
||||
params["typical_p"] = sp.typical_p;
|
||||
params["typ_p"] = sp.typical_p;
|
||||
params["xtc_probability"] = sp.xtc_probability;
|
||||
params["xtc_threshold"] = sp.xtc_threshold;
|
||||
params["repeat_last_n"] = sp.penalty_last_n;
|
||||
params["repeat_penalty"] = sp.rep_penalty;
|
||||
params["presence_penalty"] = sp.pres_penalty;
|
||||
params["frequency_penalty"] = sp.freq_penalty;
|
||||
params["dry_multiplier"] = sp.dry_multiplier;
|
||||
params["dry_base"] = sp.dry_base;
|
||||
params["dry_allowed_length"] = sp.dry_allowed_length;
|
||||
params["dry_penalty_last_n"] = sp.dry_penalty_last_n;
|
||||
params["dry_sequence_breakers"] = sp.dry_seq_breakers.empty() && !opt_.default_dry_breakers_set
|
||||
? std::vector<std::string>{ "\n", ":", "\"", "*" }
|
||||
: sp.dry_seq_breakers;
|
||||
params["mirostat"] = 0;
|
||||
params["mirostat_tau"] = 5.0;
|
||||
params["mirostat_eta"] = 0.1;
|
||||
params["stop"] = json::array();
|
||||
params["n_keep"] = 0;
|
||||
params["n_discard"] = 0;
|
||||
params["ignore_eos"] = false;
|
||||
params["stream"] = true;
|
||||
params["logit_bias"] = json::array();
|
||||
params["n_probs"] = 0;
|
||||
params["min_keep"] = 0;
|
||||
params["grammar"] = "";
|
||||
params["grammar_lazy"] = false;
|
||||
params["grammar_triggers"] = json::array();
|
||||
params["preserved_tokens"] = json::array();
|
||||
params["chat_format"] = "";
|
||||
params["reasoning_format"] = "auto";
|
||||
params["reasoning_in_content"] = false;
|
||||
params["generation_prompt"] = "";
|
||||
params["samplers"] = { "penalties", "dry", "temperature", "top_k", "top_p", "min_p", "typ_p",
|
||||
"xtc" };
|
||||
params["backend_sampling"] = false;
|
||||
params["timings_per_token"] = false;
|
||||
params["post_sampling_probs"] = false;
|
||||
params["lora"] = json::array();
|
||||
|
||||
json gen;
|
||||
if (opt_.max_ctx > 0) gen["n_ctx"] = opt_.max_ctx;
|
||||
@@ -269,13 +364,32 @@ HttpResponse Server::handle_props(const HttpRequest&) {
|
||||
|
||||
json modal;
|
||||
modal["vision"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
|
||||
modal["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
modal["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
|
||||
json o;
|
||||
o["default_generation_settings"] = std::move(gen);
|
||||
o["total_slots"] = opt_.max_seqs;
|
||||
o["model_alias"] = opt_.model_id;
|
||||
o["model_path"] = opt_.model_path;
|
||||
o["modalities"] = std::move(modal);
|
||||
o["endpoint_slots"] = false;
|
||||
o["endpoint_props"] = false;
|
||||
o["endpoint_metrics"] = true;
|
||||
o["chat_template"] = deps_.chat ? deps_.chat->source() : std::string();
|
||||
o["chat_template_caps"] = json::parse(deps_.chat ? deps_.chat->caps() : std::string("{}"),
|
||||
nullptr, false);
|
||||
std::string bos, eos;
|
||||
if (deps_.tok) {
|
||||
const ITokenizer::VocabInfo v = deps_.tok->vocab_info();
|
||||
if (v.bos >= 0) bos = deps_.tok->piece(v.bos);
|
||||
if (v.eos >= 0) eos = deps_.tok->piece(v.eos);
|
||||
}
|
||||
o["bos_token"] = bos;
|
||||
o["eos_token"] = eos;
|
||||
o["build_info"] = "radiance " + opt_.version;
|
||||
o["role"] = "model";
|
||||
o["is_sleeping"] = false;
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
json e;
|
||||
e["id"] = s.id;
|
||||
e["model"] = s.model;
|
||||
if (!s.label.empty()) e["label"] = s.label;
|
||||
e["tokens"] = s.n_tokens;
|
||||
e["bytes"] = s.bytes;
|
||||
e["idle_s"] = s.idle_s;
|
||||
@@ -681,6 +682,7 @@ th + th, td + td { padding-left:14px; }
|
||||
/* Fixed, so the tier column starts at one x in both tables. */
|
||||
.stbl .ret { width:340px; }
|
||||
.sid { font-weight:500; }
|
||||
.slabel { margin-left:8px; color:var(--faint); }
|
||||
.mv { font:500 10px/1 var(--ui); color:var(--faint); border:1px solid var(--rule);
|
||||
border-radius:4px; padding:2px 5px; margin-left:6px; }
|
||||
/* WHERE IT IS, by share of the conversation's context, one colour a tier. A conversation is
|
||||
@@ -2850,6 +2852,8 @@ function sessRow(r, hybrid, manyModels) {
|
||||
const tr = el("tr");
|
||||
const id = tr.appendChild(el("td"));
|
||||
id.appendChild(el("span", "sid", "#" + r.id));
|
||||
/* The client's own name for the conversation (`session_id`), when it sent one. */
|
||||
if (r.label) id.appendChild(el("span", "slabel", r.label));
|
||||
if (r.moving) id.appendChild(el("span", "mv", "moving"));
|
||||
if (manyModels) tr.appendChild(el("td", "l", r.model || DASH));
|
||||
tr.appendChild(el("td", null, cnt3(r.tokens) + " tok"));
|
||||
|
||||
+32
-6
@@ -363,10 +363,13 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
* leaving /tokenize open, which hands an unauthenticated caller the vocabulary and the
|
||||
* chat template. This does not. */
|
||||
const std::string& p = hreq.path;
|
||||
if (!api_key.empty() && p != "/health" && p != "/ping" && p != "/" && p != "/dashboard") {
|
||||
std::string got = hreq.get_header_value("Authorization");
|
||||
const std::string want = "Bearer " + api_key;
|
||||
if (got != want) {
|
||||
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
|
||||
p != "/dashboard") {
|
||||
/* `Authorization: Bearer` is OpenAI's spelling and `X-Api-Key` Anthropic's, which
|
||||
* llama-server takes as well; either one carrying the key is enough. */
|
||||
const bool ok = hreq.get_header_value("Authorization") == "Bearer " + api_key ||
|
||||
hreq.get_header_value("X-Api-Key") == api_key;
|
||||
if (!ok) {
|
||||
/* Said like every other refusal (Server::error_response), which this one never
|
||||
* reaches: the gate answers before the router does. */
|
||||
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
|
||||
@@ -453,15 +456,38 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
bridge(q, std::move(body), s);
|
||||
});
|
||||
}
|
||||
svr.Options(".*", [cors](const httplib::Request&, httplib::Response& res) {
|
||||
/* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than
|
||||
* the two this server reads -- the OpenAI SDK adds its x-stainless-* set -- and a preflight
|
||||
* that does not list one fails the request before it is sent. A wildcard would not do: CORS
|
||||
* never lets `*` stand for Authorization, so the requested list is echoed back. */
|
||||
svr.Options(".*", [cors](const httplib::Request& req, httplib::Response& res) {
|
||||
if (cors) {
|
||||
const std::string asked = req.get_header_value("Access-Control-Request-Headers");
|
||||
res.set_header("Access-Control-Allow-Origin", "*");
|
||||
res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
res.set_header("Access-Control-Allow-Headers",
|
||||
asked.empty() ? "Content-Type, Authorization, X-Api-Key" : asked);
|
||||
res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.set_header("Access-Control-Max-Age", "86400");
|
||||
}
|
||||
res.status = 204;
|
||||
});
|
||||
|
||||
/* A PATH NO ROUTE NAMES is answered by httplib before the router sees it, with no body. Every
|
||||
* other refusal this server makes is an error object, and a client reading one finds an
|
||||
* empty 404 unparseable; so an error with no body gets one here. A response that already
|
||||
* carries a body -- the router's own 404 and 405, the gate's 401 -- is left as it is. */
|
||||
svr.set_error_handler([cors](const httplib::Request& req, httplib::Response& res) {
|
||||
if (!res.body.empty()) return httplib::Server::HandlerResponse::Unhandled;
|
||||
if (cors) res.set_header("Access-Control-Allow-Origin", "*");
|
||||
const std::string type = res.status == 404 ? "not_found_error"
|
||||
: res.status >= 500 ? "internal_server_error"
|
||||
: "invalid_request_error";
|
||||
const std::string what = res.status == 404 ? "no route for " + req.method + " " + req.path
|
||||
: httplib::status_message(res.status);
|
||||
res.set_content(error_body(type.c_str(), what), "application/json");
|
||||
return httplib::Server::HandlerResponse::Handled;
|
||||
});
|
||||
|
||||
/* Bound once: asking for a named port and then for any port would leave the first socket
|
||||
* bound and unused. */
|
||||
const int port = o.port == 0 ? svr.bind_to_any_port(o.host.c_str())
|
||||
|
||||
@@ -160,6 +160,7 @@ struct SchedMetrics {
|
||||
struct SessionStat {
|
||||
uint64_t id = 0;
|
||||
std::string model; /* the container it was built against */
|
||||
std::string label; /* the client's name for it (`session_id`), or "" */
|
||||
int64_t n_tokens = 0;
|
||||
int64_t bytes = 0;
|
||||
double idle_s = 0; /* since its last turn */
|
||||
@@ -307,6 +308,8 @@ public:
|
||||
* search text that can no longer contain what it is searching for, and the generation would
|
||||
* run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
|
||||
virtual bool stopped() const { return false; }
|
||||
/* The stop string that stopped it, "" when none has. */
|
||||
virtual std::string stop_hit() const { return std::string(); }
|
||||
/* Match the stop strings only after `marker` has been generated (core/text Detokenizer::
|
||||
* defer_stops_until): the reply starts inside its reasoning block. */
|
||||
virtual void defer_stops_until(const std::string& /*marker*/) {}
|
||||
@@ -349,6 +352,15 @@ public:
|
||||
* turned the flag on to see. "" when the id is out of range. */
|
||||
virtual std::string piece(int32_t /*id*/) const { return std::string(); }
|
||||
|
||||
/* THE BYTES ONE ID DECODES TO, unsanitised, control tokens rendered: llama-server's
|
||||
* `with_pieces`. Not necessarily whole UTF-8 -- a byte-fallback or a split multi-byte
|
||||
* character is a fragment -- so the caller checks before putting it in a JSON string. */
|
||||
virtual std::string token_bytes(int32_t /*id*/) const { return std::string(); }
|
||||
/* The bytes one id adds to a REPLY: token_bytes with control tokens rendered as nothing, as
|
||||
* the decoder renders them -- what a logprobs entry spells the token as, so the entries'
|
||||
* texts add up to the reply, as llama-server's do. */
|
||||
virtual std::string reply_bytes(int32_t id) const { return token_bytes(id); }
|
||||
|
||||
/* One incremental decoder per in-flight generation. It is made by the tokenizer rather than
|
||||
* default-constructed by the caller, because it needs the vocabulary to decode anything.
|
||||
* `stops` is passed down because core/text's Detokenizer can suppress a stop string that
|
||||
@@ -382,6 +394,9 @@ struct ChatRenderOptions {
|
||||
std::string grammar; /* the caller's GBNF, or "" */
|
||||
std::string json_schema; /* a response_format schema, as JSON text, or "" */
|
||||
std::string reasoning_format = "auto";
|
||||
/* ASSISTANT PREFILL: continue the conversation's last (assistant) message rather than open a
|
||||
* new turn. "" off, else llama.cpp's "auto", "content" or "reasoning_content". */
|
||||
std::string continue_final;
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
/* A render whose refusal is an answer and not an error -- the startup probes of what the
|
||||
* template takes -- so the template's refusal is not logged. */
|
||||
@@ -438,6 +453,13 @@ public:
|
||||
* request that sends tools is refused with this sentence rather than answered with calls
|
||||
* nobody can read back. */
|
||||
virtual std::string tool_refusal() const { return std::string(); }
|
||||
|
||||
/* THE TEMPLATE'S SOURCE TEXT and what the capability probe found in it, for /props: what
|
||||
* llama-server reports as `chat_template` and `chat_template_caps`, so a client built against
|
||||
* it can render a prompt the way this server will. "" when unknown; the caps are a JSON
|
||||
* object as text, "{}" when unknown. */
|
||||
virtual std::string source() const { return std::string(); }
|
||||
virtual std::string caps() const { return "{}"; }
|
||||
};
|
||||
|
||||
/* A reply taken apart: what core/text's reply parser gives back once the reply is complete. */
|
||||
|
||||
+1785
-238
File diff suppressed because it is too large.
Load diff
+216
-31
@@ -8,12 +8,12 @@
|
||||
* exception crossing the transport is a connection closed with no body, which is the least
|
||||
* diagnosable thing a client can be handed.
|
||||
*
|
||||
* A parameter we do not support is a 400 that names it. Not a silent ignore. A client that sends
|
||||
* `logit_bias` and gets a 200 has been told its bias was applied, and the resulting bug report
|
||||
* ("the model ignores my bias") is unanswerable from the server side. The cost of strictness is
|
||||
* that a client sending a field we have not heard of gets a 400 rather than a shrug; the
|
||||
* allowlist below is where the genuinely inert OpenAI metadata fields (`user`, `store`, ...)
|
||||
* are named, so that cost falls only on fields that actually mean something.
|
||||
* A parameter that would change the answer and is not served is a 400 that names it, not a
|
||||
* silent ignore: a client that sends a `logit_bias` and gets a 200 has been told its bias was
|
||||
* applied, and the bug report that follows ("the model ignores my bias") is unanswerable from the
|
||||
* server side. Such a field is accepted at its "off" value, which is what llama.cpp-built clients
|
||||
* send on every request. A field this server has never heard of is ignored, as llama.cpp and vLLM
|
||||
* ignore it (oai.cpp, key vetting).
|
||||
*/
|
||||
#pragma once
|
||||
#include "iface.h"
|
||||
@@ -40,6 +40,11 @@ struct ApiError {
|
||||
/* The values `param` takes, when the error is a value outside a known set: `supported` in the
|
||||
* envelope, so a client can retry with one rather than parse the sentence. */
|
||||
std::vector<std::string> supported;
|
||||
/* A prompt the context cannot hold: its length and the context's, under llama-server's names,
|
||||
* so a client that compacts its history on overflow reads the numbers rather than the
|
||||
* sentence. -1 leaves them out. */
|
||||
int64_t n_prompt_tokens = -1;
|
||||
int64_t n_ctx = -1;
|
||||
|
||||
std::string dump() const; /* the OpenAI error envelope, as a JSON string */
|
||||
};
|
||||
@@ -60,6 +65,11 @@ ApiError err_overloaded(const std::string& why);
|
||||
|
||||
enum class Endpoint { Chat, Completion, Embedding };
|
||||
|
||||
/* WHICH API A CHAT REQUEST CAME IN THROUGH, and so which shape its answer goes out in. Every shape
|
||||
* is parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and
|
||||
* served by the same path; only the bytes on the wire differ. */
|
||||
enum class ApiShape { OpenAI, Anthropic, Responses, LlamaNative };
|
||||
|
||||
struct PromptInput {
|
||||
std::vector<int32_t> tokens;
|
||||
std::string text; /* the rendered prompt; needed for `echo` and for the logs */
|
||||
@@ -73,13 +83,36 @@ struct OaiRequest {
|
||||
std::string id; /* "chatcmpl-..." / "cmpl-..." */
|
||||
int64_t created = 0; /* unix seconds */
|
||||
|
||||
ApiShape shape = ApiShape::OpenAI;
|
||||
bool stream = false;
|
||||
bool include_usage = false; /* stream_options.include_usage */
|
||||
/* llama.cpp's streaming extras: `timings` on every chunk, not only the last; and
|
||||
* `prompt_progress` chunks while the prompt is read. */
|
||||
bool timings_per_token = false;
|
||||
bool return_progress = false;
|
||||
/* The conversation as the client names it (OpenRouter's `session_id`), "" when it names none:
|
||||
* a label on /sessions, nothing else. */
|
||||
std::string session_label;
|
||||
/* The build, as OpenAI's `system_fingerprint` and llama.cpp's own: what produced the reply. */
|
||||
std::string system_fingerprint;
|
||||
|
||||
int n = 1;
|
||||
SamplingParams sp;
|
||||
int32_t max_tokens = 0;
|
||||
std::vector<std::string> stop;
|
||||
/* Of `stop`, how many the client sent; the rest are the chat format's own end-of-turn
|
||||
* markers. A reply cut on one of the first is Anthropic's `stop_sequence`, on the rest its
|
||||
* `end_turn`. */
|
||||
size_t n_client_stops = 0;
|
||||
/* The assistant text a continued conversation ends in (assistant prefill), "" otherwise. The
|
||||
* OpenAI shape answers the whole message, as llama-server does; Anthropic's answers what
|
||||
* follows it, as Anthropic's API does. */
|
||||
std::string continued;
|
||||
/* The Responses API's request fields its response object echoes (instructions, tools,
|
||||
* tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
|
||||
std::string echo_json;
|
||||
/* llama-server's native /completion: the generated token ids beside the text. */
|
||||
bool return_tokens = false;
|
||||
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
|
||||
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
|
||||
std::string stops_after;
|
||||
@@ -94,6 +127,9 @@ struct OaiRequest {
|
||||
bool want_logprobs = false;
|
||||
|
||||
bool tools_present = false;
|
||||
/* OpenAI's deprecated functions API: the request sent `functions`, so the reply carries its
|
||||
* call as `function_call` (one at most) and ends in finish_reason "function_call". */
|
||||
bool legacy_functions = false;
|
||||
/* FOR THE REQUEST LOG, counted while the parse walks the body anyway: the messages and tools
|
||||
* a chat request carried, and the last user message's opening (one line, bounded) that the
|
||||
* debug level prints so a log line can be matched to what was typed. Completion requests
|
||||
@@ -126,6 +162,7 @@ struct OaiRequest {
|
||||
/* What the server needs to know about itself to validate a request. */
|
||||
struct OaiLimits {
|
||||
std::string model_id = "radiance";
|
||||
std::string version; /* the build, for `system_fingerprint` */
|
||||
int64_t max_ctx = 0; /* 0 = unknown, no length check */
|
||||
/* What a request that names no max_tokens may generate. 0 is "whatever the context leaves",
|
||||
* resolved against the prompt in clamp_max_tokens, which needs max_ctx to resolve against.
|
||||
@@ -250,23 +287,45 @@ struct OaiDeps {
|
||||
/* Parse. `body` is the raw request body; a malformed body is a 400 that says where. */
|
||||
int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
||||
OaiRequest* out, ApiError* err);
|
||||
/* `native` is llama-server's /completion: its `return_tokens`, and a prompt array of strings and
|
||||
* token ids mixed as ONE prompt, as llama-server reads it. */
|
||||
int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
||||
OaiRequest* out, ApiError* err);
|
||||
OaiRequest* out, ApiError* err, bool native = false);
|
||||
/* Embeddings: fills `out->prompts` with one entry per input. */
|
||||
int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
||||
OaiRequest* out, ApiError* err);
|
||||
|
||||
/* ================================================================== responses */
|
||||
|
||||
struct LogprobEntry {
|
||||
/* One emitted token's logprobs as the wire carries them. `bytes` is the token's own bytes and
|
||||
* `text` is their longest well-formed UTF-8 prefix -- a byte-level token can hold half a
|
||||
* character, and a JSON string cannot -- llama-server's spelling. `end` is where the token's
|
||||
* decoded text ends in the choice's text, which is what decides whether it went out before a stop
|
||||
* string cut the reply. */
|
||||
struct LogprobAlt {
|
||||
int32_t token = 0;
|
||||
std::string text;
|
||||
std::string text, bytes;
|
||||
float logprob = 0.0f;
|
||||
};
|
||||
struct LogprobEntry {
|
||||
int32_t token = 0;
|
||||
std::string text, bytes;
|
||||
float logprob = 0.0f;
|
||||
std::vector<LogprobAlt> top;
|
||||
size_t end = 0;
|
||||
};
|
||||
|
||||
/* The entries as a JSON array's elements, comma-joined, in OpenAI's chat shape with llama-server's
|
||||
* `id` beside each token -- which is also llama-server's native `completion_probabilities`. */
|
||||
std::string logprobs_content(const LogprobEntry* e, size_t n);
|
||||
/* OpenAI's legacy /v1/completions `logprobs` object for the entries, `offset` the text offset of
|
||||
* the first, with llama-server's `content` array beside the legacy arrays. */
|
||||
std::string logprobs_legacy(const LogprobEntry* e, size_t n, size_t offset);
|
||||
|
||||
struct ChoiceOut {
|
||||
int index = 0;
|
||||
std::string text; /* raw generated text */
|
||||
std::string stop_word; /* the stop string that cut it, "" when none or unknown */
|
||||
ParsedMessage msg; /* chat: content / reasoning / tool_calls after parsing */
|
||||
Finish finish = Finish::None;
|
||||
std::vector<LogprobEntry> logprobs;
|
||||
@@ -332,9 +391,9 @@ struct ModelCard {
|
||||
/* What the server loaded (ServerOptions::model_path), vLLM's `root`. Empty leaves it out. */
|
||||
std::string root;
|
||||
/* What the model can be asked for -- tools, reasoning, images -- as /server_info reports it.
|
||||
* There is no field for it in OpenAI's model object, so a client today learns it by sending a
|
||||
* request and reading the refusal; the entry it already fetches can say so up front. A JSON
|
||||
* object as text, spliced in as it is; empty leaves it out. */
|
||||
* There is no field for it in OpenAI's model object, so without this a client learns it by
|
||||
* sending a request and reading the refusal; the entry it already fetches can say so up
|
||||
* front. A JSON object as text, spliced in as it is; empty leaves it out. */
|
||||
std::string capabilities;
|
||||
};
|
||||
/* The list, for GET /v1/models. */
|
||||
@@ -366,42 +425,54 @@ bool calls_complete(const ParsedMessage& m);
|
||||
* what it has delivered, so nothing here diffs, holds back or reconciles: a delta is the next
|
||||
* piece of the answer, and the chunks a client concatenates are the answer the buffered path
|
||||
* returns.
|
||||
*
|
||||
* THE WIRE SHAPE IS THE SUBCLASS'S. Reading the reply -- the reader, the message it adds up to,
|
||||
* the finish it implies -- is the same for every API this server speaks, so it lives here once;
|
||||
* what one increment looks like on the wire is OpenAI's chunk (ChatDeltaStream) or Anthropic's
|
||||
* event (AnthropicStream).
|
||||
*/
|
||||
class ChatDeltaStream {
|
||||
class ReplyStream {
|
||||
public:
|
||||
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
ReplyStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
virtual ~ReplyStream() = default;
|
||||
|
||||
/* The `role: assistant` opener OpenAI clients expect before any content. */
|
||||
std::string first_chunk();
|
||||
/* What opens the stream: OpenAI's `role: assistant` chunk, Anthropic's message_start. */
|
||||
virtual std::string first_chunk() = 0;
|
||||
|
||||
/* Feed the text generated since the last push; returns zero or more SSE `data:` lines.
|
||||
/* Feed the text generated since the last push; returns the bytes for what it completed.
|
||||
* `is_final` says the generation is over, which resolves whatever the reader was holding. */
|
||||
std::string push(std::string_view appended, bool is_final);
|
||||
|
||||
/* The terminating chunk carrying finish_reason, and this choice's `timings` when they are
|
||||
* valid -- on the final chunk whether or not the request asked for a usage chunk, as
|
||||
* llama.cpp sends them. The usage chunk is the stream's, not the choice's: chat_usage_chunk. */
|
||||
std::string final_chunk(Finish f, const TimingsOut& t = TimingsOut());
|
||||
/* What closes the choice: the finish reason, and this choice's `timings` when they are valid
|
||||
* (llama.cpp sends them on the final chunk). `u` is the request's usage, for the shapes that
|
||||
* close a message with it. */
|
||||
virtual std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) = 0;
|
||||
/* What closes a choice the engine failed, in place of final_chunk: the shape's own failure,
|
||||
* so a client reading to the terminal event never takes a truncated reply as complete.
|
||||
* OpenAI's chunks have none, so theirs is the final chunk with finish_reason "error" and the
|
||||
* error object after it. */
|
||||
virtual std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u);
|
||||
|
||||
/* What the whole generation parsed to -- the non-streaming shape. Complete once push has
|
||||
* been called with is_final. */
|
||||
const ParsedMessage& parsed() const { return last_; }
|
||||
Finish adjusted_finish(Finish f) const;
|
||||
|
||||
private:
|
||||
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
|
||||
std::string emit(const std::vector<ReplyDelta>& ev);
|
||||
/* llama.cpp's `timings_per_token`, for the shapes that carry timings. */
|
||||
virtual void set_timings(const TimingsOut&) {}
|
||||
/* Logprobs entries (logprobs_content's elements) for the next chunk this stream writes, for
|
||||
* the shapes that carry them; the others drop them. */
|
||||
virtual void add_logprobs(const std::string&) {}
|
||||
|
||||
/* A delta's chunk is written, not built: the frame around the delta object is the same in
|
||||
* every one, so it is serialised once, and the delta between is written with
|
||||
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
|
||||
void delta_open(std::string& out);
|
||||
void delta_close(std::string& out) const;
|
||||
protected:
|
||||
/* The bytes for the increments one push completed. Each emitter folds every increment into
|
||||
* `last_` through absorb() first. */
|
||||
virtual std::string emit(const std::vector<ReplyDelta>& ev) = 0;
|
||||
bool absorb(const ReplyDelta& d);
|
||||
static void quote(std::string& out, std::string_view s);
|
||||
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
|
||||
|
||||
std::unique_ptr<IReplyReader> reader_;
|
||||
std::string id_, model_;
|
||||
std::string id_, model_, fingerprint_;
|
||||
int64_t created_;
|
||||
int index_;
|
||||
bool finished_ = false;
|
||||
@@ -410,6 +481,116 @@ private:
|
||||
std::vector<ReplyDelta> ev_;
|
||||
};
|
||||
|
||||
/* ANTHROPIC'S MESSAGES API, translated into the chat request it means (`*chat`, a /v1/chat/completions
|
||||
* body) so that every refusal and default is the chat endpoint's. `*label` is the conversation's
|
||||
* label if the request carries one (metadata.user_id). Claude Code's per-request billing stamp in
|
||||
* the system prompt is held constant, as llama-server holds it, or no turn of a conversation could
|
||||
* reuse the one before it. */
|
||||
int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* label, ApiError* err);
|
||||
/* The non-streaming answer, and an error, in Anthropic's shapes. */
|
||||
std::string anthropic_message_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
|
||||
std::string anthropic_error_body(const ApiError& e);
|
||||
/* OPENAI'S RESPONSES API, translated into the chat request it means, as Anthropic's is. `*echo` is
|
||||
* the request's fields the response object repeats back. previous_response_id needs responses
|
||||
* stored server-side and is refused; tool types other than function have no chat equivalent and
|
||||
* are left out, as llama-server leaves them out. */
|
||||
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* echo, ApiError* err);
|
||||
std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
|
||||
|
||||
/* Anthropic's stop_reason for a finish and the stop string that caused it. */
|
||||
const char* anthropic_stop_reason(const OaiRequest& r, Finish f, const std::string& stop_word);
|
||||
|
||||
/* OpenAI's chat.completion.chunk. */
|
||||
class ChatDeltaStream final : public ReplyStream {
|
||||
public:
|
||||
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser)
|
||||
: ReplyStream(r, index, parser), legacy_(r.legacy_functions) {}
|
||||
std::string first_chunk() override;
|
||||
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
|
||||
|
||||
/* llama.cpp's `timings_per_token`: the timings the next pushes' chunks carry, beside
|
||||
* `choices` as the final chunk carries them. Invalid timings carry nothing. */
|
||||
void set_timings(const TimingsOut& t) override;
|
||||
/* OpenAI's `logprobs.content` on the next chunk out: entries wait for one, because a push may
|
||||
* complete no delta (a tool call's opening, a held-back byte) and the tokens still count. */
|
||||
void add_logprobs(const std::string& elems) override;
|
||||
|
||||
private:
|
||||
std::string emit(const std::vector<ReplyDelta>& ev) override;
|
||||
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
|
||||
std::string lp_; /* pending logprobs entries, comma-joined */
|
||||
|
||||
/* A delta's chunk is written, not built: the frame around the delta object is the same in
|
||||
* every one, so it is serialised once, and the delta between is written with
|
||||
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
|
||||
void delta_open(std::string& out);
|
||||
void delta_close(std::string& out);
|
||||
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
|
||||
std::string timings_; /* `"timings":{...}` for every delta chunk, or "" */
|
||||
bool legacy_; /* OaiRequest::legacy_functions */
|
||||
};
|
||||
|
||||
/* ANTHROPIC'S EVENTS: message_start, then a content block a kind -- thinking, text, each tool_use
|
||||
* -- opened, filled by deltas and stopped, then message_delta with the stop reason and the usage,
|
||||
* and message_stop. The prefill a continued conversation ends in is not repeated (`continued`). */
|
||||
class AnthropicStream final : public ReplyStream {
|
||||
public:
|
||||
AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
std::string first_chunk() override;
|
||||
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
|
||||
/* Anthropic's `error` event, which ends the stream with no message_stop. */
|
||||
std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
|
||||
/* The stop string that cut the reply, for stop_reason and stop_sequence. */
|
||||
void set_stop_word(const std::string& w) { stop_word_ = w; }
|
||||
|
||||
private:
|
||||
enum class Block { None, Thinking, Text, Tool };
|
||||
std::string emit(const std::vector<ReplyDelta>& ev) override;
|
||||
void open(std::string& out, Block b, const ToolCall* tc);
|
||||
void close(std::string& out);
|
||||
static void event(std::string& out, const char* type, const json& data);
|
||||
|
||||
const OaiRequest* r_;
|
||||
int64_t n_input_ = 0;
|
||||
std::string skip_; /* the prefill still to be passed over */
|
||||
std::string stop_word_;
|
||||
Block block_ = Block::None;
|
||||
int n_blocks_ = 0; /* blocks opened so far: the next one's index */
|
||||
};
|
||||
|
||||
/* THE RESPONSES API'S EVENTS: response.created and .in_progress; an output item a kind --
|
||||
* reasoning, the message, each function call -- added, its content part added, filled by deltas,
|
||||
* and done; then response.completed (or .incomplete at the token limit) with the whole response.
|
||||
* Every event carries its output_index, content_index and sequence_number, which the OpenAI SDK's
|
||||
* stream accumulator places deltas by. */
|
||||
class ResponsesStream final : public ReplyStream {
|
||||
public:
|
||||
ResponsesStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
std::string first_chunk() override;
|
||||
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
|
||||
/* response.failed, with the items finished so far and the error. */
|
||||
std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
|
||||
|
||||
private:
|
||||
enum class Item { None, Reasoning, Message, Call };
|
||||
std::string emit(const std::vector<ReplyDelta>& ev) override;
|
||||
void open(std::string& out, Item k, size_t call);
|
||||
void close(std::string& out);
|
||||
void event(std::string& out, const char* type, json data);
|
||||
json response(const char* status) const;
|
||||
|
||||
const OaiRequest* r_;
|
||||
Item item_ = Item::None;
|
||||
std::string item_id_, text_; /* the open item's id and its text so far */
|
||||
size_t call_ = 0; /* the open call's index into last_.tool_calls */
|
||||
std::vector<std::string> items_; /* every closed item, serialised, in output order */
|
||||
int64_t seq_ = 0;
|
||||
UsageOut usage_;
|
||||
const char* incomplete_ = nullptr;
|
||||
};
|
||||
|
||||
/* The SSE terminator. Written once at the end of every stream, including a failed one, because a
|
||||
* client blocked on the reader has no other way to learn the stream is over. */
|
||||
extern const char* const SSE_DONE;
|
||||
@@ -431,6 +612,10 @@ bool token_id(const json& v, int32_t* out);
|
||||
* and either comes back holding only what fitted, which the caller refuses. See the definition
|
||||
* for why the tree is bounded rather than the body alone. */
|
||||
json parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep);
|
||||
/* The body of a generation endpoint: parse_json_bounded, and a 400 saying which bound it broke or
|
||||
* that it is not one JSON object. */
|
||||
int parse_request_object(const std::string& body, const OaiLimits& lim, json* b,
|
||||
ApiError* err);
|
||||
int64_t json_value_budget(int64_t max_ctx);
|
||||
constexpr int kJsonMaxDepth = 1024;
|
||||
|
||||
|
||||
+612
-32
@@ -3,6 +3,7 @@
|
||||
#include <cstdio>
|
||||
#include "json_partial.h"
|
||||
#include "rad_internal.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -19,12 +20,13 @@ namespace server {
|
||||
struct Server::Generation {
|
||||
std::shared_ptr<Sink> sink;
|
||||
std::unique_ptr<IDetokenizer> detok;
|
||||
std::unique_ptr<ChatDeltaStream> delta; /* chat streaming only */
|
||||
std::unique_ptr<ReplyStream> delta; /* chat streaming only, in the request's API shape */
|
||||
uint64_t id = 0;
|
||||
int index = 0;
|
||||
int prompt_index = 0;
|
||||
std::string text;
|
||||
std::vector<LogprobEntry> logprobs;
|
||||
size_t lp_sent = 0; /* streaming: how many of `logprobs` a chunk already carried */
|
||||
/* The reply against its reasoning block, every token the sink delivers: what
|
||||
* completion_tokens_details.reasoning_tokens reports. */
|
||||
ReasoningCount think;
|
||||
@@ -36,7 +38,11 @@ struct Server::Generation {
|
||||
size_t stops_floor = std::string::npos;
|
||||
size_t closer_scanned = 0;
|
||||
size_t stop_cut = std::string::npos;
|
||||
std::string stop_word; /* the stop string at stop_cut, "" when the decoder cut it */
|
||||
size_t emitted = 0; /* streaming: text already handed to the delta stream */
|
||||
std::vector<int32_t> tokens; /* llama-server's native shape: the ids generated */
|
||||
size_t tokens_sent = 0; /* ...and how many of them a stream chunk carried */
|
||||
int32_t progress_sent = -1; /* streaming: the prompt_progress last sent, -1 for none */
|
||||
bool retired = false; /* reap() has been said for this id, at most once */
|
||||
};
|
||||
|
||||
@@ -55,6 +61,7 @@ Server::Server(const Deps& d, const ServerOptions& o)
|
||||
: deps_(d), opt_(o),
|
||||
metrics_(o.model_id, o.max_ctx > 0 ? o.max_ctx : 32768) {
|
||||
lim_.model_id = opt_.model_id;
|
||||
lim_.version = opt_.version;
|
||||
lim_.max_ctx = opt_.max_ctx;
|
||||
lim_.default_max_tokens = opt_.default_max_tokens;
|
||||
lim_.max_tokens_cap = opt_.max_tokens_cap;
|
||||
@@ -131,9 +138,37 @@ void Server::register_routes() {
|
||||
router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
|
||||
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
|
||||
router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); });
|
||||
/* THE SAME ROUTES WITHOUT /v1, as llama-server answers them: a client configured with the
|
||||
* bare host as its base URL appends the path alone. */
|
||||
router_.post("/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
|
||||
/* llama-server's native completion, under both of its names: /completions without /v1 is
|
||||
* the native endpoint there, not OpenAI's. */
|
||||
router_.post("/completion", [this](const HttpRequest& q) { return handle_native_completion(q); });
|
||||
router_.post("/completions", [this](const HttpRequest& q) { return handle_native_completion(q); });
|
||||
router_.post("/infill", [this](const HttpRequest& q) { return handle_infill(q); });
|
||||
router_.post("/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
|
||||
router_.get ("/models", [this](const HttpRequest& q) { return handle_models(q); });
|
||||
/* llama-server's: the prompt a chat request renders to, and how many tokens it is. */
|
||||
router_.post("/apply-template", [this](const HttpRequest& q) { return handle_apply_template(q); });
|
||||
router_.post("/v1/chat/completions/input_tokens",
|
||||
[this](const HttpRequest& q) { return handle_input_tokens(q); });
|
||||
router_.post("/chat/completions/input_tokens",
|
||||
[this](const HttpRequest& q) { return handle_input_tokens(q); });
|
||||
/* Anthropic's Messages API, translated onto the chat path (anthropic_to_chat). */
|
||||
router_.post("/v1/messages", [this](const HttpRequest& q) { return handle_messages(q); });
|
||||
router_.post("/v1/messages/count_tokens",
|
||||
[this](const HttpRequest& q) { return handle_count_tokens(q); });
|
||||
/* OpenAI's Responses API, translated the same way (responses_to_chat). */
|
||||
router_.post("/v1/responses", [this](const HttpRequest& q) { return handle_responses(q); });
|
||||
router_.post("/responses", [this](const HttpRequest& q) { return handle_responses(q); });
|
||||
router_.post("/v1/responses/input_tokens",
|
||||
[this](const HttpRequest& q) { return handle_responses_tokens(q); });
|
||||
router_.post("/responses/input_tokens",
|
||||
[this](const HttpRequest& q) { return handle_responses_tokens(q); });
|
||||
|
||||
router_.get ("/metrics", [this](const HttpRequest& q) { return handle_metrics(q); });
|
||||
router_.get ("/health", [this](const HttpRequest& q) { return handle_health(q); });
|
||||
router_.get ("/v1/health", [this](const HttpRequest& q) { return handle_health(q); });
|
||||
router_.get ("/ping", [this](const HttpRequest& q) { return handle_ping(q); });
|
||||
router_.post("/ping", [this](const HttpRequest& q) { return handle_ping(q); });
|
||||
router_.get ("/load", [this](const HttpRequest& q) { return handle_load(q); });
|
||||
@@ -309,7 +344,7 @@ static std::string from_peer(const std::string& peer) {
|
||||
return peer.empty() ? std::string() : " from " + peer;
|
||||
}
|
||||
|
||||
HttpResponse Server::error_response(const ApiError& e, const std::string& peer) {
|
||||
HttpResponse Server::error_response(const ApiError& e, const std::string& peer, ApiShape shape) {
|
||||
metrics_.observe_http(e.status);
|
||||
/* A refusal is the line the operator is looking for when a client says "rejected": the
|
||||
* status, the type, the message, and who asked. 4xx is the client's doing and said at info;
|
||||
@@ -320,7 +355,8 @@ HttpResponse Server::error_response(const ApiError& e, const std::string& peer)
|
||||
else
|
||||
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
|
||||
e.message.c_str());
|
||||
HttpResponse r = HttpResponse::json_body(e.status, e.dump());
|
||||
HttpResponse r = HttpResponse::json_body(
|
||||
e.status, shape == ApiShape::Anthropic ? anthropic_error_body(e) : e.dump());
|
||||
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
|
||||
return r;
|
||||
}
|
||||
@@ -376,7 +412,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
g.index = idx;
|
||||
g.prompt_index = (int)p;
|
||||
g.sink = std::make_shared<Sink>();
|
||||
g.sink->set_has_logprobs(opt_.supports_logprobs);
|
||||
if (r.want_logprobs) g.sink->enable_logprobs(r.n_logprobs);
|
||||
g.think.start(r.sp.reasoning);
|
||||
g.detok = deps_.tok->detokenizer(r.stop, r.preserved_tokens);
|
||||
if (!g.detok) {
|
||||
@@ -399,6 +435,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
rq.priority = r.priority;
|
||||
rq.stream = r.stream;
|
||||
rq.media = r.prompts[p].media;
|
||||
rq.session_label = r.session_label;
|
||||
rq.sink = g.sink.get();
|
||||
rqs.push_back(std::move(rq));
|
||||
gens->push_back(std::move(g));
|
||||
@@ -447,9 +484,32 @@ bool Server::all_done(const std::vector<Generation>& gens) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A token's logprobs entry text: the bytes it adds to the reply, and the readable prefix of them. */
|
||||
static void lp_text(const ITokenizer& tok, int32_t id, std::string* text, std::string* bytes) {
|
||||
*bytes = tok.reply_bytes(id);
|
||||
*text = bytes->substr(0, utf8_valid_prefix(*bytes));
|
||||
}
|
||||
|
||||
/* How many of the entries from `from` went out with the reply: under a stop string, every one
|
||||
* whose text BEGAN before the cut -- one that straddles it contributed text the client got, and
|
||||
* the stop string's own tokens did not -- and otherwise all of them. */
|
||||
static size_t lp_before_cut(const std::vector<LogprobEntry>& lp, size_t from, size_t cut) {
|
||||
if (cut == std::string::npos) return lp.size() - from;
|
||||
size_t start = from ? lp[from - 1].end : 0, n = 0;
|
||||
for (size_t k = from; k < lp.size() && start < cut; ++k, ++n) start = lp[k].end;
|
||||
return n;
|
||||
}
|
||||
|
||||
static std::vector<LogprobEntry> kept_logprobs(const std::vector<LogprobEntry>& lp, size_t cut) {
|
||||
return std::vector<LogprobEntry>(lp.begin(), lp.begin() + (long)lp_before_cut(lp, 0, cut));
|
||||
}
|
||||
|
||||
bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
bool progress = false;
|
||||
SinkToken buf[128];
|
||||
/* Each read's alternatives; only a request that asked for them sizes this. */
|
||||
thread_local std::vector<SinkAlt> alts;
|
||||
if (r.want_logprobs) alts.resize(128 * (size_t)std::max(1, r.n_logprobs));
|
||||
|
||||
size_t maxstop = 0;
|
||||
for (const auto& s : r.stop) maxstop = std::max(maxstop, s.size());
|
||||
@@ -458,14 +518,28 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
if (g.closed) continue;
|
||||
|
||||
size_t n;
|
||||
while ((n = g.sink->read(buf, 128)) > 0) {
|
||||
while ((n = g.sink->read(buf, 128, r.want_logprobs ? alts.data() : nullptr)) > 0) {
|
||||
progress = true;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
g.think.push(r.sp.reasoning, buf[i].token);
|
||||
if (r.shape == ApiShape::LlamaNative) g.tokens.push_back(buf[i].token);
|
||||
std::string piece = g.detok->push(buf[i].token);
|
||||
if (!piece.empty()) g.text += piece;
|
||||
if (r.want_logprobs)
|
||||
g.logprobs.push_back(LogprobEntry{buf[i].token, piece, buf[i].logprob});
|
||||
if (!r.want_logprobs) continue;
|
||||
LogprobEntry e;
|
||||
e.token = buf[i].token;
|
||||
e.logprob = buf[i].logprob;
|
||||
e.end = g.text.size();
|
||||
lp_text(*deps_.tok, e.token, &e.text, &e.bytes);
|
||||
const SinkAlt* a = alts.data() + i * (size_t)g.sink->alt_width();
|
||||
for (int32_t j = 0; j < buf[i].n_alt; ++j) {
|
||||
LogprobAlt t;
|
||||
t.token = a[j].id;
|
||||
t.logprob = a[j].logprob;
|
||||
lp_text(*deps_.tok, t.token, &t.text, &t.bytes);
|
||||
e.top.push_back(std::move(t));
|
||||
}
|
||||
g.logprobs.push_back(std::move(e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,6 +547,7 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
* can never find it -- it is searching text the stop string was already removed from. */
|
||||
if (maxstop && !g.closed && g.stop_cut == std::string::npos && g.detok->stopped()) {
|
||||
g.stop_cut = g.text.size();
|
||||
g.stop_word = g.detok->stop_hit();
|
||||
g.finish = Finish::StopString;
|
||||
g.closed = true;
|
||||
progress = true;
|
||||
@@ -506,8 +581,10 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
for (const auto& s : r.stop) {
|
||||
if (s.empty()) continue;
|
||||
size_t at = g.text.find(s, start);
|
||||
if (at != std::string::npos && (g.stop_cut == std::string::npos || at < g.stop_cut))
|
||||
if (at != std::string::npos && (g.stop_cut == std::string::npos || at < g.stop_cut)) {
|
||||
g.stop_cut = at;
|
||||
g.stop_word = s;
|
||||
}
|
||||
}
|
||||
g.scanned = g.text.size();
|
||||
if (g.stop_cut != std::string::npos) {
|
||||
@@ -665,7 +742,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
if (submit_all(r, &gens, &err) < 0) {
|
||||
retire(gens);
|
||||
release(r.n_choices());
|
||||
return error_response(err, req.peer);
|
||||
return error_response(err, req.peer, r.shape);
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
@@ -686,7 +763,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
cancel_all(gens, false);
|
||||
retire(gens);
|
||||
release(r.n_choices());
|
||||
return error_response(err_overloaded("the server is shutting down"), req.peer);
|
||||
return error_response(err_overloaded("the server is shutting down"), req.peer, r.shape);
|
||||
}
|
||||
/* Wait on whichever choice is still running. Bounded, so the peer check above runs. */
|
||||
for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; }
|
||||
@@ -702,7 +779,8 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
ChoiceOut c;
|
||||
c.index = g.index;
|
||||
c.finish = g.finish;
|
||||
c.logprobs = std::move(g.logprobs);
|
||||
c.stop_word = g.stop_word;
|
||||
if (r.want_logprobs) c.logprobs = kept_logprobs(g.logprobs, g.stop_cut);
|
||||
|
||||
if (r.endpoint == Endpoint::Chat) {
|
||||
/* Parse whenever there is a parser, not only when tools were sent: the same parser
|
||||
@@ -757,7 +835,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
e.status = 500;
|
||||
e.type = "internal_server_error";
|
||||
e.message = why;
|
||||
return error_response(e, req.peer);
|
||||
return error_response(e, req.peer, r.shape);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -766,32 +844,172 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
release(r.n_choices());
|
||||
|
||||
const TimingsOut timings = timings_of(gens);
|
||||
std::string body = r.endpoint == Endpoint::Chat
|
||||
if (r.shape == ApiShape::LlamaNative) {
|
||||
/* llama-server answers one result, and an array of them for several prompts. */
|
||||
json res = json::array();
|
||||
for (const auto& g : gens) res.push_back(native_result(r, g, g.text));
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(res.size() == 1 ? res[0] : res));
|
||||
}
|
||||
std::string body = r.shape == ApiShape::Anthropic
|
||||
? anthropic_message_body(r, choices.front(), usage)
|
||||
: r.shape == ApiShape::Responses
|
||||
? responses_body(r, choices.front(), usage)
|
||||
: r.endpoint == Endpoint::Chat
|
||||
? chat_completion_body(r, choices, usage, timings)
|
||||
: text_completion_body(r, choices, usage, timings);
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, std::move(body));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ llama-server's native shape */
|
||||
|
||||
/* What a request was served with, under llama-server's names: its `generation_settings`. */
|
||||
static nlohmann::ordered_json native_settings(const OaiRequest& r) {
|
||||
const SamplingParams& sp = r.sp;
|
||||
nlohmann::ordered_json p;
|
||||
p["seed"] = sp.seed;
|
||||
p["temperature"] = sp.temp;
|
||||
p["top_k"] = sp.top_k;
|
||||
p["top_p"] = sp.top_p;
|
||||
p["min_p"] = sp.min_p;
|
||||
p["typical_p"] = sp.typical_p;
|
||||
p["xtc_probability"] = sp.xtc_probability;
|
||||
p["xtc_threshold"] = sp.xtc_threshold;
|
||||
p["repeat_last_n"] = sp.penalty_last_n;
|
||||
p["repeat_penalty"] = sp.rep_penalty;
|
||||
p["presence_penalty"] = sp.pres_penalty;
|
||||
p["frequency_penalty"] = sp.freq_penalty;
|
||||
p["dry_multiplier"] = sp.dry_multiplier;
|
||||
p["dry_base"] = sp.dry_base;
|
||||
p["dry_allowed_length"] = sp.dry_allowed_length;
|
||||
p["dry_penalty_last_n"] = sp.dry_penalty_last_n;
|
||||
p["dry_sequence_breakers"] = sp.dry_seq_breakers;
|
||||
p["mirostat"] = 0;
|
||||
p["stop"] = std::vector<std::string>(r.stop.begin(),
|
||||
r.stop.begin() + (long)std::min(r.n_client_stops, r.stop.size()));
|
||||
p["max_tokens"] = r.max_tokens;
|
||||
p["n_predict"] = r.max_tokens;
|
||||
p["ignore_eos"] = r.ignore_eos;
|
||||
p["stream"] = r.stream;
|
||||
p["grammar"] = sp.grammar;
|
||||
p["n_probs"] = r.want_logprobs ? r.n_logprobs : 0;
|
||||
p["post_sampling_probs"] = false;
|
||||
p["samplers"] = sp.temp_last
|
||||
? std::vector<std::string>{ "penalties", "dry", "top_k", "top_p", "min_p", "typ_p", "xtc", "temperature" }
|
||||
: std::vector<std::string>{ "penalties", "dry", "temperature", "top_k", "top_p", "min_p", "typ_p", "xtc" };
|
||||
return p;
|
||||
}
|
||||
|
||||
static const char* native_stop_type(Finish f) {
|
||||
switch (f) {
|
||||
case Finish::Stop: return "eos";
|
||||
case Finish::Length: return "limit";
|
||||
case Finish::StopString: return "word";
|
||||
default: return "none";
|
||||
}
|
||||
}
|
||||
|
||||
/* llama-server's final result for one choice: the text, how it ended, the prompt it ran on and
|
||||
* where the time went. A stream's last chunk is this with `content` empty -- the text went out
|
||||
* in the chunks before it. */
|
||||
json Server::native_result(const OaiRequest& r, const Generation& g, const std::string& content) {
|
||||
const Sink* one = g.sink.get();
|
||||
const TimingsOut t = timings_of(&one, 1);
|
||||
const int64_t n_prompt = (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size();
|
||||
nlohmann::ordered_json o;
|
||||
o["index"] = g.index;
|
||||
o["content"] = content;
|
||||
o["tokens"] = r.return_tokens ? g.tokens : std::vector<int32_t>{};
|
||||
o["id_slot"] = 0;
|
||||
o["stop"] = true;
|
||||
o["model"] = r.model;
|
||||
o["tokens_predicted"] = g.sink->n_produced();
|
||||
o["tokens_evaluated"] = n_prompt;
|
||||
o["generation_settings"] = native_settings(r);
|
||||
o["prompt"] = r.prompts[(size_t)g.prompt_index].text;
|
||||
o["has_new_line"] = g.text.find('\n') != std::string::npos;
|
||||
o["truncated"] = false;
|
||||
o["stop_type"] = native_stop_type(g.finish);
|
||||
o["stopping_word"] = g.stop_word;
|
||||
o["tokens_cached"] = n_prompt + g.sink->n_produced();
|
||||
if (t.valid) o["timings"] = timings_json(t);
|
||||
/* The whole reply's probabilities on the answer, as llama-server sends them: a stream
|
||||
* carried them chunk by chunk instead. */
|
||||
if (r.want_logprobs && !r.stream) {
|
||||
const std::vector<LogprobEntry> kept = kept_logprobs(g.logprobs, g.stop_cut);
|
||||
o["completion_probabilities"] =
|
||||
nlohmann::ordered_json::parse("[" + logprobs_content(kept.data(), kept.size()) + "]");
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ streaming */
|
||||
|
||||
static std::string text_chunk(const OaiRequest& r, int index, const std::string& delta,
|
||||
const char* finish_reason, const TimingsOut* t = nullptr) {
|
||||
const char* finish_reason, const TimingsOut* t = nullptr,
|
||||
const std::string& logprobs = std::string()) {
|
||||
nlohmann::ordered_json ch;
|
||||
ch["text"] = delta;
|
||||
ch["index"] = index;
|
||||
ch["logprobs"] = nullptr;
|
||||
if (!logprobs.empty()) ch["logprobs"] = nlohmann::ordered_json::parse(logprobs);
|
||||
else ch["logprobs"] = nullptr;
|
||||
if (finish_reason) ch["finish_reason"] = finish_reason; else ch["finish_reason"] = nullptr;
|
||||
nlohmann::ordered_json o;
|
||||
o["id"] = r.id;
|
||||
o["object"] = "text_completion";
|
||||
o["created"] = r.created;
|
||||
o["model"] = r.model;
|
||||
if (!r.system_fingerprint.empty()) o["system_fingerprint"] = r.system_fingerprint;
|
||||
o["choices"] = nlohmann::ordered_json::array({ch});
|
||||
if (t && t->valid) o["timings"] = timings_json(*t);
|
||||
return sse_event(o.dump());
|
||||
}
|
||||
|
||||
/* llama-server's `prompt_progress` chunk: the endpoint's opening chunk -- an assistant role with
|
||||
* no content, or an empty text -- carrying how much of the prompt is in the cache, of how much,
|
||||
* how much of that the prefix cache supplied, and the time since the prompt phase began. */
|
||||
static std::string progress_chunk(const OaiRequest& r, int index, const Sink& s) {
|
||||
nlohmann::ordered_json ch;
|
||||
if (r.shape == ApiShape::LlamaNative) {
|
||||
/* llama-server's native chunk carries the progress at its top level. */
|
||||
const int64_t ta = s.t_admitted_ns();
|
||||
nlohmann::ordered_json o;
|
||||
o["index"] = index;
|
||||
o["content"] = "";
|
||||
o["tokens"] = nlohmann::ordered_json::array();
|
||||
o["stop"] = false;
|
||||
o["prompt_progress"] = { { "total", s.progress_total() }, { "cache", s.progress_cached() },
|
||||
{ "processed", s.progress_processed() },
|
||||
{ "time_ms", ta >= 0 ? (s.age_ns() - ta) / 1000000 : 0 } };
|
||||
return sse_event(o.dump());
|
||||
}
|
||||
if (r.endpoint == Endpoint::Chat) {
|
||||
ch["index"] = index;
|
||||
ch["delta"] = { { "role", "assistant" }, { "content", nullptr } };
|
||||
} else {
|
||||
ch["text"] = "";
|
||||
ch["index"] = index;
|
||||
ch["logprobs"] = nullptr;
|
||||
}
|
||||
ch["finish_reason"] = nullptr;
|
||||
const int64_t ta = s.t_admitted_ns();
|
||||
nlohmann::ordered_json pp;
|
||||
pp["total"] = s.progress_total();
|
||||
pp["cache"] = s.progress_cached();
|
||||
pp["processed"] = s.progress_processed();
|
||||
pp["time_ms"] = ta >= 0 ? (s.age_ns() - ta) / 1000000 : 0;
|
||||
nlohmann::ordered_json o;
|
||||
o["id"] = r.id;
|
||||
o["object"] = r.endpoint == Endpoint::Chat ? "chat.completion.chunk" : "text_completion";
|
||||
o["created"] = r.created;
|
||||
o["model"] = r.model;
|
||||
if (!r.system_fingerprint.empty()) o["system_fingerprint"] = r.system_fingerprint;
|
||||
o["choices"] = nlohmann::ordered_json::array({ch});
|
||||
o["prompt_progress"] = std::move(pp);
|
||||
return sse_event(o.dump());
|
||||
}
|
||||
|
||||
HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) {
|
||||
auto st = std::make_shared<StreamState>();
|
||||
st->r = r;
|
||||
@@ -801,11 +1019,16 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
if (submit_all(st->r, &st->gens, &err) < 0) {
|
||||
retire(st->gens);
|
||||
release(r.n_choices());
|
||||
return error_response(err, req.peer);
|
||||
return error_response(err, req.peer, r.shape);
|
||||
}
|
||||
if (st->r.endpoint == Endpoint::Chat)
|
||||
for (auto& g : st->gens)
|
||||
g.delta.reset(new ChatDeltaStream(st->r, g.index, st->r.reply_parser.get()));
|
||||
g.delta.reset(
|
||||
st->r.shape == ApiShape::Anthropic
|
||||
? (ReplyStream*)new AnthropicStream(st->r, g.index, st->r.reply_parser.get())
|
||||
: st->r.shape == ApiShape::Responses
|
||||
? (ReplyStream*)new ResponsesStream(st->r, g.index, st->r.reply_parser.get())
|
||||
: (ReplyStream*)new ChatDeltaStream(st->r, g.index, st->r.reply_parser.get()));
|
||||
|
||||
HttpResponse res;
|
||||
res.status = 200;
|
||||
@@ -852,6 +1075,15 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
for (const auto& s : st->r.stop) maxstop = std::max(maxstop, s.size());
|
||||
|
||||
for (auto& g : st->gens) {
|
||||
/* The prompt's progress first, so a client sees it before the first token: every
|
||||
* advance the scheduler reported, as llama-server sends one a prefill batch. */
|
||||
if (st->r.return_progress) {
|
||||
const int32_t done = g.sink->progress_processed();
|
||||
if (done > g.progress_sent) {
|
||||
out += progress_chunk(st->r, g.index, *g.sink);
|
||||
g.progress_sent = done;
|
||||
}
|
||||
}
|
||||
/* Hold back the longest stop string minus one byte while the choice is still running:
|
||||
* otherwise the first half of a stop sequence is already on the wire by the time we
|
||||
* recognise it, and it cannot be taken back.
|
||||
@@ -867,16 +1099,67 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
if (safe <= g.emitted) continue;
|
||||
}
|
||||
|
||||
/* THE LOGPROBS OF THE TOKENS WHOSE TEXT THIS CHUNK CARRIES: every entry ending inside
|
||||
* it while the choice runs, and once it is closed the rest of what went out with the
|
||||
* reply (lp_before_cut). */
|
||||
size_t lp_n = 0, lp_off = 0;
|
||||
if (st->r.want_logprobs) {
|
||||
lp_off = g.lp_sent ? g.logprobs[g.lp_sent - 1].end : 0;
|
||||
if (g.closed)
|
||||
lp_n = lp_before_cut(g.logprobs, g.lp_sent, g.stop_cut);
|
||||
else
|
||||
while (g.lp_sent + lp_n < g.logprobs.size() &&
|
||||
g.logprobs[g.lp_sent + lp_n].end <= safe) ++lp_n;
|
||||
}
|
||||
const LogprobEntry* lp_at = lp_n ? &g.logprobs[g.lp_sent] : nullptr;
|
||||
g.lp_sent += lp_n;
|
||||
|
||||
/* llama.cpp's `timings_per_token`: this choice's timings so far on every chunk. */
|
||||
TimingsOut now;
|
||||
if (st->r.timings_per_token) {
|
||||
const Sink* one = g.sink.get();
|
||||
now = timings_of(&one, 1);
|
||||
if (g.delta) g.delta->set_timings(now);
|
||||
}
|
||||
if (st->r.endpoint == Endpoint::Chat) {
|
||||
/* Only what is new: the reader keeps its own place in the reply, which is what
|
||||
* makes a long reply cost its length rather than its length squared. */
|
||||
if (lp_n) g.delta->add_logprobs(logprobs_content(lp_at, lp_n));
|
||||
out += g.delta->push(std::string_view(g.text).substr(g.emitted, safe - g.emitted),
|
||||
g.closed);
|
||||
} else if (safe > g.emitted) {
|
||||
} else if (st->r.shape == ApiShape::LlamaNative) {
|
||||
/* llama-server's native chunk: the new text, the ids that made it, the counts. */
|
||||
if (safe > g.emitted || g.tokens.size() > g.tokens_sent || lp_n) {
|
||||
nlohmann::ordered_json o;
|
||||
o["index"] = g.index;
|
||||
o["content"] = g.text.substr(g.emitted, safe - g.emitted);
|
||||
o["tokens"] = std::vector<int32_t>(g.tokens.begin() + (long)g.tokens_sent,
|
||||
g.tokens.end());
|
||||
o["stop"] = false;
|
||||
o["id_slot"] = -1;
|
||||
o["tokens_predicted"] = g.sink->n_produced();
|
||||
o["tokens_evaluated"] =
|
||||
(int64_t)st->r.prompts[(size_t)g.prompt_index].tokens.size();
|
||||
if (st->r.timings_per_token && now.valid) o["timings"] = timings_json(now);
|
||||
if (lp_n)
|
||||
o["completion_probabilities"] = nlohmann::ordered_json::parse(
|
||||
"[" + logprobs_content(lp_at, lp_n) + "]");
|
||||
out += sse_event(o.dump());
|
||||
g.tokens_sent = g.tokens.size();
|
||||
}
|
||||
} else if (safe > g.emitted || lp_n) {
|
||||
out += text_chunk(st->r, g.index, g.text.substr(g.emitted, safe - g.emitted),
|
||||
nullptr);
|
||||
nullptr, st->r.timings_per_token ? &now : nullptr,
|
||||
lp_n ? logprobs_legacy(lp_at, lp_n, lp_off) : std::string());
|
||||
}
|
||||
g.emitted = safe;
|
||||
/* A sent entry is read again only as the one before the next, for where that one
|
||||
* starts; keeping the rest would hold ~1.7 KB a token at 20 alternatives for the
|
||||
* whole of a long stream. */
|
||||
if (g.lp_sent > 1) {
|
||||
g.logprobs.erase(g.logprobs.begin(), g.logprobs.begin() + (long)(g.lp_sent - 1));
|
||||
g.lp_sent = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (self->all_done(st->gens)) {
|
||||
@@ -887,24 +1170,34 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
* usage chunk still has them, as llama.cpp sends them. */
|
||||
const Sink* one = g.sink.get();
|
||||
const TimingsOut gt = timings_of(&one, 1);
|
||||
if (st->r.endpoint == Endpoint::Chat) {
|
||||
out += g.delta->final_chunk(g.finish, gt);
|
||||
Finish adj = g.delta->adjusted_finish(g.finish);
|
||||
if (adj == Finish::Error || adj == Finish::Cancelled) overall = adj;
|
||||
else if (adj == Finish::ToolCalls) overall = adj;
|
||||
} else {
|
||||
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish), >);
|
||||
if (g.finish == Finish::Error) overall = Finish::Error;
|
||||
}
|
||||
/* A failed generation cannot become a non-200 -- the headers left long ago -- so
|
||||
* it travels as an error event before [DONE]. Silence would look like a normal
|
||||
* it travels as an error event in the stream. Silence would look like a normal
|
||||
* end of stream and the client would use a truncated answer. */
|
||||
ApiError e;
|
||||
if (g.finish == Finish::Error) {
|
||||
ApiError e;
|
||||
e.status = 500;
|
||||
e.type = "internal_server_error";
|
||||
e.message = engine_failure(*g.sink);
|
||||
out += sse_error(e);
|
||||
overall = Finish::Error;
|
||||
}
|
||||
if (st->r.endpoint == Endpoint::Chat) {
|
||||
if (auto* a = dynamic_cast<AnthropicStream*>(g.delta.get()))
|
||||
a->set_stop_word(g.stop_word);
|
||||
if (g.finish == Finish::Error) {
|
||||
out += g.delta->error_chunk(e, gt, u);
|
||||
} else {
|
||||
out += g.delta->final_chunk(g.finish, gt, u);
|
||||
const Finish adj = g.delta->adjusted_finish(g.finish);
|
||||
if (overall != Finish::Error &&
|
||||
(adj == Finish::Cancelled || adj == Finish::ToolCalls))
|
||||
overall = adj;
|
||||
}
|
||||
} else if (st->r.shape == ApiShape::LlamaNative) {
|
||||
out += sse_event(json_dump(self->native_result(st->r, g, "")));
|
||||
if (g.finish == Finish::Error) out += sse_error(e);
|
||||
} else {
|
||||
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish), >);
|
||||
if (g.finish == Finish::Error) out += sse_error(e);
|
||||
}
|
||||
}
|
||||
/* THE USAGE CHUNK. `stream_options.include_usage` is parsed and validated on both
|
||||
@@ -921,7 +1214,9 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
: text_usage_chunk(st->r, u, t);
|
||||
}
|
||||
|
||||
out += SSE_DONE;
|
||||
/* Anthropic's stream ends with message_stop and the Responses API's with
|
||||
* response.completed, which final_chunk wrote; chat completions' with [DONE]. */
|
||||
if (st->r.shape == ApiShape::OpenAI) out += SSE_DONE;
|
||||
st->done_sent = true;
|
||||
self->record(st->r, st->gens, overall);
|
||||
self->retire(st->gens);
|
||||
@@ -981,6 +1276,291 @@ HttpResponse Server::handle_chat(const HttpRequest& req) {
|
||||
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
|
||||
}
|
||||
|
||||
/* llama-server's /apply-template and its token count. Both parse the request exactly as
|
||||
* /v1/chat/completions does -- the same template defaults, the same refusals -- and stop before
|
||||
* anything is queued, so the prompt they report is the prompt a chat request would run. */
|
||||
HttpResponse Server::handle_apply_template(const HttpRequest& req) {
|
||||
if (!deps_.tok || !deps_.chat)
|
||||
return error_response(err_not_implemented("rendering a chat requires a chat template; "
|
||||
"this model was loaded without one"), req.peer);
|
||||
OaiRequest r;
|
||||
ApiError err;
|
||||
if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
json o;
|
||||
o["prompt"] = r.prompts.empty() ? std::string() : r.prompts[0].text;
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_input_tokens(const HttpRequest& req) {
|
||||
if (!deps_.tok || !deps_.chat)
|
||||
return error_response(err_not_implemented("rendering a chat requires a chat template; "
|
||||
"this model was loaded without one"), req.peer);
|
||||
OaiRequest r;
|
||||
ApiError err;
|
||||
if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
json o;
|
||||
o["object"] = "response.input_tokens";
|
||||
o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
/* ANTHROPIC'S MESSAGES API. The request is translated into the chat request it means and parsed by
|
||||
* the chat endpoint's own parser, so every default, refusal and template rule is that endpoint's;
|
||||
* the answer and the errors go out in Anthropic's shapes. */
|
||||
HttpResponse Server::handle_messages(const HttpRequest& req) {
|
||||
if (!deps_.sched || !deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer,
|
||||
ApiShape::Anthropic);
|
||||
if (opt_.embedding_model)
|
||||
return error_response(err_not_implemented("this is an embedding model: it serves "
|
||||
"/v1/embeddings and generates no text"),
|
||||
req.peer, ApiShape::Anthropic);
|
||||
std::string chat, label;
|
||||
ApiError err;
|
||||
OaiRequest r;
|
||||
if (anthropic_to_chat(req.body, lim_, &chat, &label, &err) < 0 ||
|
||||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer, ApiShape::Anthropic);
|
||||
r.shape = ApiShape::Anthropic;
|
||||
r.id = random_id("msg_");
|
||||
if (r.session_label.empty()) r.session_label = label;
|
||||
return serve_translated(req, r);
|
||||
}
|
||||
|
||||
HttpResponse Server::serve_translated(const HttpRequest& req, OaiRequest& r) {
|
||||
r.peer = req.peer;
|
||||
sweep_abandoned();
|
||||
if (!admit(r.n_choices())) {
|
||||
metrics_.observe_rejected();
|
||||
return error_response(err_overloaded(
|
||||
"the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
|
||||
"s. The server refuses rather than queueing without bound"), req.peer, r.shape);
|
||||
}
|
||||
log_admitted(r);
|
||||
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
|
||||
}
|
||||
|
||||
/* llama-server's NATIVE /completion: the completions parser with llama-server's prompt forms,
|
||||
* answered in its shape (native_result). */
|
||||
HttpResponse Server::handle_native_completion(const HttpRequest& req) {
|
||||
if (!deps_.sched || !deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
|
||||
if (opt_.embedding_model)
|
||||
return error_response(err_not_implemented("this is an embedding model: it serves "
|
||||
"/v1/embeddings and generates no text"),
|
||||
req.peer);
|
||||
OaiRequest r;
|
||||
ApiError err;
|
||||
if (parse_completion_request(req.body, odeps_, lim_, &r, &err, /*native=*/true) < 0)
|
||||
return error_response(err, req.peer);
|
||||
r.shape = ApiShape::LlamaNative;
|
||||
return serve_translated(req, r);
|
||||
}
|
||||
|
||||
/* A control token by the spellings model families give it, or -1: what llama.cpp's vocabulary
|
||||
* loader recognises the fill-in-the-middle tokens by. A spelling counts only when it is ONE token
|
||||
* that renders as itself. */
|
||||
static int32_t special_token(const ITokenizer& tok, std::initializer_list<const char*> names) {
|
||||
for (const char* n : names) {
|
||||
const std::vector<int32_t> t = tok.encode(n, false, /*parse_special=*/true);
|
||||
if (t.size() == 1 && tok.token_bytes(t[0]) == n) return t[0];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* llama-server's /infill: code completion between a prefix and a suffix, as llama.vim and
|
||||
* llama.vscode ask for it, in the repository-level FIM layout (arXiv 2409.12186) llama-server
|
||||
* builds -- the extra files each under its name, then prefix, suffix and middle:
|
||||
*
|
||||
* [REPO]myproject\n [SEP]name\n text ... [SEP]filename\n [PRE]prefix+prompt [SUF]suffix [MID]
|
||||
*
|
||||
* A model with no fill-in-the-middle tokens cannot do it and is refused. The completion itself is
|
||||
* a native one, with every native field. */
|
||||
HttpResponse Server::handle_infill(const HttpRequest& req) {
|
||||
if (!deps_.sched || !deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
|
||||
const ITokenizer& tok = *deps_.tok;
|
||||
const int32_t pre = special_token(tok, { "<|fim_prefix|>", "<fim_prefix>", "<fim-prefix>",
|
||||
"<|fim▁begin|>", "<PRE>", "▁<PRE>", "<|code_prefix|>" });
|
||||
const int32_t suf = special_token(tok, { "<|fim_suffix|>", "<fim_suffix>", "<fim-suffix>",
|
||||
"<|fim▁hole|>", "<SUF>", "▁<SUF>", "<|code_suffix|>" });
|
||||
const int32_t mid = special_token(tok, { "<|fim_middle|>", "<fim_middle>", "<fim-middle>",
|
||||
"<|fim▁end|>", "<MID>", "▁<MID>", "<|code_middle|>" });
|
||||
if (pre < 0 || suf < 0 || mid < 0)
|
||||
return error_response(err_not_implemented("this model has no fill-in-the-middle tokens, "
|
||||
"so /infill cannot be served"), req.peer);
|
||||
const int32_t rep = special_token(tok, { "<|repo_name|>", "<|fim_repo|>", "<fim-repo>",
|
||||
"<reponame>", "<REPO>" });
|
||||
const int32_t sep = special_token(tok, { "<|file_sep|>", "<|fim_sep|>", "<fim-sep>",
|
||||
"<file_sep>", "<filename>" });
|
||||
|
||||
json b;
|
||||
{
|
||||
ApiError e;
|
||||
if (parse_request_object(req.body, lim_, &b, &e) < 0) return error_response(e, req.peer);
|
||||
}
|
||||
auto text_of = [&](const char* k, std::vector<int32_t>* out, ApiError* e) {
|
||||
auto it = b.find(k);
|
||||
if (it == b.end() || it->is_null()) return true;
|
||||
if (it->is_string()) {
|
||||
*out = tok.encode(it->get<std::string>(), false, false);
|
||||
return true;
|
||||
}
|
||||
if (it->is_array()) {
|
||||
for (const json& v : *it) {
|
||||
int32_t id = 0;
|
||||
if (v.is_string()) {
|
||||
const std::vector<int32_t> t = tok.encode(v.get<std::string>(), false, false);
|
||||
out->insert(out->end(), t.begin(), t.end());
|
||||
} else if (v.is_number_integer() && token_id(v, &id)) {
|
||||
out->push_back(id);
|
||||
} else {
|
||||
*e = err_bad(k, "expected a string, or strings and token ids");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
*e = err_bad(k, "expected a string");
|
||||
return false;
|
||||
};
|
||||
ApiError err;
|
||||
std::vector<int32_t> prefix, suffix, prompt;
|
||||
if (!text_of("input_prefix", &prefix, &err) || !text_of("input_suffix", &suffix, &err) ||
|
||||
!text_of("prompt", &prompt, &err))
|
||||
return error_response(err, req.peer);
|
||||
|
||||
std::vector<int32_t> extra;
|
||||
if (rep >= 0) {
|
||||
extra.push_back(rep);
|
||||
const std::vector<int32_t> t = tok.encode("myproject\n", false, false);
|
||||
extra.insert(extra.end(), t.begin(), t.end());
|
||||
}
|
||||
auto ex = b.find("input_extra");
|
||||
if (ex != b.end() && ex->is_array()) {
|
||||
for (const json& c : *ex) {
|
||||
if (!c.is_object()) continue;
|
||||
auto fn = c.find("filename"), tx = c.find("text");
|
||||
if ((fn != c.end() && !fn->is_null() && !fn->is_string()) ||
|
||||
(tx != c.end() && !tx->is_null() && !tx->is_string()))
|
||||
return error_response(err_bad("input_extra[]", "filename and text must be strings"),
|
||||
req.peer);
|
||||
const std::string name = fn != c.end() && fn->is_string() ? fn->get<std::string>() : "tmp";
|
||||
std::vector<int32_t> t;
|
||||
if (sep >= 0) {
|
||||
extra.push_back(sep);
|
||||
t = tok.encode(name + "\n", false, false);
|
||||
} else {
|
||||
t = tok.encode("\n\n--- snippet ---\n\n", false, false);
|
||||
}
|
||||
extra.insert(extra.end(), t.begin(), t.end());
|
||||
t = tok.encode(tx != c.end() && tx->is_string() ? tx->get<std::string>() : std::string(),
|
||||
false, false);
|
||||
extra.insert(extra.end(), t.begin(), t.end());
|
||||
}
|
||||
}
|
||||
if (sep >= 0) {
|
||||
extra.push_back(sep);
|
||||
const std::vector<int32_t> t = tok.encode("filename\n", false, false);
|
||||
extra.insert(extra.end(), t.begin(), t.end());
|
||||
}
|
||||
|
||||
/* THE EXTRA FILES GIVE WAY FIRST, newest kept, when the whole does not fit beside what the
|
||||
* reply may generate: they are context, and the prefix and suffix are the edit. */
|
||||
int64_t reserve = 256;
|
||||
for (const char* k : { "max_tokens", "n_predict" }) {
|
||||
auto it = b.find(k);
|
||||
if (it == b.end() || it->is_null()) continue;
|
||||
if (!it->is_number_integer())
|
||||
return error_response(err_bad(k, "expected an integer"), req.peer);
|
||||
reserve = it->get<int64_t>();
|
||||
}
|
||||
if (reserve <= 0) reserve = 256;
|
||||
const ITokenizer::VocabInfo vi = tok.vocab_info();
|
||||
const int64_t fixed = (int64_t)(prefix.size() + prompt.size() + suffix.size()) + 3 +
|
||||
(vi.add_bos && vi.bos >= 0 ? 1 : 0);
|
||||
if (opt_.max_ctx > 0) {
|
||||
const int64_t room = std::max<int64_t>(opt_.max_ctx - fixed - reserve, 0);
|
||||
if ((int64_t)extra.size() > room) extra.erase(extra.begin(), extra.end() - room);
|
||||
}
|
||||
std::vector<int32_t> ids;
|
||||
if (vi.add_bos && vi.bos >= 0) ids.push_back(vi.bos);
|
||||
ids.insert(ids.end(), extra.begin(), extra.end());
|
||||
ids.push_back(pre);
|
||||
ids.insert(ids.end(), prefix.begin(), prefix.end());
|
||||
ids.insert(ids.end(), prompt.begin(), prompt.end());
|
||||
ids.push_back(suf);
|
||||
ids.insert(ids.end(), suffix.begin(), suffix.end());
|
||||
ids.push_back(mid);
|
||||
|
||||
for (const char* k : { "input_prefix", "input_suffix", "input_extra", "prompt" }) b.erase(k);
|
||||
b["prompt"] = ids;
|
||||
OaiRequest r;
|
||||
if (parse_completion_request(b.dump(), odeps_, lim_, &r, &err, /*native=*/true) < 0)
|
||||
return error_response(err, req.peer);
|
||||
r.shape = ApiShape::LlamaNative;
|
||||
return serve_translated(req, r);
|
||||
}
|
||||
|
||||
/* OPENAI'S RESPONSES API, as the Messages API: translated into the chat request it means, served
|
||||
* by the chat path, answered as a response object or its event stream. */
|
||||
HttpResponse Server::handle_responses(const HttpRequest& req) {
|
||||
if (!deps_.sched || !deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
|
||||
if (opt_.embedding_model)
|
||||
return error_response(err_not_implemented("this is an embedding model: it serves "
|
||||
"/v1/embeddings and generates no text"),
|
||||
req.peer);
|
||||
std::string chat, echo;
|
||||
ApiError err;
|
||||
OaiRequest r;
|
||||
if (responses_to_chat(req.body, lim_, &chat, &echo, &err) < 0 ||
|
||||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
r.shape = ApiShape::Responses;
|
||||
r.id = random_id("resp_");
|
||||
r.echo_json = std::move(echo);
|
||||
return serve_translated(req, r);
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_responses_tokens(const HttpRequest& req) {
|
||||
if (!deps_.tok || !deps_.chat)
|
||||
return error_response(err_not_implemented("rendering a chat requires a chat template; "
|
||||
"this model was loaded without one"), req.peer);
|
||||
std::string chat;
|
||||
ApiError err;
|
||||
OaiRequest r;
|
||||
if (responses_to_chat(req.body, lim_, &chat, nullptr, &err) < 0 ||
|
||||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
json o;
|
||||
o["object"] = "response.input_tokens";
|
||||
o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_count_tokens(const HttpRequest& req) {
|
||||
if (!deps_.tok || !deps_.chat)
|
||||
return error_response(err_not_implemented("rendering a chat requires a chat template; "
|
||||
"this model was loaded without one"), req.peer,
|
||||
ApiShape::Anthropic);
|
||||
std::string chat;
|
||||
ApiError err;
|
||||
OaiRequest r;
|
||||
if (anthropic_to_chat(req.body, lim_, &chat, nullptr, &err) < 0 ||
|
||||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer, ApiShape::Anthropic);
|
||||
json o;
|
||||
o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_completion(const HttpRequest& req) {
|
||||
if (!deps_.sched || !deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
|
||||
|
||||
+14
-1
@@ -196,6 +196,18 @@ private:
|
||||
HttpResponse handle_ping(const HttpRequest& req);
|
||||
HttpResponse handle_version(const HttpRequest& req);
|
||||
HttpResponse handle_props(const HttpRequest& req);
|
||||
HttpResponse handle_apply_template(const HttpRequest& req);
|
||||
HttpResponse handle_input_tokens(const HttpRequest& req);
|
||||
HttpResponse handle_messages(const HttpRequest& req);
|
||||
HttpResponse handle_count_tokens(const HttpRequest& req);
|
||||
HttpResponse handle_responses(const HttpRequest& req);
|
||||
HttpResponse handle_responses_tokens(const HttpRequest& req);
|
||||
/* A request another API's shape was translated into: admitted and served like a chat one,
|
||||
* answered in `r.shape`. */
|
||||
HttpResponse serve_translated(const HttpRequest& req, OaiRequest& r);
|
||||
HttpResponse handle_native_completion(const HttpRequest& req);
|
||||
HttpResponse handle_infill(const HttpRequest& req);
|
||||
json native_result(const OaiRequest& r, const Generation& g, const std::string& content);
|
||||
HttpResponse handle_load(const HttpRequest& req);
|
||||
HttpResponse handle_tokenize(const HttpRequest& req);
|
||||
HttpResponse handle_detokenize(const HttpRequest& req);
|
||||
@@ -213,7 +225,8 @@ private:
|
||||
HttpResponse handle_stats(const HttpRequest& req);
|
||||
HttpResponse handle_graph(const HttpRequest& req);
|
||||
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer);
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer,
|
||||
ApiShape shape = ApiShape::OpenAI);
|
||||
/* THE REQUEST LOG. One line when a request is admitted and one from record() when it ends,
|
||||
* at the info level, so `docker logs` answers "who asked what, how long, how did it end"
|
||||
* without the engine's own levels. The debug level adds the last user message's opening. */
|
||||
|
||||
+32
-4
@@ -1,5 +1,6 @@
|
||||
#include "sink.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
@@ -57,7 +58,13 @@ void Sink::notify() {
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
bool Sink::push(int32_t token, float logprob) {
|
||||
void Sink::enable_logprobs(int n) {
|
||||
alt_w_ = n > 0 ? n : 0;
|
||||
alts_.assign(ring_.size() * (size_t)alt_w_, SinkAlt{});
|
||||
alt_n_.assign(ring_.size(), 0);
|
||||
}
|
||||
|
||||
bool Sink::push(int32_t token, const TokenLogprobs* lp) {
|
||||
const uint64_t h = head_.load(std::memory_order_relaxed);
|
||||
const uint64_t t = tail_.load(std::memory_order_acquire);
|
||||
if (h - t > mask_) {
|
||||
@@ -66,7 +73,14 @@ bool Sink::push(int32_t token, float logprob) {
|
||||
fail(RAD_E_FULL);
|
||||
return false;
|
||||
}
|
||||
ring_[h & mask_] = SinkToken{token, logprob};
|
||||
const size_t slot = (size_t)(h & mask_);
|
||||
ring_[slot] = SinkToken{ token, lp ? lp->logprob : 0.0f, 0 };
|
||||
if (alt_w_ > 0) {
|
||||
const int n = lp ? std::min(lp->n_top, alt_w_) : 0;
|
||||
for (int j = 0; j < n; ++j)
|
||||
alts_[slot * (size_t)alt_w_ + (size_t)j] = SinkAlt{ lp->top_id[j], lp->top_lp[j] };
|
||||
alt_n_[slot] = n;
|
||||
}
|
||||
head_.store(h + 1, std::memory_order_release);
|
||||
|
||||
const int64_t t_now = now_ns() - t_start_ns_;
|
||||
@@ -100,6 +114,13 @@ void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) {
|
||||
n_cached_.store(n_cached, std::memory_order_release);
|
||||
}
|
||||
|
||||
void Sink::set_prompt_progress(int32_t processed, int32_t total, int32_t cached) {
|
||||
prog_total_.store(total, std::memory_order_release);
|
||||
prog_cached_.store(cached, std::memory_order_release);
|
||||
prog_done_.store(processed, std::memory_order_release);
|
||||
notify();
|
||||
}
|
||||
|
||||
void Sink::mark_admitted() {
|
||||
if (t_admit_.load(std::memory_order_relaxed) < 0)
|
||||
t_admit_.store(now_ns() - t_start_ns_, std::memory_order_release);
|
||||
@@ -112,12 +133,19 @@ void Sink::add_drafts(int32_t n, int32_t accepted) {
|
||||
std::memory_order_release);
|
||||
}
|
||||
|
||||
size_t Sink::read(SinkToken* out, size_t max) {
|
||||
size_t Sink::read(SinkToken* out, size_t max, SinkAlt* alts) {
|
||||
const uint64_t t = tail_.load(std::memory_order_relaxed);
|
||||
const uint64_t h = head_.load(std::memory_order_acquire);
|
||||
size_t n = (size_t)(h - t);
|
||||
if (n > max) n = max;
|
||||
for (size_t i = 0; i < n; ++i) out[i] = ring_[(t + i) & mask_];
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const size_t slot = (size_t)((t + i) & mask_);
|
||||
out[i] = ring_[slot];
|
||||
if (!alts || alt_w_ <= 0) continue;
|
||||
out[i].n_alt = alt_n_[slot];
|
||||
for (int j = 0; j < alt_n_[slot]; ++j)
|
||||
alts[i * (size_t)alt_w_ + (size_t)j] = alts_[slot * (size_t)alt_w_ + (size_t)j];
|
||||
}
|
||||
if (n) tail_.store(t + n, std::memory_order_release);
|
||||
return n;
|
||||
}
|
||||
|
||||
+38
-13
@@ -49,7 +49,14 @@ const char* finish_reason_oai(Finish f);
|
||||
|
||||
struct SinkToken {
|
||||
int32_t token = 0;
|
||||
float logprob = 0.0f; /* 0 when the sampler does not supply one; see Sink::has_logprobs */
|
||||
float logprob = 0.0f; /* the token's logprob; 0 unless the request asked for logprobs */
|
||||
int32_t n_alt = 0; /* how many alternatives read() wrote for this token */
|
||||
};
|
||||
|
||||
/* One of a token's most likely alternatives, with its logprob. */
|
||||
struct SinkAlt {
|
||||
int32_t id = 0;
|
||||
float logprob = 0.0f;
|
||||
};
|
||||
|
||||
class Sink {
|
||||
@@ -73,8 +80,9 @@ public:
|
||||
|
||||
/* ------------------------------------------------------------------ producer: scheduler */
|
||||
|
||||
/* Returns false only on overflow, which also marks the request failed. */
|
||||
bool push(int32_t token, float logprob = 0.0f);
|
||||
/* Returns false only on overflow, which also marks the request failed. `lp` is the token's
|
||||
* logprobs when the request asked for them (enable_logprobs), and null otherwise. */
|
||||
bool push(int32_t token, const TokenLogprobs* lp = nullptr);
|
||||
|
||||
/* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
|
||||
* produce two finish reasons. */
|
||||
@@ -97,11 +105,20 @@ public:
|
||||
/* A verify step's speculation for this request: `n` tokens proposed, `accepted` of them
|
||||
* taken. Summed over the request, the per-request half of /metrics' draft counters. */
|
||||
void add_drafts(int32_t n, int32_t accepted);
|
||||
/* HOW MUCH OF THE PROMPT IS IN THE CACHE: at admission (what the prefix cache supplied) and
|
||||
* after every prefill step, of `total`, of which `cached` came from the prefix cache. What
|
||||
* llama-server streams as `prompt_progress` when a request asks for it; wakes the consumer. */
|
||||
void set_prompt_progress(int32_t processed, int32_t total, int32_t cached);
|
||||
int32_t progress_processed() const { return prog_done_.load(std::memory_order_acquire); }
|
||||
int32_t progress_total() const { return prog_total_.load(std::memory_order_acquire); }
|
||||
int32_t progress_cached() const { return prog_cached_.load(std::memory_order_acquire); }
|
||||
|
||||
/* ------------------------------------------------------------------ consumer: HTTP */
|
||||
|
||||
/* Copies up to `max` tokens out. Returns how many. Never blocks. */
|
||||
size_t read(SinkToken* out, size_t max);
|
||||
/* Copies up to `max` tokens out. Returns how many. Never blocks. With `alts`, each token's
|
||||
* alternatives too: token i's n_alt of them at alts[i * alt_width()], which needs room for
|
||||
* max * alt_width(). */
|
||||
size_t read(SinkToken* out, size_t max, SinkAlt* alts = nullptr);
|
||||
|
||||
/* Sleeps until there is something to read, the request is terminal, or `timeout_ms` elapses.
|
||||
* Returns true if there is now something to look at. */
|
||||
@@ -133,11 +150,11 @@ public:
|
||||
int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
|
||||
int32_t n_cached() const { return n_cached_.load(std::memory_order_acquire); }
|
||||
|
||||
/* The engine sets this at wiring time if its sampler returns per-token probabilities. Without
|
||||
* it the logprobs field of a response is null rather than zeros (spec: nothing unimplemented
|
||||
* returns success). */
|
||||
void set_has_logprobs(bool v) { has_logprobs_ = v; }
|
||||
bool has_logprobs() const { return has_logprobs_; }
|
||||
/* THE ALTERNATIVES' RING, sized for `n` a token, beside the token ring: allocated only for a
|
||||
* request that asks for them, because at RAD_MAX_LOGPROBS it is twenty times the token ring.
|
||||
* Called by the consumer before the request is handed to the scheduler. */
|
||||
void enable_logprobs(int n);
|
||||
int alt_width() const { return alt_w_; }
|
||||
|
||||
/* The engine's request id, so a dropped connection can reach IScheduler::cancel. */
|
||||
uint64_t id = 0;
|
||||
@@ -174,7 +191,12 @@ private:
|
||||
|
||||
std::atomic<int32_t> n_prompt_{0};
|
||||
std::atomic<int32_t> n_cached_{0};
|
||||
bool has_logprobs_ = false;
|
||||
std::atomic<int32_t> prog_done_{-1};
|
||||
std::atomic<int32_t> prog_total_{0};
|
||||
std::atomic<int32_t> prog_cached_{0};
|
||||
std::vector<SinkAlt> alts_; /* [capacity * alt_w_], parallel to ring_ */
|
||||
std::vector<int32_t> alt_n_; /* [capacity] */
|
||||
int alt_w_ = 0;
|
||||
std::vector<float> embd_;
|
||||
|
||||
std::mutex m_;
|
||||
@@ -183,8 +205,8 @@ private:
|
||||
|
||||
/* The scheduler's call sites, so core/sched needs one include and no casts of its own. A null
|
||||
* sink is legal and means nobody is listening -- an offline or benchmark request. */
|
||||
inline bool sink_push(void* s, int32_t token, float logprob = 0.0f) {
|
||||
return s ? static_cast<Sink*>(s)->push(token, logprob) : true;
|
||||
inline bool sink_push(void* s, int32_t token, const TokenLogprobs* lp = nullptr) {
|
||||
return s ? static_cast<Sink*>(s)->push(token, lp) : true;
|
||||
}
|
||||
inline void sink_finish(void* s, Finish f) {
|
||||
if (s) static_cast<Sink*>(s)->finish(f);
|
||||
@@ -201,6 +223,9 @@ inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) {
|
||||
inline void sink_admitted(void* s) {
|
||||
if (s) static_cast<Sink*>(s)->mark_admitted();
|
||||
}
|
||||
inline void sink_prompt_progress(void* s, int32_t processed, int32_t total, int32_t cached) {
|
||||
if (s) static_cast<Sink*>(s)->set_prompt_progress(processed, total, cached);
|
||||
}
|
||||
inline void sink_drafts(void* s, int32_t n, int32_t accepted) {
|
||||
if (s) static_cast<Sink*>(s)->add_drafts(n, accepted);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user