tabula-razer 0.1.0b1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. tabula_razer-0.1.0b1/.github/workflows/ci.yml +50 -0
  2. tabula_razer-0.1.0b1/.github/workflows/publish.yml +71 -0
  3. tabula_razer-0.1.0b1/.gitignore +14 -0
  4. tabula_razer-0.1.0b1/LICENSE +21 -0
  5. tabula_razer-0.1.0b1/PKG-INFO +265 -0
  6. tabula_razer-0.1.0b1/README.md +228 -0
  7. tabula_razer-0.1.0b1/pyproject.toml +68 -0
  8. tabula_razer-0.1.0b1/src/oc_extract/__init__.py +78 -0
  9. tabula_razer-0.1.0b1/src/oc_extract/__main__.py +7 -0
  10. tabula_razer-0.1.0b1/src/oc_extract/cli.py +259 -0
  11. tabula_razer-0.1.0b1/src/oc_extract/constants.py +195 -0
  12. tabula_razer-0.1.0b1/src/oc_extract/diagnostics.py +152 -0
  13. tabula_razer-0.1.0b1/src/oc_extract/engine.py +310 -0
  14. tabula_razer-0.1.0b1/src/oc_extract/grounding.py +369 -0
  15. tabula_razer-0.1.0b1/src/oc_extract/index.py +399 -0
  16. tabula_razer-0.1.0b1/src/oc_extract/llm.py +71 -0
  17. tabula_razer-0.1.0b1/src/oc_extract/models.py +166 -0
  18. tabula_razer-0.1.0b1/src/oc_extract/output_types.py +129 -0
  19. tabula_razer-0.1.0b1/src/oc_extract/prompts.py +202 -0
  20. tabula_razer-0.1.0b1/src/oc_extract/py.typed +0 -0
  21. tabula_razer-0.1.0b1/src/oc_extract/runner.py +339 -0
  22. tabula_razer-0.1.0b1/src/oc_extract/sources/__init__.py +20 -0
  23. tabula_razer-0.1.0b1/src/oc_extract/sources/base.py +122 -0
  24. tabula_razer-0.1.0b1/src/oc_extract/sources/bundle.py +189 -0
  25. tabula_razer-0.1.0b1/src/oc_extract/sources/graphql.py +563 -0
  26. tabula_razer-0.1.0b1/src/oc_extract/tools.py +298 -0
  27. tabula_razer-0.1.0b1/src/oc_extract/writer.py +156 -0
  28. tabula_razer-0.1.0b1/tests/conftest.py +62 -0
  29. tabula_razer-0.1.0b1/tests/fake_opencontracts.py +369 -0
  30. tabula_razer-0.1.0b1/tests/fixtures/nda_bundle.json +109 -0
  31. tabula_razer-0.1.0b1/tests/fixtures/opencontracts.graphql +99 -0
  32. tabula_razer-0.1.0b1/tests/scripted_llm.py +114 -0
  33. tabula_razer-0.1.0b1/tests/test_bundle_source.py +101 -0
  34. tabula_razer-0.1.0b1/tests/test_cli.py +236 -0
  35. tabula_razer-0.1.0b1/tests/test_diagnostics.py +124 -0
  36. tabula_razer-0.1.0b1/tests/test_engine.py +322 -0
  37. tabula_razer-0.1.0b1/tests/test_graphql_source.py +345 -0
  38. tabula_razer-0.1.0b1/tests/test_grounding.py +111 -0
  39. tabula_razer-0.1.0b1/tests/test_index.py +173 -0
  40. tabula_razer-0.1.0b1/tests/test_llm.py +71 -0
  41. tabula_razer-0.1.0b1/tests/test_output_types.py +112 -0
  42. tabula_razer-0.1.0b1/tests/test_prompts.py +89 -0
  43. tabula_razer-0.1.0b1/tests/test_runner.py +581 -0
  44. tabula_razer-0.1.0b1/tests/test_tools.py +162 -0
  45. tabula_razer-0.1.0b1/tests/test_writer.py +151 -0
