From 03ca966708f783bae2721b6793cc6b5419383c98 Mon Sep 17 00:00:00 2001 From: Aaron Po Date: Mon, 24 Aug 2026 01:13:41 -0400 Subject: [PATCH] C++ code formatting --- .../includes/web_client/http_web_client.h | 7 +- .../application_options/parse_arguments.cc | 9 +- .../log_results.cc | 40 ++++----- .../query_cities_with_countries.cc | 1 - .../generation_json_validation.cc | 9 +- .../openai/call_chat_completions_api.cc | 82 +++++++++---------- .../openai/generate_brewery.cc | 15 ++-- .../data_generation/openai/generate_user.cc | 6 +- .../openai/openai_generator.cc | 4 +- tooling/pipeline/src/main.cc | 80 +++++++++--------- .../curated_data/curated_json_data_service.cc | 22 ++--- .../src/services/sqlite/process_record.cc | 4 +- 12 files changed, 136 insertions(+), 143 deletions(-) diff --git a/tooling/pipeline/includes/web_client/http_web_client.h b/tooling/pipeline/includes/web_client/http_web_client.h index 78b46c64..d6601098 100644 --- a/tooling/pipeline/includes/web_client/http_web_client.h +++ b/tooling/pipeline/includes/web_client/http_web_client.h @@ -51,10 +51,9 @@ class HttpWebClient final : public WebClient { * @param headers Additional request headers. * @return Response body on HTTP 2xx; throws std::runtime_error otherwise. */ - std::string Post( - const std::string& url, const std::string& body, - const std::vector>& headers) - override; + std::string Post(const std::string& url, const std::string& body, + const std::vector>& + headers) override; /** * @brief Percent-encodes a single URI component (query parameter value or diff --git a/tooling/pipeline/src/application_options/parse_arguments.cc b/tooling/pipeline/src/application_options/parse_arguments.cc index bf3b37b6..6e35cfad 100644 --- a/tooling/pipeline/src/application_options/parse_arguments.cc +++ b/tooling/pipeline/src/application_options/parse_arguments.cc @@ -121,9 +121,9 @@ std::optional ParseArguments( // Enforce mutual exclusivity before any further configuration is // applied. - const int selected_generator_count = - (use_mocked ? 1 : 0) + (!model_path.empty() ? 1 : 0) + - (use_openai ? 1 : 0); + const int selected_generator_count = (use_mocked ? 1 : 0) + + (!model_path.empty() ? 1 : 0) + + (use_openai ? 1 : 0); if (selected_generator_count > 1) { const std::string msg = @@ -190,7 +190,8 @@ std::optional ParseArguments( : use_openai ? GeneratorMode::kOpenAI : GeneratorMode::kLlama; options.generator.model_path = model_path; - options.generator.openai_model = var_map["openai-model"].as(); + options.generator.openai_model = + var_map["openai-model"].as(); // Only populate sampling config when the user explicitly overrides at // least one value. Leaving it as std::nullopt lets LlamaGenerator fall diff --git a/tooling/pipeline/src/biergarten_pipeline_orchestrator/log_results.cc b/tooling/pipeline/src/biergarten_pipeline_orchestrator/log_results.cc index dee24693..6e793655 100644 --- a/tooling/pipeline/src/biergarten_pipeline_orchestrator/log_results.cc +++ b/tooling/pipeline/src/biergarten_pipeline_orchestrator/log_results.cc @@ -17,18 +17,18 @@ void BiergartenPipelineOrchestrator::LogResults() const { for (const auto& [address, brewery] : generated_breweries_) { const City& city = address.city; brewery_output.push_back(boost::json::object{ - {"name_en", brewery.name_en}, - {"description_en", brewery.description_en}, - {"name_local", brewery.name_local}, - {"description_local", brewery.description_local}, - {"address", boost::json::object{ - {"city", city.city}, - {"country", city.country}, - {"state_province", city.state_province}, - {"iso3166_2", city.iso3166_2}, - {"longitude", address.longitude}, - {"latitude", address.latitude}, - }}}); + {"name_en", brewery.name_en}, + {"description_en", brewery.description_en}, + {"name_local", brewery.name_local}, + {"description_local", brewery.description_local}, + {"address", boost::json::object{ + {"city", city.city}, + {"country", city.country}, + {"state_province", city.state_province}, + {"iso3166_2", city.iso3166_2}, + {"longitude", address.longitude}, + {"latitude", address.latitude}, + }}}); } std::ostringstream brewery_oss; @@ -41,14 +41,14 @@ void BiergartenPipelineOrchestrator::LogResults() const { for (const auto& generated_user : generated_users_) { user_output.push_back(boost::json::object{ - {"first_name", generated_user.user.first_name}, - {"last_name", generated_user.user.last_name}, - {"gender", generated_user.user.gender}, - {"username", generated_user.user.username}, - {"bio", generated_user.user.bio}, - {"activity_weight", generated_user.user.activity_weight}, - {"email", generated_user.email}, - {"date_of_birth", generated_user.date_of_birth}, + {"first_name", generated_user.user.first_name}, + {"last_name", generated_user.user.last_name}, + {"gender", generated_user.user.gender}, + {"username", generated_user.user.username}, + {"bio", generated_user.user.bio}, + {"activity_weight", generated_user.user.activity_weight}, + {"email", generated_user.email}, + {"date_of_birth", generated_user.date_of_birth}, }); } diff --git a/tooling/pipeline/src/biergarten_pipeline_orchestrator/query_cities_with_countries.cc b/tooling/pipeline/src/biergarten_pipeline_orchestrator/query_cities_with_countries.cc index 4c5d5ada..ddcbb4ff 100644 --- a/tooling/pipeline/src/biergarten_pipeline_orchestrator/query_cities_with_countries.cc +++ b/tooling/pipeline/src/biergarten_pipeline_orchestrator/query_cities_with_countries.cc @@ -43,6 +43,5 @@ std::vector BiergartenPipelineOrchestrator::QueryLocations() { " Locations available: {}\n Sampled Locations: {}", all_locations.size(), sampled_locations.size())}); - return sampled_locations; } \ No newline at end of file diff --git a/tooling/pipeline/src/data_generation/generation_json_validation.cc b/tooling/pipeline/src/data_generation/generation_json_validation.cc index b8558fc7..d5ce4359 100644 --- a/tooling/pipeline/src/data_generation/generation_json_validation.cc +++ b/tooling/pipeline/src/data_generation/generation_json_validation.cc @@ -8,14 +8,13 @@ #include #include +#include #include #include #include #include #include -#include - namespace { std::string Trim(std::string_view value) { constexpr std::string_view whitespace = " \t\n\r\f\v"; @@ -55,7 +54,8 @@ std::string CondenseWhitespace(std::string_view text) { return out; } -// Keeps truncation past the string's midpoint, preserving the critical opening content. +// Keeps truncation past the string's midpoint, preserving the critical opening +// content. constexpr size_t kTruncationGuardDivisor = 2; bool ReadRequiredTrimmedStringField(const boost::json::object& obj, @@ -64,8 +64,7 @@ bool ReadRequiredTrimmedStringField(const boost::json::object& obj, const boost::json::value* field = obj.if_contains(key); if (field == nullptr || !field->is_string()) { if (error_out != nullptr) { - *error_out = - std::format("Missing or invalid string field: {}", key); + *error_out = std::format("Missing or invalid string field: {}", key); } return false; } diff --git a/tooling/pipeline/src/data_generation/openai/call_chat_completions_api.cc b/tooling/pipeline/src/data_generation/openai/call_chat_completions_api.cc index f878616f..39dbf256 100644 --- a/tooling/pipeline/src/data_generation/openai/call_chat_completions_api.cc +++ b/tooling/pipeline/src/data_generation/openai/call_chat_completions_api.cc @@ -6,9 +6,11 @@ * * API docs last accessed 2026-08-23. * Docs: https://platform.openai.com/docs/api-reference/chat/create - * Structured Outputs: https://platform.openai.com/docs/guides/structured-outputs + * Structured Outputs: + * https://platform.openai.com/docs/guides/structured-outputs */ +#include #include #include #include @@ -16,15 +18,13 @@ #include #include -#include - #include "data_generation/openai_generator.h" namespace { // https://platform.openai.com/docs/api-reference/chat/create constexpr std::string_view kChatCompletionsUrl = - "https://api.openai.com/v1/chat/completions"; -} // namespace + "https://api.openai.com/v1/chat/completions"; +} // namespace /** * @brief Sends a single Chat Completions request constrained by a JSON @@ -45,22 +45,22 @@ constexpr std::string_view kChatCompletionsUrl = * response, model refusal, or missing content. */ std::string OpenAIGenerator::CallChatCompletionsApi( - const std::string& system_prompt, const std::string& user_prompt, - std::string_view json_schema, std::string_view schema_name, - int max_tokens) { - + const std::string& system_prompt, const std::string& user_prompt, + std::string_view json_schema, std::string_view schema_name, + int max_tokens) { boost::system::error_code schema_error; boost::json::value schema_value = - boost::json::parse(json_schema, schema_error); + boost::json::parse(json_schema, schema_error); bool schema_is_invalid = static_cast(schema_error); if (schema_is_invalid) { throw std::runtime_error( - "OpenAIGenerator: invalid embedded JSON schema: " + - schema_error.message()); + "OpenAIGenerator: invalid embedded JSON schema: " + + schema_error.message()); } - // response_format: https://platform.openai.com/docs/guides/structured-outputs + // response_format: + // https://platform.openai.com/docs/guides/structured-outputs boost::json::object json_schema_wrapper; json_schema_wrapper["name"] = std::string(schema_name); json_schema_wrapper["strict"] = true; @@ -91,27 +91,27 @@ std::string OpenAIGenerator::CallChatCompletionsApi( const std::string body = boost::json::serialize(request); const std::vector> headers = { - {"Authorization", std::format("Bearer {}", api_key_)}, + {"Authorization", std::format("Bearer {}", api_key_)}, }; const std::string response_body = - web_client_->Post(std::string(kChatCompletionsUrl), body, headers); + web_client_->Post(std::string(kChatCompletionsUrl), body, headers); boost::system::error_code response_error; boost::json::value response_value = - boost::json::parse(response_body, response_error); + boost::json::parse(response_body, response_error); bool response_body_is_invalid = static_cast(response_error); if (response_body_is_invalid) { throw std::runtime_error( - "OpenAIGenerator: failed to parse API response: " + - response_error.message()); + "OpenAIGenerator: failed to parse API response: " + + response_error.message()); } bool response_root_is_not_object = !response_value.is_object(); if (response_root_is_not_object) { throw std::runtime_error( - "OpenAIGenerator: API response root is not an object"); + "OpenAIGenerator: API response root is not an object"); } const auto& response_obj = response_value.get_object(); @@ -119,63 +119,63 @@ std::string OpenAIGenerator::CallChatCompletionsApi( const boost::json::value* error_field = response_obj.if_contains("error"); bool top_level_error_occurred = - error_field != nullptr && error_field->is_object(); + error_field != nullptr && error_field->is_object(); if (top_level_error_occurred) { std::string error_message = "unknown error"; if (const boost::json::value* message_field = - error_field->get_object().if_contains("message"); - message_field != nullptr && message_field->is_string()) { + error_field->get_object().if_contains("message"); + message_field != nullptr && message_field->is_string()) { error_message = std::string(message_field->as_string()); } - throw std::runtime_error( - std::format("OpenAIGenerator: API request failed: {}", error_message)); + throw std::runtime_error(std::format( + "OpenAIGenerator: API request failed: {}", error_message)); } - const boost::json::value* choices_field = response_obj. - if_contains("choices"); - bool choices_field_missing_or_invalid = - choices_field == nullptr || !choices_field->is_array() || - choices_field->get_array().empty(); + const boost::json::value* choices_field = + response_obj.if_contains("choices"); + bool choices_field_missing_or_invalid = choices_field == nullptr || + !choices_field->is_array() || + choices_field->get_array().empty(); if (choices_field_missing_or_invalid) { throw std::runtime_error( - "OpenAIGenerator: API response missing choices array"); + "OpenAIGenerator: API response missing choices array"); } const boost::json::value& first_choice = choices_field->get_array().front(); bool first_choice_is_not_object = !first_choice.is_object(); if (first_choice_is_not_object) { throw std::runtime_error( - "OpenAIGenerator: API response choice is not an object"); + "OpenAIGenerator: API response choice is not an object"); } const auto& choice_obj = first_choice.get_object(); const boost::json::value* message_field = choice_obj.if_contains("message"); bool message_field_missing_or_invalid = - message_field == nullptr || !message_field->is_object(); + message_field == nullptr || !message_field->is_object(); if (message_field_missing_or_invalid) { throw std::runtime_error( - "OpenAIGenerator: API response choice missing message"); + "OpenAIGenerator: API response choice missing message"); } const auto& message_obj = message_field->get_object(); // Refusal field: https://platform.openai.com/docs/guides/structured-outputs const boost::json::value* refusal_field = message_obj.if_contains("refusal"); - bool model_refused_request = - refusal_field != nullptr && refusal_field->is_string() && - !refusal_field->as_string().empty(); + bool model_refused_request = refusal_field != nullptr && + refusal_field->is_string() && + !refusal_field->as_string().empty(); if (model_refused_request) { - throw std::runtime_error(std::format( - "OpenAIGenerator: request refused by safety policies: {}", - std::string(refusal_field->as_string()))); + throw std::runtime_error( + std::format("OpenAIGenerator: request refused by safety policies: {}", + std::string(refusal_field->as_string()))); } const boost::json::value* content_field = message_obj.if_contains("content"); bool content_field_missing_or_invalid = - content_field == nullptr || !content_field->is_string(); + content_field == nullptr || !content_field->is_string(); if (content_field_missing_or_invalid) { throw std::runtime_error( - "OpenAIGenerator: API response message had no text content"); + "OpenAIGenerator: API response message had no text content"); } return std::string(content_field->as_string()); diff --git a/tooling/pipeline/src/data_generation/openai/generate_brewery.cc b/tooling/pipeline/src/data_generation/openai/generate_brewery.cc index c44d057c..6693e8f6 100644 --- a/tooling/pipeline/src/data_generation/openai/generate_brewery.cc +++ b/tooling/pipeline/src/data_generation/openai/generate_brewery.cc @@ -17,8 +17,7 @@ namespace { -std::string FormatLocalLanguageCodes( - const std::vector& codes) { +std::string FormatLocalLanguageCodes(const std::vector& codes) { if (codes.empty()) { return "Not provided"; } @@ -36,7 +35,8 @@ std::string FormatLocalLanguageCodes( constexpr int kBreweryMaxTokens = 2800; -// Structured outputs already guarantee schema-valid JSON, so retries here only cover transient failures or the model returning placeholder text. +// Structured outputs already guarantee schema-valid JSON, so retries here only +// cover transient failures or the model returning placeholder text. constexpr int kMaxAttempts = 2; } // namespace @@ -51,7 +51,8 @@ BreweryResult OpenAIGenerator::GenerateBrewery( FormatLocalLanguageCodes(location.local_languages); /** - * Loads the backend-agnostic brewery system prompt via the injected prompt directory. + * Loads the backend-agnostic brewery system prompt via the injected prompt + * directory. */ const std::string system_prompt = prompt_directory_->Load("BREWERY_GENERATION"); @@ -70,9 +71,9 @@ BreweryResult OpenAIGenerator::GenerateBrewery( std::string last_error; for (int attempt = 0; attempt < kMaxAttempts; ++attempt) { - raw = CallChatCompletionsApi(system_prompt, user_prompt, - kBreweryJsonSchema, "brewery_result", - kBreweryMaxTokens); + raw = + CallChatCompletionsApi(system_prompt, user_prompt, kBreweryJsonSchema, + "brewery_result", kBreweryMaxTokens); if (logger_) { logger_->Log({.level = LogLevel::Debug, .phase = PipelinePhase::BreweryAndBeerGeneration, diff --git a/tooling/pipeline/src/data_generation/openai/generate_user.cc b/tooling/pipeline/src/data_generation/openai/generate_user.cc index 592a1245..1a6bd7a7 100644 --- a/tooling/pipeline/src/data_generation/openai/generate_user.cc +++ b/tooling/pipeline/src/data_generation/openai/generate_user.cc @@ -16,7 +16,8 @@ namespace { constexpr int kUserMaxTokens = 1200; -// Structured outputs already guarantee schema-valid JSON, so retries here only cover transient failures or placeholder text. +// Structured outputs already guarantee schema-valid JSON, so retries here only +// cover transient failures or placeholder text. constexpr int kMaxAttempts = 2; } // namespace @@ -47,8 +48,7 @@ UserResult OpenAIGenerator::GenerateUser(const EnrichedCity& city, const std::string retry_context = std::format( "Name: {} {}\nCity: {}, {}\nPersona: {}", name.first_name, - name.last_name, city.location.city, city.location.country, - persona.name); + name.last_name, city.location.city, city.location.country, persona.name); std::string raw; std::string last_error; diff --git a/tooling/pipeline/src/data_generation/openai/openai_generator.cc b/tooling/pipeline/src/data_generation/openai/openai_generator.cc index f194a630..bbc9432f 100644 --- a/tooling/pipeline/src/data_generation/openai/openai_generator.cc +++ b/tooling/pipeline/src/data_generation/openai/openai_generator.cc @@ -3,12 +3,12 @@ * @brief OpenAIGenerator constructor. */ +#include "data_generation/openai_generator.h" + #include #include #include -#include "data_generation/openai_generator.h" - OpenAIGenerator::OpenAIGenerator( std::string api_key, std::string model, std::shared_ptr logger, std::unique_ptr prompt_directory, diff --git a/tooling/pipeline/src/main.cc b/tooling/pipeline/src/main.cc index ebed60a0..45899827 100644 --- a/tooling/pipeline/src/main.cc +++ b/tooling/pipeline/src/main.cc @@ -166,54 +166,54 @@ int main(const int argc, char** argv) { inj.template create>(), log_producer); }), - di::bind().to( - [&options, &model_path, &sampling, &prompt_directory, - &log_producer]( - const auto& inj) -> std::unique_ptr { - if (options.generator.mode == GeneratorMode::kMock) { - log_producer->Log({.level = LogLevel::Info, - .phase = PipelinePhase::Startup, - .message = "Generator: mock"}); + di::bind().to([&options, &model_path, &sampling, + &prompt_directory, + &log_producer](const auto& inj) + -> std::unique_ptr { + if (options.generator.mode == GeneratorMode::kMock) { + log_producer->Log({.level = LogLevel::Info, + .phase = PipelinePhase::Startup, + .message = "Generator: mock"}); - return std::make_unique(); - } + return std::make_unique(); + } - if (options.generator.mode == GeneratorMode::kOpenAI) { - log_producer->Log( - {.level = LogLevel::Info, - .phase = PipelinePhase::Startup, - .message = std::format( - "Generator: OpenAIGenerator | model={}", - options.generator.openai_model)}); + if (options.generator.mode == GeneratorMode::kOpenAI) { + log_producer->Log({.level = LogLevel::Info, + .phase = PipelinePhase::Startup, + .message = std::format( + "Generator: OpenAIGenerator | model={}", + options.generator.openai_model)}); - return std::make_unique( - options.generator.openai_api_key, - options.generator.openai_model, log_producer, - std::move(prompt_directory), - inj.template create>()); - } + return std::make_unique( + options.generator.openai_api_key, + options.generator.openai_model, log_producer, + std::move(prompt_directory), + inj.template create>()); + } #ifdef BIERGARTEN_MOCK_ONLY - // Only reachable when mode == Llama, which requires llama.cpp and is excluded from a BIERGARTEN_MOCK_ONLY build. - throw std::runtime_error( - "LlamaGenerator is unavailable in a BIERGARTEN_MOCK_ONLY " - "build"); + // Only reachable when mode == Llama, which requires llama.cpp and + // is excluded from a BIERGARTEN_MOCK_ONLY build. + throw std::runtime_error( + "LlamaGenerator is unavailable in a BIERGARTEN_MOCK_ONLY " + "build"); #else - log_producer->Log( - {.level = LogLevel::Info, - .phase = PipelinePhase::Startup, - .message = std::format( - "Generator: LlamaGenerator | model={} | " - "temp={:.2f} top_p={:.2f} top_k={} n_ctx={} seed={}", - model_path, sampling.temperature, sampling.top_p, - sampling.top_k, sampling.n_ctx, sampling.seed)}); + log_producer->Log( + {.level = LogLevel::Info, + .phase = PipelinePhase::Startup, + .message = std::format( + "Generator: LlamaGenerator | model={} | " + "temp={:.2f} top_p={:.2f} top_k={} n_ctx={} seed={}", + model_path, sampling.temperature, sampling.top_p, + sampling.top_k, sampling.n_ctx, sampling.seed)}); - return std::make_unique( - options, model_path, log_producer, - inj.template create>(), - std::move(prompt_directory)); + return std::make_unique( + options, model_path, log_producer, + inj.template create>(), + std::move(prompt_directory)); #endif - })); + })); const auto orchestrator = injector.create>(); diff --git a/tooling/pipeline/src/services/curated_data/curated_json_data_service.cc b/tooling/pipeline/src/services/curated_data/curated_json_data_service.cc index a0690063..09fd82e7 100644 --- a/tooling/pipeline/src/services/curated_data/curated_json_data_service.cc +++ b/tooling/pipeline/src/services/curated_data/curated_json_data_service.cc @@ -81,7 +81,7 @@ boost::json::value ParseJsonFile(const std::filesystem::path& filepath) { std::ifstream input(filepath); if (!input.is_open()) { throw std::runtime_error( - std::format("Failed to open file: {}", filepath.string())); + std::format("Failed to open file: {}", filepath.string())); } std::stringstream buffer; @@ -125,8 +125,7 @@ const LocationsList& CuratedJsonDataService::LoadLocations() { if (!cache_.locations.empty()) { return cache_.locations; } - boost::json::value root_val = - ParseJsonFile(filepaths_.locations_path); + boost::json::value root_val = ParseJsonFile(filepaths_.locations_path); if (!root_val.is_object()) { throw std::runtime_error( @@ -135,18 +134,16 @@ const LocationsList& CuratedJsonDataService::LoadLocations() { boost::json::object root_obj = root_val.as_object(); - if (!root_obj.contains("cities")) - { + if (!root_obj.contains("cities")) { throw std::runtime_error( "Invalid locations JSON: root object must contain a 'cities' key"); } - if (!root_obj["cities"].is_array()) - { + if (!root_obj["cities"].is_array()) { throw std::runtime_error( "Invalid locations JSON: 'cities' key must be an array"); } - + LocationsList locations; const boost::json::array& cities = root_obj["cities"].as_array(); locations.reserve(cities.size()); @@ -179,8 +176,7 @@ const PersonasList& CuratedJsonDataService::LoadPersonas() { return cache_.personas; } - const boost::json::value root = - ParseJsonFile(filepaths_.personas_path); + const boost::json::value root = ParseJsonFile(filepaths_.personas_path); if (!root.is_array()) { throw std::runtime_error( @@ -215,8 +211,7 @@ const ForenamesByCountryMap& CuratedJsonDataService::LoadForenamesByCountry() { return cache_.forenames_by_country; } - const boost::json::value root = - ParseJsonFile(filepaths_.forenames_path); + const boost::json::value root = ParseJsonFile(filepaths_.forenames_path); if (!root.is_object()) { throw std::runtime_error( @@ -263,8 +258,7 @@ const SurnamesByCountryMap& CuratedJsonDataService::LoadSurnamesByCountry() { return cache_.surnames_by_country; } - const boost::json::value root = - ParseJsonFile(filepaths_.surnames_path); + const boost::json::value root = ParseJsonFile(filepaths_.surnames_path); if (!root.is_object()) { throw std::runtime_error( diff --git a/tooling/pipeline/src/services/sqlite/process_record.cc b/tooling/pipeline/src/services/sqlite/process_record.cc index 64b575b7..09d62478 100644 --- a/tooling/pipeline/src/services/sqlite/process_record.cc +++ b/tooling/pipeline/src/services/sqlite/process_record.cc @@ -180,8 +180,8 @@ uint64_t SqliteExportService::ProcessRecord(const BreweryRecord& brewery) { sqlite_export_service_internal::Bind( insert_brewery_address_stmt_, sqlite_export_service_internal::BoundParam{ - .index = sqlite_export_service_internal:: - kBreweryAddressLatitudeBindIndex, + .index = + sqlite_export_service_internal::kBreweryAddressLatitudeBindIndex, .value = brewery.address.latitude, .action = "Failed to bind SQLite brewery address latitude"});