File size: 8,174 Bytes
829dbce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Minimal HTTP/1.1 client + just enough JSON to talk to a local model server.
// No libcurl, no JSON library: the request shape is fixed and only three fields
// are read back, so a dependency would cost more than it saves.
#include "ctxstream.hpp"

#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstring>
#include <sstream>
#include <string>

namespace ctxstream {

static std::string json_escape(const std::string& s) {
    std::string o;
    o.reserve(s.size() + 32);
    for (unsigned char c : s) {
        switch (c) {
            case '"':  o += "\\\""; break;
            case '\\': o += "\\\\"; break;
            case '\n': o += "\\n";  break;
            case '\r': o += "\\r";  break;
            case '\t': o += "\\t";  break;
            case '\b': o += "\\b";  break;
            case '\f': o += "\\f";  break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof buf, "\\u%04x", c);
                    o += buf;
                } else {
                    o += static_cast<char>(c);
                }
        }
    }
    return o;
}

// Unescape a JSON string body (the model's reply). Handles the escapes we emit
// and the \uXXXX that servers produce; non-ASCII code points are passed through
// as UTF-8.
static std::string json_unescape(const std::string& s) {
    std::string o;
    o.reserve(s.size());
    for (std::size_t i = 0; i < s.size(); ++i) {
        if (s[i] != '\\' || i + 1 >= s.size()) { o += s[i]; continue; }
        const char n = s[++i];
        switch (n) {
            case 'n': o += '\n'; break;
            case 't': o += '\t'; break;
            case 'r': o += '\r'; break;
            case 'b': o += '\b'; break;
            case 'f': o += '\f'; break;
            case '"': o += '"';  break;
            case '\\': o += '\\'; break;
            case '/': o += '/';  break;
            case 'u': {
                if (i + 4 >= s.size()) break;
                const unsigned cp =
                    std::stoul(s.substr(i + 1, 4), nullptr, 16);
                i += 4;
                if (cp < 0x80) {
                    o += static_cast<char>(cp);
                } else if (cp < 0x800) {
                    o += static_cast<char>(0xC0 | (cp >> 6));
                    o += static_cast<char>(0x80 | (cp & 0x3F));
                } else {
                    o += static_cast<char>(0xE0 | (cp >> 12));
                    o += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
                    o += static_cast<char>(0x80 | (cp & 0x3F));
                }
                break;
            }
            default: o += n;
        }
    }
    return o;
}

// Extract "key":"..." respecting backslash escapes.
static bool json_string_field(const std::string& body, const std::string& key,
                              std::string* out) {
    const std::string needle = "\"" + key + "\"";
    std::size_t p = body.find(needle);
    if (p == std::string::npos) return false;
    p = body.find(':', p + needle.size());
    if (p == std::string::npos) return false;
    while (p < body.size() && (body[++p] == ' ' || body[p] == '\t')) {}
    if (p >= body.size() || body[p] != '"') return false;
    const std::size_t start = ++p;
    for (; p < body.size(); ++p) {
        if (body[p] == '\\') { ++p; continue; }
        if (body[p] == '"') break;
    }
    if (p >= body.size()) return false;
    *out = json_unescape(body.substr(start, p - start));
    return true;
}

static long json_number_field(const std::string& body, const std::string& key,
                              long fallback = 0) {
    const std::string needle = "\"" + key + "\"";
    std::size_t p = body.find(needle);
    if (p == std::string::npos) return fallback;
    p = body.find(':', p + needle.size());
    if (p == std::string::npos) return fallback;
    ++p;
    while (p < body.size() && (body[p] == ' ' || body[p] == '\t')) ++p;
    const std::size_t start = p;
    while (p < body.size() && (std::isdigit(static_cast<unsigned char>(body[p])) ||
                               body[p] == '-' || body[p] == '.')) ++p;
    if (p == start) return fallback;
    try { return std::stol(body.substr(start, p - start)); }
    catch (...) { return fallback; }
}

