Repository navigation
Expand file tree
/
Copy pathapi_formats.cpp
More file actions
410 lines (358 loc) · 13.5 KB
/
Copy pathapi_formats.cpp
File metadata and controls
410 lines (358 loc) · 13.5 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
/**
* API format loader and request/response transformers
*/
#include "api_formats.h"
#include "config.h"
#include "lang.h"
#include "util/fs.h"
#include "Logger.h"
#include <fstream>
#include <filesystem>
#include <iostream>
#include <mutex>
#include <sstream>
#include <algorithm>
#include <set>
#include <format>
namespace ragger {
namespace fs = std::filesystem;
// -----------------------------------------------------------------------
// Hardcoded OpenAI default — the "no file needed" format
// -----------------------------------------------------------------------
static const ApiFormat OPENAI_FORMAT = {
"/chat/completions", // path
"bearer", // auth
"Authorization", // auth_header
"Bearer ", // auth_prefix
{}, // auth_extra
"openai", // request_transform
"choices[0].message.content", // response_content
// Thinking models (e.g. Gemma 4, DeepSeek R1 over OpenAI-compat shims)
// sometimes return the visible answer in `reasoning_content` with an
// empty `content`. Try that path as a fallback before giving up.
{ "choices[0].message.reasoning_content" }, // response_content_fallbacks
"choices[0].delta.content", // stream_content
"", // stream_type_field
"", // stream_type_value
"[DONE]" // stream_stop
};
// -----------------------------------------------------------------------
// Format search dirs
// -----------------------------------------------------------------------
static std::vector<std::string> _format_search_dirs() {
std::vector<std::string> dirs;
dirs.push_back(config().resolved_formats_dir());
// Development fallback: the formats dir of the source tree this binary
// was built from (RAGGER_DEV_FORMATS_DIR, set by CMake). On installed
// builds that path doesn't exist and the guard skips it — this replaces
// an older hardcoded "~/CLionProjects/Ragger/formats" guess, which
// baked one developer's checkout layout into every binary.
#ifdef RAGGER_DEV_FORMATS_DIR
if (fs::exists(RAGGER_DEV_FORMATS_DIR)) {
dirs.push_back(RAGGER_DEV_FORMATS_DIR);
}
#endif
return dirs;
}
// -----------------------------------------------------------------------
// Cache
// -----------------------------------------------------------------------
static std::map<std::string, ApiFormat> _cache;
// get_format() is called from httplib worker threads (summarizer requests
// run concurrently), so the cache needs one lock around check-and-load.
static std::mutex _cache_mutex;
/// Get a string from JSON, treating null as the default value.
static std::string json_string(const nlohmann::json& j, const std::string& key,
const std::string& def = "") {
if (!j.contains(key) || j[key].is_null()) return def;
return j[key].get<std::string>();
}
static std::optional<ApiFormat> _load_format_file(const std::string& name) {
for (const auto& dir : _format_search_dirs()) {
std::string path = dir + "/" + name + ".json";
if (fs::exists(path)) {
try {
std::ifstream file(path);
nlohmann::json j;
file >> j;
ApiFormat fmt;
fmt.path = json_string(j, "path", OPENAI_FORMAT.path);
fmt.auth = json_string(j, "auth", OPENAI_FORMAT.auth);
fmt.auth_header = json_string(j, "auth_header", OPENAI_FORMAT.auth_header);
fmt.auth_prefix = json_string(j, "auth_prefix", OPENAI_FORMAT.auth_prefix);
fmt.request_transform = json_string(j, "request_transform", OPENAI_FORMAT.request_transform);
fmt.response_content = json_string(j, "response_content", OPENAI_FORMAT.response_content);
if (j.contains("response_content_fallbacks") &&
j["response_content_fallbacks"].is_array()) {
for (const auto& v : j["response_content_fallbacks"]) {
if (v.is_string()) fmt.response_content_fallbacks.push_back(v.get<std::string>());
}
} else {
fmt.response_content_fallbacks = OPENAI_FORMAT.response_content_fallbacks;
}
fmt.stream_content = json_string(j, "stream_content", OPENAI_FORMAT.stream_content);
fmt.stream_type_field = json_string(j, "stream_type_field", "");
fmt.stream_type_value = json_string(j, "stream_type_value", "");
fmt.stream_stop = json_string(j, "stream_stop", OPENAI_FORMAT.stream_stop);
// Load auth_extra as a map
if (j.contains("auth_extra") && j["auth_extra"].is_object()) {
for (auto& [key, val] : j["auth_extra"].items()) {
if (val.is_string()) {
fmt.auth_extra[key] = val.get<std::string>();
}
}
}
// Loaded silently
return fmt;
} catch (const std::exception& e) {
Diskerror::Logger::warn(std::format(ragger::lang::WARN_FORMAT_LOAD_FAILED,
path, e.what()));
}
}
}
return std::nullopt;
}
ApiFormat get_format(const std::string& name) {
std::string use_name = name.empty() ? "openai" : name;
std::lock_guard<std::mutex> lock(_cache_mutex);
// Check cache
auto it = _cache.find(use_name);
if (it != _cache.end()) {
return it->second;
}
// Try to load
auto fmt = _load_format_file(use_name);
if (!fmt) {
if (use_name == "openai") {
// Fallback to hardcoded default
_cache[use_name] = OPENAI_FORMAT;
return OPENAI_FORMAT;
}
throw std::runtime_error(std::format(lang::ERR_UNKNOWN_FORMAT, use_name, use_name));
}
_cache[use_name] = *fmt;
return *fmt;
}
std::vector<std::string> list_formats() {
std::set<std::string> names;
names.insert("openai");
for (const auto& dir : _format_search_dirs()) {
if (fs::exists(dir) && fs::is_directory(dir)) {
for (const auto& entry : fs::directory_iterator(dir)) {
if (entry.is_regular_file() && entry.path().extension() == ".json") {
names.insert(entry.path().stem().string());
}
}
}
}
return std::vector<std::string>(names.begin(), names.end());
}
std::string detect_format(const std::string& api_url) {
if (api_url.find("anthropic.com") != std::string::npos) {
return "anthropic";
}
return "openai";
}
// -----------------------------------------------------------------------
// Request builders
// -----------------------------------------------------------------------
static nlohmann::json _build_openai_body(
const std::vector<ApiMessage>& messages,
const std::string& model,
int max_tokens,
bool stream
) {
nlohmann::json body;
body["model"] = model;
body["max_tokens"] = max_tokens;
body["stream"] = stream;
nlohmann::json msgs = nlohmann::json::array();
for (const auto& msg : messages) {
msgs.push_back({
{"role", msg.role},
{"content", msg.content}
});
}
body["messages"] = msgs;
return body;
}
static nlohmann::json _build_anthropic_body(
const std::vector<ApiMessage>& messages,
const std::string& model,
int max_tokens,
bool stream
) {
std::string system_text;
nlohmann::json chat_messages = nlohmann::json::array();
for (const auto& msg : messages) {
if (msg.role == "system") {
if (!system_text.empty()) {
system_text += "\n\n";
}
system_text += msg.content;
} else {
chat_messages.push_back({
{"role", msg.role},
{"content", msg.content}
});
}
}
nlohmann::json body;
body["model"] = model;
body["messages"] = chat_messages;
body["max_tokens"] = max_tokens;
if (!system_text.empty()) {
body["system"] = system_text;
}
if (stream) {
body["stream"] = true;
}
return body;
}
nlohmann::json build_request_body(
const ApiFormat& fmt,
const std::vector<ApiMessage>& messages,
const std::string& model,
int max_tokens,
bool stream
) {
if (fmt.request_transform == "anthropic") {
return _build_anthropic_body(messages, model, max_tokens, stream);
} else {
return _build_openai_body(messages, model, max_tokens, stream);
}
}
// -----------------------------------------------------------------------
// Path extraction for dot-bracket paths
// -----------------------------------------------------------------------
struct PathPart {
enum Type { KEY, INDEX };
Type type;
std::string key;
int index;
};
static std::vector<PathPart> _split_path(const std::string& path) {
std::vector<PathPart> parts;
std::string current;
for (size_t i = 0; i < path.size(); ++i) {
char c = path[i];
if (c == '.') {
if (!current.empty()) {
parts.push_back({PathPart::KEY, current, 0});
current.clear();
}
} else if (c == '[') {
if (!current.empty()) {
parts.push_back({PathPart::KEY, current, 0});
current.clear();
}
// Extract index
std::string idx_str;
i++;
while (i < path.size() && path[i] != ']') {
idx_str += path[i];
i++;
}
parts.push_back({PathPart::INDEX, "", std::stoi(idx_str)});
} else {
current += c;
}
}
if (!current.empty()) {
parts.push_back({PathPart::KEY, current, 0});
}
return parts;
}
static std::optional<nlohmann::json> _extract_path(
const nlohmann::json& data,
const std::string& path
) {
nlohmann::json obj = data;
for (const auto& part : _split_path(path)) {
if (obj.is_null()) {
return std::nullopt;
}
if (part.type == PathPart::INDEX) {
if (obj.is_array() && part.index >= 0 &&
static_cast<size_t>(part.index) < obj.size()) {
obj = obj[part.index];
} else {
return std::nullopt;
}
} else {
if (obj.is_object() && obj.contains(part.key)) {
obj = obj[part.key];
} else {
return std::nullopt;
}
}
}
return obj;
}
std::string extract_content(const ApiFormat& fmt, const nlohmann::json& response) {
auto result = _extract_path(response, fmt.response_content);
if (result && result->is_string()) {
std::string s = result->get<std::string>();
if (!s.empty()) return s;
}
for (const auto& path : fmt.response_content_fallbacks) {
auto alt = _extract_path(response, path);
if (alt && alt->is_string()) {
std::string s = alt->get<std::string>();
if (!s.empty()) return s;
}
}
return "";
}
std::string extract_stream_delta(const ApiFormat& fmt, const nlohmann::json& chunk) {
// Check type filter if specified
if (!fmt.stream_type_field.empty() && !fmt.stream_type_value.empty()) {
if (!chunk.contains(fmt.stream_type_field) ||
chunk[fmt.stream_type_field] != fmt.stream_type_value) {
return "";
}
}
auto result = _extract_path(chunk, fmt.stream_content);
if (result && result->is_string()) {
return result->get<std::string>();
}
return "";
}
bool is_stream_stop(const ApiFormat& fmt, const std::string& line, const nlohmann::json* chunk) {
// Check line format: "data: [DONE]"
std::string trimmed = line;
trimmed.erase(0, trimmed.find_first_not_of(" \t\r\n"));
trimmed.erase(trimmed.find_last_not_of(" \t\r\n") + 1);
if (trimmed == "data: " + fmt.stream_stop) {
return true;
}
// Check chunk type field
if (chunk && chunk->is_object()) {
std::string type_field = fmt.stream_type_field.empty() ? "type" : fmt.stream_type_field;
if (chunk->contains(type_field) && (*chunk)[type_field] == fmt.stream_stop) {
return true;
}
}
return false;
}
// -----------------------------------------------------------------------
// Header builder
// -----------------------------------------------------------------------
std::map<std::string, std::string> build_headers(const ApiFormat& fmt, const std::string& api_key) {
std::map<std::string, std::string> headers;
headers["Content-Type"] = "application/json";
if (!api_key.empty()) {
// Both auth modes build the header value identically (prefix + key);
// they differ only in the format's own auth_header/auth_prefix data
// (Bearer-style Authorization vs a named header). One branch so a
// future real difference must be a deliberate change here.
if (fmt.auth == "bearer" || fmt.auth == "header")
headers[fmt.auth_header] = fmt.auth_prefix + api_key;
}
// Add extra headers
for (const auto& [key, val] : fmt.auth_extra) {
headers[key] = val;
}
return headers;
}
} // namespace ragger