@contentgrowth/llm-service 0.6.3 → 0.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/llm/json-utils.js +22 -3
package/package.json
CHANGED
package/src/llm/json-utils.js
CHANGED
|
@@ -12,6 +12,19 @@ export function extractJsonFromResponse(text) {
|
|
|
12
12
|
return null;
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
// Helper to sanitize JSON strings with unescaped control characters
|
|
16
|
+
function sanitizeJsonString(str) {
|
|
17
|
+
// Find all JSON strings: "..."
|
|
18
|
+
// Handle escaped quotes \" and backslashes \\
|
|
19
|
+
return str.replace(/"(?:[^"\\]|\\.)*"/g, (match) => {
|
|
20
|
+
// Replace unescaped control characters inside the string
|
|
21
|
+
return match
|
|
22
|
+
.replace(/\n/g, "\\n")
|
|
23
|
+
.replace(/\r/g, "\\r")
|
|
24
|
+
.replace(/\t/g, "\\t");
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
15
28
|
// Helper function to attempt JSON parsing with escape sequence normalization
|
|
16
29
|
function tryParseJson(jsonStr) {
|
|
17
30
|
// First, try to parse as-is
|
|
@@ -36,10 +49,16 @@ export function extractJsonFromResponse(text) {
|
|
|
36
49
|
} catch (e2) {
|
|
37
50
|
// Log this failure too
|
|
38
51
|
console.warn('Normalized JSON parse also failed:', e2.message);
|
|
39
|
-
|
|
52
|
+
// Fall through to sanitization
|
|
40
53
|
}
|
|
41
|
-
}
|
|
42
|
-
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Try sanitizing unescaped control characters (common LLM error)
|
|
57
|
+
try {
|
|
58
|
+
const sanitized = sanitizeJsonString(jsonStr);
|
|
59
|
+
return JSON.parse(sanitized);
|
|
60
|
+
} catch (e3) {
|
|
61
|
+
// If all attempts fail, throw the original error
|
|
43
62
|
throw e;
|
|
44
63
|
}
|
|
45
64
|
}
|