Skip to content
Closed
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
4 changes: 2 additions & 2 deletions instructor/v2/core/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def extract_json_from_stream(chunks: Iterable[str]) -> Generator[str, None, None
yield from buffer
buffer = []
json_started = False
break
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop scanning arbitrary suffix text after JSON

When a complete JSON value and trailing prose arrive in the same provider chunk, this continue resumes scanning outside the JSON value, and any later balanced {...} or [...] prose is emitted because new roots are accepted without validation. For example, before {"a":1} See [section] for details now yields {"a":1}[section], corrupting downstream parsers; before this change the same-chunk suffix was skipped. Consider continuing only across whitespace/separators into another immediate JSON root rather than scanning arbitrary suffix text.

Useful? React with 👍 / 👎.


buffer.append(char)
continue
Expand Down Expand Up @@ -207,7 +207,7 @@ async def extract_json_from_stream_async(
yield buffered_char
buffer = []
json_started = False
break
continue

buffer.append(char)
continue
Expand Down
11 changes: 11 additions & 0 deletions tests/v2/test_json_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ def test_extract_json_from_stream_preserves_triple_backticks_in_plain_string() -
assert "".join(extract_json_from_stream(chunks)) == '{"code":"```py```"}'


def test_extract_json_from_stream_yields_all_objects_in_one_chunk() -> None:
# A complete object must not swallow a second object sharing its chunk.
chunks = ['{"a":1}{"b":2}']
assert "".join(extract_json_from_stream(chunks)) == '{"a":1}{"b":2}'


def test_extract_json_from_stream_yields_all_objects_in_fenced_chunk() -> None:
chunks = ['```json\n{"a":1}{"b":2}\n```']
assert "".join(extract_json_from_stream(chunks)) == '{"a":1}{"b":2}'


def test_extract_json_from_stream_preserves_backticks_in_fenced_string() -> None:
chunks = ["```json\n", '{"code":"`inline`"}', "\n```"]

Expand Down