diff --git a/README.md b/README.md index 584ae93..5761114 100644 --- a/README.md +++ b/README.md @@ -417,6 +417,27 @@ int main() { } ``` +A model that reasons before it answers (the current Claude models do so by +default) returns its reasoning as `reasoningContent` blocks, and Converse wants +them back unchanged, with their signatures, when the results of the tool calls +of the same turn are sent. Such a turn is returned in +`GenerateResult::response_messages` with the blocks as +`ai::ProviderContentPart`s in their place. The multi-step loop +(`max_steps > 1`) replays it automatically, and so do the next requests when +you append `response_messages` to the conversation as they are. The reasoning +blocks of a stream are not returned. + +A reasoning block of a Claude model is valid only in the conversation that it +was made in: its signature records the system prompt, the tools and every +earlier message, and a request that sends the block back after any of them has +changed can be refused (see +[Prefix checks on thinking blocks](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/prefix-checks)). +An application that changes what it has already sent, because it trims the +history or builds the system prompt or the tools again, has to remove the +`ai::ProviderContentPart`s from the messages that it keeps first. All of them +can be left out, and the model goes on from the text, the tool calls and the +results; one in between cannot. + ##### Bedrock Configuration Options ```cpp diff --git a/src/providers/bedrock/bedrock_request_mapper.cpp b/src/providers/bedrock/bedrock_request_mapper.cpp index 0def89c..38cdbfc 100644 --- a/src/providers/bedrock/bedrock_request_mapper.cpp +++ b/src/providers/bedrock/bedrock_request_mapper.cpp @@ -183,6 +183,17 @@ std::optional BedrockRequestMapper::convert_message( {{"toolUseId", tool_result->tool_call_id}, {"content", nlohmann::json::array({std::move(result_content)})}, {"status", tool_result->is_error ? "error" : "success"}}}}); + } else if (const auto* provider_part = + std::get_if(&part)) { + // A block of reasoning that Converse gave in this turn. It goes back as + // it came, signature included, and in its place: before the tool + // calls that it led to. The part of another provider is not for + // Converse. + if (provider_part->provider == kBedrockProviderName && + provider_part->data.is_object() && + provider_part->data.contains("reasoningContent")) { + content.push_back(provider_part->data); + } } } diff --git a/src/providers/bedrock/bedrock_request_mapper.h b/src/providers/bedrock/bedrock_request_mapper.h index d24e2cf..1ff5319 100644 --- a/src/providers/bedrock/bedrock_request_mapper.h +++ b/src/providers/bedrock/bedrock_request_mapper.h @@ -10,6 +10,13 @@ namespace ai { namespace bedrock { +/// `ProviderContentPart::provider` of the blocks of a Converse message that +/// have no provider-neutral form and go back to Converse as they came: the +/// blocks of reasoning (`reasoningContent`). `BedrockResponseParser` records +/// them in the turn of the assistant, and the mapper sends them back in their +/// place when that turn is a part of the next request. +inline constexpr const char* kBedrockProviderName = "bedrock"; + /// Maps SDK options to the body of a Bedrock Converse / ConverseStream /// request class BedrockRequestMapper { diff --git a/src/providers/bedrock/bedrock_response_parser.cpp b/src/providers/bedrock/bedrock_response_parser.cpp index 8e8e2a6..3d8d4db 100644 --- a/src/providers/bedrock/bedrock_response_parser.cpp +++ b/src/providers/bedrock/bedrock_response_parser.cpp @@ -2,6 +2,7 @@ #include "ai/logger.h" #include "bedrock_json.h" +#include "bedrock_request_mapper.h" namespace ai { namespace bedrock { @@ -22,14 +23,25 @@ GenerateResult BedrockResponseParser::parse_converse_response( GenerateResult gen_result; - // The text and the tool calls of the output message + // The blocks of the output message, in their order: the text, the tool + // calls and the reasoning. A block of reasoning (`reasoningContent`: the + // reasoning with its signature, or redacted content) has no + // provider-neutral form, and Converse wants it back as it came, in the turn + // that it is a part of, when the results of the tool calls of that turn are + // sent. It is kept as a `ProviderContentPart`. + MessageContent turn; + bool has_reasoning = false; const auto& content = json_member( json_member(json_member(response, "output"), "message"), "content"); if (content.is_array()) { for (const auto& block : content) { const auto& text = json_member(block, "text"); if (text.is_string()) { - gen_result.text += text.get(); + auto piece = text.get(); + gen_result.text += piece; + if (!piece.empty()) { + turn.emplace_back(TextContentPart{std::move(piece)}); + } } const auto& tool_use = json_member(block, "toolUse"); @@ -39,15 +51,30 @@ GenerateResult BedrockResponseParser::parse_converse_response( json_string(json_member(tool_use, "toolUseId")), json_string(json_member(tool_use, "name")), input.is_null() ? nlohmann::json::object() : input); - ai::logger::log_debug("Parsed Bedrock tool call: {}", - gen_result.tool_calls.back().tool_name); + const auto& call = gen_result.tool_calls.back(); + turn.emplace_back( + ToolCallContentPart{call.id, call.tool_name, call.arguments}); + ai::logger::log_debug("Parsed Bedrock tool call: {}", call.tool_name); + } + + if (json_member(block, "reasoningContent").is_object()) { + turn.emplace_back(ProviderContentPart{kBedrockProviderName, block}); + has_reasoning = true; } } ai::logger::log_debug("Extracted text length: {}", gen_result.text.length()); - // Add assistant response to messages - if (!gen_result.text.empty()) { + // The response message. A turn with reasoning is given as Converse gave + // it, so that it is sent back with the reasoning in its place; reasoning + // alone is not a turn, there is nothing to answer. Without reasoning the + // text is all that the message has to keep: the tool calls are in + // `tool_calls`. + if (has_reasoning && + (!gen_result.text.empty() || !gen_result.tool_calls.empty())) { + gen_result.response_messages.emplace_back(kMessageRoleAssistant, + std::move(turn)); + } else if (!gen_result.text.empty()) { gen_result.response_messages.push_back( Message::assistant(gen_result.text)); } diff --git a/tests/unit/bedrock_converse_test.cpp b/tests/unit/bedrock_converse_test.cpp index b97b699..4a5381b 100644 --- a/tests/unit/bedrock_converse_test.cpp +++ b/tests/unit/bedrock_converse_test.cpp @@ -217,6 +217,63 @@ TEST_F(BedrockConverseTest, RunsToolsBetweenTheSteps) { EXPECT_TRUE(second.contains("toolConfig")); } +// The reasoning of the turn that calls a tool goes back with the result of +// the tool, where it was: before the text and the call +TEST_F(BedrockConverseTest, SendsTheReasoningBackWithTheToolResults) { + services_.runtime->responses = { + FakeBedrockTransport::ok(R"({ + "output": {"message": {"role": "assistant", "content": [ + {"reasoningContent": {"reasoningText": { + "text": "", "signature": "c2lnbmF0dXJl"}}}, + {"text": "Let me check."}, + {"toolUse": {"toolUseId": "call_1", "name": "get_weather", + "input": {"city": "Paris"}}}]}}, + "stopReason": "tool_use", + "usage": {"inputTokens": 20, "outputTokens": 10} + })"), + FakeBedrockTransport::ok(R"({ + "output": {"message": {"role": "assistant", + "content": [{"text": "It is 20 degrees."}]}}, + "stopReason": "end_turn", + "usage": {"inputTokens": 40, "outputTokens": 6} + })"), + }; + BedrockClient client(config_, services_.transports()); + + GenerateOptions options(models::kClaudeSonnet, "Weather in Paris?"); + options.max_steps = 2; + options.tools["get_weather"] = + Tool("Get the weather for a city", + {{"type", "object"}, + {"properties", {{"city", {{"type", "string"}}}}}, + {"required", {"city"}}}, + [](const JsonValue&, const ToolExecutionContext&) { + return JsonValue{{"temperature", 20}}; + }); + + const auto result = client.generate_text(options); + + ASSERT_TRUE(result.is_success()) << result.error_message(); + + const auto requests = services_.runtime->requests(); + ASSERT_EQ(requests.size(), 2); + const Json second = Json::parse(requests[1].body); + ASSERT_EQ(second["messages"].size(), 3); + + const auto& assistant = second["messages"][1]; + EXPECT_EQ(assistant["role"], "assistant"); + ASSERT_EQ(assistant["content"].size(), 3); + EXPECT_EQ(assistant["content"][0], Json::parse(R"({ + "reasoningContent": {"reasoningText": { + "text": "", "signature": "c2lnbmF0dXJl"}}})")); + EXPECT_EQ(assistant["content"][1], (Json{{"text", "Let me check."}})); + EXPECT_EQ(assistant["content"][2]["toolUse"]["toolUseId"], "call_1"); + + const auto& results = second["messages"][2]; + EXPECT_EQ(results["role"], "user"); + EXPECT_EQ(results["content"][0]["toolResult"]["toolUseId"], "call_1"); +} + TEST_F(BedrockConverseTest, StreamsOverConverseStream) { services_.runtime->events = { {"messageStart", R"({"role":"assistant"})"}, diff --git a/tests/unit/bedrock_request_mapper_test.cpp b/tests/unit/bedrock_request_mapper_test.cpp index c11bdbc..754a897 100644 --- a/tests/unit/bedrock_request_mapper_test.cpp +++ b/tests/unit/bedrock_request_mapper_test.cpp @@ -343,6 +343,41 @@ TEST_F(BedrockRequestMapperTest, MapsToolCallsAndResults) { EXPECT_FALSE(body["toolConfig"].contains("toolChoice")); } +// A block of reasoning of a turn goes back as it came and in its place; the +// part of another provider is not sent +TEST_F(BedrockRequestMapperTest, ReplaysReasoningBlocks) { + const Json reasoning = { + {"reasoningContent", + {{"reasoningText", {{"text", ""}, {"signature", "c2lnbmF0dXJl"}}}}}}; + + GenerateOptions options; + options.model = models::kClaudeSonnet; + options.tools = make_weather_tools(); + options.messages = { + Message::user("Weather in Paris?"), + Message( + kMessageRoleAssistant, + {ProviderContentPart{kBedrockProviderName, reasoning}, + ProviderContentPart{"openai-responses", Json{{"type", "reasoning"}}}, + TextContentPart{"Let me check."}, + ToolCallContentPart("call_1", "get_weather", {{"city", "Paris"}})}), + Message::tool_results({ToolResultContentPart( + "call_1", JsonValue{{"temperature", 20}}, false)}), + }; + + const auto body = mapper_.map_to_converse_body(options); + + const auto& messages = body["messages"]; + ASSERT_EQ(messages.size(), 3); + const auto& assistant = messages[1]; + EXPECT_EQ(assistant["role"], "assistant"); + ASSERT_EQ(assistant["content"].size(), 3); + EXPECT_EQ(assistant["content"][0], reasoning); + EXPECT_EQ(assistant["content"][1], text_block("Let me check.")); + EXPECT_EQ(assistant["content"][2]["toolUse"]["toolUseId"], "call_1"); + EXPECT_EQ(messages[2]["role"], "user"); +} + // Bedrock takes only a JSON object as the `json` of a tool result: anything // else is sent as text TEST_F(BedrockRequestMapperTest, MapsToolResultsThatAreNotObjects) { diff --git a/tests/unit/bedrock_response_parser_test.cpp b/tests/unit/bedrock_response_parser_test.cpp index 12af1e4..5c9db67 100644 --- a/tests/unit/bedrock_response_parser_test.cpp +++ b/tests/unit/bedrock_response_parser_test.cpp @@ -77,6 +77,84 @@ TEST_F(BedrockResponseParserTest, ConcatenatesTextBlocks) { EXPECT_EQ(result.response_messages[0].get_text(), "SELECT 1"); } +// A block of reasoning is kept as it came, in its place in the turn: Converse +// wants it back with the results of the tool calls +TEST_F(BedrockResponseParserTest, KeepsReasoningBlocksInTheTurn) { + auto result = parser_.parse_converse_response(R"({ + "output": {"message": {"role": "assistant", "content": [ + {"reasoningContent": {"reasoningText": {"text": "", + "signature": "c2lnbmF0dXJl"}}}, + {"text": "Let me check."}, + {"toolUse": {"toolUseId": "call_1", "name": "get_weather", + "input": {"city": "Paris"}}}]}}, + "stopReason": "tool_use", + "usage": {"inputTokens": 20, "outputTokens": 10} + })"); + + EXPECT_TRUE(result.is_success()); + EXPECT_EQ(result.text, "Let me check."); + EXPECT_EQ(result.finish_reason, kFinishReasonToolCalls); + ASSERT_EQ(result.tool_calls.size(), 1); + EXPECT_EQ(result.tool_calls[0].id, "call_1"); + + ASSERT_EQ(result.response_messages.size(), 1); + const auto& turn = result.response_messages[0]; + EXPECT_EQ(turn.role, kMessageRoleAssistant); + ASSERT_EQ(turn.content.size(), 3); + + const auto* reasoning = std::get_if(&turn.content[0]); + ASSERT_NE(reasoning, nullptr); + EXPECT_EQ(reasoning->provider, "bedrock"); + EXPECT_EQ(reasoning->data, nlohmann::json::parse(R"({ + "reasoningContent": {"reasoningText": {"text": "", + "signature": "c2lnbmF0dXJl"}}})")); + + const auto* text = std::get_if(&turn.content[1]); + ASSERT_NE(text, nullptr); + EXPECT_EQ(text->text, "Let me check."); + + const auto* call = std::get_if(&turn.content[2]); + ASSERT_NE(call, nullptr); + EXPECT_EQ(call->id, "call_1"); + EXPECT_EQ(call->tool_name, "get_weather"); + EXPECT_EQ(call->arguments, (nlohmann::json{{"city", "Paris"}})); +} + +// Redacted reasoning is kept the same way, after the text that it follows +TEST_F(BedrockResponseParserTest, KeepsRedactedReasoning) { + auto result = parser_.parse_converse_response(R"({ + "output": {"message": {"role": "assistant", "content": [ + {"text": "Done."}, + {"reasoningContent": {"redactedContent": "cmVkYWN0ZWQ="}}]}}, + "stopReason": "end_turn" + })"); + + EXPECT_EQ(result.text, "Done."); + ASSERT_EQ(result.response_messages.size(), 1); + const auto& turn = result.response_messages[0]; + ASSERT_EQ(turn.content.size(), 2); + EXPECT_NE(std::get_if(&turn.content[0]), nullptr); + const auto* reasoning = std::get_if(&turn.content[1]); + ASSERT_NE(reasoning, nullptr); + EXPECT_EQ(reasoning->data, nlohmann::json::parse(R"({ + "reasoningContent": {"redactedContent": "cmVkYWN0ZWQ="}})")); +} + +// Reasoning alone is not a turn of the conversation +TEST_F(BedrockResponseParserTest, ReasoningAloneIsNotATurn) { + auto result = parser_.parse_converse_response(R"({ + "output": {"message": {"role": "assistant", "content": [ + {"reasoningContent": {"reasoningText": {"text": "Hm.", + "signature": "c2lnbmF0dXJl"}}}]}}, + "stopReason": "end_turn" + })"); + + EXPECT_TRUE(result.is_success()); + EXPECT_TRUE(result.text.empty()); + EXPECT_TRUE(result.tool_calls.empty()); + EXPECT_TRUE(result.response_messages.empty()); +} + // A tool call without an input has an empty object as its arguments TEST_F(BedrockResponseParserTest, ToolCallWithoutInput) { auto result = parser_.parse_converse_response(R"({