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
8 changes: 7 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ configure_ai_component(ai-sdk-cpp-langfuse)

# Bedrock provider (optional, requires AWS SDK)
if(AI_SDK_ENABLE_BEDROCK)
find_package(AWSSDK REQUIRED COMPONENTS core bedrock-runtime bedrock sts)
# Only the core of the AWS SDK sends the requests. Of `bedrock-runtime` and
# `bedrock` the provider uses the endpoint rules alone.
find_package(AWSSDK REQUIRED COMPONENTS core bedrock-runtime bedrock)

add_library(ai-sdk-cpp-bedrock)
set_target_properties(ai-sdk-cpp-bedrock PROPERTIES EXPORT_NAME bedrock)
Expand Down Expand Up @@ -158,6 +160,10 @@ if(AI_SDK_ENABLE_BEDROCK)
src/providers/bedrock/bedrock_stream.cpp
src/providers/bedrock/bedrock_factory.cpp
src/providers/bedrock/bedrock_credentials.cpp
src/providers/bedrock/sts_endpoint.cpp
# The requests over the core of the AWS SDK
src/providers/bedrock/aws_api_client.cpp
src/providers/bedrock/bedrock_transport.cpp
# Security components
src/providers/bedrock/input_validator.cpp
src/providers/bedrock/credential_redactor.cpp
Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,31 @@ int main() {
}
```

##### Bedrock with the Credentials of the Application

An application that already has its own way to find the credentials of AWS
(a credential chain of its own, a vault) gives them to the provider. The
provider then never looks for credentials itself, and the credential chain
of the AWS SDK is not linked into an application that creates its clients
only this way:

```cpp
ai::bedrock::BedrockConfig config;
config.region = "us-east-1";

auto client = ai::bedrock::create_client(config, [&] {
// Called when the client is created and for every request: cache the
// credentials and renew them before they expire
const auto current = my_credentials.get();
return ai::bedrock::AwsCredentials{
current.access_key_id, current.secret_access_key,
current.session_token};
});
```

A request is never sent unsigned: when the source has no access key,
creating the client throws `ai::ConfigurationError`.

##### Bedrock Security Configuration

```cpp
Expand Down
2 changes: 1 addition & 1 deletion cmake/ai-sdk-cpp-config.cmake.in
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ find_dependency(nlohmann_json CONFIG REQUIRED)
# The optional Bedrock component links the AWS SDK for C++
set(AI_SDK_ENABLE_BEDROCK @AI_SDK_ENABLE_BEDROCK@)
if(AI_SDK_ENABLE_BEDROCK)
find_dependency(AWSSDK REQUIRED COMPONENTS core bedrock-runtime bedrock sts)
find_dependency(AWSSDK REQUIRED COMPONENTS core bedrock-runtime bedrock)
endif()

# Include the targets file
Expand Down
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
52 changes: 52 additions & 0 deletions include/ai/bedrock.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "types/client.h"

#include <chrono>
#include <functional>
#include <optional>
#include <string>
#include <vector>
Expand Down Expand Up @@ -80,6 +81,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,8 +112,37 @@ 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;
};

/// Credentials of AWS that an application supplies (see
/// `AwsCredentialsSource`)
struct AwsCredentials {
std::string access_key_id;
std::string secret_access_key;
/// The session token of temporary credentials; empty for long-term ones
std::string session_token;
};

/// Returns the credentials of AWS to sign a request with. It is called while
/// the client is created, and then for every request, from the thread that
/// sends it: finding the credentials once, and renewing them before they
/// expire, is up to the application. Nothing is ever sent unsigned: if no
/// access key comes back, creating the client throws `ConfigurationError`,
/// and a request fails without being sent. An exception of the source fails
/// them with its message.
using AwsCredentialsSource = std::function<AwsCredentials()>;

/// Create a Bedrock client with default configuration
/// Uses AWS_REGION environment variable and default credential chain
/// @throws ConfigurationError if region is not configured
Expand All @@ -121,6 +155,24 @@ Client create_client();
/// @return Configured Bedrock client
Client create_client(const BedrockConfig& config);

/// Create a Bedrock client for an application that finds the credentials of
/// AWS in its own way, such as a credential chain of its own. The provider
/// then never looks for credentials itself: neither in the environment, nor
/// in the shared configuration files, nor at the metadata services.
///
/// An API key of Amazon Bedrock in `AWS_BEARER_TOKEN_BEDROCK` is still used
/// instead of a signature, and then the source is not called.
/// @param config Bedrock configuration; `profile`, `role_arn` and
/// `web_identity_token_file` name an identity for the provider to
/// find, so they must be empty
/// @param credentials The source of the credentials
/// @throws ConfigurationError if region is not configured, the source is
/// empty or has no credentials, or the configuration names an
/// identity
/// @return Configured Bedrock client
Client create_client(const BedrockConfig& config,
AwsCredentialsSource credentials);

