Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions include/ai/anthropic.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ Client create_client(const std::string& api_key,
const std::string& base_url,
const retry::RetryConfig& retry_config);

/// Create an Anthropic client that authenticates with a bearer token instead
/// of an API key. The token is sent as `Authorization: Bearer <token>`: this is
/// how the Anthropic API takes an OAuth access token (what the
/// `ANTHROPIC_AUTH_TOKEN` environment variable of the official SDKs holds), and
/// how an LLM gateway in front of it usually takes a token of its own. An API
/// key is not accepted this way: use `create_client` for it.
/// @param auth_token Bearer token; must not be empty (there is no fallback to
/// an environment variable)
/// @param base_url Custom base URL; the default one when empty
/// @return Configured Anthropic client
/// @throws ConfigurationError if the token is empty
Client create_client_with_auth_token(const std::string& auth_token,
const std::string& base_url = "");

/// Try to create an Anthropic client using environment variables
/// Reads API key from ANTHROPIC_API_KEY environment variable
/// @return Optional client - has value if environment variable is set, empty
Expand Down
26 changes: 21 additions & 5 deletions src/providers/anthropic/anthropic_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,42 @@ namespace anthropic {

AnthropicClient::AnthropicClient(const std::string& api_key,
const std::string& base_url)
: AnthropicClient(api_key, base_url, std::optional<retry::RetryConfig>{}) {}
: AnthropicClient(api_key,
base_url,
AuthScheme::kApiKey,
std::optional<retry::RetryConfig>{}) {}

AnthropicClient::AnthropicClient(const std::string& api_key,
const std::string& base_url,
const retry::RetryConfig& retry_config)
: AnthropicClient(api_key,
base_url,
AuthScheme::kApiKey,
std::optional<retry::RetryConfig>(retry_config)) {}

AnthropicClient::AnthropicClient(const std::string& api_key,
AnthropicClient::AnthropicClient(const std::string& credential,
const std::string& base_url,
AuthScheme auth_scheme)
: AnthropicClient(credential,
base_url,
auth_scheme,
std::optional<retry::RetryConfig>{}) {}

AnthropicClient::AnthropicClient(const std::string& credential,
const std::string& base_url,
AuthScheme auth_scheme,
std::optional<retry::RetryConfig> retry_config)
: BaseProviderClient(
providers::ProviderConfig{
.api_key = api_key,
.api_key = credential,
.base_url = base_url,
.completions_endpoint_path = "/v1/messages",
.embeddings_endpoint_path = "/v1/embeddings",
.auth_header_name = "x-api-key",
.auth_header_prefix = "",
.auth_header_name = auth_scheme == AuthScheme::kBearerToken
? "Authorization"
: "x-api-key",
.auth_header_prefix =
auth_scheme == AuthScheme::kBearerToken ? "Bearer " : "",
.extra_headers = {{"anthropic-version", "2023-06-01"}},
.retry_config = retry_config},
std::make_unique<AnthropicRequestBuilder>(),
Expand Down
23 changes: 22 additions & 1 deletion src/providers/anthropic/anthropic_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@
namespace ai {
namespace anthropic {

/// How the client presents its credential to the API.
enum class AuthScheme {
/// An API key, sent in the `x-api-key` header.
kApiKey,
/// A bearer token, sent as `Authorization: Bearer <token>`: an OAuth access
/// token of the Anthropic API, or the token of an LLM gateway.
kBearerToken,
};

class AnthropicClient : public providers::BaseProviderClient {
public:
explicit AnthropicClient(
Expand All @@ -21,6 +30,11 @@ class AnthropicClient : public providers::BaseProviderClient {
const std::string& base_url,
const retry::RetryConfig& retry_config);

/// `credential` is an API key or a bearer token, as `auth_scheme` says.
AnthropicClient(const std::string& credential,
const std::string& base_url,
AuthScheme auth_scheme);

// Override only what's specific to Anthropic
StreamResult stream_text(const StreamOptions& options) override;
std::string provider_name() const override;
Expand All @@ -32,10 +46,17 @@ class AnthropicClient : public providers::BaseProviderClient {
// Member access for testing
const std::string& get_api_key() const { return config_.api_key; }
const std::string& get_base_url() const { return config_.base_url; }
const std::string& get_auth_header_name() const {
return config_.auth_header_name;
}
const std::string& get_auth_header_prefix() const {
return config_.auth_header_prefix;
}

private:
AnthropicClient(const std::string& api_key,
AnthropicClient(const std::string& credential,
const std::string& base_url,
AuthScheme auth_scheme,
std::optional<retry::RetryConfig> retry_config);
};

Expand Down
9 changes: 9 additions & 0 deletions src/providers/anthropic/anthropic_factory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ Client create_client(const std::string& api_key,
retry_config));
}

Client create_client_with_auth_token(const std::string& auth_token,
const std::string& base_url) {
if (auth_token.empty()) {
throw ConfigurationError("The auth token of the Anthropic client is empty");
}
return Client(std::make_unique<AnthropicClient>(
auth_token, get_base_url_or_default(base_url), AuthScheme::kBearerToken));
}

std::optional<Client> try_create_client() {
auto api_key = utils::non_empty_env("ANTHROPIC_API_KEY");
if (!api_key) {
Expand Down
2 changes: 2 additions & 0 deletions src/providers/anthropic/anthropic_factory.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ namespace anthropic {
Client create_client();
Client create_client(const std::string& api_key);
Client create_client(const std::string& api_key, const std::string& base_url);
Client create_client_with_auth_token(const std::string& auth_token,
const std::string& base_url);

} // namespace anthropic
} // namespace ai
65 changes: 65 additions & 0 deletions tests/unit/anthropic_client_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

// Include the Anthropic client headers
#include "ai/anthropic.h"
#include "ai/errors.h"
#include "ai/types/generate_options.h"
#include "ai/types/stream_options.h"

Expand Down Expand Up @@ -90,6 +91,70 @@ TEST_F(AnthropicClientTest, ConstructorWithCustomRetryConfig) {
EXPECT_EQ(client.get_base_url(), "https://api.anthropic.com");
}

// Authentication Scheme Tests
TEST_F(AnthropicClientTest, ApiKeyIsSentInXApiKeyHeader) {
ai::anthropic::AnthropicClient client("sk-ant-test",
"https://api.anthropic.com");

EXPECT_EQ(client.get_auth_header_name(), "x-api-key");
EXPECT_EQ(client.get_auth_header_prefix(), "");

ai::anthropic::AnthropicClient explicit_client(
"sk-ant-test", "https://api.anthropic.com",
ai::anthropic::AuthScheme::kApiKey);

EXPECT_EQ(explicit_client.get_auth_header_name(), "x-api-key");
EXPECT_EQ(explicit_client.get_auth_header_prefix(), "");
}

TEST_F(AnthropicClientTest, AuthTokenIsSentAsBearer) {
ai::anthropic::AnthropicClient client(
"token-123", "https://api.anthropic.com",
ai::anthropic::AuthScheme::kBearerToken);

EXPECT_TRUE(client.is_valid());
EXPECT_EQ(client.get_api_key(), "token-123");
EXPECT_EQ(client.get_base_url(), "https://api.anthropic.com");
EXPECT_EQ(client.get_auth_header_name(), "Authorization");
EXPECT_EQ(client.get_auth_header_prefix(), "Bearer ");
}

TEST_F(AnthropicClientTest, BearerTokenHeadersKeepTheApiVersion) {
// The headers of a request are built from the configuration of the client:
// with a bearer token there is an `Authorization` header and no `x-api-key`.
providers::ProviderConfig config;
config.api_key = "token-123";
config.auth_header_name = "Authorization";
config.auth_header_prefix = "Bearer ";
config.extra_headers = {{"anthropic-version", "2023-06-01"}};

ai::anthropic::AnthropicRequestBuilder builder;
auto headers = builder.build_headers(config);

ASSERT_EQ(headers.count("Authorization"), 1U);
EXPECT_EQ(headers.find("Authorization")->second, "Bearer token-123");
EXPECT_EQ(headers.count("x-api-key"), 0U);
ASSERT_EQ(headers.count("anthropic-version"), 1U);
EXPECT_EQ(headers.find("anthropic-version")->second, "2023-06-01");
}

TEST_F(AnthropicClientTest, CreateClientWithAuthToken) {
auto client = ai::anthropic::create_client_with_auth_token(
"token-123", "http://localhost:8080");

EXPECT_TRUE(client.is_valid());
EXPECT_EQ(client.provider_name(), "anthropic");

auto default_url_client =
ai::anthropic::create_client_with_auth_token("token-123");
EXPECT_THAT(default_url_client.config_info(),
testing::HasSubstr("https://api.anthropic.com"));

// No fallback to an environment variable: an empty token is an error.
EXPECT_THROW(ai::anthropic::create_client_with_auth_token(""),
ai::ConfigurationError);
}

// Model Support Tests
TEST_F(AnthropicClientTest, SupportedModelsContainsExpectedModels) {
auto models = client_->supported_models();
Expand Down
Loading