`Parse_partial_json` Fails On Raw `\R` And `\T` Inside Strings
The `parse_partial_json` utility in langchain-core only escapes raw newline (`\n`) inside JSON strings, but raw carriage return (`\r`) and tab (`\t`) remain unescaped, causing `json.JSONDecodeError` when models emit these control characters.
The existing pre-processing helper that sanitizes illegal control characters in JSON strings only handles `\n` and omits `\r` and `\t`, which are also forbidden unescaped inside JSON strings per RFC 8259. As a result, `json.loads` raises `JSONDecodeError` on the malformed input.
1. Import `parse_partial_json` from `langchain_core.utils.json`.
2. Call `parse_partial_json('{"key": "line1\rline2"}')`.
3. Observe `json.decoder.JSONDecodeError: Invalid control character at: line 1 column 15 (char 14)`.
4. Call `parse_partial_json('{"key": "col1\tcol2"}')` and observe a similar error.
5. Note that raw `\n` works because it is already handled.
Fixing Code Block
import re
_JSON_STRING_RE = re.compile(r'"(?:[^"\\]|\\.)*"')
def _replace_newline(s: str) -> str:
"""Replace unescaped control characters inside JSON strings.
This replaces raw ``\\n``, ``\\r``, and ``\\t`` with their escaped
forms. The regex matches only string literals, so whitespace outside
strings is left untouched.
"""
def _escape_control_chars(match: re.Match) -> str:
token = match.group(0)
result = []
i = 0
while i < len(token):
if token[i] == '\\' and i + 1 < len(token):
# Preserve existing escape sequences.
result.append(token[i:i+2])
i += 2
elif token[i] == '\n':
result.append('\\n')
i += 1
elif token[i] == '\r':
result.append('\\r')
i += 1
elif token[i] == '\t':
result.append('\\t')
i += 1
else:
result.append(token[i])
i += 1
return ''.join(result)
return _JSON_STRING_RE.sub(_escape_control_chars, s)
The fix replaces the original newline-only replacement logic with a regex that matches double-quoted JSON strings, then scans each matched string token and escapes any unescaped `\n`, `\r`, or `\t`. It preserves existing escape sequences by skipping backslash-prefixed characters, thereby avoiding double escaping. Whitespace outside strings remains untouched, preventing accidental corruption of valid JSON formatting.
Edge Case Audit
This fix only processes double-quoted strings; if the input contains single-quoted JSON (invalid per spec but sometimes produced by models), the control characters will not be escaped. The state-machine logic is safer than naive negative lookbehind but may differ from previous behavior if any external code depended on the old function escaping newlines outside strings. Verify with inputs containing backslashes before control characters to avoid double escaping. Rollback suggestion: retain the original `_replace_newline` function or use version control to revert this change if unforeseen regressions occur.