Metadata-Version: 2.5
Name: tabula-razer
Version: 0.1.0b1
Summary: Standalone OpenContracts structured data extraction: run a fieldset against any OpenContracts-compatible API and emit one JSONL per field.
Project-URL: Homepage, https://github.com/Open-Source-Legal/tabula-razer
Project-URL: Documentation, https://github.com/Open-Source-Legal/tabula-razer#readme
Project-URL: Issues, https://github.com/Open-Source-Legal/tabula-razer/issues
Author: OpenContracts contributors
License-Expression: MIT
License-File: LICENSE
Keywords: extraction,legal,llm,opencontracts,pydantic-ai
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Legal Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Text Processing :: General
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic-ai-slim<2,>=1.107.10
Requires-Dist: pydantic<3,>=2.7
Provides-Extra: all
Requires-Dist: pydantic-ai-slim[anthropic,google,openai]<2,>=1.107.10; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: pydantic-ai-slim[anthropic]<2,>=1.107.10; extra == 'anthropic'
Provides-Extra: google
Requires-Dist: pydantic-ai-slim[google]<2,>=1.107.10; extra == 'google'
Provides-Extra: openai
Requires-Dist: pydantic-ai-slim[openai]<2,>=1.107.10; extra == 'openai'
Provides-Extra: test
Requires-Dist: graphql-core<3.4,>=3.2; extra == 'test'
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
Requires-Dist: pytest-cov>=5; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# Tabula Razer

OpenContracts' structured data extraction pipeline as a standalone Python
package. Choose a fieldset (a group of extraction columns) and a set of
documents. The CLI reads from an OpenContracts-compatible GraphQL server or an
offline JSON bundle and writes one JSONL file per runnable column.

```
out/
├── effective-date.jsonl      ← column "Effective Date"
├── governing-law.jsonl       ← column "Governing Law"
├── parties.jsonl             ← column "Parties"
└── manifest.json             ← run scope, model, file names, and counts
```

## Architecture

1. **Source.** A `DocumentSource` resolves the fieldset and document
   selection. The GraphQL and bundle adapters expose the same interface.
2. **Runner and index.** The asyncio runner limits concurrency, loads each
   document's text and annotations once, and shares its in-memory
   `DocumentIndex` across the selected columns. Parent IDs form the section
   hierarchy. The index supports keyword search and section traversal, with
   optional semantic search delegated to the source.
3. **Extraction engine.** A pydantic-ai agent extracts one field from one
   document at a time. It builds a prompt from the column's query, examples,
   and fenced constraints. Short documents with full text can be included in
   the prompt. The engine validates the typed result and grounds extracted
   strings in the document text when possible.
4. **Writer.** The CLI streams results to local JSONL files and records run
   state in the manifest.

The OpenContracts server's `doc_extract_query_task` imports the package's
shared prompt assembly, output parsing, diagnostics, and text alignment.
The server runs its own ORM-backed extraction and persists `Datacell` records.
See the [OpenContracts integration](https://github.com/Open-Source-Legal/OpenContracts/pull/2607).

## Install

```bash
pip install "tabula-razer[openai] @ git+https://github.com/Open-Source-Legal/tabula-razer.git"
# From a clone of this repository:
pip install -e ".[all,test]"
```

Python 3.10+, Linux / macOS / Windows. Provider keys come from the usual
environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, ...).

## Upstream requirements

