Compare commits

...
3 Commits
Author SHA1 Message Date
Mark Cockram 9a278b02b8 server : include timings in Anthropic /v1/messages responses (#30244)
Add the timings object to the non-streaming response and to the final
message_delta event of the stream, as the OpenAI chat and Responses
paths already do. Clients such as llama-swap read prompt and generation
speed from it and otherwise report -1 for /v1/messages requests.

Update test_compat_anthropic.py to expect timings there; message_stop
still carries none.
2026-11-30 02:31:01 +01:00
Evan Huus 9fcc40d3d4 common : share the kv arg parser with llama-bench (#32831)
Assisted-by: Codex
2026-11-30 01:31:06 +01:00
Aldehir Rojas 57577675aa server : pass in --json-schema to chat parsing (#31862)
* server : apply --json-schema through the chat template

* server : update comment

* cont : move field
2026-11-30 00:29:32 +01:00
12 changed files with 68 additions and 39 deletions
+14 -2
View File
@@ -291,13 +291,21 @@ const std::vector<ggml_type> kv_cache_types = {
GGML_TYPE_Q5_1,
};
static ggml_type kv_cache_type_from_str(const std::string & s) {
ggml_type common_parse_kv_cache_type(const std::string & s) {
for (const auto & type : kv_cache_types) {
if (ggml_type_name(type) == s) {
return type;
}
}
throw std::runtime_error("Unsupported cache type: " + s);
return GGML_TYPE_COUNT;
}
static ggml_type kv_cache_type_from_str(const std::string & s) {
const ggml_type type = common_parse_kv_cache_type(s);
if (type == GGML_TYPE_COUNT) {
throw std::runtime_error("Unsupported cache type: " + s);
}
return type;
}
static std::string get_all_kv_cache_types() {
@@ -2253,6 +2261,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
"BNF-like grammar to constrain generations (see samples in grammars/ dir)",
[](common_params & params, const std::string & value) {
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_USER, value};
params.sampling.json_schema.clear();
}
).set_sampling());
add_opt(common_arg(
@@ -2260,6 +2269,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
"file to read grammar from",
[](common_params & params, const std::string & value) {
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_USER, read_file(value)};
params.sampling.json_schema.clear();
}
).set_sampling());
add_opt(common_arg(
@@ -2267,6 +2277,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
"JSON schema to constrain generations (https://json-schema.org/), e.g. `{\"type\": \"object\"}` for any JSON object",
[](common_params & params, const std::string & value) {
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT, json_schema_to_grammar(json::parse(value))};
params.sampling.json_schema = value;
}
).set_sampling());
add_opt(common_arg(
@@ -2284,6 +2295,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
std::back_inserter(schema)
);
params.sampling.grammar = {COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT, json_schema_to_grammar(json::parse(schema))};
params.sampling.json_schema = schema;
}
).set_sampling());
add_opt(common_arg(
+2
View File
@@ -19,6 +19,8 @@
// CLI argument parsing
//
ggml_type common_parse_kv_cache_type(const std::string & value);
struct common_arg {
std::set<enum llama_example> examples = {LLAMA_EXAMPLE_COMMON};
std::set<enum llama_example> excludes = {};
+3
View File
@@ -2034,6 +2034,9 @@ void common_chat_session::apply_sampling(common_params_sampling & sampling) cons
}
if (!grammar_text.empty()) {
sampling.grammar = {COMMON_GRAMMAR_TYPE_TOOL_CALLS, grammar_text};
} else if (sampling.grammar.type == COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT) {
// drop the schema grammar when the template does not use it, since it would reject the generation prompt
sampling.grammar = {};
}
sampling.grammar_lazy = grammar_lazy;
sampling.generation_prompt = generation_prompt_text;
+1
View File
@@ -280,6 +280,7 @@ struct common_params_sampling {
common_grammar grammar; // optional grammar constraint (user / output-format / tool-calls)
bool grammar_lazy = false;
std::vector<common_grammar_trigger> grammar_triggers; // optional triggers (for lazy grammars)
std::string json_schema; // schema the output-format grammar was built from, applied through the chat template
std::set<llama_token> preserved_tokens;
std::vector<llama_logit_bias> logit_bias; // logit biases to apply
+2 -34
View File
@@ -493,38 +493,6 @@ static void print_usage(int /* argc */, char ** argv) {
"'first-last' or 'first-last+step' or 'first-last*mult'.\n");
}
static ggml_type ggml_type_from_name(const std::string & s) {
if (s == "f16") {
return GGML_TYPE_F16;
}
if (s == "bf16") {
return GGML_TYPE_BF16;
}
if (s == "f8_e4m3") {
return GGML_TYPE_F8_E4M3;
}
if (s == "q8_0") {
return GGML_TYPE_Q8_0;
}
if (s == "q4_0") {
return GGML_TYPE_Q4_0;
}
if (s == "q4_1") {
return GGML_TYPE_Q4_1;
}
if (s == "q5_0") {
return GGML_TYPE_Q5_0;
}
if (s == "q5_1") {
return GGML_TYPE_Q5_1;
}
if (s == "iq4_nl") {
return GGML_TYPE_IQ4_NL;
}
return GGML_TYPE_COUNT;
}
static cmd_params parse_cmd_params(int argc, char ** argv) {
cmd_params params;
std::string arg;
@@ -644,7 +612,7 @@ static cmd_params parse_cmd_params(int argc, char ** argv) {
std::vector<ggml_type> types;
for (const auto & t : p) {
ggml_type gt = ggml_type_from_name(t);
ggml_type gt = common_parse_kv_cache_type(t);
if (gt == GGML_TYPE_COUNT) {
invalid_param = true;
break;
@@ -664,7 +632,7 @@ static cmd_params parse_cmd_params(int argc, char ** argv) {
std::vector<ggml_type> types;
for (const auto & t : p) {
ggml_type gt = ggml_type_from_name(t);
ggml_type gt = common_parse_kv_cache_type(t);
if (gt == GGML_TYPE_COUNT) {
invalid_param = true;
break;
+10
View File
@@ -1542,6 +1542,12 @@ json oaicompat_chat_params_parse(
}
}
// fall back to --json-schema if the request doesn't overwrite it
bool use_tools = has_tools && tool_choice != "none";
if (!opt.json_schema.empty() && !use_tools && json_schema.is_null() && grammar.empty() && !body.contains("response_format")) {
json_schema = json::parse(opt.json_schema);
}
// an absent or empty schema means any object
if (json_schema.is_object() && json_schema.empty()) {
json_schema["type"] = "object";
@@ -1620,6 +1626,10 @@ json oaicompat_chat_params_parse(
if (body.contains("grammar")) {
throw std::invalid_argument("Cannot use custom grammar constraints with tools.");
}
if (!json_schema.is_null()) {
// only a few models natively support response_format and tools, but none have support yet
throw std::invalid_argument("Cannot use response_format or json_schema with tools.");
}
}
// merge the template args provided from command line with the args provided in the user request
+1
View File
@@ -393,6 +393,7 @@ struct server_chat_params {
std::string media_path;
bool media_allow_private_urls = false;
bool force_pure_content = false;
std::string json_schema;
};
// used by /completions endpoint
+2 -1
View File
@@ -1758,7 +1758,8 @@ private:
/* reasoning_budget_msg */ params_base.sampling.reasoning_budget_message,
/* media_path */ params_base.media_path,
/* media_allow_private */ params_base.media_allow_private_urls,
/* force_pure_content */ params_base.force_pure_content_parser
/* force_pure_content */ params_base.force_pure_content_parser,
/* json_schema */ params_base.sampling.json_schema
};
{
+8
View File
@@ -794,6 +794,10 @@ json server_task_result_cmpl_final::to_json_anthropic() {
}}
};
if (stats.is_set()) {
res["timings"] = stats.to_json();
}
return res;
}
@@ -975,6 +979,10 @@ json server_task_result_cmpl_final::to_json_anthropic_stream() {
}}
});
if (stats.is_set()) {
events.back().at("data")["timings"] = stats.to_json();
}
events.push_back({
{"event", "message_stop"},
{"data", {
@@ -291,6 +291,23 @@ def test_completion_with_json_schema(jinja: bool, json_schema: dict, n_predicted
assert match_regex(re_content, choice["message"]["content"]), f'Expected {re_content}, got {choice["message"]["content"]}'
@pytest.mark.parametrize("jinja", [False, True])
def test_completion_with_server_json_schema(jinja: bool):
global server
server.jinja = jinja
server.json_schema = '{"const": "42"}'
server.start()
res = server.make_request("POST", "/chat/completions", data={
"max_tokens": 6,
"messages": [
{"role": "system", "content": "You are a coding assistant."},
{"role": "user", "content": "Write an example"},
],
})
assert res.status_code == 200, f'Expected 200, got {res.status_code}'
assert match_regex("\"42\"", res.body["choices"][0]["message"]["content"])
@pytest.mark.parametrize("jinja,grammar,n_predicted,re_content", [
(False, 'root ::= "a"{5,5}', 6, "a{5,5}"),
(True, 'root ::= "a"{5,5}', 6, "a{5,5}"),
@@ -77,8 +77,9 @@ def test_anthropic_messages_basic():
assert isinstance(res.body["usage"]["input_tokens"], int), "input_tokens should be integer"
assert isinstance(res.body["usage"]["output_tokens"], int), "output_tokens should be integer"
assert res.body["usage"]["output_tokens"] > 0, "Should have generated some tokens"
# Anthropic API should NOT include timings
assert "timings" not in res.body, "Anthropic API should not include timings field"
# llama-server extension: timings are included so clients can read generation speed
assert "timings" in res.body, "Anthropic API should include timings field"
assert res.body["timings"]["predicted_n"] > 0
def test_anthropic_messages_with_system():
@@ -206,6 +207,8 @@ def test_anthropic_messages_streaming():
assert message_delta["delta"]["stop_reason"] in ["end_turn", "max_tokens"]
assert "usage" in message_delta
assert message_delta["usage"]["output_tokens"] > 0
assert "timings" in message_delta, "message_delta should include timings"
assert message_delta["timings"]["predicted_n"] > 0
# Check message_stop
message_stop = next(e for e in events if e["type"] == "message_stop")
+3
View File
@@ -120,6 +120,7 @@ class ServerProcess:
reasoning: Literal['on', 'off', 'auto'] | None = None
chat_template: str | None = None
chat_template_file: str | None = None
json_schema: str | None = None
server_path: str | None = None
mmproj_url: str | None = None
no_mmproj: bool | None = None
@@ -300,6 +301,8 @@ class ServerProcess:
server_args.extend(["--chat-template", self.chat_template])
if self.chat_template_file:
server_args.extend(["--chat-template-file", self.chat_template_file])
if self.json_schema:
server_args.extend(["--json-schema", self.json_schema])
if self.mmproj_url:
server_args.extend(["--mmproj-url", self.mmproj_url])
if self.no_mmproj: