diff --git a/CMakeLists.txt b/CMakeLists.txt index f23f3dc..37e8ae9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) @@ -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 diff --git a/README.md b/README.md index 8678cfd..584ae93 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/cmake/ai-sdk-cpp-config.cmake.in b/cmake/ai-sdk-cpp-config.cmake.in index 8e988cf..06c8bc9 100644 --- a/cmake/ai-sdk-cpp-config.cmake.in +++ b/cmake/ai-sdk-cpp-config.cmake.in @@ -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 diff --git a/include/ai/ai.h b/include/ai/ai.h index d4d7de3..a011efe 100644 --- a/include/ai/ai.h +++ b/include/ai/ai.h @@ -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" diff --git a/include/ai/bedrock.h b/include/ai/bedrock.h index efdbaa7..c371361 100644 --- a/include/ai/bedrock.h +++ b/include/ai/bedrock.h @@ -8,6 +8,7 @@ #include "types/client.h" #include +#include #include #include #include @@ -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; @@ -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; + /// Create a Bedrock client with default configuration /// Uses AWS_REGION environment variable and default credential chain /// @throws ConfigurationError if region is not configured @@ -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 diff --git a/include/ai/types/client.h b/include/ai/types/client.h index 7fc071f..d0a26d1 100644 --- a/include/ai/types/client.h +++ b/include/ai/types/client.h @@ -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(); diff --git a/src/providers/bedrock/aws_api_client.cpp b/src/providers/bedrock/aws_api_client.cpp new file mode 100644 index 0000000..bedad18 --- /dev/null +++ b/src/providers/bedrock/aws_api_client.cpp @@ -0,0 +1,139 @@ +#include "aws_api_client.h" + +#include +#include + +#include +#include +#include + +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& 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(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 AwsApiClient::BuildAWSError( + const std::shared_ptr& 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(&response->GetResponseBody()); + const bool retryable = + response->GetClientErrorType() == CoreErrors::NETWORK_CONNECTION && + !(streamed != nullptr && streamed->part_is_taken()); + AWSError 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 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::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(stream), + std::istreambuf_iterator()); +} + +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 diff --git a/src/providers/bedrock/aws_api_client.h b/src/providers/bedrock/aws_api_client.h new file mode 100644 index 0000000..8d32419 --- /dev/null +++ b/src/providers/bedrock/aws_api_client.h @@ -0,0 +1,115 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +/// What the body of a failed response says +struct ServiceError { + /// The name that the service gives to the error; empty when it has none + std::string name; + std::string message; + /// Set when the name alone tells whether the request can be repeated. + /// Otherwise the errors that all the services of AWS share are told by the + /// AWS SDK, and the rest by the HTTP status. + std::optional retryable; +}; + +/// Reads an error out of the body of a failed response, in the format of the +/// service (JSON for Amazon Bedrock, XML for AWS STS) +using ServiceErrorParser = + ServiceError (*)(const std::string& body, + const Aws::Http::HttpResponse& response); + +/// What the stream of a response tells about itself when the response is +/// taken from it part by part, before the request ends +class StreamedResponse { + public: + virtual ~StreamedResponse() = default; + + /// Whether a part of the response has been taken. The request is then not + /// repeated when it fails: its response would be taken once more from the + /// start. + virtual bool part_is_taken() const = 0; +}; + +/// A request whose body is already serialized +class SerializedRequest : public Aws::AmazonSerializableWebServiceRequest { + public: + /// @param name the name of the operation + /// @param body the body, or an empty string for a request without one + /// @param content_type the type of the body + /// @param event_stream_response whether the response is a stream of events: + /// an HTTP client that writes the response as it arrives then + /// writes every part of it at once + SerializedRequest(std::string name, + std::string body, + const char* content_type, + bool event_stream_response = false); + + Aws::String SerializePayload() const override; + Aws::Http::HeaderValueCollection GetHeaders() const override; + const char* GetServiceRequestName() const override; + bool HasEventStreamResponse() const override; + + private: + std::string name_; + std::string body_; + const char* content_type_; + bool event_stream_response_; +}; + +/// A client of an AWS service made of the core of the AWS SDK for C++ alone. +/// +/// The AWS SDK generates a client for every service, with a class for every +/// operation of the service and for every structure in its requests and +/// responses: hundreds of classes for Amazon Bedrock, of which the provider +/// needs four operations. What makes a request an AWS one is in the core, +/// and this client takes it from there: the HTTP client, the signature (or +/// the bearer token), the repeated attempts with their delays, the user +/// agent. The requests and the responses are the text that the caller makes +/// and reads. +class AwsApiClient : public Aws::Client::AWSClient { + public: + /// @param service_name the name of the service, for the user agent + AwsApiClient(const Aws::Client::ClientConfiguration& configuration, + const std::shared_ptr& signer, + const char* service_name, + ServiceErrorParser parse_error); + + /// Sends a request, repeating it as the retry strategy of the + /// configuration says, and returns the response with its body not read + Aws::Client::StreamOutcome send(const Aws::Http::URI& uri, + const Aws::AmazonWebServiceRequest& request, + Aws::Http::HttpMethod method) const; + + protected: + Aws::Client::AWSError BuildAWSError( + const std::shared_ptr& response) const override; + + private: + std::string signer_name_; + ServiceErrorParser parse_error_; +}; + +/// Everything that is left to read in a stream +std::string read_body(Aws::IOStream& stream); + +/// The start of a body that is not what the service was expected to answer, +/// to show in an error +std::string describe_unexpected_body(const std::string& body); + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/aws_sdk_manager.cpp b/src/providers/bedrock/aws_sdk_manager.cpp index d2bff37..2cc2ea9 100644 --- a/src/providers/bedrock/aws_sdk_manager.cpp +++ b/src/providers/bedrock/aws_sdk_manager.cpp @@ -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. @@ -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 diff --git a/src/providers/bedrock/aws_sdk_manager.h b/src/providers/bedrock/aws_sdk_manager.h index 7232f1b..d7dedd0 100644 --- a/src/providers/bedrock/aws_sdk_manager.h +++ b/src/providers/bedrock/aws_sdk_manager.h @@ -1,16 +1,32 @@ #pragma once +#include "ai/bedrock.h" + +#include + 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 diff --git a/src/providers/bedrock/bedrock_client.cpp b/src/providers/bedrock/bedrock_client.cpp index 29bba7f..d60bd30 100644 --- a/src/providers/bedrock/bedrock_client.cpp +++ b/src/providers/bedrock/bedrock_client.cpp @@ -3,8 +3,6 @@ #include "ai/bedrock.h" #include "ai/errors.h" #include "ai/tools.h" -#include "aws_sdk_manager.h" -#include "bedrock_credentials.h" #include "bedrock_request_mapper.h" #include "bedrock_response_parser.h" #include "bedrock_stream.h" @@ -14,14 +12,9 @@ #include #include -#include #include -#include #include - -#include -#include -#include +#include namespace ai { namespace bedrock { @@ -46,63 +39,51 @@ class SemaphoreGuard { } // namespace -// PImpl implementation - hides AWS SDK dependencies from public headers +// PImpl implementation struct BedrockClient::Impl { // Shared with streams, which may outlive the client - std::shared_ptr client; + BedrockTransports transports; std::shared_ptr> request_semaphore; BedrockRequestMapper request_mapper; BedrockResponseParser response_parser; InputValidator input_validator; - std::string region; std::string profile; std::string endpoint_override; - BedrockConfig config; // For model discovery, which uses its own client - bool valid{false}; - explicit Impl(const BedrockConfig& client_config_in) - : input_validator(client_config_in.security), config(client_config_in) { + Impl(const BedrockConfig& config, BedrockTransports transports_in) + : transports(std::move(transports_in)), + input_validator(config.security), + profile(config.profile), + endpoint_override(config.endpoint_override) { if (config.security.max_concurrent_requests <= 0) { throw ConfigurationError("max_concurrent_requests must be positive"); } request_semaphore = std::make_shared>( config.security.max_concurrent_requests); - region = config.region.empty() ? get_region_from_env() : config.region; - if (region.empty()) { - throw ConfigurationError( - "AWS region not configured. Set AWS_REGION environment variable or " - "provide region in BedrockConfig."); - } - - profile = config.profile; - endpoint_override = config.endpoint_override; - - Aws::Client::ClientConfiguration client_config; - client_config.region = region; - client_config.connectTimeoutMs = - static_cast(config.security.connection_timeout.count() * 1000); - client_config.requestTimeoutMs = - static_cast(config.security.request_timeout.count() * 1000); - if (!endpoint_override.empty()) { - // For VPC endpoints or local testing - client_config.endpointOverride = endpoint_override; - } - - client = std::make_shared( - make_credentials_provider(config, region), client_config); + SecureLogger::log_debug("Bedrock client initialized - region: " + + transports.region); + } - valid = true; - SecureLogger::log_debug("Bedrock client initialized - region: " + region); + /// A request of the Converse API: `POST /model/{modelId}/{action}` + TransportRequest make_converse_request(const char* operation, + const char* action, + const GenerateOptions& options) const { + TransportRequest request; + request.operation = operation; + request.path = {"model", options.model, action}; + request.body = BedrockRequestMapper::serialize( + request_mapper.map_to_converse_body(options)); + return request; } }; -BedrockClient::BedrockClient(const BedrockConfig& config) { - ensure_aws_sdk_initialized(); - pimpl_ = std::make_unique(config); +BedrockClient::BedrockClient(const BedrockConfig& config, + BedrockTransports transports) + : pimpl_(std::make_unique(config, std::move(transports))) { SecureLogger::log_info("Bedrock client created for region: " + - pimpl_->region); + pimpl_->transports.region); } BedrockClient::~BedrockClient() = default; @@ -131,32 +112,33 @@ GenerateResult BedrockClient::generate_text_single_step( } try { - auto request = pimpl_->request_mapper.map_to_converse_request(options); + const auto request = + pimpl_->make_converse_request("Converse", "converse", options); - Aws::BedrockRuntime::Model::ConverseOutcome outcome; + TransportResponse response; { // Limit the number of concurrent requests per client SemaphoreGuard guard(*pimpl_->request_semaphore); - outcome = pimpl_->client->Converse(request); + response = pimpl_->transports.runtime->send(request); } auto latency = std::chrono::duration_cast( std::chrono::steady_clock::now() - start_time); - 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(), + if (!response.success) { + auto result = pimpl_->response_parser.parse_converse_error(response); + SecureLogger::log_api_error("Converse", options.model, + pimpl_->transports.region, + response.error_name, response.error_message, 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); + pimpl_->response_parser.parse_converse_response(response.body); + SecureLogger::log_api_call("Converse", options.model, + pimpl_->transports.region, response.request_id, + latency); // Execute tools if the model made tool calls if (result.has_tool_calls() && options.has_tools()) { @@ -193,10 +175,10 @@ StreamResult BedrockClient::stream_text(const StreamOptions& options) { return StreamResult(std::move(impl)); } - Aws::BedrockRuntime::Model::ConverseStreamRequest request; + TransportRequest request; try { - request = - pimpl_->request_mapper.map_to_converse_stream_request(generate_options); + request = pimpl_->make_converse_request("ConverseStream", "converse-stream", + generate_options); } catch (const std::exception& e) { impl->fail(std::string("Bedrock API error: ") + e.what()); return StreamResult(std::move(impl)); @@ -205,14 +187,14 @@ StreamResult BedrockClient::stream_text(const StreamOptions& options) { // Limit the number of concurrent requests per client; the stream releases // the slot when it completes pimpl_->request_semaphore->acquire(); - impl->start_stream(pimpl_->client, std::move(request), + impl->start_stream(pimpl_->transports.runtime, std::move(request), pimpl_->request_semaphore); return StreamResult(std::move(impl)); } bool BedrockClient::is_valid() const { - return pimpl_ && pimpl_->valid; + return pimpl_ && pimpl_->transports.runtime != nullptr; } std::string BedrockClient::provider_name() const { @@ -247,14 +229,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); + ModelDiscovery discovery(pimpl_->transports.control_plane); 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: " + @@ -263,7 +244,7 @@ ModelListResult BedrockClient::list_models() { } std::string BedrockClient::config_info() const { - std::string info = "Bedrock API (region: " + pimpl_->region; + std::string info = "Bedrock API (region: " + pimpl_->transports.region; if (!pimpl_->profile.empty()) { info += ", profile: " + pimpl_->profile; } diff --git a/src/providers/bedrock/bedrock_client.h b/src/providers/bedrock/bedrock_client.h index ffd117e..f2dd1a7 100644 --- a/src/providers/bedrock/bedrock_client.h +++ b/src/providers/bedrock/bedrock_client.h @@ -5,6 +5,7 @@ #include "ai/types/generate_options.h" #include "ai/types/stream_options.h" #include "ai/types/stream_result.h" +#include "bedrock_transport.h" #include #include @@ -22,10 +23,12 @@ namespace bedrock { /// Bedrock client implementation /// Unlike OpenAI/Anthropic providers, this does not extend BaseProviderClient -/// because it uses AWS SDK rather than direct HTTP calls via httplib. +/// because its requests go through the AWS SDK rather than through httplib. class BedrockClient : public Client { public: - explicit BedrockClient(const BedrockConfig& config); + /// @param transports the services of Bedrock to send the requests to + /// (`make_transports` for the ones over the AWS SDK) + BedrockClient(const BedrockConfig& config, BedrockTransports transports); ~BedrockClient(); // Non-copyable, non-movable due to PImpl diff --git a/src/providers/bedrock/bedrock_credentials.cpp b/src/providers/bedrock/bedrock_credentials.cpp index 9357d89..4b4776c 100644 --- a/src/providers/bedrock/bedrock_credentials.cpp +++ b/src/providers/bedrock/bedrock_credentials.cpp @@ -1,27 +1,47 @@ #include "bedrock_credentials.h" #include "ai/errors.h" +#include "aws_api_client.h" +#include "aws_sdk_manager.h" #include "secure_logger.h" +#include "sts_endpoint.h" #include #include #include +#include +#include #include #include +#include +#include #include -#include -#include -#include +#include +#include +#include +#include +#include namespace ai { namespace bedrock { namespace { +const char kAllocationTag[] = "BedrockCredentials"; + // 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"; + +// The name of AWS STS: the requests are signed for it, and the endpoint +// settings of the environment and of the profile are looked up by it +// (`AWS_ENDPOINT_URL_STS`) +const char kStsServiceName[] = "sts"; +const char kFormContentType[] = "application/x-www-form-urlencoded"; + /// Credentials of the source identity: the configured profile, or the /// default credential chain (env vars, profile, IMDS, ...) std::shared_ptr make_source_provider( @@ -33,20 +53,99 @@ std::shared_ptr make_source_provider( return std::make_shared(); } +/// The text of a child of an XML node; empty if there is no such child +std::string child_text(const Aws::Utils::Xml::XmlNode& node, const char* name) { + auto child = node.FirstChild(name); + if (child.IsNull()) { + return {}; + } + return std::string(Aws::Utils::Xml::DecodeEscapedXmlText(child.GetText())); +} + +/// An error of AWS STS: +/// `AccessDenied...` +ServiceError parse_sts_error(const std::string& body, + const Aws::Http::HttpResponse& /*response*/) { + ServiceError error; + const auto document = + Aws::Utils::Xml::XmlDocument::CreateFromXmlString(Aws::String(body)); + if (document.WasParseSuccessful() && !document.GetRootElement().IsNull()) { + auto error_node = document.GetRootElement().FirstChild("Error"); + if (!error_node.IsNull()) { + error.name = child_text(error_node, "Code"); + error.message = child_text(error_node, "Message"); + } + } + if (error.message.empty()) { + error.message = describe_unexpected_body(body); + } + return error; +} + +/// The endpoint of AWS STS in a Region +Aws::Http::URI resolve_sts_endpoint( + const std::string& region, + const Aws::Client::ClientConfiguration& configuration) { + // An endpoint that the environment or the profile sets for the service + // (`AWS_ENDPOINT_URL_STS`, `AWS_ENDPOINT_URL`, `endpoint_url`) + const Aws::String configured = Aws::Config::EndpointResolver::EndpointSource( + kStsServiceName, configuration.profileName); + if (!configured.empty()) { + return Aws::Http::URI(configured); + } + + // The Regional endpoint, or its FIPS or dual-stack variant when the + // configuration asks for one (`AWS_USE_FIPS_ENDPOINT`, + // `AWS_USE_DUALSTACK_ENDPOINT`, or the profile): as the endpoint rules of + // the service make it, from the partitions that the AWS SDK knows + using Aws::Endpoint::AWSPartitions; + return Aws::Http::URI(Aws::String(make_sts_endpoint( + std::string(AWSPartitions::GetPartitionsBlob(), + AWSPartitions::PartitionsBlobStrLen), + region, configuration.useFIPS, configuration.useDualStack))); +} + +/// The form of an `AssumeRole` request +std::string make_assume_role_body(const BedrockConfig& config) { + using Aws::Utils::StringUtils; + std::string body = "Action=AssumeRole&Version=2011-06-15"; + body += "&RoleArn="; + body += StringUtils::URLEncode(config.role_arn.c_str()); + body += "&RoleSessionName="; + body += StringUtils::URLEncode(config.role_session_name.c_str()); + // AWS STS refuses an empty external ID + if (!config.external_id.empty()) { + body += "&ExternalId="; + body += StringUtils::URLEncode(config.external_id.c_str()); + } + return body; +} + /// Credentials of an IAM role assumed via STS `AssumeRole`, refreshed before /// they expire. The source credentials come from the configured profile or /// the default credential chain. +/// +/// `AssumeRole` is the one operation of AWS STS that is needed here, and it +/// is a form in, an XML document out: it is sent with the core of the AWS +/// SDK, without the generated client of the service. class AssumeRoleCredentialsProvider : public Aws::Auth::AWSCredentialsProvider { public: AssumeRoleCredentialsProvider(const BedrockConfig& config, const std::string& region) - : role_arn_(config.role_arn), - role_session_name_(config.role_session_name), - external_id_(config.external_id) { - Aws::STS::STSClientConfiguration sts_config; + : request_body_(make_assume_role_body(config)) { + Aws::Client::ClientConfiguration sts_config( + client_configuration_with_known_region()); sts_config.region = region; - sts_client_ = std::make_shared( - make_source_provider(config), nullptr, sts_config); + // As with Amazon Bedrock: a signed request is not repeated at another + // address + sts_config.followRedirects = Aws::Client::FollowRedirectsPolicy::NEVER; + endpoint_ = resolve_sts_endpoint(region, sts_config); + client_ = Aws::MakeShared( + kAllocationTag, sts_config, + Aws::MakeShared( + kAllocationTag, make_source_provider(config), kStsServiceName, + Aws::Region::ComputeSignerRegion(Aws::String(region))), + "STS", parse_sts_error); // Fail at client creation, not at the first request, if the role cannot // be assumed @@ -78,30 +177,62 @@ class AssumeRoleCredentialsProvider : public Aws::Auth::AWSCredentialsProvider { private: void refresh_locked() { - Aws::STS::Model::AssumeRoleRequest request; - request.SetRoleArn(role_arn_); - request.SetRoleSessionName(role_session_name_); - if (!external_id_.empty()) { - request.SetExternalId(external_id_); + const SerializedRequest request("AssumeRole", request_body_, + kFormContentType); + auto outcome = + client_->send(endpoint_, request, Aws::Http::HttpMethod::HTTP_POST); + if (!outcome.IsSuccess()) { + const auto& error = outcome.GetError(); + std::string message = "Failed to assume role: "; + if (!error.GetExceptionName().empty()) { + message += std::string(error.GetExceptionName()) + ": "; + } + throw ConfigurationError(message + std::string(error.GetMessage())); } - auto outcome = sts_client_->AssumeRole(request); - if (!outcome.IsSuccess()) { - throw ConfigurationError("Failed to assume role: " + - outcome.GetError().GetMessage()); + // `...` + const std::string body = + read_body(outcome.GetResult().GetPayload().GetUnderlyingStream()); + const auto document = + Aws::Utils::Xml::XmlDocument::CreateFromXmlString(Aws::String(body)); + std::string access_key_id; + std::string secret_access_key; + std::string session_token; + std::string expiration_text; + if (document.WasParseSuccessful() && !document.GetRootElement().IsNull()) { + auto result_node = + document.GetRootElement().FirstChild("AssumeRoleResult"); + if (!result_node.IsNull()) { + auto credentials_node = result_node.FirstChild("Credentials"); + if (!credentials_node.IsNull()) { + access_key_id = child_text(credentials_node, "AccessKeyId"); + secret_access_key = child_text(credentials_node, "SecretAccessKey"); + session_token = child_text(credentials_node, "SessionToken"); + expiration_text = child_text(credentials_node, "Expiration"); + } + } + } + + const Aws::Utils::DateTime expiration(Aws::String(expiration_text), + Aws::Utils::DateFormat::ISO_8601); + if (access_key_id.empty() || secret_access_key.empty() || + !expiration.WasParseSuccessful()) { + // The body is not shown: a response that is not understood may still + // have a secret in it + throw ConfigurationError( + "Failed to assume role: the response of AWS STS has no complete " + "credentials"); } - const auto& credentials = outcome.GetResult().GetCredentials(); credentials_ = Aws::Auth::AWSCredentials( - credentials.GetAccessKeyId(), credentials.GetSecretAccessKey(), - credentials.GetSessionToken(), credentials.GetExpiration()); + Aws::String(access_key_id), Aws::String(secret_access_key), + Aws::String(session_token), expiration); SecureLogger::log_debug("Assumed role credentials refreshed"); } - std::string role_arn_; - std::string role_session_name_; - std::string external_id_; - std::shared_ptr sts_client_; + std::string request_body_; + Aws::Http::URI endpoint_; + std::shared_ptr client_; std::mutex mutex_; Aws::Auth::AWSCredentials credentials_; }; @@ -157,5 +288,60 @@ std::shared_ptr make_credentials_provider( return make_source_provider(config); } +namespace { + +class ApplicationCredentialsProvider + : public Aws::Auth::AWSCredentialsProvider { + public: + explicit ApplicationCredentialsProvider(AwsCredentialsSource source) + : source_(std::move(source)) {} + + Aws::Auth::AWSCredentials GetAWSCredentials() override { + const AwsCredentials credentials = source_(); + // The signer of the AWS SDK sends a request unsigned when it gets no + // credentials. A request that cannot be signed is not sent at all. + if (credentials.access_key_id.empty() || + credentials.secret_access_key.empty()) { + throw ConfigurationError( + "No AWS credentials: the application has not " + "supplied an access key to sign the request " + "with"); + } + return Aws::Auth::AWSCredentials(Aws::String(credentials.access_key_id), + Aws::String(credentials.secret_access_key), + Aws::String(credentials.session_token)); + } + + private: + AwsCredentialsSource source_; +}; + +} // namespace + +std::shared_ptr +make_application_credentials_provider(AwsCredentialsSource source) { + return Aws::MakeShared(kAllocationTag, + std::move(source)); +} + +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'; +} + +std::shared_ptr make_api_key_provider() { + const char* api_key = std::getenv(kBedrockApiKeyVariable); + if (api_key == nullptr || *api_key == '\0') { + throw ConfigurationError(std::string(kBedrockApiKeyVariable) + + " is not set"); + } + return Aws::MakeShared( + kAllocationTag, Aws::Auth::AWSBearerToken(Aws::String(api_key))); +} + } // namespace bedrock } // namespace ai diff --git a/src/providers/bedrock/bedrock_credentials.h b/src/providers/bedrock/bedrock_credentials.h index 90a6ed4..f448f13 100644 --- a/src/providers/bedrock/bedrock_credentials.h +++ b/src/providers/bedrock/bedrock_credentials.h @@ -6,6 +6,7 @@ #include #include +#include namespace ai { namespace bedrock { @@ -23,5 +24,22 @@ std::shared_ptr make_credentials_provider( const BedrockConfig& config, const std::string& region); +/// A credentials provider that asks the application for the credentials +/// every time the AWS SDK wants them. It never lets a request go without a +/// signature: no credentials from the application is an error. +std::shared_ptr +make_application_credentials_provider(AwsCredentialsSource source); + +/// 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 API key of the `AWS_BEARER_TOKEN_BEDROCK` environment variable, to +/// send as a bearer token. +/// @throws ConfigurationError if the variable is not set +std::shared_ptr make_api_key_provider(); + } // namespace bedrock } // namespace ai diff --git a/src/providers/bedrock/bedrock_factory.cpp b/src/providers/bedrock/bedrock_factory.cpp index ba6a69b..4cf8f07 100644 --- a/src/providers/bedrock/bedrock_factory.cpp +++ b/src/providers/bedrock/bedrock_factory.cpp @@ -3,16 +3,22 @@ #include "ai/bedrock.h" #include "ai/errors.h" #include "bedrock_client.h" +#include "bedrock_transport.h" #include "model_discovery.h" #include "secure_logger.h" #include #include #include +#include namespace ai { namespace bedrock { +// This file is where the provider meets the AWS SDK: `make_transports` builds +// the services of Bedrock over it, and everything else of the provider talks +// to them in JSON. + Client create_client() { // Create client with default configuration // Uses AWS_REGION environment variable and default credential chain @@ -23,7 +29,16 @@ Client create_client() { Client create_client(const BedrockConfig& config) { // Create client with explicit configuration SecureLogger::log_debug("Creating Bedrock client with explicit config"); - return Client(std::make_unique(config)); + return Client( + std::make_unique(config, make_transports(config))); +} + +Client create_client(const BedrockConfig& config, + AwsCredentialsSource credentials) { + SecureLogger::log_debug( + "Creating Bedrock client with the credentials of the application"); + return Client(std::make_unique( + config, make_transports(config, std::move(credentials)))); } std::optional try_create_client() { @@ -33,7 +48,8 @@ std::optional try_create_client() { try { BedrockConfig config; - auto client = std::make_unique(config); + auto client = + std::make_unique(config, make_transports(config)); if (client->is_valid()) { SecureLogger::log_debug("Bedrock client created successfully"); @@ -61,7 +77,7 @@ std::vector list_available_models(const BedrockConfig& config) { SecureLogger::log_debug("Listing available models"); try { - ModelDiscovery discovery(config); + ModelDiscovery discovery(make_transports(config).control_plane); return discovery.list_models(); } catch (const std::exception& e) { SecureLogger::log_error("Failed to list models: " + std::string(e.what())); @@ -75,7 +91,7 @@ bool validate_model_access(const std::string& model_id, SecureLogger::log_debug("Validating model access: " + model_id); try { - ModelDiscovery discovery(config); + ModelDiscovery discovery(make_transports(config).control_plane); return discovery.is_model_accessible(model_id); } catch (const std::exception& e) { SecureLogger::log_debug("Model access validation failed: " + diff --git a/src/providers/bedrock/bedrock_json.h b/src/providers/bedrock/bedrock_json.h new file mode 100644 index 0000000..c5e44ef --- /dev/null +++ b/src/providers/bedrock/bedrock_json.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +#include + +namespace ai { +namespace bedrock { + +/// Reading what a service has answered, where nothing is taken for granted: +/// a member that is missing, or is of another type, reads as an empty value. + +/// A member of a JSON object, or null if the value is not an object or has +/// no such member +inline const nlohmann::json& json_member(const nlohmann::json& json, + const char* name) { + static const nlohmann::json null_value; + if (!json.is_object()) { + return null_value; + } + const auto it = json.find(name); + return it == json.end() ? null_value : *it; +} + +inline std::string json_string(const nlohmann::json& json) { + return json.is_string() ? json.get() : std::string(); +} + +inline int json_int(const nlohmann::json& json) { + return json.is_number_integer() ? json.get() : 0; +} + +inline bool json_bool(const nlohmann::json& json) { + return json.is_boolean() && json.get(); +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_request_mapper.cpp b/src/providers/bedrock/bedrock_request_mapper.cpp index 8c758a1..0def89c 100644 --- a/src/providers/bedrock/bedrock_request_mapper.cpp +++ b/src/providers/bedrock/bedrock_request_mapper.cpp @@ -4,25 +4,11 @@ #include #include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - namespace ai { namespace bedrock { -namespace Model = Aws::BedrockRuntime::Model; - namespace { // Claude models that reject `temperature` and `top_p`, as first-party model ID @@ -34,12 +20,23 @@ constexpr std::array kSamplingRejectingClaudePrefixes = { constexpr std::string_view kAnthropicModelPrefix = "anthropic."; +constexpr const char* kRoleUser = "user"; +constexpr const char* kRoleAssistant = "assistant"; + bool messages_use_tools(const Messages& messages) { return std::any_of(messages.begin(), messages.end(), [](const Message& m) { return m.has_tool_calls() || m.has_tool_results(); }); } +nlohmann::json text_block(const std::string& text) { + return nlohmann::json{{"text", text}}; +} + +bool is_tool_result(const nlohmann::json& content_block) { + return content_block.contains("toolResult"); +} + } // namespace bool BedrockRequestMapper::rejects_sampling_parameters( @@ -60,90 +57,62 @@ bool BedrockRequestMapper::rejects_sampling_parameters( }); } -Aws::Utils::Document BedrockRequestMapper::to_document( - const nlohmann::json& value) { - Aws::Utils::Document document(Aws::String(value.dump())); - if (!document.WasParseSuccessful()) { - throw std::invalid_argument("Failed to convert JSON to AWS document: " + - std::string(document.GetErrorMessage())); - } - return document; -} - -nlohmann::json BedrockRequestMapper::from_document( - const Aws::Utils::DocumentView& document) { - const Aws::String compact = document.WriteCompact(); - if (compact.empty()) { - return nlohmann::json::object(); - } - return nlohmann::json::parse(compact); +std::string BedrockRequestMapper::serialize(const nlohmann::json& body) { + return body.dump(-1, ' ', /*ensure_ascii=*/false, + nlohmann::json::error_handler_t::replace); } -Model::ConverseRequest BedrockRequestMapper::map_to_converse_request( +nlohmann::json BedrockRequestMapper::map_to_converse_body( const GenerateOptions& options) const { - Model::ConverseRequest request; - fill_request(request, options); - return request; -} - -Model::ConverseStreamRequest -BedrockRequestMapper::map_to_converse_stream_request( - const GenerateOptions& options) const { - Model::ConverseStreamRequest request; - fill_request(request, options); - return request; -} - -template -void BedrockRequestMapper::fill_request(Request& request, - const GenerateOptions& options) const { - request.SetModelId(options.model); + nlohmann::json body = nlohmann::json::object(); // Bedrock takes system prompts separately from the conversation: the // `system` option and every system message become system content blocks. + nlohmann::json system = nlohmann::json::array(); if (!options.system.empty()) { - Model::SystemContentBlock block; - block.SetText(options.system); - request.AddSystem(std::move(block)); + system.push_back(text_block(options.system)); } for (const auto& message : options.messages) { if (message.role == kMessageRoleSystem) { const std::string text = message.get_text(); if (!text.empty()) { - Model::SystemContentBlock block; - block.SetText(text); - request.AddSystem(std::move(block)); + system.push_back(text_block(text)); } } } + if (!system.empty()) { + body["system"] = std::move(system); + } // The conversation: the non-system messages, or the prompt if there are // none (e.g. only system messages were given) - auto messages = convert_messages(options.messages); + nlohmann::json messages = convert_messages(options.messages); if (messages.empty() && !options.prompt.empty()) { - Model::Message user_message; - user_message.SetRole(Model::ConversationRole::user); - Model::ContentBlock content_block; - content_block.SetText(options.prompt); - user_message.AddContent(std::move(content_block)); - messages.push_back(std::move(user_message)); + messages.push_back( + {{"role", kRoleUser}, + {"content", nlohmann::json::array({text_block(options.prompt)})}}); } - request.SetMessages(std::move(messages)); + body["messages"] = std::move(messages); - request.SetInferenceConfig(build_inference_config(options)); + nlohmann::json inference_config = build_inference_config(options); + if (!inference_config.empty()) { + body["inferenceConfig"] = std::move(inference_config); + } if (auto tool_config = build_tool_config(options)) { - request.SetToolConfig(std::move(*tool_config)); + body["toolConfig"] = std::move(*tool_config); } + + return body; } -Aws::Vector BedrockRequestMapper::convert_messages( +nlohmann::json BedrockRequestMapper::convert_messages( const Messages& messages) const { - Aws::Vector bedrock_messages; - bedrock_messages.reserve(messages.size()); + nlohmann::json bedrock_messages = nlohmann::json::array(); for (const auto& message : messages) { - // System messages are sent as system content blocks (see fill_request) + // System messages are sent as system content blocks (see + // map_to_converse_body) if (message.role == kMessageRoleSystem) { continue; } @@ -158,21 +127,19 @@ Aws::Vector BedrockRequestMapper::convert_messages( // come before any other content of the user turn that answers the tool // calls (text may follow them). if (!bedrock_messages.empty() && - bedrock_messages.back().GetRole() == converted->GetRole()) { + bedrock_messages.back()["role"] == (*converted)["role"]) { auto& previous = bedrock_messages.back(); - Aws::Vector merged; - merged.reserve(previous.GetContent().size() + - converted->GetContent().size()); + nlohmann::json merged = nlohmann::json::array(); for (const bool tool_results : {true, false}) { for (const auto* turn : {&previous, &*converted}) { - for (const auto& block : turn->GetContent()) { - if (block.ToolResultHasBeenSet() == tool_results) { + for (const auto& block : (*turn)["content"]) { + if (is_tool_result(block) == tool_results) { merged.push_back(block); } } } } - previous.SetContent(std::move(merged)); + previous["content"] = std::move(merged); } else { bedrock_messages.push_back(std::move(*converted)); } @@ -181,97 +148,85 @@ Aws::Vector BedrockRequestMapper::convert_messages( return bedrock_messages; } -std::optional BedrockRequestMapper::convert_message( +std::optional BedrockRequestMapper::convert_message( const Message& message) const { - Model::Message bedrock_message; - - // Bedrock expects tool results in user messages - if (message.role == kMessageRoleAssistant && !message.has_tool_results()) { - bedrock_message.SetRole(Model::ConversationRole::assistant); - } else { - bedrock_message.SetRole(Model::ConversationRole::user); - } + nlohmann::json content = nlohmann::json::array(); for (const auto& part : message.content) { - Model::ContentBlock content_block; - if (const auto* text_part = std::get_if(&part)) { if (text_part->text.empty()) { continue; // Bedrock rejects empty text blocks } - content_block.SetText(text_part->text); + content.push_back(text_block(text_part->text)); } else if (const auto* tool_call = std::get_if(&part)) { - Model::ToolUseBlock tool_use; - tool_use.SetToolUseId(tool_call->id); - tool_use.SetName(tool_call->tool_name); - tool_use.SetInput(to_document(tool_call->arguments.is_null() - ? nlohmann::json::object() - : tool_call->arguments)); - content_block.SetToolUse(std::move(tool_use)); + content.push_back({{"toolUse", + {{"toolUseId", tool_call->id}, + {"name", tool_call->tool_name}, + {"input", tool_call->arguments.is_null() + ? nlohmann::json::object() + : tool_call->arguments}}}}); } else if (const auto* tool_result = std::get_if(&part)) { - Model::ToolResultContentBlock result_content; + nlohmann::json result_content; // Bedrock accepts only JSON objects as `json` tool results if (tool_result->result.is_object()) { - result_content.SetJson(to_document(tool_result->result)); + result_content = {{"json", tool_result->result}}; } else if (tool_result->result.is_string()) { - result_content.SetText(tool_result->result.get()); + result_content = text_block(tool_result->result.get()); } else { - result_content.SetText(tool_result->result.dump()); + result_content = text_block(serialize(tool_result->result)); } - Model::ToolResultBlock result_block; - result_block.SetToolUseId(tool_result->tool_call_id); - result_block.AddContent(std::move(result_content)); - result_block.SetStatus(tool_result->is_error - ? Model::ToolResultStatus::error - : Model::ToolResultStatus::success); - content_block.SetToolResult(std::move(result_block)); - } else { - continue; + content.push_back( + {{"toolResult", + {{"toolUseId", tool_result->tool_call_id}, + {"content", nlohmann::json::array({std::move(result_content)})}, + {"status", tool_result->is_error ? "error" : "success"}}}}); } - - bedrock_message.AddContent(std::move(content_block)); } - if (bedrock_message.GetContent().empty()) { + if (content.empty()) { return std::nullopt; // Bedrock rejects messages without content } - return bedrock_message; + + // Bedrock expects tool results in user messages + const bool assistant = + message.role == kMessageRoleAssistant && !message.has_tool_results(); + return nlohmann::json{{"role", assistant ? kRoleAssistant : kRoleUser}, + {"content", std::move(content)}}; } -Model::InferenceConfiguration BedrockRequestMapper::build_inference_config( +nlohmann::json BedrockRequestMapper::build_inference_config( const GenerateOptions& options) const { - Model::InferenceConfiguration config; + nlohmann::json config = nlohmann::json::object(); if (options.max_tokens.has_value()) { - config.SetMaxTokens(options.max_tokens.value()); + config["maxTokens"] = options.max_tokens.value(); } const bool drop_sampling = rejects_sampling_parameters(options.model); - const auto set_sampling = - [&](const char* name, const std::optional& value, auto setter) { - if (!value) { - return; - } - if (drop_sampling) { - ai::logger::log_warn( - "Ignoring {} for {} because the model does not support sampling " - "parameters", - name, options.model); - return; - } - setter(static_cast(*value)); - }; - set_sampling("temperature", options.temperature, - [&](float v) { config.SetTemperature(v); }); - set_sampling("top_p", options.top_p, [&](float v) { config.SetTopP(v); }); + const auto set_sampling = [&](const char* name, const char* member, + const std::optional& value) { + if (!value) { + return; + } + if (drop_sampling) { + ai::logger::log_warn( + "Ignoring {} for {} because the model does not support sampling " + "parameters", + name, options.model); + return; + } + config[member] = *value; + }; + set_sampling("temperature", "temperature", options.temperature); + set_sampling("top_p", "topP", options.top_p); return config; } -std::optional BedrockRequestMapper::build_tool_config( +std::optional BedrockRequestMapper::build_tool_config( const GenerateOptions& options) const { if (!options.has_tools()) { return std::nullopt; @@ -285,51 +240,41 @@ std::optional BedrockRequestMapper::build_tool_config( return std::nullopt; } - Model::ToolConfiguration tool_config; + nlohmann::json tools = nlohmann::json::array(); for (const auto& tool_name : options.get_active_tool_names()) { const auto it = options.tools.find(tool_name); if (it == options.tools.end()) { continue; } - Model::ToolInputSchema input_schema; - input_schema.SetJson(to_document(it->second.parameters_schema.is_null() - ? nlohmann::json{{"type", "object"}} - : it->second.parameters_schema)); - - Model::ToolSpecification spec; - spec.SetName(tool_name); + nlohmann::json spec = {{"name", tool_name}, + {"inputSchema", + {{"json", it->second.parameters_schema.is_null() + ? nlohmann::json{{"type", "object"}} + : it->second.parameters_schema}}}}; if (!it->second.description.empty()) { - spec.SetDescription(it->second.description); + spec["description"] = it->second.description; } - spec.SetInputSchema(std::move(input_schema)); - - Model::Tool tool; - tool.SetToolSpec(std::move(spec)); - tool_config.AddTools(std::move(tool)); + tools.push_back({{"toolSpec", std::move(spec)}}); } - if (tool_config.GetTools().empty()) { + if (tools.empty()) { return std::nullopt; } - Model::ToolChoice tool_choice; + nlohmann::json tool_config = {{"tools", std::move(tools)}}; switch (options.tool_choice.type) { case ToolChoiceType::kRequired: - tool_choice.SetAny(Model::AnyToolChoice()); - tool_config.SetToolChoice(std::move(tool_choice)); + tool_config["toolChoice"] = {{"any", nlohmann::json::object()}}; break; case ToolChoiceType::kSpecific: if (options.tool_choice.tool_name) { - Model::SpecificToolChoice specific; - specific.SetName(*options.tool_choice.tool_name); - tool_choice.SetTool(std::move(specific)); - tool_config.SetToolChoice(std::move(tool_choice)); + tool_config["toolChoice"] = { + {"tool", {{"name", *options.tool_choice.tool_name}}}}; } break; case ToolChoiceType::kAuto: - tool_choice.SetAuto(Model::AutoToolChoice()); - tool_config.SetToolChoice(std::move(tool_choice)); + tool_config["toolChoice"] = {{"auto", nlohmann::json::object()}}; break; case ToolChoiceType::kNone: ai::logger::log_warn( diff --git a/src/providers/bedrock/bedrock_request_mapper.h b/src/providers/bedrock/bedrock_request_mapper.h index 7188503..d24e2cf 100644 --- a/src/providers/bedrock/bedrock_request_mapper.h +++ b/src/providers/bedrock/bedrock_request_mapper.h @@ -5,57 +5,38 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include namespace ai { namespace bedrock { -/// Maps SDK options to Bedrock Converse / ConverseStream requests +/// Maps SDK options to the body of a Bedrock Converse / ConverseStream +/// request class BedrockRequestMapper { public: - Aws::BedrockRuntime::Model::ConverseRequest map_to_converse_request( - const GenerateOptions& options) const; + /// The JSON that both `Converse` and `ConverseStream` take. The model is + /// not a part of it: it is in the path of the request. + nlohmann::json map_to_converse_body(const GenerateOptions& options) const; - Aws::BedrockRuntime::Model::ConverseStreamRequest - map_to_converse_stream_request(const GenerateOptions& options) const; + /// The text of a body to send. A byte sequence that is not UTF-8 (in a + /// prompt, or in a result of a tool) is replaced with U+FFFD instead of + /// failing the request: JSON cannot carry it. + static std::string serialize(const nlohmann::json& body); /// Whether the model rejects sampling parameters (`temperature`, `top_p`). /// Recognizes model IDs with or without a cross-region inference profile /// prefix (e.g. `us.anthropic.claude-opus-5-5`). static bool rejects_sampling_parameters(const std::string& model_id); - /// Convert JSON to an AWS document (throws std::invalid_argument on failure) - static Aws::Utils::Document to_document(const nlohmann::json& value); - - /// Convert an AWS document to JSON - static nlohmann::json from_document(const Aws::Utils::DocumentView& document); - static nlohmann::json from_document(const Aws::Utils::Document& document) { - return from_document(document.View()); - } - private: - template - void fill_request(Request& request, const GenerateOptions& options) const; + nlohmann::json convert_messages(const Messages& messages) const; - Aws::Vector convert_messages( - const Messages& messages) const; + std::optional convert_message(const Message& message) const; - std::optional convert_message( - const Message& message) const; + nlohmann::json build_inference_config(const GenerateOptions& options) const; - Aws::BedrockRuntime::Model::InferenceConfiguration build_inference_config( + std::optional build_tool_config( const GenerateOptions& options) const; - - std::optional - build_tool_config(const GenerateOptions& options) const; }; } // namespace bedrock diff --git a/src/providers/bedrock/bedrock_response_parser.cpp b/src/providers/bedrock/bedrock_response_parser.cpp index 55b5325..8e8e2a6 100644 --- a/src/providers/bedrock/bedrock_response_parser.cpp +++ b/src/providers/bedrock/bedrock_response_parser.cpp @@ -1,40 +1,50 @@ #include "bedrock_response_parser.h" #include "ai/logger.h" -#include "bedrock_request_mapper.h" - -#include -#include -#include -#include -#include +#include "bedrock_json.h" namespace ai { namespace bedrock { GenerateResult BedrockResponseParser::parse_converse_response( - const Aws::BedrockRuntime::Model::ConverseResult& result) { + const std::string& body) { ai::logger::log_debug("Parsing Bedrock Converse response"); + const auto response = + nlohmann::json::parse(body, nullptr, /*allow_exceptions=*/false); + if (!response.is_object()) { + GenerateResult result( + "Bedrock API error: the response of Converse is not a JSON object"); + result.finish_reason = kFinishReasonError; + result.is_retryable = false; + return result; + } + GenerateResult gen_result; - // Extract text from output message content blocks - if (result.GetOutput().MessageHasBeenSet()) { - const auto& message = result.GetOutput().GetMessage(); - gen_result.text = extract_text(message.GetContent()); - ai::logger::log_debug("Extracted text length: {}", - gen_result.text.length()); + // The text and the tool calls of the output message + const auto& content = json_member( + json_member(json_member(response, "output"), "message"), "content"); + if (content.is_array()) { + for (const auto& block : content) { + const auto& text = json_member(block, "text"); + if (text.is_string()) { + gen_result.text += text.get(); + } - for (const auto& block : message.GetContent()) { - if (!block.ToolUseHasBeenSet()) { - continue; + const auto& tool_use = json_member(block, "toolUse"); + if (tool_use.is_object()) { + const auto& input = json_member(tool_use, "input"); + gen_result.tool_calls.emplace_back( + json_string(json_member(tool_use, "toolUseId")), + json_string(json_member(tool_use, "name")), + input.is_null() ? nlohmann::json::object() : input); + ai::logger::log_debug("Parsed Bedrock tool call: {}", + gen_result.tool_calls.back().tool_name); } - const auto& tool_use = block.GetToolUse(); - gen_result.tool_calls.emplace_back( - tool_use.GetToolUseId(), tool_use.GetName(), - BedrockRequestMapper::from_document(tool_use.GetInput())); - ai::logger::log_debug("Parsed Bedrock tool call: {}", tool_use.GetName()); } + ai::logger::log_debug("Extracted text length: {}", + gen_result.text.length()); // Add assistant response to messages if (!gen_result.text.empty()) { @@ -44,15 +54,16 @@ GenerateResult BedrockResponseParser::parse_converse_response( } // Map stop reason to finish reason - gen_result.finish_reason = map_stop_reason(result.GetStopReason()); + gen_result.finish_reason = + map_stop_reason(json_string(json_member(response, "stopReason"))); ai::logger::log_debug("Stop reason mapped to: {}", gen_result.finishReasonToString()); // Extract usage information - // Note: Always try to get usage - the SDK initializes with zeros if not set - const auto& usage = result.GetUsage(); - gen_result.usage.prompt_tokens = usage.GetInputTokens(); - gen_result.usage.completion_tokens = usage.GetOutputTokens(); + const auto& usage = json_member(response, "usage"); + gen_result.usage.prompt_tokens = json_int(json_member(usage, "inputTokens")); + gen_result.usage.completion_tokens = + json_int(json_member(usage, "outputTokens")); gen_result.usage.total_tokens = gen_result.usage.prompt_tokens + gen_result.usage.completion_tokens; @@ -67,27 +78,23 @@ GenerateResult BedrockResponseParser::parse_converse_response( } GenerateResult BedrockResponseParser::parse_converse_error( - const Aws::BedrockRuntime::BedrockRuntimeError& error) { - ai::logger::log_debug("Parsing Bedrock error: {} - {}", - error.GetExceptionName(), error.GetMessage()); + const TransportResponse& response) { + ai::logger::log_debug("Parsing Bedrock error: {} - {}", response.error_name, + response.error_message); GenerateResult result; result.finish_reason = kFinishReasonError; // Build descriptive error message with AWS error code - std::string error_message; - const auto& exception_name = error.GetExceptionName(); - const auto& message = error.GetMessage(); - - if (!exception_name.empty()) { - error_message = exception_name + ": " + message; + if (!response.error_name.empty()) { + result.error = response.error_name + ": " + response.error_message; } else { - // Fallback to error type name if exception name is empty - error_message = "BedrockError: " + message; + result.error = "BedrockError: " + response.error_message; } - result.error = error_message; - result.is_retryable = is_error_retryable(error); + // Whether the request can be repeated is told where the response is + // received: by the name of the error, and by the HTTP status + result.is_retryable = response.retryable; ai::logger::log_debug("Error is retryable: {}", result.is_retryable.value_or(false)); @@ -95,118 +102,20 @@ GenerateResult BedrockResponseParser::parse_converse_error( return result; } -bool BedrockResponseParser::is_error_retryable( - const Aws::BedrockRuntime::BedrockRuntimeError& error) { - // Get the error type from AWS SDK - auto error_type = error.GetErrorType(); - - // Check for retryable errors based on error type - switch (error_type) { - case Aws::BedrockRuntime::BedrockRuntimeErrors::THROTTLING: - // ThrottlingException - rate limiting - return true; - - case Aws::BedrockRuntime::BedrockRuntimeErrors::SERVICE_UNAVAILABLE: - // ServiceUnavailableException - temporary service issue - return true; - - case Aws::BedrockRuntime::BedrockRuntimeErrors::INTERNAL_FAILURE: - // InternalServerException - 5xx errors - return true; - - case Aws::BedrockRuntime::BedrockRuntimeErrors::NETWORK_CONNECTION: - // Transient network failure - return true; - - case Aws::BedrockRuntime::BedrockRuntimeErrors::VALIDATION: - // ValidationException - invalid request - return false; - - case Aws::BedrockRuntime::BedrockRuntimeErrors::ACCESS_DENIED: - // AccessDeniedException - permission denied - return false; - - case Aws::BedrockRuntime::BedrockRuntimeErrors::RESOURCE_NOT_FOUND: - // ResourceNotFoundException - invalid model ID - return false; - - default: - break; +FinishReason BedrockResponseParser::map_stop_reason(const std::string& reason) { + if (reason == "max_tokens") { + return kFinishReasonLength; } - - // Check exception name for additional error types - const auto& exception_name = error.GetExceptionName(); - - // Retryable errors by exception name - if (exception_name == "ThrottlingException" || - exception_name == "ServiceUnavailableException" || - exception_name == "InternalServerException") { - return true; + // Guardrail intervention is a form of content filtering + if (reason == "content_filtered" || reason == "guardrail_intervened") { + return kFinishReasonContentFilter; } - - // Non-retryable errors by exception name - if (exception_name == "ValidationException" || - exception_name == "AccessDeniedException" || - exception_name == "ResourceNotFoundException" || - exception_name == "UnrecognizedClientException") { - return false; + if (reason == "tool_use") { + return kFinishReasonToolCalls; } - - // Check HTTP response code for 5xx errors - auto response_code = error.GetResponseCode(); - if (response_code != Aws::Http::HttpResponseCode::REQUEST_NOT_MADE) { - int status_code = static_cast(response_code); - if (status_code >= 500 && status_code < 600) { - return true; - } - } - - // Default to non-retryable for unknown errors - return false; -} - -FinishReason BedrockResponseParser::map_stop_reason( - Aws::BedrockRuntime::Model::StopReason reason) { - // Map Bedrock stop reasons to SDK FinishReason (from design doc) - switch (reason) { - case Aws::BedrockRuntime::Model::StopReason::end_turn: - return kFinishReasonStop; - - case Aws::BedrockRuntime::Model::StopReason::max_tokens: - return kFinishReasonLength; - - case Aws::BedrockRuntime::Model::StopReason::content_filtered: - return kFinishReasonContentFilter; - - case Aws::BedrockRuntime::Model::StopReason::tool_use: - return kFinishReasonToolCalls; - - case Aws::BedrockRuntime::Model::StopReason::stop_sequence: - // stop_sequence is similar to end_turn - normal completion - return kFinishReasonStop; - - case Aws::BedrockRuntime::Model::StopReason::guardrail_intervened: - // Guardrail intervention is a form of content filtering - return kFinishReasonContentFilter; - - default: - // For unknown stop reasons, default to stop - return kFinishReasonStop; - } -} - -std::string BedrockResponseParser::extract_text( - const Aws::Vector& blocks) { - std::string full_text; - - for (const auto& block : blocks) { - // Check if this is a text block and extract the text - if (block.TextHasBeenSet()) { - full_text += block.GetText(); - } - } - - return full_text; + // "end_turn" and "stop_sequence" are normal completion; an unknown stop + // reason is taken for one as well + return kFinishReasonStop; } } // namespace bedrock diff --git a/src/providers/bedrock/bedrock_response_parser.h b/src/providers/bedrock/bedrock_response_parser.h index 9039b30..b730dcd 100644 --- a/src/providers/bedrock/bedrock_response_parser.h +++ b/src/providers/bedrock/bedrock_response_parser.h @@ -1,12 +1,9 @@ #pragma once #include "ai/types/generate_options.h" +#include "bedrock_transport.h" -#include -#include -#include -#include -#include +#include namespace ai { namespace bedrock { @@ -18,34 +15,19 @@ class BedrockResponseParser { ~BedrockResponseParser() = default; /// Parse successful Converse response - /// @param result AWS Bedrock ConverseResult - /// @return SDK GenerateResult - GenerateResult parse_converse_response( - const Aws::BedrockRuntime::Model::ConverseResult& result); + /// @param body the JSON of the response + /// @return SDK GenerateResult; an error one if the body is not what + /// Converse answers with + GenerateResult parse_converse_response(const std::string& body); /// Parse Converse error into GenerateResult - /// @param error AWS Bedrock error + /// @param response a failed response /// @return SDK GenerateResult with error information - GenerateResult parse_converse_error( - const Aws::BedrockRuntime::BedrockRuntimeError& error); - - /// Determine if an error is retryable - /// @param error AWS Bedrock error - /// @return true if the error is retryable - bool is_error_retryable( - const Aws::BedrockRuntime::BedrockRuntimeError& error); - - private: - /// Map Bedrock stop reason to SDK FinishReason - /// @param reason Bedrock stop reason - /// @return SDK FinishReason - FinishReason map_stop_reason(Aws::BedrockRuntime::Model::StopReason reason); - - /// Extract text from content blocks - /// @param blocks Vector of Bedrock content blocks - /// @return Concatenated text from all blocks - std::string extract_text( - const Aws::Vector& blocks); + GenerateResult parse_converse_error(const TransportResponse& response); + + /// Map Bedrock stop reason ("end_turn", "tool_use", ...) to SDK + /// FinishReason + static FinishReason map_stop_reason(const std::string& reason); }; } // namespace bedrock diff --git a/src/providers/bedrock/bedrock_stream.cpp b/src/providers/bedrock/bedrock_stream.cpp index 1cdb8a8..4279487 100644 --- a/src/providers/bedrock/bedrock_stream.cpp +++ b/src/providers/bedrock/bedrock_stream.cpp @@ -1,21 +1,12 @@ #include "bedrock_stream.h" #include "ai/logger.h" - -#include -#include -#include -#include -#include -#include -#include -#include +#include "bedrock_json.h" +#include "bedrock_response_parser.h" namespace ai { namespace bedrock { -namespace Model = Aws::BedrockRuntime::Model; - BedrockStreamImpl::~BedrockStreamImpl() { stop_stream(); // Release the semaphore if the stream thread never ran to completion @@ -25,56 +16,38 @@ BedrockStreamImpl::~BedrockStreamImpl() { } void BedrockStreamImpl::start_stream( - std::shared_ptr client, - Model::ConverseStreamRequest request, + std::shared_ptr transport, + TransportRequest request, std::shared_ptr semaphore) { ai::logger::log_debug("Starting Bedrock ConverseStream"); semaphore_ = std::move(semaphore); - stream_thread_ = std::thread([this, client = std::move(client), + stream_thread_ = std::thread([this, transport = std::move(transport), request = std::move(request)]() mutable { - run_stream(std::move(client), std::move(request)); + run_stream(std::move(transport), std::move(request)); }); } -void BedrockStreamImpl::run_stream( - std::shared_ptr client, - Model::ConverseStreamRequest request) { +void BedrockStreamImpl::run_stream(std::shared_ptr transport, + TransportRequest request) { try { - Model::ConverseStreamHandler handler; - handler.SetContentBlockStartEventCallback( - [this](const Model::ContentBlockStartEvent& event) { - on_content_block_start(event); - }); - handler.SetContentBlockDeltaEventCallback( - [this](const Model::ContentBlockDeltaEvent& event) { - on_content_block_delta(event); - }); - handler.SetContentBlockStopEventCallback( - [this](const Model::ContentBlockStopEvent& event) { - on_content_block_stop(event); - }); - handler.SetMessageStopEventCallback( - [this](const Model::MessageStopEvent& event) { - on_message_stop(event); - }); - handler.SetConverseStreamMetadataEventCallback( - [this](const Model::ConverseStreamMetadataEvent& event) { - on_metadata(event); - }); - handler.SetOnErrorCallback( - [this](const Aws::BedrockRuntime::BedrockRuntimeError& error) { - on_error(error); - }); - request.SetEventStreamHandler(handler); - - // Abort the HTTP request when the consumer stops the stream - request.SetContinueRequestHandler( - [this](const Aws::Http::HttpRequest*) { return !stop_requested_; }); - - auto outcome = client->ConverseStream(request); - if (!outcome.IsSuccess() && !stop_requested_) { - on_error(outcome.GetError()); + // The request is abandoned when the consumer stops the stream + const auto response = transport->send_for_events( + request, + [this](const std::string& type, const std::string& payload) { + on_event(type, payload); + }, + [this] { return !stop_requested_.load(); }); + if (!response.success && !stop_requested_) { + on_error(response); + } else if (response.success && !stop_requested_ && !errored_ && + !message_stopped_) { + // A whole answer ends with `messageStop`. A stream that was cut off + // may still end as a body that is complete for the HTTP client, and + // what has arrived of it is not the answer. + push_error( + "Stream error: the stream of events ended before the end of the " + "message"); } } catch (const std::exception& e) { ai::logger::log_error("Bedrock stream thread exception: {}", e.what()); @@ -91,8 +64,8 @@ void BedrockStreamImpl::fail(const std::string& error_message) { StreamEvent BedrockStreamImpl::get_next_event() { // No timeout of its own: gaps between events can be long while the model - // thinks, and a stalled connection is ended by the AWS client's request - // timeout, after which the stream thread pushes an error and completes. + // thinks, and a stalled connection is ended by the request timeout of the + // transport, after which the stream thread pushes an error and completes. std::unique_lock lock(queue_mutex_); queue_cv_.wait(lock, [this] { return !event_queue_.empty() || complete_; }); @@ -117,42 +90,65 @@ void BedrockStreamImpl::stop_stream() { } } -void BedrockStreamImpl::on_content_block_start( - const Model::ContentBlockStartEvent& event) { - if (stop_requested_ || !event.StartHasBeenSet() || - !event.GetStart().ToolUseHasBeenSet()) { +void BedrockStreamImpl::on_event(const std::string& type, + const std::string& payload) { + if (stop_requested_) { return; } - const auto& tool_use = event.GetStart().GetToolUse(); - pending_tool_calls_[event.GetContentBlockIndex()] = - PendingToolCall{tool_use.GetToolUseId(), tool_use.GetName(), {}}; + + const auto event = + nlohmann::json::parse(payload, nullptr, /*allow_exceptions=*/false); + if (event.is_discarded()) { + push_error("Invalid JSON in the stream event '" + type + "'"); + return; + } + + if (type == "contentBlockStart") { + on_content_block_start(event); + } else if (type == "contentBlockDelta") { + on_content_block_delta(event); + } else if (type == "contentBlockStop") { + on_content_block_stop(event); + } else if (type == "messageStop") { + on_message_stop(event); + } else if (type == "metadata") { + on_metadata(event); + } + // "messageStart" has only the role, which is always the assistant one; an + // event of an unknown type is skipped } -void BedrockStreamImpl::on_content_block_delta( - const Model::ContentBlockDeltaEvent& event) { - if (stop_requested_ || !event.DeltaHasBeenSet()) { +void BedrockStreamImpl::on_content_block_start(const nlohmann::json& event) { + const auto& tool_use = json_member(json_member(event, "start"), "toolUse"); + if (!tool_use.is_object()) { return; } - const auto& delta = event.GetDelta(); + pending_tool_calls_[json_int(json_member(event, "contentBlockIndex"))] = + PendingToolCall{json_string(json_member(tool_use, "toolUseId")), + json_string(json_member(tool_use, "name")), + {}}; +} - if (delta.TextHasBeenSet()) { - push_event(StreamEvent(std::string(delta.GetText()))); +void BedrockStreamImpl::on_content_block_delta(const nlohmann::json& event) { + const auto& delta = json_member(event, "delta"); + + const auto& text = json_member(delta, "text"); + if (text.is_string()) { + push_event(StreamEvent(text.get())); } - if (delta.ToolUseHasBeenSet()) { - const auto it = pending_tool_calls_.find(event.GetContentBlockIndex()); + const auto& tool_use = json_member(delta, "toolUse"); + if (tool_use.is_object()) { + const auto it = pending_tool_calls_.find( + json_int(json_member(event, "contentBlockIndex"))); if (it != pending_tool_calls_.end()) { - it->second.input_json += delta.GetToolUse().GetInput(); + it->second.input_json += json_string(json_member(tool_use, "input")); } } } -void BedrockStreamImpl::on_content_block_stop( - const Model::ContentBlockStopEvent& event) { - if (stop_requested_) { - return; - } - flush_tool_call(event.GetContentBlockIndex()); +void BedrockStreamImpl::on_content_block_stop(const nlohmann::json& event) { + flush_tool_call(json_int(json_member(event, "contentBlockIndex"))); } void BedrockStreamImpl::flush_tool_call(int content_block_index) { @@ -177,44 +173,32 @@ void BedrockStreamImpl::flush_tool_call(int content_block_index) { StreamEvent(ToolCall(pending.id, pending.name, std::move(arguments)))); } -void BedrockStreamImpl::on_message_stop(const Model::MessageStopEvent& event) { - if (!event.StopReasonHasBeenSet()) { +void BedrockStreamImpl::on_message_stop(const nlohmann::json& event) { + message_stopped_ = true; + const auto& stop_reason = json_member(event, "stopReason"); + if (!stop_reason.is_string()) { return; } - switch (event.GetStopReason()) { - case Model::StopReason::max_tokens: - finish_reason_ = kFinishReasonLength; - break; - case Model::StopReason::content_filtered: - case Model::StopReason::guardrail_intervened: - finish_reason_ = kFinishReasonContentFilter; - break; - case Model::StopReason::tool_use: - finish_reason_ = kFinishReasonToolCalls; - break; - default: - finish_reason_ = kFinishReasonStop; - break; - } + finish_reason_ = + BedrockResponseParser::map_stop_reason(stop_reason.get()); } -void BedrockStreamImpl::on_metadata( - const Model::ConverseStreamMetadataEvent& event) { - if (!event.UsageHasBeenSet()) { +void BedrockStreamImpl::on_metadata(const nlohmann::json& event) { + const auto& usage = json_member(event, "usage"); + if (!usage.is_object()) { return; } - const auto& usage = event.GetUsage(); - usage_ = Usage(usage.GetInputTokens(), usage.GetOutputTokens()); + usage_ = Usage(json_int(json_member(usage, "inputTokens")), + json_int(json_member(usage, "outputTokens"))); } -void BedrockStreamImpl::on_error( - const Aws::BedrockRuntime::BedrockRuntimeError& error) { - ai::logger::log_error("Bedrock stream error: {} - {}", - error.GetExceptionName(), error.GetMessage()); - if (!error.GetExceptionName().empty()) { - push_error(error.GetExceptionName() + ": " + error.GetMessage()); +void BedrockStreamImpl::on_error(const TransportResponse& response) { + ai::logger::log_error("Bedrock stream error: {} - {}", response.error_name, + response.error_message); + if (!response.error_name.empty()) { + push_error(response.error_name + ": " + response.error_message); } else { - push_error("Stream error: " + error.GetMessage()); + push_error("Stream error: " + response.error_message); } } diff --git a/src/providers/bedrock/bedrock_stream.h b/src/providers/bedrock/bedrock_stream.h index baa5b0b..d01225b 100644 --- a/src/providers/bedrock/bedrock_stream.h +++ b/src/providers/bedrock/bedrock_stream.h @@ -1,6 +1,7 @@ #pragma once #include "ai/types/stream_result.h" +#include "bedrock_transport.h" #include #include @@ -13,23 +14,16 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include namespace ai { namespace bedrock { /// Implements streaming using the AWS Bedrock ConverseStream API. /// -/// The stream owns (shares) everything its background thread uses: the AWS -/// runtime client and the concurrency semaphore, so it may outlive the -/// `Client` that created it. +/// The stream owns (shares) everything its background thread uses: the +/// transport and the concurrency semaphore, so it may outlive the `Client` +/// that created it. class BedrockStreamImpl : public internal::StreamResultImpl { public: using Semaphore = std::counting_semaphore<>; @@ -43,12 +37,13 @@ class BedrockStreamImpl : public internal::StreamResultImpl { BedrockStreamImpl& operator=(BedrockStreamImpl&&) = delete; /// Start streaming on a background thread. + /// @param transport the runtime service of Bedrock + /// @param request a `ConverseStream` request /// @param semaphore Optional semaphore, already acquired by the caller, /// released when the stream completes - void start_stream( - std::shared_ptr client, - Aws::BedrockRuntime::Model::ConverseStreamRequest request, - std::shared_ptr semaphore = nullptr); + void start_stream(std::shared_ptr transport, + TransportRequest request, + std::shared_ptr semaphore = nullptr); /// Finish the stream immediately with an error event, without calling the /// API (used when the request is rejected before it is sent) @@ -66,21 +61,19 @@ class BedrockStreamImpl : public internal::StreamResultImpl { std::string input_json; }; - void run_stream( - std::shared_ptr client, - Aws::BedrockRuntime::Model::ConverseStreamRequest request); - - void on_content_block_start( - const Aws::BedrockRuntime::Model::ContentBlockStartEvent& event); - void on_content_block_delta( - const Aws::BedrockRuntime::Model::ContentBlockDeltaEvent& event); - void on_content_block_stop( - const Aws::BedrockRuntime::Model::ContentBlockStopEvent& event); - void on_message_stop( - const Aws::BedrockRuntime::Model::MessageStopEvent& event); - void on_metadata( - const Aws::BedrockRuntime::Model::ConverseStreamMetadataEvent& event); - void on_error(const Aws::BedrockRuntime::BedrockRuntimeError& error); + void run_stream(std::shared_ptr transport, + TransportRequest request); + + /// An event of the response stream: its type ("contentBlockDelta") and + /// its JSON. Does not throw. + void on_event(const std::string& type, const std::string& payload); + + void on_content_block_start(const nlohmann::json& event); + void on_content_block_delta(const nlohmann::json& event); + void on_content_block_stop(const nlohmann::json& event); + void on_message_stop(const nlohmann::json& event); + void on_metadata(const nlohmann::json& event); + void on_error(const TransportResponse& response); void push_event(StreamEvent event); void push_error(const std::string& message); @@ -103,6 +96,8 @@ class BedrockStreamImpl : public internal::StreamResultImpl { FinishReason finish_reason_ = kFinishReasonStop; std::optional usage_; bool errored_ = false; + // Whether `messageStop` has arrived: the end of a whole answer + bool message_stopped_ = false; }; } // namespace bedrock diff --git a/src/providers/bedrock/bedrock_transport.cpp b/src/providers/bedrock/bedrock_transport.cpp new file mode 100644 index 0000000..e367da2 --- /dev/null +++ b/src/providers/bedrock/bedrock_transport.cpp @@ -0,0 +1,574 @@ +#include "bedrock_transport.h" + +#include "ai/errors.h" +#include "aws_api_client.h" +#include "aws_sdk_manager.h" +#include "bedrock_credentials.h" +#include "bedrock_json.h" +#include "secure_logger.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +namespace { + +const char kAllocationTag[] = "BedrockTransport"; + +// The name that the requests of both services are signed for. It is also +// the name that the generated clients of both services look their endpoint +// settings up by, in the environment and in the profile +// (`AWS_ENDPOINT_URL_BEDROCK`). +const char kSigningName[] = "bedrock"; + +const char kJsonContentType[] = "application/json"; +const char kErrorTypeHeader[] = "x-amzn-errortype"; +const char kRequestIdHeader[] = "x-amzn-requestid"; + +// The headers of a message of an event stream +const char kMessageTypeHeader[] = ":message-type"; +const char kEventTypeHeader[] = ":event-type"; +const char kExceptionTypeHeader[] = ":exception-type"; +const char kErrorCodeHeader[] = ":error-code"; +const char kErrorMessageHeader[] = ":error-message"; + +// How much of a response stream is read at once +constexpr size_t kEventBufferSize = 8192; + +// How much of a response that is not a stream of events is kept, to tell what +// it was +constexpr size_t kMaxKeptBodySize = 64 * 1024; + +/// A member of a JSON object that is a string; empty otherwise +std::string string_member(const nlohmann::json& json, const char* name) { + return json_string(json_member(json, name)); +} + +/// An error of Amazon Bedrock: a JSON object with a `message`, named by a +/// header or by the `__type` member +ServiceError parse_bedrock_error(const std::string& body, + const Aws::Http::HttpResponse& response) { + ServiceError error; + const auto json = + nlohmann::json::parse(body, nullptr, /*allow_exceptions=*/false); + + // "ValidationException", which also comes as + // "ValidationException:http://internal.amazon.com/coral/..." and as + // "com.amazon.coral.validate#ValidationException" + error.name = response.HasHeader(kErrorTypeHeader) + ? std::string(response.GetHeader(kErrorTypeHeader)) + : string_member(json, "__type"); + if (const auto pound = error.name.find('#'); pound != std::string::npos) { + error.name.erase(0, pound + 1); + } + if (const auto colon = error.name.find(':'); colon != std::string::npos) { + error.name.erase(colon); + } + + error.message = string_member(json, "message"); + if (error.message.empty()) { + error.message = string_member(json, "Message"); + } + if (error.message.empty()) { + error.message = describe_unexpected_body(body); + } + + // The model did not answer in time. The service defines the error as one + // that is not repeated, while its HTTP status (408) is of those that are. + if (error.name == "ModelTimeoutException") { + error.retryable = false; + } + return error; +} + +/// Takes the messages of an event stream from the decoder of the AWS SDK: +/// gives the events to the handler of the caller, and keeps the error that +/// ends the stream +class EventDispatcher : public Aws::Utils::Event::EventStreamHandler { + public: + explicit EventDispatcher(const BedrockTransport::EventHandler& on_event) + : on_event_(on_event) {} + + void OnEvent() override { + if (failure_) { + return; + } + if (!*this) { + // The decoder could not read the stream: what it says about it is in + // the place of the payload + fail("", "Cannot read the stream of events: " + + std::string(GetEventPayloadAsString())); + return; + } + + const std::string message_type = header(kMessageTypeHeader); + if (message_type == "event") { + delivered_ = true; + // This is called from the C code of the decoder: an exception must not + // pass through it + try { + on_event_(header(kEventTypeHeader), + std::string(GetEventPayloadAsString())); + } catch (const std::exception& e) { + fail("", e.what()); + } + } else if (message_type == "exception" || message_type == "error") { + // An error that is modeled by the service has its name in + // `:exception-type` and its message in the JSON of the payload; any + // other one has them in the headers + std::string name = header(kErrorCodeHeader); + if (name.empty()) { + name = header(kExceptionTypeHeader); + } + std::string message = header(kErrorMessageHeader); + if (message.empty()) { + const std::string payload(GetEventPayloadAsString()); + message = string_member( + nlohmann::json::parse(payload, nullptr, /*allow_exceptions=*/false), + "message"); + if (message.empty()) { + message = describe_unexpected_body(payload); + } + } + fail(name, message); + } + // A message of another type is skipped, as the AWS SDK does + } + + /// An attempt of the request starts. What the previous attempt has + /// failed with does not count anymore: an error of a proxy, for one, which + /// an HTTP client writes to the stream as well, is not a stream of events, + /// and the decoder says so. + void start_attempt() { + if (delivered_) { + // A request whose events have been given out is not repeated (see + // `StreamedResponse`): another attempt would give them out once more + fail("", + "The stream of events was started again after a part of it had " + "been read"); + return; + } + failure_.reset(); + } + + /// The error that ended the stream, if one did + const std::optional& failure() const { return failure_; } + + /// Whether an event has been given out + bool delivered() const { return delivered_; } + + private: + std::string header(const char* name) { + const auto& headers = GetEventHeaders(); + const auto it = headers.find(name); + if (it == headers.end()) { + return {}; + } + return std::string(it->second.GetEventHeaderValueAsString()); + } + + void fail(const std::string& name, const std::string& message) { + failure_ = ServiceError{name, message, std::nullopt}; + } + + const BedrockTransport::EventHandler& on_event_; + std::optional failure_; + bool delivered_ = false; +}; + +/// What an HTTP client writes a response to, when it writes the response as +/// it arrives instead of giving a stream to read it from. What is written and +/// flushed goes to the decoder, so an event is given out as soon as it has +/// arrived: an HTTP client of the AWS SDK flushes every piece of a response +/// to a request for events. It does not flush the body of an error of the +/// service, which stays here and is read back as it is. The beginning of what +/// has gone to the decoder is read back as well until an event is found in +/// it: an error that the client did not recognize, such as the one of a +/// proxy, is not a stream of events. +/// +/// The stream of the AWS SDK for this (`EventDecoderStream`) gives back only +/// what the decoder has refused, and only what was flushed, so the body of +/// an error of the service is lost in it. +class EventStreamBuffer : public std::streambuf { + public: + EventStreamBuffer(Aws::Utils::Event::EventStreamDecoder& decoder, + const EventDispatcher& dispatcher) + : decoder_(decoder), dispatcher_(dispatcher), buffer_(kEventBufferSize) {} + + protected: + std::streamsize xsputn(const char* data, std::streamsize size) override { + pending_.append(data, static_cast(size)); + written_ += size; + return size; + } + + int_type overflow(int_type ch) override { + if (!traits_type::eq_int_type(ch, traits_type::eof())) { + pending_.push_back(traits_type::to_char_type(ch)); + ++written_; + } + return traits_type::not_eof(ch); + } + + int sync() override { + if (!dispatcher_.delivered() && kept_.size() < kMaxKeptBodySize) { + kept_.append(pending_, 0, kMaxKeptBodySize - kept_.size()); + } + + // What comes after an error of the stream is not read + char* piece = reinterpret_cast(buffer_.GetUnderlyingData()); + for (size_t pos = 0; pos < pending_.size() && !dispatcher_.failure();) { + const size_t size = std::min(kEventBufferSize, pending_.size() - pos); + std::memcpy(piece, pending_.data() + pos, size); + decoder_.Pump(buffer_, size); + pos += size; + } + pending_.clear(); + + if (dispatcher_.delivered()) { + kept_.clear(); + } + return 0; + } + + int_type underflow() override { + if (gptr() == egptr() && !read_started_) { + read_started_ = true; + kept_ += pending_; + pending_.clear(); + setg(kept_.data(), kept_.data(), kept_.data() + kept_.size()); + } + return gptr() == egptr() ? traits_type::eof() + : traits_type::to_int_type(*gptr()); + } + + /// An HTTP client asks where it writes to: how much it has written + pos_type seekoff(off_type offset, + std::ios_base::seekdir direction, + std::ios_base::openmode which) override { + if (offset == 0 && direction == std::ios_base::cur && + which == std::ios_base::out) { + return pos_type(written_); + } + return pos_type(off_type(-1)); + } + + private: + Aws::Utils::Event::EventStreamDecoder& decoder_; + const EventDispatcher& dispatcher_; + Aws::Utils::ByteBuffer buffer_; + std::string pending_; + std::string kept_; + off_type written_ = 0; + bool read_started_ = false; +}; + +class EventStream : public Aws::IOStream, public StreamedResponse { + public: + EventStream(Aws::Utils::Event::EventStreamDecoder& decoder, + const EventDispatcher& dispatcher) + : Aws::IOStream(nullptr), + dispatcher_(dispatcher), + buffer_(decoder, dispatcher) { + rdbuf(&buffer_); + } + + bool part_is_taken() const override { return dispatcher_.delivered(); } + + private: + const EventDispatcher& dispatcher_; + EventStreamBuffer buffer_; +}; + +/// Reads a response stream and decodes it, giving out every event as soon as +/// it has arrived +void pump_events(Aws::IOStream& stream, + Aws::Utils::Event::EventStreamDecoder& decoder, + const EventDispatcher& dispatcher, + const BedrockTransport::ContinueHandler& should_continue) { + Aws::Utils::ByteBuffer buffer(kEventBufferSize); + char* data = reinterpret_cast(buffer.GetUnderlyingData()); + + // `peek` waits for the next byte, and `readsome` takes what is already + // there: a plain `read` would wait until the buffer is full, and an event + // would be given out long after it has arrived. + while (!dispatcher.failure() && should_continue() && + stream.peek() != std::char_traits::eof()) { + std::streamsize size = + stream.readsome(data, static_cast(kEventBufferSize)); + if (size <= 0) { + // The stream does not tell how much of it is there. The byte that + // `peek` has seen is. + stream.read(data, 1); + size = stream.gcount(); + if (size <= 0) { + break; + } + } + decoder.Pump(buffer, static_cast(size)); + } +} + +/// What a request ended with, without the body of the response +TransportResponse to_response(const Aws::Client::StreamOutcome& outcome) { + TransportResponse response; + if (outcome.IsSuccess()) { + const auto& result = outcome.GetResult(); + response.success = true; + response.status = static_cast(result.GetResponseCode()); + const auto& headers = result.GetHeaderValueCollection(); + if (const auto it = headers.find(kRequestIdHeader); it != headers.end()) { + response.request_id = it->second; + } + return response; + } + + const auto& error = outcome.GetError(); + // The code of a request that got no response is a negative one + response.status = std::max(0, static_cast(error.GetResponseCode())); + response.error_name = error.GetExceptionName(); + response.error_message = error.GetMessage(); + response.retryable = error.ShouldRetry(); + response.request_id = error.GetRequestId(); + return response; +} + +class AwsBedrockTransport : public BedrockTransport { + public: + AwsBedrockTransport(std::shared_ptr client, + Aws::Http::URI endpoint) + : client_(std::move(client)), endpoint_(std::move(endpoint)) {} + + TransportResponse send(const TransportRequest& request) override { + const SerializedRequest aws_request(request.operation, request.body, + kJsonContentType); + auto outcome = + client_->send(make_uri(request), aws_request, + request.method == TransportRequest::Method::kGet + ? Aws::Http::HttpMethod::HTTP_GET + : Aws::Http::HttpMethod::HTTP_POST); + TransportResponse response = to_response(outcome); + if (response.success) { + response.body = + read_body(outcome.GetResult().GetPayload().GetUnderlyingStream()); + } + return response; + } + + TransportResponse send_for_events( + const TransportRequest& request, + const EventHandler& on_event, + const ContinueHandler& should_continue) override { + // The response is destroyed before the decoder that its stream writes to + EventDispatcher dispatcher(on_event); + Aws::Utils::Event::EventStreamDecoder decoder(&dispatcher); + + SerializedRequest aws_request(request.operation, request.body, + kJsonContentType, + /*event_stream_response=*/true); + // An HTTP client that writes the response as it arrives writes it to the + // stream that the request gives it: this one decodes what is written to + // it. A request that is repeated starts a new stream, and the decoder is + // put to the start of a message: the previous attempt may have ended in + // the middle of one. + aws_request.SetResponseStreamFactory([&decoder, &dispatcher] { + decoder.Reset(); + decoder.ResetEventStreamHandler(&dispatcher); + dispatcher.start_attempt(); + return Aws::New(kAllocationTag, decoder, dispatcher); + }); + aws_request.SetContinueRequestHandler( + [&should_continue](const Aws::Http::HttpRequest*) { + return should_continue(); + }); + + auto outcome = client_->send(make_uri(request), aws_request, + Aws::Http::HttpMethod::HTTP_POST); + if (outcome.IsSuccess()) { + Aws::IOStream& body = + outcome.GetResult().GetPayload().GetUnderlyingStream(); + if (dynamic_cast(&body) != nullptr) { + // What the HTTP client has written and not flushed + body.flush(); + } else { + // An HTTP client of the application may instead return as soon as it + // has the headers, with a stream of its own to read the body from. + // Then the body is still to be read. + pump_events(body, decoder, dispatcher, should_continue); + } + } + + TransportResponse response = to_response(outcome); + if (response.success && dispatcher.failure()) { + response.success = false; + response.error_name = dispatcher.failure()->name; + response.error_message = dispatcher.failure()->message; + } + return response; + } + + private: + Aws::Http::URI make_uri(const TransportRequest& request) const { + Aws::Http::URI uri = endpoint_; + // Everything but the unreserved characters of RFC 3986 is encoded, the + // colon and the slash of a model identifier too. By default the AWS SDK + // leaves the colon as it is and signs the path so: an HTTP client of the + // application that encodes the path itself, with the colon, would then + // send another path than the signed one, and the service would refuse + // the signature. + uri.SetRfc3986Encoded(true); + for (const auto& segment : request.path) { + uri.AddPathSegment(Aws::String(segment)); + } + for (const auto& [name, value] : request.query) { + uri.AddQueryStringParameter(name.c_str(), Aws::String(value)); + } + return uri; + } + + std::shared_ptr client_; + Aws::Http::URI endpoint_; +}; + +/// The endpoint of a service, by the endpoint rules that the AWS SDK has for +/// it: the endpoint that the configuration, the environment or the profile +/// sets, or the one of the Region (with its FIPS and dual-stack variants, +/// in the partition of the Region) +template +Aws::Http::URI resolve_endpoint( + const Aws::Client::ClientConfiguration& configuration) { + EndpointProvider provider; + provider.InitBuiltInParameters(ServiceConfiguration(configuration), + kSigningName); + const auto outcome = provider.ResolveEndpoint({}); + if (!outcome.IsSuccess()) { + throw ConfigurationError("Cannot find the endpoint of Amazon Bedrock: " + + std::string(outcome.GetError().GetMessage())); + } + return outcome.GetResult().GetURI(); +} + +/// Makes the credentials that sign the requests, for the Region of the +/// transports. It is not called when the requests carry an API key. +using CredentialsProviderFactory = + std::function( + const std::string& region)>; + +BedrockTransports make_transports_with( + const BedrockConfig& config, + const CredentialsProviderFactory& make_credentials) { + ensure_aws_sdk_initialized(config); + + BedrockTransports transports; + transports.region = + config.region.empty() ? get_region_from_env() : config.region; + if (transports.region.empty()) { + throw ConfigurationError( + "AWS region not configured. Set AWS_REGION environment variable or " + "provide region in BedrockConfig."); + } + + Aws::Client::ClientConfiguration control_plane_config( + client_configuration_with_known_region()); + control_plane_config.region = transports.region; + control_plane_config.connectTimeoutMs = + static_cast(config.security.connection_timeout.count() * 1000); + control_plane_config.requestTimeoutMs = + static_cast(config.security.request_timeout.count() * 1000); + // A redirect is not followed. Amazon Bedrock answers at the endpoint that + // it is asked at, and an HTTP client that follows a redirect repeats the + // request, with its API key or its signed headers and with the + // conversation, at whatever address the answer names: another host, or a + // connection without TLS, where the signer would not have sent the API key + control_plane_config.followRedirects = + Aws::Client::FollowRedirectsPolicy::NEVER; + + // `endpoint_override` is the endpoint of the runtime (a VPC endpoint, or a + // local one in a test), not of the control plane that lists the models + Aws::Client::ClientConfiguration runtime_config(control_plane_config); + if (!config.endpoint_override.empty()) { + runtime_config.endpointOverride = config.endpoint_override; + } + + // One identity for both services: the API key of Bedrock, or credentials + // to sign the requests with + std::shared_ptr signer; + if (uses_bedrock_api_key(config)) { + SecureLogger::log_debug("Using the API key of Amazon Bedrock"); + signer = Aws::MakeShared( + kAllocationTag, make_api_key_provider()); + } else { + signer = Aws::MakeShared( + kAllocationTag, make_credentials(transports.region), kSigningName, + Aws::Region::ComputeSignerRegion(Aws::String(transports.region))); + } + + transports.runtime = std::make_shared( + Aws::MakeShared(kAllocationTag, runtime_config, signer, + "Bedrock Runtime", parse_bedrock_error), + resolve_endpoint< + Aws::BedrockRuntime::Endpoint::BedrockRuntimeEndpointProvider, + Aws::BedrockRuntime::BedrockRuntimeClientConfiguration>( + runtime_config)); + transports.control_plane = std::make_shared( + Aws::MakeShared(kAllocationTag, control_plane_config, + signer, "Bedrock", parse_bedrock_error), + resolve_endpoint( + control_plane_config)); + return transports; +} + +} // namespace + +// The two functions below differ in where the credentials come from, and +// only the first one refers to the credential chain of the AWS SDK (through +// `make_credentials_provider`). Keep it so: the chain brings a lot of code +// with it, which an application that supplies the credentials should not +// have to link. + +BedrockTransports make_transports(const BedrockConfig& config) { + // A role, a web identity, a profile, or the default credential chain + return make_transports_with(config, [&config](const std::string& region) { + return make_credentials_provider(config, region); + }); +} + +BedrockTransports make_transports(const BedrockConfig& config, + AwsCredentialsSource credentials) { + if (!credentials) { + throw ConfigurationError( + "The source of the AWS credentials of the application is empty"); + } + // These tell the provider what identity to find, which it does not do + // here. Ignoring them would sign the requests as someone else than asked. + if (!config.profile.empty() || !config.role_arn.empty() || + !config.web_identity_token_file.empty()) { + throw ConfigurationError( + "`profile`, `role_arn` and `web_identity_token_file` of BedrockConfig " + "cannot be used together with the credentials of the application"); + } + return make_transports_with(config, [&credentials](const std::string&) { + return make_application_credentials_provider(std::move(credentials)); + }); +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_transport.h b/src/providers/bedrock/bedrock_transport.h new file mode 100644 index 0000000..91665cc --- /dev/null +++ b/src/providers/bedrock/bedrock_transport.h @@ -0,0 +1,103 @@ +#pragma once + +#include "ai/bedrock.h" + +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +/// A request to a service of Amazon Bedrock +struct TransportRequest { + enum class Method { kGet, kPost }; + + /// The name of the operation ("Converse"): it names the request in the + /// logs and in the traces of the AWS SDK + std::string operation; + Method method = Method::kPost; + /// The path, one segment at a time. A segment is escaped as a whole, so the + /// ARN of an inference profile, with its `/`, stays one segment. + std::vector path; + /// The parameters of the query string, in the order they are sent in + std::vector> query; + /// The JSON of the request; empty when the request has no body + std::string body; +}; + +/// What a request ended with +struct TransportResponse { + bool success = false; + /// The HTTP status; 0 when there was no response + int status = 0; + /// The body of a successful response. Empty for a response that is a stream + /// of events: the events were given to the handler. + std::string body; + /// Of a failure: the name that the service gives to the error + /// ("ThrottlingException"; empty when it has none), what the error says, + /// and whether the same request can succeed later + std::string error_name; + std::string error_message; + bool retryable = false; + std::string request_id; +}; + +/// Sends requests to one service of Amazon Bedrock: finds its endpoint, +/// authorizes the requests, repeats the ones that can be repeated. +/// +/// The rest of the provider speaks JSON to this interface and knows nothing +/// of the AWS SDK, so it is tested without it. +class BedrockTransport { + public: + /// Takes an event of a response stream: the type of the event + /// ("contentBlockDelta") and its JSON. Must not throw. + using EventHandler = + std::function; + /// Whether to go on with a request; asked while a response is read + using ContinueHandler = std::function; + + virtual ~BedrockTransport() = default; + + virtual TransportResponse send(const TransportRequest& request) = 0; + + /// Sends a request whose response is a stream of events, and gives every + /// event to `on_event` as it arrives, on the calling thread. Returns when + /// the stream ends. An error that the service reports inside the stream + /// makes the response a failed one. + virtual TransportResponse send_for_events( + const TransportRequest& request, + const EventHandler& on_event, + const ContinueHandler& should_continue) = 0; +}; + +/// The two services that the provider asks: the runtime (`Converse`, +/// `ConverseStream`) and the control plane (the lists of the models and of +/// the inference profiles). They have endpoints of their own, and take the +/// same identity. +struct BedrockTransports { + std::shared_ptr runtime; + std::shared_ptr control_plane; + /// The Region of the configuration, or of the environment + std::string region; +}; + +/// The transports over the AWS SDK for C++, with the identity that the +/// configuration names, or that the AWS SDK finds. +/// @throws ConfigurationError if the Region is not known, or the identity of +/// the configuration cannot be used +BedrockTransports make_transports(const BedrockConfig& config); + +/// The transports over the AWS SDK for C++, with the credentials that the +/// application supplies. Nothing here refers to the credential chain of the +/// AWS SDK, so an application that calls only this one does not link it. +/// @throws ConfigurationError if the Region is not known, the source is +/// empty or has no credentials, or the configuration names an +/// identity +BedrockTransports make_transports(const BedrockConfig& config, + AwsCredentialsSource credentials); + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/credential_redactor.cpp b/src/providers/bedrock/credential_redactor.cpp index ca6bba6..3519ade 100644 --- a/src/providers/bedrock/credential_redactor.cpp +++ b/src/providers/bedrock/credential_redactor.cpp @@ -6,30 +6,47 @@ namespace ai { namespace bedrock { namespace { +// The patterns are built on first use, not before `main`: a program that +// links the provider and never logs does not pay for them. + // AWS Access Key ID pattern: AKIA followed by 16 alphanumeric characters // Also matches ASIA (temporary credentials) and AIDA (IAM user IDs) -const std::regex kAccessKeyIdPattern(R"((A[KS]IA|AIDA)[A-Z0-9]{16})"); +const std::regex& access_key_id_pattern() { + static const std::regex pattern(R"((A[KS]IA|AIDA)[A-Z0-9]{16})"); + return pattern; +} -// AWS Secret Access Key pattern: 40 character base64-like string -// Note: We use a simpler pattern since std::regex doesn't support lookbehind -// This is used in context-aware redaction only -const std::regex kSecretKeyPattern(R"([A-Za-z0-9+/]{40})"); +// AWS Secret Access Key in a credential context, like +// "SecretAccessKey": "..." or secret_access_key=...: a 40 character +// base64-like string alone would match too much +const std::regex& secret_key_in_context_pattern() { + static const std::regex pattern( + R"((secret[_-]?access[_-]?key|SecretAccessKey)\s*[=:"']\s*([A-Za-z0-9+/]{40}))", + std::regex::icase); + return pattern; +} // AWS Session Token pattern: Long base64 string (typically 300+ chars) // Session tokens start with specific patterns -const std::regex kSessionTokenPattern( - R"((FwoGZXIvYXdzE|IQoJb3JpZ2luX2Vj)[A-Za-z0-9+/=]{100,})"); +const std::regex& session_token_pattern() { + static const std::regex pattern( + R"((FwoGZXIvYXdzE|IQoJb3JpZ2luX2Vj)[A-Za-z0-9+/=]{100,})"); + return pattern; +} // AWS Account ID in ARN context: 12 digit number after arn:aws:...: -const std::regex kAccountIdInArnPattern( - R"((arn:aws:[a-z0-9-]+:[a-z0-9-]*:)([0-9]{12})(:))"); - -// Generic 12-digit account ID pattern (more aggressive) -const std::regex kAccountIdPattern(R"(\b[0-9]{12}\b)"); +const std::regex& account_id_in_arn_pattern() { + static const std::regex pattern( + R"((arn:aws:[a-z0-9-]+:[a-z0-9-]*:)([0-9]{12})(:))"); + return pattern; +} // AWS credentials in environment variable format -const std::regex kEnvCredentialPattern( - R"((AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|aws_secret_access_key|aws_session_token)\s*[=:]\s*([^\s'"]+))"); +const std::regex& env_credential_pattern() { + static const std::regex pattern( + R"((AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|aws_secret_access_key|aws_session_token)\s*[=:]\s*([^\s'"]+))"); + return pattern; +} } // namespace @@ -47,7 +64,7 @@ std::string CredentialRedactor::redact(const std::string& input) { result = redact_account_id(result); // Redact credentials in environment variable format - result = std::regex_replace(result, kEnvCredentialPattern, + result = std::regex_replace(result, env_credential_pattern(), "$1=" + std::string(kRedactedPlaceholder)); return result; @@ -59,16 +76,16 @@ bool CredentialRedactor::contains_sensitive_data(const std::string& input) { } // Check for any sensitive patterns - if (std::regex_search(input, kAccessKeyIdPattern)) { + if (std::regex_search(input, access_key_id_pattern())) { return true; } - if (std::regex_search(input, kSessionTokenPattern)) { + if (std::regex_search(input, session_token_pattern())) { return true; } - if (std::regex_search(input, kAccountIdInArnPattern)) { + if (std::regex_search(input, account_id_in_arn_pattern())) { return true; } - if (std::regex_search(input, kEnvCredentialPattern)) { + if (std::regex_search(input, env_credential_pattern())) { return true; } @@ -78,32 +95,25 @@ bool CredentialRedactor::contains_sensitive_data(const std::string& input) { } std::string CredentialRedactor::redact_access_key_id(const std::string& input) { - return std::regex_replace(input, kAccessKeyIdPattern, kRedactedPlaceholder); + return std::regex_replace(input, access_key_id_pattern(), + kRedactedPlaceholder); } std::string CredentialRedactor::redact_secret_key(const std::string& input) { // Be more conservative with secret key detection to avoid false positives // Only redact if it appears to be in a credential context - std::string result = input; - - // Look for patterns like "SecretAccessKey": "..." or secret_access_key=... - std::regex secret_context_pattern( - R"((secret[_-]?access[_-]?key|SecretAccessKey)\s*[=:"']\s*([A-Za-z0-9+/]{40}))", - std::regex::icase); - - result = std::regex_replace(result, secret_context_pattern, - "$1" + std::string(kRedactedPlaceholder)); - - return result; + return std::regex_replace(input, secret_key_in_context_pattern(), + "$1" + std::string(kRedactedPlaceholder)); } std::string CredentialRedactor::redact_session_token(const std::string& input) { - return std::regex_replace(input, kSessionTokenPattern, kRedactedPlaceholder); + return std::regex_replace(input, session_token_pattern(), + kRedactedPlaceholder); } std::string CredentialRedactor::redact_account_id(const std::string& input) { // Only redact account IDs in ARN context to avoid false positives - return std::regex_replace(input, kAccountIdInArnPattern, + return std::regex_replace(input, account_id_in_arn_pattern(), "$1" + std::string(kRedactedPlaceholder) + "$3"); } diff --git a/src/providers/bedrock/input_validator.cpp b/src/providers/bedrock/input_validator.cpp index 3dbb8a5..41ed57a 100644 --- a/src/providers/bedrock/input_validator.cpp +++ b/src/providers/bedrock/input_validator.cpp @@ -1,45 +1,11 @@ #include "input_validator.h" #include -#include #include namespace ai { namespace bedrock { -namespace { -// Model ID patterns for validation -// Standard Bedrock model ID: provider.model-name-version -// Examples: anthropic.claude-3-5-sonnet-20241022-v2:0, -// amazon.titan-text-express-v1 -const std::regex kStandardModelIdPattern( - R"(^[a-z0-9-]+\.[a-z0-9-]+(-[a-z0-9]+)*(-v[0-9]+)?(:[0-9]+)?$)", - std::regex::icase); - -// Cross-region inference profile format: geo.provider.model-name-version -// Examples: us.anthropic.claude-sonnet-5-5, eu.anthropic.claude-opus-5-5, -// apac.anthropic.claude-haiku-5-5, global.anthropic.claude-fable-5-2 -const std::regex kInferenceProfilePattern( - R"(^[a-z]{2,6}\.[a-z0-9-]+\.[a-z0-9-]+(-[a-z0-9]+)*(-v[0-9]+)?(:[0-9]+)?$)", - std::regex::icase); - -// ARN format for custom/fine-tuned models -// Example: arn:aws:bedrock:us-east-1:123456789012:custom-model/my-model -const std::regex kArnModelIdPattern( - R"(^arn:aws:bedrock:[a-z0-9-]+:[0-9]+:(custom-model|provisioned-model|foundation-model)/[a-zA-Z0-9-_/]+$)"); - -// Provisioned throughput ARN format -const std::regex kProvisionedArnPattern( - R"(^arn:aws:bedrock:[a-z0-9-]+:[0-9]+:provisioned-model-throughput/[a-zA-Z0-9-_]+$)"); - -// Inference profile ARN format -// Example: -// arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.anthropic.claude-3-5-sonnet-v1:0 -const std::regex kInferenceProfileArnPattern( - R"(^arn:aws:bedrock:[a-z0-9-]+:[0-9]+:inference-profile/[a-zA-Z0-9-_.:/]+$)"); - -} // namespace - InputValidator::InputValidator() : config_() {} InputValidator::InputValidator(const SecurityConfig& config) @@ -102,36 +68,13 @@ std::optional InputValidator::validate( } bool InputValidator::is_valid_model_id(const std::string& model_id) const { - if (model_id.empty()) { - return false; - } - - // Check standard Bedrock model ID format - if (std::regex_match(model_id, kStandardModelIdPattern)) { - return true; - } - - // Check cross-region inference profile format (e.g., us.anthropic.claude-...) - if (std::regex_match(model_id, kInferenceProfilePattern)) { - return true; - } - - // Check ARN format for custom models - if (std::regex_match(model_id, kArnModelIdPattern)) { - return true; - } - - // Check provisioned throughput ARN format - if (std::regex_match(model_id, kProvisionedArnPattern)) { - return true; - } - - // Check inference profile ARN format - if (std::regex_match(model_id, kInferenceProfileArnPattern)) { - return true; - } - - return false; + // A model ID, the ID of an inference profile or an ARN: which of them + // exist, and in which form, is for Bedrock to say. Only what cannot be an + // identifier at all is refused here: an empty one, and one with whitespace, + // control or non-ASCII characters. + return !model_id.empty() && + std::all_of(model_id.begin(), model_id.end(), + [](unsigned char c) { return c > 0x20 && c < 0x7F; }); } bool InputValidator::is_valid_max_tokens(int max_tokens) const { diff --git a/src/providers/bedrock/input_validator.h b/src/providers/bedrock/input_validator.h index 81f91a1..8871e4e 100644 --- a/src/providers/bedrock/input_validator.h +++ b/src/providers/bedrock/input_validator.h @@ -6,7 +6,6 @@ #include #include -#include #include namespace ai { @@ -26,10 +25,11 @@ class InputValidator { /// @return std::nullopt if valid, error message string if invalid std::optional validate(const GenerateOptions& options) const; - /// Validate model ID format - /// Accepts: provider.model-name-version patterns and ARN formats + /// Check that a model ID can be an identifier: it is not empty and has no + /// whitespace, control or non-ASCII characters. The form is not checked: + /// Bedrock says whether it has such a model, inference profile or ARN. /// @param model_id The model identifier to validate - /// @return true if valid format + /// @return true if it can be sent to Bedrock bool is_valid_model_id(const std::string& model_id) const; /// Validate max_tokens is positive (the upper bound depends on the model and diff --git a/src/providers/bedrock/model_discovery.cpp b/src/providers/bedrock/model_discovery.cpp index a8fc63b..aed0d4a 100644 --- a/src/providers/bedrock/model_discovery.cpp +++ b/src/providers/bedrock/model_discovery.cpp @@ -1,21 +1,12 @@ #include "model_discovery.h" -#include "ai/bedrock.h" -#include "ai/errors.h" -#include "aws_sdk_manager.h" -#include "bedrock_credentials.h" +#include "bedrock_json.h" #include "secure_logger.h" #include -#include -#include - -#include -#include -#include -#include -#include -#include +#include +#include +#include namespace ai { namespace bedrock { @@ -32,57 +23,179 @@ std::string extract_provider(const std::string& model_id) { return "unknown"; } -} // namespace - -ModelDiscovery::ModelDiscovery(const BedrockConfig& config) { - // Ensure AWS SDK is initialized before creating any AWS clients - ensure_aws_sdk_initialized(); - initialize_client(config); +/// Whether a JSON array has a string +bool contains_string(const nlohmann::json& array, const char* value) { + return array.is_array() && std::any_of(array.begin(), array.end(), + [&](const nlohmann::json& item) { + return item.is_string() && + json_string(item) == value; + }); } -ModelDiscovery::~ModelDiscovery() = default; - -void ModelDiscovery::initialize_client(const BedrockConfig& config) { - // Resolve region - region_ = config.region; - if (region_.empty()) { - region_ = get_region_from_env(); +/// Calls an operation of the control plane that lists something, and +/// returns the JSON object of its response. +/// @throws std::runtime_error with the name of the operation, which tells +/// what permission is missing +nlohmann::json call_list_operation( + BedrockTransport& control_plane, + const std::string& operation, + const std::string& path, + std::vector> query) { + TransportRequest request; + request.operation = operation; + request.method = TransportRequest::Method::kGet; + request.path = {path}; + request.query = std::move(query); + + const auto response = control_plane.send(request); + if (!response.success) { + std::string message = operation + ": "; + if (!response.error_name.empty()) { + message += response.error_name + ": "; + } + throw std::runtime_error(message + response.error_message); } - if (region_.empty()) { - throw ConfigurationError( - "AWS region not configured for model discovery. Set AWS_REGION " - "environment variable or provide region in BedrockConfig."); + auto json = + nlohmann::json::parse(response.body, nullptr, /*allow_exceptions=*/false); + if (!json.is_object()) { + throw std::runtime_error(operation + ": the response is not a JSON object"); } - - // Configure AWS client. `endpoint_override` is not applied: it is the - // endpoint of the Bedrock runtime service, not of the Bedrock control plane - // that lists the models. - Aws::Client::ClientConfiguration client_config; - client_config.region = region_; - client_config.connectTimeoutMs = - static_cast(config.security.connection_timeout.count() * 1000); - client_config.requestTimeoutMs = - static_cast(config.security.request_timeout.count() * 1000); - - // The same identity as `BedrockClient` (role, web identity, profile, or the - // default chain) - auto credentials_provider = make_credentials_provider(config, region_); - - // Create Bedrock client (not BedrockRuntime - this is for management APIs) - client_ = std::make_shared(credentials_provider, - client_config); - - SecureLogger::log_debug("ModelDiscovery initialized for region: " + region_); + return json; } +} // namespace + +ModelDiscovery::ModelDiscovery(std::shared_ptr control_plane) + : control_plane_(std::move(control_plane)) {} + std::vector ModelDiscovery::list_models() { - auto models = fetch_models_from_api(); + nlohmann::json listed; + try { + listed = call_list_operation(*control_plane_, "ListFoundationModels", + "foundation-models", {}); + } catch (const std::exception& e) { + SecureLogger::log_error("Failed to list foundation models: " + + std::string(e.what())); + throw std::runtime_error("Failed to list foundation models: " + + std::string(e.what())); + } + + std::vector models; + const auto& summaries = json_member(listed, "modelSummaries"); + if (summaries.is_array()) { + for (const auto& summary : summaries) { + ModelInfo info; + info.model_id = json_string(json_member(summary, "modelId")); + info.provider = extract_provider(info.model_id); + info.name = json_string(json_member(summary, "modelName")); + + // Check streaming support + info.supports_streaming = + json_bool(json_member(summary, "responseStreamingSupported")); + + // Check for system prompt support (inferred from input modalities) + const auto& input_modalities = json_member(summary, "inputModalities"); + info.supports_system_prompt = contains_string(input_modalities, "TEXT"); + + // Build capabilities list + if (input_modalities.is_array()) { + for (const auto& modality : input_modalities) { + const std::string name = json_string(modality); + if (name == "TEXT") { + info.capabilities.push_back("text"); + } else if (name == "IMAGE") { + info.capabilities.push_back("image"); + } else if (name == "EMBEDDING") { + info.capabilities.push_back("embedding"); + } + } + } + + models.push_back(std::move(info)); + } + } + SecureLogger::log_info("Fetched " + std::to_string(models.size()) + " models from Bedrock API"); return models; } +std::vector ModelDiscovery::list_converse_model_ids() { + // The models that output text. Without `byInferenceType`: a model that is + // not invoked on demand by its own ID is the one an inference profile is + // for. + const auto listed_models = + call_list_operation(*control_plane_, "ListFoundationModels", + "foundation-models", {{"byOutputModality", "TEXT"}}); + + std::set text_models; + std::vector on_demand_models; + const auto& model_summaries = json_member(listed_models, "modelSummaries"); + if (model_summaries.is_array()) { + for (const auto& summary : model_summaries) { + const std::string model_id = json_string(json_member(summary, "modelId")); + if (model_id.empty()) { + continue; + } + text_models.insert(model_id); + if (contains_string(json_member(summary, "inferenceTypesSupported"), + "ON_DEMAND")) { + on_demand_models.push_back(model_id); + } + } + } + + // A profile names its models by ARN: + // "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-...". + const auto is_text_model = [&text_models](const nlohmann::json& model) { + const std::string model_arn = json_string(json_member(model, "modelArn")); + const auto slash = model_arn.rfind('/'); + return slash != std::string::npos && + text_models.count(model_arn.substr(slash + 1)) != 0; + }; + + std::vector ids; + std::string next_token; + do { + std::vector> query; + if (!next_token.empty()) { + query.emplace_back("nextToken", next_token); + } + query.emplace_back("type", "SYSTEM_DEFINED"); + const auto listed_profiles = + call_list_operation(*control_plane_, "ListInferenceProfiles", + "inference-profiles", std::move(query)); + + const auto& profile_summaries = + json_member(listed_profiles, "inferenceProfileSummaries"); + if (profile_summaries.is_array()) { + for (const auto& profile : profile_summaries) { + if (json_string(json_member(profile, "status")) != "ACTIVE") { + continue; + } + const auto& profile_models = json_member(profile, "models"); + const std::string profile_id = + json_string(json_member(profile, "inferenceProfileId")); + if (!profile_id.empty() && profile_models.is_array() && + std::any_of(profile_models.begin(), profile_models.end(), + is_text_model)) { + ids.push_back(profile_id); + } + } + } + next_token = json_string(json_member(listed_profiles, "nextToken")); + } while (!next_token.empty()); + + SecureLogger::log_info("Fetched " + std::to_string(ids.size()) + + " inference profiles and " + + std::to_string(on_demand_models.size()) + + " on-demand models from Bedrock API"); + + ids.insert(ids.end(), on_demand_models.begin(), on_demand_models.end()); + return ids; +} + bool ModelDiscovery::is_model_accessible(const std::string& model_id) { auto models = list_models(); @@ -101,62 +214,5 @@ bool ModelDiscovery::is_model_accessible(const std::string& model_id) { }); } -std::vector ModelDiscovery::fetch_models_from_api() { - std::vector models; - - Aws::Bedrock::Model::ListFoundationModelsRequest request; - - auto outcome = client_->ListFoundationModels(request); - - if (!outcome.IsSuccess()) { - const auto& error = outcome.GetError(); - SecureLogger::log_error( - "Failed to list foundation models: " + error.GetExceptionName() + - " - " + error.GetMessage()); - throw std::runtime_error("Failed to list foundation models: " + - error.GetMessage()); - } - - const auto& result = outcome.GetResult(); - - for (const auto& model_summary : result.GetModelSummaries()) { - ModelInfo info; - info.model_id = model_summary.GetModelId(); - info.provider = extract_provider(info.model_id); - info.name = model_summary.GetModelName(); - - // Check streaming support - info.supports_streaming = model_summary.GetResponseStreamingSupported(); - - // Check for system prompt support (inferred from input modalities) - const auto& input_modalities = model_summary.GetInputModalities(); - info.supports_system_prompt = - std::find(input_modalities.begin(), input_modalities.end(), - Aws::Bedrock::Model::ModelModality::TEXT) != - input_modalities.end(); - - // Build capabilities list - for (const auto& modality : input_modalities) { - switch (modality) { - case Aws::Bedrock::Model::ModelModality::TEXT: - info.capabilities.push_back("text"); - break; - case Aws::Bedrock::Model::ModelModality::IMAGE: - info.capabilities.push_back("image"); - break; - case Aws::Bedrock::Model::ModelModality::EMBEDDING: - info.capabilities.push_back("embedding"); - break; - default: - break; - } - } - - models.push_back(std::move(info)); - } - - return models; -} - } // namespace bedrock } // namespace ai diff --git a/src/providers/bedrock/model_discovery.h b/src/providers/bedrock/model_discovery.h index 18d774e..dfae333 100644 --- a/src/providers/bedrock/model_discovery.h +++ b/src/providers/bedrock/model_discovery.h @@ -1,51 +1,42 @@ #pragma once -#include "ai/bedrock.h" // For SecurityConfig, BedrockConfig, ModelInfo +#include "ai/bedrock.h" // For ModelInfo +#include "bedrock_transport.h" -#include #include -#include #include #include -// Forward declarations for AWS SDK types -namespace Aws { -namespace Bedrock { -class BedrockClient; -} -} // namespace Aws - namespace ai { namespace bedrock { /// Lists the foundation models available in a Region class ModelDiscovery { public: - /// Create model discovery with configuration - explicit ModelDiscovery(const BedrockConfig& config); - - /// Destructor - ~ModelDiscovery(); + /// @param control_plane the control plane service of Bedrock + explicit ModelDiscovery(std::shared_ptr control_plane); /// List available models (calls `ListFoundationModels`) /// @return Vector of ModelInfo for available models /// @throws std::runtime_error if API call fails std::vector list_models(); + /// The IDs that the Converse API can be asked with on demand: the + /// system-defined inference profiles of the models that output text + /// (`ListInferenceProfiles`), followed by the models that output text and + /// are invoked on demand by their own IDs (`ListFoundationModels`). A + /// current model is usually invoked through an inference profile only, and + /// its own ID is refused. Model access grants are not checked. + /// @throws std::runtime_error if an API call fails + std::vector list_converse_model_ids(); + /// Check if a specific model is accessible /// @param model_id The model identifier to check /// @return true if model is in the available list bool is_model_accessible(const std::string& model_id); private: - /// Fetch models from AWS API - std::vector fetch_models_from_api(); - - /// Initialize the Bedrock client - void initialize_client(const BedrockConfig& config); - - std::shared_ptr client_; - std::string region_; + std::shared_ptr control_plane_; }; } // namespace bedrock diff --git a/src/providers/bedrock/sts_endpoint.cpp b/src/providers/bedrock/sts_endpoint.cpp new file mode 100644 index 0000000..49fac34 --- /dev/null +++ b/src/providers/bedrock/sts_endpoint.cpp @@ -0,0 +1,98 @@ +#include "sts_endpoint.h" + +#include "ai/errors.h" +#include "bedrock_json.h" + +#include + +namespace ai { +namespace bedrock { + +namespace { + +/// The partition of a Region: the one that lists the Region, or else the one +/// whose Regions are named like it, or else `aws`. This is the order in which +/// the endpoint rules of AWS find it (`aws.partition`). +const nlohmann::json& find_partition(const nlohmann::json& partitions, + const std::string& region) { + for (const auto& partition : partitions) { + if (json_member(partition, "regions").contains(region)) { + return partition; + } + } + for (const auto& partition : partitions) { + const std::string pattern = + json_string(json_member(partition, "regionRegex")); + if (!pattern.empty() && std::regex_match(region, std::regex(pattern))) { + return partition; + } + } + for (const auto& partition : partitions) { + if (json_string(json_member(partition, "id")) == "aws") { + return partition; + } + } + throw ConfigurationError("Cannot find the partition of AWS for the region " + + region); +} + +} // namespace + +std::string make_sts_endpoint(const std::string& partitions, + const std::string& region, + bool use_fips, + bool use_dual_stack) { + const auto json = + nlohmann::json::parse(partitions, nullptr, /*allow_exceptions=*/false); + const auto& outputs = json_member( + find_partition(json_member(json, "partitions"), region), "outputs"); + const std::string name = json_string(json_member(outputs, "name")); + const std::string dns_suffix = json_string(json_member(outputs, "dnsSuffix")); + const std::string dual_stack_dns_suffix = + json_string(json_member(outputs, "dualStackDnsSuffix")); + if (dns_suffix.empty()) { + throw ConfigurationError( + "Cannot find the endpoint of AWS STS for the region " + region); + } + + const bool has_fips = json_bool(json_member(outputs, "supportsFIPS")); + const bool has_dual_stack = + json_bool(json_member(outputs, "supportsDualStack")) && + !dual_stack_dns_suffix.empty(); + + if (use_fips && use_dual_stack) { + if (!has_fips || !has_dual_stack) { + throw ConfigurationError( + "FIPS and dual-stack endpoints are asked for, and AWS STS does not " + "have one of them in the partition " + + name); + } + return "https://sts-fips." + region + "." + dual_stack_dns_suffix; + } + if (use_fips) { + if (!has_fips) { + throw ConfigurationError( + "A FIPS endpoint is asked for, and AWS STS does not have one in " + "the partition " + + name); + } + // In AWS GovCloud (US) the Regional endpoint is the FIPS one + if (name == "aws-us-gov") { + return "https://sts." + region + ".amazonaws.com"; + } + return "https://sts-fips." + region + "." + dns_suffix; + } + if (use_dual_stack) { + if (!has_dual_stack) { + throw ConfigurationError( + "A dual-stack endpoint is asked for, and AWS STS does not have one " + "in the partition " + + name); + } + return "https://sts." + region + "." + dual_stack_dns_suffix; + } + return "https://sts." + region + "." + dns_suffix; +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/sts_endpoint.h b/src/providers/bedrock/sts_endpoint.h new file mode 100644 index 0000000..ee28e1d --- /dev/null +++ b/src/providers/bedrock/sts_endpoint.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +namespace ai { +namespace bedrock { + +/// The endpoint of AWS STS in a Region, the way the endpoint rules of the +/// service make it: the Regional endpoint, or its FIPS or dual-stack variant. +/// +/// `partitions` is the JSON that describes the partitions of AWS, the one +/// that the AWS SDK has (`Aws::Endpoint::AWSPartitions`). It says which +/// partition a Region is in, the DNS suffixes of the partition, and which +/// variants of the endpoints it has. +/// +/// Throws `ConfigurationError` when the partition does not have the variant +/// that is asked for. +std::string make_sts_endpoint(const std::string& partitions, + const std::string& region, + bool use_fips, + bool use_dual_stack); + +} // namespace bedrock +} // namespace ai diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 40caeb2..01d1e29 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -34,9 +34,11 @@ set(AI_TEST_SOURCES if(AI_SDK_ENABLE_BEDROCK) list(APPEND AI_TEST_SOURCES unit/bedrock_client_test.cpp + unit/bedrock_converse_test.cpp unit/bedrock_request_mapper_test.cpp unit/bedrock_response_parser_test.cpp unit/bedrock_stream_test.cpp + unit/bedrock_sts_endpoint_test.cpp # Security component tests unit/input_validator_test.cpp unit/credential_redactor_test.cpp diff --git a/tests/unit/bedrock_converse_test.cpp b/tests/unit/bedrock_converse_test.cpp new file mode 100644 index 0000000..b97b699 --- /dev/null +++ b/tests/unit/bedrock_converse_test.cpp @@ -0,0 +1,445 @@ +// Bedrock client unit tests over fakes of the services of Bedrock: what the +// client asks them, and what it makes of their answers. No AWS SDK, no +// credentials and no network are involved. + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "../utils/fake_bedrock_transport.h" +#include "ai/bedrock.h" +#include "ai/errors.h" +#include "ai/types/tool.h" +#include "providers/bedrock/bedrock_client.h" + +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { +namespace { + +using test::FakeBedrockServices; +using test::FakeBedrockTransport; +using test::HeldBedrockTransport; + +using Json = nlohmann::json; +using Query = std::vector>; + +const char* const kTextAnswer = R"({ + "output": {"message": {"role": "assistant", + "content": [{"text": "SELECT 1"}]}}, + "stopReason": "end_turn", + "usage": {"inputTokens": 12, "outputTokens": 3, "totalTokens": 15} +})"; + +class BedrockConverseTest : public ::testing::Test { + protected: + FakeBedrockServices services_; + BedrockConfig config_; +}; + +TEST_F(BedrockConverseTest, SendsConverseRequest) { + services_.runtime->responses = {FakeBedrockTransport::ok(kTextAnswer)}; + BedrockClient client(config_, services_.transports()); + + GenerateOptions options(models::kNovaLite, "Count the rows"); + options.system = "Answer with a query."; + options.max_tokens = 100; + const auto result = client.generate_text(options); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "SELECT 1"); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); + EXPECT_EQ(result.usage.total_tokens, 15); + + const auto requests = services_.runtime->requests(); + ASSERT_EQ(requests.size(), 1); + EXPECT_EQ(requests[0].operation, "Converse"); + EXPECT_EQ(requests[0].method, TransportRequest::Method::kPost); + EXPECT_EQ(requests[0].path, + (std::vector{"model", models::kNovaLite, "converse"})); + EXPECT_TRUE(requests[0].query.empty()); + + const Json expected_body = { + {"system", Json::array({Json{{"text", "Answer with a query."}}})}, + {"messages", + Json::array( + {{{"role", "user"}, + {"content", Json::array({Json{{"text", "Count the rows"}}})}}})}, + {"inferenceConfig", {{"maxTokens", 100}}}}; + EXPECT_EQ(Json::parse(requests[0].body), expected_body); + + // The model lists are not asked for a request of the model + EXPECT_TRUE(services_.control_plane->requests().empty()); +} + +// An inference profile is addressed by its ARN, which has slashes and +// colons: it stays one segment of the path, for the transport to escape +TEST_F(BedrockConverseTest, ModelIdIsOneSegmentOfThePath) { + services_.runtime->responses = {FakeBedrockTransport::ok(kTextAnswer)}; + BedrockClient client(config_, services_.transports()); + + const std::string profile_arn = + "arn:aws:bedrock:us-east-1:123456789012:inference-profile/" + "us.anthropic.claude-sonnet-5-5"; + const auto result = client.generate_text(GenerateOptions(profile_arn, "Hi")); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + const auto requests = services_.runtime->requests(); + ASSERT_EQ(requests.size(), 1); + EXPECT_EQ(requests[0].path, + (std::vector{"model", profile_arn, "converse"})); +} + +TEST_F(BedrockConverseTest, ReportsTheErrorOfTheService) { + services_.runtime->responses = {FakeBedrockTransport::error( + "ThrottlingException", "Too many requests", /*retryable=*/true, 429)}; + BedrockClient client(config_, services_.transports()); + + const auto result = + client.generate_text(GenerateOptions(models::kNovaLite, "Hi")); + + EXPECT_FALSE(result.is_success()); + EXPECT_EQ(result.error_message(), "ThrottlingException: Too many requests"); + EXPECT_EQ(result.finish_reason, kFinishReasonError); + EXPECT_EQ(result.is_retryable, true); +} + +// An answer that is not the JSON of Converse (a proxy in between, say) is +// an error of the request, and not an exception +TEST_F(BedrockConverseTest, UnexpectedAnswerIsAnError) { + services_.runtime->responses = { + FakeBedrockTransport::ok("It works!")}; + BedrockClient client(config_, services_.transports()); + + const auto result = + client.generate_text(GenerateOptions(models::kNovaLite, "Hi")); + + EXPECT_FALSE(result.is_success()); + EXPECT_NE(result.error_message().find("not a JSON object"), + std::string::npos); +} + +// What the validator refuses is not sent +TEST_F(BedrockConverseTest, DoesNotSendInvalidInput) { + config_.security.max_prompt_length = 10; + BedrockClient client(config_, services_.transports()); + + auto result = client.generate_text( + GenerateOptions(models::kNovaLite, "A prompt that is too long")); + EXPECT_FALSE(result.is_success()); + EXPECT_NE(result.error_message().find("Prompt exceeds maximum length"), + std::string::npos); + + result = client.generate_text(GenerateOptions("a model", "Hi")); + EXPECT_FALSE(result.is_success()); + EXPECT_NE(result.error_message().find("Invalid model ID format"), + std::string::npos); + + auto stream = + client.stream_text(StreamOptions(GenerateOptions("a model", "Hi"))); + bool saw_error = false; + for (const auto& event : stream) { + saw_error = saw_error || event.is_error(); + } + EXPECT_TRUE(saw_error); + + EXPECT_TRUE(services_.runtime->requests().empty()); +} + +// The model calls a tool, the tool runs, and its result goes back +TEST_F(BedrockConverseTest, RunsToolsBetweenTheSteps) { + services_.runtime->responses = { + FakeBedrockTransport::ok(R"({ + "output": {"message": {"role": "assistant", "content": [ + {"toolUse": {"toolUseId": "call_1", "name": "get_weather", + "input": {"city": "Paris"}}}]}}, + "stopReason": "tool_use", + "usage": {"inputTokens": 20, "outputTokens": 10} + })"), + FakeBedrockTransport::ok(R"({ + "output": {"message": {"role": "assistant", + "content": [{"text": "It is 20 degrees."}]}}, + "stopReason": "end_turn", + "usage": {"inputTokens": 40, "outputTokens": 6} + })"), + }; + BedrockClient client(config_, services_.transports()); + + std::optional tool_arguments; + GenerateOptions options(models::kNovaLite, "Weather in Paris?"); + options.max_steps = 2; + options.tools["get_weather"] = + Tool("Get the weather for a city", + {{"type", "object"}, + {"properties", {{"city", {{"type", "string"}}}}}, + {"required", {"city"}}}, + [&](const JsonValue& arguments, const ToolExecutionContext&) { + tool_arguments = arguments; + return JsonValue{{"temperature", 20}}; + }); + + const auto result = client.generate_text(options); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "It is 20 degrees."); + ASSERT_TRUE(tool_arguments.has_value()); + EXPECT_EQ(*tool_arguments, (Json{{"city", "Paris"}})); + + // The second request carries the call of the tool and its result + const auto requests = services_.runtime->requests(); + ASSERT_EQ(requests.size(), 2); + const Json second = Json::parse(requests[1].body); + bool has_tool_use = false; + bool has_tool_result = false; + for (const auto& message : second["messages"]) { + for (const auto& block : message["content"]) { + if (block.contains("toolUse")) { + has_tool_use = true; + EXPECT_EQ(message["role"], "assistant"); + EXPECT_EQ(block["toolUse"]["toolUseId"], "call_1"); + } + if (block.contains("toolResult")) { + has_tool_result = true; + EXPECT_EQ(message["role"], "user"); + EXPECT_EQ(block["toolResult"]["toolUseId"], "call_1"); + EXPECT_EQ(block["toolResult"]["content"], + Json::array({Json{{"json", {{"temperature", 20}}}}})); + } + } + } + EXPECT_TRUE(has_tool_use); + EXPECT_TRUE(has_tool_result); + EXPECT_TRUE(second.contains("toolConfig")); +} + +TEST_F(BedrockConverseTest, StreamsOverConverseStream) { + services_.runtime->events = { + {"messageStart", R"({"role":"assistant"})"}, + {"contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"text":"SELECT "}})"}, + {"contentBlockDelta", R"({"contentBlockIndex":0,"delta":{"text":"1"}})"}, + {"contentBlockStop", R"({"contentBlockIndex":0})"}, + {"messageStop", R"({"stopReason":"end_turn"})"}, + {"metadata", R"({"usage":{"inputTokens":12,"outputTokens":3}})"}, + }; + BedrockClient client(config_, services_.transports()); + + auto stream = client.stream_text( + StreamOptions(GenerateOptions(models::kNovaLite, "Count the rows"))); + + std::string text; + std::optional finish; + for (const auto& event : stream) { + if (event.is_text_delta()) { + text += event.text_delta; + } else if (event.is_finish()) { + finish = event; + } else { + ADD_FAILURE() << "An unexpected event: " << event.error.value_or(""); + } + } + EXPECT_EQ(text, "SELECT 1"); + ASSERT_TRUE(finish.has_value()); + EXPECT_EQ(finish->finish_reason, kFinishReasonStop); + ASSERT_TRUE(finish->usage.has_value()); + EXPECT_EQ(finish->usage->prompt_tokens, 12); + + const auto requests = services_.runtime->requests(); + ASSERT_EQ(requests.size(), 1); + EXPECT_EQ(requests[0].operation, "ConverseStream"); + EXPECT_EQ(requests[0].method, TransportRequest::Method::kPost); + EXPECT_EQ(requests[0].path, + (std::vector{"model", models::kNovaLite, + "converse-stream"})); + EXPECT_EQ(Json::parse(requests[0].body)["messages"][0]["content"][0]["text"], + "Count the rows"); +} + +// A stream may outlive the client that created it: it shares ownership of +// everything its background thread uses +TEST_F(BedrockConverseTest, StreamOutlivesClient) { + auto held = std::make_shared(); + BedrockTransports transports = services_.transports(); + transports.runtime = held; + + std::optional stream; + { + BedrockClient client(config_, std::move(transports)); + stream.emplace(client.stream_text( + StreamOptions(GenerateOptions(models::kNovaLite, "Hello")))); + held->started.get_future().wait(); + } // The client is destroyed while the response is still open + held->release.set_value(); + + std::string text; + bool saw_finish = false; + int events_after_finish = 0; + for (const auto& event : *stream) { + if (saw_finish) { + // The finish event is the last one, even though it is pushed by + // another thread while this one iterates + ++events_after_finish; + } else if (event.is_text_delta()) { + text += event.text_delta; + } else if (event.is_finish()) { + saw_finish = true; + EXPECT_EQ(event.finish_reason, kFinishReasonStop); + } + } + EXPECT_EQ(text, "SELECT"); + EXPECT_TRUE(saw_finish); + EXPECT_EQ(events_after_finish, 0); +} + +// The requests of one client are limited in number; a finished stream gives +// its slot back +TEST_F(BedrockConverseTest, StreamGivesItsSlotBack) { + config_.security.max_concurrent_requests = 1; + services_.runtime->events = {{"messageStop", R"({"stopReason":"end_turn"})"}}; + services_.runtime->responses = {FakeBedrockTransport::ok(kTextAnswer)}; + BedrockClient client(config_, services_.transports()); + + for (int i = 0; i < 2; ++i) { + auto stream = client.stream_text( + StreamOptions(GenerateOptions(models::kNovaLite, "Hello"))); + for (const auto& event : stream) { + EXPECT_TRUE(event.is_finish()); + } + } + + // Would wait forever for the only slot otherwise + EXPECT_TRUE(client.generate_text(GenerateOptions(models::kNovaLite, "Hi")) + .is_success()); +} + +// The list of the models is what Converse can be asked with: the inference +// profiles of the models that output text first, then the models that are +// invoked on demand by their own IDs +TEST_F(BedrockConverseTest, ListsInferenceProfilesFirst) { + services_.control_plane->responses = { + FakeBedrockTransport::ok(R"({"modelSummaries": [ + {"modelId": "anthropic.claude-sonnet-5-5", + "inferenceTypesSupported": ["INFERENCE_PROFILE"]}, + {"modelId": "amazon.nova-lite-v1:0", + "inferenceTypesSupported": ["ON_DEMAND", "INFERENCE_PROFILE"]}, + {"modelId": "amazon.provisioned-only-v1:0", + "inferenceTypesSupported": ["PROVISIONED"]}, + {"inferenceTypesSupported": ["ON_DEMAND"]} + ]})"), + FakeBedrockTransport::ok(R"({ + "inferenceProfileSummaries": [ + {"inferenceProfileId": "global.anthropic.claude-sonnet-5-5", + "status": "ACTIVE", + "models": [{"modelArn": + "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-sonnet-5-5"}]}, + {"inferenceProfileId": "us.stability.image-model-v1", + "status": "ACTIVE", + "models": [{"modelArn": + "arn:aws:bedrock:us-east-1::foundation-model/stability.image-model-v1"}]} + ], + "nextToken": "page-2" + })"), + FakeBedrockTransport::ok(R"({ + "inferenceProfileSummaries": [ + {"inferenceProfileId": "us.amazon.nova-lite-v1:0", + "status": "ACTIVE", + "models": [{"modelArn": + "arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-lite-v1:0"}]}, + {"inferenceProfileId": "us.amazon.retired-v1:0", + "status": "LEGACY", + "models": [{"modelArn": + "arn:aws:bedrock:us-west-2::foundation-model/amazon.nova-lite-v1:0"}]} + ] + })"), + }; + BedrockClient client(config_, services_.transports()); + + const auto listed = client.list_models(); + + ASSERT_TRUE(listed.is_success()) << listed.error_message(); + EXPECT_EQ(listed.models, (std::vector{ + "global.anthropic.claude-sonnet-5-5", + "us.amazon.nova-lite-v1:0", + "amazon.nova-lite-v1:0", + })); + + const auto requests = services_.control_plane->requests(); + ASSERT_EQ(requests.size(), 3); + for (const auto& request : requests) { + EXPECT_EQ(request.method, TransportRequest::Method::kGet); + EXPECT_TRUE(request.body.empty()); + } + EXPECT_EQ(requests[0].operation, "ListFoundationModels"); + EXPECT_EQ(requests[0].path, (std::vector{"foundation-models"})); + EXPECT_EQ(requests[0].query, (Query{{"byOutputModality", "TEXT"}})); + EXPECT_EQ(requests[1].operation, "ListInferenceProfiles"); + EXPECT_EQ(requests[1].path, (std::vector{"inference-profiles"})); + EXPECT_EQ(requests[1].query, (Query{{"type", "SYSTEM_DEFINED"}})); + EXPECT_EQ(requests[2].query, + (Query{{"nextToken", "page-2"}, {"type", "SYSTEM_DEFINED"}})); + + // The runtime service is not asked for the list + EXPECT_TRUE(services_.runtime->requests().empty()); +} + +// The error names the operation, which tells what permission is missing +TEST_F(BedrockConverseTest, ListModelsNamesTheFailedOperation) { + services_.control_plane->responses = { + FakeBedrockTransport::ok(R"({"modelSummaries": []})"), + FakeBedrockTransport::error("AccessDeniedException", + "Not allowed to list the profiles", false, + 403), + }; + BedrockClient client(config_, services_.transports()); + + auto listed = client.list_models(); + EXPECT_FALSE(listed.is_success()); + EXPECT_EQ(listed.error_message(), + "Failed to list Bedrock models: ListInferenceProfiles: " + "AccessDeniedException: Not allowed to list the profiles"); + + services_.control_plane->responses = {FakeBedrockTransport::ok("[]")}; + listed = BedrockClient(config_, services_.transports()).list_models(); + EXPECT_FALSE(listed.is_success()); + EXPECT_NE(listed.error_message().find( + "ListFoundationModels: the response is not a JSON object"), + std::string::npos); +} + +TEST_F(BedrockConverseTest, DescribesItself) { + config_.profile = "analytics"; + config_.endpoint_override = "https://bedrock.example.test"; + BedrockClient client(config_, services_.transports()); + + EXPECT_TRUE(client.is_valid()); + EXPECT_EQ(client.provider_name(), "bedrock"); + EXPECT_EQ(client.default_model(), models::kDefaultModel); + EXPECT_EQ(client.config_info(), + "Bedrock API (region: us-east-1, profile: analytics, endpoint: " + "https://bedrock.example.test)"); + EXPECT_TRUE(client.supports_model("vendor.some-new-model-v1:0")); + EXPECT_FALSE(client.supports_model("")); +} + +TEST_F(BedrockConverseTest, RequiresPositiveConcurrency) { + config_.security.max_concurrent_requests = 0; + EXPECT_THROW(BedrockClient(config_, services_.transports()), + ConfigurationError); +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +TEST(BedrockConverseTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock provider not enabled. Set AI_SDK_ENABLE_BEDROCK=ON"; +} + +#endif // AI_SDK_HAS_BEDROCK diff --git a/tests/unit/bedrock_request_mapper_test.cpp b/tests/unit/bedrock_request_mapper_test.cpp index 9a3adbf..c11bdbc 100644 --- a/tests/unit/bedrock_request_mapper_test.cpp +++ b/tests/unit/bedrock_request_mapper_test.cpp @@ -1,5 +1,6 @@ // Bedrock Request Mapper Unit Tests -// Tests message conversion, parameter mapping, and system prompt handling +// Tests message conversion, parameter mapping, and system prompt handling: +// the JSON body of a request of the Converse API #include @@ -11,40 +12,48 @@ #include "ai/types/tool.h" #include "providers/bedrock/bedrock_request_mapper.h" -#include - namespace ai { namespace bedrock { namespace { +using Json = nlohmann::json; + class BedrockRequestMapperTest : public ::testing::Test { protected: BedrockRequestMapper mapper_; }; +Json text_block(const char* text) { + return Json{{"text", text}}; +} + // Test basic prompt-to-message conversion TEST_F(BedrockRequestMapperTest, ConvertsPromptToUserMessage) { GenerateOptions options; options.model = models::kClaudeSonnet; options.prompt = "Hello, world!"; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - EXPECT_EQ(request.GetModelId(), models::kClaudeSonnet); - ASSERT_EQ(request.GetMessages().size(), 1); - EXPECT_EQ(request.GetMessages()[0].GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::user); + const Json expected = { + {"messages", + Json::array( + {{{"role", "user"}, + {"content", Json::array({text_block("Hello, world!")})}}})}}; + EXPECT_EQ(body, expected); } -// Test model ID mapping -TEST_F(BedrockRequestMapperTest, MapsModelId) { +// The model is a part of the path of the request, and not of its body +TEST_F(BedrockRequestMapperTest, BodyHasNoModelId) { GenerateOptions options; options.model = "custom-model-id"; options.prompt = "Test"; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - EXPECT_EQ(request.GetModelId(), "custom-model-id"); + EXPECT_FALSE(body.contains("modelId")); + EXPECT_EQ(BedrockRequestMapper::serialize(body).find("custom-model-id"), + std::string::npos); } // Test max_tokens mapping @@ -54,9 +63,19 @@ TEST_F(BedrockRequestMapperTest, MapsMaxTokens) { options.prompt = "Test"; options.max_tokens = 1000; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); + + EXPECT_EQ(body["inferenceConfig"], (Json{{"maxTokens", 1000}})); +} + +// Without the parameters of inference there is no `inferenceConfig` +TEST_F(BedrockRequestMapperTest, OmitsEmptyInferenceConfig) { + GenerateOptions options; + options.model = models::kNovaLite; + options.prompt = "Test"; - EXPECT_EQ(request.GetInferenceConfig().GetMaxTokens(), 1000); + EXPECT_FALSE( + mapper_.map_to_converse_body(options).contains("inferenceConfig")); } // Test temperature mapping @@ -66,9 +85,9 @@ TEST_F(BedrockRequestMapperTest, MapsTemperature) { options.prompt = "Test"; options.temperature = 0.7; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - EXPECT_FLOAT_EQ(request.GetInferenceConfig().GetTemperature(), 0.7f); + EXPECT_DOUBLE_EQ(body["inferenceConfig"]["temperature"].get(), 0.7); } // Test top_p mapping @@ -78,9 +97,9 @@ TEST_F(BedrockRequestMapperTest, MapsTopP) { options.prompt = "Test"; options.top_p = 0.9; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - EXPECT_FLOAT_EQ(request.GetInferenceConfig().GetTopP(), 0.9f); + EXPECT_DOUBLE_EQ(body["inferenceConfig"]["topP"].get(), 0.9); } // Test system prompt mapping @@ -90,10 +109,10 @@ TEST_F(BedrockRequestMapperTest, MapsSystemPrompt) { options.prompt = "Test"; options.system = "You are a helpful assistant."; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - ASSERT_EQ(request.GetSystem().size(), 1); - EXPECT_EQ(request.GetSystem()[0].GetText(), "You are a helpful assistant."); + EXPECT_EQ(body["system"], + Json::array({text_block("You are a helpful assistant.")})); } // Test messages conversion @@ -106,15 +125,17 @@ TEST_F(BedrockRequestMapperTest, ConvertsMessages) { Message::user("How are you?"), }; - auto request = mapper_.map_to_converse_request(options); - - ASSERT_EQ(request.GetMessages().size(), 3); - EXPECT_EQ(request.GetMessages()[0].GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::user); - EXPECT_EQ(request.GetMessages()[1].GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::assistant); - EXPECT_EQ(request.GetMessages()[2].GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::user); + const auto body = mapper_.map_to_converse_body(options); + + const auto& messages = body["messages"]; + ASSERT_EQ(messages.size(), 3); + EXPECT_EQ(messages[0]["role"], "user"); + EXPECT_EQ(messages[0]["content"], Json::array({text_block("Hello")})); + EXPECT_EQ(messages[1]["role"], "assistant"); + EXPECT_EQ(messages[1]["content"], Json::array({text_block("Hi there!")})); + EXPECT_EQ(messages[2]["role"], "user"); + EXPECT_EQ(messages[2]["content"], Json::array({text_block("How are you?")})); + EXPECT_FALSE(body.contains("system")); } // Claude models that reject sampling parameters do not get them @@ -125,10 +146,12 @@ TEST_F(BedrockRequestMapperTest, DropsSamplingParametersForClaude) { options.temperature = 0.7; options.top_p = 0.9; - auto request = mapper_.map_to_converse_request(options); + auto body = mapper_.map_to_converse_body(options); + EXPECT_FALSE(body.contains("inferenceConfig")); - EXPECT_FALSE(request.GetInferenceConfig().TemperatureHasBeenSet()); - EXPECT_FALSE(request.GetInferenceConfig().TopPHasBeenSet()); + options.max_tokens = 100; + body = mapper_.map_to_converse_body(options); + EXPECT_EQ(body["inferenceConfig"], (Json{{"maxTokens", 100}})); } TEST_F(BedrockRequestMapperTest, RecognizesSamplingRejectingModels) { @@ -159,14 +182,12 @@ TEST_F(BedrockRequestMapperTest, MergesSystemMessagesIntoSystem) { Message::user("Hello"), }; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - ASSERT_EQ(request.GetSystem().size(), 2); - EXPECT_EQ(request.GetSystem()[0].GetText(), "Be brief."); - EXPECT_EQ(request.GetSystem()[1].GetText(), "Answer in English."); - ASSERT_EQ(request.GetMessages().size(), 1); - EXPECT_EQ(request.GetMessages()[0].GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::user); + EXPECT_EQ(body["system"], Json::array({text_block("Be brief."), + text_block("Answer in English.")})); + ASSERT_EQ(body["messages"].size(), 1); + EXPECT_EQ(body["messages"][0]["role"], "user"); } // With only system messages, the prompt becomes the conversation @@ -176,13 +197,12 @@ TEST_F(BedrockRequestMapperTest, UsesPromptWhenOnlySystemMessages) { options.prompt = "Hello"; options.messages = {Message::system("Be brief.")}; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - ASSERT_EQ(request.GetSystem().size(), 1); - ASSERT_EQ(request.GetMessages().size(), 1); - EXPECT_EQ(request.GetMessages()[0].GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::user); - EXPECT_EQ(request.GetMessages()[0].GetContent()[0].GetText(), "Hello"); + EXPECT_EQ(body["system"], Json::array({text_block("Be brief.")})); + ASSERT_EQ(body["messages"].size(), 1); + EXPECT_EQ(body["messages"][0]["role"], "user"); + EXPECT_EQ(body["messages"][0]["content"], Json::array({text_block("Hello")})); } // Dropping a system message between two user turns merges them, because @@ -197,16 +217,14 @@ TEST_F(BedrockRequestMapperTest, MergesAdjacentSameRoleTurns) { Message::assistant("Reply"), }; - auto request = mapper_.map_to_converse_request(options); + const auto body = mapper_.map_to_converse_body(options); - ASSERT_EQ(request.GetMessages().size(), 2); - const auto& user = request.GetMessages()[0]; - EXPECT_EQ(user.GetRole(), Aws::BedrockRuntime::Model::ConversationRole::user); - ASSERT_EQ(user.GetContent().size(), 2); - EXPECT_EQ(user.GetContent()[0].GetText(), "First"); - EXPECT_EQ(user.GetContent()[1].GetText(), "Second"); - EXPECT_EQ(request.GetMessages()[1].GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::assistant); + const auto& messages = body["messages"]; + ASSERT_EQ(messages.size(), 2); + EXPECT_EQ(messages[0]["role"], "user"); + EXPECT_EQ(messages[0]["content"], + Json::array({text_block("First"), text_block("Second")})); + EXPECT_EQ(messages[1]["role"], "assistant"); } // When a text turn and a tool result turn are merged, the tool results come @@ -225,17 +243,16 @@ TEST_F(BedrockRequestMapperTest, MergedTurnPutsToolResultsFirst) { Message::user("Thanks!"), }; - auto request = mapper_.map_to_converse_request(options); - - ASSERT_EQ(request.GetMessages().size(), 3); - const auto& merged = request.GetMessages()[2]; - EXPECT_EQ(merged.GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::user); - ASSERT_EQ(merged.GetContent().size(), 3); - EXPECT_TRUE(merged.GetContent()[0].ToolResultHasBeenSet()); - EXPECT_EQ(merged.GetContent()[0].GetToolResult().GetToolUseId(), "call_1"); - EXPECT_EQ(merged.GetContent()[1].GetText(), "Also, answer in French."); - EXPECT_EQ(merged.GetContent()[2].GetText(), "Thanks!"); + const auto body = mapper_.map_to_converse_body(options); + + const auto& messages = body["messages"]; + ASSERT_EQ(messages.size(), 3); + const auto& merged = messages[2]; + EXPECT_EQ(merged["role"], "user"); + ASSERT_EQ(merged["content"].size(), 3); + EXPECT_EQ(merged["content"][0]["toolResult"]["toolUseId"], "call_1"); + EXPECT_EQ(merged["content"][1], text_block("Also, answer in French.")); + EXPECT_EQ(merged["content"][2], text_block("Thanks!")); } ToolSet make_weather_tools() { @@ -257,27 +274,29 @@ TEST_F(BedrockRequestMapperTest, MapsToolsAndToolChoice) { options.prompt = "Weather in Paris?"; options.tools = make_weather_tools(); - auto request = mapper_.map_to_converse_request(options); + auto body = mapper_.map_to_converse_body(options); - ASSERT_TRUE(request.ToolConfigHasBeenSet()); - const auto& tools = request.GetToolConfig().GetTools(); + ASSERT_TRUE(body.contains("toolConfig")); + const auto& tools = body["toolConfig"]["tools"]; ASSERT_EQ(tools.size(), 1); - EXPECT_EQ(tools[0].GetToolSpec().GetName(), "get_weather"); - EXPECT_EQ(tools[0].GetToolSpec().GetDescription(), - "Get the weather for a city"); - EXPECT_EQ(BedrockRequestMapper::from_document( - tools[0].GetToolSpec().GetInputSchema().GetJson())["required"], - nlohmann::json::array({"city"})); - EXPECT_TRUE(request.GetToolConfig().GetToolChoice().AutoHasBeenSet()); + const auto& spec = tools[0]["toolSpec"]; + EXPECT_EQ(spec["name"], "get_weather"); + EXPECT_EQ(spec["description"], "Get the weather for a city"); + EXPECT_EQ(spec["inputSchema"]["json"]["required"], Json::array({"city"})); + EXPECT_EQ(body["toolConfig"]["toolChoice"], (Json{{"auto", Json::object()}})); + + options.tool_choice = ToolChoice::required(); + body = mapper_.map_to_converse_body(options); + EXPECT_EQ(body["toolConfig"]["toolChoice"], (Json{{"any", Json::object()}})); options.tool_choice = ToolChoice::specific("get_weather"); - request = mapper_.map_to_converse_request(options); - EXPECT_EQ(request.GetToolConfig().GetToolChoice().GetTool().GetName(), - "get_weather"); + body = mapper_.map_to_converse_body(options); + EXPECT_EQ(body["toolConfig"]["toolChoice"], + (Json{{"tool", {{"name", "get_weather"}}}})); options.tool_choice = ToolChoice::none(); - request = mapper_.map_to_converse_request(options); - EXPECT_FALSE(request.ToolConfigHasBeenSet()); + body = mapper_.map_to_converse_body(options); + EXPECT_FALSE(body.contains("toolConfig")); } TEST_F(BedrockRequestMapperTest, MapsToolCallsAndResults) { @@ -293,51 +312,85 @@ TEST_F(BedrockRequestMapperTest, MapsToolCallsAndResults) { "call_1", JsonValue{{"temperature", 20}}, false)}), }; - auto request = mapper_.map_to_converse_request(options); - - ASSERT_EQ(request.GetMessages().size(), 3); - - const auto& assistant = request.GetMessages()[1]; - EXPECT_EQ(assistant.GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::assistant); - ASSERT_EQ(assistant.GetContent().size(), 2); - EXPECT_EQ(assistant.GetContent()[0].GetText(), "Let me check."); - const auto& tool_use = assistant.GetContent()[1].GetToolUse(); - EXPECT_EQ(tool_use.GetToolUseId(), "call_1"); - EXPECT_EQ(tool_use.GetName(), "get_weather"); - EXPECT_EQ(BedrockRequestMapper::from_document(tool_use.GetInput()), - (nlohmann::json{{"city", "Paris"}})); - - const auto& results = request.GetMessages()[2]; - EXPECT_EQ(results.GetRole(), - Aws::BedrockRuntime::Model::ConversationRole::user); - ASSERT_EQ(results.GetContent().size(), 1); - const auto& tool_result = results.GetContent()[0].GetToolResult(); - EXPECT_EQ(tool_result.GetToolUseId(), "call_1"); - EXPECT_EQ(tool_result.GetStatus(), - Aws::BedrockRuntime::Model::ToolResultStatus::success); - ASSERT_EQ(tool_result.GetContent().size(), 1); - EXPECT_EQ(BedrockRequestMapper::from_document( - tool_result.GetContent()[0].GetJson()), - (nlohmann::json{{"temperature", 20}})); + auto body = mapper_.map_to_converse_body(options); + + const auto& messages = body["messages"]; + ASSERT_EQ(messages.size(), 3); + + const auto& assistant = messages[1]; + EXPECT_EQ(assistant["role"], "assistant"); + ASSERT_EQ(assistant["content"].size(), 2); + EXPECT_EQ(assistant["content"][0], text_block("Let me check.")); + const Json expected_tool_use = {{"toolUseId", "call_1"}, + {"name", "get_weather"}, + {"input", {{"city", "Paris"}}}}; + EXPECT_EQ(assistant["content"][1]["toolUse"], expected_tool_use); + + // The results of the tools are sent in a turn of the user + const auto& results = messages[2]; + EXPECT_EQ(results["role"], "user"); + ASSERT_EQ(results["content"].size(), 1); + const Json expected_tool_result = { + {"toolUseId", "call_1"}, + {"content", Json::array({Json{{"json", {{"temperature", 20}}}}})}, + {"status", "success"}}; + EXPECT_EQ(results["content"][0]["toolResult"], expected_tool_result); // With tool calls in the conversation the tools are sent even for "none" options.tool_choice = ToolChoice::none(); - request = mapper_.map_to_converse_request(options); - EXPECT_TRUE(request.ToolConfigHasBeenSet()); + body = mapper_.map_to_converse_body(options); + EXPECT_TRUE(body.contains("toolConfig")); + EXPECT_FALSE(body["toolConfig"].contains("toolChoice")); +} + +// Bedrock takes only a JSON object as the `json` of a tool result: anything +// else is sent as text +TEST_F(BedrockRequestMapperTest, MapsToolResultsThatAreNotObjects) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.tools = make_weather_tools(); + options.messages = { + Message::user("Weather in Paris?"), + Message::assistant_with_tools( + "", + {ToolCallContentPart("call_1", "get_weather", {{"city", "Paris"}}), + ToolCallContentPart("call_2", "get_weather", JsonValue())}), + Message::tool_results( + {ToolResultContentPart("call_1", JsonValue("sunny"), false), + ToolResultContentPart("call_2", JsonValue::array({1, 2}), true)}), + }; + + const auto body = mapper_.map_to_converse_body(options); + + const auto& messages = body["messages"]; + ASSERT_EQ(messages.size(), 3); + + // A tool call without arguments has an empty object as its input + EXPECT_EQ(messages[1]["content"][1]["toolUse"]["input"], Json::object()); + + const auto& results = messages[2]["content"]; + ASSERT_EQ(results.size(), 2); + EXPECT_EQ(results[0]["toolResult"]["content"], + Json::array({text_block("sunny")})); + EXPECT_EQ(results[0]["toolResult"]["status"], "success"); + EXPECT_EQ(results[1]["toolResult"]["content"], + Json::array({text_block("[1,2]")})); + EXPECT_EQ(results[1]["toolResult"]["status"], "error"); } -// Test stream request mapping -TEST_F(BedrockRequestMapperTest, MapsStreamRequest) { +// The body is sent as is: text that is not valid UTF-8 must not make the +// serialization throw +TEST_F(BedrockRequestMapperTest, SerializesInvalidUtf8) { GenerateOptions options; options.model = models::kClaudeSonnet; - options.prompt = "Test streaming"; - options.max_tokens = 500; + options.prompt = "caf\xE9"; - auto request = mapper_.map_to_converse_stream_request(options); + const auto serialized = + BedrockRequestMapper::serialize(mapper_.map_to_converse_body(options)); - EXPECT_EQ(request.GetModelId(), models::kClaudeSonnet); - EXPECT_EQ(request.GetInferenceConfig().GetMaxTokens(), 500); + const auto parsed = Json::parse(serialized, nullptr, false); + ASSERT_TRUE(parsed.is_object()); + EXPECT_EQ(parsed["messages"][0]["content"][0]["text"], "caf\xEF\xBF\xBD"); } } // namespace diff --git a/tests/unit/bedrock_response_parser_test.cpp b/tests/unit/bedrock_response_parser_test.cpp index b8bc143..12af1e4 100644 --- a/tests/unit/bedrock_response_parser_test.cpp +++ b/tests/unit/bedrock_response_parser_test.cpp @@ -1,5 +1,5 @@ // Bedrock Response Parser Unit Tests -// Tests response parsing, error mapping, and retryability classification +// Tests response parsing and error mapping #include @@ -9,54 +9,43 @@ #include "ai/core.h" #include "providers/bedrock/bedrock_response_parser.h" -#include -#include -#include -#include -#include -#include - namespace ai { namespace bedrock { namespace { class BedrockResponseParserTest : public ::testing::Test { protected: + static TransportResponse failed(const char* name, + const char* message, + bool retryable) { + TransportResponse response; + response.status = 400; + response.error_name = name; + response.error_message = message; + response.retryable = retryable; + return response; + } + BedrockResponseParser parser_; }; // Text, tool calls, stop reason, and usage are extracted from the response TEST_F(BedrockResponseParserTest, ParsesTextAndToolCalls) { - namespace Model = Aws::BedrockRuntime::Model; - - Model::ContentBlock text_block; - text_block.SetText("Let me check."); - - Model::ToolUseBlock tool_use; - tool_use.SetToolUseId("call_1"); - tool_use.SetName("get_weather"); - tool_use.SetInput(Aws::Utils::Document(Aws::String(R"({"city":"Paris"})"))); - Model::ContentBlock tool_block; - tool_block.SetToolUse(tool_use); - - Model::Message message; - message.SetRole(Model::ConversationRole::assistant); - message.AddContent(text_block); - message.AddContent(tool_block); - - Model::ConverseOutput output; - output.SetMessage(message); - - Model::TokenUsage usage; - usage.SetInputTokens(12); - usage.SetOutputTokens(34); - - Model::ConverseResult converse_result; - converse_result.SetOutput(output); - converse_result.SetStopReason(Model::StopReason::tool_use); - converse_result.SetUsage(usage); - - auto result = parser_.parse_converse_response(converse_result); + auto result = parser_.parse_converse_response(R"({ + "output": { + "message": { + "role": "assistant", + "content": [ + {"text": "Let me check."}, + {"toolUse": {"toolUseId": "call_1", "name": "get_weather", + "input": {"city": "Paris"}}} + ] + } + }, + "stopReason": "tool_use", + "usage": {"inputTokens": 12, "outputTokens": 34, "totalTokens": 46}, + "metrics": {"latencyMs": 551} + })"); EXPECT_TRUE(result.is_success()); EXPECT_EQ(result.text, "Let me check."); @@ -71,82 +60,116 @@ TEST_F(BedrockResponseParserTest, ParsesTextAndToolCalls) { EXPECT_EQ(result.usage.total_tokens, 46); } -// Test error retryability - ThrottlingException -TEST_F(BedrockResponseParserTest, ThrottlingErrorIsRetryable) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::THROTTLING, - "ThrottlingException", "Rate exceeded", false); - - EXPECT_TRUE(parser_.is_error_retryable(error)); -} - -// Test error retryability - ServiceUnavailable -TEST_F(BedrockResponseParserTest, ServiceUnavailableIsRetryable) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::SERVICE_UNAVAILABLE, - "ServiceUnavailableException", "Service temporarily unavailable", false); +// The text blocks of the message are concatenated +TEST_F(BedrockResponseParserTest, ConcatenatesTextBlocks) { + auto result = parser_.parse_converse_response(R"({ + "output": {"message": {"role": "assistant", + "content": [{"text": "SELECT "}, {"text": "1"}]}}, + "stopReason": "end_turn", + "usage": {"inputTokens": 3, "outputTokens": 2} + })"); - EXPECT_TRUE(parser_.is_error_retryable(error)); + EXPECT_TRUE(result.is_success()); + EXPECT_EQ(result.text, "SELECT 1"); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); + EXPECT_TRUE(result.tool_calls.empty()); + ASSERT_EQ(result.response_messages.size(), 1); + EXPECT_EQ(result.response_messages[0].get_text(), "SELECT 1"); } -// Test error retryability - InternalFailure -TEST_F(BedrockResponseParserTest, InternalFailureIsRetryable) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::INTERNAL_FAILURE, - "InternalServerException", "Internal server error", false); +// A tool call without an input has an empty object as its arguments +TEST_F(BedrockResponseParserTest, ToolCallWithoutInput) { + auto result = parser_.parse_converse_response(R"({ + "output": {"message": {"content": [ + {"toolUse": {"toolUseId": "call_1", "name": "list_tables"}}]}}, + "stopReason": "tool_use" + })"); - EXPECT_TRUE(parser_.is_error_retryable(error)); + ASSERT_EQ(result.tool_calls.size(), 1); + EXPECT_EQ(result.tool_calls[0].arguments, nlohmann::json::object()); + EXPECT_EQ(result.usage.total_tokens, 0); } -// Test error retryability - ValidationException -TEST_F(BedrockResponseParserTest, ValidationErrorIsNotRetryable) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::VALIDATION, - "ValidationException", "Invalid request", false); - - EXPECT_FALSE(parser_.is_error_retryable(error)); +TEST_F(BedrockResponseParserTest, MapsStopReasons) { + EXPECT_EQ(BedrockResponseParser::map_stop_reason("end_turn"), + kFinishReasonStop); + EXPECT_EQ(BedrockResponseParser::map_stop_reason("stop_sequence"), + kFinishReasonStop); + EXPECT_EQ(BedrockResponseParser::map_stop_reason("max_tokens"), + kFinishReasonLength); + EXPECT_EQ(BedrockResponseParser::map_stop_reason("tool_use"), + kFinishReasonToolCalls); + EXPECT_EQ(BedrockResponseParser::map_stop_reason("content_filtered"), + kFinishReasonContentFilter); + EXPECT_EQ(BedrockResponseParser::map_stop_reason("guardrail_intervened"), + kFinishReasonContentFilter); + EXPECT_EQ(BedrockResponseParser::map_stop_reason("a_new_stop_reason"), + kFinishReasonStop); } -// Test error retryability - AccessDenied -TEST_F(BedrockResponseParserTest, AccessDeniedIsNotRetryable) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::ACCESS_DENIED, - "AccessDeniedException", "Access denied", false); - - EXPECT_FALSE(parser_.is_error_retryable(error)); +// A body that is not what Converse answers with is an error, and not an +// exception; members of unexpected types are skipped +TEST_F(BedrockResponseParserTest, UnexpectedBodyIsAnError) { + for (const char* body : {"", "Bad Gateway", "[1, 2]", "null"}) { + auto result = parser_.parse_converse_response(body); + EXPECT_FALSE(result.is_success()) << body; + EXPECT_EQ(result.finish_reason, kFinishReasonError) << body; + EXPECT_EQ(result.is_retryable, false) << body; + EXPECT_NE(result.error_message().find("not a JSON object"), + std::string::npos) + << body; + } + + auto result = parser_.parse_converse_response(R"({ + "output": {"message": {"content": [ + "text", {"text": 1}, {"toolUse": "call"}, {"text": "ok"}]}}, + "stopReason": 7, + "usage": {"inputTokens": "many"} + })"); + EXPECT_TRUE(result.is_success()); + EXPECT_EQ(result.text, "ok"); + EXPECT_TRUE(result.tool_calls.empty()); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); + EXPECT_EQ(result.usage.total_tokens, 0); } -// Test error retryability - ResourceNotFound -TEST_F(BedrockResponseParserTest, ResourceNotFoundIsNotRetryable) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::RESOURCE_NOT_FOUND, - "ResourceNotFoundException", "Model not found", false); +// Whether a request can be repeated is decided where its response is +// received, and the result carries it +TEST_F(BedrockResponseParserTest, ErrorKeepsRetryability) { + auto throttled = parser_.parse_converse_error( + failed("ThrottlingException", "Rate exceeded", true)); + EXPECT_EQ(throttled.is_retryable, true); - EXPECT_FALSE(parser_.is_error_retryable(error)); + auto invalid = parser_.parse_converse_error( + failed("ValidationException", "Invalid request", false)); + EXPECT_EQ(invalid.is_retryable, false); } // Test error message contains exception name TEST_F(BedrockResponseParserTest, ErrorMessageContainsExceptionName) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::VALIDATION, - "ValidationException", "Invalid model ID", false); + auto result = parser_.parse_converse_error( + failed("ValidationException", "Invalid model ID", false)); - auto result = parser_.parse_converse_error(error); + ASSERT_TRUE(result.error.has_value()); + EXPECT_EQ(*result.error, "ValidationException: Invalid model ID"); +} - EXPECT_TRUE(result.error.has_value()); - EXPECT_NE(result.error->find("ValidationException"), std::string::npos); - EXPECT_NE(result.error->find("Invalid model ID"), std::string::npos); +// An error without a name, such as a failed connection +TEST_F(BedrockResponseParserTest, ErrorWithoutName) { + auto result = + parser_.parse_converse_error(failed("", "Connection refused", true)); + + ASSERT_TRUE(result.error.has_value()); + EXPECT_EQ(*result.error, "BedrockError: Connection refused"); } // Test error result has correct finish reason TEST_F(BedrockResponseParserTest, ErrorResultHasErrorFinishReason) { - Aws::Client::AWSError error( - Aws::BedrockRuntime::BedrockRuntimeErrors::VALIDATION, - "ValidationException", "Test error", false); - - auto result = parser_.parse_converse_error(error); + auto result = parser_.parse_converse_error( + failed("ValidationException", "Test error", false)); EXPECT_EQ(result.finish_reason, kFinishReasonError); + EXPECT_FALSE(result.is_success()); } } // namespace diff --git a/tests/unit/bedrock_stream_test.cpp b/tests/unit/bedrock_stream_test.cpp index 9ff6256..aff0ac7 100644 --- a/tests/unit/bedrock_stream_test.cpp +++ b/tests/unit/bedrock_stream_test.cpp @@ -1,30 +1,58 @@ // Bedrock Stream Unit Tests -// Tests streaming event handling and ordering +// Tests streaming event handling and ordering, with a fake of the service #include #ifdef AI_SDK_HAS_BEDROCK +#include "../utils/fake_bedrock_transport.h" #include "ai/bedrock.h" #include "ai/types/stream_event.h" #include "providers/bedrock/bedrock_stream.h" -#include -#include +#include #include +#include namespace ai { namespace bedrock { namespace { -class BedrockStreamTest : public ::testing::Test { - protected: - // Note: Full streaming tests require mocking the AWS SDK client - // These tests verify the basic structure and interface -}; +using test::FakeBedrockTransport; +using test::HeldBedrockTransport; + +TransportRequest converse_stream_request() { + TransportRequest request; + request.operation = "ConverseStream"; + request.path = {"model", models::kClaudeSonnet, "converse-stream"}; + request.body = "{}"; + return request; +} + +/// Reads a stream up to its finish event (or its end) +std::vector read_all(BedrockStreamImpl& impl) { + std::vector events; + while (impl.has_more_events()) { + events.push_back(impl.get_next_event()); + if (events.back().is_finish()) { + break; + } + } + return events; +} + +/// Runs a stream over the events of a fake service +std::vector run_stream( + std::shared_ptr transport) { + BedrockStreamImpl impl; + impl.start_stream(std::move(transport), converse_stream_request()); + auto events = read_all(impl); + EXPECT_FALSE(impl.has_more_events()); + return events; +} // Test stream implementation can be created -TEST_F(BedrockStreamTest, CanCreateStreamImpl) { +TEST(BedrockStreamTest, CanCreateStreamImpl) { BedrockStreamImpl impl; // A newly created stream that hasn't been started yet // returns true for has_more_events because it's waiting for events @@ -33,7 +61,7 @@ TEST_F(BedrockStreamTest, CanCreateStreamImpl) { } // Test stream can be stopped -TEST_F(BedrockStreamTest, CanStopStream) { +TEST(BedrockStreamTest, CanStopStream) { BedrockStreamImpl impl; impl.stop_stream(); // After stopping, the stream should still report has_more_events as true @@ -43,7 +71,7 @@ TEST_F(BedrockStreamTest, CanStopStream) { } // Test a rejected stream yields its error immediately and then ends -TEST_F(BedrockStreamTest, FailedStreamYieldsErrorAndCompletes) { +TEST(BedrockStreamTest, FailedStreamYieldsErrorAndCompletes) { BedrockStreamImpl impl; impl.fail("Invalid model ID format: bad model"); @@ -58,79 +86,243 @@ TEST_F(BedrockStreamTest, FailedStreamYieldsErrorAndCompletes) { EXPECT_FALSE(impl.has_more_events()); } -// Sets (or unsets) an environment variable and restores its previous value -class ScopedEnvVar { - public: - ScopedEnvVar(const char* name, const std::optional& value) - : name_(name) { - if (const char* previous = std::getenv(name)) { - previous_ = previous; - } - set(value); - } - ~ScopedEnvVar() { set(previous_); } +// The events of ConverseStream become text deltas, whole tool calls, and a +// finish event with the stop reason and the usage +TEST(BedrockStreamTest, StreamsTextToolCallsAndUsage) { + auto transport = std::make_shared(); + transport->events = { + {"messageStart", R"({"role":"assistant"})"}, + {"contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"text":"Let me "}})"}, + {"contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"text":"check."}})"}, + {"contentBlockStop", R"({"contentBlockIndex":0})"}, + {"contentBlockStart", + R"({"contentBlockIndex":1,"start":{"toolUse": + {"toolUseId":"call_1","name":"get_weather"}}})"}, + // The input of a tool arrives as pieces of a JSON text + {"contentBlockDelta", + R"({"contentBlockIndex":1,"delta":{"toolUse":{"input":"{\"ci"}}})"}, + {"contentBlockDelta", + R"({"contentBlockIndex":1, + "delta":{"toolUse":{"input":"ty\":\"Paris\"}"}}})"}, + {"contentBlockStop", R"({"contentBlockIndex":1})"}, + {"messageStop", R"({"stopReason":"tool_use"})"}, + {"metadata", + R"({"usage":{"inputTokens":12,"outputTokens":34,"totalTokens":46}, + "metrics":{"latencyMs":551}})"}, + }; - ScopedEnvVar(const ScopedEnvVar&) = delete; - ScopedEnvVar& operator=(const ScopedEnvVar&) = delete; + const auto events = run_stream(transport); - private: - void set(const std::optional& value) { - if (value) { - ::setenv(name_.c_str(), value->c_str(), 1); - } else { - ::unsetenv(name_.c_str()); - } - } + ASSERT_EQ(events.size(), 4); + EXPECT_TRUE(events[0].is_text_delta()); + EXPECT_EQ(events[0].text_delta, "Let me "); + EXPECT_EQ(events[1].text_delta, "check."); + + ASSERT_TRUE(events[2].is_tool_call()); + ASSERT_TRUE(events[2].tool_call.has_value()); + EXPECT_EQ(events[2].tool_call->id, "call_1"); + EXPECT_EQ(events[2].tool_call->tool_name, "get_weather"); + EXPECT_EQ(events[2].tool_call->arguments, + (nlohmann::json{{"city", "Paris"}})); + + ASSERT_TRUE(events[3].is_finish()); + EXPECT_EQ(events[3].finish_reason, kFinishReasonToolCalls); + ASSERT_TRUE(events[3].usage.has_value()); + EXPECT_EQ(events[3].usage->prompt_tokens, 12); + EXPECT_EQ(events[3].usage->completion_tokens, 34); + + const auto requests = transport->requests(); + ASSERT_EQ(requests.size(), 1); + EXPECT_EQ(requests[0].operation, "ConverseStream"); +} + +// A tool call without an input has an empty object as its arguments, and +// an event of an unknown type is skipped +TEST(BedrockStreamTest, ToolCallWithoutInputAndUnknownEvents) { + auto transport = std::make_shared(); + transport->events = { + {"contentBlockStart", + R"({"contentBlockIndex":0,"start":{"toolUse": + {"toolUseId":"call_1","name":"list_tables"}}})"}, + {"aNewKindOfEvent", R"({"something":"else"})"}, + {"contentBlockStop", R"({"contentBlockIndex":0})"}, + {"messageStop", R"({"stopReason":"tool_use"})"}, + }; + + const auto events = run_stream(transport); + + ASSERT_EQ(events.size(), 2); + ASSERT_TRUE(events[0].is_tool_call()); + EXPECT_EQ(events[0].tool_call->arguments, nlohmann::json::object()); + ASSERT_TRUE(events[1].is_finish()); + EXPECT_EQ(events[1].finish_reason, kFinishReasonToolCalls); + EXPECT_FALSE(events[1].usage.has_value()); +} + +// An event that is not JSON fails the stream instead of being lost +TEST(BedrockStreamTest, InvalidJsonEventIsAnError) { + auto transport = std::make_shared(); + transport->events = { + {"contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"text":"SELECT"}})"}, + {"contentBlockDelta", R"({"contentBlockIndex":0,"delta":{"te)"}, + {"messageStop", R"({"stopReason":"end_turn"})"}, + }; + + const auto events = run_stream(transport); + + ASSERT_EQ(events.size(), 3); + EXPECT_EQ(events[0].text_delta, "SELECT"); + ASSERT_TRUE(events[1].is_error()); + EXPECT_EQ(events[1].error.value(), + "Invalid JSON in the stream event 'contentBlockDelta'"); + // A failed stream does not finish with a clean stop reason + ASSERT_TRUE(events[2].is_finish()); + EXPECT_EQ(events[2].finish_reason, kFinishReasonError); +} + +// A stream that ends without `messageStop` was cut off: what has arrived of +// it is not taken for a whole answer +TEST(BedrockStreamTest, StreamWithoutMessageStopIsAnError) { + auto transport = std::make_shared(); + transport->events = { + {"messageStart", R"({"role":"assistant"})"}, + {"contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"text":"SELECT"}})"}, + }; + + const auto events = run_stream(transport); + + ASSERT_EQ(events.size(), 3); + EXPECT_EQ(events[0].text_delta, "SELECT"); + ASSERT_TRUE(events[1].is_error()); + EXPECT_EQ(events[1].error.value(), + "Stream error: the stream of events ended before the end of the " + "message"); + ASSERT_TRUE(events[2].is_finish()); + EXPECT_EQ(events[2].finish_reason, kFinishReasonError); +} + +// A tool call whose input is not JSON is an error, and not a call +TEST(BedrockStreamTest, InvalidToolInputIsAnError) { + auto transport = std::make_shared(); + transport->events = { + {"contentBlockStart", + R"({"contentBlockIndex":0,"start":{"toolUse": + {"toolUseId":"call_1","name":"get_weather"}}})"}, + {"contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"toolUse":{"input":"{\"city\":"}}})"}, + {"contentBlockStop", R"({"contentBlockIndex":0})"}, + {"messageStop", R"({"stopReason":"tool_use"})"}, + }; + + const auto events = run_stream(transport); + + ASSERT_EQ(events.size(), 2); + ASSERT_TRUE(events[0].is_error()); + EXPECT_NE(events[0].error.value().find( + "Invalid JSON input for tool call 'get_weather'"), + std::string::npos); + ASSERT_TRUE(events[1].is_finish()); + EXPECT_EQ(events[1].finish_reason, kFinishReasonError); +} + +// A request that the service refuses yields its error, with the name of it +TEST(BedrockStreamTest, RefusedRequestYieldsError) { + auto transport = std::make_shared(); + transport->events_response = FakeBedrockTransport::error( + "ThrottlingException", "Rate exceeded", /*retryable=*/true, 429); + + const auto events = run_stream(transport); + + ASSERT_EQ(events.size(), 2); + ASSERT_TRUE(events[0].is_error()); + EXPECT_EQ(events[0].error.value(), "ThrottlingException: Rate exceeded"); + ASSERT_TRUE(events[1].is_finish()); + EXPECT_EQ(events[1].finish_reason, kFinishReasonError); +} + +// A stream that breaks in the middle keeps what has arrived and then fails +TEST(BedrockStreamTest, ErrorAfterEvents) { + auto transport = std::make_shared(); + transport->events = { + {"contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"text":"SELECT"}})"}, + }; + transport->events_response = + FakeBedrockTransport::error("", "Connection reset", /*retryable=*/true); + + const auto events = run_stream(transport); + + ASSERT_EQ(events.size(), 3); + EXPECT_EQ(events[0].text_delta, "SELECT"); + ASSERT_TRUE(events[1].is_error()); + EXPECT_EQ(events[1].error.value(), "Stream error: Connection reset"); + ASSERT_TRUE(events[2].is_finish()); + EXPECT_EQ(events[2].finish_reason, kFinishReasonError); +} + +// The slot of the concurrency limit is given back when the stream completes +TEST(BedrockStreamTest, ReleasesSemaphore) { + auto semaphore = std::make_shared(1); + auto transport = std::make_shared(); + transport->events = {{"messageStop", R"({"stopReason":"end_turn"})"}}; - std::string name_; - std::optional previous_; -}; - -// A stream may outlive the client that created it: it shares ownership of -// everything its background thread uses -TEST_F(BedrockStreamTest, StreamOutlivesClient) { - // Static credentials and an endpoint nothing listens on, so that the request - // fails fast without network access or credential discovery - // (restored when the test ends) - ScopedEnvVar access_key("AWS_ACCESS_KEY_ID", "AKIDEXAMPLE"); - ScopedEnvVar secret_key("AWS_SECRET_ACCESS_KEY", "secret"); - ScopedEnvVar session_token("AWS_SESSION_TOKEN", std::nullopt); - - BedrockConfig config; - config.region = "us-east-1"; - config.endpoint_override = "http://127.0.0.1:1"; - - std::optional stream; { - auto client = create_client(config); - GenerateOptions options(models::kClaudeSonnet, "Hello"); - stream.emplace(client.stream_text(StreamOptions(options))); - } // The client is destroyed while the stream may still be running - - bool saw_error = false; - bool saw_finish = false; - int events_after_finish = 0; - for (const auto& event : *stream) { - if (saw_finish) { - // The finish event is the last one, even though it is pushed by - // another thread while this one iterates - ++events_after_finish; - } else if (event.is_error()) { - saw_error = true; - } else if (event.type == kStreamEventTypeFinish) { - saw_finish = true; - EXPECT_EQ(event.finish_reason, kFinishReasonError); - } + BedrockStreamImpl impl; + semaphore->acquire(); + impl.start_stream(transport, converse_stream_request(), semaphore); + const auto events = read_all(impl); + ASSERT_EQ(events.size(), 1); + EXPECT_EQ(events[0].finish_reason, kFinishReasonStop); } - EXPECT_TRUE(saw_error); - EXPECT_TRUE(saw_finish); - EXPECT_EQ(events_after_finish, 0); + + // Exactly one slot is back: neither kept nor released twice + EXPECT_TRUE(semaphore->try_acquire()); + EXPECT_FALSE(semaphore->try_acquire()); +} + +// A stream owns what its thread uses, so it goes on after its creator let +// go of the service +TEST(BedrockStreamTest, StreamSharesTheTransport) { + auto transport = std::make_shared(); + HeldBedrockTransport* service = transport.get(); + std::weak_ptr weak = transport; + + BedrockStreamImpl impl; + impl.start_stream(std::move(transport), converse_stream_request()); + service->started.get_future().wait(); + // The stream holds the only reference now + ASSERT_FALSE(weak.expired()); + service->release.set_value(); + + const auto events = read_all(impl); + ASSERT_EQ(events.size(), 2); + EXPECT_EQ(events[0].text_delta, "SELECT"); + EXPECT_EQ(events[1].finish_reason, kFinishReasonStop); } -// Note: More comprehensive streaming tests would require mocking -// the AWS BedrockRuntimeClient, which is complex due to the -// event stream handler pattern. Integration tests provide -// better coverage for streaming functionality. +// Stopping a stream abandons its request, and yields neither an error nor a +// finish event for it +TEST(BedrockStreamTest, StopAbandonsTheRequest) { + auto transport = std::make_shared(); + transport->wait_for_stop = true; + + BedrockStreamImpl impl; + impl.start_stream(transport, converse_stream_request()); + transport->started.get_future().wait(); + + impl.stop_stream(); + + EXPECT_TRUE(transport->abandoned); + // What arrived before the stop is still there to read, and nothing else + const auto event = impl.get_next_event(); + EXPECT_TRUE(event.is_text_delta()); + EXPECT_EQ(event.text_delta, "SELECT"); + EXPECT_FALSE(impl.has_more_events()); +} } // namespace } // namespace bedrock diff --git a/tests/unit/bedrock_sts_endpoint_test.cpp b/tests/unit/bedrock_sts_endpoint_test.cpp new file mode 100644 index 0000000..f4cf306 --- /dev/null +++ b/tests/unit/bedrock_sts_endpoint_test.cpp @@ -0,0 +1,143 @@ +// The endpoint of AWS STS, as the endpoint rules of the service make it + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "ai/errors.h" +#include "providers/bedrock/sts_endpoint.h" + +#include + +namespace ai { +namespace bedrock { +namespace { + +// A few partitions, in the format of the partitions of the AWS SDK. The last +// one is made up: a partition without the variants of the endpoints. +const char kPartitions[] = R"({ + "partitions": [ + { + "id": "aws", + "outputs": { + "dnsSuffix": "amazonaws.com", + "dualStackDnsSuffix": "api.aws", + "name": "aws", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + "regions": {"us-east-1": {}, "eu-west-1": {}} + }, + { + "id": "aws-cn", + "outputs": { + "dnsSuffix": "amazonaws.com.cn", + "dualStackDnsSuffix": "api.amazonwebservices.com.cn", + "name": "aws-cn", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^cn\\-\\w+\\-\\d+$", + "regions": {"cn-north-1": {}} + }, + { + "id": "aws-us-gov", + "outputs": { + "dnsSuffix": "amazonaws.com", + "dualStackDnsSuffix": "api.aws", + "name": "aws-us-gov", + "supportsDualStack": true, + "supportsFIPS": true + }, + "regionRegex": "^us\\-gov\\-\\w+\\-\\d+$", + "regions": {"us-gov-west-1": {}} + }, + { + "id": "plain", + "outputs": { + "dnsSuffix": "plain.example", + "name": "plain", + "supportsDualStack": false, + "supportsFIPS": false + }, + "regionRegex": "^plain\\-\\w+\\-\\d+$", + "regions": {} + } + ] +})"; + +std::string endpoint(const std::string& region, + bool use_fips = false, + bool use_dual_stack = false) { + return make_sts_endpoint(kPartitions, region, use_fips, use_dual_stack); +} + +TEST(BedrockStsEndpointTest, RegionalEndpoint) { + EXPECT_EQ(endpoint("us-east-1"), "https://sts.us-east-1.amazonaws.com"); + EXPECT_EQ(endpoint("cn-north-1"), "https://sts.cn-north-1.amazonaws.com.cn"); + EXPECT_EQ(endpoint("us-gov-west-1"), + "https://sts.us-gov-west-1.amazonaws.com"); +} + +// A Region that no partition lists is of the partition whose Regions are +// named like it, and of `aws` when there is none +TEST(BedrockStsEndpointTest, RegionThatIsNotListed) { + EXPECT_EQ(endpoint("cn-northwest-1"), + "https://sts.cn-northwest-1.amazonaws.com.cn"); + EXPECT_EQ(endpoint("us-gov-east-1"), + "https://sts.us-gov-east-1.amazonaws.com"); + EXPECT_EQ(endpoint("plain-north-1"), + "https://sts.plain-north-1.plain.example"); + EXPECT_EQ(endpoint("somewhere"), "https://sts.somewhere.amazonaws.com"); +} + +TEST(BedrockStsEndpointTest, FipsEndpoint) { + EXPECT_EQ(endpoint("us-east-1", /*use_fips=*/true), + "https://sts-fips.us-east-1.amazonaws.com"); + EXPECT_EQ(endpoint("cn-north-1", /*use_fips=*/true), + "https://sts-fips.cn-north-1.amazonaws.com.cn"); + // In AWS GovCloud (US) the Regional endpoint is the FIPS one + EXPECT_EQ(endpoint("us-gov-west-1", /*use_fips=*/true), + "https://sts.us-gov-west-1.amazonaws.com"); +} + +TEST(BedrockStsEndpointTest, DualStackEndpoint) { + EXPECT_EQ(endpoint("eu-west-1", /*use_fips=*/false, /*use_dual_stack=*/true), + "https://sts.eu-west-1.api.aws"); + EXPECT_EQ(endpoint("eu-west-1", /*use_fips=*/true, /*use_dual_stack=*/true), + "https://sts-fips.eu-west-1.api.aws"); +} + +// A variant that the partition does not have is not replaced with the +// Regional endpoint silently +TEST(BedrockStsEndpointTest, VariantThatThePartitionDoesNotHave) { + EXPECT_THROW(endpoint("plain-north-1", /*use_fips=*/true), + ConfigurationError); + EXPECT_THROW( + endpoint("plain-north-1", /*use_fips=*/false, /*use_dual_stack=*/true), + ConfigurationError); + EXPECT_THROW( + endpoint("plain-north-1", /*use_fips=*/true, /*use_dual_stack=*/true), + ConfigurationError); +} + +TEST(BedrockStsEndpointTest, PartitionsThatCannotBeRead) { + EXPECT_THROW(make_sts_endpoint("not JSON", "us-east-1", false, false), + ConfigurationError); + EXPECT_THROW(make_sts_endpoint("{}", "us-east-1", false, false), + ConfigurationError); +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +// Placeholder test when Bedrock is not enabled +TEST(BedrockStsEndpointTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock support not enabled"; +} + +#endif // AI_SDK_HAS_BEDROCK diff --git a/tests/unit/input_validator_test.cpp b/tests/unit/input_validator_test.cpp index 78eed5e..96a502b 100644 --- a/tests/unit/input_validator_test.cpp +++ b/tests/unit/input_validator_test.cpp @@ -55,13 +55,28 @@ TEST_F(InputValidatorTest, ValidArnModelIds) { "foundation-model/anthropic/claude")); } +// The form of a model ID is for Bedrock to say: what it lists and documents +// is not refused before it is asked +TEST_F(InputValidatorTest, ValidModelIdsOfOtherForms) { + EXPECT_TRUE( + validator_.is_valid_model_id("us-gov.anthropic.claude-sonnet-5-5")); + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws:bedrock:us-east-1:123456789012:" + "application-inference-profile/abcdef123456")); + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws-us-gov:bedrock:us-gov-west-1:123456789012:" + "inference-profile/us-gov.anthropic.claude-sonnet-5-5")); + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws:bedrock:us-east-1:123456789012:imported-model/abcdef123456")); +} + // Test invalid model IDs TEST_F(InputValidatorTest, InvalidModelIds) { EXPECT_FALSE(validator_.is_valid_model_id("")); - EXPECT_FALSE(validator_.is_valid_model_id("invalid")); - EXPECT_FALSE(validator_.is_valid_model_id("no-dot-separator")); EXPECT_FALSE(validator_.is_valid_model_id("has spaces.model")); - EXPECT_FALSE(validator_.is_valid_model_id("special!chars.model")); + EXPECT_FALSE(validator_.is_valid_model_id("line\nbreak.model")); + EXPECT_FALSE(validator_.is_valid_model_id("tab\tseparated.model")); + EXPECT_FALSE(validator_.is_valid_model_id("non-ascii-\xC3\xA9.model")); } // Test max_tokens validation diff --git a/tests/utils/fake_bedrock_transport.h b/tests/utils/fake_bedrock_transport.h new file mode 100644 index 0000000..b27d497 --- /dev/null +++ b/tests/utils/fake_bedrock_transport.h @@ -0,0 +1,147 @@ +#pragma once + +#include "providers/bedrock/bedrock_transport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { +namespace test { + +/// A service of Bedrock that answers from a script instead of the network, +/// and remembers what it was asked +class FakeBedrockTransport : public BedrockTransport { + public: + static TransportResponse ok(std::string body) { + TransportResponse response; + response.success = true; + response.status = 200; + response.body = std::move(body); + response.request_id = "fake-request-id"; + return response; + } + + static TransportResponse error(std::string name, + std::string message, + bool retryable = false, + int status = 400) { + TransportResponse response; + response.status = status; + response.error_name = std::move(name); + response.error_message = std::move(message); + response.retryable = retryable; + return response; + } + + /// What `send` answers with, one response per request; the last one + /// repeats + std::vector responses; + + /// The events that `send_for_events` delivers, as pairs of a type and a + /// JSON, and what it returns after them + std::vector> events; + TransportResponse events_response = ok(""); + + TransportResponse send(const TransportRequest& request) override { + std::lock_guard lock(mutex_); + requests_.push_back(request); + if (responses.empty()) { + return error("", "The fake transport has no response for this request"); + } + return responses[std::min(requests_.size(), responses.size()) - 1]; + } + + TransportResponse send_for_events( + const TransportRequest& request, + const EventHandler& on_event, + const ContinueHandler& should_continue) override { + { + std::lock_guard lock(mutex_); + requests_.push_back(request); + } + for (const auto& [type, payload] : events) { + if (!should_continue()) { + break; + } + on_event(type, payload); + } + return events_response; + } + + std::vector requests() const { + std::lock_guard lock(mutex_); + return requests_; + } + + private: + mutable std::mutex mutex_; + std::vector requests_; +}; + +/// A service that has sent the beginning of a stream of events, and keeps +/// the response open until it is told to end it (or, with `wait_for_stop`, +/// until the request is abandoned) +class HeldBedrockTransport : public BedrockTransport { + public: + TransportResponse send(const TransportRequest& /*request*/) override { + return FakeBedrockTransport::error("", "Not a streaming request"); + } + + TransportResponse send_for_events( + const TransportRequest& /*request*/, + const EventHandler& on_event, + const ContinueHandler& should_continue) override { + on_event("contentBlockDelta", + R"({"contentBlockIndex":0,"delta":{"text":"SELECT"}})"); + started.set_value(); + if (wait_for_stop) { + // An HTTP client asks whether to go on between the pieces of a + // response + while (should_continue()) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + abandoned = true; + return FakeBedrockTransport::error("", "The request was abandoned"); + } + release.get_future().wait(); + on_event("messageStop", R"({"stopReason":"end_turn"})"); + return FakeBedrockTransport::ok(""); + } + + bool wait_for_stop = false; + /// Set when the first event has been delivered + std::promise started; + /// Set it to let the response end + std::promise release; + std::atomic abandoned{false}; +}; + +/// The two services of Bedrock, both fake +struct FakeBedrockServices { + std::shared_ptr runtime = + std::make_shared(); + std::shared_ptr control_plane = + std::make_shared(); + + BedrockTransports transports() const { + BedrockTransports result; + result.runtime = runtime; + result.control_plane = control_plane; + result.region = "us-east-1"; + return result; + } +}; + +} // namespace test +} // namespace bedrock +} // namespace ai