diff --git a/README.md b/README.md index 44d4169..2cebb9a 100644 --- a/README.md +++ b/README.md @@ -529,6 +529,22 @@ cmake -B build -DAI_SDK_ENABLE_BEDROCK=ON cmake --build build ``` +### Models + +Model names are passed to the provider as is, so any model the provider serves works without an SDK update; the `ai::openai::models::k*` and `ai::anthropic::models::k*` constants are just well-known names. To see which models your API key can use, ask the provider: + +```cpp +auto client = ai::anthropic::create_client(); +auto listed = client.list_models(); // GET /v1/models +if (listed) { + for (const auto& model : listed.models) { + std::cout << model << "\n"; + } +} else { + std::cerr << listed.error_message() << "\n"; +} +``` + ## Features ### Currently Supported diff --git a/examples/multi_provider.cpp b/examples/multi_provider.cpp index c49257c..e22e69e 100644 --- a/examples/multi_provider.cpp +++ b/examples/multi_provider.cpp @@ -215,9 +215,14 @@ int main() { std::cout << "OpenAI client created successfully\n"; std::cout << "Provider: " << openai_client.provider_name() << "\n"; - auto openai_models = openai_client.supported_models(); - if (!openai_models.empty()) { - std::cout << "Supported models: "; + // Ask the API which models this key can use + auto listed = openai_client.list_models(); + const auto& openai_models = listed.models; + if (!listed) { + std::cout << "Failed to list models: " << listed.error_message() + << "\n"; + } else if (!openai_models.empty()) { + std::cout << "Available models: "; for (size_t i = 0; i < openai_models.size() && i < 3; ++i) { std::cout << openai_models[i]; if (i < 2 && i < openai_models.size() - 1) { diff --git a/include/ai/types/client.h b/include/ai/types/client.h index a1193a5..3cb536a 100644 --- a/include/ai/types/client.h +++ b/include/ai/types/client.h @@ -2,6 +2,7 @@ #include "embedding_options.h" #include "generate_options.h" +#include "model.h" #include "stream_options.h" #include "stream_result.h" @@ -56,12 +57,28 @@ class Client { return "unknown"; } + /// List the model IDs the provider serves to this API key, by querying its + /// models endpoint (`GET /v1/models`). Makes a network request. + virtual ModelListResult list_models() { + if (pimpl_) + return pimpl_->list_models(); + return ModelListResult("Client not initialized"); + } + + /// Well-known model IDs of the provider (the `models::k*` constants). This + /// list is neither exhaustive nor a restriction: any model name is + /// forwarded to the provider as is. Use `list_models` for the models + /// actually available. virtual std::vector supported_models() const { if (pimpl_) return pimpl_->supported_models(); return {}; } + /// Whether the client can send requests for `model_name`. The SDK forwards + /// any model name to the provider, so this is true for every non-empty + /// name; whether the provider serves the model is known only to the + /// provider (see `list_models`). virtual bool supports_model(const std::string& model_name) const { if (pimpl_) return pimpl_->supports_model(model_name); diff --git a/include/ai/types/model.h b/include/ai/types/model.h index d56619e..8cc2ebc 100644 --- a/include/ai/types/model.h +++ b/include/ai/types/model.h @@ -2,6 +2,7 @@ #include #include +#include namespace ai { @@ -34,4 +35,22 @@ struct Model { bool operator!=(const Model& other) const { return !(*this == other); } }; +/// The model IDs a provider serves to the client's API key, as returned by +/// `Client::list_models`. +struct ModelListResult { + std::vector models; + std::optional error; + + ModelListResult() = default; + + explicit ModelListResult(std::string error_message) + : error(std::move(error_message)) {} + + bool is_success() const { return !error.has_value(); } + + explicit operator bool() const { return is_success(); } + + std::string error_message() const { return error.value_or(""); } +}; + } // namespace ai \ No newline at end of file diff --git a/src/http/http_request_handler.cpp b/src/http/http_request_handler.cpp index 7bb864c..805a5db 100644 --- a/src/http/http_request_handler.cpp +++ b/src/http/http_request_handler.cpp @@ -46,13 +46,27 @@ GenerateResult HttpRequestHandler::post(const std::string& path, const httplib::Headers& headers, const std::string& body, const std::string& content_type) { + return send_with_retry(Method::kPost, path, headers, body, content_type); +} + +GenerateResult HttpRequestHandler::get(const std::string& path, + const httplib::Headers& headers) { + return send_with_retry(Method::kGet, path, headers, {}, {}); +} + +GenerateResult HttpRequestHandler::send_with_retry( + Method method, + const std::string& path, + const httplib::Headers& headers, + const std::string& body, + const std::string& content_type) { // Create a retry policy with the configured settings retry::RetryPolicy retry_policy(config_.retry_config); // Define the function to execute with retry - auto execute_request = [this, &path, &headers, &body, + auto execute_request = [this, method, &path, &headers, &body, &content_type]() -> GenerateResult { - return execute_single_request(path, headers, body, content_type); + return execute_single_request(method, path, headers, body, content_type); }; // Define the function to check if a result is retryable @@ -72,6 +86,7 @@ GenerateResult HttpRequestHandler::post(const std::string& path, } GenerateResult HttpRequestHandler::execute_single_request( + Method method, const std::string& path, const httplib::Headers& headers, const std::string& body, @@ -104,10 +119,11 @@ GenerateResult HttpRequestHandler::execute_single_request( return error_result; }; - return make_request(path, headers, body, content_type, handler); + return make_request(method, path, headers, body, content_type, handler); } -GenerateResult HttpRequestHandler::make_request(const std::string& path, +GenerateResult HttpRequestHandler::make_request(Method method, + const std::string& path, const httplib::Headers& headers, const std::string& body, const std::string& content_type, @@ -116,10 +132,16 @@ GenerateResult HttpRequestHandler::make_request(const std::string& path, // Combine base_path with the endpoint path std::string full_path = config_.base_path + path; - ai::logger::log_debug("Making {} request to {}:{}{}", - config_.use_ssl ? "HTTPS" : "HTTP", config_.host, - full_path, - " with body size: " + std::to_string(body.size())); + ai::logger::log_debug( + "Making {} {} request to {}:{}{}", config_.use_ssl ? "HTTPS" : "HTTP", + method == Method::kGet ? "GET" : "POST", config_.host, full_path, + " with body size: " + std::to_string(body.size())); + + const auto send = [&](auto& cli) { + return method == Method::kGet + ? cli.Get(full_path, headers) + : cli.Post(full_path, headers, body, content_type); + }; if (config_.use_ssl) { httplib::SSLClient cli(config_.host); @@ -127,14 +149,14 @@ GenerateResult HttpRequestHandler::make_request(const std::string& path, cli.set_read_timeout(config_.read_timeout_sec, 0); cli.enable_server_certificate_verification(config_.verify_ssl_cert); - auto res = cli.Post(full_path, headers, body, content_type); + auto res = send(cli); return handler(res, "HTTPS"); } else { httplib::Client cli(config_.host); cli.set_connection_timeout(config_.connection_timeout_sec, 0); cli.set_read_timeout(config_.read_timeout_sec, 0); - auto res = cli.Post(full_path, headers, body, content_type); + auto res = send(cli); return handler(res, "HTTP"); } } catch (const std::exception& e) { diff --git a/src/http/http_request_handler.h b/src/http/http_request_handler.h index 2c74b38..7bdd893 100644 --- a/src/http/http_request_handler.h +++ b/src/http/http_request_handler.h @@ -35,23 +35,37 @@ class HttpRequestHandler { const std::string& body, const std::string& content_type = "application/json"); + // Makes a GET request (with the same retry policy as `post`) and returns the + // raw response wrapped in GenerateResult + GenerateResult get(const std::string& path, const httplib::Headers& headers); + // Extracts host and SSL settings from a base URL static HttpConfig parse_base_url(const std::string& base_url); private: + enum class Method { kGet, kPost }; + HttpConfig config_; + GenerateResult send_with_retry(Method method, + const std::string& path, + const httplib::Headers& headers, + const std::string& body, + const std::string& content_type); + // Handler for processing HTTP responses using ResponseHandler = std::function; - GenerateResult make_request(const std::string& path, + GenerateResult make_request(Method method, + const std::string& path, const httplib::Headers& headers, const std::string& body, const std::string& content_type, ResponseHandler handler); // Execute a single HTTP request (used by retry logic) - GenerateResult execute_single_request(const std::string& path, + GenerateResult execute_single_request(Method method, + const std::string& path, const httplib::Headers& headers, const std::string& body, const std::string& content_type); diff --git a/src/providers/anthropic/anthropic_client.cpp b/src/providers/anthropic/anthropic_client.cpp index 9fa1bc6..e698238 100644 --- a/src/providers/anthropic/anthropic_client.cpp +++ b/src/providers/anthropic/anthropic_client.cpp @@ -35,7 +35,8 @@ AnthropicClient::AnthropicClient(const std::string& api_key, .auth_header_name = "x-api-key", .auth_header_prefix = "", .extra_headers = {{"anthropic-version", "2023-06-01"}}, - .retry_config = retry_config}, + .retry_config = retry_config, + .models_endpoint_path = "/v1/models"}, std::make_unique(), std::make_unique()) { ai::logger::log_debug("Anthropic client initialized with base_url: {}{}", @@ -73,10 +74,8 @@ std::string AnthropicClient::provider_name() const { } std::vector AnthropicClient::supported_models() const { - // Both the friendly aliases (e.g. "claude-sonnet-4-5") and their dated - // snapshot variants (e.g. "claude-sonnet-4-5-20250929") are accepted by the - // Anthropic API; list both so identifiers in `ai::anthropic::models::*` - // resolve via `supports_model()`. + // The well-known identifiers of `ai::anthropic::models`, aliases and dated + // snapshots. Not exhaustive: `list_models` asks the API. return {models::kClaudeFable52, models::kClaudeOpus55, models::kClaudeSonnet55, models::kClaudeHaiku55, models::kClaudeFable51, models::kClaudeFable5, @@ -90,8 +89,9 @@ std::vector AnthropicClient::supported_models() const { } bool AnthropicClient::supports_model(const std::string& model_name) const { - auto models = supported_models(); - return std::find(models.begin(), models.end(), model_name) != models.end(); + // Any model name is forwarded to the API as is; the model catalog lives + // on the provider side (see `list_models`). + return !model_name.empty(); } std::string AnthropicClient::config_info() const { diff --git a/src/providers/base_provider_client.cpp b/src/providers/base_provider_client.cpp index e165967..eafd170 100644 --- a/src/providers/base_provider_client.cpp +++ b/src/providers/base_provider_client.cpp @@ -3,6 +3,8 @@ #include "ai/logger.h" #include "ai/tools.h" +#include + namespace ai { namespace providers { @@ -197,5 +199,83 @@ EmbeddingResult BaseProviderClient::embeddings( } } +std::optional BaseProviderClient::get_json( + const std::string& path, + const httplib::Headers& headers, + nlohmann::json& out) { + auto result = http_handler_->get(path, headers); + if (!result.is_success()) { + if (result.provider_metadata.has_value()) { + const int status_code = std::stoi(result.provider_metadata.value()); + return response_parser_ + ->parse_error_completion_response(status_code, + result.error.value_or("")) + .error_message(); + } + return result.error_message(); + } + + try { + out = nlohmann::json::parse(result.text); + } catch (const nlohmann::json::exception& e) { + return "Failed to parse response: " + std::string(e.what()); + } + return std::nullopt; +} + +ModelListResult BaseProviderClient::list_models() { + if (config_.models_endpoint_path.empty()) { + return ModelListResult("The " + provider_name() + + " provider has no models endpoint"); + } + + const auto headers = request_builder_->build_headers(config_); + ModelListResult listed; + std::string path = config_.models_endpoint_path; + std::set seen_cursors; + + // OpenAI returns every model at once; Anthropic pages with `has_more` and + // `last_id` (passed back as `after_id`). + while (true) { + nlohmann::json json_response; + if (auto error = get_json(path, headers, json_response)) { + return ModelListResult(std::move(*error)); + } + + if (!json_response.contains("data") || !json_response["data"].is_array()) { + return ModelListResult("Unexpected models response: no `data` array"); + } + for (const auto& entry : json_response["data"]) { + if (entry.is_object() && entry.contains("id") && + entry["id"].is_string()) { + listed.models.push_back(entry["id"].get()); + } + } + + const auto has_more = json_response.find("has_more"); + if (has_more == json_response.end() || !has_more->is_boolean() || + !has_more->get()) { + break; + } + const auto last_id = json_response.find("last_id"); + if (last_id == json_response.end() || !last_id->is_string() || + last_id->get().empty()) { + return ModelListResult( + "Unexpected models response: `has_more` without `last_id`"); + } + // A server (or gateway) that ignores `after_id` would otherwise be paged + // forever. + if (!seen_cursors.insert(last_id->get()).second) { + return ModelListResult("Unexpected models response: pagination cursor `" + + last_id->get() + "` repeated"); + } + path = config_.models_endpoint_path + + "?after_id=" + last_id->get(); + } + + ai::logger::log_debug("Listed {} models", listed.models.size()); + return listed; +} + } // namespace providers } // namespace ai diff --git a/src/providers/base_provider_client.h b/src/providers/base_provider_client.h index 0f1cbc3..21804e2 100644 --- a/src/providers/base_provider_client.h +++ b/src/providers/base_provider_client.h @@ -27,6 +27,11 @@ struct ProviderConfig { // Optional retry configuration std::optional retry_config; + + // Endpoint listing the available models (OpenAI and Anthropic shape: + // `{"data": [{"id": ...}, ...]}`, Anthropic paginated with `has_more` and + // `last_id`). + std::string models_endpoint_path; }; // Interface for provider-specific request building @@ -66,10 +71,17 @@ class BaseProviderClient : public Client { GenerateResult generate_text(const GenerateOptions& options) override; StreamResult stream_text(const StreamOptions& options) override; EmbeddingResult embeddings(const EmbeddingOptions& options) override; + ModelListResult list_models() override; bool is_valid() const override { return !config_.api_key.empty(); } protected: + // GET `path` and parse the JSON body into `out`. Returns the error message + // (parsed by the provider's error parser for HTTP errors) on failure. + std::optional get_json(const std::string& path, + const httplib::Headers& headers, + nlohmann::json& out); + // Hook for derived classes to customize behavior virtual GenerateResult generate_text_single_step( const GenerateOptions& options); diff --git a/src/providers/bedrock/bedrock_client.cpp b/src/providers/bedrock/bedrock_client.cpp index 240e7cb..29bba7f 100644 --- a/src/providers/bedrock/bedrock_client.cpp +++ b/src/providers/bedrock/bedrock_client.cpp @@ -9,6 +9,7 @@ #include "bedrock_response_parser.h" #include "bedrock_stream.h" #include "input_validator.h" +#include "model_discovery.h" #include "secure_logger.h" #include @@ -57,10 +58,11 @@ struct BedrockClient::Impl { std::string region; std::string profile; std::string endpoint_override; + BedrockConfig config; // For model discovery, which uses its own client bool valid{false}; - explicit Impl(const BedrockConfig& config) - : input_validator(config.security) { + explicit Impl(const BedrockConfig& client_config_in) + : input_validator(client_config_in.security), config(client_config_in) { if (config.security.max_concurrent_requests <= 0) { throw ConfigurationError("max_concurrent_requests must be positive"); } @@ -239,8 +241,25 @@ std::vector BedrockClient::supported_models() const { } 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(); + // Any model ID, inference profile or ARN is forwarded to Converse as is; + // the catalog lives on the AWS side (see `list_models`). + return !model_name.empty(); +} + +ModelListResult BedrockClient::list_models() { + // `ListFoundationModels` returns foundation model IDs of the Region; + // inference profile IDs (`global.anthropic...`) are not part of it. + try { + ModelDiscovery discovery(pimpl_->config); + ModelListResult listed; + for (const auto& info : discovery.list_models()) { + listed.models.push_back(info.model_id); + } + return listed; + } catch (const std::exception& e) { + return ModelListResult("Failed to list Bedrock models: " + + std::string(e.what())); + } } std::string BedrockClient::config_info() const { diff --git a/src/providers/bedrock/bedrock_client.h b/src/providers/bedrock/bedrock_client.h index f374f79..ffd117e 100644 --- a/src/providers/bedrock/bedrock_client.h +++ b/src/providers/bedrock/bedrock_client.h @@ -43,6 +43,7 @@ class BedrockClient : public Client { std::string provider_name() const override; std::vector supported_models() const override; bool supports_model(const std::string& model_name) const override; + ModelListResult list_models() override; std::string config_info() const override; std::string default_model() const override; diff --git a/src/providers/google/google_client.cpp b/src/providers/google/google_client.cpp index 25c4a82..a5b3ae3 100644 --- a/src/providers/google/google_client.cpp +++ b/src/providers/google/google_client.cpp @@ -6,8 +6,11 @@ #include "google_response_parser.h" #include "google_stream.h" +#include #include #include +#include +#include namespace ai { namespace google { @@ -106,6 +109,85 @@ bool GoogleClient::supports_model(const std::string& model_name) const { return !model_name.empty(); } +namespace { + +std::string percent_encode(const std::string& value) { + std::string encoded; + for (const unsigned char c : value) { + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || + c == '~') { + encoded.push_back(static_cast(c)); + } else { + char buffer[4]; + std::snprintf(buffer, sizeof(buffer), "%%%02X", c); + encoded += buffer; + } + } + return encoded; +} + +} // namespace + +ModelListResult GoogleClient::list_models() { + // `GET /v1beta/models` returns `{"models": [{"name": "models/", ...}], + // "nextPageToken": ...}`; the IDs are reported without the `models/` + // prefix, the way requests take them. + constexpr std::string_view kNamePrefix = "models/"; + const auto headers = request_builder_->build_headers(config_); + ModelListResult listed; + std::set seen_tokens; + std::string page_token; + + while (true) { + std::string path = "/v1beta/models?pageSize=1000"; + if (!page_token.empty()) { + path += "&pageToken=" + percent_encode(page_token); + } + + nlohmann::json json_response; + if (auto error = get_json(path, headers, json_response)) { + return ModelListResult(std::move(*error)); + } + if (!json_response.is_object()) { + return ModelListResult("Unexpected models response: not an object"); + } + + // An empty last page may omit `models`. + if (const auto models = json_response.find("models"); + models != json_response.end()) { + if (!models->is_array()) { + return ModelListResult( + "Unexpected models response: `models` is not an array"); + } + for (const auto& entry : *models) { + if (!entry.is_object() || !entry.contains("name") || + !entry["name"].is_string()) { + continue; + } + std::string name = entry["name"].get(); + if (name.starts_with(kNamePrefix)) { + name.erase(0, kNamePrefix.size()); + } + listed.models.push_back(std::move(name)); + } + } + + const auto next = json_response.find("nextPageToken"); + if (next == json_response.end() || !next->is_string() || + next->get().empty()) { + break; + } + page_token = next->get(); + if (!seen_tokens.insert(page_token).second) { + return ModelListResult("Unexpected models response: page token repeated"); + } + } + + ai::logger::log_debug("Listed {} Gemini models", listed.models.size()); + return listed; +} + std::string GoogleClient::config_info() const { return "Google Gemini API (base_url: " + config_.base_url + ")"; } diff --git a/src/providers/google/google_client.h b/src/providers/google/google_client.h index 2110966..5749020 100644 --- a/src/providers/google/google_client.h +++ b/src/providers/google/google_client.h @@ -30,6 +30,7 @@ class GoogleClient : public providers::BaseProviderClient { std::string provider_name() const override; /// Any model name is passed to the API, which rejects unknown ones. bool supports_model(const std::string& model_name) const override; + ModelListResult list_models() override; std::string config_info() const override; std::string default_model() const override; diff --git a/src/providers/openai/openai_client.cpp b/src/providers/openai/openai_client.cpp index 7c45bd5..bb640e8 100644 --- a/src/providers/openai/openai_client.cpp +++ b/src/providers/openai/openai_client.cpp @@ -48,7 +48,8 @@ OpenAIClient::OpenAIClient( .auth_header_name = "Authorization", .auth_header_prefix = "Bearer ", .extra_headers = {}, - .retry_config = std::move(retry_config)}, + .retry_config = std::move(retry_config), + .models_endpoint_path = "/v1/models"}, std::move(request_builder), std::move(response_parser)) { ai::logger::log_debug( @@ -103,8 +104,9 @@ std::vector OpenAIClient::supported_models() const { } bool OpenAIClient::supports_model(const std::string& model_name) const { - auto models = supported_models(); - return std::find(models.begin(), models.end(), model_name) != models.end(); + // Any model name is forwarded to the API as is; the model catalog lives + // on the provider side (see `list_models`). + return !model_name.empty(); } std::string OpenAIClient::config_info() const { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 350d788..40caeb2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,6 +10,7 @@ set(AI_TEST_SOURCES unit/multi_step_coordinator_test.cpp unit/langfuse_tracer_test.cpp unit/openai_responses_test.cpp + unit/list_models_test.cpp unit/google_client_test.cpp unit/google_stream_test.cpp @@ -32,6 +33,7 @@ set(AI_TEST_SOURCES # Add Bedrock tests when enabled if(AI_SDK_ENABLE_BEDROCK) list(APPEND AI_TEST_SOURCES + unit/bedrock_client_test.cpp unit/bedrock_request_mapper_test.cpp unit/bedrock_response_parser_test.cpp unit/bedrock_stream_test.cpp diff --git a/tests/integration/anthropic_integration_test.cpp b/tests/integration/anthropic_integration_test.cpp index e09c32a..e649198 100644 --- a/tests/integration/anthropic_integration_test.cpp +++ b/tests/integration/anthropic_integration_test.cpp @@ -128,6 +128,17 @@ TEST_F(AnthropicIntegrationTest, ConversationWithMessages) { } // Model Testing +TEST_F(AnthropicIntegrationTest, ListModels) { + if (!use_real_api_) { + GTEST_SKIP() << "No ANTHROPIC_API_KEY environment variable set"; + } + + // Anthropic pages the list; every page is followed. + const auto result = client_->list_models(); + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_THAT(result.models, testing::Contains(testing::StartsWith("claude-"))); +} + TEST_F(AnthropicIntegrationTest, DifferentModelSupport) { if (!use_real_api_) { GTEST_SKIP() << "No ANTHROPIC_API_KEY environment variable set"; diff --git a/tests/integration/bedrock_integration_test.cpp b/tests/integration/bedrock_integration_test.cpp index d90e578..2fc128e 100644 --- a/tests/integration/bedrock_integration_test.cpp +++ b/tests/integration/bedrock_integration_test.cpp @@ -146,6 +146,17 @@ TEST_F(BedrockIntegrationTest, ConfigInfoContainsRegion) { EXPECT_NE(info.find("region"), std::string::npos); } +// The live model list contains the foundation models of the Region +TEST_F(BedrockIntegrationTest, ListModelsReturnsFoundationModels) { + auto result = client_.list_models(); + + ASSERT_TRUE(result.is_success()) << result.error.value_or(""); + EXPECT_FALSE(result.models.empty()); + for (const auto& model : result.models) { + EXPECT_FALSE(model.empty()); + } +} + // Test input validation - invalid max_tokens TEST_F(BedrockIntegrationTest, RejectsInvalidMaxTokens) { GenerateOptions options; diff --git a/tests/integration/google_integration_test.cpp b/tests/integration/google_integration_test.cpp index 0a2c4d5..c939c9e 100644 --- a/tests/integration/google_integration_test.cpp +++ b/tests/integration/google_integration_test.cpp @@ -41,6 +41,14 @@ class GoogleIntegrationTest : public AITestFixture { GTEST_SKIP() << "No GEMINI_API_KEY environment variable set"; \ } +TEST_F(GoogleIntegrationTest, ListModels) { + SKIP_WITHOUT_GEMINI_KEY(); + + const auto result = client_->list_models(); + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_THAT(result.models, testing::Contains(testing::StartsWith("gemini-"))); +} + TEST_F(GoogleIntegrationTest, BasicTextGeneration) { SKIP_WITHOUT_GEMINI_KEY(); diff --git a/tests/integration/openai_integration_test.cpp b/tests/integration/openai_integration_test.cpp index ad9e243..6449611 100644 --- a/tests/integration/openai_integration_test.cpp +++ b/tests/integration/openai_integration_test.cpp @@ -128,6 +128,16 @@ TEST_F(OpenAIIntegrationTest, ConversationWithMessages) { } // Model Testing +TEST_F(OpenAIIntegrationTest, ListModels) { + if (!use_real_api_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + const auto result = client_->list_models(); + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_THAT(result.models, testing::Contains(testing::StartsWith("gpt-"))); +} + TEST_F(OpenAIIntegrationTest, DifferentModelSupport) { if (!use_real_api_) { GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; @@ -428,11 +438,9 @@ TEST_F(EnvironmentConfigTest, DefaultClientCreation) { EXPECT_TRUE(client.is_valid()); EXPECT_EQ(client.provider_name(), "openai"); - // Test that supported models include expected ones - auto models = client.supported_models(); + // Any non-empty model name is forwarded to the API EXPECT_TRUE(client.supports_model(ai::openai::models::kGpt56Luna)); - EXPECT_TRUE(client.supports_model(ai::openai::models::kGpt41)); - EXPECT_FALSE(client.supports_model("gpt-3.5-turbo")); + EXPECT_TRUE(client.supports_model("gpt-3.5-turbo")); } else { GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; } diff --git a/tests/unit/anthropic_client_test.cpp b/tests/unit/anthropic_client_test.cpp index 0202a1c..30db51a 100644 --- a/tests/unit/anthropic_client_test.cpp +++ b/tests/unit/anthropic_client_test.cpp @@ -117,9 +117,7 @@ TEST_F(AnthropicClientTest, SupportsValidModel) { EXPECT_TRUE(client_->supports_model("claude-haiku-4-5-20251001")); } -TEST_F(AnthropicClientTest, DoesNotSupportInvalidModel) { - EXPECT_FALSE(client_->supports_model("invalid-model")); - EXPECT_FALSE(client_->supports_model("gpt-4")); +TEST_F(AnthropicClientTest, DoesNotSupportEmptyModelName) { EXPECT_FALSE(client_->supports_model("")); } diff --git a/tests/unit/bedrock_client_test.cpp b/tests/unit/bedrock_client_test.cpp new file mode 100644 index 0000000..6106dbb --- /dev/null +++ b/tests/unit/bedrock_client_test.cpp @@ -0,0 +1,77 @@ +// Bedrock client unit tests (no network access) + +#include + +#ifdef AI_SDK_HAS_BEDROCK + +#include "ai/bedrock.h" +#include "ai/errors.h" + +#include +#include + +namespace ai { +namespace bedrock { +namespace { + +BedrockConfig offline_config() { + BedrockConfig config; + config.region = "us-east-1"; + // Nothing listens there; the tests below do not send requests + config.endpoint_override = "http://127.0.0.1:1"; + return config; +} + +TEST(BedrockClientTest, CreatesClientWithRegion) { + auto client = create_client(offline_config()); + + EXPECT_TRUE(client.is_valid()); + EXPECT_EQ(client.provider_name(), "bedrock"); + EXPECT_EQ(client.default_model(), models::kDefaultModel); + EXPECT_NE(client.config_info().find("us-east-1"), std::string::npos); +} + +TEST(BedrockClientTest, SupportsAnyNonEmptyModelId) { + auto client = create_client(offline_config()); + + EXPECT_TRUE(client.supports_model(models::kClaudeSonnet)); + EXPECT_TRUE(client.supports_model("vendor.some-new-model-v1:0")); + EXPECT_TRUE(client.supports_model( + "arn:aws:bedrock:us-east-1:123456789012:inference-profile/" + "us.anthropic.claude-sonnet-5-5")); + EXPECT_FALSE(client.supports_model("")); +} + +TEST(BedrockClientTest, SupportedModelsContainsCurrentClaudeModels) { + auto client = create_client(offline_config()); + const auto models = client.supported_models(); + + for (const char* model : {models::kClaudeFable, models::kClaudeOpus, + models::kClaudeSonnet, models::kClaudeHaiku}) { + EXPECT_NE(std::find(models.begin(), models.end(), model), models.end()) + << model; + } +} + +TEST(BedrockClientTest, RequiresRegion) { + BedrockConfig config = offline_config(); + config.region.clear(); + if (std::getenv("AWS_REGION") != nullptr || + std::getenv("AWS_DEFAULT_REGION") != nullptr) { + GTEST_SKIP() << "AWS_REGION or AWS_DEFAULT_REGION is set"; + } + + EXPECT_THROW(create_client(config), ConfigurationError); +} + +} // namespace +} // namespace bedrock +} // namespace ai + +#else // AI_SDK_HAS_BEDROCK + +TEST(BedrockClientTest, BedrockNotEnabled) { + GTEST_SKIP() << "Bedrock provider not enabled. Set AI_SDK_ENABLE_BEDROCK=ON"; +} + +#endif // AI_SDK_HAS_BEDROCK diff --git a/tests/unit/list_models_test.cpp b/tests/unit/list_models_test.cpp new file mode 100644 index 0000000..17a1fea --- /dev/null +++ b/tests/unit/list_models_test.cpp @@ -0,0 +1,204 @@ +#include "ai/anthropic.h" +#include "ai/google.h" +#include "ai/openai.h" + +#include +#include +#include +#include + +#include +#include + +namespace ai { +namespace test { + +namespace { + +// Serves canned responses on a local port for the lifetime of the object. +class LocalServer { + public: + explicit LocalServer( + const std::function& register_handlers) { + register_handlers(server_); + port_ = server_.bind_to_any_port("127.0.0.1"); + thread_ = std::thread([this] { server_.listen_after_bind(); }); + server_.wait_until_ready(); + } + + ~LocalServer() { + server_.stop(); + thread_.join(); + } + + std::string url() const { + return "http://127.0.0.1:" + std::to_string(port_); + } + + private: + httplib::Server server_; + int port_ = 0; + std::thread thread_; +}; + +} // namespace + +TEST(ListModelsTest, AnthropicFollowsPagination) { + std::vector seen_after_ids; + std::string seen_api_key; + std::string seen_version; + LocalServer server([&](httplib::Server& s) { + s.Get("/v1/models", [&](const httplib::Request& req, + httplib::Response& res) { + seen_api_key = req.get_header_value("x-api-key"); + seen_version = req.get_header_value("anthropic-version"); + const auto after_id = req.get_param_value("after_id"); + seen_after_ids.push_back(after_id); + if (after_id.empty()) { + res.set_content( + R"({"data":[{"id":"claude-opus-5-5"},{"id":"claude-sonnet-5-5"}],)" + R"("has_more":true,"first_id":"claude-opus-5-5","last_id":"claude-sonnet-5-5"})", + "application/json"); + } else { + res.set_content( + R"({"data":[{"id":"claude-haiku-5-5"}],"has_more":false,)" + R"("first_id":"claude-haiku-5-5","last_id":"claude-haiku-5-5"})", + "application/json"); + } + }); + }); + + auto client = anthropic::create_client("sk-ant-test", server.url()); + const auto result = client.list_models(); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_THAT(result.models, + testing::ElementsAre("claude-opus-5-5", "claude-sonnet-5-5", + "claude-haiku-5-5")); + EXPECT_THAT(seen_after_ids, testing::ElementsAre("", "claude-sonnet-5-5")); + EXPECT_EQ(seen_api_key, "sk-ant-test"); + EXPECT_FALSE(seen_version.empty()); +} + +TEST(ListModelsTest, FailsWhenPaginationDoesNotAdvance) { + int requests = 0; + LocalServer server([&](httplib::Server& s) { + s.Get("/v1/models", [&](const httplib::Request&, httplib::Response& res) { + // Ignores `after_id` and always reports more pages. + ++requests; + res.set_content(R"({"data":[{"id":"claude-opus-5-5"}],"has_more":true,)" + R"("last_id":"claude-opus-5-5"})", + "application/json"); + }); + }); + + auto client = anthropic::create_client("sk-ant-test", server.url()); + const auto result = client.list_models(); + + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), testing::HasSubstr("repeated")); + EXPECT_EQ(requests, 2); +} + +TEST(ListModelsTest, OpenAIReturnsAllModelsAtOnce) { + std::string seen_authorization; + LocalServer server([&](httplib::Server& s) { + s.Get("/v1/models", [&](const httplib::Request& req, + httplib::Response& res) { + seen_authorization = req.get_header_value("Authorization"); + res.set_content( + R"({"object":"list","data":[{"id":"gpt-6.2-sol","object":"model"},)" + R"({"id":"gpt-6-luna","object":"model"}]})", + "application/json"); + }); + }); + + auto client = openai::create_client("sk-test", server.url()); + const auto result = client.list_models(); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_THAT(result.models, testing::ElementsAre("gpt-6.2-sol", "gpt-6-luna")); + EXPECT_EQ(seen_authorization, "Bearer sk-test"); +} + +TEST(ListModelsTest, GoogleFollowsPageTokensAndStripsPrefix) { + std::vector seen_tokens; + std::string seen_api_key; + LocalServer server([&](httplib::Server& s) { + s.Get("/v1beta/models", [&](const httplib::Request& req, + httplib::Response& res) { + seen_api_key = req.get_header_value("x-goog-api-key"); + const auto token = req.get_param_value("pageToken"); + seen_tokens.push_back(token); + if (token.empty()) { + res.set_content(R"({"models":[{"name":"models/gemini-4-hydrogen"}],)" + R"("nextPageToken":"a+b/c="})", + "application/json"); + } else { + res.set_content(R"({"models":[{"name":"models/gemini-3.8-flash"}]})", + "application/json"); + } + }); + }); + + auto client = google::create_client("gemini-test", server.url()); + const auto result = client.list_models(); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_THAT(result.models, + testing::ElementsAre("gemini-4-hydrogen", "gemini-3.8-flash")); + // The token round-trips through percent-encoding. + EXPECT_THAT(seen_tokens, testing::ElementsAre("", "a+b/c=")); + EXPECT_EQ(seen_api_key, "gemini-test"); +} + +TEST(ListModelsTest, ReportsProviderErrors) { + LocalServer server([](httplib::Server& s) { + s.Get("/v1/models", [](const httplib::Request&, httplib::Response& res) { + res.status = 401; + res.set_content( + R"({"error":{"message":"Incorrect API key provided","type":"invalid_request_error"}})", + "application/json"); + }); + }); + + auto client = openai::create_client("sk-wrong", server.url()); + const auto result = client.list_models(); + + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), + testing::HasSubstr("Incorrect API key provided")); + EXPECT_TRUE(result.models.empty()); +} + +TEST(ListModelsTest, RejectsUnexpectedResponseShape) { + LocalServer server([](httplib::Server& s) { + s.Get("/v1/models", [](const httplib::Request&, httplib::Response& res) { + res.set_content(R"({"models":[]})", "application/json"); + }); + }); + + auto client = openai::create_client("sk-test", server.url()); + const auto result = client.list_models(); + + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), testing::HasSubstr("data")); +} + +TEST(ListModelsTest, AnyNonEmptyModelNameIsSupported) { + auto openai_client = openai::create_client("sk-test"); + auto anthropic_client = anthropic::create_client("sk-ant-test"); + + // Model names are forwarded as is, so new and gateway-specific names work + // without an SDK update. + for (const auto* model : + {"gpt-7", "claude-opus-9-9", "anthropic/claude-sonnet-5-5"}) { + EXPECT_TRUE(openai_client.supports_model(model)) << model; + EXPECT_TRUE(anthropic_client.supports_model(model)) << model; + } + EXPECT_FALSE(openai_client.supports_model("")); + EXPECT_FALSE(anthropic_client.supports_model("")); +} + +} // namespace test +} // namespace ai diff --git a/tests/unit/openai_client_test.cpp b/tests/unit/openai_client_test.cpp index ba65d0a..fa39f6f 100644 --- a/tests/unit/openai_client_test.cpp +++ b/tests/unit/openai_client_test.cpp @@ -99,9 +99,7 @@ TEST_F(OpenAIClientTest, SupportsValidModel) { EXPECT_TRUE(client_->supports_model("gpt-4.1")); } -TEST_F(OpenAIClientTest, DoesNotSupportInvalidModel) { - EXPECT_FALSE(client_->supports_model("invalid-model")); - EXPECT_FALSE(client_->supports_model("claude-sonnet-4-6")); +TEST_F(OpenAIClientTest, DoesNotSupportEmptyModelName) { EXPECT_FALSE(client_->supports_model("")); }