Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions src/include/chat/positional_tool_results.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/// \file positional_tool_results.hpp
/// \brief Bind parallel tool results before a positional chat template drops their IDs.
#pragma once

#include <nlohmann/json.hpp>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

namespace flm::chat {

struct tool_history_error {
std::string param;
std::string message;
};

/// \brief Order each multi-call assistant turn's contiguous results. Discard the request copy on error.
inline std::optional<tool_history_error> order_parallel_tool_results(
nlohmann::ordered_json& messages, const std::vector<std::size_t>& original_indices = {}) {
using json = nlohmann::ordered_json;
auto has_role = [](const json& msg, const char* role) {
const auto it = msg.find("role");
return it != msg.end() && *it == role;
};
auto id_field = [](const json& obj, const char* key) -> const std::string* {
const auto it = obj.find(key);
return it == obj.end() ? nullptr : it->get_ptr<const std::string*>();
};
for (std::size_t i = 0; i < messages.size(); ++i) {
const auto& assistant = messages[i];
if (!has_role(assistant, "assistant")) continue;
const auto calls = assistant.find("tool_calls");
if (calls == assistant.end() || !calls->is_array() || calls->size() < 2) continue;

auto path = [&](std::size_t m) {
return "messages[" + std::to_string(original_indices.empty() ? m : original_indices[m]) + "]";
};
auto call_path = [&](std::size_t j) {
return path(i) + ".tool_calls[" + std::to_string(j) + "].id";
};
std::unordered_map<std::string, std::size_t> positions;
for (std::size_t j = 0; j < calls->size(); ++j) {
const auto* id = id_field((*calls)[j], "id");
if (!id || id->empty())
return tool_history_error{call_path(j), "Parallel tool calls require a non-empty string ID"};
if (!positions.emplace(*id, j).second)
return tool_history_error{call_path(j), "Duplicate tool call ID in this assistant turn"};
}
std::vector<json> results(calls->size());
for (std::size_t r = i + 1; r < messages.size() && has_role(messages[r], "tool"); ++r) {
const auto* id = id_field(messages[r], "tool_call_id");
auto pos = id ? positions.find(*id) : positions.end();
if (pos == positions.end() || !results[pos->second].is_null()) {
return tool_history_error{path(r) + ".tool_call_id",
pos == positions.end() ? "Result must identify a tool call in the preceding assistant turn"
: "Duplicate result for this tool call"};
}
results[pos->second] = std::move(messages[r]);
}
for (std::size_t j = 0; j < results.size(); ++j) {
if (results[j].is_null())
return tool_history_error{call_path(j), "No result for this tool call before the next turn or end of history"};
messages[i + 1 + j] = std::move(results[j]);
}
i += results.size();
}
return std::nullopt;
}

} // namespace flm::chat
2 changes: 2 additions & 0 deletions src/model_list.json
Original file line number Diff line number Diff line change
Expand Up @@ -2213,6 +2213,7 @@
"qwen3.5-oga-hipep": {
"9b": {
"name": "Qwen3.5-9B_gpuep_1.0_gpu_128",
"positional_tool_results": true,
"url": "https://huggingface.co/amd/Qwen3.5-9B_gpuep_1.0_gpu_128/resolve/f3a9b4aeb60a42542cc4fec561e1f1095e427483",
"file_url": "https://huggingface.co/api/models/amd/Qwen3.5-9B_gpuep_1.0_gpu_128/tree/f3a9b4aeb60a42542cc4fec561e1f1095e427483",
"size": 7491571939,
Expand Down Expand Up @@ -2480,6 +2481,7 @@
"qwen2.5-it-oga-hipep": {
"14b": {
"name": "Qwen2.5-14B-Instruct_gpuep_1.0_gpu_128",
"positional_tool_results": true,
"url": "https://huggingface.co/amd/Qwen2.5-14B-Instruct_gpuep_1.0_gpu_128/resolve/efc1134c0ea60c296e823237b8c43fbdd4ab3c04",
"file_url": "https://huggingface.co/api/models/amd/Qwen2.5-14B-Instruct_gpuep_1.0_gpu_128/tree/efc1134c0ea60c296e823237b8c43fbdd4ab3c04",
"size": 8849120893,
Expand Down
16 changes: 14 additions & 2 deletions src/server/rest_handler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include "image/image_reader.hpp"
#include "image/raw_rgb8.hpp"
#include "base64.hpp"
#include "chat/positional_tool_results.hpp"
#include "utils/log_privacy.hpp"
#include <algorithm>
#include <cctype>
Expand Down Expand Up @@ -124,12 +125,13 @@ T value_or(const json& request, const char* key, T fallback) {
///@brief Normalize messages by merging consecutive user messages (like Ollama does)
///@param messages the original messages
///@return normalized messages with consecutive user messages merged
static json normalize_messages(json messages) {
static json normalize_messages(json messages, std::vector<size_t>* original_indices = nullptr) {
if (messages.empty()) return messages;

json normalized = nlohmann::ordered_json::array();

for (size_t i = 0; i < messages.size(); i++) {
if (original_indices) original_indices->push_back(i);
auto current_msg = messages[i];
std::string role = current_msg.value("role", "");

Expand Down Expand Up @@ -816,6 +818,8 @@ bool RestHandler::ensure_model_loaded(const std::string& model_tag,
this->prefill_chunk_len = this->prefill_chunk_len_arg != -1
? this->prefill_chunk_len_arg
: model_info["max_prefill_len"].get<int>();
positional_tool_results = model_info.value("positional_tool_results", false)
&& engine->backend_id() == flm::backend::kOgaHipepBackendId;
this->auto_chat_engine = std::move(engine);
this->current_model_tag = ensure_tag;
this->current_backend = requested_backend;
Expand Down Expand Up @@ -1620,7 +1624,8 @@ void RestHandler::handle_openai_chat_completion(const json& request,
configure_chat_engine_parameters(options, request);
apply_sampling_request(*auto_chat_engine, sampling);

current_messages = normalize_messages(current_messages);
std::vector<size_t> original_indices;
current_messages = normalize_messages(current_messages, positional_tool_results ? &original_indices : nullptr);
std::vector<std::shared_ptr<const raw_rgb8_batch_t>> raw_rgb8;
{
// raw RGB8 frames only go to MiniCPM-V; any other model gets a clear 400 rather than a dropped image
Expand All @@ -1632,6 +1637,13 @@ void RestHandler::handle_openai_chat_completion(const json& request,
return;
}
}
if (positional_tool_results) {
if (auto error = flm::chat::order_parallel_tool_results(current_messages, original_indices)) {
send_response({{"error", {{"message", error->message}, {"param", error->param},
{"type", "invalid_request_error"}, {"code", 400}}}});
return;
}
}
if (continue_final) {
request_error = continue_final_message_error(current_messages);
if (!request_error.empty()) {
Expand Down
1 change: 1 addition & 0 deletions src/server/rest_handler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -177,5 +177,6 @@ class RestHandler {
std::string backend;
/// \brief the backend the currently loaded model was asked for
std::string current_backend;
bool positional_tool_results = false;
PromptCache prompt_cache;
};
48 changes: 48 additions & 0 deletions src/test/chat_tools/test_chat_tools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "chat/chat_gemma4_tools.hpp"
#include "chat/chat_grammar.hpp"
#include "chat/chat_parser.hpp"
#include "chat/positional_tool_results.hpp"
#include "minja/minja.hpp"

#include <cstdio>
Expand Down Expand Up @@ -676,9 +677,56 @@ void test_schema_literals_untouched() {
CHECK(grammar.takes(request, "{\"v\": {\"type\":\"string\",\"pattern\":\"\\\\S\"}}"));
}

void test_positional_tool_results() {
auto shelf = [](const char* id, const char* args) {
auto c = call("read_shelf", args);
c["id"] = id;
return c;
};
const json assistant = {{"role", "assistant"}, {"content", nullptr}, {"tool_calls", json::array({
shelf("z", R"({"shelf":"red"})"), shelf("a", R"({"shelf":"blue"})"), shelf("m", R"({"shelf":"green"})")})}};
const json red = {{"role", "tool"}, {"tool_call_id", "z"}, {"content", "731"}};
const json blue = {{"role", "tool"}, {"tool_call_id", "a"}, {"content", "482"}};
const json green = {{"role", "tool"}, {"tool_call_id", "m"}, {"content", json::array({
{{"type", "text"}, {"text", "993"}}})}};
const json boundary = {{"role", "user"}, {"content", "again"}};
const json group = json::array({assistant, red, blue, green});
// Two outstanding groups may reuse the same IDs; keep every part of the messages intact.
for (const json& separator : {boundary, json{{"role", "assistant"}, {"content", "done"}}}) {
json history = {assistant, green, red, blue, separator, assistant, blue, green, red};
CHECK(!flm::chat::order_parallel_tool_results(history));
CHECK(history == json::array({assistant, red, blue, green, separator, assistant, red, blue, green}));
}
auto invalid = [](json history, const std::string& path) {
auto err = flm::chat::order_parallel_tool_results(history);
CHECK(err && err->param == path && !err->message.empty());
};
for (const json& bad_id : {json(nullptr), json(7), json("")}) {
json history = group;
history[0]["tool_calls"][1]["id"] = bad_id;
invalid(history, "messages[0].tool_calls[1].id");
history = group;
history[2]["tool_call_id"] = bad_id;
invalid(history, "messages[2].tool_call_id");
}
json missing = group;
missing[0]["tool_calls"][1].erase("id");
invalid(missing, "messages[0].tool_calls[1].id");
invalid(json::array({assistant, blue, green, boundary, red}), "messages[0].tool_calls[0].id");
invalid(json::array({assistant, blue, green, assistant, red}), "messages[0].tool_calls[0].id");
invalid(json::array({assistant, blue, green}), "messages[0].tool_calls[0].id");
invalid(json::array({assistant, red, blue, green, red}), "messages[4].tool_call_id");
json single = assistant;
single["tool_calls"] = json::array({assistant["tool_calls"][0]});
json history = json::array({single, red});
CHECK(!flm::chat::order_parallel_tool_results(history));
CHECK(history == json::array({single, red}));
}

} // namespace

int main() {
test_positional_tool_results();
test_qwen_xml_grammar_takes_template_calls();
test_call_without_arguments();
test_stray_reasoning_end();
Expand Down
109 changes: 109 additions & 0 deletions src/test/openai_api_test/test_tool_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,115 @@ def round_trip(api: Api) -> None:
expect("23" in (msg["content"] or ""), f"the answer does not use the tool result: {msg['content']!r}")


def positional_shelf_history(api: Api) -> tuple[list[dict], list[dict]]:
if api.model not in ("qwen3.5-oga-hipep:9b", "qwen2.5-it-oga-hipep:14b"):
raise Skip("only the two verified positional OGA packages use this adapter")
turns = user("Read the red and blue shelves. Report each shelf and its numeric value as JSON.")
calls = [{"id": ident, "type": "function", "function": {
"name": "read_shelf", "arguments": json.dumps({"shelf": shelf})}}
for ident, shelf in (("call_z", "red"), ("call_a", "blue"))]
turns.append({"role": "assistant", "content": None, "tool_calls": calls})
results = [{"role": "tool", "tool_call_id": ident, "content": value}
for ident, value in (("call_z", "731"), ("call_a", "482"))]
return turns, results


@case
def positional_parallel_results(api: Api) -> None:
"""Cold reversed delivery, repeated history, and a genuine ID-only remap, over JSON and SSE."""
turns, results = positional_shelf_history(api)
schema = {"type": "object", "properties": {k: {"type": "integer"} for k in ("red", "blue")},
"required": ["red", "blue"], "additionalProperties": False}
fmt = {"type": "json_schema", "json_schema": {"name": "shelves", "strict": True, "schema": schema}}
remapped = [dict(r, tool_call_id=other["tool_call_id"]) for r, other in zip(results, reversed(results))]
mismatches = []
for stream in (False, True):
for name, delivery, values in (("reversed", results[::-1], (731, 482)),
("ordered", results, (731, 482)),
("remapped", remapped, (482, 731))):
body = api.body(turns + delivery, response_format=fmt, tool_choice="none", max_tokens=64)
if stream:
reply = api.stream(dict(body, stream_options={"include_usage": True}))
expect(reply.status == 200 and reply.done, f"{name}: incomplete stream: {reply.error}")
folded = flm_api.check_stream_contract(reply, include_usage=True)
text, usage = folded.content, folded.usage
else:
reply = api.post(body)
expect(reply.status == 200, f"{name}: HTTP {reply.status}: {reply.error_message()}")
text = flm_api.check_message_contract(reply.body["choices"][0])["content"]
usage = reply.body["usage"]
cached = usage["prompt_tokens_details"]["cached_tokens"]
print(f" {name}, stream={stream}: {cached}/{usage['prompt_tokens']} prompt tokens cached")
try:
mapping = json.loads(text)
except (ValueError, TypeError):
mapping = None
if mapping != dict(zip(("red", "blue"), values)):
mismatches.append(f"{name}, stream={stream}: expected red/blue={values}, got {text!r}")
expect(not mismatches, "; ".join(mismatches))


@case
def positional_parallel_errors(api: Api) -> None:
"""Unresolvable parallel histories get indexed JSON errors, even when streaming was requested."""
turns, (red, blue) = positional_shelf_history(api)
calls = turns[1]["tool_calls"]
for stream in (False, True):
for messages, path in (
(turns + [red, dict(blue, tool_call_id="other")], "messages[3].tool_call_id"),
(turns + [red, red], "messages[3].tool_call_id"),
(turns + [red, blue, red], "messages[4].tool_call_id"),
(turns + [red, {"role": "tool", "content": "482"}], "messages[3].tool_call_id"),
(turns + [red], "messages[1].tool_calls[1].id"),
(turns + [red, *user("Next task"), blue], "messages[1].tool_calls[1].id"),
([turns[0], dict(turns[1], tool_calls=[calls[0], calls[0]]), red, blue],
"messages[1].tool_calls[1].id"),
(user("First message") + turns + [red, red], "messages[4].tool_call_id"),
):
body = api.body(messages, tool_choice="none", max_tokens=1)
if stream:
s = api.stream(body)
status, error = s.status, s.error or {}
expect(not s.chunks and not s.done, "error arrived after SSE was committed")
else:
r = api.post(body)
status, error = r.status, r.body
expect(status == 400, f"{path}: expected HTTP 400, got {status}")
detail = error.get("error", {})
expect(detail.get("type") == "invalid_request_error" and detail.get("param") == path,
f"{path}: wrong error: {detail}")
bad_part = dict(blue, content=[{"type": "image_url", "image_url": {"url": "invalid"}}])
r = api.post(api.body(turns + [bad_part, red], tool_choice="none"))
expect(r.status == 400 and "messages[2].content[0]" in r.error_message(),
f"the content error must name the original result: {r.error_message()}")
expect(api.post(api.body(turns + [blue, red], tool_choice="none", max_tokens=1)).status == 200,
"valid request failed after the errors")


@case
def positional_single_round_trips(api: Api) -> None:
"""Replay a real named call using the ID returned on each wire format."""
positional_shelf_history(api)
for stream in (False, True):
messages = user(WEATHER_PROMPT)
body = api.body(messages, tools=WEATHER_TOOLS, tool_choice=function_choice("get_weather"))
try:
calls = (expect_streamed_calls(api, body, WEATHER_TOOLS) if stream
else expect_calls(api.ok(body), WEATHER_TOOLS))
except Skip as error:
raise AssertionError(f"this package must support named calls: {error}") from error
expect(len(calls) == 1 and calls[0]["function"]["name"] == "get_weather", f"unexpected calls: {calls}")
messages += [{"role": "assistant", "content": None, "tool_calls": calls},
{"role": "tool", "tool_call_id": calls[0]["id"], "content": '{"temperature_c": 23}'}]
follow = api.body(messages, tools=WEATHER_TOOLS, tool_choice="none", max_tokens=128)
try:
text = (flm_api.check_stream_contract(api.ok_stream(follow), include_usage=False).content
if stream else flm_api.check_message_contract(api.ok(follow))["content"])
except Skip as error:
raise AssertionError(f"this package must accept the named call result: {error}") from error
expect("23" in text, f"single-call result missing from the answer: {text!r}")


CASES = flm_api.collect(globals())

if __name__ == "__main__":
Expand Down
Loading