Responses providers bypass existing structural JSON repair before schema validation

Aperta Adatta ai principianti
#7,231 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
79/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
ai, backend

Direzione di ricerca

Leggi hindsight-api-slim/hindsight_api/engine/providers/openai_responses_llm.py nella sezione del parser delle risposte completate, quindi confrontalo con parse_llm_json() e validate_reply() in hindsight-api-slim/hindsight_api/engine/llm_wrapper.py. Verifica come il parser gestisce le risposte incomplete e i nuovi tentativi prima di modificare il percorso di parsing. Il lavoro è completato quando gli errori recuperabili del JSON esterno raggiungono la convalida dello schema e i casi validi, gli array serializzati come stringhe e i casi irrecuperabili mantengono il comportamento descritto.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

core

Bug Description

OpenAIResponsesLLM.call() parses a completed structured response with bare json.loads(). Recoverable JSON syntax therefore fails before it can reach either the existing parse_llm_json() helper or validate_reply(). Repeating a paid request is unnecessary when the existing local repair helper can recover it.

This is separate from #7177, which handles an array/object field encoded as a string inside valid outer JSON. It is the Responses-provider counterpart of #3683 and #5472, rather than a request to reopen those already-fixed provider paths.

Steps to Reproduce

Use the structured-output parsing callback from OpenAIResponsesLLM.call() with a completed response and the following Pydantic schema:

from pydantic import BaseModel

class Reply(BaseModel):
    facts: list[str]

Two entirely synthetic response texts reproduce the problem without calling a provider:

raw = '{"facts": ["alpha",]}'       # trailing comma
# Or an actual newline inside the JSON string:
raw = '{"facts": ["row one\nrow two"]}'
  1. Supply either text as response.output_text, with response.status = "completed".
  2. Set response_format=Reply, skip_validation=False.
  3. The current callback calls json.loads() and raises JSONDecodeError.
  4. Compare with validate_reply(Reply, parse_llm_json(raw)): it returns the intended Reply, retaining the newline in the second example.

An accompanying offline probe extracts the unmodified main callback and shared helpers via AST, supplies only the unrelated transport/metrics objects as stubs, and checks the cases above. This isolates parsing; it is not an end-to-end provider or database test.

Expected Behavior

A completed response with recoverable outer JSON should use the same structural repair available to other providers, then retain validate_reply() and its schema validation. Unrecoverable output must still fail and follow the existing retry/error path. Incomplete responses must still be rejected before repair.

Actual Behavior

Both synthetic malformed responses fail in the current Responses callback. The existing shared repair helper recovers both. Valid JSON and the #7177 stringified-array case already work; the fix should retain them.

The offline probe confirmed these four callback cases and two unrecoverable-input controls. No external model requests or production data were used. No claim is made about provider-specific failure rates or savings.

Version

Self-hosted 1.3.0 originally encountered this path. Still present in main d8d03e044ce172437dfa99079791947adc7781b4 (2026-12-03 UTC).

LLM Provider

Other: openai-responses; chatgpt also inherits OpenAIResponsesLLM. Provider responses in this reproduction are synthetic.

Code Locations and Related Work

Per CONTRIBUTING, this is a bug-report draft, not an external PR. The minimal direction is to reuse the existing repair path while preserving incomplete-response checks, validation, and retry semantics. This report does not propose accepting arbitrary or schema-invalid output.

Reproduction script

reproduce_responses.py
"""Offline probe of main's exact Responses parse callback and shared JSON helpers.

Run with Python >=3.11, json-repair and pydantic; pass the upstream checkout.
No provider requests, database imports, or production configuration are used.
"""
import ast
import copy
import json
import logging
import re
import sys
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Any

from json_repair import repair_json
from pydantic import BaseModel, ValidationError


def load_helpers(engine):
    wanted = {
        "sanitize_value", "_escape_control_chars_in_json", "parse_llm_json",
        "validate_reply", "_decode_stringified",
    }
    tree = ast.parse((engine / "llm_wrapper.py").read_text())
    nodes = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in wanted]
    assert len(nodes) == len(wanted)
    namespace = dict(globals(), _UNSAFE_TEXT_RE=re.compile(r"[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f\ud800-\udfff]"),
                     _JSON_CONTROL_ESCAPES={"\n": "\\n", "\r": "\\r", "\t": "\\t", "\b": "\\b", "\f": "\\f"},
                     _CONTAINER_ERRORS=frozenset({"list_type", "dict_type", "model_type", "model_attributes_type", "tuple_type"}),
                     logger=logging.getLogger("probe"))
    module = ast.Module(body=[ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0), *nodes], type_ignores=[])
    exec(compile(ast.fix_missing_locations(module), "upstream-json-helpers", "exec"), namespace)
    return namespace


class Reply(BaseModel):
    facts: list[str]


def run(checkout):
    engine = checkout / "hindsight-api-slim/hindsight_api/engine"
    ns = load_helpers(engine)
    provider = ast.parse((engine / "providers/openai_responses_llm.py").read_text())
    callbacks = [n for n in ast.walk(provider) if isinstance(n, ast.FunctionDef) and n.name == "parse"]
    assert len(callbacks) == 1
    ns.update(self=SimpleNamespace(_raise_if_incomplete=lambda response: None,
                                   _extract_usage=lambda response: None,
                                   _record_success=lambda **kw: None, provider="stub", model="stub"),
              _strip_reasoning_tags=lambda text: text, _strip_code_fences=lambda text: text,
              _reply_text=lambda response: response.output_text,
              start_time=time.perf_counter(), response_format=Reply, skip_validation=False,
              scope="offline", params={"input": []}, LLMCallResult=lambda **kw: SimpleNamespace(**kw))
    exec(compile(ast.fix_missing_locations(ast.Module(body=callbacks, type_ignores=[])), "upstream-responses-callback", "exec"), ns)
    cases = [
        ('{"facts": ["alpha",]}', ["alpha"]),
        ('{"facts": ["row one\nrow two"]}', ["row one\nrow two"]),
    ]
    for raw, expected in cases:
        try:
            ns["parse"](SimpleNamespace(output_text=raw))
        except json.JSONDecodeError:
            print("CONFIRMED: current Responses callback rejects recoverable JSON")
        else:
            raise AssertionError("Main behavior changed: update the issue")
        repaired = ns["validate_reply"](Reply, ns["parse_llm_json"](raw))
        assert repaired.facts == expected
        print("PASS: existing shared repair and schema validator preserve synthetic content")
    good = ns["parse"](SimpleNamespace(output_text='{"facts": ["alpha"]}'))
    assert good.content.facts == ["alpha"]
    nested = ns["parse"](SimpleNamespace(output_text=json.dumps({"facts": '["alpha"]'})))
    assert nested.content.facts == ["alpha"]
    for raw in ("", "not JSON at all"):
        try:
            ns["parse_llm_json"](raw)
        except json.JSONDecodeError:
            pass
        else:
            raise AssertionError("Unrecoverable input unexpectedly accepted")
    print("PASS: valid JSON, #7177 stringified array, and unrecoverable input controls")
    print("4 callback cases + 2 unusable-input controls passed; source extracted by AST, not full provider integration")


if __name__ == "__main__":
    run(Path(sys.argv[1]).resolve())

Lingua principale
Python
Stelle
45.2k
Fork
5.9k
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di vectorize-io/hindsight

Tutte le issue di vectorize-io/hindsight

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.