-
Notifications
You must be signed in to change notification settings - Fork 20k
cli : move to HTTP-based implementation #24948
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ngxson
wants to merge
10
commits into
master
Choose a base branch
from
xsn/cli_http_based
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,311
−714
Open
Changes from 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
5979767
cli: move to HTTP-based implementation
ngxson f7421ea
wip
ngxson 90c111b
Merge branch 'master' into xsn/cli_http_based
ngxson 19296c1
working
ngxson 85c58bb
remote server ok
ngxson 1401fc3
cli support router mode
ngxson b093e46
case: router with only one model
ngxson beef5cf
Apply suggestions from code review
ngxson 5d67f69
remove outdated comment
ngxson a432e6f
use destructor instead
ngxson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| #include "cli-client.h" | ||
|
|
||
| #include "http.h" | ||
|
|
||
| #include <algorithm> | ||
| #include <chrono> | ||
| #include <thread> | ||
|
|
||
| // generation can stall for a long time during prompt processing, so the | ||
| // read timeout must be generous | ||
| static constexpr time_t CLI_HTTP_READ_TIMEOUT_SEC = 3600; | ||
|
|
||
| // upper bound for the accumulated response body kept for error reporting | ||
| static constexpr size_t CLI_HTTP_MAX_ERROR_BODY = 1024 * 1024; | ||
|
|
||
| // returns the path with the base url's path prefix prepended (if any) | ||
| static std::string join_path(const common_http_url & parts, const std::string & path) { | ||
| if (parts.path.empty() || parts.path == "/") { | ||
| return path; | ||
| } | ||
| std::string prefix = parts.path; | ||
| if (prefix.back() == '/') { | ||
| prefix.pop_back(); | ||
| } | ||
| return prefix + path; | ||
| } | ||
|
|
||
| json cli_client::get(const std::string & path) { | ||
| auto [cli, parts] = common_http_client(server_base); | ||
| cli.set_read_timeout(CLI_HTTP_READ_TIMEOUT_SEC, 0); | ||
| auto path_with_model = path + (model.empty() ? "" : ("?model=" + model)); | ||
| auto res = cli.Get(join_path(parts, path_with_model)); | ||
| if (!res) { | ||
| throw std::runtime_error("failed to connect to " + server_base + ": " + httplib::to_string(res.error())); | ||
| } | ||
| if (res->status < 200 || res->status >= 300) { | ||
| throw std::runtime_error("GET " + path + " failed with status " + std::to_string(res->status) + ": " + res->body); | ||
| } | ||
| json result = json::parse(res->body, nullptr, false); | ||
| if (result.is_discarded()) { | ||
| throw std::runtime_error("GET " + path + " returned invalid JSON"); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| json cli_client::post(const std::string & path, const json & body) { | ||
| auto [cli, parts] = common_http_client(server_base); | ||
| cli.set_read_timeout(CLI_HTTP_READ_TIMEOUT_SEC, 0); | ||
| auto body_with_model = body; | ||
| if (!model.empty()) { | ||
| body_with_model["model"] = model; | ||
| } | ||
| auto res = cli.Post(join_path(parts, path), body_with_model.dump(), "application/json"); | ||
| if (!res) { | ||
| throw std::runtime_error("failed to connect to " + server_base + ": " + httplib::to_string(res.error())); | ||
| } | ||
| if (res->status < 200 || res->status >= 300) { | ||
| throw std::runtime_error("POST " + path + " failed with status " + std::to_string(res->status) + ": " + res->body); | ||
| } | ||
| json result = json::parse(res->body, nullptr, false); | ||
| if (result.is_discarded()) { | ||
| throw std::runtime_error("POST " + path + " returned invalid JSON"); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| json cli_client::post_sse(const std::string & path, | ||
| const json & body, | ||
| const std::function<bool()> & should_stop, | ||
| const std::function<void(const json &)> & on_data) { | ||
| auto [cli, parts] = common_http_client(server_base); | ||
| cli.set_read_timeout(CLI_HTTP_READ_TIMEOUT_SEC, 0); | ||
|
|
||
| std::string pending; // buffer for incomplete SSE lines | ||
| std::string raw_body; // accumulated body, used only for error reporting | ||
|
|
||
| auto receiver = [&](const char * data, size_t len) -> bool { | ||
| if (should_stop()) { | ||
| return false; // aborts the request | ||
| } | ||
| if (raw_body.size() < CLI_HTTP_MAX_ERROR_BODY) { | ||
| raw_body.append(data, std::min(len, CLI_HTTP_MAX_ERROR_BODY - raw_body.size())); | ||
| } | ||
| pending.append(data, len); | ||
| size_t pos; | ||
| while ((pos = pending.find('\n')) != std::string::npos) { | ||
| std::string line = pending.substr(0, pos); | ||
| pending.erase(0, pos + 1); | ||
| if (!line.empty() && line.back() == '\r') { | ||
| line.pop_back(); | ||
| } | ||
| if (line.rfind("data: ", 0) != 0) { | ||
| continue; | ||
| } | ||
| std::string payload = line.substr(6); | ||
| if (payload == "[DONE]") { | ||
| continue; | ||
| } | ||
| json event = json::parse(payload, nullptr, false); | ||
| if (!event.is_discarded()) { | ||
| on_data(event); | ||
| } | ||
| } | ||
| return true; | ||
| }; | ||
|
|
||
| httplib::Headers headers = {{"Accept", "text/event-stream"}}; | ||
| auto body_with_model = body; | ||
| if (!model.empty()) { | ||
| body_with_model["model"] = model; | ||
| } | ||
| auto res = cli.Post(join_path(parts, path), headers, body_with_model.dump(), "application/json", receiver); | ||
|
|
||
| if (!res) { | ||
| if (res.error() == httplib::Error::Canceled && should_stop()) { | ||
| return json(); // cancelled by the user | ||
| } | ||
| return json {{"error", {{"message", "failed to connect to " + server_base + ": " + httplib::to_string(res.error())}}}}; | ||
| } | ||
| if (res->status < 200 || res->status >= 300) { | ||
| json error_body = json::parse(raw_body, nullptr, false); | ||
| if (!error_body.is_discarded() && error_body.contains("error")) { | ||
| return error_body; | ||
| } | ||
| return json {{"error", {{"message", "request failed with status " + std::to_string(res->status)}}}}; | ||
| } | ||
| return json(); | ||
| } | ||
|
|
||
| bool cli_client::wait_health(const std::function<bool()> & is_aborted) { | ||
| int connect_attempts = 0; | ||
| while (!is_aborted()) { | ||
| auto [cli, parts] = common_http_client(server_base); | ||
| cli.set_connection_timeout(1, 0); | ||
| auto res = cli.Get(join_path(parts, "/health")); | ||
| if (res) { | ||
| if (res->status == 200) { | ||
| return true; | ||
| } | ||
| // any other status means the server is up but not ready yet | ||
| // (e.g. 503 while the model is still loading) | ||
| } else if (++connect_attempts >= 10) { | ||
| last_error = "failed to connect to " + server_base + ": " + httplib::to_string(res.error()); | ||
| return false; | ||
| } | ||
| std::this_thread::sleep_for(std::chrono::milliseconds(300)); | ||
| } | ||
| last_error = "aborted while waiting for the server to become ready"; | ||
| return false; | ||
| } | ||
|
|
||
| std::vector<std::string> cli_client::list_models() { | ||
| json resp = get("/v1/models"); | ||
| if (!resp.contains("data") || !resp.at("data").is_array()) { | ||
| throw std::runtime_error("invalid response from /v1/models"); | ||
| } | ||
| std::vector<std::string> models; | ||
| for (const auto & m : resp.at("data")) { | ||
| if (m.contains("id") && m.at("id").is_string()) { | ||
| models.push_back(m.at("id").get<std::string>()); | ||
| } | ||
| } | ||
| return models; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| #pragma once | ||
|
|
||
| #include "ggml.h" | ||
|
|
||
| #define JSON_ASSERT GGML_ASSERT | ||
| #include <nlohmann/json.hpp> | ||
|
|
||
| #include <functional> | ||
| #include <string> | ||
|
|
||
| using json = nlohmann::ordered_json; | ||
|
|
||
| // openai-like client for CLI | ||
| struct cli_client { | ||
| std::string server_base; // base url, for example "http://127.0.0.1:8080" | ||
| std::string last_error; // set when wait_health() fails | ||
|
|
||
| std::string model; // optional, set when the server has multiple models (router mode) | ||
|
|
||
| // simple GET request, returns the response json | ||
| // throws std::runtime_error on transport error or non-2xx status | ||
| json get(const std::string & path); | ||
|
|
||
| // simple POST request, returns the response json | ||
| // throws std::runtime_error on transport error or non-2xx status | ||
| json post(const std::string & path, const json & body); | ||
|
|
||
| // POST request with an SSE streaming response; on_data is invoked once | ||
| // per "data:" event; the function returns after the stream is finished: | ||
| // a null json on graceful exit (incl. cancellation via should_stop), | ||
| // the error response json otherwise | ||
| json post_sse(const std::string & path, | ||
| const json & body, | ||
| const std::function<bool()> & should_stop, | ||
| const std::function<void(const json &)> & on_data); | ||
|
|
||
| // poll /health until the server is ready to accept requests | ||
| // returns false if is_aborted returned true or the server is unreachable | ||
| bool wait_health(const std::function<bool()> & is_aborted); | ||
|
|
||
| // | ||
| // higher-level wrappers | ||
| // | ||
|
|
||
| json create_chat_completion(const json & request, | ||
| const std::function<bool()> & should_stop, | ||
| const std::function<void(const json &)> & on_data) { | ||
| return post_sse("/v1/chat/completions", request, should_stop, on_data); | ||
| } | ||
|
|
||
| json get_props() { | ||
| return get("/props"); | ||
| } | ||
|
|
||
| std::vector<std::string> list_models(); | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think the client needs to be coupled to json. It can return raw strings and let the cli context decode the json.