Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 8 additions & 3 deletions examples/multi_provider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
17 changes: 17 additions & 0 deletions include/ai/types/client.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "embedding_options.h"
#include "generate_options.h"
#include "model.h"
#include "stream_options.h"
#include "stream_result.h"

Expand Down Expand Up @@ -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<std::string> 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);
Expand Down
19 changes: 19 additions & 0 deletions include/ai/types/model.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <optional>
#include <string>
#include <vector>

namespace ai {

Expand Down Expand Up @@ -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<std::string> models;
std::optional<std::string> 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
42 changes: 32 additions & 10 deletions src/http/http_request_handler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -116,25 +132,31 @@ 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);
cli.set_connection_timeout(config_.connection_timeout_sec, 0);
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) {
Expand Down
18 changes: 16 additions & 2 deletions src/http/http_request_handler.h
Original file line number Diff line number Diff line change
Expand Up @@ -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(const httplib::Result&, const std::string&)>;
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);
Expand Down
14 changes: 7 additions & 7 deletions src/providers/anthropic/anthropic_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<AnthropicRequestBuilder>(),
std::make_unique<AnthropicResponseParser>()) {
ai::logger::log_debug("Anthropic client initialized with base_url: {}{}",
Expand Down Expand Up @@ -73,10 +74,8 @@ std::string AnthropicClient::provider_name() const {
}

std::vector<std::string> 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,
Expand All @@ -90,8 +89,9 @@ std::vector<std::string> 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 {
Expand Down
80 changes: 80 additions & 0 deletions src/providers/base_provider_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#include "ai/logger.h"
#include "ai/tools.h"

#include <set>

namespace ai {
namespace providers {

Expand Down Expand Up @@ -197,5 +199,83 @@ EmbeddingResult BaseProviderClient::embeddings(
}
}

std::optional<std::string> 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<std::string> 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<std::string>());
}
}

const auto has_more = json_response.find("has_more");
if (has_more == json_response.end() || !has_more->is_boolean() ||
!has_more->get<bool>()) {
break;
}
const auto last_id = json_response.find("last_id");
if (last_id == json_response.end() || !last_id->is_string() ||
last_id->get<std::string>().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<std::string>()).second) {
return ModelListResult("Unexpected models response: pagination cursor `" +
last_id->get<std::string>() + "` repeated");
}
path = config_.models_endpoint_path +
"?after_id=" + last_id->get<std::string>();
}
Comment thread
alexey-milovidov marked this conversation as resolved.
Resolved

ai::logger::log_debug("Listed {} models", listed.models.size());
return listed;
}

} // namespace providers
} // namespace ai
12 changes: 12 additions & 0 deletions src/providers/base_provider_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ struct ProviderConfig {

// Optional retry configuration
std::optional<retry::RetryConfig> 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
Expand Down Expand Up @@ -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<std::string> 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);
Expand Down
Loading
Loading