-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcurler.cpp
More file actions
304 lines (251 loc) · 9.06 KB
/
Copy pathcurler.cpp
File metadata and controls
304 lines (251 loc) · 9.06 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
#include "curler.h"
#include <iostream>
#include <string>
#include <curl/curl.h>
#include "json.hpp"
#include "application.h"
// Callback to write response data to a std::string
size_t Curler::WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
// Shared state for streaming
struct StreamState {
std::string buffer; // raw chunk buffer
std::string accumulated; // full response
std::function<void(const std::string&)> onChunk; // user callback
bool done = false;
};
// SSE callback for streaming
static size_t WriteStreamCallback(
char* ptr,
size_t size,
size_t nmemb,
void* userdata
) {
auto* st = static_cast<StreamState*>(userdata);
st->buffer.append(ptr, size * nmemb);
size_t pos;
while ((pos = st->buffer.find("\n")) != std::string::npos) {
std::string line = st->buffer.substr(0, pos);
st->buffer.erase(0, pos + 1);
if (line.rfind("data: ", 0) == 0) {
std::string payload = line.substr(6);
if (payload == "[DONE]") {
st->done = true;
break;
}
auto j = nlohmann::json::parse(payload);
auto object = j["choices"][0];
if (object.contains("delta")) {
auto delta = object["delta"];
if (delta.contains("content")) {
std::string text = delta["content"].get<std::string>();
st->accumulated += text;
st->onChunk(text);
}
}else if (object.contains("text")){
std::string text = object["text"].get<std::string>();
st->accumulated += text;
st->onChunk(text);
}
}
}
return size * nmemb;
}
void Curler::loadModel() {
int maxtokens = 1;
std::string request = "a";
std::string baseUrl = App::settings->getValue("ai_model_url", std::string("http://localhost:1234/v1"));
std::string url = baseUrl + "/completions";
std::string apiKey = App::settings->getValue("ai_model_api_key", std::string(""));
std::string defmdl = "qwen2.5-coder-1.5b-instruct@q4_k_m";
nlohmann::json itm;
itm["model"] = App::settings->getValue("lm_studio_model_id", defmdl);
itm["prompt"] = request;
itm["temperature"] = 0.7;
itm["max_tokens"] = maxtokens;
itm["stream"] = false;
std::string json = itm.dump();
std::thread([url, json, apiKey](){
bool wrkd;
run_curl(url, json, apiKey, wrkd);
}).detach();
}
// This is the new, updated signature
std::string Curler::run_curl(std::string url, std::string json, const std::string& apiKey, bool& worked) {
CURL* curl;
CURLcode res;
std::string readBuffer = "";
worked = false;
curl = curl_easy_init();
if(curl) {
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// --- ADDED LOGIC FOR API KEY ---
if (!apiKey.empty()) {
std::string authHeader = "Authorization: Bearer " + apiKey;
headers = curl_slist_append(headers, authHeader.c_str());
}
// ------------------------------
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
if(res != CURLE_OK){
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
worked = false;
readBuffer = "Could not access server.";
}else{
std::cout << "Response: " << readBuffer << std::endl;
worked = true;
}
// Cleanup
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
}
return readBuffer;
}
std::string Curler::StreamChatResponse(const std::vector<std::pair<bool, std::string>>& messages, std::function<void(const std::string&)> stream_callback, const std::string& system_prompt) {
nlohmann::json payload;
payload["model"] = App::settings->getValue(
"lm_studio_model_id",
std::string("qwen2.5-coder-1.5b-instruct@q4_k_m")
);
payload["stream"] = true;
nlohmann::json msgarr = nlohmann::json::array();
if (!system_prompt.empty()) {
msgarr.push_back({{"role", "system"}, {"content", system_prompt}});
}
for (auto& m : messages) {
nlohmann::json mm;
mm["role"] = m.first ? "user" : "assistant";
mm["content"] = m.second;
msgarr.push_back(mm);
}
payload["messages"] = std::move(msgarr);
std::string body = payload.dump();
std::string baseUrl = App::settings->getValue("ai_model_url", std::string("http://localhost:1234/v1"));
std::string url = baseUrl + "/chat/completions";
std::string apiKey = App::settings->getValue("ai_model_api_key", std::string(""));
CURL* curl = curl_easy_init();
if (!curl) {
throw std::runtime_error("Failed to init curl");
}
StreamState state;
state.onChunk = std::move(stream_callback);
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Accept: text/event-stream");
if (!apiKey.empty()) {
std::string authHeader = "Authorization: Bearer " + apiKey;
headers = curl_slist_append(headers, authHeader.c_str());
}
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteStreamCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
throw std::runtime_error(
std::string("curl_easy_perform() failed: ") +
curl_easy_strerror(res)
);
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return state.accumulated;
}
// Streams a fill-in-the-middle completion, invoking onChunk for each text delta
std::string Curler::StreamInsertion(
const std::string& before,
const std::string& after,
std::function<void(const std::string&)> onChunk
) {
if (!App::settings->getValue("use_non_chat_completions", true)) {
std::vector<std::pair<bool, std::string>> messages;
messages.push_back({
true,
"Provide a code insertion given the following context. Note that your response **does not include any text other than the code to be inserted**. No markdown (this includes code segmens like ```), no explanation of the code. Reply with **only** code as plaintext. You may provide multiple lines if the situation calls for it. Match the indentation such that it can be inserted without changing it. Match the indentation type (tabs vs spaces). The cursor position (place where your response will be inserted) is marked:\n\n"+before+"[cursor is here]"+after
});
return StreamChatResponse(messages, onChunk);
}
int maxtokens = App::settings->getValue("lm_studio_max_tokens", 30);
std::string request = "<|fim_prefix|>" + before + "<|fim_suffix|>" + after + "<|fim_middle|>";
// --- GET URL & API KEY FROM SETTINGS ---
std::string baseUrl = App::settings->getValue("ai_model_url", std::string("http://localhost:1234/v1"));
std::string url = baseUrl + "/completions";
std::string apiKey = App::settings->getValue("ai_model_api_key", std::string(""));
// -------------------------------------
nlohmann::json payload;
// ... (payload building is unchanged)
payload["model"] = App::settings->getValue(
"lm_studio_model_id",
std::string("qwen2.5-coder-1.5b-instruct@q4_k_m")
);
payload["prompt"] = request;
payload["temperature"] = 0.7;
payload["max_tokens"] = maxtokens;
payload["stream"] = true;
payload["stop"] = {
"<|endoftext|>",
"<|fim_prefix|>",
"<|fim_suffix|>",
"<|fim_middle|>"
};
std::string body = payload.dump();
StreamState state;
state.onChunk = std::move(onChunk);
CURL* curl = curl_easy_init();
if (!curl) {
throw std::runtime_error("Failed to init curl");
}
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Accept: text/event-stream");
// --- ADDED LOGIC FOR API KEY ---
if (!apiKey.empty()) {
std::string authHeader = "Authorization: Bearer " + apiKey;
headers = curl_slist_append(headers, authHeader.c_str());
}
// -----------------------------
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteStreamCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state);
CURLcode res = curl_easy_perform(curl);
// ... (error handling and cleanup are unchanged)
if (res != CURLE_OK) {
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
throw std::runtime_error(
std::string("curl_easy_perform() failed: ") +
curl_easy_strerror(res)
);
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return state.accumulated;
}
// Updated to call the streaming insertion
std::string Curler::getInsertion(
const std::string& before,
const std::string& after
) {
// print chunks as they arrive
std::string result = Curler::StreamInsertion(
before,
after,
[](const std::string& chunk) {
std::cout << chunk;
}
);
std::cout << std::endl;
return result;
}