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
lines 266–266◇ if (auto tc = tool_call_from_json(j))lines 266–266return tc;lines 269–271static const std::unordered_set<std::string> kMetaActions = { "delegate", "pipeline", "complete", "phase_change", "prune_context", "resume_delegation"};lines 272–272std::string action;lines 273–273◇ if (j.contains("action") && j["action"].is_string())lines 274–274action = j["action"].get<std::string>();lines 276–276◇ if (kMetaActions.find(action) == kMetaActions.end())lines 277–277return std::nullopt;lines 279–279ToolCall tc;lines 280–280tc.id = generate_uuid();lines 281–281tc.name = "entropic." + action;lines 282–282nlohmann::json args = j;lines 283–283args.erase("action");lines 284–284tc.arguments_json = args.dump();lines 285–285◇ for (auto& [k, v] : args.items())lines 285–285tc.arguments[k] = v.dump();lines 286–286return tc;

Requirements

REQ-INFER-012

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
lines 322–322◇ if (!calls.empty())lines 322–322return;lines 323–323auto recovered = recover_action_envelope_calls(raw);lines 324–324◇ if (recovered.empty())lines 324–324return;lines 325–328logger->warn( "gh#88: PEG_GEMMA4 parsed 0 tool calls; recovered {} from a " "bare-JSON {{\"action\":...}} envelope (possible context priming)", recovered.size());lines 329–329calls = std::move(recovered);

Requirements

REQ-INFER-012

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

Show on the map →

Called by coerce_string_typed_args

Calls tool_string_props

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
lines 370–370auto props = tool_string_props(tools, tc.name);lines 371–371◇ if (props.empty())lines 371–371return;lines 372–372auto args = nlohmann::json::parse(tc.arguments_json, nullptr, false);lines 373–373◇ if (!args.is_object())lines 373–373return;lines 374–374bool changed = false;lines 375–375◇ for (const auto& key : props)lines 376–376auto it = args.find(key);lines 377–377◇ if (it != args.end() && it->is_number())lines 378–378*it = it->dump();lines 379–379changed = true;lines 382–382◇ if (!changed)lines 382–382return;lines 383–383tc.arguments_json = args.dump();lines 384–384◇ for (auto it = args.begin(); it != args.end(); ++it)lines 385–386tc.arguments[it.key()] = it->is_string() ? it->get<std::string>() : it->dump();

Requirements

REQ-INFER-012

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
lines 399–399◇ if (calls.empty() || tools_json.empty())lines 399–399return;lines 400–400auto tools = nlohmann::json::parse(tools_json, nullptr, false);lines 401–401◇ if (!tools.is_array())lines 401–401return;lines 402–402◇ for (auto& tc : calls)lines 402–402coerce_call_string_args(tc, tools);

Requirements

REQ-INFER-012

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

Show on the map →

Called by none

Calls tool_call_from_json

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
lines 474–474auto j = nlohmann::json::parse(fixed);lines 475–475return tool_call_from_json(j);

Requirements

REQ-INFER-012

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

Show on the map →

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
lines 183–183std::vector<ToolCall> calls;lines 201–203std::regex pattern( R"((?:<tool_call>|<\|tool_call\|?>|<\|im_start\|>tool_call)\s*)" R"(([\s\S]*?)\s*</tool_call>)");lines 205–205auto begin = std::sregex_iterator(content.begin(), content.end(), pattern);lines 206–206auto end = std::sregex_iterator();lines 208–208◇ for (auto it = begin; it != end; ++it)lines 209–209std::string json_str = (*it)[1].str();lines 210–210auto parsed = parse_single_tool_call(json_str);lines 211–211◇ if (parsed)lines 212–212calls.push_back(*parsed);lines 213–213logger->info("Parsed tagged tool call: {}", parsed->name);lines 214–214elselines 220–222logger->warn( "Tagged tool_call matched but JSON failed to parse: {}", json_str);lines 231–234◇ 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))lines 235–238logger->warn( "Content contains tool_call markup but no tagged calls " "were extracted — possible tag/encoding mismatch. " "Raw content length={}", content.size());lines 240–240return calls;

Requirements

REQ-INFER-012

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

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
lines 298–298std::vector<ToolCall> calls;lines 299–299std::istringstream stream(raw);lines 300–300std::string line;lines 301–301◇ while (std::getline(stream, line))lines 302–302size_t start = line.find_first_not_of(" \t");lines 303–303◇ if (start == std::string::npos || line[start] != '{')lines 303–303continue;lines 304–304auto j = nlohmann::json::parse(line.substr(start), nullptr, false);lines 305–305◇ if (!j.is_object())lines 305–305continue;lines 306–306◇ if (auto tc = action_envelope_to_call(j))lines 307–307calls.push_back(std::move(*tc));lines 310–310return calls;

Requirements

REQ-INFER-012

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
lines 487–487std::regex name_pattern(R"re("name"\s*:\s*"([^"]+)")re");lines 488–488std::smatch match;lines 489–489◇ if (!std::regex_search(json_str, match, name_pattern))lines 490–490return std::nullopt;lines 492–492ToolCall tc;lines 493–493tc.id = generate_uuid();lines 494–494tc.name = match[1].str();lines 495–495return tc;

Requirements

REQ-INFER-012

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

Show on the map →

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);
}
Activity · 17 steps
lines 427–427const auto markers = thinking_markers();lines 428–428std::string result = content;lines 430–430bool truncated_unclosed = false;lines 431–431std::size_t pos;lines 432–432◇ while ((pos = result.find(markers.open)) != std::string::npos)lines 433–433auto close = result.find(markers.close, pos + markers.open.size());lines 436–436◇ if (close == std::string::npos)lines 436–436truncated_unclosed = true;lines 437–438auto span_end = (close == std::string::npos) ? result.size() : close + markers.close.size();lines 439–439result.erase(pos, span_end - pos);lines 446–447◇ if (truncated_unclosed && result.find_first_not_of(" \t\r\n") == std::string::npos)lines 448–454logger->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);lines 457–457size_t start = result.find_first_not_of(" \t\n\r");lines 458–458◇ if (start == std::string::npos)lines 458–458return "";lines 459–459size_t end_pos = result.find_last_not_of(" \t\n\r");lines 460–460return result.substr(start, end_pos - start + 1);

Requirements

REQ-INFER-011