Files
ik_llama.cpp/examples/server/parsers/qwen3_parser.hpp
Anton Sokolchenko 9ee72225dc Function calling support for Kimi-K2 (#628)
* Implement function calling / tools for ik_llama.cpp for Kimi K2

* Implement basic tool choice

* Backport llama.cpp tool calls support

* Enhance function calls with improved chat parser and string utilities

- Add new chat.h/chat.cpp and chat-parser.h/chat-parser.cpp for better chat handling
- Improve function calls parsing with fallback to llama.cpp builder pattern
- Add string utility functions (starts_with, ends_with, find_partial_stop)
- Update README with function calls testing instructions
- Enhance Kimi K2 parser and function calls documentation
- Add comprehensive test suite for function calls
- Update CMakeLists.txt and Makefile for new components

* Enhance function calling with unified streaming and parser improvements

- Fix streaming content cleanup to prevent function syntax in output
- Unify content extraction patterns with llama.cpp approach
- Improve Kimi K2 parser robustness and partial content handling
- Add comprehensive test coverage for function call scenarios
- Optimize chat message parsing and diff computation

* Replace hardcoded values in kimi_k2_parser.hpp with named constants

- Add compile-time constants for all token format markers
- Add compile-time constants for XML format markers
- Add compile-time constants for simple format patterns
- Replace all hardcoded string literals with named constants
- Use compile-time length calculation to avoid manual counting
- Improve maintainability and reduce magic numbers throughout parser

* Fix duplicate common_chat_parse definition

- Remove duplicate implementation from chat-parser.cpp
- Keep single implementation in chat.cpp following llama.cpp patterns
- Resolves linker error: multiple definition of common_chat_parse

* Fix JSON assertion failure in function call parsing

- Add proper validation that 'function' field is an object before accessing nested keys
- Handle missing 'arguments' field gracefully with default "{}"
- Prevents crash when parsing malformed tool call JSON structures

* Add comprehensive Qwen3 XML tool calling support with unit tests

- Implement Qwen3 XML parser with <tool_call>{"name": "func", "arguments": {...}}</tool_call> format
- Add model detection and routing for Qwen3 vs Kimi-K2 formats
- Create 8 comprehensive unit tests covering parsing, streaming, error handling
- Fix token format cleaning bug in kimi_k2_parser.hpp processing order
- Remove progressive parsing code and related utilities
- Add tool injection support for Qwen3 format in server utils

* Add DeepSeek R1 function calling support with comprehensive unit tests

- Implement complete DeepSeek R1 tool call parsing in common_chat_parser.cpp
- Add DeepSeek R1 model detection and tool injection in deepseek_r1_tools.hpp
- Update function_calls.hpp with DeepSeek R1 integration and content extraction
- Update documentation to reflect support for Kimi-K2, Qwen3, and DeepSeek R1 models
- Add comprehensive unit tests for DeepSeek R1 reasoning, tool calls, and integration
- Port exact implementation patterns from original llama.cpp for compatibility

Key features:
- Native DeepSeek R1 format: <|tool▁calls▁begin|>function<|tool▁sep|>name```json{}```<|tool▁call▁end|><|tool▁calls▁end|>
- Reasoning content extraction from <think>...</think> tags
- Multiple tool calls support with separate call blocks
- Model detection for deepseek-r1, deepseek_r1 naming patterns
- Integration with incremental parsing and streaming support

* Add partial parsing support for JSON and regex

- json-partial.h/cpp: JSON partial parsing functionality
- regex-partial.h/cpp: Regex partial parsing functionality

* Add format_chat integration tests for Qwen3 tool injection

- Add test_qwen3_format_chat_integration() to validate tool injection pipeline
- Test tool injection conditions and system message enhancement
- Verify JSON formatting and anti-preamble instructions
- Add comprehensive test documentation

Tests confirm tool injection works correctly - conversational preamble
issue is not in ik_llama.cpp but likely in UI configuration.

* Fix Qwen3 tool call parsing - pass model name to parser

Server was not passing model name to parse_chat_message_incremental(),
causing Qwen3 to fall back to Kimi-K2 parser and return tool calls
as content instead of proper tool_calls array.

* Fix non-streaming path to use model-specific parsing

Non-streaming responses were hardcoded to use Kimi-K2 format,
causing Qwen3 XML tool calls to be returned as content instead
of proper tool_calls array. Now uses same model detection as
streaming path for consistency.
2025-07-23 18:11:42 +02:00

147 lines
4.9 KiB
C++

#pragma once
#include "json.hpp"
#include <string>
#include <regex>
using json = nlohmann::ordered_json;
//
// Qwen3 Function Calling Parser (XML Hermes format)
// Based on original llama.cpp Hermes 2 Pro parser
//
namespace qwen3 {
// Parse Qwen3 XML-style tool calls: <tool_call>{"name": "func", "arguments": {...}}</tool_call>
static json parse_tool_calls(const std::string& text) {
json tool_calls = json::array();
try {
// Look for <tool_call> patterns
std::regex tool_call_regex(R"(<tool_call>\s*(\{[\s\S]*?\})\s*</tool_call>)");
std::sregex_iterator iter(text.begin(), text.end(), tool_call_regex);
std::sregex_iterator end;
int call_counter = 0;
for (; iter != end; ++iter) {
const std::smatch& match = *iter;
std::string json_content = match[1].str();
// Clean up the JSON content
json_content.erase(0, json_content.find_first_not_of(" \t\n\r"));
json_content.erase(json_content.find_last_not_of(" \t\n\r") + 1);
try {
// Parse the JSON content
auto parsed_json = json::parse(json_content);
// Validate required fields
if (!parsed_json.contains("name") || !parsed_json["name"].is_string()) {
continue;
}
std::string func_name = parsed_json["name"];
if (func_name.empty()) {
continue;
}
// Extract arguments
std::string arguments = "{}";
if (parsed_json.contains("arguments")) {
if (parsed_json["arguments"].is_string()) {
arguments = parsed_json["arguments"];
} else {
arguments = parsed_json["arguments"].dump();
}
}
// Generate tool call ID
std::string tool_id = "qwen3_call_" + std::to_string(++call_counter);
// Create tool call object
json tool_call = {
{"id", tool_id},
{"type", "function"},
{"function", {
{"name", func_name},
{"arguments", arguments}
}}
};
tool_calls.push_back(tool_call);
} catch (const std::exception&) {
// Skip malformed JSON
continue;
}
}
} catch (const std::exception&) {
// Return empty array on any parsing error
return json::array();
}
return tool_calls;
}
// Extract clean content by removing tool call tags
static std::string extract_content_during_parsing(const std::string& text, bool is_partial) {
std::string content = text;
try {
// Remove <tool_call>...</tool_call> sections
std::regex tool_call_regex(R"(<tool_call>[\s\S]*?</tool_call>)");
content = std::regex_replace(content, tool_call_regex, "");
// If partial, check for incomplete tool calls
if (is_partial) {
// Look for incomplete <tool_call> without closing tag
size_t incomplete_pos = content.find("<tool_call>");
if (incomplete_pos != std::string::npos) {
// Truncate at the incomplete tool call
content = content.substr(0, incomplete_pos);
}
}
// Clean up extra whitespace
content = std::regex_replace(content, std::regex(R"(\n\s*\n)"), "\n");
// Trim leading/trailing whitespace
content.erase(0, content.find_first_not_of(" \t\n\r"));
content.erase(content.find_last_not_of(" \t\n\r") + 1);
} catch (const std::exception&) {
// Return original text on regex errors
return text;
}
return content;
}
// Legacy cleaning function - kept for compatibility
static std::string clean_content(const std::string& content) {
return extract_content_during_parsing(content, false);
}
// Helper: Check if content has partial tool call syntax
static bool is_partial_content_advanced(const std::string& content) {
if (content.empty()) return false;
// Check for incomplete <tool_call> without closing
size_t open_pos = content.find("<tool_call>");
if (open_pos != std::string::npos) {
size_t close_pos = content.find("</tool_call>", open_pos);
if (close_pos == std::string::npos) {
return true; // Incomplete tool call
}
}
// Check for partial JSON in tool calls
std::regex incomplete_json_regex(R"(<tool_call>\s*\{[^}]*$)");
if (std::regex_search(content, incomplete_json_regex)) {
return true;
}
return false;
}
} // namespace qwen3