Archived
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.
This commit is contained in:
1 parent
7621e4ac2b
commit
7e04bcac2b
11 files changed
+840
-34
No files matched your search
@@ -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|>", "<eos:6124c78e>");
|
||||
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("<tools>") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("<tool_calls>") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("<tool_call>{function-name}<tool_sep>") != 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("<tool_calls>") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("<tool_call>lookup_weather<tool_sep>") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("<arg_key>city</arg_key>") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("Toronto") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("<tool_responses>") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("Cloudy, 12 C.") != std::string::npos);
|
||||
CHECK(prompt.prompt.find("<tool_response>\n42\n</tool_response>") != 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();
|
||||
|
||||
+251
-1
@@ -1052,6 +1052,33 @@ TEST(no_template_is_a_format_with_no_reasoning_and_no_calls) {
|
||||
static const char* const kBreaks[] = { "<tool_call>\n" };
|
||||
static const char* const kTriggers[] = { "<tool_call>\n" };
|
||||
|
||||
static RadChatFormat hyv3_abi() {
|
||||
static const char* const triggers[] = { "<tool_calls>" };
|
||||
RadChatFormat c;
|
||||
std::memset(&c, 0, sizeof c);
|
||||
c.struct_size = sizeof c;
|
||||
c.name = "hyv3-native";
|
||||
c.reasoning_open = "<think>";
|
||||
c.reasoning_close = "</think>";
|
||||
c.reasoning_breaks = triggers;
|
||||
c.n_reasoning_breaks = 1;
|
||||
c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
|
||||
c.section_open = "<tool_calls>";
|
||||
c.section_close = "</tool_calls>";
|
||||
c.name_prefix = "<tool_call>";
|
||||
c.name_suffix = "<tool_sep>";
|
||||
c.call_end = "</tool_call>";
|
||||
c.arg_prefix = "<arg_key>";
|
||||
c.arg_name_suffix = "</arg_key>\n";
|
||||
c.arg_value_prefix = "<arg_value>";
|
||||
c.arg_value_suffix = "</arg_value>";
|
||||
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 = "</function>\n"; }, "told apart"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.reasoning_close = ""; }, "reasoning_close"));
|
||||
static const char* const other[] = { "<call>" };
|
||||
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<Vocab> 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("<tool_calls>"));
|
||||
for (const char* marker : { "<think>", "</think>", "<tool_calls>", "</tool_calls>",
|
||||
"<tool_call>", "<tool_sep>",
|
||||
"<arg_key>", "</arg_key>", "<arg_value>", "</arg_value>" })
|
||||
CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), marker) !=
|
||||
r.preserved_tokens.end());
|
||||
REQUIRE(r.parser != nullptr);
|
||||
std::unique_ptr<server::IReplyReader> rd = r.parser->open();
|
||||
rd->feed("Cloudy.\n<tool_calls><tool_call>lookup_weather<tool_sep>\n"
|
||||
"<arg_key>city</arg_key>\n<arg_value>Toronto</arg_value>\n"
|
||||
"</tool_call></tool_calls>", 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<Vocab> 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("<think>"));
|
||||
auto rd = out.parser->open();
|
||||
rd->feed("Plan.</think>Checking.<tool_calls><tool_call>bash<tool_sep>"
|
||||
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value>"
|
||||
"</tool_call></tool_calls>", 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 `<tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value></tool_call>`. 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<const ReplyParser> p = parser_of(f, ro);
|
||||
REQUIRE(p != nullptr);
|
||||
const std::string reply =
|
||||
"Checking both results.<tool_calls>\n"
|
||||
"<tool_call>lookup_weather<tool_sep>\n"
|
||||
"<arg_key>city</arg_key>\n<arg_value>Québec & Montréal</arg_value>\n"
|
||||
"</tool_call>\n"
|
||||
"<tool_call>add<tool_sep>\n"
|
||||
"<arg_key>a</arg_key>\n<arg_value>20</arg_value>\n"
|
||||
"<arg_key>b</arg_key>\n<arg_value>22</arg_value>\n"
|
||||
"</tool_call>\n</tool_calls>";
|
||||
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("<tool_calls>") == std::string::npos);
|
||||
CHECK(m.content.find("</tool_calls>") == 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<std::string>{ "<tool_calls>" });
|
||||
const size_t section = reply.find("<tool_calls>");
|
||||
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: <tool_call>add<tool_sep>";
|
||||
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 =
|
||||
"<tool_calls>\n<tool_call>add<tool_sep>\n"
|
||||
"<arg_key>a</arg_key>\n<arg_value>20</arg_value>\n</tool_calls>";
|
||||
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 = "<tool_call>bash<tool_sep>"
|
||||
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value></tool_call>";
|
||||
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &agent_tools();
|
||||
ChatGrammar g;
|
||||
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
|
||||
CHECK_EQ(object_admits(g.text, "<tool_calls>" + call + call + "</tool_calls>"), 1);
|
||||
/* The inter-call grammar must not swallow an earlier section close as prose. */
|
||||
CHECK_EQ(object_admits(g.text, "<tool_calls>" + call + "</tool_calls>" +
|
||||
call + "</tool_calls>"), 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 = "<call>";
|
||||
f.call_close = f.call_end;
|
||||
const auto wrapped = parser_of(f, ro);
|
||||
REQUIRE(wrapped != nullptr);
|
||||
bool strict = true;
|
||||
const std::string malformed = "<tool_calls><call><tool_call>bash<tool_sep>junk</tool_calls>";
|
||||
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 = "<tool_call>bash<tool_sep>"
|
||||
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value></tool_call>";
|
||||
const std::string reply = "<tool_calls>" + call + call + "</tool_calls>";
|
||||
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, "<tool_calls>" + 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 = "<think>";
|
||||
f.reasoning_close = "</think>";
|
||||
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 = "<tool_call>bash<tool_sep>"
|
||||
"<arg_key>command</arg_key>\n<arg_value>ls</arg_value></tool_call>";
|
||||
const std::string text = "<think>Example: " + call + "</think>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, "<think>Plan.<tool_calls>" + call +
|
||||
"</tool_calls>");
|
||||
REQUIRE(actual.calls.size() == 1);
|
||||
CHECK(actual.calls[0].closed);
|
||||
}
|
||||
|
||||
TEST(json_arguments_behind_a_name_tag_read_as_one_object) {
|
||||
std::shared_ptr<const ReplyParser> p = object_format(false);
|
||||
REQUIRE(p != nullptr);
|
||||
|
||||
@@ -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.
|
||||
@@ -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 = '<eos:6124c78e>' %}
|
||||
{# ----------‑‑‑ tokens with md5 encoding (conditional on HYTK) ‑‑‑---------- #}
|
||||
{%- if HYTK %}
|
||||
{%- set think_begin_token = '<think:{}>'.format(HYTK) %}
|
||||
{%- set think_end_token = '</think:{}>'.format(HYTK) %}
|
||||
{%- set toolcalls_begin_token = '<tool_calls:{}>'.format(HYTK) %}
|
||||
{%- set toolcalls_end_token = '</tool_calls:{}>'.format(HYTK) %}
|
||||
{%- set toolcall_begin_token = '<tool_call:{}>'.format(HYTK) %}
|
||||
{%- set toolcall_end_token = '</tool_call:{}>'.format(HYTK) %}
|
||||
{%- set toolsep_token = '<tool_sep:{}>'.format(HYTK) %}
|
||||
{%- set argkey_begin_token = '<arg_key:{}>'.format(HYTK) %}
|
||||
{%- set argkey_end_token = '</arg_key:{}>'.format(HYTK) %}
|
||||
{%- set argvalue_begin_token = '<arg_value:{}>'.format(HYTK) %}
|
||||
{%- set argvalue_end_token = '</arg_value:{}>'.format(HYTK) %}
|
||||
{%- set toolresponses_begin_token = '<tool_responses:{}>'.format(HYTK) %}
|
||||
{%- set toolresponses_end_token = '</tool_responses:{}>'.format(HYTK) %}
|
||||
{%- set toolresponse_begin_token = '<tool_response:{}>'.format(HYTK) %}
|
||||
{%- set toolresponse_end_token = '</tool_response:{}>'.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 = '<think>' %}
|
||||
{%- set think_end_token = '</think>' %}
|
||||
{%- set toolcalls_begin_token = '<tool_calls>' %}
|
||||
{%- set toolcalls_end_token = '</tool_calls>' %}
|
||||
{%- set toolcall_begin_token = '<tool_call>' %}
|
||||
{%- set toolcall_end_token = '</tool_call>' %}
|
||||
{%- set toolsep_token = '<tool_sep>' %}
|
||||
{%- set argkey_begin_token = '<arg_key>' %}
|
||||
{%- set argkey_end_token = '</arg_key>' %}
|
||||
{%- set argvalue_begin_token = '<arg_value>' %}
|
||||
{%- set argvalue_end_token = '</arg_value>' %}
|
||||
{%- set toolresponses_begin_token = '<tool_responses>' %}
|
||||
{%- set toolresponses_end_token = '</tool_responses>' %}
|
||||
{%- set toolresponse_begin_token = '<tool_response>' %}
|
||||
{%- set toolresponse_end_token = '</tool_response>' %}
|
||||
{%- 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 <tools></tools> XML tags:' }}
|
||||
{{- '\n<tools>\n' }}
|
||||
{%- for tool in tools %}
|
||||
{%- if loop.index0 > 0 %}
|
||||
{{- '\n' }}
|
||||
{%- endif %}
|
||||
{{- tool | tojson }}
|
||||
{%- endfor %}
|
||||
{{- '\n</tools>\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 %}
|
||||
@@ -370,6 +370,34 @@ inline std::shared_ptr<IReplyParser> qwen_reply_parser(const json& tools) {
|
||||
return std::make_shared<ReplyParserBridge>(rp);
|
||||
}
|
||||
|
||||
/* Hy-Memory's native outer call section, name prefix, and tagged argument wire format. */
|
||||
inline std::shared_ptr<IReplyParser> hyv3_reply_parser(const json& tools) {
|
||||
ChatFormat f;
|
||||
f.reasoning_open = "<think>";
|
||||
f.reasoning_close = "</think>";
|
||||
f.reasoning_breaks = { "<tool_calls>" };
|
||||
f.section_open = "<tool_calls>";
|
||||
f.section_close = "</tool_calls>";
|
||||
f.name_prefix = "<tool_call>";
|
||||
f.name_suffix = "<tool_sep>";
|
||||
f.call_end = "</tool_call>";
|
||||
f.arg_prefix = "<arg_key>";
|
||||
f.arg_name_suffix = "</arg_key>\n";
|
||||
f.arg_value_prefix = "<arg_value>";
|
||||
f.arg_value_suffix = "</arg_value>";
|
||||
f.string_value = ChatValue::Raw;
|
||||
f.other_value = ChatValue::Json;
|
||||
f.triggers = { "<tool_calls>" };
|
||||
std::shared_ptr<const ReplyFormat> rf;
|
||||
std::string why;
|
||||
if (ReplyFormat::compile(f, &rf, &why) < 0) return nullptr;
|
||||
ReplyOptions ro;
|
||||
ro.tools = &tools;
|
||||
std::shared_ptr<const ReplyParser> rp;
|
||||
if (ReplyParser::create(rf, ro, &rp, &why) < 0) return nullptr;
|
||||
return std::make_shared<ReplyParserBridge>(rp);
|
||||
}
|
||||
|
||||
struct FakeGrammar : IGrammarCompiler {
|
||||
int from_json_schema(const json&, std::string& out, std::string&) const override {
|
||||
out = "root ::= object";
|
||||
|
||||
@@ -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<tool_calls>\n"
|
||||
"<tool_call>lookup_weather<tool_sep>\n"
|
||||
"<arg_key>city</arg_key>\n<arg_value>Toronto</arg_value>\n</tool_call>\n"
|
||||
"<tool_call>add<tool_sep>\n"
|
||||
"<arg_key>a</arg_key>\n<arg_value>20</arg_value>\n"
|
||||
"<arg_key>b</arg_key>\n<arg_value>22</arg_value>\n</tool_call>\n</tool_calls>";
|
||||
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>(), std::string("tool_calls"));
|
||||
CHECK_EQ(c["message"]["content"].get<std::string>(),
|
||||
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>(),
|
||||
std::string("lookup_weather"));
|
||||
CHECK_EQ(c["message"]["tool_calls"][0]["function"]["arguments"].get<std::string>(),
|
||||
std::string("{\"city\":\"Toronto\"}"));
|
||||
CHECK_EQ(c["message"]["tool_calls"][1]["function"]["name"].get<std::string>(),
|
||||
std::string("add"));
|
||||
CHECK_EQ(c["message"]["tool_calls"][1]["function"]["arguments"].get<std::string>(),
|
||||
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<std::string> 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<std::string>();
|
||||
const json& delta = choice["delta"];
|
||||
if (delta.contains("content")) content += delta["content"].get<std::string>();
|
||||
if (!delta.contains("tool_calls")) continue;
|
||||
for (const json& call : delta["tool_calls"]) {
|
||||
const size_t i = call["index"].get<size_t>();
|
||||
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<std::string>();
|
||||
if (call.contains("function") && call["function"].contains("arguments"))
|
||||
arguments[i] += call["function"]["arguments"].get<std::string>();
|
||||
}
|
||||
}
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user