For a live run, supply an OpenContracts server base URL or its GraphQL
endpoint with `--api-url`. The server must expose the
[GraphQL reads below](#graphql-contract) and have a fieldset and processed
documents available to the caller. A corpus run requires read access to both
the corpus and the documents. Use a bearer JWT or an API key
(`--auth-scheme KEY`) for authenticated access.

The CLI reads plain text from the media URLs returned by the server, so the
machine running it needs network access to the API and the media host.
Annotations supply section structure and retrieval. Server-side semantic
search is optional. If the source lacks a plain-text extract, the engine uses
reconstructed annotation excerpts. An explicit null based on excerpts is
recorded as `insufficient_document_text` because absence is unverified.

Bundle mode replaces the API with a local JSON export containing fieldsets,
documents, text or text-file references, and annotations. Live and bundle
runs both use the configured model provider for inference. Use
`--model test` to exercise the pipeline with a local test model.

## Command line

```bash
export OC_API_TOKEN=...     # a JWT or an API key (--auth-scheme KEY)

# every document in a corpus
tabula-razer run --api-url https://contracts.example.com \
  --fieldset 12 --corpus 4 --output-dir out/ --model openai:gpt-4o-mini

# specific documents (add --corpus to include that corpus's non-structural annotations)
tabula-razer run --api-url ... --fieldset 12 --document 101 --document 102 --output-dir out/

# the documents of an existing server extract (its fieldset is used unless --fieldset is given)
tabula-razer run --api-url ... --extract 31 --output-dir out/

# see what a fieldset will do before spending tokens
tabula-razer fieldset --api-url ... --fieldset 12
```

`run` prints the JSONL paths (one per extracted column) to stdout. Progress
and a summary go to stderr. IDs can be Relay global IDs or numeric primary
keys.

| Flag | Default | Meaning |
|---|---|---|
| `--model` | `openai:gpt-4o-mini` | Any pydantic-ai model spec. `test` makes no LLM calls (plumbing check). `openai:gpt-5.6*` is routed to the Responses API automatically. |
| `--concurrency` | 4 | Concurrent cells, and documents held in memory. |
| `--request-limit` | 20 | Model requests allowed per cell. |
| `--full-text-char-limit` | 24000 | Documents this short are inlined into the prompt. |
| `--no-semantic-search` | off | Drop the server-side `semanticSearch` tool; keyword search over annotations is always available. |
| `--no-grounding` | off | Skip locating extracted strings in the text. |
| `--include-llm-log` | off | Store each cell's full message history. |
| `--resume` | off | Keep `completed` / `not_found` lines in `--output-dir` and run the rest. |
| `--strict` | off | Exit 3 if any cell failed. |

From the repository root, run the bundled example with the local test model.

```bash
tabula-razer run --bundle tests/fixtures/nda_bundle.json \
  --fieldset fs-nda --corpus corpus-ndas --output-dir out/ --model test
```

## Outputs

Each runnable column gets a `<column>.jsonl` file with one
`ExtractionRecord` per resolved document. A row includes document and column
IDs, the typed value or failure details, source annotation IDs, grounding
spans, model usage, and timestamps. The file is flushed as each cell finishes,
so row order follows completion order.

```json
{"schema_version": 1, "fieldset_id": "RmllbGRzZXRUeXBlOjEy", "column_id": "...",
 "column_name": "Governing Law", "document_id": "...", "document_title": "Mutual NDA",
 "status": "completed", "data": "the State of Delaware", "output_type": "str",
 "extract_is_list": false,
 "sources": ["QW5ub3RhdGlvblR5cGU6OTE="],
 "grounding": [{"query_text": "the State of Delaware", "matched_text": "the State of Delaware",
                "char_start": 1840, "char_end": 1861, "match_type": "exact", "match_quality": 1.0,
                "annotation_ids": ["QW5ub3RhdGlvblR5cGU6OTE="]}],
 "failure_mode": null, "error": null, "model": "openai:gpt-4o-mini",
 "usage": {"requests": 3, "input_tokens": 5120, "output_tokens": 64},
 "started_at": "...", "completed_at": "..."}
```

- **`status`**: one of
  - `completed`: a value was extracted;
  - `not_found`: the agent explicitly committed to "not in this document" (`failure_mode: agent_committed_none`);
  - `failed`: no answer. `failure_mode` says why:
    - from the server's vocabulary: `usage_limit_exceeded`, `tool_loop_no_output`, `no_final_response`;
    - added by this package: `invalid_output`, `invalid_column`, `document_load_failed`, `insufficient_document_text`, `exception`.
- **`sources`**: annotation IDs the agent's tools surfaced while answering. These are the citations, the same signal as the server's `Datacell.sources`.
- **`grounding`**: where each extracted string sits in the document text, plus the most specific annotations containing it.

The manifest records the source and selection, model settings, document
count, each column's file name and status counts, and skipped columns. The
runner creates it before writing rows and sets `finished_at` when the run
finishes. `--resume` validates the source, fieldset definition, corpus,
extract, and resolved document set, then keeps settled rows and reruns the
rest. Start in a fresh directory if earlier output lacks a run identity.

The `skipped_columns` list covers manual-entry metadata columns, columns
with a custom server-side `task_name`, and columns with neither `query` nor
`match_text`.

## GraphQL contract

The GraphQL adapter implements `oc_extract.sources.DocumentSource` using
these reads.

| Method | OpenContracts GraphQL field used |
|---|---|
| `get_fieldset` | `fieldset(id) { fullColumnList }` |
| `get_extract` | `extract(id) { fieldset corpus fullDocumentList }` |
| `list_documents` | `corpus(id) { documents }` (paginated) / `document(id)` (alias-batched) |
| `get_document_text` | `document { txtExtractFile }` (resolved at document load; storage requests use a separate client) |
| `get_annotations` | `document { allAnnotations(corpusId:) { … parent { id } annotationLabel { … } } }` |
| `semantic_search` *(optional)* | `semanticSearch(documentId:, corpusId:)` |

Custom `DocumentSource` adapters can feed the same runner. They implement
`checkpoint_identity()` to support resume.

## Python API

```python
from oc_extract import DocumentSelection, EngineConfig, OpenContractsGraphQLSource, run_extraction

async with OpenContractsGraphQLSource("https://contracts.example.com", token=token) as source:
    result = await run_extraction(
        source,
        fieldset_id="12",
        selection=DocumentSelection(corpus_id="4"),
        output_dir="out",
        config=EngineConfig(model="anthropic:claude-sonnet-5-5"),
    )
result.files          # [Path("out/effective-date.jsonl"), ...]
```

`extract_column(DocumentContext, Column, ...)` runs a single cell when you
need finer control.

## Agent tools

| Tool | Purpose |
|---|---|
| `similarity_search` | Server-side vector search (when the source supports it) |
| `search_annotations` | IDF-weighted keyword search; filter by structural / label |
| `get_document_outline` | Section tree of structural annotations |
| `get_annotation` | One annotation with its ancestors and children |
| `get_subtree_text` | A section's full text from its heading |
| `list_annotation_labels` | Labels present, with counts |
| `load_document_text` | Raw text slices |

## Development

```bash
pip install -e ".[test]"
python -m pytest
```

The tests make no network or LLM calls:

- the GraphQL client runs against a fake OpenContracts server using the
  checked-in [SDL fixture](tests/fixtures/opencontracts.graphql);
- the agent runs on pydantic-ai's `FunctionModel` / `TestModel`.

Set `OC_GRAPHQL_SCHEMA` to the path of an OpenContracts checkout's
`config/graphql/schema.graphql` to run the same tests against its full
GraphQL contract.

## Publishing

PyPI Trusted Publishing uses project `tabula-razer`, GitHub owner
`Open-Source-Legal`, repository `tabula-razer`, workflow `publish.yml`,
and environment `pypi`.

Publish a GitHub release tagged with the package version prefixed by `v`,
such as `v0.1.0b1`. The workflow runs CI on that commit, builds and checks
the wheel and source distribution, then uploads them to PyPI using OIDC.
Run the workflow manually to build and validate the GitHub Actions artifact.
