forked from nomic-ai/gpt4all
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodellist.cpp
2090 lines (1848 loc) · 72.8 KB
/
modellist.cpp
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
#include "modellist.h"
#include "mysettings.h"
#include "network.h"
#include "../gpt4all-backend/llmodel.h"
#include <QChar>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QEventLoop>
#include <QFile>
#include <QFileInfo>
#include <QGlobalStatic>
#include <QGuiApplication>
#include <QIODevice>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QNetworkRequest>
#include <QObject>
#include <QRegularExpression>
#include <QSettings>
#include <QSslConfiguration>
#include <QSslSocket>
#include <QStringList>
#include <QTextStream>
#include <QTimer>
#include <QUrl>
#include <QtLogging>
#include <algorithm>
#include <compare>
#include <cstddef>
#include <iterator>
#include <string>
#include <utility>
using namespace Qt::Literals::StringLiterals;
//#define USE_LOCAL_MODELSJSON
static const QStringList FILENAME_BLACKLIST { u"gpt4all-nomic-embed-text-v1.rmodel"_s };
QString ModelInfo::id() const
{
return m_id;
}
void ModelInfo::setId(const QString &id)
{
m_id = id;
}
QString ModelInfo::name() const
{
return MySettings::globalInstance()->modelName(*this);
}
void ModelInfo::setName(const QString &name)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelName(*this, name, true /*force*/);
m_name = name;
}
QString ModelInfo::filename() const
{
return MySettings::globalInstance()->modelFilename(*this);
}
void ModelInfo::setFilename(const QString &filename)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelFilename(*this, filename, true /*force*/);
m_filename = filename;
}
QString ModelInfo::description() const
{
return MySettings::globalInstance()->modelDescription(*this);
}
void ModelInfo::setDescription(const QString &d)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelDescription(*this, d, true /*force*/);
m_description = d;
}
QString ModelInfo::url() const
{
return MySettings::globalInstance()->modelUrl(*this);
}
void ModelInfo::setUrl(const QString &u)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelUrl(*this, u, true /*force*/);
m_url = u;
}
QString ModelInfo::quant() const
{
return MySettings::globalInstance()->modelQuant(*this);
}
void ModelInfo::setQuant(const QString &q)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelQuant(*this, q, true /*force*/);
m_quant = q;
}
QString ModelInfo::type() const
{
return MySettings::globalInstance()->modelType(*this);
}
void ModelInfo::setType(const QString &t)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelType(*this, t, true /*force*/);
m_type = t;
}
bool ModelInfo::isClone() const
{
return MySettings::globalInstance()->modelIsClone(*this);
}
void ModelInfo::setIsClone(bool b)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelIsClone(*this, b, true /*force*/);
m_isClone = b;
}
bool ModelInfo::isDiscovered() const
{
return MySettings::globalInstance()->modelIsDiscovered(*this);
}
void ModelInfo::setIsDiscovered(bool b)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelIsDiscovered(*this, b, true /*force*/);
m_isDiscovered = b;
}
int ModelInfo::likes() const
{
return MySettings::globalInstance()->modelLikes(*this);
}
void ModelInfo::setLikes(int l)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelLikes(*this, l, true /*force*/);
m_likes = l;
}
int ModelInfo::downloads() const
{
return MySettings::globalInstance()->modelDownloads(*this);
}
void ModelInfo::setDownloads(int d)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelDownloads(*this, d, true /*force*/);
m_downloads = d;
}
QDateTime ModelInfo::recency() const
{
return MySettings::globalInstance()->modelRecency(*this);
}
void ModelInfo::setRecency(const QDateTime &r)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelRecency(*this, r, true /*force*/);
m_recency = r;
}
double ModelInfo::temperature() const
{
return MySettings::globalInstance()->modelTemperature(*this);
}
void ModelInfo::setTemperature(double t)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelTemperature(*this, t, true /*force*/);
m_temperature = t;
}
double ModelInfo::topP() const
{
return MySettings::globalInstance()->modelTopP(*this);
}
double ModelInfo::minP() const
{
return MySettings::globalInstance()->modelMinP(*this);
}
void ModelInfo::setTopP(double p)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelTopP(*this, p, true /*force*/);
m_topP = p;
}
void ModelInfo::setMinP(double p)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelMinP(*this, p, true /*force*/);
m_minP = p;
}
int ModelInfo::topK() const
{
return MySettings::globalInstance()->modelTopK(*this);
}
void ModelInfo::setTopK(int k)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelTopK(*this, k, true /*force*/);
m_topK = k;
}
int ModelInfo::maxLength() const
{
return MySettings::globalInstance()->modelMaxLength(*this);
}
void ModelInfo::setMaxLength(int l)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelMaxLength(*this, l, true /*force*/);
m_maxLength = l;
}
int ModelInfo::promptBatchSize() const
{
return MySettings::globalInstance()->modelPromptBatchSize(*this);
}
void ModelInfo::setPromptBatchSize(int s)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelPromptBatchSize(*this, s, true /*force*/);
m_promptBatchSize = s;
}
int ModelInfo::contextLength() const
{
return MySettings::globalInstance()->modelContextLength(*this);
}
void ModelInfo::setContextLength(int l)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelContextLength(*this, l, true /*force*/);
m_contextLength = l;
}
int ModelInfo::maxContextLength() const
{
if (!installed || isOnline) return -1;
if (m_maxContextLength != -1) return m_maxContextLength;
auto path = (dirpath + filename()).toStdString();
int n_ctx = LLModel::Implementation::maxContextLength(path);
if (n_ctx < 0) {
n_ctx = 4096; // fallback value
}
m_maxContextLength = n_ctx;
return m_maxContextLength;
}
int ModelInfo::gpuLayers() const
{
return MySettings::globalInstance()->modelGpuLayers(*this);
}
void ModelInfo::setGpuLayers(int l)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelGpuLayers(*this, l, true /*force*/);
m_gpuLayers = l;
}
int ModelInfo::maxGpuLayers() const
{
if (!installed || isOnline) return -1;
if (m_maxGpuLayers != -1) return m_maxGpuLayers;
auto path = (dirpath + filename()).toStdString();
int layers = LLModel::Implementation::layerCount(path);
if (layers < 0) {
layers = 100; // fallback value
}
m_maxGpuLayers = layers;
return m_maxGpuLayers;
}
double ModelInfo::repeatPenalty() const
{
return MySettings::globalInstance()->modelRepeatPenalty(*this);
}
void ModelInfo::setRepeatPenalty(double p)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelRepeatPenalty(*this, p, true /*force*/);
m_repeatPenalty = p;
}
int ModelInfo::repeatPenaltyTokens() const
{
return MySettings::globalInstance()->modelRepeatPenaltyTokens(*this);
}
void ModelInfo::setRepeatPenaltyTokens(int t)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelRepeatPenaltyTokens(*this, t, true /*force*/);
m_repeatPenaltyTokens = t;
}
QString ModelInfo::promptTemplate() const
{
return MySettings::globalInstance()->modelPromptTemplate(*this);
}
void ModelInfo::setPromptTemplate(const QString &t)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelPromptTemplate(*this, t, true /*force*/);
m_promptTemplate = t;
}
QString ModelInfo::systemPrompt() const
{
return MySettings::globalInstance()->modelSystemPrompt(*this);
}
void ModelInfo::setSystemPrompt(const QString &p)
{
if (shouldSaveMetadata()) MySettings::globalInstance()->setModelSystemPrompt(*this, p, true /*force*/);
m_systemPrompt = p;
}
bool ModelInfo::shouldSaveMetadata() const
{
return installed && (isClone() || isDiscovered() || description() == "" /*indicates sideloaded*/);
}
QVariantMap ModelInfo::getFields() const
{
return {
{ "filename", m_filename },
{ "description", m_description },
{ "url", m_url },
{ "quant", m_quant },
{ "type", m_type },
{ "isClone", m_isClone },
{ "isDiscovered", m_isDiscovered },
{ "likes", m_likes },
{ "downloads", m_downloads },
{ "recency", m_recency },
{ "temperature", m_temperature },
{ "topP", m_topP },
{ "minP", m_minP },
{ "topK", m_topK },
{ "maxLength", m_maxLength },
{ "promptBatchSize", m_promptBatchSize },
{ "contextLength", m_contextLength },
{ "gpuLayers", m_gpuLayers },
{ "repeatPenalty", m_repeatPenalty },
{ "repeatPenaltyTokens", m_repeatPenaltyTokens },
{ "promptTemplate", m_promptTemplate },
{ "systemPrompt", m_systemPrompt },
};
}
InstalledModels::InstalledModels(QObject *parent, bool selectable)
: QSortFilterProxyModel(parent)
, m_selectable(selectable)
{
connect(this, &InstalledModels::rowsInserted, this, &InstalledModels::countChanged);
connect(this, &InstalledModels::rowsRemoved, this, &InstalledModels::countChanged);
connect(this, &InstalledModels::modelReset, this, &InstalledModels::countChanged);
connect(this, &InstalledModels::layoutChanged, this, &InstalledModels::countChanged);
}
bool InstalledModels::filterAcceptsRow(int sourceRow,
const QModelIndex &sourceParent) const
{
/* TODO(jared): We should list incomplete models alongside installed models on the
* Models page. Simply replacing isDownloading with isIncomplete here doesn't work for
* some reason - the models show up as something else. */
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
bool isInstalled = sourceModel()->data(index, ModelList::InstalledRole).toBool();
bool isDownloading = sourceModel()->data(index, ModelList::DownloadingRole).toBool();
bool isEmbeddingModel = sourceModel()->data(index, ModelList::IsEmbeddingModelRole).toBool();
// list installed chat models
return (isInstalled || (!m_selectable && isDownloading)) && !isEmbeddingModel;
}
DownloadableModels::DownloadableModels(QObject *parent)
: QSortFilterProxyModel(parent)
, m_expanded(false)
, m_limit(5)
{
connect(this, &DownloadableModels::rowsInserted, this, &DownloadableModels::countChanged);
connect(this, &DownloadableModels::rowsRemoved, this, &DownloadableModels::countChanged);
connect(this, &DownloadableModels::modelReset, this, &DownloadableModels::countChanged);
connect(this, &DownloadableModels::layoutChanged, this, &DownloadableModels::countChanged);
}
bool DownloadableModels::filterAcceptsRow(int sourceRow,
const QModelIndex &sourceParent) const
{
// FIXME We can eliminate the 'expanded' code as the UI no longer uses this
bool withinLimit = sourceRow < (m_expanded ? sourceModel()->rowCount() : m_limit);
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
bool hasDescription = !sourceModel()->data(index, ModelList::DescriptionRole).toString().isEmpty();
bool isClone = sourceModel()->data(index, ModelList::IsCloneRole).toBool();
return withinLimit && hasDescription && !isClone;
}
int DownloadableModels::count() const
{
return rowCount();
}
bool DownloadableModels::isExpanded() const
{
return m_expanded;
}
void DownloadableModels::setExpanded(bool expanded)
{
if (m_expanded != expanded) {
m_expanded = expanded;
invalidateFilter();
emit expandedChanged(m_expanded);
}
}
void DownloadableModels::discoverAndFilter(const QString &discover)
{
m_discoverFilter = discover;
ModelList *ml = qobject_cast<ModelList*>(parent());
ml->discoverSearch(discover);
}
class MyModelList: public ModelList { };
Q_GLOBAL_STATIC(MyModelList, modelListInstance)
ModelList *ModelList::globalInstance()
{
return modelListInstance();
}
ModelList::ModelList()
: QAbstractListModel(nullptr)
, m_installedModels(new InstalledModels(this))
, m_selectableModels(new InstalledModels(this, /*selectable*/ true))
, m_downloadableModels(new DownloadableModels(this))
, m_asyncModelRequestOngoing(false)
, m_discoverLimit(20)
, m_discoverSortDirection(-1)
, m_discoverSort(Likes)
, m_discoverNumberOfResults(0)
, m_discoverResultsCompleted(0)
, m_discoverInProgress(false)
{
m_installedModels->setSourceModel(this);
m_selectableModels->setSourceModel(this);
m_downloadableModels->setSourceModel(this);
connect(MySettings::globalInstance(), &MySettings::modelPathChanged, this, &ModelList::updateModelsFromDirectory);
connect(MySettings::globalInstance(), &MySettings::modelPathChanged, this, &ModelList::updateModelsFromJson);
connect(MySettings::globalInstance(), &MySettings::modelPathChanged, this, &ModelList::updateModelsFromSettings);
connect(MySettings::globalInstance(), &MySettings::nameChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::temperatureChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::topPChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::minPChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::topKChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::maxLengthChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::promptBatchSizeChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::contextLengthChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::gpuLayersChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::repeatPenaltyChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::repeatPenaltyTokensChanged, this, &ModelList::updateDataForSettings);;
connect(MySettings::globalInstance(), &MySettings::promptTemplateChanged, this, &ModelList::updateDataForSettings);
connect(MySettings::globalInstance(), &MySettings::systemPromptChanged, this, &ModelList::updateDataForSettings);
connect(&m_networkManager, &QNetworkAccessManager::sslErrors, this, &ModelList::handleSslErrors);
updateModelsFromJson();
updateModelsFromSettings();
updateModelsFromDirectory();
}
QString ModelList::incompleteDownloadPath(const QString &modelFile)
{
return MySettings::globalInstance()->modelPath() + "incomplete-" + modelFile;
}
const QList<ModelInfo> ModelList::exportModelList() const
{
QMutexLocker locker(&m_mutex);
QList<ModelInfo> infos;
for (ModelInfo *info : m_models)
if (info->installed)
infos.append(*info);
return infos;
}
const QList<QString> ModelList::userDefaultModelList() const
{
QMutexLocker locker(&m_mutex);
const QString userDefaultModelName = MySettings::globalInstance()->userDefaultModel();
QList<QString> models;
bool foundUserDefault = false;
for (ModelInfo *info : m_models) {
// Only installed chat models are suitable as a default
if (!info->installed || info->isEmbeddingModel)
continue;
if (info->id() == userDefaultModelName) {
foundUserDefault = true;
models.prepend(info->name());
} else {
models.append(info->name());
}
}
const QString defaultId = "Application default";
if (foundUserDefault)
models.append(defaultId);
else
models.prepend(defaultId);
return models;
}
ModelInfo ModelList::defaultModelInfo() const
{
QMutexLocker locker(&m_mutex);
QSettings settings;
// The user default model can be set by the user in the settings dialog. The "default" user
// default model is "Application default" which signals we should use the logic here.
const QString userDefaultModelName = MySettings::globalInstance()->userDefaultModel();
const bool hasUserDefaultName = !userDefaultModelName.isEmpty() && userDefaultModelName != "Application default";
ModelInfo *defaultModel = nullptr;
for (ModelInfo *info : m_models) {
if (!info->installed)
continue;
defaultModel = info;
const size_t ramrequired = defaultModel->ramrequired;
// If we don't have either setting, then just use the first model that requires less than 16GB that is installed
if (!hasUserDefaultName && !info->isOnline && ramrequired > 0 && ramrequired < 16)
break;
// If we have a user specified default and match, then use it
if (hasUserDefaultName && (defaultModel->id() == userDefaultModelName))
break;
}
if (defaultModel)
return *defaultModel;
return ModelInfo();
}
bool ModelList::contains(const QString &id) const
{
QMutexLocker locker(&m_mutex);
return m_modelMap.contains(id);
}
bool ModelList::containsByFilename(const QString &filename) const
{
QMutexLocker locker(&m_mutex);
for (ModelInfo *info : m_models)
if (info->filename() == filename)
return true;
return false;
}
bool ModelList::lessThan(const ModelInfo* a, const ModelInfo* b, DiscoverSort s, int d)
{
// Rule -1a: Discover sort
if (a->isDiscovered() && b->isDiscovered()) {
switch (s) {
case Default: break;
case Likes: return (d > 0 ? a->likes() < b->likes() : a->likes() > b->likes());
case Downloads: return (d > 0 ? a->downloads() < b->downloads() : a->downloads() > b->downloads());
case Recent: return (d > 0 ? a->recency() < b->recency() : a->recency() > b->recency());
}
}
// Rule -1: Discovered before non-discovered
if (a->isDiscovered() != b->isDiscovered()) {
return a->isDiscovered();
}
// Rule 0: Non-clone before clone
if (a->isClone() != b->isClone()) {
return !a->isClone();
}
// Rule 1: Non-empty 'order' before empty
if (a->order.isEmpty() != b->order.isEmpty()) {
return !a->order.isEmpty();
}
// Rule 2: Both 'order' are non-empty, sort alphanumerically
if (!a->order.isEmpty() && !b->order.isEmpty()) {
return a->order < b->order;
}
// Rule 3: Both 'order' are empty, sort by id
return a->id() < b->id();
}
void ModelList::addModel(const QString &id)
{
const bool hasModel = contains(id);
Q_ASSERT(!hasModel);
if (hasModel) {
qWarning() << "ERROR: model list already contains" << id;
return;
}
ModelInfo *info = new ModelInfo;
info->setId(id);
m_mutex.lock();
auto s = m_discoverSort;
auto d = m_discoverSortDirection;
const auto insertPosition = std::lower_bound(m_models.begin(), m_models.end(), info,
[s, d](const ModelInfo* lhs, const ModelInfo* rhs) {
return ModelList::lessThan(lhs, rhs, s, d);
});
const int index = std::distance(m_models.begin(), insertPosition);
m_mutex.unlock();
// NOTE: The begin/end rows cannot have a lock placed around them. We calculate the index ahead
// of time and this works because this class is designed carefully so that only one thread is
// responsible for insertion, deletion, and update
beginInsertRows(QModelIndex(), index, index);
m_mutex.lock();
m_models.insert(insertPosition, info);
m_modelMap.insert(id, info);
m_mutex.unlock();
endInsertRows();
emit userDefaultModelListChanged();
}
void ModelList::changeId(const QString &oldId, const QString &newId)
{
const bool hasModel = contains(oldId);
Q_ASSERT(hasModel);
if (!hasModel) {
qWarning() << "ERROR: model list does not contain" << oldId;
return;
}
QMutexLocker locker(&m_mutex);
ModelInfo *info = m_modelMap.take(oldId);
info->setId(newId);
m_modelMap.insert(newId, info);
}
int ModelList::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
QMutexLocker locker(&m_mutex);
return m_models.size();
}
QVariant ModelList::dataInternal(const ModelInfo *info, int role) const
{
switch (role) {
case IdRole:
return info->id();
case NameRole:
return info->name();
case FilenameRole:
return info->filename();
case DirpathRole:
return info->dirpath;
case FilesizeRole:
return info->filesize;
case HashRole:
return info->hash;
case HashAlgorithmRole:
return info->hashAlgorithm;
case CalcHashRole:
return info->calcHash;
case InstalledRole:
return info->installed;
case DefaultRole:
return info->isDefault;
case OnlineRole:
return info->isOnline;
case DescriptionRole:
return info->description();
case RequiresVersionRole:
return info->requiresVersion;
case VersionRemovedRole:
return info->versionRemoved;
case UrlRole:
return info->url();
case BytesReceivedRole:
return info->bytesReceived;
case BytesTotalRole:
return info->bytesTotal;
case TimestampRole:
return info->timestamp;
case SpeedRole:
return info->speed;
case DownloadingRole:
return info->isDownloading;
case IncompleteRole:
return info->isIncomplete;
case DownloadErrorRole:
return info->downloadError;
case OrderRole:
return info->order;
case RamrequiredRole:
return info->ramrequired;
case ParametersRole:
return info->parameters;
case QuantRole:
return info->quant();
case TypeRole:
return info->type();
case IsCloneRole:
return info->isClone();
case IsDiscoveredRole:
return info->isDiscovered();
case IsEmbeddingModelRole:
return info->isEmbeddingModel;
case TemperatureRole:
return info->temperature();
case TopPRole:
return info->topP();
case MinPRole:
return info->minP();
case TopKRole:
return info->topK();
case MaxLengthRole:
return info->maxLength();
case PromptBatchSizeRole:
return info->promptBatchSize();
case ContextLengthRole:
return info->contextLength();
case GpuLayersRole:
return info->gpuLayers();
case RepeatPenaltyRole:
return info->repeatPenalty();
case RepeatPenaltyTokensRole:
return info->repeatPenaltyTokens();
case PromptTemplateRole:
return info->promptTemplate();
case SystemPromptRole:
return info->systemPrompt();
case LikesRole:
return info->likes();
case DownloadsRole:
return info->downloads();
case RecencyRole:
return info->recency();
}
return QVariant();
}
QVariant ModelList::data(const QString &id, int role) const
{
QMutexLocker locker(&m_mutex);
ModelInfo *info = m_modelMap.value(id);
return dataInternal(info, role);
}
QVariant ModelList::dataByFilename(const QString &filename, int role) const
{
QMutexLocker locker(&m_mutex);
for (ModelInfo *info : m_models)
if (info->filename() == filename)
return dataInternal(info, role);
return QVariant();
}
QVariant ModelList::data(const QModelIndex &index, int role) const
{
QMutexLocker locker(&m_mutex);
if (!index.isValid() || index.row() < 0 || index.row() >= m_models.size())
return QVariant();
const ModelInfo *info = m_models.at(index.row());
return dataInternal(info, role);
}
void ModelList::updateData(const QString &id, const QVector<QPair<int, QVariant>> &data)
{
int index;
{
QMutexLocker locker(&m_mutex);
if (!m_modelMap.contains(id)) {
qWarning() << "ERROR: cannot update as model map does not contain" << id;
return;
}
ModelInfo *info = m_modelMap.value(id);
index = m_models.indexOf(info);
if (index == -1) {
qWarning() << "ERROR: cannot update as model list does not contain" << id;
return;
}
// We only sort when one of the fields used by the sorting algorithm actually changes that
// is implicated or used by the sorting algorithm
bool shouldSort = false;
for (const auto &d : data) {
const int role = d.first;
const QVariant value = d.second;
switch (role) {
case IdRole:
{
if (info->id() != value.toString()) {
info->setId(value.toString());
shouldSort = true;
}
break;
}
case NameRole:
info->setName(value.toString()); break;
case FilenameRole:
info->setFilename(value.toString()); break;
case DirpathRole:
info->dirpath = value.toString(); break;
case FilesizeRole:
info->filesize = value.toString(); break;
case HashRole:
info->hash = value.toByteArray(); break;
case HashAlgorithmRole:
info->hashAlgorithm = static_cast<ModelInfo::HashAlgorithm>(value.toInt()); break;
case CalcHashRole:
info->calcHash = value.toBool(); break;
case InstalledRole:
info->installed = value.toBool(); break;
case DefaultRole:
info->isDefault = value.toBool(); break;
case OnlineRole:
info->isOnline = value.toBool(); break;
case DescriptionRole:
info->setDescription(value.toString()); break;
case RequiresVersionRole:
info->requiresVersion = value.toString(); break;
case VersionRemovedRole:
info->versionRemoved = value.toString(); break;
case UrlRole:
info->setUrl(value.toString()); break;
case BytesReceivedRole:
info->bytesReceived = value.toLongLong(); break;
case BytesTotalRole:
info->bytesTotal = value.toLongLong(); break;
case TimestampRole:
info->timestamp = value.toLongLong(); break;
case SpeedRole:
info->speed = value.toString(); break;
case DownloadingRole:
info->isDownloading = value.toBool(); break;
case IncompleteRole:
info->isIncomplete = value.toBool(); break;
case DownloadErrorRole:
info->downloadError = value.toString(); break;
case OrderRole:
{
if (info->order != value.toString()) {
info->order = value.toString();
shouldSort = true;
}
break;
}
case RamrequiredRole:
info->ramrequired = value.toInt(); break;
case ParametersRole:
info->parameters = value.toString(); break;
case QuantRole:
info->setQuant(value.toString()); break;
case TypeRole:
info->setType(value.toString()); break;
case IsCloneRole:
{
if (info->isClone() != value.toBool()) {
info->setIsClone(value.toBool());
shouldSort = true;
}
break;
}
case IsDiscoveredRole:
{
if (info->isDiscovered() != value.toBool()) {
info->setIsDiscovered(value.toBool());
shouldSort = true;
}
break;
}
case IsEmbeddingModelRole:
info->isEmbeddingModel = value.toBool(); break;
case TemperatureRole:
info->setTemperature(value.toDouble()); break;
case TopPRole:
info->setTopP(value.toDouble()); break;
case MinPRole:
info->setMinP(value.toDouble()); break;
case TopKRole:
info->setTopK(value.toInt()); break;
case MaxLengthRole:
info->setMaxLength(value.toInt()); break;
case PromptBatchSizeRole:
info->setPromptBatchSize(value.toInt()); break;
case ContextLengthRole:
info->setContextLength(value.toInt()); break;
case GpuLayersRole:
info->setGpuLayers(value.toInt()); break;
case RepeatPenaltyRole:
info->setRepeatPenalty(value.toDouble()); break;
case RepeatPenaltyTokensRole:
info->setRepeatPenaltyTokens(value.toInt()); break;
case PromptTemplateRole:
info->setPromptTemplate(value.toString()); break;
case SystemPromptRole:
info->setSystemPrompt(value.toString()); break;
case LikesRole:
{
if (info->likes() != value.toInt()) {
info->setLikes(value.toInt());
shouldSort = true;
}
break;
}
case DownloadsRole:
{
if (info->downloads() != value.toInt()) {
info->setDownloads(value.toInt());
shouldSort = true;
}
break;
}
case RecencyRole:
{
if (info->recency() != value.toDateTime()) {
info->setRecency(value.toDateTime());
shouldSort = true;
}
break;
}
}
}
// Extra guarantee that these always remains in sync with filesystem
QString modelPath = info->dirpath + info->filename();
const QFileInfo fileInfo(modelPath);
info->installed = fileInfo.exists();
const QFileInfo incompleteInfo(incompleteDownloadPath(info->filename()));
info->isIncomplete = incompleteInfo.exists();
// check installed, discovered/sideloaded models only (including clones)
if (!info->checkedEmbeddingModel && !info->isEmbeddingModel && info->installed
&& (info->isDiscovered() || info->description().isEmpty()))
{
// read GGUF and decide based on model architecture
info->isEmbeddingModel = LLModel::Implementation::isEmbeddingModel(modelPath.toStdString());
info->checkedEmbeddingModel = true;
}
if (shouldSort) {
auto s = m_discoverSort;
auto d = m_discoverSortDirection;
std::stable_sort(m_models.begin(), m_models.end(), [s, d](const ModelInfo* lhs, const ModelInfo* rhs) {
return ModelList::lessThan(lhs, rhs, s, d);
});
}
}
emit dataChanged(createIndex(index, 0), createIndex(index, 0));
emit userDefaultModelListChanged();
}
void ModelList::resortModel()
{
emit layoutAboutToBeChanged();
{
QMutexLocker locker(&m_mutex);
auto s = m_discoverSort;
auto d = m_discoverSortDirection;
std::stable_sort(m_models.begin(), m_models.end(), [s, d](const ModelInfo* lhs, const ModelInfo* rhs) {
return ModelList::lessThan(lhs, rhs, s, d);
});
}
emit layoutChanged();
}
void ModelList::updateDataByFilename(const QString &filename, QVector<QPair<int, QVariant>> data)