mirror of
https://github.com/lemonade-sdk/lemonade.git
synced 2026-11-23 08:49:28 -10:00
fix(cloud): address review feedback on the Anthropic wire-format relay
- Forward `anthropic-beta` / `anthropic-version` from the client, and reattach `?beta=true` to the upstream URL where the API reads it. - Start the upstream request before the handler returns so a non-200 is relayed as a real status instead of a 200 with an error body; httplib commits the status line only after the handler returns, so a chunked content provider cannot influence it. - Relay `retry-after`, `request-id` and `anthropic-ratelimit-*` back to the client, which requires capturing response headers in HttpClient. - Reject a registry entry with an empty checkpoint with an actionable 500, matching what CloudServer::load() does for the OpenAI endpoints. - Emit X-Lemonade-Warning on the relay path too, not just the converted one. - Document that /chat/completions against an anthropic-wire provider reports its 400 as an SSE error frame when stream is true.
This commit is contained in:
1 parent
af2eaa12ed
commit
efb47a5e4c
7 files changed
+431
-58
No files matched your search
@@ -3053,6 +3053,13 @@ if(BUILD_TESTING AND EXISTS "${_ANTHROPIC_ERROR_TEST_SRC}")
|
||||
add_cpp_ci_test(AnthropicErrorTest CI ON COMMAND test_anthropic_error)
|
||||
endif()
|
||||
|
||||
set(_ANTHROPIC_RELAY_HEADERS_TEST_SRC "${CMAKE_CURRENT_SOURCE_DIR}/test/cpp/test_anthropic_relay_headers.cpp")
|
||||
if(BUILD_TESTING AND EXISTS "${_ANTHROPIC_RELAY_HEADERS_TEST_SRC}")
|
||||
add_executable(test_anthropic_relay_headers test/cpp/test_anthropic_relay_headers.cpp)
|
||||
target_link_libraries(test_anthropic_relay_headers PRIVATE lemonade-server-core)
|
||||
add_cpp_ci_test(AnthropicRelayHeadersTest CI ON COMMAND test_anthropic_relay_headers)
|
||||
endif()
|
||||
|
||||
set(_ORIGIN_UTILS_TEST_SRC "${CMAKE_CURRENT_SOURCE_DIR}/test/cpp/test_origin_utils.cpp")
|
||||
if(BUILD_TESTING AND EXISTS "${_ORIGIN_UTILS_TEST_SRC}")
|
||||
add_executable(test_origin_utils test/cpp/test_origin_utils.cpp)
|
||||
|
||||
@@ -75,12 +75,12 @@ lemonade cloud install acme \
|
||||
|
||||
The wire format and the auth header are independent settings, but usually go together: the Anthropic API authenticates with `x-api-key`, so leaving the header at its default returns `401`. Omit the auth flags only for a gateway that fronts the Anthropic format behind bearer auth.
|
||||
|
||||
Every request to an `anthropic` provider, discovery included, carries `anthropic-version: 2023-06-01`.
|
||||
Every request to an `anthropic` provider, discovery included, carries `anthropic-version: 2023-06-01` unless the client sends its own. `anthropic-beta` is forwarded from the client, so SDK feature opt-ins reach the provider.
|
||||
|
||||
Discovery is unchanged — `GET <base_url>/models`, which these providers serve in the OpenAI envelope. Inference differs:
|
||||
|
||||
- **`POST /v1/messages`** relays to `<base_url>/messages` byte-for-byte, rewriting only the `model` field. Nothing is converted, so thinking blocks, tool use, cache control, and future Anthropic fields pass through intact. Streaming relays the upstream SSE unmodified.
|
||||
- **`POST /v1/chat/completions` and `POST /v1/completions`** return `400` pointing at `/v1/messages`, since the provider does not serve the OpenAI shape.
|
||||
- **`POST /v1/messages`** relays to `<base_url>/messages` byte-for-byte, rewriting only the `model` field. Nothing is converted, so thinking blocks, tool use, cache control, and future Anthropic fields pass through intact. Streaming relays the upstream SSE unmodified, and the upstream status code is preserved on both the streaming and non-streaming paths. `retry-after`, `request-id`, and `anthropic-ratelimit-*` response headers are relayed back.
|
||||
- **`POST /v1/chat/completions` and `POST /v1/completions`** are refused, since the provider does not serve the OpenAI shape. A non-streaming request gets `400` pointing at `/v1/messages`; a `stream: true` request gets the same message as an SSE error frame on a `200`, because the response has already begun by the time the body is written.
|
||||
|
||||
Relayed requests take no router slot — there is no local model to load — so they do not appear in `/v1/stats`.
|
||||
|
||||
@@ -151,7 +151,7 @@ A common admin pattern: set `LEMONADE_FIREWORKS_API_KEY` in the systemd / Docker
|
||||
| `POST /v1/cloud/auth` returns 409 | Env var is set for that provider. Unset it or use the env-var value going forward. |
|
||||
| Chat returns "No API key for cloud provider X" | Same as above — check `LEMONADE_<PROVIDER>_API_KEY` is exported in `lemond`'s environment, not your shell. |
|
||||
| Cloud model missing from `/v1/models` | Provider doesn't expose it as chat-capable, or discovery failed. Check `lemond` logs for warnings from the `Cloud` component. |
|
||||
| Chat completions returns "speaks the 'anthropic' wire format" | The provider was installed with `--wire-format anthropic`; send the request to `POST /v1/messages` instead. |
|
||||
| Chat completions returns "speaks the 'anthropic' wire format" | The provider was installed with `--wire-format anthropic`; send the request to `POST /v1/messages` instead. With `stream: true` this arrives as an SSE error frame on a `200`, not a `400`. |
|
||||
| An `anthropic` provider 401s with a valid key | It likely expects `x-api-key` rather than the default `Authorization: Bearer `. Re-install with `--auth-header-name x-api-key --auth-header-prefix ""`. |
|
||||
|
||||
For a structured view of every installed provider's auth state and discovered model count, hit `GET /v1/system-info` — the `cloud.providers[]` block reports `env_var_set`, `runtime_key_set`, and `models_discovered` per provider.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace lemon {
|
||||
namespace anthropic {
|
||||
|
||||
// Header allowlists for the /v1/messages relay to a provider registered with
|
||||
// --wire-format anthropic. The relay rebuilds the request envelope rather than
|
||||
// copying it, so anything a client or provider needs to survive the hop has to
|
||||
// be named here. Both predicates take an already-lowercased name.
|
||||
|
||||
// `anthropic-beta` is the consequential one: the SDK and Claude Code send it to
|
||||
// opt into features such as a 1M-token context window, and dropping it changes
|
||||
// what upstream accepts. `anthropic-version` is forwarded so a client pinning a
|
||||
// version wins over the default. Auth, hop-by-hop, Host, and Content-Length are
|
||||
// excluded because the relay sets its own.
|
||||
inline bool is_forwardable_request_header(const std::string& lower_name) {
|
||||
return lower_name == "anthropic-beta" || lower_name == "anthropic-version";
|
||||
}
|
||||
|
||||
// Without these an SDK cannot honor the provider's rate-limit window, and a bad
|
||||
// response cannot be escalated to the provider by id.
|
||||
inline bool is_forwardable_response_header(const std::string& lower_name) {
|
||||
return lower_name == "retry-after" || lower_name == "request-id" ||
|
||||
lower_name.rfind("anthropic-ratelimit-", 0) == 0;
|
||||
}
|
||||
|
||||
} // namespace anthropic
|
||||
} // namespace lemon
|
||||
@@ -16,6 +16,8 @@ namespace utils {
|
||||
struct HttpResponse {
|
||||
int status_code = 0;
|
||||
std::string body;
|
||||
// Response headers, names lowercased. Populated by post(); other verbs
|
||||
// leave this empty.
|
||||
std::map<std::string, std::string> headers;
|
||||
|
||||
// Transport status from libcurl. For non-streaming callers this remains
|
||||
@@ -128,6 +130,10 @@ public:
|
||||
// on_status fires once, before the first chunk is delivered, so callers can
|
||||
// divert an error body instead of forwarding it as payload bytes. Redirects
|
||||
// are never followed.
|
||||
//
|
||||
// out_response_headers, when non-null, is filled with the response headers
|
||||
// (names lowercased) before on_status fires, so a caller deciding what to
|
||||
// send downstream can see them without waiting for the transfer to finish.
|
||||
static HttpResponse post_stream(
|
||||
const std::string& url,
|
||||
const std::string& body,
|
||||
@@ -136,7 +142,8 @@ public:
|
||||
long timeout_seconds = 300,
|
||||
std::function<void(int status_code)> on_status = nullptr,
|
||||
HttpSecurityPolicy policy = HttpSecurityPolicy::ExternalHttpsOnly,
|
||||
std::function<bool()> should_cancel = nullptr);
|
||||
std::function<bool()> should_cancel = nullptr,
|
||||
std::map<std::string, std::string>* out_response_headers = nullptr);
|
||||
|
||||
// Download file to disk with automatic retry and resume support
|
||||
static DownloadResult download_file(const std::string& url,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "lemon/anthropic_error.h"
|
||||
#include "lemon/anthropic_relay_headers.h"
|
||||
#include "lemon/backends/cloud/cloud_server.h"
|
||||
#include "lemon/cloud_provider_registry.h"
|
||||
#include "lemon/error_types.h"
|
||||
@@ -8,8 +9,13 @@
|
||||
#include <sstream>
|
||||
#include <chrono>
|
||||
#include <algorithm>
|
||||
#include <condition_variable>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
@@ -211,9 +217,13 @@ static void set_anthropic_error_response(httplib::Response& res, int status,
|
||||
"application/json");
|
||||
}
|
||||
|
||||
using anthropic::is_forwardable_request_header;
|
||||
using anthropic::is_forwardable_response_header;
|
||||
|
||||
static AnthropicUpstreamMatch resolve_anthropic_upstream(ModelManager* model_manager,
|
||||
const std::string& model,
|
||||
const json& request_json) {
|
||||
const json& request_json,
|
||||
const httplib::Request& req) {
|
||||
AnthropicUpstreamMatch match;
|
||||
if (model_manager == nullptr) return match;
|
||||
CloudProviderRegistry* registry = model_manager->cloud_registry();
|
||||
@@ -255,6 +265,14 @@ static AnthropicUpstreamMatch resolve_anthropic_upstream(ModelManager* model_man
|
||||
"--allow-insecure-http to send the API key in plaintext");
|
||||
}
|
||||
|
||||
// CloudServer::load() rejects this for the OpenAI-shaped endpoints; without
|
||||
// the same check here a hand-authored registry entry would relay an empty
|
||||
// model id and surface an opaque provider 400 instead.
|
||||
if (info.checkpoint().empty()) {
|
||||
return fail(500, "cloud model '" + model + "' is missing the 'checkpoint' "
|
||||
"field (provider's upstream model id)");
|
||||
}
|
||||
|
||||
// The body passes through byte-for-byte apart from "model", which must name
|
||||
// the provider's own id rather than lemonade's "<provider>.<id>" public one.
|
||||
json forwarded = request_json;
|
||||
@@ -263,15 +281,69 @@ static AnthropicUpstreamMatch resolve_anthropic_upstream(ModelManager* model_man
|
||||
const auto auth_header = registry->auth_header_for(info.cloud_provider);
|
||||
AnthropicUpstream upstream;
|
||||
upstream.url = backends::CloudServer::upstream_url(base_url, "/messages");
|
||||
// The Anthropic API reads `beta` from the query string, so it has to be
|
||||
// reattached to the upstream URL rather than folded into a header.
|
||||
if (req.has_param("beta") && req.get_param_value("beta") == "true") {
|
||||
upstream.url += "?beta=true";
|
||||
}
|
||||
upstream.headers = backends::CloudServer::upstream_headers(auth_header, api_key,
|
||||
"anthropic");
|
||||
upstream.headers["Content-Type"] = "application/json";
|
||||
// The first client value replaces whatever default upstream_headers() set;
|
||||
// a repeat of the same name is joined, since a client may send
|
||||
// anthropic-beta as several headers rather than one comma-separated value.
|
||||
std::set<std::string> from_client;
|
||||
for (const auto& [name, value] : req.headers) {
|
||||
std::string lower = name;
|
||||
for (auto& c : lower) c = std::tolower(static_cast<unsigned char>(c));
|
||||
if (!is_forwardable_request_header(lower)) continue;
|
||||
if (from_client.insert(lower).second) {
|
||||
upstream.headers[lower] = value;
|
||||
} else {
|
||||
upstream.headers[lower] += "," + value;
|
||||
}
|
||||
}
|
||||
upstream.policy = backends::CloudServer::discovery_policy(base_url, allow_insecure_http);
|
||||
upstream.body = forwarded.dump();
|
||||
match.upstream = std::move(upstream);
|
||||
return match;
|
||||
}
|
||||
|
||||
static void relay_response_headers(const std::map<std::string, std::string>& upstream,
|
||||
httplib::Response& res) {
|
||||
for (const auto& [name, value] : upstream) {
|
||||
if (is_forwardable_response_header(name)) {
|
||||
res.set_header(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handoff between the thread running the upstream request and the thread
|
||||
// httplib runs the response body on. The upstream status has to be known
|
||||
// before the handler returns, because that is when httplib commits the status
|
||||
// line — so the request starts here rather than inside the content provider.
|
||||
struct AnthropicRelayStream {
|
||||
std::mutex mutex;
|
||||
std::condition_variable cv;
|
||||
|
||||
bool status_known = false;
|
||||
int status = 0;
|
||||
std::map<std::string, std::string> headers;
|
||||
|
||||
std::string pending; // 200: body bytes awaiting the client
|
||||
std::string error_body; // non-200: buffered for a one-shot response
|
||||
bool upstream_done = false;
|
||||
bool client_gone = false;
|
||||
std::string transport_error;
|
||||
bool ended_early = false;
|
||||
|
||||
// Bounds how far the upstream read can run ahead of a slow client. Large
|
||||
// enough that a normal SSE frame never blocks, small enough that a stalled
|
||||
// client cannot make the relay buffer a whole response.
|
||||
static constexpr size_t max_pending = 1 * 1024 * 1024;
|
||||
static constexpr size_t max_error_body = 64 * 1024;
|
||||
};
|
||||
|
||||
static void forward_anthropic_upstream(AnthropicUpstream upstream,
|
||||
bool stream,
|
||||
const std::string& model,
|
||||
@@ -281,6 +353,7 @@ static void forward_anthropic_upstream(AnthropicUpstream upstream,
|
||||
auto response = utils::HttpClient::post(
|
||||
upstream.url, upstream.body, upstream.headers, 0, upstream.policy);
|
||||
res.status = response.status_code;
|
||||
relay_response_headers(response.headers, res);
|
||||
res.set_content(response.body, "application/json");
|
||||
} catch (const std::exception& e) {
|
||||
set_anthropic_error_response(
|
||||
@@ -289,58 +362,160 @@ static void forward_anthropic_upstream(AnthropicUpstream upstream,
|
||||
return;
|
||||
}
|
||||
|
||||
auto state = std::make_shared<AnthropicRelayStream>();
|
||||
|
||||
std::thread([state, upstream = std::move(upstream)]() {
|
||||
std::map<std::string, std::string> response_headers;
|
||||
// curl delivers every header before the first body byte, so the map is
|
||||
// complete by the time either publisher below runs.
|
||||
auto publish_status = [&](int status) {
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
if (state->status_known) return;
|
||||
state->status = status;
|
||||
state->headers = response_headers;
|
||||
state->status_known = true;
|
||||
state->cv.notify_all();
|
||||
};
|
||||
|
||||
try {
|
||||
auto result = utils::HttpClient::post_stream(
|
||||
upstream.url, upstream.body,
|
||||
[&](const char* data, size_t length) {
|
||||
std::unique_lock<std::mutex> lock(state->mutex);
|
||||
if (state->status_known && state->status != 200) {
|
||||
if (state->error_body.size() < state->max_error_body) {
|
||||
state->error_body.append(
|
||||
data, std::min(length, state->max_error_body -
|
||||
state->error_body.size()));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
state->cv.wait(lock, [&] {
|
||||
return state->client_gone ||
|
||||
state->pending.size() < state->max_pending;
|
||||
});
|
||||
if (state->client_gone) return false;
|
||||
state->pending.append(data, length);
|
||||
state->cv.notify_all();
|
||||
return true;
|
||||
},
|
||||
upstream.headers, 0, publish_status, upstream.policy,
|
||||
[state]() {
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
return state->client_gone;
|
||||
},
|
||||
&response_headers);
|
||||
|
||||
// on_status never fires when the body is empty, so fall back to the
|
||||
// code curl always records after the transfer.
|
||||
publish_status(result.status_code);
|
||||
if (result.curl_code != 0) {
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
if (!state->client_gone) {
|
||||
state->ended_early = true;
|
||||
state->transport_error = result.curl_error;
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
state->transport_error = e.what();
|
||||
}
|
||||
publish_status(0);
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
state->upstream_done = true;
|
||||
state->cv.notify_all();
|
||||
}).detach();
|
||||
|
||||
std::unique_lock<std::mutex> lock(state->mutex);
|
||||
state->cv.wait(lock, [&] { return state->status_known || state->upstream_done; });
|
||||
const int status = state->status;
|
||||
|
||||
// A non-200 body is not SSE. Relaying it as a one-shot response keeps the
|
||||
// real status on the wire, which an SDK gating on the status code needs.
|
||||
if (status != 200) {
|
||||
state->cv.wait(lock, [&] { return state->upstream_done; });
|
||||
const std::string error_body = state->error_body;
|
||||
const std::string transport_error = state->transport_error;
|
||||
auto headers = state->headers;
|
||||
lock.unlock();
|
||||
|
||||
if (status == 0) {
|
||||
set_anthropic_error_response(
|
||||
res, 502, "cloud request for '" + model + "' failed: " + transport_error);
|
||||
return;
|
||||
}
|
||||
res.status = status;
|
||||
relay_response_headers(headers, res);
|
||||
// Providers report errors as JSON in the Anthropic error envelope, so
|
||||
// the body relays unchanged when there is one to relay.
|
||||
if (!error_body.empty()) {
|
||||
res.set_content(error_body, "application/json");
|
||||
} else {
|
||||
res.set_content(
|
||||
anthropic::build_anthropic_error(
|
||||
json{{"message", "cloud request for '" + model +
|
||||
"' failed with status " + std::to_string(status)}},
|
||||
status).dump(),
|
||||
"application/json");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
relay_response_headers(state->headers, res);
|
||||
lock.unlock();
|
||||
|
||||
res.set_header("Cache-Control", "no-cache");
|
||||
res.set_header("Connection", "keep-alive");
|
||||
res.set_header("X-Accel-Buffering", "no");
|
||||
res.set_chunked_content_provider(
|
||||
"text/event-stream",
|
||||
[upstream = std::move(upstream), model](size_t offset, httplib::DataSink& sink) {
|
||||
[state, model](size_t offset, httplib::DataSink& sink) {
|
||||
if (offset > 0) return false;
|
||||
// Both ends speak Anthropic SSE, so a 200 relays unparsed. A
|
||||
// non-200 body is not SSE, so it is diverted and re-emitted as an
|
||||
// error event rather than written into the event stream.
|
||||
static constexpr size_t max_error_body = 64 * 1024;
|
||||
int upstream_status = 200;
|
||||
std::string error_body;
|
||||
auto emit_error = [&sink, &model](int status, const std::string& message) {
|
||||
write_sse_event(sink, "error", anthropic::build_anthropic_error(
|
||||
json{{"message", "cloud request for '" + model + "' " + message}},
|
||||
status));
|
||||
};
|
||||
// Both ends speak Anthropic SSE, so the body relays unparsed.
|
||||
for (;;) {
|
||||
std::unique_lock<std::mutex> lock(state->mutex);
|
||||
state->cv.wait(lock, [&] {
|
||||
return !state->pending.empty() || state->upstream_done;
|
||||
});
|
||||
std::string chunk;
|
||||
chunk.swap(state->pending);
|
||||
const bool done = state->upstream_done;
|
||||
const bool ended_early = state->ended_early;
|
||||
const std::string transport_error = state->transport_error;
|
||||
state->cv.notify_all();
|
||||
lock.unlock();
|
||||
|
||||
try {
|
||||
auto result = utils::HttpClient::post_stream(
|
||||
upstream.url, upstream.body,
|
||||
[&](const char* data, size_t length) {
|
||||
if (upstream_status != 200) {
|
||||
if (error_body.size() < max_error_body) {
|
||||
error_body.append(
|
||||
data,
|
||||
std::min(length, max_error_body - error_body.size()));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return sink.write(data, length);
|
||||
},
|
||||
upstream.headers, 0,
|
||||
[&upstream_status](int status) { upstream_status = status; },
|
||||
upstream.policy,
|
||||
[&sink]() { return sink.is_writable && !sink.is_writable(); });
|
||||
// on_status never fires when the body is empty, so fall back to
|
||||
// the code curl always records after the transfer.
|
||||
const int status =
|
||||
upstream_status != 200 ? upstream_status : result.status_code;
|
||||
if (status != 200) {
|
||||
emit_error(status, "failed with status " + std::to_string(status) +
|
||||
(error_body.empty() ? "" : ": " + error_body));
|
||||
} else if (result.curl_code != 0 && sink.is_writable && sink.is_writable()) {
|
||||
emit_error(502, "stream ended early: " + result.curl_error);
|
||||
if (!chunk.empty() && !sink.write(chunk.data(), chunk.size())) {
|
||||
std::lock_guard<std::mutex> gone(state->mutex);
|
||||
state->client_gone = true;
|
||||
state->cv.notify_all();
|
||||
break;
|
||||
}
|
||||
if (done) {
|
||||
// Upstream committed a 200 and then broke off, so the
|
||||
// status cannot be corrected — report it in-band instead.
|
||||
if (ended_early) {
|
||||
write_sse_event(sink, "error", anthropic::build_anthropic_error(
|
||||
json{{"message", "cloud request for '" + model +
|
||||
"' stream ended early: " + transport_error}},
|
||||
502));
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
emit_error(502, std::string("failed: ") + e.what());
|
||||
}
|
||||
sink.done();
|
||||
return false;
|
||||
},
|
||||
// Runs even when the provider never does — a client that disappears
|
||||
// before the response starts would otherwise leave the upstream thread
|
||||
// parked on the pending-buffer wait with the connection still open.
|
||||
[state](bool) {
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
state->client_gone = true;
|
||||
state->cv.notify_all();
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1106,10 +1281,23 @@ void OllamaApi::handle_anthropic_messages(const httplib::Request& req, httplib::
|
||||
}
|
||||
}
|
||||
|
||||
auto emit_warning_header = [&res, &warnings]() {
|
||||
if (warnings.empty()) return;
|
||||
std::ostringstream warning_header;
|
||||
for (size_t i = 0; i < warnings.size(); ++i) {
|
||||
if (i > 0) warning_header << " | ";
|
||||
warning_header << warnings[i];
|
||||
}
|
||||
res.set_header("X-Lemonade-Warning", warning_header.str());
|
||||
std::cerr << "[OllamaApi] Anthropic compatibility warnings: "
|
||||
<< warning_header.str() << std::endl;
|
||||
};
|
||||
|
||||
// Relaying verbatim keeps thinking blocks, tool use, and cache control
|
||||
// intact. No router slot is taken — there is no local resource to hold.
|
||||
auto match = resolve_anthropic_upstream(model_manager_, model, request_json);
|
||||
auto match = resolve_anthropic_upstream(model_manager_, model, request_json, req);
|
||||
if (match.claimed) {
|
||||
emit_warning_header();
|
||||
if (!match.upstream) {
|
||||
set_anthropic_error_response(res, match.error_status,
|
||||
match.error_message);
|
||||
@@ -1141,15 +1329,7 @@ void OllamaApi::handle_anthropic_messages(const httplib::Request& req, httplib::
|
||||
}
|
||||
|
||||
bool stream = openai_req.value("stream", false);
|
||||
if (!warnings.empty()) {
|
||||
std::ostringstream warning_header;
|
||||
for (size_t i = 0; i < warnings.size(); ++i) {
|
||||
if (i > 0) warning_header << " | ";
|
||||
warning_header << warnings[i];
|
||||
}
|
||||
res.set_header("X-Lemonade-Warning", warning_header.str());
|
||||
std::cerr << "[OllamaApi] Anthropic compatibility warnings: " << warning_header.str() << std::endl;
|
||||
}
|
||||
emit_warning_header();
|
||||
|
||||
if (stream) {
|
||||
openai_req["stream"] = true;
|
||||
|
||||
@@ -248,6 +248,40 @@ static size_t write_callback(void* contents, size_t size, size_t nmemb, void* us
|
||||
return total_size;
|
||||
}
|
||||
|
||||
// Collects response headers into HttpResponse::headers, lowercasing names so
|
||||
// lookups do not depend on the casing a given provider happens to send.
|
||||
static size_t response_header_callback(char* buffer, size_t size, size_t nitems,
|
||||
void* userdata) {
|
||||
const size_t total = size * nitems;
|
||||
auto* headers = static_cast<std::map<std::string, std::string>*>(userdata);
|
||||
if (!headers) {
|
||||
return total;
|
||||
}
|
||||
|
||||
std::string line(buffer, total);
|
||||
const size_t colon = line.find(':');
|
||||
if (colon == std::string::npos) {
|
||||
// Status line, or the blank line ending a header block. A redirect or
|
||||
// an informational 1xx starts a fresh block, so drop what came before.
|
||||
if (line.rfind("HTTP/", 0) == 0) {
|
||||
headers->clear();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
std::string name = line.substr(0, colon);
|
||||
for (auto& c : name) c = std::tolower(static_cast<unsigned char>(c));
|
||||
|
||||
std::string value = line.substr(colon + 1);
|
||||
const size_t first = value.find_first_not_of(" \t");
|
||||
const size_t last = value.find_last_not_of(" \t\r\n");
|
||||
value = (first == std::string::npos) ? std::string()
|
||||
: value.substr(first, last - first + 1);
|
||||
|
||||
(*headers)[name] = value;
|
||||
return total;
|
||||
}
|
||||
|
||||
// Callback for writing to file
|
||||
static size_t write_file_callback(void* ptr, size_t size, size_t nmemb, void* stream) {
|
||||
size_t written = fwrite(ptr, size, nmemb, static_cast<FILE*>(stream));
|
||||
@@ -515,6 +549,8 @@ HttpResponse HttpClient::post(const std::string& url,
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(body.size()));
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_body);
|
||||
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, response_header_callback);
|
||||
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &response.headers);
|
||||
if (!apply_http_security_policy(curl, policy, false)) {
|
||||
curl_easy_cleanup(curl);
|
||||
throw std::runtime_error("Failed to apply HTTP security policy");
|
||||
@@ -675,7 +711,8 @@ HttpResponse HttpClient::post_stream(const std::string& url,
|
||||
long timeout_seconds,
|
||||
std::function<void(int)> on_status,
|
||||
HttpSecurityPolicy policy,
|
||||
std::function<bool()> should_cancel) {
|
||||
std::function<bool()> should_cancel,
|
||||
std::map<std::string, std::string>* out_response_headers) {
|
||||
CURL* curl = curl_easy_init();
|
||||
if (!curl) {
|
||||
throw std::runtime_error("Failed to initialize CURL");
|
||||
@@ -695,6 +732,10 @@ HttpResponse HttpClient::post_stream(const std::string& url,
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(body.size()));
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, stream_write_callback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &callback_data);
|
||||
if (out_response_headers) {
|
||||
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, response_header_callback);
|
||||
curl_easy_setopt(curl, CURLOPT_HEADERDATA, out_response_headers);
|
||||
}
|
||||
if (!apply_http_security_policy(curl, policy, false)) {
|
||||
curl_easy_cleanup(curl);
|
||||
throw std::runtime_error("Failed to apply HTTP security policy");
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// Unit tests for the /v1/messages relay header allowlists.
|
||||
//
|
||||
// The relay rebuilds the request envelope rather than copying it, so these
|
||||
// predicates are the only thing keeping a client's feature opt-in — or a
|
||||
// provider's rate-limit window — from being silently dropped on the hop. The
|
||||
// exclusions matter as much as the inclusions: forwarding a client's
|
||||
// Authorization or the upstream Content-Length would break the relay outright.
|
||||
//
|
||||
// Checks use an explicit pass/fail counter (not assert()) so the test stays
|
||||
// effective under the Release build the CI `default` preset uses, where
|
||||
// -DNDEBUG would compile assert() to a no-op.
|
||||
|
||||
#include "lemon/anthropic_relay_headers.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
using lemon::anthropic::is_forwardable_request_header;
|
||||
using lemon::anthropic::is_forwardable_response_header;
|
||||
|
||||
struct TestResult {
|
||||
int passed = 0;
|
||||
int failed = 0;
|
||||
|
||||
void check(bool condition, const std::string& name) {
|
||||
printf("[%s] %s\n", condition ? "PASS" : "FAIL", name.c_str());
|
||||
if (condition) {
|
||||
++passed;
|
||||
} else {
|
||||
++failed;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static void test_request_headers(TestResult& r) {
|
||||
r.check(is_forwardable_request_header("anthropic-beta"),
|
||||
"anthropic-beta forwarded (SDK feature opt-ins)");
|
||||
r.check(is_forwardable_request_header("anthropic-version"),
|
||||
"anthropic-version forwarded (client pin beats the default)");
|
||||
|
||||
// The relay sets its own auth from the provider's configured header; a
|
||||
// client value must never reach upstream.
|
||||
r.check(!is_forwardable_request_header("authorization"),
|
||||
"authorization not forwarded");
|
||||
r.check(!is_forwardable_request_header("x-api-key"),
|
||||
"x-api-key not forwarded");
|
||||
|
||||
// The body is re-serialized after the model rewrite, so a copied
|
||||
// Content-Length would describe the wrong body.
|
||||
r.check(!is_forwardable_request_header("content-length"),
|
||||
"content-length not forwarded");
|
||||
r.check(!is_forwardable_request_header("host"), "host not forwarded");
|
||||
r.check(!is_forwardable_request_header("connection"),
|
||||
"hop-by-hop connection not forwarded");
|
||||
r.check(!is_forwardable_request_header("content-type"),
|
||||
"content-type not forwarded (relay sets application/json)");
|
||||
|
||||
// The predicate takes an already-lowercased name; a caller that forgets to
|
||||
// normalize should miss rather than match by accident.
|
||||
r.check(!is_forwardable_request_header("Anthropic-Beta"),
|
||||
"match is exact on the lowercased name");
|
||||
r.check(!is_forwardable_request_header("anthropic-beta-extra"),
|
||||
"no prefix match on request names");
|
||||
r.check(!is_forwardable_request_header(""), "empty name not forwarded");
|
||||
}
|
||||
|
||||
static void test_response_headers(TestResult& r) {
|
||||
r.check(is_forwardable_response_header("retry-after"),
|
||||
"retry-after relayed (SDK backoff)");
|
||||
r.check(is_forwardable_response_header("request-id"),
|
||||
"request-id relayed (escalation to the provider)");
|
||||
|
||||
// Prefix match: the family is open-ended, so naming each member would rot.
|
||||
r.check(is_forwardable_response_header("anthropic-ratelimit-requests-reset"),
|
||||
"anthropic-ratelimit-requests-reset relayed");
|
||||
r.check(is_forwardable_response_header("anthropic-ratelimit-tokens-remaining"),
|
||||
"anthropic-ratelimit-tokens-remaining relayed");
|
||||
r.check(is_forwardable_response_header("anthropic-ratelimit-"),
|
||||
"bare anthropic-ratelimit- prefix matches");
|
||||
|
||||
r.check(!is_forwardable_response_header("anthropic-ratelimi"),
|
||||
"partial prefix does not match");
|
||||
r.check(!is_forwardable_response_header("x-anthropic-ratelimit-requests-reset"),
|
||||
"prefix is anchored at the start of the name");
|
||||
|
||||
// Relaying these would conflict with what httplib writes for the chunked
|
||||
// SSE response the relay actually sends.
|
||||
r.check(!is_forwardable_response_header("content-length"),
|
||||
"content-length not relayed");
|
||||
r.check(!is_forwardable_response_header("transfer-encoding"),
|
||||
"transfer-encoding not relayed");
|
||||
r.check(!is_forwardable_response_header("content-type"),
|
||||
"content-type not relayed");
|
||||
r.check(!is_forwardable_response_header("set-cookie"),
|
||||
"set-cookie not relayed");
|
||||
r.check(!is_forwardable_response_header(""), "empty name not relayed");
|
||||
}
|
||||
|
||||
int main() {
|
||||
TestResult r;
|
||||
printf("=== Anthropic Relay Header Allowlist Unit Tests ===\n\n");
|
||||
|
||||
test_request_headers(r);
|
||||
test_response_headers(r);
|
||||
|
||||
printf("\n%d/%d tests passed\n", r.passed, r.passed + r.failed);
|
||||
return r.failed == 0 ? 0 : 1;
|
||||
}
|
||||
Reference in new issue
Block a user