This repository was archived by the owner on Jul 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathmodels.cc
More file actions
845 lines (783 loc) · 28.9 KB
/
models.cc
File metadata and controls
845 lines (783 loc) · 28.9 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
#include "database/models.h"
#include <drogon/HttpTypes.h>
#include <filesystem>
#include <optional>
#include "config/gguf_parser.h"
#include "config/yaml_config.h"
#include "models.h"
#include "trantor/utils/Logger.h"
#include "utils/cortex_utils.h"
#include "utils/engine_constants.h"
#include "utils/file_manager_utils.h"
#include "utils/http_util.h"
#include "utils/logging_utils.h"
#include "utils/string_utils.h"
namespace {
std::string ToJsonStringWithPrecision(Json::Value& input, int precision = 2) {
(void)precision;
Json::StreamWriterBuilder wbuilder;
wbuilder.settings_["precision"] = 2;
return Json::writeString(wbuilder, input);
}
} // namespace
void Models::PullModel(const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) {
if (!http_util::HasFieldInReq(req, callback, "model")) {
return;
}
auto model_handle = req->getJsonObject()->get("model", "").asString();
if (model_handle.empty()) {
Json::Value ret;
ret["result"] = "Bad Request";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
return;
}
std::optional<std::string> desired_model_id = std::nullopt;
auto id = req->getJsonObject()->get("id", "").asString();
if (!id.empty()) {
desired_model_id = id;
}
std::optional<std::string> desired_model_name = std::nullopt;
auto name_value = req->getJsonObject()->get("name", "").asString();
if (!name_value.empty()) {
desired_model_name = name_value;
}
auto result = model_service_->PullModel(model_handle, desired_model_id,
desired_model_name);
if (result.has_error()) {
Json::Value ret;
ret["message"] = result.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
Json::Value ret;
ret["message"] = "Model start downloading!";
ret["task"] = result.value().ToJsonCpp();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::GetModelPullInfo(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) const {
if (!http_util::HasFieldInReq(req, callback, "model")) {
return;
}
auto model_handle = (*(req->getJsonObject())).get("model", "").asString();
auto res = model_service_->GetModelPullInfo(model_handle);
if (res.has_error()) {
Json::Value ret;
ret["message"] = res.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
auto const& info = res.value();
Json::Value ret;
Json::Value downloaded(Json::arrayValue);
for (auto const& s : info.downloaded_models) {
downloaded.append(s);
}
Json::Value avails(Json::arrayValue);
for (auto const& s : info.available_models) {
avails.append(s);
}
ret["id"] = info.id;
ret["modelSource"] = info.model_source;
ret["defaultBranch"] = info.default_branch;
ret["message"] = "Get model pull information successfully";
ret["downloadedModels"] = downloaded;
ret["availableModels"] = avails;
ret["downloadUrl"] = info.download_url;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::AbortPullModel(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) {
if (!http_util::HasFieldInReq(req, callback, "taskId")) {
return;
}
auto task_id = (*(req->getJsonObject())).get("taskId", "").asString();
if (task_id.empty()) {
Json::Value ret;
ret["result"] = "Bad Request";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
return;
}
auto result = model_service_->AbortDownloadModel(task_id);
if (result.has_error()) {
Json::Value ret;
ret["message"] = result.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
Json::Value ret;
ret["message"] = "Download stopped successfully";
ret["taskId"] = result.value();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::ListModel(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) const {
(void)req;
namespace fs = std::filesystem;
namespace fmu = file_manager_utils;
Json::Value ret;
ret["object"] = "list";
Json::Value data(Json::arrayValue);
model_service_->ForceIndexingModelList();
// Iterate through directory
config::YamlHandler yaml_handler;
auto list_entry = db_service_->LoadModelList();
if (list_entry) {
for (const auto& model_entry : list_entry.value()) {
try {
if (model_entry.status == cortex::db::ModelStatus::Downloadable) {
Json::Value obj;
obj["id"] = model_entry.model;
obj["model"] = model_entry.model;
auto status_to_string = [](cortex::db::ModelStatus status) {
switch (status) {
case cortex::db::ModelStatus::Remote:
return "remote";
case cortex::db::ModelStatus::Downloaded:
return "downloaded";
case cortex::db::ModelStatus::Downloadable:
return "downloadable";
}
return "unknown";
};
obj["modelSource"] = model_entry.model_source;
obj["status"] = status_to_string(model_entry.status);
obj["engine"] = model_entry.engine;
obj["metadata"] = model_entry.metadata;
data.append(std::move(obj));
continue;
}
if (model_entry.engine == kVllmEngine) {
Json::Value obj;
obj["id"] = model_entry.model;
obj["model"] = model_entry.model;
obj["engine"] = model_entry.engine;
obj["status"] = "downloaded";
data.append(std::move(obj));
continue;
}
yaml_handler.ModelConfigFromFile(
fmu::ToAbsoluteCortexDataPath(
fs::path(model_entry.path_to_model_yaml))
.string());
auto model_config = yaml_handler.GetModelConfig();
if (!engine_service_->IsRemoteEngine(model_config.engine)) {
Json::Value obj = model_config.ToJson();
obj["id"] = model_entry.model;
obj["model"] = model_entry.model;
obj["status"] = "downloaded";
auto es = model_service_->GetEstimation(model_entry.model);
if (es.has_value()) {
obj["recommendation"] = hardware::ToJson(*es);
}
data.append(std::move(obj));
yaml_handler.Reset();
} else {
config::RemoteModelConfig remote_model_config;
remote_model_config.LoadFromYamlFile(
fmu::ToAbsoluteCortexDataPath(
fs::path(model_entry.path_to_model_yaml))
.string());
Json::Value obj = remote_model_config.ToJson();
obj["id"] = model_entry.model;
obj["model"] = model_entry.model;
data.append(std::move(obj));
}
} catch (const std::exception& e) {
LOG_ERROR << "Failed to load yaml file for model: "
<< model_entry.path_to_model_yaml << ", error: " << e.what();
}
}
ret["data"] = data;
ret["result"] = "OK";
auto ret_str = ToJsonStringWithPrecision(ret);
auto resp = cortex_utils::CreateCortexHttpTextAsJsonResponse(ret_str);
resp->setStatusCode(k200OK);
callback(resp);
} else {
std::string message = "Fail to get list model information: " +
std::string(list_entry.error());
LOG_ERROR << message;
ret["data"] = data;
ret["result"] = "Fail to get list model information";
ret["message"] = message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
}
}
void Models::GetModel(const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback,
const std::string& model_id) const {
(void)req;
namespace fs = std::filesystem;
namespace fmu = file_manager_utils;
LOG_DEBUG << "GetModel, Model handle: " << model_id;
Json::Value ret;
try {
config::YamlHandler yaml_handler;
auto model_entry = db_service_->GetModelInfo(model_id);
if (model_entry.has_error()) {
ret["id"] = model_id;
ret["object"] = "model";
ret["result"] = "Fail to get model information";
ret["message"] = "Error: " + model_entry.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
return;
}
yaml_handler.ModelConfigFromFile(
fmu::ToAbsoluteCortexDataPath(
fs::path(model_entry.value().path_to_model_yaml))
.string());
auto model_config = yaml_handler.GetModelConfig();
if (model_config.engine == kLlamaEngine) {
auto ret = model_config.ToJsonString();
auto resp = cortex_utils::CreateCortexHttpTextAsJsonResponse(ret);
resp->setStatusCode(drogon::k200OK);
callback(resp);
} else {
config::RemoteModelConfig remote_model_config;
remote_model_config.LoadFromYamlFile(
fmu::ToAbsoluteCortexDataPath(
fs::path(model_entry.value().path_to_model_yaml))
.string());
ret = remote_model_config.ToJson();
ret["id"] = remote_model_config.model;
ret["object"] = "model";
ret["result"] = "OK";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
} catch (const std::exception& e) {
std::string message =
"Fail to get model information with ID '" + model_id + "': " + e.what();
LOG_ERROR << message;
ret["id"] = model_id;
ret["object"] = "model";
ret["result"] = "Fail to get model information";
ret["message"] = message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
}
}
void Models::DeleteModel(const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback,
const std::string& model_id) {
(void)req;
auto result = model_service_->DeleteModel(model_id);
if (result.has_error()) {
Json::Value ret;
ret["message"] = result.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
} else {
Json::Value ret;
ret["message"] = "Deleted successfully!";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::UpdateModel(const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback,
const std::string& model_id) const {
namespace fs = std::filesystem;
namespace fmu = file_manager_utils;
auto json_body = *(req->getJsonObject());
try {
auto model_entry = db_service_->GetModelInfo(model_id);
config::YamlHandler yaml_handler;
auto yaml_fp = fmu::ToAbsoluteCortexDataPath(
fs::path(model_entry.value().path_to_model_yaml));
yaml_handler.ModelConfigFromFile(yaml_fp.string());
config::ModelConfig model_config = yaml_handler.GetModelConfig();
std::string message;
if (model_config.engine == kLlamaEngine) {
model_config.FromJson(json_body);
yaml_handler.UpdateModelConfig(model_config);
yaml_handler.WriteYamlFile(yaml_fp.string());
message = "Successfully update model ID '" + model_id +
"': " + json_body.toStyledString();
} else {
config::RemoteModelConfig remote_model_config;
remote_model_config.LoadFromYamlFile(yaml_fp.string());
remote_model_config.LoadFromJson(json_body);
remote_model_config.SaveToYamlFile(yaml_fp.string());
message = "Successfully update model ID '" + model_id +
"': " + json_body.toStyledString();
}
LOG_INFO << message;
Json::Value ret;
ret["result"] = "Updated successfully!";
ret["modelHandle"] = model_id;
ret["message"] = message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
} catch (const std::exception& e) {
std::string error_message =
"Error updating with model_id '" + model_id + "': " + e.what();
LOG_ERROR << error_message;
Json::Value ret;
ret["result"] = "Updated failed!";
ret["modelHandle"] = model_id;
ret["message"] = error_message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
}
}
void Models::ImportModel(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) const {
namespace fs = std::filesystem;
namespace fmu = file_manager_utils;
if (!http_util::HasFieldInReq(req, callback, "model") ||
!http_util::HasFieldInReq(req, callback, "modelPath")) {
return;
}
auto modelHandle = (*(req->getJsonObject())).get("model", "").asString();
auto modelPath = (*(req->getJsonObject())).get("modelPath", "").asString();
auto modelName = (*(req->getJsonObject())).get("name", "").asString();
auto option = (*(req->getJsonObject())).get("option", "symlink").asString();
config::GGUFHandler gguf_handler;
config::YamlHandler yaml_handler;
std::string model_yaml_path = (file_manager_utils::GetModelsContainerPath() /
std::filesystem::path("imported") /
std::filesystem::path(modelHandle + ".yml"))
.string();
try {
// Use relative path for model_yaml_path. In case of import, we use absolute path for model
auto yaml_rel_path =
fmu::ToRelativeCortexDataPath(fs::path(model_yaml_path));
cortex::db::ModelEntry model_entry{
modelHandle, "", "", yaml_rel_path.string(),
modelHandle, "local", "imported", cortex::db::ModelStatus::Downloaded,
"", ""};
std::filesystem::create_directories(
std::filesystem::path(model_yaml_path).parent_path());
gguf_handler.Parse(modelPath);
config::ModelConfig model_config = gguf_handler.GetModelConfig();
// There are 2 options: symlink and copy
if (option == "copy") {
// Copy GGUF file to the destination path
std::filesystem::path file_path =
std::filesystem::path(model_yaml_path).parent_path() /
std::filesystem::path(modelPath).filename();
std::filesystem::copy_file(
modelPath, file_path, std::filesystem::copy_options::update_existing);
model_config.files.push_back(file_path.string());
auto size = std::filesystem::file_size(file_path);
model_config.size = size;
} else {
model_config.files.push_back(modelPath);
auto size = std::filesystem::file_size(modelPath);
model_config.size = size;
// set this so that it doesn't nuke the original file on model deletion
model_entry.branch_name = "imported";
}
model_config.model = modelHandle;
model_config.name = modelName.empty() ? model_config.name : modelName;
yaml_handler.UpdateModelConfig(model_config);
if (db_service_->AddModelEntry(model_entry).value()) {
yaml_handler.WriteYamlFile(model_yaml_path);
std::string success_message = "Model is imported successfully!";
LOG_INFO << success_message;
Json::Value ret;
ret["result"] = "OK";
ret["modelHandle"] = modelHandle;
ret["message"] = success_message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
} else {
std::string error_message = "Fail to import model, model_id '" +
modelHandle + "' already exists!";
LOG_ERROR << error_message;
Json::Value ret;
ret["result"] = "Import failed!";
ret["modelHandle"] = modelHandle;
ret["message"] = error_message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
}
} catch (const std::exception& e) {
std::string error_message = "Error importing model path '" + modelPath +
"' with model_id '" + modelHandle +
"': " + e.what();
LOG_ERROR << error_message;
Json::Value ret;
ret["result"] = "Import failed!";
ret["modelHandle"] = modelHandle;
ret["message"] = error_message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
}
}
void Models::StartModel(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) {
if (!http_util::HasFieldInReq(req, callback, "model"))
return;
auto model_handle = (*(req->getJsonObject())).get("model", "").asString();
std::optional<std::string> mmproj;
if (auto& o = (*(req->getJsonObject())); o.isMember("mmproj")) {
mmproj = o["mmproj"].asString();
}
auto bypass_llama_model_path = false;
// Support both llama_model_path and model_path for backward compatible
// model_path has higher priority
if (auto& o = (*(req->getJsonObject()))["llama_model_path"]; !o.isNull()) {
auto model_path = o.asString();
if (auto& mp = (*(req->getJsonObject()))["model_path"]; mp.isNull()) {
mp = model_path;
// Bypass if model does not exist in DB and llama_model_path exists
if (std::filesystem::exists(model_path) &&
!model_service_->HasModel(model_handle)) {
CTL_INF("llama_model_path exists, bypass check model id");
bypass_llama_model_path = true;
}
}
}
auto bypass_model_check = (mmproj.has_value() || bypass_llama_model_path);
auto model_entry = model_service_->GetDownloadedModel(model_handle);
if (!model_entry.has_value() && !bypass_model_check) {
Json::Value ret;
ret["message"] = "Cannot find model: " + model_handle;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
return;
}
std::string engine_name =
bypass_model_check ? kLlamaEngine : model_entry.value().engine;
auto engine_validate = engine_service_->IsEngineReady(engine_name);
if (engine_validate.has_error()) {
Json::Value ret;
ret["message"] = engine_validate.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
return;
}
if (!engine_validate.value()) {
Json::Value ret;
ret["message"] = "Engine is not ready! Please install first!";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
return;
}
auto result = model_service_->StartModel(
model_handle, *(req->getJsonObject()) /*params_override*/,
bypass_model_check);
if (result.has_error()) {
Json::Value ret;
ret["message"] = result.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
} else {
auto& v = result.value();
Json::Value ret;
ret["message"] = "Started successfully!";
if (v.warning) {
ret["warning"] = *(v.warning);
}
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::StopModel(const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) {
if (!http_util::HasFieldInReq(req, callback, "model")) {
return;
}
auto model_handle = (*(req->getJsonObject())).get("model", "").asString();
auto result = model_service_->StopModel(model_handle);
if (result.has_error()) {
Json::Value ret;
ret["message"] = result.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
} else {
Json::Value ret;
ret["message"] = "Stopped successfully!";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::GetModelStatus(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback,
const std::string& model_id) {
(void)req;
auto result = model_service_->GetModelStatus(model_id);
if (result.has_error()) {
Json::Value ret;
ret["message"] = result.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
} else {
Json::Value ret;
ret["message"] = "Model is running";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::GetRemoteModels(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback,
const std::string& engine_id) {
(void)req;
if (!engine_service_->IsRemoteEngine(engine_id)) {
Json::Value ret;
ret["message"] = "Not a remote engine: " + engine_id;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
return;
}
auto result = engine_service_->GetRemoteModels(engine_id);
if (result.has_error()) {
Json::Value ret;
ret["message"] = result.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
} else {
auto resp = cortex_utils::CreateCortexHttpJsonResponse(result.value());
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::AddRemoteModel(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) const {
namespace fs = std::filesystem;
namespace fmu = file_manager_utils;
if (!http_util::HasFieldInReq(req, callback, "model") ||
!http_util::HasFieldInReq(req, callback, "engine")) {
return;
}
auto model_handle = (*(req->getJsonObject())).get("model", "").asString();
auto engine_name = (*(req->getJsonObject())).get("engine", "").asString();
auto engine_validate = engine_service_->IsEngineReady(engine_name);
if (engine_validate.has_error()) {
Json::Value ret;
ret["message"] = engine_validate.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
return;
}
if (!engine_validate.value()) {
Json::Value ret;
ret["message"] = "Engine is not ready! Please install first!";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(drogon::k400BadRequest);
callback(resp);
return;
}
config::RemoteModelConfig model_config;
model_config.LoadFromJson(*(req->getJsonObject()));
std::string model_yaml_path = (file_manager_utils::GetModelsContainerPath() /
std::filesystem::path("remote") /
std::filesystem::path(model_handle + ".yml"))
.string();
try {
// Use relative path for model_yaml_path. In case of import, we use absolute path for model
auto yaml_rel_path =
fmu::ToRelativeCortexDataPath(fs::path(model_yaml_path));
cortex::db::ModelEntry model_entry{
model_handle, "", "", yaml_rel_path.string(),
model_handle, "remote", "imported", cortex::db::ModelStatus::Remote,
engine_name, ""};
std::filesystem::create_directories(
std::filesystem::path(model_yaml_path).parent_path());
if (db_service_->AddModelEntry(model_entry).value()) {
model_config.SaveToYamlFile(model_yaml_path);
std::string success_message = "Model is imported successfully!";
LOG_INFO << success_message;
Json::Value ret;
ret["result"] = "OK";
ret["modelHandle"] = model_handle;
ret["message"] = success_message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
} else {
std::string error_message = "Fail to import model, model_id '" +
model_handle + "' already exists!";
LOG_ERROR << error_message;
Json::Value ret;
ret["result"] = "Import failed!";
ret["modelHandle"] = model_handle;
ret["message"] = error_message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
}
} catch (const std::exception& e) {
std::string error_message =
"Error while adding Remote model with model_id '" + model_handle +
"': " + e.what();
LOG_ERROR << error_message;
Json::Value ret;
ret["result"] = "Add failed!";
ret["modelHandle"] = model_handle;
ret["message"] = error_message;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
}
}
void Models::AddModelSource(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) {
if (!http_util::HasFieldInReq(req, callback, "source")) {
return;
}
auto model_source = (*(req->getJsonObject())).get("source", "").asString();
auto res = model_src_svc_->AddModelSource(model_source);
if (res.has_error()) {
Json::Value ret;
ret["message"] = res.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
/* auto const& info = res.value(); */
Json::Value ret;
ret["message"] = "Model source is added successfully!";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::DeleteModelSource(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) {
if (!http_util::HasFieldInReq(req, callback, "source")) {
return;
}
auto model_source = (*(req->getJsonObject())).get("source", "").asString();
auto res = model_src_svc_->RemoveModelSource(model_source);
if (res.has_error()) {
Json::Value ret;
ret["message"] = res.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
/* auto const& info = res.value(); */
Json::Value ret;
ret["message"] = "Model source is deleted successfully!";
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::GetModelSources(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback) {
(void)req;
auto res = model_src_svc_->GetModelSources();
if (res.has_error()) {
Json::Value ret;
ret["message"] = res.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
auto& info = res.value();
Json::Value ret;
Json::Value data(Json::arrayValue);
for (auto& i : info) {
data.append(i.second.ToJson());
}
ret["data"] = data;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::GetModelSource(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback,
const std::string& src) {
(void)req;
auto res = model_src_svc_->GetModelSource(src);
if (res.has_error()) {
Json::Value ret;
ret["message"] = res.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
auto& info = res.value();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(info.ToJson());
resp->setStatusCode(k200OK);
callback(resp);
}
}
void Models::GetRepositoryList(
const HttpRequestPtr& req,
std::function<void(const HttpResponsePtr&)>&& callback,
std::optional<std::string> author, std::optional<std::string> tag) {
(void)req;
if (!author.has_value())
author = "cortexso";
auto res =
model_src_svc_->GetRepositoryList(author.value(), tag.value_or(""));
if (res.has_error()) {
Json::Value ret;
ret["message"] = res.error();
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k400BadRequest);
callback(resp);
} else {
auto& info = res.value();
Json::Value ret;
Json::Value arr(Json::arrayValue);
for (auto const& i : info) {
arr.append(i);
}
ret["data"] = arr;
auto resp = cortex_utils::CreateCortexHttpJsonResponse(ret);
resp->setStatusCode(k200OK);
callback(resp);
}
}