-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathapi_server.cpp
More file actions
2095 lines (1994 loc) · 85.2 KB
/
Copy pathapi_server.cpp
File metadata and controls
2095 lines (1994 loc) · 85.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Ported from: vllm/entrypoints/openai/api_server.py @ e24d1b24 + the
// per-endpoint api_router modules. See api_server.h for scope + the cpp-httplib
// dependency deviation.
#include "vllm/entrypoints/openai/api_server.h"
#include <atomic>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <exception>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <optional>
#include <mutex>
#include <random>
#include <thread>
#include <type_traits>
#include <stdexcept>
#include <string>
#include <utility>
#include <httplib/httplib.h>
#include <nlohmann/json.hpp>
#include "vllm/http_transport_abi.h"
#include "vllm/entrypoints/chat_template.h" // ChatTemplateError -> HTTP 400
#include "vllm/entrypoints/openai/protocol.h"
#include "vllm/entrypoints/openai/request_logger.h"
#include "vllm/tokenizer/tokenizer.h"
#include "vllm/v1/engine/async_llm.h"
#include "vllm/v1/engine/input_processor.h" // InputValidationError -> HTTP 400
#include "vllm/v1/metrics/loggers.h"
namespace vllm::entrypoints::openai {
namespace {
// Build the OpenAI ErrorResponse JSON body for a failed request
// (serve/utils/error_response.py::create_error_response). `code` == the HTTP
// status code (upstream ErrorInfo.code carries it).
ApiServer::DispatchResult MakeError(int status, const std::string& type,
const std::string& message) {
ErrorResponse err;
err.error.message = message;
err.error.type = type;
err.error.code = status;
ApiServer::DispatchResult r;
r.status = status;
r.content_type = "application/json";
r.body = nlohmann::json(err).dump();
return r;
}
} // namespace
#ifdef VLLM_WITH_DIARIZATION
static ApiServer::DispatchResult HandleAudioDiarizations(
const ApiServer& server,
const std::string& file_bytes,
const std::string& /*response_format*/) {
auto diarizer = server.diarizer_callback();
if (!diarizer) {
return MakeError(404, "NotFoundError", "diarization not enabled");
}
try {
auto segs = diarizer(reinterpret_cast<const uint8_t*>(file_bytes.data()),
file_bytes.size());
nlohmann::json j = nlohmann::json::array();
for (const auto& s : segs) {
j.push_back({{"speaker", s.speaker},
{"start", s.start},
{"end", s.end}});
}
ApiServer::DispatchResult r;
r.status = 200;
r.content_type = "application/json";
r.body = j.dump();
return r;
} catch (const std::exception& e) {
return MakeError(500, "InternalServerError", e.what());
}
}
static ApiServer::DispatchResult HandleAudioSas(
const ApiServer& server,
const std::string& file_bytes,
const std::string& /*response_format*/) {
auto sas_fn = server.sas_callback();
if (!sas_fn) {
return MakeError(404, "NotFoundError", "speaker-attributed ASR not enabled");
}
try {
auto result = sas_fn(reinterpret_cast<const uint8_t*>(file_bytes.data()),
file_bytes.size());
nlohmann::json j;
j["segments"] = nlohmann::json::array();
for (const auto& u : result.utterances) {
j["segments"].push_back({
{"speaker", u.speaker},
{"text", u.text},
{"start", u.start},
{"end", u.end},
{"confidence", u.conf}
});
}
ApiServer::DispatchResult r;
r.status = 200;
r.content_type = "application/json";
r.body = j.dump();
return r;
} catch (const std::exception& e) {
return MakeError(500, "InternalServerError", e.what());
}
}
#endif
// SystemOne helpers (ParseSystemOneBody, BuildSystemOneAnswer*, R2, R4, etc.)
// are defined in systemone.h/.cpp. Imported here so the handlers below can
// call them unqualified, matching the former anonymous-namespace usage.
using namespace systemone;
namespace {
size_t HttpWorkerCount(size_t max_concurrent_streams) {
if (max_concurrent_streams == 0) {
throw std::invalid_argument("max_concurrent_streams must be positive");
}
if (max_concurrent_streams >
std::numeric_limits<size_t>::max() -
ApiServer::kControlWorkerHeadroom) {
throw std::invalid_argument("max_concurrent_streams is too large");
}
return max_concurrent_streams + ApiServer::kControlWorkerHeadroom;
}
size_t HttpWorkerCount(size_t max_concurrent_streams,
ApiServer::HttpWorkerPoolMode mode) {
const size_t fixed_count = HttpWorkerCount(max_concurrent_streams);
return mode == ApiServer::HttpWorkerPoolMode::kCapacityFixed ? fixed_count
: 0;
}
} // namespace
// The listener type this server constructs, named ONCE so that
// `vllm::ApiServerListenerIsTls()` below and the member two dozen lines down
// cannot disagree. The same `CPPHTTPLIB_OPENSSL_SUPPORT` define that gives the
// HuggingFace fetcher `https` also makes `httplib::SSLServer` compilable, and
// ENG-HF-MODEL-DOWNLOAD W5 deliberately does NOT enable a listener: that is a
// separate decision with its own certificate, key, flags and documentation.
// Changing this alias changes the listener AND the reported value together.
using ApiServerListener = httplib::Server;
// Opaque httplib::Server (pimpl — keeps httplib.h out of api_server.h).
struct ApiServer::Impl {
Impl(size_t max_concurrent_streams, HttpWorkerPoolMode mode)
: http_worker_count(HttpWorkerCount(max_concurrent_streams, mode)) {
// cpp-httplib's default pool starts at hardware_concurrency()-1 and only
// grows if idle_thread_count_ is exactly zero at enqueue. A burst can queue
// accepted sockets while that counter is stale-positive; long-lived SSE
// jobs then prevent the queued sockets from ever being read. A fixed floor
// derived from the configured stream capacity removes that race and makes
// resource use reproducible.
if (http_worker_count != 0) {
server.new_task_queue = [workers = http_worker_count]() {
return new httplib::ThreadPool(workers);
};
}
// Mirror vLLM's serving transport: vLLM serves through uvicorn over asyncio
// (entrypoints/launcher.py:71,76), and asyncio disables Nagle on every
// accepted TCP stream socket by default (CPython asyncio/base_events.py
// _set_nodelay → setsockopt(IPPROTO_TCP, TCP_NODELAY, 1), invoked from
// selector_events.py _SelectorSocketTransport). cpp-httplib defaults it off
// (third_party/httplib/httplib.h:142) and applies it to the accepted socket
// only when tcp_nodelay_ is set (httplib.h:12083). Per-token SSE frames are
// tiny writes, so enabling TCP_NODELAY here puts each streamed frame on the
// wire immediately instead of coalescing it under Nagle/delayed-ACK.
server.set_tcp_nodelay(true);
}
ApiServerListener server;
size_t http_worker_count;
// The legacy LLMEngine serving constructors remain for small synthetic
// tests and embedding compatibility. Unlike AsyncLLM, that engine is driven
// synchronously by its caller, so retain one shared lock for that seam only.
// Production handlers use AsyncLLM and never take this request-level lock.
std::mutex legacy_engine_mutex;
};
ApiServer::ApiServer(OpenAIServingCompletion& completion,
OpenAIServingChat& chat, OpenAIServingModels& models,
std::string version, size_t max_concurrent_streams,
HttpWorkerPoolMode worker_pool_mode)
: completion_(&completion),
chat_(&chat),
models_(models),
version_(std::move(version)),
impl_(std::make_unique<Impl>(max_concurrent_streams, worker_pool_mode)) {}
// Serving-less construction (transcription-only servers, ARCH-ONE-SURFACE
// ROW 1): no AsyncLLM exists, so the generate handlers stay null and their
// routes are not registered — vLLM's task-conditional route registration
// (api_server.py:255-265) expressed at construction.
ApiServer::ApiServer(OpenAIServingModels& models, std::string version,
size_t max_concurrent_streams,
HttpWorkerPoolMode worker_pool_mode)
: models_(models),
version_(std::move(version)),
impl_(std::make_unique<Impl>(max_concurrent_streams, worker_pool_mode)) {}
ApiServer::~ApiServer() {
// Drain the async /v1/videos workers before the job store they write into is
// destroyed. Threads are joined, never detached, precisely so this ordering is
// guaranteed rather than hoped for.
std::vector<std::thread> workers;
{
std::lock_guard<std::mutex> lock(video_workers_mutex_);
workers.swap(video_workers_);
}
for (auto& worker : workers) {
if (worker.joinable()) worker.join();
}
}
// ── SERVE-REQUEST-LENGTH-GUARD (#1541) ──────────────────────────────────────
// A REFUSING byte bound at the request boundary, checked BEFORE any
// tokenization. Its two constraints come from
// .agents/specs/bpe-quadratic-merge.md `## Defence in depth`:
//
// 1. It refuses and NEVER truncates. Shortening a prompt returns model output
// for text the caller did not send.
// 2. It is here, at the boundary, and not in
// vllm::v1::InputProcessor::ValidatePromptLen, which needs the token count
// the expensive step produces and so cannot run before that step.
//
// vLLM HAS NO EQUIVALENT for a prompt BYTE bound, and this is checked rather
// than assumed at pin 555967922:
// - vllm/entrypoints/openai/cli_args.py:292-294 `h11_max_incomplete_event_size`
// (default 4 MB, vllm/entrypoints/serve/utils/constants.py:9) is an h11
// PARSER limit. Its own docstring says "header or body", but h11 applies it
// to the undrained receive buffer only (h11/_connection.py:485, whose
// comment reads "431 is Request header fields too large which is pretty
// much the only situation where we can get here"), so a body is not bounded
// by it.
// - vllm/entrypoints/openai/completion/protocol.py:536-553
// `validate_prompt_list_length` bounds the COUNT of prompts in a list
// (VLLM_MAX_COMPLETION_PROMPTS, default 1024, vllm/envs.py:110), not their
// bytes. It is the REGISTER this refusal mirrors: refused during request
// validation, ahead of the router, with the limit named in the message.
// - vllm/entrypoints/speech_to_text/base/utils.py:38-46
// `read_upload_with_limit` IS a refusing byte bound at the request boundary
// (VLLM_MAX_AUDIO_CLIP_FILESIZE_MB, default 25, vllm/envs.py:79) -- on the
// audio-upload surface, not on a text prompt.
// So the shape is mirrored and the number is ours, which is why it is derived
// below rather than picked.
std::optional<ApiServer::DispatchResult> ApiServer::refuse_oversized_prompt(
size_t prompt_bytes) const {
if (max_prompt_bytes_ == 0 || prompt_bytes <= max_prompt_bytes_) {
return std::nullopt;
}
return MakeError(
400, "BadRequestError",
"prompt length " + std::to_string(prompt_bytes) +
" bytes exceeds the maximum allowed prompt length of " +
std::to_string(max_prompt_bytes_) + " bytes (max_model_len " +
std::to_string(max_model_len_) + " x " +
std::to_string(max_token_bytes_) +
" bytes, the longest token in this tokenizer's vocabulary). A prompt "
"this long cannot fit in " +
std::to_string(max_model_len_) +
" tokens, so it is refused here rather than tokenized first. The "
"request is refused, not truncated.");
}
void ApiServer::set_tokenizer(const vllm::tok::Tokenizer* tokenizer,
int64_t max_model_len) {
tokenizer_ = tokenizer;
max_model_len_ = max_model_len;
// The bound is exactly `max_model_len * MaxTokenBytes()` -- see
// max_prompt_bytes(). Tokenizer::MaxPromptBytes holds the one copy of the
// derivation: 0 (unbounded) whenever either factor is unknown, and clamped
// rather than wrapped on the overflow a hostile max_model_len could produce.
max_token_bytes_ = tokenizer != nullptr ? tokenizer->MaxTokenBytes() : 0;
max_prompt_bytes_ =
tokenizer != nullptr ? tokenizer->MaxPromptBytes(max_model_len) : 0;
}
ApiServer::DispatchResult ApiServer::handle_completions(
const std::string& request_body) {
if (completion_ == nullptr) {
// vLLM's api_router `if handler is None: raise NotImplementedError` mirror
// for a serving-less (transcription-only) server; the socket layer never
// registers the route in that mode, so this answers direct dispatch only.
return MakeError(500, "InternalServerError",
"The model does not support Completions API "
"(transcription-only server)");
}
// completion/api_router.py:46 (create_completion): parse → check_model →
// handler → JSON (non-stream) or text/event-stream (stream).
nlohmann::json body;
try {
body = nlohmann::json::parse(request_body);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("Invalid JSON body: ") + e.what());
}
CompletionRequest request;
try {
from_json(body, request);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("Invalid request: ") + e.what());
}
// SERVE-REQUEST-LENGTH-GUARD (#1541): before check_model and before the
// encode inside create_completion. Ahead of the model lookup because the
// bound is a property of the REQUEST, which is where vLLM decides its own
// analogue too -- validate_prompt_list_length is a pydantic model_validator
// (completion/protocol.py:536), so it runs at body validation, ahead of the
// router's check_model.
if (auto refusal = refuse_oversized_prompt(request.prompt.size())) {
return *refusal;
}
if (!models_.check_model(request.model)) {
return MakeError(404, "NotFoundError",
"The model `" + request.model.value_or("") +
"` does not exist.");
}
CompletionResult result;
try {
std::unique_lock<std::mutex> legacy_lock(impl_->legacy_engine_mutex,
std::defer_lock);
if (!completion_->uses_async_engine()) legacy_lock.lock();
result = completion_->create_completion(request);
} catch (const vllm::v1::InputValidationError& e) {
// The request itself is unservable (today: a prompt at or past
// max_model_len). Upstream raises ValueError from _validate_prompt_len and
// create_error_response maps ValueError to BadRequestError / 400
// (serve/utils/error_response.py:62-65). Caught AHEAD of the generic arm
// below, which would otherwise report a client mistake as a server fault.
return MakeError(400, "BadRequestError", e.what());
} catch (const std::exception& e) {
// DISCRIMINATOR: attribute a 500 to its endpoint + model + raw cause so a
// benchmark driver that only sees the generic HTTP body can still recover
// the true failure. std::cerr only (survives SIGKILL escalation).
std::cerr << "api-server: 500 endpoint=/v1/completions model="
<< request.model.value_or("") << " what=" << e.what() << "\n";
return MakeError(500, "InternalServerError", e.what());
}
DispatchResult out;
if (result.streaming) {
out.streaming = true;
out.content_type = "text/event-stream";
out.sse_chunks = std::move(result.sse_chunks);
out.sse_stream = std::move(result.sse_stream);
} else {
out.status = 200;
out.content_type = "application/json";
out.body = nlohmann::json(*result.response).dump();
}
return out;
}
ApiServer::DispatchResult ApiServer::handle_chat_completions(
const std::string& request_body) {
if (chat_ == nullptr) {
return MakeError(500, "InternalServerError",
"The model does not support Chat Completions API "
"(transcription-only server)");
}
{
LogHttpIngress("POST", "/v1/chat/completions", request_body.size());
}
// chat_completion/api_router.py:53 (create_chat_completion).
nlohmann::json body;
try {
body = nlohmann::json::parse(request_body);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("Invalid JSON body: ") + e.what());
}
ChatCompletionRequest request;
try {
from_json(body, request);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("Invalid request: ") + e.what());
}
// SERVE-REQUEST-LENGTH-GUARD (#1541). The measured quantity is the SUM of the
// message texts, because that is what the chat template concatenates into the
// one prompt the tokenizer then sees. `content` carries the joined text spans
// even when the wire form was a content-part ARRAY (protocol.h ChatMessage),
// so inline base64 media -- which lives in `content_parts`, is never
// tokenized as text, and would make a raw body-byte bound refuse legitimate
// multimodal requests -- is correctly not counted here.
size_t prompt_bytes = 0;
for (const ChatMessage& m : request.messages) {
if (m.content.has_value()) prompt_bytes += m.content->size();
}
if (auto refusal = refuse_oversized_prompt(prompt_bytes)) {
return *refusal;
}
if (!models_.check_model(request.model)) {
return MakeError(404, "NotFoundError",
"The model `" + request.model.value_or("") +
"` does not exist.");
}
ChatCompletionResult result;
try {
std::unique_lock<std::mutex> legacy_lock(impl_->legacy_engine_mutex,
std::defer_lock);
if (!chat_->uses_async_engine()) legacy_lock.lock();
result = chat_->create_chat_completion(request);
} catch (const vllm::v1::InputValidationError& e) {
// Same mapping as /v1/completions above (error_response.py:62-65).
LogRequestError("", "/v1/chat/completions", e.what());
return MakeError(400, "BadRequestError", e.what());
} catch (const vllm::entrypoints::ChatTemplateError& e) {
// A render failure is a CLIENT error, because the conversation and the
// chat_template_kwargs that reached the template are the request's. Upstream
// reaches 400 twice over: safe_apply_chat_template wraps ANY exception out
// of apply_chat_template into a ValueError (vllm/renderers/hf.py:785-789 @
// 555967922), and create_error_response maps ValueError/TypeError
// (error_response.py:48-52) AND jinja2.TemplateError and its subclasses
// (error_response.py:61-65) to BadRequestError. Without this arm the render
// fell through to the generic 500 below, and /tokenize -- which already
// answers 400 for the identical body -- disagreed with this endpoint.
LogRequestError("", "/v1/chat/completions", e.what());
return MakeError(400, "BadRequestError", e.what());
} catch (const std::exception& e) {
std::cerr << "api-server: 500 endpoint=/v1/chat/completions model="
<< request.model.value_or("") << " what=" << e.what() << "\n";
LogRequestError("", "/v1/chat/completions", e.what());
return MakeError(500, "InternalServerError", e.what());
}
DispatchResult out;
if (result.streaming) {
out.streaming = true;
out.content_type = "text/event-stream";
out.sse_chunks = std::move(result.sse_chunks);
out.sse_stream = std::move(result.sse_stream);
} else {
out.status = 200;
out.content_type = "application/json";
out.body = nlohmann::json(*result.response).dump();
}
return out;
}
ApiServer::DispatchResult ApiServer::handle_models() const {
// models/api_router.py:21 (show_available_models).
DispatchResult out;
out.status = 200;
out.content_type = "application/json";
out.body = nlohmann::json(models_.show_available_models()).dump();
return out;
}
ApiServer::DispatchResult ApiServer::handle_health() const {
// Upstream calls engine_client.check_health() before returning an empty 200.
// This bounded server currently exposes process liveness only.
DispatchResult out;
out.status = 200;
out.content_type = "text/plain";
out.body.clear();
return out;
}
ApiServer::DispatchResult ApiServer::handle_version() const {
// serve/instrumentator/basic.py:53 — {"version": <ver>}.
DispatchResult out;
out.status = 200;
out.content_type = "application/json";
out.body = nlohmann::json{{"version", version_}}.dump();
return out;
}
ApiServer::DispatchResult ApiServer::handle_ping() const {
// sagemaker/api_router.py:47-50 — GET/POST /ping is a liveness probe that
// returns the same empty 200 as /health.
return handle_health();
}
namespace {
ApiServer::DispatchResult VideoJsonOk(std::string body) {
ApiServer::DispatchResult out;
out.status = 200;
out.content_type = "application/json";
out.body = std::move(body);
return out;
}
} // namespace
std::string ApiServer::video_model_warning(
const ::vllm::openai::VideoRequest& request) const {
// OpenAI clients send the SORA model name ("sora-2-pro"); this server generates
// with whatever video model it was started with, whose name they cannot know.
// Refusing would defeat the compatibility, and ignoring would hide a real
// mismatch, so the request is honoured and the divergence is STATED on the job.
if (request.model.empty() || models_.is_base_model(request.model)) return {};
return "requested model '" + request.model +
"' is not a served model ('" + models_.model_name() +
"'); generated with the video model this server was started with";
}
ApiServer::DispatchResult ApiServer::handle_audio_transcriptions(
const std::string& file_bytes, const std::string& response_format) const {
// Mirror of vLLM speech_to_text/transcription: api_router.py:31
// `create_transcriptions` reads the multipart upload
// (read_upload_with_limit) and hands the bytes to
// OpenAIServingTranscription.create_transcription (serving.py:50), which
// answers TranscriptionResponse {"text": ...} for response_format json and
// the raw text otherwise. The transcription itself runs through the ONE
// library seam (ParakeetTranscriber) — the same code path vllm_transcribe
// drives, so HTTP and FFI cannot drift.
if (!transcriber_) {
// The api_router `if handler is None: raise NotImplementedError` mirror;
// the socket layer never registers the route without a transcriber.
return MakeError(500, "InternalServerError",
"The model does not support Transcriptions API");
}
if (file_bytes.empty()) {
return MakeError(400, "BadRequestError",
"Expected a non-empty `file` upload (16-bit PCM mono "
"RIFF/WAVE)");
}
const std::string fmt = response_format.empty() ? "json" : response_format;
if (fmt != "json" && fmt != "text") {
// verbose_json / srt / vtt are NAMED RESIDUALS of this fold (protocol.py
// AudioResponseFormat lists them; nothing here produces segment timing).
return MakeError(400, "BadRequestError",
"response_format '" + fmt +
"' is not supported (supported: json, text; "
"verbose_json/srt/vtt are named residuals)");
}
try {
const ::vllm::multimodal::ParakeetTranscription result = transcriber_(
reinterpret_cast<const uint8_t*>(file_bytes.data()), file_bytes.size());
if (!result.has_text) {
return MakeError(500, "InternalServerError",
"the checkpoint ships no tokenizer.json, so ids-only "
"transcription has no OpenAI response shape");
}
DispatchResult r;
if (fmt == "text") {
r.content_type = "text/plain; charset=utf-8";
r.body = result.text;
} else {
r.body = nlohmann::json{{"text", result.text}}.dump();
}
return r;
} catch (const std::exception& e) {
// Undecodable audio (not RIFF/WAVE, not PCM16 mono, wrong sample rate) is
// a caller error; the pipeline names the cause.
return MakeError(400, "BadRequestError", e.what());
}
}
// ── Speaker diarization handler (ABI v30) ────────────────────────────────
#ifdef VLLM_WITH_DIARIZATION
ApiServer::DispatchResult ApiServer::handle_audio_diarizations(
const std::string& file_bytes,
const std::string& /*response_format*/) const {
if (!diarizer_) {
return MakeError(500, "InternalServerError",
"The model does not support Diarization API");
}
if (file_bytes.empty()) {
return MakeError(400, "BadRequestError",
"Expected a non-empty `file` upload (16-bit PCM mono RIFF/WAVE)");
}
try {
auto segs = diarizer_(
reinterpret_cast<const uint8_t*>(file_bytes.data()), file_bytes.size());
nlohmann::json j = nlohmann::json::array();
for (const auto& s : segs) {
j.push_back({{"speaker", s.speaker},
{"start", s.start},
{"end", s.end}});
}
DispatchResult r;
r.content_type = "application/json";
r.body = j.dump();
return r;
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError", e.what());
}
}
ApiServer::DispatchResult ApiServer::handle_audio_sas(
const std::string& file_bytes,
const std::string& /*response_format*/) const {
if (!sas_) {
return MakeError(500, "InternalServerError",
"The model does not support Speaker-Attributed ASR API");
}
if (file_bytes.empty()) {
return MakeError(400, "BadRequestError",
"Expected a non-empty `file` upload (16-bit PCM mono RIFF/WAVE)");
}
try {
auto result = sas_(
reinterpret_cast<const uint8_t*>(file_bytes.data()), file_bytes.size());
nlohmann::json j;
j["segments"] = nlohmann::json::array();
for (const auto& u : result.utterances) {
j["segments"].push_back({
{"speaker", u.speaker},
{"text", u.text},
{"start", u.start},
{"end", u.end},
{"confidence", u.conf}
});
}
DispatchResult r;
r.content_type = "application/json";
r.body = j.dump();
return r;
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError", e.what());
}
}
#endif
ApiServer::DispatchResult ApiServer::handle_embeddings(
const std::string& request_body) const {
// Mirror of vLLM pooling/embed/api_router.py:28 `create_embedding` over the
// EmbeddingCompletionRequest shape (embed/protocol.py:34: `model` + `input`
// as ONE string or an ARRAY of strings) and the EmbeddingResponse shape
// (embed/protocol.py:173-185). The embedding itself runs through the ONE
// engine path (LLMEngine::embed -> registry forward -> PoolingRunner) — the
// same code path vllm_embed drives, so HTTP and FFI cannot drift.
if (!embedder_) {
// The api_router `if handler is None` mirror (embed/api_router.py:22-25);
// the socket layer never registers the route without an embedder.
return MakeError(500, "InternalServerError",
"The model does not support Embeddings API");
}
nlohmann::json body;
try {
body = nlohmann::json::parse(request_body);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("invalid JSON body: ") + e.what());
}
if (!body.is_object()) {
return MakeError(400, "BadRequestError", "request body must be an object");
}
// model: honoured like every other serving handler — an unknown name is 404.
if (body.contains("model") && body["model"].is_string() &&
!models_.is_base_model(body["model"].get<std::string>())) {
return MakeError(404, "NotFoundError",
"The model `" + body["model"].get<std::string>() +
"` does not exist.");
}
// encoding_format: float (the default) only; base64 is a NAMED residual.
if (body.contains("encoding_format") && body["encoding_format"].is_string() &&
body["encoding_format"].get<std::string>() != "float") {
return MakeError(400, "BadRequestError",
"encoding_format '" +
body["encoding_format"].get<std::string>() +
"' is not supported (supported: float; base64 is a "
"named residual)");
}
if (body.contains("dimensions") && !body["dimensions"].is_null()) {
// Matryoshka truncation is a NAMED residual of this fold (the pooler op
// supports it; the request plumb does not yet).
return MakeError(400, "BadRequestError",
"dimensions is not supported yet (named residual)");
}
// input: ONE string or an ARRAY of strings (embed/protocol.py:34
// EmbeddingCompletionRequest via CompletionRequestMixin). Token-array
// inputs are a NAMED residual.
std::vector<std::string> inputs;
if (!body.contains("input")) {
return MakeError(400, "BadRequestError", "input is required");
}
if (body["input"].is_string()) {
inputs.push_back(body["input"].get<std::string>());
} else if (body["input"].is_array()) {
for (const nlohmann::json& item : body["input"]) {
if (!item.is_string()) {
return MakeError(400, "BadRequestError",
"input must be a string or an array of strings "
"(token-array inputs are a named residual)");
}
inputs.push_back(item.get<std::string>());
}
if (inputs.empty()) {
return MakeError(400, "BadRequestError",
"input must contain at least one string");
}
} else {
return MakeError(400, "BadRequestError",
"input must be a string or an array of strings");
}
try {
const EmbeddingBatch batch = embedder_(inputs);
if (batch.embeddings.size() != inputs.size()) {
return MakeError(500, "InternalServerError",
"embedder returned a mismatched batch");
}
nlohmann::json data = nlohmann::json::array();
for (size_t i = 0; i < batch.embeddings.size(); ++i) {
data.push_back(nlohmann::json{
{"index", static_cast<int64_t>(i)},
{"object", "embedding"},
{"embedding", batch.embeddings[i]},
});
}
// id: "embd-<counter>" (upstream f"embd-{random_uuid()}",
// embed/protocol.py:180 — the serving_completion.h counter stand-in).
static std::atomic<uint64_t> embd_counter{0};
DispatchResult r;
r.body = nlohmann::json{
{"id", "embd-" + std::to_string(embd_counter.fetch_add(1))},
{"object", "list"},
{"created", static_cast<int64_t>(std::time(nullptr))},
{"model", models_.model_name()},
{"data", std::move(data)},
{"usage",
nlohmann::json{{"prompt_tokens", batch.prompt_tokens},
{"total_tokens", batch.prompt_tokens}}},
}.dump();
return r;
} catch (const std::exception& e) {
return MakeError(500, "InternalServerError", e.what());
}
}
// SystemOne helpers moved to systemone.h/.cpp (shared with vllm_c.cpp C ABI).
ApiServer::DispatchResult ApiServer::handle_ner(
const std::string& request_body) const {
if (!ner_) {
return MakeError(500, "InternalServerError",
"The model does not support NER");
}
nlohmann::json body;
try {
body = nlohmann::json::parse(request_body);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("invalid JSON body: ") + e.what());
}
if (!body.is_object()) {
return MakeError(400, "BadRequestError", "request body must be an object");
}
// model: honoured like every other serving handler.
if (body.contains("model") && body["model"].is_string() &&
!models_.is_base_model(body["model"].get<std::string>())) {
return MakeError(404, "NotFoundError",
"The model `" + body["model"].get<std::string>() +
"` does not exist.");
}
// text: required string.
if (!body.contains("text") || !body["text"].is_string()) {
return MakeError(400, "BadRequestError",
"text is required and must be a string");
}
const std::string text = body["text"].get<std::string>();
// labels: required array of strings.
if (!body.contains("labels") || !body["labels"].is_array()) {
return MakeError(400, "BadRequestError",
"labels is required and must be an array of strings");
}
std::vector<std::string> labels;
for (const nlohmann::json& item : body["labels"]) {
if (!item.is_string()) {
return MakeError(400, "BadRequestError",
"labels must be an array of strings");
}
labels.push_back(item.get<std::string>());
}
if (labels.empty()) {
return MakeError(400, "BadRequestError",
"labels must contain at least one string");
}
// threshold: optional, default 0.5.
float threshold = 0.5F;
if (body.contains("threshold") && body["threshold"].is_number()) {
threshold = body["threshold"].get<float>();
}
// max_width: optional, default 12 (0 = use model default).
int64_t max_width = 12;
if (body.contains("max_width") && body["max_width"].is_number_integer()) {
max_width = body["max_width"].get<int64_t>();
}
try {
const NerResult result = ner_(text, labels, threshold, max_width);
nlohmann::json entities = nlohmann::json::array();
for (const NerEntity& e : result.entities) {
entities.push_back(nlohmann::json{
{"label", e.label},
{"text", e.text},
{"start", e.start},
{"end", e.end},
{"confidence", e.confidence},
});
}
static std::atomic<uint64_t> ner_counter{0};
DispatchResult r;
r.body = nlohmann::json{
{"id", "ner-" + std::to_string(ner_counter.fetch_add(1))},
{"object", "ner"},
{"created", static_cast<int64_t>(std::time(nullptr))},
{"model", models_.model_name()},
{"entities", std::move(entities)},
{"usage",
nlohmann::json{{"prompt_tokens", result.prompt_tokens},
{"total_tokens", result.prompt_tokens}}},
}.dump();
return r;
} catch (const std::exception& e) {
return MakeError(500, "InternalServerError", e.what());
}
}
ApiServer::DispatchResult ApiServer::handle_score(
const std::string& request_body) const {
if (!score_) {
return MakeError(500, "InternalServerError",
"The model does not support scoring");
}
nlohmann::json body;
try {
body = nlohmann::json::parse(request_body);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("invalid JSON body: ") + e.what());
}
if (!body.is_object()) {
return MakeError(400, "BadRequestError", "request body must be an object");
}
// model: honoured like every other serving handler.
if (body.contains("model") && body["model"].is_string() &&
!models_.is_base_model(body["model"].get<std::string>())) {
return MakeError(404, "NotFoundError",
"The model `" + body["model"].get<std::string>() +
"` does not exist.");
}
// context: required string.
if (!body.contains("context") || !body["context"].is_string()) {
return MakeError(400, "BadRequestError",
"context is required and must be a string");
}
const std::string context = body["context"].get<std::string>();
// options: required array of strings.
if (!body.contains("options") || !body["options"].is_array()) {
return MakeError(400, "BadRequestError",
"options is required and must be an array of strings");
}
std::vector<std::string> options;
for (const auto& opt : body["options"]) {
if (!opt.is_string()) {
return MakeError(400, "BadRequestError",
"each option must be a string");
}
options.push_back(opt.get<std::string>());
}
if (options.empty()) {
return MakeError(400, "BadRequestError",
"options must not be empty");
}
auto start = std::chrono::steady_clock::now();
try {
ScoreResult result = score_(context, options);
auto end = std::chrono::steady_clock::now();
double latency_ms =
std::chrono::duration<double, std::milli>(end - start).count();
nlohmann::json probs = nlohmann::json::array();
for (float p : result.probabilities) {
probs.push_back(R4(p));
}
DispatchResult r;
r.body = nlohmann::json{
{"model", models_.model_name()},
{"probabilities", std::move(probs)},
{"winner", result.winner},
{"confidence", R4(result.confidence)},
{"usage", nlohmann::json{{"input_tokens", result.prompt_tokens},
{"output_tokens", 0}}},
{"latency_ms", R2(latency_ms)},
}.dump();
return r;
} catch (const std::exception& e) {
return MakeError(500, "InternalServerError", e.what());
}
}
ApiServer::DispatchResult ApiServer::handle_systemone(
const std::string& request_body) const {
// MODEL-NIMBLE: the request-level seam owns parsing and validation, because
// its request contract (openjev's) is not ParseSystemOneBody's.
if (systemone_request_) {
nlohmann::ordered_json body;
try {
body = nlohmann::ordered_json::parse(request_body);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("invalid JSON body: ") + e.what());
}
const auto start = std::chrono::steady_clock::now();
try {
nlohmann::ordered_json result = systemone_request_(body);
const double latency_ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - start)
.count();
const bool named = body.is_object() && body.contains("model") &&
body["model"].is_string();
nlohmann::ordered_json out = nlohmann::ordered_json::object();
out["model"] = named ? body["model"].get<std::string>() : models_.model_name();
out["answers"] = std::move(result["answers"]);
out["usage"] = std::move(result["usage"]);
out["latency_ms"] = R2(latency_ms);
DispatchResult r;
r.body = out.dump();
return r;
} catch (const std::invalid_argument& e) {
return MakeError(400, "BadRequestError", e.what());
} catch (const std::exception& e) {
return MakeError(500, "InternalServerError", e.what());
}
}
if (!ner_ && !decision_) {
return MakeError(500, "InternalServerError",
"The model does not support SystemOne");
}
nlohmann::ordered_json body;
try {
body = nlohmann::ordered_json::parse(request_body);
} catch (const std::exception& e) {
return MakeError(400, "BadRequestError",
std::string("invalid JSON body: ") + e.what());
}
auto parsed = ParseSystemOneBody(body);
if (!parsed.ok) {
return MakeError(parsed.error_status, parsed.error_type, parsed.error_msg);
}
// Decision path (MODEL-LAYA): one forward per question.
if (decision_) {
auto start = std::chrono::steady_clock::now();
try {
nlohmann::json answers = nlohmann::json::object();
int64_t total_tokens = 0;
for (const auto& q : parsed.questions) {
auto result = decision_(parsed.text, q.type, q.instructions,
RenderDecisionOptions(q));
total_tokens += result.prompt_tokens;
answers[q.id] = BuildSystemOneAnswerDecision(q, result);
}
auto end = std::chrono::steady_clock::now();
double latency_ms =
std::chrono::duration<double, std::milli>(end - start).count();
DispatchResult r;
r.body = nlohmann::json{
{"model", parsed.model.empty() ? models_.model_name() : parsed.model},
{"answers", std::move(answers)},
{"usage", nlohmann::json{{"input_tokens", total_tokens},
{"output_tokens", 0}}},
{"latency_ms", R2(latency_ms)},
}.dump();
return r;
} catch (const std::exception& e) {
return MakeError(500, "InternalServerError", e.what());
}
}
// NER path (MODEL-GLINER25): one NER call, answers from shared result.
auto start = std::chrono::steady_clock::now();
try {
const NerResult result = ner_(parsed.text, parsed.all_labels,
parsed.threshold, parsed.max_width);
auto end = std::chrono::steady_clock::now();
double latency_ms =
std::chrono::duration<double, std::milli>(end - start).count();
nlohmann::json answers = nlohmann::json::object();
for (const auto& q : parsed.questions) {
answers[q.id] = BuildSystemOneAnswer(q, result);
}
DispatchResult r;
r.body = nlohmann::json{
{"model", parsed.model.empty() ? models_.model_name() : parsed.model},
{"answers", std::move(answers)},
{"usage", nlohmann::json{{"input_tokens", result.prompt_tokens},
{"output_tokens", 0}}},
{"latency_ms", R2(latency_ms)},