Skip to content

Latest commit

 

History

History
1737 lines (1586 loc) · 60.5 KB

server-task.cpp

File metadata and controls

1737 lines (1586 loc) · 60.5 KB
 
1
#include "server-task.h"
2
Apr 17, 2026
Apr 17, 2026
3
#include "build-info.h"
Apr 22, 2026
Apr 22, 2026
4
#include "server-chat.h"
Mar 6, 2026
Mar 6, 2026
5
#include "chat.h"
Mar 6, 2026
Mar 6, 2026
7
#include "json-schema-to-grammar.h"
8
#include "llama.h"
9
#include "sampling.h"
Jan 28, 2026
Jan 28, 2026
10
#include "speculative.h"
Mar 6, 2026
Mar 6, 2026
11
#include "server-common.h"
Aug 13, 2026
Aug 13, 2026
13
#include <sstream>
14
15
//
16
// task_params
17
//
18
19
json task_params::format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const {
20
json data = json::array();
21
for (const auto & lb : logit_bias) {
22
data.push_back(json{
23
{"bias", lb.bias},
24
{"token", lb.token},
25
});
26
}
27
return data;
28
}
29
30
json task_params::to_json(bool only_metrics) const {
31
std::vector<std::string> samplers;
32
samplers.reserve(sampling.samplers.size());
33
for (const auto & sampler : sampling.samplers) {
34
samplers.emplace_back(common_sampler_type_to_str(sampler));
35
}
36
37
json lora = json::array();
Dec 22, 2025
Dec 22, 2025
38
for (auto & it : this->lora) {
39
lora.push_back({{"id", it.first}, {"scale", it.second}});
40
}
41
42
if (only_metrics) {
43
return json {
44
{"seed", sampling.seed},
45
{"temperature", sampling.temp},
46
{"dynatemp_range", sampling.dynatemp_range},
47
{"dynatemp_exponent", sampling.dynatemp_exponent},
48
{"top_k", sampling.top_k},
49
{"top_p", sampling.top_p},
50
{"min_p", sampling.min_p},
51
{"top_n_sigma", sampling.top_n_sigma},
52
{"xtc_probability", sampling.xtc_probability},
53
{"xtc_threshold", sampling.xtc_threshold},
54
{"typical_p", sampling.typ_p},
55
{"repeat_last_n", sampling.penalty_last_n},
56
{"repeat_penalty", sampling.penalty_repeat},
57
{"presence_penalty", sampling.penalty_present},
58
{"frequency_penalty", sampling.penalty_freq},
59
{"dry_multiplier", sampling.dry_multiplier},
60
{"dry_base", sampling.dry_base},
61
{"dry_allowed_length", sampling.dry_allowed_length},
62
{"dry_penalty_last_n", sampling.dry_penalty_last_n},
63
{"mirostat", sampling.mirostat},
64
{"mirostat_tau", sampling.mirostat_tau},
65
{"mirostat_eta", sampling.mirostat_eta},
Jul 25, 2026
Jul 25, 2026
66
{"adaptive_target", sampling.adaptive_target},
67
{"adaptive_decay", sampling.adaptive_decay},
68
{"max_tokens", n_predict},
69
{"n_predict", n_predict}, // TODO: deduplicate?
70
{"n_keep", n_keep},
71
{"n_discard", n_discard},
72
{"ignore_eos", sampling.ignore_eos},
73
{"stream", stream},
74
{"n_probs", sampling.n_probs},
75
{"min_keep", sampling.min_keep},
Oct 9, 2026
Oct 9, 2026
76
{"chat_format", common_chat_format_name(chat_format)},
77
{"reasoning_format", common_reasoning_format_name(reasoning_format)},
78
{"reasoning_in_content", stream && reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY},
79
{"generation_prompt", sampling.generation_prompt},
80
{"samplers", samplers},
May 11, 2026
May 11, 2026
81
{"speculative.types", common_speculative_type_name_str(speculative.types)},
82
{"timings_per_token", timings_per_token},
83
{"post_sampling_probs", post_sampling_probs},
Jan 4, 2026
Jan 4, 2026
84
{"backend_sampling", sampling.backend_sampling},
85
{"lora", lora},
86
};
87
}
88
89
auto grammar_triggers = json::array();
90
for (const auto & trigger : sampling.grammar_triggers) {
91
server_grammar_trigger ct(trigger);
92
grammar_triggers.push_back(ct.to_json());
93
}
94
95
return json {
96
{"seed", sampling.seed},
97
{"temperature", sampling.temp},
98
{"dynatemp_range", sampling.dynatemp_range},
99
{"dynatemp_exponent", sampling.dynatemp_exponent},
100
{"top_k", sampling.top_k},
101
{"top_p", sampling.top_p},
102
{"min_p", sampling.min_p},
103
{"top_n_sigma", sampling.top_n_sigma},
104
{"xtc_probability", sampling.xtc_probability},
105
{"xtc_threshold", sampling.xtc_threshold},
106
{"typical_p", sampling.typ_p},
107
{"repeat_last_n", sampling.penalty_last_n},
108
{"repeat_penalty", sampling.penalty_repeat},
109
{"presence_penalty", sampling.penalty_present},
110
{"frequency_penalty", sampling.penalty_freq},
111
{"dry_multiplier", sampling.dry_multiplier},
112
{"dry_base", sampling.dry_base},
113
{"dry_allowed_length", sampling.dry_allowed_length},
114
{"dry_penalty_last_n", sampling.dry_penalty_last_n},
115
{"dry_sequence_breakers", sampling.dry_sequence_breakers},
116
{"mirostat", sampling.mirostat},
117
{"mirostat_tau", sampling.mirostat_tau},
118
{"mirostat_eta", sampling.mirostat_eta},
Jul 25, 2026
Jul 25, 2026
119
{"adaptive_target", sampling.adaptive_target},
120
{"adaptive_decay", sampling.adaptive_decay},
121
{"stop", antiprompt},
122
{"max_tokens", n_predict},
123
{"n_predict", n_predict}, // TODO: deduplicate?
124
{"n_keep", n_keep},
125
{"n_discard", n_discard},
126
{"ignore_eos", sampling.ignore_eos},
127
{"stream", stream},
128
{"logit_bias", format_logit_bias(sampling.logit_bias)},
129
{"n_probs", sampling.n_probs},
130
{"min_keep", sampling.min_keep},
Mar 19, 2026
Mar 19, 2026
131
{"grammar", common_grammar_value(sampling.grammar)},
132
{"grammar_lazy", sampling.grammar_lazy},
133
{"grammar_triggers", grammar_triggers},
134
{"preserved_tokens", sampling.preserved_tokens},
Oct 9, 2026
Oct 9, 2026
135
{"chat_format", common_chat_format_name(chat_format)},
136
{"reasoning_format", common_reasoning_format_name(reasoning_format)},
137
{"reasoning_in_content", stream && reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY},
138
{"generation_prompt", sampling.generation_prompt},
139
{"samplers", samplers},
May 11, 2026
May 11, 2026
140
{"speculative.types", common_speculative_type_name_str(speculative.types)},
141
{"timings_per_token", timings_per_token},
142
{"post_sampling_probs", post_sampling_probs},
Jan 4, 2026
Jan 4, 2026
143
{"backend_sampling", sampling.backend_sampling},
144
{"lora", lora},
145
};
146
}
147
Jan 22, 2026
Jan 22, 2026
148
//
149
// task_result_state
150
//
Oct 9, 2026
Oct 9, 2026
151
task_result_state::task_result_state(common_chat_session session)
152
: chat_session(std::move(session))
153
, chat_msg(chat_session.msg())
May 17, 2026
May 17, 2026
154
, oai_resp_id("resp_" + random_string())
155
, oai_resp_reasoning_id("rs_" + random_string())
156
, oai_resp_message_id("msg_" + random_string()) {
157
}
158
Jan 22, 2026
Jan 22, 2026
159
common_chat_msg task_result_state::update_chat_msg(
Oct 7, 2026
Oct 7, 2026
160
const common_chat_input & added,
Jan 22, 2026
Jan 22, 2026
161
bool is_partial,
Mar 6, 2026
Mar 6, 2026
162
std::vector<common_chat_msg_diff> & diffs,
163
bool filter_tool_calls) {
Jan 22, 2026
Jan 22, 2026
164
auto msg_prv_copy = chat_msg;
Oct 9, 2026
Oct 9, 2026
165
auto new_msg = is_partial ? chat_session.feed(added) : chat_session.finish(added);
Jan 22, 2026
Jan 22, 2026
166
if (!new_msg.empty()) {
167
new_msg.set_tool_call_ids(generated_tool_call_ids, gen_tool_call_id);
168
chat_msg = new_msg;
Mar 6, 2026
Mar 6, 2026
169
auto all_diffs = common_chat_msg_diff::compute_diffs(msg_prv_copy, chat_msg);
170
171
if (!filter_tool_calls) {
172
diffs = std::move(all_diffs);
173
} else {
174
for (auto & d : all_diffs) {
175
// If this is a new type of delta, flush all currently pending tool call names
176
for (size_t i = 0; i < chat_msg.tool_calls.size(); ++i) {
177
if (sent_tool_call_names.count(i) || chat_msg.tool_calls[i].name.empty()) {
178
continue;
179
}
180
if (d.tool_call_index != i || !d.tool_call_delta.arguments.empty()) {
181
common_chat_msg_diff header;
182
header.tool_call_index = i;
183
header.tool_call_delta.id = chat_msg.tool_calls[i].id;
184
header.tool_call_delta.name = chat_msg.tool_calls[i].name;
185
diffs.push_back(std::move(header));
186
sent_tool_call_names.insert(i);
187
}
188
}
189
190
if (d.tool_call_index == std::string::npos) {
191
diffs.push_back(std::move(d));
192
} else {
193
size_t i = d.tool_call_index;
194
if (sent_tool_call_names.count(i)) {
195
if (!d.tool_call_delta.arguments.empty()) {
196
d.tool_call_delta.name = "";
197
d.tool_call_delta.id = "";
198
diffs.push_back(std::move(d));
199
}
200
} else {
201
// Not sent yet.
202
if (!d.tool_call_delta.arguments.empty() || !is_partial) {
203
d.tool_call_delta.name = chat_msg.tool_calls[i].name;
204
d.tool_call_delta.id = chat_msg.tool_calls[i].id;
205
diffs.push_back(std::move(d));
206
sent_tool_call_names.insert(i);
207
} else {
208
// Suppress
209
}
210
}
211
}
212
}
213
// Final check at EOF
214
if (!is_partial) {
215
for (size_t i = 0; i < chat_msg.tool_calls.size(); ++i) {
216
if (!sent_tool_call_names.count(i) && !chat_msg.tool_calls[i].name.empty()) {
217
common_chat_msg_diff header;
218
header.tool_call_index = i;
219
header.tool_call_delta.id = chat_msg.tool_calls[i].id;
220
header.tool_call_delta.name = chat_msg.tool_calls[i].name;
221
diffs.push_back(std::move(header));
222
sent_tool_call_names.insert(i);
223
}
224
}
225
}
226
}
Jan 22, 2026
Jan 22, 2026
227
}
228
return chat_msg;
229
}
230
231
//
232
// result_prompt_progress
233
//
234
json result_prompt_progress::to_json() const {
235
return json {
236
{"total", total},
237
{"cache", cache},
238
{"processed", processed},
239
{"time_ms", time_ms},
240
};
241
}
242
243
static inline std::string stop_type_to_str(stop_type type) {
244
switch (type) {
245
case STOP_TYPE_EOS: return "eos";
246
case STOP_TYPE_WORD: return "word";
247
case STOP_TYPE_LIMIT: return "limit";
248
default: return "none";
249
}
250
}
251
252
//
253
// completion_token_output
254
//
255
256
json completion_token_output::to_json(bool post_sampling_probs) const {
257
json probs_for_token = json::array();
258
for (const auto & p : probs) {
259
std::string txt(p.txt);
260
txt.resize(validate_utf8(txt));
261
probs_for_token.push_back(json {
262
{"id", p.tok},
263
{"token", txt},
264
{"bytes", str_to_bytes(p.txt)},
265
{
266
post_sampling_probs ? "prob" : "logprob",
267
post_sampling_probs ? p.prob : logarithm(p.prob)
268
},
269
});
270
}
271
return probs_for_token;
272
}
273
274
json completion_token_output::probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs) {
275
json out = json::array();
276
for (const auto & p : probs) {
277
std::string txt(p.text_to_send);
278
txt.resize(validate_utf8(txt));
279
out.push_back(json {
280
{"id", p.tok},
281
{"token", txt},
282
{"bytes", str_to_bytes(p.text_to_send)},
283
{
284
post_sampling_probs ? "prob" : "logprob",
285
post_sampling_probs ? p.prob : logarithm(p.prob)
286
},
287
{
288
post_sampling_probs ? "top_probs" : "top_logprobs",
289
p.to_json(post_sampling_probs)
290
},
291
});
292
}
293
return out;
294
}
295
296
float completion_token_output::logarithm(float x) {
Aug 22, 2026
Aug 22, 2026
297
// the JSON library converts -inf to null, so we need to prevent that
298
return x == 0.0f ? std::numeric_limits<float>::lowest() : std::log(x);
299
}
300
301
std::vector<unsigned char> completion_token_output::str_to_bytes(const std::string & str) {
302
std::vector<unsigned char> bytes;
303
for (unsigned char c : str) {
304
bytes.push_back(c);
305
}
306
return bytes;
307
}
308
309
//
310
// server_task_result_cmpl_final
311
//
312
json server_task_result_cmpl_final::to_json() {
Dec 4, 2025
Dec 4, 2025
313
GGML_ASSERT(is_updated && "update() must be called before to_json()");
Nov 28, 2025
Nov 28, 2025
314
switch (res_type) {
315
case TASK_RESPONSE_TYPE_NONE:
316
return to_json_non_oaicompat();
Nov 28, 2025
Nov 28, 2025
317
case TASK_RESPONSE_TYPE_OAI_CMPL:
318
return to_json_oaicompat();
Nov 28, 2025
Nov 28, 2025
319
case TASK_RESPONSE_TYPE_OAI_CHAT:
320
return stream ? to_json_oaicompat_chat_stream() : to_json_oaicompat_chat();
Jan 21, 2026
Jan 21, 2026
321
case TASK_RESPONSE_TYPE_OAI_RESP:
322
return stream ? to_json_oaicompat_resp_stream() : to_json_oaicompat_resp();
Apr 14, 2026
Apr 14, 2026
323
case TASK_RESPONSE_TYPE_OAI_ASR:
324
return to_json_oaicompat_asr();
Nov 28, 2025
Nov 28, 2025
325
case TASK_RESPONSE_TYPE_ANTHROPIC:
326
return stream ? to_json_anthropic_stream() : to_json_anthropic();
Nov 28, 2025
Nov 28, 2025
328
GGML_ASSERT(false && "Invalid task_response_type");
329
}
330
}
331
332
json server_task_result_cmpl_final::to_json_non_oaicompat() {
333
json res = json {
334
{"index", index},
Oct 7, 2026
Oct 7, 2026
335
{"content", content.text},
Dec 4, 2025
Dec 4, 2025
336
{"tokens", tokens},
337
{"id_slot", id_slot},
338
{"stop", true},
339
{"model", oaicompat_model},
340
{"tokens_predicted", n_decoded},
341
{"tokens_evaluated", n_prompt_tokens},
342
{"generation_settings", generation_params.to_json()},
343
{"prompt", prompt},
344
{"has_new_line", has_new_line},
345
{"truncated", truncated},
346
{"stop_type", stop_type_to_str(stop)},
347
{"stopping_word", stopping_word},
348
{"tokens_cached", n_tokens_cached},
Aug 13, 2026
Aug 13, 2026
349
{"timings", stats.to_json()},
350
};
351
if (!stream && !probs_output.empty()) {
352
res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs);
353
}
354
return response_fields.empty() ? res : json_get_nested_values(response_fields, res);
355
}
356
Mar 19, 2026
Mar 19, 2026
357
json server_task_result_cmpl_final::usage_json_oaicompat() {
358
return json {
359
{"completion_tokens", n_decoded},
360
{"prompt_tokens", n_prompt_tokens},
361
{"total_tokens", n_decoded + n_prompt_tokens},
362
{"prompt_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
363
};
364
}
365
366
json server_task_result_cmpl_final::to_json_oaicompat() {
367
std::time_t t = std::time(0);
368
json logprobs = json(nullptr); // OAI default to null
369
if (!stream && probs_output.size() > 0) {
370
logprobs = json{
371
{"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
372
};
373
}
374
json finish_reason = "length";
375
if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
376
finish_reason = "stop";
377
}
378
json res = json {
379
{"choices", json::array({
380
json{
Oct 7, 2026
Oct 7, 2026
381
{"text", content.text},
382
{"index", index},
383
{"logprobs", logprobs},
384
{"finish_reason", finish_reason},
385
}
386
})},
387
{"created", t},
388
{"model", oaicompat_model},
Apr 17, 2026
Apr 17, 2026
389
{"system_fingerprint", std::string(llama_build_info())},
390
{"object", "text_completion"},
Mar 19, 2026
Mar 19, 2026
391
{"usage", usage_json_oaicompat()},
392
{"id", oaicompat_cmpl_id}
393
};
394
395
// extra fields for debugging purposes
396
if (verbose) {
397
res["__verbose"] = to_json_non_oaicompat();
398
}
Aug 13, 2026
Aug 13, 2026
399
if (stats.is_set()) {
Aug 22, 2026
Aug 22, 2026
400
res["timings"] = stats.to_json();
401
}
402
403
return res;
404
}
405
406
json server_task_result_cmpl_final::to_json_oaicompat_chat() {
407
std::string finish_reason = "length";
408
common_chat_msg msg;
409
if (!oaicompat_msg.empty()) {
410
msg = oaicompat_msg;
411
} else {
412
msg.role = "assistant";
Oct 7, 2026
Oct 7, 2026
413
msg.content = content.text;
414
}
415
if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
416
finish_reason = msg.tool_calls.empty() ? "stop" : "tool_calls";
417
}
418
419
json choice {
420
{"finish_reason", finish_reason},
Dec 6, 2025
Dec 6, 2025
421
{"index", index},
Jan 22, 2026
Jan 22, 2026
422
{"message", msg.to_json_oaicompat()},
423
};
424
425
if (!stream && probs_output.size() > 0) {
426
choice["logprobs"] = json{
427
{"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
428
};
429
}
430
431
std::time_t t = std::time(0);
432
433
json res = json {
434
{"choices", json::array({choice})},
435
{"created", t},
436
{"model", oaicompat_model},
Apr 17, 2026
Apr 17, 2026
437
{"system_fingerprint", std::string(llama_build_info())},
438
{"object", "chat.completion"},
Mar 19, 2026
Mar 19, 2026
439
{"usage", usage_json_oaicompat()},
440
{"id", oaicompat_cmpl_id}
441
};
442
443
// extra fields for debugging purposes
444
if (verbose) {
445
res["__verbose"] = to_json_non_oaicompat();
446
}
Aug 13, 2026
Aug 13, 2026
447
if (stats.is_set()) {
Aug 22, 2026
Aug 22, 2026
448
res["timings"] = stats.to_json();
449
}
450
451
return res;
452
}
453
454
json server_task_result_cmpl_final::to_json_oaicompat_chat_stream() {
455
std::time_t t = std::time(0);
456
std::string finish_reason = "length";
457
if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
458
finish_reason = oaicompat_msg.tool_calls.empty() ? "stop" : "tool_calls";
459
}
460
461
json deltas = json::array();
462
for (const auto & diff : oaicompat_msg_diffs) {
463
deltas.push_back({
464
{"choices", json::array({
465
json {
466
{"finish_reason", nullptr},
Mar 8, 2026
Mar 8, 2026
467
{"index", index},
Apr 22, 2026
Apr 22, 2026
468
{"delta", server_chat_msg_diff_to_json_oaicompat(diff)},
469
},
470
})},
471
{"created", t},
472
{"id", oaicompat_cmpl_id},
473
{"model", oaicompat_model},
Apr 17, 2026
Apr 17, 2026
474
{"system_fingerprint", std::string(llama_build_info())},
475
{"object", "chat.completion.chunk"},
476
});
477
}
478
479
deltas.push_back({
480
{"choices", json::array({
481
json {
482
{"finish_reason", finish_reason},
Mar 8, 2026
Mar 8, 2026
483
{"index", index},
484
{"delta", json::object()},
485
},
486
})},
487
{"created", t},
488
{"id", oaicompat_cmpl_id},
489
{"model", oaicompat_model},
Apr 17, 2026
Apr 17, 2026
490
{"system_fingerprint", std::string(llama_build_info())},
491
{"object", "chat.completion.chunk"},
492
});
493
494
if (include_usage) {
495
// OpenAI API spec for chat.completion.chunks specifies an empty `choices` array for the last chunk when including usage
496
// https://platform.openai.com/docs/api-reference/chat_streaming/streaming#chat_streaming/streaming-choices
497
deltas.push_back({
498
{"choices", json::array()},
499
{"created", t},
500
{"id", oaicompat_cmpl_id},
501
{"model", oaicompat_model},
Apr 17, 2026
Apr 17, 2026
502
{"system_fingerprint", std::string(llama_build_info())},
503
{"object", "chat.completion.chunk"},
Mar 19, 2026
Mar 19, 2026
504
{"usage", usage_json_oaicompat()},
Aug 13, 2026
Aug 13, 2026
508
if (stats.is_set()) {
Aug 22, 2026
Aug 22, 2026
509
deltas.back()["timings"] = stats.to_json();
510
}
511
512
// extra fields for debugging purposes
513
if (verbose && !deltas.empty()) {
514
deltas.front()["__verbose"] = to_json_non_oaicompat();
515
}
516
517
return deltas;
518
}
519
Jan 21, 2026
Jan 21, 2026
520
json server_task_result_cmpl_final::to_json_oaicompat_resp() {
521
common_chat_msg msg;
522
if (!oaicompat_msg.empty()) {
523
msg = oaicompat_msg;
524
} else {
525
msg.role = "assistant";
Oct 7, 2026
Oct 7, 2026
526
msg.content = content.text;
Jan 21, 2026
Jan 21, 2026
527
}
528
529
std::vector<json> output;
530
531
if (msg.reasoning_content != "") {
532
output.push_back(json {
533
{"id", "rs_" + random_string()},
534
{"summary", json::array()},
535
{"type", "reasoning"},
536
{"content", json::array({ json {
537
{"text", msg.reasoning_content},
538
{"type", "reasoning_text"},
539
}})},
540
{"encrypted_content", ""},
541
{"status", "completed"},
542
});
543
}
544
545
if (msg.content != "") {
546
output.push_back(json {
547
{"content", json::array({ json {
548
{"type", "output_text"},
549
{"annotations", json::array()},
550
{"logprobs", json::array()},
551
{"text", msg.content},
552
}})},
553
{"id", "msg_" + random_string()},
554
{"role", msg.role},
555
{"status", "completed"},
556
{"type", "message"},
557
});
558
}
559
560
for (const common_chat_tool_call & tool_call : oaicompat_msg.tool_calls) {
561
output.push_back(json {
Jun 22, 2026
Jun 22, 2026
562
{"id", "fc_" + tool_call.id},
Jan 21, 2026
Jan 21, 2026
563
{"type", "function_call"},
564
{"status", "completed"},
565
{"arguments", tool_call.arguments},
Jun 22, 2026
Jun 22, 2026
566
{"call_id", "call_" + tool_call.id},
Jan 21, 2026
Jan 21, 2026
567
{"name", tool_call.name},
568
});
569
}
570
571
std::time_t t = std::time(0);
572
json res = {
573
{"completed_at", t},
574
{"created_at", t},
575
{"id", oai_resp_id},
576
{"model", oaicompat_model},
577
{"object", "response"},
578
{"output", output},
579
{"status", "completed"},
580
{"usage", json {
581
{"input_tokens", n_prompt_tokens},
582
{"output_tokens", n_decoded},
583
{"total_tokens", n_decoded + n_prompt_tokens},
Mar 19, 2026
Mar 19, 2026
584
{"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
Jan 21, 2026
Jan 21, 2026
585
}},
586
};
587
588
return res;
589
}
590
591
json server_task_result_cmpl_final::to_json_oaicompat_resp_stream() {
592
std::vector<json> server_sent_events;
593
std::vector<json> output;
Oct 20, 2026
Oct 20, 2026
594
size_t output_index = 0;
Jan 21, 2026
Jan 21, 2026
595
596
if (oaicompat_msg.reasoning_content != "") {
Oct 20, 2026
Oct 20, 2026
597
const size_t item_output_index = output_index++;
Jan 21, 2026
Jan 21, 2026
598
const json output_item = json {
599
{"id", oai_resp_reasoning_id},
600
{"summary", json::array()},
601
{"type", "reasoning"},
602
{"content", json::array({ json {
603
{"text", oaicompat_msg.reasoning_content},
604
{"type", "reasoning_text"},
605
}})},
606
{"encrypted_content", ""},
607
};
608
609
server_sent_events.push_back(json {
610
{"event", "response.output_item.done"},
611
{"data", json {
612
{"type", "response.output_item.done"},
Oct 20, 2026
Oct 20, 2026
613
{"output_index", item_output_index},
Jan 21, 2026
Jan 21, 2026
614
{"item", output_item}
615
}}
616
});
617
output.push_back(output_item);
618
}
619
620
if (oaicompat_msg.content != "") {
Oct 20, 2026
Oct 20, 2026
621
const size_t item_output_index = output_index++;
Jan 21, 2026
Jan 21, 2026
622
server_sent_events.push_back(json {
623
{"event", "response.output_text.done"},
624
{"data", json {
625
{"type", "response.output_text.done"},
626
{"item_id", oai_resp_message_id},
Oct 20, 2026
Oct 20, 2026
627
{"output_index", item_output_index},
628
{"content_index", 0},
Jan 21, 2026
Jan 21, 2026
629
{"text", oaicompat_msg.content}
630
}}
631
});
632
633
const json content_part = {
634
{"type", "output_text"},
635
{"annotations", json::array()},
636
{"logprobs", json::array()},
637
{"text", oaicompat_msg.content}
638
};
639
640
server_sent_events.push_back(json {
641
{"event", "response.content_part.done"},
642
{"data", json {
643
{"type", "response.content_part.done"},
644
{"item_id", oai_resp_message_id},
Oct 20, 2026
Oct 20, 2026
645
{"output_index", item_output_index},
646
{"content_index", 0},
Jan 21, 2026
Jan 21, 2026
647
{"part", content_part}
648
}}
649
});
650
const json output_item = {
651
{"type", "message"},
652
{"status", "completed"},
653
{"id", oai_resp_message_id},
654
{"content", json::array({content_part})},
655
{"role", "assistant"}
656
};
657
658
server_sent_events.push_back(json {
659
{"event", "response.output_item.done"},
660
{"data", json {
661
{"type", "response.output_item.done"},
Oct 20, 2026
Oct 20, 2026
662
{"output_index", item_output_index},
Jan 21, 2026
Jan 21, 2026
663
{"item", output_item}
664
}}
665
});
666
output.push_back(output_item);
667
}
668
669
for (const common_chat_tool_call & tool_call : oaicompat_msg.tool_calls) {
Oct 20, 2026
Oct 20, 2026
670
const size_t item_output_index = output_index++;
Jan 21, 2026
Jan 21, 2026
671
const json output_item = {
Jun 22, 2026
Jun 22, 2026
672
{"id", "fc_" + tool_call.id},
Jan 21, 2026
Jan 21, 2026
673
{"type", "function_call"},
674
{"status", "completed"},
675
{"arguments", tool_call.arguments},
Jun 22, 2026
Jun 22, 2026
676
{"call_id", "call_" + tool_call.id},
Jan 21, 2026
Jan 21, 2026
677
{"name", tool_call.name}
678
};
679
server_sent_events.push_back(json {
680
{"event", "response.output_item.done"},
681
{"data", json {
682
{"type", "response.output_item.done"},
Oct 20, 2026
Oct 20, 2026
683
{"output_index", item_output_index},
Jan 21, 2026
Jan 21, 2026
684
{"item", output_item}
685
}}
686
});
687
output.push_back(output_item);
688
}
689
690
std::time_t t = std::time(0);
691
server_sent_events.push_back(json {
692
{"event", "response.completed"},
693
{"data", json {
694
{"type", "response.completed"},
695
{"response", json {
696
{"id", oai_resp_id},
697
{"object", "response"},
698
{"created_at", t},
699
{"status", "completed"},
700
{"model", oaicompat_model},
701
{"output", output},
702
{"usage", json {
703
{"input_tokens", n_prompt_tokens},
704
{"output_tokens", n_decoded},
Mar 19, 2026
Mar 19, 2026
705
{"total_tokens", n_decoded + n_prompt_tokens},
706
{"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
Jan 21, 2026
Jan 21, 2026
707
}}
708
}},
709
}}
710
});
711
Aug 13, 2026
Aug 13, 2026
712
if (stats.is_set()) {
Aug 22, 2026
Aug 22, 2026
713
server_sent_events.back().at("data")["timings"] = stats.to_json();
Jul 7, 2026
Jul 7, 2026
714
}
715
Jan 21, 2026
Jan 21, 2026
716
return server_sent_events;
717
}
718
Apr 14, 2026
Apr 14, 2026
719
json server_task_result_cmpl_final::to_json_oaicompat_asr() {
720
json event = json {
721
{"type", "transcript.text.done"},
Apr 22, 2026
Apr 22, 2026
722
{"text", oaicompat_msg.content},
Apr 14, 2026
Apr 14, 2026
723
{"usage", json {
724
{"type", "tokens"},
725
{"input_tokens", n_prompt_tokens},
726
{"output_tokens", n_decoded},
727
{"total_tokens", n_decoded + n_prompt_tokens},
728
{"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
729
}},
730
};
731
return event;
732
}
733
Nov 28, 2025
Nov 28, 2025
734
json server_task_result_cmpl_final::to_json_anthropic() {
735
std::string stop_reason = "max_tokens";
736
if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
737
stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
738
}
739
740
json content_blocks = json::array();
741
742
common_chat_msg msg;
743
if (!oaicompat_msg.empty()) {
744
msg = oaicompat_msg;
745
} else {
746
msg.role = "assistant";
Oct 7, 2026
Oct 7, 2026
747
msg.content = content.text;
Nov 28, 2025
Nov 28, 2025
748
}
749
Jan 6, 2026
Jan 6, 2026
750
// thinking block comes first (Anthropic extended thinking format)
751
if (!msg.reasoning_content.empty()) {
752
content_blocks.push_back({
753
{"type", "thinking"},
754
{"thinking", msg.reasoning_content},
755
{"signature", ""} // empty signature for local models (no cryptographic verification)
756
});
757
}
758
Nov 28, 2025
Nov 28, 2025
759
if (!msg.content.empty()) {
760
content_blocks.push_back({
761
{"type", "text"},
762
{"text", msg.content}
763
});
764
}
765
766
for (const auto & tool_call : msg.tool_calls) {
767
json tool_use_block = {
768
{"type", "tool_use"},
769
{"id", tool_call.id},
770
{"name", tool_call.name}
771
};
772
773
try {
774
tool_use_block["input"] = json::parse(tool_call.arguments);
775
} catch (const std::exception &) {
776
tool_use_block["input"] = json::object();
777
}
778
779
content_blocks.push_back(tool_use_block);
780
}
781
782
json res = {
783
{"id", oaicompat_cmpl_id},
784
{"type", "message"},
785
{"role", "assistant"},
786
{"content", content_blocks},
787
{"model", oaicompat_model},
788
{"stop_reason", stop_reason},
789
{"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)},
790
{"usage", {
Mar 19, 2026
Mar 19, 2026
791
{"cache_read_input_tokens", n_prompt_tokens_cache},
792
{"input_tokens", n_prompt_tokens - n_prompt_tokens_cache},
Nov 28, 2025
Nov 28, 2025
793
{"output_tokens", n_decoded}
794
}}
795
};
796
797
return res;
798
}
799
800
json server_task_result_cmpl_final::to_json_anthropic_stream() {
801
json events = json::array();
802
803
std::string stop_reason = "max_tokens";
804
if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
805
stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
806
}
807
Jan 6, 2026
Jan 6, 2026
808
bool has_thinking = !oaicompat_msg.reasoning_content.empty();
809
bool has_text = !oaicompat_msg.content.empty();
Nov 28, 2025
Nov 28, 2025
810
size_t num_tool_calls = oaicompat_msg.tool_calls.size();
811
Jan 6, 2026
Jan 6, 2026
812
// content block indices: thinking (0) -> text (0 or 1) -> tool_use (n+)
813
size_t thinking_block_index = 0;
814
size_t text_block_index = has_thinking ? 1 : 0;
815
816
bool thinking_block_started = false;
817
bool text_block_started = false;
Nov 28, 2025
Nov 28, 2025
818
std::unordered_set<size_t> tool_calls_started;
819
820
for (const auto & diff : oaicompat_msg_diffs) {
Jan 6, 2026
Jan 6, 2026
821
// handle thinking/reasoning content
822
if (!diff.reasoning_content_delta.empty()) {
823
if (!thinking_block_started) {
824
events.push_back({
825
{"event", "content_block_start"},
826
{"data", {
827
{"type", "content_block_start"},
828
{"index", thinking_block_index},
829
{"content_block", {
830
{"type", "thinking"},
831
{"thinking", ""}
832
}}
833
}}
834
});
835
thinking_block_started = true;
836
}
837
838
events.push_back({
839
{"event", "content_block_delta"},
840
{"data", {
841
{"type", "content_block_delta"},
842
{"index", thinking_block_index},
843
{"delta", {
844
{"type", "thinking_delta"},
845
{"thinking", diff.reasoning_content_delta}
846
}}
847
}}
848
});
849
}
850
851
// handle regular text content
Nov 28, 2025
Nov 28, 2025
852
if (!diff.content_delta.empty()) {
853
if (!text_block_started) {
854
events.push_back({
855
{"event", "content_block_start"},
856
{"data", {
857
{"type", "content_block_start"},
Jan 6, 2026
Jan 6, 2026
858
{"index", text_block_index},
Nov 28, 2025
Nov 28, 2025
859
{"content_block", {
860
{"type", "text"},
861
{"text", ""}
862
}}
863
}}
864
});
865
text_block_started = true;
866
}
867
868
events.push_back({
869
{"event", "content_block_delta"},
870
{"data", {
871
{"type", "content_block_delta"},
Jan 6, 2026
Jan 6, 2026
872
{"index", text_block_index},
Nov 28, 2025
Nov 28, 2025
873
{"delta", {
874
{"type", "text_delta"},
875
{"text", diff.content_delta}
876
}}
877
}}
878
});
879
}
880
Jan 6, 2026
Jan 6, 2026
881
// handle tool calls
Nov 28, 2025
Nov 28, 2025
882
if (diff.tool_call_index != std::string::npos) {
Jan 6, 2026
Jan 6, 2026
883
size_t content_block_index = (has_thinking ? 1 : 0) + (has_text ? 1 : 0) + diff.tool_call_index;
Nov 28, 2025
Nov 28, 2025
884
885
if (tool_calls_started.find(diff.tool_call_index) == tool_calls_started.end()) {
886
const auto & full_tool_call = oaicompat_msg.tool_calls[diff.tool_call_index];
887
888
events.push_back({
889
{"event", "content_block_start"},
890
{"data", {
891
{"type", "content_block_start"},
892
{"index", content_block_index},
893
{"content_block", {
894
{"type", "tool_use"},
895
{"id", full_tool_call.id},
896
{"name", full_tool_call.name}
897
}}
898
}}
899
});
900
tool_calls_started.insert(diff.tool_call_index);
901
}
902
903
if (!diff.tool_call_delta.arguments.empty()) {
904
events.push_back({
905
{"event", "content_block_delta"},
906
{"data", {
907
{"type", "content_block_delta"},
908
{"index", content_block_index},
909
{"delta", {
910
{"type", "input_json_delta"},
911
{"partial_json", diff.tool_call_delta.arguments}
912
}}
913
}}
914
});
915
}
916
}
917
}
918
Jan 6, 2026
Jan 6, 2026
919
// close content blocks in order
920
if (has_thinking) {
921
// Anthropic API requires a signature_delta before closing thinking blocks
922
// We use an empty signature since we can't generate a cryptographic signature for local models
923
events.push_back({
924
{"event", "content_block_delta"},
925
{"data", {
926
{"type", "content_block_delta"},
927
{"index", thinking_block_index},
928
{"delta", {
929
{"type", "signature_delta"},
930
{"signature", ""}
931
}}
932
}}
933
});
934
events.push_back({
935
{"event", "content_block_stop"},
936
{"data", {
937
{"type", "content_block_stop"},
938
{"index", thinking_block_index}
939
}}
940
});
941
}
942
Nov 28, 2025
Nov 28, 2025
943
if (has_text) {
944
events.push_back({
945
{"event", "content_block_stop"},
946
{"data", {
947
{"type", "content_block_stop"},
Jan 6, 2026
Jan 6, 2026
948
{"index", text_block_index}
Nov 28, 2025
Nov 28, 2025
949
}}
950
});
951
}
952
953
for (size_t i = 0; i < num_tool_calls; i++) {
Jan 6, 2026
Jan 6, 2026
954
size_t content_block_index = (has_thinking ? 1 : 0) + (has_text ? 1 : 0) + i;
Nov 28, 2025
Nov 28, 2025
955
events.push_back({
956
{"event", "content_block_stop"},
957
{"data", {
958
{"type", "content_block_stop"},
959
{"index", content_block_index}
960
}}
961
});
962
}
963
964
events.push_back({
965
{"event", "message_delta"},
966
{"data", {
967
{"type", "message_delta"},
968
{"delta", {
969
{"stop_reason", stop_reason},
970
{"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)}
971
}},
972
{"usage", {
973
{"output_tokens", n_decoded}
974
}}
975
}}
976
});
977
978
events.push_back({
979
{"event", "message_stop"},
980
{"data", {
981
{"type", "message_stop"}
982
}}
983
});
984
985
return events;
986
}
987
988
//
989
// server_task_result_cmpl_partial
990
//
Jan 21, 2026
Jan 21, 2026
991
void server_task_result_cmpl_partial::update(task_result_state & state) {
992
is_updated = true;
Jun 8, 2026
Jun 8, 2026
993
if (is_begin) {
994
return; // begin marker only flushes headers, skip parsing
995
}
Jan 21, 2026
Jan 21, 2026
996
state.update_chat_msg(content, true, oaicompat_msg_diffs);
997
998
// Copy current state for use in to_json_*() (reflects state BEFORE this chunk)
999
thinking_block_started = state.thinking_block_started;
1000
text_block_started = state.text_block_started;