adapter_base.cpp¶
src/inference/adapters/adapter_base.cpp
@file adapter_base.cpp @brief ChatAdapter base class implementation.
Owners: @tvanfossen
action_envelope_to_call
static std::optional< ToolCall > entropic::action_envelope_to_call(const nlohmann::json &j)
Map one parsed JSON object to a recovered ToolCall .
src/inference/adapters/adapter_base.cpp:264
Source · 24 lines
static std::optional<ToolCall> action_envelope_to_call(
const nlohmann::json& j) {
if (auto tc = tool_call_from_json(j)) { return tc; }
// gh#88: meta-tools whose result `action` verb equals their tool name.
// TodoTool (add/update/remove) and free-text actions are excluded.
static const std::unordered_set<std::string> kMetaActions = {
"delegate", "pipeline", "complete",
"phase_change", "prune_context", "resume_delegation"};
std::string action;
if (j.contains("action") && j["action"].is_string()) {
action = j["action"].get<std::string>();
}
if (kMetaActions.find(action) == kMetaActions.end()) {
return std::nullopt;
}
ToolCall tc;
tc.id = generate_uuid();
tc.name = "entropic." + action;
nlohmann::json args = j;
args.erase("action");
tc.arguments_json = args.dump();
for (auto& [k, v] : args.items()) { tc.arguments[k] = v.dump(); }
return tc;
}Activity · 17 steps
Requirements
apply_action_envelope_recovery
void entropic::apply_action_envelope_recovery(std::vector< ToolCall > &calls, const std::string &raw)
gh#88: substitute recovered bare-JSON calls when a reliable (PEG_GEMMA4 / gemma) parse produced none; logs the recovery.
src/inference/adapters/adapter_base.cpp:320
Source · 11 lines
void apply_action_envelope_recovery(std::vector<ToolCall>& calls,
const std::string& raw) {
if (!calls.empty()) { return; }
auto recovered = recover_action_envelope_calls(raw);
if (recovered.empty()) { return; }
logger->warn(
"gh#88: PEG_GEMMA4 parsed 0 tool calls; recovered {} from a "
"bare-JSON {{\"action\":...}} envelope (possible context priming)",
recovered.size());
calls = std::move(recovered);
}Activity · 7 steps
Requirements
coerce_call_string_args
static void entropic::coerce_call_string_args(ToolCall &tc, const nlohmann::json &tools)
Coerce one call's numeric args to strings per the tool schema.
src/inference/adapters/adapter_base.cpp:369
Source · 20 lines
static void coerce_call_string_args(ToolCall& tc, const nlohmann::json& tools) {
auto props = tool_string_props(tools, tc.name);
if (props.empty()) { return; }
auto args = nlohmann::json::parse(tc.arguments_json, nullptr, false);
if (!args.is_object()) { return; }
bool changed = false;
for (const auto& key : props) {
auto it = args.find(key);
if (it != args.end() && it->is_number()) {
*it = it->dump(); // JSON number 3 → JSON string "3"
changed = true;
}
}
if (!changed) { return; }
tc.arguments_json = args.dump();
for (auto it = args.begin(); it != args.end(); ++it) {
tc.arguments[it.key()] =
it->is_string() ? it->get<std::string>() : it->dump();
}
}Activity · 17 steps
Requirements
coerce_string_typed_args
void entropic::coerce_string_typed_args(std::vector< ToolCall > &calls, const std::string &tools_json)
gh#90: coerce numeric scalars back to strings for string-typed tool parameters.
src/inference/adapters/adapter_base.cpp:397
Source · 7 lines
void coerce_string_typed_args(std::vector<ToolCall>& calls,
const std::string& tools_json) {
if (calls.empty() || tools_json.empty()) { return; }
auto tools = nlohmann::json::parse(tools_json, nullptr, false);
if (!tools.is_array()) { return; }
for (auto& tc : calls) { coerce_call_string_args(tc, tools); }
}Activity · 7 steps
Requirements
parse_recovered_tool_call
static std::optional< ToolCall > entropic::parse_recovered_tool_call(const std::string &fixed)
Parse a brace/quote-fixed JSON string into a ToolCall .
src/inference/adapters/adapter_base.cpp:472
Source · 5 lines
static std::optional<ToolCall> parse_recovered_tool_call(
const std::string& fixed) {
auto j = nlohmann::json::parse(fixed);
return tool_call_from_json(j);
}Activity · 2 steps
Requirements
parse_tagged_tool_calls
std::vector< ToolCall > entropic::ChatAdapter::parse_tagged_tool_calls(const std::string &content) const
Parse JSON tagged blocks.
src/inference/adapters/adapter_base.cpp:180
Called by parse_tool_calls, parse_tool_calls, parse_tool_calls, parse_tool_calls, parse_tool_calls
Calls parse_single_tool_call
Source · 62 lines
std::vector<ToolCall> ChatAdapter::parse_tagged_tool_calls(
const std::string& content) const
{
std::vector<ToolCall> calls;
// gh#65 (v2.3.3): accept asymmetric open tags. Gemma 4 emits
// `<|tool_call>` (pipe-prefixed open, plain close) — the special
// token `<|tool_call|>` decodes through llama.cpp's current pin
// as `<|tool_call>` (trailing `|>` lost). Pre-v2.3.3 the regex
// required a plain `<tool_call>` open, so Gemma 4's actual output
// produced 0 tool calls and the engine looped on the retry banner.
//
// gh#69 (v2.3.8): add `<|im_start|>tool_call` as a fourth open
// variant. Gemma 4 (E2B + E4B) emits its tool calls inside a
// ChatML-style channel whose opening header is `<|im_start|>tool_call`
// but whose close is the plain `</tool_call>` — an asymmetric pair
// the prior three alternatives didn't cover, so both Gemma 4 sizes
// scored 0/6 completion (agent loop spiralled to the iteration cap).
//
// Open alternatives: `<tool_call>`, `<|tool_call>`, `<|tool_call|>`,
// `<|im_start|>tool_call`. Close tag stays `</tool_call>` — that's
// what the consumer's transcripts consistently show.
std::regex pattern(
R"((?:<tool_call>|<\|tool_call\|?>|<\|im_start\|>tool_call)\s*)"
R"(([\s\S]*?)\s*</tool_call>)");
auto begin = std::sregex_iterator(content.begin(), content.end(), pattern);
auto end = std::sregex_iterator();
for (auto it = begin; it != end; ++it) {
std::string json_str = (*it)[1].str();
auto parsed = parse_single_tool_call(json_str);
if (parsed) {
calls.push_back(*parsed);
logger->info("Parsed tagged tool call: {}", parsed->name);
} else {
// gh#65: when the regex matches but parse_single_tool_call
// returns nullopt, the JSON payload was malformed in a way
// try_recover_json could not fix. Log the offending text so
// future investigations have something to grep, instead of
// silently producing zero tool calls.
logger->warn(
"Tagged tool_call matched but JSON failed to parse: {}",
json_str);
}
}
// gh#65/gh#69: model emitted tool_call markup but no regex match.
// Catches plain `<tool_call>`, pipe-prefixed `<|tool_call`, and the
// Gemma 4 channel header `<|im_start|>tool_call` substrings — if
// none matched the full pattern, surface the raw content's length so
// the consumer can attach it for triage instead of seeing a silent
// "tool_calls: 0".
if (calls.empty()
&& (content.find("<tool_call>") != std::string::npos
|| content.find("<|tool_call") != std::string::npos
|| content.find("<|im_start|>tool_call") != std::string::npos)) {
logger->warn(
"Content contains tool_call markup but no tagged calls "
"were extracted — possible tag/encoding mismatch. "
"Raw content length={}", content.size());
}
return calls;
}Activity · 15 steps
Requirements
recover_action_envelope_calls
std::vector< ToolCall > entropic::recover_action_envelope_calls(const std::string &raw)
gh#88: recover tool calls a gemma model parroted as bare-JSON.
src/inference/adapters/adapter_base.cpp:297
Called by TEST_CASE, apply_action_envelope_recovery, parse_tool_calls
Calls action_envelope_to_call
Source · 15 lines
std::vector<ToolCall> recover_action_envelope_calls(const std::string& raw) {
std::vector<ToolCall> calls;
std::istringstream stream(raw);
std::string line;
while (std::getline(stream, line)) {
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos || line[start] != '{') { continue; }
auto j = nlohmann::json::parse(line.substr(start), nullptr, false);
if (!j.is_object()) { continue; }
if (auto tc = action_envelope_to_call(j)) {
calls.push_back(std::move(*tc));
}
}
return calls;
}Activity · 13 steps
Requirements
regex_recovered_tool_call
static std::optional< ToolCall > entropic::regex_recovered_tool_call(const std::string &json_str)
Last-ditch recovery: pull a tool name out via regex.
src/inference/adapters/adapter_base.cpp:485
Source · 29 lines
static std::optional<ToolCall> regex_recovered_tool_call(
const std::string& json_str) {
std::regex name_pattern(R"re("name"\s*:\s*"([^"]+)")re");
std::smatch match;
if (!std::regex_search(json_str, match, name_pattern)) {
return std::nullopt;
}
ToolCall tc;
tc.id = generate_uuid();
tc.name = match[1].str();
return tc;
}
/**
* @brief Attempt JSON recovery on malformed tool call string.
*
* Tries: trailing comma removal, quote normalization, brace matching.
*
* @param json_str Potentially malformed JSON.
* @return Recovered ToolCall if any repair produced a named call; nullopt
* when even the regex last-ditch pass finds no tool name.
* @req REQ-INFER-012
* @version 2.3.7
*/
std::optional<ToolCall> ChatAdapter::try_recover_json(
const std::string& json_str) const
{
// Fix trailing commas and single quotes
std::string fixed = std::regex_replace(json_str, std::regex(R"(,\s*\})"), "}");Activity · 8 steps
Requirements
strip_think_blocks
std::string entropic::ChatAdapter::strip_think_blocks(const std::string &content) const
Strip this family's reasoning blocks from content (gh#108).
src/inference/adapters/adapter_base.cpp:426
Called by SCENARIO, clean_content, clean_content, clean_content, is_response_complete, parse_model_response, parse_tool_calls, parse_tool_calls, parse_tool_calls
Calls thinking_markers
Source · 36 lines
std::string ChatAdapter::strip_think_blocks(const std::string& content) const {
const auto markers = thinking_markers();
std::string result = content;
bool truncated_unclosed = false;
std::size_t pos;
while ((pos = result.find(markers.open)) != std::string::npos) {
auto close = result.find(markers.close, pos + markers.open.size());
// Unclosed: generation stopped mid-reasoning, so no answer was ever
// produced. Erasing to the end beats surfacing raw reasoning.
if (close == std::string::npos) { truncated_unclosed = true; }
auto span_end = (close == std::string::npos)
? result.size() : close + markers.close.size();
result.erase(pos, span_end - pos);
}
// gh#108 (v2.10.3): without this the caller sees empty content and cannot
// tell a stalled generation from a parse failure or an engine bug — the
// same diagnostic dead end gh#130 fixed on the bridge. Carried over from
// strip_thinking_channels, whose behaviour this consolidates.
if (truncated_unclosed && result.find_first_not_of(" \t\r\n")
== std::string::npos) {
logger->warn(
"Reasoning block '{}' was never closed with '{}', so the strip "
"removed the whole generation and content is empty. Not a parse "
"error. The orchestrator reports the actual cause (budget vs the "
"model ending the turn) — it is the only layer holding "
"finish_reason. gh#137.",
markers.open, markers.close);
}
size_t start = result.find_first_not_of(" \t\n\r");
if (start == std::string::npos) { return ""; }
size_t end_pos = result.find_last_not_of(" \t\n\r");
return result.substr(start, end_pos - start + 1);
}