structa-maestro 0.2.0__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.
- structa_maestro/__init__.py +294 -0
- structa_maestro/batch.py +564 -0
- structa_maestro/binding.py +206 -0
- structa_maestro/builder/__init__.py +0 -0
- structa_maestro/builder/result_builder.py +308 -0
- structa_maestro/cli.py +730 -0
- structa_maestro/confidence/__init__.py +49 -0
- structa_maestro/confidence/calibration.py +990 -0
- structa_maestro/confidence/normalizer.py +203 -0
- structa_maestro/config.py +111 -0
- structa_maestro/contracts/__init__.py +0 -0
- structa_maestro/contracts/enums.py +86 -0
- structa_maestro/contracts/models.py +229 -0
- structa_maestro/contracts/serialization.py +169 -0
- structa_maestro/documents/__init__.py +32 -0
- structa_maestro/documents/docx_parser.py +215 -0
- structa_maestro/documents/eml_parser.py +360 -0
- structa_maestro/documents/html_parser.py +337 -0
- structa_maestro/documents/inputs.py +277 -0
- structa_maestro/documents/loader.py +675 -0
- structa_maestro/documents/markdown_parser.py +225 -0
- structa_maestro/documents/models.py +33 -0
- structa_maestro/documents/normalization.py +24 -0
- structa_maestro/documents/pdf_parser.py +186 -0
- structa_maestro/documents/txt_parser.py +169 -0
- structa_maestro/engine.py +1201 -0
- structa_maestro/exceptions.py +38 -0
- structa_maestro/provenance/__init__.py +0 -0
- structa_maestro/provenance/associator.py +234 -0
- structa_maestro/py.typed +0 -0
- structa_maestro/review.py +1234 -0
- structa_maestro/schema/__init__.py +19 -0
- structa_maestro/schema/loader.py +616 -0
- structa_maestro/schema/models.py +269 -0
- structa_maestro/schema/pydantic_adapter.py +566 -0
- structa_maestro/schema/rules.py +526 -0
- structa_maestro/schema/serializer.py +156 -0
- structa_maestro/strategies/__init__.py +45 -0
- structa_maestro/strategies/base.py +101 -0
- structa_maestro/strategies/llm_anthropic.py +1142 -0
- structa_maestro/strategies/llm_config.py +154 -0
- structa_maestro/strategies/llm_gemini.py +1171 -0
- structa_maestro/strategies/llm_helpers.py +240 -0
- structa_maestro/strategies/llm_openai_compat.py +1183 -0
- structa_maestro/strategies/schema_compiler.py +248 -0
- structa_maestro/strategies/testing.py +71 -0
- structa_maestro/telemetry.py +800 -0
- structa_maestro/validation/__init__.py +0 -0
- structa_maestro/validation/cross_field.py +463 -0
- structa_maestro/validation/validator.py +531 -0
- structa_maestro-0.2.0.dist-info/METADATA +394 -0
- structa_maestro-0.2.0.dist-info/RECORD +55 -0
- structa_maestro-0.2.0.dist-info/WHEEL +4 -0
- structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
- structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Pure deterministic helpers for LLM strategy hardening (zero external dependencies)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import secrets
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from datetime import UTC, date, datetime
|
|
11
|
+
from decimal import Decimal, InvalidOperation
|
|
12
|
+
from email.utils import parsedate_to_datetime
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from structa_maestro.contracts.enums import FieldType
|
|
16
|
+
from structa_maestro.schema.models import FieldSpec
|
|
17
|
+
from structa_maestro.strategies.llm_config import InputBudgetPolicy, RetryPolicy
|
|
18
|
+
|
|
19
|
+
_UNTRUSTED_TAG_RE = re.compile(r"<(\s*/?\s*untrusted_document\b)", re.IGNORECASE)
|
|
20
|
+
_CODE_FENCE_RE = re.compile(
|
|
21
|
+
r"^\s*```(?:json|JSON)?\s*\n(.*?)\n?\s*```\s*$",
|
|
22
|
+
re.DOTALL,
|
|
23
|
+
)
|
|
24
|
+
_STRUCTURED_OUTPUT_TOKENS: tuple[str, ...] = (
|
|
25
|
+
"response_format",
|
|
26
|
+
"json_schema",
|
|
27
|
+
"structured output",
|
|
28
|
+
"structured_output",
|
|
29
|
+
"additionalproperties",
|
|
30
|
+
)
|
|
31
|
+
_UNSUPPORTED_HINTS: tuple[str, ...] = (
|
|
32
|
+
"unsupported",
|
|
33
|
+
"not supported",
|
|
34
|
+
"does not support",
|
|
35
|
+
"invalid_request",
|
|
36
|
+
"unknown variant",
|
|
37
|
+
"invalid value",
|
|
38
|
+
"not allowed",
|
|
39
|
+
"strict",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def default_rng() -> float:
|
|
44
|
+
"""Return a uniform float in [0.0, 1.0) using stdlib secrets (Bandit S311-safe)."""
|
|
45
|
+
return secrets.randbelow(10_000) / 10_000.0
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def neutralize_untrusted_delimiters(text: str) -> str:
|
|
49
|
+
"""Escape embedded <untrusted_document / </untrusted_document tags inside document text."""
|
|
50
|
+
return _UNTRUSTED_TAG_RE.sub(r"<\1", text)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def apply_input_budget(
|
|
54
|
+
full_text: str,
|
|
55
|
+
budget: InputBudgetPolicy,
|
|
56
|
+
) -> tuple[str, bool, int, int]:
|
|
57
|
+
"""Apply InputBudgetPolicy to prepared document text.
|
|
58
|
+
|
|
59
|
+
Returns ``(retained_text, exceeded, included_chars, total_chars)``.
|
|
60
|
+
When ``exceeded`` is True and ``budget.overflow_policy`` is ``TRUNCATE``,
|
|
61
|
+
``retained_text`` is deterministically truncated on a clean newline boundary
|
|
62
|
+
when one exists in the second half of the budget, otherwise at ``max_input_chars``.
|
|
63
|
+
"""
|
|
64
|
+
total_chars = len(full_text)
|
|
65
|
+
limit = budget.max_input_chars
|
|
66
|
+
if limit is None or total_chars <= limit:
|
|
67
|
+
return full_text, False, total_chars, total_chars
|
|
68
|
+
|
|
69
|
+
prefix = full_text[:limit]
|
|
70
|
+
last_nl = prefix.rfind("\n")
|
|
71
|
+
retained = prefix[:last_nl] if last_nl >= limit // 2 else prefix
|
|
72
|
+
return retained, True, len(retained), total_chars
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_retry_after(
|
|
76
|
+
header_value: str | None,
|
|
77
|
+
*,
|
|
78
|
+
now_epoch: float | None = None,
|
|
79
|
+
) -> float | None:
|
|
80
|
+
"""Parse HTTP Retry-After header (seconds or RFC 7231 HTTP-date) into non-negative seconds."""
|
|
81
|
+
if not header_value or not isinstance(header_value, str):
|
|
82
|
+
return None
|
|
83
|
+
raw = header_value.strip()
|
|
84
|
+
if not raw:
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
# 1. Numeric delay-seconds
|
|
88
|
+
try:
|
|
89
|
+
seconds = float(raw)
|
|
90
|
+
except ValueError:
|
|
91
|
+
seconds = math.nan
|
|
92
|
+
if math.isfinite(seconds):
|
|
93
|
+
return seconds if seconds >= 0.0 else None
|
|
94
|
+
|
|
95
|
+
# 2. HTTP-date (RFC 7231)
|
|
96
|
+
try:
|
|
97
|
+
dt = parsedate_to_datetime(raw)
|
|
98
|
+
except (TypeError, ValueError, IndexError):
|
|
99
|
+
return None
|
|
100
|
+
if dt is None:
|
|
101
|
+
return None
|
|
102
|
+
if dt.tzinfo is None:
|
|
103
|
+
dt = dt.replace(tzinfo=UTC)
|
|
104
|
+
now_ts = time.time() if now_epoch is None else now_epoch
|
|
105
|
+
delta = dt.timestamp() - datetime.fromtimestamp(now_ts, tz=UTC).timestamp()
|
|
106
|
+
return max(0.0, delta)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def compute_backoff_delay(
|
|
110
|
+
attempt: int,
|
|
111
|
+
policy: RetryPolicy,
|
|
112
|
+
*,
|
|
113
|
+
retry_after: float | None = None,
|
|
114
|
+
remaining_budget: float | None = None,
|
|
115
|
+
rng: Callable[[], float] | None = None,
|
|
116
|
+
) -> float | None:
|
|
117
|
+
"""Compute bounded retry delay in seconds, or None if waiting would exceed remaining_budget.
|
|
118
|
+
|
|
119
|
+
Per Spec 003 U1: if ``remaining_budget`` is set and a valid parsed ``retry_after``
|
|
120
|
+
meets or exceeds ``remaining_budget``, return ``None`` immediately instead of clamping
|
|
121
|
+
and retrying prematurely.
|
|
122
|
+
"""
|
|
123
|
+
if remaining_budget is not None and remaining_budget <= 0.0:
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
if retry_after is not None:
|
|
127
|
+
if remaining_budget is not None and retry_after >= remaining_budget:
|
|
128
|
+
return None
|
|
129
|
+
delay = min(policy.max_backoff_seconds, max(0.0, retry_after))
|
|
130
|
+
else:
|
|
131
|
+
exponent = max(0, attempt - 1)
|
|
132
|
+
base = min(policy.max_backoff_seconds, policy.initial_backoff_seconds * (2**exponent))
|
|
133
|
+
if policy.jitter and base > 0.0:
|
|
134
|
+
draw = (rng or default_rng)()
|
|
135
|
+
clamped_draw = min(1.0, max(0.0, float(draw)))
|
|
136
|
+
delay = base * (0.5 + 0.5 * clamped_draw)
|
|
137
|
+
else:
|
|
138
|
+
delay = base
|
|
139
|
+
|
|
140
|
+
if remaining_budget is not None and delay >= remaining_budget:
|
|
141
|
+
return None
|
|
142
|
+
return delay
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def extract_json_object_text(raw_content: str) -> tuple[str, bool]:
|
|
146
|
+
"""Recover top-level JSON object text from Markdown fences or surrounding prose.
|
|
147
|
+
|
|
148
|
+
Returns ``(candidate_json_text, sanitized)`` without mutating any values inside the JSON.
|
|
149
|
+
"""
|
|
150
|
+
stripped = raw_content.strip()
|
|
151
|
+
if not stripped:
|
|
152
|
+
return stripped, False
|
|
153
|
+
|
|
154
|
+
if stripped.startswith("{") and stripped.endswith("}"):
|
|
155
|
+
return stripped, False
|
|
156
|
+
|
|
157
|
+
fenced = _CODE_FENCE_RE.match(stripped)
|
|
158
|
+
if fenced is not None:
|
|
159
|
+
inner = fenced.group(1).strip()
|
|
160
|
+
if inner.startswith("{") and inner.endswith("}"):
|
|
161
|
+
return inner, True
|
|
162
|
+
stripped = inner
|
|
163
|
+
|
|
164
|
+
# Locate the first balanced top-level JSON object using a string-aware brace scanner.
|
|
165
|
+
start_idx = stripped.find("{")
|
|
166
|
+
if start_idx == -1:
|
|
167
|
+
return raw_content.strip(), False
|
|
168
|
+
|
|
169
|
+
depth = 0
|
|
170
|
+
in_string = False
|
|
171
|
+
escaped = False
|
|
172
|
+
for idx in range(start_idx, len(stripped)):
|
|
173
|
+
ch = stripped[idx]
|
|
174
|
+
if in_string:
|
|
175
|
+
if escaped:
|
|
176
|
+
escaped = False
|
|
177
|
+
elif ch == "\\":
|
|
178
|
+
escaped = True
|
|
179
|
+
elif ch == '"':
|
|
180
|
+
in_string = False
|
|
181
|
+
continue
|
|
182
|
+
if ch == '"':
|
|
183
|
+
in_string = True
|
|
184
|
+
elif ch == "{":
|
|
185
|
+
depth += 1
|
|
186
|
+
elif ch == "}":
|
|
187
|
+
depth -= 1
|
|
188
|
+
if depth == 0:
|
|
189
|
+
candidate = stripped[start_idx : idx + 1]
|
|
190
|
+
was_modified = candidate != raw_content.strip()
|
|
191
|
+
return candidate, was_modified
|
|
192
|
+
|
|
193
|
+
return raw_content.strip(), False
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def coerce_llm_json_value(value: Any, spec: FieldSpec | None) -> Any:
|
|
197
|
+
"""Recursively convert clean JSON-wire Decimal/date values without mutating invalid inputs."""
|
|
198
|
+
if value is None or spec is None:
|
|
199
|
+
return value
|
|
200
|
+
|
|
201
|
+
if spec.field_type == FieldType.DECIMAL:
|
|
202
|
+
if isinstance(value, Decimal):
|
|
203
|
+
return value
|
|
204
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
205
|
+
return Decimal(str(value))
|
|
206
|
+
if isinstance(value, str):
|
|
207
|
+
try:
|
|
208
|
+
return Decimal(value.strip())
|
|
209
|
+
except InvalidOperation:
|
|
210
|
+
return value
|
|
211
|
+
return value
|
|
212
|
+
|
|
213
|
+
if spec.field_type == FieldType.DATE:
|
|
214
|
+
if isinstance(value, str):
|
|
215
|
+
try:
|
|
216
|
+
return date.fromisoformat(value.strip())
|
|
217
|
+
except ValueError:
|
|
218
|
+
return value
|
|
219
|
+
return value
|
|
220
|
+
|
|
221
|
+
if spec.field_type == FieldType.OBJECT and isinstance(value, dict) and spec.properties:
|
|
222
|
+
return {
|
|
223
|
+
k: coerce_llm_json_value(v, spec.properties.get(k)) if isinstance(k, str) else v
|
|
224
|
+
for k, v in value.items()
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if spec.field_type == FieldType.ARRAY and isinstance(value, list) and spec.items is not None:
|
|
228
|
+
return [coerce_llm_json_value(item, spec.items) for item in value]
|
|
229
|
+
|
|
230
|
+
return value
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def is_structured_output_unsupported(status_code: int, response_text: str) -> bool:
|
|
234
|
+
"""Detect HTTP 400/422 responses specifically rejecting strict json_schema response_format."""
|
|
235
|
+
if status_code not in (400, 422):
|
|
236
|
+
return False
|
|
237
|
+
lowered = response_text.lower()
|
|
238
|
+
if not any(tok in lowered for tok in _STRUCTURED_OUTPUT_TOKENS):
|
|
239
|
+
return False
|
|
240
|
+
return any(hint in lowered for hint in _UNSUPPORTED_HINTS) or "json_schema" in lowered
|