Skip to content

Commit cd0d7f0

Browse files
authored
Merge branch 'ikawrakow:main' into main
2 parents a09bed8 + d60c8f4 commit cd0d7f0

39 files changed

+4728
-188
lines changed

common/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ set(TARGET common)
5252

5353
add_library(${TARGET} STATIC
5454
base64.hpp
55+
chat-template.hpp
5556
common.h
5657
common.cpp
5758
chat.h
@@ -72,6 +73,7 @@ add_library(${TARGET} STATIC
7273
json-schema-to-grammar.cpp
7374
train.h
7475
train.cpp
76+
minja.hpp
7577
ngram-cache.h
7678
ngram-cache.cpp
7779
)

common/chat-parser.cpp

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -82,28 +82,38 @@ bool common_chat_msg_parser::try_consume_literal(const std::string & literal) {
8282
}
8383

8484
bool common_chat_msg_parser::try_parse_reasoning(const std::string & start_think, const std::string & end_think) {
85-
auto start_pos = input_.find(start_think, pos_);
86-
if (start_pos == std::string::npos) {
87-
return false;
88-
}
85+
auto handle_reasoning = [&](const std::string & reasoning, bool closed) {
86+
auto stripped_reasoning = string_strip(reasoning);
87+
if (stripped_reasoning.empty()) {
88+
return;
89+
}
90+
if (syntax_.reasoning_in_content) {
91+
add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "<think>" : start_think);
92+
add_content(stripped_reasoning);
93+
if (closed) {
94+
add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "</think>" : end_think);
95+
}
96+
} else {
97+
add_reasoning_content(stripped_reasoning);
98+
}
99+
};
89100