/// Try to create a Bedrock client using environment configuration
/// @return Optional client - has value if credentials and region are available
/// @note This is useful for chaining creation attempts with other providers
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
139 changes: 139 additions & 0 deletions src/providers/bedrock/aws_api_client.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
#include "aws_api_client.h"

#include <iterator>
#include <utility>

#include <aws/core/client/AWSErrorMarshaller.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/http/HttpRequest.h>

namespace ai {
namespace bedrock {

namespace {

const char kAllocationTag[] = "BedrockApiClient";
const char kRequestIdHeader[] = "x-amzn-requestid";

// How much of an unexpected body is shown in an error
constexpr size_t kMaxShownBodyLength = 300;

} // namespace

SerializedRequest::SerializedRequest(std::string name,
std::string body,
const char* content_type,
bool event_stream_response)
: name_(std::move(name)),
body_(std::move(body)),
content_type_(content_type),
event_stream_response_(event_stream_response) {}

Aws::String SerializedRequest::SerializePayload() const {
return Aws::String(body_);
}

Aws::Http::HeaderValueCollection SerializedRequest::GetHeaders() const {
Aws::Http::HeaderValueCollection headers;
if (!body_.empty()) {
headers.emplace(Aws::Http::CONTENT_TYPE_HEADER, content_type_);
}
return headers;
}

const char* SerializedRequest::GetServiceRequestName() const {
return name_.c_str();
}

bool SerializedRequest::HasEventStreamResponse() const {
return event_stream_response_;
}

AwsApiClient::AwsApiClient(
const Aws::Client::ClientConfiguration& configuration,
const std::shared_ptr<Aws::Client::AWSAuthSigner>& signer,
const char* service_name,
ServiceErrorParser parse_error)
// The marshaller is asked only for the errors that all the services
// share (`FindErrorByName`): the body of an error is read by
// `parse_error`.
: Aws::Client::AWSClient(
configuration,
signer,
Aws::MakeShared<Aws::Client::JsonErrorMarshaller>(kAllocationTag)),
signer_name_(signer->GetName()),
parse_error_(parse_error) {
SetServiceClientName(service_name);
}

Aws::Client::StreamOutcome AwsApiClient::send(
const Aws::Http::URI& uri,
const Aws::AmazonWebServiceRequest& request,
Aws::Http::HttpMethod method) const {
return MakeRequestWithUnparsedResponse(uri, request, method,
signer_name_.c_str());
}

Aws::Client::AWSError<Aws::Client::CoreErrors> AwsApiClient::BuildAWSError(
const std::shared_ptr<Aws::Http::HttpResponse>& response) const {
using Aws::Client::AWSError;
using Aws::Client::CoreErrors;

if (response->HasClientError()) {
// There is no response, or not a whole one: the connection failed, or
// the request was not sent at all
const auto* streamed =
dynamic_cast<const StreamedResponse*>(&response->GetResponseBody());
const bool retryable =
response->GetClientErrorType() == CoreErrors::NETWORK_CONNECTION &&
!(streamed != nullptr && streamed->part_is_taken());
AWSError<CoreErrors> error(response->GetClientErrorType(), "",
response->GetClientErrorMessage(), retryable);
error.SetResponseCode(response->GetResponseCode());
return error;
}

const auto code = response->GetResponseCode();
// The body is read as a stream, to its end. It is not asked how long it
// is: an HTTP client may give a stream that is only read from, which does
// not answer that.
const ServiceError parsed =
parse_error_(read_body(response->GetResponseBody()), *response);

AWSError<CoreErrors> error =
GetErrorMarshaller()->FindErrorByName(parsed.name.c_str());
if (error.GetErrorType() == CoreErrors::UNKNOWN) {
const bool retryable =
parsed.retryable.value_or(Aws::Http::IsRetryableHttpResponseCode(code));
error = AWSError<CoreErrors>(CoreErrors::UNKNOWN, Aws::String(parsed.name),
Aws::String(parsed.message), retryable);
} else {
error.SetExceptionName(Aws::String(parsed.name));
error.SetMessage(Aws::String(parsed.message));
}

error.SetResponseHeaders(response->GetHeaders());
error.SetResponseCode(code);
if (response->HasHeader(kRequestIdHeader)) {
error.SetRequestId(response->GetHeader(kRequestIdHeader));
}
return error;
}

std::string read_body(Aws::IOStream& stream) {
return std::string(std::istreambuf_iterator<char>(stream),
std::istreambuf_iterator<char>());
}

std::string describe_unexpected_body(const std::string& body) {
if (body.empty()) {
return "the response has no body";
}
if (body.size() <= kMaxShownBodyLength) {
return body;
}
return body.substr(0, kMaxShownBodyLength) + "...";
}

} // namespace bedrock
} // namespace ai
Loading
Loading