tabula-razer 0.1.0b1__py3-none-any.whl

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.
oc_extract/__init__.py ADDED
@@ -0,0 +1,78 @@
1
+ """Tabula Razer, the standalone OpenContracts structured extraction CLI and library.
2
+
3
+ Run a fieldset's columns over documents served by any OpenContracts-
4
+ compatible API and get one JSONL file per column::
5
+
6
+ import asyncio
7
+ from oc_extract import (
8
+ DocumentSelection, EngineConfig, OpenContractsGraphQLSource, run_extraction,
9
+ )
10
+
11
+ async def main():
12
+ async with OpenContractsGraphQLSource(
13
+ "https://contracts.example.com", token="..."
14
+ ) as source:
15
+ result = await run_extraction(
16
+ source,
17
+ fieldset_id="12",
18
+ selection=DocumentSelection(corpus_id="4"),
19
+ output_dir="out",
20
+ config=EngineConfig(model="anthropic:claude-sonnet-5-5"),
21
+ )
22
+ print(result.files)
23
+
24
+ asyncio.run(main())
25
+ """
26
+
27
+ __version__ = "0.1.0b1"
28
+
29
+ from oc_extract.engine import ( # noqa: E402
30
+ DocumentContext,
31
+ EngineConfig,
32
+ extract_column,
33
+ )
34
+ from oc_extract.index import DocumentIndex # noqa: E402
35
+ from oc_extract.models import ( # noqa: E402
36
+ Annotation,
37
+ Column,
38
+ Document,
39
+ ExtractionRecord,
40
+ ExtractionStatus,
41
+ Fieldset,
42
+ )
43
+ from oc_extract.runner import ( # noqa: E402
44
+ ConfigurationError,
45
+ RunResult,
46
+ run_extraction,
47
+ )
48
+ from oc_extract.sources import ( # noqa: E402
49
+ BundleSource,
50
+ DocumentSelection,
51
+ DocumentSource,
52
+ NotFoundError,
53
+ OpenContractsGraphQLSource,
54
+ SourceError,
55
+ )
56
+
57
+ __all__ = [
58
+ "Annotation",
59
+ "BundleSource",
60
+ "Column",
61
+ "ConfigurationError",
62
+ "Document",
63
+ "DocumentContext",
64
+ "DocumentIndex",
65
+ "DocumentSelection",
66
+ "DocumentSource",
67
+ "EngineConfig",
68
+ "ExtractionRecord",
69
+ "ExtractionStatus",
70
+ "Fieldset",
71
+ "NotFoundError",
72
+ "OpenContractsGraphQLSource",
73
+ "RunResult",
74
+ "SourceError",
75
+ "__version__",
76
+ "extract_column",
77
+ "run_extraction",
78
+ ]
oc_extract/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """``python -m oc_extract`` — same as the ``tabula-razer`` script."""
2
+
3
+ import sys
4
+
5
+ from oc_extract.cli import main
6
+
7
+ sys.exit(main())
oc_extract/cli.py ADDED
@@ -0,0 +1,259 @@
1
+ """``tabula-razer`` command line.
2
+
3
+ Examples::
4
+
5
+ # every document of a corpus, against a live OpenContracts server
6
+ export OC_API_TOKEN=... # JWT or API key
7
+ tabula-razer run --api-url https://contracts.example.com \\
8
+ --fieldset 12 --corpus 4 --output-dir out/
9
+
10
+ # the documents of an existing server extract (fieldset comes with it)
11
+ tabula-razer run --api-url ... --extract 31 --output-dir out/
12
+
13
+ # offline, from a JSON bundle, with no LLM calls (plumbing smoke test)
14
+ tabula-razer run --bundle bundle.json --fieldset fs-1 --corpus c-1 \\
15
+ --output-dir out/ --model test
16
+
17
+ ``run`` prints the JSONL paths (one per extracted column) on stdout;
18
+ progress and the summary go to stderr.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import asyncio
25
+ import logging
26
+ import os
27
+ import sys
28
+ from collections.abc import Sequence
29
+ from pathlib import Path
30
+
31
+ from oc_extract import __version__
32
+ from oc_extract.constants import (
33
+ AUTH_SCHEMES,
34
+ DEFAULT_AUTH_SCHEME,
35
+ DEFAULT_CONCURRENCY,
36
+ DEFAULT_EXTRACT_MODEL,
37
+ DEFAULT_SIMILARITY_TOP_K,
38
+ EXTRACT_AGENT_REQUEST_LIMIT,
39
+ EXTRACT_FULL_TEXT_CHAR_LIMIT,
40
+ TOOL_NAME,
41
+ )
42
+ from oc_extract.engine import EngineConfig
43
+ from oc_extract.models import ExtractionRecord
44
+ from oc_extract.output_types import describe_output_type
45
+ from oc_extract.runner import ConfigurationError, plan_columns, run_extraction
46
+ from oc_extract.sources import (
47
+ BundleSource,
48
+ DocumentSelection,
49
+ DocumentSource,
50
+ OpenContractsGraphQLSource,
51
+ SourceError,
52
+ )
53
+
54
+ EXIT_OK = 0
55
+ EXIT_ERROR = 1
56
+ EXIT_FAILED_CELLS = 3
57
+
58
+ ENV_API_URL = "OC_API_URL"
59
+ ENV_API_TOKEN = "OC_API_TOKEN"
60
+ ENV_AUTH_SCHEME = "OC_AUTH_SCHEME"
61
+ ENV_MODEL = "OC_EXTRACT_MODEL"
62
+
63
+
64
+ def _add_source_arguments(parser: argparse.ArgumentParser) -> None:
65
+ group = parser.add_argument_group("source (one of)")
66
+ group.add_argument(
67
+ "--api-url",
68
+ default=os.environ.get(ENV_API_URL),
69
+ help=f"OpenContracts base URL or GraphQL endpoint [${ENV_API_URL}]",
70
+ )
71
+ group.add_argument("--bundle", type=Path, help="Offline JSON bundle instead")
72
+ auth = parser.add_argument_group("authentication")
73
+ auth.add_argument(
74
+ "--token",
75
+ default=os.environ.get(ENV_API_TOKEN),
76
+ help=f"API credential; prefer ${ENV_API_TOKEN} over the flag",
77
+ )
78
+ auth.add_argument(
79
+ "--auth-scheme",
80
+ choices=AUTH_SCHEMES,
81
+ default=os.environ.get(ENV_AUTH_SCHEME, DEFAULT_AUTH_SCHEME),
82
+ help="Bearer (JWT) or KEY (API key) [%(default)s]",
83
+ )
84
+
85
+
86
+ def _build_parser() -> argparse.ArgumentParser:
87
+ parser = argparse.ArgumentParser(
88
+ prog=TOOL_NAME,
89
+ description="Run an OpenContracts fieldset against an OpenContracts-"
90
+ "compatible API and write one JSONL file per field.",
91
+ )
92
+ parser.add_argument("--version", action="version", version=__version__)
93
+ parser.add_argument("-v", "--verbose", action="count", default=0)
94
+ commands = parser.add_subparsers(dest="command", required=True)
95
+
96
+ run = commands.add_parser("run", help="Extract a fieldset to JSONL files")
97
+ _add_source_arguments(run)
98
+ target = run.add_argument_group("what to extract")
99
+ target.add_argument("--fieldset", help="Fieldset id (optional with --extract)")
100
+ target.add_argument("--corpus", help="Corpus id: all its documents")
101
+ target.add_argument(
102
+ "--document",
103
+ action="append",
104
+ default=[],
105
+ help="Document id (repeatable); combine with --corpus to scope annotations",
106
+ )
107
+ target.add_argument("--extract", help="Existing extract id: its documents")
108
+ run.add_argument("--output-dir", type=Path, required=True)
109
+ model = run.add_argument_group("model")
110
+ model.add_argument(
111
+ "--model",
112
+ default=os.environ.get(ENV_MODEL, DEFAULT_EXTRACT_MODEL),
113
+ help="pydantic-ai model spec, or 'test' for no LLM calls [%(default)s]",
114
+ )
115
+ model.add_argument("--temperature", type=float)
116
+ model.add_argument("--max-tokens", type=int)
117
+ model.add_argument("--request-limit", type=int, default=EXTRACT_AGENT_REQUEST_LIMIT)
118
+ model.add_argument("--similarity-top-k", type=int, default=DEFAULT_SIMILARITY_TOP_K)
119
+ model.add_argument(
120
+ "--full-text-char-limit",
121
+ type=int,
122
+ default=EXTRACT_FULL_TEXT_CHAR_LIMIT,
123
+ help="Inject the whole text into prompts at or below this size",
124
+ )
125
+ run.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY)
126
+ run.add_argument("--no-semantic-search", action="store_true")
127
+ run.add_argument("--no-grounding", action="store_true")
128
+ run.add_argument(
129
+ "--include-llm-log",
130
+ action="store_true",
131
+ help="Store each cell's full LLM message history in its record",
132
+ )
133
+ run.add_argument(
134
+ "--resume",
135
+ action="store_true",
136
+ help="Keep settled results in --output-dir and run only the rest",
137
+ )
138
+ run.add_argument(
139
+ "--strict",
140
+ action="store_true",
141
+ help=f"Exit {EXIT_FAILED_CELLS} if any cell failed",
142
+ )
143
+
144
+ describe = commands.add_parser("fieldset", help="Show a fieldset's columns")
145
+ _add_source_arguments(describe)
146
+ describe.add_argument("--fieldset", required=True)
147
+ return parser
148
+
149
+
150
+ def _source(args: argparse.Namespace) -> DocumentSource:
151
+ if bool(args.api_url) == bool(args.bundle):
152
+ raise ConfigurationError("Pass exactly one of --api-url or --bundle.")
153
+ if args.bundle:
154
+ return BundleSource.from_path(args.bundle)
155
+ return OpenContractsGraphQLSource(
156
+ args.api_url,
157
+ token=args.token,
158
+ auth_scheme=args.auth_scheme,
159
+ semantic_search=not getattr(args, "no_semantic_search", False),
160
+ )
161
+
162
+
163
+ def _progress(record: ExtractionRecord) -> None:
164
+ detail = f" ({record.failure_mode})" if record.failure_mode else ""
165
+ title = record.document_title or record.document_id
166
+ print(
167
+ f"{record.status.value:<9} {record.column_name} <- {title}{detail}",
168
+ file=sys.stderr,
169
+ )
170
+
171
+
172
+ async def _run(args: argparse.Namespace) -> int:
173
+ if args.extract and (args.corpus or args.document):
174
+ raise ConfigurationError(
175
+ "--extract cannot be combined with --corpus/--document."
176
+ )
177
+ selection: DocumentSelection | None = None
178
+ if not args.extract:
179
+ if not (args.corpus or args.document):
180
+ raise ConfigurationError("Pass --corpus, --document or --extract.")
181
+ if not args.fieldset:
182
+ raise ConfigurationError("--fieldset is required without --extract.")
183
+ selection = DocumentSelection(
184
+ corpus_id=args.corpus, document_ids=tuple(args.document)
185
+ )
186
+ config = EngineConfig(
187
+ model=args.model,
188
+ temperature=args.temperature,
189
+ max_tokens=args.max_tokens,
190
+ request_limit=args.request_limit,
191
+ similarity_top_k=args.similarity_top_k,
192
+ full_text_char_limit=args.full_text_char_limit,
193
+ semantic_search=not args.no_semantic_search,
194
+ ground_results=not args.no_grounding,
195
+ include_llm_log=args.include_llm_log,
196
+ )
197
+ async with _source(args) as source:
198
+ result = await run_extraction(
199
+ source,
200
+ output_dir=args.output_dir,
201
+ fieldset_id=args.fieldset,
202
+ selection=selection,
203
+ extract_id=args.extract,
204
+ config=config,
205
+ concurrency=args.concurrency,
206
+ resume=args.resume,
207
+ on_record=_progress,
208
+ )
209
+ for column, reason in result.skipped_columns:
210
+ print(f"skipped {column.name} ({reason.value})", file=sys.stderr)
211
+ print(
212
+ f"{result.fieldset.name}: {result.document_count} document(s), "
213
+ f"{len(result.files)} column file(s), {result.failed_count} failed cell(s); "
214
+ f"manifest at {result.manifest_path}",
215
+ file=sys.stderr,
216
+ )
217
+ for path in result.files:
218
+ print(path)
219
+ if args.strict and result.failed_count:
220
+ return EXIT_FAILED_CELLS
221
+ return EXIT_OK
222
+
223
+
224
+ async def _describe(args: argparse.Namespace) -> int:
225
+ async with _source(args) as source:
226
+ fieldset = await source.get_fieldset(args.fieldset)
227
+ runnable, skipped = plan_columns(fieldset)
228
+ reasons = {column.id: reason.value for column, reason in skipped}
229
+ print(f"{fieldset.name} ({fieldset.id})")
230
+ for column in fieldset.columns:
231
+ kind = describe_output_type(column)
232
+ state = f"skip: {reasons[column.id]}" if column.id in reasons else "extract"
233
+ print(f" - {column.name} [{kind}] ({state})")
234
+ print(f"{len(runnable)} extractable column(s)")
235
+ return EXIT_OK
236
+
237
+
238
+ def main(argv: Sequence[str] | None = None) -> int:
239
+ # Titles and column names can hold characters a Windows console code page
240
+ # cannot encode; escape them rather than crash mid-run.
241
+ reconfigure = getattr(sys.stdout, "reconfigure", None)
242
+ if reconfigure is not None:
243
+ reconfigure(errors="backslashreplace")
244
+ args = _build_parser().parse_args(argv)
245
+ logging.basicConfig(
246
+ level=(logging.WARNING, logging.INFO, logging.DEBUG)[min(args.verbose, 2)],
247
+ format="%(levelname)s %(name)s: %(message)s",
248
+ stream=sys.stderr,
249
+ )
250
+ handler = _run if args.command == "run" else _describe
251
+ try:
252
+ return asyncio.run(handler(args))
253
+ except (ConfigurationError, SourceError, ValueError) as exc:
254
+ print(f"{TOOL_NAME}: error: {exc}", file=sys.stderr)
255
+ return EXIT_ERROR
256
+
257
+
258
+ if __name__ == "__main__": # pragma: no cover
259
+ sys.exit(main())
@@ -0,0 +1,195 @@
1
+ """Every tunable number and vocabulary string used by ``oc_extract``.
2
+
3
+ Values that mirror the OpenContracts server are noted with the server symbol
4
+ they were ported from, so a change on either side is easy to reconcile.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ # ---------------------------------------------------------------------------
10
+ # Model / agent behaviour
11
+ # ---------------------------------------------------------------------------
12
+
13
+ #: Default pydantic-ai model spec (server: ``constants/extraction.py::DEFAULT_EXTRACT_MODEL``).
14
+ DEFAULT_EXTRACT_MODEL = "openai:gpt-4o-mini"
15
+
16
+ #: Temperature for non-Anthropic models (server: ``constants/llm.py::EXTRACT_DEFAULT_TEMPERATURE``).
17
+ EXTRACT_DEFAULT_TEMPERATURE = 0.3
18
+
19
+ #: Temperature forced for Anthropic models, which otherwise keep narrating
20
+ #: instead of committing a structured answer (server issue #1381).
21
+ ANTHROPIC_EXTRACT_TEMPERATURE = 0.0
22
+
23
+ #: Model-request budget per cell (server: ``constants/llm.py::EXTRACT_AGENT_REQUEST_LIMIT``).
24
+ EXTRACT_AGENT_REQUEST_LIMIT = 20
25
+
26
+ #: Retries pydantic-ai grants the structured output tool
27
+ #: (server: ``constants/llm.py::STRUCTURED_OUTPUT_RETRIES``).
28
+ STRUCTURED_OUTPUT_RETRIES = 3
29
+
30
+ #: Same-call repetitions treated as a tool loop. Must stay above
31
+ #: ``STRUCTURED_OUTPUT_RETRIES`` (server: ``constants/llm.py::TOOL_LOOP_THRESHOLD``).
32
+ TOOL_LOOP_THRESHOLD = 4
33
+
34
+ #: Name of the synthetic tool the agent calls to commit its answer.
35
+ OUTPUT_TOOL_NAME = "final_result"
36
+
37
+ #: OpenAI model families that reject function tools on ``/v1/chat/completions``
38
+ #: whenever ``reasoning_effort`` is set ("Function tools with reasoning_effort
39
+ #: are not supported ... use /v1/responses"). Every extraction agent carries
40
+ #: function tools, and switching reasoning off would discard what these models
41
+ #: are chosen for, so the endpoint moves instead. Shared with the server's
42
+ #: ``llms/model_factory.py::requires_responses_api``.
43
+ OPENAI_RESPONSES_ONLY_PREFIXES: tuple[str, ...] = ("gpt-5.6",)
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Failure-mode vocabulary (server: ``constants/llm.py::NONE_RESULT_*``).
47
+ # Operators grep these strings; do not rename them.
48
+ # ---------------------------------------------------------------------------
49
+
50
+ NONE_RESULT_AGENT_COMMITTED = "agent_committed_none"
51
+ NONE_RESULT_NO_FINAL = "no_final_response"
52
+ NONE_RESULT_TOOL_LOOP = "tool_loop_no_output"
53
+ NONE_RESULT_USAGE_LIMIT = "usage_limit_exceeded"
54
+ NONE_RESULT_UNKNOWN = "unknown"
55
+
56
+ #: Additional modes this package records (not written by the server):
57
+ #: the agent kept calling the result tool with values that failed validation
58
+ #: against the column's output type until its retries ran out.
59
+ NONE_RESULT_INVALID_OUTPUT = "invalid_output"
60
+ #: An exception outside the agent's own loop (provider outage, auth, ...).
61
+ FAILURE_MODE_EXCEPTION = "exception"
62
+ #: The column's ``output_type`` / prompt fields cannot be used.
63
+ FAILURE_MODE_INVALID_COLUMN = "invalid_column"
64
+ #: The document's text or annotations could not be fetched.
65
+ FAILURE_MODE_DOCUMENT_LOAD = "document_load_failed"
66
+ #: An explicit null found nothing in excerpts, so absence is unverified.
67
+ FAILURE_MODE_INSUFFICIENT_TEXT = "insufficient_document_text"
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # Prompt assembly
71
+ # ---------------------------------------------------------------------------
72
+
73
+ #: Documents at or below this many characters get their full text injected
74
+ #: into the prompt (server: ``constants/extraction.py::EXTRACT_FULL_TEXT_CHAR_LIMIT``).
75
+ EXTRACT_FULL_TEXT_CHAR_LIMIT = 24_000
76
+
77
+ #: Separator for few-shot example values inside ``Column.match_text``.
78
+ FEW_SHOT_SEPARATOR = "|||"
79
+
80
+ #: Default task name of extraction columns. Columns naming any other task run
81
+ #: custom server-side Celery code that this package cannot reproduce.
82
+ DEFAULT_EXTRACT_TASK_NAME = (
83
+ "opencontractserver.tasks.data_extract_tasks.doc_extract_query_task"
84
+ )
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Grounding (server: ``constants/extraction.py``)
88
+ # ---------------------------------------------------------------------------
89
+
90
+ MIN_GROUNDABLE_LENGTH = 5
91
+ MAX_GROUNDABLE_STRINGS = 50
92
+ MAX_DOC_LENGTH_FOR_FUZZY = 200_000
93
+ MAX_QUERY_LENGTH_FOR_FUZZY = 2_000
94
+ FUZZY_PER_QUERY_TIMEOUT_SECONDS = 2.0
95
+ FUZZY_ANCHOR_MIN_NGRAM_WORDS = 4
96
+ DEFAULT_FUZZY_THRESHOLD = 0.75
97
+ MIN_ALIGNMENT_QUERY_LENGTH = 4
98
+ #: Fuzzy windows span this fraction of the query length on either side.
99
+ FUZZY_WINDOW_MIN_RATIO = 0.8
100
+ FUZZY_WINDOW_MAX_RATIO = 1.2
101
+ #: Number of window-size steps tried between the min and max ratios.
102
+ FUZZY_WINDOW_SIZE_STEPS = 3
103
+ #: Coarse scan step, as a divisor of the query length.
104
+ FUZZY_STEP_DIVISOR = 4
105
+ NON_GROUNDABLE_LITERALS = frozenset(
106
+ {"true", "false", "yes", "no", "none", "null", "n/a"}
107
+ )
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Agent tools
111
+ # ---------------------------------------------------------------------------
112
+
113
+ DEFAULT_SIMILARITY_TOP_K = 10
114
+ DEFAULT_SEARCH_LIMIT = 10
115
+ MAX_SEARCH_LIMIT = 25
116
+ #: Characters of annotation text shown in search hits / outline entries.
117
+ TOOL_SNIPPET_CHARS = 400
118
+ #: Ceiling on a single ``load_document_text`` slice.
119
+ MAX_TEXT_SLICE_CHARS = 20_000
120
+ #: Ceiling on the text ``get_annotation`` returns for one annotation.
121
+ MAX_ANNOTATION_TEXT_CHARS = 8_000
122
+ #: Ceiling on the concatenated text ``get_subtree_text`` returns.
123
+ MAX_SUBTREE_TEXT_CHARS = 12_000
124
+ DEFAULT_OUTLINE_DEPTH = 2
125
+ MAX_OUTLINE_NODES = 200
126
+ #: Bonus applied when the whole query appears verbatim in an annotation.
127
+ SEARCH_PHRASE_BONUS = 2.0
128
+ #: Bonus applied to structural annotations (headings, sections) when tied.
129
+ SEARCH_STRUCTURAL_BONUS = 0.1
130
+ #: Words ignored by keyword search: too common to discriminate passages.
131
+ SEARCH_STOPWORDS = frozenset(
132
+ {
133
+ "a", "an", "and", "are", "as", "at", "be", "by", "does", "for", "from",
134
+ "has", "have", "in", "is", "it", "its", "of", "on", "or", "that", "the",
135
+ "this", "to", "was", "what", "when", "where", "which", "who", "will",
136
+ "with",
137
+ }
138
+ ) # fmt: skip
139
+ #: Suffixes keyword search strips (first match wins) and their replacements.
140
+ SEARCH_STEM_SUFFIXES: tuple[tuple[str, str], ...] = (
141
+ ("ies", "y"),
142
+ ("ing", ""),
143
+ ("ed", ""),
144
+ ("es", ""),
145
+ ("s", ""),
146
+ )
147
+ #: A stem must keep at least this many characters.
148
+ SEARCH_MIN_STEM_CHARS = 3
149
+ #: Most-specific annotations reported per grounded span.
150
+ MAX_GROUNDING_ANNOTATIONS = 3
151
+ #: Characters of each ancestor shown in a hit's ``section_path``.
152
+ SECTION_PATH_SNIPPET_CHARS = 80
153
+ #: Separator between annotation texts when the source has no text extract
154
+ #: and the index reconstructs the document from structural annotations.
155
+ SYNTHETIC_TEXT_SEPARATOR = "\n\n"
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # API client
159
+ # ---------------------------------------------------------------------------
160
+
161
+ GRAPHQL_PATH = "/graphql/"
162
+ GRAPHQL_PAGE_SIZE = 100
163
+ HTTP_TIMEOUT_SECONDS = 60.0
164
+ HTTP_MAX_RETRIES = 3
165
+ HTTP_MAX_REDIRECTS = 20
166
+ HTTP_RETRY_BACKOFF_SECONDS = 1.0
167
+ #: Status codes worth retrying (rate limiting + transient upstream failures).
168
+ HTTP_RETRY_STATUS_CODES = frozenset({429, 502, 503, 504})
169
+ #: Server-side ceiling on ``semanticSearch(limit:)``.
170
+ SEMANTIC_SEARCH_MAX_LIMIT = 200
171
+ DEFAULT_AUTH_SCHEME = "Bearer"
172
+ #: Auth schemes OpenContracts accepts on the ``Authorization`` header:
173
+ #: JWT (``Bearer``) and API keys (``KEY``).
174
+ AUTH_SCHEMES: tuple[str, ...] = ("Bearer", "KEY")
175
+
176
+ # ---------------------------------------------------------------------------
177
+ # Runner / output
178
+ # ---------------------------------------------------------------------------
179
+
180
+ DEFAULT_CONCURRENCY = 4
181
+ TOOL_NAME = "tabula-razer"
182
+ JSONL_SUFFIX = ".jsonl"
183
+ MANIFEST_FILENAME = "manifest.json"
184
+ #: Bumped whenever the JSONL record shape changes incompatibly.
185
+ RECORD_SCHEMA_VERSION = 1
186
+ #: Maximum length of the slug used for a column's JSONL file name.
187
+ MAX_FILENAME_SLUG_CHARS = 80
188
+ #: Device names Windows reserves regardless of extension (``con.jsonl`` fails).
189
+ WINDOWS_RESERVED_NAMES = frozenset(
190
+ {"con", "prn", "aux", "nul"}
191
+ | {f"com{n}" for n in range(1, 10)}
192
+ | {f"lpt{n}" for n in range(1, 10)}
193
+ )
194
+ #: Appended to a slug that collides with a reserved device name.
195
+ RESERVED_NAME_SUFFIX = "-field"
@@ -0,0 +1,152 @@
1
+ """Explain *why* a structured extraction produced no value.
2
+
3
+ Ported from ``opencontractserver/tasks/data_extract_tasks.py``
4
+ (``_classify_none_result`` / ``_failure_message_for_classification``) so a
5
+ ``failure_mode`` written by this package means exactly what it means on a
6
+ server ``Datacell``:
7
+
8
+ * ``agent_committed_none`` — the agent called the result tool with null: a
9
+ legitimate "not in this document" answer.
10
+ * ``usage_limit_exceeded`` — the run hit its request budget first.
11
+ * ``tool_loop_no_output`` — the agent repeated one tool call without ever
12
+ answering.
13
+ * ``no_final_response`` — the agent never called the result tool.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ from collections import Counter
20
+ from collections.abc import Sequence
21
+ from typing import Any
22
+
23
+ from pydantic_ai.messages import ModelMessage, ModelResponse, ToolCallPart
24
+
25
+ from oc_extract.constants import (
26
+ EXTRACT_AGENT_REQUEST_LIMIT,
27
+ NONE_RESULT_AGENT_COMMITTED,
28
+ NONE_RESULT_INVALID_OUTPUT,
29
+ NONE_RESULT_NO_FINAL,
30
+ NONE_RESULT_TOOL_LOOP,
31
+ NONE_RESULT_UNKNOWN,
32
+ NONE_RESULT_USAGE_LIMIT,
33
+ OUTPUT_TOOL_NAME,
34
+ TOOL_LOOP_THRESHOLD,
35
+ )
36
+ from oc_extract.models import TokenUsage
37
+
38
+
39
+ def _args_signature(raw_args: Any) -> str:
40
+ # ``ToolCallPart.args`` is ``str | dict``; normalise the JSON-string form
41
+ # so identical calls count as one signature whichever form arrived.
42
+ if isinstance(raw_args, str):
43
+ try:
44
+ raw_args = json.loads(raw_args)
45
+ except ValueError:
46
+ # Not JSON: keep the raw string; it still hashes to a stable key.
47
+ pass
48
+ try:
49
+ return json.dumps(raw_args, sort_keys=True, default=str)
50
+ except (TypeError, ValueError):
51
+ return repr(raw_args)
52
+
53
+
54
+ def classify_none_result(
55
+ messages: Sequence[ModelMessage] | None,
56
+ request_limit: int = EXTRACT_AGENT_REQUEST_LIMIT,
57
+ ) -> str:
58
+ """Return one of the ``NONE_RESULT_*`` constants for a ``None`` outcome.
59
+
60
+ ``request_limit`` must be the budget the run actually used: reaching it
61
+ with no result-tool call is the fingerprint of ``UsageLimitExceeded``.
62
+ """
63
+ if not messages:
64
+ return NONE_RESULT_UNKNOWN
65
+
66
+ saw_final_result = False
67
+ signatures: list[tuple[str, str]] = []
68
+ response_count = 0
69
+ for message in messages:
70
+ if not isinstance(message, ModelResponse):
71
+ continue
72
+ response_count += 1
73
+ for part in message.parts:
74
+ if not isinstance(part, ToolCallPart):
75
+ continue
76
+ if part.tool_name.startswith(OUTPUT_TOOL_NAME):
77
+ saw_final_result = True
78
+ else:
79
+ signatures.append((part.tool_name, _args_signature(part.args)))
80
+
81
+ if saw_final_result:
82
+ return NONE_RESULT_AGENT_COMMITTED
83
+ # A budget hit usually also repeats a call, and is the more precise
84
+ # diagnosis, so it is checked first.
85
+ if response_count >= request_limit:
86
+ return NONE_RESULT_USAGE_LIMIT
87
+ if signatures:
88
+ _, repeats = Counter(signatures).most_common(1)[0]
89
+ if repeats >= TOOL_LOOP_THRESHOLD:
90
+ return NONE_RESULT_TOOL_LOOP
91
+ return NONE_RESULT_NO_FINAL
92
+
93
+
94
+ def failure_message(
95
+ classification: str, request_limit: int = EXTRACT_AGENT_REQUEST_LIMIT
96
+ ) -> str:
97
+ """Human-readable explanation for a ``NONE_RESULT_*`` classification."""
98
+ # Wording shared with the server's Datacell.stacktrace; the server tests
99
+ # pin the ``llm_call_log`` pointer (the record field of the same name).
100
+ if classification == NONE_RESULT_AGENT_COMMITTED:
101
+ return (
102
+ "The extraction agent committed to a None result — the requested "
103
+ "information was not found in the document."
104
+ )
105
+ if classification == NONE_RESULT_NO_FINAL:
106
+ return (
107
+ "The extraction agent never produced a final structured response. "
108
+ "This is an integration failure — either the model only emitted "
109
+ "narrative text without ever calling the result tool, or it "
110
+ "exhausted its tool-use budget without committing — not a "
111
+ "statement about the document. Check ``llm_call_log`` for the "
112
+ "raw message history."
113
+ )
114
+ if classification == NONE_RESULT_TOOL_LOOP:
115
+ return (
116
+ "The extraction agent looped on the same tool call without "
117
+ "producing a final structured response. This is an integration "
118
+ "failure, not a statement about the document. Check "
119
+ "``llm_call_log`` for the repeated tool call."
120
+ )
121
+ if classification == NONE_RESULT_INVALID_OUTPUT:
122
+ return (
123
+ "The extraction agent kept submitting values that do not match the "
124
+ "column's output type until its output retries ran out. Check "
125
+ "``llm_call_log`` for the rejected values, and that the output "
126
+ "type is satisfiable."
127
+ )
128
+ if classification == NONE_RESULT_USAGE_LIMIT:
129
+ return (
130
+ "The extraction agent exhausted its request budget "
131
+ f"(request_limit={request_limit}) "
132
+ "before producing a final structured response. This is an "
133
+ "integration/configuration outcome, not a statement about the "
134
+ "document — a more capable model commits well within the budget, "
135
+ "and a budget set too low for the model/document will trip here. "
136
+ "Check ``llm_call_log`` for the message history."
137
+ )
138
+ return (
139
+ "The extraction returned None and the cause could not be classified. "
140
+ "See ``llm_call_log`` for the full message history."
141
+ )
142
+
143
+
144
+ def usage_from_messages(messages: Sequence[ModelMessage] | None) -> TokenUsage:
145
+ """Sum per-response usage, which survives even when the run raised."""
146
+ usage = TokenUsage()
147
+ for message in messages or ():
148
+ if isinstance(message, ModelResponse):
149
+ usage.requests += 1
150
+ usage.input_tokens += message.usage.input_tokens or 0
151
+ usage.output_tokens += message.usage.output_tokens or 0
152
+ return usage