Repository navigation
Description
Name and Version
marco@marco-desktop:~/ai/llama.cpp/build/bin$ ./llama-cli --version
version: 0.4.1-dev (build 10990, commit 05c7deffc)
built with GNU 13.3.0 for Linux x86_64
Operating systems
Linux
GGML backends
HIP
Hardware
i5-9600k + RX 9070 XT
Models
Ministral-3-14B-Reasoning-2512-Q4_K_M (https://huggingface.co/mistralai/Ministral-3-14B-Reasoning-2512-GGUF/tree/main)
Problem description & steps to reproduce
Tool calls emitted by Ministral-3 during reasoning (inside the [THINK]...[/THINK] block) will not be processed by the parser.
Steps to reproduce:
This issue occurs if you try to use this model for agentic workloads in Open WebUI and give it any access to tool-calling. First assistant turn usually works fine, second turn, the tool call gets piped into the reasoning.
To enable reasoning, the system prompt must contain Mistral's official prompt, which can be found here: https://huggingface.co/mistralai/Ministral-3-14B-Reasoning-2512/blob/main/SYSTEM_PROMPT.txt
After 4 h of work and several euros in API cost, trying to cleanly reproduce the issue, I've only been able to reproduce it exactly once outside Open WebUI. Request and response are in the logs below. However, in Open WebUI, I can reproduce it very reliably in any chat where web search or RAG is used. Feel free to delete this report if you believe it misplaced.
That said, the proposed change in the paragraph below completely fixes the issue for me, which I why I hope that this might still be a good patch for the Ministral-3 parser here in llama.cpp.
Proposed fix:
In common/parsers/ministral3.cpp, line 77-78, replace the following lines:
auto reasoning =
extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until("[/THINK]")) + "[/THINK]") : p.eps();
With the following:
auto reasoning =
extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until_one_of({"[/THINK]", "[TOOL_CALLS]"})) + p.optional(p.literal("[/THINK]"))) : p.eps();
This allows the model to emit tool calls during CoT reasoning, similar to how deepseek.cpp is handling it.
Disclaimer: Code is AI generated, and I'm a total C++ noob, so I am hesitant to make any commits or PRs here.
However, changing the line above, under my conditions, turned the model from being nearly unable to make any tool calls, to actually doing proper agentic loops with 10-20 tool calls in a single turn.
First Bad Commit
The source file (common/parsers/ministral3.cpp) was created during refactor in comming 895c045, but the bug is probably older.
Relevant log output
Example CoT reasoning trace from Open WebUI:
[...]
I'll set the count to a higher number (e.g., 20) to ensure I get enough results to cover all aspects.
Let me proceed with the search.[TOOL_CALLS]query_knowledge_files[ARGS]{"query": "[...]", "count": 20}
The only time I managed to catch this bug outside of Open WebUI, this was the JSON of the request sent to llama.cpp:
[
{
"role": "system",
"content": "# HOW YOU SHOULD THINK AND ANSWER\n\nFirst draft your thinking process (inner monologue) until you arrive at a response. Format your response using Markdown, and use LaTeX for any mathematical equations. Write both your thoughts and the response in the same language as the input.\n\nYour thinking process must follow the template below:[THINK]Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate the response to the user.[/THINK]Here, provide a self-contained response.\n\n##### Pyodide Environment\n\n- This Python environment runs via Pyodide in the browser. **Do not install packages** \u2014 `pip install`, `subprocess`, and `micropip.install()` are not available.\n- If a required library is unavailable, use an alternative approach with available modules. Do not attempt to install anything.\n\n##### Persistent File System\n\n- User-uploaded files are available at `/mnt/uploads/`. When the user asks you to work with their files, read from this directory.\n- You can also write output files to `/mnt/uploads/` so the user can access and download them from the file browser.\n- The file system persists across code executions within the same session.\n- Use `import os; os.listdir('/mnt/uploads')` to discover available files."
},
{
"role": "user",
"content": "Please read this file by calling read_file: /home/marco/ai/llama.cpp/common/chat.cpp"
},
{
"role": "assistant",
"content": "",
"reasoning_content": "I need to read the file located at /home/marco/ai/llama.cpp/common/chat.cpp using the `read_file` function. Since the file path is provided, I can directly call this function with the given path. Let me proceed with that.\n\nI should also consider if there are any limitations or if the file exists. The instructions mention that user-uploaded files are available at `/mnt/uploads/`, but this file is at `/home/marco/ai/llama.cpp/common/chat.cpp`. I wonder if this path is accessible in the current environment. However, since the instructions say to read from `/mnt/uploads/` when working with user files, I need to double-check if this file is indeed in that directory or if it's accessible.\n\nGiven that the file path is explicitly provided and the instructions mention that user-uploaded files are available at `/mnt/uploads/`, but this file is not under that directory, I need to clarify whether this file is accessible or if I should guide the user to upload it to `/mnt/uploads/`.\n\nBut since the user is asking me to read this specific file, I should try to read it using the `read_file` function. If it fails, I'll need to inform the user about the issue and suggest uploading the file to `/mntuploads/`.\n\nLet me proceed with calling `read_file` with the given path. If it fails, I'll handle it gracefully.",
"tool_calls": [
{
"type": "function",
"function": {
"name": "read_file",
"arguments": "{\"path\": \"/home/marco/ai/llama.cpp/common/chat.cpp\"}"
},
"id": "iIHzPdknBLTiVriJelZLR6g8xsyjLfL6"
}
]
},
{
"role": "tool",
"tool_call_id": "iIHzPdknBLTiVriJelZLR6g8xsyjLfL6",
"content": "#include \"chat.h\"\n\n#include \"chat-auto-parser-helpers.h\"\n#include \"chat-auto-parser.h\"\n#include \"chat-peg-parser.h\"\n#include \"common.h\"\n#include \"ggml.h\"\n#include \"json-schema-to-grammar.h\"\n#include \"json.h\"\n#include \"log.h\"\n#include \"parsers/parsers.h\"\n\n#include \"jinja/value.h\"\n#include \"jinja/runtime.h\"\n#include \"jinja/caps.h\"\n#include \"peg-parser.h\"\n\n#include <algorithm>\n#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <exception>\n#include <functional>\n#include <iomanip>\n#include <map>\n\n#include <optional>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing json = common_json;\n\nstatic std::string format_time(const std::chrono::system_clock::time_point & now, const std::string & format) {\n auto time = std::chrono::system_clock::to_time_t(now);\n auto local_time = *std::localtime(&time);\n std::ostringstream ss;\n ss << std::put_time(&local_time, format.c_str());\n auto res = ss.str();\n return res;\n}\n\nstatic json safe_args_parse(const std::string & to_parse) {\n std::string stripped = to_parse;\n if (to_parse.at(0) == '\"' && to_parse.at(to_parse.length() - 1) == '\"') {\n stripped = to_parse.substr(1, to_parse.length() - 1);\n }\n try {\n return json::parse(stripped);\n } catch (const common_json_error & e) {\n return stripped;\n }\n}\n\nstatic std::string string_diff(const std::string & last, const std::string & current) {\n if (last.empty()) {\n return current;\n }\n if (!string_starts_with(current, last)) {\n if (string_starts_with(last, current)) {\n // This happens if the last generation ended on a partial stop word (not erased),\n // and the current ended on a stop word (erased).\n return \"\";\n }\n throw std::runtime_error(\"Invalid diff: '\" + last + \"' not found at start of '\" + current + \"'\");\n }\n return current.substr(last.size());\n}\n\nstatic bool has_content_or_tool_calls(const common_chat_msg & msg) {\n return !msg.content.empty() || !msg.tool_calls.empty();\n}\n\nstd::string common_chat_msg::render_content(const std::string & delimiter) const {\n if (!content.empty() && !content_parts.empty()) {\n throw std::runtime_error(\"Cannot specify both content and content_parts\");\n }\n if (!content.empty()) {\n return content;\n }\n\n std::string text;\n for (const auto & part : content_parts) {\n if (part.type == \"text\") {\n if (!text.empty()) {\n text += delimiter;\n }\n text += part.text;\n }\n }\n return text;\n}\n\ncommon_chat_role common_chat_role_from_string(const std::string & role) {\n if (role == \"system\") { return COMMON_CHAT_ROLE_SYSTEM; }\n if (role == \"assistant\") { return COMMON_CHAT_ROLE_ASSISTANT; }\n if (role == \"user\") { return COMMON_CHAT_ROLE_USER; }\n if (role == \"tool\") { return COMMON_CHAT_ROLE_TOOL; }\n return COMMON_CHAT_ROLE_UNKNOWN;\n}\n\nconst char * common_chat_role_to_string(common_chat_role role) {\n switch (role) {\n case COMMON_CHAT_ROLE_SYSTEM: return \"system\";\n case COMMON_CHAT_ROLE_ASSISTANT: return \"assistant\";\n case COMMON_CHAT_ROLE_USER: return \"user\";\n case COMMON_CHAT_ROLE_TOOL: return \"tool\";\n case COMMON_CHAT_ROLE_UNKNOWN: return \"\";\n }\n return \"\";\n}\n\njson common_chat_msg_delimiters::to_json() const {\n json result = json::array();\n for (const auto & d : delimiters) {\n result.push_back({\n { \"role\", common_chat_role_to_string(d.role) },\n { \"delimiter\", d.delimiter },\n });\n }\n return result;\n}\n\ncommon_chat_msg_delimiters common_chat_msg_delimiters_parse(const json & delimiters) {\n common_chat_msg_delimiters result;\n\n if (!delimiters.is_array()) {\n return result;\n }\n\n result.delimiters.reserve(delimiters.size());\n for (const auto & d : delimiters) {\n if (!d.is_object()) {\n continue;\n }\n result.delimiters.push_back({\n common_chat_role_from_string(d.value(\"role\", std::string())),\n d.value(\"delimiter\", std::string()),\n });\n }\n\n return result;\n}\n\nvoid common_chat_msg_delimiters::tokenize(const llama_vocab * vocab) {\n for (auto & d : delimiters) {\n d.tokens = common_tokenize(vocab, d.delimiter, false, true);\n }\n}\n\ncommon_chat_msg_spans common_chat_msg_delimiters::split(const llama_tokens & tokens, const std::map<size_t, size_t> & skips) const {\n std::vector<std::pair<common_chat_role, size_t>> matches;\n\n auto skip = skips.begin();\n for (size_t i = 0; i < tokens.size();) {\n if (skip != skips.end() && i == skip->first) {\n i += skip->second;\n ++skip;\n continue;\n }\n for (const auto & d : delimiters) {\n if (i + d.tokens.size() > tokens.size()) {\n continue;\n }\n if (std::equal(d.tokens.begin(), d.tokens.end(), tokens.begin() + i)) {\n matches.emplace_back(d.role, i);\n break;\n }\n }\n i++;\n }\n\n matches.emplace_back(COMMON_CHAT_ROLE_UNKNOWN, tokens.size());\n\n common_chat_msg_spans spans;\n for (size_t i = 0; i + 1 < matches.size(); i++) {\n const auto & curr = matches[i];\n const auto & next = matches[i + 1];\n spans.add(curr.first, curr.second, next.second - curr.second);\n }\n\n return spans;\n}\n\njson common_chat_msg::to_json_oaicompat(bool concat_typed_text) const {\n if (!content.empty() && !content_parts.empty()) {\n throw std::runtime_error(\"Cannot specify both content and content_parts\");\n }\n json jmsg {\n {\"role\", role},\n };\n if (!content.empty()) {\n jmsg[\"content\"] = content;\n } else if (!content_parts.empty()) {\n if (concat_typed_text || contains_media()) {\n std::string text;\n bool last_was_media_marker = false;\n // join parts with newline, do not add newline before or after media markers\n for (const auto & part : content_parts) {\n bool add_new_line = true;\n if (part.type == \"text\") {\n add_new_line = !last_was_media_marker && !text.empty();\n last_was_media_marker = false;\n } else if (part.type == \"media_marker\") {\n add_new_line = false;\n last_was_media_marker = true;\n } else {\n LOG_WRN(\"Ignoring content part type: %s\\n\", part.type.c_str());\n continue;\n }\n\n if (add_new_line) {\n text += '\\n';\n }\n\n text += part.text;\n }\n jmsg[\"content\"] = text;\n } else {\n auto & parts = jmsg[\"content\"] = json::array();\n for (const auto & part : content_parts) {\n parts.push_back({\n {\"type\", part.type},\n {\"text\", part.text},\n });\n }\n }\n } else {\n jmsg[\"content\"] = \"\";\n }\n if (!reasoning_content.empty()) {\n jmsg[\"reasoning_content\"] = reasoning_content;\n }\n if (!tool_name.empty()) {\n jmsg[\"name\"] = tool_name;\n }\n if (!tool_call_id.empty()) {\n jmsg[\"tool_call_id\"] = tool_call_id;\n }\n if (!tool_calls.empty()) {\n jmsg[\"tool_calls\"] = json::array();\n auto & jtool_calls = jmsg[\"tool_calls\"];\n for (const auto & tool_call : tool_calls) {\n json tc {\n {\"type\", \"function\"},\n {\"function\", {\n {\"name\", tool_call.name},\n {\"arguments\", json(tool_call.arguments)},\n }},\n };\n if (!tool_call.id.empty()) {\n tc[\"id\"] = tool_call.id;\n }\n // Some templates generate and require an id (sometimes in a very specific format, e.g. Mistral Nemo).\n // We only generate a random id for the ones that don't generate one by themselves\n // (they also won't get to see it as their template likely doesn't use it, so it's all for the client)\n // {\"id\", tc.id.empty() ? gen_tool_call_id() : tc.id},\n jtool_calls.push_back(tc);\n }\n }\n\n return jmsg;\n}\n\nstd::vector<common_chat_msg_diff> common_chat_msg_diff::compute_diffs(const common_chat_msg & msg_prv,\n const common_chat_msg & msg_new) {\n std::vector<common_chat_msg_diff> diffs;\n if (msg_new.tool_calls.size() > msg_prv.tool_calls.size()) {\n diffs.reserve(msg_new.tool_calls.size() - msg_prv.tool_calls.size() + 3);\n } else {\n diffs.reserve(3);\n }\n\n // TODO: these can become expensive for long messages - how to optimize?\n if (msg_prv.reasoning_content != msg_new.reasoning_content) {\n auto & diff = diffs.emplace_back();\n diff.reasoning_content_delta = string_diff(msg_prv.reasoning_content, msg_new.reasoning_content);\n }\n if (msg_prv.content != msg_new.content) {\n auto & diff = diffs.emplace_back();\n diff.content_delta = string_diff(msg_prv.content, msg_new.content);\n }\n\n if (msg_new.tool_calls.size() < msg_prv.tool_calls.size()) {\n std::string err = \"Invalid diff: now finding less tool calls!\\n\";\n err += \" Previous (\" + std::to_string(msg_prv.tool_calls.size()) + \"):\\n\";\n for (const auto & tc : msg_prv.tool_calls) {\n err += \" - name: '\" + tc.name + \"', args: '\" + tc.arguments + \"'\\n\";\n }\n err += \" Current (\" + std::to_string(msg_new.tool_calls.size()) + \"):\\n\";\n for (const auto & tc : msg_new.tool_calls) {\n err += \" - name: '\" + tc.name + \"', args: '\" + tc.arguments + \"'\\n\";\n }\n err += \" Current msg text content:\\n\" + msg_new.content + \"\\n\";\n throw std::runtime_error(err);\n }\n\n if (!msg_prv.tool_calls.empty()) {\n const auto idx = msg_prv.tool_calls.size() - 1;\n const auto & pref = msg_prv.tool_calls[idx];\n const auto & newf = msg_new.tool_calls[idx];\n // Allow tool name to change during incremental parsing:\n // - empty -> non-empty (initial discovery)\n // - prefix -> longer string (name grows as more input is parsed)\n if (pref.name != newf.name && !pref.name.empty() && !newf.name.empty()) {\n // Check if one is a prefix of the other (for incremental parsing where names grow or shrink)\n bool is_prefix = (newf.name.rfind(pref.name, 0) == 0);\n if (!is_prefix) {\n LOG_ERR(\"Tool call mismatch: prev='%s' new='%s'\\n\", pref.name.c_str(), newf.name.c_str());\n throw std::runtime_error(\"Invalid diff: tool call mismatch!\");\n }\n }\n const auto args_diff = string_diff(pref.arguments, newf.arguments);\n if (!args_diff.empty() || pref.id != newf.id || pref.name != newf.name) {\n auto & diff = diffs.emplace_back();\n diff.tool_call_index = idx;\n if (pref.id != newf.id || pref.name != newf.name) {\n diff.tool_call_delta.id = newf.id;\n diff.tool_call_delta.name = newf.name;\n }\n diff.tool_call_delta.arguments = args_diff;\n }\n }\n for (size_t idx = msg_prv.tool_calls.size(); idx < msg_new.tool_calls.size(); ++idx) {\n auto & diff = diffs.emplace_back();\n diff.tool_call_index = idx;\n diff.tool_call_delta = msg_new.tool_calls[idx];\n }\n\n return diffs;\n}\n\nusing chat_template_caps = jinja::caps;\n\nstruct common_chat_templates {\n bool add_bos;\n bool add_eos;\n bool has_explicit_template; // Model had builtin template or template overridden was specified.\n std::unique_ptr<common_chat_template> template_default; // always set (defaults to chatml)\n std::unique_ptr<common_chat_template> template_tool_use;\n};\n\ncommon_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) {\n if (tool_choice == \"auto\") {\n return COMMON_CHAT_TOOL_CHOICE_AUTO;\n }\n if (tool_choice == \"none\") {\n return COMMON_CHAT_TOOL_CHOICE_NONE;\n }\n if (tool_choice == \"required\") {\n return COMMON_CHAT_TOOL_CHOICE_REQUIRED;\n }\n throw std::invalid_argument(\"Invalid tool_choice: \" + tool_choice);\n}\n\nbool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates) {\n common_chat_templates_inputs inputs;\n inputs.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK;\n common_chat_msg msg;\n msg.role = \"user\";\n msg.content = \"test\";\n inputs.messages = { msg };\n inputs.enable_thinking = true;\n inputs.add_generation_prompt = true;\n inputs.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK;\n\n auto params = common_chat_templates_apply(chat_templates, inputs);\n return params.supports_thinking;\n}\n\nstd::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messages) {\n std::vector<common_chat_msg> msgs;\n\n try {\n if (!messages.is_array()) {\n throw std::invalid_argument(\"Expected 'messages' to be an array, got \" + messages.dump());\n }\n\n for (const auto & message : messages) {\n if (!message.is_object()) {\n throw std::invalid_argument(\"Expected 'message' to be an object, got \" + message.dump());\n }\n\n common_chat_msg msg;\n if (!message.contains(\"role\")) {\n throw std::invalid_argument(\"Missing 'role' in message: \" + message.dump());\n }\n msg.role = message.at(\"role\");\n\n auto has_content = message.contains(\"content\");\n auto has_tool_calls = message.contains(\"tool_calls\");\n if (has_content) {\n const auto & content = message.at(\"content\");\n if (content.is_string()) {\n msg.content = content;\n } else if (content.is_array()) {\n for (const auto & part : content) {\n if (!part.contains(\"type\")) {\n throw std::invalid_argument(\"Missing content part type: \" + part.dump());\n }\n const auto & type = part.at(\"type\");\n if (type != \"text\" && type != \"media_marker\") {\n throw std::invalid_argument(\"Unsupported content part type: \" + type.dump());\n }\n common_chat_msg_content_part msg_part;\n msg_part.type = type;\n msg_part.text = part.at(\"text\");\n msg.content_parts.push_back(msg_part);\n }\n } else if (!content.is_null()) {\n throw std::invalid_argument(\"Invalid 'content' type: expected string or array, got \" +\n content.dump() +\n \" (ref: https://github.com/ggml-org/llama.cpp/issues/8367)\");\n }\n }\n if (has_tool_calls) {\n for (const auto & tool_call : message.at(\"tool_calls\")) {\n common_chat_tool_call tc;\n if (!tool_call.contains(\"type\")) {\n throw std::invalid_argument(\"Missing tool call type: \" + tool_call.dump());\n }\n const auto & type = tool_call.at(\"type\");\n if (type != \"function\") {\n throw std::invalid_argument(\"Unsupported tool call type: \" + tool_call.dump());\n }\n if (!tool_call.contains(\"function\")) {\n throw std::invalid_argument(\"Missing tool call function: \" + tool_call.dump());\n }\n const auto & fc = tool_call.at(\"function\");\n if (!fc.contains(\"name\")) {\n throw std::invalid_argument(\"Missing tool call name: \" + tool_call.dump());\n }\n tc.name = fc.at(\"name\");\n const auto & args = fc.at(\"arguments\");\n if (args.is_string()) {\n tc.arguments = args;\n } else {\n tc.arguments = args.dump();\n }\n if (tool_call.contains(\"id\")) {\n tc.id = tool_call.at(\"id\");\n }\n msg.tool_calls.push_back(tc);\n }\n }\n if (!has_content && !has_tool_calls) {\n throw std::invalid_argument(\n \"Expected 'content' or 'tool_calls' (ref: https://github.com/ggml-org/llama.cpp/issues/8367 & \"\n \"https://github.com/ggml-org/llama.cpp/issues/12279)\");\n }\n if (message.contains(\"reasoning_content\")) {\n msg.reasoning_content = message.at(\"reasoning_content\");\n }\n if (message.contains(\"name\")) {\n msg.tool_name = message.at(\"name\");\n }\n if (message.contains(\"tool_call_id\")) {\n msg.tool_call_id = message.at(\"tool_call_id\");\n }\n\n msgs.push_back(msg);\n }\n } catch (const std::exception & e) {\n // @ngxson : disable otherwise it's bloating the API response\n // printf(\"%s\\n\", std::string(\"; messages = \") + messages.dump(2));\n throw std::runtime_error(\"Failed to parse messages: \" + std::string(e.what()));\n }\n\n return msgs;\n}\n\nstruct messages_inp_normalizer {\n const jinja::caps & caps;\n\n messages_inp_normalizer(const jinja::caps & c) : caps(c) {}\n\n // handle supports_string_content / supports_typed_content\n // if string=true and array=false, convert array to string\n // if string=false and array=true, convert string to array\n // if both are true, do nothing\n json normalize(const json & messages) {\n bool only_string = caps.supports_string_content && !caps.supports_typed_content;\n bool only_typed = !caps.supports_string_content && caps.supports_typed_content;\n if ((!only_string && !only_typed) || !messages.is_array()) {\n return messages;\n }\n json normalized = json::array();\n for (const auto & msg : messages) {\n json copy = msg;\n if (copy.contains(\"content\")) {\n json & it = copy.at(\"content\");\n if (only_typed && it.is_string()) {\n it = json::array({\n json{\n {\"type\", \"text\"},\n {\"text\", it.get<std::string>()},\n }\n });\n } else if (only_string && it.is_array()) {\n it = concat_content_parts(it);\n }\n }\n normalized.push_back(std::move(copy));\n }\n return normalized;\n }\n\n // join parts with newline, do not add newline before or after media markers\n static std::string concat_content_parts(const json & parts) {\n std::string text;\n bool last_was_media_marker = false;\n for (const auto & part : parts) {\n std::string type = part.value(\"type\", \"\");\n bool add_new_line = true;\n if (type == \"text\") {\n add_new_line = !last_was_media_marker && !text.empty();\n last_was_media_marker = false;\n } else if (type == \"media_marker\") {\n add_new_line = false;\n last_was_media_marker = true;\n } else {\n LOG_WRN(\"Ignoring content part type: %s\\n\", type.c_str());\n continue;\n }\n\n if (add_new_line) {\n text += '\\n';\n }\n\n text += part.value(\"text\", \"\");\n }\n return text;\n }\n};\n\nstatic json render_message_to_json(const std::vector<common_chat_msg> & msgs, const jinja::caps & c) {\n if (!c.supports_string_content && !c.supports_typed_content) {\n LOG_WRN(\"%s: Neither string content nor typed content is supported by the template. This is unexpected and may lead to issues.\\n\", __func__);\n }\n\n json messages = json::array();\n for (const auto & msg : msgs) {\n messages.push_back(msg.to_json_oaicompat(/* concat_typed_text= */ false));\n }\n return messages_inp_normalizer(c).normalize(messages);\n}\n\n// DEPRECATED: only used in tests\njson common_chat_msgs_to_json_oaicompat(const std::vector<common_chat_msg> & msgs, bool concat_typed_text) {\n jinja::caps c;\n c.supports_string_content = true;\n c.supports_typed_content = !concat_typed_text;\n return render_message_to_json(msgs, c);\n}\n\njson common_chat_tools_to_json_oaicompat(const std::vector<common_chat_tool> & tools) {\n if (tools.empty()) {\n return json();\n }\n\n auto result = json::array();\n for (const auto & tool : tools) {\n result.push_back({\n { \"type\", \"function\" },\n { \"function\", {\n { \"name\", tool.name },\n { \"description\", tool.description },\n { \"parameters\", json::parse(tool.parameters) },\n }},\n });\n }\n return result;\n}\n\njson common_chat_tool_parameters(const json & function) {\n if (function.contains(\"parameters\")) {\n const auto & params = function.at(\"parameters\");\n if (!params.is_null() && !(params.is_object() && params.empty())) {\n return params;\n }\n }\n return json{{\"type\", \"object\"}, {\"properties\", json::object()}};\n}\n\nstd::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const json & tools) {\n std::vector<common_chat_tool> result;\n\n try {\n if (!tools.is_null()) {\n if (!tools.is_array()) {\n throw std::invalid_argument(\"Expected 'tools' to be an array, got \" + tools.dump());\n }\n for (const auto & tool : tools) {\n if (!tool.contains(\"type\")) {\n throw std::invalid_argument(\"Missing tool type: \" + tool.dump());\n }\n const auto & type = tool.at(\"type\");\n if (!type.is_string() || type != \"function\") {\n throw std::invalid_argument(\"Unsupported tool type: \" + tool.dump());\n }\n if (!tool.contains(\"function\")) {\n throw std::invalid_argument(\"Missing tool function: \" + tool.dump());\n }\n\n const auto & function = tool.at(\"function\");\n result.push_back({\n /* .name = */ function.at(\"name\"),\n /* .description = */ function.value(\"description\", \"\"),\n /* .parameters = */ function.value(\"parameters\", json::object()).dump(),\n });\n }\n }\n } catch (const std::exception & e) {\n throw std::runtime_error(\"Failed to parse tools: \" + std::string(e.what()) + \"; tools = \" + tools.dump(2));\n }\n\n return result;\n}\n\ncommon_chat_continuation common_chat_continuation_parse(const common_json & value) {\n if (value.is_boolean() && value.get<bool>()) {\n return COMMON_CHAT_CONTINUATION_AUTO;\n }\n if (value.is_string()) {\n auto value_str = value.get<std::string>();\n if (value_str == \"reasoning_content\") {\n return COMMON_CHAT_CONTINUATION_REASONING;\n }\n if (value_str == \"content\") {\n return COMMON_CHAT_CONTINUATION_CONTENT;\n }\n }\n return COMMON_CHAT_CONTINUATION_NONE;\n}\n\nbool common_chat_verify_template(const std::string & tmpl, bool use_jinja) {\n if (use_jinja) {\n try {\n common_chat_msg msg;\n msg.role = \"user\";\n msg.content = \"test\";\n\n auto tmpls = common_chat_templates_init(/* model= */ nullptr, tmpl);\n\n common_chat_templates_inputs inputs;\n inputs.messages = { msg };\n\n common_chat_templates_apply(tmpls.get(), inputs);\n return true;\n } catch (const std::exception & e) {\n LOG_ERR(\"%s: failed to apply template: %s\\n\", __func__, e.what());\n return false;\n }\n }\n llama_chat_message chat[] = {\n { \"user\", \"test\" }\n };\n const int res = llama_chat_apply_template(tmpl.c_str(), chat, 1, true, nullptr, 0);\n return res >= 0;\n}\n\nstd::string common_chat_format_single(const struct common_chat_templates * tmpls,\n const std::vector<common_chat_msg> & past_msg,\n const common_chat_msg & new_msg,\n\n\n[... truncated at 25000 chars ...]"
},
{
"role": "assistant",
"content": "The file `/home/marco/ai/llama.cpp/common/chat.cpp` contains C++ code related to chat functionality, likely part of the `llama.cpp` project. The code includes various utilities and classes for handling chat messages, delimiters, templates, and tool interactions. Some of the notable components include:\n\n1. **Chat Message Handling**:\n - Functions for parsing and manipulating chat messages, including support for content, reasoning content, and tool calls.\n - Utilities for rendering content and handling differences between messages.\n\n2. **Chat Templates**:\n - Support for chat templates with Jinja, including rendering messages and handling template-specific capabilities like thinking support.\n\n3. **JSON and Serialization**:\n - Functions for converting chat messages and tools to/from JSON format, with compatibility for OpenAI-style messages.\n\n4. **Error Handling and Validation**:\n - Methods to validate templates and messages, ensuring they adhere to expected formats.\n\n5. **Tool Interactions**:\n - Parsing and handling tool calls, including tool choice options like `auto`, `none`, and `required`.\n\n6. **Helper Functions**:\n - Utilities for string manipulation, time formatting, and safe parsing of arguments.\n\nThe code is heavily template-based and integrates with libraries like `jinja` for template rendering and `common_json` for JSON handling. It also includes error handling for invalid inputs or mismatches in message structures.\n\nWould you like me to analyze or explain any specific part of this code in more detail?"
},
{
"role": "user",
"content": "Before we continue: decide which of these two files is more likely to contain the code that decides whether a tool call gets parsed \u2014 /home/marco/ai/llama.cpp/common/chat.cpp or /home/marco/ai/llama.cpp/common/chat-peg-parser.cpp \u2014 then call read_file for the one you choose."
}
]
This is the response:
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"role": "assistant",
"content": "",
"reasoning_content": "I need to decide which of the two files is more likely to contain the code that decides whether a tool call gets parsed. The two files in question are:\n\n1. `/home/marco/ai/llama.cpp/common/chat.cpp`\n2. `/home/marco/ai/llama.cpp/common/chat-peg-parser.cpp`\n\nFrom the name `chat.cpp`, it seems like it contains general functionality related to chat, such as handling chat messages, rendering, and possibly parsing. The term \"chat\" in the filename suggests it might deal with high-level logic, including parsing tool calls.\n\nOn the other hand, `chat-peg-parser.cpp` likely deals with parsing logic, specifically using a Parsing Expression Grammar (PEG) parser. PEG parsers are typically used for parsing structured data, such as messages or tool calls. The inclusion of \"parser\" in the filename strongly suggests that this file is responsible for parsing logic, including deciding whether a tool call gets parsed.\n\nGiven this analysis, `chat-peg-parser.cpp` is more likely to contain the code that decides whether a tool call gets parsed, as parsing is its primary focus.\n\nI should now call `read_file` for `/home/marco/ai/llama.cpp/common/chat-peg-parser.cpp` to examine its contents. If that file doesn't exist or can't be read, I'll fall back to the other file or inform the user.\n\nLet me proceed with this decision.[TOOL_CALLS][TOOL_CALLS]read_file[ARGS]{\"path\": \"/home/marco/ai/llama.cpp/common/chat-peg-parser.cpp\"}"
}
}
],
"created": 1790019335,
"model": "Ministral-3-14B-Reasoning-2512-Q4_K_M",
"system_fingerprint": "b10990-05c7deffc",
"object": "chat.completion",
"usage": {
"completion_tokens": 324,
"prompt_tokens": 6843,
"total_tokens": 7167,
"prompt_tokens_details": {
"cached_tokens": 6771
}
},
"id": "chatcmpl-tay0qDJHZUIhRtRYWRijTPQeZhd53Mgd",
"timings": {
"cache_n": 6771,
"prompt_n": 72,
"prompt_ms": 62.394,
"prompt_per_token_ms": 0.8665833333333333,
"prompt_per_second": 1153.9571112606982,
"predicted_n": 324,
"predicted_ms": 6209.136,
"predicted_per_token_ms": 19.223331269349845,
"predicted_per_second": 52.02012002958221
}
}
Activity
fractal-fumbler commentedon Nov 2, 2026
llama-server b12020
model is https://huggingface.co/AtomicChat/Mistral-Small-4-119B-2603-GGUF
chat : allow tool calls inside reasoning blocks for Ministral-3 (ggml…
Sync upstream llama.cpp master into mtmd-backend (#81)
chat : allow tool calls inside reasoning blocks for Ministral-3 (ggml…
chat : allow tool calls inside reasoning blocks for Ministral-3 (ggml…