diff --git a/.github/workflows/build-ibm.yml b/.github/workflows/build-ibm.yml
index e896b87017ad..67ca8b683e40 100644
--- a/.github/workflows/build-ibm.yml
+++ b/.github/workflows/build-ibm.yml
@@ -100,7 +100,7 @@ jobs:
run: |
cd build
echo "Fetch llama2c big-endian model"
- wget https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K-be.gguf
+ wget https://huggingface.co/ggml-org-dev/stories260K/resolve/main/stories260K-be.gguf
./bin/llama-completion -m stories260K-be.gguf -p "One day, Lily met a Shoggoth" -n 500 -c 256
- name: Test quantize (s390x)
diff --git a/.github/workflows/ci-self-hosted-webgpu.yml b/.github/workflows/ci-self-hosted-webgpu.yml
index e2ef40cd25d1..f94689006dbe 100644
--- a/.github/workflows/ci-self-hosted-webgpu.yml
+++ b/.github/workflows/ci-self-hosted-webgpu.yml
@@ -58,12 +58,7 @@ jobs:
- name: Install dependencies
run: |
sudo apt update
- sudo apt install -y software-properties-common
- sudo add-apt-repository ppa:deadsnakes/ppa
- sudo apt update
- sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan1 mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3.12 python3.12-venv
- sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 1
- sudo update-alternatives --config python3
+ sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan1 mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3b08ad94a3e1..867dcaf49420 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1363,6 +1363,8 @@ jobs:
cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_def.3.dll" ./build/bin
cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_avx2.3.dll" ./build/bin
cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_tbb_thread.3.dll" ./build/bin
+ cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_intel_thread.3.dll" ./build/bin
+ cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/libimalloc.dll" ./build/bin
cp "${{ env.ONEAPI_ROOT }}/compiler/latest/bin/ur_adapter_level_zero.dll" ./build/bin
cp "${{ env.ONEAPI_ROOT }}/compiler/latest/bin/ur_adapter_level_zero_v2.dll" ./build/bin
diff --git a/.github/workflows/ui-build.yml b/.github/workflows/ui-build.yml
index e0d8dd065e98..f229fcd04480 100644
--- a/.github/workflows/ui-build.yml
+++ b/.github/workflows/ui-build.yml
@@ -15,7 +15,7 @@ permissions:
jobs:
build:
- runs-on: ubuntu-slim
+ runs-on: ubuntu-26.04-arm
steps:
- name: Checkout code
diff --git a/README.md b/README.md
index e1831c731e16..84e9eb5d9295 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# llama.cpp
-
+
diff --git a/cmake/download-models.cmake b/cmake/download-models.cmake
index de252906a01f..57c141265be7 100644
--- a/cmake/download-models.cmake
+++ b/cmake/download-models.cmake
@@ -2,11 +2,11 @@ get_filename_component(DEST_DIR "${DEST}" DIRECTORY)
file(MAKE_DIRECTORY "${DEST_DIR}")
if(NOT EXISTS "${DEST}")
- message(STATUS "Downloading ${NAME} from ggml-org/models...")
+ message(STATUS "Downloading ${NAME} from ${REPO}...")
endif()
file(DOWNLOAD
- "https://huggingface.co/ggml-org/models/resolve/main/${NAME}?download=true"
+ "https://huggingface.co/${REPO}/resolve/main/${NAME}?download=true"
"${DEST}"
TLS_VERIFY ON
EXPECTED_HASH ${HASH}
diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt
index 8e3c88dac9dc..e38485ca017c 100644
--- a/common/CMakeLists.txt
+++ b/common/CMakeLists.txt
@@ -66,6 +66,8 @@ add_library(${TARGET}
chat-diff-analyzer.cpp
chat-peg-parser.cpp
chat-peg-parser.h
+ chat-tts-norm.cpp
+ chat-tts-norm.h
chat.cpp
chat.h
common.cpp
diff --git a/common/arg.cpp b/common/arg.cpp
index 4b716398e8f3..6bf9355fb0ff 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -943,8 +943,8 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context
}
const bool mcp_enabled = !params.mcp_servers_config.empty() || !params.mcp_servers_json.empty();
- if ((!params.server_tools.empty() || mcp_enabled) && !params.cors_origins_explicit) {
- LOG_WRN("server tools or MCP servers are enabled, using localhost as default CORS origin (change via --cors-origins)\n");
+ if ((!params.server_tools.empty() || mcp_enabled || params.ui_mcp_proxy) && !params.cors_origins_explicit) {
+ LOG_WRN("server tools, MCP servers or MCP proxy are enabled, using localhost as default CORS origin (change via --cors-origins)\n");
params.cors_origins = "localhost";
}
@@ -2501,15 +2501,6 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
params.ppl_output_type = value;
}
).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
- add_opt(common_arg(
- {"-dt", "--defrag-thold"}, "N",
- string_format("KV cache defragmentation threshold (DEPRECATED)"),
- [](common_params & params, const std::string & value) {
- GGML_UNUSED(params);
- GGML_UNUSED(value);
- LOG_WRN("DEPRECATED: --defrag-thold is deprecated and no longer necessary to specify\n");
- }
- ).set_env("LLAMA_ARG_DEFRAG_THOLD"));
if (ex == LLAMA_EXAMPLE_SERVER) {
// this is to make sure this option appears in the server-specific section of the help message
add_opt(common_arg(
@@ -3361,7 +3352,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
{"--cors-origins"}, "ORIGINS",
string_format(
"comma-separated list of allowed origins for CORS (default: %s)\n"
- "if set to special value 'localhost', reflect the Origin header only if it is localhost",
+ "if set to special value 'localhost', only allow same-origin requests (e.g. the built-in UI)",
params.cors_origins.c_str()),
[](common_params & params, const std::string & value) {
params.cors_origins = value;
@@ -3417,7 +3408,8 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
add_opt(common_arg(
{"--ui-mcp-proxy", "--webui-mcp-proxy"},
{"--no-ui-mcp-proxy", "--no-webui-mcp-proxy"},
- "experimental: whether to enable MCP CORS proxy - do not enable in untrusted environments (default: disabled)",
+ "experimental: whether to enable MCP CORS proxy, for the Web UI to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)\n"
+ "note: for security reasons, this will limit --cors-origins to localhost by default",
[](common_params & params, bool value) {
params.ui_mcp_proxy = value;
}
@@ -3443,6 +3435,13 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
params.server_tools_runtime = value;
}
).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_TOOLS_RUNTIME"));
+ add_opt(common_arg(
+ {"--allow-unauthenticated-tools"},
+ "allow server tools, MCP servers or MCP proxy on a non-loopback address without an API key - only for trusted networks (default: disabled)",
+ [](common_params & params) {
+ params.server_tools_allow_unauth = true;
+ }
+ ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ALLOW_UNAUTHENTICATED_TOOLS"));
add_opt(common_arg(
{"--mcp-servers-config"}, "PATH",
"experimental: path to JSON file with MCP server definitions (Cursor-compatible format) - do not enable in untrusted environments (default: none)\n"
@@ -3668,6 +3667,13 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
}
}
).set_examples({LLAMA_EXAMPLE_SERVER}));
+ add_opt(common_arg(
+ {"--media-allow-private-urls"},
+ "allow http(s) media URLs (e.g. image_url) that point to local or private addresses (default: disabled, only public addresses)",
+ [](common_params & params) {
+ params.media_allow_private_urls = true;
+ }
+ ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_MEDIA_ALLOW_PRIVATE_URLS"));
add_opt(common_arg(
{"--models-dir"}, "PATH",
"directory containing models for the router server (default: disabled)",
diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp
index 4440b2ebd207..968cbfa98f6c 100644
--- a/common/chat-peg-parser.cpp
+++ b/common/chat-peg-parser.cpp
@@ -973,6 +973,21 @@ void common_chat_peg_gemma4_mapper::from_ast(const common_peg_ast_arena & arena,
}
}
+using gemma4 = common_chat_peg_gemma4_mapper;
+
+// Collects the nearest descendants carrying tag, looking through the rules the parser
+// wraps around the tagged nodes.
+static void gemma4_collect(const common_peg_ast_arena & arena, const common_peg_ast_node & node, const std::string & tag, std::vector
& out) {
+ for (auto child_id : node.children) {
+ const auto & child = arena.get(child_id);
+ if (child.tag == tag) {
+ out.push_back(child_id);
+ } else {
+ gemma4_collect(arena, child, tag, out);
+ }
+ }
+}
+
static std::string gemma4_to_json(const common_peg_ast_arena & arena, common_peg_ast_id id) {
const auto & node = arena.get(id);
@@ -980,51 +995,45 @@ static std::string gemma4_to_json(const common_peg_ast_arena & arena, common_peg
return "";
}
- if (node.rule == "gemma4-number" || node.rule == "gemma4-bool" || node.rule == "gemma4-null") {
+ if (node.tag == gemma4::NUMBER || node.tag == gemma4::BOOL || node.tag == gemma4::NULL_) {
return std::string(node.text);
}
- if (node.rule == "gemma4-string-content") {
+ if (node.tag == gemma4::STRING_CONTENT) {
return escape_json_string_inner(node.sanitized_text());
}
- if (node.rule == "gemma4-string") {
+ if (node.tag == gemma4::STRING) {
std::string result = "\"";
- if (!node.children.empty()) {
- result += gemma4_to_json(arena, node.children[0]);
- if (!node.is_partial) {
- result += "\"";
- }
+ for (auto child_id : node.children) {
+ result += gemma4_to_json(arena, child_id);
+ }
+ if (!node.is_partial) {
+ result += "\"";
}
return result;
}
- if (node.rule == "gemma4-array") {
+ if (node.tag == gemma4::ARRAY) {
std::string result = "[";
-
- bool add_comma = false;
- for (auto child_id : node.children) {
- if (add_comma) {
+ for (size_t i = 0; i < node.children.size(); i++) {
+ if (i > 0) {
result += ',';
}
- add_comma = true;
- result += gemma4_to_json(arena, child_id);
+ result += gemma4_to_json(arena, node.children[i]);
}
-
if (!node.is_partial) {
result += ']';
}
return result;
}
- if (node.rule == "gemma4-dict-key-name") {
- return std::string(node.text);
- }
+ if (node.tag == gemma4::DICT_KEY) {
+ auto name_id = arena.find_by_tag(node, gemma4::DICT_KEY_NAME);
- if (node.rule == "gemma4-dict-key") {
std::string result = "\"";
- if (!node.children.empty()) {
- result += escape_json_string_inner(gemma4_to_json(arena, node.children[0]));
+ if (name_id != COMMON_PEG_INVALID_AST_ID) {
+ result += escape_json_string_inner(std::string(arena.get(name_id).text));
}
if (!node.is_partial) {
result += "\":";
@@ -1032,40 +1041,29 @@ static std::string gemma4_to_json(const common_peg_ast_arena & arena, common_peg
return result;
}
- if (node.rule == "gemma4-dict-kv") {
- std::string result;
- for (auto child_id : node.children) {
- result += gemma4_to_json(arena, child_id);
- }
- return result;
- }
+ if (node.tag == gemma4::DICT) {
+ std::vector members;
+ gemma4_collect(arena, node, gemma4::DICT_KV, members);
- if (node.rule == "gemma4-dict") {
std::string result = "{";
-
- bool add_comma = false;
- for (auto child_id : node.children) {
- if (add_comma) {
+ for (size_t i = 0; i < members.size(); i++) {
+ if (i > 0) {
result += ',';
}
- add_comma = true;
- result += gemma4_to_json(arena, child_id);
+ result += gemma4_to_json(arena, members[i]);
}
-
if (!node.is_partial) {
result += '}';
}
return result;
}
- if (node.rule == "gemma4-value") {
- if (!node.children.empty()) {
- return gemma4_to_json(arena, node.children[0]);
- }
- return "";
+ // members, rules and other wrappers
+ std::string result;
+ for (auto child_id : node.children) {
+ result += gemma4_to_json(arena, child_id);
}
-
- return "";
+ return result;
}
void common_chat_peg_gemma4_mapper::visit(const common_peg_ast_arena & arena, common_peg_ast_id id) {
diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h
index 114fa049fa74..b827b60b059c 100644
--- a/common/chat-peg-parser.h
+++ b/common/chat-peg-parser.h
@@ -34,6 +34,18 @@ class common_chat_peg_mapper {
class common_chat_peg_gemma4_mapper : public common_chat_peg_mapper {
public:
+ // Tags of the Gemma 4 argument syntax. The parser may wrap them in any rules.
+ static constexpr const char * STRING = "gemma4-string";
+ static constexpr const char * STRING_CONTENT = "gemma4-string-content";
+ static constexpr const char * NUMBER = "gemma4-number";
+ static constexpr const char * BOOL = "gemma4-bool";
+ static constexpr const char * NULL_ = "gemma4-null";
+ static constexpr const char * ARRAY = "gemma4-array";
+ static constexpr const char * DICT = "gemma4-dict";
+ static constexpr const char * DICT_KV = "gemma4-dict-kv";
+ static constexpr const char * DICT_KEY = "gemma4-dict-key";
+ static constexpr const char * DICT_KEY_NAME = "gemma4-dict-key-name";
+
common_chat_peg_gemma4_mapper(common_chat_msg & msg) : common_chat_peg_mapper(msg) {}
virtual void from_ast(const common_peg_ast_arena & arena, const common_peg_parse_result & result);
private:
diff --git a/common/chat-tts-norm.cpp b/common/chat-tts-norm.cpp
new file mode 100644
index 000000000000..f84540ff96e0
--- /dev/null
+++ b/common/chat-tts-norm.cpp
@@ -0,0 +1,864 @@
+#include "chat-tts-norm.h"
+
+#include "jinja/runtime.h"
+#include "jinja/value.h"
+
+#include
+#include
+#include
+#include
+#include
+
+// TTS normalization patterns, see docs/tts-norm-patterns.md for the specification
+// keep this file in sync with the python reference: scripts/chat_tts_norm.py
+
+using namespace jinja;
+
+//
+// character classes
+// they are defined with explicit codepoint ranges, independent of any unicode database version,
+// so that the C++ and python implementations agree on every codepoint
+//
+
+struct tts_norm_range {
+ uint32_t lo;
+ uint32_t hi;
+};
+
+static const tts_norm_range TTS_NORM_SPACE[] = {
+ {0x0009, 0x000D}, {0x0020, 0x0020}, {0x0085, 0x0085}, {0x00A0, 0x00A0}, {0x1680, 0x1680},
+ {0x2000, 0x200A}, {0x2028, 0x2029}, {0x202F, 0x202F}, {0x205F, 0x205F}, {0x3000, 0x3000},
+};
+
+static const tts_norm_range TTS_NORM_PUNCT[] = {
+ {0x0021, 0x002F}, {0x003A, 0x0040}, {0x005B, 0x0060}, {0x007B, 0x007E},
+ {0x00A1, 0x00A9}, {0x00AB, 0x00B4}, {0x00B6, 0x00B9}, {0x00BB, 0x00BF}, {0x00D7, 0x00D7}, {0x00F7, 0x00F7},
+ {0x2010, 0x2027}, {0x2030, 0x205E}, {0x20A0, 0x20CF}, {0x2100, 0x218F}, {0x2190, 0x2BFF},
+ {0x3001, 0x3003}, {0x3008, 0x3020}, {0x3030, 0x3030}, {0x303D, 0x303D}, {0x30FB, 0x30FB},
+ {0xFE10, 0xFE19}, {0xFE30, 0xFE4F}, {0xFE50, 0xFE6B},
+ {0xFF01, 0xFF0F}, {0xFF1A, 0xFF20}, {0xFF3B, 0xFF40}, {0xFF5B, 0xFF65},
+ {0x1F000, 0x1FAFF},
+};
+
+static const tts_norm_range TTS_NORM_CONTROL[] = {
+ {0x0000, 0x001F}, {0x007F, 0x009F}, {0x200B, 0x200F}, {0x2060, 0x206F}, {0xFEFF, 0xFEFF},
+};
+
+static const tts_norm_range TTS_NORM_HAN[] = {
+ {0x2E80, 0x2FDF}, {0x3005, 0x3005}, {0x3007, 0x3007}, {0x3021, 0x3029}, {0x3038, 0x303B},
+ {0x3400, 0x4DBF}, {0x4E00, 0x9FFF}, {0xF900, 0xFAFF}, {0x20000, 0x323AF},
+};
+
+template
+static bool tts_norm_in(const tts_norm_range (&ranges)[N], uint32_t c) {
+ for (const auto & r : ranges) {
+ if (c >= r.lo && c <= r.hi) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool tts_norm_is_alpha(uint32_t c) {
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+ return true;
+ }
+ if (c == 0xAA || c == 0xB5 || c == 0xBA) {
+ return true;
+ }
+ return c >= 0xC0 && !tts_norm_in(TTS_NORM_SPACE, c) && !tts_norm_in(TTS_NORM_PUNCT, c) && !tts_norm_in(TTS_NORM_CONTROL, c);
+}
+
+// kind is one of "dspawulhc"
+static bool tts_norm_class_match(char kind, uint32_t c) {
+ switch (kind) {
+ case 'd': return c >= '0' && c <= '9';
+ case 's': return tts_norm_in(TTS_NORM_SPACE, c);
+ case 'p': return tts_norm_in(TTS_NORM_PUNCT, c);
+ case 'a': return tts_norm_is_alpha(c);
+ case 'w': return tts_norm_is_alpha(c) || (c >= '0' && c <= '9');
+ case 'u': return c >= 'A' && c <= 'Z';
+ case 'l': return c >= 'a' && c <= 'z';
+ case 'h': return tts_norm_in(TTS_NORM_HAN, c);
+ case 'c': return tts_norm_in(TTS_NORM_CONTROL, c);
+ }
+ return false;
+}
+
+static bool tts_norm_is_class_letter(uint32_t c) {
+ if (c >= 'A' && c <= 'Z') {
+ c += 'a' - 'A';
+ }
+ return c < 0x80 && std::string("dspawulhc").find(static_cast(c)) != std::string::npos;
+}
+
+static uint32_t tts_norm_ascii_lower(uint32_t c) {
+ return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c;
+}
+
+static uint32_t tts_norm_ascii_swapcase(uint32_t c) {
+ if (c >= 'A' && c <= 'Z') return c + ('a' - 'A');
+ if (c >= 'a' && c <= 'z') return c - ('a' - 'A');
+ return c;
+}
+
+static bool tts_norm_is_ascii_alnum(uint32_t c) {
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
+}
+
+// invalid bytes are decoded as U+FFFD, one per byte; offs[i] is the byte offset of codepoint i, offs[n] = text size
+static void tts_norm_decode_utf8(const std::string & s, std::vector & cpts, std::vector & offs) {
+ cpts.clear();
+ offs.clear();
+ size_t i = 0;
+ const size_t n = s.size();
+ while (i < n) {
+ offs.push_back(i);
+ const unsigned char c = static_cast(s[i]);
+ uint32_t cp = 0;
+ size_t len = 0;
+ if (c < 0x80) {
+ cp = c; len = 1;
+ } else if ((c & 0xE0) == 0xC0) {
+ cp = c & 0x1F; len = 2;
+ } else if ((c & 0xF0) == 0xE0) {
+ cp = c & 0x0F; len = 3;
+ } else if ((c & 0xF8) == 0xF0) {
+ cp = c & 0x07; len = 4;
+ }
+ bool ok = len > 0 && i + len <= n;
+ for (size_t k = 1; ok && k < len; k++) {
+ const unsigned char cc = static_cast(s[i + k]);
+ if ((cc & 0xC0) != 0x80) {
+ ok = false;
+ } else {
+ cp = (cp << 6) | (cc & 0x3F);
+ }
+ }
+ if (!ok) {
+ cpts.push_back(0xFFFD);
+ i += 1;
+ } else {
+ cpts.push_back(cp);
+ i += len;
+ }
+ }
+ offs.push_back(n);
+}
+
+//
+// AST
+//
+
+enum class tts_norm_op {
+ LITERAL, // one codepoint
+ SET, // one codepoint from a set; class escapes like %d are sets with a single class
+ ANY, // any codepoint
+ START, // ^
+ END, // $
+ BOUNDARY, // %b
+ GROUP, // (...), (?:...), (?...)
+ LOOKAHEAD, // (?=...), (?!...)
+ LOOKBEHIND, // (?<=c), (?> ranges;
+ std::vector classes;
+};
+
+struct tts_norm_item;
+using tts_norm_seq = std::vector;
+
+struct tts_norm_pattern_node {
+ tts_norm_op op = tts_norm_op::GROUP;
+ uint32_t cp = 0; // LITERAL
+ tts_norm_set set; // SET
+ std::vector alts; // GROUP, LOOKAHEAD; LOOKBEHIND holds a single item
+ int capture = -1; // GROUP: capture index, -1 for non-capturing
+ bool neg = false; // LOOKAHEAD, LOOKBEHIND
+};
+
+static constexpr int TTS_NORM_INF = INT_MAX;
+static constexpr int TTS_NORM_MAX_REPEAT = 1000;
+static constexpr size_t TTS_NORM_MAX_PATTERN_LEN = 4096;
+
+struct tts_norm_item {
+ tts_norm_pattern_node atom;
+ int min = 1;
+ int max = 1;
+};
+
+static bool tts_norm_is_zero_width(tts_norm_op op) {
+ return op == tts_norm_op::START || op == tts_norm_op::END || op == tts_norm_op::BOUNDARY
+ || op == tts_norm_op::LOOKAHEAD || op == tts_norm_op::LOOKBEHIND;
+}
+
+//
+// parser
+//
+
+struct tts_norm_parser {
+ std::vector s;
+ size_t p = 0;
+ size_t & n_caps;
+
+ tts_norm_parser(std::vector src, size_t & n_caps) : s(std::move(src)), n_caps(n_caps) {}
+
+ [[noreturn]] void fail(const std::string & msg) const {
+ throw std::runtime_error("invalid TTS norm pattern: " + msg + " at position " + std::to_string(p));
+ }
+
+ bool eof() const { return p >= s.size(); }
+ uint32_t peek() const { return s[p]; }
+ bool peek_is(uint32_t c) const { return !eof() && s[p] == c; }
+
+ void expect(uint32_t c, const char * what) {
+ if (!peek_is(c)) {
+ fail(std::string("expected ") + what);
+ }
+ p++;
+ }
+
+ std::vector parse_alts() {
+ std::vector alts;
+ alts.push_back(parse_seq());
+ while (peek_is('|')) {
+ p++;
+ alts.push_back(parse_seq());
+ }
+ return alts;
+ }
+
+ tts_norm_seq parse_seq() {
+ tts_norm_seq seq;
+ while (!eof() && peek() != '|' && peek() != ')') {
+ tts_norm_item item;
+ item.atom = parse_atom();
+ parse_quantifier(item);
+ seq.push_back(std::move(item));
+ }
+ return seq;
+ }
+
+ int parse_int() {
+ if (eof() || peek() < '0' || peek() > '9') {
+ fail("expected number in quantifier");
+ }
+ int v = 0;
+ while (!eof() && peek() >= '0' && peek() <= '9') {
+ v = v * 10 + static_cast(peek() - '0');
+ if (v > TTS_NORM_MAX_REPEAT) {
+ fail("repetition count exceeds " + std::to_string(TTS_NORM_MAX_REPEAT));
+ }
+ p++;
+ }
+ return v;
+ }
+
+ void parse_quantifier(tts_norm_item & item) {
+ if (eof()) {
+ return;
+ }
+ const uint32_t c = peek();
+ if (c != '?' && c != '*' && c != '+' && c != '{') {
+ return;
+ }
+ if (tts_norm_is_zero_width(item.atom.op)) {
+ fail("zero-width assertion cannot be repeated");
+ }
+ p++;
+ if (c == '?') {
+ item.min = 0; item.max = 1;
+ } else if (c == '*') {
+ item.min = 0; item.max = TTS_NORM_INF;
+ } else if (c == '+') {
+ item.min = 1; item.max = TTS_NORM_INF;
+ } else {
+ item.min = parse_int();
+ item.max = item.min;
+ if (peek_is(',')) {
+ p++;
+ item.max = peek_is('}') ? TTS_NORM_INF : parse_int();
+ }
+ expect('}', "'}' to close quantifier");
+ if (item.max < item.min) {
+ fail("quantifier max is smaller than min");
+ }
+ }
+ if (!eof() && (peek() == '?' || peek() == '*' || peek() == '+' || peek() == '{')) {
+ fail("multiple quantifiers");
+ }
+ }
+
+ tts_norm_pattern_node parse_group() {
+ // '(' already consumed
+ tts_norm_pattern_node node;
+ node.op = tts_norm_op::GROUP;
+ if (peek_is('?')) {
+ p++;
+ if (eof()) {
+ fail("unterminated group");
+ }
+ const uint32_t c = peek();
+ if (c == ':') {
+ p++;
+ } else if (c == '=' || c == '!') {
+ p++;
+ node.op = tts_norm_op::LOOKAHEAD;
+ node.neg = c == '!';
+ } else if (c == '<' && p + 1 < s.size() && (s[p + 1] == '=' || s[p + 1] == '!')) {
+ node.op = tts_norm_op::LOOKBEHIND;
+ node.neg = s[p + 1] == '!';
+ p += 2;
+ tts_norm_item item;
+ if (eof() || peek() == ')') {
+ fail("lookbehind must contain exactly one codepoint matcher");
+ }
+ item.atom = parse_atom();
+ if (item.atom.op != tts_norm_op::LITERAL && item.atom.op != tts_norm_op::SET && item.atom.op != tts_norm_op::ANY) {
+ fail("lookbehind must contain exactly one codepoint matcher");
+ }
+ if (!peek_is(')')) {
+ fail("lookbehind must contain exactly one codepoint matcher");
+ }
+ p++;
+ node.alts.push_back(tts_norm_seq{});
+ node.alts[0].push_back(std::move(item));
+ return node;
+ } else if (c == 'i') {
+ fail("(?i) is only allowed at the start of the pattern");
+ } else {
+ fail("unknown group type");
+ }
+ } else {
+ node.capture = static_cast(n_caps++);
+ }
+ node.alts = parse_alts();
+ expect(')', "')' to close group");
+ return node;
+ }
+
+ // after '%' inside or outside of a set
+ // returns true if it is a class (stored in cls), false if it is a literal (stored in lit)
+ bool parse_escape(bool in_set, tts_norm_class & cls, uint32_t & lit, bool & boundary) {
+ boundary = false;
+ if (eof()) {
+ fail("dangling '%'");
+ }
+ const uint32_t e = s[p++];
+ if (tts_norm_is_class_letter(e)) {
+ cls.kind = static_cast(tts_norm_ascii_lower(e));
+ cls.neg = e >= 'A' && e <= 'Z';
+ return true;
+ }
+ if (e == 'b' && !in_set) {
+ boundary = true;
+ return false;
+ }
+ if (tts_norm_is_ascii_alnum(e)) {
+ p--;
+ fail(std::string("unknown escape '%") + static_cast(e) + "'");
+ }
+ lit = e;
+ return false;
+ }
+
+ tts_norm_pattern_node parse_set() {
+ // '[' already consumed
+ tts_norm_pattern_node node;
+ node.op = tts_norm_op::SET;
+ if (peek_is('^')) {
+ node.set.neg = true;
+ p++;
+ }
+ bool empty = true;
+ while (true) {
+ if (eof()) {
+ fail("unterminated set");
+ }
+ if (peek() == ']') {
+ p++;
+ break;
+ }
+ empty = false;
+ uint32_t lo = 0;
+ if (peek() == '%') {
+ p++;
+ tts_norm_class cls{};
+ bool boundary = false;
+ if (parse_escape(true, cls, lo, boundary)) {
+ node.set.classes.push_back(cls);
+ continue;
+ }
+ } else {
+ lo = s[p++];
+ }
+ uint32_t hi = lo;
+ if (peek_is('-') && p + 1 < s.size() && s[p + 1] != ']') {
+ p++;
+ if (peek() == '%') {
+ p++;
+ tts_norm_class cls{};
+ bool boundary = false;
+ if (parse_escape(true, cls, hi, boundary)) {
+ fail("character class cannot be used in a range");
+ }
+ } else {
+ hi = s[p++];
+ }
+ if (hi < lo) {
+ fail("invalid range in set");
+ }
+ }
+ node.set.ranges.emplace_back(lo, hi);
+ }
+ if (empty) {
+ fail("empty set");
+ }
+ return node;
+ }
+
+ tts_norm_pattern_node parse_atom() {
+ const uint32_t c = s[p++];
+ tts_norm_pattern_node node;
+ switch (c) {
+ case '(':
+ return parse_group();
+ case '[':
+ return parse_set();
+ case '.':
+ node.op = tts_norm_op::ANY;
+ return node;
+ case '^':
+ node.op = tts_norm_op::START;
+ return node;
+ case '$':
+ node.op = tts_norm_op::END;
+ return node;
+ case '%': {
+ tts_norm_class cls{};
+ uint32_t lit = 0;
+ bool boundary = false;
+ if (parse_escape(false, cls, lit, boundary)) {
+ node.op = tts_norm_op::SET;
+ node.set.classes.push_back(cls);
+ } else if (boundary) {
+ node.op = tts_norm_op::BOUNDARY;
+ } else {
+ node.op = tts_norm_op::LITERAL;
+ node.cp = lit;
+ }
+ return node;
+ }
+ case '?':
+ case '*':
+ case '+':
+ case '{':
+ p--;
+ fail("nothing to repeat");
+ case ']':
+ case '}':
+ p--;
+ fail(std::string("unescaped '") + static_cast(c) + "', use '%" + static_cast(c) + "'");
+ default:
+ node.op = tts_norm_op::LITERAL;
+ node.cp = c;
+ return node;
+ }
+ }
+};
+
+//
+// matcher
+// PEG-style: alternatives are ordered (the first one that matches wins) and quantifiers are greedy and possessive
+// (they never give back what they consumed), so there is no backtracking
+//
+
+struct tts_norm_matcher {
+ const std::vector & t;
+ bool icase;
+ std::vector> caps;
+
+ bool is_w(size_t i) const {
+ return i < t.size() && tts_norm_class_match('w', t[i]);
+ }
+
+ bool set_match(const tts_norm_set & st, uint32_t c) const {
+ auto test = [&](uint32_t x) {
+ for (const auto & r : st.ranges) {
+ if (x >= r.first && x <= r.second) {
+ return true;
+ }
+ }
+ for (const auto & k : st.classes) {
+ if (tts_norm_class_match(k.kind, x) != k.neg) {
+ return true;
+ }
+ }
+ return false;
+ };
+ bool m = test(c);
+ if (!m && icase) {
+ const uint32_t o = tts_norm_ascii_swapcase(c);
+ if (o != c) {
+ m = test(o);
+ }
+ }
+ return m != st.neg;
+ }
+
+ bool match_alts(const std::vector & alts, size_t i, size_t & end) {
+ for (const auto & seq : alts) {
+ auto saved = caps;
+ if (match_seq(seq, i, end)) {
+ return true;
+ }
+ caps = std::move(saved);
+ }
+ return false;
+ }
+
+ bool match_seq(const tts_norm_seq & seq, size_t i, size_t & end) {
+ size_t pos = i;
+ for (const auto & it : seq) {
+ int count = 0;
+ while (count < it.max) {
+ const bool is_group = it.atom.op == tts_norm_op::GROUP;
+ std::vector> saved;
+ if (is_group) {
+ saved = caps;
+ }
+ size_t e = pos;
+ if (!match_once(it.atom, pos, e)) {
+ if (is_group) {
+ caps = std::move(saved);
+ }
+ break;
+ }
+ if (e == pos) {
+ // an empty iteration would repeat forever, it satisfies any remaining minimum
+ count = std::max(count + 1, it.min);
+ break;
+ }
+ pos = e;
+ count++;
+ }
+ if (count < it.min) {
+ return false;
+ }
+ }
+ end = pos;
+ return true;
+ }
+
+ bool match_once(const tts_norm_pattern_node & node, size_t i, size_t & end) {
+ const size_t n = t.size();
+ switch (node.op) {
+ case tts_norm_op::LITERAL:
+ if (i < n && (t[i] == node.cp || (icase && tts_norm_ascii_lower(t[i]) == tts_norm_ascii_lower(node.cp)))) {
+ end = i + 1;
+ return true;
+ }
+ return false;
+ case tts_norm_op::SET:
+ if (i < n && set_match(node.set, t[i])) {
+ end = i + 1;
+ return true;
+ }
+ return false;
+ case tts_norm_op::ANY:
+ if (i < n) {
+ end = i + 1;
+ return true;
+ }
+ return false;
+ case tts_norm_op::START:
+ end = i;
+ return i == 0;
+ case tts_norm_op::END:
+ end = i;
+ return i == n;
+ case tts_norm_op::BOUNDARY:
+ end = i;
+ return (i > 0 && is_w(i - 1)) != is_w(i);
+ case tts_norm_op::GROUP: {
+ size_t e = i;
+ if (!match_alts(node.alts, i, e)) {
+ return false;
+ }
+ if (node.capture >= 0) {
+ caps[node.capture] = {static_cast(i), static_cast(e)};
+ }
+ end = e;
+ return true;
+ }
+ case tts_norm_op::LOOKAHEAD: {
+ // captures made inside a lookahead are discarded
+ auto saved = caps;
+ size_t e = i;
+ const bool ok = match_alts(node.alts, i, e);
+ caps = std::move(saved);
+ end = i;
+ return ok != node.neg;
+ }
+ case tts_norm_op::LOOKBEHIND: {
+ size_t e = 0;
+ const bool ok = i > 0 && match_once(node.alts[0][0].atom, i - 1, e) && e == i;
+ end = i;
+ return ok != node.neg;
+ }
+ }
+ return false;
+ }
+};
+
+//
+// common_tts_norm_pattern
+//
+
+common_tts_norm_pattern::common_tts_norm_pattern(const std::string & src) {
+ if (src.size() > TTS_NORM_MAX_PATTERN_LEN) {
+ throw std::runtime_error("invalid TTS norm pattern: pattern is longer than " + std::to_string(TTS_NORM_MAX_PATTERN_LEN) + " bytes");
+ }
+ std::vector cpts;
+ std::vector offs;
+ tts_norm_decode_utf8(src, cpts, offs);
+
+ tts_norm_parser parser(std::move(cpts), n_caps);
+ static const std::vector icase_prefix = {'(', '?', 'i', ')'};
+ if (parser.s.size() >= 4 && std::equal(icase_prefix.begin(), icase_prefix.end(), parser.s.begin())) {
+ icase = true;
+ parser.p = 4;
+ }
+
+ root = std::make_unique();
+ root->op = tts_norm_op::GROUP;
+ root->alts = parser.parse_alts();
+ if (!parser.eof()) {
+ parser.fail("unbalanced ')'");
+ }
+}
+
+common_tts_norm_pattern::~common_tts_norm_pattern() = default;
+common_tts_norm_pattern::common_tts_norm_pattern(common_tts_norm_pattern &&) noexcept = default;
+common_tts_norm_pattern & common_tts_norm_pattern::operator=(common_tts_norm_pattern &&) noexcept = default;
+
+bool common_tts_norm_pattern::match_at(const std::vector & cpts, size_t pos, size_t & end, std::vector> & groups) const {
+ tts_norm_matcher m{cpts, icase, std::vector>(n_caps, {-1, -1})};
+ size_t e = pos;
+ if (!m.match_alts(root->alts, pos, e)) {
+ return false;
+ }
+ end = e;
+ groups = std::move(m.caps);
+ return true;
+}
+
+size_t common_tts_norm_pattern::n_groups() const {
+ return n_caps;
+}
+
+//
+// scan / sub
+//
+
+std::vector common_tts_norm_scan(const std::string & text, const std::vector & rules) {
+ std::vector cpts;
+ std::vector offs;
+ tts_norm_decode_utf8(text, cpts, offs);
+
+ std::vector out;
+ const size_t n = cpts.size();
+ size_t i = 0;
+ size_t pending = 0; // start of the current unmatched run
+ std::vector> groups;
+
+ while (i < n) {
+ bool matched = false;
+ for (size_t r = 0; r < rules.size(); r++) {
+ size_t end = i;
+ if (rules[r]->match_at(cpts, i, end, groups) && end > i) {
+ if (pending < i) {
+ out.push_back({-1, offs[pending], offs[i], {}});
+ }
+ common_tts_norm_segment seg;
+ seg.rule = static_cast(r);
+ seg.start = offs[i];
+ seg.end = offs[end];
+ for (const auto & g : groups) {
+ if (g.first < 0) {
+ seg.groups.emplace_back(std::string::npos, std::string::npos);
+ } else {
+ seg.groups.emplace_back(offs[g.first], offs[g.second]);
+ }
+ }
+ out.push_back(std::move(seg));
+ i = end;
+ pending = i;
+ matched = true;
+ break;
+ }
+ }
+ if (!matched) {
+ i++;
+ }
+ }
+ if (pending < n) {
+ out.push_back({-1, offs[pending], offs[n], {}});
+ }
+ return out;
+}
+
+struct tts_norm_repl_piece {
+ std::string literal;
+ int group = -1; // 0 = whole match, 1.. = groups
+};
+
+static std::vector tts_norm_parse_repl(const std::string & repl, const common_tts_norm_pattern & pattern) {
+ std::vector pieces;
+ std::string lit;
+ auto flush = [&]() {
+ if (!lit.empty()) {
+ pieces.push_back({lit, -1});
+ lit.clear();
+ }
+ };
+ for (size_t i = 0; i < repl.size(); i++) {
+ if (repl[i] != '%') {
+ lit += repl[i];
+ continue;
+ }
+ if (i + 1 >= repl.size()) {
+ throw std::runtime_error("invalid TTS norm replacement: dangling '%'");
+ }
+ const char c = repl[++i];
+ if (c == '%') {
+ lit += '%';
+ } else if (c >= '0' && c <= '9') {
+ const int g = c - '0';
+ if (static_cast(g) > pattern.n_groups()) {
+ throw std::runtime_error("invalid TTS norm replacement: group %" + std::string(1, c) + " does not exist");
+ }
+ flush();
+ pieces.push_back({"", g});
+ } else {
+ throw std::runtime_error("invalid TTS norm replacement: unknown escape '%" + std::string(1, c) + "'");
+ }
+ }
+ flush();
+ return pieces;
+}
+
+std::string common_tts_norm_sub(const std::string & text, const common_tts_norm_pattern & pattern, const std::string & repl) {
+ const auto pieces = tts_norm_parse_repl(repl, pattern);
+ std::string out;
+ for (const auto & seg : common_tts_norm_scan(text, {&pattern})) {
+ if (seg.rule < 0) {
+ out.append(text, seg.start, seg.end - seg.start);
+ continue;
+ }
+ for (const auto & piece : pieces) {
+ if (piece.group < 0) {
+ out += piece.literal;
+ } else if (piece.group == 0) {
+ out.append(text, seg.start, seg.end - seg.start);
+ } else {
+ const auto & g = seg.groups[piece.group - 1];
+ if (g.first != std::string::npos) {
+ out.append(text, g.first, g.second - g.first);
+ }
+ }
+ }
+ }
+ return out;
+}
+
+//
+// template builtins
+//
+
+// rules can be: a pattern string (rule name "match"), a dict {name: pattern}, or a list of [name, pattern] pairs
+static std::vector> tts_norm_rules_from_value(const value & v) {
+ std::vector> rules;
+ if (is_val(v)) {
+ rules.emplace_back("match", v->as_string().str());
+ } else if (is_val(v)) {
+ for (const auto & kv : v->as_ordered_object()) {
+ if (!is_val(kv.second)) {
+ throw std::runtime_error("tts_norm_scan: rule pattern must be a string");
+ }
+ rules.emplace_back(kv.first->as_string().str(), kv.second->as_string().str());
+ }
+ } else if (is_val(v)) {
+ for (const auto & item : v->as_array()) {
+ if (!is_val(item) || item->as_array().size() != 2
+ || !is_val(item->as_array()[0]) || !is_val(item->as_array()[1])) {
+ throw std::runtime_error("tts_norm_scan: each rule must be a [name, pattern] pair of strings");
+ }
+ rules.emplace_back(item->as_array()[0]->as_string().str(), item->as_array()[1]->as_string().str());
+ }
+ } else {
+ throw std::runtime_error("tts_norm_scan: rules must be a string, a dict or a list of [name, pattern] pairs, got " + v->type());
+ }
+ return rules;
+}
+
+static value tts_norm_builtin_scan(const func_args & args) {
+ args.ensure_count(2, 2);
+ args.ensure_val(args.get_pos(0));
+ const string text_val = args.get_pos(0)->as_string();
+ const std::string text = text_val.str();
+ const bool is_input = text_val.all_parts_are_input();
+
+ const auto rule_srcs = tts_norm_rules_from_value(args.get_pos(1));
+ std::vector patterns;
+ patterns.reserve(rule_srcs.size());
+ std::vector ptrs;
+ for (const auto & r : rule_srcs) {
+ patterns.emplace_back(r.second);
+ }
+ for (const auto & p : patterns) {
+ ptrs.push_back(&p);
+ }
+
+ auto mk_str = [&](size_t start, size_t end) -> value {
+ return mk_val(string(text.substr(start, end - start), is_input));
+ };
+
+ auto out = mk_val();
+ for (const auto & seg : common_tts_norm_scan(text, ptrs)) {
+ auto groups = mk_val();
+ for (const auto & g : seg.groups) {
+ // groups that did not participate are empty strings, so they render as nothing and are falsy
+ groups->push_back(g.first == std::string::npos ? mk_str(0, 0) : mk_str(g.first, g.second));
+ }
+ auto obj = mk_val();
+ obj->insert("rule", seg.rule < 0 ? value(mk_val()) : value(mk_val(rule_srcs[seg.rule].first)));
+ obj->insert("text", mk_str(seg.start, seg.end));
+ obj->insert("groups", groups);
+ out->push_back(obj);
+ }
+ return out;
+}
+
+static value tts_norm_builtin_sub(const func_args & args) {
+ args.ensure_count(3, 3);
+ args.ensure_vals();
+ const string text_val = args.get_pos(0)->as_string();
+ const common_tts_norm_pattern pattern(args.get_pos(1)->as_string().str());
+ const std::string res = common_tts_norm_sub(text_val.str(), pattern, args.get_pos(2)->as_string().str());
+ return mk_val(string(res, text_val.all_parts_are_input()));
+}
+
+void common_chat_tts_norm_add_builtins(context & ctx) {
+ ctx.set_val("tts_norm_scan", mk_val("tts_norm_scan", tts_norm_builtin_scan));
+ ctx.set_val("tts_norm_sub", mk_val("tts_norm_sub", tts_norm_builtin_sub));
+}
+
diff --git a/common/chat-tts-norm.h b/common/chat-tts-norm.h
new file mode 100644
index 000000000000..14695bb52d99
--- /dev/null
+++ b/common/chat-tts-norm.h
@@ -0,0 +1,62 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+
+// TTS normalization patterns: a small, fully specified matching language for TTS text normalization templates
+//
+// it is NOT a regex engine: the semantics are defined by llama.cpp (see docs/tts-norm-patterns.md), so that this
+// implementation and the python reference (scripts/chat_tts_norm.py) give the same result for every input
+//
+// two functions are exposed to task templates (e.g. "tts") via common_chat_tts_norm_add_builtins():
+// tts_norm_scan(text, rules) -> list of segments {rule, text, groups}
+// tts_norm_sub(text, pattern, repl) -> string
+
+namespace jinja {
+struct context;
+}
+
+struct tts_norm_pattern_node;
+
+class common_tts_norm_pattern {
+public:
+ // throws std::runtime_error on invalid pattern
+ explicit common_tts_norm_pattern(const std::string & src);
+ ~common_tts_norm_pattern();
+ common_tts_norm_pattern(common_tts_norm_pattern &&) noexcept;
+ common_tts_norm_pattern & operator=(common_tts_norm_pattern &&) noexcept;
+
+ // match anchored at codepoint index pos; on success, end is the codepoint index after the match
+ // groups[i] holds [start, end) codepoint indices of capture i+1, or {-1, -1} if the group did not participate
+ bool match_at(const std::vector & cpts, size_t pos, size_t & end, std::vector> & groups) const;
+
+ size_t n_groups() const;
+
+private:
+ std::unique_ptr root;
+ size_t n_caps = 0;
+ bool icase = false;
+};
+
+// segment produced by common_tts_norm_scan(); byte offsets into the input text
+struct common_tts_norm_segment {
+ int rule = -1; // index of the matched rule, -1 for unmatched text
+ size_t start = 0;
+ size_t end = 0;
+ std::vector> groups; // byte offsets; {npos, npos} for groups that did not participate
+};
+
+// split text into matched and unmatched segments
+// at each position, rules are tried in order and the first non-empty match wins; otherwise one codepoint is skipped
+std::vector common_tts_norm_scan(const std::string & text, const std::vector & rules);
+
+// replace every non-overlapping match of pattern with repl
+// repl references: %0 (whole match), %1..%9 (groups), %% (literal percent)
+std::string common_tts_norm_sub(const std::string & text, const common_tts_norm_pattern & pattern, const std::string & repl);
+
+// add tts_norm_scan() and tts_norm_sub() to the context of a task template
+// they are not jinja global builtins on purpose: chat templates are not affected
+void common_chat_tts_norm_add_builtins(jinja::context & ctx);
diff --git a/common/chat.cpp b/common/chat.cpp
index ef9b853f022c..da29cd671d4c 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -3,6 +3,7 @@
#include "chat-auto-parser-helpers.h"
#include "chat-auto-parser.h"
#include "chat-peg-parser.h"
+#include "chat-tts-norm.h"
#include "common.h"
#include "ggml.h"
#include "json-schema-to-grammar.h"
@@ -807,6 +808,8 @@ bool common_chat_templates_was_explicit(const struct common_chat_templates * tmp
// renders a task template (e.g. "tts") with the given variables
static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars) {
jinja::context ctx(tmpl.source());
+ // text normalization helpers: tts_norm_scan() and tts_norm_sub(), see docs/tts-norm-patterns.md
+ common_chat_tts_norm_add_builtins(ctx);
jinja::global_from_json(ctx, vars, false);
ctx.set_val("bos_token", jinja::mk_val(tmpl.bos_token()));
ctx.set_val("eos_token", jinja::mk_val(tmpl.eos_token()));
@@ -1274,13 +1277,6 @@ static common_chat_params common_chat_params_init_lfm2_5(const common_chat_templ
return common_chat_params_init_lfm2(tmpl, inputs, /* tool_list_tokens = */ false);
}
-// Older gemma4 templates need their tool responses rewritten before rendering
-static common_chat_params common_chat_params_init_gemma4_legacy(const common_chat_template & tmpl, const autoparser::generation_params & inputs) {
- auto adjusted = inputs;
- workaround::convert_tool_responses_gemma4(adjusted.messages);
- return common_chat_params_init_gemma4(tmpl, adjusted);
-}
-
// Pick the dedicated handler for a template from its source, or null for the autoparser.
// Order matters: the first match wins, and later checks assume the earlier ones did not match.
static common_chat_params_init_fn common_chat_template_detect_params_init(const std::string & src) {
@@ -1415,11 +1411,6 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const
// Gemma4 format detection
if (src.find("'<|tool_call>call:'") != std::string::npos) {
LOG_DBG("Using specialized template: Gemma4\n");
- if (src.find("{#- OpenAI Chat Completions:") == std::string::npos) {
- LOG_WRN("%s: detected an outdated gemma4 chat template, applying compatibility workarounds. "
- "Consider updating to the official template.\n", __func__);
- return common_chat_params_init_gemma4_legacy;
- }
return common_chat_params_init_gemma4;
}
diff --git a/common/common.h b/common/common.h
index cc6eef833bb3..6043ab34239f 100644
--- a/common/common.h
+++ b/common/common.h
@@ -705,6 +705,7 @@ struct common_params {
// enable built-in tools
std::vector server_tools;
std::string server_tools_runtime;
+ bool server_tools_allow_unauth = false; // allow tools/MCP on a non-loopback address without API key
// MCP server configs (Cursor-compatible JSON)
std::string mcp_servers_config; // path to JSON file with MCP server definitions
@@ -722,6 +723,7 @@ struct common_params {
std::string slot_save_path;
std::string media_path; // path to directory for loading media files
+ bool media_allow_private_urls = false; // allow http(s) media URLs on local or private addresses
float slot_prompt_similarity = 0.1f;
@@ -1147,7 +1149,7 @@ struct common_batch {
// attach a state embedding (e.g. the target hidden state for MTP) to the entry at idx, can only be set once per entry
bool set_embd_state(int32_t idx, llama_embd state);
- // the state of entry idx is row `row` of the h_nextn device buffer of the state source context, see llama_set_embd_state_src()
+ // the state of entry idx is row `row` of the h_nextn device buffer of the state source context, see llama_set_ctx_state_src()
bool set_embd_state_row(int32_t idx, int32_t row);
// add an embedding-only entry (no token id)
diff --git a/common/download.cpp b/common/download.cpp
index fbd192721589..682fd6e3ef7a 100644
--- a/common/download.cpp
+++ b/common/download.cpp
@@ -461,38 +461,55 @@ static int common_download_file_single_online(const std::string & url,
return finish(success ? head->status : -1);
}
-std::pair> common_remote_get_content(const std::string & url,
+std::pair> common_remote_get_content(const std::string & url_in,
const common_remote_params & params) {
- auto [cli, parts] = common_http_client(url);
+ static constexpr int max_redirects = 5;
+ std::string url = url_in;
+ for (int n_redirects = 0; ; n_redirects++) {
+ auto [cli, parts] = common_http_client(url);
+
+ httplib::Headers headers;
+ for (const auto & h : params.headers) {
+ headers.emplace(h.first, h.second);
+ }
+ if (headers.find("User-Agent") == headers.end()) {
+ headers.emplace("User-Agent", "llama-cpp/" + std::string(llama_build_info()));
+ }
- httplib::Headers headers;
- for (const auto & h : params.headers) {
- headers.emplace(h.first, h.second);
- }
- if (headers.find("User-Agent") == headers.end()) {
- headers.emplace("User-Agent", "llama-cpp/" + std::string(llama_build_info()));
- }
+ if (params.timeout > 0) {
+ cli.set_read_timeout(params.timeout, 0);
+ cli.set_write_timeout(params.timeout, 0);
+ }
+ if (params.resolve_host) {
+ // pin checked address, follow redirects manually to check each hop
+ cli.set_direct_hostname_addr_map({{parts.host, params.resolve_host(parts.host)}});
+ cli.set_follow_location(false);
+ }
- if (params.timeout > 0) {
- cli.set_read_timeout(params.timeout, 0);
- cli.set_write_timeout(params.timeout, 0);
- }
+ std::vector buf;
+ auto res = cli.Get(parts.path, headers,
+ [&](const char *data, size_t len) {
+ buf.insert(buf.end(), data, data + len);
+ return params.max_size == 0 ||
+ buf.size() <= static_cast(params.max_size);
+ },
+ nullptr
+ );
+
+ if (!res) {
+ throw std::runtime_error("error: cannot make GET request");
+ }
- std::vector buf;
- auto res = cli.Get(parts.path, headers,
- [&](const char *data, size_t len) {
- buf.insert(buf.end(), data, data + len);
- return params.max_size == 0 ||
- buf.size() <= static_cast(params.max_size);
- },
- nullptr
- );
+ if (params.resolve_host && res->status >= 300 && res->status < 400 && res->has_header("Location")) {
+ if (n_redirects >= max_redirects) {
+ throw std::runtime_error("error: too many redirects");
+ }
+ url = common_http_resolve_location(url, res->get_header_value("Location"));
+ continue;
+ }
- if (!res) {
- throw std::runtime_error("error: cannot make GET request");
+ return { res->status, std::move(buf) };
}
-
- return { res->status, std::move(buf) };
}
int common_download_file_single(const std::string & url,
diff --git a/common/download.h b/common/download.h
index dd09d68eeff9..c0ff5da2f687 100644
--- a/common/download.h
+++ b/common/download.h
@@ -31,6 +31,8 @@ struct common_remote_params {
common_header_list headers;
long timeout = 0; // in seconds, 0 means no timeout
long max_size = 0; // unlimited if 0
+ // if set: called per hop (redirects too), returns the address to connect to, throws to refuse
+ std::function resolve_host;
};
// get remote file content, returns
diff --git a/common/http.h b/common/http.h
index 10d017f17ed5..d8cfde262019 100644
--- a/common/http.h
+++ b/common/http.h
@@ -99,6 +99,26 @@ static common_http_url common_http_parse_url(const std::string & url) {
return parts;
}
+// resolve a redirect Location against the URL it came from
+static std::string common_http_resolve_location(const std::string & base_url, const std::string & location) {
+ if (location.find("://") != std::string::npos) {
+ return location;
+ }
+ const common_http_url base = common_http_parse_url(base_url);
+ if (location.compare(0, 2, "//") == 0) {
+ return base.scheme + ":" + location;
+ }
+ const std::string origin = base.scheme + "://" + common_http_format_host(base.host) + ":" + std::to_string(base.port);
+ const std::string path = base.path.substr(0, base.path.find('?'));
+ if (!location.empty() && location[0] == '/') {
+ return origin + location;
+ }
+ if (!location.empty() && location[0] == '?') {
+ return origin + path + location;
+ }
+ return origin + path.substr(0, path.rfind('/') + 1) + location;
+}
+
// match a loopback destination: a remote proxy can never reach the client machine's own
// loopback, so these hosts are always contacted directly, before NO_PROXY is consulted
// (similar to Go's net/http)
diff --git a/common/jinja/lexer.h b/common/jinja/lexer.h
index 439c85764c24..3f4ebb62a8d5 100644
--- a/common/jinja/lexer.h
+++ b/common/jinja/lexer.h
@@ -37,6 +37,7 @@ struct token {
call_operator, // ()
additive_binary_operator, // + - ~
multiplicative_binary_operator, // * / %
+ power_operator, // **
comparison_binary_operator, // < > <= >= == !=
unary_operator, // ! - +
comment, // {# ... #}
@@ -71,6 +72,7 @@ static std::string type_to_string(token::type t) {
case token::call_operator: return "call_operator";
case token::additive_binary_operator: return "additive_binary_operator";
case token::multiplicative_binary_operator: return "multiplicative_binary_operator";
+ case token::power_operator: return "power_operator";
case token::comparison_binary_operator: return "comparison_binary_operator";
case token::unary_operator: return "unary_operator";
case token::comment: return "comment";
@@ -137,6 +139,7 @@ struct lexer {
{"+", token::additive_binary_operator},
{"-", token::additive_binary_operator},
{"~", token::additive_binary_operator},
+ {"**", token::power_operator},
{"*", token::multiplicative_binary_operator},
{"/", token::multiplicative_binary_operator},
{"%", token::multiplicative_binary_operator},
diff --git a/common/jinja/parser.cpp b/common/jinja/parser.cpp
index 7e99a1ac8fd0..0841828c454a 100644
--- a/common/jinja/parser.cpp
+++ b/common/jinja/parser.cpp
@@ -178,7 +178,7 @@ class parser {
// bool has_caller_args = false;
if (is(token::open_paren)) {
// Optional caller arguments, e.g. {% call(user) dump_users(...) %}
- caller_args = parse_args();
+ caller_args = parse_args(false);
// has_caller_args = true;
}
auto callee = parse_primary_expression();
@@ -283,7 +283,7 @@ class parser {
statement_ptr parse_macro_statement(size_t start_pos) {
auto name = parse_primary_expression();
- auto args = parse_args();
+ auto args = parse_args(false);
expect(token::close_statement, "Expected %}");
statements body;
// Keep going until we hit {% endmacro
@@ -397,11 +397,13 @@ class parser {
statement_ptr parse_comparison_expression() {
// NOTE: membership has same precedence as comparison
- // e.g., ('a' in 'apple' == 'b' in 'banana') evaluates as ('a' in ('apple' == ('b' in 'banana')))
- auto left = parse_additive_expression();
+ // e.g., ('a' in 'apple' == 'b' in 'banana') evaluates as ('a' in 'apple' and 'apple' == 'b' and 'b' in 'banana')
+ statements operands;
+ std::vector ops;
+ operands.push_back(parse_additive_expression());
+ size_t pos = current;
while (true) {
token op;
- size_t start_pos = current;
if (is_identifier("not") && peek(1).t == token::identifier && peek(1).value == "in") {
op = {token::identifier, "not in", tokens[current].pos};
++current; // consume 'not'
@@ -411,9 +413,17 @@ class parser {
} else if (is(token::comparison_binary_operator)) {
op = next();
} else break;
- left = mk_stmt(start_pos, op, std::move(left), parse_additive_expression());
+ ops.push_back(std::move(op));
+ operands.push_back(parse_additive_expression());
}
- return left;
+ if (ops.empty()) {
+ return std::move(operands[0]);
+ }
+ if (ops.size() == 1) {
+ return mk_stmt(pos, ops[0], std::move(operands[0]), std::move(operands[1]));
+ }
+ // chained comparison, e.g. 1 <= x <= 100
+ return mk_stmt(pos, std::move(operands), std::move(ops));
}
statement_ptr parse_additive_expression() {
@@ -500,17 +510,22 @@ class parser {
return parse_call_expression(std::move(member)); // foo.x()()
}
- statements parse_args() {
+ statements parse_args(bool allow_spread = true) {
// comma-separated arguments list
expect(token::open_paren, "Expected (");
statements args;
while (!is(token::close_paren)) {
statement_ptr arg;
- // unpacking: *expr
- if (peek().t == token::multiplicative_binary_operator && peek().value == "*") {
+ // unpacking: *expr or **expr
+ const auto & t = peek();
+ if (t.t == token::power_operator || (t.t == token::multiplicative_binary_operator && t.value == "*")) {
+ if (!allow_spread) {
+ throw std::runtime_error("Unexpected token: " + t.value + " of type " + std::to_string(t.t));
+ }
size_t start_pos = current;
- ++current; // consume *
- arg = mk_stmt(start_pos, parse_expression());
+ ++current; // consume * or **
+ bool is_kwargs = t.t == token::power_operator;
+ arg = mk_stmt(start_pos, parse_expression(), is_kwargs);
} else {
arg = parse_expression();
if (is(token::equals)) {
diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp
index d32c79fa5cb5..d60a99d2591e 100644
--- a/common/jinja/runtime.cpp
+++ b/common/jinja/runtime.cpp
@@ -117,20 +117,8 @@ value object_literal::execute_impl(context & ctx) const {
return obj;
}
-value binary_expression::execute_impl(context & ctx) const {
- value left_val = left->execute(ctx);
-
- // Logical operators
- if (op.value == "and") {
- JJ_DEBUG("Executing logical test: %s AND %s", left->type().c_str(), right->type().c_str());
- return left_val->as_bool() ? right->execute(ctx) : std::move(left_val);
- } else if (op.value == "or") {
- JJ_DEBUG("Executing logical test: %s OR %s", left->type().c_str(), right->type().c_str());
- return left_val->as_bool() ? std::move(left_val) : right->execute(ctx);
- }
-
+static value exec_binary_op(context & ctx, const token & op, value left_val, value right_val) {
// Equality operators
- value right_val = right->execute(ctx);
JJ_DEBUG("Executing binary expression %s '%s' %s", left_val->type().c_str(), op.value.c_str(), right_val->type().c_str());
if (op.value == "==") {
return mk_val(*left_val == *right_val);
@@ -307,6 +295,67 @@ value binary_expression::execute_impl(context & ctx) const {
throw std::runtime_error("Unknown operator \"" + op.value + "\" between " + left_val->type() + " and " + right_val->type());
}
+value binary_expression::execute_impl(context & ctx) const {
+ value left_val = left->execute(ctx);
+
+ // Logical operators
+ if (op.value == "and") {
+ JJ_DEBUG("Executing logical test: %s AND %s", left->type().c_str(), right->type().c_str());
+ return left_val->as_bool() ? right->execute(ctx) : std::move(left_val);
+ } else if (op.value == "or") {
+ JJ_DEBUG("Executing logical test: %s OR %s", left->type().c_str(), right->type().c_str());
+ return left_val->as_bool() ? std::move(left_val) : right->execute(ctx);
+ }
+
+ return exec_binary_op(ctx, op, std::move(left_val), right->execute(ctx));
+}
+
+value comparison_chain_expression::execute_impl(context & ctx) const {
+ value left_val = operands[0]->execute(ctx);
+ value res;
+ for (size_t i = 0; i < ops.size(); ++i) {
+ value right_val = operands[i + 1]->execute(ctx);
+ res = exec_binary_op(ctx, ops[i], left_val, right_val);
+ if (!res->as_bool()) {
+ break; // same as "and", the next operands are not executed
+ }
+ left_val = std::move(right_val);
+ }
+ return res;
+}
+
+static void exec_call_args(context & ctx, const statements & arg_stmts, func_args & args) {
+ for (const auto & arg_stmt : arg_stmts) {
+ if (!is_stmt(arg_stmt)) {
+ auto arg_val = arg_stmt->execute(ctx);
+ JJ_DEBUG(" Argument type: %s", arg_val->type().c_str());
+ args.push_back(arg_val);
+ continue;
+ }
+ auto spread = cast_stmt(arg_stmt);
+ value val = spread->argument->execute(ctx);
+ JJ_DEBUG(" Unpacked argument type: %s", val->type().c_str());
+ if (spread->is_kwargs) {
+ if (!is_val(val)) {
+ throw std::runtime_error("Argument after ** must be an object, got " + val->type());
+ }
+ for (const auto & pair : val->as_ordered_object()) {
+ if (!is_val(pair.first)) {
+ throw std::runtime_error("Keyword argument key must be a string, got " + pair.first->type());
+ }
+ args.push_back(mk_val(pair.first->as_string().str(), pair.second));
+ }
+ } else {
+ if (!is_val(val)) {
+ throw std::runtime_error("Argument after * must be an array, got " + val->type());
+ }
+ for (const auto & item : val->as_array()) {
+ args.push_back(item);
+ }
+ }
+ }
+}
+
static value apply_filter(context & ctx, const statement_ptr & filter, value input) {
JJ_DEBUG("Applying filter to %s", input->type().c_str());
@@ -324,9 +373,7 @@ static value apply_filter(context & ctx, const statement_ptr & filter, value inp
JJ_DEBUG("Applying filter '%s' with arguments to %s", filter_id.c_str(), input->type().c_str());
func_args args(ctx);
- for (const auto & arg_expr : call->args) {
- args.push_back(arg_expr->execute(ctx));
- }
+ exec_call_args(ctx, call->args, args);
return apply_filter_by_name(ctx, filter_id, input, args);
@@ -369,9 +416,7 @@ value test_expression::execute_impl(context & ctx) const {
test_id = cast_stmt(call->callee)->val;
JJ_DEBUG("Applying test '%s' with arguments to %s", test_id.c_str(), input->type().c_str());
- for (const auto & arg_expr : call->args) {
- args.push_back(arg_expr->execute(ctx));
- }
+ exec_call_args(ctx, call->args, args);
} else {
throw std::runtime_error("Invalid test expression");
@@ -762,12 +807,7 @@ value call_statement::execute_impl(context & ctx) const {
call_ctx.set_val("caller", mk_val("caller", func));
func_args args(call_ctx);
-
- for (const auto & arg_expr : call_expr->args) {
- auto arg_val = arg_expr->execute(ctx);
- JJ_DEBUG(" Argument type: %s", arg_val->type().c_str());
- args.push_back(arg_val);
- }
+ exec_call_args(ctx, call_expr->args, args);
JJ_DEBUG("Calling macro '%s' with %zu arguments", callee_func->name.c_str(), args.count());
return callee_func->invoke(args);
@@ -907,11 +947,7 @@ value member_expression::execute_impl(context & ctx) const {
value call_expression::execute_impl(context & ctx) const {
// gather arguments
func_args args(ctx);
- for (auto & arg_stmt : this->args) {
- auto arg_val = arg_stmt->execute(ctx);
- JJ_DEBUG(" Argument type: %s", arg_val->type().c_str());
- args.push_back(arg_val);
- }
+ exec_call_args(ctx, this->args, args);
// execute callee
value callee_val = callee->execute(ctx);
if (!is_val(callee_val)) {
diff --git a/common/jinja/runtime.h b/common/jinja/runtime.h
index 101e927c4b7f..43e1085516da 100644
--- a/common/jinja/runtime.h
+++ b/common/jinja/runtime.h
@@ -471,6 +471,28 @@ struct binary_expression : public expression {
}
};
+/**
+ * Two or more comparisons in a row, e.g. `a < b <= c`
+ * It is the same as `a < b and b <= c`, but each operand is executed only one time.
+ */
+struct comparison_chain_expression : public expression {
+ statements operands;
+ std::vector ops;
+
+ comparison_chain_expression(statements && operands, std::vector && ops)
+ : operands(std::move(operands)), ops(std::move(ops)) {
+ assert(this->operands.size() == this->ops.size() + 1);
+ for (const auto & operand : this->operands) chk_type(operand);
+ }
+ std::string type() const override { return "ComparisonChainExpression"; }
+ value execute_impl(context & ctx) const override;
+ void visit(context & ctx) const override {
+ ctx.visitor(false, this, {
+ {"operands", stmts_to_ptr(operands)}
+ });
+ }
+};
+
/**
* An operation with two sides, separated by the | operator.
* Operator precedence: https://github.com/pallets/jinja/issues/379#issuecomment-168076202
@@ -633,7 +655,9 @@ struct keyword_argument_expression : public expression {
struct spread_expression : public expression {
statement_ptr argument;
- explicit spread_expression(statement_ptr && argument) : argument(std::move(argument)) {
+ bool is_kwargs;
+ spread_expression(statement_ptr && argument, bool is_kwargs)
+ : argument(std::move(argument)), is_kwargs(is_kwargs) {
chk_type(this->argument);
}
std::string type() const override { return "SpreadExpression"; }
diff --git a/common/json-schema.h b/common/json-schema.h
index 084208c96201..b203e7777aa8 100644
--- a/common/json-schema.h
+++ b/common/json-schema.h
@@ -85,92 +85,124 @@ struct common_chat_schema {
static const char * kind_name(node_kind kind);
static const char * type_name(value_type type);
+
+ template
+ const T & as() const {
+ GGML_ASSERT(kind() == T::KIND);
+ return static_cast(*this);
+ }
};
using common_chat_schema_ptr = std::unique_ptr;
struct common_chat_schema_any : common_chat_schema {
- node_kind kind() const override { return KIND_ANY; }
+ static constexpr node_kind KIND = KIND_ANY;
+
+ node_kind kind() const override { return KIND; }
};
// {"$ref": "#/..."}, only references into the same document are supported
struct common_chat_schema_ref : common_chat_schema {
+ static constexpr node_kind KIND = KIND_REF;
+
std::string ref;
const common_chat_schema * target = nullptr; // owned by common_chat_schema_document::refs
explicit common_chat_schema_ref(std::string ref) : ref(std::move(ref)) {}
- node_kind kind() const override { return KIND_REF; }
+ node_kind kind() const override { return KIND; }
};
// oneOf / anyOf, or a "type" array expanded to one alternative per type
struct common_chat_schema_any_of : common_chat_schema {
+ static constexpr node_kind KIND = KIND_ANY_OF;
+
std::vector children;
- node_kind kind() const override { return KIND_ANY_OF; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_all_of : common_chat_schema {
+ static constexpr node_kind KIND = KIND_ALL_OF;
+
std::vector children;
- node_kind kind() const override { return KIND_ALL_OF; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_const : common_chat_schema {
+ static constexpr node_kind KIND = KIND_CONST;
+
common_json value;
explicit common_chat_schema_const(common_json value) : value(std::move(value)) {}
- node_kind kind() const override { return KIND_CONST; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_enum : common_chat_schema {
+ static constexpr node_kind KIND = KIND_ENUM;
+
std::vector values;
- node_kind kind() const override { return KIND_ENUM; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_null : common_chat_schema {
- node_kind kind() const override { return KIND_NULL; }
+ static constexpr node_kind KIND = KIND_NULL;
+
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_boolean : common_chat_schema {
- node_kind kind() const override { return KIND_BOOLEAN; }
+ static constexpr node_kind KIND = KIND_BOOLEAN;
+
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_number : common_chat_schema {
- node_kind kind() const override { return KIND_NUMBER; }
+ static constexpr node_kind KIND = KIND_NUMBER;
+
+ node_kind kind() const override { return KIND; }
};
// bounds are inclusive, exclusiveMinimum / exclusiveMaximum are folded in
struct common_chat_schema_integer : common_chat_schema {
+ static constexpr node_kind KIND = KIND_INTEGER;
+
int64_t minimum = INT64_MIN; // INT64_MIN for unbounded
int64_t maximum = INT64_MAX; // INT64_MAX for unbounded
- node_kind kind() const override { return KIND_INTEGER; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_string : common_chat_schema {
+ static constexpr node_kind KIND = KIND_STRING;
+
std::string pattern; // empty when absent
string_format format = FORMAT_NONE;
int min_length = 0;
int max_length = -1; // -1 for unbounded
- node_kind kind() const override { return KIND_STRING; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_array : common_chat_schema {
+ static constexpr node_kind KIND = KIND_ARRAY;
+
common_chat_schema_ptr items; // a common_chat_schema_any when "items" is absent
int min_items = 0;
int max_items = -1; // -1 for unbounded
- node_kind kind() const override { return KIND_ARRAY; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_tuple : common_chat_schema {
+ static constexpr node_kind KIND = KIND_TUPLE;
+
std::vector items;
- node_kind kind() const override { return KIND_TUPLE; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_property {
@@ -180,10 +212,12 @@ struct common_chat_schema_property {
};
struct common_chat_schema_object : common_chat_schema {
+ static constexpr node_kind KIND = KIND_OBJECT;
+
std::vector properties; // in schema order
common_chat_schema_ptr additional_properties; // null when not allowed
- node_kind kind() const override { return KIND_OBJECT; }
+ node_kind kind() const override { return KIND; }
};
struct common_chat_schema_document {
diff --git a/common/parsers/gemma4.cpp b/common/parsers/gemma4.cpp
index 1a63fa927c40..5902e290bbc6 100644
--- a/common/parsers/gemma4.cpp
+++ b/common/parsers/gemma4.cpp
@@ -1,152 +1,284 @@
#include "parsers.h"
-namespace workaround {
-
-// Gemma4 uses a custom tool_responses field instead of role:tool messages.
-//
-// This will transform a sequence of messages:
-// assistant(tool_call+) -> tool+ -> assistant(content)
-//
-// Into a single assistant message containing a tool_responses field:
-// assistant(content + tool_call + tool_responses)
-//
-// This is necessary for the Gemma4 chat template to properly format the prompt.
-// See https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4
-struct gemma4_model_turn_builder {
- json & messages;
- size_t pos;
- json tool_calls = json::array();
- json tool_responses = json::array();
- json content;
- json reasoning_content;
-
- gemma4_model_turn_builder(json & msgs, size_t pos) : messages(msgs), pos(pos) {}
-
- void collect() {
- // Collect the first assistant message
- auto & msg = messages[pos];
- if (msg.contains("reasoning_content") && msg.at("reasoning_content").is_string()) {
- // According to the prompt formatting guide, we need to preserve reasoning_content
- // between function calls. The current chat templates do not support this, but we will do it anyway.
- reasoning_content = msg.at("reasoning_content");
- }
- for (auto & tc : msg.at("tool_calls")) {
- tool_calls.push_back(tc);
- }
- pos++;
+#include "log.h"
+
+#include
+#include
+#include