Skip to content
Closed
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
63 changes: 45 additions & 18 deletions Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,44 @@
import Foundation

/// Parser for Gemma format: call:name{key:value,k:<escape>str<escape>}
/// Supports both Gemma 3 (<start_function_call>/<end_function_call>) and
/// Gemma 4 (<|tool_call>/<tool_call|>) formats.
/// Reference: https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/tool_parsers/function_gemma.py
public struct GemmaFunctionParser: ToolCallParser, Sendable {
public let startTag: String? = "<start_function_call>"
public let endTag: String? = "<end_function_call>"
// Gemma 4 format tags (primary, as Gemma 4 is the current model)
public let startTag: String? = "<|tool_call>"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing startTag to only the Gemma 4 marker breaks streamed Gemma 3 tool calls. ToolCallProcessor uses parser.startTag as the sole trigger, so <start_function_call>...<end_function_call> output will now pass through as regular text even though parse(content:) can handle it directly. Since this PR also maps gemma3/gemma3n to .gemma, please either keep streaming detection compatible with both start tags or split Gemma 3 and Gemma 4 into distinct parser formats.

public let endTag: String? = "<tool_call|>"

// Gemma 3 format tags (fallback detection)
private static let gemma3StartTag = "<start_function_call>"
private static let gemma3EndTag = "<end_function_call>"

// Gemma 3 escape marker
private let escapeMarker = "<escape>"
// Gemma 4 escape marker
private static let gemma4EscapeMarker = "<|\"|>"

public init() {}

public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? {
// Strip tags if present
var text = content
if let start = startTag {
text = text.replacingOccurrences(of: start, with: "")
}
if let end = endTag {
text = text.replacingOccurrences(of: end, with: "")
/// Detects which Gemma format is being used based on content
private func detectFormat(in text: String) -> (isGemma4: Bool, stripped: String) {
// Try Gemma 4 tags first (startTag/endTag)
if let st = startTag, let et = endTag, text.contains(st) || text.contains(et) {
var stripped = text
stripped = stripped.replacingOccurrences(of: st, with: "")
stripped = stripped.replacingOccurrences(of: et, with: "")
return (true, stripped)
}
// Fallback to Gemma 3 tags
var stripped = text
stripped = stripped.replacingOccurrences(of: Self.gemma3StartTag, with: "")
stripped = stripped.replacingOccurrences(of: Self.gemma3EndTag, with: "")
return (false, stripped)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fallback mis-detects unterminated Gemma 4 calls during processEOS(). The default ToolCallParser.parseEOS splits the buffer on startTag before calling parse, so a buffered value like <|tool_call>call:search{query:<|"|>hello, world<|"|>} reaches detectFormat without either Gemma 4 wrapper tag. It then falls back to the Gemma 3 escape marker and splits the escaped string at the comma. Please override parseEOS for Gemma or otherwise preserve the detected Gemma 4 format after splitting.

}

public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? {
// Detect format and strip tags
let (isGemma4, text) = detectFormat(in: content)

// Pattern: call:(\w+)\{(.*?)\}
// Find "call:" followed by function name and arguments in braces
Expand All @@ -40,6 +60,9 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable {

var arguments: [String: any Sendable] = [:]

// Use correct escape marker based on detected format
let escMarker = isGemma4 ? Self.gemma4EscapeMarker : escapeMarker

// Parse key:value pairs
while !argsStr.isEmpty {
// Find the key (everything before :)
Expand All @@ -48,12 +71,16 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable {
argsStr = String(argsStr[argsStr.index(after: colonIdx)...])

// Handle escaped strings
if argsStr.hasPrefix(escapeMarker) {
argsStr = String(argsStr.dropFirst(escapeMarker.count))
guard let endEscape = argsStr.range(of: escapeMarker) else { break }
let value = String(argsStr[..<endEscape.lowerBound])
arguments[key] = value
var parsedValue: String?
if argsStr.hasPrefix(escMarker) {
argsStr = String(argsStr.dropFirst(escMarker.count))
guard let endEscape = argsStr.range(of: escMarker) else { break }
parsedValue = String(argsStr[..<endEscape.lowerBound])
argsStr = String(argsStr[endEscape.upperBound...])
}

if let pv = parsedValue {
arguments[key] = pv
// Skip comma if present
if argsStr.hasPrefix(",") {
argsStr = String(argsStr.dropFirst())
Expand All @@ -63,18 +90,18 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable {

// Handle regular values (until comma or end)
let commaIdx = argsStr.firstIndex(of: ",") ?? argsStr.endIndex
let value = String(argsStr[..<commaIdx])
let rawValue = String(argsStr[..<commaIdx])
argsStr =
commaIdx < argsStr.endIndex
? String(argsStr[argsStr.index(after: commaIdx)...]) : ""

// Try JSON decode, fallback to string
if let data = value.data(using: .utf8),
if let data = rawValue.data(using: .utf8),
let json = deserializeJSON(data)
{
arguments[key] = json
} else {
arguments[key] = value
arguments[key] = rawValue
}
}

Expand Down
4 changes: 2 additions & 2 deletions Libraries/MLXLMCommon/Tool/ToolCallFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable {
return .glm4
}

// Gemma
if type == "gemma" {
// Gemma family (gemma, gemma2, gemma3, gemma3n, gemma4, etc.)
if type.hasPrefix("gemma") {
return .gemma
}

Expand Down
52 changes: 50 additions & 2 deletions Tests/MLXLMTests/ToolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -453,10 +453,53 @@ struct ToolTests {
#expect(toolCall.function.arguments["query"] == .string("hello, world!"))
}

@Test("Test Gemma Function Parser - Gemma 4 Format")
func testGemmaParserGemma4Format() throws {
let parser = GemmaFunctionParser()
// Gemma 4 uses <|tool_call>/<tool_call|> tags with <|\"|> escape markers
let content = "<|tool_call>call:get_weather{location:Paris,unit:celsius}<tool_call|>"

let toolCall = try #require(parser.parse(content: content, tools: nil))

#expect(toolCall.function.name == "get_weather")
#expect(toolCall.function.arguments["location"] == .string("Paris"))
#expect(toolCall.function.arguments["unit"] == .string("celsius"))
}

@Test("Test Gemma Function Parser - Gemma 4 Format with Escaped Strings")
func testGemmaParserGemma4EscapedStrings() throws {
let parser = GemmaFunctionParser()
// Gemma 4 uses <|\"|> for escaping
let content = "<|tool_call>call:search{query:<|\"|>hello, world!<|\"|>}<tool_call|>"

let toolCall = try #require(parser.parse(content: content, tools: nil))

#expect(toolCall.function.name == "search")
#expect(toolCall.function.arguments["query"] == .string("hello, world!"))
}

@Test("Test Gemma Function Parser - Auto-Detects Gemma 3 vs Gemma 4 Format")
func testGemmaParserAutoDetection() throws {
let parser = GemmaFunctionParser()

// Gemma 3 format
let gemma3Content = "<start_function_call>call:func3{arg1:value1}<end_function_call>"
let gemma3Result = try #require(parser.parse(content: gemma3Content, tools: nil))
#expect(gemma3Result.function.name == "func3")
#expect(gemma3Result.function.arguments["arg1"] == .string("value1"))

// Gemma 4 format
let gemma4Content = "<|tool_call>call:func4{arg2:value2}<tool_call|>"
let gemma4Result = try #require(parser.parse(content: gemma4Content, tools: nil))
#expect(gemma4Result.function.name == "func4")
#expect(gemma4Result.function.arguments["arg2"] == .string("value2"))
}

@Test("Test Gemma Format via ToolCallProcessor")
func testGemmaFormatProcessor() throws {
let processor = ToolCallProcessor(format: .gemma)
let content = "<start_function_call>call:calculator{expression:2+2}<end_function_call>"
// Use Gemma 4 format (<|tool_call> tags) which is the primary format for GemmaFunctionParser
let content = "<|tool_call>call:calculator{expression:2+2}<tool_call|>"

_ = processor.processChunk(content)

Expand Down Expand Up @@ -628,9 +671,14 @@ struct ToolTests {
#expect(ToolCallFormat.infer(from: "glm4_5") == .glm4)
#expect(ToolCallFormat.infer(from: "GLM4_5") == .glm4)

// Gemma models
// Gemma models (prefix matching for all variants)
#expect(ToolCallFormat.infer(from: "gemma") == .gemma)
#expect(ToolCallFormat.infer(from: "GEMMA") == .gemma)
#expect(ToolCallFormat.infer(from: "gemma2") == .gemma)
#expect(ToolCallFormat.infer(from: "gemma3") == .gemma)
#expect(ToolCallFormat.infer(from: "gemma3n") == .gemma)
#expect(ToolCallFormat.infer(from: "gemma4") == .gemma)
#expect(ToolCallFormat.infer(from: "gemma4_text") == .gemma)

// Nemotron models (prefix matching)
#expect(ToolCallFormat.infer(from: "nemotron_h") == .xmlFunction)
Expand Down