This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/core/server/server.cpp
T
Deadcode 89cee7ce41 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
2026-10-08 18:22:08 +02:00

1760 lines
82 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "server.h"
#include <cstdio>
#include "json_partial.h"
#include "rad_internal.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <thread>
namespace rad {
namespace server {
/* ------------------------------------------------------------------ per-choice state */
struct Server::Generation {
std::shared_ptr<Sink> sink;
std::unique_ptr<IDetokenizer> detok;
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;
Finish finish = Finish::None;
bool closed = false; /* the server has decided this choice is over */
size_t scanned = 0; /* how far the stop-string scan has reached */
/* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
* has been generated) and how far the search for it has reached. */
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 */
};
struct Server::StreamState {
OaiRequest r;
std::vector<Generation> gens;
std::function<bool()> peer_closed;
bool opened = false;
bool done_sent = false;
bool released = false;
};
/* ------------------------------------------------------------------ construction */
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;
lim_.max_n = opt_.max_n;
lim_.max_stops = opt_.max_stops;
lim_.max_stop_bytes = opt_.max_stop_bytes;
lim_.allow_image = opt_.allow_image;
lim_.allow_video = opt_.allow_video;
lim_.allow_audio = opt_.allow_audio;
lim_.supports_logprobs = opt_.supports_logprobs;
lim_.default_reasoning_effort = opt_.default_reasoning_effort;
lim_.default_thinking_budget = opt_.default_thinking_budget;
lim_.default_sampling = opt_.default_sampling;
lim_.default_dry_breakers_set = opt_.default_dry_breakers_set;
lim_.default_template_kwargs = opt_.default_template_kwargs;
lim_.reasoning_effort_map = opt_.reasoning_effort_map;
lim_.reasoning_format = opt_.reasoning_format;
odeps_.tok = deps_.tok;
odeps_.chat = deps_.chat;
odeps_.grammar = deps_.grammar;
odeps_.mm = deps_.mm;
odeps_.embed = deps_.embed;
queue_depth_ = opt_.queue_depth > 0 ? opt_.queue_depth : opt_.max_seqs * 8;
started_at_ = unix_now();
register_routes();
}
Server::~Server() { stop(); }
/* Sinks the engine may still be writing into must not be freed. `Request::sink` is a raw pointer
* the scheduler holds for the life of the request, so the only safe moment to release one is
* after the scheduler has reported it terminal. At shutdown we wait a bounded time for that and,
* if it never comes, we leak the remainder on purpose and say so.
*
* A deliberate leak of a few KiB at process exit is the cheap failure. Freeing under a running
* step is the expensive one: it corrupts whatever the allocator hands out next, and it surfaces
* as garbage in an unrelated request several steps later, which is precisely the class of bug
* spec §17 exists to keep out of this engine. */
void Server::drain_graveyard(int timeout_ms) {
const int slice = 5;
for (int waited = 0; waited <= timeout_ms; waited += slice) {
sweep_abandoned();
{
std::lock_guard<std::mutex> lk(grave_m_);
if (grave_.empty()) return;
}
std::this_thread::sleep_for(std::chrono::milliseconds(slice));
}
std::lock_guard<std::mutex> lk(grave_m_);
if (grave_.empty()) return;
RAD_ERR("server: %zu cancelled requests are still held by the scheduler after %d ms. "
"Stop the scheduler before destroying the server. Leaking their sinks rather than "
"freeing memory a running step may still write to.",
grave_.size(), timeout_ms);
/* Hand the remainder to storage that outlives the process's teardown of this object. */
static std::vector<std::vector<std::shared_ptr<Sink>>>* leaked =
new std::vector<std::vector<std::shared_ptr<Sink>>>();
leaked->push_back(std::move(grave_));
grave_.clear();
}
/* WHAT IS SERVED. One table, and /server_info answers with it rather than with a copy -- a list
* kept beside this one is a list that goes stale on the next route added.
*
* Method spellings follow vLLM's, including the ones that look wrong: /tokenize and /detokenize
* are POST because their input is a body, /reset_prefix_cache is POST because it changes state,
* and /ping answers both GET and POST because different load balancers send different ones and
* neither is worth a 405 on a health probe. */
void Server::register_routes() {
router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); });
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); });
router_.get ("/version", [this](const HttpRequest& q) { return handle_version(q); });
router_.get ("/server_info", [this](const HttpRequest& q) { return handle_server_info(q); });
router_.get ("/props", [this](const HttpRequest& q) { return handle_props(q); });
router_.post("/tokenize", [this](const HttpRequest& q) { return handle_tokenize(q); });
router_.post("/detokenize", [this](const HttpRequest& q) { return handle_detokenize(q); });
router_.get ("/get_tokenizer_info", [this](const HttpRequest& q) { return handle_tokenizer_info(q); });
router_.post("/reset_prefix_cache", [this](const HttpRequest& q) { return handle_reset_prefix_cache(q); });
/* The dashboard. `/` rather than only `/dashboard` because a person who has the host and port
* of a running engine types exactly that, and answering it with a 404 is answering the
* question "is this thing alive" with "no". */
router_.get ("/", [this](const HttpRequest& q) { return handle_dashboard(q); });
router_.get ("/dashboard", [this](const HttpRequest& q) { return handle_dashboard(q); });
router_.get ("/stats", [this](const HttpRequest& q) { return handle_stats(q); });
router_.get ("/graph", [this](const HttpRequest& q) { return handle_graph(q); });
router_.get ("/sessions", [this](const HttpRequest& q) { return handle_sessions(q); });
}
/* WORKERS FOR EVERYTHING ADMISSION CAN LET IN, AND A RESERVE BESIDE THEM.
*
* A generation holds its connection's worker for as long as it runs -- a stream writes from it, a
* blocking request waits on its sink in it -- so a pool no larger than the admission ceiling runs
* out of workers before admission refuses anyone. The 429 can then never happen, and every
* connection after that waits in the pool's queue behind generations that may run for minutes,
* /health included. So the pool may grow to the ceiling plus a reserve no admitted generation can
* occupy: that is what keeps a probe, the dashboard, a request about to be told 429 and a
* client's idle keep-alive connections answerable while every admitted request is running. The
* same number bounds the connections that may wait once even the reserve is busy. */
static const int64_t kSpareWorkers = 64;
int Server::run() {
TransportOptions t;
t.host = opt_.host;
t.port = opt_.port;
t.n_threads = opt_.n_threads;
t.max_threads = queue_depth_ + kSpareWorkers;
t.max_queued = kSpareWorkers;
t.api_key = opt_.api_key;
t.cors = opt_.cors;
t.read_timeout_s = opt_.read_timeout_s;
t.write_timeout_s = opt_.write_timeout_s;
t.keep_alive_timeout_s = opt_.keep_alive_timeout_s;
t.max_body_bytes = opt_.max_body_bytes;
return transport_.serve(router_, t);
}
void Server::check_template_defaults(std::string* kwargs_why, std::string* effort_why) const {
kwargs_why->clear();
effort_why->clear();
if (!deps_.chat) return;
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1})";
auto render = [&](const OaiLimits& l, std::string* why) {
OaiRequest r;
ApiError e;
if (parse_chat_request(body, odeps_, l, &r, &e) >= 0) return true;
if (why) *why = e.message;
return false;
};
OaiLimits l = lim_;
l.default_template_kwargs.clear();
l.default_reasoning_effort.clear();
l.probe = true;
if (!render(l, nullptr)) return;
l.default_template_kwargs = lim_.default_template_kwargs;
if (!l.default_template_kwargs.empty() && !render(l, kwargs_why)) return;
l.default_reasoning_effort = lim_.default_reasoning_effort;
if (!l.default_reasoning_effort.empty()) render(l, effort_why);
}
std::vector<std::string> Server::probe_reasoning_efforts() {
lim_.reasoning_efforts.clear();
if (!deps_.chat) return {};
OaiLimits l = lim_;
l.default_template_kwargs.clear();
l.default_reasoning_effort.clear();
l.reasoning_effort_map.clear();
l.probe = true;
auto takes = [&](const std::string& effort) {
std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1)";
if (!effort.empty()) body += R"(,"reasoning_effort":)" + json(effort).dump();
body += "}";
OaiRequest r;
ApiError e;
return parse_chat_request(body, odeps_, l, &r, &e) >= 0;
};
/* A render that fails with no effort at all says nothing about efforts, and one that takes a
* word no ladder has takes every word. */
if (!takes("") || takes("radiance-probe-not-a-level")) return {};
std::vector<std::string> set;
for (const char* w : { "low", "medium", "high", "xhigh", "max" })
if (takes(w)) set.push_back(w);
lim_.reasoning_efforts = set;
return set;
}
std::string Server::check_reasoning_effort_map() const {
if (!deps_.chat) return std::string();
OaiLimits l = lim_;
l.default_template_kwargs.clear();
l.default_reasoning_effort.clear();
l.reasoning_effort_map.clear();
l.probe = true;
for (const auto& [from, to] : lim_.reasoning_effort_map) {
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)"
R"("reasoning_effort":)" + json(to).dump() + "}";
OaiRequest r;
ApiError e;
if (parse_chat_request(body, odeps_, l, &r, &e) < 0)
return from + "=" + to + ": the chat template refuses '" + to + "': " + e.message;
}
return std::string();
}
std::string Server::check_thinking_budget() const {
if (!deps_.chat || lim_.default_thinking_budget < 0) return std::string();
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)"
R"("thinking_token_budget":)" +
std::to_string(lim_.default_thinking_budget) + "}";
OaiRequest r;
ApiError e;
return parse_chat_request(body, odeps_, lim_, &r, &e) < 0 ? e.message : std::string();
}
void Server::stop() {
stopping_.store(true);
transport_.stop();
drain_graveyard(2000);
}
/* ------------------------------------------------------------------ admission */
bool Server::admit(int64_t n) {
int64_t cur = in_flight_.fetch_add(n, std::memory_order_acq_rel) + n;
if (cur > queue_depth_) {
in_flight_.fetch_sub(n, std::memory_order_acq_rel);
return false;
}
metrics_.set_queue_depth(cur);
return true;
}
void Server::release(int64_t n) {
int64_t cur = in_flight_.fetch_sub(n, std::memory_order_acq_rel) - n;
metrics_.set_queue_depth(cur);
}
void Server::sweep_abandoned() {
std::lock_guard<std::mutex> lk(grave_m_);
size_t before = grave_.size();
grave_.erase(std::remove_if(grave_.begin(), grave_.end(),
[this](const std::shared_ptr<Sink>& s) {
if (!s->done()) return false;
deps_.sched->reap(s->id);
return true;
}),
grave_.end());
if (grave_.size() > 256 && grave_.size() >= before)
RAD_WARN("server: %zu cancelled requests the scheduler has not reported terminal; "
"IScheduler::cancel must finish them, not just unschedule them",
grave_.size());
}
/* ------------------------------------------------------------------ errors */
/* " from <addr:port>" for the request log, or nothing in-process, where no transport names a
* peer. */
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, 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;
* 5xx is ours and said as a warning. */
if (e.status >= 500)
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
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, 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;
}
/* ------------------------------------------------------------------ the request log */
void Server::log_admitted(const OaiRequest& r) const {
int64_t n_prompt = 0;
for (const auto& p : r.prompts) n_prompt += (int64_t)p.tokens.size();
const char* kind = r.endpoint == Endpoint::Chat ? "chat" : "completion";
if (r.endpoint == Endpoint::Chat)
RAD_INFO("req %s %s%s%s model=%s msgs=%d tools=%d prompt=%lld tok n=%d max_tokens=%lld",
r.id.c_str(), kind, r.stream ? " stream" : "", from_peer(r.peer).c_str(),
r.model.c_str(), r.n_messages, r.n_tools, (long long)n_prompt, r.n,
(long long)r.max_tokens);
else
RAD_INFO("req %s %s%s%s model=%s prompts=%zu prompt=%lld tok n=%d max_tokens=%lld",
r.id.c_str(), kind, r.stream ? " stream" : "", from_peer(r.peer).c_str(),
r.model.c_str(), r.prompts.size(), (long long)n_prompt, r.n,
(long long)r.max_tokens);
if (!r.last_user.empty())
RAD_DEBUG("req %s last user: %s", r.id.c_str(), r.last_user.c_str());
}
/* ------------------------------------------------------------------ submission */
int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiError* err) {
const int n_choices = r.n_choices();
gens->reserve((size_t)n_choices);
/* THE SAMPLER GETS A SAY BEFORE ANYTHING IS QUEUED. A stage that did not resolve is not a
* declare failure -- it becomes one when a request asks for it. Refusing here makes that a
* 400 naming the parameter, instead of an admitted request that the step loop cancels three
* steps in with a dead stream at the client.
*
* Once, not per choice: `n` varies only the seed, and no check here reads it. */
{
std::string why;
if (deps_.sched->admit(r.sp, &why) < 0) {
*err = err_unsupported("sampling", why.empty()
? "these sampling parameters cannot be served" : why);
return RAD_E_INVAL;
}
}
int idx = 0;
std::vector<Request> rqs;
rqs.reserve(r.prompts.size() * (size_t)r.n);
const size_t first = gens->size();
for (size_t p = 0; p < r.prompts.size(); ++p) {
for (int k = 0; k < r.n; ++k, ++idx) {
Generation g;
g.index = idx;
g.prompt_index = (int)p;
g.sink = std::make_shared<Sink>();
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) {
*err = err_not_implemented("the tokenizer did not supply an incremental decoder");
return RAD_E_UNSUPPORTED;
}
if (!r.stops_after.empty()) g.detok->defer_stops_until(r.stops_after);
Request rq;
rq.prompt = r.prompts[p].tokens;
rq.sp = r.sp;
/* n identical seeds would give n identical completions, which is not what `n` means.
* Offsetting is enough: the sampler's stream is seeded, not chained. */
rq.sp.seed = r.sp.seed + (uint64_t)k;
rq.max_tokens = r.max_tokens;
/* With the stop strings deferred past the reasoning block, the scheduler -- which
* cannot tell reasoning from answer -- gets none; the decoder and pump() cut. */
rq.stop = r.stops_after.empty() ? r.stop : std::vector<std::string>{};
rq.ignore_eos = r.ignore_eos;
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));
}
}
std::vector<uint64_t> ids;
deps_.sched->submit_all(rqs, &ids);
for (size_t i = 0; i < ids.size(); ++i) {
Generation& g = (*gens)[first + i];
g.id = ids[i];
g.sink->id = g.id;
}
return RAD_OK;
}
void Server::cancel_all(std::vector<Generation>& gens, bool count_disconnect) {
for (auto& g : gens) {
if (g.sink->done()) continue;
g.sink->request_cancel();
deps_.sched->cancel(g.id);
}
if (count_disconnect) metrics_.observe_disconnect();
}
/* Every exit from a request goes through here exactly once. A generation the engine has finished
* is reaped -- that is the server telling the scheduler it may drop the Request, which it cannot
* know on its own because we are the ones holding the sink. One the engine has not finished moves
* to the graveyard, and is reaped by the sweep when it does. */
void Server::retire(std::vector<Generation>& gens) {
std::vector<std::shared_ptr<Sink>> pending;
for (auto& g : gens) {
if (g.retired) continue;
g.retired = true;
if (g.sink->done()) deps_.sched->reap(g.id);
else pending.push_back(g.sink);
}
if (pending.empty()) return;
std::lock_guard<std::mutex> lk(grave_m_);
for (auto& s : pending) grave_.push_back(std::move(s));
}
/* ------------------------------------------------------------------ draining */
bool Server::all_done(const std::vector<Generation>& gens) const {
for (const auto& g : gens) if (!g.closed) return false;
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());
for (auto& g : gens) {
if (g.closed) continue;
size_t n;
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) 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));
}
}
/* The decoder may have swallowed the stop string itself, in which case our own scan below
* 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;
g.sink->request_cancel();
deps_.sched->cancel(g.id);
continue;
}
/* Stop strings. The scheduler is given Request::stop and may stop first, but a stop
* string straddles token boundaries and only the detokenised text can be searched, so the
* authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous
* end so a match spanning two drains is still found. */
/* Stop strings deferred past the reasoning block match only after its closer. The closer
* is searched for incrementally, from (closer length - 1) bytes behind the previous end,
* so a reply that thinks for a long time is not rescanned from its start every drain. */
size_t floor = 0;
if (!r.stops_after.empty()) {
if (g.stops_floor == std::string::npos) {
const size_t n = r.stops_after.size();
const size_t from = g.closer_scanned >= n ? g.closer_scanned - n + 1 : 0;
const size_t m = g.text.find(r.stops_after, from);
g.closer_scanned = g.text.size();
if (m != std::string::npos) g.stops_floor = m + n;
}
floor = g.stops_floor;
}
if (maxstop && floor != std::string::npos && g.stop_cut == std::string::npos &&
!g.text.empty()) {
size_t start = g.scanned >= maxstop ? g.scanned - maxstop + 1 : 0;
if (start < floor) start = floor;
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)) {
g.stop_cut = at;
g.stop_word = s;
}
}
g.scanned = g.text.size();
if (g.stop_cut != std::string::npos) {
g.text.resize(g.stop_cut);
g.finish = Finish::StopString;
g.closed = true;
progress = true;
/* The client will never see another token of this choice, so the blocks it holds
* are dead weight the moment we decide that (spec §14). */
g.sink->request_cancel();
deps_.sched->cancel(g.id);
continue;
}
}
if (g.sink->done()) {
std::string tail = g.detok->flush();
if (!tail.empty()) { g.text += tail; progress = true; }
g.finish = g.sink->finish_reason();
if (g.sink->overflowed()) metrics_.observe_overflow();
g.closed = true;
progress = true;
}
}
return progress;
}
/* ------------------------------------------------------------------ usage */
/* THE REQUEST'S TOKENS, ONCE FOR BOTH PATHS. `n` choices share a prompt, so the prompt and its
* cached part are counted once per prompt. Reasoning is reported only where the reply's block can
* be counted by token (ReasoningSpan); a model without one reports no breakdown rather than a
* zero that would claim there was no reasoning. */
UsageOut Server::usage_of(const OaiRequest& r, const std::vector<Generation>& gens) {
UsageOut u;
for (const auto& p : r.prompts) u.prompt += (int64_t)p.tokens.size();
if (r.sp.reasoning.known()) u.reasoning = 0;
for (const auto& g : gens) {
u.completion += g.sink->n_produced();
if (g.prompt_index * r.n == g.index) u.cached += g.sink->n_cached();
if (u.reasoning >= 0) u.reasoning += g.think.tokens;
}
return u;
}
/* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for
* the request. Every time is moved onto one clock first -- each sink counts from its own
* construction. See TimingsOut for what each field means. */
TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) {
TimingsOut t;
int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN;
bool admitted = true;
for (size_t i = 0; i < n; ++i) {
const Sink& s = *sinks[i];
const int64_t produced = s.n_produced();
t.predicted_n += produced;
t.draft_n += s.n_drafted();
t.draft_n_accepted += s.n_draft_accepted();
const int64_t tf = s.t_first_token_ns();
if (tf < 0) continue;
t.valid = true;
t.cache_n += s.n_cached();
t.prompt_n += s.n_prompt() - s.n_cached();
if (produced > 1) t.decode_n += produced - 1;
const int64_t t0 = s.t_start_ns(), ta = s.t_admitted_ns();
if (ta < 0) admitted = false;
else admit = std::min(admit, t0 + ta);
first_lo = std::min(first_lo, t0 + tf);
first_hi = std::max(first_hi, t0 + tf);
last = std::max(last, t0 + s.t_last_token_ns());
}
if (!t.valid) return t;
if (admitted) t.prompt_ms = (double)(first_hi - admit) * 1e-6;
t.predicted_ms = (double)(last - first_lo) * 1e-6;
return t;
}
TimingsOut Server::timings_of(const std::vector<Generation>& gens) {
std::vector<const Sink*> v;
v.reserve(gens.size());
for (const auto& g : gens) v.push_back(g.sink.get());
return timings_of(v.data(), v.size());
}
/* ------------------------------------------------------------------ metrics bookkeeping */
/* WHAT FAILED, for the client: the sentence the failing component gave, and the status. A failed
* request always carries a status -- an engine that stopped carries the one that stopped it -- so
* this never reads "ok". */
static std::string engine_failure(const Sink& s) {
const int st = s.status() < 0 ? s.status() : RAD_E_STATE;
const char* why = s.why();
return why ? fmt("the engine failed this request: %s (%s)", why, rad_strerror(st))
: fmt("the engine failed this request: %s", rad_strerror(st));
}
static SuccessReason to_reason(Finish f) {
switch (f) {
case Finish::Length: return SuccessReason::Length;
case Finish::ToolCalls: return SuccessReason::ToolCalls;
case Finish::Cancelled: return SuccessReason::Abort;
case Finish::Error: return SuccessReason::Error;
default: return SuccessReason::Stop;
}
}
void Server::record(const OaiRequest& r, const std::vector<Generation>& gens, Finish overall) {
int64_t n_prompt = 0;
for (const auto& p : r.prompts) n_prompt += (int64_t)p.tokens.size();
int64_t n_gen = 0;
double ttft = -1.0, tpot = -1.0, decode = -1.0, e2e = 0.0;
for (const auto& g : gens) {
int64_t produced = g.sink->n_produced();
n_gen += produced;
e2e = std::max(e2e, (double)g.sink->age_ns() * 1e-9);
int64_t tf = g.sink->t_first_token_ns(), tl = g.sink->t_last_token_ns();
if (tf >= 0) {
double t = (double)tf * 1e-9;
ttft = ttft < 0 ? t : std::min(ttft, t);
if (produced > 1 && tl > tf) {
double d = (double)(tl - tf) * 1e-9;
decode = decode < 0 ? d : std::max(decode, d);
double per = d / (double)(produced - 1);
tpot = tpot < 0 ? per : std::max(tpot, per);
}
}
}
metrics_.observe_request(n_prompt, n_gen, ttft, tpot, e2e, decode,
r.n, r.max_tokens, to_reason(overall));
/* THE OTHER HALF OF THE REQUEST LOG. The same figures /metrics aggregates, for this one
* request: how it ended, what the prefix cache spared, the reasoning share when the parser
* knows it, time to first token, the decode rate after it, and the whole. */
const TimingsOut t = timings_of(gens);
const UsageOut u = usage_of(r, gens);
const double rate = (decode > 0.0 && n_gen > 1) ? (double)(n_gen - 1) / decode : -1.0;
char reason[32] = "";
if (u.reasoning >= 0) std::snprintf(reason, sizeof reason, " reason=%lld", (long long)u.reasoning);
char ttft_s[32] = "ttft=-";
if (ttft >= 0) std::snprintf(ttft_s, sizeof ttft_s, "ttft=%.2fs", ttft);
char rate_s[32] = "";
if (rate > 0) std::snprintf(rate_s, sizeof rate_s, " %.1f tok/s", rate);
RAD_INFO("req %s done%s finish=%s prompt=%lld (cache %lld) gen=%lld%s %s%s %.2fs",
r.id.c_str(), from_peer(r.peer).c_str(), finish_reason_oai(overall),
(long long)n_prompt, (long long)(t.valid ? t.cache_n : 0), (long long)n_gen, reason,
ttft_s, rate_s, e2e);
}
/* ------------------------------------------------------------------ non-streaming */
HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) {
std::vector<Generation> gens;
ApiError err;
if (submit_all(r, &gens, &err) < 0) {
retire(gens);
release(r.n_choices());
return error_response(err, req.peer, r.shape);
}
for (;;) {
pump(gens, r);
if (all_done(gens)) break;
/* A client that hangs up before the answer is ready is a cancellation, not something to
* finish computing for nobody. */
if (req.peer_gone()) {
cancel_all(gens, true);
retire(gens);
release(r.n_choices());
metrics_.observe_http(499);
HttpResponse res = HttpResponse::text(499, "client closed request\n");
return res;
}
if (stopping_.load()) {
cancel_all(gens, false);
retire(gens);
release(r.n_choices());
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; }
}
Finish overall = Finish::Stop;
const UsageOut usage = usage_of(r, gens);
std::vector<ChoiceOut> choices;
choices.reserve(gens.size());
for (auto& g : gens) {
ChoiceOut c;
c.index = g.index;
c.finish = g.finish;
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
* separates the reasoning block from the answer, and a request with no tools still
* wants `reasoning_content` split out rather than glued to the front of the reply.
* It is the same reader the streaming path feeds a piece at a time, fed the whole
* reply at once, so the two agree by construction. With no tools in the request the
* parser reads no calls and the tool bookkeeping below finds none. */
if (r.reply_parser) {
std::unique_ptr<IReplyReader> rd = r.reply_parser->open();
rd->feed(g.text, nullptr);
rd->finish(nullptr);
c.msg = rd->message();
/* Only claim a tool call when every call closed and its arguments parse
* (json_partial.h) -- the streaming path's rule (calls_complete). */
const bool complete = r.parse_tools && calls_complete(c.msg);
if (complete && (c.finish == Finish::Stop || c.finish == Finish::StopString))
c.finish = Finish::ToolCalls;
if (c.msg.open_call) {
/* A half-finished call is content, not a call: the client gets what the model
* wrote instead of a tool invocation with truncated arguments. Only that call
* -- the reply ended inside it, so it is the last -- and only its own text:
* the reasoning stays reasoning, and the calls before it, which closed, stay
* calls, as the stream announced them. The finish reason is the stream's. */
c.msg.content = rd->content_with_open_call(g.text);
c.msg.tool_calls.pop_back();
c.msg.open_call = false;
}
} else {
c.msg.content = g.text;
}
for (auto& tc : c.msg.tool_calls) if (tc.id.empty()) tc.id = random_id("call_");
} else {
c.text = r.echo ? r.prompts[g.prompt_index].text + g.text : g.text;
}
/* The request's outcome for record() and /metrics: a failure or a cancellation over
* anything, else a tool call over a plain stop -- the same promotion the streaming path
* makes, so a blocking tool call is not counted as "stop". */
if (c.finish == Finish::Error || c.finish == Finish::Cancelled) overall = c.finish;
else if (c.finish == Finish::ToolCalls && overall == Finish::Stop) overall = c.finish;
choices.push_back(std::move(c));
}
/* An engine-side failure is not a 200 with an empty answer. */
for (auto& g : gens) {
if (g.finish == Finish::Error) {
const std::string why = engine_failure(*g.sink);
retire(gens);
release(r.n_choices());
record(r, gens, Finish::Error);
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = why;
return error_response(e, req.peer, r.shape);
}
}
record(r, gens, overall);
retire(gens);
release(r.n_choices());
const TimingsOut timings = timings_of(gens);
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 std::string& logprobs = std::string()) {
nlohmann::ordered_json ch;
ch["text"] = delta;
ch["index"] = index;
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;
st->peer_closed = req.closed;
ApiError err;
if (submit_all(st->r, &st->gens, &err) < 0) {
retire(st->gens);
release(r.n_choices());
return error_response(err, req.peer, r.shape);
}
if (st->r.endpoint == Endpoint::Chat)
for (auto& g : st->gens)
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;
res.content_type = "text/event-stream; charset=utf-8";
res.set_header("Cache-Control", "no-cache");
res.set_header("Connection", "keep-alive");
/* nginx buffers proxied responses by default, which turns a token stream into one large
* delivery at the end. This header is the documented opt-out and costs nothing elsewhere. */
res.set_header("X-Accel-Buffering", "no");
Server* self = this;
res.next = [self, st](std::string& out) -> bool {
out.clear();
if (st->done_sent) return false;
if (!st->opened) {
st->opened = true;
if (st->r.endpoint == Endpoint::Chat) {
for (auto& g : st->gens) out += g.delta->first_chunk();
} else if (st->r.echo) {
/* `echo`, ON THE STREAMING PATH. The buffered path applies it by prepending the
* prompt to the choice's text; this is the equivalent, and without it the same
* request would answer differently depending on `stream`.
*
* The prompt goes out as the first content chunk, before any token, which is what
* "echo" means and what a client reassembling the deltas needs: concatenating the
* stream gives the same string the buffered response returns.
* Empty prompts emit nothing rather than an empty chunk. */
for (auto& g : st->gens) {
const std::string& p = st->r.prompts[(size_t)g.prompt_index].text;
if (!p.empty()) out += text_chunk(st->r, g.index, p, nullptr);
}
}
return true;
}
if (st->peer_closed && st->peer_closed()) {
return false;
}
const bool progress = self->pump(st->gens, st->r);
size_t maxstop = 0;
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.
*
* ONLY WHILE IT IS RUNNING. Every hold-back rule here waits for bytes that may still
* arrive, and a closed choice has none coming, so its whole text is the answer. That
* includes a tail the escape rule would keep -- a trailing `\` or a partial `\uXXXX`
* is ordinary text in a completion, and holding it back at the end drops it. */
size_t safe = g.text.size();
if (!g.closed) {
if (maxstop > 1) safe = safe > maxstop - 1 ? safe - (maxstop - 1) : 0;
safe = json_stable_prefix(std::string_view(g.text.data(), safe));
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 (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, 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)) {
const UsageOut u = usage_of(st->r, st->gens);
Finish overall = Finish::Stop;
for (auto& g : st->gens) {
/* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no
* usage chunk still has them, as llama.cpp sends them. */
const Sink* one = g.sink.get();
const TimingsOut gt = timings_of(&one, 1);
/* A failed generation cannot become a non-200 -- the headers left long ago -- so
* 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) {
e.status = 500;
e.type = "internal_server_error";
e.message = engine_failure(*g.sink);
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), &gt);
if (g.finish == Finish::Error) out += sse_error(e);
}
}
/* THE USAGE CHUNK. `stream_options.include_usage` is parsed and validated on both
* endpoints, so both have to honour it -- accepting a field and then ignoring it is
* the outcome oai.h's header forbids.
*
* After the per-generation final chunks and before [DONE], which is where OpenAI puts
* it, and once for the request rather than once per choice: `n` completions share one
* prompt and one total, so emitting it per generation would count the prompt n times
* and interleave usage between the choices' final chunks. */
if (st->r.include_usage) {
const TimingsOut t = timings_of(st->gens);
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t)
: text_usage_chunk(st->r, u, t);
}
/* 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);
self->metrics_.observe_http(200);
if (!st->released) { st->released = true; self->release(st->r.n_choices()); }
return false;
}
if (!progress && out.empty()) {
/* Nothing to send: sleep on the first live sink rather than spinning. The bounded
* wait is what makes the peer-closed check above run a few times a second. */
for (auto& g : st->gens) if (!g.closed) { g.sink->wait(); break; }
}
return true;
};
res.on_close = [self, st](bool ok) {
if (!st->done_sent) {
/* Either the peer went away or the write failed. Both are cancellations, and the
* blocks have to go back now rather than when the generation would have ended. */
self->cancel_all(st->gens, true);
self->record(st->r, st->gens, Finish::Cancelled);
self->retire(st->gens);
RAD_DEBUG("server: stream %s abandoned by the client (write %s)",
st->r.id.c_str(), ok ? "ok" : "failed");
}
if (!st->released) { st->released = true; self->release(st->r.n_choices()); }
};
return res;
}
/* ------------------------------------------------------------------ endpoints */
HttpResponse Server::handle_chat(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_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer);
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);
}
log_admitted(r);
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);
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) < 0)
return error_response(err, req.peer);
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);
}
log_admitted(r);
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
}
HttpResponse Server::handle_embeddings(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"),
req.peer);
if (!deps_.embed)
return error_response(err_not_implemented(
"/v1/embeddings requires an embedding model; this one generates text"), req.peer);
OaiRequest r;
ApiError err;
if (parse_embeddings_request(req.body, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer);
r.peer = req.peer;
const int64_t dim = deps_.embed->dim();
if (r.dimensions > dim)
return error_response(err_bad("dimensions", "this model's vectors are " +
std::to_string(dim) + " wide"), req.peer);
/* AN INPUT IS NEVER SPLIT (Request::embed), so one longer than a step is refused here, with
* the number, rather than by the scheduler with none. */
for (size_t i = 0; i < r.prompts.size(); ++i) {
const int64_t n = (int64_t)r.prompts[i].tokens.size();
if (n > deps_.embed->max_input()) {
ApiError e = err_bad("input", "input " + std::to_string(i) + " is " +
std::to_string(n) + " tokens; this deployment "
"embeds at most " +
std::to_string(deps_.embed->max_input()) +
" (--max-num-batched-tokens)");
e.code = "context_length_exceeded";
return error_response(e, req.peer);
}
}
sweep_abandoned();
const int n_in = (int)r.prompts.size();
if (!admit(n_in)) {
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);
}
log_admitted(r);
/* EVERY INPUT AT ONCE, so the scheduler can put them in one step. */
std::vector<Generation> gens;
std::vector<Request> rqs;
gens.reserve((size_t)n_in);
rqs.reserve((size_t)n_in);
for (int i = 0; i < n_in; ++i) {
Generation g;
g.index = i;
g.prompt_index = i;
g.sink = std::make_shared<Sink>(16);
Request rq;
rq.prompt = r.prompts[(size_t)i].tokens;
rq.media = r.prompts[(size_t)i].media;
rq.embed = true;
rq.max_tokens = 1;
rq.sp.temp = 0.0f;
rq.sink = g.sink.get();
rqs.push_back(std::move(rq));
gens.push_back(std::move(g));
}
std::vector<uint64_t> ids;
deps_.sched->submit_all(rqs, &ids);
for (size_t i = 0; i < ids.size(); ++i) {
gens[i].id = ids[i];
gens[i].sink->id = ids[i];
if (!ids[i]) {
retire(gens);
release(n_in);
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = "the scheduler refused input " + std::to_string(i);
return error_response(e, req.peer);
}
}
for (;;) {
bool all = true;
for (auto& g : gens) {
if (!g.closed && g.sink->done()) { g.closed = true; g.finish = g.sink->finish_reason(); }
all = all && g.closed;
}
if (all) break;
if (req.peer_gone()) {
cancel_all(gens, true);
retire(gens);
release(n_in);
metrics_.observe_http(499);
return HttpResponse::text(499, "client closed request\n");
}
if (stopping_.load()) {
cancel_all(gens, false);
retire(gens);
release(n_in);
return error_response(err_overloaded("the server is shutting down"), req.peer);
}
for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; }
}
/* THE VECTORS, truncated to `dimensions` and L2-normalised: what OpenAI's endpoint returns and
* what a sentence-transformers model's Normalize module does. Truncating a unit vector does
* not keep it unit, so the normalisation comes after. */
std::vector<std::vector<float>> vecs;
vecs.reserve((size_t)n_in);
UsageOut u;
const int64_t keep = r.dimensions > 0 ? r.dimensions : dim;
for (auto& g : gens) {
const std::vector<float>& v = g.sink->embedding();
if (g.finish == Finish::Error || g.finish == Finish::Cancelled || (int64_t)v.size() != dim) {
const std::string why = g.finish == Finish::Error ? engine_failure(*g.sink)
: std::string("the engine returned no vector for input ") +
std::to_string(g.index);
retire(gens);
release(n_in);
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = why;
return error_response(e, req.peer);
}
std::vector<float> out(v.begin(), v.begin() + keep);
double ss = 0.0;
for (float x : out) ss += (double)x * x;
const float inv = ss > 0.0 ? (float)(1.0 / std::sqrt(ss)) : 0.0f;
for (float& x : out) x *= inv;
u.prompt += (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size();
vecs.push_back(std::move(out));
}
retire(gens);
release(n_in);
metrics_.observe_http(200);
return HttpResponse::json_body(200, embeddings_body(r, vecs, u));
}
HttpResponse Server::handle_models(const HttpRequest& req) {
const std::string id = req.param("id");
if (!id.empty() && id != opt_.model_id) {
ApiError e;
e.status = 404;
e.type = "not_found_error";
e.param = "model";
e.message = "no such model: " + id;
return error_response(e, req.peer);
}
ModelCard c;
c.id = opt_.model_id;
c.created = started_at_;
c.max_model_len = opt_.max_ctx;
c.root = opt_.model_path;
c.capabilities = capabilities().dump();
metrics_.observe_http(200);
return HttpResponse::json_body(200, id.empty() ? models_body(c) : model_body(c));
}
HttpResponse Server::handle_metrics(const HttpRequest&) {
if (deps_.sched) metrics_.sample(deps_.sched->metrics());
metrics_.set_queue_depth(in_flight_.load(std::memory_order_relaxed));
HttpResponse r;
r.status = 200;
/* The exposition format version is part of the content type; Prometheus uses it to decide how
* to parse, and omitting it makes some scrapers fall back to OpenMetrics and fail. */
r.content_type = "text/plain; version=0.0.4; charset=utf-8";
r.body = metrics_.render();
return r;
}
} /* namespace server */
} /* namespace rad */