From 6c80bce3598789241f32cf983bff24ebe65fa0a9 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:46:30 +0000 Subject: [PATCH 1/4] server: logprobs with tools, stop strings, reasoning and the Responses API Chat completions serve logprobs with tools, stop strings, structured output and a thinking budget, from the rows the engine already returns: prose, reasoning and each tool call get their own entries, a stop string trims the entries with the text, and a token the text shows only part of keeps its row with the bytes it shows and its token_id. A stream without tools sends each entry with the chunk that completes its token; with tools the entries follow once the calls are parsed. The Responses API carries them in its output items and delta events. Text and tokens are the same with logprobs on or off. Fixes #3186 --- docs/api.md | 50 ++-- zig/build/server.zig | 4 +- zig/src/server/chat.zig | 6 +- zig/src/server/chat_generation.zig | 47 +++- zig/src/server/logprob_parts.zig | 283 ++++++++++++++++++++++ zig/src/server/logprob_parts_test.zig | 313 +++++++++++++++++++++++++ zig/src/server/logprobs.zig | 116 ++++----- zig/src/server/logprobs_test.zig | 51 ++-- zig/src/server/openai.zig | 37 +-- zig/src/server/response_logprobs.zig | 38 +++ zig/src/server/responses.zig | 92 ++++++-- zig/src/server/responses_translate.zig | 20 +- zig/src/server/root.zig | 1 + 13 files changed, 895 insertions(+), 163 deletions(-) create mode 100644 zig/src/server/logprob_parts.zig create mode 100644 zig/src/server/logprob_parts_test.zig create mode 100644 zig/src/server/response_logprobs.zig diff --git a/docs/api.md b/docs/api.md index 0092df81dad..1a9358715af 100644 --- a/docs/api.md +++ b/docs/api.md @@ -391,19 +391,36 @@ delete runs gets 503, an id that is not a number 400, and an id the graph does n `modalities` must be absent or `["text"]`, and a truthy top-level `image`, `images`, `image_url`, `input_image`, `audio`, `input_audio`, `video` or `video_url` key is refused: this server accepts and produces text only. -The native CUDA engine (Nemotron 3.5 Lightning) supports `logprobs: true` and `top_logprobs` from 0 through 20 on -`/v1/chat/completions`, streamed or not, without tools, stop strings, structured output or a thinking budget. Each -reply token has its `token`, `logprob`, `bytes` and requested `top_logprobs` in `choices[0].logprobs.content`; a -stream sends each row with the chunk whose `delta.content` completes that token's text, so the rows joined over the -chunks are the whole reply's. Probabilities describe the raw target-model distribution at temperature 1, before -temperature, top-k or top-p sampling filters, including when generation is greedy, and are the same with drafts on or -`"draft": false`. With thinking on, the rows cover the answer only, as `content` does: none for the reasoning, -`` or the newlines after it, so the first row is the answer's first token, and a reply cut inside its -reasoning has none. Alternatives are tokenizer tokens and may include leading spaces; `bytes` preserves partial UTF-8 -sequences. `/v1/completions` takes the legacy `logprobs`, an integer from 0 through 20 alternatives, and answers in -the legacy form, streamed or not: `tokens`, `token_logprobs`, `top_logprobs` (each alternative's text to its logprob) -and `text_offset` (each token's first character in the completion, counting each token's own text). Other engines, -the Responses route and the request modes above return HTTP 400 when probabilities are requested. +Engines that advertise `capabilities.logprobs` and give each token's exact bytes accept `logprobs: true` and +`top_logprobs` from 0 through 20 on `/v1/chat/completions`, streamed or not, with tools, stop strings, structured +output, reasoning and a thinking budget. Asking for them changes nothing else: the prompt, the sampled tokens and the +text are the same with them on or off. Probabilities describe the raw target-model distribution at temperature 1, +before temperature, top-k or top-p sampling filters, including when generation is greedy, and are the same with drafts +on or `"draft": false`. Alternatives are tokenizer tokens and may include leading spaces; `bytes` preserves partial +UTF-8 sequences. + +`choices[0].logprobs.content` has an entry for each token of the reply's `content` (`token`, `logprob`, `bytes` and +the requested `top_logprobs`), and the entries' `bytes` joined spell `content`. With thinking on, the reasoning's +tokens are in `logprobs.reasoning_content`; with tools, each call has an `{index, content}` group in +`logprobs.tool_calls` with the entries of the markup the model wrote for it (not the arguments JSON the reply returns; +a closer the server adds to a cut call has none). Thinking markers, the whitespace the text drops, a stop string and +the text after it have no entries. A token the text shows only part of, such as one a stop string ends inside, shows +the kept bytes in `token` and `bytes` and its id in `token_id`, with its own `logprob` and alternatives. + +A stream sends each entry with the chunk whose text completes that token, reasoning entries before the answer's first +text; with tools offered, the entries come in one chunk before the finishing one, once the calls are parsed. The +entries joined over the chunks are the whole reply's. `/v1/completions` takes the legacy `logprobs`, an integer from 0 +through 20 alternatives, and answers in the legacy form, streamed or not: `tokens`, `token_logprobs`, `top_logprobs` +(each alternative's text to its logprob) and `text_offset` (each token's first character in the completion, counting +each token's own text). Other engines return HTTP 400 when probabilities are requested. + +The Responses API gives the same entries for `top_logprobs` (0 through 20) or the `include` name +`message.output_text.logprobs`: in each `output_text` part's `logprobs`, and as extensions in `reasoning_text` parts +and `function_call` items. A stream sends them in the `response.output_text.delta` and +`response.reasoning_text.delta` events; with tools offered they come once the calls are parsed, as deltas with empty +text, and each item's done events wait for them. `include` alone on an engine without logprobs answers without them; +`top_logprobs` there returns HTTP 400. + Nonstreamed `/v1/completions` also takes vLLM's `prompt_logprobs`, an integer from 0 through 20, on the same engine and on GLM-5.3-Flash's CUDA engine. `choices[0].prompt_logprobs` has one entry per prompt token: `null` for the first, then an object keyed by token id @@ -674,7 +691,7 @@ thinking on they start after the think end. HTTP 400 comes before any token for a malformed field, a grammar xgrammar cannot compile (with xgrammar's reason), a server without xgrammar (with the install command; on the native server, a server that cannot load `libtfgrammar`), -a grammar sent with `tool_choice: "required"` or a named function, and `logprobs` with a grammar or tools. A reply whose +a grammar sent with `tool_choice: "required"` or a named function. A reply whose grammar fails while decoding ends with HTTP 500 (an error event when streaming); the other requests go on. ## Reasoning @@ -1269,10 +1286,11 @@ prompt cache resumes the shared prefix as it does for chat. `store: false` keeps response. HTTP 400 refuses what this server does not run: built-in tools (web search, file search, computer use and the -others), `background`, `conversation`, `prompt` templates, `context_management`, `truncation: "auto"`, `top_logprobs`, file IDs and +others), `background`, `conversation`, `prompt` templates, `context_management`, `truncation: "auto"`, file IDs and remote file URLs (`input_file` parts with inline `file_data` run on a model started with `--vision --vision-pdf`), `item_reference` items, encrypted reasoning items, and a `previous_response_id` that is not stored. -`include` takes a list of OpenAI's names, which the server accepts and ignores (it has nothing to add for them): +`include` takes a list of OpenAI's names. `message.output_text.logprobs` asks for logprobs where the engine has them +(see the chat section's logprobs); the server has nothing to add for the others: `code_interpreter_call.outputs`, `computer_call_output.output.image_url`, `file_search_call.results`, `message.input_image.image_url`, `message.output_text.logprobs`, `reasoning.encrypted_content`, `web_search_call.action.sources` and `web_search_call.results`. Any other name, or a value that is not a list of diff --git a/zig/build/server.zig b/zig/build/server.zig index 3af132fafa2..4b90243c750 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -77,8 +77,8 @@ pub fn toolHostTests(b: *std.Build, parser: *std.Build.Module, server: *std.Buil b.step("test-thinking-tail-host", "Finished calls before a think close, whole and streamed without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"thinking tail:"} })).step); const environment = b.step("test-environment-report-host", "Named environment discovery, new registry rows and startup reporting"); environment.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "capability audit: environment", "stable profile:", "profile line:" } })).step); - const logprobs = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"logprobs_test"} })); - b.step("test-logprob-offers-host", "Logprob request capability refusals before engine submission").dependOn(&logprobs.step); + const logprobs = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "logprobs_test", "logprob combinations:" } })); + b.step("test-logprob-offers-host", "Logprob refusals before submission, and entries with tools, stops, reasoning and Responses").dependOn(&logprobs.step); const limits = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"limit pins:"} })); b.step("test-limit-pins-host", "Documented request and flag limits pinned at their bounds").dependOn(&limits.step); const deps = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"flag deps:"} })); diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 36f37f1ac7d..2b44473aea3 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -77,8 +77,10 @@ pub const Reply = struct { /// The template switches the prompt was rendered with (the next turn's prefill renders with them too). thinking: bool = false, effort: ?[]const u8 = null, - /// ``choices[0].logprobs`` (``{"content": [...]}``) for a request that asked; null otherwise. + /// ``choices[0].logprobs`` (prose, reasoning and call entries) for a request that asked; null otherwise. logprobs: ?Value = null, + /// The tokens and target rows ``logprobs`` are projected from, once the route's tool policy is final. + probability_rows: ?@import("logprob_parts.zig").Capture = null, /// ``choices[0].prompt_logprobs`` (vLLM's form) for a request that asked; null otherwise. prompt_logprobs: ?Value = null, loop_stop: ?u32 = null, // the loop period when --loop-guard-stop ended the reply in its reasoning @@ -218,7 +220,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa // The answer quota is separate only on engines that enforce it. if (srv.info.capability(.answer_limit)) @import("thinking_reserve.zig").apply(&request, srv.config.thinking_reserve, if (window > 0) window - n else std.math.maxInt(u32), srv.think_close_end); } - if (input.logprobs) |count| request.logprobs = try @import("logprobs.zig").admit(srv, cx, reasoning, request.think_budget, count); + request.logprobs = input.logprobs; request.prompt_logprobs = input.prompt_logprobs; if (try engine_refusal.of(srv.engine, cx, &request)) |message| return cx.refuse(message); return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames }; diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index dc65688ad41..bbce5e35334 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -22,6 +22,14 @@ const nowNs = clock.nowNs; const seconds = clock.seconds; const deltaOf = reply_text.deltaOf; +/// One chunk's logprobs: ``content`` always, as OpenAI clients read it, and ``key``'s entries. +fn rowsOf(a: Allocator, key: []const u8, entries: Value) Allocator.Error!Value { + const o = try json.newObject(a); + try o.put(a, "content", .{ .array = &.{} }); + try o.put(a, key, entries); + return .{ .object = o }; +} + pub const Generation = struct { srv: *Server, a: Allocator, @@ -55,7 +63,7 @@ pub const Generation = struct { engine_done: bool = false, consumed: usize = 0, chunk_index: usize = 0, - lp: ?@import("logprobs.zig").Stream = null, // the request asked for logprobs: its rows, copied with each round + lp: ?@import("logprob_parts.zig").Live = null, // the request asked for logprobs: its rows, copied with each round loop_stop: bool = false, // --loop-guard-stop: the engine ends the reply where the loop guard fires fn eos(g: *const Generation, t: u32) bool { @@ -107,21 +115,21 @@ pub const Generation = struct { } try fresh.append(g.a, t); } + const live = g.liveRows(); + if (live) |l| try l.add(g.srv, g.a, fresh.items); const all = try g.visible.extend(g.a, g.srv.text, reply_text.decodeText, fresh.items); if (g.visible.pending()) return; // a character still split across tokens if (g.srv.text.vtable.format == .kimi) return @import("chat_kimi.zig").stream(g, sink); const raw_visible = g.stops.visible(all, true); const text = try @import("tool_minimax.zig").dsml(g.a, raw_visible, g.tools); // MiniMax-M3's calls as DSML var answer = text; + var thought: []const u8 = ""; if (g.thinking) { const original_close = try g.visible.closeOf(g.a, reply_text.decodeText, g.srv.text, g.srv.close_id); const close = try @import("tool_minimax.zig").closeAfterRewrite(g.a, raw_visible, g.tools, original_close); const split = try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); - const piece = g.streamed_reasoning.after(reply_text.pyStrip(split.reasoning), true); // the whole reply strips it - if (piece.len > 0) { - try g.streamed_reasoning.set(g.a, reply_text.pyStrip(split.reasoning), piece); - try g.emit(sink, try deltaOf(g.a, "reasoning_content", piece)); - } + thought = g.streamed_reasoning.after(reply_text.pyStrip(split.reasoning), true); // the whole reply strips it + if (thought.len > 0) try g.streamed_reasoning.set(g.a, reply_text.pyStrip(split.reasoning), thought); answer = split.answer; } answer = try tool_lfm2.dsml(g.a, answer, g.tools, false); // the answer only, so a call the reasoning mentions is not made @@ -129,9 +137,20 @@ pub const Generation = struct { const vis = reply_text.heldBack(if (g.srv.info.capability(.reasoning)) reply_text.streamingVisible(shown) else shown, g.calls != null); const copied = @intFromPtr(vis.ptr) >= @intFromPtr(g.hidden.items.ptr) and @intFromPtr(vis.ptr) <= @intFromPtr(g.hidden.items.ptr) + g.hidden.items.len; const delta = g.streamed.after(vis, !copied); - if (delta.len > 0) { - try g.streamed.set(g.a, vis, delta); - try g.emit(sink, if (g.lp) |*l| (try l.delta(g.srv, g.a, g.thinking, g.ignore_eos, g.collected.items, delta, g.streamed.text.items.len, false)).? else .{ .string = delta }); + if (delta.len > 0) try g.streamed.set(g.a, vis, delta); + // each chunk carries the entries its text settles: reasoning ones before the answer's first text + const rows = if (live) |l| try l.settle(g.srv, g.a, g.collected.items[0..l.spelled.ends.items.len], g.thinking, g.stops, g.streamed.text.items, g.streamed_reasoning.text.items) else null; + const thought_rows = if (rows) |r| r.get("reasoning_content") else null; + if (thought.len > 0 or thought_rows != null) { + const d: Value = if (thought.len > 0) try deltaOf(g.a, "reasoning_content", thought) else .{ .object = try json.newObject(g.a) }; + if (thought_rows) |t| try d.object.put(g.a, "logprobs", try rowsOf(g.a, "reasoning_content", t)); + try g.emit(sink, d); + } + const prose_rows: []Value = if (rows) |r| r.get("content").?.array else &.{}; + if (delta.len > 0 or prose_rows.len > 0) { + const d: Value = if (prose_rows.len > 0) try deltaOf(g.a, "content", delta) else .{ .string = delta }; + if (prose_rows.len > 0) try d.object.put(g.a, "logprobs", try rowsOf(g.a, "content", .{ .array = prose_rows })); + try g.emit(sink, d); } if (g.calls) |*c| { var out: std.ArrayList(Value) = .empty; @@ -140,6 +159,12 @@ pub const Generation = struct { } } + /// Logprob state when chunks carry their own entries: without tools, no call can claim streamed text. + fn liveRows(g: *Generation) ?*@import("logprob_parts.zig").Live { + if (g.tools.len > 0) return null; + return if (g.lp) |*l| l else null; + } + pub fn emit(g: *Generation, sink: Sink, delta: Value) Failure!void { sink.call(sink.ctx, delta) catch { g.cancel(); @@ -269,7 +294,7 @@ pub const Generation = struct { const shown = if (g.calls != null) try tool_stream.endProse(a, content, if (g.thinking) content else text, g.tools, reason, g.single) else content; const sent = g.streamed.text.items; const rest = if (std.mem.startsWith(u8, shown, sent) and shown.len > sent.len) shown[sent.len..] else ""; - if (g.lp) |*l| (if (try l.delta(g.srv, a, g.thinking, g.ignore_eos, g.collected.items, rest, shown.len, true)) |d| try g.emit(sink, d)) else if (rest.len > 0) try g.emit(sink, .{ .string = rest }); + if (rest.len > 0) try g.emit(sink, .{ .string = rest }); if (g.calls) |*c| if (close.len > 0 or std.mem.eql(u8, reason, "length")) { // the streamer reads the closers as markup the model wrote, so the call ends with the same deltas var out: std.ArrayList(Value) = .empty; @@ -344,7 +369,7 @@ pub const Generation = struct { .speculative = .{ .object = spec }, .thinking = thinking, .effort = effort, - .logprobs = if (g.lp) |l| try @import("logprobs.zig").value(g.srv, cx, a, g.thinking, content_tokens, l.rows.items) else null, + .probability_rows = if (g.lp) |l| .{ .tokens = content_tokens, .rows = l.rows.items, .thinking = g.thinking, .stops = g.stops, .closer = close, .sent = l.sent } else null, .prompt_logprobs = if (m.prompt_rows) |r| try @import("logprobs.zig").promptValue(g.srv, a, r) else null, .loop_stop = stopped, }; diff --git a/zig/src/server/logprob_parts.zig b/zig/src/server/logprob_parts.zig new file mode 100644 index 00000000000..52d3de2997a --- /dev/null +++ b/zig/src/server/logprob_parts.zig @@ -0,0 +1,283 @@ +//! Target rows projected onto a reply's prose, reasoning and tool envelopes: whole, or as a stream settles them. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const rt = @import("reply_text.zig"); +const lp = @import("logprobs.zig"); +const tp = @import("tool_parse.zig"); +const mm = @import("tool_minimax.zig"); +const errors = @import("errors.zig"); +const Server = @import("server.zig").Server; +const Cx = errors.Cx; +const A = std.mem.Allocator; +const V = json.Value; +const Error = error{ Failed, OutOfMemory }; + +/// Entries a stream already sent with its text, by channel. +pub const Sent = struct { content: usize = 0, reasoning: usize = 0 }; + +/// A finished reply's tokens and rows, projected once its text and calls are final; `closer` ends a call EOS cut. +pub const Capture = struct { tokens: []const u32, rows: []const api.LogprobRow, thinking: bool, stops: rt.Stops, closer: []const u8 = "", sent: Sent = .{} }; + +const Channel = enum { content, reasoning, tool, dropped }; +/// Visible bytes of one channel; an open range may still grow while the reply streams. +const Range = struct { start: usize, end: usize, channel: Channel, index: usize = 0, open: bool = false }; +/// One entry: token `token` shows bytes [lo, hi); settled once later text cannot change it. +const Piece = struct { token: usize, lo: usize, hi: usize, settled: bool }; +/// What the reply shows: its prose, reasoning and, for a whole reply, the calls the tool policy kept. +const Shown = struct { content: []const u8, reasoning: ?[]const u8, tools: []const V = &.{}, calls: ?usize = null }; + +/// Each token's exact bytes, joined, and where each token ends. +const Spelled = struct { + raw: std.ArrayList(u8) = .empty, + ends: std.ArrayList(usize) = .empty, + + fn add(s: *Spelled, srv: *Server, a: A, tokens: []const u32) Error!void { + for (tokens) |id| { + try s.raw.appendSlice(a, (try srv.text.tokenBytes(a, id)) orelse return error.Failed); + try s.ends.append(a, s.raw.items.len); + } + } + + fn from(s: *const Spelled, i: usize) usize { + return if (i == 0) 0 else s.ends.items[i - 1]; + } +}; + +/// A streamed reply's rows and bytes, and the entries its chunks already carried. +pub const Live = struct { + rows: std.ArrayList(api.LogprobRow) = .empty, // copied with each round's tokens + spelled: Spelled = .{}, + sent: Sent = .{}, + + pub fn add(l: *Live, srv: *Server, a: A, tokens: []const u32) Error!void { + return l.spelled.add(srv, a, tokens); + } + + /// ``{content, reasoning_content}`` entries the streamed text now settles; null when there are none. + pub fn settle(l: *Live, srv: *Server, a: A, tokens: []const u32, thinking: bool, stops: rt.Stops, content: []const u8, reasoning: []const u8) Error!?V { + const visible = stops.visible(l.spelled.raw.items, false); + const ranges = try layout(srv, a, visible, tokens, thinking, false, .{ .content = content, .reasoning = reasoning }); + const prose = try fresh(srv, a, &l.spelled, tokens, l.rows.items, ranges, .content, &l.sent.content); + const thought = try fresh(srv, a, &l.spelled, tokens, l.rows.items, ranges, .reasoning, &l.sent.reasoning); + if (prose.len == 0 and thought.len == 0) return null; + const out = try json.newObject(a); + try out.put(a, "content", .{ .array = prose }); + if (thought.len > 0) try out.put(a, "reasoning_content", .{ .array = thought }); + return .{ .object = out }; + } +}; + +/// The newly settled entries of one channel past `sent`, which grows by their count. +fn fresh(srv: *Server, a: A, s: *const Spelled, tokens: []const u32, rows: []const api.LogprobRow, ranges: []const Range, channel: Channel, sent: *usize) Error![]V { + const all = try pieces(a, s, ranges, channel, 0); + var end = sent.*; + while (end < all.len and all[end].settled) end += 1; + if (end <= sent.*) return &.{}; + const out = try values(srv, a, s, tokens, rows, all[sent.*..end]); + sent.* = end; + return out; +} + +/// ``choices[0].logprobs``: prose in ``content``, ``reasoning_content``, and one ``{index, content}`` group a call. +pub fn project(srv: *Server, cx: *Cx, c: Capture, content: []const u8, reasoning: ?[]const u8, tools: []const V, calls: ?[]V) errors.Refused!V { + const a = cx.a; + if (c.rows.len < c.tokens.len) return cx.other("the engine gave fewer logprob rows than reply tokens"); + return whole(srv, a, c, .{ .content = content, .reasoning = reasoning, .tools = tools, .calls = if (calls) |list| list.len else null }) catch |e| switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Failed => cx.other("the logprob rows are out of step with the reply's tokens, or a token has no exact bytes"), + }; +} + +fn whole(srv: *Server, a: A, c: Capture, shown: Shown) Error!V { + var s: Spelled = .{}; + try s.add(srv, a, c.tokens); + const visible = c.stops.visible(s.raw.items, false); + // the reply's text splits with the closer it was given, as chat_generation's finish splits it + const text = if (c.closer.len > 0) try std.mem.concat(a, u8, &.{ visible, c.closer }) else visible; + const ranges = try layout(srv, a, text, c.tokens, c.thinking, true, shown); + const out = try json.newObject(a); + try out.put(a, "content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .content, 0)) }); + if (shown.reasoning != null or c.thinking) try out.put(a, "reasoning_content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .reasoning, 0)) }); + const count = shown.calls orelse return .{ .object = out }; + const groups = try a.alloc(V, count); + for (groups, 0..) |*slot, i| { + const o = try json.newObject(a); + try o.put(a, "index", try json.intValue(a, i)); + try o.put(a, "content", .{ .array = try values(srv, a, &s, c.tokens, c.rows, try pieces(a, &s, ranges, .tool, i)) }); + slot.* = .{ .object = o }; + } + try out.put(a, "tool_calls", .{ .array = groups }); + return .{ .object = out }; +} + +/// A streamed reply's last logprobs: the whole reply's entries past those its chunks carried; null when none are left. +pub fn rest(a: A, rows: V, sent: Sent) A.Error!?V { + const out = try json.newObject(a); + var left = false; + for ([_]struct { []const u8, usize }{ .{ "content", sent.content }, .{ "reasoning_content", sent.reasoning } }) |key| { + const list = (rows.get(key[0]) orelse continue).items() orelse continue; + const tail = list[@min(key[1], list.len)..]; + left = left or tail.len > 0; + if (tail.len > 0 or std.mem.eql(u8, key[0], "content")) try out.put(a, key[0], .{ .array = tail }); + } + if (rows.get("tool_calls")) |groups| { + try out.put(a, "tool_calls", groups); + left = true; + } + return if (left) .{ .object = out } else null; +} + +fn values(srv: *Server, a: A, s: *const Spelled, tokens: []const u32, rows: []const api.LogprobRow, list: []const Piece) Error![]V { + const out = try a.alloc(V, list.len); + for (list, out) |p, *slot| { + const cropped = p.lo != s.from(p.token) or p.hi != s.ends.items[p.token]; + slot.* = try lp.rowValue(srv, a, tokens[p.token], rows[p.token], s.raw.items[p.lo..p.hi], cropped); + } + return out; +} + +/// One channel's entries in token order: each token's overlap with each of the channel's ranges. +fn pieces(a: A, s: *const Spelled, ranges: []const Range, channel: Channel, index: usize) A.Error![]Piece { + var out: std.ArrayList(Piece) = .empty; + var i: usize = 0; + for (ranges) |r| { + if (r.channel != channel or r.index != index) continue; + while (i < s.ends.items.len and s.ends.items[i] <= r.start) i += 1; + var j = i; + while (j < s.ends.items.len and s.from(j) < r.end) : (j += 1) { + const lo = @max(s.from(j), r.start); + const hi = @min(s.ends.items[j], r.end); + if (lo < hi) try out.append(a, .{ .token = j, .lo = lo, .hi = hi, .settled = !r.open or hi == s.ends.items[j] }); + } + } + return out.items; +} + +/// Where `part` lies in `whole` when it is a slice of it. +fn offset(all: []const u8, part: []const u8) ?usize { + const at = @intFromPtr(part.ptr); + const base = @intFromPtr(all.ptr); + return if (part.len > 0 and at >= base and at + part.len <= base + all.len) at - base else null; +} + +/// The ranges of each channel in the visible text; a reply still streaming (`finished` false) leaves growing ones open. +fn layout(srv: *Server, a: A, visible: []const u8, tokens: []const u32, thinking: bool, finished: bool, shown: Shown) A.Error![]Range { + var ranges: std.ArrayList(Range) = .empty; + var answer_at: usize = 0; + var prose_end: usize = visible.len; // stray prose before a think block ends where the block starts + var resume_at: usize = visible.len; + var reasoning_from: usize = 0; + var closed = true; + if (thinking) { + const m = srv.markers; + const close = try rt.closeWhere(a, rt.decodeText, srv.text, tokens, srv.close_id); + const split = try rt.splitThinkingAt(a, visible, finished, m, close); + const seen = switch (close) { + .token => true, + .spelled => rt.findTag(visible, 0, m.close) != null, + .pending => false, + }; + closed = finished or (seen and split.answer.len > 0); + reasoning_from = offset(visible, split.reasoning) orelse 0; + answer_at = offset(visible, split.answer) orelse visible.len; + if (split.answer.len > 0 and answer_at == visible.len) { + // the answer joins prose written before the block to the text after its close + const open_at = rt.findTag(visible, 0, m.open) orelse 0; + const stray = open_at - rt.partialTag(visible[0..open_at], m.open); + answer_at = 0; + prose_end = stray; + resume_at = visible.len -| (split.answer.len -| stray); + } + } + if (shown.reasoning) |r| if (r.len > 0) { + const at = std.mem.indexOfPos(u8, visible, reasoning_from, r) orelse visible.len; + if (at < visible.len) try ranges.append(a, .{ .start = at, .end = at + r.len, .channel = .reasoning, .open = !closed }); + }; + const calls_at = if (prose_end < visible.len) resume_at else answer_at; + if (shown.calls) |count| if (shown.tools.len > 0) try toolRanges(a, visible[calls_at..], shown.tools, count, calls_at, &ranges); + const held = ranges.items.len; + var cursor = answer_at; + var wanted: usize = 0; + while (wanted < shown.content.len and cursor < visible.len) { + if (cursor == prose_end) cursor = @max(cursor, resume_at); + if (cursor >= visible.len) break; + if (heldBy(ranges.items[0..held], cursor)) |end| { + cursor = end; + continue; + } + if (visible[cursor] != shown.content[wanted]) { + cursor += 1; + continue; + } + const start = cursor; + while (wanted < shown.content.len and cursor < visible.len and cursor != prose_end and visible[cursor] == shown.content[wanted] and heldBy(ranges.items[0..held], cursor) == null) { + wanted += 1; + cursor += 1; + } + try ranges.append(a, .{ .start = start, .end = cursor, .channel = .content }); + } + if (!finished and ranges.items.len > held) ranges.items[ranges.items.len - 1].open = true; + return ranges.items; +} + +/// The end of the reasoning, call or dropped range holding `at`, which prose matching skips. +fn heldBy(ranges: []const Range, at: usize) ?usize { + for (ranges) |r| if (at >= r.start and at < r.end) return r.end; + return null; +} + +/// Ranges of the calls `answer` makes: the first `count` are the reply's calls, those past the policy are dropped. +fn toolRanges(a: A, answer: []const u8, tools: []const V, count: usize, offset_at: usize, out: *std.ArrayList(Range)) A.Error!void { + var envelopes: std.ArrayList(tp.Envelope) = .empty; + try envelopes.appendSlice(a, try tp.envelopes(a, answer)); + const lfm = rt.calls[3]; + var pos: usize = 0; + while (std.mem.indexOfPos(u8, answer, pos, lfm[0])) |at| { + const end = if (std.mem.indexOfPos(u8, answer, at + lfm[0].len, lfm[1])) |e| e + lfm[1].len else answer.len; + try envelopes.append(a, .{ .start = at, .end = end, .payload = answer[at..end] }); + pos = end; + } + if (tp.openCall(answer)) |at| try envelopes.append(a, .{ .start = at, .end = answer.len, .payload = answer[at..] }); + std.mem.sort(tp.Envelope, envelopes.items, {}, struct { + fn less(_: void, x: tp.Envelope, y: tp.Envelope) bool { + return x.start < y.start; + } + }.less); + var index: usize = 0; + var consumed: usize = 0; + for (envelopes.items) |env| { + if (env.start < consumed) continue; + consumed = env.end; + var start = env.start; + var end = env.end; + if (start >= mm.ns.len and std.mem.endsWith(u8, answer[0..start], mm.ns)) start -= mm.ns.len; + if (std.mem.indexOfPos(u8, answer, start, mm.close)) |at| if (at < end) { + end = at + mm.close.len; + }; + const normalized = try mm.dsml(a, answer[start..end], tools); + const text = try @import("tool_lfm2.zig").dsml(a, normalized, tools, true); + const closed = try tp.closeCall(a, text, tools); + const parsed = try tp.parse(a, try std.mem.concat(a, u8, &.{ text, closed }), tools, null); + const found = parsed.calls orelse (try @import("tool_stream.zig").cutCalls(a, text, tools)) orelse continue; + // A DSML envelope can hold several invokes: each call's range starts at its own opening tag. + var at = start; + for (found, 0..) |_, j| { + var next = end; + if (j + 1 < found.len) { + const needle = if (std.mem.startsWith(u8, answer[start..], mm.open)) mm.ns ++ " 0) { + const normalized = try @import("tool_lfm2.zig").dsml(a, answer, tools, true); + if ((try tp.parse(a, normalized, tools, null)).calls != null) try out.append(a, .{ .start = offset_at, .end = offset_at + answer.len, .channel = .tool }); + } +} diff --git a/zig/src/server/logprob_parts_test.zig b/zig/src/server/logprob_parts_test.zig new file mode 100644 index 00000000000..3fe07f76a3d --- /dev/null +++ b/zig/src/server/logprob_parts_test.zig @@ -0,0 +1,313 @@ +//! Logprobs with tools, stops, reasoning and Responses: unchanged text and tokens, each token's plain entry. +const std = @import("std"); +const api = @import("engine_api"); +const root = @import("root.zig"); +const json = root.json; +const fixture = @import("logprobs_test.zig"); +const responses = @import("responses.zig"); +const translate = @import("responses_translate.zig"); +const errors = @import("errors.zig"); +const V = json.Value; +const A = std.mem.Allocator; +const ask = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"max_tokens\":56,\"return_token_ids\":true"; +const tools_json = "[{\"type\":\"function\",\"function\":{\"name\":\"f\",\"parameters\":{\"type\":\"object\"}}}]"; +const tool = ",\"tools\":" ++ tools_json; +const rows_on = ",\"logprobs\":true,\"top_logprobs\":2"; +const call = "{\"name\":\"f\",\"arguments\":{}}"; +const named: @import("server.zig").Config = .{ .served_name = "test-model", .model_ids = &.{"test-model"}, .enable_thinking = false }; + +/// `text` as byte tokens, then the end token. +fn tokens(a: A, text: []const u8) ![]u32 { + const ids = try a.alloc(u32, text.len + 1); + for (text, ids[0..text.len]) |b, *id| id.* = b; + ids[text.len] = 301; + return ids; +} + +fn choice(v: V) V { + return v.get("choices").?.array[0]; +} + +fn parse(a: A, body: []const u8) !V { + return (try json.parse(a, body)).ok; +} + +fn same(a: A, x: V, y: V) !void { + try std.testing.expectEqualStrings(try json.stringify(a, x, .{}), try json.stringify(a, y, .{})); +} + +/// The same text and calls; a call's id derives from its request's body, so it is not compared. +fn sameMessage(a: A, x: V, y: V) !void { + try same(a, x.get("content").?, y.get("content").?); + const xs = (x.get("tool_calls") orelse return std.testing.expect(y.get("tool_calls") == null)).array; + const ys = y.get("tool_calls").?.array; + try std.testing.expectEqual(xs.len, ys.len); + for (xs, ys) |p, q| try same(a, p.get("function").?, q.get("function").?); +} + +/// The bytes a list of entries spells. +fn spell(a: A, rows: V) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (rows.array) |row| for (row.get("bytes").?.array) |b| try out.append(a, @intCast(b.int64().?)); + return out.items; +} + +/// The whole reply body for `body`, which must answer 200. +fn whole(a: A, ids: []const u32, thinking: bool, body: []const u8) !V { + var got = try fixture.send(ids, thinking, .chat, body); + defer got.deinit(); + try std.testing.expectEqual(@as(u16, 200), got.status); + return parse(a, try a.dupe(u8, got.body)); +} + +/// A stream's text and its chunks' logprobs joined: each channel's entries in order, and the calls' groups. +const Joined = struct { text: []const u8, content: V, reasoning: V, calls: ?V, carried: usize }; + +fn joined(a: A, ids: []const u32, thinking: bool, body: []const u8) !Joined { + var got = try fixture.send(ids, thinking, .chat, body); + defer got.deinit(); + var text: std.ArrayList(u8) = .empty; + var prose: std.ArrayList(V) = .empty; + var thought: std.ArrayList(V) = .empty; + var calls: ?V = null; + var carried: usize = 0; + for (got.events.items) |event| { + const cs = (try parse(a, try a.dupe(u8, event))).get("choices") orelse continue; + if (cs.array.len == 0) continue; + const said = cs.array[0].get("delta").?.get("content"); + if (said) |c| if (c == .string) try text.appendSlice(a, c.string); + const rows = cs.array[0].get("logprobs") orelse continue; + try prose.appendSlice(a, rows.get("content").?.array); + if (said != null and rows.get("content").?.array.len > 0) carried += 1; + if (rows.get("reasoning_content")) |r| try thought.appendSlice(a, r.array); + if (rows.get("tool_calls")) |t| calls = t; + } + return .{ .text = text.items, .content = .{ .array = prose.items }, .reasoning = .{ .array = thought.items }, .calls = calls, .carried = carried }; +} + +test "logprob combinations: a stop and a call keep the text and token ids, and each entry is its token's plain entry" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]struct { text: []const u8, options: []const u8, shown: []const u8, at: []const usize }{ + .{ .text = "HiENDtrailing", .options = ",\"stop\":[\"END\"]", .shown = "Hi", .at = &.{ 0, 1 } }, + .{ .text = "a" ++ call ++ "b", .options = tool, .shown = "ab", .at = &.{ 0, call.len + 1 } }, + }) |case| { + const ids = try tokens(a, case.text); + const off = try whole(a, ids, false, try std.mem.concat(a, u8, &.{ ask, case.options, "}" })); + const on = try whole(a, ids, false, try std.mem.concat(a, u8, &.{ ask, case.options, rows_on, "}" })); + try std.testing.expectEqualStrings(case.shown, choice(on).get("message").?.get("content").?.string); + try sameMessage(a, choice(off).get("message").?, choice(on).get("message").?); + try same(a, off.get("tensorfold").?.get("token_ids").?, on.get("tensorfold").?.get("token_ids").?); + // a request without tools or stops has every token's entry in order + const plain = choice(try whole(a, ids, false, ask ++ rows_on ++ "}")).get("logprobs").?.get("content").?.array; + const rows = choice(on).get("logprobs").?; + try std.testing.expectEqual(case.at.len, rows.get("content").?.array.len); + for (rows.get("content").?.array, case.at) |row, i| try same(a, plain[i], row); + if (rows.get("tool_calls")) |groups| { + const group = groups.array[0].get("content").?; + try std.testing.expectEqualStrings(call, try spell(a, group)); + for (group.array, 1..) |row, i| try same(a, plain[i], row); + } + } +} + +test "logprob combinations: a stop inside a token or across two rounds trims entries with the text, whole and streamed" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const split_token = [_]u32{ 'H', 'i', 300, 'x', 301 }; + for ([_]struct { ids: []const u32, stop: []const u8, shown: []const u8 }{ + .{ .ids = &split_token, .stop = ",\"stop\":[\"think>\"]", .shown = "Hi= 1); + } + // the token the stop cuts shows its kept bytes, with its own id, logprob and alternatives + const last = choice(try whole(a, &split_token, false, ask ++ ",\"stop\":[\"think>\"]" ++ rows_on ++ "}")).get("logprobs").?.get("content").?.array[2]; + try std.testing.expectEqualStrings("", last.get("top_logprobs").?.array[0].get("token").?.string); +} + +test "logprob combinations: a thinking budget keeps reasoning entries apart, and the stream carries the same entries" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ids = [_]u32{ 'a', 'b', 300, '\n', 'H', 'i', 301 }; + const options = ",\"thinking_budget\":5" ++ rows_on; + const on = try whole(a, &ids, true, ask ++ options ++ "}"); + const lp = choice(on).get("logprobs").?; + try std.testing.expectEqualStrings("ab", try spell(a, lp.get("reasoning_content").?)); + try std.testing.expectEqualStrings("Hi", try spell(a, lp.get("content").?)); + try std.testing.expectEqual(@as(f64, -1.25), lp.get("content").?.array[0].get("logprob").?.float); + const off = try whole(a, &ids, true, ask ++ ",\"thinking_budget\":5}"); + try same(a, choice(off).get("message").?, choice(on).get("message").?); + try same(a, off.get("tensorfold").?.get("token_ids").?, on.get("tensorfold").?.get("token_ids").?); + const stream = try joined(a, &ids, true, ask ++ options ++ ",\"stream\":true}"); + try same(a, lp.get("content").?, stream.content); + try same(a, lp.get("reasoning_content").?, stream.reasoning); +} + +test "logprob combinations: answer text that repeats the reasoning takes the answer's own entries" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const rows = choice(try whole(arena.allocator(), &.{ 'H', 'i', 300, 'H', 'i', 301 }, true, ask ++ rows_on ++ "}")).get("logprobs").?; + try std.testing.expectEqual(@as(f64, -1), rows.get("content").?.array[0].get("logprob").?.float); + try std.testing.expectEqual(@as(f64, -0.25), rows.get("reasoning_content").?.array[0].get("logprob").?.float); +} + +test "logprob combinations: a call past parallel_tool_calls false is dropped, not read as prose" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: fixture.Text = .{}; + var backend: fixture.Script = .{ .reply = &.{} }; + var srv = try root.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), named, null); + defer srv.deinit(); + const reply = "a" ++ call ++ "{\"name\":\"f\",\"arguments\":{\"b\":1}}b"; + const ids = (try tokens(a, reply))[0..reply.len]; + const rows = try a.alloc(api.LogprobRow, ids.len); + for (rows, ids, 0..) |*row, id, i| row.* = .{ .token = id, .logprob = -@as(f32, @floatFromInt(i + 1)) }; + const tools = (try parse(a, tools_json)).array; + const parsed = try @import("tool_parse.zig").parse(a, reply, tools, 1); + try std.testing.expectEqualStrings("ab", parsed.content); + var cx: errors.Cx = .{ .a = a }; + const lp = try @import("logprob_parts.zig").project(srv, &cx, .{ .tokens = ids, .rows = rows, .thinking = false, .stops = .{ .strings = &.{} } }, parsed.content, null, tools, parsed.calls); + const prose = lp.get("content").?.array; + try std.testing.expectEqualStrings("ab", try spell(a, lp.get("content").?)); + try std.testing.expectEqual(-@as(f64, @floatFromInt(reply.len)), prose[1].get("logprob").?.float); + try std.testing.expectEqualStrings(call, try spell(a, lp.get("tool_calls").?.array[0].get("content").?)); +} + +test "logprob combinations: stop and call streams end with the whole reply's remaining entries" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][2][]const u8{ .{ "HiENDignored", ",\"stop\":[\"END\"]" }, .{ "Hi " ++ call, tool } }) |case| { + const ids = try tokens(a, case[0]); + const body = try std.mem.concat(a, u8, &.{ ask, case[1], rows_on }); + const expected = choice(try whole(a, ids, false, try std.mem.concat(a, u8, &.{ body, "}" }))).get("logprobs").?; + const stream = try joined(a, ids, false, try std.mem.concat(a, u8, &.{ body, ",\"stream\":true}" })); + try same(a, expected.get("content").?, stream.content); + if (expected.get("tool_calls")) |groups| try same(a, groups, stream.calls.?) else try std.testing.expect(stream.calls == null); + } +} + +test "logprob combinations: a prepared structured request keeps its tokens and target rows" { + var text: fixture.Text = .{}; + var backend: fixture.Script = .{ .reply = &.{ '{', '}', 301 } }; + var srv = try root.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), named, null); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Gone = struct { + pub fn check(_: @This()) bool { + return false; + } + }; + var previous: ?@import("chat.zig").Reply = null; + for ([_]bool{ false, true }) |enabled| { + var cx: errors.Cx = .{ .a = a }; + const plan = try @import("openai.zig").plan(srv, &cx, true, try parse(a, if (enabled) ask ++ ",\"logprobs\":true}" else ask ++ "}"), null, true); + var prepared = try @import("chat.zig").prepare(srv, &cx, plan.input, Gone{}); + prepared.request.structure = .{ .kind = .json }; + var reply = try @import("chat.zig").generate(srv, &cx, prepared, null, Gone{}); + try @import("logprobs.zig").project(srv, &cx, &reply, &.{}, null); + if (previous) |plain| { + try std.testing.expectEqualStrings(plain.content, reply.content); + try same(a, plain.runtime.get("token_ids").?, reply.runtime.get("token_ids").?); + try std.testing.expectEqualStrings("{}", try spell(a, reply.logprobs.?.get("content").?)); + try std.testing.expectEqual(@as(f64, -0.5), reply.logprobs.?.get("content").?.array[1].get("logprob").?.float); + } + previous = reply; + } +} + +/// A Responses stream's events, copied as they come. +const Events = struct { + a: A, + list: std.ArrayList(V) = .empty, + + fn sink(e: *@This()) @import("responses_sink.zig").Sink { + return .{ .ctx = e, .vt = &.{ .open = open, .event = event, .keepalive = open } }; + } + + fn open(_: *anyopaque) error{Closed}!void {} + + fn event(ctx: *anyopaque, _: A, _: []const u8, value: *json.Object) error{Closed}!void { + const e: *@This() = @ptrCast(@alignCast(ctx)); + e.list.append(e.a, json.deepCopy(e.a, .{ .object = value }) catch return error.Closed) catch return error.Closed; + } +}; + +/// One Responses turn on the fixture engine: its outcome and, when streamed, its events. +fn turn(a: A, reply: []const u32, thinking: bool, rows: bool, body: []const u8, events: *Events) !responses.Outcome { + var text: fixture.Text = .{}; + var backend: fixture.Script = .{ .reply = reply, .logprobs = rows }; + var config = named; + config.enable_thinking = thinking; + var srv = try root.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), config, null); + defer srv.deinit(); + var cx: errors.Cx = .{ .a = a }; + const raw = try parse(a, body); + const t = try translate.translate(&cx, raw, fixture.NoHistory{}); + var conn: @import("http_conn.zig").Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + return responses.turn(srv, a, &conn, &cx, raw, t, events.sink(), .{}); +} + +test "logprob combinations: Responses parts carry the entries, and each delta and done event carries its own" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]bool{ false, true }) |streaming| { + var events: Events = .{ .a = a }; + const body = if (streaming) "{\"input\":\"x\",\"top_logprobs\":2,\"store\":false,\"stream\":true}" else "{\"input\":\"x\",\"include\":[\"message.output_text.logprobs\"],\"store\":false}"; + const outcome = try turn(a, &.{ 'a', 'b', 300, 'H', 'i', 301 }, true, true, body, &events); + const final = if (streaming) outcome.streamed.? else outcome.whole; + const output = final.get("output").?.array; + const thought = output[0].get("content").?.array[0]; + const part = output[1].get("content").?.array[0]; + try std.testing.expectEqualStrings("Hi", part.get("text").?.string); + try std.testing.expectEqualStrings("Hi", try spell(a, part.get("logprobs").?)); + try std.testing.expectEqualStrings("ab", try spell(a, thought.get("logprobs").?)); + try std.testing.expectEqual(@as(f64, -1), part.get("logprobs").?.array[0].get("logprob").?.float); + if (!streaming) continue; + var deltas: std.ArrayList(V) = .empty; + var reasoning_done = false; + for (events.list.items) |event| { + const kind = event.get("type").?.string; + if (std.mem.eql(u8, kind, "response.output_text.delta")) try deltas.appendSlice(a, event.get("logprobs").?.array); + if (std.mem.eql(u8, kind, "response.output_text.done")) try same(a, part.get("logprobs").?, event.get("logprobs").?); + if (std.mem.eql(u8, kind, "response.output_item.done") and event.get("output_index").?.int64().? == 0) reasoning_done = true; + // without tools the reasoning item is whole, rows included, before the message item opens + if (std.mem.eql(u8, kind, "response.output_item.added") and event.get("output_index").?.int64().? == 1) try std.testing.expect(reasoning_done); + } + try same(a, part.get("logprobs").?, .{ .array = deltas.items }); + } +} + +test "logprob combinations: Responses include alone asks for rows only where the engine has them" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var events: Events = .{ .a = a }; + const listed = try turn(a, &.{ 'H', 'i', 301 }, false, false, "{\"input\":\"x\",\"include\":[\"message.output_text.logprobs\"],\"store\":false}", &events); + const part = listed.whole.get("output").?.array[0].get("content").?.array[0]; + try std.testing.expectEqualStrings("Hi", part.get("text").?.string); + try std.testing.expectEqual(@as(usize, 0), part.get("logprobs").?.array.len); + const asked = try turn(a, &.{ 'H', 'i', 301 }, false, false, "{\"input\":\"x\",\"top_logprobs\":2,\"store\":false}", &events); + try std.testing.expectEqual(@as(u16, 400), asked.refused.status); +} diff --git a/zig/src/server/logprobs.zig b/zig/src/server/logprobs.zig index 549ec9ea15c..f647e0e1c08 100644 --- a/zig/src/server/logprobs.zig +++ b/zig/src/server/logprobs.zig @@ -1,4 +1,4 @@ -//! OpenAI ``logprobs`` (who may ask, ``choices[0].logprobs`` from the engine's rows) and vLLM's ``prompt_logprobs``. +//! OpenAI ``logprobs`` entries from the engine's rows, their legacy completions form, and vLLM's ``prompt_logprobs``. const std = @import("std"); const api = @import("engine_api"); const json = @import("json"); @@ -9,60 +9,6 @@ const Value = json.Value; const Cx = errors.Cx; const Allocator = std.mem.Allocator; -/// The rows are cut where the text is: after the end-of-thinking token, which must be a token of its own. -pub fn admit(srv: *Server, cx: *Cx, thinking: bool, think_budget: u32, count: u8) errors.Refused!u8 { - if (thinking and srv.text.tokenId(srv.markers.close) == null) return cx.refuse("logprobs with thinking on need the template's end-of-thinking marker as one token"); - if (think_budget > 0) return cx.refuse("logprobs support chat without tools, stop strings, structured output or a thinking budget"); - return count; -} - -/// ``choices[0].logprobs`` for the answer's tokens: after the first end-of-thinking token and dropped newlines. -pub fn value(srv: *Server, cx: *Cx, a: Allocator, thinking: bool, tokens: []const u32, rows: []const api.LogprobRow) errors.Refused!Value { - if (rows.len < tokens.len) return cx.other("the engine gave fewer logprob rows than reply tokens"); - const start = (try answerStart(srv, a, thinking, tokens)) orelse tokens.len; - return wrap(a, entries(srv, a, tokens[start..], rows[start..tokens.len]) catch |e| return switch (e) { - error.OutOfMemory => error.OutOfMemory, - error.Failed => cx.other("the logprob rows are out of step with the reply's tokens, or a forced token has none"), - }); -} - -/// A streamed reply's rows: each content chunk carries those of the answer tokens its text now spells. -pub const Stream = struct { - rows: std.ArrayList(api.LogprobRow) = .empty, // the reply's rows, copied with each round's tokens - sent: usize = 0, // answer rows already sent - spelled: usize = 0, // bytes of the streamed content those rows spell - - /// ``{content, logprobs}`` for `text`, with the rows `streamed` content bytes now cover (all of them once `done`). - pub fn delta(st: *Stream, srv: *Server, a: Allocator, thinking: bool, ignore_eos: bool, collected: []const u32, text: []const u8, streamed: usize, done: bool) error{ Failed, OutOfMemory }!?Value { - const tokens = if (ignore_eos) collected else reply_text.stripTrailing(collected, srv.eos); - if (st.rows.items.len < tokens.len) return error.Failed; - var ready: usize = 0; - if (try answerStart(srv, a, thinking, tokens)) |start| { - for (tokens[start + st.sent ..], start + st.sent..) |id, i| { - const bytes = (try srv.text.tokenBytes(a, id)) orelse &.{}; - // the answer's text drops the newlines its first token may start with - const lead = if (thinking and i == start) bytes.len - std.mem.trimStart(u8, bytes, "\n").len else 0; - if (!done and st.spelled + bytes.len - lead > streamed) break; - st.spelled += bytes.len - lead; - ready += 1; - } - if (ready > 0) { - const from = start + st.sent; - const lp = try wrap(a, try entries(srv, a, tokens[from..][0..ready], st.rows.items[from..][0..ready])); - st.sent += ready; - const o = try json.newObject(a); - try o.put(a, "content", .{ .string = text }); - try o.put(a, "logprobs", lp); - return .{ .object = o }; - } - } - if (text.len == 0) return null; - const o = try json.newObject(a); - try o.put(a, "content", .{ .string = text }); - return .{ .object = o }; - } -}; - /// ``/v1/completions``' legacy ``logprobs`` from the chat form's rows; ``text_offset`` counts on from `offset` chars. pub fn legacy(a: Allocator, rows: Value, offset: *usize) Allocator.Error!Value { const items = rows.object.get("content").?.array; @@ -112,24 +58,6 @@ fn promptEntry(srv: *Server, a: Allocator, o: *json.Object, id: u32, logprob: f3 try o.put(a, try std.fmt.allocPrint(a, "{d}", .{id}), .{ .object = e }); } -/// Where the answer's rows start: past the first end-of-thinking token and newline-only tokens; null: no answer yet. -fn answerStart(srv: *Server, a: Allocator, thinking: bool, tokens: []const u32) Allocator.Error!?usize { - if (!thinking) return 0; - const end = srv.text.tokenId(srv.markers.close) orelse return null; - var start = (std.mem.indexOfScalar(u32, tokens, end) orelse return null) + 1; - while (start < tokens.len) : (start += 1) { - const bytes = (try srv.text.tokenBytes(a, tokens[start])) orelse return start; - if (bytes.len == 0 or std.mem.indexOfNone(u8, bytes, "\n") != null) return start; - } - return null; -} - -fn wrap(a: Allocator, content: []Value) Allocator.Error!Value { - const out = try json.newObject(a); - try out.put(a, "content", .{ .array = content }); - return .{ .object = out }; -} - fn entries(srv: *Server, a: Allocator, tokens: []const u32, rows: []const api.LogprobRow) error{ Failed, OutOfMemory }![]Value { const content = try a.alloc(Value, tokens.len); for (content, tokens, rows) |*slot, id, r| { @@ -154,3 +82,45 @@ fn entry(srv: *Server, a: Allocator, id: u32, logprob: f32) Allocator.Error!*jso try o.put(a, "bytes", .{ .array = b }); return o; } + +/// The engine gives rows and each token's exact bytes, in a reply format read as text (not Kimi's token channels). +pub fn offered(srv: *Server, a: Allocator) Allocator.Error!bool { + if (!srv.info.capability(.logprobs) or srv.text.vtable.format == .kimi) return false; + return (try srv.text.tokenBytes(a, 0)) != null; // a tokenizer whose decoding depends on context has none +} + +/// ``reply.logprobs`` from its captured rows, once the route's tool policy has settled its content and calls. +pub fn project(srv: *Server, cx: *Cx, reply: *@import("chat.zig").Reply, tools: []const Value, calls: ?[]Value) errors.Refused!void { + const captured = reply.probability_rows orelse return; + reply.logprobs = try @import("logprob_parts.zig").project(srv, cx, captured, reply.content, reply.reasoning, tools, calls); +} + +/// One token's entry; a token the reply shows only part of keeps its row but shows those `bytes` and its ``token_id``. +pub fn rowValue(srv: *Server, a: Allocator, id: u32, row: api.LogprobRow, bytes: []const u8, cropped: bool) error{ Failed, OutOfMemory }!Value { + const made = try entries(srv, a, &.{id}, &.{row}); + if (!cropped) return made[0]; + const o = made[0].object; + try o.put(a, "token", .{ .string = try validText(a, bytes) }); + const b = try a.alloc(Value, bytes.len); + for (bytes, b) |x, *v| v.* = try json.intValue(a, x); + try o.put(a, "bytes", .{ .array = b }); + try o.put(a, "token_id", try json.intValue(a, id)); + return made[0]; +} + +/// `bytes` as text, each byte of an incomplete or invalid UTF-8 sequence as U+FFFD. +fn validText(a: Allocator, bytes: []const u8) Allocator.Error![]const u8 { + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < bytes.len) { + const n = std.unicode.utf8ByteSequenceLength(bytes[i]) catch 0; + if (n > 0 and i + n <= bytes.len and std.unicode.utf8ValidateSlice(bytes[i..][0..n])) { + try out.appendSlice(a, bytes[i..][0..n]); + i += n; + continue; + } + try out.appendSlice(a, "\u{fffd}"); + i += 1; + } + return out.items; +} diff --git a/zig/src/server/logprobs_test.zig b/zig/src/server/logprobs_test.zig index ec2ce7076d7..f311766ccab 100644 --- a/zig/src/server/logprobs_test.zig +++ b/zig/src/server/logprobs_test.zig @@ -1,4 +1,4 @@ -//! `logprobs`: rows cover the answer as `content` does, the 0.6.6 refusals hold; `prompt_logprobs` on /v1/completions. +//! Target logprob rows on chat and completions, including streamed projection and prompt rows. const std = @import("std"); const api = @import("engine_api"); const server = @import("root.zig"); @@ -18,8 +18,8 @@ const all_bytes = blk: { }; /// Bytes as tokens, `` as token 300 and an end token 301; every prompt renders as "prompt". -const Text = struct { - fn text(t: *@This()) model_text.Text { +pub const Text = struct { + pub fn text(t: *@This()) model_text.Text { return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource, .token_bytes = tokenBytes } }; } @@ -71,14 +71,14 @@ const Text = struct { }; /// Answers `reply` in two rounds; token i at -(i + 1) / 4, best itself then 'z'; even prompt rows rank their token 1. -const Script = struct { +pub const Script = struct { reply: []const u32, asked: ?u8 = null, prompt_rows: bool = true, logprobs: bool = true, submits: usize = 0, - fn engine(e: *@This()) api.Engine { + pub fn engine(e: *@This()) api.Engine { return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; } @@ -91,7 +91,7 @@ const Script = struct { const e: *Script = @ptrCast(@alignCast(ctx)); e.submits += 1; e.asked = r.logprobs; - var rows: [32]api.LogprobRow = undefined; + var rows: [1024]api.LogprobRow = undefined; for (e.reply, rows[0..e.reply.len], 0..) |t, *row, i| { const lp = -@as(f32, @floatFromInt(i + 1)) / 4; row.* = .{ .token = t, .logprob = lp, .count = r.logprobs orelse 0 }; @@ -134,16 +134,16 @@ const Script = struct { }; /// The reply the route wrote: its status and body, or a stream's events, as JSON text (testing-allocator owned). -const Got = struct { +pub const Got = struct { status: u16 = 0, body: []u8 = &.{}, events: std.ArrayList([]u8) = .empty, - fn out(g: *Got) openai.Out { + pub fn out(g: *Got) openai.Out { return .{ .ctx = g, .vt = &.{ .open = open, .event = event, .reply = reply } }; } - fn deinit(g: *Got) void { + pub fn deinit(g: *Got) void { std.testing.allocator.free(g.body); for (g.events.items) |e| std.testing.allocator.free(e); g.events.deinit(std.testing.allocator); @@ -169,9 +169,9 @@ const Got = struct { } }; -const Route = enum { chat, responses, completions }; +pub const Route = enum { chat, responses, completions }; -fn send(reply: []const u32, thinking: bool, route: Route, body: []const u8) !Got { +pub fn send(reply: []const u32, thinking: bool, route: Route, body: []const u8) !Got { return sendWith(reply, thinking, route, body, true); } @@ -202,7 +202,7 @@ fn sendCapabilities(reply: []const u32, thinking: bool, route: Route, body: []co return got; } -const NoHistory = struct { +pub const NoHistory = struct { pub fn conversation(_: NoHistory, cx: *errors.Cx, _: json.Value) errors.Refused![]json.Value { return cx.refuse("no stored responses in this test"); } @@ -330,14 +330,17 @@ test "a streamed reply's rows, joined over its chunks, are the whole reply's and defer spelled.deinit(std.testing.allocator); var text: std.ArrayList(u8) = .empty; defer text.deinit(std.testing.allocator); + var carried: usize = 0; // chunks whose own text came with its entries for (streamed.events.items) |e| { const chunk = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, e, .{}); defer chunk.deinit(); const choices = chunk.value.object.get("choices") orelse continue; if (choices.array.items.len == 0) continue; const choice = choices.array.items[0].object; - if (choice.get("delta").?.object.get("content")) |c| try text.appendSlice(std.testing.allocator, c.string); + const said = choice.get("delta").?.object.get("content"); + if (said) |c| try text.appendSlice(std.testing.allocator, c.string); const lp = choice.get("logprobs") orelse continue; + if (said != null and lp.object.get("content").?.array.items.len > 0) carried += 1; for (lp.object.get("content").?.array.items) |r| { try rows.print(std.testing.allocator, "{s}:{d};", .{ r.object.get("token").?.string, r.object.get("logprob").?.float }); for (r.object.get("bytes").?.array.items) |b| try spelled.append(std.testing.allocator, @intCast(b.integer)); @@ -349,24 +352,30 @@ test "a streamed reply's rows, joined over its chunks, are the whole reply's and try std.testing.expectEqualStrings(expected.items, rows.items); try std.testing.expectEqualStrings("Hello", text.items); try std.testing.expectEqualStrings("Hello", spelled.items); + // the answer's text streams with its own entries, each round's (two for the plain reply), not all at the end + try std.testing.expect(carried >= @as(usize, if (case[1]) 1 else 2)); } } -test "logprobs refuse tools, stop strings, structured output, a thinking budget and other routes" { +test "logprobs combinations reach planning while unsupported legacy boolean probabilities still refuse" { const reply = tokensOf("Hi"); - const refused = [_][]const u8{ + const bodies = [_][]const u8{ ask ++ ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"f\",\"parameters\":{\"type\":\"object\"}}}]}", ask ++ ",\"stop\":[\"x\"]}", ask ++ ",\"response_format\":{\"type\":\"json_object\"}}", ask ++ ",\"thinking_budget\":5}", }; - for (refused) |body| { - const got = try send(&reply, false, .chat, body); - defer std.testing.allocator.free(got.body); - try std.testing.expectEqual(@as(u16, 400), got.status); + var text: Text = .{}; + var backend: Script = .{ .reply = &reply }; + var srv = try server.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), .{ .served_name = "test-model", .model_ids = &.{"test-model"} }, null); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var cx: errors.Cx = .{ .a = arena.allocator() }; + for (bodies) |body| { + const p = try openai.plan(srv, &cx, true, (try json.parse(cx.a, body)).ok, null, true); + try std.testing.expectEqual(@as(?u8, 2), p.input.logprobs); } - const responses = send(&reply, false, .responses, "{\"model\":\"test-model\",\"input\":\"x\",\"logprobs\":true}"); - try std.testing.expectError(error.Refused, responses); var boolean = try send(&reply, false, .completions, "{\"model\":\"test-model\",\"prompt\":\"x\",\"logprobs\":true}"); defer boolean.deinit(); try std.testing.expectEqual(@as(u16, 400), boolean.status); diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index bb85757f60c..9f9075dde57 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -130,9 +130,8 @@ pub fn chatInput(srv: *Server, cx: *Cx, raw: Value) errors.Refused!chat.Input { pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u8, client_thinking: bool) errors.Refused!Plan { const body = try fields.parseNumbers(cx, raw); try fields.validateModalities(cx, body); - // rows need each token's exact bytes: a tokenizer whose decoding depends on context (null) can't give them const asked = if (is_chat) json.truthyField(body, "logprobs") else body.field("logprobs") != null; - const exact_bytes = asked and srv.info.capability(.logprobs) and (srv.text.tokenBytes(cx.a, 0) catch return error.OutOfMemory) != null; + const exact_bytes = asked and try @import("logprobs.zig").offered(srv, cx.a); const logprobs = if (is_chat) try fields.probabilityOptions(cx, body, exact_bytes) else try fields.legacyLogprobs(cx, body, exact_bytes); if (srv.config.request_log) |path| request_log.append(cx.a, path, body); var input: chat.Input = .{ .fields = undefined, .format = format }; @@ -167,13 +166,6 @@ pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u input.explicit_off = client_thinking and !(thinking.enable orelse true); const streamed = if (body.get("stream")) |s| s.truthy() else false; input.prompt_logprobs = try fields.promptLogprobs(cx, body, !is_chat, streamed, srv.info.capability(.prompt_logprobs)); - if (logprobs != null) { - // 0.6.6's set: the rows describe the plain reply text, so nothing may reshape it - var structured = false; - for (grammar.fields) |k| structured = structured or json.truthyField(body, k); - if (input.tools.len > 0 or json.truthyField(body, "stop") or structured or json.truthyField(body, "thinking_budget")) - return cx.refuse("logprobs support chat without tools, stop strings, structured output or a thinking budget"); - } input.logprobs = logprobs; var policy: tool_stream.Policy = .{}; if (body.field("parallel_tool_calls")) |p| { @@ -382,6 +374,7 @@ const Run = struct { var cx: Cx = .{ .a = a }; var reply = (if (r.turn) |t| cortheon.loop.whole(t, r.srv, &cx, &r.plan.input, gone) else chat.run(r.srv, &cx, r.plan.input, null, gone)) catch |e| return r.unsent(&cx, e, field); const calls = r.attachCalls(&reply) catch return; + @import("logprobs.zig").project(r.srv, &cx, &reply, r.plan.input.tools, calls) catch |e| return r.unsent(&cx, e, field); const o = json.newObject(a) catch return; r.wholeBody(o, &reply, calls) catch return; r.out.vt.reply(r.out.ctx, 200, .{ .object = o }); @@ -499,6 +492,16 @@ const Run = struct { return r.emit(r.chunk(role, null) catch return error.Closed); } + /// A server error after the stream opened: its error event, then [DONE]. + fn streamFailed(r: *Run, message: []const u8) void { + log.line("stream error: {s}", .{message}); + const err = json.newObject(r.a) catch return; + err.put(r.a, "message", .{ .string = message }) catch return; + err.put(r.a, "type", .{ .string = "server_error" }) catch return; + r.emit(wrapError(r.a, .{ .object = err }) catch return) catch return; + r.out.vt.event(r.out.ctx, null) catch {}; + } + fn stream(r: *Run, gone: Gone, field: []const u8) void { const a = r.a; const tools = r.plan.input.tools.len > 0; @@ -541,14 +544,7 @@ const Run = struct { }, else => {}, } - const message = if (e == error.Refused) cx.message else if (e == error.OutOfMemory) "out of memory" else "the reply failed"; - log.line("stream error: {s}", .{message}); - const err = json.newObject(a) catch return; - err.put(a, "message", .{ .string = message }) catch return; - err.put(a, "type", .{ .string = "server_error" }) catch return; - r.emit(wrapError(a, .{ .object = err }) catch return) catch return; - r.out.vt.event(r.out.ctx, null) catch {}; - return; + return r.streamFailed(if (e == error.Refused) cx.message else if (e == error.OutOfMemory) "out of memory" else "the reply failed"); }; var calls: ?[]Value = null; if (tools) { @@ -572,6 +568,13 @@ const Run = struct { r.emit(r.chunk(.{ .string = rest }, null) catch return) catch return; } } + @import("logprobs.zig").project(r.srv, &cx, &reply, r.plan.input.tools, calls) catch |e| return r.streamFailed(if (e == error.Refused) cx.message else "out of memory"); + // the entries no chunk carried yet, once the stop and tool policies are final + if (reply.logprobs) |rows| if (@import("logprob_parts.zig").rest(a, rows, reply.probability_rows.?.sent) catch return) |left| { + const delta = json.newObject(a) catch return; + delta.put(a, "logprobs", left) catch return; + r.emit(r.chunk(.{ .object = delta }, null) catch return) catch return; + }; const last = r.chunk(.{ .string = "" }, if (reply.finish_reason.len > 0) reply.finish_reason else "length") catch return; if (compaction) |s| compact.stamp(&cx, &reply, s) catch return; r.extras(last.object, &reply) catch return; diff --git a/zig/src/server/response_logprobs.zig b/zig/src/server/response_logprobs.zig new file mode 100644 index 00000000000..4a130579597 --- /dev/null +++ b/zig/src/server/response_logprobs.zig @@ -0,0 +1,38 @@ +//! Logprob entries attached to the Responses items whose text they spell, after the entries those items already carry. +const std = @import("std"); +const json = @import("json"); +const V = json.Value; +const A = std.mem.Allocator; + +/// New entries for one item: `owner` holds them, the item's text part or, for a call, the item itself. +pub const Added = struct { item: *json.Object, owner: *json.Object, rows: []V }; + +/// Reasoning and prose entries to the items of their kind in order, each filled up to its text before the next. +pub fn attach(a: A, items: []const *json.Object, rows: V, skip_reasoning: bool, skip_content: bool, out: *std.ArrayList(Added)) A.Error!void { + for ([_]struct { []const u8, []const u8, bool }{ .{ "reasoning", "reasoning_content", skip_reasoning }, .{ "message", "content", skip_content } }) |group| { + if (group[2]) continue; + const all = (rows.get(group[1]) orelse continue).items() orelse continue; + var last: ?usize = null; + for (items, 0..) |item, i| if (std.mem.eql(u8, item.get("type").?.string, group[0])) { + last = i; + }; + var at: usize = 0; + for (items, 0..) |item, i| { + if (at == all.len) break; + if (!std.mem.eql(u8, item.get("type").?.string, group[0])) continue; + const part = item.get("content").?.array[0].object; + var used = spelled(if (part.get("logprobs")) |v| v.array else &.{}); + const size = part.get("text").?.string.len; + const start = at; + // the last item takes any entries past the text, so none is lost + while (at < all.len and (used < size or i == last.?)) : (at += 1) used += spelled(all[at .. at + 1]); + if (at > start) try out.append(a, .{ .item = item, .owner = part, .rows = all[start..at] }); + } + } +} + +fn spelled(entries: []const V) usize { + var n: usize = 0; + for (entries) |e| n += (e.get("bytes") orelse continue).array.len; + return n; +} diff --git a/zig/src/server/responses.zig b/zig/src/server/responses.zig index 71ebc744d92..93d9467e13d 100644 --- a/zig/src/server/responses.zig +++ b/zig/src/server/responses.zig @@ -95,7 +95,10 @@ pub const TurnOptions = struct { /// One translated Responses request run as its chat completion, its events sent through ``sink``. pub fn turn(srv: *Server, a: Allocator, conn: *Conn, cx: *Cx, body: Value, t: translate_mod.Request, sink: Sink, opts: TurnOptions) Outcome { const base = newBase(srv, a, body, t) catch return .{ .streamed = null }; - var reply: Reply = .{ .srv = srv, .a = a, .sink = sink, .base = base, .streaming = t.stream, .keep = t.store, .added = t.added, .cx = cx, .call_ids = .{ .key = &srv.tool_ids, .body = t.chat }, .whole_history = opts.whole_history }; + if (t.rows_if_offered and !(@import("logprobs.zig").offered(srv, a) catch false)) _ = t.chat.object.orderedRemove("logprobs"); + // a reply with tools gets its rows once its calls are parsed: each item's done events wait for them + const late = json.truthyField(t.chat, "logprobs") and json.truthyField(t.chat, "tools"); + var reply: Reply = .{ .srv = srv, .a = a, .sink = sink, .base = base, .streaming = t.stream, .keep = t.store, .added = t.added, .cx = cx, .call_ids = .{ .key = &srv.tool_ids, .body = t.chat }, .whole_history = opts.whole_history, .late_rows = late }; var out: Wire = .{ .reply = &reply }; cancel_ids.alias = base.get("id").?.string; // the cancel route takes the response's id too defer cancel_ids.alias = null; @@ -192,6 +195,9 @@ const Reply = struct { whole_history: ?[]Value = null, /// A warmup turn: no empty message item, so its output stays empty. warmup: bool = false, + /// Logprobs come after the calls are parsed: done events wait until ``finish``, when every item has its rows. + late_rows: bool = false, + finishing: bool = false, const E = error{Closed}; @@ -277,6 +283,7 @@ const Reply = struct { const item = r.current orelse return; r.current = null; try r.put(item, "status", .{ .string = status }); + if (r.late_rows and !r.finishing) return; const where_id = item.get("id").?; const where_index = try r.int(r.index(item)); if (std.mem.eql(u8, item.get("type").?.string, "function_call")) { @@ -284,7 +291,7 @@ const Reply = struct { } else { const part = item.get("content").?.array[0].object; if (std.mem.eql(u8, item.get("type").?.string, "message")) { - try r.event("response.output_text.done", &.{ .{ "item_id", where_id }, .{ "output_index", where_index }, .{ "content_index", .{ .int = "0" } }, .{ "text", part.get("text").? }, .{ "logprobs", .{ .array = &.{} } } }); + try r.event("response.output_text.done", &.{ .{ "item_id", where_id }, .{ "output_index", where_index }, .{ "content_index", .{ .int = "0" } }, .{ "text", part.get("text").? }, .{ "logprobs", part.get("logprobs").? } }); } else { try r.event("response.reasoning_text.done", &.{ .{ "item_id", where_id }, .{ "output_index", where_index }, .{ "content_index", .{ .int = "0" } }, .{ "text", part.get("text").? } }); } @@ -293,6 +300,17 @@ const Reply = struct { try r.event("response.output_item.done", &.{ .{ "output_index", where_index }, .{ "item", .{ .object = item } } }); } + /// The open item ends with `status`; with late rows every item sends its deferred done events now, in order. + fn closeAll(r: *Reply, status: []const u8) E!void { + if (!r.late_rows) return r.close(status); + r.finishing = true; + const current = r.current; + for (r.items.items) |item| { + r.current = item; + try r.close(if (item == current) status else item.get("status").?.string); + } + } + /// Each item's text or arguments grows in one buffer, including calls whose deltas interleave. fn append(r: *Reply, item: *json.Object, text: []const u8) E![]const u8 { const buffer = &r.buffers.items[r.index(item)]; @@ -300,28 +318,42 @@ const Reply = struct { return buffer.items; } - fn write(r: *Reply, kind: []const u8, text: []const u8) E!void { + /// A text delta, with the entries the chunk carried for it (null: none asked). + fn write(r: *Reply, kind: []const u8, text: []const u8, rows: ?[]Value) E!void { const reuse = if (r.current) |c| std.mem.eql(u8, c.get("type").?.string, kind) else false; const item = if (reuse) r.current.? else try r.open(kind, "", ""); const part = item.get("content").?.array[0].object; try r.put(part, "text", .{ .string = try r.append(item, text) }); + const entries: Value = .{ .array = if (rows) |list| try r.carry(part, list) else &.{} }; const where_id = item.get("id").?; const where_index = try r.int(r.index(item)); if (std.mem.eql(u8, kind, "message")) { - try r.event("response.output_text.delta", &.{ .{ "item_id", where_id }, .{ "output_index", where_index }, .{ "content_index", .{ .int = "0" } }, .{ "delta", .{ .string = text } }, .{ "logprobs", .{ .array = &.{} } } }); + try r.event("response.output_text.delta", &.{ .{ "item_id", where_id }, .{ "output_index", where_index }, .{ "content_index", .{ .int = "0" } }, .{ "delta", .{ .string = text } }, .{ "logprobs", entries } }); + } else if (rows != null) { + try r.event("response.reasoning_text.delta", &.{ .{ "item_id", where_id }, .{ "output_index", where_index }, .{ "content_index", .{ .int = "0" } }, .{ "delta", .{ .string = text } }, .{ "logprobs", entries } }); } else try r.event("response.reasoning_text.delta", &.{ .{ "item_id", where_id }, .{ "output_index", where_index }, .{ "content_index", .{ .int = "0" } }, .{ "delta", .{ .string = text } } }); } + /// `list` appended to what `owner` already carries; returns `list`. + fn carry(r: *Reply, owner: *json.Object, list: []Value) E![]Value { + const had = if (owner.get("logprobs")) |v| v.array else &.{}; + try r.put(owner, "logprobs", .{ .array = std.mem.concat(r.a, Value, &.{ had, list }) catch return error.Closed }); + return list; + } + fn textOf(v: ?Value) ?[]const u8 { const x = v orelse return null; return if (x == .string and x.string.len > 0) x.string else null; } - fn delta(r: *Reply, d: Value) E!void { + /// One chat delta, with its chunk's logprobs (null: none): a channel's entries go with its text, others to items. + fn delta(r: *Reply, d: Value, rows: ?Value) E!void { + const thought = if (d == .object) textOf(d.get("reasoning_content")) orelse textOf(d.get("reasoning")) else null; + const content = if (d == .object) textOf(d.get("content")) else null; + if (thought) |t| try r.write("reasoning", t, if (rows) |v| listOf(v, "reasoning_content") else null); + if (content) |c| try r.write("message", c, if (rows) |v| listOf(v, "content") else null); + if (rows) |v| try r.probabilityItems(v, thought != null, content != null); if (d != .object) return; - const thought = textOf(d.get("reasoning_content")) orelse textOf(d.get("reasoning")); - if (thought) |t| try r.write("reasoning", t); - if (textOf(d.get("content"))) |c| try r.write("message", c); const calls = d.get("tool_calls") orelse return; if (calls != .array) return; for (calls.array) |call| { @@ -341,6 +373,33 @@ const Reply = struct { } } + /// Entries that arrived without their text, and the calls' groups: each to its item, with an empty delta. + fn probabilityItems(r: *Reply, rows: Value, skip_reasoning: bool, skip_content: bool) E!void { + const logprobs = @import("response_logprobs.zig"); + var added: std.ArrayList(logprobs.Added) = .empty; + logprobs.attach(r.a, r.items.items, rows, skip_reasoning, skip_content, &added) catch return error.Closed; + if (listOf(rows, "tool_calls")) |groups| for (groups) |group| { + const item = r.calls.get((group.get("index") orelse continue).int64() orelse continue) orelse continue; + const list = (group.get("content") orelse continue).items() orelse continue; + added.append(r.a, .{ .item = item, .owner = item, .rows = list }) catch return error.Closed; + }; + for (added.items) |one| { + _ = try r.carry(one.owner, one.rows); + const where = try r.int(r.index(one.item)); + const entries: Value = .{ .array = one.rows }; + if (one.item == one.owner) { + try r.event("response.function_call_arguments.delta", &.{ .{ "item_id", one.item.get("id").? }, .{ "output_index", where }, .{ "delta", .{ .string = "" } }, .{ "logprobs", entries } }); + continue; + } + const name = if (std.mem.eql(u8, one.item.get("type").?.string, "reasoning")) "response.reasoning_text.delta" else "response.output_text.delta"; + try r.event(name, &.{ .{ "item_id", one.item.get("id").? }, .{ "output_index", where }, .{ "content_index", .{ .int = "0" } }, .{ "delta", .{ .string = "" } }, .{ "logprobs", entries } }); + } + } + + fn listOf(rows: Value, key: []const u8) ?[]Value { + return (rows.get(key) orelse return null).items(); + } + fn usage(r: *Reply, chat: ?Value) E!Value { const c = chat orelse return .null; if (!c.truthy()) return .null; @@ -379,7 +438,7 @@ const Reply = struct { } else true; if (all_reasoning) _ = try r.open("message", "", ""); // an empty answer is still a message } - try r.close(if (cancelled) "incomplete" else status); // an output item is never "cancelled" + try r.closeAll(if (cancelled) "incomplete" else status); // an output item is never "cancelled" const final = json.copyObject(r.a, r.base) catch return error.Closed; try r.put(final, "status", .{ .string = status }); try r.put(final, "output", try r.itemsValue()); @@ -408,7 +467,7 @@ const Reply = struct { } fn fail(r: *Reply, problem: Value) E!void { - try r.close("incomplete"); + try r.closeAll("incomplete"); const message = if (problem == .object) problem.get("message") else null; const kind = if (problem == .object) problem.get("type") else null; const is_request = kind != null and kind.? == .string and std.mem.eql(u8, kind.?.string, "invalid_request_error"); @@ -431,7 +490,7 @@ const Reply = struct { if (p.has("error")) return r.fail(p.get("error").?); const choices = p.get("choices"); const choice: Value = if (choices != null and choices.? == .array and choices.?.array.len > 0) choices.?.array[0] else .null; - try r.delta(if (choice.get("delta")) |d| d else .null); + try r.delta(if (choice.get("delta")) |d| d else .null, choice.get("logprobs")); if (choice.get("finish_reason")) |f| if (f.truthy()) { _ = try r.finish(if (f == .string) f.string else null, p.get("usage"), p.get("tensorfold")); }; @@ -452,7 +511,8 @@ const Reply = struct { calls.append(r.a, .{ .object = c }) catch return error.Closed; }; try r.put(d, "tool_calls", .{ .array = calls.items }); - try r.delta(.{ .object = d }); + try r.delta(.{ .object = d }, null); + if (choice.get("logprobs")) |rows| try r.probabilityItems(rows, false, false); const reason = choice.get("finish_reason"); return r.finish(if (reason != null and reason.? == .string) reason.?.string else null, data.get("usage"), data.get("tensorfold")); } @@ -466,7 +526,7 @@ test "a call delta that names no id takes the chat run's id at its index, and on const chat = (try json.parse(a, "{\"model\":\"m\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}]}")).ok; var cx: Cx = .{ .a = a }; var reply: Reply = .{ .srv = undefined, .a = a, .sink = undefined, .base = try json.newObject(a), .streaming = false, .keep = false, .added = &.{}, .cx = &cx, .call_ids = .{ .key = &key, .body = chat } }; - try reply.delta((try json.parse(a, "{\"tool_calls\":[{\"index\":1,\"function\":{\"name\":\"f\"}},{\"index\":2,\"id\":\"call_sent\",\"function\":{\"name\":\"f\"}}]}")).ok); + try reply.delta((try json.parse(a, "{\"tool_calls\":[{\"index\":1,\"function\":{\"name\":\"f\"}},{\"index\":2,\"id\":\"call_sent\",\"function\":{\"name\":\"f\"}}]}")).ok, null); var calls: ids.Calls = .{ .key = &key, .body = chat }; try std.testing.expectEqualStrings(try calls.id(a, 0, 1), reply.items.items[0].get("call_id").?.string); try std.testing.expectEqualStrings("call_sent", reply.items.items[1].get("call_id").?.string); @@ -482,7 +542,7 @@ test "Server recovery: Responses grows reasoning, text and interleaved call argu var r: Reply = .{ .srv = &srv, .a = a, .sink = undefined, .base = try json.newObject(a), .streaming = false, .keep = false, .added = &.{}, .cx = &cx, .call_ids = .{ .key = &key, .body = .null } }; const chunk = "abcdefgh"; for ([_][]const u8{ "reasoning", "message" }) |kind| { - for (0..3000) |_| try r.write(kind, chunk); + for (0..3000) |_| try r.write(kind, chunk, null); const text = r.current.?.get("content").?.array[0].get("text").?.string; try std.testing.expectEqual(@as(usize, 3000 * chunk.len), text.len); for (0..3000) |i| try std.testing.expectEqualStrings(chunk, text[i * chunk.len ..][0..chunk.len]); @@ -490,8 +550,8 @@ test "Server recovery: Responses grows reasoning, text and interleaved call argu const first = (try json.parse(a, "{\"tool_calls\":[{\"index\":0,\"id\":\"a\",\"function\":{\"name\":\"f\",\"arguments\":\"abcdefgh\"}}]}")).ok; const second = (try json.parse(a, "{\"tool_calls\":[{\"index\":1,\"id\":\"b\",\"function\":{\"name\":\"g\",\"arguments\":\"abcdefgh\"}}]}")).ok; for (0..3000) |_| { - try r.delta(first); - try r.delta(second); + try r.delta(first, null); + try r.delta(second, null); } for ([_]i64{ 0, 1 }) |i| { const args = r.calls.get(i).?.get("arguments").?.string; diff --git a/zig/src/server/responses_translate.zig b/zig/src/server/responses_translate.zig index b112a8ccc32..43a73f5299e 100644 --- a/zig/src/server/responses_translate.zig +++ b/zig/src/server/responses_translate.zig @@ -26,6 +26,8 @@ pub const Request = struct { stream: bool, /// The client's own name for the grammar field when ``text.format`` asked for a structure; null for plain text. format: ?[]const u8 = null, + /// Only ``include`` asked for logprobs: an engine without rows answers without them, as before it had any. + rows_if_offered: bool = false, }; fn kindOf(v: Value) ?Value { @@ -273,10 +275,10 @@ fn format(cx: *Cx, text: ?Value) errors.Refused!?Value { return cx.refuse("text.format must be text, json_object or json_schema"); } -/// OpenAI's include values, sorted: each asks for output this server has none of (plain reasoning, no tools here). +/// OpenAI's include values, sorted: only ``message.output_text.logprobs`` adds output, where the engine has rows. const include_values = [_][]const u8{ "code_interpreter_call.outputs", "computer_call_output.output.image_url", "file_search_call.results", "message.input_image.image_url", "message.output_text.logprobs", "reasoning.encrypted_content", "web_search_call.action.sources", "web_search_call.results" }; -/// ``include`` of OpenAI's values accepted and ignored (clients send some by habit), others refused by name. +/// ``include`` of OpenAI's values accepted (clients send some by habit), others refused by name. pub fn include(cx: *Cx, given: Value) errors.Refused!void { if (given == .null) return; if (given != .array) return cx.refuse("include must be a list of strings"); @@ -294,11 +296,9 @@ pub fn include(cx: *Cx, given: Value) errors.Refused!void { pub fn translate(cx: *Cx, body: Value, history: anytype) errors.Refused!Request { const a = cx.a; if (body != .object) return cx.refuse("the request body must be a JSON object"); - _ = try fields.probabilityOptions(cx, body, false); // logprobs come on /v1/chat/completions only for (refused) |r| if (json.truthyField(body, r[0])) return cx.refuse(r[1]); if (body.get("include")) |inc| try include(cx, inc); if (body.field("truncation")) |t| if (!(t == .string and std.mem.eql(u8, t.string, "disabled"))) return cx.refuse("truncation must be \"disabled\": a prompt too long for the context is refused"); - if (json.truthyField(body, "top_logprobs")) return cx.refuse("top_logprobs is not supported"); const meta_raw = body.get("metadata"); const metadata: Value = if (meta_raw != null and meta_raw.?.truthy()) meta_raw.? else .{ .object = try json.newObject(a) }; const meta_ok = metadata == .object and metadata.object.count() <= 16 and for (metadata.object.keys(), metadata.object.values()) |k, v| { @@ -323,6 +323,16 @@ pub fn translate(cx: *Cx, body: Value, history: anytype) errors.Refused!Request const offered = try tools(cx, body.get("tools")); const choice = try toolChoice(cx, body.get("tool_choice"), offered); const chat = try json.newObject(a); + // rows come with top_logprobs or logprobs; the include name alone asks for them only where the engine has them + const listed = if (body.get("include")) |inc| inc == .array and for (inc.array) |v| { + if (std.mem.eql(u8, v.string, "message.output_text.logprobs")) break true; + } else false else false; + const rows = try json.newObject(a); + for ([_][]const u8{ "n", "logprobs", "top_logprobs" }) |k| if (body.get(k)) |v| try rows.put(a, k, v); + const asked = body.field("top_logprobs") != null or json.truthyField(body, "logprobs"); + if (listed or asked) try rows.put(a, "logprobs", .{ .bool = true }); + _ = try fields.probabilityOptions(cx, .{ .object = rows }, true); + for ([_][]const u8{ "logprobs", "top_logprobs" }) |k| if (rows.get(k)) |v| try chat.put(a, k, v); for (passed) |k| if (body.get(k)) |v| try chat.put(a, k, v); var msgs: std.ArrayList(Value) = .empty; if (instructions != null and instructions.?.string.len > 0) { @@ -374,7 +384,7 @@ pub fn translate(cx: *Cx, body: Value, history: anytype) errors.Refused!Request try echo.put(a, "truncation", .{ .string = "disabled" }); try echo.put(a, "user", body.get("user") orelse .null); try echo.put(a, "background", .{ .bool = false }); - return .{ .chat = .{ .object = chat }, .echo = echo, .added = added, .store = store, .stream = json.truthyField(body, "stream"), .format = if (rf != null) "text.format" else null }; + return .{ .chat = .{ .object = chat }, .echo = echo, .added = added, .store = store, .stream = json.truthyField(body, "stream"), .format = if (rf != null) "text.format" else null, .rows_if_offered = listed and !asked }; } test "input_file refuses remote file_url" { diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 1afe9ea063f..f5399466729 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -138,6 +138,7 @@ test { _ = @import("tool_dsml_messages_test.zig"); _ = @import("tool_single_stream_test.zig"); _ = @import("logprobs_test.zig"); + _ = @import("logprob_parts_test.zig"); _ = @import("limit_pins_test.zig"); _ = @import("flag_deps_test.zig"); _ = @import("think_split_test.zig"); From a4803c55babea2e6bd63d0899d4004db6ebcc841 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:23:54 +0000 Subject: [PATCH 2/4] server: responses logprobs refusals keep the route's error writer After the rebase, a /v1/responses logprobs ask on an engine without rows was refused by the chat plan's writer, which omits the param and code fields the route's own refusals carry. Refuse in the turn before the chat runs, through the route's writer, with main's message; include alone still serves without rows, as before. --- zig/src/server/responses.zig | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/zig/src/server/responses.zig b/zig/src/server/responses.zig index 93d9467e13d..0856baf6206 100644 --- a/zig/src/server/responses.zig +++ b/zig/src/server/responses.zig @@ -95,7 +95,14 @@ pub const TurnOptions = struct { /// One translated Responses request run as its chat completion, its events sent through ``sink``. pub fn turn(srv: *Server, a: Allocator, conn: *Conn, cx: *Cx, body: Value, t: translate_mod.Request, sink: Sink, opts: TurnOptions) Outcome { const base = newBase(srv, a, body, t) catch return .{ .streamed = null }; - if (t.rows_if_offered and !(@import("logprobs.zig").offered(srv, a) catch false)) _ = t.chat.object.orderedRemove("logprobs"); + if (!(@import("logprobs.zig").offered(srv, a) catch false)) { + // an engine without rows keeps main's refusal, written by this route's own writer; include alone serves without + if (json.truthyField(t.chat, "logprobs")) { + refuse(conn, a, "logprobs are not supported by this model or backend", 400, null); + return .{ .streamed = null }; + } + if (t.rows_if_offered) _ = t.chat.object.orderedRemove("logprobs"); + } // a reply with tools gets its rows once its calls are parsed: each item's done events wait for them const late = json.truthyField(t.chat, "logprobs") and json.truthyField(t.chat, "tools"); var reply: Reply = .{ .srv = srv, .a = a, .sink = sink, .base = base, .streaming = t.stream, .keep = t.store, .added = t.added, .cx = cx, .call_ids = .{ .key = &srv.tool_ids, .body = t.chat }, .whole_history = opts.whole_history, .late_rows = late }; From c4402df34c73b0cf65f5defbc7f88bb9cc9f66c1 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:28:20 +0000 Subject: [PATCH 3/4] responses: distinguish optional logprob includes from unsupported explicit rows --- zig/src/server/logprob_parts_test.zig | 32 +++++++++++++++++++++------ zig/src/server/responses.zig | 24 ++++++++++++++------ zig/src/server/tool_parse.zig | 4 ++-- 3 files changed, 44 insertions(+), 16 deletions(-) diff --git a/zig/src/server/logprob_parts_test.zig b/zig/src/server/logprob_parts_test.zig index 3fe07f76a3d..454f0936beb 100644 --- a/zig/src/server/logprob_parts_test.zig +++ b/zig/src/server/logprob_parts_test.zig @@ -303,11 +303,29 @@ test "logprob combinations: Responses include alone asks for rows only where the var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - var events: Events = .{ .a = a }; - const listed = try turn(a, &.{ 'H', 'i', 301 }, false, false, "{\"input\":\"x\",\"include\":[\"message.output_text.logprobs\"],\"store\":false}", &events); - const part = listed.whole.get("output").?.array[0].get("content").?.array[0]; - try std.testing.expectEqualStrings("Hi", part.get("text").?.string); - try std.testing.expectEqual(@as(usize, 0), part.get("logprobs").?.array.len); - const asked = try turn(a, &.{ 'H', 'i', 301 }, false, false, "{\"input\":\"x\",\"top_logprobs\":2,\"store\":false}", &events); - try std.testing.expectEqual(@as(u16, 400), asked.refused.status); + for ([_]bool{ false, true }) |streaming| { + var events: Events = .{ .a = a }; + const body = if (streaming) "{\"input\":\"x\",\"include\":[\"message.output_text.logprobs\"],\"store\":false,\"stream\":true}" else "{\"input\":\"x\",\"include\":[\"message.output_text.logprobs\"],\"store\":false}"; + const listed = try turn(a, &.{ 'H', 'i', 301 }, false, false, body, &events); + try std.testing.expect(if (streaming) listed == .streamed else listed == .whole); + const final = if (streaming) listed.streamed.? else listed.whole; + const part = final.get("output").?.array[0].get("content").?.array[0]; + try std.testing.expectEqualStrings("Hi", part.get("text").?.string); + try std.testing.expectEqual(@as(usize, 0), part.get("logprobs").?.array.len); + if (streaming) try std.testing.expect(events.list.items.len > 0) else try std.testing.expectEqual(@as(usize, 0), events.list.items.len); + } + for ([_][]const u8{ + "{\"input\":\"x\",\"top_logprobs\":2,\"store\":false}", + "{\"input\":\"x\",\"top_logprobs\":2,\"include\":[\"message.output_text.logprobs\"],\"store\":false,\"stream\":true}", + }) |body| { + var events: Events = .{ .a = a }; + const asked = try turn(a, &.{ 'H', 'i', 301 }, false, false, body, &events); + try std.testing.expect(asked == .refused); + try std.testing.expectEqual(@as(u16, 400), asked.refused.status); + const err = asked.refused.payload.get("error").?; + try std.testing.expectEqualStrings("invalid_request_error", err.strField("type").?); + try std.testing.expectEqualStrings("logprobs are not supported by this model or backend", err.strField("message").?); + try std.testing.expect(err.get("param").? == .null and err.get("code").? == .null); + try std.testing.expectEqual(@as(usize, 0), events.list.items.len); + } } diff --git a/zig/src/server/responses.zig b/zig/src/server/responses.zig index 0856baf6206..f462b73ea64 100644 --- a/zig/src/server/responses.zig +++ b/zig/src/server/responses.zig @@ -33,8 +33,18 @@ pub fn route(path: []const u8) ?[]const u8 { pub const Store = store_mod.Store; fn refuse(conn: *Conn, a: Allocator, message: []const u8, status: u16, param: ?[]const u8) void { - const body = std.fmt.allocPrint(a, "{{\"error\": {{\"message\": {s}, \"type\": \"invalid_request_error\", \"param\": {s}, \"code\": null}}}}", .{ json.quote(a, message, .{}) catch return, if (param) |p| json.quote(a, p, .{}) catch return else "null" }) catch return; - conn.sendJson(status, body); + routes.sendValue(conn, a, status, refusal(a, message, param) catch return); +} + +fn refusal(a: Allocator, message: []const u8, param: ?[]const u8) !Value { + const detail = try json.newObject(a); + try detail.put(a, "message", .{ .string = message }); + try detail.put(a, "type", .{ .string = "invalid_request_error" }); + try detail.put(a, "param", if (param) |p| .{ .string = p } else .null); + try detail.put(a, "code", .null); + const payload = try json.newObject(a); + try payload.put(a, "error", .{ .object = detail }); + return .{ .object = payload }; } pub fn get(srv: *Server, conn: *Conn, a: Allocator, rid: []const u8) void { @@ -96,12 +106,12 @@ pub const TurnOptions = struct { pub fn turn(srv: *Server, a: Allocator, conn: *Conn, cx: *Cx, body: Value, t: translate_mod.Request, sink: Sink, opts: TurnOptions) Outcome { const base = newBase(srv, a, body, t) catch return .{ .streamed = null }; if (!(@import("logprobs.zig").offered(srv, a) catch false)) { - // an engine without rows keeps main's refusal, written by this route's own writer; include alone serves without - if (json.truthyField(t.chat, "logprobs")) { - refuse(conn, a, "logprobs are not supported by this model or backend", 400, null); - return .{ .streamed = null }; + if (t.rows_if_offered) { + _ = t.chat.object.orderedRemove("logprobs"); + } else if (json.truthyField(t.chat, "logprobs")) { + const payload = refusal(a, "logprobs are not supported by this model or backend", null) catch return .{ .streamed = null }; + return .{ .refused = .{ .status = 400, .payload = payload } }; } - if (t.rows_if_offered) _ = t.chat.object.orderedRemove("logprobs"); } // a reply with tools gets its rows once its calls are parsed: each item's done events wait for them const late = json.truthyField(t.chat, "logprobs") and json.truthyField(t.chat, "tools"); diff --git a/zig/src/server/tool_parse.zig b/zig/src/server/tool_parse.zig index e65ca96802f..6d1252dc61f 100644 --- a/zig/src/server/tool_parse.zig +++ b/zig/src/server/tool_parse.zig @@ -18,7 +18,7 @@ pub const wrapCalls = tool_streaming.wrapCalls; const Error = tool_dsml.Error; const Call = tool_dsml.Call; -const Envelope = struct { start: usize, end: usize, payload: []const u8, complete: bool = true }; +pub const Envelope = struct { start: usize, end: usize, payload: []const u8, complete: bool = true }; pub const Parsed = struct { content: []const u8, @@ -52,7 +52,7 @@ fn allSpace(s: []const u8) bool { } /// (start, end, payload) of each tool-call block in order; a block inside an earlier one is part of it. -fn envelopes(a: Allocator, text: []const u8) Allocator.Error![]Envelope { +pub fn envelopes(a: Allocator, text: []const u8) Allocator.Error![]Envelope { var found: std.ArrayList(Envelope) = .empty; var pos: usize = 0; var dsml = tool_dsml.findOpen(text, 0); // the DSML opener at or after `pos`, searched again only once `pos` passes it From 516c095f9fc96140a310149ea9005c763adf50e8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 04:53:25 +0000 Subject: [PATCH 4/4] changelog: #3298 under Unreleased --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3131c85f3c2..c8f7fe0d2ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.8-Flash-Next on HIP stops its MTP draft chains under a 0.8 confidence floor by default instead of the HIP-wide 0.3; `--mtp-confidence` still overrides it, and the other HIP families keep 0.3. On a Strix Halo iGPU one-stream decode is about 6% faster on code and on chat, and four distinct streams about 3%, with one-stream throughput on `tools/bench_prompts.json` unchanged. Replies are unchanged. - Server: a reply that keeps a tool-call envelope as plain text now says so. `tensorfold.kept_tool_calls` counts the envelopes that name a tool the request did not offer and the malformed ones, and lists up to eight unoffered names, on the whole reply and on a stream's final chunk; `/metrics` gains `kept_tool_calls_unoffered_total` and `kept_tool_calls_malformed_total`. Replies are otherwise unchanged (#2814, for #2800). Thanks to @tarsnake for the report. +- CI: the No GPU zig and zig-windows jobs get 90 minutes, as test-host now takes about 50 (#3298). - CI: the app workflow keeps its Linux AppImage artifact for 3 days instead of GitHub's default 90 (#2966). - CI: the Linux no-GPU job runs `zig build test-host`, which collects the named host tests and compile checks apart from nine reviewed exclusions (the optional xgrammar steps, the release-path check, the two large-state timing commands, which stay available for explicit runs, and four fixture and source-pin checks held back under #2031); the build graph refuses empty checks, stale exclusions and aliases that bring excluded work back (#2095, part of #2031). Thanks to @garvrao80.