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
4 changes: 4 additions & 0 deletions include/ai/ai.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
#include "google.h"
#endif

#ifdef AI_SDK_HAS_BEDROCK
#include "bedrock.h"
#endif

// Type definitions
#include "types/client.h"
#include "types/enums.h"
Expand Down
15 changes: 15 additions & 0 deletions include/ai/bedrock.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ struct SecurityConfig {
};

/// Configuration for Bedrock client
///
/// When none of `profile`, `role_arn` and `web_identity_token_file` is set
/// and the `AWS_BEARER_TOKEN_BEDROCK` environment variable has an API key of
/// Amazon Bedrock, the requests carry the key instead of a signature.
struct BedrockConfig {
/// AWS region (e.g., "us-east-1"). If empty, uses AWS_REGION env var.
std::string region;
Expand Down Expand Up @@ -107,6 +111,17 @@ struct BedrockConfig {

/// Security configuration
SecurityConfig security;

/// Whether the application initializes the AWS SDK for C++ itself: it has
/// called `Aws::InitAPI` before the provider is used, and it calls
/// `Aws::ShutdownAPI` after the last client of the provider is destroyed.
///
/// The provider does not call `Aws::InitAPI` then. The AWS SDK counts the
/// calls: a second `Aws::InitAPI` initializes nothing, and it makes the
/// `Aws::ShutdownAPI` of the application do nothing as well, so the threads
/// of the AWS SDK are still running when the static objects that they use
/// are destroyed at the exit of the process.
bool aws_sdk_initialized_by_application = false;
};

/// Create a Bedrock client with default configuration
Expand Down
3 changes: 3 additions & 0 deletions include/ai/types/client.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ class Client {
/// models endpoint (`GET /v1/models`). Makes a network request. Where the
/// provider says what a model is for (Gemini: `supportedGenerationMethods`),
/// the models that cannot be asked through this client are left out.
/// Bedrock lists the inference profiles of the Region whose models output
/// text, followed by the text models that are invoked on demand by their
/// own IDs.
virtual ModelListResult list_models() {
if (pimpl_)
return pimpl_->list_models();
Expand Down
13 changes: 12 additions & 1 deletion src/providers/bedrock/aws_sdk_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@
namespace ai {
namespace bedrock {

void ensure_aws_sdk_initialized() {
void ensure_aws_sdk_initialized(const BedrockConfig& config) {
if (config.aws_sdk_initialized_by_application) {
return;
}

static std::once_flag once;
std::call_once(once, [] {
// Intentionally leaked: see the comment in the header.
Expand All @@ -19,5 +23,12 @@ void ensure_aws_sdk_initialized() {
});
}

Aws::Client::ClientConfigurationInitValues
client_configuration_with_known_region() {
Aws::Client::ClientConfigurationInitValues init_values;
init_values.shouldDisableIMDS = true;
return init_values;
}

} // namespace bedrock
} // namespace ai
20 changes: 18 additions & 2 deletions src/providers/bedrock/aws_sdk_manager.h
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
#pragma once

#include "ai/bedrock.h"

#include <aws/core/client/ClientConfiguration.h>

namespace ai {
namespace bedrock {

/// Initializes the AWS SDK for C++ once per process.
/// Initializes the AWS SDK for C++ once per process, unless the application
/// does it (`BedrockConfig::aws_sdk_initialized_by_application`).
///
/// The SDK does not support `Aws::InitAPI` after `Aws::ShutdownAPI`, and
/// calling `Aws::ShutdownAPI` from a static destructor races with other static
/// objects (and with streams that may still be running on background
/// threads). So the SDK is initialized on first use and is never shut down:
/// its resources are released by the operating system at process exit.
void ensure_aws_sdk_initialized();
void ensure_aws_sdk_initialized(const BedrockConfig& config);

/// The initial values of a client configuration whose Region the caller sets.
///
/// The default constructor of the configuration asks the EC2 instance
/// metadata service for the Region when neither the environment nor the
/// profile names one: a network request, made every time a client is
/// created, for a value that is overwritten. This does not change where the
/// credentials are looked for: the credential chain is made separately, and
/// still uses the role of the instance.
Aws::Client::ClientConfigurationInitValues
client_configuration_with_known_region();

} // namespace bedrock
} // namespace ai
42 changes: 28 additions & 14 deletions src/providers/bedrock/bedrock_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <semaphore>

#include <aws/bedrock-runtime/BedrockRuntimeClient.h>
#include <aws/bedrock-runtime/BedrockRuntimeClientConfiguration.h>
#include <aws/bedrock-runtime/model/ConverseRequest.h>
#include <aws/core/client/ClientConfiguration.h>

Expand Down Expand Up @@ -79,7 +80,8 @@ struct BedrockClient::Impl {
profile = config.profile;
endpoint_override = config.endpoint_override;

Aws::Client::ClientConfiguration client_config;
Aws::Client::ClientConfiguration client_config(
client_configuration_with_known_region());
client_config.region = region;
client_config.connectTimeoutMs =
static_cast<long>(config.security.connection_timeout.count() * 1000);
Expand All @@ -90,16 +92,27 @@ struct BedrockClient::Impl {
client_config.endpointOverride = endpoint_override;
}

client = std::make_shared<Aws::BedrockRuntime::BedrockRuntimeClient>(
make_credentials_provider(config, region), client_config);
if (uses_bedrock_api_key(config)) {
SecureLogger::log_debug("Using the API key of Amazon Bedrock");
client = std::make_shared<Aws::BedrockRuntime::BedrockRuntimeClient>(
make_api_key_auth_schemes(
Aws::BedrockRuntime::BedrockRuntimeClient::GetServiceName(),
region),
nullptr,
Aws::BedrockRuntime::BedrockRuntimeClientConfiguration(
client_config));
} else {
client = std::make_shared<Aws::BedrockRuntime::BedrockRuntimeClient>(
make_credentials_provider(config, region), client_config);
}

valid = true;
SecureLogger::log_debug("Bedrock client initialized - region: " + region);
}
};

BedrockClient::BedrockClient(const BedrockConfig& config) {
ensure_aws_sdk_initialized();
ensure_aws_sdk_initialized(config);
pimpl_ = std::make_unique<Impl>(config);
SecureLogger::log_info("Bedrock client created for region: " +
pimpl_->region);
Expand Down Expand Up @@ -146,17 +159,19 @@ GenerateResult BedrockClient::generate_text_single_step(
if (!outcome.IsSuccess()) {
auto result =
pimpl_->response_parser.parse_converse_error(outcome.GetError());
SecureLogger::log_api_error("Converse", options.model, pimpl_->region,
outcome.GetError().GetExceptionName(),
outcome.GetError().GetMessage(),
result.is_retryable.value_or(false));
SecureLogger::log_api_error(
"Converse", options.model, pimpl_->region,
std::string(outcome.GetError().GetExceptionName()),
std::string(outcome.GetError().GetMessage()),
result.is_retryable.value_or(false));
return result;
}

auto result =
pimpl_->response_parser.parse_converse_response(outcome.GetResult());
SecureLogger::log_api_call("Converse", options.model, pimpl_->region,
outcome.GetResult().GetRequestId(), latency);
std::string(outcome.GetResult().GetRequestId()),
latency);

// Execute tools if the model made tool calls
if (result.has_tool_calls() && options.has_tools()) {
Expand Down Expand Up @@ -247,14 +262,13 @@ bool BedrockClient::supports_model(const std::string& model_name) const {
}

ModelListResult BedrockClient::list_models() {
// `ListFoundationModels` returns foundation model IDs of the Region;
// inference profile IDs (`global.anthropic...`) are not part of it.
// What Converse can be asked with on demand: the inference profiles
// (`global.anthropic...`) come first, because a current model is invoked
// through one and not by its own ID.
try {
ModelDiscovery discovery(pimpl_->config);
ModelListResult listed;
for (const auto& info : discovery.list_models()) {
listed.models.push_back(info.model_id);
}
listed.models = discovery.list_converse_model_ids();
return listed;
} catch (const std::exception& e) {
return ModelListResult("Failed to list Bedrock models: " +
Expand Down
43 changes: 41 additions & 2 deletions src/providers/bedrock/bedrock_credentials.cpp
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
#include "bedrock_credentials.h"

#include "ai/errors.h"
#include "aws_sdk_manager.h"
#include "secure_logger.h"

#include <chrono>
#include <cstdlib>
#include <mutex>

#include <aws/core/auth/AWSBearerToken.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/auth/STSCredentialsProvider.h>
#include <aws/core/auth/bearer-token-provider/StaticBearerTokenProvider.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/sts/STSClient.h>
#include <aws/sts/STSServiceClientModel.h>
Expand All @@ -22,6 +25,9 @@ namespace {
// Refresh assumed-role credentials this long before they expire
constexpr auto kCredentialsRefreshMargin = std::chrono::minutes(5);

// The environment variable with an API key of Amazon Bedrock
constexpr char kBedrockApiKeyVariable[] = "AWS_BEARER_TOKEN_BEDROCK";

/// Credentials of the source identity: the configured profile, or the
/// default credential chain (env vars, profile, IMDS, ...)
std::shared_ptr<Aws::Auth::AWSCredentialsProvider> make_source_provider(
Expand All @@ -43,7 +49,8 @@ class AssumeRoleCredentialsProvider : public Aws::Auth::AWSCredentialsProvider {
: role_arn_(config.role_arn),
role_session_name_(config.role_session_name),
external_id_(config.external_id) {
Aws::STS::STSClientConfiguration sts_config;
Aws::STS::STSClientConfiguration sts_config(
client_configuration_with_known_region());
sts_config.region = region;
sts_client_ = std::make_shared<Aws::STS::STSClient>(
make_source_provider(config), nullptr, sts_config);
Expand Down Expand Up @@ -88,7 +95,7 @@ class AssumeRoleCredentialsProvider : public Aws::Auth::AWSCredentialsProvider {
auto outcome = sts_client_->AssumeRole(request);
if (!outcome.IsSuccess()) {
throw ConfigurationError("Failed to assume role: " +
outcome.GetError().GetMessage());
std::string(outcome.GetError().GetMessage()));
}

const auto& credentials = outcome.GetResult().GetCredentials();
Expand Down Expand Up @@ -157,5 +164,37 @@ std::shared_ptr<Aws::Auth::AWSCredentialsProvider> make_credentials_provider(
return make_source_provider(config);
}

bool uses_bedrock_api_key(const BedrockConfig& config) {
if (!config.profile.empty() || !config.role_arn.empty() ||
!config.web_identity_token_file.empty()) {
return false;
}
const char* api_key = std::getenv(kBedrockApiKeyVariable);
return api_key != nullptr && *api_key != '\0';
}

BedrockAuthSchemes make_api_key_auth_schemes(const char* service_name,
const std::string& region) {
const char* api_key = std::getenv(kBedrockApiKeyVariable);
if (api_key == nullptr || *api_key == '\0') {
throw ConfigurationError(std::string(kBedrockApiKeyVariable) +
" is not set");
}

static const char kAllocationTag[] = "BedrockApiKey";
std::shared_ptr<Aws::Auth::AWSBearerTokenProviderBase> token_provider =
Aws::MakeShared<Aws::Auth::StaticAWSBearerTokenProvider>(
kAllocationTag, Aws::Auth::AWSBearerToken(Aws::String(api_key)));

BedrockAuthSchemes schemes;
schemes.emplace(
smithy::BearerTokenAuthSchemeOption::bearerTokenAuthSchemeOption.schemeId,
smithy::BearerTokenAuthScheme(
Aws::MakeShared<smithy::AwsBearerTokenIdentityResolver>(
kAllocationTag, token_provider),
service_name, Aws::String(region)));
return schemes;
}

} // namespace bedrock
} // namespace ai
30 changes: 30 additions & 0 deletions src/providers/bedrock/bedrock_credentials.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
#include <memory>
#include <string>

// The header of a client brings the auth scheme types: their own headers
// do not include what they need.
#include <aws/bedrock-runtime/BedrockRuntimeClient.h>
#include <aws/core/auth/AWSCredentialsProvider.h>

namespace ai {
Expand All @@ -23,5 +26,32 @@ std::shared_ptr<Aws::Auth::AWSCredentialsProvider> make_credentials_provider(
const BedrockConfig& config,
const std::string& region);

/// Whether the requests carry the API key of Amazon Bedrock instead of a
/// signature: the `AWS_BEARER_TOKEN_BEDROCK` environment variable has one,
/// and the configuration names no identity of its own (a profile, a role or
/// a web identity token).
bool uses_bedrock_api_key(const BedrockConfig& config);

/// The ways to authorize a request that a client of Bedrock is constructed
/// with: the type that its generated constructor takes.
using BedrockAuthSchemes = Aws::UnorderedMap<
Aws::String,
Aws::Crt::Variant<smithy::SigV4AuthScheme, smithy::BearerTokenAuthScheme>>;

/// The API key of the `AWS_BEARER_TOKEN_BEDROCK` environment variable, sent
/// as a bearer token, as the only way to authorize the requests of a client.
///
/// An AWS client that is constructed with a credentials provider signs with
/// it and has no other way to authorize a request. One that is constructed
/// from the configuration of the service alone knows the API key, but it
/// also makes the default credential chain of that configuration and looks
/// for a token of IAM Identity Center first. So the client is given the one
/// scheme it is to use.
/// @param service_name the signing name of the service (`GetServiceName` of
/// the client)
/// @throws ConfigurationError if the variable is not set
BedrockAuthSchemes make_api_key_auth_schemes(const char* service_name,
const std::string& region);

} // namespace bedrock
} // namespace ai
4 changes: 3 additions & 1 deletion src/providers/bedrock/bedrock_response_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ GenerateResult BedrockResponseParser::parse_converse_response(
continue;
}
const auto& tool_use = block.GetToolUse();
// `Aws::String` is not `std::string` when the AWS SDK is built with
// custom memory management: the conversion is explicit.
gen_result.tool_calls.emplace_back(
tool_use.GetToolUseId(), tool_use.GetName(),
std::string(tool_use.GetToolUseId()), std::string(tool_use.GetName()),
BedrockRequestMapper::from_document(tool_use.GetInput()));
ai::logger::log_debug("Parsed Bedrock tool call: {}", tool_use.GetName());
}
Expand Down
9 changes: 6 additions & 3 deletions src/providers/bedrock/bedrock_stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ void BedrockStreamImpl::on_content_block_start(
}
const auto& tool_use = event.GetStart().GetToolUse();
pending_tool_calls_[event.GetContentBlockIndex()] =
PendingToolCall{tool_use.GetToolUseId(), tool_use.GetName(), {}};
PendingToolCall{std::string(tool_use.GetToolUseId()),
std::string(tool_use.GetName()),
{}};
}

void BedrockStreamImpl::on_content_block_delta(
Expand Down Expand Up @@ -212,9 +214,10 @@ void BedrockStreamImpl::on_error(
ai::logger::log_error("Bedrock stream error: {} - {}",
error.GetExceptionName(), error.GetMessage());
if (!error.GetExceptionName().empty()) {
push_error(error.GetExceptionName() + ": " + error.GetMessage());
push_error(std::string(error.GetExceptionName()) + ": " +
std::string(error.GetMessage()));
} else {
push_error("Stream error: " + error.GetMessage());
push_error("Stream error: " + std::string(error.GetMessage()));
}
}

Expand Down
Loading