Entropic 2.11.1
Local-first agentic inference engine
Loading...
Searching...
No Matches
adapter_base.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
14
15#include <nlohmann/json.hpp>
16
17#include <algorithm>
18#include <atomic>
19#include <cstdint>
20#include <regex>
21#include <sstream>
22#include <unordered_set>
23
24namespace entropic {
25
26namespace {
27auto logger = entropic::log::get("inference.adapter");
28
30constexpr const char* TOOL_RESULT_SUFFIX =
31 "Continue. Batch multiple tool calls in one response when possible.";
32
39std::string generate_uuid() {
40 // Simple counter-based ID for now. Replace with proper UUID if needed.
41 static std::atomic<uint64_t> counter{0};
42 return "tc-" + std::to_string(counter.fetch_add(1, std::memory_order_relaxed));
43}
44
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>();
64 }
65 }
66 return "";
67}
68
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; }
85 ToolCall tc;
86 tc.id = generate_uuid();
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(); }
90 return tc;
91}
92
93} // anonymous namespace
94
95// ── Constructor ────────────────────────────────────────────
96
103ChatAdapter::ChatAdapter(std::string tier_name, std::string identity_prompt)
104 : tier_name_(std::move(tier_name))
105 , identity_prompt_(std::move(identity_prompt))
106{
107}
108
109// ── System prompt assembly ─────────────────────────────────
110
111// ── Tool result formatting ─────────────────────────────────
112
122 const ToolCall& tool_call,
123 const std::string& result) const
124{
125 Message msg;
126 msg.role = "user";
127 msg.content = "Tool `" + tool_call.name + "` returned:\n\n" +
128 result + "\n\n" + TOOL_RESULT_SUFFIX;
129 return msg;
130}
131
132// ── Response completeness ──────────────────────────────────
133
146 const std::string& content,
147 const std::vector<ToolCall>& tool_calls) const
148{
149 // Has tool calls → not complete (needs execution)
150 if (!tool_calls.empty()) {
151 return false;
152 }
153
154 // Unclosed think block → still thinking
155 if (content.find("<think>") != std::string::npos &&
156 content.find("</think>") == std::string::npos)
157 {
158 return false;
159 }
160
161 // Strip think blocks and check for real content
162 std::string stripped = strip_think_blocks(content);
163 return !stripped.empty();
164}
165
166// ── Tagged tool call parsing ───────────────────────────────
167
181 const std::string& content) const
182{
183 std::vector<ToolCall> calls;
184 // gh#65 (v2.3.3): accept asymmetric open tags. Gemma 4 emits
185 // `<|tool_call>` (pipe-prefixed open, plain close) — the special
186 // token `<|tool_call|>` decodes through llama.cpp's current pin
187 // as `<|tool_call>` (trailing `|>` lost). Pre-v2.3.3 the regex
188 // required a plain `<tool_call>` open, so Gemma 4's actual output
189 // produced 0 tool calls and the engine looped on the retry banner.
190 //
191 // gh#69 (v2.3.8): add `<|im_start|>tool_call` as a fourth open
192 // variant. Gemma 4 (E2B + E4B) emits its tool calls inside a
193 // ChatML-style channel whose opening header is `<|im_start|>tool_call`
194 // but whose close is the plain `</tool_call>` — an asymmetric pair
195 // the prior three alternatives didn't cover, so both Gemma 4 sizes
196 // scored 0/6 completion (agent loop spiralled to the iteration cap).
197 //
198 // Open alternatives: `<tool_call>`, `<|tool_call>`, `<|tool_call|>`,
199 // `<|im_start|>tool_call`. Close tag stays `</tool_call>` — that's
200 // what the consumer's transcripts consistently show.
201 std::regex pattern(
202 R"((?:<tool_call>|<\|tool_call\|?>|<\|im_start\|>tool_call)\s*)"
203 R"(([\s\S]*?)\s*</tool_call>)");
204
205 auto begin = std::sregex_iterator(content.begin(), content.end(), pattern);
206 auto end = std::sregex_iterator();
207
208 for (auto it = begin; it != end; ++it) {
209 std::string json_str = (*it)[1].str();
210 auto parsed = parse_single_tool_call(json_str);
211 if (parsed) {
212 calls.push_back(*parsed);
213 logger->info("Parsed tagged tool call: {}", parsed->name);
214 } else {
215 // gh#65: when the regex matches but parse_single_tool_call
216 // returns nullopt, the JSON payload was malformed in a way
217 // try_recover_json could not fix. Log the offending text so
218 // future investigations have something to grep, instead of
219 // silently producing zero tool calls.
220 logger->warn(
221 "Tagged tool_call matched but JSON failed to parse: {}",
222 json_str);
223 }
224 }
225 // gh#65/gh#69: model emitted tool_call markup but no regex match.
226 // Catches plain `<tool_call>`, pipe-prefixed `<|tool_call`, and the
227 // Gemma 4 channel header `<|im_start|>tool_call` substrings — if
228 // none matched the full pattern, surface the raw content's length so
229 // the consumer can attach it for triage instead of seeing a silent
230 // "tool_calls: 0".
231 if (calls.empty()
232 && (content.find("<tool_call>") != std::string::npos
233 || content.find("<|tool_call") != std::string::npos
234 || content.find("<|im_start|>tool_call") != std::string::npos)) {
235 logger->warn(
236 "Content contains tool_call markup but no tagged calls "
237 "were extracted — possible tag/encoding mismatch. "
238 "Raw content length={}", content.size());
239 }
240 return calls;
241}
242
243// ── Bare JSON parsing ──────────────────────────────────────
244
245// ── gh#88 action-envelope recovery (free functions) ─────────
246
264static std::optional<ToolCall> action_envelope_to_call(
265 const nlohmann::json& j) {
266 if (auto tc = tool_call_from_json(j)) { return tc; }
267 // gh#88: meta-tools whose result `action` verb equals their tool name.
268 // TodoTool (add/update/remove) and free-text actions are excluded.
269 static const std::unordered_set<std::string> kMetaActions = {
270 "delegate", "pipeline", "complete",
271 "phase_change", "prune_context", "resume_delegation"};
272 std::string action;
273 if (j.contains("action") && j["action"].is_string()) {
274 action = j["action"].get<std::string>();
275 }
276 if (kMetaActions.find(action) == kMetaActions.end()) {
277 return std::nullopt;
278 }
279 ToolCall tc;
280 tc.id = generate_uuid();
281 tc.name = "entropic." + action;
282 nlohmann::json args = j;
283 args.erase("action");
284 tc.arguments_json = args.dump();
285 for (auto& [k, v] : args.items()) { tc.arguments[k] = v.dump(); }
286 return tc;
287}
288
297std::vector<ToolCall> recover_action_envelope_calls(const std::string& raw) {
298 std::vector<ToolCall> calls;
299 std::istringstream stream(raw);
300 std::string line;
301 while (std::getline(stream, line)) {
302 size_t start = line.find_first_not_of(" \t");
303 if (start == std::string::npos || line[start] != '{') { continue; }
304 auto j = nlohmann::json::parse(line.substr(start), nullptr, false);
305 if (!j.is_object()) { continue; }
306 if (auto tc = action_envelope_to_call(j)) {
307 calls.push_back(std::move(*tc));
308 }
309 }
310 return calls;
311}
312
320void apply_action_envelope_recovery(std::vector<ToolCall>& calls,
321 const std::string& raw) {
322 if (!calls.empty()) { return; }
323 auto recovered = recover_action_envelope_calls(raw);
324 if (recovered.empty()) { return; }
325 logger->warn(
326 "gh#88: PEG_GEMMA4 parsed 0 tool calls; recovered {} from a "
327 "bare-JSON {{\"action\":...}} envelope (possible context priming)",
328 recovered.size());
329 calls = std::move(recovered);
330}
331
332// ── gh#90 string-typed-arg coercion (free functions) ────────
333
342static std::unordered_set<std::string> tool_string_props(
343 const nlohmann::json& tools, const std::string& name) {
344 std::unordered_set<std::string> props;
345 for (const auto& t : tools) {
346 if (!t.is_object() || t.value("name", std::string()) != name) {
347 continue;
348 }
349 auto schema = t.value("inputSchema", nlohmann::json::object());
350 auto properties = schema.value("properties", nlohmann::json::object());
351 for (auto it = properties.begin(); it != properties.end(); ++it) {
352 if (it->is_object()
353 && it->value("type", std::string()) == "string") {
354 props.insert(it.key());
355 }
356 }
357 break;
358 }
359 return props;
360}
361
369static void coerce_call_string_args(ToolCall& tc, const nlohmann::json& tools) {
370 auto props = tool_string_props(tools, tc.name);
371 if (props.empty()) { return; }
372 auto args = nlohmann::json::parse(tc.arguments_json, nullptr, false);
373 if (!args.is_object()) { return; }
374 bool changed = false;
375 for (const auto& key : props) {
376 auto it = args.find(key);
377 if (it != args.end() && it->is_number()) {
378 *it = it->dump(); // JSON number 3 → JSON string "3"
379 changed = true;
380 }
381 }
382 if (!changed) { return; }
383 tc.arguments_json = args.dump();
384 for (auto it = args.begin(); it != args.end(); ++it) {
385 tc.arguments[it.key()] =
386 it->is_string() ? it->get<std::string>() : it->dump();
387 }
388}
389
397void coerce_string_typed_args(std::vector<ToolCall>& calls,
398 const std::string& tools_json) {
399 if (calls.empty() || tools_json.empty()) { return; }
400 auto tools = nlohmann::json::parse(tools_json, nullptr, false);
401 if (!tools.is_array()) { return; }
402 for (auto& tc : calls) { coerce_call_string_args(tc, tools); }
403}
404
405// ── Think block handling ───────────────────────────────────
406
426std::string ChatAdapter::strip_think_blocks(const std::string& content) const {
427 const auto markers = thinking_markers();
428 std::string result = content;
429
430 bool truncated_unclosed = false;
431 std::size_t pos;
432 while ((pos = result.find(markers.open)) != std::string::npos) {
433 auto close = result.find(markers.close, pos + markers.open.size());
434 // Unclosed: generation stopped mid-reasoning, so no answer was ever
435 // produced. Erasing to the end beats surfacing raw reasoning.
436 if (close == std::string::npos) { truncated_unclosed = true; }
437 auto span_end = (close == std::string::npos)
438 ? result.size() : close + markers.close.size();
439 result.erase(pos, span_end - pos);
440 }
441
442 // gh#108 (v2.10.3): without this the caller sees empty content and cannot
443 // tell a stalled generation from a parse failure or an engine bug — the
444 // same diagnostic dead end gh#130 fixed on the bridge. Carried over from
445 // strip_thinking_channels, whose behaviour this consolidates.
446 if (truncated_unclosed && result.find_first_not_of(" \t\r\n")
447 == std::string::npos) {
448 logger->warn(
449 "Reasoning block '{}' was never closed with '{}', so the strip "
450 "removed the whole generation and content is empty. Not a parse "
451 "error. The orchestrator reports the actual cause (budget vs the "
452 "model ending the turn) — it is the only layer holding "
453 "finish_reason. gh#137.",
454 markers.open, markers.close);
455 }
456
457 size_t start = result.find_first_not_of(" \t\n\r");
458 if (start == std::string::npos) { return ""; }
459 size_t end_pos = result.find_last_not_of(" \t\n\r");
460 return result.substr(start, end_pos - start + 1);
461}
462
463// ── JSON recovery ──────────────────────────────────────────
464
472static std::optional<ToolCall> parse_recovered_tool_call(
473 const std::string& fixed) {
474 auto j = nlohmann::json::parse(fixed);
475 return tool_call_from_json(j);
476}
477
485static std::optional<ToolCall> regex_recovered_tool_call(
486 const std::string& json_str) {
487 std::regex name_pattern(R"re("name"\s*:\s*"([^"]+)")re");
488 std::smatch match;
489 if (!std::regex_search(json_str, match, name_pattern)) {
490 return std::nullopt;
491 }
492 ToolCall tc;
493 tc.id = generate_uuid();
494 tc.name = match[1].str();
495 return tc;
496}
497
509std::optional<ToolCall> ChatAdapter::try_recover_json(
510 const std::string& json_str) const
511{
512 // Fix trailing commas and single quotes
513 std::string fixed = std::regex_replace(json_str, std::regex(R"(,\s*\})"), "}");
514 fixed = std::regex_replace(fixed, std::regex(R"(,\s*\])"), "]");
515 std::replace(fixed.begin(), fixed.end(), '\'', '"');
516
517 logger->info("JSON recovery attempt: {} chars", json_str.size());
518 try {
519 if (auto tc = parse_recovered_tool_call(fixed)) { return tc; }
520 } catch (...) {
521 return regex_recovered_tool_call(json_str);
522 }
523 return std::nullopt;
524}
525
526// ── Tool formatting (default) ──────────────────────────────
527
536 const std::vector<std::string>& tool_jsons) const
537{
538 std::ostringstream out;
539 out << "## Tools\n\n"
540 << "Call tools with: `<tool_call>{\"name\": \"tool.name\", \"arguments\": {...}}</tool_call>`\n"
541 << "Batch independent calls in one response with multiple `<tool_call>` blocks.\n\n";
542
543 for (const auto& json_str : tool_jsons) {
544 try {
545 auto j = nlohmann::json::parse(json_str);
546 out << "### " << j.value("name", "unknown") << "\n"
547 << j.value("description", "No description") << "\n\n"
548 << "Schema:\n```json\n"
549 << j.value("inputSchema", nlohmann::json::object()).dump(2)
550 << "\n```\n\n";
551 } catch (...) {
552 out << "### (malformed tool definition)\n\n";
553 }
554 }
555 return out.str();
556}
557
558// ── Internal helper ────────────────────────────────────────
559
568 const std::string& json_str) const
569{
570 try {
571 auto j = nlohmann::json::parse(json_str);
572 if (auto tc = tool_call_from_json(j)) {
573 return tc;
574 }
575 } catch (...) {
576 return try_recover_json(json_str);
577 }
578 return std::nullopt;
579}
580
581// ── Vision / multimodal (v1.9.11) ──────────────────────────
582
592 const std::string& base_system,
593 bool /*has_vision*/) const {
594 return base_system;
595}
596
605 const std::vector<ContentPart>& parts) const {
606 nlohmann::json arr = nlohmann::json::array();
607 for (const auto& part : parts) {
608 nlohmann::json obj;
609 if (part.type == ContentPartType::TEXT) {
610 obj["type"] = "text";
611 obj["text"] = part.text;
612 } else {
613 obj["type"] = "image";
614 if (!part.image_path.empty()) {
615 obj["path"] = part.image_path;
616 }
617 if (!part.image_url.empty()) {
618 obj["url"] = part.image_url;
619 }
620 }
621 arr.push_back(std::move(obj));
622 }
623 return arr.dump();
624}
625
626} // namespace entropic
ChatAdapter concrete base class.
ChatAdapter(std::string tier_name, std::string identity_prompt)
Construct adapter with tier identity.
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.
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 this family's reasoning blocks from content (gh#108).
virtual ThinkMarkers thinking_markers() const
Parse tool calls from model output.
virtual Message format_tool_result(const ToolCall &tool_call, const std::string &result) const
Format a tool result as a user message.
spdlog initialization and logger access.
ENTROPIC_EXPORT std::shared_ptr< spdlog::logger > get(const std::string &name)
Get or create a named logger.
Definition logging.cpp:211
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.
@ tool_call
Render-derived (COMMON_GRAMMAR_TYPE_TOOL_CALLS, needs prefill)
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.
Definition backend.cpp:950
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.
Definition message.h:36
std::string content
Message text content (always populated)
Definition message.h:38
std::string role
Message role.
Definition message.h:37
A tool call request parsed from model output.
Definition tool_call.h:31
std::unordered_map< std::string, std::string > arguments
Tool arguments as string key-value pairs.
Definition tool_call.h:34
std::string id
Unique call ID (UUID)
Definition tool_call.h:32
std::string arguments_json
Original JSON string (for passthrough dispatch)
Definition tool_call.h:35
std::string name
Tool name (e.g. "filesystem.read_file")
Definition tool_call.h:33