|
| 1 | +#include "../utils/test_fixtures.h" |
| 2 | +#include "ai/anthropic.h" |
| 3 | +#include "ai/logger.h" |
| 4 | +#include "ai/openai.h" |
| 5 | +#include "ai/tools.h" |
| 6 | +#include "ai/types/generate_options.h" |
| 7 | +#include "ai/types/tool.h" |
| 8 | + |
| 9 | +#include <atomic> |
| 10 | +#include <memory> |
| 11 | +#include <optional> |
| 12 | +#include <string> |
| 13 | + |
| 14 | +#include <gmock/gmock.h> |
| 15 | +#include <gtest/gtest.h> |
| 16 | + |
| 17 | +namespace ai { |
| 18 | +namespace test { |
| 19 | + |
| 20 | +// Test for issue #26: Tools executed twice in multi-step mode |
| 21 | +// https://github.com/ClickHouse/ai-sdk-cpp/issues/26 |
| 22 | + |
| 23 | +// Parameterized test class for multi-step tool execution |
| 24 | +class MultiStepDuplicateExecutionTest |
| 25 | + : public ::testing::TestWithParam<std::string> { |
| 26 | + protected: |
| 27 | + void SetUp() override { |
| 28 | + std::string provider = GetParam(); |
| 29 | + |
| 30 | + if (provider == "openai") { |
| 31 | + const char* api_key = std::getenv("OPENAI_API_KEY"); |
| 32 | + if (api_key) { |
| 33 | + use_real_api_ = true; |
| 34 | + client_ = ai::openai::create_client(api_key); |
| 35 | + model_ = ai::openai::models::kGpt4oMini; |
| 36 | + } else { |
| 37 | + use_real_api_ = false; |
| 38 | + } |
| 39 | + } else if (provider == "anthropic") { |
| 40 | + const char* api_key = std::getenv("ANTHROPIC_API_KEY"); |
| 41 | + if (api_key) { |
| 42 | + use_real_api_ = true; |
| 43 | + client_ = ai::anthropic::create_client(api_key); |
| 44 | + model_ = ai::anthropic::models::kClaudeSonnet35; |
| 45 | + } else { |
| 46 | + use_real_api_ = false; |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + bool use_real_api_ = false; |
| 52 | + std::optional<ai::Client> client_; |
| 53 | + std::string model_; |
| 54 | +}; |
| 55 | + |
| 56 | +// Test that tools are executed only once per step in multi-step mode |
| 57 | +TEST_P(MultiStepDuplicateExecutionTest, ToolsExecutedOncePerStepNotTwice) { |
| 58 | + if (!use_real_api_) { |
| 59 | + GTEST_SKIP() << "No API key set for " << GetParam(); |
| 60 | + } |
| 61 | + |
| 62 | + // Create a shared counter to track tool executions |
| 63 | + auto execution_count = std::make_shared<std::atomic<int>>(0); |
| 64 | + |
| 65 | + // Create a tool that increments the counter each time it's called |
| 66 | + Tool counter_tool = create_simple_tool( |
| 67 | + "get_counter", "Returns the current count", {{"message", "string"}}, |
| 68 | + [execution_count](const JsonValue& args, |
| 69 | + const ToolExecutionContext& context) { |
| 70 | + int count = execution_count->fetch_add(1) + 1; |
| 71 | + std::string message = args["message"].get<std::string>(); |
| 72 | + ai::logger::log_info("Counter tool executed! Count: {}, Message: {}", |
| 73 | + count, message); |
| 74 | + return JsonValue{{"count", count}, {"message", message}}; |
| 75 | + }); |
| 76 | + |
| 77 | + ToolSet tools = {{"get_counter", counter_tool}}; |
| 78 | + |
| 79 | + // Configure options with multi-step mode enabled (max_steps > 1) |
| 80 | + GenerateOptions options(model_, |
| 81 | + "Please use the get_counter tool with message " |
| 82 | + "'test' to get the current count."); |
| 83 | + options.tools = tools; |
| 84 | + options.max_steps = 2; // Enable multi-step mode |
| 85 | + options.max_tokens = 300; |
| 86 | + |
| 87 | + // Reset counter before test |
| 88 | + execution_count->store(0); |
| 89 | + |
| 90 | + // Execute the request |
| 91 | + auto result = client_->generate_text(options); |
| 92 | + |
| 93 | + // Verify result is successful |
| 94 | + EXPECT_TRUE(result.is_success()) |
| 95 | + << "Expected successful result but got error: " << result.error_message(); |
| 96 | + |
| 97 | + // Verify the tool was called |
| 98 | + EXPECT_TRUE(result.has_tool_calls()) << "Expected tool calls to be made"; |
| 99 | + EXPECT_GT(result.tool_calls.size(), 0) << "Expected at least one tool call"; |
| 100 | + |
| 101 | + // Verify tool results exist |
| 102 | + EXPECT_TRUE(result.has_tool_results()) |
| 103 | + << "Expected tool results to be present"; |
| 104 | + |
| 105 | + // Log the execution count |
| 106 | + int final_count = execution_count->load(); |
| 107 | + ai::logger::log_info( |
| 108 | + "Final execution count: {} (expected 1 per tool call, got {})", |
| 109 | + final_count, result.tool_calls.size()); |
| 110 | + |
| 111 | + // CRITICAL ASSERTION: Each tool call should be executed exactly once |
| 112 | + // If this fails, it means tools are being executed multiple times |
| 113 | + EXPECT_EQ(final_count, static_cast<int>(result.tool_calls.size())) |
| 114 | + << "Tool execution count (" << final_count |
| 115 | + << ") does not match tool call count (" << result.tool_calls.size() |
| 116 | + << "). This indicates duplicate execution! " |
| 117 | + << "See https://github.com/ClickHouse/ai-sdk-cpp/issues/26"; |
| 118 | + |
| 119 | + // Additional verification: check the tool results |
| 120 | + for (const auto& tool_result : result.tool_results) { |
| 121 | + EXPECT_TRUE(tool_result.is_success()) |
| 122 | + << "Tool execution failed: " << tool_result.error_message(); |
| 123 | + |
| 124 | + if (tool_result.is_success() && tool_result.result.contains("count")) { |
| 125 | + ai::logger::log_info("Tool result count: {}", |
| 126 | + tool_result.result["count"].get<int>()); |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +// Test with multiple steps to verify the issue persists across steps |
| 132 | +TEST_P(MultiStepDuplicateExecutionTest, MultipleStepsNoDuplicateExecution) { |
| 133 | + if (!use_real_api_) { |
| 134 | + GTEST_SKIP() << "No API key set for " << GetParam(); |
| 135 | + } |
| 136 | + |
| 137 | + // Create a shared counter to track tool executions |
| 138 | + auto execution_count = std::make_shared<std::atomic<int>>(0); |
| 139 | + |
| 140 | + // Create a calculator tool that also tracks executions |
| 141 | + Tool tracked_calculator = create_simple_tool( |
| 142 | + "add", "Add two numbers together", {{"a", "number"}, {"b", "number"}}, |
| 143 | + [execution_count](const JsonValue& args, |
| 144 | + const ToolExecutionContext& context) { |
| 145 | + int exec_num = execution_count->fetch_add(1) + 1; |
| 146 | + double a = args["a"].get<double>(); |
| 147 | + double b = args["b"].get<double>(); |
| 148 | + double result = a + b; |
| 149 | + |
| 150 | + ai::logger::log_info( |
| 151 | + "Calculator executed (execution #{}): {} + {} = {}", exec_num, a, b, |
| 152 | + result); |
| 153 | + |
| 154 | + return JsonValue{{"result", result}, |
| 155 | + {"execution_number", exec_num}, |
| 156 | + {"a", a}, |
| 157 | + {"b", b}}; |
| 158 | + }); |
| 159 | + |
| 160 | + ToolSet tools = {{"add", tracked_calculator}}; |
| 161 | + |
| 162 | + // Configure options with higher max_steps |
| 163 | + GenerateOptions options(model_, |
| 164 | + "Calculate 5 + 3 using the add tool. " |
| 165 | + "Then tell me the result."); |
| 166 | + options.tools = tools; |
| 167 | + options.max_steps = 3; // Allow multiple steps |
| 168 | + options.max_tokens = 500; |
| 169 | + |
| 170 | + // Reset counter before test |
| 171 | + execution_count->store(0); |
| 172 | + |
| 173 | + // Execute the request |
| 174 | + auto result = client_->generate_text(options); |
| 175 | + |
| 176 | + // Verify result is successful |
| 177 | + EXPECT_TRUE(result.is_success()) |
| 178 | + << "Expected successful result but got error: " << result.error_message(); |
| 179 | + |
| 180 | + // Verify the tool was called |
| 181 | + EXPECT_TRUE(result.has_tool_calls()) << "Expected tool calls to be made"; |
| 182 | + |
| 183 | + // Log step information |
| 184 | + ai::logger::log_info("Total steps executed: {}", result.steps.size()); |
| 185 | + ai::logger::log_info("Total tool calls: {}", result.tool_calls.size()); |
| 186 | + |
| 187 | + int final_count = execution_count->load(); |
| 188 | + ai::logger::log_info("Total tool executions: {}", final_count); |
| 189 | + |
| 190 | + // CRITICAL ASSERTION: Total executions should equal total tool calls |
| 191 | + EXPECT_EQ(final_count, static_cast<int>(result.tool_calls.size())) |
| 192 | + << "Tool execution count (" << final_count |
| 193 | + << ") does not match tool call count (" << result.tool_calls.size() |
| 194 | + << "). This indicates duplicate execution across steps! " |
| 195 | + << "See https://github.com/ClickHouse/ai-sdk-cpp/issues/26"; |
| 196 | + |
| 197 | + // Verify each step's tool results show unique execution numbers |
| 198 | + for (size_t i = 0; i < result.steps.size(); ++i) { |
| 199 | + const auto& step = result.steps[i]; |
| 200 | + if (!step.tool_results.empty()) { |
| 201 | + ai::logger::log_info("Step {} had {} tool results", i + 1, |
| 202 | + step.tool_results.size()); |
| 203 | + for (const auto& tool_result : step.tool_results) { |
| 204 | + if (tool_result.is_success() && |
| 205 | + tool_result.result.contains("execution_number")) { |
| 206 | + int exec_num = tool_result.result["execution_number"].get<int>(); |
| 207 | + ai::logger::log_info(" - Execution number: {}", exec_num); |
| 208 | + } |
| 209 | + } |
| 210 | + } |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +// Instantiate tests for both providers |
| 215 | +INSTANTIATE_TEST_SUITE_P( |
| 216 | + ProviderTests, |
| 217 | + MultiStepDuplicateExecutionTest, |
| 218 | + ::testing::Values("openai", "anthropic"), |
| 219 | + [](const ::testing::TestParamInfo< |
| 220 | + MultiStepDuplicateExecutionTest::ParamType>& info) { |
| 221 | + return info.param; |
| 222 | + }); |
| 223 | + |
| 224 | +} // namespace test |
| 225 | +} // namespace ai |
0 commit comments