-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1554 lines (1363 loc) · 60.9 KB
/
main.cpp
File metadata and controls
1554 lines (1363 loc) · 60.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
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 <algorithm>
#include <atomic>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdarg>
#include <ctime>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <limits>
#include <optional>
#include <pwd.h>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <thread>
#include <unistd.h>
#include <vector>
#include <curl/curl.h>
#include "vendor/cjson/cJSON.h"
namespace {
constexpr const char *DEFAULT_MODEL = "gpt-5.2-chat-latest";
constexpr size_t MAX_BUFFER_SIZE = 8192;
constexpr int DEFAULT_TOKEN_LIMIT = 128000;
constexpr const char *MODELS_CACHE_FILE = "~/.cache/ask_models_cache.json";
constexpr time_t MODELS_CACHE_EXPIRY = 86400; // 24 hours
constexpr long CONNECT_TIMEOUT = 10L;
constexpr long REQUEST_TIMEOUT = 60L;
constexpr int MAX_RETRIES = 1; // total attempts = MAX_RETRIES + 1
constexpr const char *LAST_CONTEXT_FILE = "~/.cache/ask_last_context.json";
constexpr const char *DEFAULT_SYSTEM_PROMPT =
"Terminal assistant. Give shortest answer with directly copyable commands. "
"No emoji, no filler. For errors: brief cause then fix. "
"Style: man page, not chatbot.";
enum class LogLevel {
None = 0,
Error = 1,
Warn = 2,
Info = 3,
Debug = 4
};
struct Message {
std::string role;
std::string content;
};
struct ModelInfo {
std::string id;
time_t created{};
};
struct ModelsCacheData {
std::vector<ModelInfo> models;
time_t lastUpdated{};
};
struct ResponseBuffer {
std::string data;
std::string responseContent;
bool streamEnabled{false};
bool sawStreamData{false};
bool rawMode{false};
std::atomic_bool *firstTokenFlag{nullptr};
class Logger *logger{nullptr};
};
class Logger {
public:
Logger() = default;
~Logger() { close(); }
void configure(LogLevel level, bool debug, bool logToFile, std::string filePath) {
level_ = level;
debug_ = debug;
logToFile_ = logToFile;
filePath_ = std::move(filePath);
if (logToFile_) {
openFile();
}
}
void log(LogLevel level, const char *format, ...) {
if (level > level_) return;
char levelStr[10];
switch (level) {
case LogLevel::Error: std::strcpy(levelStr, "ERROR"); break;
case LogLevel::Warn: std::strcpy(levelStr, "WARN"); break;
case LogLevel::Info: std::strcpy(levelStr, "INFO"); break;
case LogLevel::Debug: std::strcpy(levelStr, "DEBUG"); break;
default: std::strcpy(levelStr, "NONE"); break;
}
std::time_t now = std::time(nullptr);
std::tm *localTime = std::localtime(&now);
char timeStr[20];
std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", localTime);
va_list args;
va_start(args, format);
char message[MAX_BUFFER_SIZE];
std::vsnprintf(message, sizeof(message), format, args);
if (level <= LogLevel::Warn || debug_) {
std::fprintf(stdout, "[%s] %s: %s\n", timeStr, levelStr, message);
}
if (logToFile_ && file_) {
std::fprintf(file_, "[%s] %s: %s\n", timeStr, levelStr, message);
std::fflush(file_);
}
va_end(args);
}
LogLevel level() const { return level_; }
bool debug() const { return debug_; }
private:
void openFile() {
file_ = std::fopen(filePath_.c_str(), "a");
if (!file_) {
std::fprintf(stderr, "Failed to open log file %s\n", filePath_.c_str());
logToFile_ = false;
}
}
void close() {
if (file_) {
std::fclose(file_);
file_ = nullptr;
}
}
LogLevel level_{LogLevel::Info};
bool debug_{false};
bool logToFile_{false};
std::string filePath_{"ask.log"};
FILE *file_{nullptr};
};
struct Settings {
std::string apiKey;
std::string model = DEFAULT_MODEL;
std::string systemPrompt;
int tokenLimit = DEFAULT_TOKEN_LIMIT;
int fileSizeLimit = 10000;
bool debugMode{false};
LogLevel logLevel{LogLevel::Info};
bool logToFile{false};
std::string logFilePath{"ask.log"};
};
class FileUtil {
public:
static std::string expandHomePath(const std::string &path, Logger &logger) {
if (path.empty() || path[0] != '~') {
return path;
}
struct passwd *pw = getpwuid(getuid());
if (pw == nullptr) {
logger.log(LogLevel::Error, "Could not determine home directory");
return path;
}
if (pw->pw_dir == nullptr) {
logger.log(LogLevel::Error, "Home directory path is null");
return path;
}
std::string expanded = pw->pw_dir;
expanded += path.substr(1);
auto lastSlash = expanded.find_last_of('/');
if (lastSlash != std::string::npos) {
std::string dir = expanded.substr(0, lastSlash);
if (mkdir(dir.c_str(), 0700) == -1 && errno != EEXIST) {
logger.log(LogLevel::Error, "Failed to create directory: %s", dir.c_str());
}
}
logger.log(LogLevel::Debug, "Expanded path: %s", expanded.c_str());
return expanded;
}
static bool isPlainTextFile(const std::string &filename, Logger &logger) {
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
logger.log(LogLevel::Warn, "Cannot open file: %s", filename.c_str());
return false;
}
std::vector<unsigned char> buffer(1024);
file.read(reinterpret_cast<char *>(buffer.data()), buffer.size());
size_t bytesRead = static_cast<size_t>(file.gcount());
if (bytesRead == 0) {
return true;
}
size_t nullCount = 0;
size_t controlCount = 0;
for (size_t i = 0; i < bytesRead; ++i) {
if (buffer[i] == 0) {
++nullCount;
} else if (buffer[i] < 32 && buffer[i] != '\n' && buffer[i] != '\r' && buffer[i] != '\t') {
++controlCount;
}
}
if (nullCount > 0 || controlCount > bytesRead / 20) {
return false;
}
return true;
}
static std::optional<std::string> readFileContent(const std::string &filename, Logger &logger, int fileSizeLimit = 10000, bool interactive = false) {
std::ifstream file(filename);
if (!file.is_open()) {
logger.log(LogLevel::Error, "Failed to open file: %s", filename.c_str());
return std::nullopt;
}
file.seekg(0, std::ios::end);
std::streampos fileSize = file.tellg();
file.seekg(0, std::ios::beg);
if (fileSize <= 0) {
return std::string();
}
if (fileSize > fileSizeLimit) {
if (interactive) {
std::fprintf(stderr, "File '%s' is %ldKB (limit: %dKB). Include anyway? [y/N]: ",
filename.c_str(), static_cast<long>(fileSize) / 1000, fileSizeLimit / 1000);
char answer = 'n';
if (std::scanf(" %c", &answer) == 1 && (answer == 'y' || answer == 'Y')) {
// proceed to read
} else {
return std::nullopt;
}
} else {
logger.log(LogLevel::Warn, "File too large (>%dKB): %s", fileSizeLimit / 1000, filename.c_str());
return std::nullopt;
}
}
std::string content(static_cast<size_t>(fileSize), '\0');
file.read(content.data(), fileSize);
content.resize(static_cast<size_t>(file.gcount()));
logger.log(LogLevel::Debug, "Read %zu bytes from file: %s", content.size(), filename.c_str());
return content;
}
static bool writeSecureFile(const std::string &path, const std::string &content, Logger &logger) {
int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd == -1) {
logger.log(LogLevel::Error, "Failed to open file for secure writing: %s", path.c_str());
return false;
}
ssize_t written = ::write(fd, content.data(), content.size());
::close(fd);
if (written < 0 || static_cast<size_t>(written) != content.size()) {
logger.log(LogLevel::Error, "Failed to write to file: %s", path.c_str());
return false;
}
return true;
}
static std::string processFileReferences(const std::string &input, Logger &logger, int fileSizeLimit = 10000, bool interactive = false) {
if (input.empty()) return {};
std::string result = input;
size_t searchPos = 0;
while ((searchPos = result.find('@', searchPos)) != std::string::npos) {
if (searchPos > 0) {
char prev = result[searchPos - 1];
if (!std::isspace(static_cast<unsigned char>(prev)) && prev != '(' && prev != '[' && prev != '{' && prev != '\n') {
searchPos += 1;
continue;
}
}
size_t filenameStart = searchPos + 1;
if (filenameStart >= result.size()) break;
bool quoted = false;
char quoteChar = '\0';
if (result[filenameStart] == '"' || result[filenameStart] == '\'') {
quoted = true;
quoteChar = result[filenameStart];
++filenameStart;
}
size_t filenameEnd = filenameStart;
if (quoted) {
while (filenameEnd < result.size() && result[filenameEnd] != quoteChar) {
++filenameEnd;
}
} else {
while (filenameEnd < result.size()) {
char c = result[filenameEnd];
if (std::isspace(static_cast<unsigned char>(c)) ||
c == '?' || c == '!' || c == ';' ||
(c == '.' && (filenameEnd + 1 >= result.size() || std::isspace(static_cast<unsigned char>(result[filenameEnd + 1])))) ||
c == ',' || c == ')' || c == '}') {
break;
}
++filenameEnd;
}
}
if (filenameEnd == filenameStart) {
searchPos = filenameStart;
continue;
}
std::string filename = result.substr(filenameStart, filenameEnd - filenameStart);
size_t suffixStart = filenameEnd;
while (!filename.empty() && (filename.back() == '"' || filename.back() == '\'' || filename.back() == '`')) {
filename.pop_back();
}
if (filename.empty()) {
searchPos = suffixStart;
continue;
}
if (quoted && suffixStart < result.size() && result[suffixStart] == quoteChar) {
++suffixStart;
}
std::string prefix = result.substr(0, searchPos);
std::string suffix = result.substr(suffixStart);
std::string replacement;
if (access(filename.c_str(), F_OK) == 0 && isPlainTextFile(filename, logger)) {
auto contentOpt = readFileContent(filename, logger, fileSizeLimit, interactive);
if (contentOpt.has_value()) {
replacement = prefix + "\nFile: " + filename + "\n```\n" + *contentOpt + "\n```" + suffix;
logger.log(LogLevel::Info, "Attached file content: %s (%zu bytes)", filename.c_str(), contentOpt->size());
} else {
replacement = prefix + "[Skipped: " + filename + " (too large)]" + suffix;
}
} else {
logger.log(LogLevel::Warn, "File not found or not plain text: %s", filename.c_str());
replacement = prefix + "[File not found: " + filename + "]" + suffix;
}
result.swap(replacement);
searchPos = result.size() - suffix.size();
}
return result;
}
};
class ModelsCacheManager {
public:
ModelsCacheData &data() { return data_; }
bool load(Logger &logger) {
std::string cachePath = FileUtil::expandHomePath(MODELS_CACHE_FILE, logger);
std::ifstream cacheFile(cachePath);
if (!cacheFile.is_open()) {
logger.log(LogLevel::Debug, "No models cache file found");
return false;
}
std::stringstream buffer;
buffer << cacheFile.rdbuf();
std::string content = buffer.str();
if (content.empty()) {
logger.log(LogLevel::Warn, "Empty models cache file");
return false;
}
cJSON *root = cJSON_Parse(content.c_str());
if (!root) {
logger.log(LogLevel::Error, "Failed to parse models cache file: %s", cJSON_GetErrorPtr());
return false;
}
cJSON *timestamp = cJSON_GetObjectItem(root, "timestamp");
if (!timestamp || !cJSON_IsNumber(timestamp)) {
logger.log(LogLevel::Error, "Invalid timestamp in models cache");
cJSON_Delete(root);
return false;
}
data_.lastUpdated = static_cast<time_t>(timestamp->valuedouble);
time_t now = time(nullptr);
if (now - data_.lastUpdated > MODELS_CACHE_EXPIRY) {
logger.log(LogLevel::Info, "Models cache is expired (older than 24 hours)");
cJSON_Delete(root);
return false;
}
cJSON *modelsArray = cJSON_GetObjectItem(root, "models");
if (!modelsArray || !cJSON_IsArray(modelsArray)) {
logger.log(LogLevel::Error, "Invalid models array in cache");
cJSON_Delete(root);
return false;
}
data_.models.clear();
int modelCount = cJSON_GetArraySize(modelsArray);
for (int i = 0; i < modelCount; ++i) {
cJSON *model = cJSON_GetArrayItem(modelsArray, i);
if (!model || !cJSON_IsObject(model)) continue;
cJSON *id = cJSON_GetObjectItem(model, "id");
cJSON *created = cJSON_GetObjectItem(model, "created");
if (!id || !cJSON_IsString(id) || !created || !cJSON_IsNumber(created)) continue;
data_.models.push_back({id->valuestring, static_cast<time_t>(created->valuedouble)});
}
cJSON_Delete(root);
logger.log(LogLevel::Info, "Loaded %zu models from cache", data_.models.size());
return !data_.models.empty();
}
bool save(Logger &logger) {
if (data_.models.empty()) {
logger.log(LogLevel::Warn, "No models to save to cache");
return false;
}
cJSON *root = cJSON_CreateObject();
if (!root) {
logger.log(LogLevel::Error, "Failed to create JSON object for cache");
return false;
}
cJSON_AddNumberToObject(root, "timestamp", static_cast<double>(data_.lastUpdated));
cJSON *modelsArray = cJSON_CreateArray();
if (!modelsArray) {
logger.log(LogLevel::Error, "Failed to create models array for cache");
cJSON_Delete(root);
return false;
}
cJSON_AddItemToObject(root, "models", modelsArray);
for (const auto &model : data_.models) {
cJSON *node = cJSON_CreateObject();
if (!node) continue;
cJSON_AddStringToObject(node, "id", model.id.c_str());
cJSON_AddNumberToObject(node, "created", static_cast<double>(model.created));
cJSON_AddItemToArray(modelsArray, node);
}
char *jsonStr = cJSON_Print(root);
if (!jsonStr) {
logger.log(LogLevel::Error, "Failed to print JSON for cache");
cJSON_Delete(root);
return false;
}
std::string cachePath = FileUtil::expandHomePath(MODELS_CACHE_FILE, logger);
std::ofstream cacheFile(cachePath);
if (!cacheFile.is_open()) {
logger.log(LogLevel::Error, "Failed to open cache file for writing");
std::free(jsonStr);
cJSON_Delete(root);
return false;
}
cacheFile << jsonStr;
cacheFile.close();
std::free(jsonStr);
cJSON_Delete(root);
logger.log(LogLevel::Info, "Saved %zu models to cache", data_.models.size());
return true;
}
private:
ModelsCacheData data_{};
};
class ContextManager {
public:
void save(const std::vector<Message> &messages, Logger &logger) {
cJSON *arr = cJSON_CreateArray();
if (!arr) return;
for (const auto &msg : messages) {
cJSON *obj = cJSON_CreateObject();
if (!obj) continue;
cJSON_AddStringToObject(obj, "role", msg.role.c_str());
cJSON_AddStringToObject(obj, "content", msg.content.c_str());
cJSON_AddItemToArray(arr, obj);
}
char *jsonStr = cJSON_Print(arr);
cJSON_Delete(arr);
if (!jsonStr) return;
std::string path = FileUtil::expandHomePath(LAST_CONTEXT_FILE, logger);
FileUtil::writeSecureFile(path, jsonStr, logger);
std::free(jsonStr);
logger.log(LogLevel::Debug, "Saved %zu messages to context file", messages.size());
}
std::vector<Message> load(Logger &logger) {
std::string path = FileUtil::expandHomePath(LAST_CONTEXT_FILE, logger);
std::ifstream file(path);
if (!file.is_open()) {
logger.log(LogLevel::Debug, "No context file found");
return {};
}
std::stringstream buf;
buf << file.rdbuf();
std::string content = buf.str();
if (content.empty()) return {};
cJSON *arr = cJSON_Parse(content.c_str());
if (!arr || !cJSON_IsArray(arr)) {
if (arr) cJSON_Delete(arr);
logger.log(LogLevel::Warn, "Failed to parse context file");
return {};
}
std::vector<Message> messages;
int n = cJSON_GetArraySize(arr);
for (int i = 0; i < n; ++i) {
cJSON *obj = cJSON_GetArrayItem(arr, i);
if (!obj) continue;
cJSON *role = cJSON_GetObjectItem(obj, "role");
cJSON *cont = cJSON_GetObjectItem(obj, "content");
if (role && cJSON_IsString(role) && cont && cJSON_IsString(cont)) {
messages.push_back({role->valuestring, cont->valuestring});
}
}
cJSON_Delete(arr);
logger.log(LogLevel::Debug, "Loaded %zu messages from context file", messages.size());
return messages;
}
};
class CurlHandle {
public:
CurlHandle() : handle_(curl_easy_init()) {}
~CurlHandle() {
if (handle_) curl_easy_cleanup(handle_);
}
CURL *get() { return handle_; }
bool valid() const { return handle_ != nullptr; }
private:
CURL *handle_{nullptr};
};
class ApiClient {
public:
ApiClient(Logger &logger, Settings &settings, ModelsCacheManager &cache)
: logger_(logger), settings_(settings), cache_(cache) {}
bool validateModel(CURL *curl, const std::string &model) {
bool cacheLoaded = cache_.load(logger_);
if (!cacheLoaded || cache_.data().models.empty()) {
if (!fetchModelsList(curl)) {
logger_.log(LogLevel::Warn, "Failed to fetch models list, continuing without validation");
return true;
}
}
for (const auto &info : cache_.data().models) {
if (info.id == model) {
logger_.log(LogLevel::Debug, "Model '%s' is valid", model.c_str());
return true;
}
}
suggestSimilarModel(model);
return false;
}
std::string sendChat(CURL *curl, std::vector<Message> &messages, double temperature, bool noStream, int tokenLimit, bool rawMode = false) {
if (messages.empty()) {
logger_.log(LogLevel::Warn, "No messages to send to API");
return {};
}
logger_.log(LogLevel::Info, "Sending request (model: %s, temp: %.2f, stream: %s)", settings_.model.c_str(), temperature, noStream ? "disabled" : "enabled");
size_t droppedCount = 0;
while (messages.size() > 1 && countTokens(messages, settings_.model) + 100 > tokenLimit) {
messages.erase(messages.begin() + 1);
++droppedCount;
}
if (droppedCount > 0) {
std::fprintf(stderr, "Warning: dropped %zu message(s) to fit within token limit.\n", droppedCount);
logger_.log(LogLevel::Debug, "Dropped %zu messages (token counting is approximate)", droppedCount);
}
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "model", settings_.model.c_str());
cJSON_AddNumberToObject(root, "temperature", temperature);
cJSON_AddBoolToObject(root, "stream", !noStream);
cJSON *messageArray = cJSON_CreateArray();
for (const auto &msg : messages) {
cJSON *message = cJSON_CreateObject();
cJSON_AddStringToObject(message, "role", msg.role.c_str());
cJSON_AddStringToObject(message, "content", msg.content.c_str());
cJSON_AddItemToArray(messageArray, message);
}
cJSON_AddItemToObject(root, "messages", messageArray);
char *jsonStr = cJSON_Print(root);
logger_.log(LogLevel::Debug, "Request: model=%s, messages=%zu, temperature=%.2f, stream=%s",
settings_.model.c_str(), messages.size(), temperature, noStream ? "false" : "true");
struct curl_slist *headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
std::string authHeader = "Authorization: Bearer " + settings_.apiKey;
headers = curl_slist_append(headers, authHeader.c_str());
if (!noStream) {
headers = curl_slist_append(headers, "Accept: text/event-stream");
}
int attempt = 0;
std::string result;
while (attempt <= MAX_RETRIES) {
attempt++;
logger_.log(LogLevel::Info, "Attempt %d/%d", attempt, MAX_RETRIES + 1);
std::atomic_bool spinnerStop(false);
std::atomic_bool firstTokenReceived(false);
ResponseBuffer buffer;
buffer.streamEnabled = !noStream;
buffer.rawMode = rawMode;
buffer.firstTokenFlag = &firstTokenReceived;
buffer.logger = &logger_;
std::thread spinnerThread;
if (!rawMode) {
spinnerThread = std::thread(spinnerLoop, std::ref(spinnerStop), std::ref(firstTokenReceived));
}
curl_easy_reset(curl);
curl_easy_setopt(curl, CURLOPT_URL, "https://api.openai.com/v1/chat/completions");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonStr);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, CONNECT_TIMEOUT);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, REQUEST_TIMEOUT);
logger_.log(LogLevel::Info, "Sending request to API...");
CURLcode res = curl_easy_perform(curl);
long httpCode = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
spinnerStop.store(true);
if (spinnerThread.joinable()) spinnerThread.join();
if (res != CURLE_OK) {
logger_.log(LogLevel::Error, "curl_easy_perform() failed: %s", curl_easy_strerror(res));
bool shouldRetry = (res == CURLE_OPERATION_TIMEDOUT) && attempt <= MAX_RETRIES;
if (shouldRetry) {
std::cout << "Request timed out, retrying (" << attempt << "/" << MAX_RETRIES + 1 << ")...\n";
continue;
} else {
std::fprintf(stderr, "Request failed: %s\n", curl_easy_strerror(res));
}
} else {
logger_.log(LogLevel::Info, "Request completed successfully");
logger_.log(LogLevel::Debug, "Response size: %zu bytes", buffer.data.size());
if (httpCode >= 400) {
printApiError(httpCode, buffer.data);
} else if (noStream) {
buffer.responseContent = extractAndPrintContent(buffer.data);
} else {
if (!buffer.sawStreamData && !buffer.data.empty()) {
buffer.responseContent = extractAndPrintContent(buffer.data);
if (buffer.responseContent.empty()) {
printApiError(httpCode, buffer.data);
}
}
if (!rawMode) std::cout << std::endl;
}
}
result = buffer.responseContent;
break;
}
curl_slist_free_all(headers);
cJSON_Delete(root);
std::free(jsonStr);
return result;
}
private:
static size_t writeCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realSize = size * nmemb;
auto *buffer = static_cast<ResponseBuffer *>(userp);
if (buffer->firstTokenFlag) {
buffer->firstTokenFlag->store(true);
}
buffer->data.append(static_cast<char *>(contents), realSize);
if (buffer->streamEnabled) {
while (true) {
size_t sepPos = buffer->data.find("\n\n");
if (sepPos == std::string::npos) break;
std::string line = buffer->data.substr(0, sepPos);
buffer->data.erase(0, sepPos + 2);
if (line.rfind("data: ", 0) == 0 && line.compare(6, std::string::npos, "[DONE]") != 0) {
std::string jsonPayload = line.substr(6);
cJSON *json = cJSON_Parse(jsonPayload.c_str());
if (json) {
cJSON *choices = cJSON_GetObjectItem(json, "choices");
if (choices && cJSON_IsArray(choices) && cJSON_GetArraySize(choices) > 0) {
cJSON *choice = cJSON_GetArrayItem(choices, 0);
cJSON *delta = cJSON_GetObjectItem(choice, "delta");
if (delta) {
cJSON *content = cJSON_GetObjectItem(delta, "content");
if (content && cJSON_IsString(content) && content->valuestring) {
buffer->responseContent += content->valuestring;
if (!buffer->sawStreamData && !buffer->rawMode) {
std::cout << "\n";
}
std::cout << content->valuestring;
std::cout.flush();
buffer->sawStreamData = true;
if (buffer->firstTokenFlag) {
buffer->firstTokenFlag->store(true);
}
}
}
}
cJSON_Delete(json);
}
}
}
}
if (buffer->logger) {
buffer->logger->log(LogLevel::Debug, "Received %zu bytes from API", realSize);
}
return realSize;
}
bool fetchModelsList(CURL *curl) {
logger_.log(LogLevel::Info, "Fetching available models from OpenAI API");
ResponseBuffer buffer;
buffer.streamEnabled = false;
buffer.sawStreamData = false;
buffer.logger = &logger_;
curl_easy_reset(curl);
struct curl_slist *headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
std::string authHeader = "Authorization: Bearer " + settings_.apiKey;
headers = curl_slist_append(headers, authHeader.c_str());
curl_easy_setopt(curl, CURLOPT_URL, "https://api.openai.com/v1/models");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
logger_.log(LogLevel::Error, "Failed to fetch models: %s", curl_easy_strerror(res));
curl_slist_free_all(headers);
return false;
}
long httpCode = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
if (httpCode != 200) {
logger_.log(LogLevel::Error, "API returned HTTP %ld when fetching models", httpCode);
curl_slist_free_all(headers);
return false;
}
cJSON *root = cJSON_Parse(buffer.data.c_str());
if (!root) {
logger_.log(LogLevel::Error, "Failed to parse API response: %s", cJSON_GetErrorPtr());
curl_slist_free_all(headers);
return false;
}
cJSON *data = cJSON_GetObjectItem(root, "data");
if (!data || !cJSON_IsArray(data)) {
logger_.log(LogLevel::Error, "Invalid response format: 'data' array not found");
cJSON_Delete(root);
curl_slist_free_all(headers);
return false;
}
cache_.data().models.clear();
cache_.data().lastUpdated = time(nullptr);
int modelCount = cJSON_GetArraySize(data);
for (int i = 0; i < modelCount; ++i) {
cJSON *model = cJSON_GetArrayItem(data, i);
if (!model || !cJSON_IsObject(model)) continue;
cJSON *id = cJSON_GetObjectItem(model, "id");
cJSON *created = cJSON_GetObjectItem(model, "created");
if (!id || !cJSON_IsString(id)) continue;
ModelInfo info;
info.id = id->valuestring;
info.created = created && cJSON_IsNumber(created) ? static_cast<time_t>(created->valuedouble) : time(nullptr);
cache_.data().models.push_back(info);
}
cJSON_Delete(root);
curl_slist_free_all(headers);
logger_.log(LogLevel::Info, "Fetched %zu models from API", cache_.data().models.size());
if (!cache_.data().models.empty()) {
cache_.save(logger_);
}
return !cache_.data().models.empty();
}
void suggestSimilarModel(const std::string &invalidModel) {
if (cache_.data().models.empty()) return;
int minDistance = std::numeric_limits<int>::max();
std::string closestModel;
for (const auto &info : cache_.data().models) {
int distance = levenshteinDistance(invalidModel, info.id);
if (distance < minDistance) {
minDistance = distance;
closestModel = info.id;
}
}
if (minDistance <= 5) {
std::printf("Model '%s' not found. Did you mean '%s'?\n", invalidModel.c_str(), closestModel.c_str());
logger_.log(LogLevel::Info, "Suggested alternative model: %s (distance: %d)", closestModel.c_str(), minDistance);
} else {
std::printf("Model '%s' not found. Available models include: gpt-4o, gpt-4o-mini, gpt-3.5-turbo\n", invalidModel.c_str());
}
}
static std::string extractAndPrintContent(const std::string &body, bool print = true) {
cJSON *json = cJSON_Parse(body.c_str());
if (!json) {
return {};
}
std::string result;
cJSON *choices = cJSON_GetObjectItem(json, "choices");
if (choices && cJSON_IsArray(choices) && cJSON_GetArraySize(choices) > 0) {
cJSON *choice = cJSON_GetArrayItem(choices, 0);
cJSON *message = cJSON_GetObjectItem(choice, "message");
if (message) {
cJSON *content = cJSON_GetObjectItem(message, "content");
if (content && cJSON_IsString(content) && content->valuestring) {
result = content->valuestring;
if (print) {
std::cout << result << "\n";
}
}
}
}
cJSON_Delete(json);
return result;
}
static void printApiError(long httpCode, const std::string &body) {
cJSON *err = cJSON_Parse(body.c_str());
if (err) {
cJSON *errorObj = cJSON_GetObjectItem(err, "error");
cJSON *msg = errorObj ? cJSON_GetObjectItem(errorObj, "message") : nullptr;
if (msg && cJSON_IsString(msg) && msg->valuestring) {
std::fprintf(stderr, "API error (HTTP %ld): %s\n", httpCode, msg->valuestring);
} else {
std::fprintf(stderr, "API error (HTTP %ld).\n", httpCode);
}
cJSON_Delete(err);
} else {
std::fprintf(stderr, "API error (HTTP %ld).\n", httpCode);
}
}
public:
static int countTokens(const std::vector<Message> &messages, const std::string &model) {
(void)model;
int tokens = 3;
for (const auto &message : messages) {
tokens += 3;
tokens += static_cast<int>(message.content.size()) / 4;
if (!message.role.empty()) tokens += 1;
}
return tokens;
}
private:
static int levenshteinDistance(const std::string &s1, const std::string &s2) {
size_t len1 = s1.size();
size_t len2 = s2.size();
std::vector<std::vector<int>> matrix(len1 + 1, std::vector<int>(len2 + 1));
for (size_t i = 0; i <= len1; ++i) matrix[i][0] = static_cast<int>(i);
for (size_t j = 0; j <= len2; ++j) matrix[0][j] = static_cast<int>(j);
for (size_t i = 1; i <= len1; ++i) {
for (size_t j = 1; j <= len2; ++j) {
int cost = s1[i - 1] == s2[j - 1] ? 0 : 1;
int deletion = matrix[i - 1][j] + 1;
int insertion = matrix[i][j - 1] + 1;
int substitution = matrix[i - 1][j - 1] + cost;
matrix[i][j] = std::min({deletion, insertion, substitution});
}
}
return matrix[len1][len2];
}
static void spinnerLoop(std::atomic_bool &stopFlag, std::atomic_bool &firstTokenFlag) {
const char frames[] = {'|', '/', '-', '\\'};
size_t idx = 0;
std::cout << "thinking... " << std::flush;
while (!stopFlag.load()) {
if (firstTokenFlag.load()) {
std::cout << "\n" << std::flush; // newline to separate spinner from response output
return;
}
std::cout << "\rthinking... " << frames[idx % 4] << std::flush;
idx++;
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
std::cout << std::endl << std::flush;
}
Logger &logger_;
Settings &settings_;
ModelsCacheManager &cache_;
};
struct ParseOutcome {
bool continueMode{false};
bool noStream{false};
bool rawMode{false};
bool contextLast{false};
double temperature{1.0};
std::string inputText;
bool shouldExit{false};
int exitCode{0};
};
std::string maskApiKey(const std::string &key) {
if (key.size() <= 8) return "****";
return key.substr(0, 5) + "..." + key.substr(key.size() - 4);
}
class Application {
public:
Application() : logger_() {
curl_global_init(CURL_GLOBAL_ALL);
}
~Application() {
curl_global_cleanup();
}
int run(int argc, char *argv[]) {
// Pre-pass for logging flags
preParseLogging(argc, argv);
logger_.configure(settings_.logLevel, settings_.debugMode, settings_.logToFile, settings_.logFilePath);
loadEnvironment();
ParseOutcome outcome = parseArguments(argc, argv);
if (outcome.shouldExit) {
return outcome.exitCode;
}
if (outcome.contextLast && outcome.continueMode) {
std::fprintf(stderr, "Error: --context last and --continue are mutually exclusive.\n");
return 1;
}
if (!curlHandle_.valid()) {
logger_.log(LogLevel::Error, "Failed to initialize curl");
return 1;