File tree Expand file tree Collapse file tree 3 files changed +30
-1
lines changed Expand file tree Collapse file tree 3 files changed +30
-1
lines changed Original file line number Diff line number Diff line change @@ -184,4 +184,15 @@ def llm_read_json(text: str) -> dict:
184
184
text = "{" + text .split ("{" , 1 )[- 1 ]
185
185
# split anything after the last }
186
186
text = text .rsplit ("}" , 1 )[0 ] + "}"
187
+
188
+ # escape new lines within strings
189
+ def replace_newlines (match : re .Match ) -> str :
190
+ return match .group (0 ).replace ("\n " , "\\ n" )
191
+
192
+ # Match anything between double quotes
193
+ # including escaped quotes and other escaped characters.
194
+ # https://regex101.com/r/VFcDmB/1
195
+ pattern = r'"(?:[^"\\]|\\.)*"'
196
+ text = re .sub (pattern , replace_newlines , text )
197
+
187
198
return json .loads (text )
Original file line number Diff line number Diff line change @@ -40,7 +40,7 @@ name = "paper-qa"
40
40
readme = " README.md"
41
41
requires-python = " >=3.8"
42
42
urls = {repository = " https://github.com/whitead/paper-qa" }
43
- version = " 4.8.0 "
43
+ version = " 4.8.1 "
44
44
45
45
[tool .codespell ]
46
46
check-filenames = true
Original file line number Diff line number Diff line change 3
3
import os
4
4
import pickle
5
5
import tempfile
6
+ import textwrap
6
7
from io import BytesIO
7
8
from pathlib import Path
8
9
@@ -457,6 +458,23 @@ def test_llm_read_json(example: str):
457
458
assert llm_read_json (example ) == {"example" : "json" }
458
459
459
460
461
+ def test_llm_read_json_newlines ():
462
+ """Make sure that newlines in json are preserved and escaped."""
463
+ example = textwrap .dedent (
464
+ """
465
+ {
466
+ "summary": "A line
467
+
468
+ Another line",
469
+ "relevance_score": 7
470
+ }"""
471
+ )
472
+ assert llm_read_json (example ) == {
473
+ "summary" : "A line\n \n Another line" ,
474
+ "relevance_score" : 7 ,
475
+ }
476
+
477
+
460
478
@pytest .mark .asyncio ()
461
479
async def test_chain_completion ():
462
480
client = AsyncOpenAI ()
You can’t perform that action at this time.
0 commit comments