// 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 #include #include #include #include #include #include #include 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(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(cp); } else if (cp < 0x800) { o += static_cast(0xC0 | (cp >> 6)); o += static_cast(0x80 | (cp & 0x3F)); } else { o += static_cast(0xE0 | (cp >> 12)); o += static_cast(0x80 | ((cp >> 6) & 0x3F)); o += static_cast(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(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(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(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(prompt_tokens) < prompt_chars / 5; } } // namespace ctxstream