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
34 changes: 32 additions & 2 deletions Libraries/MLXLMCommon/Tool/Parsers/PythonLiteralParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,8 @@ struct PythonLiteralParser {
defer { depth -= 1 }
skipWhitespace()

if isAtString { return parseString() }
switch current {
case "'", "\"":
return parseString()
case "[", "(":
return parseArray()
case "{":
Expand Down Expand Up @@ -104,7 +103,31 @@ struct PythonLiteralParser {
}
}

/// Python joins adjacent string literals, as in `('first part ' 'second part')`.
private mutating func parseString() -> String? {
guard var result = parseStringLiteral() else { return nil }
skipWhitespace()
while isAtString {
guard let next = parseStringLiteral() else { return nil }
result += next
skipWhitespace()
}
return result
}

/// Whether a string literal starts here, with or without an `r` or `u` prefix.
private var isAtString: Bool {
var rest = source[index...]
if let prefix = rest.first, "rRuU".contains(prefix) { rest = rest.dropFirst() }
return rest.first == "'" || rest.first == "\""
}

private mutating func parseStringLiteral() -> String? {
var isRaw = false
if let prefix = current, "rRuU".contains(prefix) {
isRaw = prefix == "r" || prefix == "R"
advance()
}
guard let quote = current, quote == "'" || quote == "\"" else { return nil }
advance()

Expand Down Expand Up @@ -137,6 +160,13 @@ struct PythonLiteralParser {
guard let escaped = current else { return nil }
advance()

// A raw string keeps the backslash; it only stops a quote from closing the string.
if isRaw {
result.append(character)
result.append(escaped)
continue
}

switch escaped {
case "\\": result.append("\\")
case "'": result.append("'")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,11 +137,15 @@ public struct PythonicToolCallParser: ToolCallParser, Sendable {
return tryParseJSON(literal) ?? tryParsePythonLiteral(literal) ?? literal
}

if value.first == "'" || value.first == "\"" {
let string = (tryParsePythonLiteral(literal) as? String) ?? literal
// Also covers `r'...'`, which does not start with a quote.
if let string = tryParsePythonLiteral(literal) as? String {
return convertParameterValue(
string, paramName: key, funcName: funcName, tools: tools)
}
if value.first == "'" || value.first == "\"" {
return convertParameterValue(
literal, paramName: key, funcName: funcName, tools: tools)
}

if getParameterType(funcName: funcName, paramName: key, tools: tools) != nil {
return convertParameterValue(
Expand Down
20 changes: 20 additions & 0 deletions Tests/MLXLMTests/ToolArgumentNormalizationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,4 +196,24 @@ struct ToolArgumentNormalizationTests {
#expect(tryParsePythonLiteral("'''a''''") == nil)
#expect(tryParsePythonLiteral("'''a''") == nil)
}

@Test("Python string prefixes and adjacent strings read as Python does")
func pythonStringPrefixesAndAdjacentStrings() throws {
for (literal, value) in [
(#"r'\d+\.\d'"#, #"\d+\.\d"#),
(#"R"C:\new\table""#, #"C:\new\table"#),
(#"r'it\'s'"#, #"it\'s"#),
(#"u'caf\xe9'"#, "café"),
("'Hello, ' 'world'", "Hello, world"),
(#"'tab\t' r'\t'"#, "tab\t\\t"),
("(\"first line \"\n \"second line\")", "first line second line"),
] {
#expect(tryParsePythonLiteral(literal) as? String == value)
}
let object = try #require(tryParsePythonLiteral(#"{'path': r'C:\tmp', 'a' 'b': 1}"#))
#expect(JSONValue.from(object) == .object(["path": .string(#"C:\tmp"#), "ab": .int(1)]))
for literal in [#"r'a\'"#, "b'bytes'", "f'{x}'", "r 'x'", "'a' b"] {
#expect(tryParsePythonLiteral(literal) == nil)
}
}
}
28 changes: 28 additions & 0 deletions Tests/MLXLMTests/ToolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,34 @@ struct ToolTests {
#expect(toolCall.function.arguments["code"] == .string("print('hello')"))
}

@Test("Test Pythonic Tool Call Parser - Raw and Adjacent String Arguments")
func testPythonicParserRawAndAdjacentStrings() throws {
let parser = PythonicToolCallParser(
startTag: "<|tool_call_start|>", endTag: "<|tool_call_end|>")
let content =
#"<|tool_call_start|>[grep(pattern=r"\d{3}-\d{4}", path=('notes/'"#
+ "\n" + #" 'calls.txt'))]<|tool_call_end|>"#
let tools: [[String: any Sendable]] = [
[
"function": [
"name": "grep",
"parameters": [
"properties": [
"pattern": ["type": "string"],
"path": ["type": "string"],
]
],
] as [String: any Sendable]
]
]

for schemas in [nil, tools] {
let toolCall = try #require(parser.parse(content: content, tools: schemas))
#expect(toolCall.function.arguments["pattern"] == .string(#"\d{3}-\d{4}"#))
#expect(toolCall.function.arguments["path"] == .string("notes/calls.txt"))
}
}

@Test("Test Pythonic Tool Call Parser - No Arguments")
func testPythonicParserNoArguments() throws {
let parser = PythonicToolCallParser(
Expand Down
Loading