mirror of
https://github.com/ikawrakow/ik_llama.cpp.git
synced 2026-05-24 06:35:28 +00:00
* Autoparser - complete refactoring of parser architecture Autoparser: add optional argument reshuffle capability Autoparser: True streaming (#20177) * Relax atomicity constraint for nicer, more pleasent, True Streaming parsing * Whitespace * Remove redundant atomics Revert to OAI-compatible args (#20213) * Revert to OAI-compatible args * Apply workaround::func_args_not_string Fix structured outputs (#20223) * Fix structured outputs * Update common/chat-auto-parser-generator.cpp Co-authored-by: Aldehir Rojas <hello@alde.dev> --------- Co-authored-by: Aldehir Rojas <hello@alde.dev> Fix compile bug (#20203) * Fix compile bug * Update common/chat-auto-parser-helpers.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> # Conflicts: # common/chat-auto-parser-helpers.cpp common : gracefully handle incomplete output (#20191) * common : handle incomplete UTF-8 at end of input in PEG parser * cont : if reached end prematurely, emit needs_more_input to propagate partial output * cont: refactor peg parse context to add lenient flag * cont : remove partial flag, keep lenient flag PEG parser for LFM2 (#20251) * PEG parser for LFM2 * Simplify using python_value() common: map developer role to system (#20215) * Map developer role to system * Simplify common: consolidate PEG string parsers (#20263) * common : consolidate PEG string parsers * cont : fix json_string_content() examples : fix empty items in json_schema_to_grammar.py [no ci] (#19968) * Fix logic for retrieving schema items in `json_schema_to_grammar.py` If `schema['items']` is `{}` and `prefixItems not in schema', as `{}` is Falsy, the original code here will raise an error. I think if `schema['items']` is `{}`, them items should just be `{}` * Apply suggestion from @CISC Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Add tests for arrays with empty items Add two unit tests to `tests/test-json-schema-to-grammar.cpp` that validate handling of arrays when 'items' is an empty schema and when 'prefixItems' is present alongside an empty 'items'. Both tests expect the same generated grammar, ensuring the JSON Schema->grammar conversion treats an empty 'items' schema (and the presence of 'prefixItems') correctly and covering this edge case. --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Reduce level of content parser warning message to avoid log spam on non-debug verbosity (#20347) do not return if template parse failed add arg to enable parallel tool call common : fix incorrect uses of stoul (#20313) # Conflicts: # common/arg.cpp # src/llama-grammar.cpp examples : fix empty items in json_schema_to_grammar.py [no ci] (#19968) * Fix logic for retrieving schema items in `json_schema_to_grammar.py` If `schema['items']` is `{}` and `prefixItems not in schema', as `{}` is Falsy, the original code here will raise an error. I think if `schema['items']` is `{}`, them items should just be `{}` * Apply suggestion from @CISC Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Add tests for arrays with empty items Add two unit tests to `tests/test-json-schema-to-grammar.cpp` that validate handling of arrays when 'items' is an empty schema and when 'prefixItems' is present alongside an empty 'items'. Both tests expect the same generated grammar, ensuring the JSON Schema->grammar conversion treats an empty 'items' schema (and the presence of 'prefixItems') correctly and covering this edge case. --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Add support for MiroThinker with new jinja template common/parser: handle reasoning budget (#20297) * v1 * Finished! * Handlie cli * Reasoning sampler * Apply suggestions from code review Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Less explosive terminology :) * Add utf-8 case and tests * common : migrate reasoning budget sampler to common * cont : clean up * cont : expose state and allow passing as initial state * cont : remove unused imports * cont : update state machine doc string --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Co-authored-by: Alde Rojas <hello@alde.dev> common/parser: use nlohmann::ordered_json to preserve parameter order (#20385) common/parser: add GigaChatV3/3.1 models support (#19931) Co-authored-by: Mishusha <pmv26021975@gmail.com> common/parser: gracefully handle undetected tool parser, print error message. (#20286) fix: prevent nullptr dereference (#20552) common : fix iterator::end() dereference (#20445) # Conflicts: # common/regex-partial.cpp jinja : add capability check for object args (#20612) common/parser: add `--skip-chat-parsing` to force a pure content parser. (#20289) * Add `--force-pure-content` to force a pure content parser. * Update common/arg.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : rework gpt-oss parser (#20393) * common : rework gpt-oss parser * cont : fix gpt-oss tests * cont : add structured output test * cont : rename final to final_msg common : fix gpt-oss content removal (#20745) common/parser: add proper reasoning tag prefill reading (#20424) * Implement proper prefill extraction * Refactor cli parameters, update docs, move reasoning budget sampler part to common/reasoning-budget.cpp * Update tools/server/server-task.cpp * refactor: move grammars to variant, remove grammar_external, handle exception internally * Make code less C++y Co-authored-by: Georgi Gerganov <ggerganov@gmail.com> chat : handle tool calls with no required args in TAG_WITH_TAGGED format (#20764) * chat : handle tool calls with no required args in TAG_WITH_TAGGED format * Update tests/test-chat.cpp [no ci] Co-authored-by: Aldehir Rojas <hello@alde.dev> --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> Co-authored-by: Aldehir Rojas <hello@alde.dev> common/parser : fix out_of_range crash in throw path (#20424 regression) (#20777) * chat : fix out_of_range crash in throw path (#20424 regression) #20424 introduced effective_input = generation_prompt + input, but the throw path uses input.substr(result.end) where result.end is a position within effective_input. Every thinking model with a non-empty generation_prompt crashes with std::out_of_range instead of the intended error message. Test crashes on unpatched master, passes with fix: cmake -B build -DLLAMA_BUILD_TESTS=ON -DLLAMA_BUILD_TOOLS=OFF cmake --build build --target test-chat ./build/bin/test-chat * Update test-chat.cpp * Update test-chat.cpp * Update test-chat.cpp --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> jinja : fix heap OOB read in value equality comparison (#20782) Address GHSA-q9j6-4hhc-rq9p and GHSA-2q4c-9gq5-5vfp. The three-iterator overload of std::equal in value_array_t::equivalent() and value_object_t::equivalent() reads past the end of the shorter container when comparing arrays or objects of different lengths. Use the four-iterator overload (C++14) which checks both range lengths. Found-by: Pwno common : fix typo in debug log ('extracft' -> 'extract') (#20807) common/parser: fix nasty bug causing subtle corruption of generation prompt (#20825) jinja : refactor token advancement (#20864) * refactor token advancement * exercise sub-expressions common/autoparser : detect reasoning markers when enable_thinking changes system prompt (#20859) common : replace wrap_for_generation with a prefix convenience function and fix gpt-oss (#20912) jinja: fix macro with kwargs (#20960) * jinja: fix macro with kwargs * Apply suggestions from code review Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * fix newline problem --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : inhibit lazy grammar sampler while reasoning is active (#20970) * common : inhibit grammar while reasoning budget is active * cont : update force_pos in accept * cont : fix tests * cont : tweak should apply logic * cont : return early not using grammar sampler * Add tests * cont : prevent backend sampling when reasoning budget enabled * cont : fix typo --------- Co-authored-by: Piotr Wilkin <piotr.wilkin@syndatis.com> # Conflicts: # common/reasoning-budget.h # common/sampling.cpp # tools/cli/cli.cpp # tools/server/server-common.cpp # tools/server/server-task.cpp common/parser: fix reasoning whitespace bugs + extra parser tests (#21085) * fix whitespace reasoning issues + add reconstruction tests * Proper fix * fix Nemotron autoparser test expectations to include newline in marker common : add reasoning_format = none support to gpt-oss (#21094) common/json-schema: fix: handle non-capturing groups (?:...) in JSON schema pattern converter (#21124) The regex-to-grammar converter in _visit_pattern() crashes with SIGSEGV when a JSON schema "pattern" field contains a non-capturing group (?:...). Root cause: when the parser sees '(' followed by '?', it pushes a warning but does not advance past '?:'. The recursive transform() call then interprets '?' as a quantifier and calls seq.back() on an empty vector, causing undefined behavior. This commonly occurs when serving OpenAI-compatible tool calls from clients that include complex regex patterns in their JSON schemas (e.g., date validation patterns like ^(?:(?:\d\d[2468][048]|...)-02-29|...)$). The fix: - Skip '?:' after '(' to treat non-capturing groups as regular groups - For unsupported syntax (?=, ?!, etc.), skip to matching ')' safely, handling escaped characters to avoid miscounting parenthesis depth - Adjust the ')' unbalanced-parentheses check using direct char comparisons instead of substr - Add test cases for non-capturing groups (C++ only, as the JS/Python implementations do not yet support this syntax) common/parser: fix handling of tool definition with missing properties key (#21128) jinja : handle empty expressions correctly (#20913) * Reject empty computed member expressions before returning slices[0] from parse_member_expression_arguments(). * Treat empty computed member expressions with Jinja2 undefined semantics Treat empty computed member expressions like `a[]` as undefined instead of raising a parser error, to match Jinja2 behavior. - return a noop expression for empty computed member arguments - return undefined when a computed member key evaluates to undefined - add Jinja tests covering `a[]|default('fallback')` and `a[] is undefined` * Handle undefined computed member properties Move undefined-property handling to the common member access path, and add a test covering `a[undefined] is undefined`. * Use default undefined value in member access Initialize val and then return it when property is undefined. Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * empty statement parses to blank_expression instead of noop_statement --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : gpt-oss handle builtin and unsolicited tool calls (#21213) fix: tool call parsing for LFM2 and LFM2.5 models (#21242) * fix: tool call parsing for LFM2 and LFM2.5 models' * refactor: add test / break out lfm2 and lfm2.5 parsing logic # Conflicts: # common/chat.cpp Relax prefill parser to allow space. (#21240) * Relax prefill parser to allow space. * Move changes from prefix() to parser generation * Only allow spaces if we're not having a pure content parser next common : add commentary rules for gpt-oss-20b (#21286) add reasoning budget model, mtmd: fix gguf conversion for audio/vision mmproj (#21309) * fix gguf conversion for audio/vision mmproj * fix test # Conflicts: # convert_hf_to_gguf.py # examples/eval-callback/eval-callback.cpp # examples/mtmd/CMakeLists.txt # examples/mtmd/clip-impl.h # examples/mtmd/mtmd.cpp # gguf-py/gguf/constants.py # gguf-py/gguf/gguf_writer.py # gguf-py/gguf/tensor_mapping.py # src/CMakeLists.txt # src/llama-arch.cpp # src/llama-arch.h # src/llama-model.cpp # src/llama-model.h # src/llama-vocab.cpp # src/models/models.h # tests/test-llama-archs.cpp # tools/mtmd/clip-graph.h # tools/mtmd/clip-model.h # tools/mtmd/clip.cpp # tools/mtmd/models/models.h fix: gemma 4 template (#21326) chat : avoid including json in chat.h (#21306) jinja: coerce input for string-specific filters (#21370) common : fix tool call type detection for nullable and enum schemas (#21327) * common : fix tool call type detection for nullable and enum schemas * common, tests : fix grammar delegation for nullable/enum schemas and add tests Fix enum type inference to scan all enum values (not just index 0) so schemas like {"enum": [0, "celsius"]} correctly detect string type. Fix schema_delegates in peg-parser to handle nullable type arrays (["string", "null"]) and typeless enum schemas in raw mode, allowing the tagged parser to use raw text instead of JSON-formatted strings. Add test cases for Qwen3-Coder (TAG_WITH_TAGGED format): - nullable string ["string", "null"] - nullable string with null first ["null", "string"] - nullable integer ["integer", "null"] - enum without explicit type key common/parser: fix call ID detection (Mistral parser mostly) + atomicity for tag-json parsers (#21230) * Fix call ID detection (Mistral parser mostly) + atomicity for tag-json parsers * Rename * Update common/chat-auto-parser-generator.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : add gemma 4 specialized parser (#21418) * common : add gemma4 dedicated parser * cont : add '<|tool_response>' as eog * cont : emit JSON from Gemma4 tool call AST * cont : more fixes * cont : refactor convert function * cont : refine rules and mapping * cont : add more tests * cont : clean up * cont : remove autoparser gemma4 implementation * cont : more cleanup * cont : rename gemma4.jinja to match the others * cont : add custom template to support interleaved thinking * cont : preserve reasoning in model turns * cont : fix initializer error * cont : fix unused vars * cont : fix accidental static * cont : fix specialized_template signature * fix extra semicolon * remove debug line and extra space [no ci] fix reasoning budget parser: fix MiniMax handling (#21573) jinja : support ensure_ascii=true, string repetition and int/float self-filtering (#21623) * feat: jinja engine improvements for reka-edge Port three Jinja engine improvements needed for the reka-edge model: 1. Python-style string repetition ("ab" * 3 → "ababab") 2. ensure_ascii=true support for tojson filter (escapes non-ASCII to \uXXXX) 3. int() builtin on value_int_t (identity, needed for Reka Edge template) * fix: escape invalid utf8 bytes when ensure_ascii=true The json_ensure_ascii_preserving_format function does not correctly handle an edge case where if UTF-8 parsing fails, it adds the non-ascii character back to the output as a raw byte. This commit fixes that by adding the unicode standard replacement character \\ufffd to the output instead. This is the standard behavior for various programming languages like Python, Rust, Go, etc. * chore: address PR comments 1. Add todo comment for supporting string repetition for array/tuples 2. Add support for float identity operation 3. Move invalid ascii test case to test_fuzzing * chore: accept suggestion for common/jinja/value.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : simplify autoparser tagged parser rules (#21216) * common : simplify autoparser tagged parser rules * cont : remove upper limit on optional args * cont : revert changes to parsing at the end * cont : undo arbitrary ordering of optional args * cont : fix uninitialized required parameters * revert to simplify merge * re-apply patches * restore flexible optional arg ordering tests common : fix ambiguous grammar rule in gemma4 (#21661) * common : fix ambiguous grammar rule in gemma4 * cont : fix missing comma... common : enable reasoning budget sampler for gemma4 (#21697) * fix: enable reasoning budget sampler for gemma4 Add thinking_start_tag and thinking_end_tag to common_chat_params_init_gemma4(). Without these, the reasoning budget sampler never activates for gemma4. Make the newline after "thought" optional in the PEG parser to handle budget=0 (sampler forces end tag before the newline). Add test case for empty thinking block. Fixes #21487 * use p.space() instead of p.optional(p.literal("\n")) in gemma4 thought parser common : better align to the updated official gemma4 template (#21704) fix: Fix broken structured output when using $refs in json_schema (#21699) chat: dedicated DeepSeek v3.2 parser + "official" template (#21785) Hide render_message_to_json warning common/gemma4 : handle parsing edge cases (#21760) common: skip reasoning budget sampler when no budget is requested (#21870) * common: skip reasoning budget sampler when no budget is requested After I added thinking_start_tag / thinking_end_tag for gemma4 in #21697, the reasoning budget sampler gets unconditionally created even when no budget is configured (the default -1). The same applies to kimi_k2, lfm2, lfm2_5, and ministral_3 which also set these tags. The budget gets converted to INT_MAX, so the sampler never actually forces any tokens but still runs per-token checks (start tag matching in IDLE state, token-to-piece conversion + UTF-8 checks in COUNTING state). More importantly, the mere existence of the sampler (non-null rbudget) disables backend sampling. Backend sampling lets the GPU select tokens directly, avoiding a full logits transfer from GPU to CPU every token. This could explain the 30% speed regression reported in #21784 (98 t/s to 70 t/s on Vulkan). So I added a reasoning_budget_tokens >= 0 check to the sampler creation condition. When the budget is unlimited, the sampler is not created, backend sampling stays enabled, and no per-token overhead is added. When a budget is explicitly set (0, 128, 1024, etc.), the sampler is created and works as before. * common: preserve rbudget when grammar is lazy Following up on the review feedback on #21870: keep the reasoning budget sampler when grammar_lazy is true, so the thinking-block grammar suppression from #20970 still works when tools are in use. This way, we only skip the sampler when both no budget is set AND grammar is not lazy. autoparser: support case of JSON_NATIVE with per-call markers (test case: Reka-Edge) (#21892) * fix grammar * fix add sampled token --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> Co-authored-by: firecoperana <firecoperana>
984 lines
43 KiB
C++
984 lines
43 KiB
C++
#include "chat-peg-parser.h"
|
|
#include "chat.h"
|
|
#include "common.h"
|
|
#include "json-schema-to-grammar.h"
|
|
#include "peg-parser.h"
|
|
#include "testing.h"
|
|
#include "peg-parser/simple-tokenize.h"
|
|
|
|
#include <iostream>
|
|
#include <numeric>
|
|
#include <string>
|
|
|
|
#include "nlohmann/json.hpp"
|
|
|
|
using json = nlohmann::ordered_json;
|
|
|
|
static json create_tools();
|
|
static void test_example_native(testing & t);
|
|
static void test_example_qwen3_coder(testing & t);
|
|
static void test_example_qwen3_non_coder(testing & t);
|
|
static void test_command7_parser_compare(testing & t);
|
|
static void test_prefix_tool_names(testing & t);
|
|
static void test_tagged_peg_parser(testing & t);
|
|
|
|
int main(int argc, char * argv[]) {
|
|
testing t(std::cout);
|
|
if (argc >= 2) {
|
|
t.set_filter(argv[1]);
|
|
}
|
|
|
|
const char * verbose = getenv("LLAMA_TEST_VERBOSE");
|
|
if (verbose) {
|
|
t.verbose = std::string(verbose) == "1";
|
|
}
|
|
|
|
t.test("native", test_example_native);
|
|
t.test("qwen3 coder", test_example_qwen3_coder);
|
|
t.test("qwen3 non-coder", test_example_qwen3_non_coder);
|
|
t.test("comparison", test_command7_parser_compare);
|
|
t.test("prefix tool names", test_prefix_tool_names);
|
|
t.test("tagged peg parser", test_tagged_peg_parser);
|
|
|
|
return t.summary();
|
|
}
|
|
|
|
static json create_tools() {
|
|
json tools = json::array();
|
|
|
|
json tool_weather = {
|
|
{ "type", "function" },
|
|
{ "function",
|
|
{
|
|
{ "name", "get_current_weather" },
|
|
{ "description", "Get the current weather in a given location" },
|
|
{ "parameters",
|
|
{
|
|
{ "type", "object" },
|
|
{ "properties",
|
|
{ { "location",
|
|
{ { "type", "string" }, { "description", "The city and state, e.g. San Francisco, CA" } } },
|
|
{ "unit",
|
|
{ { "type", "string" },
|
|
{ "enum", { "celsius", "fahrenheit" } },
|
|
{ "description",
|
|
"The temperature unit to use. Infer this from the users location." } } } } },
|
|
{ "required", { "location", "unit" } },
|
|
} },
|
|
} }
|
|
};
|
|
tools.push_back(tool_weather);
|
|
|
|
json tool_forecast = {
|
|
{ "type", "function" },
|
|
{ "function",
|
|
{
|
|
{ "name", "get_forecast" },
|
|
{ "description", "Get the weather forecast for a given location" },
|
|
{ "parameters",
|
|
{
|
|
{ "type", "object" },
|
|
{ "properties",
|
|
{ { "location",
|
|
{ { "type", "string" }, { "description", "The city and state, e.g. San Francisco, CA" } } },
|
|
{ "unit",
|
|
{ { "type", "string" },
|
|
{ "enum", { "celsius", "fahrenheit" } },
|
|
{ "description", "The temperature unit to use. Infer this from the users location." } } },
|
|
{ "days",
|
|
{ { "type", "integer" },
|
|
{ "description", "Number of days to forecast (1-10)" },
|
|
{ "minimum", 1 },
|
|
{ "maximum", 10 } } } } },
|
|
{ "required", { "location", "unit" } },
|
|
} },
|
|
} }
|
|
};
|
|
tools.push_back(tool_forecast);
|
|
|
|
json tool_search = {
|
|
{ "type", "function" },
|
|
{ "function",
|
|
{ { "name", "search_knowledge_base" },
|
|
{ "description", "Search the internal technical documentation knowledge base." },
|
|
{ "parameters",
|
|
{ { "type", "object" },
|
|
{ "properties",
|
|
{ { "query", { { "type", "string" }, { "description", "The search query string." } } },
|
|
{ "max_results",
|
|
{ { "type", "integer" },
|
|
{ "description", "The maximum number of results to return." },
|
|
{ "default", 5 } } },
|
|
{ "category",
|
|
{ { "type", "string" },
|
|
{ "enum", { "api", "troubleshooting", "billing", "general" } },
|
|
{ "description", "Filter search by specific category." } } } } },
|
|
{ "required", { "query", "category" } },
|
|
{ "additionalProperties", false } } },
|
|
{ "strict", true } } }
|
|
};
|
|
tools.push_back(tool_search);
|
|
|
|
return tools;
|
|
}
|
|
|
|
struct tool_argument {
|
|
std::string name;
|
|
std::string type;
|
|
bool is_required;
|
|
json schema;
|
|
};
|
|
|
|
struct tool_definition {
|
|
std::string name;
|
|
std::vector<tool_argument> arguments;
|
|
json schema;
|
|
};
|
|
|
|
// Test fictitious model output that emits arguments as JSON.
|
|
static void test_example_native(testing & t) {
|
|
struct test_case {
|
|
// Parameters
|
|
std::string name;
|
|
json tools;
|
|
common_chat_tool_choice tool_choice;
|
|
common_reasoning_format reasoning_format;
|
|
json json_schema;
|
|
bool parallel_tool_calls;
|
|
std::string generation_prompt;
|
|
std::string input;
|
|
|
|
// Expect
|
|
std::string expect_reasoning;
|
|
std::string expect_content;
|
|
std::vector<common_chat_tool_call> expect_tool_calls;
|
|
};
|
|
|
|
auto build_parser = [](const test_case & tc) {
|
|
return build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
|
auto reasoning_in_content = (tc.reasoning_format == COMMON_REASONING_FORMAT_NONE);
|
|
// Always use optional TAG_BASED pattern; generation_prompt is prepended to input
|
|
auto reasoning = p.optional("<think>" + p.reasoning(p.until("</think>")) + "</think>" + p.space());
|
|
|
|
// tool calling parser
|
|
if (tc.tools.is_array() && !tc.tools.empty()) {
|
|
auto tool_call =
|
|
p.standard_json_tools("<tool_call>[", "]</tool_call>", tc.tools, tc.parallel_tool_calls,
|
|
tc.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED);
|
|
|
|
return p.sequence({ (reasoning_in_content ? p.eps() : reasoning), p.content(p.until("<tool_call>")),
|
|
p.optional(p.space() + tool_call), p.space(), p.end() });
|
|
}
|
|
|
|
// response_format parser
|
|
if (tc.json_schema.is_object() && !tc.json_schema.empty()) {
|
|
return p.sequence({ (reasoning_in_content ? p.eps() : reasoning),
|
|
p.content(p.schema(p.json(), "response-output", tc.json_schema)), p.space(),
|
|
p.end() });
|
|
}
|
|
|
|
// Content-only parser
|
|
return p.sequence({ (reasoning_in_content ? p.eps() : reasoning), p.content(p.rest()), p.end() });
|
|
});
|
|
};
|
|
|
|
std::vector<test_case> test_cases = std::vector<test_case>{
|
|
{
|
|
/* .name = */ "content with reasoning (no generation_prompt)",
|
|
/* .tools = */ {},
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_NONE,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "",
|
|
/* .input = */ ("<think>The user said hello, I must say hello back</think>\nHello"),
|
|
/* .expect_reasoning = */ "The user said hello, I must say hello back",
|
|
/* .expect_content = */ "Hello",
|
|
/* .expect_tool_calls = */ {},
|
|
},
|
|
{
|
|
/* .name = */ "content without reasoning (no generation_prompt)",
|
|
/* .tools = */ {},
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_NONE,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "",
|
|
/* .input = */ ("Hello"),
|
|
/* .expect_reasoning = */ "",
|
|
/* .expect_content = */ "Hello",
|
|
/* .expect_tool_calls = */ {},
|
|
},
|
|
{
|
|
/* .name = */ "content with reasoning_format = none (tags appear in content)",
|
|
/* .tools = */ {},
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_NONE,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "",
|
|
/* .input = */ ("<think>The user said hello, I must say hello back</think>\nHello"),
|
|
/* .expect_reasoning = */ "",
|
|
/* .expect_content = */ "<think>The user said hello, I must say hello back</think>\nHello",
|
|
/* .expect_tool_calls = */ {},
|
|
},
|
|
{
|
|
/* .name = */ "content with reasoning generation_prompt",
|
|
/* .tools = */ {},
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_NONE,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "<think>",
|
|
/* .input = */ ("The user said hello, I must say hello back</think>\nHello"),
|
|
/* .expect_reasoning = */ "The user said hello, I must say hello back",
|
|
/* .expect_content = */ "Hello",
|
|
/* .expect_tool_calls = */ {},
|
|
},
|
|
{
|
|
/* .name = */ "content with reasoning generation_prompt and reasoning_format = none",
|
|
/* .tools = */ {},
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_NONE,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "",
|
|
/* .input = */ ("The user said hello, I must say hello back</think>\nHello"),
|
|
/* .expect_reasoning = */ "",
|
|
/* .expect_content = */ "The user said hello, I must say hello back</think>\nHello",
|
|
/* .expect_tool_calls = */ {},
|
|
},
|
|
{
|
|
/* .name = */ "content with closed reasoning generation_prompt (empty reasoning discarded)",
|
|
/* .tools = */ {},
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_NONE,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "<think></think>",
|
|
/* .input = */ ("Hello"),
|
|
/* .expect_reasoning = */ "",
|
|
/* .expect_content = */ "Hello",
|
|
/* .expect_tool_calls = */ {},
|
|
},
|
|
{
|
|
/* .name = */ "tools with reasoning generation_prompt",
|
|
/* .tools = */ create_tools(),
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_AUTO,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "<think>",
|
|
/* .input = */
|
|
("I must get the weather in New York</think>\n"
|
|
"<tool_call>["
|
|
R"({"name": "get_current_weather", "arguments": {"location": "New York City, NY", "unit": "fahrenheit"}})"
|
|
"]</tool_call>"),
|
|
/* .expect_reasoning = */ "I must get the weather in New York",
|
|
/* .expect_content = */ "",
|
|
/* .expect_tool_calls = */
|
|
{ {
|
|
/* .name = */ "get_current_weather",
|
|
/* .arguments = */ R"({"location": "New York City, NY", "unit": "fahrenheit"})",
|
|
/* .id = */ "",
|
|
} },
|
|
},
|
|
{
|
|
/* .name = */ "parallel tools with reasoning generation_prompt",
|
|
/* .tools = */ create_tools(),
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_AUTO,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
|
|
/* .json_schema = */ {},
|
|
/* .parallel_tool_calls = */ true,
|
|
/* .generation_prompt = */ "<think>",
|
|
/* .input = */
|
|
("I must get the weather in New York and San Francisco and a 3 day forecast of each.</think>\nLet me "
|
|
"search that for you."
|
|
"<tool_call>["
|
|
R"({"name": "get_current_weather", "arguments": {"location": "New York City, NY", "unit": "fahrenheit"}})"
|
|
", "
|
|
R"({"name": "get_current_weather", "arguments": {"location": "San Francisco, CA", "unit": "fahrenheit"}})"
|
|
", "
|
|
R"({"name": "get_forecast", "arguments": {"location": "New York City, NY", "unit": "fahrenheit", "days": 3}})"
|
|
", "
|
|
R"({"name": "get_forecast", "arguments": {"location": "San Francisco, CA", "unit": "fahrenheit", "days": 3}})"
|
|
"]</tool_call>"),
|
|
/* .expect_reasoning = */
|
|
"I must get the weather in New York and San Francisco and a 3 day forecast of each.", /* .expect_content = */ "Let me search that for you.",
|
|
/* .expect_tool_calls = */
|
|
{ {
|
|
/* .name = */ "get_current_weather",
|
|
/* .arguments = */ R"({"location": "New York City, NY", "unit": "fahrenheit"})",
|
|
/* .id = */ "",
|
|
},
|
|
{
|
|
/* .name = */ "get_current_weather",
|
|
/* .arguments = */ R"({"location": "San Francisco, CA", "unit": "fahrenheit"})",
|
|
/* .id = */ "",
|
|
},
|
|
{
|
|
/* .name = */ "get_forecast",
|
|
/* .arguments = */ R"({"location": "New York City, NY", "unit": "fahrenheit", "days": 3})",
|
|
/* .id = */ "",
|
|
},
|
|
{
|
|
/* .name = */ "get_forecast",
|
|
/* .arguments = */ R"({"location": "San Francisco, CA", "unit": "fahrenheit", "days": 3})",
|
|
/* .id = */ "",
|
|
} },
|
|
},
|
|
{
|
|
/* .name = */ "response_format with reasoning generation_prompt",
|
|
/* .tools = */ {},
|
|
/* .tool_choice = */ COMMON_CHAT_TOOL_CHOICE_NONE,
|
|
/* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
|
|
/* .json_schema = */
|
|
{ { "type", "object" },
|
|
{ "properties",
|
|
{ { "invoice_number", { { "type", "string" } } },
|
|
{ "amount", { { "type", "number" } } },
|
|
{ "due_date", { { "type", "string" } } } } },
|
|
{ "required", { "invoice_number", "amount", "due_date" } } },
|
|
/* .parallel_tool_calls = */ false,
|
|
/* .generation_prompt = */ "<think>",
|
|
/* .input = */
|
|
("I must produce the invoice in the requested format</think>\n"
|
|
R"({"invoice_number": "INV-2025-001", "amount": 1250.50, "due_date": "2025-12-31"})"),
|
|
/* .expect_reasoning = */ "I must produce the invoice in the requested format",
|
|
/* .expect_content = */
|
|
R"({"invoice_number": "INV-2025-001", "amount": 1250.50, "due_date": "2025-12-31"})", /* .expect_tool_calls = */ {},
|
|
},
|
|
};
|
|
|
|
for (const auto & tc : test_cases) {
|
|
t.test(tc.name, [&](testing & t) {
|
|
auto parser = build_parser(tc);
|
|
auto lazy = !tc.tools.empty() && tc.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
|
|
auto grammar = build_grammar([&](const common_grammar_builder & builder) {
|
|
for (const auto & def : tc.tools) {
|
|
auto function = def.at("function");
|
|
auto parameters = function.at("parameters");
|
|
builder.resolve_refs(parameters);
|
|
};
|
|
parser.build_grammar(builder, lazy);
|
|
});
|
|
|
|
t.log("Grammar:");
|
|
for (const auto & line : string_split(grammar, "\n")) {
|
|
t.log(line);
|
|
}
|
|
|
|
std::string effective_input = tc.generation_prompt + tc.input;
|
|
common_peg_parse_context ctx(effective_input);
|
|
auto result = parser.parse(ctx);
|
|
|
|
t.assert_true("success", result.success());
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
t.assert_equal("content equal", tc.expect_content, msg.content);
|
|
t.assert_equal("reasoning equal", tc.expect_reasoning, msg.reasoning_content);
|
|
t.assert_equal("number of tool calls", tc.expect_tool_calls.size(), msg.tool_calls.size());
|
|
for (auto i = 0u; i < std::min(tc.expect_tool_calls.size(), msg.tool_calls.size()); i++) {
|
|
t.assert_equal("tool name", tc.expect_tool_calls[i].name, msg.tool_calls[i].name);
|
|
t.assert_equal("tool args", tc.expect_tool_calls[i].arguments, msg.tool_calls[i].arguments);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
static void test_example_qwen3_coder(testing & t) {
|
|
auto tools = create_tools();
|
|
auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
|
auto content = p.rule("content", p.content(p.until("<tool_call>")));
|
|
|
|
std::vector<common_peg_parser> tool_parsers;
|
|
for (const auto & def : tools) {
|
|
auto function = def.at("function");
|
|
std::string name = function.at("name");
|
|
auto parameters = function.at("parameters");
|
|
auto properties = parameters.at("properties");
|
|
|
|
std::set<std::string> required_properties;
|
|
if (function.contains("required")) {
|
|
function.at("required").get_to(required_properties);
|
|
}
|
|
|
|
std::vector<common_peg_parser> arg_parsers;
|
|
for (const auto & [param_name, param_schema] : properties.items()) {
|
|
bool is_required = required_properties.find(param_name) != required_properties.end();
|
|
auto type = param_schema.value("type", "object");
|
|
|
|
auto arg = p.tool_arg(
|
|
p.sequence({ p.tool_arg_open("<parameter=" + p.tool_arg_name(p.literal(param_name)) + ">"),
|
|
(type == "string" ?
|
|
p.tool_arg_string_value(p.schema(
|
|
p.until_one_of({ "</parameter>\n<parameter=", "</parameter>\n</function>" }),
|
|
"tool-" + name + "-arg-" + param_name + "-schema", param_schema, true)) :
|
|
p.tool_arg_json_value(p.schema(
|
|
p.json(), "tool-" + name + "-arg-" + param_name + "-schema", param_schema))),
|
|
p.tool_arg_close("</parameter>\n" +
|
|
p.peek(p.literal("<parameter=") | p.literal("</function>"))) }));
|
|
|
|
arg_parsers.push_back(is_required ? p.rule("tool-" + name + "-arg-" + param_name, arg) :
|
|
p.optional(p.rule("tool-" + name + "-arg-" + param_name, arg)));
|
|
}
|
|
|
|
tool_parsers.push_back(p.rule("tool-" + name, p.tool_open("<function=" + p.tool_name(p.literal(name)) + ">")
|
|
<< p.sequence(arg_parsers)
|
|
<< p.tool_close(p.literal("</function>"))));
|
|
};
|
|
|
|
auto tool_call = p.trigger_rule("tool-call", "<tool_call>" << p.choice(tool_parsers) << "</tool_call>");
|
|
|
|
return content + p.zero_or_more(p.space() + tool_call) + p.end();
|
|
});
|
|
|
|
auto grammar = build_grammar([&](const common_grammar_builder & builder) {
|
|
for (const auto & def : tools) {
|
|
auto function = def.at("function");
|
|
auto parameters = function.at("parameters");
|
|
builder.resolve_refs(parameters);
|
|
};
|
|
parser.build_grammar(builder);
|
|
});
|
|
|
|
t.log("Grammar:");
|
|
for (const auto & line : string_split(grammar, "\n")) {
|
|
t.log(line);
|
|
}
|
|
|
|
t.test("incremental parsing", [&](testing & t) {
|
|
std::string input =
|
|
"Let me search the knowledge base for cat pictures."
|
|
"<tool_call>\n"
|
|
"<function=search_knowledge_base>\n"
|
|
"<parameter=query>cat pictures</parameter>\n"
|
|
"<parameter=category>general</parameter>\n"
|
|
"</function>\n"
|
|
"</tool_call>";
|
|
|
|
std::vector<std::string> tokens = simple_tokenize(input);
|
|
|
|
common_chat_msg prev;
|
|
for (auto it = tokens.begin(); it != tokens.end(); it++) {
|
|
std::string in = std::accumulate(tokens.begin(), it + 1, std::string());
|
|
|
|
common_peg_parse_context ctx(in, (it + 1 < tokens.end()) ? COMMON_PEG_PARSE_FLAG_LENIENT : COMMON_PEG_PARSE_FLAG_NONE);
|
|
|
|
auto result = parser.parse(ctx);
|
|
if (!t.assert_equal("not fail", false, result.fail())) {
|
|
t.log(in.substr(0, result.end) + "[failed->]" + in.substr(result.end));
|
|
}
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
//t.log("Input: " + input);
|
|
t.log("===========================================");
|
|
t.log("Iteration " + std::to_string(in.size()));
|
|
t.log("Reasoning: " + msg.reasoning_content);
|
|
t.log("Content : " + msg.content);
|
|
for (const auto & tc : msg.tool_calls) {
|
|
t.log("Tool name: " + tc.name);
|
|
t.log("Tool args: " + tc.arguments);
|
|
}
|
|
|
|
try {
|
|
// This shouldn't emit any runtime errors
|
|
auto diffs = common_chat_msg_diff::compute_diffs(prev, msg);
|
|
} catch (const std::exception & e) {
|
|
t.log(in.substr(0, result.end) + "[failed->]" + in.substr(result.end));
|
|
t.assert_true(std::string("failed with ") + e.what(), false);
|
|
}
|
|
|
|
prev = msg;
|
|
}
|
|
});
|
|
}
|
|
|
|
static void test_example_qwen3_non_coder(testing & t) {
|
|
auto tools = create_tools();
|
|
auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
|
// tool calling parser using standard JSON format
|
|
auto tool_call = p.standard_json_tools("<tool_call>", "</tool_call>", tools, true, false);
|
|
|
|
return p.sequence({ p.content(p.until("<tool_call>")), p.optional(p.space() + tool_call), p.end() });
|
|
});
|
|
|
|
auto grammar = build_grammar([&](const common_grammar_builder & builder) {
|
|
for (const auto & def : tools) {
|
|
auto function = def.at("function");
|
|
auto parameters = function.at("parameters");
|
|
builder.resolve_refs(parameters);
|
|
};
|
|
parser.build_grammar(builder);
|
|
});
|
|
|
|
t.log("Grammar:");
|
|
for (const auto & line : string_split(grammar, "\n")) {
|
|
t.log(line);
|
|
}
|
|
|
|
t.test("tool call parsing", [&](testing & t) {
|
|
std::string input =
|
|
"I need to get the weather.\n"
|
|
"<tool_call>"
|
|
"{\"name\": \"get_current_weather\", \"arguments\": {\"location\": \"New York City, NY\", \"unit\": "
|
|
"\"fahrenheit\"}}"
|
|
"</tool_call>";
|
|
|
|
common_peg_parse_context ctx(input);
|
|
auto result = parser.parse(ctx);
|
|
|
|
t.assert_true("success", result.success());
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
t.assert_equal("content", "I need to get the weather.\n", msg.content);
|
|
t.assert_equal("reasoning", "", msg.reasoning_content);
|
|
t.assert_equal("tool calls count", 1u, msg.tool_calls.size());
|
|
if (!msg.tool_calls.empty()) {
|
|
t.assert_equal("tool name", "get_current_weather", msg.tool_calls[0].name);
|
|
t.assert_equal("tool args", "{\"location\": \"New York City, NY\", \"unit\": \"fahrenheit\"}",
|
|
msg.tool_calls[0].arguments);
|
|
}
|
|
});
|
|
|
|
t.test("incremental parsing", [&](testing & t) {
|
|
std::string input =
|
|
"I need to get the weather.\n"
|
|
"<tool_call>"
|
|
"{\"name\": \"get_current_weather\", \"arguments\": {\"location\": \"New York City, NY\", \"unit\": "
|
|
"\"fahrenheit\"}}"
|
|
"</tool_call>";
|
|
|
|
std::vector<std::string> tokens = simple_tokenize(input);
|
|
|
|
common_chat_msg prev;
|
|
for (auto it = tokens.begin(); it != tokens.end(); it++) {
|
|
std::string in = std::accumulate(tokens.begin(), it + 1, std::string());
|
|
|
|
common_peg_parse_context ctx(in, (it + 1 < tokens.end()) ? COMMON_PEG_PARSE_FLAG_LENIENT : COMMON_PEG_PARSE_FLAG_NONE);
|
|
|
|
auto result = parser.parse(ctx);
|
|
if (!t.assert_equal("not fail", false, result.fail())) {
|
|
t.log(in.substr(0, result.end) + "[failed->]" + in.substr(result.end));
|
|
}
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
//t.log("Input: " + input);
|
|
t.log("===========================================");
|
|
t.log("Iteration " + std::to_string(in.size()));
|
|
t.log("Reasoning: " + msg.reasoning_content);
|
|
t.log("Content : " + msg.content);
|
|
for (const auto & tc : msg.tool_calls) {
|
|
t.log("Tool name: " + tc.name);
|
|
t.log("Tool args: " + tc.arguments);
|
|
}
|
|
|
|
try {
|
|
// This shouldn't emit any runtime errors
|
|
auto diffs = common_chat_msg_diff::compute_diffs(prev, msg);
|
|
} catch (const std::exception & e) {
|
|
t.log(in.substr(0, result.end) + "[failed->]" + in.substr(result.end));
|
|
t.assert_true(std::string("failed with ") + e.what(), false);
|
|
}
|
|
|
|
prev = msg;
|
|
}
|
|
});
|
|
}
|
|
|
|
void test_command7_parser_compare(testing & t) {
|
|
auto parser = build_chat_peg_parser([](common_chat_peg_builder & p) {
|
|
auto thinking =
|
|
p.reasoning_block("<|START_THINKING|>" << p.reasoning(p.until("<|END_THINKING|>")) << "<|END_THINKING|>");
|
|
|
|
auto response = "<|START_RESPONSE|>" << p.content(p.until("<|END_RESPONSE|>")) << "<|END_RESPONSE|>";
|
|
|
|
auto tool_call_id = p.atomic("\"tool_call_id\"" << (":" << ("\"" + p.tool_id(p.string_content('"')) + "\"")));
|
|
auto tool_call_name =
|
|
p.atomic("\"tool_name\"" << (":" << ("\"" + p.tool_name(p.string_content('"')) + "\"")));
|
|
auto tool_call_args = "\"parameters\"" << (":" << p.tool_args(p.json()));
|
|
|
|
auto tool_call_fields = p.rule("tool-call-fields", tool_call_id | tool_call_name | tool_call_args);
|
|
auto tool_call =
|
|
p.rule("tool-call", p.tool(p.tool_open(p.literal("{"))
|
|
<< tool_call_fields << p.zero_or_more(p.literal(",") << tool_call_fields)
|
|
<< p.tool_close(p.literal("}"))));
|
|
|
|
auto tool_calls = p.rule(
|
|
"tool-calls", "<|START_ACTION|>" << ("[" << tool_call << p.zero_or_more(p.literal(",") << tool_call) << "]")
|
|
<< "<|END_ACTION|>");
|
|
|
|
return p.optional(thinking) << (tool_calls | response) + p.end();
|
|
});
|
|
|
|
auto test_current = [&](const common_peg_arena & p, const std::string & input, bool is_partial,
|
|
bool print_results) {
|
|
common_peg_parse_context ctx(input, is_partial ? COMMON_PEG_PARSE_FLAG_LENIENT : COMMON_PEG_PARSE_FLAG_NONE);
|
|
auto result = p.parse(ctx);
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
if (print_results) {
|
|
std::cout << "== Parsed (new) ==\n";
|
|
std::cout << "=== Reasoning ===\n";
|
|
std::cout << msg.reasoning_content << "\n";
|
|
std::cout << "\n\n=== Content ===\n";
|
|
std::cout << msg.content << "\n";
|
|
std::cout << "\n\n=== Tool Calls ===\n";
|
|
for (const auto & tc : msg.tool_calls) {
|
|
std::cout << "id: " << tc.id << "\n";
|
|
std::cout << "name: " << tc.name << "\n";
|
|
std::cout << "args: " << tc.arguments << "\n";
|
|
}
|
|
}
|
|
};
|
|
|
|
std::string reasoning =
|
|
"To plan an effective trip to Japan that includes both historical sites and modern attractions within a "
|
|
"budget of $4000 for a two-week stay, we need to:\n\n"
|
|
"1. Identify key historical sites and modern attractions in Japan.\n"
|
|
"2. Find affordable accommodation options that provide a balance between comfort and cost.\n"
|
|
"3. Determine the best modes of transportation for getting around Japan.\n"
|
|
"4. Create a day-by-day itinerary that ensures the user gets to see a variety of attractions without "
|
|
"overspending.\n"
|
|
"5. Provide a detailed cost breakdown that includes accommodation, transportation, meals, and entry fees "
|
|
"to attractions.";
|
|
|
|
std::vector<std::tuple<std::string, std::string, nlohmann::json>> tool_calls = {
|
|
{ "call_0", "plan_trip", nlohmann::json::parse(R"({
|
|
"destination": "Japan",
|
|
"duration": 14,
|
|
"budget": 4000,
|
|
"interests": ["historical sites", "modern attractions"],
|
|
"accommodation_preferences": "affordable",
|
|
"transportation_preferences": "efficient",
|
|
"meal_preferences": "local cuisine"
|
|
})") }
|
|
};
|
|
|
|
std::vector<std::string> tokens;
|
|
|
|
// Build tokens
|
|
if (!reasoning.empty()) {
|
|
auto tokenized = simple_tokenize(reasoning);
|
|
tokens.emplace_back("<|START_THINKING|>");
|
|
tokens.insert(tokens.end(), tokenized.begin(), tokenized.end());
|
|
tokens.emplace_back("<|END_THINKING|>");
|
|
}
|
|
|
|
if (!tool_calls.empty()) {
|
|
tokens.emplace_back("<|START_ACTION|>");
|
|
|
|
auto json = nlohmann::json::array();
|
|
for (const auto & tc : tool_calls) {
|
|
auto tc_json = nlohmann::json::object();
|
|
tc_json["tool_call_id"] = std::get<0>(tc);
|
|
tc_json["tool_name"] = std::get<1>(tc);
|
|
tc_json["parameters"] = std::get<2>(tc);
|
|
json.push_back(tc_json);
|
|
}
|
|
|
|
auto tokenized = simple_tokenize(json.dump(-1, ' ', true));
|
|
tokens.insert(tokens.end(), tokenized.begin(), tokenized.end());
|
|
|
|
tokens.emplace_back("<|END_ACTION|>");
|
|
}
|
|
|
|
std::string input = std::accumulate(tokens.begin(), tokens.end(), std::string());
|
|
|
|
t.test("current_parse", [&](testing & /* t */) { test_current(parser, input, false, false); });
|
|
t.bench("current_parse_benchmark complete", [&]() { test_current(parser, input, false, false); }, 100);
|
|
t.bench(
|
|
"current_parse_benchmark incremental",
|
|
[&]() {
|
|
std::string in;
|
|
for (auto i = 0u; i < tokens.size(); i++) {
|
|
in += tokens[i];
|
|
test_current(parser, in, i + 1 < tokens.size(), false);
|
|
}
|
|
},
|
|
20);
|
|
}
|
|
|
|
// Test that tool names that are proper prefixes of other tool names don't cause
|
|
// premature matching during incremental parsing.
|
|
// For example, "special_function" should not match when parsing "special_function_with_opt".
|
|
static void test_prefix_tool_names(testing & t) {
|
|
// Create tools where one name is a proper prefix of another
|
|
json tools = json::array();
|
|
|
|
json tool_short = {
|
|
{ "type", "function" },
|
|
{ "function",
|
|
{
|
|
{ "name", "special_function" },
|
|
{ "description", "A special function" },
|
|
{ "parameters",
|
|
{
|
|
{ "type", "object" },
|
|
{ "properties",
|
|
{
|
|
{ "arg1", { { "type", "integer" } } },
|
|
} },
|
|
{ "required", { "arg1" } },
|
|
} },
|
|
} }
|
|
};
|
|
tools.push_back(tool_short);
|
|
|
|
json tool_long = {
|
|
{ "type", "function" },
|
|
{ "function",
|
|
{
|
|
{ "name", "special_function_with_opt" },
|
|
{ "description", "A special function with optional params" },
|
|
{ "parameters",
|
|
{
|
|
{ "type", "object" },
|
|
{ "properties",
|
|
{
|
|
{ "arg1", { { "type", "integer" } } },
|
|
{ "arg2", { { "type", "integer" } } },
|
|
} },
|
|
{ "required", { "arg1" } },
|
|
} },
|
|
} }
|
|
};
|
|
tools.push_back(tool_long);
|
|
|
|
// Use standard_constructed_tools which had the prefix matching bug
|
|
std::map<std::string, std::string> markers = {
|
|
{ "tool_call_start_marker", "<tool_call>" },
|
|
{ "tool_call_end_marker", "</tool_call>" },
|
|
{ "function_opener", "<function=" },
|
|
{ "function_closer", "</function>" },
|
|
{ "function_name_suffix", ">" },
|
|
{ "parameter_key_prefix", "<param=" },
|
|
{ "parameter_key_suffix", ">" },
|
|
{ "parameter_closer", "</param>" },
|
|
};
|
|
|
|
auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
|
auto content = p.rule("content", p.content(p.until("<tool_call>")));
|
|
auto tool_call = p.standard_constructed_tools(markers, tools, false, false);
|
|
return content + p.zero_or_more(p.space() + tool_call) + p.end();
|
|
});
|
|
|
|
// Test parsing the long tool name - this should NOT trigger the short tool name
|
|
t.test("parse long tool name", [&](testing & t) {
|
|
std::string input =
|
|
"Let me call the function."
|
|
"<tool_call>"
|
|
"<function=special_function_with_opt>"
|
|
"<param=arg1>42</param>"
|
|
"</function>"
|
|
"</tool_call>";
|
|
|
|
common_peg_parse_context ctx(input);
|
|
auto result = parser.parse(ctx);
|
|
|
|
t.assert_true("success", result.success());
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
t.assert_equal("content", "Let me call the function.", msg.content);
|
|
t.assert_equal("tool calls count", 1u, msg.tool_calls.size());
|
|
if (!msg.tool_calls.empty()) {
|
|
t.assert_equal("tool name", "special_function_with_opt", msg.tool_calls[0].name);
|
|
}
|
|
});
|
|
|
|
// Test incremental parsing - the key test case
|
|
// This ensures that when incrementally parsing "special_function_with_opt",
|
|
// we don't prematurely emit "special_function" as a tool call
|
|
t.test("incremental parse long tool name", [&](testing & t) {
|
|
std::string input =
|
|
"Let me call the function."
|
|
"<tool_call>"
|
|
"<function=special_function_with_opt>"
|
|
"<param=arg1>42</param>"
|
|
"</function>"
|
|
"</tool_call>";
|
|
|
|
std::vector<std::string> tokens = simple_tokenize(input);
|
|
|
|
common_chat_msg prev;
|
|
for (auto it = tokens.begin(); it != tokens.end(); it++) {
|
|
std::string in = std::accumulate(tokens.begin(), it + 1, std::string());
|
|
|
|
common_peg_parse_context ctx(in, (it + 1 < tokens.end()) ? COMMON_PEG_PARSE_FLAG_LENIENT : COMMON_PEG_PARSE_FLAG_NONE);
|
|
auto result = parser.parse(ctx);
|
|
|
|
if (!t.assert_equal("not fail", false, result.fail())) {
|
|
t.log(in.substr(0, result.end) + "[failed->]" + in.substr(result.end));
|
|
return;
|
|
}
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
// The critical check: during incremental parsing, we should never
|
|
// see "special_function" as the tool name when parsing "special_function_with_opt"
|
|
for (const auto & tc : msg.tool_calls) {
|
|
if (!t.assert_equal("tool name should not be short prefix", false,
|
|
tc.name == "special_function")) {
|
|
t.log("Premature tool name match at input: " + in);
|
|
return;
|
|
}
|
|
}
|
|
|
|
try {
|
|
auto diffs = common_chat_msg_diff::compute_diffs(prev, msg);
|
|
} catch (const std::exception & e) {
|
|
t.log(in.substr(0, result.end) + "[failed->]" + in.substr(result.end));
|
|
t.assert_true(std::string("diff failed with ") + e.what(), false);
|
|
return;
|
|
}
|
|
|
|
prev = msg;
|
|
}
|
|
|
|
// Final check: the complete parse should have the correct tool name
|
|
t.assert_equal("final tool calls count", 1u, prev.tool_calls.size());
|
|
if (!prev.tool_calls.empty()) {
|
|
t.assert_equal("final tool name", "special_function_with_opt", prev.tool_calls[0].name);
|
|
}
|
|
});
|
|
|
|
// Test parsing the short tool name still works
|
|
t.test("parse short tool name", [&](testing & t) {
|
|
std::string input =
|
|
"Let me call the function."
|
|
"<tool_call>"
|
|
"<function=special_function>"
|
|
"<param=arg1>42</param>"
|
|
"</function>"
|
|
"</tool_call>";
|
|
|
|
common_peg_parse_context ctx(input);
|
|
auto result = parser.parse(ctx);
|
|
|
|
t.assert_true("success", result.success());
|
|
|
|
common_chat_msg msg;
|
|
auto mapper = common_chat_peg_mapper(msg);
|
|
mapper.from_ast(ctx.ast, result);
|
|
|
|
t.assert_equal("content", "Let me call the function.", msg.content);
|
|
t.assert_equal("tool calls count", 1u, msg.tool_calls.size());
|
|
if (!msg.tool_calls.empty()) {
|
|
t.assert_equal("tool name", "special_function", msg.tool_calls[0].name);
|
|
}
|
|
});
|
|
}
|
|
|
|
static void test_tagged_peg_parser(testing & t) {
|
|
t.test("basic tag extraction", [&](testing & t) {
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
return p.tag("greeting", p.until(" ")) + " " + p.tag("name", p.rest()) + p.end();
|
|
});
|
|
|
|
auto result = parser.parse_and_extract("Hello World");
|
|
t.assert_true("success", result.result.success());
|
|
t.assert_equal("greeting tag", "Hello", result.tags.at("greeting"));
|
|
t.assert_equal("name tag", "World", result.tags.at("name"));
|
|
});
|
|
|
|
t.test("duplicate tags overwrite", [&](testing & t) {
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
return p.tag("item", p.until(",")) + "," + p.tag("item", p.rest()) + p.end();
|
|
});
|
|
|
|
auto result = parser.parse_and_extract("first,second");
|
|
t.assert_true("success", result.result.success());
|
|
t.assert_equal("item tag", "second", result.tags.at("item"));
|
|
});
|
|
|
|
t.test("no tags extracted", [&](testing & t) {
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
return p.rest() + p.end();
|
|
});
|
|
|
|
auto result = parser.parse_and_extract("Hello");
|
|
t.assert_true("success", result.result.success());
|
|
t.assert_equal("empty tags", 0u, result.tags.size());
|
|
});
|
|
|
|
t.test("structured extraction", [&](testing & t) {
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
auto header = p.tag("header", p.until("\n"));
|
|
auto body = p.tag("body", p.rest());
|
|
return header + "\n" + body + p.end();
|
|
});
|
|
|
|
auto result = parser.parse_and_extract("Title\nBody content here");
|
|
t.assert_true("success", result.result.success());
|
|
t.assert_equal("header", "Title", result.tags.at("header"));
|
|
t.assert_equal("body", "Body content here", result.tags.at("body"));
|
|
});
|
|
|
|
t.test("partial parse", [&](testing & t) {
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
return p.tag("prefix", p.until(":")) + ":" + p.tag("value", p.rest()) + p.end();
|
|
});
|
|
|
|
auto result = parser.parse_and_extract("key:val", COMMON_PEG_PARSE_FLAG_LENIENT);
|
|
t.assert_true("not fail", !result.result.fail());
|
|
t.assert_equal("prefix tag", "key", result.tags.at("prefix"));
|
|
t.assert_equal("value tag", "val", result.tags.at("value"));
|
|
});
|
|
|
|
t.test("find in the middle", [&](testing & t) {
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
return p.choice({ p.literal("{"), p.literal(":") }) + p.space() + p.literal("\"") + p.atomic(p.literal("fun_name"));
|
|
});
|
|
|
|
std::string tpl = "This is a very long jinja template string. We have tools. We will try to call them now: <tool_call>{ \"fun_name\" : { \"arg\" : 1 }</tool_call>";
|
|
auto result = parser.parse_anywhere_and_extract(tpl);
|
|
t.assert_true("success", result.result.success());
|
|
});
|
|
|
|
t.test("fail find in the middle", [&](testing & t) {
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
return p.choice({ p.literal("{"), p.literal(":") }) + p.space() + p.literal("\"") + p.atomic(p.literal("fun_name"));
|
|
});
|
|
|
|
std::string tpl = "This is a very long jinja template string. We have tools. We will try to call them now: <tool_call><fun=fun_name><arg name=arg>1</arg></tool_call>";
|
|
auto result = parser.parse_anywhere_and_extract(tpl);
|
|
t.assert_true("failure", result.result.fail());
|
|
});
|
|
|
|
t.test("find function tag with name", [&](testing &t) {
|
|
std::string haystack = "\n<tool_call>\n<function=foofoo>\n<parameter=first>\nXXXX\n</parameter>\n<parameter=second>\nYYYY\n</parameter>\n</function>\n</tool_call>\n";
|
|
auto parser = build_tagged_peg_parser([](common_peg_parser_builder & p) {
|
|
std::string needle = "foofoo";
|
|
return p.tag("fun_marker", p.choice({
|
|
p.tag("fun_pre", p.literal("<") + p.until_one_of({ ">", needle })) + p.literal(needle) +
|
|
p.tag("fun_post", p.negate(p.space() + p.literal("<")) + p.until(">") + p.literal(">")) + p.space(),
|
|
p.tag("fun_pre", p.literal("[") + p.until_one_of({ "]", needle })) + p.literal(needle) +
|
|
p.tag("fun_post", p.negate(p.space() + p.literal("[") + p.until("]") + p.literal("]")) + p.space()) }));
|
|
});
|
|
auto result = parser.parse_anywhere_and_extract(haystack);
|
|
t.assert_true("success", result.result.success());
|
|
t.assert_equal("fun_pre should be '<function='", "<function=", result.tags["fun_pre"]);
|
|
t.assert_equal("fun_post should be '>'", ">", result.tags["fun_post"]);
|
|
});
|
|
}
|