From 7e04bcac2b0413f643b1326443735912284bae46 Mon Sep 17 00:00:00 2001 From: Constantin Date: Sun, 25 Oct 2026 06:57:16 -0400 Subject: [PATCH] Parse HYV3 native sectioned tool calls and tagged arguments Use the existing RadChatFormat fields for the outer tool-call section, name separator and tagged values. Cover grammar, template replay, streaming at every truncation, section boundaries and OpenAI response lifting; leave the supports_reasoning adapter unchanged. --- NOTICE | 5 + abi/rad_builder.h | 7 +- core/text/chatfmt.cpp | 44 +++- core/text/chatfmt.h | 2 +- core/text/chatparse.cpp | 144 +++++++++++-- tests/chat_test.cpp | 58 ++++++ tests/chatparse_test.cpp | 252 ++++++++++++++++++++++- tests/data/chat/hyv3/README.md | 13 ++ tests/data/chat/hyv3/chat_template.jinja | 233 +++++++++++++++++++++ tests/server_fakes.h | 28 +++ tests/server_test.cpp | 88 ++++++++ 11 files changed, 840 insertions(+), 34 deletions(-) create mode 100644 tests/data/chat/hyv3/README.md create mode 100644 tests/data/chat/hyv3/chat_template.jinja diff --git a/NOTICE b/NOTICE index 58d10852..0b741430 100644 --- a/NOTICE +++ b/NOTICE @@ -94,6 +94,11 @@ license text is in the file named beside each. nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE +tests/data/chat/hyv3/chat_template.jinja is Tencent's Hy-Memory-30B-A3B chat template, +copied unchanged from tencent/Hy-Memory-30B-A3B on Hugging Face. +Copyright (C) 2026 Tencent. All rights reserved. Licensed under Apache-2.0 (LICENSE). +Its source and content checksum are recorded in tests/data/chat/hyv3/README.md. + core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid diff --git a/abi/rad_builder.h b/abi/rad_builder.h index fdd8889b..4e1062e7 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1509,14 +1509,13 @@ typedef struct RadChatFormat { const char* reasoning_open; /* "" when the model does not reason */ const char* reasoning_close; /* Literals that end a reasoning block the model forgot to close, when a call starts there. - * Each must be the call opener: `call_open`, or `name_prefix` when there is no call_open. */ + * Each must be a call opener (`call_open`, or `name_prefix` without one) or section_open. */ const char* const* reasoning_breaks; uint32_t n_reasoning_breaks; uint32_t reasoning_in_prompt; /* RAD_CHAT_THINK_* */ - /* Around all of a turn's calls, and between two calls beyond whitespace. The parser does not - * read these yet, so a format that sets one is refused at startup by name; they are fields so - * supporting them later does not change the struct. */ + /* Around the complete list of calls. section_open and section_close must be set together. + * call_separator is additional text between calls beyond whitespace; it is not supported. */ const char* section_open; const char* section_close; const char* call_separator; diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index 7def6d6f..ad7c2301 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -173,15 +173,34 @@ int chat_format_check(const ChatFormat& f, std::string* why) { return reasoning_anywhere_check(f, why); } - if (!f.section_open.empty() || !f.section_close.empty()) - return no("a section around all calls (section_open/section_close) is not read by the " - "streaming parser"); + if (f.section_open.empty() != f.section_close.empty()) + return no("section_open and section_close must be set together"); + if (!f.section_open.empty()) { + const std::string so = trim_ws(f.section_open), sc = trim_ws(f.section_close); + if (so.empty() || sc.empty()) return no("section_open/section_close may not be whitespace"); + if (so != f.section_open || sc != f.section_close) + return no("section_open/section_close must not have surrounding whitespace"); + if (confusable(so, sc)) + return no("section_open " + show(so) + " and section_close " + show(sc) + + " cannot be told apart"); + for (const std::string* d : { &f.reasoning_open, &f.reasoning_close, &f.call_open, + &f.call_close, &f.name_prefix, &f.name_suffix, + &f.call_end, &f.arg_prefix, &f.arg_name_suffix, + &f.arg_value_prefix, &f.arg_value_suffix }) { + if (!d->empty() && confusable(so, trim_ws(*d))) + return no("section_open " + show(so) + " overlaps delimiter " + show(*d)); + if (!d->empty() && confusable(sc, trim_ws(*d))) + return no("section_close " + show(sc) + " overlaps delimiter " + show(*d)); + } + } if (!f.call_separator.empty()) return no("a separator between calls (call_separator " + show(f.call_separator) + ") is not read by the streaming parser; tagged calls separate on whitespace"); if (f.call_open.empty() && !f.call_close.empty()) return no("call_close without call_open"); const bool object = f.object_args(); + if (object && !f.section_open.empty()) + return no("section-wrapped object arguments are not supported"); /* Without a suffix the name ends at what follows it: the object's `{`, or a tagged call's * first argument or close. */ if (!f.name_suffix.empty()) { @@ -238,9 +257,10 @@ int chat_format_check(const ChatFormat& f, std::string* why) { show(f.name_prefix) + " cannot be told apart"); } const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open; + const std::string section_opener = trim_ws(f.section_open); for (const std::string& b : f.reasoning_breaks) - if (b != opener) - return no("reasoning break " + show(b) + " is not the call opener " + show(opener)); + if (b != opener && (section_opener.empty() || b != section_opener)) + return no("reasoning break " + show(b) + " is not a call or section opener"); if (!f.reasoning_breaks.empty() && !f.has_reasoning()) return no("reasoning_breaks without a reasoning block"); for (const std::string& t : f.triggers) @@ -432,6 +452,8 @@ std::string chat_format_describe(const ChatFormat& f) { (f.reasoning_anywhere ? " anywhere" : ""); else s += " no reasoning"; + if (f.has_tools() && !f.section_open.empty()) + s += "; section " + show(f.section_open) + ".." + show(f.section_close); if (f.has_tools() && f.object_args()) { s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) + " {OBJECT"; @@ -912,11 +934,17 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat ? seq({ wrapped, rep(seq({ space(), wrapped }), 0, -1), space() }) : seq({ wrapped, space() }); } else { - G next = seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice }); + /* Section-wrapped dialects contain only calls and whitespace. In particular, + * inter-call prose must not consume a section close and admit later calls. */ + G next = f.section_open.empty() + ? seq({ space(), opt(wrap(leaf(until_pattern({ opener })))), choice }) + : seq({ space(), choice }); calls = req.parallel_tool_calls - ? seq({ lit(""), space(), choice, rep(next, 0, -1), space(), lit("") }) - : seq({ lit(""), space(), choice, space(), lit("") }); + ? seq({ choice, rep(next, 0, -1), space() }) + : seq({ choice, space() }); } + if (!f.section_open.empty()) + calls = seq({ lit(f.section_open), space(), calls, space(), lit(f.section_close) }); b.add_rule("tool-call", render(calls)); if (req.require_call) { /* Nothing after the calls: a complete grammar admits only the end of the turn, diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index c2b72444..ba76ce75 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -104,7 +104,7 @@ struct ChatFormat { /* ------------------------------------------------------------------ tool calls * `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the * format has no tool calls. */ - std::string section_open, section_close; /* around all calls; not read yet, must be empty */ + std::string section_open, section_close; /* around the complete list of calls */ /* Between two calls, beyond whitespace (a JSON-array format would use ", "). Tagged calls are * self-delimiting. Not read yet, must be empty. */ std::string call_separator; diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index 5222a659..41af41a2 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -720,12 +720,15 @@ struct ReplyFormat::Impl { ChatFormat f; /* Each tag split into its core and the whitespace around it that is optional to match. */ std::string open_core, open_trail, close_core, close_trail, ns_core, ns_trail, end_core, - end_trail, co_core, co_trail; + end_trail, co_core, co_trail, section_open_core, section_close_core; /* What begins a call in content. First the format's own opener: call_open's core, or * name_prefix when calls are not wrapped. A wrapped format also takes name_prefix alone, * second, since models often write a call without its wrapper; a wrapper written without * its trailing whitespace is read too. */ - std::vector openers; + std::vector openers, text_markers; + size_t section_open_hit = (size_t)-1, section_close_hit = (size_t)-1; + size_t think_open_hit = (size_t)-1, think_close_hit = (size_t)-1; + size_t body_section_close_hit = (size_t)-1; /* What ends an argument name: arg_name_suffix and arg_value_prefix, back to back. */ std::string name_end; /* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so it was @@ -792,6 +795,16 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr split_ws(f.call_open, &m.co_core, &m.co_trail); if (f.call_open.empty()) m.openers = { f.name_prefix }; else m.openers = { m.co_core, f.name_prefix }; + m.text_markers = m.openers; + if (!f.section_open.empty()) { + std::string section_trail; + split_ws(f.section_open, &m.section_open_core, §ion_trail); + split_ws(f.section_close, &m.section_close_core, §ion_trail); + m.section_open_hit = m.text_markers.size(); + m.text_markers.push_back(m.section_open_core); + m.section_close_hit = m.text_markers.size(); + m.text_markers.push_back(m.section_close_core); + } m.name_end = f.arg_name_suffix + f.arg_value_prefix; m.object = f.has_tools() && f.object_args(); m.name_open = f.has_tools() && !m.object && f.name_suffix.empty(); @@ -808,15 +821,16 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr m.think_breaks.build(b); } if (f.reasoning_anywhere && f.has_reasoning()) { - std::vector t; - if (f.has_tools()) t = m.openers; + std::vector t = m.text_markers; + m.think_open_hit = t.size(); t.push_back(m.open_core); + m.think_close_hit = t.size(); t.push_back(m.close_core); m.text_think.build(t); m.think_only.build({ m.open_core, m.close_core }); } if (m.object) { - m.text.build(m.openers); + m.text.build(m.text_markers); std::string trail; split_ws(f.call_close, &m.cc_core, &trail); std::vector bare{ ",", "}", "]" }, key{ ":", ",", "}" }; @@ -851,7 +865,7 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr m.obj_bare.build(bare); m.obj_key.build(key); } else if (f.has_tools()) { - m.text.build(m.openers); + m.text.build(m.text_markers); m.arg_name.build({ m.name_end }); m.value.build({ f.arg_value_suffix }); std::string trail; @@ -864,11 +878,17 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr return a.find(b) == std::string::npos && b.find(a) == std::string::npos; }; if (!apart(m.cc_core, f.arg_prefix) || !apart(m.cc_core, m.end_core)) m.cc_core.clear(); - if (m.cc_core.empty()) m.junk.build({ f.arg_prefix, m.end_core }); - else m.junk.build({ f.arg_prefix, m.end_core, m.cc_core }); + std::vector junk{ f.arg_prefix, m.end_core }; + if (!m.cc_core.empty()) junk.push_back(m.cc_core); + if (!m.section_close_core.empty()) { + m.body_section_close_hit = junk.size(); + junk.push_back(m.section_close_core); + } + m.junk.build(junk); } - const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open, - &f.call_close, &f.name_prefix, &f.name_suffix, + const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.section_open, + &f.section_close, &f.call_open, &f.call_close, + &f.name_prefix, &f.name_suffix, &f.call_end, &f.arg_prefix, &m.name_end, &f.arg_value_suffix, &f.object_string_open, &f.object_string_close }; @@ -1139,6 +1159,11 @@ struct ReplyStream::Impl { St st; bool strict = true, finished = false, fed_tail = false; bool post_call = false; /* content after a call */ + bool section_active = false; + size_t section_calls_at_open = 0; + /* The last completed inner call is not executable until another call starts or the outer + * section closes. Deferring CallEnd keeps truncation consistent with the one-shot parse. */ + size_t pending_section_call = (size_t)-1; /* delimiter scan */ uint16_t ds = 0; @@ -1413,6 +1438,40 @@ struct ReplyStream::Impl { return p + 1; } + void complete_section_call() { + if (pending_section_call == (size_t)-1) return; + msg.calls[pending_section_call].closed = true; + event(ReplyEvent::CallEnd, (uint32_t)pending_section_call, {}); + pending_section_call = (size_t)-1; + } + + void open_section() { + if (section_active) { lenient(); return; } + section_active = true; + section_calls_at_open = calls; + } + + void close_section() { + if (!section_active) { lenient(); return; } + if (calls == section_calls_at_open) lenient(); + complete_section_call(); + section_active = false; + } + + /* A section close before call_end leaves the last call incomplete: it must never be exposed + * as an executable tool call. Keep its bytes available to content_with_open_call(). */ + void abandon_call_at_section_close() { + lenient(); + if (cur == 2) publish(2, true); + cur = -1; + section_active = false; + post_call = false; + ds = 0; + hold.clear(); + lhold.clear(); + st = St::Text; + } + /* The call opener has matched at `att`; whether a call follows is decided below. */ void begin_attempt(St from) { origin = from; @@ -1472,6 +1531,7 @@ struct ReplyStream::Impl { } void begin_call(bool exact) { + complete_section_call(); if (!exact || tool < 0) lenient(); if (!P.opt.parallel_tool_calls && calls > 0) lenient(); if (cur >= 0) publish(cur, false); @@ -1810,8 +1870,12 @@ struct ReplyStream::Impl { args_out(close); } publish(2, true); - msg.calls.back().closed = true; - event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {}); + if (section_active) { + pending_section_call = msg.calls.size() - 1; + } else { + msg.calls.back().closed = true; + event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {}); + } cur = -1; lpos = 0; lhold.clear(); @@ -1984,9 +2048,19 @@ struct ReplyStream::Impl { p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); }); if (hit == 0) { trail = 0; st = St::ThinkCloseWs; } else if (hit > 0) { - att = d.pattern(hit); - att_at = here(p) - att.size(); - begin_attempt(St::Think); + const std::string& marker = d.pattern(hit); + if (!F.section_open_core.empty() && marker == F.section_open_core) { + open_section(); + st = St::Text; + } else if (!F.section_open_core.empty() && !section_active) { + /* A call-looking tag cannot bypass the required outer section, including + * when it appears in an unclosed reasoning block. */ + think_out(marker.data(), marker.size()); + } else { + att = marker; + att_at = here(p) - att.size(); + begin_attempt(St::Think); + } } return p; } @@ -2004,14 +2078,35 @@ struct ReplyStream::Impl { } p = scan(*text_dfa, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); if (hit < 0) return p; + if (P.anywhere && !P.calls) { + if (hit == 0) { trail = 0; st = St::ThinkOpenWs; } + else lenient(); /* A reasoning close with no block open. */ + return p; + } if ((size_t)hit < n_open) { - att_at = here(p) - F.openers[(size_t)hit].size(); - begin_text_attempt(hit); - } else if ((size_t)hit == n_open) { + if (!F.section_open_core.empty() && !section_active) { + /* The call-looking tag is ordinary content outside the required wrapper. */ + const std::string& marker = F.text_markers[(size_t)hit]; + text_out(marker.data(), marker.size()); + } else { + att_at = here(p) - F.openers[(size_t)hit].size(); + begin_text_attempt(hit); + } + } else if ((size_t)hit == F.section_open_hit) { + open_section(); + } else if ((size_t)hit == F.section_close_hit) { + if (!section_active) { + lenient(); + const std::string& marker = F.text_markers[(size_t)hit]; + text_out(marker.data(), marker.size()); + } else { + close_section(); + } + } else if ((size_t)hit == F.think_open_hit) { /* A reasoning block opens again, later in the reply. */ trail = 0; st = St::ThinkOpenWs; - } else { + } else if ((size_t)hit == F.think_close_hit) { /* Its close with no block open: not part of the answer. */ lenient(); } @@ -2153,10 +2248,12 @@ struct ReplyStream::Impl { const std::string& ap = F.f.arg_prefix; const std::string& fc = F.end_core; const std::string& cc = F.cc_core; + const std::string& sc = F.section_close_core; const bool a_ok = extends(ap, c); const bool f_ok = extends(fc, c); const bool c_ok = wrapped && extends(cc, c); - if (!a_ok && !f_ok && !c_ok) { + const bool s_ok = !sc.empty() && extends(sc, c); + if (!a_ok && !f_ok && !c_ok && !s_ok) { lenient(); st = St::Junk; ds = 0; @@ -2171,6 +2268,7 @@ struct ReplyStream::Impl { if (a_ok && lpos == ap.size()) { start_arg(); return p + 1; } if (f_ok && lpos == fc.size()) { finish_call_strictness(); end_core_done(); return p + 1; } if (c_ok && lpos == cc.size()) { end_call_at_close(); return p + 1; } + if (s_ok && lpos == sc.size()) { abandon_call_at_section_close(); return p + 1; } return p + 1; } @@ -2251,6 +2349,8 @@ struct ReplyStream::Impl { p = scan(F.junk, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); if (hit == 0) start_arg(); else if (hit == 1) end_core_done(); + else if (hit >= 0 && (size_t)hit == F.body_section_close_hit) + abandon_call_at_section_close(); else if (hit == 2 && wrapped) end_call_at_close(); else if (hit == 2) text_out(F.cc_core.data(), F.cc_core.size()); return p; @@ -2804,6 +2904,10 @@ struct ReplyStream::Impl { default: break; } + if (section_active) { + lenient(); + section_active = false; + } hold.clear(); ds = 0; if (!think_text) think_pend.clear(); diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index d748754c..952877b8 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -87,6 +87,12 @@ static const TemplateFixture& qwen() { return f; } +static const TemplateFixture& hyv3() { + static const TemplateFixture f("RAD_TEST_HYV3_JINJA", "hyv3/chat_template.jinja", + "<|hy_begin▁of▁sentence|>", ""); + return f; +} + static json tools_json() { return json::parse(R"([{ "type": "function", @@ -106,6 +112,58 @@ static json tools_json() { "required":["path","old_string","new_string"]}}}])"); } +static json hyv3_tools_json() { + return json::parse(R"([{ + "type":"function","function":{"name":"lookup_weather","description":"Look up weather.", + "parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}, + {"type":"function","function":{"name":"add","description":"Add two integers.", + "parameters":{"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"integer"}}, + "required":["a","b"]}}}])"); +} + +TEST(hyv3_template_renders_openai_tool_schemas_and_replayed_history) { + if (!hyv3().need()) return; + REQUIRE(hyv3().t->caps().tools && hyv3().t->caps().tool_calls); + const json tools = hyv3_tools_json(); + json messages = json::array({ + {{"role", "system"}, {"content", "Use tools when useful."}}, + {{"role", "user"}, {"content", "Check Toronto weather and add 20 and 22."}} + }); + ChatOptions opt; + opt.add_generation_prompt = true; + ChatPrompt prompt; + CHECK_OK(hyv3().t->apply(messages, tools, opt, &prompt)); + if (!prompt.error.empty()) return; + CHECK(prompt.prompt.find("") != std::string::npos); + CHECK(prompt.prompt.find("") != std::string::npos); + CHECK(prompt.prompt.find("{function-name}") != std::string::npos); + CHECK(prompt.generation_prompt.find("<|hy_Assistant|>") != std::string::npos); + + messages.push_back({{"role", "assistant"}, {"content", ""}, + {"tool_calls", json::array({ + {{"id", "call-weather"}, {"type", "function"}, + {"function", {{"name", "lookup_weather"}, + {"arguments", "{\"city\":\"Toronto\"}"}}}}, + {{"id", "call-add"}, {"type", "function"}, + {"function", {{"name", "add"}, {"arguments", "{\"a\":20,\"b\":22}"}}}} + })}}); + messages.push_back({{"role", "tool"}, {"tool_call_id", "call-weather"}, + {"content", "Cloudy, 12 C."}}); + messages.push_back({{"role", "tool"}, {"tool_call_id", "call-add"}, {"content", "42"}}); + messages.push_back({{"role", "user"}, {"content", "Summarize the results."}}); + prompt = ChatPrompt{}; + CHECK_OK(hyv3().t->apply(messages, tools, opt, &prompt)); + if (!prompt.error.empty()) return; + CHECK(prompt.prompt.find("") != std::string::npos); + CHECK(prompt.prompt.find("lookup_weather") != std::string::npos); + CHECK(prompt.prompt.find("city") != std::string::npos); + CHECK(prompt.prompt.find("Toronto") != std::string::npos); + CHECK(prompt.prompt.find("") != std::string::npos); + CHECK(prompt.prompt.find("Cloudy, 12 C.") != std::string::npos); + CHECK(prompt.prompt.find("\n42\n") != std::string::npos); + CHECK(prompt.prompt.find("Summarize the results.") != std::string::npos); +} + /* Render one turn, passing `effort` as the template's reasoning_effort when set. */ static int render_turn(ChatPrompt* p, bool with_tools, const char* effort) { json msgs = json::array(); diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index 53747dbe..5f70e68a 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -1052,6 +1052,33 @@ TEST(no_template_is_a_format_with_no_reasoning_and_no_calls) { static const char* const kBreaks[] = { "\n" }; static const char* const kTriggers[] = { "\n" }; +static RadChatFormat hyv3_abi() { + static const char* const triggers[] = { "" }; + RadChatFormat c; + std::memset(&c, 0, sizeof c); + c.struct_size = sizeof c; + c.name = "hyv3-native"; + c.reasoning_open = ""; + c.reasoning_close = ""; + c.reasoning_breaks = triggers; + c.n_reasoning_breaks = 1; + c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT; + c.section_open = ""; + c.section_close = ""; + c.name_prefix = ""; + c.name_suffix = ""; + c.call_end = ""; + c.arg_prefix = ""; + c.arg_name_suffix = "\n"; + c.arg_value_prefix = ""; + c.arg_value_suffix = ""; + c.string_value = RAD_CHAT_VALUE_RAW; + c.other_value = RAD_CHAT_VALUE_JSON; + c.triggers = triggers; + c.n_triggers = 1; + return c; +} + static RadChatFormat qwen_abi() { RadChatFormat c; std::memset(&c, 0, sizeof c); @@ -1268,7 +1295,7 @@ TEST(a_format_the_parser_cannot_read_is_refused_by_name) { CHECK(refused([](RadChatFormat& c) { c.arg_prefix = "\n"; }, "told apart")); CHECK(refused([](RadChatFormat& c) { c.reasoning_close = ""; }, "reasoning_close")); static const char* const other[] = { "" }; - CHECK(refused([](RadChatFormat& c) { c.reasoning_breaks = other; }, "call opener")); + CHECK(refused([](RadChatFormat& c) { c.reasoning_breaks = other; }, "opener")); CHECK(refused([](RadChatFormat& c) { c.string_value = RAD_CHAT_VALUE_JSON; }, "string_value")); } @@ -1446,6 +1473,68 @@ TEST(the_chat_bridge_derives_the_whole_request_from_one_format) { CHECK(why.find("a>b") != std::string::npos); } +/* The declared format preserves HYV3's outer section and all of its argument markers. */ +TEST(hyv3_plugin_format_runs_through_the_chat_template_bridge) { + std::shared_ptr v = vocab_with(fixture("hyv3")); + REQUIRE(v != nullptr); + RadChatFormat c = hyv3_abi(); + server::ChatTemplateBridge br; + CHECK_OK(br.init(*v, &c, "hyv3_bf16")); + CHECK(br.supports_tools()); + CHECK_EQ(br.tool_refusal(), std::string()); + const json tools = json::parse(R"([{"type":"function","function":{"name":"lookup_weather", + "parameters":{"type":"object","properties":{"city":{"type":"string"}}, + "required":["city"]}}}])"); + const server::ChatRender r = bridge_render(br, tools); + REQUIRE(!r.prompt.empty()); + CHECK(!r.grammar.empty()); + CHECK(r.grammar_lazy); + REQUIRE(r.grammar_triggers.size() == 1); + CHECK_EQ(r.grammar_triggers[0].value, std::string("")); + for (const char* marker : { "", "", "", "", + "", "", + "", "", "", "" }) + CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), marker) != + r.preserved_tokens.end()); + REQUIRE(r.parser != nullptr); + std::unique_ptr rd = r.parser->open(); + rd->feed("Cloudy.\nlookup_weather\n" + "city\nToronto\n" + "", nullptr); + rd->finish(nullptr); + const server::ParsedMessage pm = rd->message(); + CHECK_EQ(pm.content, std::string("Cloudy.")); + REQUIRE(pm.tool_calls.size() == 1); + CHECK_EQ(pm.tool_calls[0].name, std::string("lookup_weather")); + CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"city\":\"Toronto\"}")); +} + +TEST(hyv3_plugin_format_splits_requested_reasoning_before_native_tools) { + std::shared_ptr v = vocab_with(fixture("hyv3")); + REQUIRE(v != nullptr); + RadChatFormat c = hyv3_abi(); + server::ChatTemplateBridge br; + CHECK_OK(br.init(*v, &c, "hyv3_bf16")); + const json msgs = json::array({ { {"role", "user"}, {"content", "List the files."} } }); + server::ChatRenderOptions opt; + opt.template_kwargs["reasoning_effort"] = json("high").dump(); + server::ChatRender out; + std::string why; + CHECK_OK(br.apply(msgs, agent_tools(), opt, &out, &why)); + REQUIRE(out.parser != nullptr); + CHECK(out.generation_prompt.ends_with("")); + auto rd = out.parser->open(); + rd->feed("Plan.Checking.bash" + "command\nls" + "", nullptr); + rd->finish(nullptr); + const server::ParsedMessage m = rd->message(); + CHECK_EQ(m.reasoning, std::string("Plan.")); + CHECK_EQ(m.content, std::string("Checking.")); + REQUIRE(m.tool_calls.size() == 1); + CHECK_EQ(m.tool_calls[0].name, std::string("bash")); +} + /* GLM-5.3-Flash's template reads list items as `m.content.0.type`, jinja2's dotted index, and * writes calls as `NAMEKV`. The * capability probe renders with tools and tool calls, so a runtime that throws on the dotted index @@ -1579,6 +1668,167 @@ static int object_admits(const std::string& gbnf, const std::string& text) { return gr->complete() ? 1 : 0; } +TEST(hyv3_sectioned_tagged_calls_parse_stream_and_constrain) { + RadChatFormat abi = hyv3_abi(); + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(&abi, &f, &why)); + CHECK_OK(chat_format_check(f, &why)); + + const json tools = json::parse(R"([{"type":"function","function":{"name":"lookup_weather", + "parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}, + {"type":"function","function":{"name":"add","parameters":{"type":"object", + "properties":{"a":{"type":"integer"},"b":{"type":"integer"}},"required":["a","b"]}}}])"); + ReplyOptions ro; + ro.tools = &tools; + const std::shared_ptr p = parser_of(f, ro); + REQUIRE(p != nullptr); + const std::string reply = + "Checking both results.\n" + "lookup_weather\n" + "city\nQuébec & Montréal\n" + "\n" + "add\n" + "a\n20\n" + "b\n22\n" + "\n"; + bool strict = false; + const ReplyMessage m = reply_parse(*p, reply, &strict); + CHECK(strict); + CHECK_EQ(m.content, std::string("Checking both results.")); + REQUIRE(m.calls.size() == 2); + CHECK_EQ(m.calls[0].name, std::string("lookup_weather")); + CHECK_EQ(m.calls[0].arguments, std::string("{\"city\":\"Québec & Montréal\"}")); + CHECK(m.calls[0].closed); + CHECK_EQ(m.calls[1].name, std::string("add")); + CHECK_EQ(m.calls[1].arguments, std::string("{\"a\":20,\"b\":22}")); + CHECK(m.calls[1].closed); + CHECK(m.content.find("") == std::string::npos); + CHECK(m.content.find("") == std::string::npos); + const std::string stream_error = stream_all(*p, reply); + if (!stream_error.empty()) ::radtest::fail(__FILE__, __LINE__, stream_error); + + ChatGrammarRequest gq; + gq.tools = &tools; + ChatGrammar g; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK(g.lazy); + CHECK(g.trigger_words == std::vector{ "" }); + const size_t section = reply.find(""); + REQUIRE(section != std::string::npos); + CHECK_EQ(object_admits(g.text, reply.substr(section)), 1); + gq.parallel_tool_calls = false; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK_EQ(object_admits(g.text, reply.substr(section)), 0); + + /* A quoted call tag outside the section remains user-visible content, not an invocation. */ + const std::string outside = "Example: add"; + const ReplyMessage quoted = reply_parse(*p, outside, &strict); + CHECK_EQ(quoted.calls.size(), (size_t)0); + CHECK_EQ(quoted.content, outside); + + /* A section close cannot turn a call missing its own close tag into an executable call. */ + const std::string truncated = + "\nadd\n" + "a\n20\n"; + const ReplyMessage incomplete = reply_parse(*p, truncated, &strict); + CHECK(!strict); + REQUIRE(incomplete.calls.size() == 1); + CHECK(!incomplete.calls[0].closed); + const std::string truncated_stream_error = stream_all(*p, truncated); + if (!truncated_stream_error.empty()) + ::radtest::fail(__FILE__, __LINE__, truncated_stream_error); +} + +TEST(section_wrapped_calls_do_not_cross_section_boundaries) { + ChatFormat f; + std::string why; + RadChatFormat abi = hyv3_abi(); + CHECK_OK(chat_format_from_abi(&abi, &f, &why)); + ReplyOptions ro; + ro.tools = &agent_tools(); + const auto p = parser_of(f, ro); + REQUIRE(p != nullptr); + const std::string call = "bash" + "command\nls"; + + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + ChatGrammar g; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK_EQ(object_admits(g.text, "" + call + call + ""), 1); + /* The inter-call grammar must not swallow an earlier section close as prose. */ + CHECK_EQ(object_admits(g.text, "" + call + "" + + call + ""), 0); + + /* A wrapped dialect whose call close duplicates call_end has no distinct close scanner. + * Its section close must still abandon a malformed call, not close it as executable. */ + f.call_open = ""; + f.call_close = f.call_end; + const auto wrapped = parser_of(f, ro); + REQUIRE(wrapped != nullptr); + bool strict = true; + const std::string malformed = "bashjunk"; + const ReplyMessage m = reply_parse(*wrapped, malformed, &strict); + CHECK(!strict); + REQUIRE(m.calls.size() == 1); + CHECK(!m.calls[0].closed); + const std::string err = stream_all(*wrapped, malformed); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); +} + +TEST(section_wrapped_calls_stream_consistently_at_every_truncation) { + ChatFormat f; + std::string why; + RadChatFormat abi = hyv3_abi(); + CHECK_OK(chat_format_from_abi(&abi, &f, &why)); + ReplyOptions ro; + ro.tools = &agent_tools(); + const auto p = parser_of(f, ro); + REQUIRE(p != nullptr); + const std::string call = "bash" + "command\nls"; + const std::string reply = "" + call + call + ""; + for (size_t n = 0; n <= reply.size(); ++n) { + const std::string err = stream_all(*p, reply.substr(0, n), 0); + if (!err.empty()) { + ::radtest::fail(__FILE__, __LINE__, "truncated at " + std::to_string(n) + ": " + err); + break; + } + } + const ReplyMessage incomplete = reply_parse(*p, "" + call); + REQUIRE(incomplete.calls.size() == 1); + CHECK(!incomplete.calls[0].closed); +} + +TEST(section_wrapped_calls_cannot_bypass_the_wrapper_in_reasoning) { + ChatFormat f; + std::string why; + RadChatFormat abi = hyv3_abi(); + CHECK_OK(chat_format_from_abi(&abi, &f, &why)); + f.reasoning_open = ""; + f.reasoning_close = ""; + f.reasoning_breaks = { f.section_open, f.name_prefix }; + ReplyOptions ro; + ro.tools = &agent_tools(); + const auto p = parser_of(f, ro); + REQUIRE(p != nullptr); + const std::string call = "bash" + "command\nls"; + const std::string text = "Example: " + call + "Answer."; + const ReplyMessage quoted = reply_parse(*p, text); + CHECK(quoted.calls.empty()); + CHECK_EQ(quoted.reasoning, "Example: " + call); + CHECK_EQ(quoted.content, std::string("Answer.")); + const std::string err = stream_all(*p, text); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + + const ReplyMessage actual = reply_parse(*p, "Plan." + call + + ""); + REQUIRE(actual.calls.size() == 1); + CHECK(actual.calls[0].closed); +} + TEST(json_arguments_behind_a_name_tag_read_as_one_object) { std::shared_ptr p = object_format(false); REQUIRE(p != nullptr); diff --git a/tests/data/chat/hyv3/README.md b/tests/data/chat/hyv3/README.md new file mode 100644 index 00000000..a8ea5c44 --- /dev/null +++ b/tests/data/chat/hyv3/README.md @@ -0,0 +1,13 @@ +# Hy-Memory chat-template fixture + +`chat_template.jinja` is an unchanged copy of the template distributed with +[Tencent Hy-Memory-30B-A3B](https://huggingface.co/tencent/Hy-Memory-30B-A3B). + +- Source file: `chat_template.jinja` +- SHA-256: `8759492d33deb19b2f58855f62d3e431276da89d698b2800d1e353fbb12d5320` +- Copyright (C) 2026 Tencent. All rights reserved. +- License: Apache-2.0; see the repository's root `LICENSE` and `NOTICE`. + +Tests use the original template to validate tool-schema rendering, tool-result replay, +reasoning prefixes, and native section-wrapped tool-call parsing. No model weights or +calibration corpus are included in this fixture. diff --git a/tests/data/chat/hyv3/chat_template.jinja b/tests/data/chat/hyv3/chat_template.jinja new file mode 100644 index 00000000..3c754dfa --- /dev/null +++ b/tests/data/chat/hyv3/chat_template.jinja @@ -0,0 +1,233 @@ +{# ----------‑‑‑ special token variables ‑‑‑---------- #} +{%- set HYTK = '' %} +{%- set bos_token = '<|hy_begin▁of▁sentence|>' %} +{%- set pad_token = '<|hy_▁pad▁|>' %} +{%- set user_token = '<|hy_User|>' %} +{%- set assistant_token = '<|hy_Assistant|>' %} +{%- set eos_token = '' %} +{# ----------‑‑‑ tokens with md5 encoding (conditional on HYTK) ‑‑‑---------- #} +{%- if HYTK %} + {%- set think_begin_token = ''.format(HYTK) %} + {%- set think_end_token = ''.format(HYTK) %} + {%- set toolcalls_begin_token = ''.format(HYTK) %} + {%- set toolcalls_end_token = ''.format(HYTK) %} + {%- set toolcall_begin_token = ''.format(HYTK) %} + {%- set toolcall_end_token = ''.format(HYTK) %} + {%- set toolsep_token = ''.format(HYTK) %} + {%- set argkey_begin_token = ''.format(HYTK) %} + {%- set argkey_end_token = ''.format(HYTK) %} + {%- set argvalue_begin_token = ''.format(HYTK) %} + {%- set argvalue_end_token = ''.format(HYTK) %} + {%- set toolresponses_begin_token = ''.format(HYTK) %} + {%- set toolresponses_end_token = ''.format(HYTK) %} + {%- set toolresponse_begin_token = ''.format(HYTK) %} + {%- set toolresponse_end_token = ''.format(HYTK) %} + {%- set reasoning_mode_token = '<|reasoning_mode|>' %} + {%- set toolcalls_begin_ds_token = '<|tool▁calls▁begin|>' %} + {%- set toolcalls_end_ds_token = '<|tool▁calls▁end|>' %} + {%- set toolcall_begin_ds_token = '<|tool▁call▁begin|>' %} + {%- set toolcall_end_ds_token = '<|tool▁call▁end|>' %} + {%- set toolsep_ds_token = '<|tool▁sep|>' %} + {%- set tooloutput_begin_ds_token = '<|tool▁output▁begin|>' %} + {%- set tooloutput_end_ds_token = '<|tool▁output▁end|>' %} +{%- else %} + {%- set think_begin_token = '' %} + {%- set think_end_token = '' %} + {%- set toolcalls_begin_token = '' %} + {%- set toolcalls_end_token = '' %} + {%- set toolcall_begin_token = '' %} + {%- set toolcall_end_token = '' %} + {%- set toolsep_token = '' %} + {%- set argkey_begin_token = '' %} + {%- set argkey_end_token = '' %} + {%- set argvalue_begin_token = '' %} + {%- set argvalue_end_token = '' %} + {%- set toolresponses_begin_token = '' %} + {%- set toolresponses_end_token = '' %} + {%- set toolresponse_begin_token = '' %} + {%- set toolresponse_end_token = '' %} + {%- set reasoning_mode_token = '<|reasoning_mode|>' %} + {%- set toolcalls_begin_ds_token = '<|tool▁calls▁begin|>' %} + {%- set toolcalls_end_ds_token = '<|tool▁calls▁end|>' %} + {%- set toolcall_begin_ds_token = '<|tool▁call▁begin|>' %} + {%- set toolcall_end_ds_token = '<|tool▁call▁end|>' %} + {%- set toolsep_ds_token = '<|tool▁sep|>' %} + {%- set tooloutput_begin_ds_token = '<|tool▁output▁begin|>' %} + {%- set tooloutput_end_ds_token = '<|tool▁output▁end|>' %} +{%- endif %} +{# ----------‑‑‑ hyperparameters variables ‑‑‑---------- #} +{%- if not add_generation_prompt is defined %} + {%- set add_generation_prompt = false %} +{%- endif %} +{%- if not interleaved_thinking is defined %} + {%- set interleaved_thinking = false %} +{%- endif %} +{%- if not tools %} + {%- set interleaved_thinking = false %} +{%- endif %} +{%- if not is_training is defined %} + {%- set is_training = false %} +{%- endif %} +{%- if not is_ai_search is defined %} + {%- set is_ai_search = false %} +{%- endif %} +{%- if not reasoning_effort is defined or reasoning_effort not in ['high', 'low', 'no_think'] %} + {%- set reasoning_effort = 'no_think' %} +{%- endif %} + +{%- macro visible_text(content) -%} + {%- if content is string -%} + {{- content }} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping and item.type == 'text' -%} + {{- item.text }} + {%- elif item is string -%} + {{- item }} + {%- endif -%} + {%- endfor -%} + {%- elif content is none -%} + {{- '' }} + {%- else -%} + {{- content }} + {%- endif -%} +{%- endmacro -%} + +{%- set ns = namespace(last_user_index=-1) %} +{%- set sp_ns = namespace(system_prompt='', is_first_sp=true) %} +{%- for message in messages %} + {%- if message['role'] == 'system' %} + {%- set sp_ns.system_prompt = sp_ns.system_prompt + visible_text(message['content']) %} + {%- endif %} + {%- if message['role'] == 'user' %} + {%- set ns.last_user_index = loop.index0 %} + {%- endif %} +{%- endfor %} +{%- if reasoning_effort is defined and reasoning_effort is string and reasoning_effort != '' and not tools %} + {%- set sp_ns.system_prompt = sp_ns.system_prompt + reasoning_mode_token + 'reasoning_effort:' + reasoning_effort %} +{%- endif %} +{{- bos_token }} +{{- sp_ns.system_prompt }} +{%- if tools %} + {%- if sp_ns.system_prompt != '' %} + {{- '\n\n# Tools\n\nYou may call one or more functions to assist with the user query.' }} + {%- else %} + {{- '# Tools\n\nYou may call one or more functions to assist with the user query.' }} + {%- endif %} + {{- '\n\nYou are provided with function signatures within XML tags:' }} + {{- '\n\n' }} + {%- for tool in tools %} + {%- if loop.index0 > 0 %} + {{- '\n' }} + {%- endif %} + {{- tool | tojson }} + {%- endfor %} + {{- '\n\n\n' }} + {{- 'For function call returns, you should first print ' + toolcalls_begin_token + '\n' }} + {{- 'For each function call, you should return object like:\n' }} + {{- toolcall_begin_token + '{function-name}' + toolsep_token + '\n' }} + {{- argkey_begin_token + '{arg-key-1}' + argkey_end_token + '\n' }} + {{- argvalue_begin_token + '{arg-value-1}' + argvalue_end_token + '\n' }} + {{- argkey_begin_token + '{arg-key-2}' + argkey_end_token + '\n' }} + {{- argvalue_begin_token + '{arg-value-2}' + argvalue_end_token + '\n' }} + {{- '...\n' }} + {{- toolcall_end_token + '\n' }} + {%- if reasoning_effort is defined and reasoning_effort is string and reasoning_effort != '' %} + {{- 'At the end of function call returns, you should print ' + toolcalls_end_token + reasoning_mode_token + 'reasoning_effort:' + reasoning_effort }} + {%- else %} + {{- 'At the end of function call returns, you should print ' + toolcalls_end_token }} + {%- endif %} +{%- endif %} + +{%- set prev_ns = namespace(is_tool=false, is_tool_first=true) %} +{%- set last_ns = namespace(last_is_assistant=false) %} +{%- for message in messages %} + {%- if message['role'] == 'user' %} + {%- if prev_ns.is_tool and not is_ai_search %} + {{- toolresponses_end_token }} + {%- endif %} + {{- user_token + visible_text(message['content']) }} + {%- set prev_ns.is_tool = false %} + {%- endif %} + {%- if message['role'] == 'assistant' %} + {%- if is_training %} + {%- if 'reasoning_content' in message and message['reasoning_content'] is string %} + {%- set content = think_begin_token + message['reasoning_content'] + think_end_token + visible_text(message['content']) %} + {%- else %} + {%- set content = think_begin_token + think_end_token + visible_text(message['content']) %} + {%- endif %} + {%- else %} + {%- if interleaved_thinking %} + {%- if loop.index0 > ns.last_user_index and 'reasoning_content' in message and message['reasoning_content'] is string %} + {%- set content = think_begin_token + message['reasoning_content'] + think_end_token + visible_text(message['content']) %} + {%- else %} + {%- set content = think_begin_token + think_end_token + visible_text(message['content']) %} + {%- endif %} + {%- else %} + {%- set content = think_begin_token + think_end_token + visible_text(message['content']) %} + {%- endif %} + {%- endif %} + {%- if prev_ns.is_tool and not is_ai_search %} + {{- toolresponses_end_token }} + {%- endif %} + {{- assistant_token }} + {%- if message['tool_calls'] is defined and message['tool_calls'] %} + {%- set prev_ns.is_tool_first = true %} + {{- content }} + {{- toolcalls_begin_token + '\n' }} + {%- for tool in message['tool_calls'] %} + {%- set arguments = tool['function']['arguments'] %} + {{- toolcall_begin_token + tool['function']['name'] + toolsep_token + '\n' }} + {%- for key, value in arguments.items() %} + {{- argkey_begin_token + key + argkey_end_token + '\n' }} + {%- if value is not string %} + {%- set value = value | tojson(ensure_ascii=False) %} + {%- endif %} + {{- argvalue_begin_token + value + argvalue_end_token + '\n' }} + {%- endfor %} + {{- toolcall_end_token + '\n' }} + {%- endfor %} + {{- toolcalls_end_token + eos_token }} + {%- else %} + {%- if not loop.last or is_training %} + {{- content + eos_token }} + {%- else %} + {{- content }} + {%- endif %} + {%- endif %} + {%- set prev_ns.is_tool = false %} + {%- endif %} + {%- if message['role'] == 'tool' %} + {%- set prev_ns.is_tool = true %} + {%- if prev_ns.is_tool_first and not is_ai_search %} + {{- toolresponses_begin_token + '\n' }} + {%- set prev_ns.is_tool_first = false %} + {%- endif %} + {%- if is_ai_search %} + {{- tooloutput_begin_ds_token + visible_text(message['content']) + tooloutput_end_ds_token }} + {%- else %} + {{- toolresponse_begin_token + '\n' + visible_text(message['content']) + '\n' + toolresponse_end_token + '\n' }} + {%- endif %} + {%- endif %} + {%- if loop.last and message['role'] == 'assistant' %} + {%- set last_ns.last_is_assistant = true %} + {%- endif %} + +{%- endfor %} +{%- if prev_ns.is_tool and not is_ai_search %} + {{- toolresponses_end_token }} +{%- endif %} +{%- if add_generation_prompt %} + {%- if not last_ns.last_is_assistant %} + {%- if is_ai_search %} + {{- assistant_token }} + {{- think_begin_token + think_end_token }} + {%- elif reasoning_effort is defined and reasoning_effort in ['low', 'high'] %} + {{- assistant_token + think_begin_token }} + {%- elif reasoning_effort is defined and reasoning_effort == 'no_think' %} + {{- assistant_token + think_begin_token + think_end_token }} + {%- else %} + {{- assistant_token }} + {%- endif %} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/tests/server_fakes.h b/tests/server_fakes.h index ea5b6aa1..a96b6c76 100644 --- a/tests/server_fakes.h +++ b/tests/server_fakes.h @@ -370,6 +370,34 @@ inline std::shared_ptr qwen_reply_parser(const json& tools) { return std::make_shared(rp); } +/* Hy-Memory's native outer call section, name prefix, and tagged argument wire format. */ +inline std::shared_ptr hyv3_reply_parser(const json& tools) { + ChatFormat f; + f.reasoning_open = ""; + f.reasoning_close = ""; + f.reasoning_breaks = { "" }; + f.section_open = ""; + f.section_close = ""; + f.name_prefix = ""; + f.name_suffix = ""; + f.call_end = ""; + f.arg_prefix = ""; + f.arg_name_suffix = "\n"; + f.arg_value_prefix = ""; + f.arg_value_suffix = ""; + f.string_value = ChatValue::Raw; + f.other_value = ChatValue::Json; + f.triggers = { "" }; + std::shared_ptr rf; + std::string why; + if (ReplyFormat::compile(f, &rf, &why) < 0) return nullptr; + ReplyOptions ro; + ro.tools = &tools; + std::shared_ptr rp; + if (ReplyParser::create(rf, ro, &rp, &why) < 0) return nullptr; + return std::make_shared(rp); +} + struct FakeGrammar : IGrammarCompiler { int from_json_schema(const json&, std::string& out, std::string&) const override { out = "root ::= object"; diff --git a/tests/server_test.cpp b/tests/server_test.cpp index f046f719..ef8ab8fe 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -621,6 +621,94 @@ TEST(a_complete_tool_call_is_reported_as_tool_calls) { CHECK(c["message"]["content"].is_null()); } +TEST(hyv3_native_markup_flows_through_openai_tools_api) { + const json tools = json::parse(R"([{ + "type":"function","function":{"name":"lookup_weather","parameters":{"type":"object", + "properties":{"city":{"type":"string"}},"required":["city"]}}}, + {"type":"function","function":{"name":"add","parameters":{"type":"object", + "properties":{"a":{"type":"integer"},"b":{"type":"integer"}},"required":["a","b"]}}}])"); + const json messages = json::array({ + {{"role", "user"}, {"content", "Check Toronto weather and add 20 and 22."}}, + {{"role", "assistant"}, {"content", nullptr}, + {"tool_calls", json::array({ + {{"id", "call-weather"}, {"type", "function"}, + {"function", {{"name", "lookup_weather"}, + {"arguments", "{\"city\":\"Toronto\"}"}}}}, + {{"id", "call-add"}, {"type", "function"}, + {"function", {{"name", "add"}, {"arguments", "{\"a\":20,\"b\":22}"}}}} + })}}, + {{"role", "tool"}, {"tool_call_id", "call-weather"}, {"content", "Cloudy, 12 C."}}, + {{"role", "tool"}, {"tool_call_id", "call-add"}, {"content", "42"}}, + {{"role", "user"}, {"content", "Summarize the results."}} + }); + const std::string reply = + "The weather is cloudy, and the sum is 42.\n\n" + "lookup_weather\n" + "city\nToronto\n\n" + "add\n" + "a\n20\n" + "b\n22\n\n"; + Fixture f; + f.tmpl.real_parser = hyv3_reply_parser(tools); + REQUIRE(f.tmpl.real_parser != nullptr); + f.sched.reply = reply; + const std::string body = json({{"messages", messages}, {"tools", tools}, + {"parallel_tool_calls", true}, {"max_tokens", 512}}).dump(); + + HttpResponse buffered = f.post("/v1/chat/completions", body); + CHECK_EQ(buffered.status, 200); + const json c = json::parse(buffered.body)["choices"][0]; + CHECK_EQ(c["finish_reason"].get(), std::string("tool_calls")); + CHECK_EQ(c["message"]["content"].get(), + std::string("The weather is cloudy, and the sum is 42.")); + REQUIRE(c["message"]["tool_calls"].size() == 2); + CHECK_EQ(c["message"]["tool_calls"][0]["function"]["name"].get(), + std::string("lookup_weather")); + CHECK_EQ(c["message"]["tool_calls"][0]["function"]["arguments"].get(), + std::string("{\"city\":\"Toronto\"}")); + CHECK_EQ(c["message"]["tool_calls"][1]["function"]["name"].get(), + std::string("add")); + CHECK_EQ(c["message"]["tool_calls"][1]["function"]["arguments"].get(), + std::string("{\"a\":20,\"b\":22}")); + CHECK_EQ(f.tmpl.last_tool_msgs, 2); + CHECK(has(f.tmpl.last_prompt, "Summarize the results.")); + + HttpResponse streamed = f.post("/v1/chat/completions", + json({{"messages", messages}, {"tools", tools}, + {"stream", true}, {"max_tokens", 512}}).dump()); + CHECK_EQ(streamed.status, 200); + int bad = 0; + std::string finish, content; + std::vector names, arguments; + for (const std::string& payload : sse_payloads(drain(streamed), &bad)) { + if (payload == "[DONE]") continue; + const json event = json::parse(payload); + if (event["choices"].empty()) continue; + const json& choice = event["choices"][0]; + if (!choice["finish_reason"].is_null()) + finish = choice["finish_reason"].get(); + const json& delta = choice["delta"]; + if (delta.contains("content")) content += delta["content"].get(); + if (!delta.contains("tool_calls")) continue; + for (const json& call : delta["tool_calls"]) { + const size_t i = call["index"].get(); + if (i >= names.size()) { names.resize(i + 1); arguments.resize(i + 1); } + if (call.contains("function") && call["function"].contains("name")) + names[i] = call["function"]["name"].get(); + if (call.contains("function") && call["function"].contains("arguments")) + arguments[i] += call["function"]["arguments"].get(); + } + } + CHECK_EQ(bad, 0); + CHECK_EQ(finish, std::string("tool_calls")); + CHECK_EQ(content, std::string("The weather is cloudy, and the sum is 42.")); + REQUIRE(names.size() == 2); + CHECK_EQ(names[0], std::string("lookup_weather")); + CHECK_EQ(arguments[0], std::string("{\"city\":\"Toronto\"}")); + CHECK_EQ(names[1], std::string("add")); + CHECK_EQ(arguments[1], std::string("{\"a\":20,\"b\":22}")); +} + /* The three spellings of "do not think" must all reach the template, and the kwarg must reach * both places: the lift overwrites the context key `enable_thinking` with its own field * (chat-auto-parser-helpers.cpp), so a kwarg not also lifted into the field would be discarded