90-
auto end_pos = input_.find(end_think, start_pos + start_think.size());
91-
if (end_pos == std::string::npos) {
92-
if (is_partial_) {
93-
// Partial reasoning content
94-
auto reasoning = input_.substr(start_pos + start_think.size());
95-
add_reasoning_content(string_strip(reasoning));
96-
pos_ = input_.size();
101+
if (syntax_.reasoning_format != COMMON_REASONING_FORMAT_NONE) {
102+
if (syntax_.thinking_forced_open || try_consume_literal(start_think)) {
103+
if (auto res = try_find_literal(end_think)) {
104+
handle_reasoning(res->prelude, /* closed */ true);
105+
consume_spaces();
106+
return true;
107+
}
108+
auto rest = consume_rest();
109+
if (!rest.empty()) {
110+
handle_reasoning(rest, /* closed */ !is_partial());
111+
}
112+
// Allow unclosed thinking tags for now (following original llama.cpp)
97113
return true;
98114
}
99-
return false;
100115
}
101-
102-
// Extract reasoning content
103-
auto reasoning = input_.substr(start_pos + start_think.size(), end_pos - start_pos - start_think.size());
104-
add_reasoning_content(string_strip(reasoning));
105-
pos_ = end_pos + end_think.size();
106-
return true;
116+
return false;
107117
}
108118

109119
std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_find_literal_legacy(const std::string & literal) {

common/chat-template.hpp

Lines changed: 249 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
/*
2+
Copyright 2024 Google LLC
3+
4+
Use of this source code is governed by an MIT-style
5+
license that can be found in the LICENSE file or at
6+
https://opensource.org/licenses/MIT.
7+
*/
8+
// SPDX-License-Identifier: MIT
9+
#pragma once
10+
11+
#include "minja.hpp"
12+
#include <json.hpp>
13+
#include <string>
14+
#include <vector>
15+
16+
using json = nlohmann::ordered_json;
17+
18+
namespace minja {
19+
20+
class chat_template {
21+
public:
22+
23+
private:
24+
bool supports_tools_ = true;
25+
// Meta-Llama-3.1-8B-Instruct's template expects arguments to be an object.
26+
// Most other templates (and OpenAI's API) expect the arguments object to be stringified.
27+
bool requires_object_arguments_ = false;
28+
bool supports_system_role_ = true;
29+
bool supports_parallel_tool_calls_ = false;
30+
std::string source_;
31+
std::string bos_token_;
32+
std::string eos_token_;
33+
std::shared_ptr<minja::TemplateNode> template_root_;
34+
35+
std::string try_render(
36+
const nlohmann::ordered_json & messages,
37+
const nlohmann::ordered_json & tools,
38+
bool add_generation_prompt,
39+
const nlohmann::ordered_json & extra_context = nlohmann::ordered_json()) const
40+
{
41+
try {
42+
auto prompt = apply(messages, tools, add_generation_prompt, extra_context);
43+
// fprintf(stderr, "Prompt: %s\n", prompt.c_str());
44+
return prompt;
45+
} catch (const std::exception & e) {
46+
// fprintf(stderr, "Error: %s\n", e.what());
47+
return "";
48+
}
49+
}
50+
51+
public:
52+
chat_template(const std::string & source, const std::string & bos_token, const std::string & eos_token)
53+
: source_(source), bos_token_(bos_token), eos_token_(eos_token)
54+
{
55+
template_root_ = minja::Parser::parse(source_, {
56+
/* .trim_blocks = */ true,
57+
/* .lstrip_blocks = */ true,
58+
/* .keep_trailing_newline = */ false,
59+
});
60+
supports_tools_ = source.find("tools") != std::string::npos;
61+
62+
auto renders_string_arguments =
63+
try_render({
64+
{
65+
{"role", "user"},
66+
{"content", "Hey"}
67+
},
68+
{
69+
{"role", "assistant"},
70+
{"tool_calls", json::array({
71+
{
72+
{"id", "call_1___"},
73+
{"type", "function"},
74+
{"function", {
75+
{"arguments", "{\"code\": \"print('Hello, World!')\"}"},
76+
{"name", "ipython"},
77+
}},
78+
},
79+
})},
80+
}
81+
}, {}, false).find("{\"code\": \"print") != std::string::npos;
82+
if (!renders_string_arguments) {
83+
auto renders_object_arguments =
84+
try_render({
85+
{
86+
{"role", "user"},
87+
{"content", "Hey"}
88+
},
89+
{
90+
{"role", "assistant"},
91+
{"tool_calls", json::array({
92+
{
93+
{"id", "call_1___"},
94+
{"type", "function"},
95+
{"function", {
96+
{"arguments", {
97+
{"code", "print('Hello, World!')"},
98+
}},
99+
{"name", "ipython"},
100+
}},
101+
},
102+
})},
103+
}
104+
}, {}, false).find("{\"code\": \"print") != std::string::npos;
105+
requires_object_arguments_ = renders_object_arguments;
106+
}
107+
supports_parallel_tool_calls_ = source.find("tool_call_id") != std::string::npos;
108+
109+
supports_system_role_ = try_render({
110+
{{"role", "system"}, {"content", "<System Needle>"}},
111+
{{"role", "user"}, {"content", "Hey"}}
112+
}, {}, false).find("<System Needle>") != std::string::npos;
113+
}
114+
115+
const std::string & source() const { return source_; }
116+
const std::string & bos_token() const { return bos_token_; }
117+
const std::string & eos_token() const { return eos_token_; }
118+
bool supports_tools() const { return supports_tools_; }
119+
bool supports_parallel_tool_calls() const { return supports_parallel_tool_calls_; }
120+
121+
std::string apply(
122+
const nlohmann::ordered_json & messages,
123+
const nlohmann::ordered_json & tools,
124+
bool add_generation_prompt,
125+
const nlohmann::ordered_json & extra_context = nlohmann::ordered_json()) const
126+
{
127+
json actual_messages;
128+
129+
// First, "fix" messages so they have a chance to be rendered correctly by the template
130+
131+
if (requires_object_arguments_ || !supports_system_role_ || !supports_tools_) {
132+
actual_messages = json::array();
133+
134+
std::string pending_system;
135+
auto flush_sys = [&]() {
136+
if (!pending_system.empty()) {
137+
actual_messages.push_back({
138+
{"role", "user"},
139+
{"content", pending_system},
140+
});
141+
pending_system.clear();
142+
}
143+
};
144+
for (const auto & message_ : messages) {
145+
auto message = message_;
146+
if (!message.contains("role") || !message.contains("content")) {
147+
throw std::runtime_error("message must have 'role' and 'content' fields: " + message.dump());
148+
}
149+
std::string role = message.at("role");
150+
151+
if (message.contains("tool_calls")) {
152+
if (requires_object_arguments_ || !supports_tools_) {
153+
for (auto & tool_call : message.at("tool_calls")) {
154+
if (tool_call["type"] == "function") {
155+
auto & function = tool_call.at("function");
156+
std::string arguments = function.at("arguments");
157+
function["arguments"] = json::parse(arguments);
158+
}
159+
}
160+
}
161+
if (!supports_tools_) {
162+
auto content = message.at("content");
163+
auto tool_calls = json::array();
164+
for (const auto & tool_call : message.at("tool_calls")) {
165+
if (tool_call.at("type") != "function") {
166+
continue;
167+
}
168+
const auto & function = tool_call.at("function");
169+
auto tc = json {
170+
{"name", function.at("name")},
171+
{"arguments", function.at("arguments")},
172+
};
173+
if (tool_call.contains("id")) {
174+
tc["id"] = tool_call["id"];
175+
}
176+
tool_calls.push_back(tc);
177+
}
178+
auto obj = json {
179+
{"tool_calls", tool_calls},
180+
};
181+
if (!content.is_null() && content != "") {
182+
obj["content"] = content;
183+
}
184+
message["content"] = obj.dump(2);
185+
message.erase("tool_calls");
186+
}
187+
}
188+
if (!supports_tools_ && role == "tool") {
189+
message["role"] = "user";
190+
auto obj = json {
191+
{"tool_response", {
192+
{"tool", message.at("name")},
193+
{"content", message.at("content")},
194+
}},
195+
};
196+
if (message.contains("tool_call_id")) {
197+
obj["tool_response"]["tool_call_id"] = message.at("tool_call_id");
198+
}
199+
message["content"] = obj.dump(2);
200+
message.erase("name");
201+
}
202+
203+
if (!message["content"].is_null() && !supports_system_role_) {
204+
std::string content = message.at("content");
205+
if (role == "system") {
206+
if (!pending_system.empty()) pending_system += "\n";
207+
pending_system += content;
208+
continue;
209+
} else {
210+
if (role == "user") {
211+
if (!pending_system.empty()) {
212+
message["content"] = pending_system + (content.empty() ? "" : "\n" + content);
213+
pending_system.clear();
214+
}
215+
} else {
216+
flush_sys();
217+
}
218+
}
219+
}
220+
actual_messages.push_back(message);
221+
}
222+
flush_sys();
223+
} else {
224+
actual_messages = messages;
225+
}
226+
227+
auto context = minja::Context::make(json({
228+
{"messages", actual_messages},
229+
{"add_generation_prompt", add_generation_prompt},
230+
{"bos_token", bos_token_},
231+
{"eos_token", eos_token_},
232+
}));
233+
234+
if (!tools.is_null()) {
235+
auto tools_val = minja::Value(tools);
236+
context->set("tools", tools_val);
237+
}
238+
if (!extra_context.is_null()) {
239+
for (auto & kv : extra_context.items()) {
240+
minja::Value val(kv.value());
241+
context->set(kv.key(), val);
242+
}
243+
}
244+
245+
return template_root_->render(context);
246+
}
247+
};
248+
249+
} // namespace minja

common/chat.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,9 @@ void common_chat_parse_deepseek_r1(common_chat_msg_parser & builder) {
278278
throw; // Re-throw for partial mode
279279
}
280280
}
281+
282+
// Add any remaining content (critical for responses without tool calls)
283+
builder.add_content(builder.consume_rest());
281284
}
282285

283286
// Parse DeepSeek R1 tools array format following original llama.cpp parse_prefixed_json_tool_call_array pattern

common/chat.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,18 @@ enum common_chat_format {
135135
COMMON_CHAT_FORMAT_KIMI_K2, // Our custom format (keep last for backward compatibility)
136136
};
137137

138+
enum common_reasoning_format {
139+
COMMON_REASONING_FORMAT_NONE,
140+
COMMON_REASONING_FORMAT_DEEPSEEK,
141+
COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY,
142+
};
143+
138144
struct common_chat_syntax {
139145
common_chat_format format = COMMON_CHAT_FORMAT_KIMI_K2;
146+
common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_NONE;
147+
// Whether reasoning_content should be inlined in the content (e.g. for reasoning_format=deepseek in stream mode)
148+
bool reasoning_in_content = false;
149+
bool thinking_forced_open = false;
140150
bool enable_thinking = false;
141151
bool enable_tool_calls = true;
142152
};

0 commit comments

Comments
 (0)