From 9b06835d9012c512655dd16172700d410018f7bd Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 00:30:37 +0000 Subject: [PATCH 1/6] Add the current Claude and GPT-6 models Anthropic: - Add `claude-fable-5-2`, `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5` and `claude-fable-5-1`; the default model is now `claude-sonnet-5-5`. - Omit sampling parameters for `claude-haiku-5-5`, which rejects non-default values; the existing prefixes already cover the point releases of Opus 5, Fable 5 and Sonnet 5. - Map the `refusal` stop reason to `kFinishReasonContentFilter` instead of `kFinishReasonStop`, both in responses and in streams. - Document that the newest models reject a forced tool choice. OpenAI: - Add `gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6.1-terra` and `gpt-6-luna`. - Treat the GPT-6 family as reasoning-first: omit sampling parameters, and send the lowest accepted `reasoning_effort` (`low`; `none` for `gpt-6-luna` and `gpt-6.1-terra`; GPT-6.2 rejects `none`). - Note the shutdown dates of `gpt-5-mini`, `gpt-5-nano`, `gpt-4.1`, `gpt-4.1-mini` and `gpt-5.4-nano`. - Keep `gpt-5.6` as the default: GPT-6 models support tool calling only through the Responses API, not Chat Completions. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- examples/basic_chat.cpp | 2 +- examples/components/all/main.cpp | 5 ++- examples/test_anthropic.cpp | 4 +- examples/tool_calling_async.cpp | 2 +- include/ai/anthropic.h | 14 +++++- include/ai/openai.h | 22 +++++++--- src/providers/anthropic/anthropic_client.cpp | 18 ++++---- .../anthropic/anthropic_request_builder.cpp | 8 ++-- .../anthropic/anthropic_response_parser.cpp | 5 +++ src/providers/anthropic/anthropic_stream.cpp | 2 + src/providers/openai/openai_client.cpp | 7 ++- .../openai/openai_request_builder.cpp | 29 +++++++++--- .../anthropic_integration_test.cpp | 19 ++++---- tests/integration/openai_integration_test.cpp | 5 ++- tests/unit/anthropic_client_test.cpp | 15 ++++++- tests/unit/anthropic_stream_test.cpp | 12 +++++ tests/unit/openai_client_test.cpp | 44 +++++++++++++++---- 18 files changed, 160 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 410c92d..c738420 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ int main() { int main() { // Ensure ANTHROPIC_API_KEY environment variable is set auto client = ai::anthropic::create_client(); - ai::GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, + ai::GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, "Explain quantum computing in simple terms."); options.system = "You are a helpful assistant."; auto result = client.generate_text(options); diff --git a/examples/basic_chat.cpp b/examples/basic_chat.cpp index d179b31..2d24d80 100644 --- a/examples/basic_chat.cpp +++ b/examples/basic_chat.cpp @@ -98,7 +98,7 @@ int main() { auto client4 = ai::anthropic::create_client(); ai::GenerateOptions options4; - options4.model = ai::anthropic::models::kClaudeSonnet5; + options4.model = ai::anthropic::models::kClaudeSonnet55; options4.prompt = "Write a haiku about programming. Just the haiku, nothing else."; diff --git a/examples/components/all/main.cpp b/examples/components/all/main.cpp index 67dd8fe..3bd204a 100644 --- a/examples/components/all/main.cpp +++ b/examples/components/all/main.cpp @@ -51,8 +51,9 @@ int main() { try { auto anthropic_client = ai::anthropic::create_client(); std::cout << "✓ Anthropic client created successfully\n"; - std::cout << "✓ Available models: " << ai::anthropic::models::kClaudeSonnet5 - << ", " << ai::anthropic::models::kClaudeHaiku45 << "\n"; + std::cout << "✓ Available models: " + << ai::anthropic::models::kClaudeSonnet55 << ", " + << ai::anthropic::models::kClaudeHaiku55 << "\n"; } catch (const std::exception& e) { std::cout << "✗ Anthropic client failed: " << e.what() << "\n"; } diff --git a/examples/test_anthropic.cpp b/examples/test_anthropic.cpp index 5b72ca3..13149d8 100644 --- a/examples/test_anthropic.cpp +++ b/examples/test_anthropic.cpp @@ -16,7 +16,7 @@ int main() { // Test simple generation std::cout << "Testing Anthropic text generation...\n\n"; - ai::GenerateOptions options(ai::anthropic::models::kClaudeHaiku45, + ai::GenerateOptions options(ai::anthropic::models::kClaudeHaiku55, "You are a helpful assistant.", "Why is the sky blue? Give a short answer."); @@ -35,7 +35,7 @@ int main() { std::cout << "\nTesting streaming...\n"; ai::GenerateOptions stream_opts( - ai::anthropic::models::kClaudeHaiku45, + ai::anthropic::models::kClaudeHaiku55, "Count from 1 to 5 slowly and with each number say 'tick'"); ai::StreamOptions stream_options(stream_opts); diff --git a/examples/tool_calling_async.cpp b/examples/tool_calling_async.cpp index 2510d1f..89435f8 100644 --- a/examples/tool_calling_async.cpp +++ b/examples/tool_calling_async.cpp @@ -342,7 +342,7 @@ int main() { start_time = std::chrono::high_resolution_clock::now(); ai::GenerateOptions anthropic_options; - anthropic_options.model = ai::anthropic::models::kClaudeSonnet5; + anthropic_options.model = ai::anthropic::models::kClaudeSonnet55; anthropic_options.prompt = R"( Please help me with these THREE tasks. You MUST use the tools to complete ALL of them: 1. Use the fetch_news tool to get tech news articles diff --git a/include/ai/anthropic.h b/include/ai/anthropic.h index 0a10da7..67df022 100644 --- a/include/ai/anthropic.h +++ b/include/ai/anthropic.h @@ -16,6 +16,18 @@ namespace anthropic { namespace models { /// Current Anthropic model identifiers +/// +/// Claude Fable 5.1 and later, Claude Opus 5.5 and Claude Sonnet 5.5 reject a +/// forced tool choice (`ToolChoice::required()` and `ToolChoice::specific()`) +/// with HTTP 400; use `ToolChoice::auto_choice()` and name the tool in the +/// prompt instead. +constexpr const char* kClaudeFable52 = "claude-fable-5-2"; +constexpr const char* kClaudeOpus55 = "claude-opus-5-5"; +constexpr const char* kClaudeSonnet55 = "claude-sonnet-5-5"; +constexpr const char* kClaudeHaiku55 = "claude-haiku-5-5"; + +/// Previous-generation model identifiers (still available) +constexpr const char* kClaudeFable51 = "claude-fable-5-1"; constexpr const char* kClaudeFable5 = "claude-fable-5"; constexpr const char* kClaudeOpus5 = "claude-opus-5"; constexpr const char* kClaudeOpus48 = "claude-opus-4-8"; @@ -39,7 +51,7 @@ constexpr const char* kClaudeOpus41 = constexpr const char* kClaudeOpus41Snapshot = "claude-opus-4-1-20250805"; /// Default model used when none is specified -constexpr const char* kDefaultModel = kClaudeSonnet5; +constexpr const char* kDefaultModel = kClaudeSonnet55; } // namespace models /// Create an Anthropic client with default configuration diff --git a/include/ai/openai.h b/include/ai/openai.h index 1ed0df1..7772c0f 100644 --- a/include/ai/openai.h +++ b/include/ai/openai.h @@ -17,24 +17,33 @@ namespace openai { namespace models { /// Common OpenAI model identifiers -// GPT-5.6 series (current frontier family) +// GPT-6 series (current frontier family). On Chat Completions, which this +// SDK uses, these models reject sampling parameters and do not support tool +// calling (OpenAI serves their tool calling through the Responses API only). +constexpr const char* kGpt62Astra = "gpt-6.2-astra"; +constexpr const char* kGpt62Sol = "gpt-6.2-sol"; +constexpr const char* kGpt61Terra = "gpt-6.1-terra"; +constexpr const char* kGpt6Luna = "gpt-6-luna"; + +// GPT-5.6 series (latest family with tool calling on Chat Completions) constexpr const char* kGpt56 = "gpt-5.6"; // Alias for GPT-5.6 Sol constexpr const char* kGpt56Sol = "gpt-5.6-sol"; constexpr const char* kGpt56Terra = "gpt-5.6-terra"; constexpr const char* kGpt56Luna = "gpt-5.6-luna"; -// Earlier current GPT-5 series +// Earlier GPT-5 series constexpr const char* kGpt55 = "gpt-5.5"; constexpr const char* kGpt54 = "gpt-5.4"; constexpr const char* kGpt54Pro = "gpt-5.4-pro"; constexpr const char* kGpt54Mini = "gpt-5.4-mini"; -constexpr const char* kGpt54Nano = "gpt-5.4-nano"; +constexpr const char* kGpt54Nano = "gpt-5.4-nano"; // Shutdown: 2027-04-01 -// GPT-5 small variants (current) +// GPT-5 small variants (deprecated, shutdown: 2026-12-11; use kGpt61Terra +// and kGpt6Luna) constexpr const char* kGpt5Mini = "gpt-5-mini"; constexpr const char* kGpt5Nano = "gpt-5-nano"; -// GPT-4.1 series (still current non-reasoning leaders) +// GPT-4.1 series (deprecated, shutdown: 2027-01-14; use kGpt6Luna) constexpr const char* kGpt41 = "gpt-4.1"; constexpr const char* kGpt41Mini = "gpt-4.1-mini"; @@ -42,7 +51,8 @@ constexpr const char* kGpt41Mini = "gpt-4.1-mini"; constexpr const char* kTextEmbedding3Small = "text-embedding-3-small"; constexpr const char* kTextEmbedding3Large = "text-embedding-3-large"; -/// Default model used when none is specified +/// Default model used when none is specified. It stays on GPT-5.6 because the +/// GPT-6 series does not support tool calling on Chat Completions. constexpr const char* kDefaultModel = kGpt56; } // namespace models diff --git a/src/providers/anthropic/anthropic_client.cpp b/src/providers/anthropic/anthropic_client.cpp index 4516235..9fa1bc6 100644 --- a/src/providers/anthropic/anthropic_client.cpp +++ b/src/providers/anthropic/anthropic_client.cpp @@ -77,14 +77,16 @@ std::vector AnthropicClient::supported_models() const { // snapshot variants (e.g. "claude-sonnet-4-5-20250929") are accepted by the // Anthropic API; list both so identifiers in `ai::anthropic::models::*` // resolve via `supports_model()`. - return {models::kClaudeFable5, models::kClaudeOpus5, - models::kClaudeOpus48, models::kClaudeSonnet5, - models::kClaudeOpus47, models::kClaudeSonnet46, - models::kClaudeOpus46, models::kClaudeHaiku45, - models::kClaudeHaiku45Snapshot, models::kClaudeOpus45, - models::kClaudeOpus45Snapshot, models::kClaudeSonnet45, - models::kClaudeSonnet45Snapshot, models::kClaudeOpus41, - models::kClaudeOpus41Snapshot}; + return {models::kClaudeFable52, models::kClaudeOpus55, + models::kClaudeSonnet55, models::kClaudeHaiku55, + models::kClaudeFable51, models::kClaudeFable5, + models::kClaudeOpus5, models::kClaudeOpus48, + models::kClaudeSonnet5, models::kClaudeOpus47, + models::kClaudeSonnet46, models::kClaudeOpus46, + models::kClaudeHaiku45, models::kClaudeHaiku45Snapshot, + models::kClaudeOpus45, models::kClaudeOpus45Snapshot, + models::kClaudeSonnet45, models::kClaudeSonnet45Snapshot, + models::kClaudeOpus41, models::kClaudeOpus41Snapshot}; } bool AnthropicClient::supports_model(const std::string& model_name) const { diff --git a/src/providers/anthropic/anthropic_request_builder.cpp b/src/providers/anthropic/anthropic_request_builder.cpp index f63fd09..504d015 100644 --- a/src/providers/anthropic/anthropic_request_builder.cpp +++ b/src/providers/anthropic/anthropic_request_builder.cpp @@ -99,9 +99,11 @@ nlohmann::json AnthropicRequestBuilder::build_request_json( // Add optional parameters // Recent Anthropic models reject sampling controls. Keep accepting the // provider-neutral options while omitting them for those model IDs. - constexpr std::array kSamplingRejectingModelPrefixes = { - models::kClaudeOpus5, models::kClaudeOpus48, models::kClaudeOpus47, - models::kClaudeFable5, models::kClaudeSonnet5}; + // The prefixes also cover the later point releases ("claude-opus-5-5", + // "claude-fable-5-2", "claude-sonnet-5-5", ...). + constexpr std::array kSamplingRejectingModelPrefixes = { + models::kClaudeOpus5, models::kClaudeOpus48, models::kClaudeOpus47, + models::kClaudeFable5, models::kClaudeSonnet5, models::kClaudeHaiku55}; const bool rejects_sampling_parameters = std::any_of( kSamplingRejectingModelPrefixes.begin(), kSamplingRejectingModelPrefixes.end(), [&options](const char* prefix) { diff --git a/src/providers/anthropic/anthropic_response_parser.cpp b/src/providers/anthropic/anthropic_response_parser.cpp index a78bbe1..4ad3e51 100644 --- a/src/providers/anthropic/anthropic_response_parser.cpp +++ b/src/providers/anthropic/anthropic_response_parser.cpp @@ -146,6 +146,11 @@ FinishReason AnthropicResponseParser::parse_stop_reason( if (reason == "tool_use") { return kFinishReasonToolCalls; } + if (reason == "refusal") { + // Safety classifiers declined the request (HTTP 200, details in + // `stop_details`). + return kFinishReasonContentFilter; + } return kFinishReasonStop; } diff --git a/src/providers/anthropic/anthropic_stream.cpp b/src/providers/anthropic/anthropic_stream.cpp index 5a3b6a6..14078bf 100644 --- a/src/providers/anthropic/anthropic_stream.cpp +++ b/src/providers/anthropic/anthropic_stream.cpp @@ -138,6 +138,8 @@ void AnthropicStreamImpl::process_sse_event(const std::string& data) { finish_reason_ = kFinishReasonLength; } else if (stop_reason == "tool_use") { finish_reason_ = kFinishReasonToolCalls; + } else if (stop_reason == "refusal") { + finish_reason_ = kFinishReasonContentFilter; } else if (!stop_reason.empty()) { finish_reason_ = kFinishReasonStop; } diff --git a/src/providers/openai/openai_client.cpp b/src/providers/openai/openai_client.cpp index ef52005..4f0e947 100644 --- a/src/providers/openai/openai_client.cpp +++ b/src/providers/openai/openai_client.cpp @@ -83,12 +83,15 @@ std::string OpenAIClient::provider_name() const { } std::vector OpenAIClient::supported_models() const { - return {// Current GPT-5 series + return {// GPT-6 series + models::kGpt62Astra, models::kGpt62Sol, models::kGpt61Terra, + models::kGpt6Luna, + // GPT-5 series models::kGpt56, models::kGpt56Sol, models::kGpt56Terra, models::kGpt56Luna, models::kGpt55, models::kGpt54, models::kGpt54Pro, models::kGpt54Mini, models::kGpt54Nano, models::kGpt5Mini, models::kGpt5Nano, - // Current GPT-4.1 series + // GPT-4.1 series models::kGpt41, models::kGpt41Mini}; } diff --git a/src/providers/openai/openai_request_builder.cpp b/src/providers/openai/openai_request_builder.cpp index 621243c..bef33e9 100644 --- a/src/providers/openai/openai_request_builder.cpp +++ b/src/providers/openai/openai_request_builder.cpp @@ -13,13 +13,28 @@ namespace openai { namespace { -// The lowest `reasoning_effort` a GPT-5 family model accepts on Chat +// The lowest `reasoning_effort` a GPT-5 or GPT-6 family model accepts on Chat // Completions, or nullopt when the parameter must be left out: the model is // not in the family, or it is a variant whose accepted values are fixed or // not known. An unsupported value fails the request with HTTP 400, so the // field is only sent where the value is known to be accepted. std::optional lowest_reasoning_effort( std::string_view model) { + if (model.starts_with("gpt-6")) { + // The pro and cyber variants have value sets of their own. + for (const std::string_view variant : {"-pro", "-cyber"}) { + if (model.find(variant) != std::string_view::npos) { + return std::nullopt; + } + } + // Every GPT-6 model accepts "low"; GPT-6.2 and later reject "none", which + // only GPT-6 Luna and GPT-6.1 Terra are documented to accept. + if (model.starts_with("gpt-6-luna") || model.starts_with("gpt-6.1-terra")) { + return "none"; + } + return "low"; + } + if (!model.starts_with("gpt-5")) { return std::nullopt; } @@ -141,13 +156,13 @@ nlohmann::json OpenAIRequestBuilder::build_request_json( } // Add optional parameters - // The GPT-5 family is reasoning-first on Chat Completions: it rejects - // sampling controls ("'temperature' does not support 0.0 with this model. - // Only the default (1) value is supported."). Keep accepting the + // The GPT-5 and GPT-6 families are reasoning-first on Chat Completions: they + // reject sampling controls ("'temperature' does not support 0.0 with this + // model. Only the default (1) value is supported."). Keep accepting the // provider-neutral options while omitting them for those model IDs, // mirroring the Anthropic builder. - const bool is_gpt5_family = options.model.starts_with("gpt-5"); - const bool rejects_sampling_parameters = is_gpt5_family; + const bool rejects_sampling_parameters = + options.model.starts_with("gpt-5") || options.model.starts_with("gpt-6"); const auto add_sampling_parameter = [&](const char* key, const std::optional& value) { if (!value) { @@ -181,7 +196,7 @@ nlohmann::json OpenAIRequestBuilder::build_request_json( request["seed"] = *options.seed; } - // Much of the GPT-5 family defaults to reasoning in Chat Completions. That + // The GPT-5 and GPT-6 families default to reasoning in Chat Completions. That // mode can consume the full completion budget on hidden reasoning without // producing user-visible text (acute with a small max_tokens), and on // GPT-5.6 it does not support function tools. The unified SDK currently diff --git a/tests/integration/anthropic_integration_test.cpp b/tests/integration/anthropic_integration_test.cpp index 83bb9ab..e09c32a 100644 --- a/tests/integration/anthropic_integration_test.cpp +++ b/tests/integration/anthropic_integration_test.cpp @@ -135,6 +135,8 @@ TEST_F(AnthropicIntegrationTest, DifferentModelSupport) { std::vector models_to_test = { ai::anthropic::models::kDefaultModel, + ai::anthropic::models::kClaudeOpus55, + ai::anthropic::models::kClaudeHaiku55, ai::anthropic::models::kClaudeHaiku45}; for (const auto& model : models_to_test) { @@ -278,7 +280,7 @@ TEST_F(AnthropicIntegrationTest, LargePromptHandling) { auto large_prompt = TestDataGenerator::createLargePrompt(2000); // ~2KB prompt - GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, large_prompt); + GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, large_prompt); auto result = client_->generate_text(options); TestAssertions::assertSuccess(result); @@ -299,7 +301,7 @@ TEST_F(AnthropicIntegrationTest, CustomBaseUrl) { auto custom_client = ai::anthropic::create_client(api_key, "https://api.anthropic.com"); - GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, + GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, "Test custom base URL"); auto result = custom_client.generate_text(options); @@ -313,7 +315,7 @@ TEST_F(AnthropicIntegrationTest, EmptyPrompt) { GTEST_SKIP() << "No ANTHROPIC_API_KEY environment variable set"; } - GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, ""); + GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, ""); // Empty prompt should be caught by validation EXPECT_FALSE(options.is_valid()); @@ -328,7 +330,7 @@ TEST_F(AnthropicIntegrationTest, VeryLongResponse) { GTEST_SKIP() << "No ANTHROPIC_API_KEY environment variable set"; } - GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, + GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, "Write a detailed explanation of quantum physics"); options.max_tokens = 500; // Reasonable limit for testing @@ -349,7 +351,8 @@ TEST_F(AnthropicIntegrationTest, NetworkTimeout) { // Note: This test documents timeout behavior but cannot reliably trigger it // with the real API under normal conditions - GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, "Simple test"); + GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, + "Simple test"); auto result = client_->generate_text(options); // Under normal conditions, this should succeed @@ -374,7 +377,7 @@ TEST_F(AnthropicIntegrationTest, NetworkFailure) { auto failing_client = ai::anthropic::create_client( api_key, "http://localhost:59999"); // Very unlikely port to be in use - GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, + GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, "Test network failure"); auto result = failing_client.generate_text(options); @@ -425,7 +428,7 @@ TEST_F(AnthropicIntegrationTest, MaxTokensRequired) { GTEST_SKIP() << "No ANTHROPIC_API_KEY environment variable set"; } - GenerateOptions options(ai::anthropic::models::kClaudeSonnet5, + GenerateOptions options(ai::anthropic::models::kClaudeSonnet55, "Tell me about artificial intelligence"); // Anthropic requires max_tokens to be set options.max_tokens = 100; @@ -444,7 +447,7 @@ TEST_F(AnthropicIntegrationTest, SystemMessageHandling) { // Anthropic has specific handling for system messages GenerateOptions options( - ai::anthropic::models::kClaudeSonnet5, + ai::anthropic::models::kClaudeSonnet55, "You are Claude, an AI assistant created by Anthropic.", "What is your name?"); options.max_tokens = 50; diff --git a/tests/integration/openai_integration_test.cpp b/tests/integration/openai_integration_test.cpp index cbabff3..ad9e243 100644 --- a/tests/integration/openai_integration_test.cpp +++ b/tests/integration/openai_integration_test.cpp @@ -133,8 +133,9 @@ TEST_F(OpenAIIntegrationTest, DifferentModelSupport) { GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; } - std::vector models_to_test = {ai::openai::models::kGpt56, - ai::openai::models::kGpt56Luna}; + std::vector models_to_test = { + ai::openai::models::kGpt56, ai::openai::models::kGpt56Luna, + ai::openai::models::kGpt62Sol, ai::openai::models::kGpt6Luna}; for (const auto& model : models_to_test) { if (!client_->supports_model(model)) { diff --git a/tests/unit/anthropic_client_test.cpp b/tests/unit/anthropic_client_test.cpp index aeab3da..0202a1c 100644 --- a/tests/unit/anthropic_client_test.cpp +++ b/tests/unit/anthropic_client_test.cpp @@ -94,6 +94,11 @@ TEST_F(AnthropicClientTest, ConstructorWithCustomRetryConfig) { TEST_F(AnthropicClientTest, SupportedModelsContainsExpectedModels) { auto models = client_->supported_models(); + EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeFable52)); + EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeOpus55)); + EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeSonnet55)); + EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeHaiku55)); + EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeFable51)); EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeFable5)); EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeOpus5)); EXPECT_THAT(models, testing::Contains(anthropic::models::kClaudeOpus48)); @@ -104,6 +109,7 @@ TEST_F(AnthropicClientTest, SupportedModelsContainsExpectedModels) { } TEST_F(AnthropicClientTest, SupportsValidModel) { + EXPECT_TRUE(client_->supports_model(anthropic::models::kDefaultModel)); EXPECT_TRUE(client_->supports_model(anthropic::models::kClaudeFable5)); EXPECT_TRUE(client_->supports_model(anthropic::models::kClaudeOpus5)); EXPECT_TRUE(client_->supports_model(anthropic::models::kClaudeOpus48)); @@ -170,8 +176,11 @@ TEST_F(AnthropicClientTest, ValidateOptionsValidation) { TEST_F(AnthropicClientTest, RecentModelsOmitUnsupportedSamplingParameters) { anthropic::AnthropicRequestBuilder builder; for (const auto* model : - {anthropic::models::kClaudeOpus48, anthropic::models::kClaudeOpus47, - anthropic::models::kClaudeFable5, anthropic::models::kClaudeSonnet5}) { + {anthropic::models::kClaudeFable52, anthropic::models::kClaudeFable51, + anthropic::models::kClaudeOpus55, anthropic::models::kClaudeSonnet55, + anthropic::models::kClaudeHaiku55, anthropic::models::kClaudeOpus48, + anthropic::models::kClaudeOpus47, anthropic::models::kClaudeFable5, + anthropic::models::kClaudeSonnet5}) { GenerateOptions options(model, "Hello"); options.temperature = 0.7; options.top_p = 0.8; @@ -232,6 +241,8 @@ TEST_F(AnthropicClientTest, TestStopReasonParsing) { EXPECT_EQ(client_->parse_stop_reason("max_tokens"), kFinishReasonLength); EXPECT_EQ(client_->parse_stop_reason("stop_sequence"), kFinishReasonStop); EXPECT_EQ(client_->parse_stop_reason("tool_use"), kFinishReasonToolCalls); + EXPECT_EQ(client_->parse_stop_reason("refusal"), + kFinishReasonContentFilter); EXPECT_EQ(client_->parse_stop_reason("unknown"), kFinishReasonStop); // Anthropic defaults unknown to stop } diff --git a/tests/unit/anthropic_stream_test.cpp b/tests/unit/anthropic_stream_test.cpp index ded11ba..747f78c 100644 --- a/tests/unit/anthropic_stream_test.cpp +++ b/tests/unit/anthropic_stream_test.cpp @@ -450,5 +450,17 @@ TEST_F(AnthropicStreamEventTypesTest, MessageStopEvent) { EXPECT_THAT(event_data, testing::HasSubstr("message_stop")); } +TEST_F(AnthropicStreamEventTest, MapsRefusalToContentFilter) { + anthropic::AnthropicStreamImpl stream; + stream.process_sse_chunk_for_testing( + "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":" + "\"refusal\"}}\n\n" + "data: {\"type\":\"message_stop\"}\n\n"); + + auto finish_event = stream.get_next_event(); + ASSERT_TRUE(finish_event.is_finish()); + EXPECT_EQ(finish_event.finish_reason, kFinishReasonContentFilter); +} + } // namespace test } // namespace ai diff --git a/tests/unit/openai_client_test.cpp b/tests/unit/openai_client_test.cpp index 3cac86b..ba65d0a 100644 --- a/tests/unit/openai_client_test.cpp +++ b/tests/unit/openai_client_test.cpp @@ -81,6 +81,10 @@ TEST_F(OpenAIClientTest, ConstructorWithHttpUrl) { TEST_F(OpenAIClientTest, SupportedModelsContainsExpectedModels) { auto models = client_->supported_models(); + EXPECT_THAT(models, testing::Contains(openai::models::kGpt62Astra)); + EXPECT_THAT(models, testing::Contains(openai::models::kGpt62Sol)); + EXPECT_THAT(models, testing::Contains(openai::models::kGpt61Terra)); + EXPECT_THAT(models, testing::Contains(openai::models::kGpt6Luna)); EXPECT_THAT(models, testing::Contains(openai::models::kGpt56)); EXPECT_THAT(models, testing::Contains(openai::models::kGpt56Sol)); EXPECT_THAT(models, testing::Contains(openai::models::kGpt56Terra)); @@ -154,20 +158,19 @@ TEST_F(OpenAIClientTest, Gpt5FamilyUsesChatCompletionsCompatibleReasoning) { openai::OpenAIRequestBuilder builder; // GPT-5.1 and later accept "none" and reject "minimal". - for (const auto* model : - {openai::models::kGpt56, openai::models::kGpt56Luna, - openai::models::kGpt55, openai::models::kGpt54, - openai::models::kGpt54Mini, openai::models::kGpt54Nano, "gpt-5.2", - "gpt-5.1"}) { + for (const auto* model : {openai::models::kGpt56, openai::models::kGpt56Luna, + openai::models::kGpt55, openai::models::kGpt54, + openai::models::kGpt54Mini, + openai::models::kGpt54Nano, "gpt-5.2", "gpt-5.1"}) { GenerateOptions options(model, "Use a tool"); EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "none") << model; } // The original GPT-5 models reject "none"; they get the "minimal" floor. - for (const auto* model : {"gpt-5", "gpt-5-2025-08-07", - openai::models::kGpt5Mini, - openai::models::kGpt5Nano}) { + for (const auto* model : + {"gpt-5", "gpt-5-2025-08-07", openai::models::kGpt5Mini, + openai::models::kGpt5Nano}) { GenerateOptions options(model, "Use a tool"); EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "minimal") @@ -175,6 +178,28 @@ TEST_F(OpenAIClientTest, Gpt5FamilyUsesChatCompletionsCompatibleReasoning) { } } +TEST_F(OpenAIClientTest, Gpt6FamilyUsesLowestAcceptedReasoningEffort) { + openai::OpenAIRequestBuilder builder; + + // GPT-6.2 rejects "none"; "low" is accepted by every GPT-6 model. + for (const auto* model : + {openai::models::kGpt62Astra, openai::models::kGpt62Sol, "gpt-6-sol"}) { + GenerateOptions options(model, "Hello"); + EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "low") + << model; + } + + for (const auto* model : + {openai::models::kGpt61Terra, openai::models::kGpt6Luna}) { + GenerateOptions options(model, "Hello"); + EXPECT_EQ(builder.build_request_json(options)["reasoning_effort"], "none") + << model; + } + + GenerateOptions cyber("gpt-6-cyber", "Hello"); + EXPECT_FALSE(builder.build_request_json(cyber).contains("reasoning_effort")); +} + TEST_F(OpenAIClientTest, ReasoningEffortIsOmittedWhereItsValuesAreNotKnown) { openai::OpenAIRequestBuilder builder; @@ -194,7 +219,8 @@ TEST_F(OpenAIClientTest, ReasoningEffortIsOmittedWhereItsValuesAreNotKnown) { TEST_F(OpenAIClientTest, Gpt5FamilyOmitsUnsupportedSamplingParameters) { openai::OpenAIRequestBuilder builder; for (const auto* model : - {openai::models::kGpt56, openai::models::kGpt56Terra, + {openai::models::kGpt62Sol, openai::models::kGpt6Luna, + openai::models::kGpt56, openai::models::kGpt56Terra, openai::models::kGpt55, openai::models::kGpt5Mini}) { GenerateOptions options(model, "Hello"); options.temperature = 0.0; From 01b88fa3aba9c4556b4660806422ca2f1076cddb Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 00:42:29 +0000 Subject: [PATCH 2/6] Format `openai_stream.cpp` with clang-format 18 (as in #63) Co-Authored-By: Claude Opus 5.5 --- src/providers/openai/openai_stream.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/providers/openai/openai_stream.cpp b/src/providers/openai/openai_stream.cpp index bf3ce39..105e9c8 100644 --- a/src/providers/openai/openai_stream.cpp +++ b/src/providers/openai/openai_stream.cpp @@ -45,13 +45,14 @@ void OpenAIStreamImpl::process_sse_line(std::string_view line) { if (delta.contains("reasoning_content") && !delta["reasoning_content"].is_null()) { - std::string content = delta["reasoning_content"].get(); ai::logger::log_debug("Received reasoning_content chunk - length: {}", content.length()); - //TODO: currently not passing content, needs revamping of StreamEvent constructor - push_event(StreamEvent(StreamEventType::kStreamEventTypeReasoningDelta)); - } + // TODO: currently not passing content, needs revamping of StreamEvent + // constructor + push_event( + StreamEvent(StreamEventType::kStreamEventTypeReasoningDelta)); + } if (delta.contains("tool_calls") && delta["tool_calls"].is_array()) { for (const auto& fragment : delta["tool_calls"]) { From e1fccd11ea341bc3fb222519029b79a288bf82c2 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 00:55:30 +0000 Subject: [PATCH 3/6] Add the OpenAI Responses API client The GPT-6 models (`gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6.1-terra`, `gpt-6-luna`) call tools only through the Responses API (`POST /v1/responses`), while the SDK only spoke Chat Completions. `ai::openai::create_responses_client` (with the same overloads as `create_client`, plus `try_create_responses_client`) creates a client with its own request builder, response parser, and SSE stream for the Responses API. `create_client` stays on Chat Completions, which OpenAI-compatible providers implement; neither falls back to the other API. Requests are stateless (`store: false`). The `reasoning` items that a reasoning model returns with its function calls must be sent back with the tool outputs, so the parser returns the assistant turn in `response_messages` with its items in their original order, carrying the reasoning items (and the item IDs of the function calls) as a new `ProviderContentPart`, which other providers ignore. The multi-step coordinator feeds that turn back as is when it carries the tool calls. The lowest accepted reasoning effort and the sampling parameter omission are shared with the Chat Completions builder. Closes: https://github.com/ClickHouse/ai-sdk-cpp/issues/44 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 5 + README.md | 48 ++ examples/CMakeLists.txt | 3 + examples/openai_responses.cpp | 109 ++++ include/ai/openai.h | 57 +- include/ai/types/message.h | 20 +- src/providers/openai/openai_client.cpp | 49 +- src/providers/openai/openai_client.h | 12 + src/providers/openai/openai_factory.cpp | 67 ++- src/providers/openai/openai_model_traits.cpp | 57 ++ src/providers/openai/openai_model_traits.h | 24 + .../openai/openai_request_builder.cpp | 59 +- .../openai/openai_responses_client.cpp | 68 +++ .../openai/openai_responses_client.h | 30 + .../openai_responses_request_builder.cpp | 248 ++++++++ .../openai/openai_responses_request_builder.h | 28 + .../openai_responses_response_parser.cpp | 183 ++++++ .../openai/openai_responses_response_parser.h | 40 ++ .../openai/openai_responses_stream.cpp | 176 ++++++ .../openai/openai_responses_stream.h | 39 ++ src/tools/multi_step_coordinator.cpp | 39 +- tests/CMakeLists.txt | 2 + .../openai_responses_integration_test.cpp | 290 ++++++++++ .../tool_calling_integration_test.cpp | 16 +- tests/unit/openai_responses_test.cpp | 538 ++++++++++++++++++ 25 files changed, 2100 insertions(+), 107 deletions(-) create mode 100644 examples/openai_responses.cpp create mode 100644 src/providers/openai/openai_model_traits.cpp create mode 100644 src/providers/openai/openai_model_traits.h create mode 100644 src/providers/openai/openai_responses_client.cpp create mode 100644 src/providers/openai/openai_responses_client.h create mode 100644 src/providers/openai/openai_responses_request_builder.cpp create mode 100644 src/providers/openai/openai_responses_request_builder.h create mode 100644 src/providers/openai/openai_responses_response_parser.cpp create mode 100644 src/providers/openai/openai_responses_response_parser.h create mode 100644 src/providers/openai/openai_responses_stream.cpp create mode 100644 src/providers/openai/openai_responses_stream.h create mode 100644 tests/integration/openai_responses_integration_test.cpp create mode 100644 tests/unit/openai_responses_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index bad5064..6c99325 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,6 +101,11 @@ set(OPENAI_SOURCES src/providers/openai/openai_response_parser.cpp src/providers/openai/openai_stream.cpp src/providers/openai/openai_factory.cpp + src/providers/openai/openai_model_traits.cpp + src/providers/openai/openai_responses_client.cpp + src/providers/openai/openai_responses_request_builder.cpp + src/providers/openai/openai_responses_response_parser.cpp + src/providers/openai/openai_responses_stream.cpp ) set(ANTHROPIC_SOURCES diff --git a/README.md b/README.md index c738420..93208d4 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,53 @@ int main() { } ``` +#### OpenAI Responses API + +`ai::openai::create_client` speaks Chat Completions, which OpenAI-compatible +providers implement too. The GPT-6 models (`kGpt62Astra`, `kGpt62Sol`, +`kGpt61Terra`, `kGpt6Luna`) call tools through the Responses API +(`POST /v1/responses`) only, so use `ai::openai::create_responses_client` for +them. It takes the same arguments as `create_client` and the same +`GenerateOptions`; neither client falls back to the other API. + +```cpp +#include +#include +#include + +// get_weather as in the Tool Calling example above + +int main() { + auto client = ai::openai::create_responses_client(); + + ai::GenerateOptions options(ai::openai::models::kGpt62Sol, + "What's the weather like in San Francisco?"); + options.tools = { + {"weather", ai::create_simple_tool( + "weather", "Get current weather for a location", + {{"location", "string"}}, get_weather)}}; + options.max_steps = 3; + + auto result = client.generate_text(options); + if (result) { + std::cout << result.text << std::endl; + } + return 0; +} +``` + +Requests are stateless (`store: false`), and the whole conversation is sent +with every request. When a reasoning model calls tools, the API requires its +`reasoning` items to be sent back with the tool results. They are returned in +`GenerateResult::response_messages` as `ai::ProviderContentPart`s, which the +multi-step loop (`max_steps > 1`) replays automatically, as do the next +requests when you append `response_messages` to your conversation. Other +providers ignore these parts. `system` becomes the `instructions` of the +request, `max_tokens` becomes `max_output_tokens` (it counts reasoning tokens +too), and `response_format` becomes `text.format`. The Responses API has no +`frequency_penalty`, `presence_penalty`, or `seed`; they are ignored with a +warning. See the [Responses API example](examples/openai_responses.cpp). + #### Async Tool Calling For long-running operations, you can define asynchronous tools: @@ -331,6 +378,7 @@ Check out our [examples directory](examples/) for more comprehensive usage examp - [Retry Configuration](examples/retry_config_example.cpp) - [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 - [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/examples/CMakeLists.txt b/examples/CMakeLists.txt index 875cd76..fa9908e 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -41,6 +41,9 @@ add_ai_example(retry_config_example retry_config_example.cpp) add_ai_example(test_openai test_openai.cpp) add_ai_example(test_anthropic test_anthropic.cpp) +# OpenAI Responses API example (tool calling with the GPT-6 models) +add_ai_example(openai_responses openai_responses.cpp) + # OpenRouter example (OpenAI-compatible) add_ai_example(openrouter_example openrouter_example.cpp) diff --git a/examples/openai_responses.cpp b/examples/openai_responses.cpp new file mode 100644 index 0000000..00732f8 --- /dev/null +++ b/examples/openai_responses.cpp @@ -0,0 +1,109 @@ +/** + * OpenAI Responses API Example - AI SDK C++ + * + * The GPT-6 models call tools through the Responses API only. This example + * creates a Responses API client with `ai::openai::create_responses_client` + * and shows: + * - a multi-step tool loop on GPT-6.2 Sol (the reasoning items of each step + * are replayed automatically along with the tool results) + * - continuing the conversation from `response_messages` + * - streaming + * + * Usage: + * export OPENAI_API_KEY=your_key_here + * ./openai_responses + */ + +#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::openai::try_create_responses_client(); + if (!client) { + std::cerr << "Set OPENAI_API_KEY to run this example\n"; + return 1; + } + std::cout << "Using " << client->config_info() << "\n\n"; + + // 1. Multi-step tool calling. + ai::GenerateOptions options( + ai::openai::models::kGpt62Sol, + "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"; + std::cout << "Tokens: " << result.usage.total_tokens << "\n\n"; + + // 2. Continue the conversation. `response_messages` holds the assistant + // turns, tool results, and reasoning items of the previous call. + ai::Messages conversation = {ai::Message::user(options.prompt)}; + conversation.insert(conversation.end(), result.response_messages.begin(), + result.response_messages.end()); + conversation.push_back(ai::Message::user("And what about in two hours?")); + + ai::GenerateOptions follow_up(ai::openai::models::kGpt62Sol, + std::move(conversation)); + follow_up.tools = options.tools; + follow_up.max_steps = 3; + auto follow_up_result = client->generate_text(follow_up); + if (!follow_up_result) { + std::cerr << "Error: " << follow_up_result.error_message() << "\n"; + return 1; + } + std::cout << "Follow-up: " << follow_up_result.text << "\n\n"; + + // 3. Streaming. + std::cout << "Streaming: "; + auto stream = client->stream_text(ai::StreamOptions(ai::GenerateOptions( + ai::openai::models::kGpt6Luna, "Write a haiku about rain."))); + 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; + } else if (event.is_finish()) { + break; + } + } + std::cout << "\n"; + return 0; +} diff --git a/include/ai/openai.h b/include/ai/openai.h index 7772c0f..b00aa6c 100644 --- a/include/ai/openai.h +++ b/include/ai/openai.h @@ -17,9 +17,10 @@ namespace openai { namespace models { /// Common OpenAI model identifiers -// GPT-6 series (current frontier family). On Chat Completions, which this -// SDK uses, these models reject sampling parameters and do not support tool -// calling (OpenAI serves their tool calling through the Responses API only). +// GPT-6 series (current frontier family). These models reject sampling +// parameters, and OpenAI serves their tool calling through the Responses API +// only: use them with `create_responses_client`. On Chat Completions +// (`create_client`) they generate text but cannot call tools. constexpr const char* kGpt62Astra = "gpt-6.2-astra"; constexpr const char* kGpt62Sol = "gpt-6.2-sol"; constexpr const char* kGpt61Terra = "gpt-6.1-terra"; @@ -55,6 +56,9 @@ constexpr const char* kTextEmbedding3Large = "text-embedding-3-large"; /// GPT-6 series does not support tool calling on Chat Completions. constexpr const char* kDefaultModel = kGpt56; +/// Default model of the Responses API clients (`create_responses_client`). +constexpr const char* kDefaultResponsesModel = kGpt62Sol; + } // namespace models /// Create an OpenAI client with default configuration @@ -89,5 +93,52 @@ Client create_client(const std::string& api_key, /// @note This is useful for chaining creation attempts with other providers std::optional try_create_client(); +/// The `create_responses_client` functions create OpenAI clients that use the +/// Responses API (`POST /v1/responses`) instead of Chat Completions. It is +/// required for tool calling with the GPT-6 models. The `create_client` +/// functions keep using Chat Completions, which is what OpenAI-compatible +/// providers (OpenRouter and others) implement; neither kind of client falls +/// back to the other API. +/// +/// Requests are stateless (`store: false`): nothing is stored on OpenAI's +/// side, and the conversation is replayed on every request. The `reasoning` +/// items of a reply are returned in `GenerateResult::response_messages` as +/// `ProviderContentPart`s, and replayed when those messages are sent back, +/// which the multi-step tool loop (`max_steps > 1`) does automatically. +/// `frequency_penalty`, `presence_penalty`, and `seed` are not supported by +/// the Responses API and are ignored with a warning. + +/// Create an OpenAI Responses API client +/// Reads API key from OPENAI_API_KEY environment variable +/// @return Configured OpenAI Responses API client +Client create_responses_client(); + +/// Create an OpenAI Responses API client with explicit API key +/// @param api_key OpenAI API key +/// @return Configured OpenAI Responses API client +Client create_responses_client(const std::string& api_key); + +/// Create an OpenAI Responses API client with a custom base URL +/// @param api_key OpenAI API key +/// @param base_url Custom base URL (for Responses-compatible APIs) +/// @return Configured OpenAI Responses API client +Client create_responses_client(const std::string& api_key, + const std::string& base_url); + +/// Create an OpenAI Responses API client with custom retry settings +/// @param api_key OpenAI API key +/// @param base_url Custom base URL (for Responses-compatible APIs) +/// @param retry_config Custom retry configuration +/// @return Configured OpenAI Responses API client +Client create_responses_client(const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config); + +/// Try to create an OpenAI Responses API client using environment variables +/// Reads API key from OPENAI_API_KEY environment variable +/// @return Optional client - has value if environment variable is set, empty +/// otherwise +std::optional try_create_responses_client(); + } // namespace openai } // namespace ai diff --git a/include/ai/types/message.h b/include/ai/types/message.h index f42ba4b..2189181 100644 --- a/include/ai/types/message.h +++ b/include/ai/types/message.h @@ -37,9 +37,25 @@ struct ToolResultContentPart { : tool_call_id(std::move(id)), result(std::move(r)), is_error(err) {} }; +/// Provider-specific state with no provider-neutral representation, such as +/// an OpenAI Responses API `reasoning` item. The provider named in `provider` +/// produced `data` and replays it in follow-up requests (for example in +/// `response_messages` fed back by the multi-step tool loop); every other +/// provider ignores the part. The text and tool calls of the same turn are +/// still carried as `TextContentPart` and `ToolCallContentPart`. +struct ProviderContentPart { + std::string provider; + JsonValue data; + + ProviderContentPart(std::string p, JsonValue d) + : provider(std::move(p)), data(std::move(d)) {} +}; + // Content part variant -using ContentPart = - std::variant; +using ContentPart = std::variant; // Message content is now a vector of content parts using MessageContent = std::vector; diff --git a/src/providers/openai/openai_client.cpp b/src/providers/openai/openai_client.cpp index 4f0e947..7c45bd5 100644 --- a/src/providers/openai/openai_client.cpp +++ b/src/providers/openai/openai_client.cpp @@ -8,46 +8,53 @@ #include #include +#include namespace ai { namespace openai { OpenAIClient::OpenAIClient(const std::string& api_key, const std::string& base_url) - : BaseProviderClient( - providers::ProviderConfig{ - .api_key = api_key, - .base_url = base_url, - .completions_endpoint_path = "/v1/chat/completions", - .embeddings_endpoint_path = "/v1/embeddings", - .auth_header_name = "Authorization", - .auth_header_prefix = "Bearer ", - .extra_headers = {}, - .retry_config = std::nullopt}, - std::make_unique(), - std::make_unique()) { - ai::logger::log_debug("OpenAI client initialized with base_url: {}", - base_url); -} + : OpenAIClient(api_key, + base_url, + "/v1/chat/completions", + std::nullopt, + std::make_unique(), + std::make_unique()) {} OpenAIClient::OpenAIClient(const std::string& api_key, const std::string& base_url, const retry::RetryConfig& retry_config) + : OpenAIClient(api_key, + base_url, + "/v1/chat/completions", + retry_config, + std::make_unique(), + std::make_unique()) {} + +OpenAIClient::OpenAIClient( + const std::string& api_key, + const std::string& base_url, + std::string completions_endpoint_path, + std::optional retry_config, + std::unique_ptr request_builder, + std::unique_ptr response_parser) : BaseProviderClient( providers::ProviderConfig{ .api_key = api_key, .base_url = base_url, - .completions_endpoint_path = "/v1/chat/completions", + .completions_endpoint_path = std::move(completions_endpoint_path), .embeddings_endpoint_path = "/v1/embeddings", .auth_header_name = "Authorization", .auth_header_prefix = "Bearer ", .extra_headers = {}, - .retry_config = retry_config}, - std::make_unique(), - std::make_unique()) { + .retry_config = std::move(retry_config)}, + std::move(request_builder), + std::move(response_parser)) { ai::logger::log_debug( - "OpenAI client initialized with base_url: {} and custom retry config", - base_url); + "OpenAI client initialized with base_url: {}, endpoint: {}{}", base_url, + config_.completions_endpoint_path, + config_.retry_config ? " and custom retry config" : ""); } StreamResult OpenAIClient::stream_text(const StreamOptions& options) { diff --git a/src/providers/openai/openai_client.h b/src/providers/openai/openai_client.h index 12df8bc..6166344 100644 --- a/src/providers/openai/openai_client.h +++ b/src/providers/openai/openai_client.h @@ -4,6 +4,8 @@ #include "ai/types/stream_options.h" #include "providers/base_provider_client.h" +#include +#include #include #include @@ -30,6 +32,16 @@ class OpenAIClient : public providers::BaseProviderClient { // 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; } + + protected: + /// For clients of the other OpenAI APIs, which share the models, the + /// authentication, and the embeddings endpoint. + OpenAIClient(const std::string& api_key, + const std::string& base_url, + std::string completions_endpoint_path, + std::optional retry_config, + std::unique_ptr request_builder, + std::unique_ptr response_parser); }; } // namespace openai diff --git a/src/providers/openai/openai_factory.cpp b/src/providers/openai/openai_factory.cpp index da9eb28..68571ca 100644 --- a/src/providers/openai/openai_factory.cpp +++ b/src/providers/openai/openai_factory.cpp @@ -2,6 +2,7 @@ #include "ai/errors.h" #include "openai_client.h" +#include "openai_responses_client.h" #include "utils/env_utils.h" #include @@ -29,37 +30,75 @@ std::string get_api_key_or_default(const std::string& api_key) { std::string get_base_url_or_default(const std::string& base_url) { return base_url.empty() ? kDefaultBaseUrl : base_url; } + +template +Client make_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))); +} + +template +Client make_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)); +} + +template +std::optional try_make_client() { + auto api_key = utils::non_empty_env("OPENAI_API_KEY"); + if (!api_key) { + return std::nullopt; + } + return Client(std::make_unique(*api_key, kDefaultBaseUrl)); +} } // namespace Client create_client() { - return Client(std::make_unique(get_api_key_or_default(""), - kDefaultBaseUrl)); + return make_client("", ""); } Client create_client(const std::string& api_key) { - return Client(std::make_unique(get_api_key_or_default(api_key), - kDefaultBaseUrl)); + return make_client(api_key, ""); } 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))); + return make_client(api_key, 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)); + return make_client(api_key, base_url, retry_config); } std::optional try_create_client() { - auto api_key = utils::non_empty_env("OPENAI_API_KEY"); - if (!api_key) { - return std::nullopt; - } - return Client(std::make_unique(*api_key, kDefaultBaseUrl)); + return try_make_client(); +} + +Client create_responses_client() { + return make_client("", ""); +} + +Client create_responses_client(const std::string& api_key) { + return make_client(api_key, ""); +} + +Client create_responses_client(const std::string& api_key, + const std::string& base_url) { + return make_client(api_key, base_url); +} + +Client create_responses_client(const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config) { + return make_client(api_key, base_url, retry_config); +} + +std::optional try_create_responses_client() { + return try_make_client(); } } // namespace openai diff --git a/src/providers/openai/openai_model_traits.cpp b/src/providers/openai/openai_model_traits.cpp new file mode 100644 index 0000000..94d508d --- /dev/null +++ b/src/providers/openai/openai_model_traits.cpp @@ -0,0 +1,57 @@ +#include "openai_model_traits.h" + +namespace ai { +namespace openai { + +bool is_reasoning_family(std::string_view model) { + return model.starts_with("gpt-5") || model.starts_with("gpt-6"); +} + +std::optional lowest_reasoning_effort( + std::string_view model) { + if (model.starts_with("gpt-6")) { + // The pro and cyber variants have value sets of their own. + for (const std::string_view variant : {"-pro", "-cyber"}) { + if (model.find(variant) != std::string_view::npos) { + return std::nullopt; + } + } + // Every GPT-6 model accepts "low"; GPT-6.2 and later reject "none", which + // only GPT-6 Luna and GPT-6.1 Terra are documented to accept. + if (model.starts_with("gpt-6-luna") || model.starts_with("gpt-6.1-terra")) { + return "none"; + } + return "low"; + } + + if (!model.starts_with("gpt-5")) { + return std::nullopt; + } + + // The pro variants only take the higher efforts (and are served by the + // Responses API only), the chat variants are the non-reasoning ChatGPT + // snapshots, and the codex variants have value sets of their own. + for (const std::string_view variant : {"-pro", "-chat", "-codex"}) { + if (model.find(variant) != std::string_view::npos) { + return std::nullopt; + } + } + + // GPT-5.1 and later ("gpt-5.1", "gpt-5.4-mini", "gpt-5.6-sol", ...) accept + // "none", which replaced "minimal": they reject "minimal". + if (model.starts_with("gpt-5.")) { + return "none"; + } + + // The original GPT-5 models ("gpt-5", "gpt-5-mini", "gpt-5-nano" and their + // dated snapshots) reject "none" ("Supported values are: 'minimal', 'low', + // 'medium', and 'high'."); "minimal" is their floor. + if (model == "gpt-5" || model.starts_with("gpt-5-")) { + return "minimal"; + } + + return std::nullopt; +} + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_model_traits.h b/src/providers/openai/openai_model_traits.h new file mode 100644 index 0000000..adcf5ef --- /dev/null +++ b/src/providers/openai/openai_model_traits.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +namespace ai { +namespace openai { + +/// Whether `model` belongs to the GPT-5 or GPT-6 family. These models are +/// reasoning-first and reject the sampling controls (`temperature`, `top_p`) +/// on both Chat Completions and the Responses API. +bool is_reasoning_family(std::string_view model); + +/// The lowest reasoning effort a GPT-5 or GPT-6 family model accepts, or +/// nullopt when the parameter must be left out: the model is not in the +/// family, or it is a variant whose accepted values are fixed or not known. +/// An unsupported value fails the request with HTTP 400, so the field is only +/// sent where the value is known to be accepted. The same values apply to +/// `reasoning_effort` on Chat Completions and `reasoning.effort` on the +/// Responses API. +std::optional lowest_reasoning_effort(std::string_view model); + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_request_builder.cpp b/src/providers/openai/openai_request_builder.cpp index bef33e9..f3f70f6 100644 --- a/src/providers/openai/openai_request_builder.cpp +++ b/src/providers/openai/openai_request_builder.cpp @@ -2,6 +2,7 @@ #include "ai/logger.h" #include "ai/openai.h" +#include "openai_model_traits.h" #include "utils/message_utils.h" #include @@ -11,61 +12,6 @@ namespace ai { namespace openai { -namespace { - -// The lowest `reasoning_effort` a GPT-5 or GPT-6 family model accepts on Chat -// Completions, or nullopt when the parameter must be left out: the model is -// not in the family, or it is a variant whose accepted values are fixed or -// not known. An unsupported value fails the request with HTTP 400, so the -// field is only sent where the value is known to be accepted. -std::optional lowest_reasoning_effort( - std::string_view model) { - if (model.starts_with("gpt-6")) { - // The pro and cyber variants have value sets of their own. - for (const std::string_view variant : {"-pro", "-cyber"}) { - if (model.find(variant) != std::string_view::npos) { - return std::nullopt; - } - } - // Every GPT-6 model accepts "low"; GPT-6.2 and later reject "none", which - // only GPT-6 Luna and GPT-6.1 Terra are documented to accept. - if (model.starts_with("gpt-6-luna") || model.starts_with("gpt-6.1-terra")) { - return "none"; - } - return "low"; - } - - if (!model.starts_with("gpt-5")) { - return std::nullopt; - } - - // The pro variants only take the higher efforts (and are served by the - // Responses API only), the chat variants are the non-reasoning ChatGPT - // snapshots, and the codex variants have value sets of their own. - for (const std::string_view variant : {"-pro", "-chat", "-codex"}) { - if (model.find(variant) != std::string_view::npos) { - return std::nullopt; - } - } - - // GPT-5.1 and later ("gpt-5.1", "gpt-5.4-mini", "gpt-5.6-sol", ...) accept - // "none", which replaced "minimal": they reject "minimal". - if (model.starts_with("gpt-5.")) { - return "none"; - } - - // The original GPT-5 models ("gpt-5", "gpt-5-mini", "gpt-5-nano" and their - // dated snapshots) reject "none" ("Supported values are: 'minimal', 'low', - // 'medium', and 'high'."); "minimal" is their floor. - if (model == "gpt-5" || model.starts_with("gpt-5-")) { - return "minimal"; - } - - return std::nullopt; -} - -} // namespace - nlohmann::json OpenAIRequestBuilder::build_request_json( const GenerateOptions& options) { nlohmann::json request{{"model", options.model}, @@ -161,8 +107,7 @@ nlohmann::json OpenAIRequestBuilder::build_request_json( // model. Only the default (1) value is supported."). Keep accepting the // provider-neutral options while omitting them for those model IDs, // mirroring the Anthropic builder. - const bool rejects_sampling_parameters = - options.model.starts_with("gpt-5") || options.model.starts_with("gpt-6"); + const bool rejects_sampling_parameters = is_reasoning_family(options.model); const auto add_sampling_parameter = [&](const char* key, const std::optional& value) { if (!value) { diff --git a/src/providers/openai/openai_responses_client.cpp b/src/providers/openai/openai_responses_client.cpp new file mode 100644 index 0000000..076e216 --- /dev/null +++ b/src/providers/openai/openai_responses_client.cpp @@ -0,0 +1,68 @@ +#include "openai_responses_client.h" + +#include "ai/logger.h" +#include "ai/openai.h" +#include "openai_responses_request_builder.h" +#include "openai_responses_response_parser.h" +#include "openai_responses_stream.h" + +#include + +namespace ai { +namespace openai { + +namespace { +constexpr const char* kResponsesEndpointPath = "/v1/responses"; +} // namespace + +OpenAIResponsesClient::OpenAIResponsesClient(const std::string& api_key, + const std::string& base_url) + : OpenAIClient(api_key, + base_url, + kResponsesEndpointPath, + std::nullopt, + std::make_unique(), + std::make_unique()) {} + +OpenAIResponsesClient::OpenAIResponsesClient( + const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config) + : OpenAIClient(api_key, + base_url, + kResponsesEndpointPath, + retry_config, + std::make_unique(), + std::make_unique()) {} + +StreamResult OpenAIResponsesClient::stream_text(const StreamOptions& options) { + ai::logger::log_debug( + "Starting Responses API streaming - model: {}, prompt length: {}", + options.model, options.prompt.length()); + + auto request_json = request_builder_->build_request_json(options); + // `response.completed` carries the usage, no stream options are needed. + request_json["stream"] = true; + + auto headers = request_builder_->build_headers(config_); + headers.emplace("Accept", "text/event-stream"); + + auto impl = std::make_unique(); + impl->start_stream(config_.base_url + config_.completions_endpoint_path, + headers, request_json); + + ai::logger::log_info("Responses API streaming started - model: {}", + options.model); + return StreamResult(std::move(impl)); +} + +std::string OpenAIResponsesClient::config_info() const { + return "OpenAI Responses API (base_url: " + config_.base_url + ")"; +} + +std::string OpenAIResponsesClient::default_model() const { + return models::kDefaultResponsesModel; +} + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_responses_client.h b/src/providers/openai/openai_responses_client.h new file mode 100644 index 0000000..f040c8c --- /dev/null +++ b/src/providers/openai/openai_responses_client.h @@ -0,0 +1,30 @@ +#pragma once + +#include "ai/retry/retry_policy.h" +#include "ai/types/stream_options.h" +#include "openai_client.h" + +#include + +namespace ai { +namespace openai { + +/// OpenAI client speaking the Responses API (`POST /v1/responses`) instead of +/// Chat Completions. Embeddings still use `/v1/embeddings`. +class OpenAIResponsesClient : public OpenAIClient { + public: + explicit OpenAIResponsesClient( + const std::string& api_key, + const std::string& base_url = "https://api.openai.com"); + + OpenAIResponsesClient(const std::string& api_key, + const std::string& base_url, + const retry::RetryConfig& retry_config); + + StreamResult stream_text(const StreamOptions& options) override; + std::string config_info() const override; + std::string default_model() const override; +}; + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_responses_request_builder.cpp b/src/providers/openai/openai_responses_request_builder.cpp new file mode 100644 index 0000000..d6bca25 --- /dev/null +++ b/src/providers/openai/openai_responses_request_builder.cpp @@ -0,0 +1,248 @@ +#include "openai_responses_request_builder.h" + +#include "ai/logger.h" +#include "openai_model_traits.h" +#include "utils/message_utils.h" + +#include +#include +#include +#include + +namespace ai { +namespace openai { + +namespace { + +nlohmann::json make_text_message(MessageRole role, std::string text) { + return {{"type", "message"}, + {"role", utils::message_role_to_string(role)}, + {"content", std::move(text)}}; +} + +/// The `id` of the `function_call` output item each tool call came from, by +/// `call_id`. The parser records them as `ProviderContentPart`s; replaying the +/// item IDs keeps the calls paired with the `reasoning` items before them. +std::map function_call_item_ids( + const Message& message) { + std::map ids; + for (const auto& part : message.content) { + const auto* provider_part = std::get_if(&part); + if (provider_part == nullptr || + provider_part->provider != kResponsesProviderName) { + continue; + } + const auto& data = provider_part->data; + if (data.value("type", "") == "function_call" && data.contains("id") && + data.contains("call_id")) { + ids[data["call_id"].get()] = data["id"].get(); + } + } + return ids; +} + +/// Append the items of an assistant turn in their original order: text as +/// assistant messages, tool calls as `function_call` items, and the replayed +/// provider items (`reasoning`) verbatim. +void append_assistant_items(const Message& message, nlohmann::json& input) { + const auto item_ids = function_call_item_ids(message); + std::string pending_text; + const auto flush_text = [&]() { + if (!pending_text.empty()) { + input.push_back( + make_text_message(kMessageRoleAssistant, std::move(pending_text))); + pending_text.clear(); + } + }; + + for (const auto& part : message.content) { + if (const auto* text_part = std::get_if(&part)) { + pending_text += text_part->text; + } else if (const auto* tool_call = std::get_if(&part)) { + flush_text(); + nlohmann::json item{{"type", "function_call"}, + {"call_id", tool_call->id}, + {"name", tool_call->tool_name}, + {"arguments", tool_call->arguments.dump()}}; + if (const auto it = item_ids.find(tool_call->id); it != item_ids.end()) { + item["id"] = it->second; + } + input.push_back(std::move(item)); + } else if (const auto* provider_part = + std::get_if(&part)) { + // Function call items are replayed from their ToolCallContentPart above. + if (provider_part->provider != kResponsesProviderName || + provider_part->data.value("type", "") == "function_call") { + continue; + } + flush_text(); + input.push_back(provider_part->data); + } + } + flush_text(); +} + +nlohmann::json build_input(const GenerateOptions& options) { + nlohmann::json input = nlohmann::json::array(); + + if (options.messages.empty()) { + if (!options.prompt.empty()) { + input.push_back(make_text_message(kMessageRoleUser, options.prompt)); + } + return input; + } + + for (const auto& message : options.messages) { + if (message.has_tool_results()) { + for (const auto& result : message.get_tool_results()) { + input.push_back( + {{"type", "function_call_output"}, + {"call_id", result.tool_call_id}, + {"output", result.is_error ? "Error: " + result.result.dump() + : result.result.dump()}}); + } + continue; + } + + if (message.role == kMessageRoleAssistant) { + append_assistant_items(message, input); + continue; + } + + auto text = message.get_text(); + if (!text.empty()) { + input.push_back(make_text_message(message.role, std::move(text))); + } + } + return input; +} + +/// Chat Completions nests a JSON schema under `json_schema`; `text.format` +/// carries its fields at the top level. Formats already in the Responses shape +/// (`text`, `json_object`, or a flat `json_schema`) pass through unchanged. +nlohmann::json to_text_format(const nlohmann::json& response_format) { + if (response_format.is_object() && + response_format.value("type", "") == "json_schema" && + response_format.contains("json_schema") && + response_format["json_schema"].is_object()) { + auto format = response_format["json_schema"]; + format["type"] = "json_schema"; + return format; + } + return response_format; +} + +} // namespace + +nlohmann::json OpenAIResponsesRequestBuilder::build_request_json( + const GenerateOptions& options) { + nlohmann::json request{{"model", options.model}, + {"input", build_input(options)}, + // Stateless: every request replays the whole + // conversation, so nothing has to be stored. + {"store", false}}; + + if (!options.system.empty()) { + request["instructions"] = options.system; + } + + // With `store: false` the API returns the `reasoning` items with their + // `encrypted_content` by default, which is what lets them be replayed; the + // legacy `include: ["reasoning.encrypted_content"]` is not needed. + const bool reasoning_model = is_reasoning_family(options.model); + + if (options.response_format) { + request["text"] = {{"format", to_text_format(*options.response_format)}}; + } + + // The GPT-5 and GPT-6 families reject sampling controls; see the Chat + // Completions builder. + const auto add_sampling_parameter = [&](const char* key, + const std::optional& value) { + if (!value) { + return; + } + if (reasoning_model) { + ai::logger::log_warn( + "Ignoring {} for {} because the model does not support " + "sampling parameters", + key, options.model); + } else { + request[key] = *value; + } + }; + add_sampling_parameter("temperature", options.temperature); + add_sampling_parameter("top_p", options.top_p); + + // The Responses API has no `frequency_penalty`, `presence_penalty`, or + // `seed`; sending them fails the request with "Unknown parameter". + const auto warn_unsupported = [&](const char* key, bool is_set) { + if (is_set) { + ai::logger::log_warn( + "Ignoring {} because the OpenAI Responses API does not support it", + key); + } + }; + warn_unsupported("frequency_penalty", options.frequency_penalty.has_value()); + warn_unsupported("presence_penalty", options.presence_penalty.has_value()); + warn_unsupported("seed", options.seed.has_value()); + + if (options.max_tokens) { + request["max_output_tokens"] = *options.max_tokens; + } + + // Use the lowest reasoning effort the model accepts, like the Chat + // Completions builder, so that the provider-neutral options keep their + // latency and token budget (`max_tokens` covers reasoning tokens too). + if (const auto effort = lowest_reasoning_effort(options.model)) { + request["reasoning"] = {{"effort", std::string(*effort)}}; + } + + if (options.has_tools()) { + nlohmann::json tools = 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; + } + // Without `strict` the API attempts strict mode, which requires every + // property to be listed in `required` and `additionalProperties: false`. + // Keep the non-strict semantics of Chat Completions instead. + tools.push_back({{"type", "function"}, + {"name", tool_name}, + {"description", it->second.description}, + {"parameters", it->second.parameters_schema}, + {"strict", false}}); + } + + if (!tools.empty()) { + ai::logger::log_debug("Added {} tools with choice: {}", tools.size(), + options.tool_choice.to_string()); + request["tools"] = std::move(tools); + + switch (options.tool_choice.type) { + case ToolChoiceType::kAuto: + request["tool_choice"] = "auto"; + break; + case ToolChoiceType::kRequired: + request["tool_choice"] = "required"; + break; + case ToolChoiceType::kNone: + request["tool_choice"] = "none"; + break; + case ToolChoiceType::kSpecific: + if (options.tool_choice.tool_name) { + request["tool_choice"] = { + {"type", "function"}, + {"name", *options.tool_choice.tool_name}}; + } + break; + } + } + } + + return request; +} + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_responses_request_builder.h b/src/providers/openai/openai_responses_request_builder.h new file mode 100644 index 0000000..3fd561b --- /dev/null +++ b/src/providers/openai/openai_responses_request_builder.h @@ -0,0 +1,28 @@ +#pragma once + +#include "openai_request_builder.h" + +#include + +namespace ai { +namespace openai { + +/// Provider name of the `ProviderContentPart`s that the Responses API parser +/// produces and the Responses API request builder replays. +inline constexpr const char* kResponsesProviderName = "openai.responses"; + +/// Builds `POST /v1/responses` requests. Embedding requests and headers are +/// shared with the Chat Completions builder. +/// +/// Requests are stateless (`store: false`): the conversation, including the +/// `reasoning` items of earlier turns (carried as `ProviderContentPart`s), is +/// replayed in `input` on every request instead of being referenced by +/// `previous_response_id`. +class OpenAIResponsesRequestBuilder : public OpenAIRequestBuilder { + public: + using OpenAIRequestBuilder::build_request_json; + nlohmann::json build_request_json(const GenerateOptions& options) override; +}; + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_responses_response_parser.cpp b/src/providers/openai/openai_responses_response_parser.cpp new file mode 100644 index 0000000..024d27a --- /dev/null +++ b/src/providers/openai/openai_responses_response_parser.cpp @@ -0,0 +1,183 @@ +#include "openai_responses_response_parser.h" + +#include "ai/logger.h" +#include "openai_responses_request_builder.h" + +#include + +namespace ai { +namespace openai { + +namespace { + +std::string string_field(const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + if (it == object.end() || !it->is_string()) { + return ""; + } + return it->get(); +} + +} // namespace + +Usage OpenAIResponsesResponseParser::parse_usage(const nlohmann::json& usage) { + Usage result; + if (!usage.is_object()) { + return result; + } + result.prompt_tokens = usage.value("input_tokens", 0); + result.completion_tokens = usage.value("output_tokens", 0); + result.total_tokens = usage.value("total_tokens", 0); + return result; +} + +std::optional OpenAIResponsesResponseParser::parse_finish_reason( + const nlohmann::json& response, + bool has_function_calls, + std::string& error) { + const auto status = string_field(response, "status"); + + if (status == "completed") { + return has_function_calls ? kFinishReasonToolCalls : kFinishReasonStop; + } + + if (status == "incomplete") { + std::string reason; + if (const auto it = response.find("incomplete_details"); + it != response.end() && it->is_object()) { + reason = string_field(*it, "reason"); + } + if (reason == "max_output_tokens") { + return kFinishReasonLength; + } + if (reason == "content_filter") { + return kFinishReasonContentFilter; + } + error = "OpenAI response incomplete: " + + (reason.empty() ? std::string("unknown reason") : reason); + return std::nullopt; + } + + if (status == "failed") { + error = "OpenAI response failed"; + if (const auto it = response.find("error"); + it != response.end() && it->is_object()) { + const auto code = string_field(*it, "code"); + const auto message = string_field(*it, "message"); + if (!code.empty()) { + error += " (" + code + ")"; + } + if (!message.empty()) { + error += ": " + message; + } + } + return std::nullopt; + } + + error = "OpenAI response has unexpected status: " + + (status.empty() ? std::string("") : status); + return std::nullopt; +} + +GenerateResult OpenAIResponsesResponseParser::parse_success_completion_response( + const nlohmann::json& response) { + ai::logger::log_debug("Parsing OpenAI Responses API response"); + + GenerateResult result; + result.id = string_field(response, "id"); + result.model = string_field(response, "model"); + if (const auto it = response.find("created_at"); + it != response.end() && it->is_number()) { + result.created = it->get(); + } + if (const auto it = response.find("usage"); it != response.end()) { + result.usage = parse_usage(*it); + } + result.provider_metadata = response.dump(); + + // The assistant turn, with the output items in their original order. + MessageContent turn; + + if (const auto output = response.find("output"); + output != response.end() && output->is_array()) { + for (const auto& item : *output) { + const auto type = string_field(item, "type"); + + if (type == "message") { + std::string text; + if (const auto content = item.find("content"); + content != item.end() && content->is_array()) { + for (const auto& part : *content) { + const auto part_type = string_field(part, "type"); + if (part_type == "output_text") { + text += string_field(part, "text"); + } else if (part_type == "refusal") { + text += string_field(part, "refusal"); + } + } + } + if (!text.empty()) { + result.text += text; + turn.emplace_back(TextContentPart{std::move(text)}); + } + } else if (type == "function_call") { + const auto call_id = string_field(item, "call_id"); + const auto name = string_field(item, "name"); + const auto arguments_text = string_field(item, "arguments"); + JsonValue arguments; + try { + arguments = arguments_text.empty() + ? JsonValue::object() + : JsonValue::parse(arguments_text); + } catch (const nlohmann::json::exception& e) { + return GenerateResult("Failed to parse arguments of the " + name + + " function call: " + e.what()); + } + + if (const auto item_id = string_field(item, "id"); !item_id.empty()) { + turn.emplace_back(ProviderContentPart{ + kResponsesProviderName, {{"type", "function_call"}, + {"id", item_id}, + {"call_id", call_id}}}); + } + turn.emplace_back(ToolCallContentPart{call_id, name, arguments}); + result.tool_calls.emplace_back(call_id, name, std::move(arguments)); + ai::logger::log_debug("Parsed function call: {} with args: {}", name, + arguments_text); + } else if (type == "reasoning") { + // Reasoning items must accompany the function calls they led to when + // the outputs are sent back; keep them for replay. + turn.emplace_back(ProviderContentPart{kResponsesProviderName, item}); + } else { + ai::logger::log_debug("Ignoring Responses API output item of type: {}", + type); + } + } + } + + std::string error; + const auto finish_reason = + parse_finish_reason(response, !result.tool_calls.empty(), error); + if (!finish_reason) { + ai::logger::log_error("{}", error); + result.error = std::move(error); + result.finish_reason = kFinishReasonError; + return result; + } + result.finish_reason = *finish_reason; + + // A turn of reasoning alone (cut off by `max_output_tokens`) is not kept: a + // replayed `reasoning` item has to be followed by the item it led to. + 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 Responses API response - text length: {}, function calls: {}", + result.text.length(), result.tool_calls.size()); + return result; +} + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_responses_response_parser.h b/src/providers/openai/openai_responses_response_parser.h new file mode 100644 index 0000000..ef43a5a --- /dev/null +++ b/src/providers/openai/openai_responses_response_parser.h @@ -0,0 +1,40 @@ +#pragma once + +#include "openai_response_parser.h" + +#include +#include + +#include + +namespace ai { +namespace openai { + +/// Parses `POST /v1/responses` replies. Errors and embeddings are shared with +/// the Chat Completions parser. +/// +/// The assistant turn is returned in `response_messages` with its items in +/// their original order: text as `TextContentPart`, function calls as +/// `ToolCallContentPart`, and the items that have to be replayed verbatim +/// (`reasoning`, and the item IDs of the function calls) as +/// `ProviderContentPart`s named `kResponsesProviderName`. +class OpenAIResponsesResponseParser : public OpenAIResponseParser { + public: + GenerateResult parse_success_completion_response( + const nlohmann::json& response) override; + + /// Token usage of a Responses API `usage` object. + static Usage parse_usage(const nlohmann::json& usage); + + /// The finish reason of a response with the given `status` and + /// `incomplete_details`, or nullopt when the response did not finish + /// (failed, cancelled, still in progress, or incomplete for a reason without + /// a finish reason), in which case `error` describes why. + static std::optional parse_finish_reason( + const nlohmann::json& response, + bool has_function_calls, + std::string& error); +}; + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_responses_stream.cpp b/src/providers/openai/openai_responses_stream.cpp new file mode 100644 index 0000000..af3a205 --- /dev/null +++ b/src/providers/openai/openai_responses_stream.cpp @@ -0,0 +1,176 @@ +#include "openai_responses_stream.h" + +#include "ai/logger.h" +#include "openai_responses_response_parser.h" + +#include +#include + +namespace ai { +namespace openai { + +namespace { + +std::string string_field(const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + if (it == object.end() || !it->is_string()) { + return ""; + } + return it->get(); +} + +} // namespace + +OpenAIResponsesStreamImpl::~OpenAIResponsesStreamImpl() { + // Join before this class's state is destroyed; the stream thread calls + // process_sse_line. + stop_stream(); +} + +void OpenAIResponsesStreamImpl::reset_stream_state() { + has_function_calls_ = false; + finished_ = false; +} + +void OpenAIResponsesStreamImpl::process_sse_line(std::string_view line) { + // Every `data:` payload names its event in `type`, so the `event:` lines + // that precede them carry nothing extra. + if (!line.starts_with("data:")) { + return; + } + auto data = line.substr(5); + if (data.starts_with(' ')) { + data.remove_prefix(1); + } + if (finished_ || data.empty()) { + return; + } + + nlohmann::json event; + try { + event = nlohmann::json::parse(data); + } catch (const nlohmann::json::exception& e) { + fail("Failed to parse Responses API stream event: " + + std::string(e.what())); + return; + } + handle_event(event); +} + +void OpenAIResponsesStreamImpl::handle_event(const nlohmann::json& event) { + const auto type = string_field(event, "type"); + + if (type == "response.output_text.delta" || + type == "response.refusal.delta") { + auto delta = string_field(event, "delta"); + if (!delta.empty()) { + push_event(StreamEvent(std::move(delta))); + } + return; + } + + if (type == "response.output_item.added" || + type == "response.output_item.done") { + const auto item_it = event.find("item"); + if (item_it == event.end() || !item_it->is_object() || + string_field(*item_it, "type") != "function_call") { + return; + } + const auto index = event.value("output_index", std::size_t{0}); + auto& pending = pending_tool_calls_[index]; + pending.id = string_field(*item_it, "call_id"); + pending.name = string_field(*item_it, "name"); + if (const auto arguments = string_field(*item_it, "arguments"); + !arguments.empty() || type == "response.output_item.done") { + pending.arguments = arguments; + } + has_function_calls_ = true; + if (type == "response.output_item.done") { + flush_pending_tool_call(index); + } + return; + } + + if (type == "response.function_call_arguments.delta") { + const auto index = event.value("output_index", std::size_t{0}); + pending_tool_calls_[index].arguments += string_field(event, "delta"); + return; + } + + if (type == "response.function_call_arguments.done") { + const auto index = event.value("output_index", std::size_t{0}); + pending_tool_calls_[index].arguments = string_field(event, "arguments"); + return; + } + + if (type == "response.completed" || type == "response.incomplete" || + type == "response.failed") { + const auto response_it = event.find("response"); + if (response_it == event.end() || !response_it->is_object()) { + fail("Responses API stream event " + type + " has no response"); + return; + } + finish_response(*response_it); + return; + } + + if (type == "error") { + std::string message = "OpenAI stream error"; + if (const auto code = string_field(event, "code"); !code.empty()) { + message += " (" + code + ")"; + } + if (const auto text = string_field(event, "message"); !text.empty()) { + message += ": " + text; + } + fail(message); + return; + } + + // Lifecycle (`response.created`, `response.in_progress`, ...), content part, + // and reasoning summary events carry nothing that is streamed. +} + +void OpenAIResponsesStreamImpl::finish_response( + const nlohmann::json& response) { + if (const auto usage_it = response.find("usage"); + usage_it != response.end() && usage_it->is_object()) { + usage_ = OpenAIResponsesResponseParser::parse_usage(*usage_it); + } + + std::string error; + const auto finish_reason = OpenAIResponsesResponseParser::parse_finish_reason( + response, has_function_calls_, error); + if (!finish_reason) { + fail(error); + return; + } + + finish_reason_ = *finish_reason; + flush_all_pending_tool_calls(); + finished_ = true; + if (usage_) { + ai::logger::log_info( + "Stream completed - tokens used: {} prompt, {} completion, {} total", + usage_->prompt_tokens, usage_->completion_tokens, + usage_->total_tokens); + } + mark_complete(); +} + +void OpenAIResponsesStreamImpl::fail(const std::string& message) { + ai::logger::log_error("{}", message); + pending_tool_calls_.clear(); + finished_ = true; + note_stream_error(); + push_event(create_error_event(message)); + mark_complete(); +} + +void OpenAIResponsesStreamImpl::finalize_stream() { + if (!finished_) { + fail("Responses API stream ended without a terminal response event"); + } +} + +} // namespace openai +} // namespace ai diff --git a/src/providers/openai/openai_responses_stream.h b/src/providers/openai/openai_responses_stream.h new file mode 100644 index 0000000..bac6844 --- /dev/null +++ b/src/providers/openai/openai_responses_stream.h @@ -0,0 +1,39 @@ +#pragma once + +#include "providers/http_sse_stream.h" + +#include + +#include + +namespace ai { +namespace openai { + +/// Translates the server-sent events of a streaming `POST /v1/responses` +/// request: text deltas, function calls (emitted when their output item is +/// done), and the terminal `response.completed`, `response.incomplete`, +/// `response.failed`, or `error` event. +class OpenAIResponsesStreamImpl : public providers::streaming::HttpSseStream { + public: + OpenAIResponsesStreamImpl() + : HttpSseStream({.default_path = "/v1/responses", + .connection_timeout_seconds = 30, + // 5 minutes for long generations + .read_timeout_seconds = 300}) {} + ~OpenAIResponsesStreamImpl() override; + + private: + void reset_stream_state() override; + void process_sse_line(std::string_view line) override; + void finalize_stream() override; + + void handle_event(const nlohmann::json& event); + void finish_response(const nlohmann::json& response); + void fail(const std::string& message); + + bool has_function_calls_ = false; + bool finished_ = false; +}; + +} // namespace openai +} // namespace ai diff --git a/src/tools/multi_step_coordinator.cpp b/src/tools/multi_step_coordinator.cpp index f655968..6c2bf80 100644 --- a/src/tools/multi_step_coordinator.cpp +++ b/src/tools/multi_step_coordinator.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -11,10 +12,28 @@ namespace { // its contract of holding the complete conversation continuation. void append_terminal_assistant_reply(const ai::GenerateResult& step_result, ai::Messages& response_messages) { - if (!step_result.text.empty()) { + if (!step_result.response_messages.empty()) { + response_messages.insert(response_messages.end(), + step_result.response_messages.begin(), + step_result.response_messages.end()); + } else if (!step_result.text.empty()) { response_messages.push_back(ai::Message::assistant(step_result.text)); } } + +// Whether the provider returned the complete assistant turn, tool calls +// included, in the step's response_messages. Providers whose replies carry +// state the next request has to replay (the `reasoning` items of the OpenAI +// Responses API, see `ProviderContentPart`) do so; that turn is fed back as is +// instead of being rebuilt from the text and the tool calls. +bool has_provider_tool_call_turn(const ai::GenerateResult& step_result) { + return std::any_of( + step_result.response_messages.begin(), + step_result.response_messages.end(), [](const ai::Message& message) { + return message.role == ai::kMessageRoleAssistant && + message.has_tool_calls(); + }); +} } // namespace namespace ai { @@ -136,13 +155,19 @@ GenerateResult MultiStepCoordinator::execute_multi_step( // Append assistant turn (text + tool calls) and tool result messages to // the running accumulator. Next iteration's input messages are rebuilt // from `initial_messages + response_messages` at the top of the loop. - std::vector tool_call_contents; - tool_call_contents.reserve(step_result.tool_calls.size()); - for (const auto& tc : step_result.tool_calls) { - tool_call_contents.emplace_back(tc.id, tc.tool_name, tc.arguments); + if (has_provider_tool_call_turn(step_result)) { + response_messages.insert(response_messages.end(), + step_result.response_messages.begin(), + step_result.response_messages.end()); + } else { + std::vector tool_call_contents; + tool_call_contents.reserve(step_result.tool_calls.size()); + for (const auto& tc : step_result.tool_calls) { + tool_call_contents.emplace_back(tc.id, tc.tool_name, tc.arguments); + } + response_messages.push_back(Message::assistant_with_tools( + step_result.text, tool_call_contents)); } - response_messages.push_back( - Message::assistant_with_tools(step_result.text, tool_call_contents)); Messages tool_messages = tool_results_to_messages(step_result.tool_calls, tool_results); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 7ece7c7..bae1d2a 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -8,9 +8,11 @@ add_executable(ai_tests unit/anthropic_stream_test.cpp unit/openai_embeddings_test.cpp unit/multi_step_coordinator_test.cpp + unit/openai_responses_test.cpp # Integration tests integration/openai_integration_test.cpp + integration/openai_responses_integration_test.cpp integration/anthropic_integration_test.cpp integration/tool_calling_integration_test.cpp integration/clickhouse_integration_test.cpp diff --git a/tests/integration/openai_responses_integration_test.cpp b/tests/integration/openai_responses_integration_test.cpp new file mode 100644 index 0000000..e1ec935 --- /dev/null +++ b/tests/integration/openai_responses_integration_test.cpp @@ -0,0 +1,290 @@ +#include "../utils/test_fixtures.h" +#include "ai/openai.h" +#include "ai/tools.h" +#include "ai/types/generate_options.h" +#include "ai/types/stream_options.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// Note: These tests connect to the real OpenAI Responses API when +// OPENAI_API_KEY is set. Otherwise they are skipped. + +namespace ai { +namespace test { + +namespace { + +Tool make_weather_tool(std::atomic* calls = nullptr) { + return create_simple_tool( + "weather", "Get the current weather for a city", + {{"location", "string"}}, + [calls](const JsonValue& args, const ToolExecutionContext&) { + if (calls != nullptr) { + ++*calls; + } + return JsonValue{{"location", args["location"]}, + {"temperature_fahrenheit", 72}, + {"condition", "Sunny"}}; + }); +} + +Tool make_population_tool(std::atomic* calls) { + return create_simple_tool( + "population", "Get the population of a city", {{"city", "string"}}, + [calls](const JsonValue& args, const ToolExecutionContext&) { + ++*calls; + return JsonValue{{"city", args["city"]}, {"population", 2100000}}; + }); +} + +bool has_reasoning_part(const Messages& messages) { + return std::any_of( + messages.begin(), messages.end(), [](const Message& message) { + return std::any_of(message.content.begin(), message.content.end(), + [](const ContentPart& part) { + return std::holds_alternative( + part); + }); + }); +} + +} // namespace + +class OpenAIResponsesIntegrationTest : public AITestFixture { + protected: + void SetUp() override { + AITestFixture::SetUp(); + const char* api_key = std::getenv("OPENAI_API_KEY"); + if (api_key && *api_key != '\0') { + client_ = ai::openai::create_responses_client(api_key); + } + } + + std::optional client_; +}; + +TEST_F(OpenAIResponsesIntegrationTest, BasicTextGeneration) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + GenerateOptions options(ai::openai::models::kGpt6Luna, + "Reply with a short greeting."); + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_FALSE(result.text.empty()); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); + EXPECT_GT(result.usage.total_tokens, 0); + ASSERT_TRUE(result.id.has_value()); + EXPECT_THAT(*result.id, testing::StartsWith("resp_")); +} + +TEST_F(OpenAIResponsesIntegrationTest, InstructionsAndSamplingParameters) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + // GPT-6.2 rejects sampling parameters and the "none" effort; the request + // must still succeed. + GenerateOptions options(ai::openai::models::kGpt62Sol, + "You always answer in French.", "Hello, how are you?"); + options.temperature = 0.3; + options.max_tokens = 400; + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_FALSE(result.text.empty()); +} + +TEST_F(OpenAIResponsesIntegrationTest, MaxOutputTokensFinishesWithLength) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + GenerateOptions options(ai::openai::models::kGpt6Luna, + "Write a 500-word essay about the sea."); + options.max_tokens = 16; + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_EQ(result.finish_reason, kFinishReasonLength); +} + +TEST_F(OpenAIResponsesIntegrationTest, StructuredOutput) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + const JsonValue format = { + {"type", "json_schema"}, + {"json_schema", + {{"name", "city"}, + {"strict", true}, + {"schema", + {{"type", "object"}, + {"properties", + {{"name", {{"type", "string"}}}, + {"country", {{"type", "string"}}}}}, + {"required", {"name", "country"}}, + {"additionalProperties", false}}}}}}; + GenerateOptions options(ai::openai::models::kGpt6Luna, "", + "Name the capital of France.", format); + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + const auto json = JsonValue::parse(result.text); + EXPECT_TRUE(json.contains("name")); + EXPECT_TRUE(json.contains("country")); +} + +TEST_F(OpenAIResponsesIntegrationTest, ToolCallingWithGpt62Sol) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + GenerateOptions options(ai::openai::models::kGpt62Sol, + "What's the weather like in Paris?"); + options.tools["weather"] = make_weather_tool(); + options.tool_choice = ToolChoice::required(); + options.max_tokens = 1000; + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_EQ(result.finish_reason, kFinishReasonToolCalls); + ASSERT_FALSE(result.tool_calls.empty()); + EXPECT_EQ(result.tool_calls[0].tool_name, "weather"); + EXPECT_TRUE(result.tool_calls[0].arguments.contains("location")); + ASSERT_EQ(result.tool_results.size(), result.tool_calls.size()); + EXPECT_TRUE(result.tool_results[0].is_success()); +} + +TEST_F(OpenAIResponsesIntegrationTest, MultiStepToolLoopWithReasoning) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + std::atomic weather_calls{0}; + std::atomic population_calls{0}; + GenerateOptions options( + ai::openai::models::kGpt62Sol, + "Use the tools to find the weather in Paris and the population of " + "Paris, then answer in one sentence that includes both the " + "temperature and the population."); + options.tools["weather"] = make_weather_tool(&weather_calls); + options.tools["population"] = make_population_tool(&population_calls); + options.max_steps = 5; + options.max_tokens = 2000; + auto result = client_->generate_text(options); + + TestAssertions::assertSuccess(result); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); + EXPECT_GE(result.steps.size(), 2u); + EXPECT_GE(weather_calls.load(), 1); + EXPECT_GE(population_calls.load(), 1); + EXPECT_THAT(result.text, testing::HasSubstr("72")); + EXPECT_FALSE(result.response_messages.empty()); + if (!has_reasoning_part(result.response_messages)) { + // Not a failure: the model may skip reasoning at the lowest effort. + std::cout << "No reasoning items were returned to replay\n"; + } + + // The continuation, reasoning items included, is accepted as the input of + // the next request. + Messages conversation = {Message::user(options.prompt)}; + conversation.insert(conversation.end(), result.response_messages.begin(), + result.response_messages.end()); + conversation.push_back(Message::user("And what is the weather in Paris?")); + GenerateOptions follow_up(ai::openai::models::kGpt62Sol, + std::move(conversation)); + follow_up.tools = options.tools; + follow_up.max_steps = 3; + follow_up.max_tokens = 2000; + auto follow_up_result = client_->generate_text(follow_up); + TestAssertions::assertSuccess(follow_up_result); + EXPECT_FALSE(follow_up_result.text.empty()); +} + +TEST_F(OpenAIResponsesIntegrationTest, StreamingText) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + GenerateOptions generate_options(ai::openai::models::kGpt6Luna, + "Count from 1 to 5."); + auto stream = client_->stream_text(StreamOptions(generate_options)); + + std::string text; + std::optional finish; + for (const auto& event : stream) { + if (event.is_text_delta()) { + text += event.text_delta; + } else if (event.is_error()) { + FAIL() << "Stream error: " << event.error.value_or(""); + } else if (event.is_finish()) { + finish = event; + break; + } + } + + EXPECT_THAT(text, testing::HasSubstr("5")); + ASSERT_TRUE(finish.has_value()); + EXPECT_EQ(finish->finish_reason, kFinishReasonStop); + ASSERT_TRUE(finish->usage.has_value()); + EXPECT_GT(finish->usage->total_tokens, 0); +} + +TEST_F(OpenAIResponsesIntegrationTest, StreamingToolCall) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + GenerateOptions generate_options(ai::openai::models::kGpt6Luna, + "What's the weather like in Tokyo?"); + generate_options.tools["weather"] = make_weather_tool(); + generate_options.tool_choice = ToolChoice::required(); + auto stream = client_->stream_text(StreamOptions(generate_options)); + + std::optional tool_call; + std::optional finish; + for (const auto& event : stream) { + if (event.is_tool_call()) { + tool_call = event.tool_call; + } else if (event.is_error()) { + FAIL() << "Stream error: " << event.error.value_or(""); + } else if (event.is_finish()) { + finish = event; + break; + } + } + + ASSERT_TRUE(tool_call.has_value()); + EXPECT_EQ(tool_call->tool_name, "weather"); + EXPECT_TRUE(tool_call->arguments.contains("location")); + ASSERT_TRUE(finish.has_value()); + EXPECT_EQ(finish->finish_reason, kFinishReasonToolCalls); +} + +TEST_F(OpenAIResponsesIntegrationTest, InvalidApiKey) { + if (!client_) { + GTEST_SKIP() << "No OPENAI_API_KEY environment variable set"; + } + + auto client = ai::openai::create_responses_client("sk-invalid"); + auto result = client.generate_text( + GenerateOptions(ai::openai::models::kGpt6Luna, "Hello")); + EXPECT_FALSE(result.is_success()); + EXPECT_FALSE(result.error_message().empty()); +} + +} // namespace test +} // namespace ai diff --git a/tests/integration/tool_calling_integration_test.cpp b/tests/integration/tool_calling_integration_test.cpp index 0a739ca..11ae6af 100644 --- a/tests/integration/tool_calling_integration_test.cpp +++ b/tests/integration/tool_calling_integration_test.cpp @@ -125,7 +125,7 @@ class ToolTestFixtures { } }; -// Parameterized test class that works with both providers +// Parameterized test class that works with every provider class ToolCallingIntegrationTest : public ::testing::TestWithParam { protected: @@ -141,6 +141,16 @@ class ToolCallingIntegrationTest } else { use_real_api_ = false; } + } else if (provider == "openai_responses") { + // GPT-6 models call tools through the Responses API only. + const char* api_key = std::getenv("OPENAI_API_KEY"); + if (api_key && *api_key != '\0') { + use_real_api_ = true; + client_ = ai::openai::create_responses_client(api_key); + model_ = ai::openai::models::kGpt6Luna; + } else { + use_real_api_ = false; + } } else if (provider == "anthropic") { const char* api_key = std::getenv("ANTHROPIC_API_KEY"); if (api_key && *api_key != '\0') { @@ -617,11 +627,11 @@ TEST_P(ToolCallingIntegrationTest, ToolSchemaValidation) { } } -// Instantiate tests for both providers +// Instantiate tests for every provider INSTANTIATE_TEST_SUITE_P( ProviderTests, ToolCallingIntegrationTest, - ::testing::Values("openai", "anthropic"), + ::testing::Values("openai", "openai_responses", "anthropic"), [](const ::testing::TestParamInfo& info) { return info.param; }); diff --git a/tests/unit/openai_responses_test.cpp b/tests/unit/openai_responses_test.cpp new file mode 100644 index 0000000..45d2df5 --- /dev/null +++ b/tests/unit/openai_responses_test.cpp @@ -0,0 +1,538 @@ +#include "../utils/test_fixtures.h" +#include "ai/openai.h" +#include "ai/tools.h" +#include "ai/types/generate_options.h" +#include "providers/openai/openai_responses_client.h" +#include "providers/openai/openai_responses_request_builder.h" +#include "providers/openai/openai_responses_response_parser.h" +#include "providers/openai/openai_responses_stream.h" + +#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}}; + }); +} + +const nlohmann::json kReasoningItem = {{"id", "rs_1"}, + {"type", "reasoning"}, + {"summary", nlohmann::json::array()}, + {"encrypted_content", "gAAAA-secret"}}; + +nlohmann::json make_tool_call_response() { + return {{"id", "resp_1"}, + {"object", "response"}, + {"created_at", 1741487325}, + {"model", "gpt-6.2-sol"}, + {"status", "completed"}, + {"output", + {kReasoningItem, + {{"id", "fc_1"}, + {"type", "function_call"}, + {"status", "completed"}, + {"call_id", "call_1"}, + {"name", "weather"}, + {"arguments", R"({"location":"Paris"})"}}}}, + {"usage", + {{"input_tokens", 75}, + {"output_tokens", 30}, + {"output_tokens_details", {{"reasoning_tokens", 12}}}, + {"total_tokens", 105}}}}; +} + +} // namespace + +// Request building + +TEST(OpenAIResponsesRequestTest, BuildsStatelessRequestFromPrompt) { + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt62Sol, "Be brief.", "Hello"); + options.max_tokens = 64; + + const auto request = builder.build_request_json(options); + + EXPECT_EQ(request["model"], "gpt-6.2-sol"); + EXPECT_EQ(request["store"], false); + EXPECT_EQ(request["instructions"], "Be brief."); + EXPECT_EQ(request["max_output_tokens"], 64); + EXPECT_FALSE(request.contains("messages")); + EXPECT_FALSE(request.contains("max_completion_tokens")); + ASSERT_EQ(request["input"].size(), 1u); + EXPECT_EQ(request["input"][0]["role"], "user"); + EXPECT_EQ(request["input"][0]["content"], "Hello"); +} + +TEST(OpenAIResponsesRequestTest, UsesLowestAcceptedReasoningEffort) { + openai::OpenAIResponsesRequestBuilder builder; + + for (const auto* model : + {openai::models::kGpt62Astra, openai::models::kGpt62Sol}) { + const auto request = builder.build_request_json(GenerateOptions(model, "Hi")); + EXPECT_EQ(request["reasoning"]["effort"], "low") << model; + } + for (const auto* model : + {openai::models::kGpt61Terra, openai::models::kGpt6Luna, + openai::models::kGpt56}) { + const auto request = builder.build_request_json(GenerateOptions(model, "Hi")); + EXPECT_EQ(request["reasoning"]["effort"], "none") << model; + } + for (const auto* model : {openai::models::kGpt54Pro, openai::models::kGpt41}) { + const auto request = builder.build_request_json(GenerateOptions(model, "Hi")); + EXPECT_FALSE(request.contains("reasoning")) << model; + } +} + +TEST(OpenAIResponsesRequestTest, OmitsUnsupportedParameters) { + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt6Luna, "Hi"); + options.temperature = 0.2; + options.top_p = 0.9; + options.seed = 7; + options.frequency_penalty = 0.1; + options.presence_penalty = 0.1; + + const auto request = builder.build_request_json(options); + for (const auto* key : + {"temperature", "top_p", "seed", "frequency_penalty", + "presence_penalty"}) { + EXPECT_FALSE(request.contains(key)) << key; + } + + GenerateOptions non_reasoning(openai::models::kGpt41, "Hi"); + non_reasoning.temperature = 0.2; + non_reasoning.top_p = 0.9; + const auto kept = builder.build_request_json(non_reasoning); + EXPECT_EQ(kept["temperature"], 0.2); + EXPECT_EQ(kept["top_p"], 0.9); +} + +TEST(OpenAIResponsesRequestTest, BuildsFlatFunctionTools) { + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt62Sol, "Weather in Paris?"); + options.tools["weather"] = make_weather_tool(); + + auto request = builder.build_request_json(options); + ASSERT_EQ(request["tools"].size(), 1u); + const auto& tool = request["tools"][0]; + EXPECT_EQ(tool["type"], "function"); + EXPECT_EQ(tool["name"], "weather"); + EXPECT_EQ(tool["description"], "Get the weather"); + EXPECT_EQ(tool["parameters"]["required"][0], "location"); + EXPECT_EQ(tool["strict"], false); + EXPECT_FALSE(tool.contains("function")); + EXPECT_EQ(request["tool_choice"], "auto"); + + options.tool_choice = ToolChoice::specific("weather"); + request = builder.build_request_json(options); + EXPECT_EQ(request["tool_choice"], + nlohmann::json({{"type", "function"}, {"name", "weather"}})); + + options.tool_choice = ToolChoice::required(); + EXPECT_EQ(builder.build_request_json(options)["tool_choice"], "required"); + options.tool_choice = ToolChoice::none(); + EXPECT_EQ(builder.build_request_json(options)["tool_choice"], "none"); +} + +TEST(OpenAIResponsesRequestTest, MapsResponseFormatToTextFormat) { + openai::OpenAIResponsesRequestBuilder builder; + const nlohmann::json schema = { + {"type", "object"}, + {"properties", {{"name", {{"type", "string"}}}}}, + {"required", {"name"}}, + {"additionalProperties", false}}; + + // The Chat Completions shape is flattened. + GenerateOptions chat_shape(openai::models::kGpt62Sol, "", "Name a city", + nlohmann::json{{"type", "json_schema"}, + {"json_schema", + {{"name", "city"}, + {"schema", schema}, + {"strict", true}}}}); + EXPECT_EQ(builder.build_request_json(chat_shape)["text"]["format"], + nlohmann::json({{"type", "json_schema"}, + {"name", "city"}, + {"schema", schema}, + {"strict", true}})); + EXPECT_FALSE(builder.build_request_json(chat_shape).contains( + "response_format")); + + GenerateOptions json_object(openai::models::kGpt62Sol, "", "Name a city", + nlohmann::json{{"type", "json_object"}}); + EXPECT_EQ(builder.build_request_json(json_object)["text"]["format"], + nlohmann::json({{"type", "json_object"}})); +} + +TEST(OpenAIResponsesRequestTest, ReplaysToolRoundTripWithReasoningInOrder) { + openai::OpenAIResponsesResponseParser parser; + auto step = parser.parse_success_completion_response(make_tool_call_response()); + ASSERT_EQ(step.response_messages.size(), 1u); + + Messages conversation = {Message::system("Use the tools."), + Message::user("Weather in Paris?")}; + conversation.push_back(step.response_messages[0]); + conversation.push_back(Message::tool_results( + {ToolResultContentPart("call_1", {{"temperature", 72}})})); + + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt62Sol, std::move(conversation)); + const auto input = builder.build_request_json(options)["input"]; + + ASSERT_EQ(input.size(), 5u); + EXPECT_EQ(input[0]["role"], "system"); + EXPECT_EQ(input[1]["role"], "user"); + // The reasoning item is replayed verbatim, before the call it led to. + EXPECT_EQ(input[2], kReasoningItem); + EXPECT_EQ(input[3], nlohmann::json({{"type", "function_call"}, + {"id", "fc_1"}, + {"call_id", "call_1"}, + {"name", "weather"}, + {"arguments", R"({"location":"Paris"})"}})); + EXPECT_EQ(input[4], nlohmann::json({{"type", "function_call_output"}, + {"call_id", "call_1"}, + {"output", R"({"temperature":72})"}})); +} + +TEST(OpenAIResponsesRequestTest, BuildsFunctionCallsFromPlainMessages) { + // Messages built by hand (or by another provider) carry no provider parts. + Messages conversation = { + Message::user("Weather in Paris?"), + Message::assistant_with_tools( + "Checking.", {ToolCallContentPart("call_9", "weather", + {{"location", "Paris"}})}), + Message::tool_results({ToolResultContentPart( + "call_9", {{"error", "unavailable"}}, /*err=*/true)})}; + + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt6Luna, std::move(conversation)); + const auto input = builder.build_request_json(options)["input"]; + + ASSERT_EQ(input.size(), 4u); + EXPECT_EQ(input[1]["role"], "assistant"); + EXPECT_EQ(input[1]["content"], "Checking."); + EXPECT_EQ(input[2]["type"], "function_call"); + EXPECT_FALSE(input[2].contains("id")); + EXPECT_EQ(input[2]["call_id"], "call_9"); + EXPECT_EQ(input[3]["output"], R"(Error: {"error":"unavailable"})"); +} + +TEST(OpenAIResponsesRequestTest, IgnoresOtherProvidersParts) { + Messages conversation = { + Message::user("Hi"), + Message(kMessageRoleAssistant, + {ProviderContentPart("anthropic", {{"type", "thinking"}}), + TextContentPart("Hello")}), + Message::user("Bye")}; + + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt6Luna, std::move(conversation)); + const auto input = builder.build_request_json(options)["input"]; + + ASSERT_EQ(input.size(), 3u); + EXPECT_EQ(input[1]["content"], "Hello"); +} + +// Response parsing + +TEST(OpenAIResponsesParserTest, ParsesTextResponse) { + const nlohmann::json response = { + {"id", "resp_2"}, + {"created_at", 1740855869}, + {"model", "gpt-6-luna"}, + {"status", "completed"}, + {"output", + {{{"id", "msg_1"}, + {"type", "message"}, + {"role", "assistant"}, + {"status", "completed"}, + {"content", + {{{"type", "output_text"}, + {"text", "Hello"}, + {"annotations", nlohmann::json::array()}}, + {{"type", "output_text"}, {"text", " there"}}}}}}}, + {"usage", + {{"input_tokens", 5}, {"output_tokens", 2}, {"total_tokens", 7}}}}; + + openai::OpenAIResponsesResponseParser parser; + const auto result = parser.parse_success_completion_response(response); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "Hello there"); + EXPECT_EQ(result.finish_reason, kFinishReasonStop); + EXPECT_EQ(result.id, "resp_2"); + EXPECT_EQ(result.model, "gpt-6-luna"); + EXPECT_EQ(result.created, 1740855869); + EXPECT_EQ(result.usage.prompt_tokens, 5); + EXPECT_EQ(result.usage.completion_tokens, 2); + EXPECT_EQ(result.usage.total_tokens, 7); + ASSERT_EQ(result.response_messages.size(), 1u); + EXPECT_EQ(result.response_messages[0].get_text(), "Hello there"); +} + +TEST(OpenAIResponsesParserTest, ParsesFunctionCallsAndKeepsReasoning) { + openai::OpenAIResponsesResponseParser parser; + const auto result = + parser.parse_success_completion_response(make_tool_call_response()); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.finish_reason, kFinishReasonToolCalls); + ASSERT_EQ(result.tool_calls.size(), 1u); + EXPECT_EQ(result.tool_calls[0].id, "call_1"); + EXPECT_EQ(result.tool_calls[0].tool_name, "weather"); + EXPECT_EQ(result.tool_calls[0].arguments["location"], "Paris"); + EXPECT_EQ(result.usage.total_tokens, 105); + + ASSERT_EQ(result.response_messages.size(), 1u); + const auto& turn = result.response_messages[0]; + EXPECT_EQ(turn.role, kMessageRoleAssistant); + ASSERT_EQ(turn.content.size(), 3u); + const auto* reasoning = std::get_if(&turn.content[0]); + ASSERT_NE(reasoning, nullptr); + EXPECT_EQ(reasoning->provider, openai::kResponsesProviderName); + EXPECT_EQ(reasoning->data, kReasoningItem); + ASSERT_EQ(turn.get_tool_calls().size(), 1u); + EXPECT_EQ(turn.get_tool_calls()[0].id, "call_1"); +} + +TEST(OpenAIResponsesParserTest, MapsIncompleteAndFailedStatuses) { + openai::OpenAIResponsesResponseParser parser; + + nlohmann::json response = { + {"status", "incomplete"}, + {"incomplete_details", {{"reason", "max_output_tokens"}}}, + {"output", {kReasoningItem}}}; + auto result = parser.parse_success_completion_response(response); + EXPECT_TRUE(result.is_success()); + EXPECT_EQ(result.finish_reason, kFinishReasonLength); + // Reasoning alone cannot be replayed without the item that follows it. + EXPECT_TRUE(result.response_messages.empty()); + + response["incomplete_details"]["reason"] = "content_filter"; + result = parser.parse_success_completion_response(response); + EXPECT_EQ(result.finish_reason, kFinishReasonContentFilter); + + response["incomplete_details"]["reason"] = "max_messages"; + result = parser.parse_success_completion_response(response); + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), testing::HasSubstr("max_messages")); + + result = parser.parse_success_completion_response( + {{"status", "failed"}, + {"error", + {{"code", "server_error"}, + {"message", "The model failed to generate a response."}}}}); + EXPECT_FALSE(result.is_success()); + EXPECT_EQ(result.finish_reason, kFinishReasonError); + EXPECT_THAT(result.error_message(), testing::HasSubstr("server_error")); + EXPECT_THAT(result.error_message(), + testing::HasSubstr("The model failed to generate a response.")); +} + +TEST(OpenAIResponsesParserTest, RejectsMalformedFunctionCallArguments) { + auto response = make_tool_call_response(); + response["output"][1]["arguments"] = "{not json"; + + openai::OpenAIResponsesResponseParser parser; + const auto result = parser.parse_success_completion_response(response); + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), testing::HasSubstr("weather")); +} + +TEST(OpenAIResponsesParserTest, ParsesStandardErrors) { + openai::OpenAIResponsesResponseParser parser; + const auto result = parser.parse_error_completion_response( + 400, + R"({"error":{"message":"Unsupported value: 'reasoning.effort' does not support 'none' with this model.","type":"invalid_request_error","param":"reasoning.effort","code":"unsupported_value"}})"); + EXPECT_FALSE(result.is_success()); + EXPECT_THAT(result.error_message(), testing::HasSubstr("reasoning.effort")); +} + +// Multi-step tool loop: the reasoning items reach the follow-up request. + +TEST(OpenAIResponsesMultiStepTest, FollowUpRequestReplaysReasoning) { + GenerateOptions options(openai::models::kGpt62Sol, "Weather in Paris?"); + options.tools["weather"] = make_weather_tool(); + options.max_steps = 3; + + openai::OpenAIResponsesResponseParser parser; + openai::OpenAIResponsesRequestBuilder builder; + 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_tool_call_response()); + step.tool_results = ToolExecutor::execute_tools_with_options( + step.tool_calls, step_options, false); + return step; + } + return parser.parse_success_completion_response( + {{"status", "completed"}, + {"output", + {{{"type", "message"}, + {"role", "assistant"}, + {"content", + {{{"type", "output_text"}, {"text", "It is 72F."}}}}}}}}); + }); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "It is 72F."); + ASSERT_EQ(requests.size(), 2u); + const auto& input = requests[1]["input"]; + ASSERT_EQ(input.size(), 4u); + EXPECT_EQ(input[0]["role"], "user"); + EXPECT_EQ(input[1], kReasoningItem); + EXPECT_EQ(input[2]["type"], "function_call"); + EXPECT_EQ(input[2]["id"], "fc_1"); + EXPECT_EQ(input[3]["type"], "function_call_output"); + EXPECT_EQ(input[3]["call_id"], "call_1"); + EXPECT_THAT(input[3]["output"].get(), + testing::HasSubstr("72")); + + // The continuation holds the replayable turn, the results, and the answer. + ASSERT_EQ(result.response_messages.size(), 3u); + EXPECT_EQ(result.response_messages.back().get_text(), "It is 72F."); +} + +// Streaming + +TEST(OpenAIResponsesStreamTest, StreamsTextAndUsage) { + openai::OpenAIResponsesStreamImpl stream; + stream.process_sse_line_for_testing("event: response.created"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[]},"sequence_number":0})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","status":"in_progress","role":"assistant","content":[]},"sequence_number":1})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"Hel","sequence_number":2})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"lo","sequence_number":3})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":4,"output_tokens":3,"total_tokens":7}},"sequence_number":4})"); + + 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->total_tokens, 7); + EXPECT_FALSE(stream.has_more_events()); +} + +TEST(OpenAIResponsesStreamTest, StreamsFunctionCall) { + openai::OpenAIResponsesStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"weather","arguments":""}})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":1,"delta":"{\"location\":"})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":1,"delta":"\"Paris\"}"})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.function_call_arguments.done","item_id":"fc_1","output_index":1,"arguments":"{\"location\":\"Paris\"}"})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_item.done","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"weather","arguments":"{\"location\":\"Paris\"}","status":"completed"}})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":10,"output_tokens":5,"total_tokens":15}}})"); + + const auto tool_event = stream.get_next_event(); + ASSERT_TRUE(tool_event.is_tool_call()); + EXPECT_EQ(tool_event.tool_call->id, "call_1"); + EXPECT_EQ(tool_event.tool_call->tool_name, "weather"); + EXPECT_EQ(tool_event.tool_call->arguments["location"], "Paris"); + + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonToolCalls); + EXPECT_EQ(finish.usage->total_tokens, 15); +} + +TEST(OpenAIResponsesStreamTest, IncompleteResponseFinishesWithLength) { + openai::OpenAIResponsesStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_text.delta","output_index":0,"delta":"Once"})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"usage":{"input_tokens":3,"output_tokens":16,"total_tokens":19}}})"); + + 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); + EXPECT_EQ(finish.usage->completion_tokens, 16); +} + +TEST(OpenAIResponsesStreamTest, FailedResponseEmitsError) { + openai::OpenAIResponsesStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"The model failed to generate a response."}}})"); + + const auto error = stream.get_next_event(); + ASSERT_TRUE(error.is_error()); + EXPECT_THAT(*error.error, testing::HasSubstr("server_error")); + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonError); + EXPECT_FALSE(finish.usage.has_value()); +} + +TEST(OpenAIResponsesStreamTest, ErrorEventEmitsError) { + openai::OpenAIResponsesStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"type":"error","code":"rate_limit_exceeded","message":"Slow down","param":null,"sequence_number":1})"); + // Nothing after the terminal event is emitted. + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_text.delta","output_index":0,"delta":"late"})"); + + ASSERT_EQ(stream.queued_event_count_for_testing(), 2u); + const auto error = stream.get_next_event(); + ASSERT_TRUE(error.is_error()); + EXPECT_THAT(*error.error, testing::HasSubstr("rate_limit_exceeded")); + EXPECT_THAT(*error.error, testing::HasSubstr("Slow down")); + EXPECT_EQ(stream.get_next_event().finish_reason, kFinishReasonError); +} + +TEST(OpenAIResponsesStreamTest, ChunkedEventsAreReassembled) { + openai::OpenAIResponsesStreamImpl stream; + stream.process_sse_chunk_for_testing( + "event: response.output_text.delta\ndata: {\"type\":\"response.output_" + "text.delta\",\"output_index\":0,\"del"); + stream.process_sse_chunk_for_testing( + "ta\":\"Hi\"}\n\nevent: response.completed\ndata: {\"type\":\"response." + "completed\",\"response\":{\"status\":\"completed\"}}\n\n"); + + EXPECT_EQ(stream.get_next_event().text_delta, "Hi"); + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonStop); +} + +// Client + +TEST(OpenAIResponsesClientTest, UsesResponsesEndpointAndDefaults) { + openai::OpenAIResponsesClient client("sk-test", "https://api.openai.com"); + EXPECT_EQ(client.provider_name(), "openai"); + EXPECT_EQ(client.default_model(), openai::models::kDefaultResponsesModel); + EXPECT_THAT(client.config_info(), testing::HasSubstr("Responses API")); + EXPECT_TRUE(client.supports_model(openai::models::kGpt62Sol)); + EXPECT_TRUE(client.is_valid()); +} + +} // namespace test +} // namespace ai From 78171ee343505e3fe626294ec25cfe505bd38b3f Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 02:24:31 +0000 Subject: [PATCH 4/6] Format with clang-format 18 and fix an ambiguous `std::optional` conversion in a test Co-Authored-By: Claude Opus 5.5 --- examples/openai_responses.cpp | 4 +- src/providers/openai/openai_factory.cpp | 4 +- .../openai_responses_request_builder.cpp | 8 +-- .../openai_responses_response_parser.cpp | 13 ++--- .../openai/openai_responses_stream.cpp | 3 +- src/tools/multi_step_coordinator.cpp | 12 ++-- .../openai_responses_integration_test.cpp | 22 +++---- tests/unit/openai_responses_test.cpp | 58 ++++++++++--------- 8 files changed, 63 insertions(+), 61 deletions(-) diff --git a/examples/openai_responses.cpp b/examples/openai_responses.cpp index 00732f8..96cd7c1 100644 --- a/examples/openai_responses.cpp +++ b/examples/openai_responses.cpp @@ -68,8 +68,8 @@ int main() { std::cerr << "Error: " << result.error_message() << "\n"; return 1; } - std::cout << "Answer (" << result.steps.size() - << " steps): " << result.text << "\n"; + std::cout << "Answer (" << result.steps.size() << " steps): " << result.text + << "\n"; std::cout << "Tokens: " << result.usage.total_tokens << "\n\n"; // 2. Continue the conversation. `response_messages` holds the assistant diff --git a/src/providers/openai/openai_factory.cpp b/src/providers/openai/openai_factory.cpp index 68571ca..99d8a3a 100644 --- a/src/providers/openai/openai_factory.cpp +++ b/src/providers/openai/openai_factory.cpp @@ -33,8 +33,8 @@ std::string get_base_url_or_default(const std::string& base_url) { template Client make_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))); + return Client(std::make_unique( + get_api_key_or_default(api_key), get_base_url_or_default(base_url))); } template diff --git a/src/providers/openai/openai_responses_request_builder.cpp b/src/providers/openai/openai_responses_request_builder.cpp index d6bca25..3adbd33 100644 --- a/src/providers/openai/openai_responses_request_builder.cpp +++ b/src/providers/openai/openai_responses_request_builder.cpp @@ -58,7 +58,8 @@ void append_assistant_items(const Message& message, nlohmann::json& input) { for (const auto& part : message.content) { if (const auto* text_part = std::get_if(&part)) { pending_text += text_part->text; - } else if (const auto* tool_call = std::get_if(&part)) { + } else if (const auto* tool_call = + std::get_if(&part)) { flush_text(); nlohmann::json item{{"type", "function_call"}, {"call_id", tool_call->id}, @@ -232,9 +233,8 @@ nlohmann::json OpenAIResponsesRequestBuilder::build_request_json( break; case ToolChoiceType::kSpecific: if (options.tool_choice.tool_name) { - request["tool_choice"] = { - {"type", "function"}, - {"name", *options.tool_choice.tool_name}}; + request["tool_choice"] = {{"type", "function"}, + {"name", *options.tool_choice.tool_name}}; } break; } diff --git a/src/providers/openai/openai_responses_response_parser.cpp b/src/providers/openai/openai_responses_response_parser.cpp index 024d27a..19e0235 100644 --- a/src/providers/openai/openai_responses_response_parser.cpp +++ b/src/providers/openai/openai_responses_response_parser.cpp @@ -126,19 +126,18 @@ GenerateResult OpenAIResponsesResponseParser::parse_success_completion_response( const auto arguments_text = string_field(item, "arguments"); JsonValue arguments; try { - arguments = arguments_text.empty() - ? JsonValue::object() - : JsonValue::parse(arguments_text); + arguments = arguments_text.empty() ? JsonValue::object() + : JsonValue::parse(arguments_text); } catch (const nlohmann::json::exception& e) { return GenerateResult("Failed to parse arguments of the " + name + " function call: " + e.what()); } if (const auto item_id = string_field(item, "id"); !item_id.empty()) { - turn.emplace_back(ProviderContentPart{ - kResponsesProviderName, {{"type", "function_call"}, - {"id", item_id}, - {"call_id", call_id}}}); + turn.emplace_back(ProviderContentPart{kResponsesProviderName, + {{"type", "function_call"}, + {"id", item_id}, + {"call_id", call_id}}}); } turn.emplace_back(ToolCallContentPart{call_id, name, arguments}); result.tool_calls.emplace_back(call_id, name, std::move(arguments)); diff --git a/src/providers/openai/openai_responses_stream.cpp b/src/providers/openai/openai_responses_stream.cpp index af3a205..6de013b 100644 --- a/src/providers/openai/openai_responses_stream.cpp +++ b/src/providers/openai/openai_responses_stream.cpp @@ -151,8 +151,7 @@ void OpenAIResponsesStreamImpl::finish_response( if (usage_) { ai::logger::log_info( "Stream completed - tokens used: {} prompt, {} completion, {} total", - usage_->prompt_tokens, usage_->completion_tokens, - usage_->total_tokens); + usage_->prompt_tokens, usage_->completion_tokens, usage_->total_tokens); } mark_complete(); } diff --git a/src/tools/multi_step_coordinator.cpp b/src/tools/multi_step_coordinator.cpp index 6c2bf80..4d9cfb2 100644 --- a/src/tools/multi_step_coordinator.cpp +++ b/src/tools/multi_step_coordinator.cpp @@ -27,12 +27,12 @@ void append_terminal_assistant_reply(const ai::GenerateResult& step_result, // Responses API, see `ProviderContentPart`) do so; that turn is fed back as is // instead of being rebuilt from the text and the tool calls. bool has_provider_tool_call_turn(const ai::GenerateResult& step_result) { - return std::any_of( - step_result.response_messages.begin(), - step_result.response_messages.end(), [](const ai::Message& message) { - return message.role == ai::kMessageRoleAssistant && - message.has_tool_calls(); - }); + return std::any_of(step_result.response_messages.begin(), + step_result.response_messages.end(), + [](const ai::Message& message) { + return message.role == ai::kMessageRoleAssistant && + message.has_tool_calls(); + }); } } // namespace diff --git a/tests/integration/openai_responses_integration_test.cpp b/tests/integration/openai_responses_integration_test.cpp index e1ec935..9321d2a 100644 --- a/tests/integration/openai_responses_integration_test.cpp +++ b/tests/integration/openai_responses_integration_test.cpp @@ -25,8 +25,7 @@ namespace { Tool make_weather_tool(std::atomic* calls = nullptr) { return create_simple_tool( - "weather", "Get the current weather for a city", - {{"location", "string"}}, + "weather", "Get the current weather for a city", {{"location", "string"}}, [calls](const JsonValue& args, const ToolExecutionContext&) { if (calls != nullptr) { ++*calls; @@ -49,11 +48,11 @@ Tool make_population_tool(std::atomic* calls) { bool has_reasoning_part(const Messages& messages) { return std::any_of( messages.begin(), messages.end(), [](const Message& message) { - return std::any_of(message.content.begin(), message.content.end(), - [](const ContentPart& part) { - return std::holds_alternative( - part); - }); + return std::any_of( + message.content.begin(), message.content.end(), + [](const ContentPart& part) { + return std::holds_alternative(part); + }); }); } @@ -97,7 +96,8 @@ TEST_F(OpenAIResponsesIntegrationTest, InstructionsAndSamplingParameters) { // GPT-6.2 rejects sampling parameters and the "none" effort; the request // must still succeed. GenerateOptions options(ai::openai::models::kGpt62Sol, - "You always answer in French.", "Hello, how are you?"); + "You always answer in French.", + "Hello, how are you?"); options.temperature = 0.3; options.max_tokens = 400; auto result = client_->generate_text(options); @@ -133,12 +133,12 @@ TEST_F(OpenAIResponsesIntegrationTest, StructuredOutput) { {"schema", {{"type", "object"}, {"properties", - {{"name", {{"type", "string"}}}, - {"country", {{"type", "string"}}}}}, + {{"name", {{"type", "string"}}}, {"country", {{"type", "string"}}}}}, {"required", {"name", "country"}}, {"additionalProperties", false}}}}}}; GenerateOptions options(ai::openai::models::kGpt6Luna, "", - "Name the capital of France.", format); + "Name the capital of France.", + std::optional(std::in_place, format)); auto result = client_->generate_text(options); TestAssertions::assertSuccess(result); diff --git a/tests/unit/openai_responses_test.cpp b/tests/unit/openai_responses_test.cpp index 45d2df5..a10d7b6 100644 --- a/tests/unit/openai_responses_test.cpp +++ b/tests/unit/openai_responses_test.cpp @@ -81,17 +81,21 @@ TEST(OpenAIResponsesRequestTest, UsesLowestAcceptedReasoningEffort) { for (const auto* model : {openai::models::kGpt62Astra, openai::models::kGpt62Sol}) { - const auto request = builder.build_request_json(GenerateOptions(model, "Hi")); + const auto request = + builder.build_request_json(GenerateOptions(model, "Hi")); EXPECT_EQ(request["reasoning"]["effort"], "low") << model; } for (const auto* model : {openai::models::kGpt61Terra, openai::models::kGpt6Luna, openai::models::kGpt56}) { - const auto request = builder.build_request_json(GenerateOptions(model, "Hi")); + const auto request = + builder.build_request_json(GenerateOptions(model, "Hi")); EXPECT_EQ(request["reasoning"]["effort"], "none") << model; } - for (const auto* model : {openai::models::kGpt54Pro, openai::models::kGpt41}) { - const auto request = builder.build_request_json(GenerateOptions(model, "Hi")); + for (const auto* model : + {openai::models::kGpt54Pro, openai::models::kGpt41}) { + const auto request = + builder.build_request_json(GenerateOptions(model, "Hi")); EXPECT_FALSE(request.contains("reasoning")) << model; } } @@ -106,9 +110,8 @@ TEST(OpenAIResponsesRequestTest, OmitsUnsupportedParameters) { options.presence_penalty = 0.1; const auto request = builder.build_request_json(options); - for (const auto* key : - {"temperature", "top_p", "seed", "frequency_penalty", - "presence_penalty"}) { + for (const auto* key : {"temperature", "top_p", "seed", "frequency_penalty", + "presence_penalty"}) { EXPECT_FALSE(request.contains(key)) << key; } @@ -156,19 +159,19 @@ TEST(OpenAIResponsesRequestTest, MapsResponseFormatToTextFormat) { {"additionalProperties", false}}; // The Chat Completions shape is flattened. - GenerateOptions chat_shape(openai::models::kGpt62Sol, "", "Name a city", - nlohmann::json{{"type", "json_schema"}, - {"json_schema", - {{"name", "city"}, - {"schema", schema}, - {"strict", true}}}}); + GenerateOptions chat_shape( + openai::models::kGpt62Sol, "", "Name a city", + nlohmann::json{ + {"type", "json_schema"}, + {"json_schema", + {{"name", "city"}, {"schema", schema}, {"strict", true}}}}); EXPECT_EQ(builder.build_request_json(chat_shape)["text"]["format"], nlohmann::json({{"type", "json_schema"}, {"name", "city"}, {"schema", schema}, {"strict", true}})); - EXPECT_FALSE(builder.build_request_json(chat_shape).contains( - "response_format")); + EXPECT_FALSE( + builder.build_request_json(chat_shape).contains("response_format")); GenerateOptions json_object(openai::models::kGpt62Sol, "", "Name a city", nlohmann::json{{"type", "json_object"}}); @@ -178,7 +181,8 @@ TEST(OpenAIResponsesRequestTest, MapsResponseFormatToTextFormat) { TEST(OpenAIResponsesRequestTest, ReplaysToolRoundTripWithReasoningInOrder) { openai::OpenAIResponsesResponseParser parser; - auto step = parser.parse_success_completion_response(make_tool_call_response()); + auto step = + parser.parse_success_completion_response(make_tool_call_response()); ASSERT_EQ(step.response_messages.size(), 1u); Messages conversation = {Message::system("Use the tools."), @@ -196,11 +200,12 @@ TEST(OpenAIResponsesRequestTest, ReplaysToolRoundTripWithReasoningInOrder) { EXPECT_EQ(input[1]["role"], "user"); // The reasoning item is replayed verbatim, before the call it led to. EXPECT_EQ(input[2], kReasoningItem); - EXPECT_EQ(input[3], nlohmann::json({{"type", "function_call"}, - {"id", "fc_1"}, - {"call_id", "call_1"}, - {"name", "weather"}, - {"arguments", R"({"location":"Paris"})"}})); + EXPECT_EQ(input[3], + nlohmann::json({{"type", "function_call"}, + {"id", "fc_1"}, + {"call_id", "call_1"}, + {"name", "weather"}, + {"arguments", R"({"location":"Paris"})"}})); EXPECT_EQ(input[4], nlohmann::json({{"type", "function_call_output"}, {"call_id", "call_1"}, {"output", R"({"temperature":72})"}})); @@ -211,8 +216,8 @@ TEST(OpenAIResponsesRequestTest, BuildsFunctionCallsFromPlainMessages) { Messages conversation = { Message::user("Weather in Paris?"), Message::assistant_with_tools( - "Checking.", {ToolCallContentPart("call_9", "weather", - {{"location", "Paris"}})}), + "Checking.", + {ToolCallContentPart("call_9", "weather", {{"location", "Paris"}})}), Message::tool_results({ToolResultContentPart( "call_9", {{"error", "unavailable"}}, /*err=*/true)})}; @@ -375,8 +380,8 @@ TEST(OpenAIResponsesMultiStepTest, FollowUpRequestReplaysReasoning) { 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_tool_call_response()); + auto step = parser.parse_success_completion_response( + make_tool_call_response()); step.tool_results = ToolExecutor::execute_tools_with_options( step.tool_calls, step_options, false); return step; @@ -401,8 +406,7 @@ TEST(OpenAIResponsesMultiStepTest, FollowUpRequestReplaysReasoning) { EXPECT_EQ(input[2]["id"], "fc_1"); EXPECT_EQ(input[3]["type"], "function_call_output"); EXPECT_EQ(input[3]["call_id"], "call_1"); - EXPECT_THAT(input[3]["output"].get(), - testing::HasSubstr("72")); + EXPECT_THAT(input[3]["output"].get(), testing::HasSubstr("72")); // The continuation holds the replayable turn, the results, and the answer. ASSERT_EQ(result.response_messages.size(), 3u); From f3385a1504f06e07e35a36561649dc27bf3801e4 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 02:44:35 +0000 Subject: [PATCH 5/6] Do not expect text from a single tool-calling step in the GPT-6.2 Sol test The step stops at the tool calls, so `TestAssertions::assertSuccess`, which requires text, failed in CI. Co-Authored-By: Claude Opus 5.5 --- tests/integration/openai_responses_integration_test.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/integration/openai_responses_integration_test.cpp b/tests/integration/openai_responses_integration_test.cpp index 9321d2a..f024a58 100644 --- a/tests/integration/openai_responses_integration_test.cpp +++ b/tests/integration/openai_responses_integration_test.cpp @@ -159,7 +159,8 @@ TEST_F(OpenAIResponsesIntegrationTest, ToolCallingWithGpt62Sol) { options.max_tokens = 1000; auto result = client_->generate_text(options); - TestAssertions::assertSuccess(result); + // A single step stops at the tool calls, so there is no text to expect. + ASSERT_TRUE(result.is_success()) << result.error_message(); EXPECT_EQ(result.finish_reason, kFinishReasonToolCalls); ASSERT_FALSE(result.tool_calls.empty()); EXPECT_EQ(result.tool_calls[0].tool_name, "weather"); From 99508bdf9383cccdcdf0a413a135b1e6dc502702 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 27 Nov 2026 03:20:23 +0000 Subject: [PATCH 6/6] Answer the function calls completed before `max_output_tokens` `max_output_tokens` counts reasoning tokens too, so a response can end as `incomplete` after some of its function calls were completed. Those calls are now executed and answered (finish reason `tool_calls`), while the truncated ones (`status: incomplete`) are dropped instead of failing on their cut-off arguments. A terminal step no longer keeps a provider-built turn with tool calls in `response_messages`, because an unanswered `function_call` cannot be replayed. Reported by Cursor Bugbot in https://github.com/ClickHouse/ai-sdk-cpp/pull/67 Co-Authored-By: Claude Opus 5.5 --- .../openai_responses_response_parser.cpp | 12 ++- .../openai/openai_responses_response_parser.h | 3 +- .../openai/openai_responses_stream.cpp | 15 +++- src/tools/multi_step_coordinator.cpp | 7 +- tests/unit/openai_responses_test.cpp | 73 +++++++++++++++++++ 5 files changed, 104 insertions(+), 6 deletions(-) diff --git a/src/providers/openai/openai_responses_response_parser.cpp b/src/providers/openai/openai_responses_response_parser.cpp index 19e0235..04b82a0 100644 --- a/src/providers/openai/openai_responses_response_parser.cpp +++ b/src/providers/openai/openai_responses_response_parser.cpp @@ -48,7 +48,11 @@ std::optional OpenAIResponsesResponseParser::parse_finish_reason( reason = string_field(*it, "reason"); } if (reason == "max_output_tokens") { - return kFinishReasonLength; + // `max_output_tokens` counts reasoning tokens too, so the limit can be + // hit after function calls were completed. Those calls still have to be + // answered (an unanswered call cannot be replayed), so the tool loop + // continues; the truncated ones were dropped by the caller. + return has_function_calls ? kFinishReasonToolCalls : kFinishReasonLength; } if (reason == "content_filter") { return kFinishReasonContentFilter; @@ -120,6 +124,12 @@ GenerateResult OpenAIResponsesResponseParser::parse_success_completion_response( result.text += text; turn.emplace_back(TextContentPart{std::move(text)}); } + } else if (type == "function_call" && + string_field(item, "status") == "incomplete") { + // Cut off by `max_output_tokens`: the arguments are truncated, and the + // call cannot be executed or replayed. + ai::logger::log_warn("Dropping incomplete function call: {}", + string_field(item, "name")); } else if (type == "function_call") { const auto call_id = string_field(item, "call_id"); const auto name = string_field(item, "name"); diff --git a/src/providers/openai/openai_responses_response_parser.h b/src/providers/openai/openai_responses_response_parser.h index ef43a5a..2b041d4 100644 --- a/src/providers/openai/openai_responses_response_parser.h +++ b/src/providers/openai/openai_responses_response_parser.h @@ -27,7 +27,8 @@ class OpenAIResponsesResponseParser : public OpenAIResponseParser { static Usage parse_usage(const nlohmann::json& usage); /// The finish reason of a response with the given `status` and - /// `incomplete_details`, or nullopt when the response did not finish + /// `incomplete_details` (`has_function_calls`: whether it has completed + /// function calls), or nullopt when the response did not finish /// (failed, cancelled, still in progress, or incomplete for a reason without /// a finish reason), in which case `error` describes why. static std::optional parse_finish_reason( diff --git a/src/providers/openai/openai_responses_stream.cpp b/src/providers/openai/openai_responses_stream.cpp index 6de013b..3cdc3d1 100644 --- a/src/providers/openai/openai_responses_stream.cpp +++ b/src/providers/openai/openai_responses_stream.cpp @@ -84,9 +84,16 @@ void OpenAIResponsesStreamImpl::handle_event(const nlohmann::json& event) { !arguments.empty() || type == "response.output_item.done") { pending.arguments = arguments; } - has_function_calls_ = true; if (type == "response.output_item.done") { - flush_pending_tool_call(index); + if (string_field(*item_it, "status") == "incomplete") { + // Cut off by `max_output_tokens`: the arguments are truncated. + ai::logger::log_warn("Dropping incomplete function call: {}", + pending.name); + pending_tool_calls_.erase(index); + } else { + has_function_calls_ = true; + flush_pending_tool_call(index); + } } return; } @@ -146,7 +153,9 @@ void OpenAIResponsesStreamImpl::finish_response( } finish_reason_ = *finish_reason; - flush_all_pending_tool_calls(); + // Function calls are emitted when their output item is done; one that never + // got there was cut off. + pending_tool_calls_.clear(); finished_ = true; if (usage_) { ai::logger::log_info( diff --git a/src/tools/multi_step_coordinator.cpp b/src/tools/multi_step_coordinator.cpp index 4d9cfb2..528fffc 100644 --- a/src/tools/multi_step_coordinator.cpp +++ b/src/tools/multi_step_coordinator.cpp @@ -10,9 +10,14 @@ namespace { // Terminal steps never reach the tool-call feedback path below, so their // assistant reply has to be appended here for response_messages to satisfy // its contract of holding the complete conversation continuation. +bool has_provider_tool_call_turn(const ai::GenerateResult& step_result); + void append_terminal_assistant_reply(const ai::GenerateResult& step_result, ai::Messages& response_messages) { - if (!step_result.response_messages.empty()) { + // A provider-built turn is kept unless it has tool calls: those are not + // answered on a terminal step, and an unanswered call cannot be replayed. + if (!step_result.response_messages.empty() && + !has_provider_tool_call_turn(step_result)) { response_messages.insert(response_messages.end(), step_result.response_messages.begin(), step_result.response_messages.end()); diff --git a/tests/unit/openai_responses_test.cpp b/tests/unit/openai_responses_test.cpp index a10d7b6..87918e6 100644 --- a/tests/unit/openai_responses_test.cpp +++ b/tests/unit/openai_responses_test.cpp @@ -346,6 +346,37 @@ TEST(OpenAIResponsesParserTest, MapsIncompleteAndFailedStatuses) { testing::HasSubstr("The model failed to generate a response.")); } +TEST(OpenAIResponsesParserTest, OutputLimitAfterCompletedFunctionCalls) { + // `max_output_tokens` counts reasoning, so it can cut a turn after a call + // was completed; that call is answered, the truncated one is dropped. + auto response = make_tool_call_response(); + response["status"] = "incomplete"; + response["incomplete_details"] = {{"reason", "max_output_tokens"}}; + response["output"].push_back({{"id", "fc_2"}, + {"type", "function_call"}, + {"status", "incomplete"}, + {"call_id", "call_2"}, + {"name", "weather"}, + {"arguments", R"({"locat)"}}); + + openai::OpenAIResponsesResponseParser parser; + auto result = parser.parse_success_completion_response(response); + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.finish_reason, kFinishReasonToolCalls); + ASSERT_EQ(result.tool_calls.size(), 1u); + EXPECT_EQ(result.tool_calls[0].id, "call_1"); + ASSERT_EQ(result.response_messages.size(), 1u); + EXPECT_EQ(result.response_messages[0].get_tool_calls().size(), 1u); + + // With only the truncated call left, the turn just ran out of tokens. + response["output"].erase(1); + result = parser.parse_success_completion_response(response); + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.finish_reason, kFinishReasonLength); + EXPECT_TRUE(result.tool_calls.empty()); + EXPECT_TRUE(result.response_messages.empty()); +} + TEST(OpenAIResponsesParserTest, RejectsMalformedFunctionCallArguments) { auto response = make_tool_call_response(); response["output"][1]["arguments"] = "{not json"; @@ -413,6 +444,31 @@ TEST(OpenAIResponsesMultiStepTest, FollowUpRequestReplaysReasoning) { EXPECT_EQ(result.response_messages.back().get_text(), "It is 72F."); } +TEST(OpenAIResponsesMultiStepTest, TerminalStepDoesNotKeepUnansweredCalls) { + GenerateOptions options(openai::models::kGpt62Sol, "Weather in Paris?"); + options.max_steps = 3; + + auto result = MultiStepCoordinator::execute_multi_step( + options, [](const GenerateOptions&) { + GenerateResult step("Checking", kFinishReasonLength, Usage{}); + step.tool_calls.emplace_back("call_1", "weather", + JsonValue{{"location", "Paris"}}); + step.response_messages.push_back( + Message(kMessageRoleAssistant, + {ProviderContentPart(openai::kResponsesProviderName, + kReasoningItem), + TextContentPart("Checking"), + ToolCallContentPart("call_1", "weather", + {{"location", "Paris"}})})); + return step; + }); + + // The call was never answered, so only the text of the turn is kept. + ASSERT_EQ(result.response_messages.size(), 1u); + EXPECT_FALSE(result.response_messages[0].has_tool_calls()); + EXPECT_EQ(result.response_messages[0].get_text(), "Checking"); +} + // Streaming TEST(OpenAIResponsesStreamTest, StreamsTextAndUsage) { @@ -482,6 +538,23 @@ TEST(OpenAIResponsesStreamTest, IncompleteResponseFinishesWithLength) { EXPECT_EQ(finish.usage->completion_tokens, 16); } +TEST(OpenAIResponsesStreamTest, DropsTruncatedFunctionCall) { + openai::OpenAIResponsesStreamImpl stream; + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"weather","arguments":""}})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\"loc"})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"weather","arguments":"{\"loc","status":"incomplete"}})"); + stream.process_sse_line_for_testing( + R"(data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}})"); + + ASSERT_EQ(stream.queued_event_count_for_testing(), 1u); + const auto finish = stream.get_next_event(); + ASSERT_TRUE(finish.is_finish()); + EXPECT_EQ(finish.finish_reason, kFinishReasonLength); +} + TEST(OpenAIResponsesStreamTest, FailedResponseEmitsError) { openai::OpenAIResponsesStreamImpl stream; stream.process_sse_line_for_testing(