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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions src/providers/bedrock/bedrock_request_mapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,17 @@ std::optional<nlohmann::json> 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<ProviderContentPart>(&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);
}
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/providers/bedrock/bedrock_request_mapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
39 changes: 33 additions & 6 deletions src/providers/bedrock/bedrock_response_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "ai/logger.h"
#include "bedrock_json.h"
#include "bedrock_request_mapper.h"

namespace ai {
namespace bedrock {
Expand All @@ -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<std::string>();
auto piece = text.get<std::string>();
gen_result.text += piece;
if (!piece.empty()) {
turn.emplace_back(TextContentPart{std::move(piece)});
}
}

const auto& tool_use = json_member(block, "toolUse");
Expand All @@ -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));
}
Expand Down
57 changes: 57 additions & 0 deletions tests/unit/bedrock_converse_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"})"},
Expand Down
35 changes: 35 additions & 0 deletions tests/unit/bedrock_request_mapper_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
78 changes: 78 additions & 0 deletions tests/unit/bedrock_response_parser_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<ProviderContentPart>(&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<TextContentPart>(&turn.content[1]);
ASSERT_NE(text, nullptr);
EXPECT_EQ(text->text, "Let me check.");

const auto* call = std::get_if<ToolCallContentPart>(&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<TextContentPart>(&turn.content[0]), nullptr);
const auto* reasoning = std::get_if<ProviderContentPart>(&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"({
Expand Down
Loading