15#include <nlohmann/json.hpp>
22#include <unordered_set>
30constexpr const char* TOOL_RESULT_SUFFIX =
31 "Continue. Batch multiple tool calls in one response when possible.";
41 static std::atomic<uint64_t> counter{0};
42 return "tc-" + std::to_string(counter.fetch_add(1, std::memory_order_relaxed));
60std::string tool_name_from_json(
const nlohmann::json& j) {
61 for (
const char* key : {
"name",
"tool_name",
"function",
"function_name"}) {
62 if (j.contains(key) && j[key].is_string()) {
63 return j[key].get<std::string>();
82std::optional<ToolCall> tool_call_from_json(
const nlohmann::json& j) {
83 std::string name = tool_name_from_json(j);
84 if (name.empty()) {
return std::nullopt; }
87 tc.name = std::move(name);
88 auto args = j.value(
"arguments", j.value(
"parameters", nlohmann::json::object()));
89 for (
auto& [k, v] : args.items()) { tc.arguments[k] = v.dump(); }
104 : tier_name_(std::move(tier_name))
105 , identity_prompt_(std::move(identity_prompt))
120 const std::string& base_prompt,
121 const std::vector<std::string>& tool_jsons)
const
125 if (!base_prompt.empty()) {
126 prompt +=
"\n\n" + base_prompt;
129 if (!tool_jsons.empty()) {
131 for (
const auto& json_str : tool_jsons) {
133 auto j = nlohmann::json::parse(json_str);
134 std::string name = j.value(
"name",
"");
135 auto dot = name.find(
'.');
136 if (dot != std::string::npos) {
161 const std::string& result)
const
165 msg.
content =
"Tool `" + tool_call.
name +
"` returned:\n\n" +
166 result +
"\n\n" + TOOL_RESULT_SUFFIX;
184 const std::string& content,
185 const std::vector<ToolCall>& tool_calls)
const
188 if (!tool_calls.empty()) {
193 if (content.find(
"<think>") != std::string::npos &&
194 content.find(
"</think>") == std::string::npos)
201 return !stripped.empty();
214 const std::string& content)
const
216 std::vector<ToolCall> calls;
235 R
"((?:<tool_call>|<\|tool_call\|?>|<\|im_start\|>tool_call)\s*)"
236 R"(([\s\S]*?)\s*</tool_call>)");
238 auto begin = std::sregex_iterator(content.begin(), content.end(), pattern);
239 auto end = std::sregex_iterator();
241 for (
auto it = begin; it != end; ++it) {
242 std::string json_str = (*it)[1].str();
245 calls.push_back(*parsed);
246 logger->info(
"Parsed tagged tool call: {}", parsed->name);
254 "Tagged tool_call matched but JSON failed to parse: {}",
265 && (content.find(
"<tool_call>") != std::string::npos
266 || content.find(
"<|tool_call") != std::string::npos
267 || content.find(
"<|im_start|>tool_call") != std::string::npos)) {
269 "Content contains tool_call markup but no tagged calls "
270 "were extracted — possible tag/encoding mismatch. "
271 "Raw content length={}", content.size());
286 const std::string& content)
const
288 std::vector<ToolCall> calls;
289 std::istringstream stream(content);
292 while (std::getline(stream, line)) {
294 size_t start = line.find_first_not_of(
" \t");
295 if (start == std::string::npos)
continue;
296 std::string_view stripped(line.data() + start, line.size() - start);
300 if (stripped.front() !=
'{'
301 || (stripped.find(
"name") == std::string_view::npos)) {
306 auto j = nlohmann::json::parse(stripped);
307 if (
auto tc = tool_call_from_json(j)) {
308 calls.push_back(*tc);
337 const nlohmann::json& j) {
338 if (
auto tc = tool_call_from_json(j)) {
return tc; }
341 static const std::unordered_set<std::string> kMetaActions = {
342 "delegate",
"pipeline",
"complete",
343 "phase_change",
"prune_context",
"resume_delegation"};
345 if (j.contains(
"action") && j[
"action"].is_string()) {
346 action = j[
"action"].get<std::string>();
348 if (kMetaActions.find(action) == kMetaActions.end()) {
353 tc.
name =
"entropic." + action;
354 nlohmann::json args = j;
355 args.erase(
"action");
357 for (
auto& [k, v] : args.items()) { tc.
arguments[k] = v.dump(); }
369 std::vector<ToolCall> calls;
370 std::istringstream stream(raw);
372 while (std::getline(stream, line)) {
373 size_t start = line.find_first_not_of(
" \t");
374 if (start == std::string::npos || line[start] !=
'{') {
continue; }
375 auto j = nlohmann::json::parse(line.substr(start),
nullptr,
false);
376 if (!j.is_object()) {
continue; }
378 calls.push_back(std::move(*tc));
392 const std::string& raw) {
393 if (!calls.empty()) {
return; }
395 if (recovered.empty()) {
return; }
397 "gh#88: PEG_GEMMA4 parsed 0 tool calls; recovered {} from a "
398 "bare-JSON {{\"action\":...}} envelope (possible context priming)",
400 calls = std::move(recovered);
414 const nlohmann::json& tools,
const std::string& name) {
415 std::unordered_set<std::string> props;
416 for (
const auto& t : tools) {
417 if (!t.is_object() || t.value(
"name", std::string()) != name) {
420 auto schema = t.value(
"inputSchema", nlohmann::json::object());
421 auto properties = schema.value(
"properties", nlohmann::json::object());
422 for (
auto it = properties.begin(); it != properties.end(); ++it) {
424 && it->value(
"type", std::string()) ==
"string") {
425 props.insert(it.key());
442 if (props.empty()) {
return; }
443 auto args = nlohmann::json::parse(tc.
arguments_json,
nullptr,
false);
444 if (!args.is_object()) {
return; }
445 bool changed =
false;
446 for (
const auto& key : props) {
447 auto it = args.find(key);
448 if (it != args.end() && it->is_number()) {
453 if (!changed) {
return; }
455 for (
auto it = args.begin(); it != args.end(); ++it) {
457 it->is_string() ? it->get<std::string>() : it->dump();
469 const std::string& tools_json) {
470 if (calls.empty() || tools_json.empty()) {
return; }
471 auto tools = nlohmann::json::parse(tools_json,
nullptr,
false);
472 if (!tools.is_array()) {
return; }
487 std::regex pattern(R
"(<think>([\s\S]*?)</think>)");
489 auto begin = std::sregex_iterator(content.begin(), content.end(), pattern);
490 auto end = std::sregex_iterator();
492 for (
auto it = begin; it != end; ++it) {
493 if (!result.empty()) result +=
"\n";
494 result += (*it)[1].str();
507 std::regex pattern(R
"(<think>[\s\S]*?</think>)");
508 std::string result = std::regex_replace(content, pattern, "");
511 size_t start = result.find_first_not_of(
" \t\n\r");
512 if (start == std::string::npos)
return "";
513 size_t end_pos = result.find_last_not_of(
" \t\n\r");
514 return result.substr(start, end_pos - start + 1);
527 const std::string& fixed) {
528 auto j = nlohmann::json::parse(fixed);
529 return tool_call_from_json(j);
540 const std::string& json_str) {
541 std::regex name_pattern(R
"re("name"\s*:\s*"([^"]+)")re");
543 if (!std::regex_search(json_str, match, name_pattern)) {
548 tc.
name = match[1].str();
563 const std::string& json_str)
const
566 std::string fixed = std::regex_replace(json_str, std::regex(R
"(,\s*\})"), "}");
567 fixed = std::regex_replace(fixed, std::regex(R
"(,\s*\])"), "]");
568 std::replace(fixed.begin(), fixed.end(),
'\'',
'"');
570 logger->info(
"JSON recovery attempt: {} chars", json_str.size());
589 const std::vector<std::string>& tool_jsons)
const
591 std::ostringstream out;
592 out <<
"## Tools\n\n"
593 <<
"Call tools with: `<tool_call>{\"name\": \"tool.name\", \"arguments\": {...}}</tool_call>`\n"
594 <<
"Batch independent calls in one response with multiple `<tool_call>` blocks.\n\n";
596 for (
const auto& json_str : tool_jsons) {
598 auto j = nlohmann::json::parse(json_str);
599 out <<
"### " << j.value(
"name",
"unknown") <<
"\n"
600 << j.value(
"description",
"No description") <<
"\n\n"
601 <<
"Schema:\n```json\n"
602 << j.value(
"inputSchema", nlohmann::json::object()).dump(2)
605 out <<
"### (malformed tool definition)\n\n";
621 const std::string& json_str)
const
624 auto j = nlohmann::json::parse(json_str);
625 if (
auto tc = tool_call_from_json(j)) {
645 const std::string& base_system,
658 const std::vector<ContentPart>& parts)
const {
659 nlohmann::json arr = nlohmann::json::array();
660 for (
const auto& part : parts) {
663 obj[
"type"] =
"text";
664 obj[
"text"] = part.text;
666 obj[
"type"] =
"image";
667 if (!part.image_path.empty()) {
668 obj[
"path"] = part.image_path;
670 if (!part.image_url.empty()) {
671 obj[
"url"] = part.image_url;
674 arr.push_back(std::move(obj));
ChatAdapter concrete base class.
std::string format_system_prompt(const std::string &base_prompt, const std::vector< std::string > &tool_jsons) const
Assemble system prompt: identity + context + tools.
ChatAdapter(std::string tier_name, std::string identity_prompt)
Construct adapter with tier identity.
std::unordered_set< std::string > tool_prefixes_
Known tool prefixes.
std::optional< ToolCall > try_recover_json(const std::string &json_str) const
Attempt JSON recovery on malformed tool call string.
virtual std::string format_content_parts(const std::vector< ContentPart > &parts) const
Convert multimodal content parts to adapter-specific format.
virtual std::string format_system_with_vision(const std::string &base_system, bool has_vision) const
Format system prompt with optional vision context.
std::optional< ToolCall > parse_single_tool_call(const std::string &json_str) const
Parse a single JSON tool call string.
std::vector< ToolCall > parse_tagged_tool_calls(const std::string &content) const
Parse <tool_call>JSON</tool_call> tagged blocks.
std::vector< ToolCall > parse_bare_json_tool_calls(const std::string &content) const
Parse bare JSON lines containing "name" key.
virtual std::string format_tools(const std::vector< std::string > &tool_jsons) const
Format tool definitions for injection into system prompt.
bool is_response_complete(const std::string &content, const std::vector< ToolCall > &tool_calls) const
Check if response represents task completion.
std::string strip_think_blocks(const std::string &content) const
Strip all <think>...</think> blocks from content.
std::string identity_prompt_
Assembled identity prompt.
virtual Message format_tool_result(const ToolCall &tool_call, const std::string &result) const
Format a tool result as a user message.
std::string extract_thinking(const std::string &content) const
Extract <think>...</think> content.
spdlog initialization and logger access.
ENTROPIC_EXPORT std::shared_ptr< spdlog::logger > get(const std::string &name)
Get or create a named logger.
Activate model on GPU (WARM → ACTIVE).
@ TEXT
Plain text content.
static std::optional< ToolCall > parse_recovered_tool_call(const std::string &fixed)
Parse a brace/quote-fixed JSON string into a ToolCall.
void 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.
std::vector< ToolCall > recover_action_envelope_calls(const std::string &raw)
gh#88: recover tool calls a gemma model parroted as bare-JSON.
void 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;...
static std::optional< ToolCall > action_envelope_to_call(const nlohmann::json &j)
Map one parsed JSON object to a recovered ToolCall.
static void coerce_call_string_args(ToolCall &tc, const nlohmann::json &tools)
Coerce one call's numeric args to strings per the tool schema.
std::string generate_uuid()
Generate a UUID v4 string.
static std::optional< ToolCall > regex_recovered_tool_call(const std::string &json_str)
Last-ditch recovery: pull a tool name out via regex.
static std::unordered_set< std::string > tool_string_props(const nlohmann::json &tools, const std::string &name)
String-typed property names for a tool in the staged MCP defs.
A message in a conversation.
std::string content
Message text content (always populated)
std::string role
Message role.