diff --git a/Libraries/MLXLMCommon/Tool/Parsers/PythonLiteralParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/PythonLiteralParser.swift index 877427559e..de10f5926a 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/PythonLiteralParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/PythonLiteralParser.swift @@ -46,9 +46,8 @@ struct PythonLiteralParser { defer { depth -= 1 } skipWhitespace() + if isAtString { return parseString() } switch current { - case "'", "\"": - return parseString() case "[", "(": return parseArray() case "{": @@ -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() @@ -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("'") diff --git a/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift index ecfcb6d4c3..105b625d90 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift @@ -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( diff --git a/Tests/MLXLMTests/ToolArgumentNormalizationTests.swift b/Tests/MLXLMTests/ToolArgumentNormalizationTests.swift index dd2cdd3c66..e92e8021a2 100644 --- a/Tests/MLXLMTests/ToolArgumentNormalizationTests.swift +++ b/Tests/MLXLMTests/ToolArgumentNormalizationTests.swift @@ -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) + } + } } diff --git a/Tests/MLXLMTests/ToolTests.swift b/Tests/MLXLMTests/ToolTests.swift index 8b656ca87f..2b70a60218 100644 --- a/Tests/MLXLMTests/ToolTests.swift +++ b/Tests/MLXLMTests/ToolTests.swift @@ -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(