@@ -0,0 +1,50 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+ workflow_call:
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ test:
14
+ name: Tests (${{ matrix.os }}, Python ${{ matrix.python-version }})
15
+ runs-on: ${{ matrix.os }}
16
+ timeout-minutes: 20
17
+ strategy:
18
+ fail-fast: false
19
+ matrix:
20
+ os: [ubuntu-latest, macos-latest, windows-latest]
21
+ python-version: ["3.10", "3.12", "3.13"]
22
+ steps:
23
+ - uses: actions/checkout@v7.0.1
24
+ - uses: actions/setup-python@v7
25
+ with:
26
+ python-version: ${{ matrix.python-version }}
27
+ cache: pip
28
+ cache-dependency-path: pyproject.toml
29
+ - run: python -m pip install -e ".[test]"
30
+ - run: python -m pytest --cov=oc_extract --cov-report=term-missing --cov-fail-under=90
31
+
32
+ package:
33
+ name: Type check and package
34
+ runs-on: ubuntu-latest
35
+ timeout-minutes: 10
36
+ steps:
37
+ - uses: actions/checkout@v7.0.1
38
+ - uses: actions/setup-python@v7
39
+ with:
40
+ python-version: "3.12"
41
+ - run: python -m pip install -e ".[test]" mypy build
42
+ - run: python -m mypy --config-file pyproject.toml
43
+ - run: python -m build
44
+ - name: Smoke-test the installed wheel
45
+ run: |
46
+ python -m venv "${RUNNER_TEMP}/tabula-razer-wheel"
47
+ "${RUNNER_TEMP}/tabula-razer-wheel/bin/python" -m pip install dist/*.whl
48
+ "${RUNNER_TEMP}/tabula-razer-wheel/bin/tabula-razer" run \
49
+ --bundle tests/fixtures/nda_bundle.json --fieldset fs-nda \
50
+ --corpus corpus-ndas --model test --output-dir "${RUNNER_TEMP}/extract" --strict
@@ -0,0 +1,71 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ permissions: {}
9
+
10
+ jobs:
11
+ verify:
12
+ name: Verify release commit
13
+ if: github.event_name == 'release'
14
+ uses: ./.github/workflows/ci.yml
15
+ permissions:
16
+ contents: read
17
+
18
+ build:
19
+ name: Build distributions
20
+ runs-on: ubuntu-latest
21
+ timeout-minutes: 10
22
+ permissions:
23
+ contents: read
24
+ steps:
25
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
26
+ with:
27
+ persist-credentials: false
28
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
29
+ with:
30
+ python-version: "3.12"
31
+ - name: Check release tag against the package version
32
+ if: github.event_name == 'release'
33
+ env:
34
+ RELEASE_TAG: ${{ github.event.release.tag_name }}
35
+ run: |
36
+ python - <<'PY'
37
+ import os
38
+ import tomllib
39
+
40
+ with open("pyproject.toml", "rb") as project:
41
+ version = tomllib.load(project)["project"]["version"]
42
+ expected = f"v{version}"
43
+ if os.environ["RELEASE_TAG"] != expected:
44
+ raise SystemExit(f"The release tag must be {expected}.")
45
+ PY
46
+ - run: python -m pip install build twine
47
+ - run: python -m build
48
+ - run: python -m twine check --strict dist/*
49
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
50
+ with:
51
+ name: tabula-razer-dist
52
+ path: dist/
53
+ if-no-files-found: error
54
+
55
+ publish:
56
+ name: Publish distributions
57
+ if: github.event_name == 'release'
58
+ needs: [verify, build]
59
+ runs-on: ubuntu-latest
60
+ timeout-minutes: 10
61
+ environment:
62
+ name: pypi
63
+ url: https://pypi.org/project/tabula-razer/
64
+ permissions:
65
+ id-token: write
66
+ steps:
67
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
68
+ with:
69
+ name: tabula-razer-dist
70
+ path: dist/
71
+ - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
@@ -0,0 +1,14 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .env
5
+ .env.*
6
+ .coverage
7
+ .coverage.*
8
+ .mypy_cache/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+ *.egg-info/
12
+ build/
13
+ dist/
14
+ out/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 John Scrudato IV
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.5
2
+ Name: tabula-razer
3
+ Version: 0.1.0b1
4
+ Summary: Standalone OpenContracts structured data extraction: run a fieldset against any OpenContracts-compatible API and emit one JSONL per field.
5
+ Project-URL: Homepage, https://github.com/Open-Source-Legal/tabula-razer
6
+ Project-URL: Documentation, https://github.com/Open-Source-Legal/tabula-razer#readme
7
+ Project-URL: Issues, https://github.com/Open-Source-Legal/tabula-razer/issues
8
+ Author: OpenContracts contributors
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: extraction,legal,llm,opencontracts,pydantic-ai
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Legal Industry
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: Text Processing :: General
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: httpx<1,>=0.27
21
+ Requires-Dist: pydantic-ai-slim<2,>=1.107.10
22
+ Requires-Dist: pydantic<3,>=2.7
23
+ Provides-Extra: all
24
+ Requires-Dist: pydantic-ai-slim[anthropic,google,openai]<2,>=1.107.10; extra == 'all'
25
+ Provides-Extra: anthropic
26
+ Requires-Dist: pydantic-ai-slim[anthropic]<2,>=1.107.10; extra == 'anthropic'
27
+ Provides-Extra: google
28
+ Requires-Dist: pydantic-ai-slim[google]<2,>=1.107.10; extra == 'google'
29
+ Provides-Extra: openai
30
+ Requires-Dist: pydantic-ai-slim[openai]<2,>=1.107.10; extra == 'openai'
31
+ Provides-Extra: test
32
+ Requires-Dist: graphql-core<3.4,>=3.2; extra == 'test'
33
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
34
+ Requires-Dist: pytest-cov>=5; extra == 'test'
35
+ Requires-Dist: pytest>=8; extra == 'test'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # Tabula Razer
39
+
40
+ OpenContracts' structured data extraction pipeline as a standalone Python
41
+ package. Choose a fieldset (a group of extraction columns) and a set of
42
+ documents. The CLI reads from an OpenContracts-compatible GraphQL server or an
43
+ offline JSON bundle and writes one JSONL file per runnable column.
44
+
45
+ ```
46
+ out/
47
+ ├── effective-date.jsonl ← column "Effective Date"
48
+ ├── governing-law.jsonl ← column "Governing Law"
49
+ ├── parties.jsonl ← column "Parties"
50
+ └── manifest.json ← run scope, model, file names, and counts
51
+ ```
52
+
53
+ ## Architecture
54
+
55
+ 1. **Source.** A `DocumentSource` resolves the fieldset and document
56
+ selection. The GraphQL and bundle adapters expose the same interface.
57
+ 2. **Runner and index.** The asyncio runner limits concurrency, loads each
58
+ document's text and annotations once, and shares its in-memory
59
+ `DocumentIndex` across the selected columns. Parent IDs form the section
60
+ hierarchy. The index supports keyword search and section traversal, with
61
+ optional semantic search delegated to the source.
62
+ 3. **Extraction engine.** A pydantic-ai agent extracts one field from one
63
+ document at a time. It builds a prompt from the column's query, examples,
64
+ and fenced constraints. Short documents with full text can be included in
65
+ the prompt. The engine validates the typed result and grounds extracted
66
+ strings in the document text when possible.
67
+ 4. **Writer.** The CLI streams results to local JSONL files and records run
68
+ state in the manifest.
69
+
70
+ The OpenContracts server's `doc_extract_query_task` imports the package's
71
+ shared prompt assembly, output parsing, diagnostics, and text alignment.
72
+ The server runs its own ORM-backed extraction and persists `Datacell` records.
73
+ See the [OpenContracts integration](https://github.com/Open-Source-Legal/OpenContracts/pull/2607).
74
+
75
+ ## Install
76
+
77
+ ```bash
78
+ pip install "tabula-razer[openai] @ git+https://github.com/Open-Source-Legal/tabula-razer.git"
79
+ # From a clone of this repository:
80
+ pip install -e ".[all,test]"
81
+ ```
82
+
83
+ Python 3.10+, Linux / macOS / Windows. Provider keys come from the usual
84
+ environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, ...).
85
+
86
+ ## Upstream requirements
87
+
88
+ For a live run, supply an OpenContracts server base URL or its GraphQL
89
+ endpoint with `--api-url`. The server must expose the
90
+ [GraphQL reads below](#graphql-contract) and have a fieldset and processed
91
+ documents available to the caller. A corpus run requires read access to both
92
+ the corpus and the documents. Use a bearer JWT or an API key
93
+ (`--auth-scheme KEY`) for authenticated access.
94
+
95
+ The CLI reads plain text from the media URLs returned by the server, so the
96
+ machine running it needs network access to the API and the media host.
97
+ Annotations supply section structure and retrieval. Server-side semantic
98
+ search is optional. If the source lacks a plain-text extract, the engine uses
99
+ reconstructed annotation excerpts. An explicit null based on excerpts is
100
+ recorded as `insufficient_document_text` because absence is unverified.
101
+
102
+ Bundle mode replaces the API with a local JSON export containing fieldsets,
103
+ documents, text or text-file references, and annotations. Live and bundle
104
+ runs both use the configured model provider for inference. Use
105
+ `--model test` to exercise the pipeline with a local test model.
106
+
107
+ ## Command line
108
+
109
+ ```bash
110
+ export OC_API_TOKEN=... # a JWT or an API key (--auth-scheme KEY)
111
+
112
+ # every document in a corpus
113
+ tabula-razer run --api-url https://contracts.example.com \
114
+ --fieldset 12 --corpus 4 --output-dir out/ --model openai:gpt-4o-mini
115
+
116
+ # specific documents (add --corpus to include that corpus's non-structural annotations)
117
+ tabula-razer run --api-url ... --fieldset 12 --document 101 --document 102 --output-dir out/
118
+
119
+ # the documents of an existing server extract (its fieldset is used unless --fieldset is given)
120
+ tabula-razer run --api-url ... --extract 31 --output-dir out/
121
+
122
+ # see what a fieldset will do before spending tokens
123
+ tabula-razer fieldset --api-url ... --fieldset 12
124
+ ```
125
+
126
+ `run` prints the JSONL paths (one per extracted column) to stdout. Progress
127
+ and a summary go to stderr. IDs can be Relay global IDs or numeric primary
128
+ keys.
129
+
130
+ | Flag | Default | Meaning |
131
+ |---|---|---|
132
+ | `--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. |
133
+ | `--concurrency` | 4 | Concurrent cells, and documents held in memory. |
134
+ | `--request-limit` | 20 | Model requests allowed per cell. |
135
+ | `--full-text-char-limit` | 24000 | Documents this short are inlined into the prompt. |
136
+ | `--no-semantic-search` | off | Drop the server-side `semanticSearch` tool; keyword search over annotations is always available. |
137
+ | `--no-grounding` | off | Skip locating extracted strings in the text. |
138
+ | `--include-llm-log` | off | Store each cell's full message history. |
139
+ | `--resume` | off | Keep `completed` / `not_found` lines in `--output-dir` and run the rest. |
140
+ | `--strict` | off | Exit 3 if any cell failed. |
141
+
142
+ From the repository root, run the bundled example with the local test model.
143
+
144
+ ```bash
145
+ tabula-razer run --bundle tests/fixtures/nda_bundle.json \
146
+ --fieldset fs-nda --corpus corpus-ndas --output-dir out/ --model test
147
+ ```
148
+
149
+ ## Outputs
150
+
151
+ Each runnable column gets a `<column>.jsonl` file with one
152
+ `ExtractionRecord` per resolved document. A row includes document and column
153
+ IDs, the typed value or failure details, source annotation IDs, grounding
154
+ spans, model usage, and timestamps. The file is flushed as each cell finishes,
155
+ so row order follows completion order.
156
+
157
+ ```json
158
+ {"schema_version": 1, "fieldset_id": "RmllbGRzZXRUeXBlOjEy", "column_id": "...",
159
+ "column_name": "Governing Law", "document_id": "...", "document_title": "Mutual NDA",
160
+ "status": "completed", "data": "the State of Delaware", "output_type": "str",
161
+ "extract_is_list": false,
162
+ "sources": ["QW5ub3RhdGlvblR5cGU6OTE="],
163
+ "grounding": [{"query_text": "the State of Delaware", "matched_text": "the State of Delaware",
164
+ "char_start": 1840, "char_end": 1861, "match_type": "exact", "match_quality": 1.0,
165
+ "annotation_ids": ["QW5ub3RhdGlvblR5cGU6OTE="]}],
166
+ "failure_mode": null, "error": null, "model": "openai:gpt-4o-mini",
167
+ "usage": {"requests": 3, "input_tokens": 5120, "output_tokens": 64},
168
+ "started_at": "...", "completed_at": "..."}
169
+ ```
170
+
171
+ - **`status`**: one of
172
+ - `completed`: a value was extracted;
173
+ - `not_found`: the agent explicitly committed to "not in this document" (`failure_mode: agent_committed_none`);
174
+ - `failed`: no answer. `failure_mode` says why:
175
+ - from the server's vocabulary: `usage_limit_exceeded`, `tool_loop_no_output`, `no_final_response`;
176
+ - added by this package: `invalid_output`, `invalid_column`, `document_load_failed`, `insufficient_document_text`, `exception`.
177
+ - **`sources`**: annotation IDs the agent's tools surfaced while answering. These are the citations, the same signal as the server's `Datacell.sources`.
178
+ - **`grounding`**: where each extracted string sits in the document text, plus the most specific annotations containing it.
179
+
180
+ The manifest records the source and selection, model settings, document
181
+ count, each column's file name and status counts, and skipped columns. The
182
+ runner creates it before writing rows and sets `finished_at` when the run
183
+ finishes. `--resume` validates the source, fieldset definition, corpus,
184
+ extract, and resolved document set, then keeps settled rows and reruns the
185
+ rest. Start in a fresh directory if earlier output lacks a run identity.
186
+
187
+ The `skipped_columns` list covers manual-entry metadata columns, columns
188
+ with a custom server-side `task_name`, and columns with neither `query` nor
189
+ `match_text`.
190
+
191
+ ## GraphQL contract
192
+
193
+ The GraphQL adapter implements `oc_extract.sources.DocumentSource` using
194
+ these reads.
195
+
196
+ | Method | OpenContracts GraphQL field used |
197
+ |---|---|
198
+ | `get_fieldset` | `fieldset(id) { fullColumnList }` |
199
+ | `get_extract` | `extract(id) { fieldset corpus fullDocumentList }` |
200
+ | `list_documents` | `corpus(id) { documents }` (paginated) / `document(id)` (alias-batched) |
201
+ | `get_document_text` | `document { txtExtractFile }` (resolved at document load; storage requests use a separate client) |
202
+ | `get_annotations` | `document { allAnnotations(corpusId:) { … parent { id } annotationLabel { … } } }` |
203
+ | `semantic_search` *(optional)* | `semanticSearch(documentId:, corpusId:)` |
204
+
205
+ Custom `DocumentSource` adapters can feed the same runner. They implement
206
+ `checkpoint_identity()` to support resume.
207
+
208
+ ## Python API
209
+
210
+ ```python
211
+ from oc_extract import DocumentSelection, EngineConfig, OpenContractsGraphQLSource, run_extraction
212
+
213
+ async with OpenContractsGraphQLSource("https://contracts.example.com", token=token) as source:
214
+ result = await run_extraction(
215
+ source,
216
+ fieldset_id="12",
217
+ selection=DocumentSelection(corpus_id="4"),
218
+ output_dir="out",
219
+ config=EngineConfig(model="anthropic:claude-sonnet-5-5"),
220
+ )
221
+ result.files # [Path("out/effective-date.jsonl"), ...]
222
+ ```
223
+
224
+ `extract_column(DocumentContext, Column, ...)` runs a single cell when you
225
+ need finer control.
226
+
227
+ ## Agent tools
228
+
229
+ | Tool | Purpose |
230
+ |---|---|
231
+ | `similarity_search` | Server-side vector search (when the source supports it) |
232
+ | `search_annotations` | IDF-weighted keyword search; filter by structural / label |
233
+ | `get_document_outline` | Section tree of structural annotations |
234
+ | `get_annotation` | One annotation with its ancestors and children |
235
+ | `get_subtree_text` | A section's full text from its heading |
236
+ | `list_annotation_labels` | Labels present, with counts |
237
+ | `load_document_text` | Raw text slices |
238
+
239
+ ## Development
240
+
241
+ ```bash
242
+ pip install -e ".[test]"
243
+ python -m pytest
244
+ ```
245
+
246
+ The tests make no network or LLM calls:
247
+
248
+ - the GraphQL client runs against a fake OpenContracts server using the
249
+ checked-in [SDL fixture](tests/fixtures/opencontracts.graphql);
250
+ - the agent runs on pydantic-ai's `FunctionModel` / `TestModel`.
251
+
252
+ Set `OC_GRAPHQL_SCHEMA` to the path of an OpenContracts checkout's
253
+ `config/graphql/schema.graphql` to run the same tests against its full
254
+ GraphQL contract.
255
+
256
+ ## Publishing
257
+
258
+ PyPI Trusted Publishing uses project `tabula-razer`, GitHub owner
259
+ `Open-Source-Legal`, repository `tabula-razer`, workflow `publish.yml`,
260
+ and environment `pypi`.
261
+
262
+ Publish a GitHub release tagged with the package version prefixed by `v`,
263
+ such as `v0.1.0b1`. The workflow runs CI on that commit, builds and checks
264
+ the wheel and source distribution, then uploads them to PyPI using OIDC.
265
+ Run the workflow manually to build and validate the GitHub Actions artifact.
@@ -0,0 +1,228 @@
1
+ # Tabula Razer
2
+
3
+ OpenContracts' structured data extraction pipeline as a standalone Python
4
+ package. Choose a fieldset (a group of extraction columns) and a set of
5
+ documents. The CLI reads from an OpenContracts-compatible GraphQL server or an
6
+ offline JSON bundle and writes one JSONL file per runnable column.
7
+
8
+ ```
9
+ out/
10
+ ├── effective-date.jsonl ← column "Effective Date"
11
+ ├── governing-law.jsonl ← column "Governing Law"
12
+ ├── parties.jsonl ← column "Parties"
13
+ └── manifest.json ← run scope, model, file names, and counts
14
+ ```
15
+
16
+ ## Architecture
17
+
18
+ 1. **Source.** A `DocumentSource` resolves the fieldset and document
19
+ selection. The GraphQL and bundle adapters expose the same interface.
20
+ 2. **Runner and index.** The asyncio runner limits concurrency, loads each
21
+ document's text and annotations once, and shares its in-memory
22
+ `DocumentIndex` across the selected columns. Parent IDs form the section
23
+ hierarchy. The index supports keyword search and section traversal, with
24
+ optional semantic search delegated to the source.
25
+ 3. **Extraction engine.** A pydantic-ai agent extracts one field from one
26
+ document at a time. It builds a prompt from the column's query, examples,
27
+ and fenced constraints. Short documents with full text can be included in
28
+ the prompt. The engine validates the typed result and grounds extracted
29
+ strings in the document text when possible.
30
+ 4. **Writer.** The CLI streams results to local JSONL files and records run
31
+ state in the manifest.
32
+
33
+ The OpenContracts server's `doc_extract_query_task` imports the package's
34
+ shared prompt assembly, output parsing, diagnostics, and text alignment.
35
+ The server runs its own ORM-backed extraction and persists `Datacell` records.
36
+ See the [OpenContracts integration](https://github.com/Open-Source-Legal/OpenContracts/pull/2607).
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install "tabula-razer[openai] @ git+https://github.com/Open-Source-Legal/tabula-razer.git"
42
+ # From a clone of this repository:
43
+ pip install -e ".[all,test]"
44
+ ```
45
+
46
+ Python 3.10+, Linux / macOS / Windows. Provider keys come from the usual
47
+ environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, ...).
48
+
49
+ ## Upstream requirements
50
+
51
+ For a live run, supply an OpenContracts server base URL or its GraphQL
52
+ endpoint with `--api-url`. The server must expose the
53
+ [GraphQL reads below](#graphql-contract) and have a fieldset and processed
54
+ documents available to the caller. A corpus run requires read access to both
55
+ the corpus and the documents. Use a bearer JWT or an API key
56
+ (`--auth-scheme KEY`) for authenticated access.
57
+
58
+ The CLI reads plain text from the media URLs returned by the server, so the
59
+ machine running it needs network access to the API and the media host.
60
+ Annotations supply section structure and retrieval. Server-side semantic
61
+ search is optional. If the source lacks a plain-text extract, the engine uses
62
+ reconstructed annotation excerpts. An explicit null based on excerpts is
63
+ recorded as `insufficient_document_text` because absence is unverified.
64
+
65
+ Bundle mode replaces the API with a local JSON export containing fieldsets,
66
+ documents, text or text-file references, and annotations. Live and bundle
67
+ runs both use the configured model provider for inference. Use
68
+ `--model test` to exercise the pipeline with a local test model.
69
+
70
+ ## Command line
71
+
72
+ ```bash
73
+ export OC_API_TOKEN=... # a JWT or an API key (--auth-scheme KEY)
74
+
75
+ # every document in a corpus
76
+ tabula-razer run --api-url https://contracts.example.com \
77
+ --fieldset 12 --corpus 4 --output-dir out/ --model openai:gpt-4o-mini
78
+
79
+ # specific documents (add --corpus to include that corpus's non-structural annotations)
80
+ tabula-razer run --api-url ... --fieldset 12 --document 101 --document 102 --output-dir out/
81
+
82
+ # the documents of an existing server extract (its fieldset is used unless --fieldset is given)
83
+ tabula-razer run --api-url ... --extract 31 --output-dir out/
84
+
85
+ # see what a fieldset will do before spending tokens
86
+ tabula-razer fieldset --api-url ... --fieldset 12
87
+ ```
88
+
89
+ `run` prints the JSONL paths (one per extracted column) to stdout. Progress
90
+ and a summary go to stderr. IDs can be Relay global IDs or numeric primary
91
+ keys.
92
+
93
+ | Flag | Default | Meaning |
94
+ |---|---|---|
95
+ | `--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. |
96
+ | `--concurrency` | 4 | Concurrent cells, and documents held in memory. |
97
+ | `--request-limit` | 20 | Model requests allowed per cell. |
98
+ | `--full-text-char-limit` | 24000 | Documents this short are inlined into the prompt. |
99
+ | `--no-semantic-search` | off | Drop the server-side `semanticSearch` tool; keyword search over annotations is always available. |
100
+ | `--no-grounding` | off | Skip locating extracted strings in the text. |
101
+ | `--include-llm-log` | off | Store each cell's full message history. |
102
+ | `--resume` | off | Keep `completed` / `not_found` lines in `--output-dir` and run the rest. |
103
+ | `--strict` | off | Exit 3 if any cell failed. |
104
+
105
+ From the repository root, run the bundled example with the local test model.
106
+
107
+ ```bash
108
+ tabula-razer run --bundle tests/fixtures/nda_bundle.json \
109
+ --fieldset fs-nda --corpus corpus-ndas --output-dir out/ --model test
110
+ ```
111
+
112
+ ## Outputs
113
+
114
+ Each runnable column gets a `<column>.jsonl` file with one
115
+ `ExtractionRecord` per resolved document. A row includes document and column
116
+ IDs, the typed value or failure details, source annotation IDs, grounding
117
+ spans, model usage, and timestamps. The file is flushed as each cell finishes,
118
+ so row order follows completion order.
119
+
120
+ ```json
121
+ {"schema_version": 1, "fieldset_id": "RmllbGRzZXRUeXBlOjEy", "column_id": "...",
122
+ "column_name": "Governing Law", "document_id": "...", "document_title": "Mutual NDA",
123
+ "status": "completed", "data": "the State of Delaware", "output_type": "str",
124
+ "extract_is_list": false,
125
+ "sources": ["QW5ub3RhdGlvblR5cGU6OTE="],
126
+ "grounding": [{"query_text": "the State of Delaware", "matched_text": "the State of Delaware",
127
+ "char_start": 1840, "char_end": 1861, "match_type": "exact", "match_quality": 1.0,
128
+ "annotation_ids": ["QW5ub3RhdGlvblR5cGU6OTE="]}],
129
+ "failure_mode": null, "error": null, "model": "openai:gpt-4o-mini",
130
+ "usage": {"requests": 3, "input_tokens": 5120, "output_tokens": 64},
131
+ "started_at": "...", "completed_at": "..."}
132
+ ```
133
+
134
+ - **`status`**: one of
135
+ - `completed`: a value was extracted;
136
+ - `not_found`: the agent explicitly committed to "not in this document" (`failure_mode: agent_committed_none`);
137
+ - `failed`: no answer. `failure_mode` says why:
138
+ - from the server's vocabulary: `usage_limit_exceeded`, `tool_loop_no_output`, `no_final_response`;
139
+ - added by this package: `invalid_output`, `invalid_column`, `document_load_failed`, `insufficient_document_text`, `exception`.
140
+ - **`sources`**: annotation IDs the agent's tools surfaced while answering. These are the citations, the same signal as the server's `Datacell.sources`.
141
+ - **`grounding`**: where each extracted string sits in the document text, plus the most specific annotations containing it.
142
+
143
+ The manifest records the source and selection, model settings, document
144
+ count, each column's file name and status counts, and skipped columns. The
145
+ runner creates it before writing rows and sets `finished_at` when the run
146
+ finishes. `--resume` validates the source, fieldset definition, corpus,
147
+ extract, and resolved document set, then keeps settled rows and reruns the
148
+ rest. Start in a fresh directory if earlier output lacks a run identity.
149
+
150
+ The `skipped_columns` list covers manual-entry metadata columns, columns
151
+ with a custom server-side `task_name`, and columns with neither `query` nor
152
+ `match_text`.
153
+
154
+ ## GraphQL contract
155
+
156
+ The GraphQL adapter implements `oc_extract.sources.DocumentSource` using
157
+ these reads.
158
+
159
+ | Method | OpenContracts GraphQL field used |
160
+ |---|---|
161
+ | `get_fieldset` | `fieldset(id) { fullColumnList }` |
162
+ | `get_extract` | `extract(id) { fieldset corpus fullDocumentList }` |
163
+ | `list_documents` | `corpus(id) { documents }` (paginated) / `document(id)` (alias-batched) |
164
+ | `get_document_text` | `document { txtExtractFile }` (resolved at document load; storage requests use a separate client) |
165
+ | `get_annotations` | `document { allAnnotations(corpusId:) { … parent { id } annotationLabel { … } } }` |
166
+ | `semantic_search` *(optional)* | `semanticSearch(documentId:, corpusId:)` |
167
+
168
+ Custom `DocumentSource` adapters can feed the same runner. They implement
169
+ `checkpoint_identity()` to support resume.
170
+
171
+ ## Python API
172
+
173
+ ```python
174
+ from oc_extract import DocumentSelection, EngineConfig, OpenContractsGraphQLSource, run_extraction
175
+
176
+ async with OpenContractsGraphQLSource("https://contracts.example.com", token=token) as source:
177
+ result = await run_extraction(
178
+ source,
179
+ fieldset_id="12",
180
+ selection=DocumentSelection(corpus_id="4"),
181
+ output_dir="out",
182
+ config=EngineConfig(model="anthropic:claude-sonnet-5-5"),
183
+ )
184
+ result.files # [Path("out/effective-date.jsonl"), ...]
185
+ ```
186
+
187
+ `extract_column(DocumentContext, Column, ...)` runs a single cell when you
188
+ need finer control.
189
+
190
+ ## Agent tools
191
+
192
+ | Tool | Purpose |
193
+ |---|---|
194
+ | `similarity_search` | Server-side vector search (when the source supports it) |
195
+ | `search_annotations` | IDF-weighted keyword search; filter by structural / label |
196
+ | `get_document_outline` | Section tree of structural annotations |
197
+ | `get_annotation` | One annotation with its ancestors and children |
198
+ | `get_subtree_text` | A section's full text from its heading |
199
+ | `list_annotation_labels` | Labels present, with counts |
200
+ | `load_document_text` | Raw text slices |
201
+
202
+ ## Development
203
+
204
+ ```bash
205
+ pip install -e ".[test]"
206
+ python -m pytest
207
+ ```
208
+
209
+ The tests make no network or LLM calls:
210
+
211
+ - the GraphQL client runs against a fake OpenContracts server using the
212
+ checked-in [SDL fixture](tests/fixtures/opencontracts.graphql);
213
+ - the agent runs on pydantic-ai's `FunctionModel` / `TestModel`.
214
+
215
+ Set `OC_GRAPHQL_SCHEMA` to the path of an OpenContracts checkout's
216
+ `config/graphql/schema.graphql` to run the same tests against its full
217
+ GraphQL contract.
218
+
219
+ ## Publishing
220
+
221
+ PyPI Trusted Publishing uses project `tabula-razer`, GitHub owner
222
+ `Open-Source-Legal`, repository `tabula-razer`, workflow `publish.yml`,
223
+ and environment `pypi`.
224
+
225
+ Publish a GitHub release tagged with the package version prefixed by `v`,
226
+ such as `v0.1.0b1`. The workflow runs CI on that commit, builds and checks
227
+ the wheel and source distribution, then uploads them to PyPI using OIDC.
228
+ Run the workflow manually to build and validate the GitHub Actions artifact.