radiance 2.0.0

Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
Deadcode committed 2026-11-14 22:32:28 +01:00
1 parent b4c04b6042
commit ddcb9c69bb
696 files changed
+120770 -56596

No files matched your search

+21 -2
View File
@@ -29,6 +29,10 @@ add_library(rad_vendor_llama STATIC
llama/common/regex-partial.cpp
shim/llama_shim.cpp)
target_compile_options(rad_vendor_llama PRIVATE -w)
# The chat lift's JSON DOM is ours (core/util/json.h) since the DOM swap; its
# translation units include it by that path and link the same small library core does.
target_include_directories(rad_vendor_llama PRIVATE ${CMAKE_SOURCE_DIR}/core)
target_link_libraries(rad_vendor_llama PUBLIC rad_json)
# SYSTEM, so vendored headers included by our sources do not warn either (`-w` covers only the
# vendor's own translation units).
target_include_directories(rad_vendor_llama SYSTEM PUBLIC
@@ -62,12 +66,27 @@ target_compile_definitions(rad_vendor_httplib PUBLIC
# hundred milliseconds a message; a larger message closes the connection.
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH=2097152)
# rapidyaml 0.16.0 ships as one amalgamated header; shim/ryml_impl.cpp compiles its implementation
# once. The include directory is SYSTEM so the header does not warn in our translation units. The
# YAML configuration reader (core/fleet/config.cpp) is its only user.
add_library(rad_vendor_ryml STATIC shim/ryml_impl.cpp)
target_compile_options(rad_vendor_ryml PRIVATE -w)
target_include_directories(rad_vendor_ryml SYSTEM PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/rapidyaml)
# yyjson: the reader inside the tree's JSON DOM (core/util/json.cpp converts its tree into
# rad::Json, the DOM everything downstream consumes). One C file; the header rides on
# rad_vendor_yyjson's include path (<yyjson/yyjson.h>).
add_library(rad_vendor_yyjson STATIC yyjson/yyjson.c)
target_compile_options(rad_vendor_yyjson PRIVATE -w)
target_include_directories(rad_vendor_yyjson SYSTEM PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
# ---------------------------------------------------------------- the public face
# Header-only vendors need only a path:
# <nlohmann/json.hpp> vendor/nlohmann/json.hpp
# <cpp-httplib/httplib.h> vendor/cpp-httplib/httplib.h (or plain "httplib.h")
# "llama/src/unicode.h" the tokeniser's codepoint tables
# "llama/common/jinja/*.h" the jinja engine
# <ryml.hpp> vendor/rapidyaml/ryml.hpp
add_library(rad_vendor INTERFACE)
target_include_directories(rad_vendor INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(rad_vendor INTERFACE rad_vendor_llama rad_vendor_httplib)
target_link_libraries(rad_vendor INTERFACE rad_vendor_llama rad_vendor_httplib rad_vendor_ryml
rad_vendor_yyjson)
+31 -48
View File
@@ -1,36 +1,36 @@
fa7f402b6441af6f1b6fd819c793f9148a5a8df69b6f49eef9a82f76916e23c7 vendor/CMakeLists.txt
a01f72edb9d0a7e9da75c5648cf62ae6f1c335afbfc150088a129288072dc32b vendor/CMakeLists.txt
d6f9a0fe461e2f7c0b051e39d7979c53e8b14884f87377e3b616a339d481fee9 vendor/cpp-httplib/httplib.cpp
d7168fd3d9266985c01e827c7a7cc002c0b0a0abcc8ff16d965ccbbaca3e4a2d vendor/cpp-httplib/httplib.h
4b45cbe16d7b71b89ae6127e26e0d90a029198ca5e958ad8e3d0b8bbed364d8b vendor/cpp-httplib/LICENSE
4491c18fe222d5d486ddf770efbf280b108caa1e680ed799661120a1f1a240e6 vendor/llama/common/chat-auto-parser-generator.cpp
eaac4504c9c36e4c6452158eb05b19423ec80a274f442368198cdbc51e5a05f5 vendor/llama/common/chat-auto-parser.h
e1d5ce28501aa564fdd49103b13dd61a43c84d11e37517b4d216f029b17ec595 vendor/llama/common/chat-auto-parser-helpers.cpp
f5a25d5d70073fe26494962e0b4f300565511f0028f8b1548f1a0c6c531bfc6d vendor/llama/common/chat-auto-parser-generator.cpp
eb93af41e2ec50e62880af5da55f68bee83e00c5a6a4896e77cb9d3f8a970b20 vendor/llama/common/chat-auto-parser.h
4d09ee4cc08e491b080952fdc2b5958003122d8e51454149841f031c40add995 vendor/llama/common/chat-auto-parser-helpers.cpp
a2866e5411ab5c23171db7214fa9aa60171b52ed4737bd37ce66f828d8683998 vendor/llama/common/chat-auto-parser-helpers.h
226e4ae215224020529e30c8f829b23839a7bd4f8aaef9aac909ffbdcbb6782b vendor/llama/common/chat.cpp
6667d0ea6cd0a73655d780cdf9ac4e41b866a1bf1abdc625ae8adcb5704d2cf6 vendor/llama/common/chat-diff-analyzer.cpp
a6c718f2f332ea0d9d9a3b0b671bb120ec9942535009794ed11d354bae79a257 vendor/llama/common/chat.h
eabe9f3c52e0585e2536d868487300badb0481a2e2e35bb5019741581c720f29 vendor/llama/common/chat-peg-parser.cpp
601ece524b39716bf8da2f4bc91f796cd3ee159ad40878acac365f32518cb1c7 vendor/llama/common/chat-peg-parser.h
b8b7d61bd4d89f816b053317f387f4483d9bff79c3b822758aa33d7af5c82b05 vendor/llama/common/jinja/caps.cpp
a0a79b4c22f4e73cca9eeeb89b093bd31387c5548086201c419e13df7db1bb69 vendor/llama/common/jinja/caps.h
0671967b8d7339df2690bdc64ab4044fd95b99da71d56158b8b993b494e48a8d vendor/llama/common/chat.cpp
15dc12c1211f57289ab904f068c3232a4f8e70d0b0f77f082be645f15d018b93 vendor/llama/common/chat-diff-analyzer.cpp
999bfbdbf4f193ccfa82193036893e57088e1767c84f26352a8b0805b32b5992 vendor/llama/common/chat.h
d69538a573f3490faa11f7c429ab6dac10305b903b41e957820a6acf82c5314b vendor/llama/common/chat-peg-parser.cpp
51b151ef2798c89e222188d60accaf2ef2dd7f29a01cd837fdecc92e9e757728 vendor/llama/common/chat-peg-parser.h
bb12b9cc7940d6728304b6ae1d0d9c53637098f6df00119d4ba5ef7f186c385e vendor/llama/common/jinja/caps.cpp
97866824d4dacfdeeb14839183e959d665ac766e12014f38e74610933a8b9cdc vendor/llama/common/jinja/caps.h
3d6774bc2dac477e10ddbee69eff403df36f5925c8512ccf8a249bde5c26dbd7 vendor/llama/common/jinja/lexer.cpp
93aecd72cc952fab08f657aa2a70e9f58421672b19d3179f8bdf555e683a1cc7 vendor/llama/common/jinja/lexer.h
284c3dcc92cfcbdb3391f4b251bdc2bd5191899973bf665e9351aca3b795c724 vendor/llama/common/jinja/parser.cpp
6225eb759da910f3dd7753aed71c6938131cfa04c609d744e6f1390396422316 vendor/llama/common/jinja/parser.h
345767ad59a6e193751e57d5b46d7c3bcdfa761c337aa4e2c94f0c06328e9361 vendor/llama/common/jinja/README.md
d2fe5e4198608320ae362b3611499e6c0900df007e626dfe19d96831bc3c1225 vendor/llama/common/jinja/runtime.cpp
7f1fe4751aef4f8eea1fd7957ad61f267e9796f376c1f72f986cd01c0184594e vendor/llama/common/jinja/runtime.h
baf915bfb220f54fb1238e8b6b634c69221577691ed18f9c3190e8c5d832fa5b vendor/llama/common/jinja/string.cpp
4cbff76daf9c9e23da83310cf1b667b710777f074598277222e4650e055c8bd7 vendor/llama/common/jinja/string.h
e3bfa255e10e81c756e1376740d752d6f73762233253f830dea2bcedd50f247f vendor/llama/common/jinja/README.md
dee35610e7de346501f49a0f62bb9c99f9dc10534a22c0ee20baabf11fc61ca3 vendor/llama/common/jinja/runtime.cpp
427e1a8471394674b56c24c1946393b6c242481ffa49f3af396e6b257634a645 vendor/llama/common/jinja/runtime.h
1f7b1d6161c48a735853608849781736b69e526bf31549fc2cb692469f193715 vendor/llama/common/jinja/string.cpp
943ad34975e87c1a39570ac45238e2416cfb99530b53d853547c630198ea4b18 vendor/llama/common/jinja/string.h
61ae8bc57a7a551bdfb294a23a0ef8b5ba8e3cf4d695389f0f0797e2d7689781 vendor/llama/common/jinja/utils.h
c70e50c139322abcb5800e5bf72aa16a708605fa93799d1fe9f46cc0309071cd vendor/llama/common/jinja/value.cpp
1690f51b5948e72270016a2e087c56b572dcd925db2f15ab3264f606ce650b3c vendor/llama/common/jinja/value.h
9b39cf1464f856dfd7c7e49ede93c6b10c8387ee06ce76f69bdd54cfee3fc526 vendor/llama/common/json-partial.cpp
938863feab004b56ce8530393a98dffc838cd958847e39eaec42b246739eb934 vendor/llama/common/json-partial.h
32b036b2ce62886cc2e5705a6fd5d7345278b9e1cf938c0ed7362a337f1020ae vendor/llama/common/json-schema-to-grammar.cpp
6030771287c82eced7ea225033e61ccf2836195c3146e34041a6cd507719ab80 vendor/llama/common/json-schema-to-grammar.h
01900c427f10f9fa50650acb25a80e4abc6077637a6332aafa1d67935a4ab27a vendor/llama/common/peg-parser.cpp
be6572602d0795e545ae5bf8c4871663c7d2acb7105234d80b0e2e72658e05e8 vendor/llama/common/peg-parser.h
9de5a424bc1339427800c3a22b708badd534bba2099ea35676a7e759a2a2cdb9 vendor/llama/common/jinja/value.cpp
fe5bb39af419fffc5291796848edc9f6d990c416ea8ff5fe602b9e4b8dd4140b vendor/llama/common/jinja/value.h
00a6eb892deb9c0578fec97e72b8dbb2518216bb325a972987691b67a14ecc02 vendor/llama/common/json-partial.cpp
1ff33e25293b376c9262c5e5842fcb50ebcf8f4e5c5222505a8a757be53fd4a5 vendor/llama/common/json-partial.h
a8743199b372fc75feb74b6441fbe860227751b0c379860f06a57e82953769bf vendor/llama/common/json-schema-to-grammar.cpp
e2e2d20d39e57ecf3c440df04097be4c6b3d59ba09f0655f675384d1c99f6801 vendor/llama/common/json-schema-to-grammar.h
d4b2739e4b06668dc14a1d3c6ed15c4fcb93d5c6e976f06bc3363e797fff9c1c vendor/llama/common/peg-parser.cpp
4e77267b71d77a5a5617d89a1cfb1e7b43df0af52e6ba38f305abfdf9f443464 vendor/llama/common/peg-parser.h
40f1cd28206abfd16e8ec9716d08f1455b74e55cbfef1d581fce08b7984775f8 vendor/llama/common/regex-partial.cpp
c4198e922a2a889668e3e03fabfc7d2ab0ae7d54b324bbda490831d8f8d5748d vendor/llama/common/regex-partial.h
a07137a4fe6a657acf0d4b16ee5fa4ba388f7e9c8d3c98993410b28720b69b6d vendor/llama/common/unicode.cpp
@@ -40,34 +40,17 @@ b88c29194f028c27988c05a64bd72948ff55081dc1b07e5ff9c3bb72601c62b5 vendor/llama/c
95170cd1c105a5b41a1b2dce73b0fae8ce8011ef7897600828bb2babe8b26e5d vendor/llama/src/unicode-data.cpp
1854f4494e5666db6036f0bf4cf818e01588b40b48a89e3372e775c4d5174402 vendor/llama/src/unicode-data.h
f1562388d5b9d2dac1152ad8eda56e0bcae25dd407cf15d9dd2e96fe0124f4e7 vendor/llama/src/unicode.h
fb6aa70cbece087f37ab4685c182b287c53be54f785f981b9db9d30d2d028b37 vendor/nlohmann/json_fwd.hpp
aaf127c04cb31c406e5b04a63f1ae89369fccde6d8fa7cdda1ed4f32dfc5de63 vendor/nlohmann/json.hpp
46a65cffd1ea955132d95a8dd921640714a8d6b537d2e4e482d31145ae95b603 vendor/nlohmann/LICENSE.MIT
e9115a6b8ba3388b271beb76c06a5d322305957650e0898a7bc83d12a169bb1e vendor/patches/0001-unicode-reject-codepoints-above-U-10FFFF.patch
eba995aa49294e3e5a9f2133abcb73b9287e2f043133a4b324c94ce1942d8ae2 vendor/patches/0002-chat-unclosed-reasoning-must-not-swallow-a-tool-call.patch
242c9bd080552bb0faf36983712e852909f1543b806834a08462ee8ce4b2381b vendor/patches/0003-json-schema-pattern-must-not-hang-or-index-empty.patch
61af2caa76bed5322ea2668a49d9b89d6e5ab97b07acf302de7b29569bda4ce8 vendor/patches/0004-json-schema-refuse-what-it-cannot-enforce.patch
38991cf830781feeee2a0bfee7b6cf04a1515f27308e7d1bc4ec7a06a1e59e74 vendor/patches/0005-chat-an-xml-argument-value-owns-its-indentation.patch
1287289401a9a13d8de4d35d6c58c9c0ce420e53b617935800c7bd2ade8c928a vendor/patches/0006-jinja-min-and-max-over-a-sequence.patch
7495ca4835bf26e2c4a8682a28e4257aa0d83c265a73abaf9c92b34ff127e83f vendor/patches/0007-autoparser-split-the-per-argument-suffix-from-the-call-close.patch
a8a55507fff3ac3ad615e681439c5cdfdbec0008612a6f3023672488b1b6685e vendor/patches/0008-autoparser-tagged-calls-separate-on-space-and-named-args-in-any-order.patch
f6570067a3ad2f88e27b863ff712b1e6b521af003d1109bc069aef377fc98741 vendor/patches/0009-chat-a-cdata-section-is-punctuation-not-content.patch
40bbf124e3cf04a11a67689c8a856b2a375355c1514cb5d10fd22b9ce2b8e130 vendor/patches/0010-autoparser-an-undeclared-argument-must-not-lose-the-call.patch
ced5c703b83d611adf679d04d2e55096ec6b23324801ed61909569161e274eb5 vendor/patches/0011-chat-add_bos-must-come-from-the-inputs.patch
86ab83f452e9a7e1d0eab9c9fc9bd45286222bea496b9bc6807f450b737073a3 vendor/patches/0012-json-schema-a-schema-no-value-satisfies.patch
73d43aca338a7e95cac2c6bc4cfd92ff1aee189d8f91216240a5eb0382b17f50 vendor/patches/0013-json-schema-a-count-past-int-is-no-bound.patch
deec83cf499003c57079788146c90c5daf7f890450a5f5fbc9464c0173f45041 vendor/patches/0014-json-schema-a-not-of-every-type-is-never.patch
cc3a01794f96cbd4b220d7fca7af71caf4f92292aceedf5a75e0db200a57e6c3 vendor/patches/0015-jinja-print-a-list-or-a-dict-as-its-repr.patch
b65f151faa7b7d2352e912abef7a1481612b886850ca9ab0c300c6699cae5311 vendor/patches/0016-chat-analyse-a-template-once.patch
e9ba1c95b3b282e603e1522771e102e1ab4dc53a014f0b63a8fd1b05a6d94bd8 vendor/patches/0017-json-schema-a-pattern-without-anchors-searches.patch
38ad0dba18ea563aad64ebee37d0d334fbd672a4abdef5aff9feb249c74dd436 vendor/patches/0018-json-schema-shorthand-classes-are-written-out.patch
b6c8d0d83f9be852f232cb006cf1a8475e10def6e609d0ebfba9162342016e6b vendor/patches/0019-json-schema-identity-escapes-of-punctuation.patch
e089be9c985d0ada3451d8abf211c6d11a9ca280eee67c2d968979bcd592460c vendor/patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch
ce99a693521103110c6ff99cad447664083e2c1872127a4ba9984ff5bc641aac vendor/patches/0021-jinja-a-dotted-integer-is-an-index.patch
f8b105c8e5032ab557e3d24632d7c07938383b3d183ce8dd0fe9051b5ea1e4b9 vendor/patches/0022-httplib-the-drain-keeps-a-five-second-budget.patch
d21acdde3276a3706f41c0a7e911a3953ac1ca6b33c5ae05f92d6651f77ce627 vendor/rapidyaml/LICENSE.txt
0d0b8076174cf62f034406b03529fda542ebc9a17506d3bd6d949aedc4bfa6ab vendor/rapidyaml/ryml.hpp
2970cf5b064edfd93581f0f1e027cff69ab328a60bb8ab23eaeb4854c841a412 vendor/shim/common.h
699953eab99abd173ee2b3b16f540b3c72dff103dbe92f1ac733bc9e26a798e7 vendor/shim/ggml.h
d5104362705e687271807f499481db6033d85988e13fac12f36e370c6fce0551 vendor/shim/llama.h
5d556a22069133f7931850a13094d7390ba091051f0dc98cb1cfca824142a705 vendor/shim/llama_shim.cpp
628efd8a88524082c4736d3bc52790aa459b40728f213246c54550011f2754a2 vendor/shim/log.h
d499ac92806108afa43c8bec88d57d747b8a05df663b4fbd55ebbe531f9519e4 vendor/UPSTREAM
1c343ff2dbf801873acc2ee67c0e874137fb36df31421f36fc5cb6812463aae4 vendor/shim/ryml_impl.cpp
c06f36e9ccb21458ed37af649e00b143f7bc773e0c7623d4f19f49c7a15ecfe5 vendor/UPSTREAM
45e384d3d52c73cba3a64d6e6c25d47cd738cd8a55c30629e3201046eda62947 vendor/yyjson/LICENSE
d2d58ef0a3b2267862dc363832c4f3185fd375aea933d5d3419d1a940d6ece2e vendor/yyjson/yyjson.c
ef803cda5c06b8962face6dfa39c3284b3bcf3e73f4d7317664690cc779679ca vendor/yyjson/yyjson.h
+90 -39
View File
@@ -7,6 +7,16 @@ patch was REWRITTEN into core/ under our own name instead, so this directory sta
The bottom half of this file is the list of things that went the other way, and why -- that list
is as much a part of the record as the lifts are.
One exception, taken deliberately: the chat lift (common/chat*, the auto-parser, jinja/ and
json-schema-to-grammar) is maintained directly in place. Its former patch series (0002-0021)
was verified applied -- the whole stack reverses cleanly on a copy of the tree it was removed
from, and on the directly edited tree only context lines of 0012 and 0015 have moved -- and the
patch files were then removed: the code itself is the change, the PATCH SERIES notes at the
bottom keep the rationale for each former patch by its old name, and the diffs are in git
history at 008eed4f, the last commit that has vendor/patches/0002-0021. Later changes -- the
render-path work that cut a chat request from three template renders to two and made the
Jinja string machinery move instead of copy -- are likewise direct edits. A refresh of those files is therefore a manual port, not a re-copy and re-apply.
The mechanical half of the promise is vendor/SHA256SUMS: every file under this directory -- lifts,
patch series, this record -- hashed, recomputed by tests/vendor_sums.sh (ctest: vendor_sums). A
file that differs, or arrived unrecorded, fails the suite: an unrecorded change to a lifted
@@ -23,10 +33,11 @@ UPSTREAM
("tests : add support for qwen3 SSM archs (#24031)")
MIT.
To refresh: check out the new upstream commit, re-copy the files listed below to the same paths,
re-apply patches/*.patch with `patch -p1` from vendor/llama/, and update the commit above. Paths
under vendor/llama/ mirror the upstream tree exactly so a patch generated with `git diff` in
llama.cpp applies here unchanged.
To refresh the lifts still under the rule: check out the new upstream commit, re-copy the files
listed below to the same paths, re-apply patches/*.patch with `patch -p1` from vendor/llama/,
and update the commit above. Paths under vendor/llama/ mirror the upstream tree exactly so a
patch generated with `git diff` in llama.cpp applies here unchanged. The chat lift is the
exception above: do not re-copy it; port by hand.
LIFTED FILES
@@ -68,11 +79,20 @@ vendor/llama/common/jinja/ <- llama.cpp common/jinja/
utils.h README.md
The Jinja engine and the template capability probe (spec §12: 5.0k + 0.5k lines). It depends
on nlohmann/json and common/unicode.h and on nothing else in llama.cpp -- no ggml, no
llama.h, no common.h -- which is why it lifts cleanly and chat.cpp did not.
on the tree's JSON DOM (core/util/json.h; nlohmann/json when lifted) and common/unicode.h
and on nothing else in llama.cpp -- no ggml, no llama.h, no common.h -- which is why it
lifts cleanly and chat.cpp did not.
LOCAL CHANGES: patches/0015-jinja-print-a-list-or-a-dict-as-its-repr.patch
patches/0021-jinja-a-dotted-integer-is-an-index.patch
LOCAL CHANGES: maintained directly (see the chat exception at the top of this file). The
former patches 0006 (min/max over a sequence), 0015 (print a list or dict
as its repr) and 0021 (a dotted integer is an index), `unique` over a sequence
with jinja2's semantics (upstream's is a stub that throws, which the capability
probe reports as a template without tool support: GLM-5.3-Flash's), the probe's
first exception under tools kept (caps::probe_error,
common_chat_templates_get_probe_error), then the string/render
hot paths: parts are moved instead of copied through the gather, appends no
longer return a copy, the parts join is one compaction pass, the flat render
is gathered without a parts list, and loop/member lookups stop rehashing.
vendor/llama/common/chat.{h,cpp}
vendor/llama/common/chat-auto-parser.h
@@ -97,23 +117,17 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/*
files in core/ that include any of these, which keeps a vendor refresh from rippling into the
server.
LOCAL CHANGES: patches/0002-chat-unclosed-reasoning-must-not-swallow-a-tool-call.patch
patches/0003-json-schema-pattern-must-not-hang-or-index-empty.patch
patches/0004-json-schema-refuse-what-it-cannot-enforce.patch
patches/0005-chat-an-xml-argument-value-owns-its-indentation.patch
patches/0006-jinja-min-and-max-over-a-sequence.patch
patches/0007-autoparser-split-the-per-argument-suffix-from-the-call-close.patch
patches/0008-autoparser-tagged-calls-separate-on-space-and-named-args-in-any-order.patch
patches/0009-chat-a-cdata-section-is-punctuation-not-content.patch
patches/0011-chat-add_bos-must-come-from-the-inputs.patch
patches/0012-json-schema-a-schema-no-value-satisfies.patch
patches/0013-json-schema-a-count-past-int-is-no-bound.patch
patches/0014-json-schema-a-not-of-every-type-is-never.patch
patches/0016-chat-analyse-a-template-once.patch
patches/0017-json-schema-a-pattern-without-anchors-searches.patch
patches/0018-json-schema-shorthand-classes-are-written-out.patch
patches/0019-json-schema-identity-escapes-of-punctuation.patch
patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch
LOCAL CHANGES: maintained directly (see the chat exception at the top of this file). The
former patches 0002-0005 and 0007-0020 (listed with their rationale under
PATCH SERIES below), then in place: the generation-prompt render reuse and
the dropped message_spans computation. The
whole lift's JSON type is now the tree's own DOM (core/util/json.h,
rad::Json) where upstream spells nlohmann::ordered_json (and
nlohmann::json in peg-parser's to_json/save, whose text now keeps
insertion order instead of sorting keys), and
json-partial.cpp's error locator is a small structural scanner where
upstream drives nlohmann's SAX interface; a refresh re-applies both by
renaming the type and keeping the scanner.
On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three
of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs
@@ -142,24 +156,19 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/*
serves every structured-output request was the unhardened one. The fork is deleted and its
refusals are here, which is where they were needed all along.
vendor/nlohmann/json.hpp
vendor/nlohmann/json_fwd.hpp <- llama.cpp vendor/nlohmann/nlohmann/*
vendor/nlohmann/LICENSE.MIT <- nlohmann/json LICENSE.MIT at v3.12.0, the release
json.hpp names; llama.cpp does not carry it
vendor/cpp-httplib/httplib.h
vendor/cpp-httplib/httplib.cpp
vendor/cpp-httplib/LICENSE <- llama.cpp vendor/cpp-httplib/cpp-httplib/*
Header-only JSON, byte for byte as lifted, and the HTTP library at cpp-httplib v0.64.0 SPLIT from
upstream's single ~24,300-line header into a .h/.cpp pair, so one translation unit pays for it.
Apart from the split the httplib pair matches upstream exactly when it was lifted; the split itself
drops two decorative `// ----` separator comment lines, moves `inline` from definitions to
declarations, and adds the .cpp's `#include "httplib.h"` and namespace brace. The only difference
from upstream for both is the PATH: llama.cpp nests them one directory deeper
(vendor/nlohmann/nlohmann/) and puts the outer directory on the include path. Flattening lets
`<nlohmann/json.hpp>` and `<cpp-httplib/httplib.h>` resolve with vendor/ alone on the path, which
is the one include directory core/CMakeLists.txt already adds.
The HTTP library at cpp-httplib v0.64.0 SPLIT from upstream's single ~24,300-line header
into a .h/.cpp pair, so one translation unit pays for it. Apart from the split the pair
matches upstream exactly when it was lifted; the split itself drops two decorative
`// ----` separator comment lines, moves `inline` from definitions to declarations, and
adds the .cpp's `#include "httplib.h"` and namespace brace. The only other difference
from upstream is the PATH: llama.cpp nests it one directory deeper and puts the outer
directory on the include path. Flattening lets `<cpp-httplib/httplib.h>` resolve with
vendor/ alone on the path, which is the one include directory core/CMakeLists.txt
already adds.
cpp-httplib's own CMakeLists.txt is NOT carried. vendor/CMakeLists.txt builds httplib.cpp
itself, because upstream's version reaches for llama.cpp's license and compile-flag helpers
@@ -187,6 +196,44 @@ vendor/cpp-httplib/LICENSE <- llama.cpp vendor/cpp-httplib/cpp
one byte per gap paces a worker for that full timeout after the response was already sent.
0022 caps the drain's total budget at 5 s (or the connection timeout, whichever is smaller).
vendor/yyjson/yyjson.h
vendor/yyjson/yyjson.c
vendor/yyjson/LICENSE <- ibireme/yyjson src/* and LICENSE at tag 0.13.0
(commit 138b4a7e757426bbbaa11ca37f257ce8d8489007)
The reader inside the tree's JSON DOM. Parsing a large agent-turn body with the DOM
library this replaced cost ~340 MB/s -- the largest single host item on the serving path
once rendering was optimised -- and almost all of it was the lexer, not the tree. The
DOM now lives in core/util/json.{h,cpp} (rad::Json, ours): yyjson reads under a
byte-budgeted allocator and a converter rebuilds the value tree, enforcing the value
budget and depth cap the request path's bounded parse promises. That displaced the old
DOM everywhere -- server, chat templates, the vendored lift above, config and
checkpoint files, tests -- and vendor/nlohmann is gone with it. The behavioural
contract carried over (typing, refusals, boundaries, dump bytes bar a float's digits
where the old ones were not the shortest that read back) is recorded in
tests/json_test.cpp. MIT.
Upstream tracked: yyjson tag 0.13.0. To refresh: re-copy src/yyjson.{h,c} and LICENSE from
the new tag, keep the include spelled <yyjson/yyjson.h>, and re-run the parse contract
cases (tests/json_test.cpp, tests/wire_test.cpp) -- the converter and the budget
arithmetic in core/util/json.cpp assume yyjson's reader allocates an input copy plus
one value buffer and nothing else, which a refresh must re-confirm.
LOCAL CHANGES: none.
vendor/rapidyaml/ryml.hpp <- rapidyaml v0.16.0 release asset
rapidyaml.v0.16.0.singlehdr.hpp (biojppm/rapidyaml),
renamed; byte-identical
vendor/rapidyaml/LICENSE.txt <- rapidyaml LICENSE.txt at tag v0.16.0
vendor/shim/ryml_impl.cpp ours: defines RYML_SINGLE_HDR_DEFINE_NOW and includes
the header, the one TU holding the implementation
The YAML configuration reader (core/fleet/config.cpp) is the only user. The amalgamated header
carries c4core and fast_float inside it, so nothing else is fetched. MIT.
LOCAL CHANGES: none.
REWRITTEN INTO core/ INSTEAD
----------------------------
@@ -232,6 +279,10 @@ core/ under our own name, with a comment at the top naming what it was read from
PATCH SERIES
------------
Only 0001 and 0022 still live in patches/. The entries for 0002-0021 keep the rationale for
changes that are now maintained directly in the chat lift (see the top of this file); their
headings name the removed patch files, whose diffs are in git history.
patches/0001-unicode-reject-codepoints-above-U-10FFFF.patch
unicode_cpt_from_utf8() accepts a 4-byte sequence with a 0xF5..0xF7 lead and returns a
+3 -3
View File
@@ -5,13 +5,13 @@
#include "common.h"
#include "json-schema-to-grammar.h"
#include "log.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include "peg-parser.h"
#include <stdexcept>
#include <string>
using json = nlohmann::ordered_json;
using json = rad::Json;
// Helper to iterate over tools/functions
static void foreach_function(const json & tools, const std::function<void(const json &)> & fn) {
@@ -44,7 +44,7 @@ common_chat_params peg_generator::generate_parser(const common_chat_template &
// Create the result structure
common_chat_params data;
data.prompt = common_chat_template_direct_apply(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_with_rendered(tmpl, inputs, data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.preserved_tokens = autoparser.preserved_tokens;
+2 -2
View File
@@ -4,13 +4,13 @@
#include "chat-peg-parser.h"
#include "chat.h"
#include "log.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include "peg-parser.h"
#include <cctype>
#include <numeric>
using json = nlohmann::ordered_json;
using json = rad::Json;
std::string trim_whitespace(const std::string & str) {
size_t start = 0;
+2 -2
View File
@@ -4,7 +4,7 @@
#include "common.h"
#include "jinja/caps.h"
#include "peg-parser.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include <chrono>
#include <optional>
@@ -12,7 +12,7 @@
#include <utility>
#include <vector>
using json = nlohmann::ordered_json;
using json = rad::Json;
class common_chat_peg_builder;
+4 -3
View File
@@ -4,11 +4,12 @@
#include "chat.h"
#include "common.h"
#include "log.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include "peg-parser.h"
#include <algorithm>
#include <cctype>
#include <numeric>
#include <ostream>
#include <sstream>
@@ -17,7 +18,7 @@
#define ANSI_ORANGE "\033[1m\x1b[38;5;214m"
#define ANSI_RED "\033[1m\x1b[38;5;196m"
using json = nlohmann::ordered_json;
using json = rad::Json;
namespace autoparser {
@@ -896,7 +897,7 @@ void analyze_tools::analyze_tool_call_format_json_native(const std::string & cle
int json_end = clean_haystack.find_last_of('}');
std::string cut = clean_haystack.substr(json_start, json_end - json_start + 1);
json call_struct = json::parse(cut);
auto register_field = [&](const std::string & prefix, const nlohmann::detail::iteration_proxy_value<json::iterator> & subel) {
auto register_field = [&](const std::string & prefix, const auto & subel) {
if (subel.value().is_string() && std::string(subel.value()).find("call0000") != std::string::npos) {
format.id_field = !prefix.empty() ? prefix + "." + subel.key() : subel.key();
} else if (subel.value().is_string() && std::string(subel.value()) == fun_name_needle) {
+2 -2
View File
@@ -4,9 +4,9 @@
#include "ggml.h"
#include "peg-parser.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
using ordered_json = nlohmann::ordered_json;
using ordered_json = rad::Json;
static std::string_view trim_trailing_space(std::string_view sv, int max = -1) {
int count = 0;
+6 -6
View File
@@ -111,7 +111,7 @@ class common_chat_peg_builder : public common_peg_parser_builder {
// parameters_order: order in which JSON fields should be parsed
common_peg_parser standard_json_tools(const std::string & section_start,
const std::string & section_end,
const nlohmann::ordered_json & tools,
const rad::Json & tools,
bool parallel_tool_calls,
bool force_tool_calls,
const std::string & name_key = "",
@@ -125,30 +125,30 @@ class common_chat_peg_builder : public common_peg_parser_builder {
// Legacy-compatible helper for building XML/tagged style tool calls
// Used by tests and manual parsers
common_peg_parser standard_constructed_tools(const std::map<std::string, std::string> & markers,
const nlohmann::ordered_json & tools,
const rad::Json & tools,
bool parallel_tool_calls,
bool force_tool_calls);
// Helper for Python-style function call format: name(arg1="value1", arg2=123)
// Used by LFM2 and similar templates
common_peg_parser python_style_tool_calls(const nlohmann::ordered_json & tools,
common_peg_parser python_style_tool_calls(const rad::Json & tools,
bool parallel_tool_calls);
private:
// Implementation helpers for standard_json_tools — one per JSON tool call layout mode
common_peg_parser build_json_tools_function_is_key(const nlohmann::ordered_json & tools,
common_peg_parser build_json_tools_function_is_key(const rad::Json & tools,
const std::string & args_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
common_peg_parser build_json_tools_nested_keys(const nlohmann::ordered_json & tools,
common_peg_parser build_json_tools_nested_keys(const rad::Json & tools,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
common_peg_parser build_json_tools_flat_keys(const nlohmann::ordered_json & tools,
common_peg_parser build_json_tools_flat_keys(const rad::Json & tools,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
+209 -85
View File
@@ -13,15 +13,18 @@
#include "jinja/caps.h"
#include "peg-parser.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <exception>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <optional>
#include <sstream>
@@ -30,7 +33,20 @@
#include <utility>
#include <vector>
using json = nlohmann::ordered_json;
using json = rad::Json;
bool common_chat_tool_call::operator==(const common_chat_tool_call & other) const {
if (name != other.name || id != other.id) {
return false;
}
if (arguments_json || other.arguments_json) {
// Compare on the parsed form; dumping here is a diff/error path, not a render path.
const std::string a = arguments_json ? arguments_json->dump() : arguments;
const std::string b = other.arguments_json ? other.arguments_json->dump() : other.arguments;
return a == b;
}
return arguments == other.arguments;
}
static std::string format_time(const std::chrono::system_clock::time_point & now, const std::string & format) {
auto time = std::chrono::system_clock::to_time_t(now);
@@ -164,7 +180,7 @@ json common_chat_msg::to_json_oaicompat(bool concat_typed_text) const {
text += part.text;
}
jmsg["content"] = text;
jmsg["content"] = std::move(text);
} else {
auto & parts = jmsg["content"] = json::array();
for (const auto & part : content_parts) {
@@ -194,7 +210,8 @@ json common_chat_msg::to_json_oaicompat(bool concat_typed_text) const {
{"type", "function"},
{"function", {
{"name", tool_call.name},
{"arguments", json(tool_call.arguments)},
{"arguments", tool_call.arguments_json ? *tool_call.arguments_json
: json(tool_call.arguments)},
}},
};
if (!tool_call.id.empty()) {
@@ -204,7 +221,7 @@ json common_chat_msg::to_json_oaicompat(bool concat_typed_text) const {
// We only generate a random id for the ones that don't generate one by themselves
// (they also won't get to see it as their template likely doesn't use it, so it's all for the client)
// {"id", tc.id.empty() ? gen_tool_call_id() : tc.id},
jtool_calls.push_back(tc);
jtool_calls.push_back(std::move(tc));
}
}
@@ -379,7 +396,7 @@ std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messa
common_chat_msg_content_part msg_part;
msg_part.type = type;
msg_part.text = part.at("text");
msg.content_parts.push_back(msg_part);
msg.content_parts.push_back(std::move(msg_part));
}
} else if (!content.is_null()) {
throw std::invalid_argument("Invalid 'content' type: expected string or array, got " +
@@ -408,13 +425,15 @@ std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messa
const auto & args = fc.at("arguments");
if (args.is_string()) {
tc.arguments = args;
} else if (args.is_object() || args.is_array()) {
tc.arguments_json = std::make_shared<const json>(args);
} else {
tc.arguments = args.dump();
}
if (tool_call.contains("id")) {
tc.id = tool_call.at("id");
}
msg.tool_calls.push_back(tc);
msg.tool_calls.push_back(std::move(tc));
}
}
if (!has_content && !has_tool_calls) {
@@ -432,7 +451,7 @@ std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messa
msg.tool_call_id = message.at("tool_call_id");
}
msgs.push_back(msg);
msgs.push_back(std::move(msg));
}
} catch (const std::exception & e) {
// @ngxson : disable otherwise it's bloating the API response
@@ -455,21 +474,22 @@ static json render_message_to_json(const std::vector<common_chat_msg> & msgs, co
for (const auto & msg : msgs) {
if (only_string_accepted) {
json jmsg = msg.to_json_oaicompat(/* concat_typed_text= */ true);
messages.push_back(jmsg);
messages.push_back(std::move(jmsg));
} else if (only_typed_accepted) {
json jmsg = msg.to_json_oaicompat(/* concat_typed_text= */ false);
if (jmsg.at("content").is_string()) {
std::string text = std::move(jmsg.at("content").get_ref<std::string &>());
jmsg["content"] = json::array({
json{
{"type", "text"},
{"text", jmsg.at("content").get<std::string>()},
{"text", std::move(text)},
}
});
}
messages.push_back(jmsg);
messages.push_back(std::move(jmsg));
} else {
json jmsg = msg.to_json_oaicompat(/* concat_typed_text= */ false);
messages.push_back(jmsg);
messages.push_back(std::move(jmsg));
}
}
return messages;
@@ -537,7 +557,7 @@ std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const json & too
return result;
}
common_chat_continuation common_chat_continuation_parse(const nlohmann::ordered_json & value) {
common_chat_continuation common_chat_continuation_parse(const rad::Json & value) {
if (value.is_boolean() && value.get<bool>()) {
return COMMON_CHAT_CONTINUATION_AUTO;
}
@@ -863,39 +883,41 @@ static std::string common_chat_template_direct_apply_impl(
const std::optional<json> & additional_context = std::nullopt) {
jinja::context ctx(tmpl.source());
nlohmann::ordered_json inp = nlohmann::ordered_json{
{"messages", messages_override.has_value() ? *messages_override : inputs.messages},
{"bos_token", tmpl.bos_token()},
{"eos_token", tmpl.eos_token()},
{"enable_thinking", inputs.enable_thinking},
// Set the globals straight from the JSON values already held, in the same order (and so
// with the same overwrites) as the intermediate object this used to build first: copying
// the messages and tools DOMs into that object just to convert them back out was a deep
// copy of the whole conversation per render.
auto set_json = [&](const std::string & k, const json & v) {
jinja::global_set_from_json(ctx, k, v, inputs.mark_input);
};
set_json("messages", messages_override.has_value() ? *messages_override : inputs.messages);
set_json("bos_token", json(tmpl.bos_token()));
set_json("eos_token", json(tmpl.eos_token()));
set_json("enable_thinking", json(inputs.enable_thinking));
if (tools_override.has_value() || !inputs.tools.empty()) {
inp["tools"] = tools_override.has_value() ? *tools_override : inputs.tools;
set_json("tools", tools_override.has_value() ? *tools_override : inputs.tools);
}
if (inputs.extra_context.is_object()) {
// TODO: do we need to merge, or replacing is fine?
for (const auto & [k, v] : inputs.extra_context.items()) {
inp[k] = v;
set_json(k, v);
}
}
if (additional_context.has_value()) {
// TODO: merge properly instead of overwriting (matching old behavior)
for (const auto & [k, v] : additional_context->items()) {
inp[k] = v;
set_json(k, v);
}
}
if (inputs.add_generation_prompt) {
inp["add_generation_prompt"] = true;
set_json("add_generation_prompt", json(true));
}
jinja::global_from_json(ctx, inp, inputs.mark_input);
// render
jinja::runtime runtime(ctx);
const jinja::value results = runtime.execute(tmpl.prog);
auto parts = jinja::runtime::gather_string_parts(results);
std::string result = parts->as_string().str();
std::string result = jinja::runtime::gather_string(results);
// TODO: improve this later
if (inputs.add_bos && string_starts_with(result, tmpl.bos_token())) {
@@ -913,36 +935,65 @@ std::string common_chat_template_direct_apply(
return common_chat_template_direct_apply_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt);
}
static std::string common_chat_template_generation_prompt_impl(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::optional<json> & messages_override = std::nullopt,
const std::optional<json> & tools_override = std::nullopt,
const std::optional<json> & additional_context = std::nullopt) {
auto adjusted_messages = messages_override ? *messages_override : inputs.messages;
autoparser::generation_params params = inputs;
params.add_generation_prompt = false;
params.continue_final_message = COMMON_CHAT_CONTINUATION_NONE;
std::string no_gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
params.add_generation_prompt = true;
std::string gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
static std::string gen_prompt_diff(const std::string & no_gen_prompt, const std::string & gen_prompt) {
size_t prefix_len = 0;
size_t min_size = std::min(no_gen_prompt.size(), gen_prompt.size());
const size_t min_size = std::min(no_gen_prompt.size(), gen_prompt.size());
while (prefix_len < min_size && no_gen_prompt[prefix_len] == gen_prompt[prefix_len]) {
prefix_len++;
}
return gen_prompt.substr(prefix_len);
}
static std::string common_chat_template_generation_prompt_impl(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::optional<json> & messages_override = std::nullopt,
const std::optional<json> & tools_override = std::nullopt,
const std::optional<json> & additional_context = std::nullopt,
// The caller's own direct_apply of these inputs and overrides, when it has one.
const std::string * rendered_prompt = nullptr) {
auto adjusted_messages = messages_override ? *messages_override : inputs.messages;
autoparser::generation_params params = inputs;
params.continue_final_message = COMMON_CHAT_CONTINUATION_NONE;
std::string no_gen_prompt;
std::string gen_prompt;
// A rendered prompt is one of the two renders below -- the with-generation-prompt one when
// inputs asks for it, the without one when it does not (direct_apply does not read
// continue_final_message, the only other toggled field) -- so render only the other one. A
// chat request otherwise renders its whole conversation three times.
if (rendered_prompt && inputs.add_generation_prompt) {
gen_prompt = *rendered_prompt;
params.add_generation_prompt = false;
no_gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
} else if (rendered_prompt) {
no_gen_prompt = *rendered_prompt;
params.add_generation_prompt = true;
gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
} else {
params.add_generation_prompt = false;
no_gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
params.add_generation_prompt = true;
gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
}
return gen_prompt_diff(no_gen_prompt, gen_prompt);
}
std::string common_chat_template_generation_prompt(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs) {
return common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt);
}
std::string common_chat_template_generation_prompt_with_rendered(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::string & rendered_prompt) {
return common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &rendered_prompt);
}
static common_chat_params common_chat_params_init_ministral_3(const common_chat_template & tmpl,
const autoparser::generation_params & inputs) {
common_chat_params data;
@@ -981,9 +1032,9 @@ static common_chat_params common_chat_params_init_ministral_3(const common_chat_
}
auto adjusted = msg;
adjusted["content"] = content;
adjusted["content"] = std::move(content);
adjusted.erase("reasoning_content");
adjusted_messages.push_back(adjusted);
adjusted_messages.push_back(std::move(adjusted));
}
auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
@@ -995,7 +1046,7 @@ static common_chat_params common_chat_params_init_ministral_3(const common_chat_
data.thinking_start_tag = "[THINK]";
data.thinking_end_tag = "[/THINK]";
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs, /* messages_override = */ adjusted_messages);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override = */ adjusted_messages);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override = */ adjusted_messages, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.preserved_tokens = {
"[THINK]",
@@ -1085,12 +1136,15 @@ static common_chat_params common_chat_params_init_gpt_oss(const common_chat_temp
auto adjusted_messages = json::array();
for (auto msg : inputs.messages) {
if (msg.contains("reasoning_content") && msg.at("reasoning_content").is_string()) {
msg["thinking"] = msg.at("reasoning_content");
/* By value first: inserting "thinking" can reallocate msg's member vector,
* which at() reads through. */
const json reasoning = msg.at("reasoning_content");
msg["thinking"] = reasoning;
if (msg.contains("tool_calls") && msg.at("tool_calls").is_array() && !msg.at("tool_calls").empty()) {
msg.erase("content");
}
}
adjusted_messages.push_back(msg);
adjusted_messages.push_back(std::move(msg));
}
auto prompt = common_chat_template_direct_apply_impl(tmpl, inputs, /* messages_override= */ adjusted_messages);
@@ -1108,13 +1162,6 @@ static common_chat_params common_chat_params_init_gpt_oss(const common_chat_temp
data.prompt = prompt;
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override= */ adjusted_messages);
data.message_spans = common_chat_split_by_role(prompt, {
{ "assistant", "<|start|>assistant" },
{ "user", "<|start|>user" },
{ "system", "<|start|>developer" },
{ "system", "<|start|>system" },
{ "tool", "<|start|>functions" },
});
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
@@ -1245,7 +1292,7 @@ static common_chat_params common_chat_params_init_gemma4(const common_chat_templ
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
if (inputs.add_generation_prompt && string_ends_with(data.prompt, "<turn|>\n")) {
// This may happen if the model generates content + tool_call, the
@@ -1255,11 +1302,6 @@ static common_chat_params common_chat_params_init_gemma4(const common_chat_templ
data.prompt += data.generation_prompt;
}
data.message_spans = common_chat_split_by_role(data.prompt, {
{ "user", "<|turn>user\n" },
{ "assistant", "<|turn>model\n" },
});
data.format = COMMON_CHAT_FORMAT_PEG_GEMMA4;
data.supports_thinking = true;
data.thinking_start_tag = "<|channel>thought";
@@ -1409,7 +1451,7 @@ static common_chat_params common_chat_params_init_functionary_v3_2(const common_
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.preserved_tokens = {
">>>all",
@@ -1510,7 +1552,7 @@ static common_chat_params common_chat_params_init_kimi_k2(const common_chat_temp
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.preserved_tokens = {
@@ -1646,7 +1688,7 @@ static common_chat_params common_chat_params_init_lfm2(const common_chat_templat
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.preserved_tokens = {
@@ -1738,7 +1780,7 @@ static common_chat_params common_chat_params_init_lfm2_5(const common_chat_templ
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.preserved_tokens = {
@@ -1822,7 +1864,7 @@ static common_chat_params common_chat_params_init_gigachat_v3(
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = false;
data.preserved_tokens = {
@@ -1900,7 +1942,7 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.thinking_start_tag = "<think>";
@@ -2263,16 +2305,81 @@ static void convert_tool_responses_gemma4(json & messages) {
messages = result;
}
/* Parsed tool-call arguments by their JSON text. An agent re-sends its whole history every
* turn, so the same arguments strings are parsed again on every request; copying the parsed
* DOM back out is several times cheaper than lexing it again. Bounded by key bytes and
* cleared whole when full -- a cache of convenience, never correctness. */
struct ArgsParseCache {
std::mutex mu;
std::unordered_map<std::string, std::shared_ptr<const json>> by_text;
size_t bytes = 0;
};
static ArgsParseCache & args_parse_cache() {
static ArgsParseCache cache;
return cache;
}
// Tool-call arguments a request sent as an object or array reach the template as that value
// (common_chat_tool_call::arguments_json). A template that does not take object arguments
// reads them as a string, so it gets their compact JSON text, as a request sending the string
// would have given it.
static void func_args_string(json & messages) {
GGML_ASSERT(messages.is_array());
for (auto & message : messages) {
if (!message.is_object() || !message.contains("tool_calls") || !message["tool_calls"].is_array()) {
continue;
}
for (auto & tool_call : message["tool_calls"]) {
if (!tool_call.is_object() || !tool_call.contains("function")) {
continue;
}
auto & fn = tool_call["function"];
if (fn.is_object() && fn.contains("arguments")) {
auto & args = fn["arguments"];
if (args.is_object() || args.is_array()) {
args = json(args.dump());
}
}
}
}
}
static void func_args_not_string(json & messages) {
GGML_ASSERT(messages.is_array());
ArgsParseCache & cache = args_parse_cache();
for (auto & message : messages) {
if (message.contains("tool_calls")) {
for (auto & tool_call : message["tool_calls"]) {
if (tool_call.contains("function") && tool_call["function"].contains("arguments")) {
auto & args = tool_call["function"]["arguments"];
if (args.is_string()) {
const std::string & text = args.get_ref<const std::string &>();
std::shared_ptr<const json> hit;
{
std::lock_guard<std::mutex> lock(cache.mu);
auto it = cache.by_text.find(text);
if (it != cache.by_text.end()) {
hit = it->second;
}
}
if (hit) {
args = *hit;
continue;
}
try {
args = json::parse(args.get<std::string>());
json parsed = json::parse(text);
{
std::lock_guard<std::mutex> lock(cache.mu);
if (cache.bytes + text.size() > 8 * 1024 * 1024 ||
cache.by_text.size() >= 4096) {
cache.by_text.clear();
cache.bytes = 0;
}
cache.bytes += text.size();
cache.by_text[text] = std::make_shared<const json>(parsed);
}
args = std::move(parsed);
} catch (const std::exception & e) {
throw std::runtime_error("Failed to parse tool call arguments as JSON: " + std::string(e.what()));
}
@@ -2446,11 +2553,28 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
if (tmpl.original_caps().supports_object_arguments) {
workaround::func_args_not_string(params.messages);
} else {
workaround::func_args_string(params.messages);
}
params.extra_context = common_chat_extra_context();
for (auto el : inputs.chat_template_kwargs) {
params.extra_context[el.first] = json::parse(el.second);
{
// The base context's members in place (a kwarg of the same name replacing one), then
// the other kwargs in order. Appended, not assigned by key: an object lookup is a scan,
// and a request may send many kwargs.
const json base = common_chat_extra_context();
json::object_t ctx;
ctx.reserve(base.size() + inputs.chat_template_kwargs.size());
for (auto it = base.begin(); it != base.end(); ++it) {
auto kw = inputs.chat_template_kwargs.find(it.key());
ctx.emplace_back(it.key(), kw != inputs.chat_template_kwargs.end() ? json::parse(kw->second)
: it.value());
}
for (const auto & el : inputs.chat_template_kwargs) {
if (!base.contains(el.first)) {
ctx.emplace_back(el.first, json::parse(el.second));
}
}
params.extra_context = json(std::move(ctx));
}
if (!inputs.json_schema.empty()) {
@@ -2496,26 +2620,19 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
const autoparser::autoparser & autoparser = *analysis;
auto auto_params = autoparser::peg_generator::generate_parser(tmpl, params, autoparser);
std::vector<common_chat_msg_delimiter> delimiters;
if (!autoparser.assistant_start.empty()) {
delimiters.push_back({ "assistant", autoparser.assistant_start });
}
if (!autoparser.user_start.empty()) {
delimiters.push_back({ "user", autoparser.user_start });
}
if (!delimiters.empty()) {
auto_params.message_spans = common_chat_split_by_role(auto_params.prompt, delimiters);
}
// No message_spans: nothing in this tree reads them, and splitting the rendered
// prompt by role is a full extra scan of every conversation.
auto_params.supports_thinking = autoparser.reasoning.mode != autoparser::reasoning_mode::NONE;
if (auto_params.supports_thinking) {
auto_params.thinking_start_tag = trim_whitespace(autoparser.reasoning.start);
auto_params.thinking_end_tag = trim_whitespace(autoparser.reasoning.end);
}
common_peg_arena arena;
arena.load(auto_params.parser);
LOG_DBG("%s: generated parser:\n%s\n\nparser generation prompt: %s\n", __func__, arena.dump(arena.root()).c_str(), auto_params.generation_prompt.c_str());
if (::rad_vendor_log::verbose()) {
common_peg_arena arena;
arena.load(auto_params.parser);
LOG_DBG("%s: generated parser:\n%s\n\nparser generation prompt: %s\n", __func__, arena.dump(arena.root()).c_str(), auto_params.generation_prompt.c_str());
}
return auto_params;
} catch (const std::exception & e) {
throw std::invalid_argument(std::string("Unable to generate parser for this template. Automatic parser generation failed: ") + e.what());
@@ -2679,3 +2796,10 @@ std::map<std::string, bool> common_chat_templates_get_caps(const common_chat_tem
GGML_ASSERT(chat_templates->template_default != nullptr);
return chat_templates->template_default->caps.to_map();
}
// RADIANCE: jinja::caps::probe_error of the default template.
std::string common_chat_templates_get_probe_error(const common_chat_templates * chat_templates) {
GGML_ASSERT(chat_templates != nullptr);
GGML_ASSERT(chat_templates->template_default != nullptr);
return chat_templates->template_default->caps.probe_error;
}
+24 -11
View File
@@ -8,16 +8,17 @@
#include "jinja/runtime.h"
#include "jinja/caps.h"
#include "nlohmann/json_fwd.hpp"
#include "util/json.h"
#include <chrono>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>
using chat_template_caps = jinja::caps;
using json = nlohmann::ordered_json;
using json = rad::Json;
struct common_chat_templates;
@@ -29,10 +30,13 @@ struct common_chat_tool_call {
std::string name;
std::string arguments;
std::string id;
/* Arguments that arrived already parsed (an object in the request), carried as JSON so
* the render path neither dumps them to a string here nor parses that string back when a
* template reads them as a mapping. When set, `arguments` stays empty and this is the
* value common_chat_msgs_to_json_oaicompat emits. */
std::shared_ptr<const rad::Json> arguments_json;
bool operator==(const common_chat_tool_call & other) const {
return name == other.name && arguments == other.arguments && id == other.id;
}
bool operator==(const common_chat_tool_call & other) const;
};
struct common_chat_msg_content_part {
@@ -87,7 +91,7 @@ struct common_chat_msg {
std::string tool_name;
std::string tool_call_id;
nlohmann::ordered_json to_json_oaicompat(bool concat_typed_text = false) const;
rad::Json to_json_oaicompat(bool concat_typed_text = false) const;
std::string render_content(const std::string & delimiter = "\n\n") const;
@@ -289,19 +293,20 @@ common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::strin
bool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates);
// Parses a JSON array of messages in OpenAI's chat completion API format.
std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const nlohmann::ordered_json & messages);
std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const rad::Json & messages);
std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const nlohmann::ordered_json & tools);
std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const rad::Json & tools);
common_chat_continuation common_chat_continuation_parse(const nlohmann::ordered_json & value);
common_chat_continuation common_chat_continuation_parse(const rad::Json & value);
// DEPRECATED: only used in tests
nlohmann::ordered_json common_chat_msgs_to_json_oaicompat(const std::vector<common_chat_msg> & msgs, bool concat_typed_text = false);
rad::Json common_chat_msgs_to_json_oaicompat(const std::vector<common_chat_msg> & msgs, bool concat_typed_text = false);
nlohmann::ordered_json common_chat_tools_to_json_oaicompat(const std::vector<common_chat_tool> & tools);
rad::Json common_chat_tools_to_json_oaicompat(const std::vector<common_chat_tool> & tools);
// get template caps, useful for reporting to server /props endpoint
std::map<std::string, bool> common_chat_templates_get_caps(const common_chat_templates * chat_templates);
std::string common_chat_templates_get_probe_error(const common_chat_templates * chat_templates);
std::string common_chat_template_direct_apply(
const common_chat_template & tmpl,
@@ -311,6 +316,14 @@ std::string common_chat_template_generation_prompt(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs);
// As above, with the caller's own direct_apply of `inputs` in hand: it is one of the two
// renders the generation prompt is diffed from, so the other is the only one still needed
// (and a repeat request whose generation prompt proved message-independent needs neither).
std::string common_chat_template_generation_prompt_with_rendered(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::string & rendered_prompt);
std::optional<common_chat_params> common_chat_try_specialized_template(
const common_chat_template & tmpl,
const std::string & src,
+1 -1
View File
@@ -7,7 +7,7 @@ The implementation can be found in the `common/jinja` directory.
## Key Features
- Input marking: security against special token injection
- Decoupled from `nlohmann::json`: this dependency is only used for JSON-to-internal type translation and is completely optional
- Decoupled from `Json`: this dependency is only used for JSON-to-internal type translation and is completely optional
- Minimal primitive types: int, float, bool, string, array, object, none, undefined
- Detailed logging: allow source tracing on error
- Clean architecture: workarounds are applied to input data before entering the runtime (see `common/chat.cpp`)
+12 -2
View File
@@ -4,20 +4,24 @@
// note: the json dependency is only for defining input in a convenient way
// we can remove it in the future when we figure out a better way to define inputs using jinja::value
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <functional>
#include <sstream>
#define FILENAME "jinja-caps"
using json = nlohmann::ordered_json;
using json = rad::Json;
namespace jinja {
using caps_json_fn = std::function<json()>;
using caps_analyze_fn = std::function<void(bool, value &, value &)>;
// RADIANCE: where caps_get collects the first exception of a probe that carried tools
// (caps::probe_error).
static thread_local std::string * caps_probe_error = nullptr;
static void caps_try_execute(jinja::program & prog,
const caps_json_fn & messages_fn,
const caps_json_fn & tools_fn,
@@ -45,6 +49,10 @@ static void caps_try_execute(jinja::program & prog,
success = true;
} catch (const std::exception & e) {
JJ_DEBUG("Exception during execution: %s", e.what());
if (caps_probe_error && caps_probe_error->empty() && is_val<value_array>(tools) &&
!tools->as_array().empty()) {
*caps_probe_error = e.what();
}
result = "";
// ignore exceptions during capability analysis
}
@@ -90,6 +98,7 @@ std::string caps::to_string() const {
caps caps_get(jinja::program & prog) {
caps result;
caps_probe_error = &result.probe_error;
static const auto has_op = [](value & v, const std::string & op_name) {
return v->stats.ops.find(op_name) != v->stats.ops.end();
@@ -475,6 +484,7 @@ caps caps_get(jinja::program & prog) {
JJ_DEBUG("%s\n", result.to_string().c_str());
caps_probe_error = nullptr;
return result;
}
+5
View File
@@ -20,6 +20,11 @@ struct caps {
bool supports_object_arguments = false;
// RADIANCE: what the first probe render that threw said, empty when none did. The probes
// ignore exceptions, so a template calling something this engine lacks and a template
// without tool support both come back supports_tools = false; this tells them apart.
std::string probe_error;
// for reporting on server
std::map<std::string, bool> to_map() const;
+104 -69
View File
@@ -18,16 +18,27 @@ void enable_debug(bool enable) {
g_jinja_debug = enable;
}
/* A block's statement results as one string value. A lone string result already is that
* value -- regathering it would copy (or move) its parts into a fresh string for nothing,
* and blocks with a single output statement are the common shape inside a message loop. */
static value_string gather_array_result(const value_array & result) {
if (result->val_arr.size() == 1) {
if (auto s = std::dynamic_pointer_cast<value_string_t>(result->val_arr[0])) {
return s;
}
}
value_string str = mk_val<value_string>();
gather_string_parts_recursive(result, str);
return str;
}
static value_string exec_statements(const statements & stmts, context & ctx) {
auto result = mk_val<value_array>();
for (const auto & stmt : stmts) {
JJ_DEBUG("Executing statement of type %s", stmt->type().c_str());
result->push_back(stmt->execute(ctx));
}
// convert to string parts
value_string str = mk_val<value_string>();
gather_string_parts_recursive(result, str);
return str;
return gather_array_result(result);
}
static std::string get_line_col(const std::string & source, size_t pos) {
@@ -82,14 +93,17 @@ value statement::execute(context & ctx) {
value identifier::execute_impl(context & ctx) {
auto it = ctx.get_val(val);
auto builtins = global_builtins();
if (!it->is_undefined()) {
if (ctx.is_get_stats) {
value_t::stats_t::mark_used(it);
}
JJ_DEBUG("Identifier '%s' found, type = %s", val.c_str(), it->type().c_str());
return it;
} else if (builtins.find(val) != builtins.end()) {
}
// By reference, and only on the miss path: this used to copy the whole builtins map
// (every std::function in it) for every identifier evaluated.
const auto & builtins = global_builtins();
if (builtins.find(val) != builtins.end()) {
JJ_DEBUG("Identifier '%s' found in builtins", val.c_str());
return mk_val<value_func>(val, builtins.at(val));
} else {
@@ -139,8 +153,8 @@ value binary_expression::execute_impl(context & ctx) {
JJ_DEBUG("%s", "Workaround: treating null/undefined as empty string for string concatenation");
string left_str = is_left_null ? string() : left_val->as_string();
string right_str = is_right_null ? string() : right_val->as_string();
auto output = left_str.append(right_str);
res = mk_val<value_string>(std::move(output));
left_str.append(right_str);
res = mk_val<value_string>(std::move(left_str));
return true;
}
return false;
@@ -245,7 +259,8 @@ value binary_expression::execute_impl(context & ctx) {
if ((is_val<value_string>(left_val) || is_val<value_string>(right_val)) &&
(op.value == "~" || op.value == "+")) {
JJ_DEBUG("String concatenation with %s operator", op.value.c_str());
auto output = left_val->as_string().append(right_val->as_string());
string output = left_val->as_string();
output.append(right_val->as_string());
auto res = mk_val<value_string>();
res->val_str = std::move(output);
return res;
@@ -263,7 +278,7 @@ value binary_expression::execute_impl(context & ctx) {
return res;
}
for (int64_t i = 0; i < repeat; ++i) {
res->val_str = res->val_str.append(str);
res->val_str.append(str);
}
return res;
}
@@ -299,7 +314,7 @@ static value try_builtin_func(context & ctx, const std::string & name, value & i
value_t::stats_t::mark_used(input);
input->stats.ops.insert(name);
}
auto builtins = input->get_builtins();
const auto & builtins = input->get_builtins();
auto it = builtins.find(name);
if (it != builtins.end()) {
JJ_DEBUG("Binding built-in '%s'", name.c_str());
@@ -441,7 +456,7 @@ value unary_expression::execute_impl(context & ctx) {
value if_statement::execute_impl(context & ctx) {
value test_val = test->execute(ctx);
auto out = mk_val<value_array>();
auto out = mk_val<value_stmt_results>();
if (test_val->as_bool()) {
for (auto & stmt : body) {
JJ_DEBUG("IF --> Executing THEN body, current block: %s", stmt->type().c_str());
@@ -453,10 +468,7 @@ value if_statement::execute_impl(context & ctx) {
out->push_back(stmt->execute(ctx));
}
}
// convert to string parts
value_string str = mk_val<value_string>();
gather_string_parts_recursive(out, str);
return str;
return out;
}
value for_statement::execute_impl(context & ctx) {
@@ -517,31 +529,36 @@ value for_statement::execute_impl(context & ctx) {
}
}
std::vector<std::function<void(context &)>> scope_update_fns;
std::vector<value> filtered_items;
for (size_t i = 0; i < items.size(); ++i) {
context loop_scope(scope);
value current = items[i];
std::function<void(context&)> scope_update_fn = [](context &) { /* no-op */};
// Bind the loop variable(s) for items[i] in a context. One lambda for the whole loop:
// this used to build a std::function per item (and a copied scope to test it on, selected
// or not), which made filtering cost more than the iterations it sets up.
auto apply_loop_var = [&](context & c, size_t i) {
if (is_stmt<identifier>(loopvar)) {
auto id = cast_stmt<identifier>(loopvar)->val;
if (is_val<value_object>(iterable_val)) {
// case example: {% for key in dict %}
current = items[i]->as_array()[0];
scope_update_fn = [id, &items, i](context & ctx) {
ctx.set_val(id, items[i]->as_array()[0]);
};
} else {
// case example: {% for item in list %}
scope_update_fn = [id, &items, i](context & ctx) {
ctx.set_val(id, items[i]);
};
// {% for key in dict %} binds the key, {% for item in list %} the item.
c.set_val(id, is_val<value_object>(iterable_val) ? items[i]->as_array()[0] : items[i]);
} else {
auto tuple = cast_stmt<tuple_literal>(loopvar);
auto & c_arr = items[i]->as_array();
for (size_t j = 0; j < tuple->val.size(); ++j) {
if (!is_stmt<identifier>(tuple->val[j])) {
throw std::runtime_error("Cannot unpack non-identifier type: " + tuple->val[j]->type());
}
auto id = cast_stmt<identifier>(tuple->val[j])->val;
c.set_val(id, c_arr[j]);
}
}
};
std::vector<value> filtered_items;
std::vector<size_t> filtered_idx;
for (size_t i = 0; i < items.size(); ++i) {
value current = items[i];
if (is_stmt<identifier>(loopvar)) {
if (is_val<value_object>(iterable_val)) {
current = items[i]->as_array()[0];
}
} else if (is_stmt<tuple_literal>(loopvar)) {
// case example: {% for key, value in dict %}
auto tuple = cast_stmt<tuple_literal>(loopvar);
@@ -552,23 +569,13 @@ value for_statement::execute_impl(context & ctx) {
if (tuple->val.size() != c_arr.size()) {
throw std::runtime_error(std::string("Too ") + (tuple->val.size() > c_arr.size() ? "few" : "many") + " items to unpack");
}
scope_update_fn = [tuple, &items, i](context & ctx) {
auto & c_arr = items[i]->as_array();
for (size_t j = 0; j < tuple->val.size(); ++j) {
if (!is_stmt<identifier>(tuple->val[j])) {
throw std::runtime_error("Cannot unpack non-identifier type: " + tuple->val[j]->type());
}
auto id = cast_stmt<identifier>(tuple->val[j])->val;
ctx.set_val(id, c_arr[j]);
}
};
} else {
throw std::runtime_error("Invalid loop variable(s): " + loopvar->type());
}
if (select_expr && test_expr) {
scope_update_fn(loop_scope);
context loop_scope(scope);
apply_loop_var(loop_scope, i);
value test_val = test_expr->execute(loop_scope);
if (!test_val->as_bool()) {
continue;
@@ -576,28 +583,45 @@ value for_statement::execute_impl(context & ctx) {
}
JJ_DEBUG("For loop: adding item type %s at index %zu", current->type().c_str(), i);
filtered_items.push_back(current);
scope_update_fns.push_back(scope_update_fn);
filtered_idx.push_back(i);
}
JJ_DEBUG("For loop: %zu items after filtering", filtered_items.size());
auto result = mk_val<value_array>();
auto result = mk_val<value_stmt_results>();
// One loop object for the whole loop, its fields replaced per iteration (as in Jinja2,
// where `loop` is one context object whose counters move): a fresh object per iteration
// was nine hash nodes and a bucket array allocated to describe a counter.
value_object loop_obj;
if (!filtered_items.empty()) {
loop_obj = mk_val<value_object>();
loop_obj->has_builtins = false; // loop object has no builtins
loop_obj->insert_new("index", mk_val<value_int>(1));
loop_obj->insert_new("index0", mk_val<value_int>(0));
loop_obj->insert_new("revindex", mk_val<value_int>(filtered_items.size()));
loop_obj->insert_new("revindex0", mk_val<value_int>(filtered_items.size() - 1));
loop_obj->insert_new("first", mk_val<value_bool>(true));
loop_obj->insert_new("last", mk_val<value_bool>(filtered_items.size() == 1));
loop_obj->insert_new("length", mk_val<value_int>(filtered_items.size()));
loop_obj->insert_new("previtem", mk_val<value_undefined>("previtem"));
loop_obj->insert_new("nextitem", filtered_items.size() > 1 ? filtered_items[1] : mk_val<value_undefined>("nextitem"));
}
bool noIteration = true;
for (size_t i = 0; i < filtered_items.size(); i++) {
JJ_DEBUG("For loop iteration %zu/%zu", i + 1, filtered_items.size());
value_object loop_obj = mk_val<value_object>();
loop_obj->has_builtins = false; // loop object has no builtins
loop_obj->insert("index", mk_val<value_int>(i + 1));
loop_obj->insert("index0", mk_val<value_int>(i));
loop_obj->insert("revindex", mk_val<value_int>(filtered_items.size() - i));
loop_obj->insert("revindex0", mk_val<value_int>(filtered_items.size() - i - 1));
loop_obj->insert("first", mk_val<value_bool>(i == 0));
loop_obj->insert("last", mk_val<value_bool>(i == filtered_items.size() - 1));
loop_obj->insert("length", mk_val<value_int>(filtered_items.size()));
loop_obj->insert("previtem", i > 0 ? filtered_items[i - 1] : mk_val<value_undefined>("previtem"));
loop_obj->insert("nextitem", i < filtered_items.size() - 1 ? filtered_items[i + 1] : mk_val<value_undefined>("nextitem"));
if (i > 0) {
loop_obj->at("index") = mk_val<value_int>(i + 1);
loop_obj->at("index0") = mk_val<value_int>(i);
loop_obj->at("revindex") = mk_val<value_int>(filtered_items.size() - i);
loop_obj->at("revindex0") = mk_val<value_int>(filtered_items.size() - i - 1);
loop_obj->at("first") = mk_val<value_bool>(false);
loop_obj->at("last") = mk_val<value_bool>(i == filtered_items.size() - 1);
loop_obj->at("previtem") = filtered_items[i - 1];
loop_obj->at("nextitem") = i < filtered_items.size() - 1 ? filtered_items[i + 1] : mk_val<value_undefined>("nextitem");
}
scope.set_val("loop", loop_obj);
scope_update_fns[i](scope);
apply_loop_var(scope, filtered_idx[i]);
try {
for (auto & stmt : body) {
value val = stmt->execute(scope);
@@ -619,10 +643,7 @@ value for_statement::execute_impl(context & ctx) {
}
}
// convert to string parts
value_string str = mk_val<value_string>();
gather_string_parts_recursive(result, str);
return str;
return result;
}
value set_statement::execute_impl(context & ctx) {
@@ -790,8 +811,7 @@ value member_expression::execute_impl(context & ctx) {
if (!is_stmt<identifier>(this->property)) {
throw std::runtime_error("Static member property must be an identifier");
}
property = mk_val<value_string>(cast_stmt<identifier>(this->property)->val);
std::string prop = property->as_string().str();
const std::string & prop = cast_stmt<identifier>(this->property)->val;
JJ_DEBUG("Member expression, object type %s, static property '%s'", object->type().c_str(), prop.c_str());
// behavior of jinja2: obj having prop as a built-in function AND 'prop', as an object key,
@@ -803,6 +823,21 @@ value member_expression::execute_impl(context & ctx) {
if (!is_val<value_undefined>(val)) {
return val;
}
if (is_val<value_object>(object)) {
// The common case (a message field): look the name up directly instead of
// allocating a key value and hashing it, then trying the builtins a second time.
value out = mk_val<value_undefined>("object_property");
out = object->at(prop, out);
if (ctx.is_get_stats && out && object) {
value prop_val = mk_val<value_string>(prop);
value_t::stats_t::mark_used(out);
value_t::stats_t::mark_used(object);
value_t::stats_t::mark_used(prop_val);
object->stats.ops.insert("object_access");
}
return out;
}
property = mk_val<value_string>(prop);
// else, fallthrough to normal property access below
}
+103 -27
View File
@@ -69,18 +69,17 @@ struct context {
context(const context & parent) : context() {
// inherit variables (for example, when entering a new scope)
auto & pvar = parent.env->as_ordered_object();
for (const auto & pair : pvar) {
set_val(pair.first, pair.second);
}
env->copy_entries_from(*parent.env);
current_time = parent.current_time;
is_get_stats = parent.is_get_stats;
src = parent.src;
}
value get_val(const std::string & name) {
value default_val = mk_val<value_undefined>(name);
return env->at(name, default_val);
if (value * v = env->find_string_key(name)) {
return *v;
}
return mk_val<value_undefined>(name);
}
void set_val(const std::string & name, const value & val) {
@@ -316,30 +315,37 @@ struct identifier : public expression {
// Literals
/* A literal's value made once, at parse time: literals sit inside the loops a template runs
* per message, and allocating a fresh value (and copying the text) for every evaluation was
* thousands of allocations per render for values nothing ever mutates -- every operation on
* a string works on an as_string() copy, and numbers are only read. */
struct integer_literal : public expression {
int64_t val;
explicit integer_literal(int64_t val) : val(val) {}
value cached;
explicit integer_literal(int64_t val) : val(val), cached(mk_val<value_int>(val)) {}
std::string type() const override { return "IntegerLiteral"; }
value execute_impl(context &) override {
return mk_val<value_int>(val);
return cached;
}
};
struct float_literal : public expression {
double val;
explicit float_literal(double val) : val(val) {}
value cached;
explicit float_literal(double val) : val(val), cached(mk_val<value_float>(val)) {}
std::string type() const override { return "FloatLiteral"; }
value execute_impl(context &) override {
return mk_val<value_float>(val);
return cached;
}
};
struct string_literal : public expression {
std::string val;
explicit string_literal(const std::string & val) : val(val) {}
value cached;
explicit string_literal(const std::string & val) : val(val), cached(mk_val<value_string>(val)) {}
std::string type() const override { return "StringLiteral"; }
value execute_impl(context &) override {
return mk_val<value_string>(val);
return cached;
}
};
@@ -598,19 +604,35 @@ struct rethrown_exception : public std::exception {
static void gather_string_parts_recursive(const value & val, value_string & parts) {
// TODO: probably allow print value_none as "None" string? currently this breaks some templates
if (is_val<value_string>(val)) {
const auto & str_val = cast_val<value_string>(val)->val_str;
parts->val_str.append(str_val);
// A uniquely owned string is a statement result being consumed by this gather; move its
// parts instead of copying every byte again at each nesting level. A shared one is an
// input value the context still holds, and is copied as before.
if (val.use_count() == 1) {
auto & src = const_cast<value_string_t *>(cast_val<value_string>(val))->val_str.parts;
auto & dst = parts->val_str.parts;
dst.reserve(dst.size() + src.size());
for (auto & part : src) {
dst.push_back(std::move(part));
}
src.clear();
} else {
const auto & str_val = cast_val<value_string>(val)->val_str;
parts->val_str.append(str_val);
}
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
std::string str_val = val->as_string().str();
parts->val_str.append(str_val);
} else if (is_val<value_array>(val)) {
auto items = cast_val<value_array>(val)->as_array();
const auto & items = cast_val<value_array>(val)->as_array();
for (const auto & item : items) {
/* RADIANCE: `val` is a block's statement results, and every block statement returns
* a string, so a list or a dict among them is the value of an expression the template
* prints. jinja2 prints its repr; flattening it ran its strings together and printed
* nothing for a dict. */
if (is_val<value_array>(item) || is_val<value_object>(item)) {
* nothing for a dict. A statement-results carrier is the one array that is not a
* value: flattening it is its whole purpose. */
if (is_val<value_stmt_results>(item)) {
gather_string_parts_recursive(item, parts);
} else if (is_val<value_array>(item) || is_val<value_object>(item)) {
parts->val_str.append(item->as_string().str());
} else {
gather_string_parts_recursive(item, parts);
@@ -620,11 +642,54 @@ static void gather_string_parts_recursive(const value & val, value_string & part
}
static std::string render_string_parts(const value_string & parts) {
std::ostringstream oss;
std::string out;
out.reserve(parts->val_str.length());
for (const auto & part : parts->val_str.parts) {
oss << part.val;
out += part.val;
}
return out;
}
// The flat text of a statement-result tree, gathered without building a parts list: the parts
// (and their is_input flags) matter to the capability probe, but a caller that only wants the
// rendered string otherwise pays to copy every byte into parts, join them, and copy them out.
static size_t gather_string_length_recursive(const value & val) {
if (is_val<value_string>(val)) {
return cast_val<value_string>(val)->val_str.length();
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
return val->as_string().str().size();
} else if (is_val<value_array>(val)) {
size_t len = 0;
for (const auto & item : cast_val<value_array>(val)->as_array()) {
if (!is_val<value_stmt_results>(item) &&
(is_val<value_array>(item) || is_val<value_object>(item))) {
len += item->as_string().str().size();
} else {
len += gather_string_length_recursive(item);
}
}
return len;
}
return 0;
}
static void gather_string_recursive(const value & val, std::string & out) {
if (is_val<value_string>(val)) {
for (const auto & part : cast_val<value_string>(val)->val_str.parts) {
out += part.val;
}
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
out += val->as_string().str();
} else if (is_val<value_array>(val)) {
for (const auto & item : cast_val<value_array>(val)->as_array()) {
if (!is_val<value_stmt_results>(item) &&
(is_val<value_array>(item) || is_val<value_object>(item))) {
out += item->as_string().str();
} else {
gather_string_recursive(item, out);
}
}
}
return oss.str();
}
struct runtime {
@@ -643,18 +708,29 @@ struct runtime {
static value_string gather_string_parts(const value & val) {
value_string parts = mk_val<value_string>();
gather_string_parts_recursive(val, parts);
// join consecutive parts with the same type
// Join consecutive parts with the same type, in one compaction pass: erasing each
// merged part from the middle shifts the rest of the vector every time.
auto & p = parts->val_str.parts;
for (size_t i = 1; i < p.size(); ) {
if (p[i].is_input == p[i - 1].is_input) {
p[i - 1].val += p[i].val;
p.erase(p.begin() + i);
} else {
i++;
if (!p.empty()) {
size_t w = 0;
for (size_t r = 1; r < p.size(); ++r) {
if (p[r].is_input == p[w].is_input) {
p[w].val += p[r].val;
} else {
p[++w] = std::move(p[r]);
}
}
p.resize(w + 1);
}
return parts;
}
static std::string gather_string(const value & val) {
std::string out;
out.reserve(gather_string_length_recursive(val));
gather_string_recursive(val, out);
return out;
}
};
} // namespace jinja
+41 -12
View File
@@ -2,6 +2,7 @@
#include "jinja/value.h"
#include <algorithm>
#include <cstring>
#include <functional>
#include <optional>
#include <sstream>
@@ -46,11 +47,38 @@ std::string string::str() const {
if (parts.size() == 1) {
return parts[0].val;
}
std::ostringstream oss;
std::string out;
out.reserve(length());
for (const auto & part : parts) {
oss << part.val;
out += part.val;
}
return oss.str();
return out;
}
bool string::equals(const string & other) const {
if (parts.size() == 1 && other.parts.size() == 1) {
return parts[0].val == other.parts[0].val;
}
if (length() != other.length()) {
return false;
}
size_t i = 0, j = 0; // part cursors
size_t a = 0, b = 0; // byte offsets within the cursors' parts
while (i < parts.size() && j < other.parts.size()) {
const std::string & pa = parts[i].val;
const std::string & pb = other.parts[j].val;
const size_t n = std::min(pa.size() - a, pb.size() - b);
if (n > 0 && std::memcmp(pa.data() + a, pb.data() + b, n) != 0) {
return false;
}
a += n;
b += n;
if (a == pa.size()) { ++i; a = 0; }
if (b == pb.size()) { ++j; b = 0; }
}
// The lengths are equal and every byte compared equal; what is left on either side is
// empty parts.
return true;
}
size_t string::length() const {
@@ -103,7 +131,8 @@ void string::mark_input_based_on(const string & other) {
}
}
string string::append(const string & other) {
string & string::append(const string & other) {
parts.reserve(parts.size() + other.parts.size());
for (const auto & part : other.parts) {
parts.push_back(part);
}
@@ -113,29 +142,29 @@ string string::append(const string & other) {
// in-place transformation
using transform_fn = std::function<std::string(const std::string&)>;
static string apply_transform(string & self, const transform_fn & fn) {
static string apply_transform(string && self, const transform_fn & fn) {
for (auto & part : self.parts) {
part.val = fn(part.val);
}
return self;
return std::move(self);
}
string string::uppercase() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
std::string res = s;
std::transform(res.begin(), res.end(), res.begin(), ::toupper);
return res;
});
}
string string::lowercase() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
std::string res = s;
std::transform(res.begin(), res.end(), res.begin(), ::tolower);
return res;
});
}
string string::capitalize() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
if (s.empty()) return s;
std::string res = s;
res[0] = ::toupper(static_cast<unsigned char>(res[0]));
@@ -144,7 +173,7 @@ string string::capitalize() {
});
}
string string::titlecase() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
std::string res = s;
bool capitalize_next = true;
for (char &c : res) {
@@ -180,7 +209,7 @@ string string::strip(bool left, bool right, std::optional<const std::string_view
return s.substr(start, end - start);
};
if (parts.empty()) {
return *this;
return std::move(*this);
}
if (left) {
for (size_t i = 0; i < parts.size(); ++i) {
@@ -207,7 +236,7 @@ string string::strip(bool left, bool right, std::optional<const std::string_view
}
}
}
return *this;
return std::move(*this);
}
} // namespace jinja
+7 -1
View File
@@ -27,6 +27,9 @@ struct string {
string(const std::string & v, bool user_input = false) {
parts.push_back({user_input, v});
}
string(std::string && v, bool user_input = false) {
parts.push_back({user_input, std::move(v)});
}
string(int v) {
parts.push_back({false, std::to_string(v)});
}
@@ -38,6 +41,8 @@ struct string {
void mark_input();
std::string str() const;
// Flattened equality without flattening: walk both part lists segment by segment.
bool equals(const string & other) const;
size_t length() const;
void hash_update(hasher & hash) const noexcept;
bool all_parts_are_input() const;
@@ -47,7 +52,8 @@ struct string {
// mark this string as input if other has ALL parts as input
void mark_input_based_on(const string & other);
string append(const string & other);
// In place: the parts are appended to this string. Returns *this so callers can move it on.
string & append(const string & other);
// in-place transformations
+65 -9
View File
@@ -3,7 +3,7 @@
#include "value.h"
// for converting from JSON to jinja values
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <sstream>
#include <string>
@@ -299,6 +299,58 @@ static value minmax_fn(const func_args & args) {
return best;
}
/* jinja2's unique() over a sequence: the first occurrence of each item, in order, compared by
* `attribute` where one is given. Strings compare lowercased unless `case_sensitive` is true
* (jinja2's default is false). A tuple stays a tuple. */
static value unique_fn(const func_args & args) {
args.ensure_count(1, 3);
if (!is_val<value_array>(args.get_pos(0))) {
throw raised_exception("unique: first argument must be an array");
}
value val = args.get_pos(0);
value cs = args.get_kwarg_or_pos("case_sensitive", 1);
value attribute = args.get_kwarg_or_pos("attribute", 2);
const bool case_sensitive = !cs->is_undefined() && cs->as_bool();
const bool attr_is_int = is_val<value_int>(attribute);
const int64_t attr_int = attr_is_int ? attribute->as_int() : 0;
const std::vector<value> & arr = val->as_array();
auto key = [&](const value & v) -> value {
value k = v;
if (!attribute->is_undefined()) {
if (attr_is_int && is_val<value_array>(v)) {
k = v->at(attr_int);
} else if (!attr_is_int && is_val<value_object>(v)) {
k = v->at(attribute);
} else {
throw raised_exception("unique: unsupported object attribute comparison on " + v->type());
}
}
if (!case_sensitive && is_val<value_string>(k)) {
jinja::string low = k->as_string().lowercase();
return mk_val<value_string>(low);
}
return k;
};
std::vector<value> keys, out;
for (const auto & item : arr) {
value k = key(item);
bool seen = false;
for (const auto & have : keys) {
/* value_compare reads a number against a string as text; jinja2 keeps 1 and "1" apart */
if (is_val<value_string>(k) == is_val<value_string>(have) &&
value_compare(k, have, value_compare_op::eq)) {
seen = true;
break;
}
}
if (!seen) {
keys.push_back(std::move(k));
out.push_back(item);
}
}
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(out)) : mk_val<value_array>(std::move(out));
}
template<bool is_reject>
static value selectattr(const func_args & args) {
args.ensure_count(2, 4);
@@ -924,10 +976,6 @@ const func_builtins & value_bool_t::get_builtins() const {
return builtins;
}
[[noreturn]] static value array_unique_not_implemented(const func_args &) {
throw not_implemented_exception("Array unique builtin not implemented");
}
const func_builtins & value_array_t::get_builtins() const {
static const func_builtins builtins = {
{"default", default_value},
@@ -1133,7 +1181,10 @@ const func_builtins & value_array_t::get_builtins() const {
std::reverse(arr.begin(), arr.end());
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(arr)) : mk_val<value_array>(std::move(arr));
}},
{"unique", array_unique_not_implemented},
/* RADIANCE: upstream leaves `unique` a stub that throws, with the same result as a
* missing min or max above: GLM-5.3-Flash's template checks its tool-call ids with it,
* and the model was reported as having no tool support. */
{"unique", unique_fn},
};
return builtins;
}
@@ -1297,7 +1348,7 @@ const func_builtins & value_undefined_t::get_builtins() const {
//////////////////////////////////
static value from_json(const nlohmann::ordered_json & j, bool mark_input) {
static value from_json(const rad::Json & j, bool mark_input) {
if (j.is_null()) {
return mk_val<value_none>();
} else if (j.is_boolean()) {
@@ -1307,7 +1358,7 @@ static value from_json(const nlohmann::ordered_json & j, bool mark_input) {
} else if (j.is_number_float()) {
return mk_val<value_float>(j.get<double>());
} else if (j.is_string()) {
auto str = mk_val<value_string>(j.get<std::string>());
auto str = mk_val<value_string>(j.get_ref<const std::string &>());
if (mark_input) {
str->mark_input();
}
@@ -1394,7 +1445,7 @@ bool value_compare(const value & a, const value & b, value_compare_op op) {
}
template<>
void global_from_json(context & ctx, const nlohmann::ordered_json & json_obj, bool mark_input) {
void global_from_json(context & ctx, const rad::Json & json_obj, bool mark_input) {
// printf("global_from_json: %s\n" , json_obj.dump(2).c_str());
if (json_obj.is_null() || !json_obj.is_object()) {
throw std::runtime_error("global_from_json: input JSON value must be an object");
@@ -1405,6 +1456,11 @@ void global_from_json(context & ctx, const nlohmann::ordered_json & json_obj, bo
}
}
void global_set_from_json(context & ctx, const std::string & key,
const rad::Json & j, bool mark_input) {
ctx.set_val(key, from_json(j, mark_input));
}
// recursively convert value to JSON string
// TODO: avoid circular references
static void value_to_json_internal(std::ostringstream & oss, const value & val, int curr_lvl, int indent, const std::string_view item_sep, const std::string_view key_sep) {
+170 -28
View File
@@ -3,6 +3,8 @@
#include "string.h"
#include "utils.h"
#include "util/json.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
@@ -86,10 +88,16 @@ struct context; // forward declaration
// marking input can be useful for tracking data provenance
// and preventing template injection attacks
//
// Note: T_JSON can be nlohmann::ordered_json
// Note: T_JSON can be rad::Json
template<typename T_JSON>
void global_from_json(context & ctx, const T_JSON & json_obj, bool mark_input);
/* One global from a JSON value, converted in place: a caller assembling several globals from
* JSON values it already holds (a chat render's messages and tools) need not first copy them
* into an intermediate JSON object for global_from_json to convert back out. */
void global_set_from_json(context & ctx, const std::string & key,
const rad::Json & j, bool mark_input);
//
// base value type
//
@@ -290,7 +298,9 @@ using value_float = std::shared_ptr<value_float_t>;
struct value_string_t : public value_t {
value_string_t() { val_str = string(); }
value_string_t(const std::string & v) { val_str = string(v); }
value_string_t(std::string && v) { val_str = string(std::move(v)); }
value_string_t(const string & v) { val_str = v; }
value_string_t(string && v) { val_str = std::move(v); }
virtual std::string type() const override { return "String"; }
virtual string as_string() const override { return val_str; }
virtual std::string as_repr() const override {
@@ -317,7 +327,7 @@ struct value_string_t : public value_t {
}
protected:
virtual bool equivalent(const value_t & other) const override {
return typeid(*this) == typeid(other) && val_str.str() == other.val_str.str();
return typeid(*this) == typeid(other) && val_str.equals(other.val_str);
}
};
using value_string = std::shared_ptr<value_string_t>;
@@ -459,6 +469,15 @@ protected:
};
using value_array = std::shared_ptr<value_array_t>;
/* A block statement's results, carried up to the gather that actually needs text. If and for
* statements used to gather their bodies into a fresh string at every nesting level, copying
* every shared part's bytes each time; as a carrier, the parts are only flattened once -- by
* the top-level render, or by exec_statements where a real string value is required (a set
* block, a macro body). It is an array for storage only: the gathers recurse into it where a
* plain array value would print its repr, and it never reaches template expressions. */
struct value_stmt_results_t : public value_array_t {};
using value_stmt_results = std::shared_ptr<value_stmt_results_t>;
struct value_tuple_t : public value_array_t {
value_tuple_t(value & v) {
@@ -482,13 +501,40 @@ using value_tuple = std::shared_ptr<value_tuple_t>;
struct value_object_t : public value_t {
std::unordered_map<value, value, value_hasher, value_equivalence> unordered;
/* The hash index over val_obj, built only once an object outgrows a linear scan. The
* objects a chat render builds by the thousand -- messages, calls, scopes -- hold a
* handful of keys each, and for those the map's bucket array and per-key nodes cost more
* than every lookup they would ever serve. val_obj stays the ordered authority either way. */
bool unordered_built_ = false;
static constexpr size_t kHashIndexThreshold = 32;
void build_unordered() {
if (unordered_built_) {
return;
}
unordered.reserve(val_obj.size() * 2);
for (const auto & pair : val_obj) {
unordered.emplace(pair.first, pair.second);
}
unordered_built_ = true;
}
void maybe_build_unordered() {
if (val_obj.size() > kHashIndexThreshold) {
build_unordered();
}
}
value * find_key_linear(const value & key) {
for (auto & pair : val_obj) {
if (*(pair.first) == *key) {
return &pair.second;
}
}
return nullptr;
}
bool has_builtins = true; // context and loop objects do not have builtins
value_object_t() = default;
value_object_t(value & v) {
val_obj = v->val_obj;
for (const auto & pair : val_obj) {
unordered[pair.first] = pair.second;
}
maybe_build_unordered();
}
value_object_t(const std::map<value, value> & obj) {
for (const auto & pair : obj) {
@@ -501,8 +547,32 @@ struct value_object_t : public value_t {
}
}
void insert(const std::string & key, const value & val) {
// The common case is re-binding a name that is already present (a loop variable, a
// scope copy): find it by name first so no key value is allocated for the lookup.
if (is_immutable()) {
throw std::runtime_error("Attempting to modify immutable type");
}
for (auto & pair : val_obj) {
const auto * ks = dynamic_cast<const value_string_t *>(pair.first.get());
if (ks && ks->val_str.parts.size() == 1 && ks->val_str.parts[0].val == key) {
pair.second = val;
if (unordered_built_) {
unordered[pair.first] = val;
}
return;
}
}
insert(mk_val<value_string>(key), val);
}
/* Take another object's entries wholesale (a scope inheriting its parent's variables):
* the ordered list copies in one allocation instead of a key allocation and a scan per
* variable. The hash index, if the size calls for one, is rebuilt from the copy. */
void copy_entries_from(const value_object_t & other) {
val_obj = other.val_obj;
unordered.clear();
unordered_built_ = false;
maybe_build_unordered();
}
virtual std::string type() const override { return "Object"; }
virtual bool is_immutable() const override { return false; }
virtual const std::vector<std::pair<value, value>> & as_ordered_object() const override { return val_obj; }
@@ -518,53 +588,125 @@ struct value_object_t : public value_t {
return ss.str();
}
virtual bool as_bool() const override {
return !unordered.empty();
return !val_obj.empty();
}
virtual bool has_key(const value & key) override {
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
return unordered.find(key) != unordered.end();
if (unordered_built_) {
return unordered.find(key) != unordered.end();
}
return find_key_linear(key) != nullptr;
}
virtual void insert(const value & key, const value & val) override {
bool replaced = false;
if (is_immutable()) {
throw std::runtime_error("Attempting to modify immutable type");
}
if (has_key(key)) {
// if key exists, replace value in ordered list instead of appending
for (auto & pair : val_obj) {
if (*(pair.first) == *key) {
pair.second = val;
replaced = true;
break;
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
if (unordered_built_) {
auto it = unordered.find(key);
if (it != unordered.end()) {
// if key exists, replace value in ordered list instead of appending
it->second = val;
for (auto & pair : val_obj) {
if (*(pair.first) == *key) {
pair.second = val;
break;
}
}
return;
}
}
unordered[key] = val;
if (!replaced) {
unordered.emplace(key, val);
val_obj.push_back({key, val});
return;
}
if (value * existing = find_key_linear(key)) {
*existing = val;
return;
}
val_obj.push_back({key, val});
maybe_build_unordered();
}
/* Insert a key the caller knows is absent (a fresh object's fields): no lookup first. */
void insert_new(const value & key, const value & val) {
if (is_immutable()) {
throw std::runtime_error("Attempting to modify immutable type");
}
if (unordered_built_) {
unordered.emplace(key, val);
}
val_obj.push_back({key, val});
maybe_build_unordered();
}
void insert_new(const std::string & key, const value & val) {
insert_new(mk_val<value_string>(key), val);
}
virtual value & at(const value & key, value & default_val) override {
if (!has_key(key)) {
return default_val;
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
return unordered.at(key);
if (unordered_built_) {
auto it = unordered.find(key);
return it == unordered.end() ? default_val : it->second;
}
if (value * v = find_key_linear(key)) {
return *v;
}
return default_val;
}
virtual value & at(const value & key) override {
if (!has_key(key)) {
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
return unordered.at(key);
if (unordered_built_) {
auto it = unordered.find(key);
if (it == unordered.end()) {
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
}
return it->second;
}
if (value * v = find_key_linear(key)) {
return *v;
}
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
}
/* A string key by value, without allocating a key value and hashing it: objects here are
* message/argument records of a few keys, so the ordered scan is the cheaper lookup. */
value * find_string_key(const std::string & key) {
for (auto & pair : val_obj) {
const auto * ks = dynamic_cast<const value_string_t *>(pair.first.get());
if (!ks) {
continue;
}
size_t off = 0;
bool eq = true;
for (const auto & part : ks->val_str.parts) {
if (key.compare(off, part.val.size(), part.val) != 0) {
eq = false;
break;
}
off += part.val.size();
}
if (eq && off == key.size()) {
return &pair.second;
}
}
return nullptr;
}
virtual value & at(const std::string & key, value & default_val) override {
value key_val = mk_val<value_string>(key);
return at(key_val, default_val);
if (value * v = find_string_key(key)) {
return *v;
}
return default_val;
}
virtual value & at(const std::string & key) override {
value key_val = mk_val<value_string>(key);
return at(key_val);
if (value * v = find_string_key(key)) {
return *v;
}
throw std::runtime_error("Key '" + key + "' not found in value of type " + type());
}
virtual const func_builtins & get_builtins() const override;
virtual bool is_hashable() const override {
+151 -71
View File
@@ -2,12 +2,12 @@
#include "log.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <string>
#include <regex>
using json = nlohmann::ordered_json;
using json = rad::Json;
enum common_json_stack_element_type {
COMMON_JSON_STACK_ELEMENT_OBJECT,
@@ -36,84 +36,164 @@ bool common_json_parse(
const std::string & healing_marker,
common_json & out)
{
// // https://json.nlohmann.me/features/parsing/sax_interface/
struct json_error_locator : public nlohmann::json_sax<json> {
std::size_t position;
bool found_error;
std::string last_token;
std::string exception_message;
// What the healing below needs from a failed parse: where it stopped and which
// containers (and object key) were still open there. This was a SAX walk
// before the DOM swap; a small scanner over the (usually truncated) input produces the
// same stack and cut point. It only ever runs on text json::parse has already refused,
// and every healing candidate is re-parsed before it is believed, so the scanner tracks
// structure, not validity in the small (number and literal spellings are consumed, not
// checked).
struct json_error_locator {
std::size_t position = 0;
bool found_error = false;
std::vector<common_json_stack_element> stack;
json_error_locator() : position(0), found_error(false) {}
bool parse_error(std::size_t position, const std::string & last_token, const json::exception & ex) override { // NOLINT
this->position = position - 1;
this->found_error = true;
this->last_token = last_token;
this->exception_message = ex.what();
return false;
}
void close_value() {
if (!stack.empty() && (stack.back().type == COMMON_JSON_STACK_ELEMENT_KEY)) {
stack.pop_back();
}
}
bool null() override { // NOLINT
close_value();
return true;
}
bool boolean(bool) override { // NOLINT
close_value();
return true;
}
bool number_integer(number_integer_t) override { // NOLINT
close_value();
return true;
}
bool number_unsigned(number_unsigned_t) override { // NOLINT
close_value();
return true;
}
bool number_float(number_float_t, const string_t &) override { // NOLINT
close_value();
return true;
}
bool string(string_t &) override { // NOLINT
close_value();
return true;
}
bool binary(binary_t &) override { // NOLINT
close_value();
return true;
}
bool start_object(std::size_t) override { // NOLINT
stack.push_back({COMMON_JSON_STACK_ELEMENT_OBJECT, ""});
return true;
}
bool end_object() override {
GGML_ASSERT(!stack.empty() && stack.back().type == COMMON_JSON_STACK_ELEMENT_OBJECT);
stack.pop_back();
close_value();
return true;
}
bool key(string_t & key) override { // NOLINT
stack.push_back({COMMON_JSON_STACK_ELEMENT_KEY, key});
return true;
}
bool start_array(std::size_t) override { // NOLINT
stack.push_back({COMMON_JSON_STACK_ELEMENT_ARRAY, ""});
return true;
}
bool end_array() override {
GGML_ASSERT(!stack.empty() && stack.back().type == COMMON_JSON_STACK_ELEMENT_ARRAY);
stack.pop_back();
close_value();
return true;
}
};
json_error_locator err_loc;
auto start = it;
json::sax_parse(it, end, &err_loc);
{
const std::string text(it, end);
const char * s = text.data();
const size_t n = text.size();
size_t i = 0;
struct scan_stop {};
auto fail = [&](size_t at) {
err_loc.found_error = true;
err_loc.position = at;
throw scan_stop{};
};
std::function<void()> skip_ws = [&]() {
while (i < n && (s[i] == ' ' || s[i] == '\n' || s[i] == '\r' || s[i] == '\t')) {
++i;
}
};
std::function<bool()> scan_string = [&]() {
++i; // opening quote
while (true) {
if (i >= n) fail(n);
const char c = s[i];
if (c == '"') {
++i;
return true;
}
if (c == '\\') {
++i;
if (i >= n) fail(n);
if (s[i] == 'u') {
for (int k = 0; k < 4; ++k) {
++i;
if (i >= n || !std::isxdigit((unsigned char) s[i])) fail(i >= n ? n : i);
}
}
++i;
continue;
}
if ((unsigned char) c < 0x20) fail(i);
++i;
}
};
std::function<void(int)> scan_value = [&](int depth) {
if (depth > 512) fail(i);
skip_ws();
if (i >= n) fail(n);
const char c = s[i];
if (c == '{') {
++i;
err_loc.stack.push_back({COMMON_JSON_STACK_ELEMENT_OBJECT, ""});
skip_ws();
if (i < n && s[i] == '}') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
while (true) {
skip_ws();
if (i >= n) fail(n);
if (s[i] != '"') fail(i);
scan_string();
err_loc.stack.push_back({COMMON_JSON_STACK_ELEMENT_KEY, ""});
skip_ws();
if (i >= n) fail(n);
if (s[i] != ':') fail(i);
++i;
scan_value(depth + 1);
skip_ws();
if (i >= n) fail(n);
if (s[i] == ',') {
++i;
continue;
}
if (s[i] == '}') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
fail(i);
}
}
if (c == '[') {
++i;
err_loc.stack.push_back({COMMON_JSON_STACK_ELEMENT_ARRAY, ""});
skip_ws();
if (i < n && s[i] == ']') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
while (true) {
scan_value(depth + 1);
skip_ws();
if (i >= n) fail(n);
if (s[i] == ',') {
++i;
continue;
}
if (s[i] == ']') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
fail(i);
}
}
if (c == '"') {
scan_string();
err_loc.close_value();
return;
}
if (c == '-' || (c >= '0' && c <= '9')) {
while (i < n && (std::isdigit((unsigned char) s[i]) || s[i] == '-' || s[i] == '+' ||
s[i] == '.' || s[i] == 'e' || s[i] == 'E')) {
++i;
}
err_loc.close_value();
return;
}
if (std::isalpha((unsigned char) c)) {
while (i < n && std::isalpha((unsigned char) s[i])) {
++i;
}
err_loc.close_value();
return;
}
fail(i);
};
try {
scan_value(0);
skip_ws();
if (i < n) fail(i);
} catch (const scan_stop &) {
}
}
if (err_loc.found_error) {
it = start;
@@ -318,7 +398,7 @@ bool common_json_parse(
}
return false;
}
out.json = json::parse(it, end);
out.json = json::parse(std::string(it, end));
it = end;
return true;
}
+2 -2
View File
@@ -1,7 +1,7 @@
#pragma once
// TODO: use json_fwd.hpp when possible
#include <nlohmann/json.hpp>
#include "util/json.h"
// Healing marker (empty if the JSON was fully parsed / wasn't healed).
struct common_healing_marker {
@@ -14,7 +14,7 @@ struct common_healing_marker {
// Represents a parsed JSON object, with its optional healing marker (a JSON dump fragment that can be used to find the position of healing in the JSON dump string)
struct common_json {
nlohmann::ordered_json json;
rad::Json json;
common_healing_marker healing_marker;
};
+8 -7
View File
@@ -1,10 +1,11 @@
#include "json-schema-to-grammar.h"
#include "common.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <algorithm>
#include <cctype>
#include <limits>
#include <map>
#include <regex>
#include <sstream>
@@ -13,7 +14,7 @@
#include <unordered_set>
#include <vector>
using json = nlohmann::ordered_json;
using json = rad::Json;
static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
auto has_max = max_items != std::numeric_limits<int>::max();
@@ -1437,11 +1438,11 @@ common_schema_info::~common_schema_info() = default;
common_schema_info::common_schema_info(common_schema_info &&) noexcept = default;
common_schema_info & common_schema_info::operator=(common_schema_info &&) noexcept = default;
void common_schema_info::resolve_refs(nlohmann::ordered_json & schema) {
void common_schema_info::resolve_refs(rad::Json & schema) {
impl_->resolve_refs(schema, "");
}
bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) const {
bool common_schema_info::unsatisfiable(const rad::Json & schema) const {
return common_schema_converter::is_unsatisfiable(schema);
}
@@ -1449,7 +1450,7 @@ bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) co
// Some models emit raw string values rather than JSON-encoded strings for string parameters.
// If any branch of the schema (via oneOf, anyOf, $ref, etc.) permits a string, this returns
// true, allowing callers to handle the value as a raw string for simplicity.
bool common_schema_info::resolves_to_string(const nlohmann::ordered_json & schema) {
bool common_schema_info::resolves_to_string(const rad::Json & schema) {
std::unordered_set<std::string> visited_refs;
std::function<bool(const json &)> check = [&](const json & s) -> bool {
@@ -1578,10 +1579,10 @@ std::string build_grammar(const std::function<void(const common_grammar_builder
/* .add_rule = */ [&](const std::string & name, const std::string & rule) {
return converter._add_rule(name, rule);
},
/* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) {
/* .add_schema = */ [&](const std::string & name, const rad::Json & schema) {
return converter.visit(schema, name == "root" ? "" : name);
},
/* .resolve_refs = */ [&](nlohmann::ordered_json & schema) {
/* .resolve_refs = */ [&](rad::Json & schema) {
converter.resolve_refs(schema, "");
}
};
+7 -7
View File
@@ -1,12 +1,12 @@
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "util/json.h"
#include <functional>
#include <memory>
#include <string>
std::string json_schema_to_grammar(const nlohmann::ordered_json & schema,
std::string json_schema_to_grammar(const rad::Json & schema,
bool force_gbnf = false);
class common_schema_converter;
@@ -24,17 +24,17 @@ class common_schema_info {
common_schema_info(common_schema_info &&) noexcept;
common_schema_info & operator=(common_schema_info &&) noexcept;
void resolve_refs(nlohmann::ordered_json & schema);
bool resolves_to_string(const nlohmann::ordered_json & schema);
void resolve_refs(rad::Json & schema);
bool resolves_to_string(const rad::Json & schema);
// RADIANCE: whether no value satisfies the schema -- `false`, or a `not` of a schema every
// value satisfies (`{}`, or types naming all six JSON types).
bool unsatisfiable(const nlohmann::ordered_json & schema) const;
bool unsatisfiable(const rad::Json & schema) const;
};
struct common_grammar_builder {
std::function<std::string(const std::string &, const std::string &)> add_rule;
std::function<std::string(const std::string &, const nlohmann::ordered_json &)> add_schema;
std::function<void(nlohmann::ordered_json &)> resolve_refs;
std::function<std::string(const std::string &, const rad::Json &)> add_schema;
std::function<void(rad::Json &)> resolve_refs;
};
struct common_grammar_options {
+12 -12
View File
@@ -9,7 +9,7 @@
#include <initializer_list>
#include <map>
#include <memory>
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <regex>
#include <stdexcept>
#include <unordered_set>
@@ -1223,8 +1223,8 @@ common_peg_parser common_peg_parser_builder::chars(const std::string & classes,
return wrap(arena_.add_parser(common_peg_chars_parser{classes, ranges, negated, min, max}));
}
common_peg_parser common_peg_parser_builder::schema(const common_peg_parser & p, const std::string & name, const nlohmann::ordered_json & schema, bool raw) {
return wrap(arena_.add_parser(common_peg_schema_parser{p.id(), name, std::make_shared<nlohmann::ordered_json>(schema), raw}));
common_peg_parser common_peg_parser_builder::schema(const common_peg_parser & p, const std::string & name, const rad::Json & schema, bool raw) {
return wrap(arena_.add_parser(common_peg_schema_parser{p.id(), name, std::make_shared<rad::Json>(schema), raw}));
}
common_peg_parser common_peg_parser_builder::rule(const std::string & name, const common_peg_parser & p, bool trigger) {
@@ -1826,8 +1826,8 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
}
}
static nlohmann::json serialize_parser_variant(const common_peg_parser_variant & variant) {
using json = nlohmann::json;
static rad::Json serialize_parser_variant(const common_peg_parser_variant & variant) {
using json = rad::Json;
return std::visit([](const auto & p) -> json {
using T = std::decay_t<decltype(p)>;
@@ -1907,19 +1907,19 @@ static nlohmann::json serialize_parser_variant(const common_peg_parser_variant &
}, variant);
}
nlohmann::json common_peg_arena::to_json() const {
auto parsers = nlohmann::json::array();
rad::Json common_peg_arena::to_json() const {
auto parsers = rad::Json::array();
for (const auto & parser : parsers_) {
parsers.push_back(serialize_parser_variant(parser));
}
return nlohmann::json{
return rad::Json{
{"parsers", parsers},
{"rules", rules_},
{"root", root_}
};
}
static common_peg_parser_variant deserialize_parser_variant(const nlohmann::json & j) {
static common_peg_parser_variant deserialize_parser_variant(const rad::Json & j) {
if (!j.contains("type") || !j["type"].is_string()) {
throw std::runtime_error("Parser variant JSON missing or invalid 'type' field");
}
@@ -2026,7 +2026,7 @@ static common_peg_parser_variant deserialize_parser_variant(const nlohmann::json
parser.child = j["child"].get<common_peg_parser_id>();
parser.name = j["name"];
if (!j["schema"].is_null()) {
parser.schema = std::make_shared<nlohmann::ordered_json>(j["schema"]);
parser.schema = std::make_shared<rad::Json>(j["schema"]);
}
parser.raw = j["raw"].get<bool>();
return parser;
@@ -2078,7 +2078,7 @@ static common_peg_parser_variant deserialize_parser_variant(const nlohmann::json
throw std::runtime_error("Unknown parser type: " + type);
}
common_peg_arena common_peg_arena::from_json(const nlohmann::json & j) {
common_peg_arena common_peg_arena::from_json(const rad::Json & j) {
if (!j.contains("parsers") || !j["parsers"].is_array()) {
throw std::runtime_error("JSON missing or invalid 'parsers' array");
}
@@ -2118,7 +2118,7 @@ std::string common_peg_arena::save() const {
}
void common_peg_arena::load(const std::string & data) {
*this = from_json(nlohmann::json::parse(data));
*this = from_json(rad::Json::parse(data));
}
common_peg_arena build_peg_parser(const std::function<common_peg_parser(common_peg_parser_builder & builder)> & fn) {
+5 -5
View File
@@ -1,6 +1,6 @@
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "util/json.h"
#include <memory>
#include <unordered_map>
@@ -245,7 +245,7 @@ struct common_peg_until_parser {
struct common_peg_schema_parser {
common_peg_parser_id child;
std::string name;
std::shared_ptr<nlohmann::ordered_json> schema;
std::shared_ptr<rad::Json> schema;
// Indicates if the GBNF should accept a raw string that matches the schema.
bool raw;
@@ -326,8 +326,8 @@ class common_peg_arena {
std::string dump(common_peg_parser_id id) const;
nlohmann::json to_json() const;
static common_peg_arena from_json(const nlohmann::json & j);
rad::Json to_json() const;
static common_peg_arena from_json(const rad::Json & j);
std::string save() const;
void load(const std::string & data);
@@ -484,7 +484,7 @@ class common_peg_parser_builder {
// Wraps a parser with JSON schema metadata for grammar generation.
// Used internally to convert JSON schemas to GBNF grammar rules.
common_peg_parser schema(const common_peg_parser & p, const std::string & name, const nlohmann::ordered_json & schema, bool raw = false);
common_peg_parser schema(const common_peg_parser & p, const std::string & name, const rad::Json & schema, bool raw = false);
// Creates a named rule, stores it in the grammar, and returns a ref.
// If trigger=true, marks this rule as an entry point for lazy grammar generation.
-25526
View File
File diff suppressed because it is too large. Load diff
-187
View File
@@ -1,187 +0,0 @@
// __ _____ _____ _____
// __| | __| | | | JSON for Modern C++
// | | |__ | | | | | | version 3.12.0
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT
#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
#define INCLUDE_NLOHMANN_JSON_FWD_HPP_
#include <cstdint> // int64_t, uint64_t
#include <map> // map
#include <memory> // allocator
#include <string> // string
#include <vector> // vector
// #include <nlohmann/detail/abi_macros.hpp>
// __ _____ _____ _____
// __| | __| | | | JSON for Modern C++
// | | |__ | | | | | | version 3.12.0
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT
// This file contains all macro definitions affecting or depending on the ABI
#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK
#if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH)
#if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 12 || NLOHMANN_JSON_VERSION_PATCH != 0
#warning "Already included a different version of the library!"
#endif
#endif
#endif
#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum)
#define NLOHMANN_JSON_VERSION_MINOR 12 // NOLINT(modernize-macro-to-enum)
#define NLOHMANN_JSON_VERSION_PATCH 0 // NOLINT(modernize-macro-to-enum)
#ifndef JSON_DIAGNOSTICS
#define JSON_DIAGNOSTICS 0
#endif
#ifndef JSON_DIAGNOSTIC_POSITIONS
#define JSON_DIAGNOSTIC_POSITIONS 0
#endif
#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0
#endif
#if JSON_DIAGNOSTICS
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
#else
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS
#endif
#if JSON_DIAGNOSTIC_POSITIONS
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS _dp
#else
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS
#endif
#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp
#else
#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON
#endif
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
#endif
// Construct the namespace ABI tags component
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) json_abi ## a ## b ## c
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c) \
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c)
#define NLOHMANN_JSON_ABI_TAGS \
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \
NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON, \
NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS)
// Construct the namespace version component
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
_v ## major ## _ ## minor ## _ ## patch
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \
NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch)
#if NLOHMANN_JSON_NAMESPACE_NO_VERSION
#define NLOHMANN_JSON_NAMESPACE_VERSION
#else
#define NLOHMANN_JSON_NAMESPACE_VERSION \
NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \
NLOHMANN_JSON_VERSION_MINOR, \
NLOHMANN_JSON_VERSION_PATCH)
#endif
// Combine namespace components
#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b
#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \
NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b)
#ifndef NLOHMANN_JSON_NAMESPACE
#define NLOHMANN_JSON_NAMESPACE \
nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \
NLOHMANN_JSON_ABI_TAGS, \
NLOHMANN_JSON_NAMESPACE_VERSION)
#endif
#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN
#define NLOHMANN_JSON_NAMESPACE_BEGIN \
namespace nlohmann \
{ \
inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \
NLOHMANN_JSON_ABI_TAGS, \
NLOHMANN_JSON_NAMESPACE_VERSION) \
{
#endif
#ifndef NLOHMANN_JSON_NAMESPACE_END
#define NLOHMANN_JSON_NAMESPACE_END \
} /* namespace (inline namespace) NOLINT(readability/namespace) */ \
} // namespace nlohmann
#endif
/*!
@brief namespace for Niels Lohmann
@see https://github.com/nlohmann
@since version 1.0.0
*/
NLOHMANN_JSON_NAMESPACE_BEGIN
/*!
@brief default JSONSerializer template argument
This serializer ignores the template arguments and uses ADL
([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
for serialization.
*/
template<typename T = void, typename SFINAE = void>
struct adl_serializer;
/// a class to store JSON values
/// @sa https://json.nlohmann.me/api/basic_json/
template<template<typename U, typename V, typename... Args> class ObjectType =
std::map,
template<typename U, typename... Args> class ArrayType = std::vector,
class StringType = std::string, class BooleanType = bool,
class NumberIntegerType = std::int64_t,
class NumberUnsignedType = std::uint64_t,
class NumberFloatType = double,
template<typename U> class AllocatorType = std::allocator,
template<typename T, typename SFINAE = void> class JSONSerializer =
adl_serializer,
class BinaryType = std::vector<std::uint8_t>, // cppcheck-suppress syntaxError
class CustomBaseClass = void>
class basic_json;
/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
/// @sa https://json.nlohmann.me/api/json_pointer/
template<typename RefStringType>
class json_pointer;
/*!
@brief default specialization
@sa https://json.nlohmann.me/api/json/
*/
using json = basic_json<>;
/// @brief a minimal map-like container that preserves insertion order
/// @sa https://json.nlohmann.me/api/ordered_map/
template<class Key, class T, class IgnoredLess, class Allocator>
struct ordered_map;
/// @brief specialization that maintains the insertion order of object keys
/// @sa https://json.nlohmann.me/api/ordered_json/
using ordered_json = basic_json<nlohmann::ordered_map>;
NLOHMANN_JSON_NAMESPACE_END
#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
@@ -1,109 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index db3a6cc..ed895b5 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -121,13 +121,25 @@ common_peg_arena autoparser::build_parser(const generation_params & inputs, cons
ctx.content = &content;
ctx.reasoning = &reasoning;
+ bool has_tools = inputs.tools.is_array() && !inputs.tools.empty();
+ bool has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
+
+ // RADIANCE: tell the reasoning parser where a tool call starts, so an unclosed reasoning
+ // block cannot swallow one. This is the same marker the tool parsers below use to split
+ // content from calls, computed here because only this scope can see both analyzers.
+ if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE && jinja_caps.supports_tool_calls) {
+ const std::string & marker = !tools.format.section_start.empty()
+ ? tools.format.section_start
+ : tools.format.per_call_start;
+ if (!marker.empty()) {
+ ctx.reasoning_terminators.push_back(marker);
+ }
+ }
+
// Build reasoning parser
ctx.reasoning_parser = reasoning.build_parser(ctx);
auto parser = p.eps();
-
- bool has_tools = inputs.tools.is_array() && !inputs.tools.empty();
- bool has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
bool pure_content = reasoning.mode == reasoning_mode::NONE;
if (has_response_format) {
@@ -156,12 +168,57 @@ common_peg_parser analyze_reasoning::build_parser(parser_build_context & ctx) co
if (mode == reasoning_mode::TAG_BASED || mode == reasoning_mode::TOOLS_ONLY) {
if (!end.empty()) {
+ const std::string trimmed_end = trim_whitespace(end);
+
+ // RADIANCE: `until(end)` runs to the END OF THE INPUT when the closing tag never
+ // arrives, so a reasoning block the model forgot to close swallowed the entire
+ // reply -- including a <tool_call> written from inside it, which meant the call was
+ // parsed as reasoning text and LOST. The turn then carried no tool call and no
+ // content, and an agent driving it simply stopped. Templates in the wild carry
+ // explicit self-heals for this shape, which is how we know models emit it.
+ //
+ // The repair is an ORDERED CHOICE whose first branch is GUARDED BY A LOOKAHEAD, so
+ // it can only win in the one situation it was written for. The unclosed branch runs
+ // `until` over both the closing tag and the tool-call opener and then REQUIRES, on a
+ // peek that consumes nothing, that what stopped it was the opener. So:
+ //
+ // reasoning </think> <tool_call> -> stops at </think>, peek fails, upstream rule
+ // reasoning <tool_call> -> stops at the opener, peek holds, call parsed
+ // reasoning, no tag, no call -> runs to EOF, peek fails, upstream rule
+ //
+ // The guard is what makes this additive: every reply that closes its reasoning block
+ // takes the second branch, which is upstream's rule byte for byte. It also keeps
+ // reasoning that merely MENTIONS an opener on the upstream path, because such a reply
+ // still has its closing tag and the peek therefore never fires.
+ //
+ // Ordering matters and is not free to swap: `until` returns "need more input" rather
+ // than failing when it reaches the end of the input, so a closed branch placed first
+ // would short-circuit before its required closing literal was ever checked, and the
+ // unclosed branch would be unreachable. That is the bug this comment cost.
+ if (!ctx.reasoning_terminators.empty()) {
+ std::vector<std::string> stops = ctx.reasoning_terminators;
+ stops.insert(stops.begin(), trimmed_end);
+
+ std::vector<common_peg_parser> openers;
+ openers.reserve(ctx.reasoning_terminators.size());
+ for (const auto & t : ctx.reasoning_terminators) {
+ openers.push_back(p.literal(t));
+ }
+ auto unclosed = p.reasoning(p.until_one_of(stops)) + p.peek(p.choice(openers));
+ auto closed = p.reasoning(p.until(trimmed_end)) + p.optspace(end);
+ if (!start.empty()) {
+ return p.optional(p.choice({ p.optspace(start) + unclosed,
+ p.optspace(start) + closed }));
+ }
+ return p.optional(p.choice({ unclosed, closed }));
+ }
+
if (!start.empty()) {
// Standard tag-based: optional(<think>reasoning</think>)
- return p.optional(p.optspace(start) + p.reasoning(p.until(trim_whitespace(end))) + p.optspace(end));
+ return p.optional(p.optspace(start) + p.reasoning(p.until(trimmed_end)) + p.optspace(end));
}
// Delimiter-style (empty start)
- return p.optional(p.reasoning(p.until(trim_whitespace(end))) + p.optspace(end));
+ return p.optional(p.reasoning(p.until(trimmed_end)) + p.optspace(end));
}
}
diff --git a/common/chat-auto-parser.h b/common/chat-auto-parser.h
index 7858f65..478edef 100644
--- a/common/chat-auto-parser.h
+++ b/common/chat-auto-parser.h
@@ -228,6 +228,11 @@ struct parser_build_context {
const analyze_reasoning * reasoning = nullptr;
const analyze_content * content = nullptr;
+ // RADIANCE: markers that end an UNCLOSED reasoning block, in addition to its closing tag --
+ // in practice the tool-call opener. Empty unless this turn can call tools. See the comment
+ // in analyze_reasoning::build_parser for what goes wrong without it.
+ std::vector<std::string> reasoning_terminators;
+
parser_build_context(common_chat_peg_builder & p, const generation_params & inputs);
};
@@ -1,91 +0,0 @@
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -343,13 +343,15 @@ private:
rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
}
return string_join(rules, " | ");
}
std::string _visit_pattern(const std::string & pattern, const std::string & name) {
- if (!(pattern.front() == '^' && pattern.back() == '$')) {
+ // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight
+ // off the wire. The size test has to come first.
+ if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) {
_errors.push_back("Pattern must start with '^' and end with '$'");
return "";
}
std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
std::unordered_map<std::string, std::string> sub_rule_ids;
@@ -407,12 +409,18 @@ private:
results.push_back(to_rule(item));
}
return std::make_pair(string_join(results, " "), false);
};
while (i < length) {
+ // RADIANCE: every arm below must consume at least one byte. The literal arm does not when
+ // it meets a byte that is in NON_LITERAL_SET but that no arm above claims -- a
+ // stray ']' or '}' -- so it breaks out with `literal` empty, nothing is pushed,
+ // and the loop reconsiders the same byte forever. `pattern` is client data, so
+ // that is a one-string denial of service. Checked at the bottom of the body.
+ const size_t progress_at = i;
char c = sub_pattern[i];
if (c == '.') {
seq.emplace_back(get_dot(), false);
i++;
} else if (c == '(') {
i++;
@@ -462,12 +470,17 @@ private:
i++;
seq.emplace_back(square_brackets, false);
} else if (c == '|') {
seq.emplace_back("|", false);
i++;
} else if (c == '*' || c == '+' || c == '?') {
+ if (seq.empty()) {
+ // RADIANCE: a leading quantifier, "^*$". back() on an empty vector is UB.
+ _errors.push_back("Quantifier with nothing to repeat");
+ break;
+ }
seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
i++;
} else if (c == '{') {
std::string curly_brackets = std::string(1, c);
i++;
while (i < length && sub_pattern[i] != '}') {
@@ -496,12 +509,17 @@ private:
}
}
} catch (const std::invalid_argument & e) {
_errors.push_back("Invalid number in curly brackets");
return std::make_pair("", false);
}
+ if (seq.empty()) {
+ // RADIANCE: a leading "{n,m}" has nothing before it to repeat; back() would be UB.
+ _errors.push_back("Quantifier with nothing to repeat");
+ break;
+ }
auto &last = seq.back();
auto &sub = last.first;
auto sub_is_literal = last.second;
if (!sub_is_literal) {
std::string & sub_id = sub_rule_ids[sub];
@@ -545,12 +563,16 @@ private:
}
}
if (!literal.empty()) {
seq.emplace_back(literal, true);
}
}
+ if (i == progress_at) {
+ _errors.push_back("Unsupported pattern syntax");
+ break;
+ }
}
return join_seq();
};
return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space");
}
@@ -1,97 +0,0 @@
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -276,12 +276,24 @@ static std::regex GRAMMAR_LITERAL_ESCAPE_RE("[\r\n\"\\\\]");
static std::regex GRAMMAR_RANGE_LITERAL_ESCAPE_RE("[\r\n\"\\]\\-\\\\]");
static std::unordered_map<char, std::string> GRAMMAR_LITERAL_ESCAPES = {
{'\r', "\\r"}, {'\n', "\\n"}, {'"', "\\\""}, {'-', "\\-"}, {']', "\\]"}, {'\\', "\\\\"}
};
static std::unordered_set<char> NON_LITERAL_SET = {'|', '.', '(', ')', '[', ']', '{', '}', '*', '+', '?'};
+
+// RADIANCE: the escapes GBNF can actually spell. Anything else in a pattern is refused rather
+// than copied into a grammar that will not load. See the use site in _visit_pattern.
+static inline bool is_gbnf_escape(char c) {
+ switch (c) {
+ case 'x': case 'u': case 'U': case 't': case 'r': case 'n':
+ case '\\': case '"': case '[': case ']':
+ return true;
+ default:
+ return false;
+ }
+}
static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) {
std::smatch match;
std::string result;
@@ -545,12 +557,24 @@ private:
char next = sub_pattern[i + 1];
if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
i++;
literal += sub_pattern[i];
i++;
} else {
+ // RADIANCE: GBNF knows \x \u \U \t \r \n \\ \" \[ \] and nothing
+ // else. Copying an escape it cannot spell (\d \w \s \b \/ \-, a
+ // backreference) produces a grammar that returns success here and
+ // then fails to LOAD, which the caller sees as an internal error
+ // on a schema we told it was fine.
+ if (!is_gbnf_escape(next)) {
+ _errors.push_back(
+ std::string("Unsupported regex escape '\\") + next +
+ "' in a pattern: GBNF cannot spell it, so the grammar "
+ "would not load");
+ return std::make_pair(std::string(), true);
+ }
literal += sub_pattern.substr(i, 2);
i += 2;
}
} else if (sub_pattern[i] == '"') {
literal += "\\\"";
i++;
@@ -791,12 +815,21 @@ public:
for (auto & x : n) {
visit_refs(x);
}
} else if (n.is_object()) {
if (n.contains("$ref")) {
std::string ref = n["$ref"];
+ // RADIANCE: a sampler that reaches the network to decide what tokens are legal
+ // is not a sampler we will ship. Upstream fetches through an injected callback
+ // which the public entry point then stubs out to return null -- so a remote
+ // $ref silently degrades into "accepts any object". Refuse, and fetch nothing.
+ if (ref.rfind("http://", 0) == 0 || ref.rfind("https://", 0) == 0) {
+ throw std::runtime_error(
+ "remote $ref is not supported: '" + ref + "'. Inline the referenced "
+ "schema; this converter does not fetch over the network.");
+ }
if (_refs.find(ref) == _refs.end()) {
json target;
if (ref.find("https://") == 0) {
std::string base_url = ref.substr(0, ref.find('#'));
auto it = _refs.find(base_url);
if (it != _refs.end()) {
@@ -860,12 +893,22 @@ public:
std::string visit(const json & schema, const std::string & name) {
json schema_type = schema.contains("type") ? schema["type"] : json();
std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
+ // RADIANCE: "not" has no case below, so it falls through to a rule that accepts anything
+ // -- a constraint the caller asked for, did not get, and is not told about. Complementing
+ // a regular language is representable but the blowup is real; refusing beats pretending.
+ if (schema.is_object() && schema.contains("not")) {
+ _errors.push_back("Unsupported schema keyword \"not\": this converter cannot "
+ "complement a grammar, and accepting the schema without it would "
+ "silently drop the constraint");
+ return "";
+ }
+
if (schema.contains("$ref")) {
return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
}
if (schema.contains("oneOf") || schema.contains("anyOf")) {
std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
@@ -1,46 +0,0 @@
diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp
index 12e747d..111acd0 100644
--- a/common/chat-peg-parser.cpp
+++ b/common/chat-peg-parser.cpp
@@ -36,6 +36,31 @@ static std::string_view trim(std::string_view sv) {
return trim_trailing_space(trim_leading_space(sv, 1));
}
+// RADIANCE: the delimiter around an XML argument value is a NEWLINE, not "whitespace". The
+// template writes <parameter=old_string>\n return a + b\n</parameter>, and exactly the first
+// and last newline are punctuation -- everything between them, INCLUDING the indentation, is the
+// value the model meant to send. Stripping "one leading whitespace character" eats the first
+// column of every indented hunk, so an agent's exact-match edit never applies and the model that
+// wrote a perfectly good call gets the blame. Strip the delimiter and nothing else.
+static std::string_view strip_one_leading_newline(std::string_view sv) {
+ if (!sv.empty() && sv.front() == '\n') {
+ sv.remove_prefix(1);
+ } else if (sv.size() >= 2 && sv[0] == '\r' && sv[1] == '\n') {
+ sv.remove_prefix(2);
+ }
+ return sv;
+}
+
+static std::string_view strip_one_trailing_newline(std::string_view sv) {
+ if (!sv.empty() && sv.back() == '\n') {
+ sv.remove_suffix(1);
+ if (!sv.empty() && sv.back() == '\r') {
+ sv.remove_suffix(1);
+ }
+ }
+ return sv;
+}
+
// Count the number of unclosed '{' braces in a JSON-like string,
// properly skipping braces inside quoted strings.
static int json_brace_depth(const std::string & s) {
@@ -338,7 +363,8 @@ void common_chat_peg_mapper::map(const common_peg_ast_node & node) {
}
if ((is_arg_value || is_arg_string_value) && current_tool) {
- std::string value_content = std::string(trim_trailing_space(trim_leading_space(node.text, 1), 1));
+ std::string value_content =
+ std::string(strip_one_trailing_newline(strip_one_leading_newline(node.text)));
std::string value_to_add;
if (value_content.empty() && is_arg_string_value) {
@@ -1,62 +0,0 @@
diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp
index 0b79098..16b8bbf 100644
--- a/common/jinja/value.cpp
+++ b/common/jinja/value.cpp
@@ -261,6 +261,44 @@ static value tojson(const func_args & args) {
return mk_val<value_string>(json_str);
}
+/* jinja2's min()/max() over a sequence: the smallest (largest) ITEM, compared by `attribute`
+ * where one is given, and undefined for an empty sequence. `case_sensitive` is accepted and
+ * ignored, exactly as `sort` above it does. */
+template<value_compare_op op>
+static value minmax_fn(const func_args & args) {
+ args.ensure_count(1, 3);
+ if (!is_val<value_array>(args.get_pos(0))) {
+ throw raised_exception("min/max: first argument must be an array");
+ }
+ value val = args.get_pos(0);
+ value attribute = args.get_kwarg_or_pos("attribute", 2);
+ const bool attr_is_int = is_val<value_int>(attribute);
+ const int64_t attr_int = attr_is_int ? attribute->as_int() : 0;
+ const std::vector<value> arr = val->as_array(); // copy, as sort does
+ if (arr.empty()) {
+ return mk_val<value_undefined>();
+ }
+ auto key = [&](const value & v) -> value {
+ if (attribute->is_undefined()) {
+ return v;
+ }
+ if (attr_is_int && is_val<value_array>(v)) {
+ return v->at(attr_int);
+ }
+ if (!attr_is_int && is_val<value_object>(v)) {
+ return v->at(attribute);
+ }
+ throw raised_exception("min/max: unsupported object attribute comparison on " + v->type());
+ };
+ value best = arr[0];
+ for (size_t i = 1; i < arr.size(); ++i) {
+ if (value_compare(key(arr[i]), key(best), op)) {
+ best = arr[i];
+ }
+ }
+ return best;
+}
+
template<bool is_reject>
static value selectattr(const func_args & args) {
args.ensure_count(2, 4);
@@ -1082,6 +1120,12 @@ const func_builtins & value_array_t::get_builtins() const {
});
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(arr)) : mk_val<value_array>(std::move(arr));
}},
+ /* RADIANCE: upstream has sort but neither min nor max, and a template that uses one
+ * throws mid-render -- which the capability probe SWALLOWS, so the model is reported as
+ * having no tool support at all instead of the engine being reported as short a filter.
+ * MiniCPM5-2B's tool block is exactly that template. */
+ {"min", minmax_fn<value_compare_op::lt>},
+ {"max", minmax_fn<value_compare_op::gt>},
{"reverse", [](const func_args & args) -> value {
args.ensure_vals<value_array>();
value val = args.get_pos(0);
@@ -1,104 +0,0 @@
diff --git a/common/chat-diff-analyzer.cpp b/common/chat-diff-analyzer.cpp
index 0875c53..695765a 100644
--- a/common/chat-diff-analyzer.cpp
+++ b/common/chat-diff-analyzer.cpp
@@ -25,6 +25,10 @@ static const std::string FUN_FIRST = "FFF_FIRST_FUN_F";
static const std::string FUN_SECOND = "SSS_SECOND_FUN_S";
static const std::string ARG_FIRST = "AA_ARG_FST_AA";
static const std::string ARG_SECOND = "BB_ARG_SND_BB";
+/* RADIANCE: the value the one- and two-argument probes give ARG_FIRST. Named so the split in
+ * extract_argument_separator can find it rather than repeating the literal. */
+static const std::string ARG_FIRST_VALUE = "XXXX";
+static const std::string ARG_SECOND_VALUE = "YYYY";
static const std::string USER_MSG = "U_USER_MSG Hello END_U";
static const std::string USER_MSG_TWO = "V_USER_MSG Hello END_V";
static const std::string ASSISTANT_MSG = "A_ASST_MSG I can help END_A";
@@ -261,6 +265,7 @@ void autoparser::analyze_template(const common_chat_template & tmpl) {
LOG_DBG("arg_name_suffix: '%s'\n", tools.arguments.name_suffix.c_str());
LOG_DBG("arg_value_prefix: '%s'\n", tools.arguments.value_prefix.c_str());
LOG_DBG("arg_value_suffix: '%s'\n", tools.arguments.value_suffix.c_str());
+ LOG_DBG("arg_separator: '%s'\n", tools.arguments.separator.c_str()); /* RADIANCE */
LOG_DBG("name_field: '%s'\n", tools.format.name_field.c_str());
LOG_DBG("args_field: '%s'\n", tools.format.args_field.c_str());
LOG_DBG("id_field: '%s'\n", tools.format.id_field.c_str());
@@ -1355,6 +1360,80 @@ void analyze_tools::extract_argument_separator() {
std::string separator = until_common_prefix(diff.right, ARG_FIRST, ARG_SECOND);
arguments.separator = separator;
}
+
+ /* RADIANCE: THE PER-ARGUMENT SUFFIX AND THE CALL CLOSE CAME OUT AS ONE STRING.
+ *
+ * analyze_arguments() takes everything after the argument value as `value_suffix` and then
+ * trims `function.close`, `per_call_end` or `section_end` off it. A template that declares
+ * none of the three has nothing to cut against. MiniCPM5-2B is one: its calls are
+ * `<function name="F"><param name="A">V</param></function>`, so the suffix came out
+ * `</param></function><|im_end|>\n` with an EMPTY close, and two things then cannot parse --
+ * a call carrying a SECOND argument, because the suffix closes the whole call, and a call
+ * carrying one, because a generated turn ends at `<|im_end|>` and never carries the newline
+ * the template writes BETWEEN turns.
+ *
+ * The boundary is right here, in the render this function already has. Between the first
+ * argument's value and the second argument's name marker is exactly the per-argument suffix.
+ * Nothing is guessed: it is measured off a two-argument render, and every step declines
+ * rather than assuming if the markers do not line up. */
+ if (format.mode == tool_format::TAG_WITH_TAGGED && function.close.empty() &&
+ !arguments.name_prefix.empty() && !arguments.value_suffix.empty()) {
+ const std::string two = diff.prefix + diff.right + diff.suffix;
+ const size_t v1 = two.find(ARG_FIRST_VALUE);
+ const size_t a2 = v1 == std::string::npos ? std::string::npos : two.find(ARG_SECOND, v1);
+ const size_t npx = a2 == std::string::npos
+ ? std::string::npos : two.rfind(arguments.name_prefix, a2);
+ if (npx != std::string::npos && npx >= v1 + ARG_FIRST_VALUE.size()) {
+ const std::string per_arg = two.substr(v1 + ARG_FIRST_VALUE.size(),
+ npx - (v1 + ARG_FIRST_VALUE.size()));
+ const std::string tail = arguments.value_suffix;
+ if (!per_arg.empty() && tail.size() > per_arg.size() &&
+ tail.compare(0, per_arg.size(), per_arg) == 0) {
+ arguments.value_suffix = per_arg;
+ function.close = trim_trailing_whitespace(tail.substr(per_arg.size()));
+
+ /* AND THE CLOSE FROM A TWO-CALL RENDER, for the same reason and by the same
+ * method. The tail above is what a template writes after the LAST call of a
+ * turn, so it carries the turn terminator -- `</function><|im_end|>` -- and a
+ * close that demands the terminator can only ever match a reply with exactly ONE
+ * call in it. Between the end of the first call and the opener of the second
+ * there is no terminator, so that render measures the close alone.
+ *
+ * Anchored on the first call's second argument VALUE rather than on a count of
+ * openers: `<function name="` also appears in this template's own instructions to
+ * the model, in the system prompt, so counting occurrences finds the wrong one. */
+ json assistant_two_calls = json{
+ { "role", "assistant" },
+ { "content", "" },
+ { "tool_calls", json::array({ first_tool_call, second_tool_call }) }
+ };
+ auto calls = compare_variants(*tmpl, params, [&](template_params & p) {
+ p.messages = json::array({ user_msg, assistant_two_calls }); });
+ if (calls) {
+ const std::string c2 = calls->diff.prefix + calls->diff.right + calls->diff.suffix;
+ const size_t lastv = c2.find(ARG_SECOND_VALUE);
+ const size_t open2 = lastv == std::string::npos
+ ? std::string::npos
+ : c2.find(function.name_prefix,
+ lastv + ARG_SECOND_VALUE.size());
+ if (open2 != std::string::npos) {
+ const std::string between =
+ c2.substr(lastv + ARG_SECOND_VALUE.size(),
+ open2 - (lastv + ARG_SECOND_VALUE.size()));
+ if (between.size() > per_arg.size() &&
+ between.compare(0, per_arg.size(), per_arg) == 0) {
+ /* Trailing whitespace is between-turn layout, never part of a
+ * generated close; the parser skips space between calls itself. */
+ function.close = trim_trailing_whitespace(between.substr(per_arg.size()));
+ }
+ }
+ }
+ LOG_DBG("RADIANCE split: value_suffix '%s', func_close '%s'\n",
+ arguments.value_suffix.c_str(), function.close.c_str());
+
+ }
+ }
+ }
}
void analyze_tools::extract_args_markers() {
@@ -1,174 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index ed895b5..104fe47 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -412,7 +412,11 @@ common_peg_parser analyze_tools::build_tool_parser_tag_json(parser_build_context
std::string trigger_marker = !format.section_start.empty() ? format.section_start : format.per_call_start;
auto content_before_tools = trigger_marker.empty() ? p.eps() : p.until(trigger_marker);
- return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls + p.end();
+ /* RADIANCE: and anything AFTER the last call is content too. p.end() immediately after the
+ * calls means a model that signs off -- "Created the file." -- fails the whole parse for it,
+ * which is the same trap as the one above with the ends swapped. */
+ return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls +
+ p.optional(p.content(p.rest())) + p.end();
}
common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_context & ctx) const {
@@ -443,15 +447,38 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
for (const auto & [param_name, param_schema] : properties.items()) {
bool is_required = required.find(param_name) != required.end();
+ /* RADIANCE: A NON-STRING ARGUMENT THAT IS NOT VALID JSON IS STILL AN ARGUMENT.
+ *
+ * An array or object parameter is matched by a schema-constrained JSON parser, and
+ * models do not reliably write JSON inside an XML tag. MiniCPM5 writes Python:
+ * `<param name="edits">[{'oldText': 'a', 'newText': 'b'}]</param>`. The JSON parser
+ * cannot begin on a single quote, so the argument does not match, the call does not
+ * match, and p.end() makes that the whole reply -- which comes back as prose with
+ * the tags in it. The model reads that as the tool rejecting its call and tries
+ * again, differently and just as fruitlessly; in one session it went round four
+ * times, and once rewrote the call with the arguments reordered to appease it.
+ *
+ * Strict JSON is still tried FIRST, so nothing that parses today parses differently.
+ * The fallback takes the value the way a string argument takes it -- as the text up
+ * to `</param>`, which is what actually delimits it in this format -- and the mapper
+ * already normalises a Python-style container to JSON from there
+ * (normalize_container_value in chat-peg-parser.cpp). What is given up is schema
+ * VALIDATION of the argument, and a mistyped argument reaching the tool as a mistyped
+ * argument is strictly better than a correct call reaching the user as prose. */
+ common_peg_parser value_parser = p.choice();
+ if (schema_info.resolves_to_string(param_schema)) {
+ value_parser = p.tool_arg_string_value(until_suffix);
+ } else {
+ value_parser |= p.tool_arg_json_value(p.schema(
+ p.json(), "tool-" + name + "-arg-" + param_name + "-schema",
+ param_schema, false)) + p.space();
+ value_parser |= p.tool_arg_json_value(until_suffix);
+ }
+
auto arg =
p.tool_arg(p.tool_arg_open(arguments.name_prefix + p.tool_arg_name(p.literal(param_name)) +
arguments.name_suffix) +
- arguments.value_prefix +
- (schema_info.resolves_to_string(param_schema) ?
- p.tool_arg_string_value(until_suffix) :
- p.tool_arg_json_value(p.schema(
- p.json(), "tool-" + name + "-arg-" + param_name + "-schema", param_schema, false)) +
- p.space()) +
+ arguments.value_prefix + value_parser +
p.tool_arg_close(p.literal(arguments.value_suffix)));
auto named_arg = p.rule("tool-" + name + "-arg-" + param_name, arg);
@@ -462,22 +489,33 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
}
}
- // Build required arg sequence in definition order
- common_peg_parser args_seq = p.eps();
- for (size_t i = 0; i < required_parsers.size(); i++) {
- if (i > 0) {
- args_seq = args_seq + p.space();
- }
- args_seq = args_seq + required_parsers[i];
+ /* RADIANCE: A NAMED ARGUMENT CARRIES ITS OWN NAME, SO ITS POSITION MEANS NOTHING.
+ *
+ * Required arguments were required IN SCHEMA ORDER. This format writes them as
+ * `<param name="path">..</param><param name="content">..</param>` -- the name is right
+ * there in the tag -- and a model emits them in whatever order it composed them, which
+ * for a write is very often the content first, because that is the part it was thinking
+ * about. The sequence then does not match, and since the rule ends in p.end() the failure
+ * is TOTAL: the call comes back to the client as prose with the tags still in it, which
+ * looks exactly like a model that cannot call tools.
+ *
+ * Every argument is accepted in any order here, required and optional alike. What the
+ * grammar gives up -- checking that each required argument appears exactly once -- was
+ * never its job: a call missing one is a bad call, and arriving at the tool AS a bad call
+ * says so, where arriving as prose says nothing at all. */
+ common_peg_parser any_arg = p.choice();
+ for (const auto & req : required_parsers) {
+ any_arg |= req;
+ }
+ for (const auto & opt : optional_parsers) {
+ any_arg |= opt;
}
- // Build optional args with flexible ordering
- if (!optional_parsers.empty()) {
- common_peg_parser any_opt = p.choice();
- for (const auto & opt : optional_parsers) {
- any_opt |= opt;
- }
- args_seq = args_seq + p.repeat(p.space() + any_opt, 0, -1);
+ common_peg_parser args_seq = p.eps();
+ if (!required_parsers.empty()) {
+ args_seq = any_arg + p.repeat(p.space() + any_arg, 0, -1);
+ } else if (!optional_parsers.empty()) {
+ args_seq = args_seq + p.repeat(p.space() + any_arg, 0, -1);
}
if (!arguments.start.empty()) {
@@ -510,6 +548,12 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
auto require_tools = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED;
+ /* RADIANCE: what opens a call, and therefore what content is read up to. See the return
+ * statement; computed here because the between-calls rule below needs it too. */
+ std::string trigger_marker = !format.section_start.empty() ? format.section_start
+ : !format.per_call_start.empty() ? format.per_call_start
+ : function.name_prefix;
+
common_peg_parser tool_calls = p.eps();
if (!format.per_call_start.empty()) {
@@ -525,11 +569,28 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
(format.section_end.empty() ? p.end() : p.literal(format.section_end) + p.space()));
}
} else {
- std::string separator = ", "; // Default
+ /* RADIANCE: A TAGGED CALL IS SELF-DELIMITING, SO THE SEPARATOR IS WHITESPACE.
+ *
+ * This used a literal ", " -- the separator of a JSON ARRAY of calls -- for a format
+ * whose calls are tags. MiniCPM5-2B writes
+ * `<function name="ls">..</function>\n<function name="bash">..</function>`, and the
+ * second call was required to begin with a comma and a space. It never does, so the
+ * rule failed -- and because the whole thing ends in p.end(), the failure is not "one
+ * call and some text", it is NO MATCH AT ALL: every reply with two calls in it came back
+ * as raw prose with the reasoning and the tags still in it. One call parsed, two never.
+ *
+ * A tagged call opens with its own name prefix and closes with its own close, so nothing
+ * between them is needed to tell one from the next. p.space() accepts the newline these
+ * models put there and the nothing that a template writing them adjacently produces. */
+ /* RADIANCE: and a model narrates BETWEEN calls too -- "Let me look at the tree." then a
+ * call, "Now the tests." then another. Only whitespace was allowed between them. */
+ common_peg_parser next_call =
+ p.space() + (trigger_marker.empty() ? p.eps() : p.optional(p.content(p.until(trigger_marker)))) +
+ tool_choice;
if (inputs.parallel_tool_calls) {
tool_calls = p.trigger_rule("tool-call", format.section_start + p.space() + tool_choice +
- p.zero_or_more(separator + tool_choice) + p.space() +
+ p.zero_or_more(next_call) + p.space() +
format.section_end);
} else {
tool_calls = p.trigger_rule(
@@ -541,7 +602,18 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
tool_calls = p.optional(tool_calls);
}
- std::string trigger_marker = !format.section_start.empty() ? format.section_start : format.per_call_start;
+ /* RADIANCE: WITH NO SECTION OR PER-CALL MARKER, NOTHING WAS ALLOWED BEFORE THE CALL.
+ *
+ * `content_before_tools` is what lets a model say something and THEN call a tool. It is
+ * driven by the section or per-call opener, and a format with neither -- this one -- got
+ * p.eps(), which permits no content at all. So a reply that opens with a sentence ("The
+ * workspace is empty. I will create a Tic Tac Toe implementation.") and then makes a
+ * perfectly well-formed call does not match, and p.end() turns that into a whole-parse
+ * failure: the call comes back as prose.
+ *
+ * What opens a call in a tagged format is the function name prefix, `<function name="`, so
+ * that is the marker to read up to. It is only a fallback -- a format that really does have
+ * a section or per-call opener still uses it, because that one starts earlier in the text. */
auto content_before_tools = trigger_marker.empty() ? p.eps() : p.until(trigger_marker);
return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls + p.end();
}
@@ -1,72 +0,0 @@
diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp
index 111acd0..b674d6e 100644
--- a/common/chat-peg-parser.cpp
+++ b/common/chat-peg-parser.cpp
@@ -51,6 +51,54 @@ static std::string_view strip_one_leading_newline(std::string_view sv) {
return sv;
}
+// RADIANCE: A CDATA SECTION IS PUNCTUATION, NOT CONTENT. MiniCPM5's template tells the model
+// verbatim: "If it contains <, & or newline characters, wrap it in a CDATA block:
+// <param name="param-name"><![CDATA[...multi-line value...]]></param>" -- so every source file an
+// agent writes arrives wrapped, and handing `<![CDATA[def main():...]]>` to a write tool puts
+// those characters into the file.
+//
+// THE TWO ENDS ARE STRIPPED INDEPENDENTLY, AND THAT IS THE WHOLE POINT. A streamed value is
+// parsed again from the top on every chunk, and what the server sends the client is the part
+// that is new -- so a value already emitted cannot be taken back. Requiring both delimiters
+// before removing either means the opener escapes in the first chunk, every time, and the
+// closing `]]>` is then half-eaten by the suffix match: the agent's files came out starting
+// `<![CDATA[` and ending `]]`, the model saw its own output corrupted, and it spent the rest of
+// the session trying to edit the markers back out.
+//
+// While a value is still partial, a trailing `]` or `]]` is held back: it is either the start of
+// the closer or the end of a JSON array, and withholding is safe either way -- what is emitted
+// stays a prefix of the finished value, which is the contract the streaming diff needs.
+static void unwrap_cdata(std::string_view & sv, bool is_partial) {
+ static constexpr std::string_view cd_open = "<![CDATA[";
+ static constexpr std::string_view cd_close = "]]>";
+ if (sv.size() < cd_open.size()) {
+ /* Not enough of it to tell yet. While the value is still arriving, anything that could
+ * still BECOME the opener is held back whole -- `<![CDATA` went out as content once and
+ * could never be taken back. A complete value this short is just a short value. */
+ if (is_partial && !sv.empty() && cd_open.compare(0, sv.size(), sv) == 0) {
+ sv = std::string_view();
+ }
+ return;
+ }
+ if (sv.compare(0, cd_open.size(), cd_open) != 0) {
+ return;
+ }
+ sv.remove_prefix(cd_open.size());
+ if (sv.size() >= cd_close.size() &&
+ sv.compare(sv.size() - cd_close.size(), cd_close.size(), cd_close) == 0) {
+ sv.remove_suffix(cd_close.size());
+ return;
+ }
+ if (!is_partial) {
+ return;
+ }
+ size_t hold = 0;
+ while (hold + 1 < cd_close.size() && sv.size() > hold && sv[sv.size() - 1 - hold] == ']') {
+ ++hold;
+ }
+ sv.remove_suffix(hold);
+}
+
static std::string_view strip_one_trailing_newline(std::string_view sv) {
if (!sv.empty() && sv.back() == '\n') {
sv.remove_suffix(1);
@@ -363,8 +411,10 @@ void common_chat_peg_mapper::map(const common_peg_ast_node & node) {
}
if ((is_arg_value || is_arg_string_value) && current_tool) {
- std::string value_content =
- std::string(strip_one_trailing_newline(strip_one_leading_newline(node.text)));
+ std::string_view value_view =
+ strip_one_trailing_newline(strip_one_leading_newline(node.text));
+ unwrap_cdata(value_view, node.is_partial);
+ std::string value_content = std::string(value_view);
std::string value_to_add;
if (value_content.empty() && is_arg_string_value) {
@@ -1,46 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index 104fe47..b682578 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -511,6 +511,41 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
any_arg |= opt;
}
+ /* RADIANCE: AN ARGUMENT THE SCHEMA DOES NOT DECLARE MUST NOT TAKE THE REPLY DOWN WITH IT.
+ *
+ * Every arm above matches its parameter name as a LITERAL, so a name outside the schema
+ * matches nothing, the call matches nothing, and p.end() makes that the whole reply --
+ * which comes back to the caller as prose with the XML in it. Observed on MiniCPM5-2B
+ * calling a `read` tool whose only parameter is `path`:
+ *
+ * <function name="read"><param name="action">read</param></function>
+ *
+ * one hallucinated argument name, and the turn was lost. The model then reads its own
+ * call echoed back as text, concludes the tool is broken, and rewrites it.
+ *
+ * Tried LAST, so every declared name still binds to its own schema-checked arm and
+ * nothing that parses today parses differently. The value is taken the way a string
+ * argument takes it -- the text up to the value suffix, which is what delimits it in
+ * this format. What is given up is knowing that the argument was undeclared; the TOOL
+ * gets to say so, which it can do properly, and which a reply that never arrives cannot.
+ * Same argument as the non-JSON container fallback above. */
+ /* WHAT ENDS THE NAME IS NOT ALWAYS `name_suffix`. This format decomposes
+ * `<param name="path">v</param>` as prefix `<param name="`, name_suffix EMPTY and
+ * value_prefix `">` -- so a generic name runs until value_prefix here, and the first
+ * cut of this arm guarded on `!name_suffix.empty()` and silently never built itself. */
+ const std::string & name_end =
+ arguments.name_suffix.empty() ? arguments.value_prefix : arguments.name_suffix;
+ if (!arguments.name_prefix.empty() && !name_end.empty() &&
+ !arguments.value_suffix.empty()) {
+ auto unknown_arg =
+ p.tool_arg(p.tool_arg_open(arguments.name_prefix +
+ p.tool_arg_name(p.until(name_end)) +
+ arguments.name_suffix) +
+ arguments.value_prefix + p.tool_arg_string_value(until_suffix) +
+ p.tool_arg_close(p.literal(arguments.value_suffix)));
+ any_arg |= p.rule("tool-" + name + "-arg-undeclared", unknown_arg);
+ }
+
common_peg_parser args_seq = p.eps();
if (!required_parsers.empty()) {
args_seq = any_arg + p.repeat(p.space() + any_arg, 0, -1);
@@ -1,33 +0,0 @@
diff --git a/common/chat.cpp b/common/chat.cpp
index ef15169..1398152 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -2354,8 +2354,26 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
params.grammar = inputs.grammar;
params.now = inputs.now;
params.add_generation_prompt = inputs.add_generation_prompt;
- params.add_bos = tmpls->add_bos;
- params.add_eos = tmpls->add_eos;
+ /* RADIANCE: `add_bos` HAS TO COME FROM THE INPUTS, OR THE INPUT FIELD IS DEAD.
+ *
+ * `common_chat_templates_inputs` carries add_bos/add_eos and every caller fills them, but
+ * this conversion overwrote both from the TEMPLATES object -- which is only ever set inside
+ * common_chat_templates_init, from a llama_vocab. A host that passes `model = nullptr` and
+ * supplies the vocabulary's facts as overrides (which is what radiance does: the container
+ * carries the template, the BOS/EOS spellings and the add flags, so there is no llama_model
+ * to read them off) therefore had both flags stuck at false no matter what it asked for.
+ *
+ * What the flag does is strip a BOS the TEMPLATE rendered, because the tokeniser is about to
+ * add one -- so with it stuck off, a container whose tokeniser adds BOS and whose template
+ * also writes `bos_token` gets TWO. The Llama-family templates write it; Qwen's do not,
+ * which is why this stayed invisible here.
+ *
+ * The two upstream callers that do set it -- common_chat_format_single and
+ * common_chat_format_example -- assign `inputs.add_bos = tmpls->add_bos` immediately before
+ * calling apply, which is exactly the redundancy you would expect if apply were meant to read
+ * the inputs. Falling back to the templates object keeps them working unchanged. */
+ params.add_bos = inputs.add_bos || tmpls->add_bos;
+ params.add_eos = inputs.add_eos || tmpls->add_eos;
params.continue_final_message = inputs.continue_final_message;
if (params.continue_final_message != COMMON_CHAT_CONTINUATION_NONE) {
@@ -1,142 +0,0 @@
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
index b682578..71520db 100644
--- a/common/chat-auto-parser-generator.cpp
+++ b/common/chat-auto-parser-generator.cpp
@@ -447,6 +447,17 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
for (const auto & [param_name, param_schema] : properties.items()) {
bool is_required = required.find(param_name) != required.end();
+ /* RADIANCE: AN OPTIONAL ARGUMENT NO VALUE SATISFIES IS ONE NO CALL WRITES -- an
+ * Arktype "never", exported as `{"not": {}}` (oh-my-pi's `task` tool declares its batch
+ * form's `model` so). It gets no arm: a schema-checked arm for it is a grammar for a
+ * value that does not exist, and the converter refuses to build one. A model that
+ * writes it anyway reaches the undeclared-argument arm below, as any name outside the
+ * schema does, and the tool says what is wrong. Required, it goes through the schema
+ * and is refused there by name. */
+ if (!is_required && schema_info.unsatisfiable(param_schema)) {
+ continue;
+ }
+
/* RADIANCE: A NON-STRING ARGUMENT THAT IS NOT VALID JSON IS STILL AN ARGUMENT.
*
* An array or object parameter is matched by a schema-constrained JSON parser, and
diff --git a/common/chat.cpp b/common/chat.cpp
index 1398152..5bc91eb 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -1955,6 +1955,11 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha
std::vector<common_peg_parser> optional_parsers;
for (const auto & [param_name, param_schema] : props.items()) {
bool is_required = required.find(param_name) != required.end();
+ // RADIANCE: an optional argument no value satisfies is one no call writes, so it
+ // gets no arm (see chat-auto-parser-generator.cpp); required, it is refused by name.
+ if (!is_required && schema_info.unsatisfiable(param_schema)) {
+ continue;
+ }
bool is_string = schema_info.resolves_to_string(param_schema);
auto arg = p.tool_arg(
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index ccf857a..95640fb 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -697,6 +697,19 @@ private:
const auto &prop_name = kv.first;
const auto &prop_schema = kv.second;
+ // RADIANCE: a property no value satisfies is a key the object never carries, which the
+ // grammar states exactly by having no rule for it. Its name stays in prop_names, so an
+ // additionalProperties rule cannot readmit the key with a value of its own. Required,
+ // it makes the whole object unsatisfiable, and that is refused.
+ if (is_unsatisfiable(prop_schema)) {
+ if (required.find(prop_name) != required.end()) {
+ _errors.push_back("Property \"" + prop_name + "\" is required, but its schema "
+ "accepts no value");
+ }
+ prop_names.push_back(prop_name);
+ continue;
+ }
+
std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
prop_kv_rule_names[prop_name] = _add_rule(
name + (name.empty() ? "" : "-") + prop_name + "-kv",
@@ -887,6 +900,17 @@ public:
visit_refs(schema);
}
+ // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` --
+ // which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an
+ // optional property no call may set. A `not` of the empty schema makes its whole schema
+ // unsatisfiable whatever sits beside it, so the sibling keywords do not matter.
+ static bool is_unsatisfiable(const json & schema) {
+ if (schema.is_boolean()) return !schema.get<bool>();
+ if (!schema.is_object() || !schema.contains("not")) return false;
+ const json & n = schema["not"];
+ return (n.is_object() && n.empty()) || (n.is_boolean() && n.get<bool>());
+ }
+
static std::string _generate_constant_rule(const json & value) {
return format_literal(value.dump());
}
@@ -896,9 +920,19 @@ public:
std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
- // RADIANCE: "not" has no case below, so it falls through to a rule that accepts anything
- // -- a constraint the caller asked for, did not get, and is not told about. Complementing
- // a regular language is representable but the blowup is real; refusing beats pretending.
+ // RADIANCE: an unsatisfiable schema in a place that must hold a value -- the root, an array's
+ // items, a $ref target -- has no grammar: GBNF has no empty language to give it. An object
+ // property and a union alternative of this kind are handled where they occur.
+ if (is_unsatisfiable(schema)) {
+ _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\" accepts no "
+ "value, where a value is required");
+ return "";
+ }
+
+ // RADIANCE: any other "not" has no case below, so it would fall through to a rule that
+ // accepts anything -- a constraint the caller asked for, did not get, and is not told
+ // about. Complementing a regular language is representable but the blowup is real;
+ // refusing beats pretending.
if (schema.is_object() && schema.contains("not")) {
_errors.push_back("Unsupported schema keyword \"not\": this converter cannot "
"complement a grammar, and accepting the schema without it would "
@@ -911,6 +945,14 @@ public:
}
if (schema.contains("oneOf") || schema.contains("anyOf")) {
std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
+ // RADIANCE: an alternative no value satisfies contributes nothing to the union.
+ alt_schemas.erase(std::remove_if(alt_schemas.begin(), alt_schemas.end(), is_unsatisfiable),
+ alt_schemas.end());
+ if (alt_schemas.empty()) {
+ _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\": no "
+ "alternative of its union accepts a value");
+ return "";
+ }
return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
}
if (schema_type.is_array()) {
@@ -1108,6 +1150,10 @@ void common_schema_info::resolve_refs(nlohmann::ordered_json & schema) {
impl_->resolve_refs(schema, "");
}
+bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) const {
+ return common_schema_converter::is_unsatisfiable(schema);
+}
+
// Determines if a JSON schema can resolve to a string type through any path.
// Some models emit raw string values rather than JSON-encoded strings for string parameters.
// If any branch of the schema (via oneOf, anyOf, $ref, etc.) permits a string, this returns
diff --git a/common/json-schema-to-grammar.h b/common/json-schema-to-grammar.h
index 240d642..86c78f3 100644
--- a/common/json-schema-to-grammar.h
+++ b/common/json-schema-to-grammar.h
@@ -26,6 +26,8 @@ class common_schema_info {
void resolve_refs(nlohmann::ordered_json & schema);
bool resolves_to_string(const nlohmann::ordered_json & schema);
+ // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`.
+ bool unsatisfiable(const nlohmann::ordered_json & schema) const;
};
struct common_grammar_builder {
@@ -1,54 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 95640fb..0bf2b72 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -904,6 +904,26 @@ public:
// which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an
// optional property no call may set. A `not` of the empty schema makes its whole schema
// unsatisfiable whatever sits beside it, so the sibling keywords do not matter.
+ // RADIANCE: a count -- minLength, maxLength, minItems, maxItems -- as the int build_repetition
+ // takes, or `dflt` where the schema has none. get<int>() casts, so a bound past INT_MAX wrapped:
+ // Number.MAX_SAFE_INTEGER, a common way to write "no limit", came out as -1 and the grammar did
+ // not parse. A count at or past INT_MAX is INT_MAX, which build_repetition reads as no maximum;
+ // no context the engine serves holds a string or an array that long, so the bound changes
+ // nothing a generation can write. A count that is not a non-negative number is refused.
+ int _schema_count(const json & schema, const char * key, int dflt, const std::string & name) {
+ if (!schema.contains(key)) {
+ return dflt;
+ }
+ const json & v = schema[key];
+ const double d = v.is_number() ? v.get<double>() : -1.0;
+ if (!(d >= 0)) {
+ _errors.push_back(std::string(key) + " of \"" + (name.empty() ? std::string("root") : name) +
+ "\" must be a non-negative number");
+ return dflt;
+ }
+ return d >= (double) std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : (int) d;
+ }
+
static bool is_unsatisfiable(const json & schema) {
if (schema.is_boolean()) return !schema.get<bool>();
if (!schema.is_object() || !schema.contains("not")) return false;
@@ -1059,9 +1079,8 @@ public:
return _add_rule(rule_name, rule);
}
std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
- int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
- json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
- int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
+ int min_items = _schema_count(schema, "minItems", 0, name);
+ int max_items = _schema_count(schema, "maxItems", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
}
@@ -1077,8 +1096,8 @@ public:
}
if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
- int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
- int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
+ int min_len = _schema_count(schema, "minLength", 0, name);
+ int max_len = _schema_count(schema, "maxLength", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
}
if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
@@ -1,106 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 0bf2b72..12e2756 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -900,10 +900,6 @@ public:
visit_refs(schema);
}
- // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` --
- // which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an
- // optional property no call may set. A `not` of the empty schema makes its whole schema
- // unsatisfiable whatever sits beside it, so the sibling keywords do not matter.
// RADIANCE: a count -- minLength, maxLength, minItems, maxItems -- as the int build_repetition
// takes, or `dflt` where the schema has none. get<int>() casts, so a bound past INT_MAX wrapped:
// Number.MAX_SAFE_INTEGER, a common way to write "no limit", came out as -1 and the grammar did
@@ -924,11 +920,74 @@ public:
return d >= (double) std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : (int) d;
}
+ // RADIANCE: the schema every value satisfies, whose `not` is therefore the schema none does.
+ // `{}` and `true` are it, and so is a type list, or a union of bare types, that between them
+ // name all six JSON types -- the way Arktype exports the complement of `never` for an optional
+ // property: {"not": {"anyOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"},
+ // {"type": "object"}, {"type": "array"}, {"type": "null"}]}}. Annotations may sit beside; any
+ // other keyword narrows the schema, and its `not` is a real complement, refused below. A union
+ // alternative that constrains more than its type is not counted, so a union is only ever read
+ // as universal when it is.
+ static bool is_universal(const json & s) {
+ if (s.is_boolean()) return s.get<bool>();
+ if (!s.is_object()) return false;
+ static const std::unordered_set<std::string> annotations = {
+ "description", "title", "default", "examples", "$comment", "deprecated", "readOnly",
+ "writeOnly",
+ };
+ // Whether every key of `o` is an annotation or `allowed`.
+ auto only = [&](const json & o, const char * allowed) {
+ for (auto it = o.begin(); it != o.end(); ++it) {
+ if (annotations.count(it.key()) == 0 && (allowed == nullptr || it.key() != allowed)) {
+ return false;
+ }
+ }
+ return true;
+ };
+ // The types a bare `type` names, into `out`; false for anything that is not one.
+ auto types_of = [](const json & t, std::unordered_set<std::string> & out) {
+ if (t.is_string()) {
+ out.insert(t.get<std::string>());
+ return true;
+ }
+ if (!t.is_array()) return false;
+ for (const auto & e : t) {
+ if (!e.is_string()) return false;
+ out.insert(e.get<std::string>());
+ }
+ return true;
+ };
+ auto covers = [](const std::unordered_set<std::string> & ts) {
+ for (const char * t : { "string", "number", "boolean", "object", "array", "null" }) {
+ if (ts.count(t) == 0) return false;
+ }
+ return true;
+ };
+ if (only(s, nullptr)) return true;
+ std::unordered_set<std::string> ts;
+ if (s.contains("type") && only(s, "type")) {
+ return types_of(s["type"], ts) && covers(ts);
+ }
+ if (s.contains("anyOf") && only(s, "anyOf") && s["anyOf"].is_array()) {
+ for (const auto & a : s["anyOf"]) {
+ if (is_universal(a)) return true;
+ if (a.is_object() && a.contains("type") && only(a, "type")) {
+ types_of(a["type"], ts);
+ }
+ }
+ return covers(ts);
+ }
+ return false;
+ }
+
+ // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and TypeBox's
+ // Type.Never and Arktype's "never" export it as a `not` of the universal schema above, the
+ // latter for an optional property no call may set. Such a `not` makes its whole schema
+ // unsatisfiable whatever sits beside it, so the sibling keywords do not matter.
static bool is_unsatisfiable(const json & schema) {
if (schema.is_boolean()) return !schema.get<bool>();
if (!schema.is_object() || !schema.contains("not")) return false;
- const json & n = schema["not"];
- return (n.is_object() && n.empty()) || (n.is_boolean() && n.get<bool>());
+ return is_universal(schema["not"]);
}
static std::string _generate_constant_rule(const json & value) {
diff --git a/common/json-schema-to-grammar.h b/common/json-schema-to-grammar.h
index 86c78f3..8223dd4 100644
--- a/common/json-schema-to-grammar.h
+++ b/common/json-schema-to-grammar.h
@@ -26,7 +26,8 @@ class common_schema_info {
void resolve_refs(nlohmann::ordered_json & schema);
bool resolves_to_string(const nlohmann::ordered_json & schema);
- // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`.
+ // RADIANCE: whether no value satisfies the schema -- `false`, or a `not` of a schema every
+ // value satisfies (`{}`, or types naming all six JSON types).
bool unsatisfiable(const nlohmann::ordered_json & schema) const;
};
@@ -1,67 +0,0 @@
diff --git a/common/jinja/runtime.h b/common/jinja/runtime.h
index b6f4a6ab..af84c910 100644
--- a/common/jinja/runtime.h
+++ b/common/jinja/runtime.h
@@ -606,7 +606,15 @@ static void gather_string_parts_recursive(const value & val, value_string & part
} else if (is_val<value_array>(val)) {
auto items = cast_val<value_array>(val)->as_array();
for (const auto & item : items) {
- gather_string_parts_recursive(item, parts);
+ /* RADIANCE: `val` is a block's statement results, and every block statement returns
+ * a string, so a list or a dict among them is the value of an expression the template
+ * prints. jinja2 prints its repr; flattening it ran its strings together and printed
+ * nothing for a dict. */
+ if (is_val<value_array>(item) || is_val<value_object>(item)) {
+ parts->val_str.append(item->as_string().str());
+ } else {
+ gather_string_parts_recursive(item, parts);
+ }
}
}
}
diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp
index 16b8bbf1..b7af1ae1 100644
--- a/common/jinja/value.cpp
+++ b/common/jinja/value.cpp
@@ -1496,13 +1496,35 @@ std::string value_to_json(const value & val, int indent, const std::string_view
// TODO: avoid circular references
std::string value_to_string_repr(const value & val) {
if (is_val<value_string>(val)) {
- const std::string val_str = val->as_string().str();
-
- if (val_str.find('\'') != std::string::npos) {
- return value_to_json(val);
- } else {
- return "'" + val_str + "'";
+ /* RADIANCE: Python's str repr, which jinja2 prints for a string inside a list or a dict:
+ * single quotes unless the text holds one and no double quote, and backslash escapes for
+ * the backslash, the quote, \t \n \r and the other ASCII controls. Python also escapes
+ * non-printable non-ASCII code points; those pass through here. */
+ const std::string s = val->as_string().str();
+ const char q = s.find('\'') != std::string::npos && s.find('"') == std::string::npos ? '"' : '\'';
+ std::string out(1, q);
+ for (const char ch : s) {
+ const unsigned char c = (unsigned char) ch;
+ if (ch == q || ch == '\\') {
+ out += '\\';
+ out += ch;
+ } else if (ch == '\t') {
+ out += "\\t";
+ } else if (ch == '\n') {
+ out += "\\n";
+ } else if (ch == '\r') {
+ out += "\\r";
+ } else if (c < 0x20 || c == 0x7f) {
+ static const char hex[] = "0123456789abcdef";
+ out += "\\x";
+ out += hex[c >> 4];
+ out += hex[c & 15];
+ } else {
+ out += ch;
+ }
}
+ out += q;
+ return out;
} else {
return val->as_repr();
}
-58
View File
@@ -1,58 +0,0 @@
diff --git a/common/chat.cpp b/common/chat.cpp
index 5bc91ebd..90172e9e 100644
--- a/common/chat.cpp
+++ b/common/chat.cpp
@@ -20,6 +20,8 @@
#include <ctime>
#include <exception>
#include <functional>
+#include <memory>
+#include <mutex>
#include <optional>
#include <sstream>
@@ -285,8 +287,33 @@ struct common_chat_templates {
bool has_explicit_template; // Model had builtin template or template overridden was specified.
std::unique_ptr<common_chat_template> template_default; // always set (defaults to chatml)
std::unique_ptr<common_chat_template> template_tool_use;
+ /* RADIANCE: the differential analysis of template_default ([0]) and template_tool_use ([1]),
+ * made on first use (template_analysis). */
+ mutable std::mutex analysis_lock;
+ mutable std::shared_ptr<const autoparser::autoparser> analysis[2];
};
+/* RADIANCE: autoparser::analyze_template renders the template over synthetic messages and reads
+ * nothing but the template, so one analysis serves every request rendered through it. One that
+ * throws is not kept, and the next request analyses again and throws again. */
+static std::shared_ptr<const autoparser::autoparser> template_analysis(
+ const common_chat_templates * tmpls, const common_chat_template & tmpl) {
+ const size_t slot = &tmpl == tmpls->template_default.get() ? 0 : 1;
+ {
+ std::lock_guard<std::mutex> lock(tmpls->analysis_lock);
+ if (tmpls->analysis[slot]) {
+ return tmpls->analysis[slot];
+ }
+ }
+ auto made = std::make_shared<autoparser::autoparser>();
+ made->analyze_template(tmpl);
+ std::lock_guard<std::mutex> lock(tmpls->analysis_lock);
+ if (!tmpls->analysis[slot]) {
+ tmpls->analysis[slot] = std::move(made);
+ }
+ return tmpls->analysis[slot];
+}
+
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) {
if (tool_choice == "auto") {
return COMMON_CHAT_TOOL_CHOICE_AUTO;
@@ -2465,8 +2492,8 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
try {
LOG_DBG("%s: using differential autoparser\n", __func__);
- struct autoparser::autoparser autoparser;
- autoparser.analyze_template(tmpl);
+ const std::shared_ptr<const autoparser::autoparser> analysis = template_analysis(tmpls, tmpl);
+ const autoparser::autoparser & autoparser = *analysis;
auto auto_params = autoparser::peg_generator::generate_parser(tmpl, params, autoparser);
std::vector<common_chat_msg_delimiter> delimiters;
@@ -1,60 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 12e2756..df4846d 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -291,6 +291,45 @@ static inline bool is_gbnf_escape(char c) {
return false;
}
}
+
+// RADIANCE: a JSON Schema `pattern` is unanchored (ECMA-262 search semantics, JSON Schema
+// validation 6.3.3): "[0-9]+" admits any string holding a digit. _visit_pattern() reads only
+// ^...$, so a missing anchor is written out as "any string text" on that side. That filler is
+// not ".*": '.' here matches '"', and the string would run on past its closing quote. A
+// one-sided anchor beside a top-level '|' binds to one branch only, so that pattern is
+// returned as it came and refused.
+static std::string anchor_pattern(const std::string & p) {
+ static const std::string any = "(?:[^\"\\\\]|\\\\.)*";
+ const bool starts = !p.empty() && p.front() == '^';
+ size_t slashes = 0; // backslashes before a final '$': an odd count makes it a literal
+ if (!p.empty() && p.back() == '$') {
+ for (size_t k = p.size() - 1; k > 0 && p[k - 1] == '\\'; --k) slashes++;
+ }
+ const bool ends = p.size() > (starts ? 1u : 0u) && p.back() == '$' && slashes % 2 == 0;
+ if (starts && ends) {
+ return p;
+ }
+ const size_t from = starts ? 1 : 0;
+ const std::string core = p.substr(from, p.size() - from - (ends ? 1 : 0));
+ if (core.empty()) {
+ return "^" + any + "$";
+ }
+ if (starts != ends) {
+ int depth = 0;
+ bool in_class = false;
+ for (size_t k = 0; k < core.size(); ++k) {
+ const char c = core[k];
+ if (c == '\\') { ++k; continue; }
+ if (in_class) { if (c == ']') in_class = false; continue; }
+ if (c == '[') in_class = true;
+ else if (c == '(') depth++;
+ else if (c == ')') depth--;
+ else if (c == '|' && depth == 0) return p;
+ }
+ }
+ return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$";
+}
+
static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) {
@@ -357,7 +396,8 @@ private:
return string_join(rules, " | ");
}
- std::string _visit_pattern(const std::string & pattern, const std::string & name) {
+ std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
+ const std::string pattern = anchor_pattern(client_pattern);
// RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight
// off the wire. The size test has to come first.
if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) {
@@ -1,97 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index df4846d..4664833 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -330,6 +330,77 @@ static std::string anchor_pattern(const std::string & p) {
return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$";
}
+// RADIANCE: \d \w \s and their negations, which GBNF cannot spell, written out as the classes
+// ECMA-262 gives them, before the scanner reads the pattern. A JSON string holds text, not raw
+// bytes: the negated forms leave out '"', '\' and the control characters, which a string can only
+// carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote;
+// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
+// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
+// so false is returned and the pattern refused.
+static bool expand_shorthands(const std::string & p, std::string & out) {
+ static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
+ static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
+ static const std::string raw = "\"\\\\\\x00-\\x1F";
+ auto negated = [&](const std::string & cls) { return "(?:[^" + cls + raw + "]|" + esc + ")"; };
+ out.clear();
+ for (size_t i = 0; i < p.size(); ++i) {
+ const char c = p[i];
+ if (c == '\\' && i + 1 < p.size()) {
+ const char n = p[++i];
+ switch (n) {
+ case 'd': out += "[0-9]"; break;
+ case 'w': out += "[A-Za-z0-9_]"; break;
+ case 's': out += "(?:[" + sp + "]|\\\\[tnfr])"; break;
+ case 'D': out += negated("0-9"); break;
+ case 'W': out += negated("A-Za-z0-9_"); break;
+ case 'S': out += negated(sp); break;
+ default: out += c; out += n; break;
+ }
+ continue;
+ }
+ if (c != '[') {
+ out += c;
+ continue;
+ }
+ // The class runs to the first unescaped ']', as the scanner reads it.
+ size_t j = i + 1;
+ std::string body;
+ while (j < p.size() && p[j] != ']') {
+ if (p[j] == '\\' && j + 1 < p.size()) {
+ body += p.substr(j, 2);
+ j += 2;
+ } else {
+ body += p[j++];
+ }
+ }
+ if (body == "\\s\\S" || body == "\\S\\s" || body == "\\d\\D" || body == "\\D\\d" ||
+ body == "\\w\\W" || body == "\\W\\w") {
+ out += "(?:[^" + raw + "]|" + esc + ")";
+ i = j;
+ continue;
+ }
+ std::string cls = "[";
+ for (size_t k = 0; k < body.size(); ++k) {
+ if (body[k] == '\\' && k + 1 < body.size()) {
+ const char n = body[++k];
+ if (n == 'd') cls += "0-9";
+ else if (n == 'w') cls += "A-Za-z0-9_";
+ else if (n == 's') cls += sp;
+ else if (n == 'D' || n == 'W' || n == 'S') return false;
+ else { cls += '\\'; cls += n; }
+ } else {
+ cls += body[k];
+ }
+ }
+ out += cls;
+ if (j < p.size()) {
+ out += ']';
+ }
+ i = j;
+ }
+ return true;
+}
+
static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) {
@@ -397,7 +468,13 @@ private:
}
std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
- const std::string pattern = anchor_pattern(client_pattern);
+ std::string expanded;
+ if (!expand_shorthands(client_pattern, expanded)) {
+ _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class "
+ "cannot be spelled in GBNF");
+ return "";
+ }
+ const std::string pattern = anchor_pattern(expanded);
// RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight
// off the wire. The size test has to come first.
if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) {
@@ -1,58 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 4664833..92561c4 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -4,6 +4,7 @@
#include <nlohmann/json.hpp>
#include <algorithm>
+#include <cctype>
#include <map>
#include <regex>
#include <sstream>
@@ -336,7 +337,12 @@ static std::string anchor_pattern(const std::string & p) {
// carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote;
// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
-// so false is returned and the pattern refused.
+// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript
+// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read.
+static bool is_identity_punct(char c) {
+ return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast<unsigned char>(c));
+}
+
static bool expand_shorthands(const std::string & p, std::string & out) {
static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
@@ -354,7 +360,16 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
case 'D': out += negated("0-9"); break;
case 'W': out += negated("A-Za-z0-9_"); break;
case 'S': out += negated(sp); break;
- default: out += c; out += n; break;
+ default:
+ // An identity escape of punctuation GBNF has no escape for ("\/", "\-") is the
+ // bare character; regex syntax characters and '"' keep their backslash.
+ if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) {
+ out += n;
+ } else {
+ out += c;
+ out += n;
+ }
+ break;
}
continue;
}
@@ -387,6 +402,13 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
else if (n == 'w') cls += "A-Za-z0-9_";
else if (n == 's') cls += sp;
else if (n == 'D' || n == 'W' || n == 'S') return false;
+ else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') {
+ // "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could
+ // read as a range or a negation, so they are written as \xHH.
+ cls += "\\x";
+ cls += "0123456789ABCDEF"[(n >> 4) & 0xF];
+ cls += "0123456789ABCDEF"[n & 0xF];
+ }
else { cls += '\\'; cls += n; }
} else {
cls += body[k];
@@ -1,150 +0,0 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 92561c4..53f067c 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -338,12 +338,33 @@ static std::string anchor_pattern(const std::string & p) {
// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its
// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling,
// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript
-// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read.
+// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. \t \n \r \f
+// \b (in a class) \v \0 are control characters, which a JSON string carries only as escapes, so
+// they match the escape. Any other escape in a class (\p{..}, \c, a backreference) has no GBNF
+// spelling: `bad` names it and false is returned, rather than copying it into a grammar that
+// would then fail to load.
static bool is_identity_punct(char c) {
return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast<unsigned char>(c));
}
-static bool expand_shorthands(const std::string & p, std::string & out) {
+// The JSON escape for the control character a regex escape names, or "" if it names none.
+static std::string json_control_escape(char n) {
+ switch (n) {
+ case 't': case 'n': case 'r': case 'f': case 'b': return std::string("\\\\") + n;
+ case 'v': return "\\\\u000[bB]";
+ case '0': return "\\\\u0000";
+ default: return "";
+ }
+}
+
+static std::string hex_escape(char n) {
+ std::string s = "\\x";
+ s += "0123456789ABCDEF"[(n >> 4) & 0xF];
+ s += "0123456789ABCDEF"[n & 0xF];
+ return s;
+}
+
+static bool expand_shorthands(const std::string & p, std::string & out, char & bad) {
static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF";
static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})";
static const std::string raw = "\"\\\\\\x00-\\x1F";
@@ -365,6 +386,12 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
// bare character; regex syntax characters and '"' keep their backslash.
if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) {
out += n;
+ } else if (n != 'b' && !json_control_escape(n).empty()) {
+ // A group, so a following quantifier takes the whole escape. Outside a class
+ // \b is a word boundary, which the scanner refuses.
+ out += "(?:" + json_control_escape(n) + ")";
+ } else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) {
+ out += n;
} else {
out += c;
out += n;
@@ -395,28 +422,74 @@ static bool expand_shorthands(const std::string & p, std::string & out) {
continue;
}
std::string cls = "[";
+ // A positive class's control characters can only appear as JSON escapes, which are two
+ // or six characters long, so they become alternatives beside the class.
+ std::vector<std::string> escapes;
+ const bool negated_cls = !body.empty() && body[0] == '^';
+ std::string excluded; // the control characters a negated class leaves out, by escape letter
for (size_t k = 0; k < body.size(); ++k) {
if (body[k] == '\\' && k + 1 < body.size()) {
const char n = body[++k];
if (n == 'd') cls += "0-9";
else if (n == 'w') cls += "A-Za-z0-9_";
- else if (n == 's') cls += sp;
- else if (n == 'D' || n == 'W' || n == 'S') return false;
+ else if (n == 's') {
+ cls += sp;
+ if (!negated_cls) escapes.push_back("\\\\[tnfr]");
+ else excluded += "tnfr";
+ }
+ else if (n == 'D' || n == 'W' || n == 'S') { bad = n; return false; }
+ else if (!json_control_escape(n).empty()) {
+ if (n == '0' && k + 1 < body.size() && std::isdigit(static_cast<unsigned char>(body[k + 1]))) {
+ bad = n; // "\01" is a legacy octal escape
+ return false;
+ }
+ if (negated_cls) excluded += n;
+ else escapes.push_back(json_control_escape(n));
+ }
else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') {
// "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could
// read as a range or a negation, so they are written as \xHH.
- cls += "\\x";
- cls += "0123456789ABCDEF"[(n >> 4) & 0xF];
- cls += "0123456789ABCDEF"[n & 0xF];
+ cls += hex_escape(n);
}
- else { cls += '\\'; cls += n; }
+ else if (n == 'x' || n == 'u') {
+ // Copied for GBNF to read, so the hex digits must be there.
+ const size_t len = n == 'x' ? 2 : 4;
+ for (size_t h = 1; h <= len; ++h) {
+ if (k + h >= body.size() || !std::isxdigit(static_cast<unsigned char>(body[k + h]))) {
+ bad = n;
+ return false;
+ }
+ }
+ cls += '\\';
+ cls += n;
+ }
+ else if (std::string("\"[]\\").find(n) != std::string::npos) { cls += '\\'; cls += n; }
+ else if (n == ' ' || static_cast<unsigned char>(n) >= 0x80) cls += n;
+ else { bad = n; return false; }
} else {
cls += body[k];
}
}
- out += cls;
if (j < p.size()) {
- out += ']';
+ cls += ']';
+ }
+ if (negated_cls && !excluded.empty() && j < p.size()) {
+ // A string holds those characters only as escapes, so the class becomes text that is
+ // neither a listed character nor one of those escapes. Their \u forms (\u0009 for \t)
+ // are still admitted.
+ std::string letters;
+ for (char e : std::string("bfnrt")) {
+ if (excluded.find(e) == std::string::npos) letters += e;
+ }
+ out += "(?:[^" + cls.substr(2, cls.size() - 3) + raw + "]|\\\\(?:[\"\\\\/" + letters +
+ "]|u[0-9A-Fa-f]{4}))";
+ } else if (!escapes.empty() && j < p.size()) {
+ out += "(?:";
+ if (cls != "[]") out += cls + "|";
+ for (size_t e = 0; e < escapes.size(); ++e) out += (e ? "|" : "") + escapes[e];
+ out += ")";
+ } else {
+ out += cls;
}
i = j;
}
@@ -491,9 +564,10 @@ private:
std::string _visit_pattern(const std::string & client_pattern, const std::string & name) {
std::string expanded;
- if (!expand_shorthands(client_pattern, expanded)) {
- _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class "
- "cannot be spelled in GBNF");
+ char bad = 0;
+ if (!expand_shorthands(client_pattern, expanded, bad)) {
+ _errors.push_back(std::string("Unsupported regex escape '\\") + bad +
+ "' inside a character class: GBNF cannot spell it");
return "";
}
const std::string pattern = anchor_pattern(expanded);
@@ -1,17 +0,0 @@
diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp
index f81d98d..5a089d3 100644
--- a/common/jinja/runtime.cpp
+++ b/common/jinja/runtime.cpp
@@ -779,6 +779,12 @@ value member_expression::execute_impl(context & ctx) {
} else {
property = this->property->execute(ctx);
}
+ } else if (is_stmt<integer_literal>(this->property)) {
+ // syntax: obj.index
+ property = mk_val<value_int>(cast_stmt<integer_literal>(this->property)->val);
+ if (property->as_int() < 0) {
+ throw std::runtime_error("Static member property cannot be negative");
+ }
} else {
// syntax: obj.prop
if (!is_stmt<identifier>(this->property)) {
+20
View File
@@ -0,0 +1,20 @@
Copyright (c) 2018, Joao Paulo Magalhaes <dev@jpmag.me>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+47392
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
/* ryml_impl.cpp -- the one translation unit that compiles rapidyaml's implementation out of its
* single header (vendor/rapidyaml/ryml.hpp). Every other file includes the header for declarations
* only. */
#define RYML_SINGLE_HDR_DEFINE_NOW
#include <ryml.hpp>
+2 -2
View File
@@ -1,6 +1,6 @@
MIT License
MIT License
Copyright (c) 2013-2025 Niels Lohmann
Copyright (c) 2020 YaoYuan <ibireme@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+11480
View File
File diff suppressed because it is too large. Load diff
+8467
View File
File diff suppressed because it is too large. Load diff