Retrieval¶
Retrieval-augmented answers over ingested documents (contractex[rag]). Every model call goes through the privacy router; see the privacy guide.
LegalRAGPipeline ¶
End-to-end RAG pipeline for legal document corpora.
Parameters¶
llm_provider: LLM provider for answer generation. Required. embedding_model: Sentence-transformers model name for embedding. Defaults to "all-MiniLM-L6-v2" (lightweight, no GPU required). vector_store: An object implementing add() and search() (see _InMemoryVectorStore). Defaults to in-memory store. If it also implements remove(doc_id), re-ingesting a URL replaces its previous chunks; otherwise they accumulate. privacy_router: PrivacyAwareLLMRouter instance. A default router is created if not supplied. citation_format: One of "inline", "footnote", "bluebook". reranker: Optional callable (query: str, chunks: list[dict]) → list[dict] for cross-encoder reranking. alpha: Weight for semantic similarity in final retrieval score [0, 1]. Default: 0.60. beta: Weight for authority score in final retrieval score [0, 1]. Default: 0.30. gamma: Weight for recency score in final retrieval score [0, 1]. Default: 0.10. conflict_detector: ConflictDetector instance. Pass None to disable conflict detection. A default detector is created if not supplied.
ingest(sources: list[str | Path | LegalDoc]) -> IngestResult ¶
query(question: str, filters: dict[str, Any] | None = None, top_k: int = 5, stream: bool = False, jurisdiction_filter: Any | None = None) -> RAGResponse | Iterator[RAGResponse] ¶
Answer question using retrieved source passages.
Parameters¶
question: The user's natural-language question. filters: Metadata filters for vector search (e.g. {"doc_type": "statute"}). top_k: Number of source chunks to retrieve. stream: If True, return an iterator of partial RAGResponse objects. jurisdiction_filter: JurisdictionTag instance. When supplied, results are hard-filtered to sources whose jurisdiction is compatible. Sources from other jurisdictions never appear in the answer without an explicit flag — this is not a soft preference.
Returns¶
RAGResponse | Iterator[RAGResponse]
query_async(question: str, filters: dict[str, Any] | None = None, top_k: int = 5, jurisdiction_filter: Any | None = None) -> RAGResponse async ¶
Async version of query() (non-streaming).
sync_sources() -> SyncResult ¶
Re-fetch every ingested URL and re-index those whose text changed.
A changed source replaces its previous copy. A source that cannot be fetched keeps its previous copy and is reported in errors. Each sync is a full fetch; conditional GETs (ETag) are not used.
RAGResponse ¶
Bases: BaseModel
A response from LegalRAGPipeline.query().
Attributes¶
answer: The generated answer (may be partial when streaming). citations: Source citations for the answer. source_docs: The LegalDoc objects used as context. conflicts: Conflicts detected among the retrieved sources before LLM generation. Empty list means no conflicts were detected. authority_range: Tuple of (min_authority_weight, max_authority_weight) across all source documents used in the context, as floats in [0.01, 1.00]. confidence: Weighted retrieval score for the top-k sources (semantic + authority). disclaimer: Always populated: "This is legal information, not legal advice." is_partial: True for intermediate streaming chunks.
IngestResult ¶
Bases: BaseModel
Summary of a LegalRAGPipeline.ingest() call.
SyncResult ¶
Bases: BaseModel
Summary of a LegalRAGPipeline.sync_sources() call.
Citation ¶
Bases: BaseModel
A source reference attached to an answer fragment in a RAGResponse.
Attributes¶
text_fragment: The fragment of the answer text this citation supports. source_title: Human-readable title of the source document. source_url: Canonical URL of the source (may be None for local documents). source_span: Exact location in the source document (chunk, page, char offsets). citation_string: Formatted citation string (populated by CitationFormatter). index: 1-based citation number within the response (for footnote style).
CitationFormatter ¶
Render Citation objects in different legal citation styles.
Supported styles¶
"inline"—(Source Title, p. N)appended to the fragment."footnote"— superscript[N]in text; full reference at the end."bluebook"— abbreviated Bluebook format (US legal standard).
Usage::
formatter = CitationFormatter()
formatted = formatter.format(citation, style="bluebook")
format(citation: Citation, style: Literal['inline', 'footnote', 'bluebook'] = 'inline') -> str ¶
Return a formatted citation string for citation.
format_inline(citation: Citation) -> str ¶
(Source Title, p. N) inline reference.
format_footnote(citation: Citation) -> str ¶
[N] Source Title (URL, page N).
format_bluebook(citation: Citation) -> str ¶
Abbreviated Bluebook-style citation.
Format: Source Title, at N (URL). For statutes and regulations, callers should override this with a proper Bluebook citation form constructed from the document's metadata.
format_all(citations: list[Citation], style: Literal['inline', 'footnote', 'bluebook'] = 'inline') -> list[str] ¶
Format a list of citations, setting index sequentially.
ConflictDetector ¶
Scans a list of retrieved LegalDoc objects for conflicting positions before the context window is assembled for the LLM.
When conflicts are detected, the caller is expected to: 1. Pass both positions to the LLM with an explicit instruction to present both and flag the disagreement. 2. Populate RAGResponse.conflicts so downstream consumers can surface the conflict to users. 3. Never allow the LLM prompt to present a false consensus.
Parameters¶
authority_conflict_gap: Minimum AuthorityLevel gap between two sources for their disagreement to be classified as AUTHORITY_CONFLICT rather than UNSETTLED_QUESTION. Default: 20 points. temporal_conflict_years: Minimum year gap between two sources for a disagreement to be flagged as TEMPORAL_CONFLICT. Default: 5 years.
detect(docs: list[LegalDoc], query: str = '') -> list[Conflict] ¶
build_conflict_prompt_addendum(conflicts: list[Conflict]) -> str ¶
Return text to append to the RAG prompt when conflicts are present.
The detector compares jurisdiction, authority and dates; it does not read the sources. So the addendum states how they differ and tells the model what to do if they turn out to disagree, without asserting that they do.
Conflict ¶
Bases: BaseModel
A detected conflict between two or more retrieved sources.
Attributes¶
conflict_type: Classification of the conflict. source_a_id: doc_id of the first conflicting source. source_b_id: doc_id of the second conflicting source (may be None for multi-source unsettled questions). source_a_title: Human-readable title for source A. source_b_title: Human-readable title for source B. description: One-sentence description of the conflict for the LLM prompt. severity: "high" — directly contradictory holdings from binding sources. "medium" — persuasive vs binding, or regional vs federal. "low" — minor variation or different emphasis.
ConflictType ¶
Bases: str, Enum
Classification of the conflict between two sources.
JURISDICTION_CONFLICT = 'jurisdiction_conflict' class-attribute instance-attribute ¶
Same question, different regional outcomes.
AUTHORITY_CONFLICT = 'authority_conflict' class-attribute instance-attribute ¶
Lower court / source contradicts higher-authority source.
TEMPORAL_CONFLICT = 'temporal_conflict' class-attribute instance-attribute ¶
Older source conflicts with newer source on same issue.
UNSETTLED_QUESTION = 'unsettled_question' class-attribute instance-attribute ¶
Multiple high-authority sources disagree — no clear winner.