diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7839dcd..db28e1f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,4 +52,5 @@ jobs: run: ctest --build-config ${{ matrix.build_type == 'debug' && 'Debug' || 'Release' }} --output-on-failure --parallel env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} \ No newline at end of file + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} diff --git a/CMakeLists.txt b/CMakeLists.txt index 33d92c3..f23f3dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,6 +46,7 @@ set(HTTPLIB_COMPILE_DEFS add_library(ai-sdk-cpp-core) add_library(ai-sdk-cpp-openai) add_library(ai-sdk-cpp-anthropic) +add_library(ai-sdk-cpp-google) add_library(ai-sdk-cpp-langfuse) add_library(ai-sdk-cpp INTERFACE) @@ -53,6 +54,7 @@ add_library(ai-sdk-cpp INTERFACE) set_target_properties(ai-sdk-cpp-core PROPERTIES EXPORT_NAME core) set_target_properties(ai-sdk-cpp-openai PROPERTIES EXPORT_NAME openai) set_target_properties(ai-sdk-cpp-anthropic PROPERTIES EXPORT_NAME anthropic) +set_target_properties(ai-sdk-cpp-google PROPERTIES EXPORT_NAME google) set_target_properties(ai-sdk-cpp-langfuse PROPERTIES EXPORT_NAME langfuse) set_target_properties(ai-sdk-cpp PROPERTIES EXPORT_NAME sdk) @@ -61,12 +63,14 @@ add_library(ai::sdk ALIAS ai-sdk-cpp) add_library(ai::core ALIAS ai-sdk-cpp-core) add_library(ai::openai ALIAS ai-sdk-cpp-openai) add_library(ai::anthropic ALIAS ai-sdk-cpp-anthropic) +add_library(ai::google ALIAS ai-sdk-cpp-google) add_library(ai::langfuse ALIAS ai-sdk-cpp-langfuse) # Configure all component libraries configure_ai_component(ai-sdk-cpp-core) configure_ai_component(ai-sdk-cpp-openai) configure_ai_component(ai-sdk-cpp-anthropic) +configure_ai_component(ai-sdk-cpp-google) configure_ai_component(ai-sdk-cpp-langfuse) # Bedrock provider (optional, requires AWS SDK) @@ -127,8 +131,17 @@ set(ANTHROPIC_SOURCES src/providers/anthropic/anthropic_factory.cpp ) +set(GOOGLE_SOURCES + src/providers/google/google_client.cpp + src/providers/google/google_request_builder.cpp + src/providers/google/google_response_parser.cpp + src/providers/google/google_stream.cpp + src/providers/google/google_factory.cpp +) + target_sources(ai-sdk-cpp-openai PRIVATE ${OPENAI_SOURCES}) target_sources(ai-sdk-cpp-anthropic PRIVATE ${ANTHROPIC_SOURCES}) +target_sources(ai-sdk-cpp-google PRIVATE ${GOOGLE_SOURCES}) # Langfuse tracing component target_sources(ai-sdk-cpp-langfuse @@ -172,7 +185,7 @@ target_link_libraries(ai-sdk-cpp-core ) # Provider components link to core and share common dependencies -foreach(provider openai anthropic) +foreach(provider openai anthropic google) target_link_libraries(ai-sdk-cpp-${provider} PUBLIC ai::core @@ -248,6 +261,7 @@ target_link_libraries(ai-sdk-cpp ai::core ai::openai ai::anthropic + ai::google ai::langfuse ) @@ -264,6 +278,7 @@ target_compile_definitions(ai-sdk-cpp INTERFACE AI_SDK_HAS_OPENAI=1 AI_SDK_HAS_ANTHROPIC=1 + AI_SDK_HAS_GOOGLE=1 AI_SDK_HAS_LANGFUSE=1 ) @@ -280,6 +295,7 @@ set(COMPONENT_TARGETS ai-sdk-cpp-core ai-sdk-cpp-openai ai-sdk-cpp-anthropic + ai-sdk-cpp-google ai-sdk-cpp-langfuse ) if(AI_SDK_ENABLE_BEDROCK) diff --git a/README.md b/README.md index 81c910d..44d4169 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # AI SDK CPP -The AI SDK CPP is a modern C++ toolkit designed to help you build AI-powered applications with popular model providers like OpenAI and Anthropic. It provides a unified, easy-to-use API that abstracts away the complexity of different provider implementations. +The AI SDK CPP is a modern C++ toolkit designed to help you build AI-powered applications with popular model providers like OpenAI, Anthropic, and Google Gemini. It provides a unified, easy-to-use API that abstracts away the complexity of different provider implementations. ## Motivation @@ -18,7 +18,7 @@ You will need a C++20 compatible compiler and CMake 3.16+ installed on your deve ### Core API -The AI SDK CPP Core module provides a unified API to interact with model providers like OpenAI and Anthropic. +The AI SDK CPP Core module provides a unified API to interact with model providers like OpenAI, Anthropic, and Google Gemini. #### OpenAI Integration @@ -67,6 +67,45 @@ int main() { } ``` +#### Google Gemini Integration + +The Google provider speaks the native Gemini API (`generateContent` and +`streamGenerateContent`), not the OpenAI-compatibility endpoint. + +```cpp +#include +#include +#include + +int main() { + // Ensure GEMINI_API_KEY (or GOOGLE_API_KEY) environment variable is set + auto client = ai::google::create_client(); + ai::GenerateOptions options(ai::google::models::kGemini4Hydrogen, + "Explain quantum 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; + } + + return 0; +} +``` + +Tool calling, multi-step tool loops, structured output (`response_format`), +and streaming work as with the other providers. Gemini 4 and Gemini 3 models +attach thought signatures to their function calls and reject a follow-up +request that does not send them back; the client keeps them in +`response_messages` (as `ai::ProviderContentPart`), so the multi-step loop and +conversations continued from `response_messages` replay them automatically. +Thinking tokens count against `max_tokens`, so the client asks for the least +thinking each model accepts (`thinkingLevel` `low` or `minimal`, or the +smallest `thinkingBudget` on Gemini 2.5), like the lowest reasoning effort of +the OpenAI client; streams request thought summaries and emit them as +reasoning events (`StreamEvent::is_reasoning_delta`). Gemini 4 and Gemini 3.6+ models ignore `temperature` and +`top_p`, and the client does not send them for those models. Embeddings are not supported by this provider yet. + #### Streaming Responses ```cpp @@ -299,7 +338,8 @@ int main() { ``` The same retry-config overload is available from -`ai::anthropic::create_client` for Anthropic requests. +`ai::anthropic::create_client` for Anthropic requests and from +`ai::google::create_client` for Gemini requests. #### Using OpenAI-Compatible APIs (OpenRouter, etc.) @@ -493,7 +533,7 @@ cmake --build build ### Currently Supported -- ✅ **Text Generation**: Generate text completions with OpenAI, Anthropic, and Bedrock models +- ✅ **Text Generation**: Generate text completions with OpenAI, Anthropic, Bedrock, and Google Gemini models - ✅ **Streaming**: Real-time streaming of generated content - ✅ **Multi-turn Conversations**: Support for conversation history - ✅ **Error Handling**: Comprehensive error handling with optional types @@ -509,7 +549,7 @@ cmake --build build ### Coming Soon -- 🚧 **Additional Providers**: Google, Cohere, and other providers +- 🚧 **Additional Providers**: Cohere and other providers - 🚧 **Bedrock Embeddings**: Text embedding support for Bedrock - 🚧 **Image Generation**: Support for image generation models @@ -525,6 +565,7 @@ Check out our [examples directory](examples/) for more comprehensive usage examp - [Basic Tool Calling](examples/tool_calling_basic.cpp) - [Multi-Step Tool Workflows](examples/tool_calling_multistep.cpp) - [OpenAI Responses API](examples/openai_responses.cpp) - Tool calling with the GPT-6 models +- [Google Gemini](examples/google_gemini.cpp) - Native Gemini API: tools, structured output, streaming - [Async Tool Execution](examples/tool_calling_async.cpp) - [Search Team Documents with Loom](examples/loom_document_search.md) - [OpenRouter Integration](examples/openrouter_example.cpp) - Using OpenAI-compatible APIs diff --git a/cmake/ai-sdk-cpp-config.cmake.in b/cmake/ai-sdk-cpp-config.cmake.in index 1c660a3..8e988cf 100644 --- a/cmake/ai-sdk-cpp-config.cmake.in +++ b/cmake/ai-sdk-cpp-config.cmake.in @@ -22,7 +22,7 @@ endif() include("${CMAKE_CURRENT_LIST_DIR}/ai-sdk-cpp-targets.cmake") # Available components -set(AI_SDK_AVAILABLE_COMPONENTS core openai anthropic langfuse) +set(AI_SDK_AVAILABLE_COMPONENTS core openai anthropic google langfuse) if(AI_SDK_ENABLE_BEDROCK) list(APPEND AI_SDK_AVAILABLE_COMPONENTS bedrock) endif() diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 1df494b..16359d8 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -45,6 +45,9 @@ 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) +# Google Gemini example (native Gemini API) +add_ai_example(google_gemini google_gemini.cpp) + # OpenRouter example (OpenAI-compatible) add_ai_example(openrouter_example openrouter_example.cpp) @@ -65,6 +68,7 @@ add_ai_example(langfuse_tracing langfuse_tracing.cpp) # Component-specific examples add_subdirectory(components/openai) add_subdirectory(components/anthropic) +add_subdirectory(components/google) add_subdirectory(components/bedrock) add_subdirectory(components/all) @@ -77,17 +81,19 @@ endif() message(STATUS "Examples will be built in: ${CMAKE_BINARY_DIR}/examples/") message(STATUS "To run examples:") -message(STATUS " Set environment variables: OPENAI_API_KEY, ANTHROPIC_API_KEY, OPENROUTER_API_KEY") +message(STATUS " Set environment variables: OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY") message(STATUS " Run: ./examples/basic_chat${EXAMPLE_DISPLAY_SUFFIX}") message(STATUS " ./examples/streaming_chat${EXAMPLE_DISPLAY_SUFFIX}") message(STATUS " ./examples/multi_provider${EXAMPLE_DISPLAY_SUFFIX}") message(STATUS " ./examples/error_handling${EXAMPLE_DISPLAY_SUFFIX}") message(STATUS " ./examples/test_openai${EXAMPLE_DISPLAY_SUFFIX}") message(STATUS " ./examples/test_anthropic${EXAMPLE_DISPLAY_SUFFIX}") +message(STATUS " ./examples/google_gemini${EXAMPLE_DISPLAY_SUFFIX}") message(STATUS " ./examples/openrouter_example${EXAMPLE_DISPLAY_SUFFIX}") 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/google/google_component_demo (Google + 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/components/all/main.cpp b/examples/components/all/main.cpp index 3bd204a..7b6d599 100644 --- a/examples/components/all/main.cpp +++ b/examples/components/all/main.cpp @@ -21,6 +21,12 @@ int main() { std::cout << "- Anthropic: NO\n"; #endif +#ifdef AI_SDK_HAS_GOOGLE + std::cout << "- Google: YES\n"; +#else + std::cout << "- Google: NO\n"; +#endif + std::cout << "\n"; // Test core functionality @@ -61,10 +67,25 @@ int main() { std::cout << "\nAnthropic functionality not available\n"; #endif + // Test Google functionality +#ifdef AI_SDK_HAS_GOOGLE + std::cout << "\nTesting Google functionality...\n"; + try { + auto google_client = ai::google::create_client(); + std::cout << "✓ Google client created successfully\n"; + std::cout << "✓ Available models: " << ai::google::models::kGemini4Hydrogen + << ", " << ai::google::models::kGemini35FlashLite << "\n"; + } catch (const std::exception& e) { + std::cout << "✗ Google client failed: " << e.what() << "\n"; + } +#else + std::cout << "\nGoogle functionality not available\n"; +#endif + std::cout << "\n"; std::cout << "This example demonstrates using all components together.\n"; - std::cout - << "Both OpenAI and Anthropic should be available when linking ai::sdk\n"; + std::cout << "OpenAI, Anthropic, and Google should be available when linking " + "ai::sdk\n"; return 0; } diff --git a/examples/components/google/CMakeLists.txt b/examples/components/google/CMakeLists.txt new file mode 100644 index 0000000..8923b9f --- /dev/null +++ b/examples/components/google/CMakeLists.txt @@ -0,0 +1,13 @@ +# Google-only component example + +add_executable(google_component_demo main.cpp) +target_link_libraries(google_component_demo PRIVATE + ai::core + ai::google +) + +set_target_properties(google_component_demo PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/examples/components/google +) + +message(STATUS "Google component example will be built in: ${CMAKE_BINARY_DIR}/examples/components/google/") \ No newline at end of file diff --git a/examples/components/google/main.cpp b/examples/components/google/main.cpp new file mode 100644 index 0000000..ecc16c2 --- /dev/null +++ b/examples/components/google/main.cpp @@ -0,0 +1,47 @@ +#include + +#include + +int main() { + std::cout << "AI SDK C++ - Google 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_GOOGLE + std::cout << "- Google: YES\n"; +#else + std::cout << "- Google: NO\n"; +#endif + + std::cout << "\n"; + +#ifdef AI_SDK_HAS_GOOGLE + std::cout << "Testing Google functionality...\n"; + try { + auto client = ai::google::create_client(); + std::cout << "✓ Google client created successfully\n"; + std::cout << "✓ Default model: " << client.default_model() << "\n"; + } catch (const std::exception& e) { + std::cout << "✗ Google client failed: " << e.what() << "\n"; + } +#else + std::cout << "Google functionality not available\n"; +#endif + + std::cout << "\nThis example only links the ai::google component\n"; + return 0; +} diff --git a/examples/google_gemini.cpp b/examples/google_gemini.cpp new file mode 100644 index 0000000..82c1a04 --- /dev/null +++ b/examples/google_gemini.cpp @@ -0,0 +1,121 @@ +/** + * Google Gemini Example - AI SDK C++ + * + * Uses the native Gemini API (`generateContent` and `streamGenerateContent`) + * through `ai::google::create_client` and shows: + * - a simple generation with a system instruction + * - a multi-step tool loop (the thought signatures that Gemini attaches to + * its function calls are replayed automatically along with the tool + * results) + * - structured JSON output + * - streaming + * + * Usage: + * export GEMINI_API_KEY=your_key_here + * ./google_gemini + */ + +#include +#include + +#include +#include + +namespace { + +ai::JsonValue get_weather(const ai::JsonValue& args, + const ai::ToolExecutionContext& /*context*/) { + const auto location = args["location"].get(); + std::cout << " [tool] weather(" << location << ")\n"; + return {{"location", location}, + {"temperature", 68}, + {"unit", "Fahrenheit"}, + {"condition", "Light rain"}}; +} + +ai::JsonValue get_time(const ai::JsonValue& args, + const ai::ToolExecutionContext& /*context*/) { + const auto city = args["city"].get(); + std::cout << " [tool] local_time(" << city << ")\n"; + return {{"city", city}, {"local_time", "16:20"}}; +} + +} // namespace + +int main() { + auto client = ai::google::try_create_client(); + if (!client) { + std::cerr << "Set GEMINI_API_KEY to run this example\n"; + return 1; + } + std::cout << "Using " << client->config_info() << "\n\n"; + + // 1. Simple generation. + ai::GenerateOptions simple(ai::google::models::kDefaultModel, + "You answer in one sentence.", + "Why is the sky blue?"); + auto answer = client->generate_text(simple); + if (!answer) { + std::cerr << "Error: " << answer.error_message() << "\n"; + return 1; + } + std::cout << "Answer: " << answer.text << "\n"; + std::cout << "Tokens: " << answer.usage.total_tokens << "\n\n"; + + // 2. Multi-step tool calling. + ai::GenerateOptions options( + ai::google::models::kDefaultModel, + "What is the weather in Seattle, and what time is it there? Should I " + "take an umbrella for a walk now?"); + options.tools = { + {"weather", + ai::create_simple_tool("weather", "Get the current weather for a city", + {{"location", "string"}}, get_weather)}, + {"local_time", + ai::create_simple_tool("local_time", "Get the local time in a city", + {{"city", "string"}}, get_time)}}; + options.max_steps = 5; + + auto result = client->generate_text(options); + if (!result) { + std::cerr << "Error: " << result.error_message() << "\n"; + return 1; + } + std::cout << "Answer (" << result.steps.size() << " steps): " << result.text + << "\n\n"; + + // 3. Structured output: `responseMimeType` + `responseJsonSchema`. + ai::GenerateOptions structured(ai::google::models::kDefaultModel, + "Name the three largest cities of Japan."); + structured.response_format = { + {"type", "json_schema"}, + {"json_schema", + {{"name", "cities"}, + {"schema", + {{"type", "object"}, + {"properties", + {{"cities", {{"type", "array"}, {"items", {{"type", "string"}}}}}}}, + {"required", {"cities"}}}}}}}; + auto cities = client->generate_text(structured); + if (!cities) { + std::cerr << "Error: " << cities.error_message() << "\n"; + return 1; + } + std::cout << "JSON: " << cities.text << "\n\n"; + + // 4. Streaming. + ai::GenerateOptions stream_options(ai::google::models::kDefaultModel, + "Write a haiku about the sea."); + auto stream = client->stream_text(ai::StreamOptions(stream_options)); + std::cout << "Streaming: "; + for (const auto& event : stream) { + if (event.is_text_delta()) { + std::cout << event.text_delta << std::flush; + } else if (event.is_error()) { + std::cerr << "\nStream error: " << event.error.value_or("") << "\n"; + return 1; + } + } + std::cout << "\n"; + return 0; +} diff --git a/include/ai/ai.h b/include/ai/ai.h index f64a259..d4d7de3 100644 --- a/include/ai/ai.h +++ b/include/ai/ai.h @@ -12,6 +12,10 @@ #include "anthropic.h" #endif +#ifdef AI_SDK_HAS_GOOGLE +#include "google.h" +#endif + // Type definitions #include "types/client.h" #include "types/enums.h" @@ -80,4 +84,12 @@ /// std::cout << result->text << std::endl; /// } /// ``` +/// +/// Google Gemini Integration: +/// ```cpp +/// auto client = ai::google::create_client(); // GEMINI_API_KEY +/// ai::GenerateOptions options(ai::google::models::kDefaultModel, +/// "Explain quantum computing in simple terms."); +/// auto result = client.generate_text(options); +/// ``` namespace ai {} diff --git a/include/ai/google.h b/include/ai/google.h new file mode 100644 index 0000000..d8360b5 --- /dev/null +++ b/include/ai/google.h @@ -0,0 +1,82 @@ +#pragma once + +#ifndef AI_SDK_HAS_GOOGLE +#error \ + "Google component not available. Link with ai::google or ai::sdk to use Google Gemini functionality." +#endif + +#include "retry/retry_policy.h" +#include "types/client.h" + +#include +#include + +namespace ai { +namespace google { + +namespace models { +/// Gemini 4 model identifiers +/// +/// Gemini 4 and Gemini 3.6+ models ignore `temperature` and `top_p` (and warn +/// about them), so the client does not send them for those models. +/// +/// Thinking tokens count against `max_tokens` (`maxOutputTokens`). Like the +/// OpenAI client with its lowest reasoning effort, the client asks the models +/// listed here (and Gemini 2.5) for the least thinking they accept: +/// `thinkingLevel` `low` on Gemini 4 and Gemini 3.8 Flash, `minimal` on Gemini +/// 3.6 Flash and the Flash-Lite models, and the smallest `thinkingBudget` on +/// Gemini 2.5. +constexpr const char* kGemini4Carbon = "gemini-4-carbon"; +constexpr const char* kGemini4Neon = "gemini-4-neon"; +constexpr const char* kGemini4Hydrogen = "gemini-4-hydrogen"; +constexpr const char* kGemini4Argon = "gemini-4-argon"; + +/// Gemini 3 model identifiers (stable) +constexpr const char* kGemini38Flash = "gemini-3.8-flash"; +constexpr const char* kGemini36Flash = "gemini-3.6-flash"; +constexpr const char* kGemini35FlashLite = "gemini-3.5-flash-lite"; +constexpr const char* kGemini31FlashLite = "gemini-3.1-flash-lite"; + +/// Default model used when none is specified (Google's recommended +/// general-purpose model) +constexpr const char* kDefaultModel = kGemini4Hydrogen; +} // namespace models + +/// Create a Google Gemini client with default configuration +/// Reads the API key from the GOOGLE_API_KEY or GEMINI_API_KEY environment +/// variable (GOOGLE_API_KEY takes precedence when both are set, like in the +/// official Google Gen AI SDKs) +/// @return Configured Gemini client +Client create_client(); + +/// Create a Google Gemini client with explicit API key +/// @param api_key Gemini API key +/// @return Configured Gemini client +Client create_client(const std::string& api_key); + +/// Create a Google Gemini client with custom configuration +/// @param api_key Gemini API key +/// @param base_url Custom base URL (defaults to +/// https://generativelanguage.googleapis.com); requests go to +/// `{base_url}/v1beta/models/{model}:generateContent` +/// @return Configured Gemini client +Client create_client(const std::string& api_key, const std::string& base_url); + +/// Create a Google Gemini client with custom configuration and retry settings +/// @param api_key Gemini API key +/// @param base_url Custom base URL +/// @param retry_config Custom retry configuration +/// @return Configured Gemini client +Client create_client(const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config); + +/// Try to create a Google Gemini client using environment variables +/// Reads the API key from GOOGLE_API_KEY or GEMINI_API_KEY +/// @return Optional client - has value if an environment variable is set, +/// empty otherwise +/// @note This is useful for chaining creation attempts with other providers +std::optional try_create_client(); + +} // namespace google +} // namespace ai diff --git a/src/providers/base_provider_client.cpp b/src/providers/base_provider_client.cpp index 24c16d1..e165967 100644 --- a/src/providers/base_provider_client.cpp +++ b/src/providers/base_provider_client.cpp @@ -66,8 +66,8 @@ GenerateResult BaseProviderClient::generate_text_single_step( auto headers = request_builder_->build_headers(config_); // Make the request - auto result = http_handler_->post(config_.completions_endpoint_path, - headers, json_body); + auto result = + http_handler_->post(completions_path(options), headers, json_body); if (!result.is_success()) { // Parse error response using provider-specific parser diff --git a/src/providers/base_provider_client.h b/src/providers/base_provider_client.h index 47f5e75..0f1cbc3 100644 --- a/src/providers/base_provider_client.h +++ b/src/providers/base_provider_client.h @@ -74,6 +74,14 @@ class BaseProviderClient : public Client { virtual GenerateResult generate_text_single_step( const GenerateOptions& options); + // Path of the completion request; providers that address the model in the + // URL (such as Gemini's `/v1beta/models/{model}:generateContent`) override + // it. + virtual std::string completions_path(const GenerateOptions& options) const { + (void)options; + return config_.completions_endpoint_path; + } + ProviderConfig config_; std::unique_ptr http_handler_; std::unique_ptr request_builder_; diff --git a/src/providers/google/google_client.cpp b/src/providers/google/google_client.cpp new file mode 100644 index 0000000..25c4a82 --- /dev/null +++ b/src/providers/google/google_client.cpp @@ -0,0 +1,118 @@ +#include "google_client.h" + +#include "ai/google.h" +#include "ai/logger.h" +#include "google_request_builder.h" +#include "google_response_parser.h" +#include "google_stream.h" + +#include +#include + +namespace ai { +namespace google { + +namespace { +constexpr const char* kApiVersionPath = "/v1beta"; +} // namespace + +GoogleClient::GoogleClient(const std::string& api_key, + const std::string& base_url) + : GoogleClient(api_key, base_url, std::optional{}) {} + +GoogleClient::GoogleClient(const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config) + : GoogleClient(api_key, + base_url, + std::optional(retry_config)) {} + +GoogleClient::GoogleClient(const std::string& api_key, + const std::string& base_url, + std::optional retry_config) + : BaseProviderClient( + providers::ProviderConfig{ + .api_key = api_key, + .base_url = base_url, + // The model is part of the path; see completions_path(). + .completions_endpoint_path = "", + .embeddings_endpoint_path = "", + .auth_header_name = "x-goog-api-key", + .auth_header_prefix = "", + .extra_headers = {}, + .retry_config = retry_config}, + std::make_unique(), + std::make_unique()) { + ai::logger::log_debug("Google client initialized with base_url: {}{}", + base_url, + config_.retry_config ? " and custom retry config" : ""); +} + +std::string GoogleClient::model_path(const std::string& model, + const std::string& method) { + return std::string(kApiVersionPath) + "/" + model_resource_name(model) + ":" + + method; +} + +std::string GoogleClient::completions_path( + const GenerateOptions& options) const { + return model_path(options.model, "generateContent"); +} + +StreamResult GoogleClient::stream_text(const StreamOptions& options) { + ai::logger::log_debug( + "Starting text streaming - model: {}, prompt length: {}", options.model, + options.prompt.length()); + + auto impl = std::make_unique(); + + // Report requests that cannot be built (unsupported `response_format`, a + // tool result without its call) as stream errors, like generate_text does. + nlohmann::json request_json; + try { + request_json = request_builder_->build_request_json(options); + } catch (const std::exception& e) { + ai::logger::log_error("Failed to build Gemini stream request: {}", + e.what()); + impl->fail(std::string("Exception: ") + e.what()); + return StreamResult(std::move(impl)); + } + + include_thought_summaries(request_json); + + auto headers = request_builder_->build_headers(config_); + headers.emplace("Accept", "text/event-stream"); + + impl->start_stream(config_.base_url + + model_path(options.model, "streamGenerateContent") + + "?alt=sse", + headers, request_json); + + ai::logger::log_info("Text streaming started - model: {}", options.model); + return StreamResult(std::move(impl)); +} + +EmbeddingResult GoogleClient::embeddings(const EmbeddingOptions& options) { + (void)options; + return EmbeddingResult( + std::string("Embeddings are not supported by the Google Gemini client")); +} + +std::string GoogleClient::provider_name() const { + return "google"; +} + +bool GoogleClient::supports_model(const std::string& model_name) const { + return !model_name.empty(); +} + +std::string GoogleClient::config_info() const { + return "Google Gemini API (base_url: " + config_.base_url + ")"; +} + +std::string GoogleClient::default_model() const { + return models::kDefaultModel; +} + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_client.h b/src/providers/google/google_client.h new file mode 100644 index 0000000..2110966 --- /dev/null +++ b/src/providers/google/google_client.h @@ -0,0 +1,54 @@ +#pragma once + +#include "ai/retry/retry_policy.h" +#include "ai/types/stream_options.h" +#include "providers/base_provider_client.h" + +#include +#include + +namespace ai { +namespace google { + +inline constexpr const char* kDefaultBaseUrl = + "https://generativelanguage.googleapis.com"; + +/// Native Gemini API client (`generateContent` and +/// `streamGenerateContent?alt=sse` under `/v1beta`), authenticated with the +/// `x-goog-api-key` header. +class GoogleClient : public providers::BaseProviderClient { + public: + explicit GoogleClient(const std::string& api_key, + const std::string& base_url = kDefaultBaseUrl); + + GoogleClient(const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config); + + StreamResult stream_text(const StreamOptions& options) override; + EmbeddingResult embeddings(const EmbeddingOptions& options) override; + 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; + std::string config_info() const override; + std::string default_model() const override; + + // Member access for testing + const std::string& get_api_key() const { return config_.api_key; } + const std::string& get_base_url() const { return config_.base_url; } + + /// `/v1beta/models/{model}:{method}` + static std::string model_path(const std::string& model, + const std::string& method); + + protected: + std::string completions_path(const GenerateOptions& options) const override; + + private: + GoogleClient(const std::string& api_key, + const std::string& base_url, + std::optional retry_config); +}; + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_factory.cpp b/src/providers/google/google_factory.cpp new file mode 100644 index 0000000..834f151 --- /dev/null +++ b/src/providers/google/google_factory.cpp @@ -0,0 +1,82 @@ +#include "ai/errors.h" +#include "ai/google.h" +#include "google_client.h" +#include "utils/env_utils.h" + +#include +#include + +namespace ai { +namespace google { + +namespace { + +/// GOOGLE_API_KEY takes precedence over GEMINI_API_KEY, as in the Google Gen +/// AI SDKs. +std::optional api_key_from_env() { + if (auto key = utils::non_empty_env("GOOGLE_API_KEY")) { + return key; + } + return utils::non_empty_env("GEMINI_API_KEY"); +} + +std::string get_api_key_or_default(const std::string& api_key) { + if (!api_key.empty()) { + return api_key; + } + auto env_api_key = api_key_from_env(); + if (!env_api_key) { + throw ConfigurationError( + "API key not provided and neither GOOGLE_API_KEY nor GEMINI_API_KEY " + "environment variable is set"); + } + return *std::move(env_api_key); +} + +std::string get_base_url_or_default(const std::string& base_url) { + if (base_url.empty()) { + return kDefaultBaseUrl; + } + // Paths are appended to the base URL. + std::string url = base_url; + while (!url.empty() && url.back() == '/') { + url.pop_back(); + } + return url; +} + +} // namespace + +Client create_client() { + return Client(std::make_unique(get_api_key_or_default(""), + kDefaultBaseUrl)); +} + +Client create_client(const std::string& api_key) { + return Client(std::make_unique(get_api_key_or_default(api_key), + kDefaultBaseUrl)); +} + +Client create_client(const std::string& api_key, const std::string& base_url) { + return Client(std::make_unique( + get_api_key_or_default(api_key), get_base_url_or_default(base_url))); +} + +Client create_client(const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config) { + return Client(std::make_unique( + get_api_key_or_default(api_key), get_base_url_or_default(base_url), + retry_config)); +} + +std::optional try_create_client() { + auto api_key = api_key_from_env(); + if (!api_key) { + return std::nullopt; + } + return Client(std::make_unique(*api_key, kDefaultBaseUrl)); +} + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_request_builder.cpp b/src/providers/google/google_request_builder.cpp new file mode 100644 index 0000000..e67e650 --- /dev/null +++ b/src/providers/google/google_request_builder.cpp @@ -0,0 +1,498 @@ +#include "google_request_builder.h" + +#include "ai/logger.h" + +#include +#include +#include +#include +#include +#include + +namespace ai { +namespace google { + +namespace { + +constexpr std::string_view kModelsPrefix = "models/"; + +bool is_synthetic_call_id(const std::string& id) { + return id.starts_with(kSyntheticCallIdPrefix); +} + +/// Parse the leading "[.]" of a "gemini-…" model name. +std::optional> gemini_version(std::string_view model) { + if (model.starts_with(kModelsPrefix)) { + model.remove_prefix(kModelsPrefix.size()); + } + constexpr std::string_view kGeminiPrefix = "gemini-"; + if (!model.starts_with(kGeminiPrefix)) { + return std::nullopt; + } + model.remove_prefix(kGeminiPrefix.size()); + + const auto read_number = [&model]() -> std::optional { + int value = 0; + std::size_t digits = 0; + while (digits < model.size() && + std::isdigit(static_cast(model[digits]))) { + value = value * 10 + (model[digits] - '0'); + ++digits; + } + if (digits == 0) { + return std::nullopt; + } + model.remove_prefix(digits); + return value; + }; + + const auto major = read_number(); + if (!major) { + return std::nullopt; + } + int minor = 0; + if (model.starts_with('.')) { + model.remove_prefix(1); + minor = read_number().value_or(0); + } + return std::make_pair(*major, minor); +} + +/// Gemini 4 and Gemini 3.6+ ignore custom `temperature`, `topP` and `topK` +/// values, answer them with deprecation warnings, and are announced to reject +/// them with HTTP 400 in a future release. +bool ignores_sampling_parameters(const std::string& model) { + const auto version = gemini_version(model); + if (!version) { + return false; + } + const auto [major, minor] = *version; + return major >= 4 || (major == 3 && minor >= 6); +} + +/// The `thinkingConfig` with the least thinking the model accepts, or +/// std::nullopt for models with no known thinking settings. Like the lowest +/// reasoning effort of the OpenAI builders, it keeps the provider-neutral +/// options within their latency and token budget: thinking tokens count +/// against `maxOutputTokens`, and the default levels (`high` on Gemini 4 Neon +/// and Hydrogen) can use up a small limit before any text is produced. +std::optional lowest_thinking_config(std::string_view model) { + if (model.starts_with(kModelsPrefix)) { + model.remove_prefix(kModelsPrefix.size()); + } + // Gemini 4 requires `thinkingLevel` (`thinkingBudget` is deprecated), and + // every Gemini 4 model supports `low`; `minimal` is not supported. + if (const auto version = gemini_version(model); + version && version->first >= 4) { + return nlohmann::json{{"thinkingLevel", "low"}}; + } + // Gemini 3 levels per model, from the thinking guide. + for (const auto* low_model : + {"gemini-3.8-flash", "gemini-3.1-pro-preview", "gemini-3-pro-preview"}) { + if (model == low_model) { + return nlohmann::json{{"thinkingLevel", "low"}}; + } + } + for (const auto* minimal_model : + {"gemini-3.6-flash", "gemini-3.5-flash-lite", "gemini-3.1-flash-lite", + "gemini-3-flash-preview"}) { + if (model == minimal_model) { + return nlohmann::json{{"thinkingLevel", "minimal"}}; + } + } + // Gemini 2.5 takes a token budget: 0 disables thinking on Flash and + // Flash-Lite, Pro cannot disable it and accepts at least 128. + if (model == "gemini-2.5-flash" || model == "gemini-2.5-flash-lite") { + return nlohmann::json{{"thinkingBudget", 0}}; + } + if (model == "gemini-2.5-pro") { + return nlohmann::json{{"thinkingBudget", 128}}; + } + return std::nullopt; +} + +nlohmann::json text_part(const std::string& text) { + return {{"text", text}}; +} + +/// `functionResponse.response` must be an object; the API documents an +/// `error` key for failed calls and `output` for the function output. +nlohmann::json function_response_object(const ToolResultContentPart& result) { + if (result.is_error) { + if (result.result.is_object() && result.result.contains("error")) { + return result.result; + } + return {{"error", result.result}}; + } + if (result.result.is_object()) { + return result.result; + } + return {{"output", result.result}}; +} + +class ContentsBuilder { + public: + void add_message(const Message& message) { + switch (message.role) { + case kMessageRoleSystem: + // Gemini has no system role in `contents`; system messages join the + // `systemInstruction`. + for (const auto& part : message.content) { + if (const auto* text = std::get_if(&part); + text != nullptr && !text->text.empty()) { + system_parts_.push_back(text_part(text->text)); + } + } + return; + case kMessageRoleAssistant: + add_model_content(message); + return; + case kMessageRoleUser: + default: + add_user_content(message); + return; + } + } + + void add_system_text(const std::string& text) { + if (!text.empty()) { + system_parts_.push_back(text_part(text)); + } + } + + void add_user_text(const std::string& text) { + append_content("user", nlohmann::json::array({text_part(text)})); + } + + nlohmann::json& contents() { return contents_; } + nlohmann::json& system_parts() { return system_parts_; } + + private: + /// Gemini expects alternating `user` and `model` turns: parts of + /// consecutive messages with the same role (two user messages in a row, or + /// tool results followed by a user message) join one content entry. + void append_content(const char* role, nlohmann::json parts) { + if (!contents_.empty() && contents_.back()["role"] == role) { + auto& previous = contents_.back()["parts"]; + for (auto& part : parts) { + previous.push_back(std::move(part)); + } + return; + } + contents_.push_back({{"role", role}, {"parts", std::move(parts)}}); + } + + void add_user_content(const Message& message) { + nlohmann::json parts = nlohmann::json::array(); + for (const auto& part : message.content) { + if (const auto* text = std::get_if(&part)) { + if (!text->text.empty()) { + parts.push_back(text_part(text->text)); + } + } else if (const auto* result = + std::get_if(&part)) { + parts.push_back(function_response_part(*result)); + } + } + if (!parts.empty()) { + append_content("user", std::move(parts)); + } + } + + nlohmann::json function_response_part(const ToolResultContentPart& result) { + // `functionResponse.name` is required, and tool results carry only the + // call ID: take the name from the call they answer. + const auto name_it = call_names_.find(result.tool_call_id); + if (name_it == call_names_.end()) { + throw std::invalid_argument( + "Gemini needs the function name of every tool result, but the " + "result for tool call '" + + result.tool_call_id + + "' does not follow an assistant message with that tool call"); + } + nlohmann::json response{{"name", name_it->second}, + {"response", function_response_object(result)}}; + if (!result.tool_call_id.empty() && + !is_synthetic_call_id(result.tool_call_id)) { + response["id"] = result.tool_call_id; + } + return {{"functionResponse", std::move(response)}}; + } + + void add_model_content(const Message& message) { + nlohmann::json parts = nlohmann::json::array(); + std::optional pending_signature; + bool has_signature = false; + std::optional first_function_call; + + const auto push_part = [&](nlohmann::json part) { + if (pending_signature) { + part["thoughtSignature"] = std::move(*pending_signature); + pending_signature.reset(); + has_signature = true; + } + parts.push_back(std::move(part)); + }; + + for (const auto& part : message.content) { + if (const auto* text = std::get_if(&part)) { + if (!text->text.empty()) { + push_part(text_part(text->text)); + } + } else if (const auto* call = std::get_if(&part)) { + nlohmann::json function_call{ + {"name", call->tool_name}, + {"args", call->arguments.is_null() ? nlohmann::json::object() + : call->arguments}}; + if (!call->id.empty() && !is_synthetic_call_id(call->id)) { + function_call["id"] = call->id; + } + call_names_[call->id] = call->tool_name; + if (!first_function_call) { + first_function_call = parts.size(); + } + push_part({{"functionCall", std::move(function_call)}}); + } else if (const auto* provider = std::get_if(&part); + provider != nullptr && + provider->provider == kGoogleProviderName && + provider->data.is_object()) { + const auto type = provider->data.value("type", ""); + if (type == kThoughtSignaturePartType && + provider->data.contains("thoughtSignature") && + provider->data["thoughtSignature"].is_string()) { + pending_signature = + provider->data["thoughtSignature"].get(); + } else if (type == kRawPartType && provider->data.contains("part") && + provider->data["part"].is_object()) { + const auto& raw = provider->data["part"]; + has_signature = has_signature || raw.contains("thoughtSignature"); + parts.push_back(raw); + } + } + // Parts of other providers and tool results are not part of a model + // turn. + } + + if (parts.empty()) { + return; + } + + // Gemini 3 and later reject a turn whose function calls come without the + // thought signature the model attached to them. Calls the model did not + // produce in this form (streamed, hand-built, or from another provider) + // carry the signature the API documents for that case. + if (!has_signature && first_function_call) { + parts[*first_function_call]["thoughtSignature"] = + kSkipThoughtSignatureValidator; + } + + append_content("model", std::move(parts)); + } + + nlohmann::json contents_ = nlohmann::json::array(); + nlohmann::json system_parts_ = nlohmann::json::array(); + std::map call_names_; +}; + +/// Map the OpenAI-style `response_format` of `GenerateOptions` (Chat +/// Completions `json_schema` / `json_object` / `text`, or the flat Responses +/// `json_schema` shape) to Gemini's structured-output settings. +void apply_response_format(const nlohmann::json& response_format, + nlohmann::json& generation_config) { + const auto type = response_format.is_object() + ? response_format.value("type", std::string{}) + : std::string{}; + if (type == "text") { + return; + } + if (type == "json_object") { + generation_config["responseMimeType"] = "application/json"; + return; + } + if (type == "json_schema") { + const nlohmann::json* schema = nullptr; + if (const auto it = response_format.find("json_schema"); + it != response_format.end() && it->is_object() && + it->contains("schema")) { + schema = &(*it)["schema"]; + } else if (const auto flat = response_format.find("schema"); + flat != response_format.end()) { + schema = &*flat; + } + if (schema == nullptr || !schema->is_object()) { + throw std::invalid_argument( + "response_format of type json_schema has no schema object"); + } + generation_config["responseMimeType"] = "application/json"; + generation_config["responseJsonSchema"] = *schema; + return; + } + throw std::invalid_argument( + "Unsupported response_format for Gemini: " + response_format.dump() + + " (expected type text, json_object, or json_schema)"); +} + +} // namespace + +std::string model_resource_name(const std::string& model) { + if (std::string_view(model).starts_with(kModelsPrefix)) { + return model; + } + return std::string(kModelsPrefix) + model; +} + +void include_thought_summaries(nlohmann::json& request) { + const auto config = request.find("generationConfig"); + if (config == request.end() || !config->is_object()) { + return; + } + const auto thinking = config->find("thinkingConfig"); + if (thinking == config->end() || !thinking->is_object()) { + return; + } + if (const auto budget = thinking->find("thinkingBudget"); + budget != thinking->end() && budget->is_number() && + budget->get() == 0) { + return; + } + (*thinking)["includeThoughts"] = true; +} + +nlohmann::json GoogleRequestBuilder::build_request_json( + const GenerateOptions& options) { + ContentsBuilder builder; + builder.add_system_text(options.system); + + if (options.messages.empty()) { + if (!options.prompt.empty()) { + builder.add_user_text(options.prompt); + } + } else { + for (const auto& message : options.messages) { + builder.add_message(message); + } + } + + nlohmann::json request{{"contents", std::move(builder.contents())}}; + if (!builder.system_parts().empty()) { + request["systemInstruction"] = { + {"parts", std::move(builder.system_parts())}}; + } + + nlohmann::json generation_config = nlohmann::json::object(); + if (options.max_tokens) { + generation_config["maxOutputTokens"] = *options.max_tokens; + } + + const bool sampling_ignored = ignores_sampling_parameters(options.model); + const auto add_sampling_parameter = [&](const char* option, const char* key, + const std::optional& value) { + if (!value) { + return; + } + if (sampling_ignored) { + ai::logger::log_warn( + "Ignoring {} for {} because the model does not support sampling " + "parameters", + option, options.model); + } else { + generation_config[key] = *value; + } + }; + add_sampling_parameter("temperature", "temperature", options.temperature); + add_sampling_parameter("top_p", "topP", options.top_p); + + if (options.seed) { + generation_config["seed"] = *options.seed; + } + if (options.presence_penalty) { + generation_config["presencePenalty"] = *options.presence_penalty; + } + if (options.frequency_penalty) { + generation_config["frequencyPenalty"] = *options.frequency_penalty; + } + if (options.response_format) { + apply_response_format(*options.response_format, generation_config); + } + if (auto thinking_config = lowest_thinking_config(options.model)) { + generation_config["thinkingConfig"] = std::move(*thinking_config); + } + if (!generation_config.empty()) { + request["generationConfig"] = std::move(generation_config); + } + + if (options.has_tools()) { + nlohmann::json declarations = nlohmann::json::array(); + for (const auto& tool_name : options.get_active_tool_names()) { + const auto it = options.tools.find(tool_name); + if (it == options.tools.end()) { + continue; + } + nlohmann::json declaration{{"name", tool_name}, + {"description", it->second.description}}; + // `parametersJsonSchema` takes JSON Schema as is; the alternative + // `parameters` field only accepts an OpenAPI 3.0 subset. + if (!it->second.parameters_schema.is_null()) { + declaration["parametersJsonSchema"] = it->second.parameters_schema; + } + declarations.push_back(std::move(declaration)); + } + + if (!declarations.empty()) { + request["tools"] = nlohmann::json::array( + {{{"functionDeclarations", std::move(declarations)}}}); + + nlohmann::json function_calling_config; + switch (options.tool_choice.type) { + case ToolChoiceType::kAuto: + function_calling_config = {{"mode", "AUTO"}}; + break; + case ToolChoiceType::kRequired: + function_calling_config = {{"mode", "ANY"}}; + break; + case ToolChoiceType::kNone: + function_calling_config = {{"mode", "NONE"}}; + break; + case ToolChoiceType::kSpecific: + if (options.tool_choice.tool_name) { + function_calling_config = { + {"mode", "ANY"}, + {"allowedFunctionNames", + nlohmann::json::array({*options.tool_choice.tool_name})}}; + } + break; + } + if (!function_calling_config.is_null()) { + request["toolConfig"] = { + {"functionCallingConfig", std::move(function_calling_config)}}; + } + + ai::logger::log_debug("Added {} function declarations with choice: {}", + request["tools"][0]["functionDeclarations"].size(), + options.tool_choice.to_string()); + } + } + + return request; +} + +nlohmann::json GoogleRequestBuilder::build_request_json( + const EmbeddingOptions& options) { + // Gemini embeddings use a separate `embedContent` API that the client does + // not implement (see `GoogleClient::embeddings`). + return {{"model", model_resource_name(options.model)}, + {"input", options.input}}; +} + +httplib::Headers GoogleRequestBuilder::build_headers( + const providers::ProviderConfig& config) { + httplib::Headers headers = { + {config.auth_header_name, config.auth_header_prefix + config.api_key}}; + for (const auto& [key, value] : config.extra_headers) { + headers.emplace(key, value); + } + return headers; +} + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_request_builder.h b/src/providers/google/google_request_builder.h new file mode 100644 index 0000000..c9e8c9a --- /dev/null +++ b/src/providers/google/google_request_builder.h @@ -0,0 +1,58 @@ +#pragma once + +#include "ai/types/embedding_options.h" +#include "ai/types/generate_options.h" +#include "providers/base_provider_client.h" + +#include + +#include + +namespace ai { +namespace google { + +/// `ProviderContentPart::provider` of the Gemini-specific parts of an +/// assistant turn: thought signatures and parts with no provider-neutral +/// representation (thoughts, signature-only parts). +inline constexpr const char* kGoogleProviderName = "google"; + +/// `ProviderContentPart::data["type"]` of a thought signature that belongs to +/// the text or tool-call part right after it; `data["thoughtSignature"]` holds +/// the signature. +inline constexpr const char* kThoughtSignaturePartType = "thought_signature"; + +/// `ProviderContentPart::data["type"]` of a Gemini part replayed verbatim from +/// `data["part"]`. +inline constexpr const char* kRawPartType = "part"; + +/// Prefix of the tool-call IDs the client makes up for `functionCall` parts +/// that come without an `id` (Gemini 2.5). They are only used to pair calls +/// with their results and are not sent to the API. +inline constexpr const char* kSyntheticCallIdPrefix = "gemini-call-"; + +/// Thought signature that the Gemini API documents for function calls it did +/// not produce itself (for example a conversation built from streamed tool +/// calls or from another provider): it skips the signature validation that +/// Gemini 3 and later models apply to the function calls of the current turn. +inline constexpr const char* kSkipThoughtSignatureValidator = + "skip_thought_signature_validator"; + +/// Model name for the URL path: accepts both "gemini-…" and "models/gemini-…". +std::string model_resource_name(const std::string& model); + +/// Ask for thought summaries (`includeThoughts`) in a request that thinks +/// (has a `thinkingConfig` other than `thinkingBudget: 0`); streams emit them +/// as reasoning events. +void include_thought_summaries(nlohmann::json& request); + +class GoogleRequestBuilder : public providers::RequestBuilder { + public: + /// The `GenerateContentRequest` body; the model is part of the URL. + nlohmann::json build_request_json(const GenerateOptions& options) override; + nlohmann::json build_request_json(const EmbeddingOptions& options) override; + httplib::Headers build_headers( + const providers::ProviderConfig& config) override; +}; + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_response_parser.cpp b/src/providers/google/google_response_parser.cpp new file mode 100644 index 0000000..40fd43e --- /dev/null +++ b/src/providers/google/google_response_parser.cpp @@ -0,0 +1,242 @@ +#include "google_response_parser.h" + +#include "ai/logger.h" +#include "google_request_builder.h" +#include "utils/response_utils.h" + +#include + +namespace ai { +namespace google { + +namespace { + +constexpr const char* kEmbeddingsNotSupported = + "Embeddings are not supported by the Google Gemini client"; + +std::string string_field(const nlohmann::json& object, const char* key) { + if (!object.is_object()) { + return ""; + } + const auto it = object.find(key); + if (it == object.end() || !it->is_string()) { + return ""; + } + return it->get(); +} + +int int_field(const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + return it != object.end() && it->is_number_integer() ? it->get() : 0; +} + +} // namespace + +std::optional parse_finish_reason(const std::string& reason, + bool has_function_calls) { + if (reason == "STOP") { + return has_function_calls ? kFinishReasonToolCalls : kFinishReasonStop; + } + if (reason == "MAX_TOKENS" || reason == "CONTINUATION") { + // `CONTINUATION` (long decode on Gemini 4) stops at the per-request + // output limit; the client does not resume with `continuationToken`. + return has_function_calls ? kFinishReasonToolCalls : kFinishReasonLength; + } + if (reason == "SAFETY" || reason == "RECITATION" || reason == "LANGUAGE" || + reason == "BLOCKLIST" || reason == "PROHIBITED_CONTENT" || + reason == "SPII" || reason == "IMAGE_SAFETY" || + reason == "IMAGE_PROHIBITED_CONTENT" || reason == "IMAGE_RECITATION" || + reason == "ESCALATION") { + return kFinishReasonContentFilter; + } + // MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS, + // MISSING_THOUGHT_SIGNATURE, MALFORMED_RESPONSE, OTHER, ... and reasons + // added after this client was written. + return std::nullopt; +} + +Usage parse_usage(const nlohmann::json& usage_metadata) { + Usage usage; + if (!usage_metadata.is_object()) { + return usage; + } + usage.prompt_tokens = int_field(usage_metadata, "promptTokenCount"); + // Thinking tokens are billed as output tokens. + usage.completion_tokens = int_field(usage_metadata, "candidatesTokenCount") + + int_field(usage_metadata, "thoughtsTokenCount"); + usage.total_tokens = int_field(usage_metadata, "totalTokenCount"); + if (usage.total_tokens == 0) { + usage.total_tokens = usage.prompt_tokens + usage.completion_tokens; + } + return usage; +} + +std::optional prompt_block_error(const nlohmann::json& response) { + const auto it = response.find("promptFeedback"); + if (it == response.end() || !it->is_object()) { + return std::nullopt; + } + const auto reason = string_field(*it, "blockReason"); + if (reason.empty() || reason == "BLOCK_REASON_UNSPECIFIED") { + return std::nullopt; + } + return "Gemini blocked the prompt (" + reason + ")"; +} + +std::string synthetic_call_id(std::size_t index) { + return kSyntheticCallIdPrefix + std::to_string(index); +} + +GenerateResult GoogleResponseParser::parse_success_completion_response( + const nlohmann::json& response) { + ai::logger::log_debug("Parsing Gemini generateContent response"); + + GenerateResult result; + if (auto id = string_field(response, "responseId"); !id.empty()) { + result.id = std::move(id); + } + if (auto model = string_field(response, "modelVersion"); !model.empty()) { + result.model = std::move(model); + } + if (const auto it = response.find("usageMetadata"); it != response.end()) { + result.usage = parse_usage(*it); + } + result.provider_metadata = response.dump(); + + if (auto blocked = prompt_block_error(response)) { + ai::logger::log_error("{}", *blocked); + result.error = std::move(blocked); + result.finish_reason = kFinishReasonContentFilter; + return result; + } + + const auto candidates = response.find("candidates"); + if (candidates == response.end() || !candidates->is_array() || + candidates->empty() || !(*candidates)[0].is_object()) { + result.error = "Gemini response has no candidates"; + result.finish_reason = kFinishReasonError; + return result; + } + const auto& candidate = (*candidates)[0]; + + // The model turn with its parts in their original order. Thought + // signatures, thoughts, and parts without a provider-neutral form are kept + // as `ProviderContentPart`s so the turn can be replayed exactly as the API + // requires. + MessageContent turn; + std::size_t call_index = 0; + + const auto content = candidate.find("content"); + if (content != candidate.end() && content->is_object()) { + const auto parts = content->find("parts"); + if (parts != content->end() && parts->is_array()) { + for (const auto& part : *parts) { + if (!part.is_object()) { + continue; + } + const auto raw_part = [&part]() { + return ProviderContentPart{kGoogleProviderName, + {{"type", kRawPartType}, {"part", part}}}; + }; + + if (const auto thought = part.find("thought"); thought != part.end() && + thought->is_boolean() && + thought->get()) { + // Thought summaries (`includeThoughts`) are not answer text. + turn.emplace_back(raw_part()); + continue; + } + + const auto signature = string_field(part, "thoughtSignature"); + const auto add_signature = [&]() { + if (!signature.empty()) { + turn.emplace_back( + ProviderContentPart{kGoogleProviderName, + {{"type", kThoughtSignaturePartType}, + {"thoughtSignature", signature}}}); + } + }; + + if (const auto call = part.find("functionCall"); + call != part.end() && call->is_object()) { + auto id = string_field(*call, "id"); + if (id.empty()) { + id = synthetic_call_id(call_index); + } + ++call_index; + const auto name = string_field(*call, "name"); + JsonValue arguments = JsonValue::object(); + if (const auto args = call->find("args"); + args != call->end() && args->is_object()) { + arguments = *args; + } + add_signature(); + turn.emplace_back(ToolCallContentPart{id, name, arguments}); + result.tool_calls.emplace_back(id, name, std::move(arguments)); + ai::logger::log_debug("Parsed Gemini function call: {}", name); + } else if (auto text = string_field(part, "text"); !text.empty()) { + add_signature(); + result.text += text; + turn.emplace_back(TextContentPart{std::move(text)}); + } else { + // An empty text part that only carries the signature, or a part + // kind this client does not interpret. + turn.emplace_back(raw_part()); + } + } + } + } + + const auto reason = string_field(candidate, "finishReason"); + const auto finish_reason = + parse_finish_reason(reason, !result.tool_calls.empty()); + if (!finish_reason) { + std::string error = + "Gemini response finished with " + + (reason.empty() ? std::string("no finishReason") : reason); + if (const auto message = string_field(candidate, "finishMessage"); + !message.empty()) { + error += ": " + message; + } + ai::logger::log_error("{}", error); + result.error = std::move(error); + result.finish_reason = kFinishReasonError; + return result; + } + result.finish_reason = *finish_reason; + + // A turn of thoughts alone is not kept: there is nothing to answer. + Message message(kMessageRoleAssistant, std::move(turn)); + if (message.has_text() || message.has_tool_calls()) { + result.response_messages.push_back(std::move(message)); + } + + ai::logger::log_debug( + "Parsed Gemini response - text length: {}, function calls: {}, " + "finish reason: {}", + result.text.length(), result.tool_calls.size(), reason); + return result; +} + +GenerateResult GoogleResponseParser::parse_error_completion_response( + int status_code, + const std::string& body) { + return utils::parse_standard_error_response("Google", status_code, body); +} + +EmbeddingResult GoogleResponseParser::parse_success_embedding_response( + const nlohmann::json& response) { + (void)response; + return EmbeddingResult(std::string(kEmbeddingsNotSupported)); +} + +EmbeddingResult GoogleResponseParser::parse_error_embedding_response( + int status_code, + const std::string& body) { + auto generate_result = + utils::parse_standard_error_response("Google", status_code, body); + return EmbeddingResult(generate_result.error); +} + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_response_parser.h b/src/providers/google/google_response_parser.h new file mode 100644 index 0000000..a28a4e5 --- /dev/null +++ b/src/providers/google/google_response_parser.h @@ -0,0 +1,49 @@ +#pragma once + +#include "ai/types/generate_options.h" +#include "providers/base_provider_client.h" + +#include +#include +#include + +#include + +namespace ai { +namespace google { + +/// Translate a candidate's `finishReason`; std::nullopt for the reasons that +/// mean the request failed (`MALFORMED_FUNCTION_CALL`, `OTHER`, ...). +/// A turn with function calls finishes with kFinishReasonToolCalls when it +/// stopped normally or at the output limit: the calls are complete either way +/// and have to be answered. +std::optional parse_finish_reason(const std::string& reason, + bool has_function_calls); + +/// Map `usageMetadata`; thinking tokens count as completion tokens. +Usage parse_usage(const nlohmann::json& usage_metadata); + +/// The error for a prompt the API refused to answer +/// (`promptFeedback.blockReason`), if any. +std::optional prompt_block_error(const nlohmann::json& response); + +/// The ID given to the `index`-th `functionCall` part of a response that has +/// no `id` (see `kSyntheticCallIdPrefix`). +std::string synthetic_call_id(std::size_t index); + +class GoogleResponseParser : public providers::ResponseParser { + public: + GenerateResult parse_success_completion_response( + const nlohmann::json& response) override; + GenerateResult parse_error_completion_response( + int status_code, + const std::string& body) override; + EmbeddingResult parse_success_embedding_response( + const nlohmann::json& response) override; + EmbeddingResult parse_error_embedding_response( + int status_code, + const std::string& body) override; +}; + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_stream.cpp b/src/providers/google/google_stream.cpp new file mode 100644 index 0000000..88d4e9e --- /dev/null +++ b/src/providers/google/google_stream.cpp @@ -0,0 +1,177 @@ +#include "google_stream.h" + +#include "ai/logger.h" +#include "google_response_parser.h" + +#include + +namespace ai { +namespace google { + +namespace { + +std::string string_field(const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + return it != object.end() && it->is_string() ? it->get() + : std::string{}; +} + +} // namespace + +GoogleStreamImpl::~GoogleStreamImpl() { + // Join before this class's state is destroyed; the stream thread calls + // process_sse_line. + stop_stream(); +} + +void GoogleStreamImpl::fail(const std::string& message) { + note_stream_error(); + push_event(create_error_event(message)); + mark_complete(); +} + +void GoogleStreamImpl::reset_stream_state() { + event_data_.clear(); + call_index_ = 0; + saw_function_call_ = false; +} + +void GoogleStreamImpl::process_sse_line(std::string_view line) { + if (line.empty()) { + // Blank line terminates the SSE event. + if (!event_data_.empty()) { + process_sse_event(event_data_); + event_data_.clear(); + } + } else if (line.starts_with("data:")) { + auto data = line.substr(5); + if (!data.empty() && data.front() == ' ') { + data.remove_prefix(1); + } + if (!event_data_.empty()) { + event_data_ += '\n'; + } + event_data_.append(data); + } +} + +void GoogleStreamImpl::finalize_stream() { + // Dispatch an event whose terminating blank line never arrived. + if (!event_data_.empty()) { + process_sse_event(event_data_); + event_data_.clear(); + } +} + +void GoogleStreamImpl::process_sse_event(const std::string& data) { + nlohmann::json chunk; + try { + chunk = nlohmann::json::parse(data); + } catch (const nlohmann::json::exception& e) { + ai::logger::log_error("Failed to parse Gemini SSE event: {}", e.what()); + note_stream_error(); + push_event(create_error_event("Failed to parse Gemini stream chunk: " + + std::string(e.what()))); + return; + } + if (!chunk.is_object()) { + return; + } + + if (const auto error = chunk.find("error"); + error != chunk.end() && error->is_object()) { + std::string message = "Google API error: " + + error->value("message", std::string("unknown error")); + if (const auto status = string_field(*error, "status"); !status.empty()) { + message += " [" + status + "]"; + } + note_stream_error(); + push_event(create_error_event(message)); + mark_complete(); + return; + } + + if (const auto usage = chunk.find("usageMetadata"); usage != chunk.end()) { + // Every chunk carries the running totals; the last one wins. + usage_ = parse_usage(*usage); + } + + if (auto blocked = prompt_block_error(chunk)) { + note_stream_error(); + push_event(create_error_event(*blocked)); + mark_complete(); + return; + } + + const auto candidates = chunk.find("candidates"); + if (candidates == chunk.end() || !candidates->is_array() || + candidates->empty() || !(*candidates)[0].is_object()) { + return; + } + const auto& candidate = (*candidates)[0]; + + if (const auto content = candidate.find("content"); + content != candidate.end() && content->is_object()) { + if (const auto parts = content->find("parts"); + parts != content->end() && parts->is_array()) { + for (const auto& part : *parts) { + if (!part.is_object()) { + continue; + } + if (const auto thought = part.find("thought"); thought != part.end() && + thought->is_boolean() && + thought->get()) { + // Thought summaries (`includeThoughts`) are reasoning, not answer + // text. + if (auto text = string_field(part, "text"); !text.empty()) { + push_event(StreamEvent::reasoning(std::move(text))); + } + continue; + } + if (const auto call = part.find("functionCall"); + call != part.end() && call->is_object()) { + // Gemini streams each function call whole, never in fragments. + auto id = string_field(*call, "id"); + if (id.empty()) { + id = synthetic_call_id(call_index_); + } + ++call_index_; + JsonValue arguments = JsonValue::object(); + if (const auto args = call->find("args"); + args != call->end() && args->is_object()) { + arguments = *args; + } + saw_function_call_ = true; + push_event( + StreamEvent(ToolCall(std::move(id), string_field(*call, "name"), + std::move(arguments)))); + } else if (auto text = string_field(part, "text"); !text.empty()) { + push_event(StreamEvent(std::move(text))); + } + } + } + } + + const auto reason = string_field(candidate, "finishReason"); + if (reason.empty()) { + return; + } + if (const auto finish_reason = + parse_finish_reason(reason, saw_function_call_)) { + finish_reason_ = *finish_reason; + } else { + std::string message = "Gemini response finished with " + reason; + if (const auto finish_message = string_field(candidate, "finishMessage"); + !finish_message.empty()) { + message += ": " + finish_message; + } + note_stream_error(); + push_event(create_error_event(message)); + } + // The chunk with the finish reason is the last one; complete right away so + // consumers are not left waiting for the connection to close. + mark_complete(); +} + +} // namespace google +} // namespace ai diff --git a/src/providers/google/google_stream.h b/src/providers/google/google_stream.h new file mode 100644 index 0000000..826226d --- /dev/null +++ b/src/providers/google/google_stream.h @@ -0,0 +1,39 @@ +#pragma once + +#include "providers/http_sse_stream.h" + +#include +#include +#include + +namespace ai { +namespace google { + +/// `streamGenerateContent?alt=sse`: every SSE event carries a complete +/// `GenerateContentResponse` chunk; the last one has the `finishReason`. +class GoogleStreamImpl : public providers::streaming::HttpSseStream { + public: + GoogleStreamImpl() + : HttpSseStream({.default_path = "/", + .connection_timeout_seconds = 30, + .read_timeout_seconds = 120}) {} + ~GoogleStreamImpl() override; + + /// Finish a stream that was never started with an error event (and an + /// error finish event), e.g. when the request could not be built. + void fail(const std::string& message); + + private: + void reset_stream_state() override; + void process_sse_line(std::string_view line) override; + void finalize_stream() override; + + void process_sse_event(const std::string& data); + + std::string event_data_; + std::size_t call_index_ = 0; + bool saw_function_call_ = false; +}; + +} // namespace google +} // namespace ai diff --git a/src/utils/response_utils.h b/src/utils/response_utils.h index 894995b..c62b792 100644 --- a/src/utils/response_utils.h +++ b/src/utils/response_utils.h @@ -28,7 +28,9 @@ inline GenerateResult parse_standard_error_response( if (json.contains("error")) { auto& error = json["error"]; std::string message = error.value("message", "Unknown error"); - std::string type = error.value("type", ""); + // OpenAI and Anthropic name the error kind `type`; Google uses + // `status` (e.g. "INVALID_ARGUMENT") next to the numeric `code`. + std::string type = error.value("type", error.value("status", "")); std::string full_error = provider_name + " API error (" + std::to_string(status_code) + "): " + message + diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0fc68db..350d788 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,11 +10,14 @@ set(AI_TEST_SOURCES unit/multi_step_coordinator_test.cpp unit/langfuse_tracer_test.cpp unit/openai_responses_test.cpp + unit/google_client_test.cpp + unit/google_stream_test.cpp # Integration tests integration/openai_integration_test.cpp integration/openai_responses_integration_test.cpp integration/anthropic_integration_test.cpp + integration/google_integration_test.cpp integration/tool_calling_integration_test.cpp integration/clickhouse_integration_test.cpp integration/openai_embeddings_integration_test.cpp diff --git a/tests/integration/google_integration_test.cpp b/tests/integration/google_integration_test.cpp new file mode 100644 index 0000000..0a2c4d5 --- /dev/null +++ b/tests/integration/google_integration_test.cpp @@ -0,0 +1,246 @@ +#include "../utils/test_fixtures.h" +#include "ai/google.h" +#include "ai/tools.h" +#include "ai/types/generate_options.h" +#include "ai/types/stream_options.h" + +#include +#include + +#include +#include + +// Note: These tests connect to the real Gemini API when GEMINI_API_KEY (or +// GOOGLE_API_KEY) is set. Otherwise they are skipped. + +namespace ai { +namespace test { + +namespace { + +// Gemini 3.5 Flash-Lite thinks at the `minimal` level by default, so small +// `max_tokens` values are not used up by thinking. +constexpr const char* kTestModel = ai::google::models::kGemini35FlashLite; + +} // namespace + +class GoogleIntegrationTest : public AITestFixture { + protected: + void SetUp() override { + AITestFixture::SetUp(); + client_ = ai::google::try_create_client(); + } + + bool use_real_api() const { return client_.has_value(); } + + std::optional client_; +}; + +#define SKIP_WITHOUT_GEMINI_KEY() \ + if (!use_real_api()) { \ + GTEST_SKIP() << "No GEMINI_API_KEY environment variable set"; \ + } + +TEST_F(GoogleIntegrationTest, BasicTextGeneration) { + SKIP_WITHOUT_GEMINI_KEY(); + + GenerateOptions options(kTestModel, "Hello, how are you?"); + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_FALSE(result.text.empty()); + EXPECT_GT(result.usage.total_tokens, 0); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); +} + +TEST_F(GoogleIntegrationTest, TextGenerationWithSystemPrompt) { + SKIP_WITHOUT_GEMINI_KEY(); + + GenerateOptions options( + kTestModel, "You are a helpful assistant that responds in French.", + "Hello, how are you?"); + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_THAT( + result.text, + testing::AnyOf(testing::HasSubstr("Bonjour"), testing::HasSubstr("salut"), + testing::HasSubstr("ça va"), testing::HasSubstr("bien"), + testing::HasSubstr("merci"))); +} + +TEST_F(GoogleIntegrationTest, TextGenerationWithParameters) { + SKIP_WITHOUT_GEMINI_KEY(); + + GenerateOptions options(kTestModel, "Write a very short story about a cat."); + options.max_tokens = 50; + options.temperature = 0.7; + + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_FALSE(result.text.empty()); + EXPECT_THAT(result.finish_reason, + testing::AnyOf(kFinishReasonStop, kFinishReasonLength)); + EXPECT_LE(result.text.length(), 400); +} + +TEST_F(GoogleIntegrationTest, ConversationWithMessages) { + SKIP_WITHOUT_GEMINI_KEY(); + + Messages conversation = { + Message::user("My name is Ada."), + Message::assistant("Nice to meet you, Ada!"), + Message::user("What is my name? Answer with the name only.")}; + + GenerateOptions options(kTestModel, std::move(conversation)); + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_THAT(result.text, testing::HasSubstr("Ada")); +} + +TEST_F(GoogleIntegrationTest, StructuredOutput) { + SKIP_WITHOUT_GEMINI_KEY(); + + GenerateOptions options(kTestModel, "Name the capital of France."); + options.response_format = { + {"type", "json_schema"}, + {"json_schema", + {{"name", "capital"}, + {"schema", + {{"type", "object"}, + {"properties", {{"city", {{"type", "string"}}}}}, + {"required", {"city"}}}}}}}; + + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + const auto json = nlohmann::json::parse(result.text); + EXPECT_THAT(json["city"].get(), testing::HasSubstr("Paris")); +} + +TEST_F(GoogleIntegrationTest, MultiStepToolCallingReplaysSignatures) { + SKIP_WITHOUT_GEMINI_KEY(); + + int calls = 0; + GenerateOptions options( + ai::google::models::kDefaultModel, + "What is the weather in Paris? Use the weather tool, then answer in " + "one sentence."); + options.tools = { + {"weather", + create_simple_tool( + "weather", "Get the current weather for a city", + {{"location", "string"}}, + [&calls](const JsonValue& args, const ToolExecutionContext&) { + ++calls; + return JsonValue{{"location", args["location"]}, + {"temperature_celsius", 21}, + {"condition", "sunny"}}; + })}}; + options.max_steps = 4; + + auto result = client_->generate_text(options); + + // Gemini 4 rejects the second step with HTTP 400 if the thought signature + // of the function call is not sent back. + TestAssertions::assertSuccess(result); + EXPECT_GE(calls, 1); + EXPECT_GE(result.steps.size(), 2u); + EXPECT_FALSE(result.text.empty()); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); +} + +TEST_F(GoogleIntegrationTest, InvalidApiKey) { + auto invalid_client = ai::google::create_client("invalid-gemini-key"); + + GenerateOptions options(kTestModel, "Test prompt"); + auto result = invalid_client.generate_text(options); + + TestAssertions::assertError(result); + EXPECT_THAT( + result.error_message(), + testing::AnyOf(testing::HasSubstr("400"), testing::HasSubstr("401"), + testing::HasSubstr("403"), testing::HasSubstr("API key"))); +} + +TEST_F(GoogleIntegrationTest, InvalidModel) { + SKIP_WITHOUT_GEMINI_KEY(); + + GenerateOptions options("invalid-model-name", "Test prompt"); + auto result = client_->generate_text(options); + + TestAssertions::assertError(result); + EXPECT_THAT( + result.error_message(), + testing::AnyOf(testing::HasSubstr("404"), testing::HasSubstr("400"), + testing::HasSubstr("not found"))); +} + +TEST_F(GoogleIntegrationTest, BasicStreaming) { + SKIP_WITHOUT_GEMINI_KEY(); + + GenerateOptions gen_options(kTestModel, "Count from 1 to 3"); + auto stream = client_->stream_text(StreamOptions(gen_options)); + + bool stream_finished = false; + std::string accumulated_text; + for (const auto& event : stream) { + if (event.is_text_delta()) { + accumulated_text += event.text_delta; + } else if (event.is_finish()) { + stream_finished = true; + EXPECT_EQ(event.finish_reason, kFinishReasonStop); + ASSERT_TRUE(event.usage.has_value()); + EXPECT_GT(event.usage->total_tokens, 0); + break; + } else if (event.is_error()) { + FAIL() << "Streaming error: " << event.error.value_or("unknown"); + } + } + + EXPECT_TRUE(stream_finished) << "Stream should have finished"; + EXPECT_THAT(accumulated_text, testing::HasSubstr("2")); +} + +TEST_F(GoogleIntegrationTest, DefaultModelGeneration) { + SKIP_WITHOUT_GEMINI_KEY(); + + EXPECT_EQ(client_->default_model(), ai::google::models::kDefaultModel); + GenerateOptions options(client_->default_model(), "Count to 3"); + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_FALSE(result.text.empty()); + if (result.model.has_value()) { + EXPECT_THAT(*result.model, + testing::HasSubstr(ai::google::models::kDefaultModel)); + } +} + +TEST_F(GoogleIntegrationTest, DefaultModelStreaming) { + SKIP_WITHOUT_GEMINI_KEY(); + + GenerateOptions gen_options(client_->default_model(), "Count from 1 to 3"); + auto stream = client_->stream_text(StreamOptions(gen_options)); + + bool stream_finished = false; + std::string accumulated_text; + for (const auto& event : stream) { + if (event.is_text_delta()) { + accumulated_text += event.text_delta; + } else if (event.is_finish()) { + stream_finished = true; + break; + } else if (event.is_error()) { + FAIL() << "Streaming error: " << event.error.value_or("unknown"); + } + } + + EXPECT_TRUE(stream_finished) << "Stream should have finished"; + EXPECT_FALSE(accumulated_text.empty()); +} + +} // namespace test +} // namespace ai diff --git a/tests/integration/tool_calling_integration_test.cpp b/tests/integration/tool_calling_integration_test.cpp index 11ae6af..3406977 100644 --- a/tests/integration/tool_calling_integration_test.cpp +++ b/tests/integration/tool_calling_integration_test.cpp @@ -1,5 +1,6 @@ #include "../utils/test_fixtures.h" #include "ai/anthropic.h" +#include "ai/google.h" #include "ai/logger.h" #include "ai/openai.h" #include "ai/tools.h" @@ -160,6 +161,12 @@ class ToolCallingIntegrationTest } else { use_real_api_ = false; } + } else if (provider == "google") { + client_ = ai::google::try_create_client(); + use_real_api_ = client_.has_value(); + // Thinks at the `minimal` level by default, so the small `max_tokens` + // of these tests is not used up by thinking. + model_ = ai::google::models::kGemini35FlashLite; } tools_ = ToolTestFixtures::createTestToolSet(); @@ -631,7 +638,7 @@ TEST_P(ToolCallingIntegrationTest, ToolSchemaValidation) { INSTANTIATE_TEST_SUITE_P( ProviderTests, ToolCallingIntegrationTest, - ::testing::Values("openai", "openai_responses", "anthropic"), + ::testing::Values("openai", "openai_responses", "anthropic", "google"), [](const ::testing::TestParamInfo& info) { return info.param; }); diff --git a/tests/unit/google_client_test.cpp b/tests/unit/google_client_test.cpp new file mode 100644 index 0000000..2fad133 --- /dev/null +++ b/tests/unit/google_client_test.cpp @@ -0,0 +1,725 @@ +#include "providers/google/google_client.h" + +#include "ai/errors.h" +#include "ai/google.h" +#include "ai/tools.h" +#include "ai/types/generate_options.h" +#include "ai/types/stream_options.h" +#include "providers/google/google_request_builder.h" +#include "providers/google/google_response_parser.h" + +#include +#include +#include +#include + +#include +#include + +namespace ai { +namespace test { + +namespace { + +Tool make_weather_tool() { + return Tool("Get the weather", + {{"type", "object"}, + {"properties", {{"location", {{"type", "string"}}}}}, + {"required", {"location"}}}, + [](const JsonValue& args, const ToolExecutionContext&) { + return JsonValue{{"location", args["location"]}, + {"temperature", 72}}; + }); +} + +nlohmann::json make_text_response(const std::string& text) { + return {{"candidates", + {{{"content", {{"role", "model"}, {"parts", {{{"text", text}}}}}}, + {"finishReason", "STOP"}, + {"index", 0}}}}, + {"usageMetadata", + {{"promptTokenCount", 8}, + {"candidatesTokenCount", 5}, + {"thoughtsTokenCount", 20}, + {"totalTokenCount", 33}}}, + {"modelVersion", "gemini-4-hydrogen"}, + {"responseId", "resp-1"}}; +} + +nlohmann::json make_function_call_response() { + return {{"candidates", + {{{"content", + {{"role", "model"}, + {"parts", + {{{"functionCall", + {{"id", "fc-1"}, + {"name", "weather"}, + {"args", {{"location", "Paris"}}}}}, + {"thoughtSignature", "sig-A"}}, + {{"functionCall", + {{"id", "fc-2"}, + {"name", "weather"}, + {"args", {{"location", "London"}}}}}}}}}}, + {"finishReason", "STOP"}}}}, + {"usageMetadata", + {{"promptTokenCount", 40}, + {"candidatesTokenCount", 12}, + {"totalTokenCount", 52}}}}; +} + +std::string env_or_empty(const char* name) { + const char* value = std::getenv(name); + return value ? value : ""; +} + +/// Set an environment variable for the lifetime of the object. +class ScopedEnv { + public: + ScopedEnv(const char* name, const char* value) + : name_(name), + previous_(std::getenv(name) != nullptr + ? std::optional(env_or_empty(name)) + : std::nullopt) { + if (value) { + setenv(name, value, 1); + } else { + unsetenv(name); + } + } + ~ScopedEnv() { + if (previous_) { + setenv(name_, previous_->c_str(), 1); + } else { + unsetenv(name_); + } + } + ScopedEnv(const ScopedEnv&) = delete; + ScopedEnv& operator=(const ScopedEnv&) = delete; + + private: + const char* name_; + std::optional previous_; +}; + +} // namespace + +// Request building + +TEST(GoogleRequestTest, BuildsRequestFromPrompt) { + google::GoogleRequestBuilder builder; + GenerateOptions options(google::models::kGemini35FlashLite, "Be brief.", + "Hello"); + options.max_tokens = 64; + options.temperature = 0.3; + options.top_p = 0.9; + options.seed = 7; + + const auto request = builder.build_request_json(options); + + EXPECT_FALSE(request.contains("model")); + ASSERT_EQ(request["contents"].size(), 1u); + EXPECT_EQ(request["contents"][0]["role"], "user"); + EXPECT_EQ(request["contents"][0]["parts"][0]["text"], "Hello"); + EXPECT_EQ(request["systemInstruction"]["parts"][0]["text"], "Be brief."); + const auto& config = request["generationConfig"]; + EXPECT_EQ(config["maxOutputTokens"], 64); + EXPECT_DOUBLE_EQ(config["temperature"].get(), 0.3); + EXPECT_DOUBLE_EQ(config["topP"].get(), 0.9); + EXPECT_EQ(config["seed"], 7); + EXPECT_FALSE(request.contains("tools")); +} + +TEST(GoogleRequestTest, OmitsSamplingParametersForRecentModels) { + google::GoogleRequestBuilder builder; + for (const auto* model : + {google::models::kGemini4Carbon, google::models::kGemini4Neon, + google::models::kGemini4Hydrogen, google::models::kGemini4Argon, + google::models::kGemini38Flash, google::models::kGemini36Flash, + "models/gemini-4-neon"}) { + GenerateOptions options(model, "Hello"); + options.temperature = 0.7; + options.top_p = 0.8; + + const auto request = builder.build_request_json(options); + + EXPECT_FALSE(request["generationConfig"].contains("temperature")) << model; + EXPECT_FALSE(request["generationConfig"].contains("topP")) << model; + } + + // Earlier models still accept them. + for (const auto* model : + {google::models::kGemini35FlashLite, google::models::kGemini31FlashLite, + "gemini-2.5-flash"}) { + GenerateOptions options(model, "Hello"); + options.temperature = 0.7; + const auto request = builder.build_request_json(options); + EXPECT_TRUE(request["generationConfig"].contains("temperature")) << model; + } +} + +TEST(GoogleRequestTest, AsksForTheLeastThinkingTheModelAccepts) { + google::GoogleRequestBuilder builder; + const auto thinking_config = [&builder](const std::string& model) { + const auto request = + builder.build_request_json(GenerateOptions(model, "Hi")); + return request.contains("generationConfig") + ? request["generationConfig"].value("thinkingConfig", + nlohmann::json()) + : nlohmann::json(); + }; + + const nlohmann::json low = {{"thinkingLevel", "low"}}; + const nlohmann::json minimal = {{"thinkingLevel", "minimal"}}; + for (const auto* model : + {google::models::kGemini4Carbon, google::models::kGemini4Neon, + google::models::kGemini4Hydrogen, google::models::kGemini4Argon, + "models/gemini-4-neon", google::models::kGemini38Flash, + "gemini-3.1-pro-preview"}) { + EXPECT_EQ(thinking_config(model), low) << model; + } + for (const auto* model : + {google::models::kGemini36Flash, google::models::kGemini35FlashLite, + google::models::kGemini31FlashLite, "gemini-3-flash-preview"}) { + EXPECT_EQ(thinking_config(model), minimal) << model; + } + EXPECT_EQ(thinking_config("gemini-2.5-flash"), + nlohmann::json({{"thinkingBudget", 0}})); + EXPECT_EQ(thinking_config("gemini-2.5-pro"), + nlohmann::json({{"thinkingBudget", 128}})); + // Models without known thinking settings get none. + EXPECT_TRUE(thinking_config("gemini-3.8-flash-tts").is_null()); + EXPECT_TRUE(thinking_config("custom-model").is_null()); +} + +TEST(GoogleRequestTest, StreamRequestsIncludeThoughtSummaries) { + google::GoogleRequestBuilder builder; + auto request = builder.build_request_json( + GenerateOptions(google::models::kGemini4Hydrogen, "Hi")); + google::include_thought_summaries(request); + EXPECT_EQ( + request["generationConfig"]["thinkingConfig"], + nlohmann::json({{"thinkingLevel", "low"}, {"includeThoughts", true}})); + + // No summaries when thinking is off or the model has no thinking settings. + request = + builder.build_request_json(GenerateOptions("gemini-2.5-flash", "Hi")); + google::include_thought_summaries(request); + EXPECT_FALSE(request["generationConfig"]["thinkingConfig"].contains( + "includeThoughts")); + request = builder.build_request_json(GenerateOptions("custom-model", "Hi")); + google::include_thought_summaries(request); + EXPECT_FALSE(request.contains("generationConfig")); +} + +TEST(GoogleRequestTest, MapsRolesAndSystemMessages) { + google::GoogleRequestBuilder builder; + GenerateOptions options( + google::models::kDefaultModel, + Messages{Message::system("Be terse."), Message::user("What is 2 + 2?"), + Message::assistant("4."), Message::user("And 4 + 4?")}); + options.system = "You are a math tutor."; + + const auto request = builder.build_request_json(options); + + const auto& system_parts = request["systemInstruction"]["parts"]; + ASSERT_EQ(system_parts.size(), 2u); + EXPECT_EQ(system_parts[0]["text"], "You are a math tutor."); + EXPECT_EQ(system_parts[1]["text"], "Be terse."); + + const auto& contents = request["contents"]; + ASSERT_EQ(contents.size(), 3u); + EXPECT_EQ(contents[0]["role"], "user"); + EXPECT_EQ(contents[1]["role"], "model"); + EXPECT_EQ(contents[1]["parts"][0]["text"], "4."); + EXPECT_EQ(contents[2]["role"], "user"); +} + +TEST(GoogleRequestTest, BuildsFunctionDeclarationsAndToolConfig) { + google::GoogleRequestBuilder builder; + GenerateOptions options(google::models::kDefaultModel, "Weather?"); + options.tools = {{"weather", make_weather_tool()}}; + + auto request = builder.build_request_json(options); + ASSERT_EQ(request["tools"].size(), 1u); + const auto& declarations = request["tools"][0]["functionDeclarations"]; + ASSERT_EQ(declarations.size(), 1u); + EXPECT_EQ(declarations[0]["name"], "weather"); + EXPECT_EQ(declarations[0]["description"], "Get the weather"); + EXPECT_EQ(declarations[0]["parametersJsonSchema"]["required"][0], "location"); + EXPECT_FALSE(declarations[0].contains("parameters")); + EXPECT_EQ(request["toolConfig"]["functionCallingConfig"]["mode"], "AUTO"); + + options.tool_choice = ToolChoice::required(); + request = builder.build_request_json(options); + EXPECT_EQ(request["toolConfig"]["functionCallingConfig"]["mode"], "ANY"); + EXPECT_FALSE(request["toolConfig"]["functionCallingConfig"].contains( + "allowedFunctionNames")); + + options.tool_choice = ToolChoice::none(); + request = builder.build_request_json(options); + EXPECT_EQ(request["toolConfig"]["functionCallingConfig"]["mode"], "NONE"); + + options.tool_choice = ToolChoice::specific("weather"); + request = builder.build_request_json(options); + const auto& config = request["toolConfig"]["functionCallingConfig"]; + EXPECT_EQ(config["mode"], "ANY"); + EXPECT_EQ(config["allowedFunctionNames"], nlohmann::json::array({"weather"})); +} + +TEST(GoogleRequestTest, MapsResponseFormat) { + google::GoogleRequestBuilder builder; + const nlohmann::json schema = { + {"type", "object"}, + {"properties", {{"name", {{"type", "string"}}}}}, + {"required", {"name"}}}; + + GenerateOptions chat_shape(google::models::kDefaultModel, "Name?"); + chat_shape.response_format = { + {"type", "json_schema"}, + {"json_schema", {{"name", "person"}, {"schema", schema}}}}; + auto request = builder.build_request_json(chat_shape); + EXPECT_EQ(request["generationConfig"]["responseMimeType"], + "application/json"); + EXPECT_EQ(request["generationConfig"]["responseJsonSchema"], schema); + + GenerateOptions flat_shape(google::models::kDefaultModel, "Name?"); + flat_shape.response_format = { + {"type", "json_schema"}, {"name", "person"}, {"schema", schema}}; + request = builder.build_request_json(flat_shape); + EXPECT_EQ(request["generationConfig"]["responseJsonSchema"], schema); + + GenerateOptions json_object(google::models::kDefaultModel, "Name?"); + json_object.response_format = + nlohmann::json::object({{"type", "json_object"}}); + request = builder.build_request_json(json_object); + EXPECT_EQ(request["generationConfig"]["responseMimeType"], + "application/json"); + EXPECT_FALSE(request["generationConfig"].contains("responseJsonSchema")); + + GenerateOptions unsupported(google::models::kDefaultModel, "Name?"); + unsupported.response_format = nlohmann::json::object({{"type", "xml"}}); + EXPECT_THROW(builder.build_request_json(unsupported), std::invalid_argument); +} + +TEST(GoogleRequestTest, ReplaysParsedTurnWithThoughtSignatures) { + google::GoogleResponseParser parser; + google::GoogleRequestBuilder builder; + auto step = + parser.parse_success_completion_response(make_function_call_response()); + ASSERT_EQ(step.response_messages.size(), 1u); + + Messages messages = {Message::user("Weather in Paris and London?")}; + messages.push_back(step.response_messages[0]); + messages.push_back(Message::tool_results( + {ToolResultContentPart("fc-1", {{"temperature", 18}}), + ToolResultContentPart("fc-2", "cloudy"), + ToolResultContentPart("fc-2", {{"error", "timeout"}}, true)})); + GenerateOptions options(google::models::kDefaultModel, std::move(messages)); + + const auto request = builder.build_request_json(options); + const auto& contents = request["contents"]; + ASSERT_EQ(contents.size(), 3u); + + // The model turn comes back exactly as received: the signature stays on + // the first call only. + const auto& model_parts = contents[1]["parts"]; + EXPECT_EQ(contents[1]["role"], "model"); + ASSERT_EQ(model_parts.size(), 2u); + EXPECT_EQ(model_parts[0]["thoughtSignature"], "sig-A"); + EXPECT_EQ(model_parts[0]["functionCall"]["id"], "fc-1"); + EXPECT_EQ(model_parts[0]["functionCall"]["name"], "weather"); + EXPECT_EQ(model_parts[0]["functionCall"]["args"]["location"], "Paris"); + EXPECT_FALSE(model_parts[1].contains("thoughtSignature")); + EXPECT_EQ(model_parts[1]["functionCall"]["id"], "fc-2"); + + // The results take the function name from the call they answer. + const auto& result_parts = contents[2]["parts"]; + EXPECT_EQ(contents[2]["role"], "user"); + ASSERT_EQ(result_parts.size(), 3u); + EXPECT_EQ(result_parts[0]["functionResponse"]["name"], "weather"); + EXPECT_EQ(result_parts[0]["functionResponse"]["id"], "fc-1"); + EXPECT_EQ(result_parts[0]["functionResponse"]["response"]["temperature"], 18); + EXPECT_EQ(result_parts[1]["functionResponse"]["response"]["output"], + "cloudy"); + EXPECT_EQ(result_parts[2]["functionResponse"]["response"]["error"], + "timeout"); +} + +TEST(GoogleRequestTest, UsesSkipSignatureForCallsWithoutSignature) { + google::GoogleRequestBuilder builder; + GenerateOptions options( + google::models::kDefaultModel, + Messages{Message::user("Weather?"), + Message::assistant_with_tools( + "Checking.", {ToolCallContentPart("call_1", "weather", + {{"location", "Paris"}}), + ToolCallContentPart("call_2", "weather", + {{"location", "Rome"}})}), + Message::tool_results( + {ToolResultContentPart("call_1", {{"temperature", 18}}), + ToolResultContentPart("call_2", {{"temperature", 25}})})}); + + const auto request = builder.build_request_json(options); + const auto& model_parts = request["contents"][1]["parts"]; + ASSERT_EQ(model_parts.size(), 3u); + EXPECT_EQ(model_parts[0]["text"], "Checking."); + EXPECT_FALSE(model_parts[0].contains("thoughtSignature")); + EXPECT_EQ(model_parts[1]["thoughtSignature"], + google::kSkipThoughtSignatureValidator); + EXPECT_FALSE(model_parts[2].contains("thoughtSignature")); +} + +TEST(GoogleRequestTest, OmitsSyntheticCallIds) { + google::GoogleResponseParser parser; + google::GoogleRequestBuilder builder; + // Gemini 2.5 returns function calls without an `id`. + auto step = parser.parse_success_completion_response( + {{"candidates", + {{{"content", + {{"role", "model"}, + {"parts", + {{{"functionCall", + {{"name", "weather"}, {"args", {{"location", "Oslo"}}}}}}}}}}, + {"finishReason", "STOP"}}}}}); + ASSERT_EQ(step.tool_calls.size(), 1u); + const auto id = step.tool_calls[0].id; + EXPECT_THAT(id, testing::StartsWith(google::kSyntheticCallIdPrefix)); + + Messages messages = { + Message::user("Weather in Oslo?"), step.response_messages[0], + Message::tool_results({ToolResultContentPart(id, {{"temperature", 3}})})}; + const auto request = builder.build_request_json( + GenerateOptions(google::models::kGemini35FlashLite, std::move(messages))); + + const auto& call = request["contents"][1]["parts"][0]["functionCall"]; + EXPECT_FALSE(call.contains("id")); + const auto& response = request["contents"][2]["parts"][0]["functionResponse"]; + EXPECT_FALSE(response.contains("id")); + EXPECT_EQ(response["name"], "weather"); +} + +TEST(GoogleRequestTest, RejectsToolResultWithoutMatchingCall) { + google::GoogleRequestBuilder builder; + GenerateOptions options( + google::models::kDefaultModel, + Messages{Message::user("Weather?"), + Message::tool_results({ToolResultContentPart("call_x", {})})}); + EXPECT_THROW(builder.build_request_json(options), std::invalid_argument); +} + +TEST(GoogleRequestTest, IgnoresOtherProvidersParts) { + google::GoogleRequestBuilder builder; + GenerateOptions options( + google::models::kDefaultModel, + Messages{Message::user("Hi"), + Message(kMessageRoleAssistant, + {ProviderContentPart("openai.responses", + {{"type", "reasoning"}}), + TextContentPart("Hello!")})}); + + const auto request = builder.build_request_json(options); + const auto& model_parts = request["contents"][1]["parts"]; + ASSERT_EQ(model_parts.size(), 1u); + EXPECT_EQ(model_parts[0], nlohmann::json({{"text", "Hello!"}})); +} + +TEST(GoogleRequestTest, MergesConsecutiveTurnsOfTheSameRole) { + google::GoogleRequestBuilder builder; + GenerateOptions options( + google::models::kDefaultModel, + Messages{Message::user("First."), Message::user("Second."), + Message::assistant_with_tools( + "", {ToolCallContentPart("call_1", "weather", + {{"location", "Paris"}})}), + Message::tool_results( + {ToolResultContentPart("call_1", {{"temperature", 18}})}), + Message::user("Thanks, and Rome?")}); + + const auto request = builder.build_request_json(options); + const auto& contents = request["contents"]; + ASSERT_EQ(contents.size(), 3u); + EXPECT_EQ(contents[0]["role"], "user"); + ASSERT_EQ(contents[0]["parts"].size(), 2u); + EXPECT_EQ(contents[0]["parts"][1]["text"], "Second."); + EXPECT_EQ(contents[1]["role"], "model"); + EXPECT_EQ(contents[2]["role"], "user"); + ASSERT_EQ(contents[2]["parts"].size(), 2u); + EXPECT_TRUE(contents[2]["parts"][0].contains("functionResponse")); + EXPECT_EQ(contents[2]["parts"][1]["text"], "Thanks, and Rome?"); +} + +// Response parsing + +TEST(GoogleParserTest, ParsesTextResponse) { + google::GoogleResponseParser parser; + const auto result = + parser.parse_success_completion_response(make_text_response("Hi!")); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "Hi!"); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); + EXPECT_EQ(result.id, "resp-1"); + EXPECT_EQ(result.model, "gemini-4-hydrogen"); + EXPECT_EQ(result.usage.prompt_tokens, 8); + EXPECT_EQ(result.usage.completion_tokens, 25); // answer + thinking + EXPECT_EQ(result.usage.total_tokens, 33); + ASSERT_EQ(result.response_messages.size(), 1u); + EXPECT_EQ(result.response_messages[0].get_text(), "Hi!"); +} + +TEST(GoogleParserTest, KeepsThoughtsAndSignaturesOutOfText) { + google::GoogleResponseParser parser; + const nlohmann::json thought = {{"text", "Let me think."}, {"thought", true}}; + const nlohmann::json signature_only = {{"text", ""}, + {"thoughtSignature", "sig-T"}}; + const auto result = parser.parse_success_completion_response( + {{"candidates", + {{{"content", + {{"role", "model"}, + {"parts", + {thought, + {{"text", "The answer is 42."}, {"thoughtSignature", "sig-X"}}, + signature_only}}}}, + {"finishReason", "STOP"}}}}}); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "The answer is 42."); + ASSERT_EQ(result.response_messages.size(), 1u); + + // Replaying the turn restores every part as received. + google::GoogleRequestBuilder builder; + Messages messages = {Message::user("Question"), result.response_messages[0], + Message::user("Thanks")}; + const auto request = builder.build_request_json( + GenerateOptions(google::models::kDefaultModel, std::move(messages))); + const auto& parts = request["contents"][1]["parts"]; + ASSERT_EQ(parts.size(), 3u); + EXPECT_EQ(parts[0], thought); + EXPECT_EQ(parts[1], nlohmann::json({{"text", "The answer is 42."}, + {"thoughtSignature", "sig-X"}})); + EXPECT_EQ(parts[2], signature_only); +} + +TEST(GoogleParserTest, ParsesFunctionCalls) { + google::GoogleResponseParser parser; + const auto result = + parser.parse_success_completion_response(make_function_call_response()); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.finish_reason, kFinishReasonToolCalls); + ASSERT_EQ(result.tool_calls.size(), 2u); + EXPECT_EQ(result.tool_calls[0].id, "fc-1"); + EXPECT_EQ(result.tool_calls[0].tool_name, "weather"); + EXPECT_EQ(result.tool_calls[0].arguments["location"], "Paris"); + EXPECT_EQ(result.tool_calls[1].id, "fc-2"); + ASSERT_EQ(result.response_messages.size(), 1u); + EXPECT_TRUE(result.response_messages[0].has_tool_calls()); +} + +TEST(GoogleParserTest, MapsFinishReasons) { + EXPECT_EQ(google::parse_finish_reason("STOP", false), kFinishReasonStop); + EXPECT_EQ(google::parse_finish_reason("STOP", true), kFinishReasonToolCalls); + EXPECT_EQ(google::parse_finish_reason("MAX_TOKENS", false), + kFinishReasonLength); + EXPECT_EQ(google::parse_finish_reason("MAX_TOKENS", true), + kFinishReasonToolCalls); + EXPECT_EQ(google::parse_finish_reason("CONTINUATION", false), + kFinishReasonLength); + for (const auto* reason : + {"SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII"}) { + EXPECT_EQ(google::parse_finish_reason(reason, false), + kFinishReasonContentFilter) + << reason; + } + for (const auto* reason : + {"MALFORMED_FUNCTION_CALL", "MISSING_THOUGHT_SIGNATURE", "OTHER", + "FINISH_REASON_UNSPECIFIED", ""}) { + EXPECT_FALSE(google::parse_finish_reason(reason, false).has_value()) + << reason; + } +} + +TEST(GoogleParserTest, ReportsMaxTokensAndSafety) { + google::GoogleResponseParser parser; + auto response = make_text_response("Truncated"); + response["candidates"][0]["finishReason"] = "MAX_TOKENS"; + auto result = parser.parse_success_completion_response(response); + ASSERT_TRUE(result.is_success()); + EXPECT_EQ(result.finish_reason, kFinishReasonLength); + + result = parser.parse_success_completion_response( + {{"candidates", {{{"finishReason", "SAFETY"}}}}}); + ASSERT_TRUE(result.is_success()); + EXPECT_EQ(result.finish_reason, kFinishReasonContentFilter); + EXPECT_TRUE(result.text.empty()); +} + +TEST(GoogleParserTest, ReportsFailedFinishReasonAsError) { + google::GoogleResponseParser parser; + const auto result = parser.parse_success_completion_response( + {{"candidates", + {{{"finishReason", "MALFORMED_FUNCTION_CALL"}, + {"finishMessage", "Malformed function call: weather("}}}}}); + EXPECT_FALSE(result.is_success()); + EXPECT_EQ(result.finish_reason, kFinishReasonError); + EXPECT_THAT(result.error_message(), + testing::HasSubstr("MALFORMED_FUNCTION_CALL")); + EXPECT_THAT(result.error_message(), testing::HasSubstr("weather(")); +} + +TEST(GoogleParserTest, ReportsBlockedPrompt) { + google::GoogleResponseParser parser; + const auto result = parser.parse_success_completion_response( + {{"promptFeedback", {{"blockReason", "SAFETY"}}}, + {"usageMetadata", {{"promptTokenCount", 5}, {"totalTokenCount", 5}}}}); + EXPECT_FALSE(result.is_success()); + EXPECT_EQ(result.finish_reason, kFinishReasonContentFilter); + EXPECT_THAT(result.error_message(), testing::HasSubstr("SAFETY")); +} + +TEST(GoogleParserTest, ParsesGoogleErrors) { + google::GoogleResponseParser parser; + const auto result = parser.parse_error_completion_response( + 400, + R"({"error":{"code":400,"message":"API key not valid.","status":"INVALID_ARGUMENT"}})"); + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), testing::HasSubstr("Google API error")); + EXPECT_THAT(result.error_message(), testing::HasSubstr("API key not valid.")); + EXPECT_THAT(result.error_message(), testing::HasSubstr("INVALID_ARGUMENT")); + EXPECT_FALSE(result.is_retryable.value_or(true)); + + EXPECT_TRUE( + parser.parse_error_completion_response(503, "{}").is_retryable.value_or( + false)); +} + +// Multi-step tool loop + +TEST(GoogleMultiStepTest, FollowUpRequestReplaysThoughtSignature) { + google::GoogleRequestBuilder builder; + google::GoogleResponseParser parser; + GenerateOptions options(google::models::kDefaultModel, + "Weather in Paris and London?"); + options.tools = {{"weather", make_weather_tool()}}; + options.max_steps = 3; + + std::vector requests; + auto result = MultiStepCoordinator::execute_multi_step( + options, [&](const GenerateOptions& step_options) { + requests.push_back(builder.build_request_json(step_options)); + if (requests.size() == 1) { + auto step = parser.parse_success_completion_response( + make_function_call_response()); + step.tool_results = ToolExecutor::execute_tools_with_options( + step.tool_calls, step_options, false); + return step; + } + return parser.parse_success_completion_response( + make_text_response("Both are 72F.")); + }); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "Both are 72F."); + ASSERT_EQ(requests.size(), 2u); + const auto& contents = requests[1]["contents"]; + ASSERT_EQ(contents.size(), 3u); + EXPECT_EQ(contents[1]["parts"][0]["thoughtSignature"], "sig-A"); + EXPECT_EQ(contents[1]["parts"][1]["functionCall"]["args"]["location"], + "London"); + ASSERT_EQ(contents[2]["parts"].size(), 2u); + EXPECT_EQ(contents[2]["parts"][0]["functionResponse"]["id"], "fc-1"); + EXPECT_EQ(contents[2]["parts"][0]["functionResponse"]["response"]["location"], + "Paris"); + EXPECT_EQ(contents[2]["parts"][1]["functionResponse"]["id"], "fc-2"); + + ASSERT_EQ(result.response_messages.size(), 3u); + EXPECT_EQ(result.response_messages.back().get_text(), "Both are 72F."); +} + +// Client + +TEST(GoogleClientTest, UsesModelPathAndDefaults) { + google::GoogleClient client("test-key"); + EXPECT_EQ(client.provider_name(), "google"); + EXPECT_EQ(client.default_model(), google::models::kDefaultModel); + EXPECT_EQ(client.get_base_url(), google::kDefaultBaseUrl); + EXPECT_THAT(client.config_info(), testing::HasSubstr("Gemini")); + EXPECT_TRUE(client.is_valid()); + EXPECT_TRUE(client.supports_model(google::models::kGemini4Neon)); + EXPECT_TRUE(client.supports_model("gemini-some-future-model")); + EXPECT_FALSE(client.supports_model("")); + EXPECT_FALSE(google::GoogleClient("").is_valid()); + + EXPECT_EQ( + google::GoogleClient::model_path("gemini-4-neon", "generateContent"), + "/v1beta/models/gemini-4-neon:generateContent"); + EXPECT_EQ(google::GoogleClient::model_path("models/gemini-4-neon", + "streamGenerateContent"), + "/v1beta/models/gemini-4-neon:streamGenerateContent"); +} + +TEST(GoogleClientTest, StreamReportsRequestBuildErrors) { + google::GoogleClient client("test-key", "http://127.0.0.1:9"); + GenerateOptions options(google::models::kDefaultModel, "Name?"); + options.response_format = nlohmann::json::object({{"type", "xml"}}); + + auto stream = client.stream_text(StreamOptions(options)); + bool saw_error = false; + bool saw_finish = false; + for (const auto& event : stream) { + if (event.is_error()) { + saw_error = true; + EXPECT_THAT(event.error.value_or(""), + testing::HasSubstr("Unsupported response_format")); + } else if (event.is_finish()) { + saw_finish = true; + EXPECT_EQ(event.finish_reason, kFinishReasonError); + break; + } + } + EXPECT_TRUE(saw_error); + EXPECT_TRUE(saw_finish); +} + +TEST(GoogleClientTest, AuthenticatesWithGoogApiKeyHeader) { + google::GoogleRequestBuilder builder; + providers::ProviderConfig config{.api_key = "test-key", + .auth_header_name = "x-goog-api-key"}; + const auto headers = builder.build_headers(config); + const auto it = headers.find("x-goog-api-key"); + ASSERT_NE(it, headers.end()); + EXPECT_EQ(it->second, "test-key"); +} + +TEST(GoogleClientTest, EmbeddingsAreNotSupported) { + google::GoogleClient client("test-key"); + const auto result = + client.embeddings(EmbeddingOptions("gemini-embedding-2", "text")); + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), testing::HasSubstr("not supported")); +} + +TEST(GoogleClientTest, FactoryReadsApiKeyFromEnvironment) { + { + ScopedEnv google_key("GOOGLE_API_KEY", nullptr); + ScopedEnv gemini_key("GEMINI_API_KEY", nullptr); + EXPECT_FALSE(google::try_create_client().has_value()); + EXPECT_THROW(google::create_client(), ConfigurationError); + } + { + ScopedEnv google_key("GOOGLE_API_KEY", nullptr); + ScopedEnv gemini_key("GEMINI_API_KEY", "gemini-key"); + auto client = google::try_create_client(); + ASSERT_TRUE(client.has_value()); + EXPECT_EQ(client->provider_name(), "google"); + EXPECT_TRUE(client->is_valid()); + } + { + ScopedEnv google_key("GOOGLE_API_KEY", "google-key"); + ScopedEnv gemini_key("GEMINI_API_KEY", nullptr); + EXPECT_TRUE(google::create_client().is_valid()); + } +} + +} // namespace test +} // namespace ai diff --git a/tests/unit/google_stream_test.cpp b/tests/unit/google_stream_test.cpp new file mode 100644 index 0000000..87c6dfe --- /dev/null +++ b/tests/unit/google_stream_test.cpp @@ -0,0 +1,158 @@ +#include "providers/google/google_stream.h" + +#include "ai/types/stream_event.h" +#include "providers/google/google_request_builder.h" + +#include +#include + +namespace ai { +namespace test { + +TEST(GoogleStreamTest, StreamsTextAndUsage) { + google::GoogleStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Hel"}]},"index":0}],"usageMetadata":{"promptTokenCount":4,"totalTokenCount":4},"modelVersion":"gemini-4-hydrogen","responseId":"r1"})"); + stream.process_sse_line_for_testing(""); + stream.process_sse_line_for_testing( + R"(data: {"candidates":[{"content":{"role":"model","parts":[{"text":"lo"}]},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2,"thoughtsTokenCount":3,"totalTokenCount":9},"modelVersion":"gemini-4-hydrogen","responseId":"r1"})"); + stream.process_sse_line_for_testing(""); + + ASSERT_EQ(stream.queued_event_count_for_testing(), 3u); + EXPECT_EQ(stream.get_next_event().text_delta, "Hel"); + EXPECT_EQ(stream.get_next_event().text_delta, "lo"); + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonStop); + ASSERT_TRUE(finish.usage.has_value()); + EXPECT_EQ(finish.usage->prompt_tokens, 4); + EXPECT_EQ(finish.usage->completion_tokens, 5); + EXPECT_EQ(finish.usage->total_tokens, 9); + EXPECT_FALSE(stream.has_more_events()); +} + +TEST(GoogleStreamTest, ChunkedEventsAreReassembled) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Hi"); + stream.process_sse_chunk_for_testing( + " there\"}]},\"finishReason\":\"STOP\"}]}\r\n\r\n"); + + ASSERT_EQ(stream.queued_event_count_for_testing(), 2u); + EXPECT_EQ(stream.get_next_event().text_delta, "Hi there"); + EXPECT_TRUE(stream.get_next_event().is_finish()); +} + +TEST(GoogleStreamTest, StreamsThoughtsAsReasoning) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"candidates":[{"content":{"parts":[{"text":"Considering the question.","thought":true}]}}]} + +data: {"candidates":[{"content":{"parts":[{"text":"42"}]},"finishReason":"STOP"}]} + +)"); + + ASSERT_EQ(stream.queued_event_count_for_testing(), 3u); + const auto reasoning = stream.get_next_event(); + ASSERT_TRUE(reasoning.is_reasoning_delta()); + EXPECT_EQ(reasoning.reasoning_delta, "Considering the question."); + EXPECT_TRUE(reasoning.text_delta.empty()); + const auto text = stream.get_next_event(); + ASSERT_TRUE(text.is_text_delta()); + EXPECT_EQ(text.text_delta, "42"); + EXPECT_TRUE(stream.get_next_event().is_finish()); +} + +TEST(GoogleStreamTest, SkipsSignatureOnlyParts) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"candidates":[{"content":{"parts":[{"text":"Answer"}]}}]} + +data: {"candidates":[{"content":{"parts":[{"text":"","thoughtSignature":"sig"}]},"finishReason":"STOP"}]} + +)"); + + ASSERT_EQ(stream.queued_event_count_for_testing(), 2u); + EXPECT_EQ(stream.get_next_event().text_delta, "Answer"); + EXPECT_TRUE(stream.get_next_event().is_finish()); +} + +TEST(GoogleStreamTest, StreamsFunctionCalls) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"id":"fc-1","name":"weather","args":{"location":"Paris"}},"thoughtSignature":"sig"},{"functionCall":{"name":"weather","args":{"location":"Rome"}}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":6,"totalTokenCount":16}} + +)"); + + ASSERT_EQ(stream.queued_event_count_for_testing(), 3u); + auto first = stream.get_next_event(); + ASSERT_TRUE(first.is_tool_call()); + EXPECT_EQ(first.tool_call->id, "fc-1"); + EXPECT_EQ(first.tool_call->tool_name, "weather"); + EXPECT_EQ(first.tool_call->arguments["location"], "Paris"); + auto second = stream.get_next_event(); + ASSERT_TRUE(second.is_tool_call()); + EXPECT_THAT(second.tool_call->id, + testing::StartsWith(google::kSyntheticCallIdPrefix)); + EXPECT_EQ(second.tool_call->arguments["location"], "Rome"); + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonToolCalls); +} + +TEST(GoogleStreamTest, MaxTokensFinishesWithLength) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"candidates":[{"content":{"parts":[{"text":"Once"}]},"finishReason":"MAX_TOKENS"}]} + +)"); + EXPECT_EQ(stream.get_next_event().text_delta, "Once"); + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonLength); +} + +TEST(GoogleStreamTest, FailedFinishReasonEmitsError) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"candidates":[{"finishReason":"MALFORMED_FUNCTION_CALL","finishMessage":"bad call"}]} + +)"); + const auto error = stream.get_next_event(); + ASSERT_TRUE(error.is_error()); + EXPECT_THAT(error.error.value_or(""), + testing::HasSubstr("MALFORMED_FUNCTION_CALL")); + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonError); +} + +TEST(GoogleStreamTest, BlockedPromptEmitsError) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"},"usageMetadata":{"promptTokenCount":3,"totalTokenCount":3}} + +)"); + const auto error = stream.get_next_event(); + ASSERT_TRUE(error.is_error()); + EXPECT_THAT(error.error.value_or(""), + testing::HasSubstr("PROHIBITED_CONTENT")); + EXPECT_EQ(stream.get_next_event().finish_reason, kFinishReasonError); +} + +TEST(GoogleStreamTest, ErrorChunkEmitsError) { + google::GoogleStreamImpl stream; + stream.process_sse_chunk_for_testing( + R"(data: {"error":{"code":500,"message":"Internal error encountered.","status":"INTERNAL"}} + +)"); + const auto error = stream.get_next_event(); + ASSERT_TRUE(error.is_error()); + EXPECT_THAT(error.error.value_or(""), + testing::HasSubstr("Internal error encountered.")); + EXPECT_THAT(error.error.value_or(""), testing::HasSubstr("INTERNAL")); + EXPECT_EQ(stream.get_next_event().finish_reason, kFinishReasonError); +} + +} // namespace test +} // namespace ai