mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-14 18:44:05 +02:00
## Summary Adds a new AI specialist that finds **textual contradictions** across one or more PDFs — conflicting claims, recommendations, points of view, contested facts — built entirely in Python on top of the new `DocumentService` + `ChunkedReasoner` stack from #6314. Replaces the closed #6304, which was started before #6314 landed and therefore over-engineered (Java orchestrator, two-round handshake, resume artifact, discriminated-union lift). Two commits: 1. **`refactor(engine): extract ChunkedMapper[T] from ChunkedReasoner`** — pure refactor, public API of ChunkedReasoner unchanged. New `ChunkedMapper[T: BaseModel]` is a generic parallel-chunk primitive (slicing, semaphore, time-bounded extraction, cancellation drain, progress events) that's now a peer to ChunkedReasoner rather than locked inside it. The compression loop stays on ChunkedReasoner where it belongs. 2. **`feat(ai): add Contradiction Agent on ChunkedMapper`** — the agent itself, plus integrations into `PdfReviewAgent` and `PdfQuestionAgent`. ## Architecture - **Python-only.** No Java code. No `AgentToolId.CONTRADICTION_AGENT`. No dedicated HTTP endpoint. No resume artifact, no discriminated-union lift in `contracts/common.py`. Detector runs inside the Python engine and the Python engine alone. - **Review path** (`PdfReviewAgent`): a new `ContradictionIntentClassifier` fires on contradiction-flavoured prompts; agent runs detection synchronously and emits a single `EditPlanResponse(steps=[ADD_COMMENTS])`. Single-turn flow — no resume. - **Question path** (`PdfQuestionAgent`): a new `ContradictionCapability` joins `RagCapability` and `WholeDocReaderCapability` in the smart-model toolset, exposing `find_contradictions(query)`. The smart model picks it from the toolset alongside `search_knowledge` and `read_full_document`. ## Inside `ContradictionDetector.detect()` 1. `DocumentService.read_pages(file_id)` → ordered `list[Page]`. 2. `ChunkedMapper[_ExtractedClaims].map_pages(...)` — char-budgeted multi-page slicing; each slice runs the claim-extractor LLM in parallel under a semaphore. 3. Page-traceability: the extractor returns `_ExtractedClaim.page` (which `[Page N]` marker the claim came from). The wrapper validates `page ∈ chunk.pages`; if not, mechanical fallback searches the chunk's page text for the verbatim quote and reassigns. If still no match, drop the claim. 4. `Claim.anchor_quality: Literal[\"verbatim\", \"paraphrased\"]` is set by a substring check against the declared page's text. Verbatim quotes feed `anchor_text` for snap-to-quote add-comments placement; paraphrased ones fall back to margin geometry. 5. Subject canonicalisation: ONE fast-model LLM call collapses synonyms across the document. Fails open to lexical bucketing. 6. Pre-filters: drop identical-quote pairs; drop same-page same-polarity paraphrases. 7. Per-bucket pair detection in parallel (separate semaphore, cap 5). Buckets > 12 claims chunk into windows of 12 with overlap 2; pairs deduped across overlapping windows by frozen `(i, j)` index pair. 8. Summary fast-model call with fallback string on error. ## Prompt-injection hardening Every prompt that interpolates user-supplied or PDF-extracted text wraps content in `<user_message>` / `<verdict>` / `<content>` tags with an explicit SECURITY preamble instructing the model to treat tagged content as data only. ## Limitations - **Combined math + contradiction intent**: when both intent classifiers fire on the same prompt, contradiction takes precedence and the math intent is silently dropped. Documented in the Review module docstring and pinned by `test_review_integration.py::test_contradiction_precedence_over_math`. - **Cross-window contradiction reach**: within a subject bucket, pairs more than ~10 claim indices apart in the same chunked window may be missed by the overlap-2 strategy. Documented in `test_detector.py`. Acceptable for v1. ## Settings (engine/src/stirling/config/settings.py) ```python contradiction_detect_concurrency = 5 # per-bucket detector semaphore contradiction_bucket_chunk_size = 12 # max claims per detector call contradiction_bucket_chunk_overlap = 2 # overlap for >threshold buckets ``` `chars_per_slice` and extraction concurrency are reused from the existing `chunked_reasoner_*` settings. ## Test plan - [x] `uv run pytest tests/ -v` — **245/245 pass** (210 pre-existing + 35 new) - [x] `uv run ruff check src/ tests/` — clean - [x] `uv run pyright src/stirling/agents/contradiction/ src/stirling/contracts/contradiction.py` — 0 errors - [x] `./gradlew :proprietary:test` — green; no Java was touched, but verified untouched - [x] Page-traceability tests cover: valid page kept, hallucinated page dropped, mechanical-reassign on misattribution, anchor-quality verbatim vs paraphrased - [x] Review integration: ADD_COMMENTS plan with two paired CommentSpecs per contradiction; NeedIngestResponse precheck; precedence vs math intent pinned - [x] Question integration: all three capabilities wired into smart-model toolset; `find_contradictions` returns formatted report text - [x] ChunkedMapper standalone: slicing, multi-chunk ordering, worker failures, timeouts, cancellation drain, semaphore saturation - [x] ChunkedReasoner regression: all pre-existing tests pass unchanged after the internal split ## Relationship to closed #6304 #6304 was closed in favour of this PR. The closed PR predated #6314 and modelled the agent as a Java-orchestrated two-round examine/deliberate flow with its own HTTP endpoint and a discriminated-union resume artifact. With #6314 making full ordered page text available to the engine via `DocumentService.read_pages`, none of that is needed. Net effect: drop ~600 lines of Java, drop the two-round handshake, drop the `ToolReportArtifact` lift, while ending up with a more scalable agent (chunk-based instead of page-based extraction; tested to ChunkedReasoner-equivalent scale).
123 lines
4.3 KiB
Python
123 lines
4.3 KiB
Python
"""PdfQuestionAgent — contradiction capability wiring.
|
|
|
|
The smart-model agent picks the right tool based on the question; here
|
|
we don't drive the smart model — we directly verify that the agent
|
|
wires the contradiction capability into its toolset alongside RAG and
|
|
the whole-document reader, and that the capability dispatches to the
|
|
detector when invoked.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import replace
|
|
|
|
import pytest
|
|
from pydantic_ai.toolsets import FunctionToolset
|
|
|
|
from stirling.agents.pdf_questions import PdfQuestionAgent
|
|
from stirling.contracts import (
|
|
AiFile,
|
|
PageText,
|
|
PdfQuestionRequest,
|
|
)
|
|
from stirling.contracts.contradiction import Claim
|
|
from stirling.documents import DocumentService, SqliteVecStore
|
|
from stirling.models import FileId
|
|
from stirling.services.runtime import AppRuntime
|
|
from tests.test_pdf_question_agent import StubEmbedder
|
|
|
|
|
|
def _file(file_id: str, name: str) -> AiFile:
|
|
return AiFile(id=FileId(file_id), name=name)
|
|
|
|
|
|
def _claim(page: int, quote: str) -> Claim:
|
|
return Claim(
|
|
page=page,
|
|
subject="deadline",
|
|
polarity="assert",
|
|
text=f"paraphrase {page}",
|
|
quote=quote,
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def runtime_with_stub_docs(runtime: AppRuntime) -> AppRuntime:
|
|
stub = DocumentService(
|
|
embedder=StubEmbedder(), # type: ignore[arg-type]
|
|
store=SqliteVecStore.ephemeral(),
|
|
default_top_k=runtime.settings.rag_default_top_k,
|
|
)
|
|
return replace(runtime, documents=stub)
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_run_answer_agent_builds_agent_with_three_toolsets(
|
|
runtime_with_stub_docs: AppRuntime,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""``_run_answer_agent`` constructs an ``Agent`` with all three retrieval
|
|
toolsets (rag, whole-doc, contradiction). We intercept the Agent
|
|
constructor and inspect what was wired.
|
|
|
|
Uses pytest's ``monkeypatch`` fixture rather than direct attribute
|
|
assignment so pyright sees the swap as a typed test-only operation
|
|
and restoration is automatic if the test raises.
|
|
"""
|
|
file = _file("doc-a", "a.pdf")
|
|
await runtime_with_stub_docs.documents.ingest(
|
|
file.id,
|
|
[PageText(page_number=1, text="content")],
|
|
source=file.name,
|
|
)
|
|
|
|
agent = PdfQuestionAgent(runtime_with_stub_docs)
|
|
|
|
captured: dict[str, object] = {}
|
|
|
|
import pydantic_ai
|
|
|
|
real_agent_init = pydantic_ai.Agent.__init__
|
|
|
|
# The Agent class is generic on deps/output types — its __init__ accepts
|
|
# arbitrary positional+keyword arguments depending on those parameters.
|
|
# We're monkey-patching the class itself for one test, so the bound
|
|
# method's signature is intentionally opaque here. Typing through Any
|
|
# is honest about that boundary ("we can't statically describe it")
|
|
# and avoids wallpapering the body with type-ignore directives.
|
|
from typing import Any
|
|
|
|
def _capture_init(self: Any, *args: Any, **kwargs: Any) -> None:
|
|
captured["toolsets"] = kwargs.get("toolsets")
|
|
captured["instructions"] = kwargs.get("instructions")
|
|
# Call the real init for safety.
|
|
real_agent_init(self, *args, **kwargs)
|
|
|
|
# Stub the agent's `.run` so we don't reach a real model.
|
|
async def _stub_run(self: Any, *args: Any, **kwargs: Any) -> object:
|
|
class _Result:
|
|
output = "stubbed"
|
|
|
|
return _Result()
|
|
|
|
monkeypatch.setattr(pydantic_ai.Agent, "__init__", _capture_init)
|
|
monkeypatch.setattr(pydantic_ai.Agent, "run", _stub_run)
|
|
await agent._run_answer_agent(PdfQuestionRequest(question="any conflicts?", files=[file]))
|
|
|
|
toolsets = captured.get("toolsets")
|
|
assert isinstance(toolsets, list)
|
|
assert len(toolsets) == 3
|
|
|
|
# Inspect the registered tool names. A regression that double-wired
|
|
# one capability (e.g. two ``rag.toolset`` and dropping
|
|
# ``contradiction.toolset``) would still satisfy ``len == 3`` but
|
|
# the union of tool names would not include ``find_contradictions``.
|
|
tool_names: set[str] = set()
|
|
for ts in toolsets:
|
|
assert isinstance(ts, FunctionToolset), f"expected FunctionToolset, got {type(ts).__name__}"
|
|
tool_names.update(ts.tools.keys())
|
|
|
|
assert tool_names == {"search_knowledge", "read_full_document", "find_contradictions"}, (
|
|
f"unexpected toolset wiring; tool names = {sorted(tool_names)}"
|
|
)
|