#2694·instructor

Streaming JSON extract takes first object; non-stream takes last (Partial/MD_JSON wrong answer)

Author: michaelkillgtaCreated Sep 25, 2026Updated Sep 25, 2026

Description

Streaming JSON extraction and non-streaming extraction disagree on which JSON object wins when the model (or prompt) contains multiple objects.

extract_json_from_codeblock was deliberately changed to return the last JSON object so prompt-embedded JSON cannot hijack parsing. extract_json_from_stream / _async still emit every complete candidate (concatenated). Partial.model_from_chunks then accumulates that into {"a":1}{"a":2}; jiter trailing-strings keeps the first object, and final validation is skipped because the concatenated string is not strict-complete JSON.

Result: streaming Partial / MD_JSON returns the first object while non-stream returns the last — wrong structured results and a broken anti-injection invariant on the streaming path.

Environment

  • instructor==1.17.0
  • Python 3.13

Minimal repro

python
from instructor.v2.core.json import (
    extract_json_from_codeblock,
    extract_json_from_stream,
)
from instructor.v2.dsl.partial import Partial
from pydantic import BaseModel

class M(BaseModel):
    a: int

text = 'prefix {"a": 1} suffix {"a": 2}'
print(extract_json_from_codeblock(text))  # {"a": 2}  — last (intended)

chunks = list(text)
streamed = "".join(extract_json_from_stream(iter(chunks)))
print(streamed)  # '{"a": 1}{"a": 2}'  — concatenated

final = None
for m in Partial[M].model_from_chunks(iter(chunks)):
    final = m
print(final)  # a=1  — first (wrong vs non-stream)

Expected

Streaming extraction should match non-stream: prefer the last complete JSON object (same anti-injection rule), so Partial streaming ends with a=2.

Actual

  • Non-stream: {"a": 2}
  • Stream extract: '{"a": 1}{"a": 2}'
  • Partial streaming final: a=1

Root cause (pointer)

instructor/v2/core/json.py — extract_json_from_stream* concatenates every complete candidate; only the non-stream helper applies the last-object policy. Consumed by OpenAI/Anthropic/etc. streaming Partial handlers.

Suggested fix direction

Make stream extractors keep only the latest complete object (or otherwise align with extract_json_from_codeblock), and ensure Partial finalization does not prefer the first object via concatenated jiter input.