Metadata-Version: 2.5
Name: tabula-razer
Version: 0.1.0b3
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
Requires-Dist: regex>=2024.4.16
Requires-Dist: typing-extensions>=4.6
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: hypothesis>=6.100; extra == 'test'
Requires-Dist: plasmapdf<0.2,>=0.1.3; extra == 'test'
Requires-Dist: pydantic-ai-slim[anthropic]<2,>=1.107.10; extra == 'test'
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
Requires-Dist: pytest-cov>=5; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Requires-Dist: types-regex; 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, an
OpenContracts corpus export, 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, corpus export and bundle adapters expose the same
   interface.
2. **Runner and index.** The asyncio runner limits concurrency, loads each
   document's text, annotations, relationships and (for PDFs) PAWLS token
   layer once, and shares its in-memory `DocumentIndex` across the selected
   columns. Parent IDs, or parent → child relationships where those are
   absent, form the section hierarchy. The index supports keyword search,
   section traversal and following relationships, with optional semantic
   search delegated to the source. See
   [Native OpenContracts layers](#native-opencontracts-layers) and
   [Relationships](#relationships).
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. Before it commits, the agent resolves the defined terms and
   cross-references the answer depends on, and it returns the passages and
   the reasoning behind the value along with it. The engine validates the
   typed result, checks every quoted passage against the document, and
   grounds extracted strings in the document text when possible. See
   [Multi-hop extraction](#multi-hop-extraction).
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
engine, document index, models, prompt assembly, output parsing,
diagnostics, and grounding.
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. Besides pydantic and pydantic-ai the
package depends on [`regex`](https://pypi.org/project/regex/), whose match
timeout bounds the `search_text` tool.

Provider keys come from the usual environment variables (`OPENAI_API_KEY`,
`ANTHROPIC_API_KEY`, ...), and they must be exported into the environment
of the process: the package does not read a `.env` file. Either export the
key, or pass it for one command only:

```bash
export ANTHROPIC_API_KEY=...          # for the shell session

# or for a single command, from a .env file, without echoing it
ANTHROPIC_API_KEY="$(sed -n 's/^ANTHROPIC_API_KEY=//p' .env)" \
  tabula-razer run --bundle bundle.json --fieldset fs-1 --corpus c-1 \
  --output-dir out/ --model anthropic:claude-sonnet-5-5
```

## 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.

For PDFs the source also reads the PAWLS token layer (`pawlsParseFile`) and
each annotation's native `json` position, so annotations are placed by their
tokens and grounded values carry bounding boxes. Without them, annotations
are located by searching for their text.

Two offline sources replace the API:

- `--oc-export` reads an OpenContracts corpus export (V1, V2 or V3) as it
  is. Pass the export ZIP, its extracted directory, or its `data.json`.
  Exports carry no extraction columns, so `--fieldsets` supplies them, in
  the bundle's `fieldsets` shape.
- `--bundle` reads a local JSON file containing fieldsets, documents, text
  or text-file references, annotations and, optionally, relationships,
  document relationships and PAWLS layers. Unknown keys are rejected rather
  than ignored.

Every run uses 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

# an OpenContracts corpus export, no server; --corpus is the export's corpus.id
tabula-razer run --oc-export corpus_export.zip --fieldsets fieldsets.json \
  --fieldset fs-nda --corpus 7 --output-dir out/
```

`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. |
| `--reasoning-effort` | model default | `minimal`, `low`, `medium`, `high`, `xhigh` or `max`: how much reasoning/thinking to ask of the model. |
| `--legacy-protocol` | off | Run the 0.1.0b2 protocol: its prompts, tools and result schema, with no evidence or reasoning. See [Multi-hop extraction](#multi-hop-extraction). |
| `--require-evidence` | off | Fail a cell (`evidence_unverified`) whose answer has no evidence that can be found in the document. |
| `--evidence-retries` | 1 | Times the model is asked to correct a quote that cannot be found. |
| `--no-prompt-cache` | off | Do not mark the document as a prompt-cache breakpoint. |
| `--all-extracts` | off | Run every extract of a `--bundle`, each into its own directory under `--output-dir` (how a benchmark is run; see [Evaluation](#evaluation)). |
| `--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. |
| `--no-layout` | off | Ignore PDF token layers: locate annotations by text search and ground values without bounding boxes. |
| `--hierarchy-label` | `OC_PARENT_CHILD` | Relationship label read as parent → child edges where annotations have no `parent_id` (repeatable, added to the default). |
| `--oc-export` / `--fieldsets` | — | Read an OpenContracts corpus export natively, with fieldsets from a JSON file. |
| `--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`, and, only with `--require-evidence`, `evidence_unverified`.
- **`sources`**: annotation IDs the agent's tools surfaced while answering. These are the citations, the same signal as the server's `Datacell.sources`.
- **`evidence`**, **`reasoning`**, **`steps`**: the passages the agent quoted for the answer, each checked against the document; the ordered steps from those passages to the answer; and the answers to the column's declared hops. See [Multi-hop extraction](#multi-hop-extraction). All three are empty lists under `--legacy-protocol`.
- **`usage`**: requests and tokens for the cell. `input_tokens` counts every prompt token; `cache_read_tokens` and `cache_write_tokens` say how many of them the provider read from, or wrote to, its prompt cache.
- **`grounding`**: where each extracted string sits in the document text, plus the most specific annotations containing it. Each span also gives its OpenContracts-native location, ready to highlight or import as an annotation:
  - **`annotation_type`**: `TOKEN_LABEL` for a PDF whose PAWLS layer is in use, otherwise `SPAN_LABEL`;
  - **`page`**: for a token location, its first page;
  - **`annotation_json`**: for a token location, per page the `bounds`, `tokensJsons` and `rawText` PlasmaPDF would give the match, as the server does; for a span, `{start, end, text}`;
  - **`page_sizes`**: for a token location, each page's `{width, height}` in PDF points, to scale the bounds.

  These are `null` when the text was rebuilt from annotations.

From the test export (`tests/oc_export_fixture.py`), the match ends inside
the token `Delaware.`, and the location covers that whole token:

```json
"grounding": [{"query_text": "the State of Delaware", "matched_text": "the State of Delaware",
  "char_start": 236, "char_end": 257, "match_type": "exact", "match_quality": 1.0,
  "annotation_ids": ["102", "s-3-p"], "annotation_type": "TOKEN_LABEL", "page": 1,
  "annotation_json": {"1": {"bounds": {"top": 146.935, "bottom": 159.365, "left": 208.0, "right": 516.65},
    "tokensJsons": [{"pageIndex": 1, "tokenIndex": 20}, {"pageIndex": 1, "tokenIndex": 21},
                    {"pageIndex": 1, "tokenIndex": 22}, {"pageIndex": 1, "tokenIndex": 23}],
    "rawText": "the State of Delaware."}},
  "page_sizes": {"1": {"width": 612.0, "height": 792.0}}}]
```

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`.

## Multi-hop extraction

A contract's answer is often one or two hops from the passage that first
matches the question: the clause says "the Applicable Rate", the definition
of that term points at a pricing schedule, and the figure in the schedule
has to be combined with another. By default the agent follows those hops
before it commits, and the record keeps what it relied on.

**Protocol.** The system prompt has the agent find the passage, then check
what the passage depends on: look up each defined term the answer turns on
(`find_definition`), open each cross-reference (`resolve_reference`), read
schedules as tables (`read_table`), and run any arithmetic through
`calculate`. It stops when the answer no longer depends on something it has
not read.

**Evidence.** With the value, the agent returns the passages the answer
rests on, each a verbatim quote with a role. Every quote is located in the
document with the grounding aligner (exact, then whitespace- and
case-normalised, then fuzzy at a similarity of at least 0.9), first inside
the annotation the agent cited and then anywhere:

```json
"evidence": [
  {"id": "e1", "role": "definition", "annotation_id": "lease-015",
   "quote": "\"Base Rent\" means, for any Lease Year, the annual amount obtained by multiplying the Rentable Area of the Premises by the Annual Rate for that Lease Year.",
   "verified": true, "char_start": 1101, "char_end": 1255, "match_type": "exact", "match_quality": 1.0,
   "matched_text": "\"Base Rent\" means, ...", "annotation_ids": ["lease-015"],
   "annotation_type": "SPAN_LABEL", "page": null,
   "annotation_json": {"start": 1101, "end": 1255, "text": "\"Base Rent\" means, ..."}, "page_sizes": null},
  {"id": "e2", "role": "schedule", "annotation_id": "lease-060", "quote": "3 | $34.50", "verified": true, "...": "..."}
],
"reasoning": [
  {"index": 1, "kind": "definition", "statement": "Base Rent is the Rentable Area times the Annual Rate.",
   "evidence_ids": ["e1"], "computation": null},
  {"index": 2, "kind": "computation", "statement": "12,500 square feet at $34.50.", "evidence_ids": ["e2", "e3"],
   "computation": {"expression": "12500 * 34.5", "result": 431250.0, "verified": true}}
]
```

- A **verified** quote carries its character span and the same
  OpenContracts-native location a grounding span has (`TOKEN_LABEL` with
  page bounds for a PDF whose PAWLS layer is in use, otherwise `SPAN_LABEL`).
  An unverified quote keeps the agent's wording and has no location.
- `role` is one of `value`, `definition`, `reference`, `schedule`,
  `condition`, `other`.
- A quote that cannot be found is sent back to the model once
  (`--evidence-retries`) with the instruction to quote exactly. If it still
  cannot be found, the answer is recorded with that quote marked
  `"verified": false`.
- **Evidence never costs a cell its answer** unless you ask it to. A cell
  whose value has the right type completes whatever its evidence looks like:
  malformed evidence is dropped, the evidence retry never uses the last
  output retry, and if the run ends during a retry (request budget, output
  retries, a provider error) the value already committed is kept. `--require-evidence`
  changes that: a non-null answer with no evidence, or with an unverified
  quote, fails with `failure_mode: evidence_unverified`.
- A computation step is `verified` when its expression was run through the
  `calculate` tool, or when re-evaluating it gives the stated result. Every
  `calculate` call is recorded in `reasoning`, including ones the agent did
  not mention.

**Declared hops.** A column can spell the hops out. `steps` is an ordered
list of sub-questions with types (`str`, `int`, `float`, `bool` or a list
of one); the agent answers each on the way, and the record's `steps` holds
each value with the evidence that supports it. Bundles and `--fieldsets`
JSON accept it (`type` and `output_type` are the same key):

```json
{"id": "c1", "name": "Base Rent, year 3", "output_type": "float",
 "query": "What is the Base Rent, in dollars, for the third Lease Year?",
 "steps": [{"question": "What is the Annual Rate for the third Lease Year?", "type": "float"},
           {"question": "What is the Rentable Area of the Premises?", "type": "float"}]}
```

```json
"steps": [{"index": 1, "question": "What is the Annual Rate for the third Lease Year?",
           "output_type": "float", "value": 34.5, "evidence_ids": ["e2"]},
          {"index": 2, "question": "What is the Rentable Area of the Premises?",
           "output_type": "float", "value": 12500.0, "evidence_ids": ["e3"]}]
```

`steps` is not an OpenContracts column field, so columns read over GraphQL
have none. Like evidence, declared steps cannot cost a cell its answer: a
step that is missing, or whose value does not fit its type, is sent back to
the model once and is otherwise recorded with a null value.

**Constraints are enforced.** Under this protocol a column's
`limit_to_label` and `must_contain_text` narrow what the search tools
return, instead of only being stated in the prompt. `limit_to_label` keeps
`search_annotations`, `similarity_search` and `search_text` to annotations
with that label, what is nested in them, and the sections that contain
them; a document in which no annotation carries the label is searched
whole. `must_contain_text` keeps them to sections that contain the text; if
nothing does, the tools say so and the agent answers null.

**Documents without annotations.** A document that has text but no
annotations gets paragraph annotations made from the text (headings are
recognised by their shape and parent what follows), so search, outline and
subtree reads work on it. Their ids start with `tr-chunk-`. They exist only
in the index, so they never appear in `sources`; evidence still reports the
character span.

**Prompt layout and caching.** When the document fits
`--full-text-char-limit`, it goes into the conversation ahead of the
question, in a message of its own that ends at a cache point. The system
prompt and the document message do not depend on the column, so for a
provider with prompt caching every request of a cell, and every other
column of the document with the same result type, reuses that prefix. (The
result tool's schema is part of the prefix, which is why the type matters.)
For a model on the Anthropic API the runner lets the first cell of each
result type finish before starting the others, so the document is written
to the cache once and read from it afterwards, and the conversation is
cached as it grows. `--no-prompt-cache` turns both off.

**Reasoning effort.** `--reasoning-effort` (`EngineConfig.reasoning_effort`)
asks the model for more or less reasoning. On the Anthropic API it is sent
as `output_config.effort`; other providers get pydantic-ai's unified
`thinking` setting.

**Claude 5 models.** The Claude 5 models on the Anthropic API reject a
forced tool choice and sampling settings. pydantic-ai 1.x predates them, so
this package gives `anthropic:claude-opus-5*`, `claude-sonnet-5*` and
`claude-haiku-5*` a request profile they accept (no forced tool choice, no
temperature unless you pass one). 0.1.0b2 could not reach these models:
every request failed with a 400.

**The legacy protocol.** `--legacy-protocol`
(`EngineConfig(protocol="legacy")`) restores 0.1.0b2 exactly: its system
and user prompts word for word, its nine tools, a result tool that takes
the bare value, no enforcement of column constraints, no paragraph
annotations and no cache points. `evidence`, `reasoning` and `steps` are
then empty.

## Evaluation

`tabula-razer eval` scores a run against a gold file:

```bash
tabula-razer run --bundle benchmarks/multihop/bundle.json --all-extracts \
  --output-dir out/multihop --model anthropic:claude-sonnet-5-5
tabula-razer eval --gold benchmarks/multihop/gold.json --run-dir out/multihop \
  --input-price 2 --output-price 10 --cache-read-price 0.10 --cache-write-price 2.50
```

It reports:

- **answer accuracy**, overall and per answer type (`number` within a
  relative tolerance, `bool`, `string` after normalisation or by alias,
  `list`, `span` for a quoted passage, `null` for "not in the document");
- **evidence character precision and recall**: of the characters a record
  points at, how many are gold evidence, and of the gold evidence, how much
  it points at. Both the mean over questions (the LegalBench-RAG
  convention) and the pooled totals are given. A record's evidence is its
  verified `evidence` spans; a record with none (0.1.0b2, or the legacy
  protocol) is scored on its `grounding` spans. `--evidence-source` forces
  one or the other;
- **abstention accuracy**: whether the run answered exactly the questions
  the document can answer;
- **declared-hop accuracy**, when the gold lists step answers;
- **requests and tokens**, with a cost estimate when prices are given.

A gold file lists one item per (document, column), with the answer, its
type, and evidence as character spans of the document text
([format](src/oc_extract/evals/gold.py)). `--run-dir` is searched
recursively, so the directory `--all-extracts` writes is scored as a whole.
`--report report.json` also writes the per-question results.

**Benchmark adapters.** `tabula-razer convert` turns a benchmark file that
is already on disk into a bundle plus gold (nothing is downloaded). Each
question becomes a column of a fieldset that belongs to its own document:

```bash
# LegalBench-RAG: a data directory with benchmarks/ and corpus/
tabula-razer convert --format legalbench-rag --input data/legalbenchrag \
  --benchmark cuad --sample 50 --seed 0 --max-document-chars 100000 \
  --bundle-out cuad50/bundle.json --gold-out cuad50/gold.json

# DocMath-Eval: complong_testmini.json or another split
tabula-razer convert --format docmath --input complong_testmini.json \
  --bundle-out docmath/bundle.json --gold-out docmath/gold.json
```

- [LegalBench-RAG](https://github.com/zeroentropy-ai/legalbenchrag): the
  gold snippets are the gold evidence, and their text is the gold answer,
  scored as a `span`. Documents come without annotations, so the
  paragraph fallback applies.
- [DocMath-Eval](https://github.com/yale-nlp/DocMath-Eval): each item is
  its own document, with one annotation per paragraph (`Table` for the
  markdown tables); the gold evidence is the listed evidence paragraphs.

**The multi-hop benchmark.** [`benchmarks/multihop`](benchmarks/multihop)
holds three hand-written contracts (a credit agreement, a services
agreement and an office lease) and 23 questions whose answers need a
definition, then a schedule or cross-referenced clause, then usually a
computation; three have no answer in the document. `bundle.json` and
`gold.json` are built from the documents and the question list by
`python benchmarks/multihop/build.py`; `bundle_steps.json` is the same
bundle with each question's hops declared. The credit agreement is longer
than the inline limit, so its questions are answered through the tools.

### Live results

Recorded on 2026-11-30 with `anthropic:claude-sonnet-5-5`, before and after
multi-hop extraction was added. Token counts are the records' own;
`input` counts every prompt token, cached or not. Costs are estimates at
list prices ($2 / $10 per million input / output tokens, $0.10 cache read,
$2.50 cache write). Every run, including the repeats mentioned below, is
summarised in
[`benchmarks/results/live-2026-11-30.json`](benchmarks/results/live-2026-11-30.json).

0.1.0b2 as released cannot reach this model: the API rejects its forced
tool choice, so every cell fails with `failure_mode: exception` and no
tokens are used. "Before" is therefore the 0.1.0b2 extraction code run
through the library with a model profile that neither forces a tool choice
nor sends a temperature, which is the only change it needs to run. Run the
same way under `--legacy-protocol`, this version gives the same picture as
"before" (23/23, no evidence, 44 requests, $0.56).

**Multi-hop benchmark** (23 questions; evidence scored on the 20 with gold
evidence):

| | Before (0.1.0b2) | After |
|---|---|---|
| Answer accuracy | 23/23 | 23/23 |
| Evidence precision / recall, per question | 0.0% / 0.0% | 82.5% / 82.9% |
| Evidence precision / recall, pooled characters | 0.0% / 0.0% | 82.4% / 81.1% |
| Abstention accuracy | 23/23 | 23/23 |
| Requests | 42 | 61 |
| Input tokens | 232,754 | 505,381 (380,826 read from cache, 124,387 written) |
| Output tokens | 5,728 | 20,151 |
| Estimated cost | $0.52 | $0.55 |

The model already answers every question correctly before. What changes
is that the answer can be checked: before, a record's only provenance is
grounding, which locates extracted strings and so has nothing for a
computed number; after, all 106 quoted passages were found, character for
character, in the documents. That costs half again as many requests (the
calculations, mostly) and more than three times the output tokens; prompt
caching keeps the bill level. With the hops declared (`bundle_steps.json`),
all 37 hop answers were right, for 61 requests and $0.74.

**Single-hop regression check** (50 CUAD questions from LegalBench-RAG:
`--sample 50 --seed 0 --max-document-chars 100000`, 48 contracts, none with
annotations):

| | Before (0.1.0b2) | After |
|---|---|---|
| Answer accuracy | 43/50 | 45/50 |
| Evidence precision / recall, per question | 48.4% / 69.0% | 72.8% / 73.0% |
| Evidence precision / recall, pooled characters | 44.2% / 45.6% | 74.4% / 57.8% |
| Answerable questions declined | 2 | 3 |
| Requests | 217 | 137 |
| Input tokens | 1,656,803 | 1,228,745 (697,259 read from cache, 531,112 written) |
| Output tokens | 38,522 | 37,721 |
| Estimated cost | $3.70 | $1.78 |

How to read this table:

- **Accuracy is level, not improved.** The "after" column is the third of
  three runs, made as the code changed: they scored 43, 44 and 45 of 50.
  A question or two either way is run-to-run variation at this sample
  size, so the fair summary is no regression in answers, with evidence
  that is more precise and about half the cost.
- **The agent declines slightly more often.** It answered null on 4, 3 and
  3 answerable questions in the three runs, against 2 before. The repeat
  offender asks whether there is a cap on liability, of a contract that
  excludes kinds of damages instead of capping an amount; it was declined
  in two of the three runs. After the first run the system prompt's
  negative case was reworded so that null means the document is silent
  rather than that it does not answer squarely. That wording was prompted
  by questions in this very sample, and it did not make the behaviour go
  away, so treat it as unresolved: if a missed clause costs you more than
  a loosely matching one, review `not_found` cells.
- **The saving comes from searching instead of paging.** Before, a
  contract longer than the inline limit and without annotations could only
  be read page by page, which is thorough and expensive. After, the agent
  searches the paragraph annotations made for it. Keyword search can miss
  a clause worded unlike the question: in one run the agent declined a
  non-disparagement question whose clause speaks of bringing trademarks
  "into disrepute". A source with semantic search does not depend on
  shared wording.

## Native OpenContracts layers

OpenContracts positions PDF annotations in token space: page → token
indices plus a bounding box, over the document's PAWLS layer. Its plain-text
layer is derived from the same tokens (PlasmaPDF joins every token's text, in
order, with one space), so a character offset and a token index are two views
of one layer. Nothing needs converting down. Tabula Razer keeps each
annotation's `annotation_json` as stored (v1 `tokensJsons`, compact v2 ranges,
or a `{start, end, text}` span), along with `link_url` and
`content_modalities`.

Per document, the index builds a compact `LayoutIndex` from the PAWLS layer,
holding each token's character range and box, and each page's size, in flat
arrays, and then drops the parsed pages. The index maps both ways:

- **Inbound.** An annotation's token references become its exact character
  segments. This places annotations a text search would put at the wrong
  occurrence of repeated boilerplate, and ones it cannot find at all: OCR'd
  `rawText`, or text holding the `´` / `⋅` the text layer normalises.
  Tokens join one segment only while nothing but image or empty tokens
  separate them, so an annotation over tokens that are not adjacent covers
  each run and never the text between. Containment, citations and grounding
  use the segments; `DocumentIndex.span()` gives the extent, for ordering.
- **Outbound.** A grounded character span becomes token `annotation_json`
  as PlasmaPDF's `convert_doc_span_to_opencontract_annotation_json`
  projects it: every text token the span touches plus image tokens inside
  it, `rawText` joined PlasmaPDF's way, and `bounds` widened by
  `0.1 × size / 2` per side, capped at 1pt vertically and 5pt horizontally,
  so every token box stays enclosed. PlasmaPDF pads pages before the last
  from a box that also counts the next page's first token; every page here
  gets its last-page rule instead.

The layer is used only when the text it derives matches the document's
text. Only differences that move no offset are allowed: the 1:1 look-alike
replacements PlasmaPDF versions disagree on (`‘ ’ ´` → `'`, `⋅` → `.`) and
trailing whitespace. Real server text layers differ in exactly those ways.
Any other mismatch (logged as a warning for PDFs), DOCX display PAWLS, or an
unreadable layer falls back to text search, with no annotation dropped. A
PDF with no plain-text extract takes the derived text, and so does a PDF in
a corpus export, as the server's importer does.

Property tests (`tests/test_layout.py`, `tests/test_index_layout.py`) check
over generated layers that no content is clipped or lost:
- every token's text appears in the derived text, whole and in order,
  identical to PlasmaPDF's;
- token references resolve to segments that hold every referenced token
  whole and no text of any token they do not reference;
- projections keep every token the span touches, with bounds that enclose
  each token box, and equal PlasmaPDF's tokens, `rawText` and bounds;
- compact and verbose encodings carry the same tokens;
- annotations larger than the server's 50,000-token decode limit are not
  truncated;
- the alignment check accepts look-alike folds and trailing whitespace, and
  rejects any other character change, insertion or deletion.

Text and projection parity are checked against PlasmaPDF (a test
dependency), the library the server builds its PDF text layer and grounding
boxes with. Bounds are compared on single-page spans and last pages, and
spans ending at offset 1 or earlier are skipped, where PlasmaPDF records the
first token one character late. Two deliberate differences from the
server's own decoders:
- a malformed compact page or token keeps its position as an empty
  placeholder rather than being dropped, so later references still resolve;
- spans are computed from range ends, so the decode limit never applies.

Set `OC_EXPORT_FIXTURE` to a real corpus export to check that every token
annotation in it places on its own `rawText` and maps back to exactly its
own tokens. For example, the OpenContracts repository's
`opencontractserver/tests/fixtures/Test_Corpus_EXPORT.zip` passes.

## 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_pawls_pages` *(PDFs)* | `document { pawlsParseFile }` (fetched like the text) |
| `get_annotations` | `document { allAnnotations(corpusId:) { … json linkUrl contentModalities parent { id } annotationLabel { … } } }` |
| `get_relationships` | `document { allRelationships(corpusId:) { id structural relationshipLabel sourceAnnotations targetAnnotations } }`, endpoints past 100 paged through `relationship(id:)` |
| `get_document_relationships` | `document { allDocRelationships(corpusId:) { id relationshipType data annotationLabel sourceDocument targetDocument } }` |
| `semantic_search` *(optional)* | `semanticSearch(documentId:, corpusId:)` |

Custom `DocumentSource` adapters can feed the same runner. They implement
`checkpoint_identity()` to support resume, and may implement
`get_pawls_pages()` to return a PAWLS layer (v1 or compact),
`get_relationships()` and `get_document_relationships()`.

## Corpus exports

`OpenContractsExportSource` (`--oc-export`) reads an export's `data.json` as
the server writes it:

- **Documents** are `annotated_docs`, keyed by file name, which becomes the
  document ID. Each document's `content` and `pawls_file_content` are its
  layers, falling back to its structural set for either.
- **Annotations** are `labelled_text` plus the parser's
  `structural_annotations` from `structural_annotation_sets`, matched by the
  document's `structural_set_hash`. `parent_id` links may cross between the
  two groups.
- **Labels.** `annotationLabel` resolves through `text_labels`, by label key
  for labelled annotations and by name for structural ones, as the server
  writes them.
- **Relationships** are the document's `relationships`, its structural set's
  `structural_relationships` and the corpus-level `relationships` that touch
  its annotations, labelled by name.

The export's `corpus.id` selects every document except the V3 `Readme.CAML`
article. The PDFs in the ZIP are not read. `from_paths` parses `data.json`
one document at a time and keeps each token layer as minified JSON text,
about a tenth of its parsed size, until its document loads, so the whole
export is never held parsed at once.

A bundle can carry the same layers: `pawls_file_content` (or `pawls_path`)
and `relationships` on a document, and `annotation_json` on an annotation.

## Relationships

Relationships link source annotations to target annotations under a label
(`Relationship`: `id`, `label`, `source_annotation_ids`,
`target_annotation_ids`, `structural`). They come from every source: a
bundle document's `relationships`, the three places an export keeps them,
or GraphQL `allRelationships`.

- **Structure.** Where annotations have no `parent_id`, relationships with a
  hierarchy label make the tree: `OC_PARENT_CHILD`, plus any
  `--hierarchy-label` (source parent → target children; the first listed
  wins if several name a parent). If neither gives any hierarchy, the
  server's `OC_SUBTREE_GROUP` rows do: each annotation's parent is the
  smallest group holding it. Groups are capped at 500 descendants, so this
  can skip a level but never names a non-ancestor. GraphQL skips those rows,
  which the server derives from the parent links and `OC_PARENT_CHILD` rows
  it already reads.
- **Links.** Every other relationship is something the agent can follow.
  Annotations carry a `relationship_count`, and `get_related_annotations`
  lists each relationship's label, this annotation's role (source or
  target) and the annotations on the other side. Ones in other documents
  are given by ID. What it surfaces is cited in `sources`. The tool and its
  prompt line appear only for documents that have relationships.

Document relationships link whole documents (`DocumentRelationship`:
`relationship_type` RELATIONSHIP or NOTES, `label`, the two document IDs and
titles, and `data`, the relationship's JSON payload, kept verbatim). They
come from GraphQL `allDocRelationships` or a bundle's top-level
`document_relationships`; corpus exports carry none.
`get_document_relationships` gives the agent each link's direction, the
other document and its data (cut short past 4,000 characters for the
prompt, never in the model). The tool and its prompt line appear only for
documents that have such links.

## 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.

`EngineConfig` options added for multi-hop extraction, all optional:

| Option | Default | Meaning |
|---|---|---|
| `protocol` | `"multi_hop"` | `"legacy"` runs the 0.1.0b2 protocol. |
| `require_evidence` | `False` | Fail a cell whose answer lacks verified evidence. |
| `evidence_retries` | `1` | Times the model is asked to correct an unverifiable quote. |
| `reasoning_effort` | `None` | `"minimal"` to `"max"`; `None` leaves the model's default. |
| `prompt_cache` | `True` | Cache point after the document; conversation caching on the Anthropic API. |

Scoring is available as a library too:

```python
from oc_extract.evals import GoldFile, load_records, score_run

report = score_run(GoldFile.from_path("gold.json"), load_records("out"))
report.answer_accuracy.accuracy, report.evidence.precision_macro, report.usage.requests
```

## 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. A passage that defines a term named in the query ranks ahead of passages that only use it |
| `find_definition` | Where a term is defined (`"Term" means ...` or `(the "Term")`), with the full defining text |
| `resolve_reference` | The provision a cross-reference points at (`Section 2.05(b)`, `Schedule 1`, `Article VII`), with offsets |
| `search_text` | Regular-expression (or literal) search over the raw text, with character offsets and context. Matching is cut off after 2 seconds, since the model writes the pattern |
| `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; a truncated read gives `next_offset` to continue from |
| `read_table` | A table as rows of cells. For a PDF whose PAWLS layer is in use the rows are rebuilt from the token boxes; otherwise the text is parsed (`\|`, tab or wide-space separated) |
| `get_related_annotations` | Annotations linked by labelled relationships (only when the document has any) |
| `get_document_relationships` | Links to other documents, with their data (only when the document has any) |
| `list_annotation_labels` | Labels present, with counts |
| `load_document_text` | Raw text slices |
| `calculate` | Exact arithmetic (`+ - * / // **`, `round`, `min`, `max`, `sum`, ...); every call is recorded in the record's `reasoning`. `%` is refused rather than read as modulo: 5% is written `0.05` |

`find_definition`, `resolve_reference`, `search_text`, `read_table` and
`calculate` belong to the multi-hop protocol. With `--legacy-protocol` the
toolset is the other nine, as in 0.1.0b2 (`get_subtree_text` without
continuation, `search_annotations` without the definition ranking).

## 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`;
- the benchmark adapters run on small fixtures in each dataset's own format
  (`tests/fixtures/legalbench_rag`, `tests/fixtures/docmath`).

`tests/test_compat.py` pins the 0.1.0b2 surface (exports, CLI flags, record
fields, failure modes, defaults) and loads records and a bundle that
release wrote. After editing a benchmark contract or question, rebuild the
checked-in files with `python benchmarks/multihop/build.py`; a test fails
if they are stale.

Live runs cost money and are not part of the test suite.
`benchmarks/run_live.py` runs every extract of a bundle against a real
model with a spend cap (`--max-cost`), and resumes where it stopped.

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. Set `OC_EXPORT_FIXTURE` to a corpus export to check
native placement on real data (see
[Native OpenContracts layers](#native-opencontracts-layers)).

## 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.