static bool http_post(const BackendOptions& opt, const std::string& payload,
                      std::string* response, std::string* err) {
    addrinfo hints{};
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    addrinfo* res = nullptr;
    const std::string port = std::to_string(opt.port);
    if (getaddrinfo(opt.host.c_str(), port.c_str(), &hints, &res) != 0 || !res) {
        *err = "getaddrinfo failed for " + opt.host + ":" + port;
        return false;
    }

    int fd = -1;
    for (addrinfo* a = res; a; a = a->ai_next) {
        fd = ::socket(a->ai_family, a->ai_socktype, a->ai_protocol);
        if (fd < 0) continue;
        timeval tv{opt.timeout_sec, 0};
        setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
        setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
        if (::connect(fd, a->ai_addr, a->ai_addrlen) == 0) break;
        ::close(fd);
        fd = -1;
    }
    freeaddrinfo(res);
    if (fd < 0) { *err = "connect failed to " + opt.host + ":" + port; return false; }

    std::ostringstream req;
    req << "POST " << opt.path << " HTTP/1.1\r\n"
        << "Host: " << opt.host << ":" << opt.port << "\r\n"
        << "Content-Type: application/json\r\n"
        << "Content-Length: " << payload.size() << "\r\n"
        << "Connection: close\r\n\r\n"
        << payload;
    const std::string raw = req.str();

    for (std::size_t sent = 0; sent < raw.size();) {
        const ssize_t n = ::send(fd, raw.data() + sent, raw.size() - sent, 0);
        if (n <= 0) { ::close(fd); *err = "send failed"; return false; }
        sent += static_cast<std::size_t>(n);
    }

    std::string all;
    char buf[16384];
    for (;;) {
        const ssize_t n = ::recv(fd, buf, sizeof buf, 0);
        if (n < 0) { ::close(fd); *err = "recv timeout/error"; return false; }
        if (n == 0) break;
        all.append(buf, static_cast<std::size_t>(n));
    }
    ::close(fd);

    const std::size_t hdr = all.find("\r\n\r\n");
    if (hdr == std::string::npos) { *err = "malformed HTTP response"; return false; }
    *response = all.substr(hdr + 4);
    return true;
}

Completion complete(const BackendOptions& opt, const std::string& system_prompt,
                    const std::string& user_prompt) {
    Completion c;
    std::ostringstream body;
    body << "{\"model\":\"" << json_escape(opt.model) << "\","
         << "\"stream\":false,"
         << "\"options\":{\"num_ctx\":" << opt.num_ctx
         << ",\"num_predict\":" << opt.num_predict
         << ",\"temperature\":0},"
         << "\"messages\":[";
    if (!system_prompt.empty()) {
        body << "{\"role\":\"system\",\"content\":\"" << json_escape(system_prompt)
             << "\"},";
    }
    body << "{\"role\":\"user\",\"content\":\"" << json_escape(user_prompt)
         << "\"}]}";

    std::string resp;
    if (!http_post(opt, body.str(), &resp, &c.error)) return c;

    std::string err;
    if (json_string_field(resp, "error", &err) && !err.empty()) {
        c.error = "server: " + err;
        return c;
    }
    if (!json_string_field(resp, "content", &c.text)) {
        c.error = "no content field in response: " + resp.substr(0, 200);
        return c;
    }
    c.prompt_tokens = json_number_field(resp, "prompt_eval_count");
    c.output_tokens = json_number_field(resp, "eval_count");
    c.ok = true;
    return c;
}

bool looks_truncated(std::size_t prompt_chars, long prompt_tokens) {
    if (prompt_tokens <= 0) return false;  // server did not report; cannot judge
    // Deliberately loose: no real tokenizer reaches 5 chars/token, so this fires
    // only on gross clipping (measured: 50,000 tokens sent, 16,387 processed),
    // never on tokenizer variance.
    return static_cast<std::size_t>(prompt_tokens) < prompt_chars / 5;
}

}  // namespace ctxstream