diff --git a/.gitignore b/.gitignore index 75030b4..690b256 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Build directories build/ build-*/ +build_*/ out/ bin/ lib/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 6c99325..33d92c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,6 +16,7 @@ set(CMAKE_CXX_EXTENSIONS OFF) option(BUILD_TESTS "Build tests" OFF) option(BUILD_EXAMPLES "Build example applications" ON) option(BUILD_SHARED_LIBS "Build shared libraries" OFF) +option(AI_SDK_ENABLE_BEDROCK "Enable Amazon Bedrock provider (requires AWS SDK)" OFF) # Add third party directory (vendored and CMake-fetched dependencies) add_subdirectory(third_party) @@ -68,6 +69,16 @@ configure_ai_component(ai-sdk-cpp-openai) configure_ai_component(ai-sdk-cpp-anthropic) 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) + + add_library(ai-sdk-cpp-bedrock) + set_target_properties(ai-sdk-cpp-bedrock PROPERTIES EXPORT_NAME bedrock) + add_library(ai::bedrock ALIAS ai-sdk-cpp-bedrock) + configure_ai_component(ai-sdk-cpp-bedrock) +endif() + # Configure main interface library target_include_directories(ai-sdk-cpp INTERFACE @@ -125,6 +136,26 @@ target_sources(ai-sdk-cpp-langfuse src/langfuse/tracer.cpp ) +# Bedrock provider sources (conditional) +if(AI_SDK_ENABLE_BEDROCK) + set(BEDROCK_SOURCES + src/providers/bedrock/bedrock_client.cpp + src/providers/bedrock/bedrock_request_mapper.cpp + src/providers/bedrock/bedrock_response_parser.cpp + src/providers/bedrock/bedrock_stream.cpp + src/providers/bedrock/bedrock_factory.cpp + src/providers/bedrock/bedrock_credentials.cpp + # Security components + src/providers/bedrock/input_validator.cpp + src/providers/bedrock/credential_redactor.cpp + src/providers/bedrock/secure_logger.cpp + src/providers/bedrock/model_discovery.cpp + # SDK lifecycle management + src/providers/bedrock/aws_sdk_manager.cpp + ) + target_sources(ai-sdk-cpp-bedrock PRIVATE ${BEDROCK_SOURCES}) +endif() + # Link dependencies target_link_libraries(ai-sdk-cpp-core PUBLIC @@ -188,6 +219,23 @@ target_compile_definitions(ai-sdk-cpp-langfuse ${HTTPLIB_COMPILE_DEFS} ) +# Bedrock provider dependencies (uses AWS SDK instead of httplib) +if(AI_SDK_ENABLE_BEDROCK) + target_link_libraries(ai-sdk-cpp-bedrock + PUBLIC + ai::core + nlohmann_json::nlohmann_json + PRIVATE + ${AWSSDK_LINK_LIBRARIES} + $ + ) + + target_compile_definitions(ai-sdk-cpp-bedrock + PUBLIC + AI_SDK_HAS_BEDROCK=1 + ) +endif() + # Core needs HTTP definitions too target_compile_definitions(ai-sdk-cpp-core PRIVATE @@ -203,6 +251,14 @@ target_link_libraries(ai-sdk-cpp ai::langfuse ) +# Conditionally link Bedrock to main library +if(AI_SDK_ENABLE_BEDROCK) + target_link_libraries(ai-sdk-cpp + INTERFACE + ai::bedrock + ) +endif() + # Define all component availability for main library target_compile_definitions(ai-sdk-cpp INTERFACE @@ -211,6 +267,14 @@ target_compile_definitions(ai-sdk-cpp AI_SDK_HAS_LANGFUSE=1 ) +# Add Bedrock availability definition when enabled +if(AI_SDK_ENABLE_BEDROCK) + target_compile_definitions(ai-sdk-cpp + INTERFACE + AI_SDK_HAS_BEDROCK=1 + ) +endif() + # List of all concrete component targets set(COMPONENT_TARGETS ai-sdk-cpp-core @@ -218,6 +282,9 @@ set(COMPONENT_TARGETS ai-sdk-cpp-anthropic ai-sdk-cpp-langfuse ) +if(AI_SDK_ENABLE_BEDROCK) + list(APPEND COMPONENT_TARGETS ai-sdk-cpp-bedrock) +endif() # Common compile options if(MSVC) @@ -315,5 +382,6 @@ message(STATUS " Build type: ${CMAKE_BUILD_TYPE}") message(STATUS " C++ standard: ${CMAKE_CXX_STANDARD}") message(STATUS " Build examples: ${BUILD_EXAMPLES}") message(STATUS " Build tests: ${BUILD_TESTS}") +message(STATUS " Bedrock provider: ${AI_SDK_ENABLE_BEDROCK}") message(STATUS " Install prefix: ${CMAKE_INSTALL_PREFIX}") message(STATUS "") diff --git a/README.md b/README.md index 93208d4..81c910d 100644 --- a/README.md +++ b/README.md @@ -346,25 +346,171 @@ This approach works with any OpenAI-compatible API provider. Simply provide: See the [OpenRouter example](examples/openrouter_example.cpp) for a complete demonstration. +#### Amazon Bedrock Integration + +Amazon Bedrock provides access to foundation models from Anthropic, Amazon, Meta, and others through AWS infrastructure. The Bedrock provider uses the [Converse API](https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html), including streaming and tool calling (with multi-step tool execution via `max_steps`), and uses AWS credentials and IAM for authentication. Assumed-role and web identity credentials are refreshed automatically. + +```cpp +#include +#include + +int main() { + // Uses AWS_REGION env var and default credential chain + auto client = ai::bedrock::create_client(); + + ai::GenerateOptions options(ai::bedrock::models::kClaudeSonnet, + "Explain cloud computing in simple terms."); + options.system = "You are a helpful assistant."; + auto result = client.generate_text(options); + + if (result) { + std::cout << result.text << std::endl; + } else { + std::cerr << result.error_message() << std::endl; + } + + return 0; +} +``` + +##### Bedrock Configuration Options + +```cpp +#include + +int main() { + ai::bedrock::BedrockConfig config; + + // AWS region (required - or set AWS_REGION env var) + config.region = "us-east-1"; + + // Optional: Use a specific AWS profile + config.profile = "my-profile"; + + // Optional: Custom endpoint for VPC endpoints or local testing + config.endpoint_override = "https://vpce-xxx.bedrock-runtime.us-east-1.vpce.amazonaws.com"; + + // Optional: Cross-account access via STS AssumeRole + config.role_arn = "arn:aws:iam::123456789012:role/BedrockAccessRole"; + config.external_id = "my-external-id"; // Optional security enhancement + + // Optional: EKS/OIDC web identity federation + config.web_identity_token_file = "/var/run/secrets/eks.amazonaws.com/serviceaccount/token"; + + auto client = ai::bedrock::create_client(config); + + return 0; +} +``` + +##### Bedrock Security Configuration + +```cpp +ai::bedrock::SecurityConfig security; + +// Concurrency control +security.max_concurrent_requests = 10; + +// Timeouts +security.connection_timeout = std::chrono::seconds(5); +security.request_timeout = std::chrono::seconds(120); + +// Input validation limits +security.max_prompt_length = 200000; +security.max_message_length = 200000; + +ai::bedrock::BedrockConfig config; +config.security = security; +auto client = ai::bedrock::create_client(config); +``` + +##### Available Bedrock Models + +```cpp +// Claude models (current generation), as global inference profile IDs: +// current Claude models need an inference profile for on-demand invocation +ai::bedrock::models::kClaudeFable // global.anthropic.claude-fable-5-2 +ai::bedrock::models::kClaudeOpus // global.anthropic.claude-opus-5-5 +ai::bedrock::models::kClaudeSonnet // global.anthropic.claude-sonnet-5-5 +ai::bedrock::models::kClaudeHaiku // global.anthropic.claude-haiku-5-5 + +// Geographic inference profiles are passed as plain strings, +// e.g. "us.anthropic.claude-sonnet-5-5" or "eu.anthropic.claude-opus-5-5" + +// Amazon Titan models +ai::bedrock::models::kTitanTextExpress // amazon.titan-text-express-v1 +ai::bedrock::models::kTitanTextLite // amazon.titan-text-lite-v1 +ai::bedrock::models::kTitanTextPremier // amazon.titan-text-premier-v1:0 + +// Meta Llama models +ai::bedrock::models::kLlama3_8B // meta.llama3-8b-instruct-v1:0 +ai::bedrock::models::kLlama3_70B // meta.llama3-70b-instruct-v1:0 +``` + +##### Bedrock Streaming + +```cpp +#include +#include + +int main() { + auto client = ai::bedrock::create_client(); + + ai::GenerateOptions options(ai::bedrock::models::kClaudeSonnet, + "Write a haiku about programming."); + options.system = "You are a helpful assistant."; + auto stream = client.stream_text(ai::StreamOptions(options)); + + for (const auto& event : stream) { + if (event.is_text_delta()) { + std::cout << event.text_delta << std::flush; + } else if (event.is_error()) { + std::cerr << event.error.value_or("unknown error") << std::endl; + } + } + + return 0; +} +``` + +##### Building with Bedrock Support + +Bedrock support requires the AWS SDK for C++. Enable it with the CMake option: + +```bash +cmake -B build -DAI_SDK_ENABLE_BEDROCK=ON +cmake --build build +``` + +On macOS with Homebrew: +```bash +brew install aws-sdk-cpp +cmake -B build -DAI_SDK_ENABLE_BEDROCK=ON +cmake --build build +``` + ## Features ### Currently Supported -- ✅ **Text Generation**: Generate text completions with OpenAI and Anthropic models +- ✅ **Text Generation**: Generate text completions with OpenAI, Anthropic, and Bedrock models - ✅ **Streaming**: Real-time streaming of generated content - ✅ **Multi-turn Conversations**: Support for conversation history - ✅ **Error Handling**: Comprehensive error handling with optional types - ✅ **Embeddings**: OpenAI text embedding support +- ✅ **Amazon Bedrock**: AWS-native access to Claude, Titan, and Llama models ### Recently Added - ✅ **Tool Calling**: Function calling and tool integration with multi-step support - ✅ **Async Tools**: Asynchronous tool execution with parallel processing - ✅ **Configurable Retries**: Customizable retry behavior with exponential backoff +- ✅ **Bedrock Provider**: Amazon Bedrock integration via the Converse API (optional, requires the AWS SDK for C++) ### Coming Soon - 🚧 **Additional Providers**: Google, Cohere, and other providers +- 🚧 **Bedrock Embeddings**: Text embedding support for Bedrock - 🚧 **Image Generation**: Support for image generation models ## Examples diff --git a/cmake/ai-sdk-cpp-config.cmake.in b/cmake/ai-sdk-cpp-config.cmake.in index b6801db..1c660a3 100644 --- a/cmake/ai-sdk-cpp-config.cmake.in +++ b/cmake/ai-sdk-cpp-config.cmake.in @@ -12,11 +12,20 @@ set(AI_SDK_VERSION "@PROJECT_VERSION@") # Find PUBLIC dependencies only 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) +endif() + # Include the targets file include("${CMAKE_CURRENT_LIST_DIR}/ai-sdk-cpp-targets.cmake") # Available components set(AI_SDK_AVAILABLE_COMPONENTS core openai anthropic langfuse) +if(AI_SDK_ENABLE_BEDROCK) + list(APPEND AI_SDK_AVAILABLE_COMPONENTS bedrock) +endif() # Check requested components set(AI_SDK_REQUESTED_COMPONENTS ${ai-sdk-cpp_FIND_COMPONENTS}) diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index fa9908e..1df494b 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -40,6 +40,7 @@ add_ai_example(retry_config_example retry_config_example.cpp) # Simple test examples add_ai_example(test_openai test_openai.cpp) add_ai_example(test_anthropic test_anthropic.cpp) +add_ai_example(test_bedrock test_bedrock.cpp) # OpenAI Responses API example (tool calling with the GPT-6 models) add_ai_example(openai_responses openai_responses.cpp) @@ -63,7 +64,8 @@ add_ai_example(langfuse_tracing langfuse_tracing.cpp) # Component-specific examples add_subdirectory(components/openai) -add_subdirectory(components/anthropic) +add_subdirectory(components/anthropic) +add_subdirectory(components/bedrock) add_subdirectory(components/all) # Message to show how to run examples @@ -87,4 +89,5 @@ message(STATUS "") message(STATUS "Component-specific examples:") message(STATUS " ./examples/components/openai/openai_component_demo (OpenAI + Core only)") message(STATUS " ./examples/components/anthropic/anthropic_component_demo (Anthropic + Core only)") +message(STATUS " ./examples/components/bedrock/bedrock_component_demo (Bedrock + Core only)") message(STATUS " ./examples/components/all/all_components_demo (All components)") diff --git a/examples/basic_chat.cpp b/examples/basic_chat.cpp index 2d24d80..758ed45 100644 --- a/examples/basic_chat.cpp +++ b/examples/basic_chat.cpp @@ -4,12 +4,13 @@ * This example demonstrates basic text generation using the AI SDK. * It shows how to: * - Use the simple generate_text API - * - Handle both OpenAI and Anthropic providers + * - Handle OpenAI, Anthropic, and Bedrock providers * - Check for errors and display results * * Usage: * export OPENAI_API_KEY=your_key_here * export ANTHROPIC_API_KEY=your_key_here + * # For Bedrock: configure AWS credentials (env vars, profile, or IAM role) * ./basic_chat */ @@ -19,6 +20,10 @@ #include #include +#ifdef AI_SDK_HAS_BEDROCK +#include +#endif + int main() { std::cout << "AI SDK C++ - Basic Chat Example\n"; std::cout << "================================\n\n"; @@ -111,8 +116,39 @@ int main() { std::cout << "Error: " << result4.error_message() << "\n\n"; } - // Example 5: Using GenerateOptions for more control - std::cout << "5. Using GenerateOptions for fine control:\n"; + // Example 5: Try AWS Bedrock (if available and credentials configured) +#ifdef AI_SDK_HAS_BEDROCK + std::cout << "5. Generating text with AWS Bedrock:\n"; + std::cout << "Question: What are the benefits of cloud computing?\n\n"; + + auto maybe_bedrock = ai::bedrock::try_create_client(); + if (maybe_bedrock.has_value()) { + auto& bedrock_client = maybe_bedrock.value(); + ai::GenerateOptions bedrock_options; + bedrock_options.model = ai::bedrock::models::kClaudeSonnet; + bedrock_options.prompt = + "What are the benefits of cloud computing? Give a brief answer."; + bedrock_options.max_tokens = 150; + + auto bedrock_result = bedrock_client.generate_text(bedrock_options); + + if (bedrock_result) { + std::cout << "Answer: " << bedrock_result.text << "\n"; + std::cout << "Usage: " << bedrock_result.usage.total_tokens + << " tokens\n\n"; + } else { + std::cout << "Error: " << bedrock_result.error_message() << "\n\n"; + } + } else { + std::cout << "Bedrock client not available (check AWS credentials)\n\n"; + } +#else + std::cout << "5. AWS Bedrock: Not available in this build\n"; + std::cout << " Build with -DAI_SDK_ENABLE_BEDROCK=ON to enable\n\n"; +#endif + + // Example 6: Using GenerateOptions for more control + std::cout << "6. Using GenerateOptions for fine control:\n"; ai::GenerateOptions options; options.model = ai::openai::models::kGpt56; @@ -135,6 +171,7 @@ int main() { std::cout << "\nTip: Make sure to set your API keys:\n"; std::cout << " export OPENAI_API_KEY=your_openai_key\n"; std::cout << " export ANTHROPIC_API_KEY=your_anthropic_key\n"; + std::cout << " # For Bedrock: configure AWS credentials\n"; return 0; } \ No newline at end of file diff --git a/examples/components/bedrock/CMakeLists.txt b/examples/components/bedrock/CMakeLists.txt new file mode 100644 index 0000000..c7a01e0 --- /dev/null +++ b/examples/components/bedrock/CMakeLists.txt @@ -0,0 +1,17 @@ +# Bedrock-only component example + +if(AI_SDK_ENABLE_BEDROCK) + add_executable(bedrock_component_demo main.cpp) + target_link_libraries(bedrock_component_demo PRIVATE + ai::core + ai::bedrock + ) + + set_target_properties(bedrock_component_demo PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/examples/components/bedrock + ) + + message(STATUS "Bedrock component example will be built in: ${CMAKE_BINARY_DIR}/examples/components/bedrock/") +else() + message(STATUS "Bedrock component example skipped (AI_SDK_ENABLE_BEDROCK=OFF)") +endif() diff --git a/examples/components/bedrock/main.cpp b/examples/components/bedrock/main.cpp new file mode 100644 index 0000000..7deb4d0 --- /dev/null +++ b/examples/components/bedrock/main.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include + +int main() { + std::cout << "AI SDK C++ - Bedrock Component Demo\n"; + std::cout << "====================================\n\n"; + + std::cout << "Available components:\n"; + std::cout << "- Core: YES\n"; + +#ifdef AI_SDK_HAS_OPENAI + std::cout << "- OpenAI: YES\n"; +#else + std::cout << "- OpenAI: NO\n"; +#endif + +#ifdef AI_SDK_HAS_ANTHROPIC + std::cout << "- Anthropic: YES\n"; +#else + std::cout << "- Anthropic: NO\n"; +#endif + +#ifdef AI_SDK_HAS_BEDROCK + std::cout << "- Bedrock: YES\n"; +#else + std::cout << "- Bedrock: NO\n"; +#endif + + std::cout << "\n"; + + // Test core functionality + std::cout << "Testing core functionality...\n"; + ai::GenerateOptions options; + options.model = ai::bedrock::models::kClaudeSonnet; + options.prompt = "Hello world"; + std::cout << "✓ Core types work fine\n\n"; + + // Test Bedrock functionality +#ifdef AI_SDK_HAS_BEDROCK + std::cout << "Testing Bedrock functionality...\n"; + try { + auto maybe_client = ai::bedrock::try_create_client(); + if (maybe_client.has_value()) { + std::cout << "✓ Bedrock client created successfully\n"; + std::cout << "✓ Provider: " << maybe_client->provider_name() << "\n"; + std::cout << "✓ Default model: " << maybe_client->default_model() << "\n"; + std::cout << "✓ Available models: " << ai::bedrock::models::kClaudeSonnet + << ", " << ai::bedrock::models::kClaudeHaiku << ", " + << ai::bedrock::models::kTitanTextExpress << "\n"; + } else { + std::cout << "✗ Bedrock client creation failed (check AWS credentials)\n"; + } + } catch (const std::exception& e) { + std::cout << "✗ Bedrock client failed: " << e.what() << "\n"; + } +#else + std::cout << "Bedrock functionality not available\n"; +#endif + + // Demonstrate that OpenAI is NOT available +#ifdef AI_SDK_HAS_OPENAI + std::cout << "\nTesting OpenAI functionality...\n"; + auto openai_client = ai::openai::create_client(); + std::cout << "✓ OpenAI client created\n"; +#else + std::cout + << "\nOpenAI functionality intentionally not available in this build\n"; + std::cout << "This example only links ai::bedrock component\n"; +#endif + + return 0; +} diff --git a/examples/test_bedrock.cpp b/examples/test_bedrock.cpp new file mode 100644 index 0000000..b60ea00 --- /dev/null +++ b/examples/test_bedrock.cpp @@ -0,0 +1,88 @@ +#include "ai/logger.h" + +#include + +#include + +#ifdef AI_SDK_HAS_BEDROCK +#include +#endif + +int main() { +#ifdef AI_SDK_HAS_BEDROCK + try { + // Enable debug logging + ai::logger::install_logger(std::make_shared( + ai::logger::LogLevel::kLogLevelInfo)); + + // Create Bedrock client + auto maybe_client = ai::bedrock::try_create_client(); + if (!maybe_client.has_value()) { + std::cerr << "Failed to create Bedrock client. Check AWS credentials.\n"; + return 1; + } + auto& client = maybe_client.value(); + + std::cout << "Bedrock client created successfully\n"; + std::cout << "Provider: " << client.provider_name() << "\n"; + std::cout << "Default model: " << client.default_model() << "\n\n"; + + // Test simple generation + std::cout << "Testing Bedrock text generation...\n\n"; + + ai::GenerateOptions options; + options.model = ai::bedrock::models::kClaudeSonnet; + options.system = "You are a helpful assistant."; + options.prompt = "Why is the sky blue? Give a short answer."; + options.max_tokens = 200; + + auto result = client.generate_text(options); + + if (result) { + std::cout << "Response: " << result.text << "\n"; + std::cout << "Model: " << result.model.value_or("unknown") << "\n"; + std::cout << "Tokens used: " << result.usage.total_tokens << "\n"; + std::cout << "Finish reason: " << result.finishReasonToString() << "\n"; + } else { + std::cout << "Error: " << result.error_message() << "\n"; + } + + // Test streaming + std::cout << "\nTesting streaming...\n"; + + ai::StreamOptions stream_options; + stream_options.model = ai::bedrock::models::kClaudeSonnet; + stream_options.prompt = + "Count from 1 to 5 slowly and with each number say 'tick'"; + stream_options.max_tokens = 100; + + auto stream = client.stream_text(stream_options); + + for (const auto& event : stream) { + if (event.is_text_delta()) { + std::cout << event.text_delta << std::flush; + } else if (event.is_error()) { + std::cout << "\nStream error: " << event.error.value_or("unknown") + << "\n"; + } else if (event.is_finish()) { + std::cout << "\n\nStream finished.\n"; + if (event.usage.has_value()) { + std::cout << "Total tokens: " << event.usage->total_tokens << "\n"; + } else { + std::cout << "Note: Token usage data may not be available in " + "streaming mode.\n"; + } + } + } + + } catch (const std::exception& e) { + std::cerr << "Exception: " << e.what() << "\n"; + return 1; + } +#else + std::cout << "Bedrock support not enabled in this build.\n"; + std::cout << "Build with -DAI_SDK_ENABLE_BEDROCK=ON to enable.\n"; +#endif + + return 0; +} diff --git a/include/ai/bedrock.h b/include/ai/bedrock.h new file mode 100644 index 0000000..efdbaa7 --- /dev/null +++ b/include/ai/bedrock.h @@ -0,0 +1,154 @@ +#pragma once + +#ifndef AI_SDK_HAS_BEDROCK +#error \ + "Bedrock component not available. Link with ai::bedrock or enable AI_SDK_ENABLE_BEDROCK to use Bedrock functionality." +#endif + +#include "types/client.h" + +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +namespace models { +/// Claude models on Bedrock, as global cross-region inference profile IDs. +/// The current Claude models cannot be invoked on demand with the bare model +/// ID (`anthropic.claude-...`) in most or all Regions: Bedrock requires an +/// inference profile. Geographic profiles keep the processing in one +/// geography, e.g. "us.anthropic.claude-sonnet-5-5" or +/// "eu.anthropic.claude-opus-5-5"; which geographies exist differs per model. +constexpr const char* kClaudeFable52 = "global.anthropic.claude-fable-5-2"; +constexpr const char* kClaudeOpus55 = "global.anthropic.claude-opus-5-5"; +constexpr const char* kClaudeSonnet55 = "global.anthropic.claude-sonnet-5-5"; +constexpr const char* kClaudeHaiku55 = "global.anthropic.claude-haiku-5-5"; + +/// Aliases for the current generation of each Claude model family +constexpr const char* kClaudeFable = kClaudeFable52; +constexpr const char* kClaudeOpus = kClaudeOpus55; +constexpr const char* kClaudeSonnet = kClaudeSonnet55; +constexpr const char* kClaudeHaiku = kClaudeHaiku55; + +/// Amazon Titan models (direct model IDs - on-demand supported) +constexpr const char* kTitanTextExpress = "amazon.titan-text-express-v1"; +constexpr const char* kTitanTextLite = "amazon.titan-text-lite-v1"; +constexpr const char* kTitanTextPremier = "amazon.titan-text-premier-v1:0"; + +/// Amazon Nova models (direct model IDs - on-demand supported) +constexpr const char* kNovaLite = "amazon.nova-lite-v1:0"; +constexpr const char* kNovaPro = "amazon.nova-pro-v1:0"; +constexpr const char* kNovaMicro = "amazon.nova-micro-v1:0"; + +/// Meta Llama models +constexpr const char* kLlama3_8B = "meta.llama3-8b-instruct-v1:0"; +constexpr const char* kLlama3_70B = "meta.llama3-70b-instruct-v1:0"; + +/// Default model used when none is specified +constexpr const char* kDefaultModel = kClaudeSonnet; +} // namespace models + +/// Model information returned by model discovery +struct ModelInfo { + std::string model_id; // Full model identifier + std::string provider; // Model provider (e.g., "anthropic", "amazon", "meta") + std::string name; // Human-readable model name + bool supports_streaming; // Whether model supports streaming + bool supports_system_prompt; // Whether model supports system prompts + std::vector capabilities; // List of capabilities +}; + +/// Security configuration for the Bedrock client +struct SecurityConfig { + /// Maximum concurrent requests per client (default: 10) + int max_concurrent_requests = 10; + + /// Connection timeout (default: 5 seconds) + std::chrono::seconds connection_timeout{5}; + + /// Request timeout (default: 120 seconds) + std::chrono::seconds request_timeout{120}; + + /// Maximum prompt length in characters (default: 200000) + size_t max_prompt_length = 200000; + + /// Maximum total message content length (default: 200000) + size_t max_message_length = 200000; +}; + +/// Configuration for Bedrock client +struct BedrockConfig { + /// AWS region (e.g., "us-east-1"). If empty, uses AWS_REGION env var. + std::string region; + + /// AWS profile name for credential resolution. If empty, uses default chain. + std::string profile; + + /// Custom endpoint URL for VPC endpoints or local testing. + std::string endpoint_override; + + /// IAM role ARN for cross-account access via STS AssumeRole. + /// If set, the provider will assume this role before making API calls. + std::string role_arn; + + /// External ID for STS AssumeRole (optional, for enhanced security). + std::string external_id; + + /// Path to web identity token file for EKS/OIDC authentication. + /// Used with role_arn for web identity federation. + std::string web_identity_token_file; + + /// Role session name for STS AssumeRole (default: + /// "bedrock-provider-session"). + std::string role_session_name = "bedrock-provider-session"; + + /// Security configuration + SecurityConfig security; +}; + +/// Create a Bedrock client with default configuration +/// Uses AWS_REGION environment variable and default credential chain +/// @throws ConfigurationError if region is not configured +/// @return Configured Bedrock client +Client create_client(); + +/// Create a Bedrock client with explicit configuration +/// @param config Bedrock configuration +/// @throws ConfigurationError if region is not configured +/// @return Configured Bedrock client +Client create_client(const BedrockConfig& config); + +/// 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 +std::optional try_create_client(); + +/// List available foundation models in the user's AWS account +/// @param config Bedrock configuration (uses region and credentials) +/// @return Vector of ModelInfo for available models +/// @throws ConfigurationError if region is not configured +/// @throws std::runtime_error if API call fails +/// @note Every call queries the Bedrock API (`ListFoundationModels`) +std::vector list_available_models(const BedrockConfig& config = {}); + +/// Check that a model is offered in the configured Region: the model ID (or, +/// for an inference profile ID, the model ID after the geography prefix) is in +/// the `ListFoundationModels` result. Model access grants are not checked. +/// @param model_id The model identifier to validate +/// @param config Bedrock configuration +/// @return true if the model is accessible, false otherwise +/// @note This does not throw - returns false for any access issues +bool validate_model_access(const std::string& model_id, + const BedrockConfig& config = {}); + +/// Get the provider name +/// @return "bedrock" +constexpr const char* provider_name() { + return "bedrock"; +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/aws_sdk_manager.cpp b/src/providers/bedrock/aws_sdk_manager.cpp new file mode 100644 index 0000000..d2bff37 --- /dev/null +++ b/src/providers/bedrock/aws_sdk_manager.cpp @@ -0,0 +1,23 @@ +#include "aws_sdk_manager.h" + +#include "secure_logger.h" + +#include + +#include + +namespace ai { +namespace bedrock { + +void ensure_aws_sdk_initialized() { + static std::once_flag once; + std::call_once(once, [] { + // Intentionally leaked: see the comment in the header. + auto* options = new Aws::SDKOptions(); + Aws::InitAPI(*options); + SecureLogger::log_debug("AWS SDK initialized"); + }); +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/aws_sdk_manager.h b/src/providers/bedrock/aws_sdk_manager.h new file mode 100644 index 0000000..7232f1b --- /dev/null +++ b/src/providers/bedrock/aws_sdk_manager.h @@ -0,0 +1,16 @@ +#pragma once + +namespace ai { +namespace bedrock { + +/// Initializes the AWS SDK for C++ once per process. +/// +/// 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(); + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_client.cpp b/src/providers/bedrock/bedrock_client.cpp new file mode 100644 index 0000000..240e7cb --- /dev/null +++ b/src/providers/bedrock/bedrock_client.cpp @@ -0,0 +1,263 @@ +#include "bedrock_client.h" + +#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" +#include "input_validator.h" +#include "secure_logger.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace ai { +namespace bedrock { + +namespace { + +/// Releases an acquired semaphore slot on scope exit +class SemaphoreGuard { + public: + explicit SemaphoreGuard(std::counting_semaphore<>& semaphore) + : semaphore_(semaphore) { + semaphore_.acquire(); + } + ~SemaphoreGuard() { semaphore_.release(); } + + SemaphoreGuard(const SemaphoreGuard&) = delete; + SemaphoreGuard& operator=(const SemaphoreGuard&) = delete; + + private: + std::counting_semaphore<>& semaphore_; +}; + +} // namespace + +// PImpl implementation - hides AWS SDK dependencies from public headers +struct BedrockClient::Impl { + // Shared with streams, which may outlive the client + std::shared_ptr client; + std::shared_ptr> request_semaphore; + + BedrockRequestMapper request_mapper; + BedrockResponseParser response_parser; + InputValidator input_validator; + std::string region; + std::string profile; + std::string endpoint_override; + bool valid{false}; + + explicit Impl(const BedrockConfig& config) + : input_validator(config.security) { + 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); + + valid = true; + SecureLogger::log_debug("Bedrock client initialized - region: " + region); + } +}; + +BedrockClient::BedrockClient(const BedrockConfig& config) { + ensure_aws_sdk_initialized(); + pimpl_ = std::make_unique(config); + SecureLogger::log_info("Bedrock client created for region: " + + pimpl_->region); +} + +BedrockClient::~BedrockClient() = default; + +GenerateResult BedrockClient::generate_text(const GenerateOptions& options) { + if (options.has_tools() && options.is_multi_step()) { + return MultiStepCoordinator::execute_multi_step( + options, [this](const GenerateOptions& step_options) { + return generate_text_single_step(step_options); + }); + } + return generate_text_single_step(options); +} + +GenerateResult BedrockClient::generate_text_single_step( + const GenerateOptions& options) { + auto start_time = std::chrono::steady_clock::now(); + SecureLogger::log_debug("generate_text called", options.model); + + if (auto validation_error = pimpl_->input_validator.validate(options)) { + SecureLogger::log_warn("Input validation failed: " + *validation_error); + GenerateResult result(*validation_error); + result.finish_reason = kFinishReasonError; + result.is_retryable = false; + return result; + } + + try { + auto request = pimpl_->request_mapper.map_to_converse_request(options); + + Aws::BedrockRuntime::Model::ConverseOutcome outcome; + { + // Limit the number of concurrent requests per client + SemaphoreGuard guard(*pimpl_->request_semaphore); + outcome = pimpl_->client->Converse(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(), + 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); + + // Execute tools if the model made tool calls + if (result.has_tool_calls() && options.has_tools()) { + result.tool_results = ToolExecutor::execute_tools_with_options( + result.tool_calls, options, false); + } + + return result; + } catch (const std::exception& e) { + SecureLogger::log_error("Bedrock API exception: " + std::string(e.what())); + GenerateResult result(std::string("Bedrock API error: ") + e.what()); + result.finish_reason = kFinishReasonError; + result.is_retryable = false; + return result; + } +} + +EmbeddingResult BedrockClient::embeddings(const EmbeddingOptions& /*options*/) { + EmbeddingResult result; + result.error = "Bedrock embeddings are not supported yet"; + return result; +} + +StreamResult BedrockClient::stream_text(const StreamOptions& options) { + SecureLogger::log_debug("stream_text called", options.model); + const GenerateOptions& generate_options = options; + + auto impl = std::make_unique(); + + if (auto validation_error = + pimpl_->input_validator.validate(generate_options)) { + SecureLogger::log_warn("Input validation failed: " + *validation_error); + impl->fail(*validation_error); + return StreamResult(std::move(impl)); + } + + Aws::BedrockRuntime::Model::ConverseStreamRequest request; + try { + request = + pimpl_->request_mapper.map_to_converse_stream_request(generate_options); + } catch (const std::exception& e) { + impl->fail(std::string("Bedrock API error: ") + e.what()); + return StreamResult(std::move(impl)); + } + + // 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), + pimpl_->request_semaphore); + + return StreamResult(std::move(impl)); +} + +bool BedrockClient::is_valid() const { + return pimpl_ && pimpl_->valid; +} + +std::string BedrockClient::provider_name() const { + return "bedrock"; +} + +std::vector BedrockClient::supported_models() const { + return { + // Claude models on Bedrock + models::kClaudeFable52, + models::kClaudeOpus55, + models::kClaudeSonnet55, + models::kClaudeHaiku55, + // Amazon Titan models + models::kTitanTextExpress, + models::kTitanTextLite, + models::kTitanTextPremier, + // Amazon Nova models + models::kNovaLite, + models::kNovaPro, + models::kNovaMicro, + // Meta Llama models + models::kLlama3_8B, + models::kLlama3_70B, + }; +} + +bool BedrockClient::supports_model(const std::string& model_name) const { + auto models = supported_models(); + return std::find(models.begin(), models.end(), model_name) != models.end(); +} + +std::string BedrockClient::config_info() const { + std::string info = "Bedrock API (region: " + pimpl_->region; + if (!pimpl_->profile.empty()) { + info += ", profile: " + pimpl_->profile; + } + if (!pimpl_->endpoint_override.empty()) { + info += ", endpoint: " + pimpl_->endpoint_override; + } + info += ")"; + return info; +} + +std::string BedrockClient::default_model() const { + return models::kDefaultModel; +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_client.h b/src/providers/bedrock/bedrock_client.h new file mode 100644 index 0000000..f374f79 --- /dev/null +++ b/src/providers/bedrock/bedrock_client.h @@ -0,0 +1,57 @@ +#pragma once + +#include "ai/types/client.h" +#include "ai/types/embedding_options.h" +#include "ai/types/generate_options.h" +#include "ai/types/stream_options.h" +#include "ai/types/stream_result.h" + +#include +#include +#include + +// Forward declaration for BedrockConfig +namespace ai { +namespace bedrock { +struct BedrockConfig; +} +} // namespace ai + +namespace ai { +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. +class BedrockClient : public Client { + public: + explicit BedrockClient(const BedrockConfig& config); + ~BedrockClient(); + + // Non-copyable, non-movable due to PImpl + BedrockClient(const BedrockClient&) = delete; + BedrockClient& operator=(const BedrockClient&) = delete; + BedrockClient(BedrockClient&&) = delete; + BedrockClient& operator=(BedrockClient&&) = delete; + + // Client interface + GenerateResult generate_text(const GenerateOptions& options) override; + EmbeddingResult embeddings(const EmbeddingOptions& options) override; + StreamResult stream_text(const StreamOptions& options) override; + + bool is_valid() const override; + std::string provider_name() const override; + std::vector supported_models() const override; + bool supports_model(const std::string& model_name) const override; + std::string config_info() const override; + std::string default_model() const override; + + private: + GenerateResult generate_text_single_step(const GenerateOptions& options); + + struct Impl; + std::unique_ptr pimpl_; +}; + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_credentials.cpp b/src/providers/bedrock/bedrock_credentials.cpp new file mode 100644 index 0000000..9357d89 --- /dev/null +++ b/src/providers/bedrock/bedrock_credentials.cpp @@ -0,0 +1,161 @@ +#include "bedrock_credentials.h" + +#include "ai/errors.h" +#include "secure_logger.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +namespace { + +// Refresh assumed-role credentials this long before they expire +constexpr auto kCredentialsRefreshMargin = std::chrono::minutes(5); + +/// Credentials of the source identity: the configured profile, or the +/// default credential chain (env vars, profile, IMDS, ...) +std::shared_ptr make_source_provider( + const BedrockConfig& config) { + if (!config.profile.empty()) { + return std::make_shared( + config.profile.c_str()); + } + return std::make_shared(); +} + +/// 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. +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; + sts_config.region = region; + sts_client_ = std::make_shared( + make_source_provider(config), nullptr, sts_config); + + // Fail at client creation, not at the first request, if the role cannot + // be assumed + std::lock_guard lock(mutex_); + refresh_locked(); + } + + Aws::Auth::AWSCredentials GetAWSCredentials() override { + std::lock_guard lock(mutex_); + const auto now = Aws::Utils::DateTime::Now(); + const auto refresh_at = + credentials_.GetExpiration() - + std::chrono::milliseconds(kCredentialsRefreshMargin); + if (now >= refresh_at) { + try { + refresh_locked(); + } catch (const ConfigurationError& e) { + SecureLogger::log_error(e.what()); + // Keep using the cached credentials until they actually expire (the + // next call retries the refresh); after that, the request fails with + // an authentication error instead of using any other identity. + if (now >= credentials_.GetExpiration()) { + return Aws::Auth::AWSCredentials(); + } + } + } + return credentials_; + } + + 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_); + } + + auto outcome = sts_client_->AssumeRole(request); + if (!outcome.IsSuccess()) { + throw ConfigurationError("Failed to assume role: " + + outcome.GetError().GetMessage()); + } + + const auto& credentials = outcome.GetResult().GetCredentials(); + credentials_ = Aws::Auth::AWSCredentials( + credentials.GetAccessKeyId(), credentials.GetSecretAccessKey(), + credentials.GetSessionToken(), credentials.GetExpiration()); + 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::mutex mutex_; + Aws::Auth::AWSCredentials credentials_; +}; + +} // namespace + +std::string get_region_from_env() { + // Check AWS_REGION first, then AWS_DEFAULT_REGION + if (const char* region = std::getenv("AWS_REGION")) { + return region; + } + if (const char* region = std::getenv("AWS_DEFAULT_REGION")) { + return region; + } + return ""; +} + +std::shared_ptr make_credentials_provider( + const BedrockConfig& config, + const std::string& region) { + // Web identity (EKS / OIDC): the SDK provider re-reads the token file and + // refreshes the credentials + if (!config.web_identity_token_file.empty()) { + if (config.role_arn.empty()) { + throw ConfigurationError( + "web_identity_token_file requires role_arn to be set in " + "BedrockConfig"); + } + SecureLogger::log_debug("Using STS web identity credentials"); + Aws::Client::ClientConfiguration::CredentialProviderConfiguration + provider_config; + provider_config.region = region; + provider_config.profile = config.profile; + provider_config.stsCredentialsProviderConfig.roleArn = config.role_arn; + provider_config.stsCredentialsProviderConfig.sessionName = + config.role_session_name; + provider_config.stsCredentialsProviderConfig.tokenFilePath = + config.web_identity_token_file; + return std::make_shared< + Aws::Auth::STSAssumeRoleWebIdentityCredentialsProvider>( + provider_config); + } + + // Cross-account access via STS AssumeRole + if (!config.role_arn.empty()) { + SecureLogger::log_debug("Using STS AssumeRole credentials"); + return std::make_shared(config, region); + } + + SecureLogger::log_debug(config.profile.empty() + ? "Using default AWS credential chain" + : "Using AWS profile for credentials"); + return make_source_provider(config); +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_credentials.h b/src/providers/bedrock/bedrock_credentials.h new file mode 100644 index 0000000..90a6ed4 --- /dev/null +++ b/src/providers/bedrock/bedrock_credentials.h @@ -0,0 +1,27 @@ +#pragma once + +#include "ai/bedrock.h" + +#include +#include + +#include + +namespace ai { +namespace bedrock { + +/// Region from `AWS_REGION`, else `AWS_DEFAULT_REGION`, else empty +std::string get_region_from_env(); + +/// Credentials provider for a Bedrock configuration: web identity (with +/// `role_arn`), STS AssumeRole (`role_arn`), the configured profile, or the +/// default credential chain. Assumed-role credentials are refreshed before +/// they expire. +/// @throws ConfigurationError if the configuration is invalid or the role +/// cannot be assumed +std::shared_ptr make_credentials_provider( + const BedrockConfig& config, + const std::string& region); + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_factory.cpp b/src/providers/bedrock/bedrock_factory.cpp new file mode 100644 index 0000000..ba6a69b --- /dev/null +++ b/src/providers/bedrock/bedrock_factory.cpp @@ -0,0 +1,88 @@ +#include "bedrock_factory.h" + +#include "ai/bedrock.h" +#include "ai/errors.h" +#include "bedrock_client.h" +#include "model_discovery.h" +#include "secure_logger.h" + +#include +#include +#include + +namespace ai { +namespace bedrock { + +Client create_client() { + // Create client with default configuration + // Uses AWS_REGION environment variable and default credential chain + BedrockConfig config; + return create_client(config); +} + +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)); +} + +std::optional try_create_client() { + // Try to create client without throwing + // Returns nullopt if credentials or region are unavailable + SecureLogger::log_debug("Attempting to create Bedrock client"); + + try { + BedrockConfig config; + auto client = std::make_unique(config); + + if (client->is_valid()) { + SecureLogger::log_debug("Bedrock client created successfully"); + return Client(std::move(client)); + } + + SecureLogger::log_debug("Bedrock client is not valid"); + return std::nullopt; + + } catch (const ConfigurationError& e) { + // Configuration error (e.g., missing region) - return nullopt + SecureLogger::log_debug("Bedrock client creation failed: " + + std::string(e.what())); + return std::nullopt; + } catch (const std::exception& e) { + // Any other error - return nullopt + SecureLogger::log_debug("Bedrock client creation failed with exception: " + + std::string(e.what())); + return std::nullopt; + } +} + +std::vector list_available_models(const BedrockConfig& config) { + // List available models from user's AWS account + SecureLogger::log_debug("Listing available models"); + + try { + ModelDiscovery discovery(config); + return discovery.list_models(); + } catch (const std::exception& e) { + SecureLogger::log_error("Failed to list models: " + std::string(e.what())); + throw; + } +} + +bool validate_model_access(const std::string& model_id, + const BedrockConfig& config) { + // Validate model access - returns false for any access issues, does not throw + SecureLogger::log_debug("Validating model access: " + model_id); + + try { + ModelDiscovery discovery(config); + return discovery.is_model_accessible(model_id); + } catch (const std::exception& e) { + SecureLogger::log_debug("Model access validation failed: " + + std::string(e.what())); + return false; + } +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_factory.h b/src/providers/bedrock/bedrock_factory.h new file mode 100644 index 0000000..3d96872 --- /dev/null +++ b/src/providers/bedrock/bedrock_factory.h @@ -0,0 +1,31 @@ +#pragma once + +#include "ai/types/client.h" + +#include +#include + +namespace ai { +namespace bedrock { + +struct BedrockConfig; + +/// Create a Bedrock client with default configuration +/// Uses AWS_REGION environment variable and default credential chain +/// @throws ConfigurationError if region is not configured +/// @return Configured Bedrock client +Client create_client(); + +/// Create a Bedrock client with explicit configuration +/// @param config Bedrock configuration +/// @throws ConfigurationError if region is not configured +/// @return Configured Bedrock client +Client create_client(const BedrockConfig& config); + +/// 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 +std::optional try_create_client(); + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_request_mapper.cpp b/src/providers/bedrock/bedrock_request_mapper.cpp new file mode 100644 index 0000000..8c758a1 --- /dev/null +++ b/src/providers/bedrock/bedrock_request_mapper.cpp @@ -0,0 +1,345 @@ +#include "bedrock_request_mapper.h" + +#include "ai/logger.h" + +#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 +// prefixes. Mirrors `kSamplingRejectingModelPrefixes` in +// `anthropic_request_builder.cpp`, plus Claude Haiku 5. +constexpr std::array kSamplingRejectingClaudePrefixes = { + "claude-opus-5", "claude-opus-4-8", "claude-opus-4-7", + "claude-fable-5", "claude-sonnet-5", "claude-haiku-5"}; + +constexpr std::string_view kAnthropicModelPrefix = "anthropic."; + +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(); + }); +} + +} // namespace + +bool BedrockRequestMapper::rejects_sampling_parameters( + const std::string& model_id) { + // Bedrock IDs look like `anthropic.claude-opus-5-5`, optionally with a + // cross-region prefix (`us.`, `global.`) or inside an inference profile ARN. + const auto pos = + model_id.find(std::string(kAnthropicModelPrefix) + "claude-"); + if (pos == std::string::npos) { + return false; + } + const std::string_view first_party_id = + std::string_view(model_id).substr(pos + kAnthropicModelPrefix.size()); + return std::any_of(kSamplingRejectingClaudePrefixes.begin(), + kSamplingRejectingClaudePrefixes.end(), + [&](std::string_view prefix) { + return first_party_id.starts_with(prefix); + }); +} + +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); +} + +Model::ConverseRequest BedrockRequestMapper::map_to_converse_request( + 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); + + // Bedrock takes system prompts separately from the conversation: the + // `system` option and every system message become system content blocks. + if (!options.system.empty()) { + Model::SystemContentBlock block; + block.SetText(options.system); + request.AddSystem(std::move(block)); + } + 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)); + } + } + } + + // 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); + 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)); + } + request.SetMessages(std::move(messages)); + + request.SetInferenceConfig(build_inference_config(options)); + + if (auto tool_config = build_tool_config(options)) { + request.SetToolConfig(std::move(*tool_config)); + } +} + +Aws::Vector BedrockRequestMapper::convert_messages( + const Messages& messages) const { + Aws::Vector bedrock_messages; + bedrock_messages.reserve(messages.size()); + + for (const auto& message : messages) { + // System messages are sent as system content blocks (see fill_request) + if (message.role == kMessageRoleSystem) { + continue; + } + auto converted = convert_message(message); + if (!converted) { + continue; + } + // Converse requires alternating roles; dropping system (or empty) + // messages can leave two turns of the same role next to each other, so + // merge such turns (as the Anthropic API does itself). In a merged turn + // the tool results go first: Claude requires `tool_result` blocks to + // 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()) { + auto& previous = bedrock_messages.back(); + Aws::Vector merged; + merged.reserve(previous.GetContent().size() + + converted->GetContent().size()); + for (const bool tool_results : {true, false}) { + for (const auto* turn : {&previous, &*converted}) { + for (const auto& block : turn->GetContent()) { + if (block.ToolResultHasBeenSet() == tool_results) { + merged.push_back(block); + } + } + } + } + previous.SetContent(std::move(merged)); + } else { + bedrock_messages.push_back(std::move(*converted)); + } + } + + return bedrock_messages; +} + +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); + } + + 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); + } 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)); + } else if (const auto* tool_result = + std::get_if(&part)) { + Model::ToolResultContentBlock 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)); + } else if (tool_result->result.is_string()) { + result_content.SetText(tool_result->result.get()); + } else { + result_content.SetText(tool_result->result.dump()); + } + + 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; + } + + bedrock_message.AddContent(std::move(content_block)); + } + + if (bedrock_message.GetContent().empty()) { + return std::nullopt; // Bedrock rejects messages without content + } + return bedrock_message; +} + +Model::InferenceConfiguration BedrockRequestMapper::build_inference_config( + const GenerateOptions& options) const { + Model::InferenceConfiguration config; + + if (options.max_tokens.has_value()) { + config.SetMaxTokens(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); }); + + return config; +} + +std::optional BedrockRequestMapper::build_tool_config( + const GenerateOptions& options) const { + if (!options.has_tools()) { + return std::nullopt; + } + + // Converse has no "none" tool choice. Omit the tools, unless the + // conversation already contains tool calls: Bedrock requires a tool + // configuration for requests with `toolUse` / `toolResult` blocks. + const bool tools_disabled = options.tool_choice.type == ToolChoiceType::kNone; + if (tools_disabled && !messages_use_tools(options.messages)) { + return std::nullopt; + } + + Model::ToolConfiguration tool_config; + 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); + if (!it->second.description.empty()) { + spec.SetDescription(it->second.description); + } + spec.SetInputSchema(std::move(input_schema)); + + Model::Tool tool; + tool.SetToolSpec(std::move(spec)); + tool_config.AddTools(std::move(tool)); + } + + if (tool_config.GetTools().empty()) { + return std::nullopt; + } + + Model::ToolChoice tool_choice; + switch (options.tool_choice.type) { + case ToolChoiceType::kRequired: + tool_choice.SetAny(Model::AnyToolChoice()); + tool_config.SetToolChoice(std::move(tool_choice)); + 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)); + } + break; + case ToolChoiceType::kAuto: + tool_choice.SetAuto(Model::AutoToolChoice()); + tool_config.SetToolChoice(std::move(tool_choice)); + break; + case ToolChoiceType::kNone: + ai::logger::log_warn( + "Bedrock Converse has no \"none\" tool choice; sending the tools " + "because the conversation contains tool calls"); + break; + } + + return tool_config; +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_request_mapper.h b/src/providers/bedrock/bedrock_request_mapper.h new file mode 100644 index 0000000..7188503 --- /dev/null +++ b/src/providers/bedrock/bedrock_request_mapper.h @@ -0,0 +1,62 @@ +#pragma once + +#include "ai/types/generate_options.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +/// Maps SDK options to Bedrock Converse / ConverseStream requests +class BedrockRequestMapper { + public: + Aws::BedrockRuntime::Model::ConverseRequest map_to_converse_request( + const GenerateOptions& options) const; + + Aws::BedrockRuntime::Model::ConverseStreamRequest + map_to_converse_stream_request(const GenerateOptions& options) const; + + /// 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; + + Aws::Vector convert_messages( + const Messages& messages) const; + + std::optional convert_message( + const Message& message) const; + + Aws::BedrockRuntime::Model::InferenceConfiguration build_inference_config( + const GenerateOptions& options) const; + + std::optional + build_tool_config(const GenerateOptions& options) const; +}; + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_response_parser.cpp b/src/providers/bedrock/bedrock_response_parser.cpp new file mode 100644 index 0000000..55b5325 --- /dev/null +++ b/src/providers/bedrock/bedrock_response_parser.cpp @@ -0,0 +1,213 @@ +#include "bedrock_response_parser.h" + +#include "ai/logger.h" +#include "bedrock_request_mapper.h" + +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +GenerateResult BedrockResponseParser::parse_converse_response( + const Aws::BedrockRuntime::Model::ConverseResult& result) { + ai::logger::log_debug("Parsing Bedrock Converse response"); + + 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()); + + for (const auto& block : message.GetContent()) { + if (!block.ToolUseHasBeenSet()) { + continue; + } + 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()); + } + + // Add assistant response to messages + if (!gen_result.text.empty()) { + gen_result.response_messages.push_back( + Message::assistant(gen_result.text)); + } + } + + // Map stop reason to finish reason + gen_result.finish_reason = map_stop_reason(result.GetStopReason()); + 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(); + gen_result.usage.total_tokens = + gen_result.usage.prompt_tokens + gen_result.usage.completion_tokens; + + if (gen_result.usage.total_tokens > 0) { + ai::logger::log_debug("Token usage - input: {}, output: {}, total: {}", + gen_result.usage.prompt_tokens, + gen_result.usage.completion_tokens, + gen_result.usage.total_tokens); + } + + return gen_result; +} + +GenerateResult BedrockResponseParser::parse_converse_error( + const Aws::BedrockRuntime::BedrockRuntimeError& error) { + ai::logger::log_debug("Parsing Bedrock error: {} - {}", + error.GetExceptionName(), error.GetMessage()); + + 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; + } else { + // Fallback to error type name if exception name is empty + error_message = "BedrockError: " + message; + } + + result.error = error_message; + result.is_retryable = is_error_retryable(error); + + ai::logger::log_debug("Error is retryable: {}", + result.is_retryable.value_or(false)); + + 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; + } + + // 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; + } + + // Non-retryable errors by exception name + if (exception_name == "ValidationException" || + exception_name == "AccessDeniedException" || + exception_name == "ResourceNotFoundException" || + exception_name == "UnrecognizedClientException") { + return false; + } + + // 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; +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_response_parser.h b/src/providers/bedrock/bedrock_response_parser.h new file mode 100644 index 0000000..9039b30 --- /dev/null +++ b/src/providers/bedrock/bedrock_response_parser.h @@ -0,0 +1,52 @@ +#pragma once + +#include "ai/types/generate_options.h" + +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +/// Parses AWS Bedrock Converse API responses to SDK types +class BedrockResponseParser { + public: + BedrockResponseParser() = default; + ~BedrockResponseParser() = default; + + /// Parse successful Converse response + /// @param result AWS Bedrock ConverseResult + /// @return SDK GenerateResult + GenerateResult parse_converse_response( + const Aws::BedrockRuntime::Model::ConverseResult& result); + + /// Parse Converse error into GenerateResult + /// @param error AWS Bedrock error + /// @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); +}; + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_stream.cpp b/src/providers/bedrock/bedrock_stream.cpp new file mode 100644 index 0000000..1cdb8a8 --- /dev/null +++ b/src/providers/bedrock/bedrock_stream.cpp @@ -0,0 +1,266 @@ +#include "bedrock_stream.h" + +#include "ai/logger.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +namespace Model = Aws::BedrockRuntime::Model; + +BedrockStreamImpl::~BedrockStreamImpl() { + stop_stream(); + // Release the semaphore if the stream thread never ran to completion + if (semaphore_) { + semaphore_->release(); + } +} + +void BedrockStreamImpl::start_stream( + std::shared_ptr client, + Model::ConverseStreamRequest 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), + request = std::move(request)]() mutable { + run_stream(std::move(client), std::move(request)); + }); +} + +void BedrockStreamImpl::run_stream( + std::shared_ptr client, + Model::ConverseStreamRequest 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()); + } + } catch (const std::exception& e) { + ai::logger::log_error("Bedrock stream thread exception: {}", e.what()); + push_error(std::string("Stream error: ") + e.what()); + } + + mark_complete(); +} + +void BedrockStreamImpl::fail(const std::string& error_message) { + push_error(error_message); + mark_complete(); +} + +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. + std::unique_lock lock(queue_mutex_); + queue_cv_.wait(lock, [this] { return !event_queue_.empty() || complete_; }); + + if (event_queue_.empty()) { + return StreamEvent(""); + } + + StreamEvent event = std::move(event_queue_.front()); + event_queue_.pop_front(); + return event; +} + +bool BedrockStreamImpl::has_more_events() const { + std::lock_guard lock(queue_mutex_); + return !event_queue_.empty() || !complete_; +} + +void BedrockStreamImpl::stop_stream() { + stop_requested_ = true; + if (stream_thread_.joinable()) { + stream_thread_.join(); + } +} + +void BedrockStreamImpl::on_content_block_start( + const Model::ContentBlockStartEvent& event) { + if (stop_requested_ || !event.StartHasBeenSet() || + !event.GetStart().ToolUseHasBeenSet()) { + return; + } + const auto& tool_use = event.GetStart().GetToolUse(); + pending_tool_calls_[event.GetContentBlockIndex()] = + PendingToolCall{tool_use.GetToolUseId(), tool_use.GetName(), {}}; +} + +void BedrockStreamImpl::on_content_block_delta( + const Model::ContentBlockDeltaEvent& event) { + if (stop_requested_ || !event.DeltaHasBeenSet()) { + return; + } + const auto& delta = event.GetDelta(); + + if (delta.TextHasBeenSet()) { + push_event(StreamEvent(std::string(delta.GetText()))); + } + + if (delta.ToolUseHasBeenSet()) { + const auto it = pending_tool_calls_.find(event.GetContentBlockIndex()); + if (it != pending_tool_calls_.end()) { + it->second.input_json += delta.GetToolUse().GetInput(); + } + } +} + +void BedrockStreamImpl::on_content_block_stop( + const Model::ContentBlockStopEvent& event) { + if (stop_requested_) { + return; + } + flush_tool_call(event.GetContentBlockIndex()); +} + +void BedrockStreamImpl::flush_tool_call(int content_block_index) { + const auto it = pending_tool_calls_.find(content_block_index); + if (it == pending_tool_calls_.end()) { + return; + } + PendingToolCall pending = std::move(it->second); + pending_tool_calls_.erase(it); + + nlohmann::json arguments = nlohmann::json::object(); + if (!pending.input_json.empty()) { + arguments = nlohmann::json::parse(pending.input_json, nullptr, + /*allow_exceptions=*/false); + if (arguments.is_discarded()) { + push_error("Invalid JSON input for tool call '" + pending.name + + "': " + pending.input_json); + return; + } + } + push_event( + StreamEvent(ToolCall(pending.id, pending.name, std::move(arguments)))); +} + +void BedrockStreamImpl::on_message_stop(const Model::MessageStopEvent& event) { + if (!event.StopReasonHasBeenSet()) { + 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; + } +} + +void BedrockStreamImpl::on_metadata( + const Model::ConverseStreamMetadataEvent& event) { + if (!event.UsageHasBeenSet()) { + return; + } + const auto& usage = event.GetUsage(); + usage_ = Usage(usage.GetInputTokens(), usage.GetOutputTokens()); +} + +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()); + } else { + push_error("Stream error: " + error.GetMessage()); + } +} + +void BedrockStreamImpl::push_event(StreamEvent event) { + { + std::lock_guard lock(queue_mutex_); + event_queue_.push_back(std::move(event)); + } + queue_cv_.notify_one(); +} + +void BedrockStreamImpl::push_error(const std::string& message) { + errored_ = true; + push_event(StreamEvent(kStreamEventTypeError, message)); +} + +void BedrockStreamImpl::mark_complete() { + if (semaphore_) { + semaphore_->release(); + semaphore_.reset(); + } + + std::optional finish_event; + if (errored_) { + // Do not stamp a failed stream with a clean finish reason or usage + finish_event.emplace(kStreamEventTypeFinish, kFinishReasonError); + } else if (!stop_requested_) { + if (usage_) { + finish_event.emplace(kStreamEventTypeFinish, *usage_, finish_reason_); + } else { + finish_event.emplace(kStreamEventTypeFinish, finish_reason_); + } + } + + // Push the finish event and mark the stream complete in one critical + // section: otherwise a consumer that has just read the finish event could + // see `has_more_events() == true`, wait, and get an empty event after it. + { + std::lock_guard lock(queue_mutex_); + if (finish_event) { + event_queue_.push_back(std::move(*finish_event)); + } + complete_ = true; + } + queue_cv_.notify_all(); +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/bedrock_stream.h b/src/providers/bedrock/bedrock_stream.h new file mode 100644 index 0000000..baa5b0b --- /dev/null +++ b/src/providers/bedrock/bedrock_stream.h @@ -0,0 +1,109 @@ +#pragma once + +#include "ai/types/stream_result.h" + +#include +#include +#include +#include +#include +#include +#include +#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. +class BedrockStreamImpl : public internal::StreamResultImpl { + public: + using Semaphore = std::counting_semaphore<>; + + BedrockStreamImpl() = default; + ~BedrockStreamImpl() override; + + BedrockStreamImpl(const BedrockStreamImpl&) = delete; + BedrockStreamImpl& operator=(const BedrockStreamImpl&) = delete; + BedrockStreamImpl(BedrockStreamImpl&&) = delete; + BedrockStreamImpl& operator=(BedrockStreamImpl&&) = delete; + + /// Start streaming on a background thread. + /// @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); + + /// Finish the stream immediately with an error event, without calling the + /// API (used when the request is rejected before it is sent) + void fail(const std::string& error_message); + + // StreamResultImpl interface + StreamEvent get_next_event() override; + bool has_more_events() const override; + void stop_stream() override; + + private: + struct PendingToolCall { + std::string id; + std::string name; + 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 push_event(StreamEvent event); + void push_error(const std::string& message); + void flush_tool_call(int content_block_index); + + /// Push the finish event, release the semaphore, and wake up readers + void mark_complete(); + + mutable std::mutex queue_mutex_; + std::condition_variable queue_cv_; + std::deque event_queue_; + bool complete_ = false; + + std::atomic stop_requested_{false}; + std::thread stream_thread_; + std::shared_ptr semaphore_; + + // Accessed only by the stream thread (or before it starts) + std::map pending_tool_calls_; + FinishReason finish_reason_ = kFinishReasonStop; + std::optional usage_; + bool errored_ = false; +}; + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/credential_redactor.cpp b/src/providers/bedrock/credential_redactor.cpp new file mode 100644 index 0000000..ca6bba6 --- /dev/null +++ b/src/providers/bedrock/credential_redactor.cpp @@ -0,0 +1,111 @@ +#include "credential_redactor.h" + +#include + +namespace ai { +namespace bedrock { + +namespace { +// 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})"); + +// 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 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,})"); + +// 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)"); + +// 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'"]+))"); + +} // namespace + +std::string CredentialRedactor::redact(const std::string& input) { + if (input.empty()) { + return input; + } + + std::string result = input; + + // Order matters - redact more specific patterns first + result = redact_session_token(result); + result = redact_access_key_id(result); + result = redact_secret_key(result); + result = redact_account_id(result); + + // Redact credentials in environment variable format + result = std::regex_replace(result, kEnvCredentialPattern, + "$1=" + std::string(kRedactedPlaceholder)); + + return result; +} + +bool CredentialRedactor::contains_sensitive_data(const std::string& input) { + if (input.empty()) { + return false; + } + + // Check for any sensitive patterns + if (std::regex_search(input, kAccessKeyIdPattern)) { + return true; + } + if (std::regex_search(input, kSessionTokenPattern)) { + return true; + } + if (std::regex_search(input, kAccountIdInArnPattern)) { + return true; + } + if (std::regex_search(input, kEnvCredentialPattern)) { + return true; + } + + // Secret key detection is more heuristic, so we're conservative here + // Only flag if it looks like it's in a credential context + return false; +} + +std::string CredentialRedactor::redact_access_key_id(const std::string& input) { + return std::regex_replace(input, kAccessKeyIdPattern, 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; +} + +std::string CredentialRedactor::redact_session_token(const std::string& input) { + return std::regex_replace(input, kSessionTokenPattern, 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, + "$1" + std::string(kRedactedPlaceholder) + "$3"); +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/credential_redactor.h b/src/providers/bedrock/credential_redactor.h new file mode 100644 index 0000000..7f10e08 --- /dev/null +++ b/src/providers/bedrock/credential_redactor.h @@ -0,0 +1,43 @@ +#pragma once + +#include + +namespace ai { +namespace bedrock { + +/// Redacts sensitive information from strings before logging +class CredentialRedactor { + public: + /// Placeholder text for redacted content + static constexpr const char* kRedactedPlaceholder = "[REDACTED]"; + + /// Redact all sensitive patterns from a string + /// Patterns redacted: + /// - AWS Access Key IDs (AKIA...) + /// - AWS Secret Access Keys (40-char base64-like strings) + /// - Session tokens (long base64 strings) + /// - Account IDs in ARN context + /// @param input The string to redact + /// @return String with sensitive data replaced by [REDACTED] + static std::string redact(const std::string& input); + + /// Check if a string contains sensitive patterns + /// @param input The string to check + /// @return true if sensitive patterns are detected + static bool contains_sensitive_data(const std::string& input); + + /// Redact AWS Access Key ID pattern (AKIA followed by 16 alphanumeric chars) + static std::string redact_access_key_id(const std::string& input); + + /// Redact AWS Secret Access Key pattern (40 char base64-like string) + static std::string redact_secret_key(const std::string& input); + + /// Redact AWS Session Token (long base64 string) + static std::string redact_session_token(const std::string& input); + + /// Redact AWS Account IDs in ARN context + static std::string redact_account_id(const std::string& input); +}; + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/input_validator.cpp b/src/providers/bedrock/input_validator.cpp new file mode 100644 index 0000000..3dbb8a5 --- /dev/null +++ b/src/providers/bedrock/input_validator.cpp @@ -0,0 +1,165 @@ +#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) + : config_(config) {} + +std::optional InputValidator::validate( + const GenerateOptions& options) const { + // Validate model ID + if (options.model.empty()) { + return "Model ID is required"; + } + if (!is_valid_model_id(options.model)) { + return "Invalid model ID format: " + options.model; + } + + // Validate max_tokens if set + if (options.max_tokens.has_value()) { + if (!is_valid_max_tokens(options.max_tokens.value())) { + return "Max tokens must be positive, got: " + + std::to_string(options.max_tokens.value()); + } + } + + // Validate prompt length + if (!options.prompt.empty()) { + if (!is_valid_prompt_length(options.prompt)) { + return "Prompt exceeds maximum length of " + + std::to_string(config_.max_prompt_length) + " characters"; + } + } + + // Validate message content length + if (!options.messages.empty()) { + if (!is_valid_message_length(options.messages)) { + return "Total message content exceeds maximum length of " + + std::to_string(config_.max_message_length) + " characters"; + } + } + + // Validate system prompt length + if (!options.system.empty()) { + if (options.system.length() > config_.max_prompt_length) { + return "System prompt exceeds maximum length of " + + std::to_string(config_.max_prompt_length) + " characters"; + } + } + + // Must have a prompt or a non-system message: Bedrock takes system + // messages separately, and a conversation cannot be empty + const bool has_conversation_message = + std::any_of(options.messages.begin(), options.messages.end(), + [](const Message& message) { + return message.role != kMessageRoleSystem; + }); + if (options.prompt.empty() && !has_conversation_message) { + return "Either prompt or non-system messages must be provided"; + } + + return std::nullopt; // Valid +} + +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; +} + +bool InputValidator::is_valid_max_tokens(int max_tokens) const { + return max_tokens > 0; +} + +bool InputValidator::is_valid_prompt_length(const std::string& prompt) const { + return prompt.length() <= config_.max_prompt_length; +} + +bool InputValidator::is_valid_message_length(const Messages& messages) const { + return calculate_message_length(messages) <= config_.max_message_length; +} + +size_t InputValidator::calculate_message_length( + const Messages& messages) const { + size_t total_length = 0; + + for (const auto& message : messages) { + for (const auto& part : message.content) { + if (const auto* text_part = std::get_if(&part)) { + total_length += text_part->text.length(); + } + } + } + + return total_length; +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/input_validator.h b/src/providers/bedrock/input_validator.h new file mode 100644 index 0000000..81f91a1 --- /dev/null +++ b/src/providers/bedrock/input_validator.h @@ -0,0 +1,62 @@ +#pragma once + +#include "ai/bedrock.h" // For SecurityConfig +#include "ai/types/generate_options.h" +#include "ai/types/message.h" + +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +/// Validates all input parameters before making API calls +class InputValidator { + public: + /// Create validator with default security config + InputValidator(); + + /// Create validator with custom security config + explicit InputValidator(const SecurityConfig& config); + + /// Validate GenerateOptions, returns error message if invalid + /// @param options The options to validate + /// @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 + /// @param model_id The model identifier to validate + /// @return true if valid format + bool is_valid_model_id(const std::string& model_id) const; + + /// Validate max_tokens is positive (the upper bound depends on the model and + /// is checked by Bedrock) + /// @param max_tokens The max_tokens value + /// @return true if valid + bool is_valid_max_tokens(int max_tokens) const; + + /// Validate prompt length against configured maximum + /// @param prompt The prompt string + /// @return true if within length limit + bool is_valid_prompt_length(const std::string& prompt) const; + + /// Validate total message content length + /// @param messages The messages to validate + /// @return true if total content within limit + bool is_valid_message_length(const Messages& messages) const; + + /// Get the current security configuration + const SecurityConfig& config() const { return config_; } + + private: + SecurityConfig config_; + + /// Calculate total content length across all messages + size_t calculate_message_length(const Messages& messages) const; +}; + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/model_discovery.cpp b/src/providers/bedrock/model_discovery.cpp new file mode 100644 index 0000000..a8fc63b --- /dev/null +++ b/src/providers/bedrock/model_discovery.cpp @@ -0,0 +1,162 @@ +#include "model_discovery.h" + +#include "ai/bedrock.h" +#include "ai/errors.h" +#include "aws_sdk_manager.h" +#include "bedrock_credentials.h" +#include "secure_logger.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace bedrock { + +namespace { + +// Extract provider from model ID (e.g., "anthropic" from +// "anthropic.claude-3-5-sonnet-v1:0") +std::string extract_provider(const std::string& model_id) { + auto dot_pos = model_id.find('.'); + if (dot_pos != std::string::npos) { + return model_id.substr(0, dot_pos); + } + 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); +} + +ModelDiscovery::~ModelDiscovery() = default; + +void ModelDiscovery::initialize_client(const BedrockConfig& config) { + // Resolve region + region_ = config.region; + if (region_.empty()) { + region_ = get_region_from_env(); + } + + if (region_.empty()) { + throw ConfigurationError( + "AWS region not configured for model discovery. Set AWS_REGION " + "environment variable or provide region in BedrockConfig."); + } + + // 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_); +} + +std::vector ModelDiscovery::list_models() { + auto models = fetch_models_from_api(); + SecureLogger::log_info("Fetched " + std::to_string(models.size()) + + " models from Bedrock API"); + return models; +} + +bool ModelDiscovery::is_model_accessible(const std::string& model_id) { + auto models = list_models(); + + // A cross-region inference profile ID (`us.anthropic.claude-...`, + // `global.anthropic.claude-...`) refers to the foundation model ID after + // the geography prefix + std::string foundation_model_id = model_id; + const auto first_dot = model_id.find('.'); + if (model_id.rfind("arn:", 0) != 0 && first_dot != std::string::npos && + model_id.find('.', first_dot + 1) != std::string::npos) { + foundation_model_id = model_id.substr(first_dot + 1); + } + + return std::any_of(models.begin(), models.end(), [&](const ModelInfo& info) { + return info.model_id == model_id || info.model_id == foundation_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 new file mode 100644 index 0000000..18d774e --- /dev/null +++ b/src/providers/bedrock/model_discovery.h @@ -0,0 +1,52 @@ +#pragma once + +#include "ai/bedrock.h" // For SecurityConfig, BedrockConfig, ModelInfo + +#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(); + + /// List available models (calls `ListFoundationModels`) + /// @return Vector of ModelInfo for available models + /// @throws std::runtime_error if API call fails + std::vector list_models(); + + /// 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_; +}; + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/secure_logger.cpp b/src/providers/bedrock/secure_logger.cpp new file mode 100644 index 0000000..c6c551d --- /dev/null +++ b/src/providers/bedrock/secure_logger.cpp @@ -0,0 +1,88 @@ +#include "secure_logger.h" + +#include "ai/logger.h" +#include "credential_redactor.h" + +namespace ai { +namespace bedrock { + +void SecureLogger::log_debug(const std::string& message, + const std::string& content, + size_t max_content_length) { + std::string sanitized_message = sanitize_for_log(message); + + if (content.empty()) { + ai::logger::log_debug("[bedrock] {}", sanitized_message); + } else { + // Truncate and redact content + std::string truncated = truncate_content(content, max_content_length); + std::string sanitized_content = sanitize_for_log(truncated); + ai::logger::log_debug("[bedrock] {} - content: {}", sanitized_message, + sanitized_content); + } +} + +void SecureLogger::log_info(const std::string& message) { + // INFO level: NO content, only operation summaries + std::string sanitized = sanitize_for_log(message); + ai::logger::log_info("[bedrock] {}", sanitized); +} + +void SecureLogger::log_warn(const std::string& message) { + std::string sanitized = sanitize_for_log(message); + ai::logger::log_warn("[bedrock] {}", sanitized); +} + +void SecureLogger::log_error(const std::string& message) { + std::string sanitized = sanitize_for_log(message); + ai::logger::log_error("[bedrock] {}", sanitized); +} + +void SecureLogger::log_api_call(const std::string& operation, + const std::string& model, + const std::string& region, + const std::string& request_id, + std::chrono::milliseconds latency) { + // Structured logging for observability + // Redact model in case it contains account info (custom model ARNs) + std::string safe_model = sanitize_for_log(model); + + ai::logger::log_info( + "[bedrock] API call completed - operation: {}, model: {}, region: {}, " + "request_id: {}, latency_ms: {}", + operation, safe_model, region, request_id, latency.count()); +} + +void SecureLogger::log_api_error(const std::string& operation, + const std::string& model, + const std::string& region, + const std::string& error_code, + const std::string& error_message, + bool is_retryable) { + std::string safe_model = sanitize_for_log(model); + std::string safe_error = sanitize_for_log(error_message); + + ai::logger::log_error( + "[bedrock] API error - operation: {}, model: {}, region: {}, " + "error_code: {}, retryable: {}, message: {}", + operation, safe_model, region, error_code, is_retryable ? "yes" : "no", + safe_error); +} + +std::string SecureLogger::truncate_content(const std::string& content, + size_t max_length) { + if (content.length() <= max_length) { + return content; + } + + // Truncate and add ellipsis + return content.substr(0, max_length) + "..."; +} + +std::string SecureLogger::sanitize_for_log(const std::string& message) { + // Use CredentialRedactor to remove any sensitive data + return CredentialRedactor::redact(message); +} + +} // namespace bedrock +} // namespace ai diff --git a/src/providers/bedrock/secure_logger.h b/src/providers/bedrock/secure_logger.h new file mode 100644 index 0000000..5b03adb --- /dev/null +++ b/src/providers/bedrock/secure_logger.h @@ -0,0 +1,74 @@ +#pragma once + +#include +#include + +namespace ai { +namespace bedrock { + +/// Secure logging wrapper that ensures sensitive data is never logged +class SecureLogger { + public: + /// Maximum content length for debug logging (chars) + static constexpr size_t kMaxDebugContentLength = 500; + + /// Log at debug level with content truncation and redaction + /// Content is truncated to kMaxDebugContentLength and redacted + /// @param message The log message + /// @param content Optional content to log (will be truncated/redacted) + /// @param max_content_length Maximum content length (default: 100) + static void log_debug(const std::string& message, + const std::string& content = "", + size_t max_content_length = 100); + + /// Log at info level - NO content allowed + /// Only operation summaries and metrics + /// @param message The log message (will be redacted) + static void log_info(const std::string& message); + + /// Log at warning level with redaction + /// @param message The warning message (will be redacted) + static void log_warn(const std::string& message); + + /// Log at error level with full redaction + /// @param message The error message (will be redacted) + static void log_error(const std::string& message); + + /// Log API call with observability fields + /// Logs: operation, model, region, request_id, latency + /// @param operation The API operation (e.g., "Converse", "ConverseStream") + /// @param model The model ID used + /// @param region The AWS region + /// @param request_id The AWS request ID (for troubleshooting) + /// @param latency The request latency + static void log_api_call(const std::string& operation, + const std::string& model, + const std::string& region, + const std::string& request_id, + std::chrono::milliseconds latency); + + /// Log API error with observability fields + /// @param operation The API operation + /// @param model The model ID + /// @param region The AWS region + /// @param error_code The error code + /// @param error_message The error message (will be redacted) + /// @param is_retryable Whether the error is retryable + static void log_api_error(const std::string& operation, + const std::string& model, + const std::string& region, + const std::string& error_code, + const std::string& error_message, + bool is_retryable); + + private: + /// Truncate content to specified length, appending "..." if truncated + static std::string truncate_content(const std::string& content, + size_t max_length); + + /// Redact and sanitize a message for logging + static std::string sanitize_for_log(const std::string& message); +}; + +} // namespace bedrock +} // namespace ai diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index bae1d2a..6bd82e0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,5 +1,5 @@ # Test executable for AI SDK C++ -add_executable(ai_tests +set(AI_TEST_SOURCES # Unit tests unit/openai_client_test.cpp unit/anthropic_client_test.cpp @@ -25,6 +25,21 @@ add_executable(ai_tests utils/test_fixtures.cpp ) +# Add Bedrock tests when enabled +if(AI_SDK_ENABLE_BEDROCK) + list(APPEND AI_TEST_SOURCES + unit/bedrock_request_mapper_test.cpp + unit/bedrock_response_parser_test.cpp + unit/bedrock_stream_test.cpp + # Security component tests + unit/input_validator_test.cpp + unit/credential_redactor_test.cpp + integration/bedrock_integration_test.cpp + ) +endif() + +add_executable(ai_tests ${AI_TEST_SOURCES}) + # Link against the main library and test dependencies target_link_libraries(ai_tests PRIVATE @@ -37,6 +52,14 @@ target_link_libraries(ai_tests ClickHouse::Client # ClickHouse C++ client for integration tests ) +# Link AWS SDK for Bedrock tests when enabled +if(AI_SDK_ENABLE_BEDROCK) + target_link_libraries(ai_tests + PRIVATE + ${AWSSDK_LINK_LIBRARIES} + ) +endif() + # Include directories for tests target_include_directories(ai_tests PRIVATE diff --git a/tests/integration/bedrock_integration_test.cpp b/tests/integration/bedrock_integration_test.cpp new file mode 100644 index 0000000..d90e578 --- /dev/null +++ b/tests/integration/bedrock_integration_test.cpp @@ -0,0 +1,388 @@ +// Bedrock Integration Tests +// Tests actual API calls to AWS Bedrock +// +// These tests only run when: +// - AI_SDK_IT_BEDROCK=1 environment variable is set +// - Valid AWS credentials are available +// - AWS_REGION is configured + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "ai/bedrock.h" +#include "ai/types/generate_options.h" +#include "ai/types/stream_options.h" + +#include +#include + +namespace ai { +namespace bedrock { +namespace { + +class BedrockIntegrationTest : public ::testing::Test { + protected: + void SetUp() override { + // Skip if integration tests not enabled + if (std::getenv("AI_SDK_IT_BEDROCK") == nullptr) { + GTEST_SKIP() + << "Bedrock integration tests disabled. Set AI_SDK_IT_BEDROCK=1 to " + "enable."; + } + + // Try to create client - skip if credentials unavailable + auto maybe_client = try_create_client(); + if (!maybe_client.has_value()) { + GTEST_SKIP() + << "AWS credentials not available for Bedrock integration tests."; + } + client_ = std::move(maybe_client.value()); + } + + Client client_; +}; + +// Test basic text generation +TEST_F(BedrockIntegrationTest, GenerateTextReturnsValidResponse) { + GenerateOptions options; + // Use Amazon Nova which supports on-demand throughput + options.model = "amazon.nova-lite-v1:0"; + options.prompt = "Say 'Hello, World!' and nothing else."; + options.max_tokens = 50; + + auto result = client_.generate_text(options); + + EXPECT_FALSE(result.error.has_value()) + << "Error: " << result.error.value_or(""); + EXPECT_FALSE(result.text.empty()); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); +} + +// Test generation with system prompt +TEST_F(BedrockIntegrationTest, GenerateTextWithSystemPrompt) { + GenerateOptions options; + // Use Amazon Nova which supports on-demand throughput + options.model = "amazon.nova-lite-v1:0"; + options.system = + "You are a helpful assistant that responds in exactly one word."; + options.prompt = "What color is the sky?"; + options.max_tokens = 20; + + auto result = client_.generate_text(options); + + EXPECT_FALSE(result.error.has_value()) + << "Error: " << result.error.value_or(""); + EXPECT_FALSE(result.text.empty()); +} + +// Test generation with multi-turn conversation +TEST_F(BedrockIntegrationTest, GenerateTextWithMessages) { + GenerateOptions options; + // Use Amazon Nova which supports on-demand throughput + options.model = "amazon.nova-lite-v1:0"; + options.messages = { + Message::user("My name is Alice."), + Message::assistant("Nice to meet you, Alice!"), + Message::user("What is my name?"), + }; + options.max_tokens = 50; + + auto result = client_.generate_text(options); + + EXPECT_FALSE(result.error.has_value()) + << "Error: " << result.error.value_or(""); + EXPECT_FALSE(result.text.empty()); + // Response should mention "Alice" + EXPECT_NE(result.text.find("Alice"), std::string::npos); +} + +// Test streaming response +TEST_F(BedrockIntegrationTest, StreamTextYieldsIncrementalOutput) { + StreamOptions options; + // Use Amazon Nova which supports on-demand throughput + options.model = "amazon.nova-lite-v1:0"; + options.prompt = "Count from 1 to 5, one number per line."; + options.max_tokens = 50; + + auto stream = client_.stream_text(options); + + std::string full_text; + int chunk_count = 0; + bool got_finish = false; + + // Use iterator interface for streaming + for (const auto& event : stream) { + if (event.type == kStreamEventTypeTextDelta) { + full_text += event.text_delta; + chunk_count++; + } else if (event.type == kStreamEventTypeFinish) { + got_finish = true; + break; + } else if (event.type == kStreamEventTypeError) { + FAIL() << "Stream error: " << event.error.value_or("unknown error"); + } + } + + EXPECT_GT(chunk_count, 0) << "Should receive multiple text chunks"; + EXPECT_FALSE(full_text.empty()) << "Should receive text content"; + EXPECT_TRUE(got_finish) << "Should receive finish event"; +} + +// Test provider name +TEST_F(BedrockIntegrationTest, ProviderNameIsBedrock) { + EXPECT_EQ(client_.provider_name(), "bedrock"); +} + +// Test default model +TEST_F(BedrockIntegrationTest, DefaultModelIsSet) { + EXPECT_FALSE(client_.default_model().empty()); + EXPECT_EQ(client_.default_model(), models::kDefaultModel); +} + +// Test config info +TEST_F(BedrockIntegrationTest, ConfigInfoContainsRegion) { + auto info = client_.config_info(); + EXPECT_NE(info.find("region"), std::string::npos); +} + +// Test input validation - invalid max_tokens +TEST_F(BedrockIntegrationTest, RejectsInvalidMaxTokens) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Hello"; + options.max_tokens = 0; // Invalid - must be positive + + auto result = client_.generate_text(options); + + EXPECT_TRUE(result.error.has_value()); + EXPECT_NE(result.error->find("Max tokens"), std::string::npos); +} + +// ============================================================================ +// Model Discovery Tests +// ============================================================================ + +class BedrockModelDiscoveryTest : public ::testing::Test { + protected: + void SetUp() override { + if (std::getenv("AI_SDK_IT_BEDROCK") == nullptr) { + GTEST_SKIP() + << "Bedrock integration tests disabled. Set AI_SDK_IT_BEDROCK=1 to " + "enable."; + } + } +}; + +// Test list_available_models returns results +TEST_F(BedrockModelDiscoveryTest, ListAvailableModelsReturnsResults) { + try { + auto models = list_available_models(); + + // Should return at least some models + EXPECT_GT(models.size(), 0) << "Should have at least one available model"; + + // Print available models for debugging + std::cout << "Available models (" << models.size() << "):" << std::endl; + for (const auto& model : models) { + std::cout << " - " << model.model_id << " (" << model.provider << ")" + << " streaming=" << model.supports_streaming << std::endl; + } + + // Check model info structure + for (const auto& model : models) { + EXPECT_FALSE(model.model_id.empty()); + EXPECT_FALSE(model.provider.empty()); + } + } catch (const std::exception& e) { + FAIL() << "list_available_models threw exception: " << e.what(); + } +} + +// Test validate_model_access for known models +TEST_F(BedrockModelDiscoveryTest, ValidateModelAccessForKnownModels) { + // Test with models that should be available in most accounts + // Note: Claude models require inference profiles for on-demand access + // Amazon Nova models support direct on-demand access + bool has_nova_lite = validate_model_access(models::kNovaLite); + bool has_nova_micro = validate_model_access(models::kNovaMicro); + bool has_titan = validate_model_access(models::kTitanTextExpress); + + // At least one of these should be accessible + EXPECT_TRUE(has_nova_lite || has_nova_micro || has_titan) + << "At least one common model should be accessible"; +} + +// Test validate_model_access returns false for invalid model +TEST_F(BedrockModelDiscoveryTest, ValidateModelAccessReturnsFalseForInvalid) { + bool result = validate_model_access("invalid.nonexistent-model-v1:0"); + EXPECT_FALSE(result); +} + +// ============================================================================ +// Multi-Model Tests +// ============================================================================ + +class BedrockMultiModelTest : public ::testing::Test { + protected: + void SetUp() override { + if (std::getenv("AI_SDK_IT_BEDROCK") == nullptr) { + GTEST_SKIP() + << "Bedrock integration tests disabled. Set AI_SDK_IT_BEDROCK=1 to " + "enable."; + } + + auto maybe_client = try_create_client(); + if (!maybe_client.has_value()) { + GTEST_SKIP() + << "AWS credentials not available for Bedrock integration tests."; + } + client_ = std::move(maybe_client.value()); + } + + Client client_; +}; + +// Test generation with different models +TEST_F(BedrockMultiModelTest, GenerateWithDifferentModels) { + // Get available models + std::vector models_to_test; + + try { + auto available = list_available_models(); + for (const auto& model : available) { + // Only test text models that support streaming + if (model.supports_streaming && + std::find(model.capabilities.begin(), model.capabilities.end(), + "text") != model.capabilities.end()) { + models_to_test.push_back(model.model_id); + if (models_to_test.size() >= 3) + break; // Test up to 3 models + } + } + } catch (const std::exception& e) { + // Fall back to hardcoded models if discovery fails + models_to_test = {models::kClaudeSonnet}; + } + + if (models_to_test.empty()) { + GTEST_SKIP() << "No suitable models available for testing"; + } + + for (const auto& model_id : models_to_test) { + std::cout << "Testing model: " << model_id << std::endl; + + GenerateOptions options; + options.model = model_id; + options.prompt = "Say 'test' and nothing else."; + options.max_tokens = 20; + + auto result = client_.generate_text(options); + + // Some models may not be enabled - that's OK + if (result.error.has_value()) { + std::cout << " Model " << model_id << " error: " << result.error.value() + << std::endl; + continue; + } + + EXPECT_FALSE(result.text.empty()) + << "Model " << model_id << " should return text"; + std::cout << " Model " << model_id << " response: " << result.text + << std::endl; + } +} + +// Test using custom model ID (ARN format) +TEST_F(BedrockMultiModelTest, SupportsCustomModelArn) { + // This test verifies that ARN-format model IDs pass validation + // The actual API call may fail if the model doesn't exist + + GenerateOptions options; + // Use a valid ARN format (will fail at API level, but should pass validation) + options.model = "arn:aws:bedrock:us-east-1:123456789012:custom-model/test"; + options.prompt = "Hello"; + options.max_tokens = 10; + + auto result = client_.generate_text(options); + + // Should not fail on validation - may fail on API call + // The error should be from AWS, not from input validation + if (result.error.has_value()) { + // Should be an AWS error, not a validation error + EXPECT_EQ(result.error->find("Invalid model ID format"), std::string::npos) + << "ARN format should pass validation"; + } +} + +// Test using inference profile for Claude models +TEST_F(BedrockMultiModelTest, SupportsInferenceProfile) { + GenerateOptions options; + // Use Claude Sonnet 4.5 inference profile (cross-region) + options.model = "us.anthropic.claude-sonnet-5-5"; + options.prompt = "Say 'Hello from Claude!' and nothing else."; + options.max_tokens = 50; + + std::cout << "Testing inference profile: " << options.model << std::endl; + + auto result = client_.generate_text(options); + + // Should succeed with inference profile + EXPECT_FALSE(result.error.has_value()) + << "Error: " << result.error.value_or(""); + EXPECT_FALSE(result.text.empty()) << "Should return text"; + + std::cout << " Response: " << result.text << std::endl; + std::cout << " Tokens - prompt: " << result.usage.prompt_tokens + << ", completion: " << result.usage.completion_tokens << std::endl; +} + +// Test streaming with inference profile +TEST_F(BedrockMultiModelTest, StreamingWithInferenceProfile) { + StreamOptions options; + // Use Claude Sonnet 4.5 inference profile (cross-region) + options.model = "us.anthropic.claude-sonnet-5-5"; + options.prompt = "Count from 1 to 3."; + options.max_tokens = 50; + + std::cout << "Testing streaming with inference profile: " << options.model + << std::endl; + + auto stream = client_.stream_text(options); + + std::string full_text; + int chunk_count = 0; + bool got_finish = false; + + for (const auto& event : stream) { + if (event.type == kStreamEventTypeTextDelta) { + full_text += event.text_delta; + chunk_count++; + } else if (event.type == kStreamEventTypeFinish) { + got_finish = true; + break; + } else if (event.type == kStreamEventTypeError) { + FAIL() << "Stream error: " << event.error.value_or("unknown error"); + } + } + + EXPECT_GT(chunk_count, 0) << "Should receive multiple text chunks"; + EXPECT_FALSE(full_text.empty()) << "Should receive text content"; + EXPECT_TRUE(got_finish) << "Should receive finish event"; + + std::cout << " Received " << chunk_count << " chunks" << std::endl; + std::cout << " Full response: " << full_text << std::endl; +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +// Placeholder test when Bedrock is not enabled +TEST(BedrockIntegrationTest, 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 new file mode 100644 index 0000000..9a3adbf --- /dev/null +++ b/tests/unit/bedrock_request_mapper_test.cpp @@ -0,0 +1,354 @@ +// Bedrock Request Mapper Unit Tests +// Tests message conversion, parameter mapping, and system prompt handling + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "ai/bedrock.h" +#include "ai/types/generate_options.h" +#include "ai/types/message.h" +#include "ai/types/tool.h" +#include "providers/bedrock/bedrock_request_mapper.h" + +#include + +namespace ai { +namespace bedrock { +namespace { + +class BedrockRequestMapperTest : public ::testing::Test { + protected: + BedrockRequestMapper mapper_; +}; + +// 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); + + EXPECT_EQ(request.GetModelId(), models::kClaudeSonnet); + ASSERT_EQ(request.GetMessages().size(), 1); + EXPECT_EQ(request.GetMessages()[0].GetRole(), + Aws::BedrockRuntime::Model::ConversationRole::user); +} + +// Test model ID mapping +TEST_F(BedrockRequestMapperTest, MapsModelId) { + GenerateOptions options; + options.model = "custom-model-id"; + options.prompt = "Test"; + + auto request = mapper_.map_to_converse_request(options); + + EXPECT_EQ(request.GetModelId(), "custom-model-id"); +} + +// Test max_tokens mapping +TEST_F(BedrockRequestMapperTest, MapsMaxTokens) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Test"; + options.max_tokens = 1000; + + auto request = mapper_.map_to_converse_request(options); + + EXPECT_EQ(request.GetInferenceConfig().GetMaxTokens(), 1000); +} + +// Test temperature mapping +TEST_F(BedrockRequestMapperTest, MapsTemperature) { + GenerateOptions options; + options.model = models::kNovaLite; + options.prompt = "Test"; + options.temperature = 0.7; + + auto request = mapper_.map_to_converse_request(options); + + EXPECT_FLOAT_EQ(request.GetInferenceConfig().GetTemperature(), 0.7f); +} + +// Test top_p mapping +TEST_F(BedrockRequestMapperTest, MapsTopP) { + GenerateOptions options; + options.model = models::kNovaLite; + options.prompt = "Test"; + options.top_p = 0.9; + + auto request = mapper_.map_to_converse_request(options); + + EXPECT_FLOAT_EQ(request.GetInferenceConfig().GetTopP(), 0.9f); +} + +// Test system prompt mapping +TEST_F(BedrockRequestMapperTest, MapsSystemPrompt) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Test"; + options.system = "You are a helpful assistant."; + + auto request = mapper_.map_to_converse_request(options); + + ASSERT_EQ(request.GetSystem().size(), 1); + EXPECT_EQ(request.GetSystem()[0].GetText(), "You are a helpful assistant."); +} + +// Test messages conversion +TEST_F(BedrockRequestMapperTest, ConvertsMessages) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.messages = { + Message::user("Hello"), + Message::assistant("Hi there!"), + 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); +} + +// Claude models that reject sampling parameters do not get them +TEST_F(BedrockRequestMapperTest, DropsSamplingParametersForClaude) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Test"; + options.temperature = 0.7; + options.top_p = 0.9; + + auto request = mapper_.map_to_converse_request(options); + + EXPECT_FALSE(request.GetInferenceConfig().TemperatureHasBeenSet()); + EXPECT_FALSE(request.GetInferenceConfig().TopPHasBeenSet()); +} + +TEST_F(BedrockRequestMapperTest, RecognizesSamplingRejectingModels) { + EXPECT_TRUE(BedrockRequestMapper::rejects_sampling_parameters( + "anthropic.claude-opus-5-5")); + EXPECT_TRUE(BedrockRequestMapper::rejects_sampling_parameters( + "us.anthropic.claude-sonnet-5-5")); + EXPECT_TRUE(BedrockRequestMapper::rejects_sampling_parameters( + "global.anthropic.claude-fable-5-2")); + EXPECT_TRUE(BedrockRequestMapper::rejects_sampling_parameters( + "arn:aws:bedrock:us-east-1:123456789012:inference-profile/" + "us.anthropic.claude-haiku-5-5")); + EXPECT_FALSE(BedrockRequestMapper::rejects_sampling_parameters( + "anthropic.claude-sonnet-4-6")); + EXPECT_FALSE( + BedrockRequestMapper::rejects_sampling_parameters(models::kNovaLite)); + EXPECT_FALSE( + BedrockRequestMapper::rejects_sampling_parameters(models::kLlama3_8B)); +} + +// System messages inside `messages` become system content blocks +TEST_F(BedrockRequestMapperTest, MergesSystemMessagesIntoSystem) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.system = "Be brief."; + options.messages = { + Message::system("Answer in English."), + Message::user("Hello"), + }; + + auto request = mapper_.map_to_converse_request(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); +} + +// With only system messages, the prompt becomes the conversation +TEST_F(BedrockRequestMapperTest, UsesPromptWhenOnlySystemMessages) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Hello"; + options.messages = {Message::system("Be brief.")}; + + auto request = mapper_.map_to_converse_request(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"); +} + +// Dropping a system message between two user turns merges them, because +// Converse requires alternating roles +TEST_F(BedrockRequestMapperTest, MergesAdjacentSameRoleTurns) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.messages = { + Message::user("First"), + Message::system("Answer in English."), + Message::user("Second"), + Message::assistant("Reply"), + }; + + auto request = mapper_.map_to_converse_request(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); +} + +// When a text turn and a tool result turn are merged, the tool results come +// first, as Claude requires +TEST_F(BedrockRequestMapperTest, MergedTurnPutsToolResultsFirst) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.messages = { + Message::user("Weather in Paris?"), + Message::assistant_with_tools( + "", + {ToolCallContentPart("call_1", "get_weather", {{"city", "Paris"}})}), + Message::user("Also, answer in French."), + Message::tool_results({ToolResultContentPart( + "call_1", JsonValue{{"temperature", 20}}, false)}), + 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!"); +} + +ToolSet make_weather_tools() { + ToolSet tools; + tools["get_weather"] = + Tool("Get the weather for a city", + {{"type", "object"}, + {"properties", {{"city", {{"type", "string"}}}}}, + {"required", {"city"}}}, + [](const JsonValue&, const ToolExecutionContext&) { + return JsonValue{{"temperature", 20}}; + }); + return tools; +} + +TEST_F(BedrockRequestMapperTest, MapsToolsAndToolChoice) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Weather in Paris?"; + options.tools = make_weather_tools(); + + auto request = mapper_.map_to_converse_request(options); + + ASSERT_TRUE(request.ToolConfigHasBeenSet()); + const auto& tools = request.GetToolConfig().GetTools(); + 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()); + + options.tool_choice = ToolChoice::specific("get_weather"); + request = mapper_.map_to_converse_request(options); + EXPECT_EQ(request.GetToolConfig().GetToolChoice().GetTool().GetName(), + "get_weather"); + + options.tool_choice = ToolChoice::none(); + request = mapper_.map_to_converse_request(options); + EXPECT_FALSE(request.ToolConfigHasBeenSet()); +} + +TEST_F(BedrockRequestMapperTest, MapsToolCallsAndResults) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.tools = make_weather_tools(); + options.messages = { + Message::user("Weather in Paris?"), + Message::assistant_with_tools( + "Let me check.", + {ToolCallContentPart("call_1", "get_weather", {{"city", "Paris"}})}), + Message::tool_results({ToolResultContentPart( + "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}})); + + // 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()); +} + +// Test stream request mapping +TEST_F(BedrockRequestMapperTest, MapsStreamRequest) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Test streaming"; + options.max_tokens = 500; + + auto request = mapper_.map_to_converse_stream_request(options); + + EXPECT_EQ(request.GetModelId(), models::kClaudeSonnet); + EXPECT_EQ(request.GetInferenceConfig().GetMaxTokens(), 500); +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +// Placeholder test when Bedrock is not enabled +TEST(BedrockRequestMapperTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock provider not enabled. Set AI_SDK_ENABLE_BEDROCK=ON"; +} + +#endif // AI_SDK_HAS_BEDROCK diff --git a/tests/unit/bedrock_response_parser_test.cpp b/tests/unit/bedrock_response_parser_test.cpp new file mode 100644 index 0000000..b8bc143 --- /dev/null +++ b/tests/unit/bedrock_response_parser_test.cpp @@ -0,0 +1,163 @@ +// Bedrock Response Parser Unit Tests +// Tests response parsing, error mapping, and retryability classification + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "ai/bedrock.h" +#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: + 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); + + EXPECT_TRUE(result.is_success()); + EXPECT_EQ(result.text, "Let me check."); + EXPECT_EQ(result.finish_reason, kFinishReasonToolCalls); + ASSERT_EQ(result.tool_calls.size(), 1); + EXPECT_EQ(result.tool_calls[0].id, "call_1"); + EXPECT_EQ(result.tool_calls[0].tool_name, "get_weather"); + EXPECT_EQ(result.tool_calls[0].arguments, + (nlohmann::json{{"city", "Paris"}})); + EXPECT_EQ(result.usage.prompt_tokens, 12); + EXPECT_EQ(result.usage.completion_tokens, 34); + 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); + + EXPECT_TRUE(parser_.is_error_retryable(error)); +} + +// Test error retryability - InternalFailure +TEST_F(BedrockResponseParserTest, InternalFailureIsRetryable) { + Aws::Client::AWSError error( + Aws::BedrockRuntime::BedrockRuntimeErrors::INTERNAL_FAILURE, + "InternalServerException", "Internal server error", false); + + EXPECT_TRUE(parser_.is_error_retryable(error)); +} + +// 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 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)); +} + +// Test error retryability - ResourceNotFound +TEST_F(BedrockResponseParserTest, ResourceNotFoundIsNotRetryable) { + Aws::Client::AWSError error( + Aws::BedrockRuntime::BedrockRuntimeErrors::RESOURCE_NOT_FOUND, + "ResourceNotFoundException", "Model not found", false); + + EXPECT_FALSE(parser_.is_error_retryable(error)); +} + +// 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(error); + + 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); +} + +// 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); + + EXPECT_EQ(result.finish_reason, kFinishReasonError); +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +// Placeholder test when Bedrock is not enabled +TEST(BedrockResponseParserTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock provider not enabled. Set AI_SDK_ENABLE_BEDROCK=ON"; +} + +#endif // AI_SDK_HAS_BEDROCK diff --git a/tests/unit/bedrock_stream_test.cpp b/tests/unit/bedrock_stream_test.cpp new file mode 100644 index 0000000..9ff6256 --- /dev/null +++ b/tests/unit/bedrock_stream_test.cpp @@ -0,0 +1,146 @@ +// Bedrock Stream Unit Tests +// Tests streaming event handling and ordering + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "ai/bedrock.h" +#include "ai/types/stream_event.h" +#include "providers/bedrock/bedrock_stream.h" + +#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 +}; + +// Test stream implementation can be created +TEST_F(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 + // The stream is not complete until start_stream is called and finishes + EXPECT_TRUE(impl.has_more_events()); +} + +// Test stream can be stopped +TEST_F(BedrockStreamTest, CanStopStream) { + BedrockStreamImpl impl; + impl.stop_stream(); + // After stopping, the stream should still report has_more_events as true + // because stream_complete_ is only set when the stream thread finishes + // For a stream that was never started, stop_stream is a no-op + EXPECT_TRUE(impl.has_more_events()); +} + +// Test a rejected stream yields its error immediately and then ends +TEST_F(BedrockStreamTest, FailedStreamYieldsErrorAndCompletes) { + BedrockStreamImpl impl; + impl.fail("Invalid model ID format: bad model"); + + auto event = impl.get_next_event(); + EXPECT_EQ(event.type, kStreamEventTypeError); + ASSERT_TRUE(event.error.has_value()); + EXPECT_EQ(event.error.value(), "Invalid model ID format: bad model"); + + auto finish = impl.get_next_event(); + EXPECT_EQ(finish.type, kStreamEventTypeFinish); + EXPECT_EQ(finish.finish_reason, kFinishReasonError); + 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_); } + + ScopedEnvVar(const ScopedEnvVar&) = delete; + ScopedEnvVar& operator=(const ScopedEnvVar&) = delete; + + private: + void set(const std::optional& value) { + if (value) { + ::setenv(name_.c_str(), value->c_str(), 1); + } else { + ::unsetenv(name_.c_str()); + } + } + + 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); + } + } + EXPECT_TRUE(saw_error); + EXPECT_TRUE(saw_finish); + EXPECT_EQ(events_after_finish, 0); +} + +// 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. + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +// Placeholder test when Bedrock is not enabled +TEST(BedrockStreamTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock provider not enabled. Set AI_SDK_ENABLE_BEDROCK=ON"; +} + +#endif // AI_SDK_HAS_BEDROCK diff --git a/tests/unit/credential_redactor_test.cpp b/tests/unit/credential_redactor_test.cpp new file mode 100644 index 0000000..8b9f8e5 --- /dev/null +++ b/tests/unit/credential_redactor_test.cpp @@ -0,0 +1,127 @@ +// Credential Redactor Unit Tests +// Tests credential redaction in logs + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "providers/bedrock/credential_redactor.h" + +namespace ai { +namespace bedrock { +namespace { + +class CredentialRedactorTest : public ::testing::Test {}; + +// Test AWS Access Key ID redaction +TEST_F(CredentialRedactorTest, RedactsAccessKeyId) { + std::string input = "Access key: AKIAIOSFODNN7EXAMPLE"; + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result.find("AKIAIOSFODNN7EXAMPLE"), std::string::npos); + EXPECT_NE(result.find("[REDACTED]"), std::string::npos); +} + +TEST_F(CredentialRedactorTest, RedactsMultipleAccessKeyIds) { + std::string input = "Keys: AKIAIOSFODNN7EXAMPLE and AKIAI44QH8DHBEXAMPLE"; + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result.find("AKIAIOSFODNN7EXAMPLE"), std::string::npos); + EXPECT_EQ(result.find("AKIAI44QH8DHBEXAMPLE"), std::string::npos); +} + +// Test temporary credentials (ASIA prefix) +TEST_F(CredentialRedactorTest, RedactsTemporaryAccessKeyId) { + // Test that ASIA-prefixed keys (temporary credentials) are redacted + // ASIA + 16 uppercase alphanumeric chars = 20 chars total + std::string input = "Temp key: ASIAX7EXAMPLE1234567"; + std::string result = CredentialRedactor::redact(input); + + // The ASIA pattern should be redacted + EXPECT_EQ(result.find("ASIAX7EXAMPLE1234567"), std::string::npos); + EXPECT_NE(result.find("[REDACTED]"), std::string::npos); +} + +// Test session token redaction +TEST_F(CredentialRedactorTest, RedactsSessionToken) { + // Session tokens start with specific patterns + std::string input = "Token: FwoGZXIvYXdzEBYaDHVzLWVhc3QtMSJHMEUCIQDExample" + + std::string(100, 'A'); + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result.find("FwoGZXIvYXdzE"), std::string::npos); + EXPECT_NE(result.find("[REDACTED]"), std::string::npos); +} + +// Test account ID redaction in ARN context +TEST_F(CredentialRedactorTest, RedactsAccountIdInArn) { + std::string input = "arn:aws:bedrock:us-east-1:123456789012:model/my-model"; + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result.find("123456789012"), std::string::npos); + EXPECT_NE(result.find("[REDACTED]"), std::string::npos); + // ARN structure should be preserved + EXPECT_NE(result.find("arn:aws:bedrock:us-east-1:"), std::string::npos); +} + +// Test environment variable format redaction +TEST_F(CredentialRedactorTest, RedactsEnvVarFormat) { + std::string input = + "AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result.find("wJalrXUtnFEMI"), std::string::npos); + EXPECT_NE(result.find("[REDACTED]"), std::string::npos); +} + +// Test that non-sensitive data is preserved +TEST_F(CredentialRedactorTest, PreservesNonSensitiveData) { + std::string input = + "Model: anthropic.claude-3-5-sonnet-v1:0, Region: us-east-1"; + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result, input); +} + +// Test empty string handling +TEST_F(CredentialRedactorTest, HandlesEmptyString) { + std::string input = ""; + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result, ""); +} + +// Test contains_sensitive_data detection +TEST_F(CredentialRedactorTest, DetectsSensitiveData) { + EXPECT_TRUE( + CredentialRedactor::contains_sensitive_data("Key: AKIAIOSFODNN7EXAMPLE")); + EXPECT_TRUE(CredentialRedactor::contains_sensitive_data( + "arn:aws:bedrock:us-east-1:123456789012:model")); + EXPECT_FALSE(CredentialRedactor::contains_sensitive_data( + "Model: anthropic.claude-3-5-sonnet-v1:0")); +} + +// Test mixed content +TEST_F(CredentialRedactorTest, RedactsMixedContent) { + std::string input = + "Request to arn:aws:bedrock:us-east-1:123456789012:model " + "with key AKIAIOSFODNN7EXAMPLE failed"; + std::string result = CredentialRedactor::redact(input); + + EXPECT_EQ(result.find("123456789012"), std::string::npos); + EXPECT_EQ(result.find("AKIAIOSFODNN7EXAMPLE"), std::string::npos); + EXPECT_NE(result.find("Request to"), std::string::npos); + EXPECT_NE(result.find("failed"), std::string::npos); +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +TEST(CredentialRedactorTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock provider not enabled. Set AI_SDK_ENABLE_BEDROCK=ON"; +} + +#endif // AI_SDK_HAS_BEDROCK diff --git a/tests/unit/input_validator_test.cpp b/tests/unit/input_validator_test.cpp new file mode 100644 index 0000000..78eed5e --- /dev/null +++ b/tests/unit/input_validator_test.cpp @@ -0,0 +1,177 @@ +// Input Validator Unit Tests +// Tests input validation for GenerateOptions + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "ai/bedrock.h" +#include "ai/types/generate_options.h" +#include "ai/types/message.h" +#include "providers/bedrock/input_validator.h" + +namespace ai { +namespace bedrock { +namespace { + +class InputValidatorTest : public ::testing::Test { + protected: + InputValidator validator_; +}; + +// Test valid model ID patterns +TEST_F(InputValidatorTest, ValidStandardModelIds) { + EXPECT_TRUE(validator_.is_valid_model_id( + "anthropic.claude-3-5-sonnet-20241022-v2:0")); + EXPECT_TRUE( + validator_.is_valid_model_id("anthropic.claude-3-5-haiku-20241022-v1:0")); + EXPECT_TRUE(validator_.is_valid_model_id("amazon.titan-text-express-v1")); + EXPECT_TRUE(validator_.is_valid_model_id("amazon.titan-text-lite-v1")); + EXPECT_TRUE(validator_.is_valid_model_id("meta.llama3-8b-instruct-v1:0")); + EXPECT_TRUE(validator_.is_valid_model_id("meta.llama3-70b-instruct-v1:0")); +} + +// Test current Claude model IDs and cross-region inference profiles +TEST_F(InputValidatorTest, ValidCurrentClaudeModelIdsAndInferenceProfiles) { + EXPECT_TRUE(validator_.is_valid_model_id(models::kClaudeFable52)); + EXPECT_TRUE(validator_.is_valid_model_id(models::kClaudeOpus55)); + EXPECT_TRUE(validator_.is_valid_model_id(models::kClaudeSonnet55)); + EXPECT_TRUE(validator_.is_valid_model_id(models::kClaudeHaiku55)); + EXPECT_TRUE(validator_.is_valid_model_id("us.anthropic.claude-sonnet-5-5")); + EXPECT_TRUE(validator_.is_valid_model_id("eu.anthropic.claude-opus-5-5")); + EXPECT_TRUE(validator_.is_valid_model_id("apac.anthropic.claude-haiku-5-5")); + EXPECT_TRUE( + validator_.is_valid_model_id("global.anthropic.claude-fable-5-2")); +} + +// Test valid ARN model IDs +TEST_F(InputValidatorTest, ValidArnModelIds) { + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws:bedrock:us-east-1:123456789012:custom-model/my-model")); + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws:bedrock:us-west-2:123456789012:provisioned-model/my-model")); + EXPECT_TRUE( + validator_.is_valid_model_id("arn:aws:bedrock:eu-west-1:123456789012:" + "foundation-model/anthropic/claude")); +} + +// 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")); +} + +// Test max_tokens validation +TEST_F(InputValidatorTest, ValidMaxTokens) { + EXPECT_TRUE(validator_.is_valid_max_tokens(1)); + EXPECT_TRUE(validator_.is_valid_max_tokens(100)); + EXPECT_TRUE(validator_.is_valid_max_tokens(1000)); + EXPECT_TRUE(validator_.is_valid_max_tokens(200000)); + EXPECT_TRUE(validator_.is_valid_max_tokens(1000000)); +} + +TEST_F(InputValidatorTest, InvalidMaxTokens) { + EXPECT_FALSE(validator_.is_valid_max_tokens(0)); + EXPECT_FALSE(validator_.is_valid_max_tokens(-1)); + EXPECT_FALSE(validator_.is_valid_max_tokens(-100)); +} + +// Test prompt length validation +TEST_F(InputValidatorTest, ValidPromptLength) { + std::string short_prompt = "Hello, world!"; + std::string medium_prompt(1000, 'a'); + + EXPECT_TRUE(validator_.is_valid_prompt_length(short_prompt)); + EXPECT_TRUE(validator_.is_valid_prompt_length(medium_prompt)); + EXPECT_TRUE(validator_.is_valid_prompt_length("")); +} + +TEST_F(InputValidatorTest, InvalidPromptLength) { + SecurityConfig config; + config.max_prompt_length = 100; + InputValidator strict_validator(config); + + std::string long_prompt(101, 'a'); + EXPECT_FALSE(strict_validator.is_valid_prompt_length(long_prompt)); +} + +// Test full validation +TEST_F(InputValidatorTest, ValidGenerateOptions) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Hello, world!"; + options.temperature = 0.7; + options.top_p = 0.9; + options.max_tokens = 100; + + auto error = validator_.validate(options); + EXPECT_FALSE(error.has_value()) << "Error: " << error.value_or(""); +} + +TEST_F(InputValidatorTest, ValidationFailsOnEmptyModel) { + GenerateOptions options; + options.model = ""; + options.prompt = "Hello"; + + auto error = validator_.validate(options); + EXPECT_TRUE(error.has_value()); + EXPECT_NE(error->find("Model ID"), std::string::npos); +} + +TEST_F(InputValidatorTest, ValidationFailsOnInvalidMaxTokens) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.prompt = "Hello"; + options.max_tokens = 0; + + auto error = validator_.validate(options); + EXPECT_TRUE(error.has_value()); + EXPECT_NE(error->find("Max tokens"), std::string::npos); +} + +TEST_F(InputValidatorTest, ValidationFailsOnMissingPromptAndMessages) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + // No prompt or messages + + auto error = validator_.validate(options); + EXPECT_TRUE(error.has_value()); + EXPECT_NE(error->find("Either prompt or"), std::string::npos); +} + +TEST_F(InputValidatorTest, ValidationFailsWithOnlySystemMessages) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.messages = {Message::system("Be brief.")}; + + auto error = validator_.validate(options); + ASSERT_TRUE(error.has_value()); + EXPECT_NE(error->find("non-system messages"), std::string::npos); + + options.prompt = "Hello"; + EXPECT_FALSE(validator_.validate(options).has_value()); +} + +TEST_F(InputValidatorTest, ValidationPassesWithMessages) { + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.messages = {Message::user("Hello")}; + + auto error = validator_.validate(options); + EXPECT_FALSE(error.has_value()) << "Error: " << error.value_or(""); +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +TEST(InputValidatorTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock provider not enabled. Set AI_SDK_ENABLE_BEDROCK=ON"; +} + +#endif // AI_SDK_HAS_BEDROCK