docling-studio/document-parser/api/reasoning.py
Pier-Jean Malandrino efc27932dd refactor(audit): remediate 0.5.0 audit findings — clean architecture, security, DRY, SOLID, perf
Closes the 12 MAJ raised by the release/0.5.0 audit pipeline (cf.
docs/audit/reports/release-0.5.0/summary.md → summary-reaudit.md).

Volet 1 — Reasoning architecture (audits 01/02/06/07 strengthening)
  * Domain ports: LLMProvider, ReasoningRunner, ReasoningParseError
  * Domain DTOs: LLMProviderType, ReasoningResult, ReasoningIteration
  * infra/llm/ollama_provider.py — OllamaProvider with health_check
  * infra/docling_agent_reasoning.py — runner adapter, encapsulates the
    private _rag_loop call (tracked at docling-project/docling-agent#26),
    commits OLLAMA_HOST once at boot (eliminates the per-request env race),
    translates upstream IndexError into ReasoningParseError
  * api/reasoning.py — zero coupling to docling-agent / mellea / docling-core,
    consumes app.state.reasoning_runner via the port
  * main.py — DI wires OllamaProvider + DoclingAgentReasoningRunner at boot
    when REASONING_ENABLED=true and deps are importable
  * Rename RAG_* env vars → REASONING_*, endpoint /rag → /reasoning,
    type RAGResult → ReasoningResult, frontend feature flag wiring,
    i18n strings, tests, docs (BREAKING — pre-1.0 surface, no external
    consumers in production)
  * 17 new tests: adapter unit tests with sys.modules stubs, OllamaProvider
    httpx tests, R3 concurrent-host isolation, R6 multi-iteration trace
    serialization, R13 Protocol conformance via isinstance
  * E2E Karate scenario: nav-reasoning hidden when REASONING_ENABLED=false
  * README — Live Reasoning section (env vars, archi, link to issue #26)

Bloc B — Security (audit 08, dev-only context)
  * docker-compose.yml — DEV DEFAULTS header, OpenSearch DISABLE_SECURITY_PLUGIN
    flagged as dev-only with link to OpenSearch security docs
  * main.py — boot warning if NEO4J_URI is set with the default 'changeme'
    password, so prod operators can't silently inherit it

Bloc C — DRY frontend (audit 05)
  * shared/storage/keys.ts — STORAGE_KEYS centralised (theme, locale)
  * features/settings/store.ts — dead apiUrl ref + orphan i18n keys removed
  * api/schemas.py — DOCUMENT_STATUS_UPLOADED constant

Bloc D — Quality (audits 02/06/07/09/10/12)
  * domain/ports.py — DocumentConverter.supports_page_batching property
    (LSP fix, replaces isinstance(ServeConverter) check)
  * domain/ports.py — VectorStore.ping() (encapsulation, replaces
    _vector_store._client.info() reach-around)
  * api/analyses.py + api/ingestion.py — path params {job_id} → {analysis_id}
    aligned with the user-facing terminology (URLs unchanged)
  * api/documents.py — Path.read_bytes() + generate_preview() wrapped in
    asyncio.to_thread, unblocks the FastAPI event loop on /preview
  * infra/docling_tree.py — PEP 604 union for isinstance (Ruff UP038)
  * src/__tests__/integration/ — cross-feature integration test relocated
    out of features/history/ so feature folders stay self-contained
  * Tightened terminal `assert X is not None` checks (isinstance(.., datetime),
    exact value comparisons)

Validation
  * 446 backend pytest, 202 frontend vitest — all green
  * ruff + ruff format + ESLint + Prettier + vue-tsc clean
  * Re-audit verdict: 0 CRIT / 0 MAJ, score ~94/100, GO

Closes #200
2026-04-29 14:00:00 +02:00

113 lines
3.9 KiB
Python

"""Reasoning API — HTTP layer over a `ReasoningRunner` port.
`POST /api/documents/:id/reasoning` invokes the wired-up `ReasoningRunner`
against the stored `DoclingDocument` and returns a `ReasoningResultResponse`
in the same shape the v1 import dialog already consumes — so the frontend
overlay code is fully reused.
This module has zero coupling to docling-agent / mellea / docling-core. The
runner (concrete adapter in `infra/docling_agent_reasoning.py`) is set on
`app.state.reasoning_runner` at boot when `REASONING_ENABLED=true` and the
deps are importable. Otherwise it stays `None` and we 503.
Sync blocking call offloaded to a thread by the adapter so we don't stall
the event loop. No streaming at this step (see design doc §7 for v2 SSE plan).
"""
from __future__ import annotations
import logging
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from domain.ports import ReasoningParseError, ReasoningRunner
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/documents", tags=["reasoning"])
class ReasoningRunRequest(BaseModel):
query: str
# Optional per-run override; falls back to the runner's default model.
model_id: str | None = None
class ReasoningIterationResponse(BaseModel):
iteration: int
section_ref: str
reason: str
section_text_length: int
can_answer: bool
response: str
class ReasoningResultResponse(BaseModel):
answer: str
iterations: list[ReasoningIterationResponse]
converged: bool
@router.post("/{doc_id}/reasoning", response_model=ReasoningResultResponse)
async def run_reasoning(
doc_id: str, body: ReasoningRunRequest, request: Request
) -> ReasoningResultResponse:
runner: ReasoningRunner | None = getattr(request.app.state, "reasoning_runner", None)
if runner is None or not runner.is_available:
raise HTTPException(
status_code=503,
detail=(
"Live reasoning disabled (REASONING_ENABLED=false or docling-agent not installed)"
),
)
if not body.query.strip():
raise HTTPException(status_code=400, detail="Query must not be empty")
analysis_repo = getattr(request.app.state, "analysis_repo", None)
if analysis_repo is None:
raise HTTPException(status_code=500, detail="AnalysisRepository not wired")
latest = await analysis_repo.find_latest_completed_by_document(doc_id)
if latest is None or not latest.document_json:
raise HTTPException(
status_code=404,
detail=f"No completed analysis with document_json for {doc_id}",
)
try:
result = await runner.run(
document_json=latest.document_json,
query=body.query,
model_id=body.model_id,
)
except ReasoningParseError as e:
# The upstream LLM couldn't produce a parseable answer after retries.
# 502 Bad Gateway — not our fault — with guidance the UI can show.
raise HTTPException(
status_code=502,
detail=(
f"The model '{e.model_id}' couldn't produce a parseable "
"answer after retries. Try a different model (e.g. "
"mistral-small3.2) or rephrase the question."
),
) from e
except Exception as e:
logger.exception("Reasoning loop failed for doc %s", doc_id)
raise HTTPException(status_code=500, detail=f"Reasoning loop failed: {e}") from e
return ReasoningResultResponse(
answer=result.answer,
iterations=[
ReasoningIterationResponse(
iteration=it.iteration,
section_ref=it.section_ref,
reason=it.reason,
section_text_length=it.section_text_length,
can_answer=it.can_answer,
response=it.response,
)
for it in result.iterations
],
converged=result.converged,
)