Skip to content

Commit a097b4f

Browse files
committed
Add tighter check before running toolcalls
1 parent 7b076ee commit a097b4f

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

examples/main/main.cpp

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -846,20 +846,33 @@ int main(int argc, char ** argv) {
846846
if (params.enable_chat_template) {
847847
chat_add_and_format("assistant", assistant_ss.str(), true);
848848
#ifdef LLAMA_USE_TOOLCALL
849-
if (! params.use_jinja || tc_handler == nullptr || ! nlohmann::json::accept(assistant_ss.str())) {
850-
is_interacting = true;
851-
LOG("\n");
849+
auto should_use_toolcall = [&params, tc_handler] (const std::string & asst_msg) {
850+
if (! params.use_jinja || tc_handler == nullptr) {
851+
return false;
852+
}
853+
try {
854+
nlohmann::json j = nlohmann::json::parse(asst_msg);
855+
return (j.contains("name") && j.contains("parameters"));
852856

853-
} else {
857+
} catch (const nlohmann::json::exception & err) {
858+
return false;
859+
}
860+
};
861+
862+
if (should_use_toolcall(assistant_ss.str())) {
854863
toolcall::result_set res = tc_handler->call(assistant_ss.str());
855864
if (! res.empty()) {
856865
std::string toolcall_result_str;
857866
for (const auto & r : res) {
858-
toolcall_result_str += (r.data + "\n");
867+
toolcall_result_str += ("\n" + r.data);
859868
}
860869
auto toolcall_result_tok = common_tokenize(ctx, toolcall_result_str, false, true);
861870
embd_inp.insert(embd_inp.end(), toolcall_result_tok.begin(), toolcall_result_tok.end());
862871
}
872+
873+
} else {
874+
is_interacting = true;
875+
LOG("\n");
863876
}
864877
#else
865878

0 commit comments

Comments
 (0)