Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions include/ai/openai.h
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,10 @@ std::optional<Client> 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
Expand Down
7 changes: 7 additions & 0 deletions include/ai/types/generate_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ struct GenerateOptions {
std::optional<double> frequency_penalty;
std::optional<double> 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<bool> store;

// Tool calling support
ToolSet tools;
ToolChoice tool_choice = ToolChoice::auto_choice();
Expand Down
5 changes: 5 additions & 0 deletions src/providers/openai/openai_request_builder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 26 additions & 3 deletions src/providers/openai/openai_responses_request_builder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,14 @@ std::map<std::string, std::string> 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<std::string> next_phase;
const auto flush_text = [&]() {
if (!pending_text.empty()) {
input.push_back(
Expand All @@ -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<TextContentPart>(&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<ToolCallContentPart>(&part)) {
next_phase.reset();
flush_text();
nlohmann::json item{{"type", "function_call"},
{"call_id", tool_call->id},
Expand All @@ -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<std::string>();
}
continue;
}
input.push_back(provider_part->data);
}
}
Expand Down Expand Up @@ -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;
Expand Down
9 changes: 5 additions & 4 deletions src/providers/openai/openai_responses_request_builder.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions src/providers/openai/openai_responses_response_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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" &&
Expand Down
7 changes: 4 additions & 3 deletions src/providers/openai/openai_responses_response_parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions tests/unit/openai_client_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
137 changes: 137 additions & 0 deletions tests/unit/openai_responses_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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<ProviderContentPart>(&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<TextContentPart>(&turn.content[1]);
ASSERT_NE(text, nullptr);
EXPECT_EQ(text->text, "Let me look.");
}

TEST(OpenAIResponsesParserTest, MapsIncompleteAndFailedStatuses) {
openai::OpenAIResponsesResponseParser parser;

Expand Down
Loading