radiance 1.1.0

- The VRAM split has no ratio: --expert-vs-cache-ratio is gone (now an unknown option). The
  experts keep what the pinned host pool cannot hold, the KV cache takes the rest and lends idle
  blocks to the experts. Flash-Next at tp2: 7.9 GiB of KV a card, up from 4.7. Startup, /stats,
  /metrics and the dashboard report the most the cache can hold.
- Linear-state snapshots live in pinned host memory, not VRAM (--checkpoint-slots sizes the
  store). Prefix-cache misses on agent sessions fixed; a published conversation is no longer
  trimmed away.
- Any world size from the shipped container (baKon): --tp 3 on Flash-Next with no padded
  checkpoint -- the attention world, uneven delta-net heads, the fill op.
- Kernels (keptn42): moe_gemm_q decode loads and one-trip run search, hc_read's prefill form
  (+3.7% prefill at 18K), hc_up row groups up to eight, the fused router launch. Each is the rule
  where it was measured faster; no environment switches.
- Tool calls: a typed argument is always JSON (Python True/None no longer leak into arguments --
  Codeberg #21); nine further reply-parser fixes; the reply path inside a call is ~12x cheaper on
  the host.
- The kernel changes: prefill +2-3% and decode -2% a step on 2x R9700 at tp2, identical text.
This commit is contained in:
Deadcode committed 2026-10-06 14:04:49 +02:00
1 parent 9f5feb24ee
commit 82b5835c02
101 files changed
+5105 -3767

No files matched your search

+12 -4
View File
@@ -116,10 +116,11 @@ public:
c.host_freed = s.host_freed; c.host_drops = s.host_drops; c.failures = s.failures;
c.fetched = s.fetched; c.ck_fetched = s.ck_fetched;
c.host_bytes = s.host_bytes; c.disk_bytes = s.disk_bytes;
c.ck_to_host = s.ck_to_host; c.ck_to_disk = s.ck_to_disk; c.ck_promoted = s.ck_promoted;
c.ck_drops = s.ck_drops; c.ck_starved = s.ck_starved;
c.ck_to_disk = s.ck_to_disk; c.ck_drops = s.ck_drops;
c.restores = s.restores; c.restore_ns = s.restore_ns;
c.flushes = s.flushes; c.flush_ns = s.flush_ns;
c.ck_bytes = tiers_->ckpt_bytes();
c.ck_host_slots = tiers_->ckpt_arena().capacity();
c.ck_host_slots = tiers_->ckpt_slots();
c.ck_disk_slots = tiers_->ckpt_disk_slots();
c.host_on = tiers_->host_on();
c.disk_on = tiers_->disk_on();
@@ -150,7 +151,6 @@ public:
o.on_disk = s.on_disk;
o.moving = s.moving;
o.snapshots = s.snapshots;
o.snap_device = s.snap_device;
o.snap_host = s.snap_host;
o.snap_disk = s.snap_disk;
o.snap_bytes = s.snap_bytes;
@@ -246,6 +246,9 @@ public:
o.kv_bytes_total += m.kv[i].bytes_total;
o.kv_bytes_used += m.kv[i].bytes_used;
o.kv_bytes_carved += m.kv[i].bytes_carved;
if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue;
const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens;
if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
}
/* vLLM's gpu_prefix_cache_hit_rate is a single number and attention caching is what it
@@ -432,9 +435,14 @@ public:
m.reasoning = r.reasoning;
m.tool_calls.reserve(r.calls.size());
for (const ReplyCall& c : r.calls) m.tool_calls.push_back({ std::string(), c.name, c.arguments });
m.open_call = !r.calls.empty() && !r.calls.back().closed;
return m;
}
std::string content_with_open_call(std::string_view reply) const override {
return s_->content_with_open_call(reply);
}
private:
void move_out(std::vector<ReplyDelta>* out) {
if (!out) return;
+22 -14
View File
@@ -53,7 +53,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
if (deps_.sched) deps_.sched->sessions(&v, &occ);
int64_t dev = 0, host = 0, disk = 0, bytes = 0;
int64_t sdev = 0, shost = 0, sdisk = 0;
int64_t shost = 0, sdisk = 0;
json a = json::array();
for (const SessionStat& s : v) {
json e;
@@ -69,17 +69,16 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
e["moving"] = s.moving;
/* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of
* what it needs back; the rest is its linear-state snapshots, which are a different size
* of object in a different store. Counted where the BYTES are, so a snapshot that stayed
* on the device while its blocks went to disk shows as exactly that. */
* of object in a different store. Counted where the BYTES are: in the store in host
* memory, or on disk alone. */
e["snapshots"] = s.snapshots;
e["snap_device"] = s.snap_device;
e["snap_host"] = s.snap_host;
e["snap_disk"] = s.snap_disk;
e["snap_bytes"] = s.snap_bytes;
e["resume_tokens"] = s.resume_tokens;
a.push_back(std::move(e));
dev += s.on_device; host += s.on_host; disk += s.on_disk;
sdev += s.snap_device; shost += s.snap_host; sdisk += s.snap_disk;
shost += s.snap_host; sdisk += s.snap_disk;
bytes += s.bytes;
}
o["sessions"] = std::move(a);
@@ -88,7 +87,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
* a server carrying long agent transcripts by more than an order of magnitude. The field
* names say so rather than pretending the sums are totals. */
o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } };
o["snapshots"] = { { "device", sdev }, { "host", shost }, { "disk", sdisk } };
o["snapshots"] = { { "host", shost }, { "disk", sdisk } };
o["bytes_sum_overlapping"] = bytes;
const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{};
/* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has
@@ -109,15 +108,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
{ "fetched", c.fetched } };
/* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every
* block it has and no snapshots at all looks identical in the block counters to one where
* tiering works -- and the difference is a full linear replay on every restored session.
* `starved` is the one to read when `to_host` stays at zero: it means the snapshot arena had
* no room, which --prefix-cache-host-mib fixes. */
o["snapshots_moved"] = { { "to_host", c.ck_to_host }, { "to_disk", c.ck_to_disk },
{ "promoted", c.ck_promoted }, { "fetched", c.ck_fetched },
{ "drops", c.ck_drops },
{ "starved", c.ck_starved }, { "bytes_each", c.ck_bytes },
* tiering works -- and the difference is a full linear replay on every restored session. */
o["snapshots_moved"] = { { "to_disk", c.ck_to_disk }, { "fetched", c.ck_fetched },
{ "drops", c.ck_drops }, { "bytes_each", c.ck_bytes },
{ "host_slots", c.ck_host_slots },
{ "disk_slots", c.ck_disk_slots } };
/* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */
o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 },
{ "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } };
/* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes
* travelled; this is the number that says a lookup then SERVED one. A hybrid server can move
* snapshots all day and still replay from token zero if the checkpoint the restore put back
@@ -170,6 +168,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
o["kv_bytes_used"] = (double)m.kv_bytes_used;
o["kv_bytes_total"] = (double)m.kv_bytes_total;
o["kv_bytes_carved"] = (double)m.kv_bytes_carved;
o["kv_tokens_max"] = m.kv_tokens_max;
o["prefix_hit_rate"] = m.prefix_hit_rate;
/* The leading indicator beside the lagging one: past ~75% kv utilisation the cache
* begins dropping prefixes the next turn wants, and the hit rate only falls once
@@ -1484,6 +1483,10 @@ function meter(host, cls, title, idx, split) {
const mKv = meter($("mem"), "meter", "KV cache", undefined, true);
const mKvSub = el("div", "ksub");
mKv.wrap.appendChild(mKvSub);
/* AND HOW FAR IT CAN GROW: every block of the carve, the ones lent to the expert slab taken
back -- which a request that needs them does, the same step. */
const mKvMax = el("div", "ksub");
mKv.wrap.appendChild(mKvMax);
const mPc = meter($("mem"), "meter", "Prefix hits");
/* `hot` is for a meter whose ceiling is a FAILURE -- KV utilisation near 100% preempts. A device
* VRAM bar near 100% is the engine doing its job, so it passes false and stays neutral. */
@@ -1729,7 +1732,8 @@ function update(s, dt) {
of the pool is not among them: it is the bar in the memory panel, and repeating it here cost
the line that says how much context the bytes are actually holding. */
$("m-kvdet").textContent = s.kv_bytes_total > 0
? "of " + hb(s.kv_bytes_total) + " · " + cnt3(s.kv_tokens_used) + " tok"
? "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
+ cnt3(s.kv_tokens_used) + " tok"
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
: "";
setMetric("accept", 100 * s.draft_accept,
@@ -1769,6 +1773,10 @@ function update(s, dt) {
mKvSub.textContent = s.kv_tokens_used > 0
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
: "";
mKvMax.textContent = s.kv_tokens_max > 0
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
+ " tok, with what the experts borrowed taken back"
: "";
mPc.v.textContent = pct(s.prefix_hit_rate); setBar(mPc.i, s.prefix_hit_rate, false);
/* ---- draft. The bar is the CONDITIONAL acceptance at that position; the reach row under the
+17 -5
View File
@@ -67,6 +67,11 @@ struct SchedMetrics {
int64_t kv_bytes_total = 0;
/* What the pool was carved to address, which an elastic pool may not be holding. */
int64_t kv_bytes_carved = 0;
/* THE MOST CONTEXT THE CACHE CAN HOLD: every block of its carve, the ones lent to the expert
* slab taken back. `kv_bytes_carved` is the same figure in bytes. The paged groups share one
* token axis, so it is the smallest of theirs; a windowed group is left out, because its carve
* bounds how far back a sequence keeps context rather than how much fits. */
int64_t kv_tokens_max = 0;
double prefix_hit_rate = 0.0; /* 0..1 */
/* Cumulative prefix-cache evictions. `prefix_hit_rate` falls only AFTER a prefix that
@@ -157,7 +162,7 @@ struct SessionStat {
* back and re-run every recurrent layer over its whole transcript -- which the hit rate will
* report as a hit. Zero everywhere on a model that has no recurrent state. */
int64_t snapshots = 0;
int64_t snap_device = 0, snap_host = 0, snap_disk = 0;
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
int64_t snap_bytes = 0;
/* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */
int64_t resume_tokens = 0;
@@ -264,11 +269,12 @@ public:
int64_t fetched = 0, ck_fetched = 0;
int64_t host_bytes = 0, disk_bytes = 0;
/* THE LINEAR HALF, MOVED. Separate counters because a hybrid server can move every block
* it has and no snapshots at all -- the arena too small, the device slots contended --
* and no block counter can tell that apart from tiering working. */
int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0;
* it has and no snapshots at all, and no block counter can tell that apart from tiering
* working. `ck_drops` is snapshots whose only copy was lost. */
int64_t ck_to_disk = 0, ck_drops = 0;
int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */
int64_t ck_host_slots = 0, ck_disk_slots = 0;
int64_t ck_host_slots = 0, ck_disk_slots = 0; /* the store's; the disk store's */
int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; /* IdleTiers::Stats */
/* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on
* and has had nothing to do reads the same as one that was never given a size, and the
* two call for opposite responses from whoever is looking. */
@@ -430,6 +436,8 @@ struct ParsedMessage {
std::string content;
std::string reasoning; /* "" unless the template supports reasoning */
std::vector<ToolCall> tool_calls;
/* The reply ended inside its last call: that call never closed, and is no call to run. */
bool open_call = false;
};
/* One increment of a reply that is being read as it is generated. What has been delivered is
@@ -458,6 +466,10 @@ public:
virtual void finish(std::vector<ReplyDelta>* out) = 0;
/* The whole reply, once finish() has run. */
virtual ParsedMessage message() const = 0;
/* Once finish() has run: the content with an open last call (ParsedMessage::open_call) read
* as the text it was written as -- the content before the call, then the call's own bytes
* from `reply`, the whole text fed. The content alone when no call is open. */
virtual std::string content_with_open_call(std::string_view reply) const = 0;
};
/* A request's reply format. Each choice opens its own reader, and a request that sent no tools
+58
View File
@@ -174,5 +174,63 @@ size_t json_stable_prefix(std::string_view s) {
return n;
}
bool json_quote_append(std::string& out, std::string_view s) {
static const char kHex[] = "0123456789abcdef";
const size_t mark = out.size();
out.reserve(mark + s.size() + 2);
out.push_back('"');
const unsigned char* p = (const unsigned char*)s.data();
const unsigned char* e = p + s.size();
const unsigned char* run = p; /* [run, p) is verified and goes out as it is */
while (p < e) {
const unsigned char c = *p;
if (c >= 0x80) {
/* Length, and the range the SECOND byte is restricted to, which is what rejects
* overlong forms, surrogates and anything past U+10FFFF without decoding. */
size_t len;
unsigned char lo = 0x80, hi = 0xBF;
if (c >= 0xC2 && c <= 0xDF) len = 2;
else if (c == 0xE0) { len = 3; lo = 0xA0; }
else if (c >= 0xE1 && c <= 0xEC) len = 3;
else if (c == 0xED) { len = 3; hi = 0x9F; }
else if (c >= 0xEE && c <= 0xEF) len = 3;
else if (c == 0xF0) { len = 4; lo = 0x90; }
else if (c >= 0xF1 && c <= 0xF3) len = 4;
else if (c == 0xF4) { len = 4; hi = 0x8F; }
else len = 0;
bool ok = len != 0 && (size_t)(e - p) >= len && p[1] >= lo && p[1] <= hi;
for (size_t k = 2; ok && k < len; ++k) ok = p[k] >= 0x80 && p[k] <= 0xBF;
if (!ok) {
out.resize(mark);
return false;
}
p += len;
continue;
}
if (c >= 0x20 && c != '"' && c != '\\') {
++p;
continue;
}
out.append((const char*)run, (size_t)(p - run));
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\t': out += "\\t"; break;
case '\n': out += "\\n"; break;
case '\f': out += "\\f"; break;
case '\r': out += "\\r"; break;
default: {
const char u[6] = { '\\', 'u', '0', '0', kHex[c >> 4], kHex[c & 15] };
out.append(u, 6);
}
}
run = ++p;
}
out.append((const char*)run, (size_t)(p - run));
out.push_back('"');
return true;
}
} /* namespace server */
} /* namespace rad */
+14
View File
@@ -12,11 +12,15 @@
* boundary: cutting a multi-byte code point in half turns one delta into mojibake and the
* next into a decode error.
*
* And one way to write it: `json_quote_append`, a string literal exactly as nlohmann writes one,
* for the chunks that carry a delta.
*
* This is a scanner, not a parser: it allocates nothing and builds no DOM.
*/
#pragma once
#include <cstddef>
#include <string>
#include <string_view>
namespace rad {
@@ -36,5 +40,15 @@ size_t utf8_trunc(std::string_view s);
* escape, and the class of bug that produces is unbisectable from the server side. */
size_t json_stable_prefix(std::string_view s);
/* Append `s` to `out` as a JSON string literal, quotes included, byte for byte as nlohmann's
* dump() writes one: `\b \t \n \f \r \" \\` as two characters, every other control character
* as `\u00xx` in lowercase hex, and everything else -- DEL and non-ASCII included -- as itself.
* Returns false, with `out` as it was, when `s` is not well-formed UTF-8 (overlong forms,
* surrogates and code points past U+10FFFF included), which nlohmann refuses rather than writes.
*
* A streamed chunk is written with this around a fixed frame instead of through a DOM: building
* and dumping a tree per token cost more than every other part of the token's host work. */
bool json_quote_append(std::string& out, std::string_view s);
} /* namespace server */
} /* namespace rad */
+8
View File
@@ -130,6 +130,8 @@ void Metrics::sample(const SchedMetrics& m) {
g_waiting_.set((double)m.waiting);
g_preempted_.set((double)m.preempted);
g_kv_util_.set(m.kv_util);
g_kv_max_tokens_.set((double)m.kv_tokens_max);
g_kv_max_bytes_.set((double)m.kv_bytes_carved);
g_prefix_hit_.set(m.prefix_hit_rate);
g_prefill_tps_.set(m.prefill_tps);
g_decode_tps_.set(m.decode_tps);
@@ -239,6 +241,12 @@ std::string Metrics::render() const {
"GPU KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
w.gauge("vllm:kv_cache_usage_perc",
"KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
w.gauge("radiance:kv_cache_max_tokens",
"Tokens of context the KV cache holds with every block it lends the experts taken "
"back.", L, g_kv_max_tokens_.get());
w.gauge("radiance:kv_cache_max_bytes",
"VRAM the KV cache holds with every block it lends the experts taken back, one card.",
L, g_kv_max_bytes_.get());
w.gauge("vllm:gpu_prefix_cache_hit_rate",
"GPU prefix cache block hit rate.", L, g_prefix_hit_.get());
+1
View File
@@ -112,6 +112,7 @@ private:
std::string labels_; /* {model_name="...",engine="0"} */
Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_;
Gauge g_kv_max_tokens_, g_kv_max_bytes_;
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
Gauge queue_depth_;
/* The per-position draft hazard, kept as plain gauges because that is what it is: a
+61 -29
View File
@@ -1962,6 +1962,27 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const
return sse_event(o.dump());
}
void ChatDeltaStream::delta_open(std::string& out) {
/* Built from nlohmann's own serialisation of each field, on first use rather than in the
* constructor, so a field nlohmann refuses throws where chunk() would have. */
if (head_.empty())
head_ = "data: {\"id\":" + json(id_).dump() +
",\"object\":\"chat.completion.chunk\",\"created\":" + json(created_).dump() +
",\"model\":" + json(model_).dump() + ",\"choices\":[{\"index\":" +
json(index_).dump() + ",\"delta\":";
out += head_;
}
void ChatDeltaStream::delta_close(std::string& out) const {
out += ",\"finish_reason\":null}]}\n\n";
}
/* Text that is not well-formed UTF-8 goes to nlohmann, which refuses it with the exception the
* tree in chunk() raises for it. */
void ChatDeltaStream::quote(std::string& out, std::string_view s) {
if (!json_quote_append(out, s)) out += json(std::string(s)).dump();
}
std::string ChatDeltaStream::first_chunk() {
json d;
d["role"] = "assistant";
@@ -1976,49 +1997,53 @@ std::string ChatDeltaStream::first_chunk() {
std::string ChatDeltaStream::emit(const std::vector<ReplyDelta>& ev) {
std::string out;
for (const ReplyDelta& d : ev) {
json delta;
switch (d.kind) {
case ReplyDelta::Reasoning:
if (d.text.empty()) continue;
last_.reasoning += d.text;
delta["reasoning_content"] = d.text;
delta_open(out);
out += "{\"reasoning_content\":";
quote(out, d.text);
out += '}';
break;
case ReplyDelta::Content:
if (d.text.empty()) continue;
last_.content += d.text;
delta["content"] = d.text;
delta_open(out);
out += "{\"content\":";
quote(out, d.text);
out += '}';
break;
case ReplyDelta::CallBegin: {
ToolCall tc;
tc.id = random_id("call_");
tc.name = d.text;
last_.tool_calls.push_back(tc);
json f;
f["name"] = tc.name;
f["arguments"] = "";
json e;
e["index"] = (int64_t)d.call;
e["id"] = tc.id;
e["type"] = "function";
e["function"] = std::move(f);
delta["tool_calls"] = json::array({e});
delta_open(out);
out += "{\"tool_calls\":[{\"index\":";
out += std::to_string((int64_t)d.call);
out += ",\"id\":";
quote(out, tc.id);
out += ",\"type\":\"function\",\"function\":{\"name\":";
quote(out, tc.name);
out += ",\"arguments\":\"\"}}]}";
last_.tool_calls.push_back(std::move(tc));
break;
}
case ReplyDelta::CallArgs: {
if (d.text.empty() || d.call >= last_.tool_calls.size()) continue;
last_.tool_calls[d.call].arguments += d.text;
json f;
f["arguments"] = d.text;
json e;
e["index"] = (int64_t)d.call;
e["function"] = std::move(f);
delta["tool_calls"] = json::array({e});
delta_open(out);
out += "{\"tool_calls\":[{\"index\":";
out += std::to_string((int64_t)d.call);
out += ",\"function\":{\"arguments\":";
quote(out, d.text);
out += "}}]}";
break;
}
case ReplyDelta::CallEnd:
continue;
}
out += chunk(std::move(delta), nullptr);
delta_close(out);
}
return out;
}
@@ -2030,9 +2055,11 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) {
/* Nothing to parse: the text is the answer, as it arrives. */
if (!appended.empty()) {
last_.content.append(appended);
json d;
d["content"] = std::string(appended);
out = chunk(std::move(d), nullptr);
delta_open(out);
out += "{\"content\":";
quote(out, appended);
out += '}';
delta_close(out);
}
finished_ = is_final;
return out;
@@ -2053,14 +2080,19 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) {
return out;
}
bool calls_complete(const ParsedMessage& m) {
if (m.tool_calls.empty() || m.open_call) return false;
for (const auto& tc : m.tool_calls)
if (tc.name.empty() || !json_complete(tc.arguments)) return false;
return true;
}
Finish ChatDeltaStream::adjusted_finish(Finish f) const {
if (f != Finish::Stop && f != Finish::StopString) return f;
if (last_.tool_calls.empty()) return f;
/* Only claim tool_calls if every call's arguments actually parse. A truncated arguments
* object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h). */
for (const auto& tc : last_.tool_calls)
if (tc.name.empty() || !json_complete(tc.arguments)) return f;
return Finish::ToolCalls;
/* Only claim tool_calls if every call closed and its arguments parse. A truncated arguments
* object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h).
* The deltas of an open call have gone out already; the finish reason says not to run it. */
return calls_complete(last_) ? Finish::ToolCalls : f;
}
std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t) {
+13
View File
@@ -290,6 +290,11 @@ std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
/* The `timings` object, for a stream's final chunks. */
json timings_json(const TimingsOut& t);
/* Whether a parsed reply's calls are all calls a client can run: none left open, each named,
* each one's arguments one JSON value (json_partial.h). A reply is answered `tool_calls` by this
* alone, streamed or not. */
bool calls_complete(const ParsedMessage& m);
/* ================================================================== streaming
*
* One of these per choice. It feeds the generated text to the choice's reply reader as it grows
@@ -323,6 +328,14 @@ private:
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
std::string emit(const std::vector<ReplyDelta>& ev);
/* 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;
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_;
int64_t created_;
+12 -9
View File
@@ -644,17 +644,20 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
rd->feed(g.text, nullptr);
rd->finish(nullptr);
c.msg = rd->message();
/* Only claim a tool call when the arguments actually parse (json_partial.h). */
bool complete = r.parse_tools && !c.msg.tool_calls.empty();
for (const auto& tc : c.msg.tool_calls)
if (tc.name.empty() || !json_complete(tc.arguments)) complete = false;
/* 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;
else if (!c.msg.tool_calls.empty() && !complete) {
/* A half-finished call is content, not a call. The client gets what the model
* actually produced instead of a tool invocation with truncated arguments. */
c.msg.tool_calls.clear();
c.msg.content = g.text;
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;