Skip to content

Commit 1209b95

Browse files
committed
Only invoke toolcall with valid JSON
1 parent 8a3497b commit 1209b95

File tree

2 files changed

+24
-19
lines changed

2 files changed

+24
-19
lines changed

examples/main/main.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include "sampling.h"
66
#include "llama.h"
77
#include "chat.h"
8+
#include <json.hpp>
89

910
#include <cstdio>
1011
#include <cstring>
@@ -126,12 +127,17 @@ class chat_formatter {
126127
LOG_DBG("formatted: '%s'\n", formatted.c_str());
127128

128129
#ifdef LLAMA_USE_TOOLCALL
129-
if (params_.use_jinja) {
130+
if (params_.use_jinja && use_toolcalls) {
130131
common_chat_grammar_to_sampler(&cparams, vocab_, &params_.sampling);
131132
if (tc_handler_ != nullptr) {
132-
std::string response;
133-
tc_handler_->call(formatted, response);
134-
return std::string(response);
133+
if (nlohmann::json::accept(formatted)) { // May need a better way to ensure
134+
std::string response; // this is intended for a tool-call.
135+
tc_handler_->call(formatted, response);
136+
return std::string(response);
137+
138+
} else {
139+
return formatted;
140+
}
135141
}
136142
}
137143
#endif

toolcall/handler.cpp

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -134,30 +134,29 @@ void toolcall::mcp_impl::initialize() {
134134
static std::string tools_list_to_oai_json(const mcp::tools_list & tools) {
135135
json tool_list = json::array();
136136
for (const auto & tool : tools) {
137-
json props;
137+
json t = json::object();
138+
139+
t["type"] = "function";
140+
t["function"]["name"] = tool.tool_name;
141+
t["function"]["description"] = tool.tool_description;
142+
143+
json props = json::object();
138144
for (const auto & param : tool.params) {
139145
props[param.name]["type"] = param.type;
140146
props[param.name]["description"] = param.description;
141147
}
148+
t["function"]["parameters"]["type"] = "object";
149+
t["function"]["parameters"]["properties"] = props;
150+
142151
json required = json::array();
143152
for (const auto & name : tool.required_params) {
144153
required.push_back(name);
145154
}
146-
tool_list.push_back({
147-
{"type", "function"},
148-
{"function", {
149-
{"name", tool.tool_name},
150-
{"description", tool.tool_description},
151-
{"parameters", {
152-
{"type", "object"},
153-
{"properties", props}
154-
}
155-
},
156-
{"required", required}
157-
}
158-
}
159-
});
155+
t["function"]["required"] = required;
156+
157+
tool_list.push_back(t);
160158
}
159+
161160
return tool_list.dump(-1);
162161
}
163162

0 commit comments

Comments
 (0)