From b5f793591db63056fd8e37aa0875ce52832907b4 Mon Sep 17 00:00:00 2001 From: Alexey Milovidov Date: Fri, 4 Dec 2026 21:11:27 +0000 Subject: [PATCH] Replay the phase of assistant messages over the Responses API, add `GenerateOptions::store` The Responses API gives an assistant message a `phase`: `commentary` for a preamble before tool calls, `final_answer` for the answer. A client that replays the history by itself has to send each message back with its phase: without it a preamble can be taken for the final answer. The parser reduced a message to its text, and the request builder rebuilt the assistant messages without the field. Now the parser records the phase of a message as a `ProviderContentPart` right before the text of the message, next to the `reasoning` items that it records already, and the builder sends the text that follows such a part as a message of its own with that phase. A message without a phase is built as before. Add `GenerateOptions::store`. A Responses API request always said `store: false`, and a Chat Completions request could not say it at all, while OpenAI stores Chat Completions by default for new accounts. Nothing changes when the option is not set: a Responses API request says `false`, and a Chat Completions request does not say. Co-Authored-By: Claude Fable 5.2 --- README.md | 18 ++- include/ai/openai.h | 7 +- include/ai/types/generate_options.h | 7 + .../openai/openai_request_builder.cpp | 5 + .../openai_responses_request_builder.cpp | 29 +++- .../openai/openai_responses_request_builder.h | 9 +- .../openai_responses_response_parser.cpp | 8 + .../openai/openai_responses_response_parser.h | 7 +- tests/unit/openai_client_test.cpp | 14 ++ tests/unit/openai_responses_test.cpp | 137 ++++++++++++++++++ 10 files changed, 221 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 2cebb9a..8678cfd 100644 --- a/README.md +++ b/README.md @@ -249,13 +249,17 @@ int main() { } ``` -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 +Requests are stateless, and the whole conversation is sent with every request. +A request says `store: false` unless you set `GenerateOptions::store`. (A Chat +Completions request says nothing about storing unless you set it.) When a +reasoning model calls tools, the API requires its `reasoning` items to be sent +back with the tool results, and a message has to come back with the `phase` +the model gave it: without it a preamble before tool calls can be taken for +the final answer. Both 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 diff --git a/include/ai/openai.h b/include/ai/openai.h index b00aa6c..237306f 100644 --- a/include/ai/openai.h +++ b/include/ai/openai.h @@ -100,9 +100,10 @@ std::optional try_create_client(); /// 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 +/// Requests are stateless: the conversation is replayed on every request, and +/// a request says `store: false` unless `GenerateOptions::store` says +/// otherwise. The `reasoning` items of a reply and the `phase` of its messages +/// 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 diff --git a/include/ai/types/generate_options.h b/include/ai/types/generate_options.h index bfa27f8..42c6bc0 100644 --- a/include/ai/types/generate_options.h +++ b/include/ai/types/generate_options.h @@ -26,6 +26,13 @@ struct GenerateOptions { std::optional frequency_penalty; std::optional presence_penalty; + /// Whether the provider may store the request and its output, for a provider + /// that takes such a parameter: `store` of OpenAI. When it is not set, a + /// Responses API request says `false`, because it replays the whole + /// conversation by itself, and a Chat Completions request does not say, + /// which leaves it to the default of the account. + std::optional store; + // Tool calling support ToolSet tools; ToolChoice tool_choice = ToolChoice::auto_choice(); diff --git a/src/providers/openai/openai_request_builder.cpp b/src/providers/openai/openai_request_builder.cpp index f3f70f6..fe8689b 100644 --- a/src/providers/openai/openai_request_builder.cpp +++ b/src/providers/openai/openai_request_builder.cpp @@ -20,6 +20,11 @@ nlohmann::json OpenAIRequestBuilder::build_request_json( if (options.response_format) { request["response_format"] = options.response_format.value(); } + // Left out unless the caller says: a compatible service may not know the + // parameter, and OpenAI then applies the default of the account. + if (options.store) { + request["store"] = *options.store; + } // Build messages array if (!options.messages.empty()) { // Prepend system as a message when caller supplies a messages array; the diff --git a/src/providers/openai/openai_responses_request_builder.cpp b/src/providers/openai/openai_responses_request_builder.cpp index 3adbd33..cc34d29 100644 --- a/src/providers/openai/openai_responses_request_builder.cpp +++ b/src/providers/openai/openai_responses_request_builder.cpp @@ -43,10 +43,14 @@ std::map function_call_item_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. +/// provider items (`reasoning`) verbatim. A message that the parser recorded a +/// `phase` for is replayed as a message of its own with that phase: without it +/// a preamble before tool calls can be taken for the final answer. void append_assistant_items(const Message& message, nlohmann::json& input) { const auto item_ids = function_call_item_ids(message); std::string pending_text; + // The phase of the message whose text is the next text part. + std::optional next_phase; const auto flush_text = [&]() { if (!pending_text.empty()) { input.push_back( @@ -57,9 +61,18 @@ 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; + if (next_phase) { + flush_text(); + auto item = make_text_message(kMessageRoleAssistant, text_part->text); + item["phase"] = std::move(*next_phase); + next_phase.reset(); + input.push_back(std::move(item)); + } else { + pending_text += text_part->text; + } } else if (const auto* tool_call = std::get_if(&part)) { + next_phase.reset(); flush_text(); nlohmann::json item{{"type", "function_call"}, {"call_id", tool_call->id}, @@ -76,7 +89,17 @@ void append_assistant_items(const Message& message, nlohmann::json& input) { provider_part->data.value("type", "") == "function_call") { continue; } + next_phase.reset(); flush_text(); + // The record of a message is not an item: it says what the phase of the + // message in the next text part is. + if (provider_part->data.value("type", "") == "message") { + if (const auto phase = provider_part->data.find("phase"); + phase != provider_part->data.end() && phase->is_string()) { + next_phase = phase->get(); + } + continue; + } input.push_back(provider_part->data); } } @@ -141,7 +164,7 @@ nlohmann::json OpenAIResponsesRequestBuilder::build_request_json( {"input", build_input(options)}, // Stateless: every request replays the whole // conversation, so nothing has to be stored. - {"store", false}}; + {"store", options.store.value_or(false)}}; if (!options.system.empty()) { request["instructions"] = options.system; diff --git a/src/providers/openai/openai_responses_request_builder.h b/src/providers/openai/openai_responses_request_builder.h index 3fd561b..b8aab20 100644 --- a/src/providers/openai/openai_responses_request_builder.h +++ b/src/providers/openai/openai_responses_request_builder.h @@ -14,10 +14,11 @@ 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`. +/// Requests are stateless: the conversation, including the `reasoning` items +/// of earlier turns and the `phase` of their messages (carried as +/// `ProviderContentPart`s), is replayed in `input` on every request instead of +/// being referenced by `previous_response_id`. So a request says +/// `store: false`, unless `GenerateOptions::store` says otherwise. class OpenAIResponsesRequestBuilder : public OpenAIRequestBuilder { public: using OpenAIRequestBuilder::build_request_json; diff --git a/src/providers/openai/openai_responses_response_parser.cpp b/src/providers/openai/openai_responses_response_parser.cpp index 04b82a0..dfb91ce 100644 --- a/src/providers/openai/openai_responses_response_parser.cpp +++ b/src/providers/openai/openai_responses_response_parser.cpp @@ -122,6 +122,14 @@ GenerateResult OpenAIResponsesResponseParser::parse_success_completion_response( } if (!text.empty()) { result.text += text; + // The phase tells a preamble before tool calls (`commentary`) from + // the answer (`final_answer`). It has to come back with the message + // when the history is replayed, so it is kept right before the text. + if (const auto phase = string_field(item, "phase"); !phase.empty()) { + turn.emplace_back( + ProviderContentPart{kResponsesProviderName, + {{"type", "message"}, {"phase", phase}}}); + } turn.emplace_back(TextContentPart{std::move(text)}); } } else if (type == "function_call" && diff --git a/src/providers/openai/openai_responses_response_parser.h b/src/providers/openai/openai_responses_response_parser.h index 2b041d4..41220cf 100644 --- a/src/providers/openai/openai_responses_response_parser.h +++ b/src/providers/openai/openai_responses_response_parser.h @@ -15,9 +15,10 @@ namespace openai { /// /// 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`. +/// `ToolCallContentPart`, and what has to be replayed along with them (the +/// `reasoning` items, the item IDs of the function calls, and the `phase` of a +/// message, right before its text) as `ProviderContentPart`s named +/// `kResponsesProviderName`. class OpenAIResponsesResponseParser : public OpenAIResponseParser { public: GenerateResult parse_success_completion_response( diff --git a/tests/unit/openai_client_test.cpp b/tests/unit/openai_client_test.cpp index fa39f6f..07582d0 100644 --- a/tests/unit/openai_client_test.cpp +++ b/tests/unit/openai_client_test.cpp @@ -243,6 +243,20 @@ TEST_F(OpenAIClientTest, NonReasoningModelsKeepSamplingParameters) { EXPECT_EQ(request["top_p"], 0.9); } +TEST_F(OpenAIClientTest, SaysWhetherToStoreOnlyWhenTheCallerDoes) { + openai::OpenAIRequestBuilder builder; + GenerateOptions options(openai::models::kGpt41, "Hello"); + + // A compatible service may not know the parameter. + EXPECT_FALSE(builder.build_request_json(options).contains("store")); + + options.store = false; + EXPECT_EQ(builder.build_request_json(options)["store"], false); + + options.store = true; + EXPECT_EQ(builder.build_request_json(options)["store"], true); +} + // Stream Tests (Basic validation) TEST_F(OpenAIClientTest, StreamTextBasicValidation) { auto options = StreamOptions(GenerateOptions(kTestModel, kTestPrompt)); diff --git a/tests/unit/openai_responses_test.cpp b/tests/unit/openai_responses_test.cpp index 87918e6..21a69c8 100644 --- a/tests/unit/openai_responses_test.cpp +++ b/tests/unit/openai_responses_test.cpp @@ -54,6 +54,24 @@ nlohmann::json make_tool_call_response() { {"total_tokens", 105}}}}; } +/// A preamble before a tool call: a message of the `commentary` phase, then +/// the reasoning and the call. +nlohmann::json make_preamble_and_tool_call_response() { + auto response = make_tool_call_response(); + response["output"].insert( + response["output"].begin(), + nlohmann::json{{"id", "msg_1"}, + {"type", "message"}, + {"role", "assistant"}, + {"status", "completed"}, + {"phase", "commentary"}, + {"content", + {{{"type", "output_text"}, + {"text", "Let me look."}, + {"annotations", nlohmann::json::array()}}}}}); + return response; +} + } // namespace // Request building @@ -211,6 +229,103 @@ TEST(OpenAIResponsesRequestTest, ReplaysToolRoundTripWithReasoningInOrder) { {"output", R"({"temperature":72})"}})); } +TEST(OpenAIResponsesRequestTest, ReplaysThePhaseOfAssistantMessages) { + openai::OpenAIResponsesResponseParser parser; + auto first_step = parser.parse_success_completion_response( + make_preamble_and_tool_call_response()); + ASSERT_EQ(first_step.response_messages.size(), 1u); + + const nlohmann::json answer_response = { + {"id", "resp_2"}, + {"status", "completed"}, + {"output", + {{{"id", "msg_2"}, + {"type", "message"}, + {"role", "assistant"}, + {"status", "completed"}, + {"phase", "final_answer"}, + {"content", + {{{"type", "output_text"}, + {"text", "It is warm."}, + {"annotations", nlohmann::json::array()}}}}}}}}; + auto second_step = parser.parse_success_completion_response(answer_response); + ASSERT_EQ(second_step.response_messages.size(), 1u); + // The text of the turn is the text of the message, as without a phase. + EXPECT_EQ(second_step.text, "It is warm."); + EXPECT_EQ(second_step.response_messages[0].get_text(), "It is warm."); + + Messages conversation = {Message::user("Weather in Paris?")}; + conversation.push_back(first_step.response_messages[0]); + conversation.push_back(Message::tool_results( + {ToolResultContentPart("call_1", {{"temperature", 72}})})); + conversation.push_back(second_step.response_messages[0]); + conversation.push_back(Message::user("And tomorrow?")); + + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt62Sol, std::move(conversation)); + const auto input = builder.build_request_json(options)["input"]; + + // Each message comes back with its phase, in its place among the items: + // without it a preamble can be taken for the answer. + ASSERT_EQ(input.size(), 7u); + EXPECT_EQ(input[0]["role"], "user"); + EXPECT_EQ(input[1], nlohmann::json({{"type", "message"}, + {"role", "assistant"}, + {"phase", "commentary"}, + {"content", "Let me look."}})); + EXPECT_EQ(input[2], kReasoningItem); + EXPECT_EQ(input[3]["type"], "function_call"); + EXPECT_EQ(input[4]["type"], "function_call_output"); + EXPECT_EQ(input[5], nlohmann::json({{"type", "message"}, + {"role", "assistant"}, + {"phase", "final_answer"}, + {"content", "It is warm."}})); + EXPECT_EQ(input[6]["role"], "user"); + EXPECT_FALSE(input[6].contains("phase")); +} + +TEST(OpenAIResponsesRequestTest, MessagesWithoutPhaseStayAsTheyWere) { + // A message that the provider gave no phase gets none, also next to one + // that has a phase, and a phase whose text is gone is not given to the text + // that follows. + Messages conversation = { + Message::user("Hi"), + Message( + kMessageRoleAssistant, + {TextContentPart("One. "), TextContentPart("Two."), + ProviderContentPart(openai::kResponsesProviderName, + {{"type", "message"}, {"phase", "commentary"}}), + TextContentPart("Three."), TextContentPart("Four."), + ProviderContentPart(openai::kResponsesProviderName, + {{"type", "message"}, {"phase", "commentary"}}), + ToolCallContentPart("call_9", "weather", {{"location", "Rome"}}), + TextContentPart("Five.")})}; + + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt62Sol, std::move(conversation)); + const auto input = builder.build_request_json(options)["input"]; + + ASSERT_EQ(input.size(), 6u); + EXPECT_EQ(input[1]["content"], "One. Two."); + EXPECT_FALSE(input[1].contains("phase")); + EXPECT_EQ(input[2]["content"], "Three."); + EXPECT_EQ(input[2]["phase"], "commentary"); + EXPECT_EQ(input[3]["content"], "Four."); + EXPECT_FALSE(input[3].contains("phase")); + EXPECT_EQ(input[4]["type"], "function_call"); + EXPECT_EQ(input[5]["content"], "Five."); + EXPECT_FALSE(input[5].contains("phase")); +} + +TEST(OpenAIResponsesRequestTest, StoresOnlyWhenTheCallerSays) { + openai::OpenAIResponsesRequestBuilder builder; + GenerateOptions options(openai::models::kGpt62Sol, "Hello"); + EXPECT_EQ(builder.build_request_json(options)["store"], false); + + options.store = true; + EXPECT_EQ(builder.build_request_json(options)["store"], true); +} + TEST(OpenAIResponsesRequestTest, BuildsFunctionCallsFromPlainMessages) { // Messages built by hand (or by another provider) carry no provider parts. Messages conversation = { @@ -312,6 +427,28 @@ TEST(OpenAIResponsesParserTest, ParsesFunctionCallsAndKeepsReasoning) { EXPECT_EQ(turn.get_tool_calls()[0].id, "call_1"); } +TEST(OpenAIResponsesParserTest, KeepsThePhaseOfAMessageBeforeItsText) { + openai::OpenAIResponsesResponseParser parser; + const auto result = parser.parse_success_completion_response( + make_preamble_and_tool_call_response()); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + EXPECT_EQ(result.text, "Let me look."); + ASSERT_EQ(result.response_messages.size(), 1u); + const auto& turn = result.response_messages[0]; + + // The phase, the text, the reasoning, the item of the call, the call. + ASSERT_EQ(turn.content.size(), 5u); + const auto* phase = std::get_if(&turn.content[0]); + ASSERT_NE(phase, nullptr); + EXPECT_EQ(phase->provider, openai::kResponsesProviderName); + EXPECT_EQ(phase->data, + nlohmann::json({{"type", "message"}, {"phase", "commentary"}})); + const auto* text = std::get_if(&turn.content[1]); + ASSERT_NE(text, nullptr); + EXPECT_EQ(text->text, "Let me look."); +} + TEST(OpenAIResponsesParserTest, MapsIncompleteAndFailedStatuses) { openai::OpenAIResponsesResponseParser parser;