From 7a4a9420da1b0916521530a559225a33a34b39c4 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sat, 26 Sep 2026 21:05:17 +0200 Subject: [PATCH 01/58] feat(agent): enforcement axis and per-provider schema preparation - Enforcement makes an arm a value, so orchestration can be held fixed - five arms declared, with A0 split into a prose and a json sub-arm - ProviderProfile is declared in config, never inferred from a model name - prepare() reports what a provider subset removed, as a fidelity number - core stays LLM free, oold.agent pulls only stdlib today --- src/oold/agent/__init__.py | 46 +++ src/oold/agent/enforcement.py | 192 ++++++++++++ src/oold/agent/provider.py | 361 ++++++++++++++++++++++ tests/test_agent/__init__.py | 0 tests/test_agent/test_enforcement.py | 141 +++++++++ tests/test_agent/test_provider_profile.py | 218 +++++++++++++ 6 files changed, 958 insertions(+) create mode 100644 src/oold/agent/__init__.py create mode 100644 src/oold/agent/enforcement.py create mode 100644 src/oold/agent/provider.py create mode 100644 tests/test_agent/__init__.py create mode 100644 tests/test_agent/test_enforcement.py create mode 100644 tests/test_agent/test_provider_profile.py diff --git a/src/oold/agent/__init__.py b/src/oold/agent/__init__.py new file mode 100644 index 0000000..1cc1cc3 --- /dev/null +++ b/src/oold/agent/__init__.py @@ -0,0 +1,46 @@ +"""Turn an OO-LD schema into a validated typed instance with an LLM. + +Orchestration and enforcement are separate axes here, so a study can hold one +fixed while varying the other. The three agents in the `osl-eln-demo` project +become three values of :class:`Orchestration` rather than three code paths. + +Nothing in the core of ``oold`` imports this package, so installing ``oold`` +for typed data never pulls in an LLM client. + +Requires the ``agent`` extra:: + + uv add "oold[agent]" + pip install "oold[agent]" +""" + +from oold.agent.enforcement import ( + ARMS, + DecodeConstraint, + Enforcement, + Orchestration, + OutputForm, + arm, +) +from oold.agent.provider import ( + PROFILES, + Degradation, + ProviderProfile, + prepare, + profile_for, + schema_hash, +) + +__all__ = [ + "ARMS", + "PROFILES", + "DecodeConstraint", + "Degradation", + "Enforcement", + "Orchestration", + "OutputForm", + "ProviderProfile", + "arm", + "prepare", + "profile_for", + "schema_hash", +] diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py new file mode 100644 index 0000000..1ccc3e0 --- /dev/null +++ b/src/oold/agent/enforcement.py @@ -0,0 +1,192 @@ +"""Where structure is enforced, as data rather than as separate code paths. + +Orchestration and enforcement are independent. The agent that walks a document +recursively and the agent that runs a five-step pipeline can both be given a +schema in the prompt, a decode-time constraint, a commit-time gate, all three, +or none. Entangling the two is what makes a comparison of typed against untyped +extraction impossible to interpret, because every measured difference has two +candidate causes. +""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from enum import Enum +from typing import Literal + +__all__ = [ + "ARMS", + "DecodeConstraint", + "Enforcement", + "Orchestration", + "OutputForm", + "arm", +] + + +class Orchestration(str, Enum): + """How the work is broken up, held constant while enforcement varies.""" + + RECURSIVE = "recursive" + """Depth first. Resolve each entity, recursing into its linked entities.""" + + SEGMENTED = "segmented" + """Plan the whole entity graph in one call, then fill it.""" + + MULTI_STEP = "multi_step" + """Detect, select properties, extract, construct, deduplicate.""" + + +class DecodeConstraint(str, Enum): + """What the model is prevented from emitting in the first place.""" + + NONE = "none" + """Free generation. Conformance is whatever the model volunteers.""" + + JSON_SCHEMA = "json_schema" + """Structured output against the schema, without a class enumeration.""" + + JSON_SCHEMA_ENUM = "json_schema+enum" + """Structured output with the class slot pinned to the catalogue.""" + + +class OutputForm(str, Enum): + """The shape the model is asked to answer in.""" + + PROSE = "prose" + JSON = "json" + + +@dataclass(frozen=True) +class Enforcement: + """One point in the enforcement space. + + Every field is a separate question a reviewer can ask, and every field is + set independently, so a result can be attributed to one of them. + """ + + schema_in_prompt: bool + """Whether the target schema is shown to the model at all.""" + + catalogue: tuple[str, ...] | None + """Class paths offered for selection. ``None`` offers no catalogue, which + is a different condition from offering an empty one. The length is the + variable a catalogue-weight sweep moves.""" + + decode_constraint: DecodeConstraint + commit_gate: bool + """Whether a produced class path is checked against the catalogue after + generation, and the instance dropped when it cannot be resolved.""" + + grounding: bool + """Whether the schema keeps its ``@context`` and IRIs, or is flattened to + a structured-output subset that carries the semantics in ``title`` and + ``description`` instead.""" + + output_form: OutputForm = OutputForm.JSON + + def __post_init__(self) -> None: + if self.grounding and not self.schema_in_prompt: + raise ValueError( + "grounding needs a schema to ground; " + "set schema_in_prompt when grounding is on" + ) + if self.output_form is OutputForm.PROSE: + if self.decode_constraint is not DecodeConstraint.NONE: + raise ValueError( + "prose output cannot carry a decode-time constraint" + ) + if self.commit_gate: + raise ValueError("prose output has no class path to gate") + + @property + def catalogue_size(self) -> int: + """How many classes were offered. Zero when none were.""" + return 0 if self.catalogue is None else len(self.catalogue) + + def with_catalogue(self, paths: tuple[str, ...] | None) -> "Enforcement": + """The same condition over a different catalogue. + + This is the one knob a catalogue-weight sweep moves, so it gets a + method rather than being reconstructed by hand at each size. + """ + return replace(self, catalogue=paths) + + def describe(self) -> dict[str, object]: + """The condition, for the result record. + + Catalogue contents are not included; they are large and belong in a + hash alongside the record. The size is here because it is the variable. + """ + return { + "schema_in_prompt": self.schema_in_prompt, + "catalogue_size": self.catalogue_size, + "catalogue_offered": self.catalogue is not None, + "decode_constraint": self.decode_constraint.value, + "commit_gate": self.commit_gate, + "grounding": self.grounding, + "output_form": self.output_form.value, + } + + +ArmName = Literal["A0-prose", "A0-json", "A1", "A2", "A3"] + +ARMS: dict[str, Enforcement] = { + "A0-prose": Enforcement( + schema_in_prompt=False, + catalogue=None, + decode_constraint=DecodeConstraint.NONE, + commit_gate=False, + grounding=False, + output_form=OutputForm.PROSE, + ), + "A0-json": Enforcement( + schema_in_prompt=False, + catalogue=None, + decode_constraint=DecodeConstraint.NONE, + commit_gate=False, + grounding=False, + output_form=OutputForm.JSON, + ), + "A1": Enforcement( + schema_in_prompt=True, + catalogue=(), + decode_constraint=DecodeConstraint.NONE, + commit_gate=True, + grounding=False, + ), + "A2": Enforcement( + schema_in_prompt=True, + catalogue=(), + decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, + commit_gate=True, + grounding=False, + ), + "A3": Enforcement( + schema_in_prompt=True, + catalogue=(), + decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, + commit_gate=True, + grounding=True, + ), +} +"""The five arms, with an empty catalogue that a run fills in. + +A0 is two arms rather than one. ``A0-json`` is the headline comparison, because +its output reduces to triples by the same path as every other arm and needs no +judge. ``A0-prose`` is reported beside it with the parse loss of its extractor +stated, so the objection that JSON is already a form of structure has an answer +in the results rather than in the discussion. +""" + + +def arm(name: str, catalogue: tuple[str, ...] | None = None) -> Enforcement: + """One of the five arms, over a given catalogue.""" + if name not in ARMS: + raise KeyError(f"unknown arm {name!r}, expected one of {sorted(ARMS)}") + base = ARMS[name] + if catalogue is None: + return base + if base.catalogue is None: + raise ValueError(f"arm {name} offers no catalogue") + return base.with_catalogue(catalogue) diff --git a/src/oold/agent/provider.py b/src/oold/agent/provider.py new file mode 100644 index 0000000..0811355 --- /dev/null +++ b/src/oold/agent/provider.py @@ -0,0 +1,361 @@ +"""Per-provider schema preparation, with a record of what it cost. + +Providers accept different subsets of JSON Schema, so the same OO-LD schema +reaches each of them differently. That makes the transform part of the +treatment, not a utility: if one provider is handed a schema that lost its +constraints and another is not, a measured difference between them is partly a +difference between transforms. So the profile is declared in configuration +rather than sniffed from a model name, the prepared schema is hashed into the +result, and what the transform removed is reported as a number. + +The combinator flattening follows the approach taken by LiteLLM's +``flatten_top_level_schema_combinators``: merge where merging is sound, and +pass a subschema through untouched when it is not. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +from dataclasses import dataclass, field +from typing import Any + +__all__ = [ + "PROFILES", + "Degradation", + "ProviderProfile", + "prepare", + "profile_for", +] + +_COMBINATORS = ("allOf", "oneOf", "anyOf") +_NUMERIC_CONSTRAINTS = ( + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "multipleOf", +) +_STRING_CONSTRAINTS = ("minLength", "maxLength", "pattern", "format") +_ARRAY_CONSTRAINTS = ("minItems", "maxItems", "uniqueItems") +_SEMANTIC_KEYWORDS = ("@context", "x-oold-iri", "x-oold-instance-rdf-type") + + +@dataclass +class Degradation: + """What preparing a schema for one provider removed from it. + + Reported per arm and provider. A structured-output subset that loses most + of a schema is a different condition from one that loses none, and saying + so with a number is cheaper than arguing about it. + """ + + dropped: dict[str, int] = field(default_factory=dict) + """Keyword to how many times it was removed.""" + refs_inlined: int = 0 + recursion_cut: int = 0 + """Subschemas replaced by a permissive stub because recursion was not + supported and the cycle had to end somewhere.""" + made_required: int = 0 + constraints_described: int = 0 + """Constraints moved into ``description`` because the provider rejects + them but the model can still read them.""" + semantics_dropped: int = 0 + """``@context`` and IRI keywords removed. This is the difference between a + grounded arm and a flattened one.""" + keywords_before: int = 0 + keywords_after: int = 0 + + @property + def fidelity(self) -> float: + """Share of the original keywords that survived, 1.0 when none were + lost. Inlining a ``$ref`` duplicates keywords, so this can exceed 1.0; + that is information preserved, not lost.""" + if not self.keywords_before: + return 1.0 + return self.keywords_after / self.keywords_before + + def _note(self, keyword: str) -> None: + self.dropped[keyword] = self.dropped.get(keyword, 0) + 1 + + def describe(self) -> dict[str, Any]: + return { + "fidelity": round(self.fidelity, 4), + "keywords_before": self.keywords_before, + "keywords_after": self.keywords_after, + "dropped": dict(sorted(self.dropped.items())), + "refs_inlined": self.refs_inlined, + "recursion_cut": self.recursion_cut, + "made_required": self.made_required, + "constraints_described": self.constraints_described, + "semantics_dropped": self.semantics_dropped, + } + + +@dataclass(frozen=True) +class ProviderProfile: + """What one provider's structured-output mode accepts. + + Declared, never inferred from the model name. A substring test on a + deployment name silently sends an OpenAI-compatible endpoint serving an + open-weight model down the OpenAI branch. + """ + + name: str + supports_combinators: bool = False + """Whether ``allOf``, ``oneOf`` and ``not`` survive. Only a consumer that + takes arbitrary JSON Schema keywords does; every strict structured-output + mode rejects them.""" + supports_recursive_ref: bool = True + supports_any_of: bool = True + supports_numeric_constraints: bool = True + supports_string_constraints: bool = True + requires_all_properties_required: bool = False + requires_additional_properties_false: bool = False + max_optional_properties: int | None = None + max_recursion_depth: int = 4 + """Where to cut a cycle when the provider cannot express one.""" + + def accepts(self, keyword: str) -> bool: + if keyword in ("allOf", "oneOf", "not"): + return self.supports_combinators + if keyword == "anyOf": + return self.supports_any_of + if keyword in _NUMERIC_CONSTRAINTS: + return self.supports_numeric_constraints + if keyword in _STRING_CONSTRAINTS: + return self.supports_string_constraints + return True + + +PROFILES: dict[str, ProviderProfile] = { + "native": ProviderProfile( + name="native", + supports_combinators=True, + supports_recursive_ref=True, + supports_any_of=True, + supports_numeric_constraints=True, + supports_string_constraints=True, + ), + "openai": ProviderProfile( + name="openai", + supports_recursive_ref=True, + supports_any_of=True, + supports_numeric_constraints=True, + supports_string_constraints=True, + requires_all_properties_required=True, + requires_additional_properties_false=True, + ), + "anthropic": ProviderProfile( + name="anthropic", + supports_recursive_ref=False, + supports_any_of=False, + supports_numeric_constraints=False, + supports_string_constraints=False, + requires_all_properties_required=False, + requires_additional_properties_false=True, + max_optional_properties=24, + ), + "google": ProviderProfile( + name="google", + supports_recursive_ref=True, + supports_any_of=True, + supports_numeric_constraints=True, + supports_string_constraints=False, + requires_all_properties_required=False, + requires_additional_properties_false=False, + ), +} +"""Declared subsets. + +``native`` sends the schema through unchanged, which is the grounded arm: the +consumer takes arbitrary JSON Schema keywords and the ``@context`` is carried +through as grounding. The others are the strict structured-output subset, and +what each of them removes is the reason the two arms can differ. +""" + + +def profile_for(name: str) -> ProviderProfile: + if name not in PROFILES: + raise KeyError( + f"unknown provider profile {name!r}, " + f"expected one of {sorted(PROFILES)}" + ) + return PROFILES[name] + + +def _count_keywords(node: Any) -> int: + if isinstance(node, dict): + return len(node) + sum(_count_keywords(v) for v in node.values()) + if isinstance(node, list): + return sum(_count_keywords(v) for v in node) + return 0 + + +def _merge(into: dict[str, Any], other: dict[str, Any]) -> None: + """Merge one subschema into another, union-ing the parts that union.""" + for key, value in other.items(): + if key == "properties": + into.setdefault("properties", {}).update(value) + elif key == "required": + merged = list(into.get("required", [])) + list(value) + into["required"] = sorted(set(merged)) + elif key not in into: + into[key] = value + + +def _describe_constraint(node: dict[str, Any], keyword: str) -> None: + """Fold a rejected constraint into the description, as the SDKs do.""" + note = f"{keyword}: {node[keyword]}" + existing = node.get("description") + node["description"] = f"{existing} ({note})" if existing else note + + +def prepare( + schema: dict[str, Any], + profile: ProviderProfile, + *, + grounding: bool = True, +) -> tuple[dict[str, Any], Degradation]: + """Prepare a schema for one provider, and report what that cost. + + ``grounding`` keeps ``@context`` and the IRI keywords in place. Turning it + off is the flattened structured-output subset, where the semantics survive + only in ``title`` and ``description``. + """ + report = Degradation() + report.keywords_before = _count_keywords(schema) + defs = {**schema.get("$defs", {}), **schema.get("definitions", {})} + inlining = not profile.supports_combinators + """Flattening combinators forces refs to be inlined, because a merged + parent cannot stay behind a reference. A provider that keeps combinators + keeps ``$defs`` and needs neither.""" + + def _close_object(node: dict[str, Any]) -> dict[str, Any]: + """Apply the object-level rules a provider imposes.""" + if node.get("type") != "object" and "properties" not in node: + return node + properties = node.get("properties") or {} + if profile.requires_additional_properties_false: + node["additionalProperties"] = False + if profile.requires_all_properties_required and properties: + optional = [ + k for k in properties if k not in node.get("required", []) + ] + report.made_required += len(optional) + for key in optional: + child = properties[key] + if isinstance(child, dict) and "type" in child: + current = child["type"] + types = current if isinstance(current, list) else [current] + if "null" not in types: + child["type"] = [*types, "null"] + node["required"] = list(properties) + elif profile.max_optional_properties is not None and properties: + required = node.get("required", []) + optional = [k for k in properties if k not in required] + overflow = len(optional) - profile.max_optional_properties + if overflow > 0: + for key in optional[-overflow:]: + properties.pop(key, None) + report._note("optional-property-overflow") + return node + + def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: + if isinstance(node, list): + return [walk(item, seen, depth) for item in node] + if not isinstance(node, dict): + return node + + node = dict(node) + + ref = node.pop("$ref", None) + if ref is not None: + name = ref.rsplit("/", 1)[-1] + recursing = name in seen + too_deep = depth > profile.max_recursion_depth + keep_ref = ( + # A consumer that takes arbitrary keywords keeps $defs too, so + # there is nothing to inline and nothing is lost. + not inlining + or (recursing and profile.supports_recursive_ref and not too_deep) + ) + if keep_ref: + node["$ref"] = ref + return node + if name not in defs or too_deep or recursing: + report.recursion_cut += 1 + return { + "type": "string", + "description": node.get( + "description", f"reference to {name}" + ), + } + report.refs_inlined += 1 + resolved = walk(defs[name], (*seen, name), depth + 1) + if isinstance(resolved, dict): + _merge(node, resolved) + # The inlined body has been walked already, under a `seen` that + # knows about this reference. Walking it again from here would not. + return _close_object(node) + + for combinator in _COMBINATORS: + if combinator not in node: + continue + if profile.accepts(combinator): + node[combinator] = walk(node[combinator], seen, depth) + continue + branches = node.pop(combinator) + report._note(combinator) + if combinator == "allOf": + for branch in branches: + resolved = walk(branch, seen, depth + 1) + if isinstance(resolved, dict): + _merge(node, resolved) + elif branches: + resolved = walk(branches[0], seen, depth + 1) + if isinstance(resolved, dict): + _merge(node, resolved) + + if "not" in node: + node.pop("not") + report._note("not") + + for keyword in (*_NUMERIC_CONSTRAINTS, *_STRING_CONSTRAINTS): + if keyword in node and not profile.accepts(keyword): + _describe_constraint(node, keyword) + node.pop(keyword) + report.constraints_described += 1 + report._note(keyword) + + if not grounding: + for keyword in _SEMANTIC_KEYWORDS: + if keyword in node: + node.pop(keyword) + report.semantics_dropped += 1 + report._note(keyword) + + for keyword in ("properties", "items", "prefixItems"): + if keyword in node: + node[keyword] = walk(node[keyword], seen, depth) + for key, value in list(node.items()): + if key in _COMBINATORS or key in ("properties", "items", "prefixItems"): + continue + if isinstance(value, (dict, list)) and key not in ("enum", "default"): + node[key] = walk(value, seen, depth) + + return _close_object(node) + + prepared = walk(copy.deepcopy(schema), (), 0) + if inlining and isinstance(prepared, dict): + prepared.pop("$defs", None) + prepared.pop("definitions", None) + report.keywords_after = _count_keywords(prepared) + return prepared, report + + +def schema_hash(schema: dict[str, Any]) -> str: + """Stable hash of the schema actually sent, for the result record.""" + canonical = json.dumps(schema, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() diff --git a/tests/test_agent/__init__.py b/tests/test_agent/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_agent/test_enforcement.py b/tests/test_agent/test_enforcement.py new file mode 100644 index 0000000..702cfd2 --- /dev/null +++ b/tests/test_agent/test_enforcement.py @@ -0,0 +1,141 @@ +"""The enforcement axis: arms are values, and the invalid ones are refused.""" + +import pytest + +from oold.agent import ( + ARMS, + DecodeConstraint, + Enforcement, + Orchestration, + OutputForm, + arm, +) + + +def typed(**overrides) -> Enforcement: + kwargs = { + "schema_in_prompt": True, + "catalogue": ("schemaorg.Person",), + "decode_constraint": DecodeConstraint.JSON_SCHEMA_ENUM, + "commit_gate": True, + "grounding": False, + } + kwargs.update(overrides) + return Enforcement(**kwargs) + + +class TestArms: + def test_all_five_arms_exist(self): + assert sorted(ARMS) == ["A0-json", "A0-prose", "A1", "A2", "A3"] + + def test_a0_offers_no_schema_and_no_catalogue(self): + for name in ("A0-prose", "A0-json"): + condition = ARMS[name] + assert condition.schema_in_prompt is False + assert condition.catalogue is None + assert condition.commit_gate is False + + def test_the_two_a0_arms_differ_only_in_output_form(self): + prose, as_json = ARMS["A0-prose"], ARMS["A0-json"] + assert prose.output_form is OutputForm.PROSE + assert as_json.output_form is OutputForm.JSON + for field in ("schema_in_prompt", "catalogue", "commit_gate", "grounding"): + assert getattr(prose, field) == getattr(as_json, field) + + def test_a1_to_a2_varies_only_the_decode_constraint(self): + """The cheapest real contrast in the study, so nothing else may move.""" + a1, a2 = ARMS["A1"], ARMS["A2"] + assert a1.decode_constraint is DecodeConstraint.NONE + assert a2.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM + for field in ( + "schema_in_prompt", + "catalogue", + "commit_gate", + "grounding", + "output_form", + ): + assert getattr(a1, field) == getattr(a2, field) + + def test_a2_to_a3_varies_only_grounding(self): + a2, a3 = ARMS["A2"], ARMS["A3"] + assert a2.grounding is False + assert a3.grounding is True + for field in ( + "schema_in_prompt", + "catalogue", + "commit_gate", + "decode_constraint", + "output_form", + ): + assert getattr(a2, field) == getattr(a3, field) + + def test_arm_applies_a_catalogue(self): + condition = arm("A2", ("a.B", "a.C")) + assert condition.catalogue == ("a.B", "a.C") + assert condition.catalogue_size == 2 + + def test_arm_refuses_a_catalogue_on_an_arm_that_offers_none(self): + with pytest.raises(ValueError, match="offers no catalogue"): + arm("A0-json", ("a.B",)) + + def test_unknown_arm_is_refused(self): + with pytest.raises(KeyError, match="unknown arm"): + arm("A4") + + +class TestEnforcement: + def test_no_catalogue_is_not_an_empty_catalogue(self): + """Offering nothing and offering an empty list are different arms.""" + assert typed(catalogue=None).catalogue_size == 0 + assert typed(catalogue=()).catalogue_size == 0 + assert typed(catalogue=None).describe()["catalogue_offered"] is False + assert typed(catalogue=()).describe()["catalogue_offered"] is True + + def test_grounding_without_a_schema_is_refused(self): + with pytest.raises(ValueError, match="needs a schema to ground"): + typed(schema_in_prompt=False, grounding=True) + + def test_prose_cannot_carry_a_decode_constraint(self): + with pytest.raises(ValueError, match="cannot carry a decode-time"): + typed( + output_form=OutputForm.PROSE, + decode_constraint=DecodeConstraint.JSON_SCHEMA, + commit_gate=False, + ) + + def test_prose_cannot_carry_a_commit_gate(self): + with pytest.raises(ValueError, match="no class path to gate"): + typed( + output_form=OutputForm.PROSE, + decode_constraint=DecodeConstraint.NONE, + commit_gate=True, + ) + + def test_with_catalogue_changes_nothing_else(self): + before = typed() + after = before.with_catalogue(("x.Y",) * 50) + assert after.catalogue_size == 50 + for field in ( + "schema_in_prompt", + "decode_constraint", + "commit_gate", + "grounding", + ): + assert getattr(before, field) == getattr(after, field) + + def test_describe_omits_catalogue_contents(self): + described = typed(catalogue=("a.B",) * 900).describe() + assert described["catalogue_size"] == 900 + assert "catalogue" not in described + + def test_is_frozen(self): + with pytest.raises(Exception): + setattr(typed(), "commit_gate", False) # noqa: B010 + + +def test_orchestration_covers_the_three_reference_agents(): + assert [o.value for o in Orchestration] == [ + "recursive", + "segmented", + "multi_step", + ] diff --git a/tests/test_agent/test_provider_profile.py b/tests/test_agent/test_provider_profile.py new file mode 100644 index 0000000..1b2478d2 --- /dev/null +++ b/tests/test_agent/test_provider_profile.py @@ -0,0 +1,218 @@ +"""Per-provider schema preparation. + +Each assertion pins a documented provider limit. If a provider widens its +subset, the test that says so should be the thing that fails. +""" + +import pytest + +from oold.agent import prepare, profile_for, schema_hash + +RECURSIVE = { + "type": "object", + "$defs": { + "Node": { + "type": "object", + "properties": { + "label": {"type": "string"}, + "children": { + "type": "array", + "items": {"$ref": "#/$defs/Node"}, + }, + }, + "required": ["label"], + } + }, + "properties": {"root": {"$ref": "#/$defs/Node"}}, + "required": ["root"], +} + +CONSTRAINED = { + "type": "object", + "properties": { + "name": {"type": "string", "maxLength": 200}, + "count": {"type": "integer", "minimum": 0, "maximum": 10}, + }, + "required": ["name"], +} + +INHERITED = { + "@context": ["Thing.schema.json", {}], + "x-oold-iri": "https://schema.org/Person", + "allOf": [{"$ref": "#/$defs/Thing"}], + "$defs": { + "Thing": { + "type": "object", + "properties": {"name": {"type": "string"}}, + "required": ["name"], + } + }, + "type": "object", + "properties": {"email": {"type": "string", "format": "email"}}, +} + + +def keywords(node, found=None): + found = set() if found is None else found + if isinstance(node, dict): + found.update(node) + for value in node.values(): + keywords(value, found) + elif isinstance(node, list): + for value in node: + keywords(value, found) + return found + + +class TestCombinators: + @pytest.mark.parametrize("provider", ["openai", "anthropic", "google"]) + def test_all_of_never_survives(self, provider): + """allOf is rejected in strict mode by all three.""" + prepared, report = prepare(INHERITED, profile_for(provider)) + assert "allOf" not in keywords(prepared) + assert report.dropped.get("allOf") == 1 + + def test_all_of_merges_the_parent_in(self): + prepared, _ = prepare(INHERITED, profile_for("openai")) + assert set(prepared["properties"]) == {"name", "email"} + + def test_native_keeps_the_schema_intact(self): + prepared, report = prepare(INHERITED, profile_for("native")) + assert "allOf" in keywords(prepared) + assert report.dropped == {} + assert report.semantics_dropped == 0 + + +class TestRecursion: + def test_openai_keeps_a_recursive_ref(self): + prepared, report = prepare(RECURSIVE, profile_for("openai")) + assert "$ref" in keywords(prepared) + assert report.recursion_cut == 0 + + def test_anthropic_cuts_the_cycle(self): + """Anthropic does not support recursive $ref, so it has to end.""" + prepared, report = prepare(RECURSIVE, profile_for("anthropic")) + assert "$ref" not in keywords(prepared) + assert report.recursion_cut >= 1 + + def test_a_cut_schema_is_still_a_schema(self): + prepared, _ = prepare(RECURSIVE, profile_for("anthropic")) + assert prepared["type"] == "object" + assert "root" in prepared["properties"] + + +class TestConstraints: + def test_anthropic_moves_constraints_into_the_description(self): + """Anthropic rejects minimum and maxLength; the SDKs describe them.""" + prepared, report = prepare(CONSTRAINED, profile_for("anthropic")) + assert "maxLength" not in keywords(prepared) + assert "minimum" not in keywords(prepared) + assert "maxLength: 200" in prepared["properties"]["name"]["description"] + assert report.constraints_described == 3 + + def test_openai_keeps_constraints(self): + prepared, report = prepare(CONSTRAINED, profile_for("openai")) + assert "maxLength" in keywords(prepared) + assert report.constraints_described == 0 + + +class TestRequiredAndAdditional: + def test_openai_requires_every_property(self): + prepared, report = prepare(CONSTRAINED, profile_for("openai")) + assert set(prepared["required"]) == {"name", "count"} + assert report.made_required == 1 + + def test_a_property_made_required_becomes_nullable(self): + prepared, _ = prepare(CONSTRAINED, profile_for("openai")) + assert "null" in prepared["properties"]["count"]["type"] + + def test_google_leaves_optional_properties_optional(self): + prepared, report = prepare(CONSTRAINED, profile_for("google")) + assert prepared["required"] == ["name"] + assert report.made_required == 0 + + @pytest.mark.parametrize("provider", ["openai", "anthropic"]) + def test_additional_properties_is_closed(self, provider): + prepared, _ = prepare(CONSTRAINED, profile_for(provider)) + assert prepared["additionalProperties"] is False + + def test_google_does_not_require_a_closed_object(self): + prepared, _ = prepare(CONSTRAINED, profile_for("google")) + assert "additionalProperties" not in prepared + + def test_anthropic_caps_optional_properties_at_24(self): + wide = { + "type": "object", + "properties": {f"p{i}": {"type": "string"} for i in range(40)}, + "required": [], + } + prepared, report = prepare(wide, profile_for("anthropic")) + assert len(prepared["properties"]) == 24 + assert report.dropped["optional-property-overflow"] == 16 + + +class TestGrounding: + def test_grounding_keeps_the_context_and_the_iris(self): + prepared, report = prepare( + INHERITED, profile_for("openai"), grounding=True + ) + assert "@context" in prepared + assert prepared["x-oold-iri"] == "https://schema.org/Person" + assert report.semantics_dropped == 0 + + def test_flattening_removes_them_and_counts_it(self): + prepared, report = prepare( + INHERITED, profile_for("openai"), grounding=False + ) + assert "@context" not in prepared + assert "x-oold-iri" not in prepared + assert report.semantics_dropped == 2 + + def test_grounding_is_the_only_difference_between_the_two(self): + grounded, _ = prepare(INHERITED, profile_for("openai"), grounding=True) + flat, _ = prepare(INHERITED, profile_for("openai"), grounding=False) + for keyword in ("@context", "x-oold-iri"): + grounded.pop(keyword, None) + assert grounded == flat + + +class TestDegradation: + def test_native_loses_nothing(self): + _, report = prepare(INHERITED, profile_for("native")) + assert report.fidelity == pytest.approx(1.0) + + def test_anthropic_loses_more_than_openai(self): + _, strict = prepare(CONSTRAINED, profile_for("anthropic")) + _, lenient = prepare(CONSTRAINED, profile_for("openai")) + assert len(strict.dropped) > len(lenient.dropped) + + def test_the_report_is_serialisable(self): + _, report = prepare(INHERITED, profile_for("anthropic")) + described = report.describe() + assert set(described) >= {"fidelity", "dropped", "semantics_dropped"} + + def test_fidelity_is_one_when_nothing_was_there_to_lose(self): + _, report = prepare({}, profile_for("anthropic")) + assert report.fidelity == 1.0 + + +class TestReproducibility: + def test_preparation_is_deterministic(self): + first, _ = prepare(INHERITED, profile_for("anthropic")) + second, _ = prepare(INHERITED, profile_for("anthropic")) + assert schema_hash(first) == schema_hash(second) + + def test_different_providers_give_different_hashes(self): + a, _ = prepare(CONSTRAINED, profile_for("anthropic")) + b, _ = prepare(CONSTRAINED, profile_for("openai")) + assert schema_hash(a) != schema_hash(b) + + def test_the_input_is_not_mutated(self): + before = dict(CONSTRAINED) + prepare(CONSTRAINED, profile_for("openai")) + assert CONSTRAINED == before + + def test_an_unknown_profile_is_refused_rather_than_guessed(self): + """A model name must never select a profile by substring.""" + with pytest.raises(KeyError, match="unknown provider profile"): + profile_for("gpt-oss-120b") From c9a70c015bb4ec3778d8525232f65c875752bc9e Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sat, 26 Sep 2026 21:13:54 +0200 Subject: [PATCH 02/58] feat(agent): model boundary with per-call token attribution - ChatClient protocol, so the agent depends on a shape and not on an SDK - CallLog records every call with its step, attempt and any failure - cached and reasoning tokens held apart, because they are priced apart - appends are locked, since some orchestrations fan out across threads - agent extra declared, carrying langchain-core and nothing else --- pyproject.toml | 13 + src/oold/agent/__init__.py | 14 + src/oold/agent/client.py | 215 ++++++++++ src/oold/agent/enforcement.py | 16 +- src/oold/agent/langchain_client.py | 93 ++++ src/oold/agent/provider.py | 32 +- tests/test_agent/test_client.py | 187 ++++++++ tests/test_agent/test_provider_profile.py | 10 +- uv.lock | 494 +++++++++++++++++++++- 9 files changed, 1036 insertions(+), 38 deletions(-) create mode 100644 src/oold/agent/client.py create mode 100644 src/oold/agent/langchain_client.py create mode 100644 tests/test_agent/test_client.py diff --git a/pyproject.toml b/pyproject.toml index 7ae4960..82e33bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,6 +63,17 @@ mcp = [ "referencing>=0.30", "click>=8.1", ] +# The agent turns a schema into a validated instance with an LLM. Only the +# bundled client adapter needs anything: the enforcement model and the +# per-provider schema preparation are stdlib, and a consumer that brings its +# own ChatClient implementation needs no extra at all. +# +# langchain-core, not langchain: this is the message and chat-model interface +# only, without the agent framework or any provider package. A consumer +# installs the provider integration it actually uses. +agent = [ + "langchain-core>=0.3", +] UI-panel = [ "panel", "jupyter_bokeh", @@ -100,6 +111,7 @@ all = [ "referencing>=0.30", "click>=8.1", "mcp>=1.2", + "langchain-core>=0.3", ] [dependency-groups] @@ -110,6 +122,7 @@ dev = [ "referencing>=0.30", "click>=8.1", "mcp>=1.2", + "langchain-core>=0.3", "pytest", "pytest-cov>=7.0.0", "pytest-benchmark", diff --git a/src/oold/agent/__init__.py b/src/oold/agent/__init__.py index 1cc1cc3..1e4f876 100644 --- a/src/oold/agent/__init__.py +++ b/src/oold/agent/__init__.py @@ -13,6 +13,14 @@ pip install "oold[agent]" """ +from oold.agent.client import ( + Call, + CallLog, + ChatClient, + ChatResponse, + Message, + TokenUsage, +) from oold.agent.enforcement import ( ARMS, DecodeConstraint, @@ -33,12 +41,18 @@ __all__ = [ "ARMS", "PROFILES", + "Call", + "CallLog", + "ChatClient", + "ChatResponse", "DecodeConstraint", "Degradation", "Enforcement", + "Message", "Orchestration", "OutputForm", "ProviderProfile", + "TokenUsage", "arm", "prepare", "profile_for", diff --git a/src/oold/agent/client.py b/src/oold/agent/client.py new file mode 100644 index 0000000..57b4d8a --- /dev/null +++ b/src/oold/agent/client.py @@ -0,0 +1,215 @@ +"""The boundary between the agent and whatever talks to a model. + +Two things live here. A :class:`ChatClient` protocol, so the agent depends on a +shape rather than on a vendor SDK, and a :class:`CallLog`, so token cost is +attributed to the step that spent it. + +Per-call attribution is not a nicety. A run total cannot separate what the +schema cost from what the instructions cost from what the document cost, which +means the interesting question has to be modelled after the fact instead of +measured. It also hides a whole class of bug, because a counter reset in the +wrong place makes every figure a fraction of the truth while still looking +plausible. +""" + +from __future__ import annotations + +import threading +import time +from contextlib import contextmanager +from dataclasses import dataclass, field +from typing import Any, Iterator, Protocol, Sequence, runtime_checkable + +__all__ = [ + "Call", + "CallLog", + "ChatClient", + "ChatResponse", + "Message", + "TokenUsage", +] + + +@dataclass(frozen=True) +class Message: + role: str + content: str + + +@dataclass(frozen=True) +class TokenUsage: + """Tokens for one call, with the tiers that are priced differently.""" + + input_tokens: int = 0 + output_tokens: int = 0 + cached_input_tokens: int = 0 + """Counted inside ``input_tokens``, not in addition to it. Held separately + because a cached input token costs a fraction of an uncached one, and a + repeated schema prefix is mostly cache hits.""" + reasoning_tokens: int = 0 + """Counted inside ``output_tokens``. Reasoning models bill these.""" + + @property + def total(self) -> int: + return self.input_tokens + self.output_tokens + + @property + def billable_input(self) -> int: + return self.input_tokens - self.cached_input_tokens + + def __add__(self, other: "TokenUsage") -> "TokenUsage": + return TokenUsage( + input_tokens=self.input_tokens + other.input_tokens, + output_tokens=self.output_tokens + other.output_tokens, + cached_input_tokens=( + self.cached_input_tokens + other.cached_input_tokens + ), + reasoning_tokens=self.reasoning_tokens + other.reasoning_tokens, + ) + + def describe(self) -> dict[str, int]: + return { + "input_tokens": self.input_tokens, + "output_tokens": self.output_tokens, + "cached_input_tokens": self.cached_input_tokens, + "reasoning_tokens": self.reasoning_tokens, + "total_tokens": self.total, + } + + +@dataclass(frozen=True) +class ChatResponse: + text: str + parsed: dict[str, Any] | None = None + usage: TokenUsage = field(default_factory=TokenUsage) + raw: Any = None + + +@runtime_checkable +class ChatClient(Protocol): + """What the agent needs from a model, and nothing more. + + Implemented here for LangChain. A benchmark or another consumer can + implement it over any SDK, or over a recording, without this package + growing a dependency on either. + """ + + model: str + + def invoke( + self, + messages: Sequence[Message], + *, + response_format: dict[str, Any] | None = None, + ) -> ChatResponse: ... + + +@dataclass(frozen=True) +class Call: + """One call to a model, as it goes into the result record.""" + + step: str + model: str + usage: TokenUsage + elapsed_s: float + attempt: int = 1 + schema_sha256: str | None = None + """Hash of the schema actually sent, so a result names the bytes the model + saw rather than the schema someone believes it saw.""" + error: str | None = None + + def describe(self) -> dict[str, Any]: + return { + "step": self.step, + "model": self.model, + "attempt": self.attempt, + "elapsed_s": round(self.elapsed_s, 4), + "schema_sha256": self.schema_sha256, + "error": self.error, + **self.usage.describe(), + } + + +class CallLog: + """Every call made during one run, in order. + + Appends are locked because some orchestrations fan out across threads. The + predecessor of this class worked around that with a per-step buffer merged + on the main thread, which was correct for the one step that had it and + silently wrong for the others. + """ + + def __init__(self) -> None: + self._calls: list[Call] = [] + self._lock = threading.Lock() + + def __len__(self) -> int: + return len(self._calls) + + def __iter__(self) -> Iterator[Call]: + return iter(tuple(self._calls)) + + def append(self, call: Call) -> None: + with self._lock: + self._calls.append(call) + + @contextmanager + def timed( + self, + step: str, + model: str, + *, + attempt: int = 1, + schema_sha256: str | None = None, + ) -> Iterator[list[TokenUsage]]: + """Record one call, including one that raises. + + Yields a one-slot list to put the usage into, so a call that fails + still leaves a record with the error on it. A failed attempt that + vanishes from the log makes retries look free. + """ + started = time.monotonic() + sink: list[TokenUsage] = [] + error: str | None = None + try: + yield sink + except Exception as exc: + error = f"{type(exc).__name__}: {exc}" + raise + finally: + self.append( + Call( + step=step, + model=model, + usage=sink[0] if sink else TokenUsage(), + elapsed_s=time.monotonic() - started, + attempt=attempt, + schema_sha256=schema_sha256, + error=error, + ) + ) + + def totals(self) -> TokenUsage: + total = TokenUsage() + for call in self._calls: + total = total + call.usage + return total + + def by_step(self) -> dict[str, TokenUsage]: + """Tokens per step, which is the attribution the run total hides.""" + out: dict[str, TokenUsage] = {} + for call in self._calls: + out[call.step] = out.get(call.step, TokenUsage()) + call.usage + return out + + def describe(self) -> dict[str, Any]: + return { + "calls": [call.describe() for call in self._calls], + "totals": self.totals().describe(), + "by_step": { + step: usage.describe() + for step, usage in sorted(self.by_step().items()) + }, + "n_calls": len(self._calls), + "n_errors": sum(1 for call in self._calls if call.error), + } diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index 1ccc3e0..764d678 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -87,15 +87,10 @@ class Enforcement: def __post_init__(self) -> None: if self.grounding and not self.schema_in_prompt: - raise ValueError( - "grounding needs a schema to ground; " - "set schema_in_prompt when grounding is on" - ) + raise ValueError("grounding needs a schema to ground, so set schema_in_prompt when grounding is on") if self.output_form is OutputForm.PROSE: if self.decode_constraint is not DecodeConstraint.NONE: - raise ValueError( - "prose output cannot carry a decode-time constraint" - ) + raise ValueError("prose output cannot carry a decode-time constraint") if self.commit_gate: raise ValueError("prose output has no class path to gate") @@ -104,7 +99,7 @@ def catalogue_size(self) -> int: """How many classes were offered. Zero when none were.""" return 0 if self.catalogue is None else len(self.catalogue) - def with_catalogue(self, paths: tuple[str, ...] | None) -> "Enforcement": + def with_catalogue(self, paths: tuple[str, ...] | None) -> Enforcement: """The same condition over a different catalogue. This is the one knob a catalogue-weight sweep moves, so it gets a @@ -115,8 +110,9 @@ def with_catalogue(self, paths: tuple[str, ...] | None) -> "Enforcement": def describe(self) -> dict[str, object]: """The condition, for the result record. - Catalogue contents are not included; they are large and belong in a - hash alongside the record. The size is here because it is the variable. + Catalogue contents are not included, because they are large and belong + in a hash alongside the record. The size is here because it is the + variable a sweep moves. """ return { "schema_in_prompt": self.schema_in_prompt, diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py new file mode 100644 index 0000000..c6f2b1a --- /dev/null +++ b/src/oold/agent/langchain_client.py @@ -0,0 +1,93 @@ +"""A :class:`~oold.agent.client.ChatClient` over LangChain. + +One bundled adapter, so the package is usable without writing one, and only +one, so the abstraction stays honest. Provider packages are not declared here, +because a consumer installs the LangChain integration for the provider it uses. + +Requires the ``agent`` extra. +""" + +from __future__ import annotations + +from typing import Any, Sequence + +from langchain_core.language_models import BaseChatModel + +from oold.agent.client import ChatResponse, Message, TokenUsage + +__all__ = ["LangChainClient", "usage_from_message"] + + +def usage_from_message(message: Any) -> TokenUsage: + """Read token counts off a LangChain message. + + LangChain normalises providers into ``usage_metadata``, but the nested + detail dictionaries are optional and differ by provider, so every lookup + is defensive. A provider that reports nothing yields zeros rather than + raising, and a zero total is the signal that a model is uninstrumented. + """ + metadata = getattr(message, "usage_metadata", None) or {} + input_details = metadata.get("input_token_details") or {} + output_details = metadata.get("output_token_details") or {} + return TokenUsage( + input_tokens=int(metadata.get("input_tokens") or 0), + output_tokens=int(metadata.get("output_tokens") or 0), + cached_input_tokens=int(input_details.get("cache_read") or 0), + reasoning_tokens=int(output_details.get("reasoning") or 0), + ) + + +class LangChainClient: + """Adapt a LangChain chat model to the :class:`ChatClient` protocol.""" + + def __init__(self, llm: BaseChatModel, model: str) -> None: + self._llm = llm + self.model = model + """The identifier recorded in the result. Passed in rather than read + off the object, because what a provider calls a model and what a + deployment is named are different strings and the result needs the + one that identifies the weights.""" + + def invoke( + self, + messages: Sequence[Message], + *, + response_format: dict[str, Any] | None = None, + ) -> ChatResponse: + llm: Any = self._llm + parsed: dict[str, Any] | None = None + + if response_format is not None: + structured = llm.with_structured_output( + response_format, include_raw=True + ) + result = structured.invoke( + [(m.role, m.content) for m in messages] + ) + raw = result.get("raw") if isinstance(result, dict) else None + parsing_error = ( + result.get("parsing_error") if isinstance(result, dict) else None + ) + if parsing_error is not None: + raise ValueError( + f"structured output did not parse: {parsing_error}" + ) + parsed = result.get("parsed") if isinstance(result, dict) else None + if parsed is not None and not isinstance(parsed, dict): + parsed = dict(parsed) + text = getattr(raw, "content", "") or "" + return ChatResponse( + text=text if isinstance(text, str) else str(text), + parsed=parsed, + usage=usage_from_message(raw), + raw=raw, + ) + + reply = llm.invoke([(m.role, m.content) for m in messages]) + content = getattr(reply, "content", reply) + return ChatResponse( + text=content if isinstance(content, str) else str(content), + parsed=None, + usage=usage_from_message(reply), + raw=reply, + ) diff --git a/src/oold/agent/provider.py b/src/oold/agent/provider.py index 0811355..3c4a372 100644 --- a/src/oold/agent/provider.py +++ b/src/oold/agent/provider.py @@ -2,11 +2,11 @@ Providers accept different subsets of JSON Schema, so the same OO-LD schema reaches each of them differently. That makes the transform part of the -treatment, not a utility: if one provider is handed a schema that lost its -constraints and another is not, a measured difference between them is partly a -difference between transforms. So the profile is declared in configuration -rather than sniffed from a model name, the prepared schema is hashed into the -result, and what the transform removed is reported as a number. +treatment rather than a utility. If one provider is handed a schema that lost +its constraints and another is not, a measured difference between them is +partly a difference between transforms. So the profile is declared in +configuration rather than sniffed from a model name, the prepared schema is +hashed into the result, and what the transform removed is reported as a number. The combinator flattening follows the approach taken by LiteLLM's ``flatten_top_level_schema_combinators``: merge where merging is sound, and @@ -105,8 +105,8 @@ class ProviderProfile: name: str supports_combinators: bool = False """Whether ``allOf``, ``oneOf`` and ``not`` survive. Only a consumer that - takes arbitrary JSON Schema keywords does; every strict structured-output - mode rejects them.""" + takes arbitrary JSON Schema keywords accepts them, because every strict + structured-output mode rejects all three.""" supports_recursive_ref: bool = True supports_any_of: bool = True supports_numeric_constraints: bool = True @@ -169,7 +169,7 @@ def accepts(self, keyword: str) -> bool: } """Declared subsets. -``native`` sends the schema through unchanged, which is the grounded arm: the +``native`` sends the schema through unchanged, which is the grounded arm. The consumer takes arbitrary JSON Schema keywords and the ``@context`` is carried through as grounding. The others are the strict structured-output subset, and what each of them removes is the reason the two arms can differ. @@ -178,10 +178,7 @@ def accepts(self, keyword: str) -> bool: def profile_for(name: str) -> ProviderProfile: if name not in PROFILES: - raise KeyError( - f"unknown provider profile {name!r}, " - f"expected one of {sorted(PROFILES)}" - ) + raise KeyError(f"unknown provider profile {name!r}, expected one of {sorted(PROFILES)}") return PROFILES[name] @@ -240,9 +237,7 @@ def _close_object(node: dict[str, Any]) -> dict[str, Any]: if profile.requires_additional_properties_false: node["additionalProperties"] = False if profile.requires_all_properties_required and properties: - optional = [ - k for k in properties if k not in node.get("required", []) - ] + optional = [k for k in properties if k not in node.get("required", [])] report.made_required += len(optional) for key in optional: child = properties[key] @@ -278,8 +273,7 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: keep_ref = ( # A consumer that takes arbitrary keywords keeps $defs too, so # there is nothing to inline and nothing is lost. - not inlining - or (recursing and profile.supports_recursive_ref and not too_deep) + not inlining or (recursing and profile.supports_recursive_ref and not too_deep) ) if keep_ref: node["$ref"] = ref @@ -288,9 +282,7 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: report.recursion_cut += 1 return { "type": "string", - "description": node.get( - "description", f"reference to {name}" - ), + "description": node.get("description", f"reference to {name}"), } report.refs_inlined += 1 resolved = walk(defs[name], (*seen, name), depth + 1) diff --git a/tests/test_agent/test_client.py b/tests/test_agent/test_client.py new file mode 100644 index 0000000..f865566 --- /dev/null +++ b/tests/test_agent/test_client.py @@ -0,0 +1,187 @@ +"""The model boundary and per-call token attribution.""" + +import threading + +import pytest + +from oold.agent import Call, CallLog, ChatClient, ChatResponse, Message, TokenUsage + + +class FakeClient: + """A ChatClient that never talks to anything.""" + + model = "fake-1" + + def __init__(self, usage: TokenUsage | None = None) -> None: + self.usage = usage or TokenUsage(input_tokens=100, output_tokens=10) + self.calls: list[tuple[Message, ...]] = [] + + def invoke(self, messages, *, response_format=None) -> ChatResponse: + self.calls.append(tuple(messages)) + return ChatResponse(text="ok", parsed=None, usage=self.usage) + + +class TestTokenUsage: + def test_cached_input_is_inside_input_not_added_to_it(self): + usage = TokenUsage(input_tokens=1000, cached_input_tokens=900) + assert usage.total == 1000 + assert usage.billable_input == 100 + + def test_usage_adds(self): + total = TokenUsage(input_tokens=10, output_tokens=1) + TokenUsage( + input_tokens=20, output_tokens=2, cached_input_tokens=5 + ) + assert total.input_tokens == 30 + assert total.output_tokens == 3 + assert total.cached_input_tokens == 5 + + def test_an_uninstrumented_client_reports_zero_rather_than_guessing(self): + assert TokenUsage().total == 0 + + def test_describe_carries_every_tier(self): + described = TokenUsage(1, 2, 3, 4).describe() + assert set(described) == { + "input_tokens", + "output_tokens", + "cached_input_tokens", + "reasoning_tokens", + "total_tokens", + } + + +class TestCallLog: + def test_totals_sum_every_call(self): + log = CallLog() + for step in ("detect", "extract", "construct"): + log.append( + Call( + step=step, + model="m", + usage=TokenUsage(input_tokens=100, output_tokens=5), + elapsed_s=0.1, + ) + ) + assert len(log) == 3 + assert log.totals().input_tokens == 300 + + def test_by_step_separates_what_the_run_total_hides(self): + log = CallLog() + log.append( + Call("detect", "m", TokenUsage(input_tokens=8000), 0.1) + ) + log.append( + Call("extract", "m", TokenUsage(input_tokens=500), 0.1) + ) + by_step = log.by_step() + assert by_step["detect"].input_tokens == 8000 + assert by_step["extract"].input_tokens == 500 + + def test_timed_records_the_usage_put_into_the_sink(self): + log = CallLog() + with log.timed("detect", "m", schema_sha256="abc") as sink: + sink.append(TokenUsage(input_tokens=42)) + call = next(iter(log)) + assert call.usage.input_tokens == 42 + assert call.schema_sha256 == "abc" + assert call.error is None + assert call.elapsed_s >= 0 + + def test_a_failed_call_still_leaves_a_record(self): + """A retry that vanishes from the log makes retries look free.""" + log = CallLog() + with pytest.raises(RuntimeError): + with log.timed("extract", "m"): + raise RuntimeError("provider said no") + call = next(iter(log)) + assert call.error == "RuntimeError: provider said no" + assert call.usage.total == 0 + + def test_attempts_are_recorded_separately(self): + log = CallLog() + for attempt in (1, 2, 3): + log.append( + Call("construct", "m", TokenUsage(input_tokens=10), 0.1, attempt) + ) + assert [c.attempt for c in log] == [1, 2, 3] + assert log.totals().input_tokens == 30 + + def test_appends_from_several_threads_all_arrive(self): + """Some orchestrations fan out; a lost append is a silent undercount.""" + log = CallLog() + + def work(): + for _ in range(50): + log.append( + Call("parallel", "m", TokenUsage(input_tokens=1), 0.0) + ) + + threads = [threading.Thread(target=work) for _ in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert len(log) == 400 + assert log.totals().input_tokens == 400 + + def test_describe_counts_errors(self): + log = CallLog() + log.append(Call("a", "m", TokenUsage(), 0.1)) + log.append(Call("b", "m", TokenUsage(), 0.1, error="boom")) + described = log.describe() + assert described["n_calls"] == 2 + assert described["n_errors"] == 1 + assert set(described["by_step"]) == {"a", "b"} + + +class TestProtocol: + def test_a_plain_object_satisfies_the_protocol(self): + assert isinstance(FakeClient(), ChatClient) + + def test_the_agent_needs_no_sdk_to_be_exercised(self): + client = FakeClient() + reply = client.invoke([Message(role="user", content="hello")]) + assert reply.text == "ok" + assert reply.usage.input_tokens == 100 + + +class TestLangChainAdapter: + def test_usage_is_read_off_a_langchain_message(self): + adapter = pytest.importorskip( + "oold.agent.langchain_client", + reason="the agent extra is not installed", + ) + + class Reply: + usage_metadata = { + "input_tokens": 1200, + "output_tokens": 80, + "input_token_details": {"cache_read": 1000}, + "output_token_details": {"reasoning": 40}, + } + + usage = adapter.usage_from_message(Reply()) + assert usage.input_tokens == 1200 + assert usage.cached_input_tokens == 1000 + assert usage.reasoning_tokens == 40 + assert usage.billable_input == 200 + + def test_a_provider_reporting_nothing_yields_zeros(self): + adapter = pytest.importorskip( + "oold.agent.langchain_client", + reason="the agent extra is not installed", + ) + assert adapter.usage_from_message(object()).total == 0 + + def test_missing_detail_dictionaries_do_not_raise(self): + adapter = pytest.importorskip( + "oold.agent.langchain_client", + reason="the agent extra is not installed", + ) + + class Reply: + usage_metadata = {"input_tokens": 10, "output_tokens": 2} + + usage = adapter.usage_from_message(Reply()) + assert usage.total == 12 + assert usage.cached_input_tokens == 0 diff --git a/tests/test_agent/test_provider_profile.py b/tests/test_agent/test_provider_profile.py index 1b2478d2..52672fd 100644 --- a/tests/test_agent/test_provider_profile.py +++ b/tests/test_agent/test_provider_profile.py @@ -153,17 +153,13 @@ def test_anthropic_caps_optional_properties_at_24(self): class TestGrounding: def test_grounding_keeps_the_context_and_the_iris(self): - prepared, report = prepare( - INHERITED, profile_for("openai"), grounding=True - ) + prepared, report = prepare(INHERITED, profile_for("openai"), grounding=True) assert "@context" in prepared assert prepared["x-oold-iri"] == "https://schema.org/Person" assert report.semantics_dropped == 0 def test_flattening_removes_them_and_counts_it(self): - prepared, report = prepare( - INHERITED, profile_for("openai"), grounding=False - ) + prepared, report = prepare(INHERITED, profile_for("openai"), grounding=False) assert "@context" not in prepared assert "x-oold-iri" not in prepared assert report.semantics_dropped == 2 @@ -210,7 +206,7 @@ def test_different_providers_give_different_hashes(self): def test_the_input_is_not_mutated(self): before = dict(CONSTRAINED) prepare(CONSTRAINED, profile_for("openai")) - assert CONSTRAINED == before + assert before == CONSTRAINED def test_an_unknown_profile_is_refused_rather_than_guessed(self): """A model name must never select a profile by substring.""" diff --git a/uv.lock b/uv.lock index 45a22b1..5f12f22 100644 --- a/uv.lock +++ b/uv.lock @@ -1068,6 +1068,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/02/08/9c41fb51ab5b43eb21674aff13df270e8ba6c4b29c8624e328dc7a9482af/distlib-0.4.3-py2.py3-none-any.whl", hash = "sha256:4b0ce306c966eb73bc3a7b6abad017c556dadd92c44701562cd528ac7fde4d5b", size = 470628, upload-time = "2026-06-12T08:04:50.506Z" }, ] +[[package]] +name = "distro" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722, upload-time = "2023-12-24T09:54:32.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, +] + [[package]] name = "docutils" version = "0.23" @@ -1790,6 +1799,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/94/a8066f84d62ab666d61ef97deba1a33126e3e5c0c0da2c458ada17053ed6/jsondiff-2.2.1-py3-none-any.whl", hash = "sha256:b1f0f7e2421881848b1d556d541ac01a91680cfcc14f51a9b62cdf4da0e56722", size = 13440, upload-time = "2024-08-29T04:09:04.955Z" }, ] +[[package]] +name = "jsonpatch" +version = "1.33" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonpointer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/42/78/18813351fe5d63acad16aec57f94ec2b70a09e53ca98145589e185423873/jsonpatch-1.33.tar.gz", hash = "sha256:9fcd4009c41e6d12348b4a0ff2563ba56a2923a7dfee731d004e212e1ee5030c", size = 21699, upload-time = "2023-06-26T12:07:29.144Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/07/02e16ed01e04a374e644b575638ec7987ae846d25ad97bcc9945a3ee4b0e/jsonpatch-1.33-py2.py3-none-any.whl", hash = "sha256:0ae28c0cd062bbd8b8ecc26d7d164fbbea9652a1a3693f3b956c1eae5145dade", size = 12898, upload-time = "2023-06-16T21:01:28.466Z" }, +] + [[package]] name = "jsonpointer" version = "3.1.1" @@ -1892,6 +1913,64 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ab/b5/36c712098e6191d1b4e349304ef73a8d06aed77e56ceaac8c0a306c7bda1/jupyterlab_widgets-3.0.16-py3-none-any.whl", hash = "sha256:45fa36d9c6422cf2559198e4db481aa243c7a32d9926b500781c830c80f7ecf8", size = 914926, upload-time = "2025-11-01T21:11:28.008Z" }, ] +[[package]] +name = "langchain-core" +version = "1.6.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "httpx" }, + { name = "jsonpatch" }, + { name = "langchain-protocol" }, + { name = "langsmith" }, + { name = "packaging" }, + { name = "pydantic" }, + { name = "pyyaml" }, + { name = "tenacity" }, + { name = "typing-extensions" }, + { name = "uuid-utils" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ed/ed/ceecd3bfcfc77a94cf30a9f1506e907fdea447458825e01914a72d2d1a6f/langchain_core-1.6.5.tar.gz", hash = "sha256:bdb059fef65473fd444558dbb18f50901657402c43ceed9dc0fdc7b76a393c6b", size = 1007041, upload-time = "2026-09-24T18:11:06.487Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/59/68/447ac7e734990b7ed9dcfc3b6dee9a4cd4d4169e296429fa71a9a47c1c7b/langchain_core-1.6.5-py3-none-any.whl", hash = "sha256:54c7b0e9314b9084fb04405bb33dc5d32986d512d92b7b8863899cd5f6267556", size = 572136, upload-time = "2026-09-24T18:11:04.837Z" }, +] + +[[package]] +name = "langchain-protocol" +version = "0.0.19" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/14/56/913599f2f9cec8524868929f12d72b2ede377a6056ca8a40a32bdadfa535/langchain_protocol-0.0.19.tar.gz", hash = "sha256:79d90a1425122ac87e8052e2ec054fbd09c3edbf341bdfb6397112a495c7bf8c", size = 6265, upload-time = "2026-08-26T21:12:00.703Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/80/c9/f6cbf357d48ccbd18bb394433b1fd7ad9be004eed9377ad08bb85777e5e6/langchain_protocol-0.0.19-py3-none-any.whl", hash = "sha256:4cdf879a492a35980fd859ae792d3c65458ccaae504e183c9a10d7eac1f0720f", size = 7327, upload-time = "2026-08-26T21:11:59.781Z" }, +] + +[[package]] +name = "langsmith" +version = "0.14.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "distro" }, + { name = "httpx2" }, + { name = "orjson", marker = "platform_python_implementation != 'PyPy'" }, + { name = "packaging" }, + { name = "pydantic" }, + { name = "requests" }, + { name = "requests-toolbelt" }, + { name = "sniffio" }, + { name = "typing-extensions" }, + { name = "uuid-utils" }, + { name = "websockets" }, + { name = "xxhash" }, + { name = "zstandard" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/96/23/ba753811d6d768f4d98d0336ba49c2b3021afeeaa59a8f63ab83bf83efe7/langsmith-0.14.1.tar.gz", hash = "sha256:0b5cd2473420c9c5acef33a9bafe6c812a7cf96741e9a5af465b1d93bf77f7ae", size = 4966485, upload-time = "2026-09-25T17:38:08.216Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/d6/1771421302dd230d3e52f29546b187cda824cff1443031067b69d46207ee/langsmith-0.14.1-py3-none-any.whl", hash = "sha256:dcfd8a25ba72d8663024bd87df02e372e470f43e18f4a726f37fbacc772c0193", size = 812092, upload-time = "2026-09-25T17:38:05.704Z" }, +] + [[package]] name = "lark" version = "1.3.1" @@ -2744,6 +2823,9 @@ dependencies = [ ] [package.optional-dependencies] +agent = [ + { name = "langchain-core" }, +] all = [ { name = "anywidget" }, { name = "click" }, @@ -2752,6 +2834,7 @@ all = [ { name = "ipython", version = "9.14.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "jsonschema", extra = ["format-nongpl"] }, { name = "jupyter-bokeh" }, + { name = "langchain-core" }, { name = "mcp" }, { name = "nicegui" }, { name = "panel" }, @@ -2803,6 +2886,7 @@ dev = [ { name = "deptry" }, { name = "jsondiff" }, { name = "jsonschema", extra = ["format-nongpl"] }, + { name = "langchain-core" }, { name = "mcp" }, { name = "mkdocstrings-python" }, { name = "panel" }, @@ -2841,6 +2925,8 @@ requires-dist = [ { name = "jupyter-bokeh", marker = "extra == 'all'" }, { name = "jupyter-bokeh", marker = "extra == 'ui'" }, { name = "jupyter-bokeh", marker = "extra == 'ui-panel'" }, + { name = "langchain-core", marker = "extra == 'agent'", specifier = ">=0.3" }, + { name = "langchain-core", marker = "extra == 'all'", specifier = ">=0.3" }, { name = "mcp", marker = "extra == 'all'", specifier = ">=1.2" }, { name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.2" }, { name = "nicegui", marker = "extra == 'all'" }, @@ -2865,7 +2951,7 @@ requires-dist = [ { name = "traitlets", marker = "extra == 'ui-jupyter'" }, { name = "typing-extensions" }, ] -provides-extras = ["validation", "mcp", "ui-panel", "ui-jupyter", "ui-nicegui", "ui", "all"] +provides-extras = ["validation", "mcp", "agent", "ui-panel", "ui-jupyter", "ui-nicegui", "ui", "all"] [package.metadata.requires-dev] dev = [ @@ -2873,6 +2959,7 @@ dev = [ { name = "deptry", specifier = ">=0.25.1" }, { name = "jsondiff" }, { name = "jsonschema", extras = ["format-nongpl"], specifier = ">=4.20" }, + { name = "langchain-core", specifier = ">=0.3" }, { name = "mcp", specifier = ">=1.2" }, { name = "mkdocstrings-python", specifier = ">=1.0.3" }, { name = "panel" }, @@ -4672,6 +4759,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, ] +[[package]] +name = "sniffio" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372, upload-time = "2024-02-25T23:20:04.057Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, +] + [[package]] name = "sparqlwrapper" version = "2.0.0" @@ -4724,6 +4820,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" }, ] +[[package]] +name = "tenacity" +version = "9.1.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/47/c6/ee486fd809e357697ee8a44d3d69222b344920433d3b6666ccd9b374630c/tenacity-9.1.4.tar.gz", hash = "sha256:adb31d4c263f2bd041081ab33b498309a57c77f9acf2db65aadf0898179cf93a", size = 49413, upload-time = "2026-02-07T10:45:33.841Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d7/c1/eb8f9debc45d3b7918a32ab756658a0904732f75e555402972246b0b8e71/tenacity-9.1.4-py3-none-any.whl", hash = "sha256:6095a360c919085f28c6527de529e76a06ad89b23659fa881ae0649b867a9d55", size = 28926, upload-time = "2026-02-07T10:45:32.24Z" }, +] + [[package]] name = "text-unidecode" version = "1.3" @@ -5007,6 +5112,107 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, ] +[[package]] +name = "uuid-utils" +version = "0.17.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4c/80/cf6934a2030a5f6763f604314c1105f851d90aa1fe344c2692c3b88a9d95/uuid_utils-0.17.1.tar.gz", hash = "sha256:10c51d54ecdf0617640e505eae6d2e6443d8e414d4f9d6e8d43949a450c56e6b", size = 43323, upload-time = "2026-09-08T11:29:35.42Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/db/af/bfe6e67693597361a65daaa37029c489b24e3302c2f7a676e8e5b0eb20ac/uuid_utils-0.17.1-cp310-cp310-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:53abc29fcfa4cdbf53988409f297fce76a8de6ad292115f5e48ff5e9e3606d79", size = 563706, upload-time = "2026-09-08T11:27:33.172Z" }, + { url = "https://files.pythonhosted.org/packages/9e/8d/a367d0eefe3730763ba22bf4b966a94106328cfd01980844c7fb8a6a7082/uuid_utils-0.17.1-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:ee8dbeb24fa796f091658d5692c0e00f0d524db25e1f7a816933e80b6cd3883c", size = 287312, upload-time = "2026-09-08T11:27:34.794Z" }, + { url = "https://files.pythonhosted.org/packages/c3/f7/f085bedf0601e7a3aca57748059f96ae118c41a4615cfc0142f291bde481/uuid_utils-0.17.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:87b3cccf71cbe4c1fe29eb007005cde2f86fda2549a5f412e27ee8579a264d27", size = 325354, upload-time = "2026-09-08T11:27:36.21Z" }, + { url = "https://files.pythonhosted.org/packages/f0/cd/a8c8c93aa533173a2078496b58ade7233fcca124fb77c68fd9053fe59f76/uuid_utils-0.17.1-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c3aae364b97bed00db4549784ab5ba769a7b88d0ceea87adb833501624fe16ed", size = 332982, upload-time = "2026-09-08T11:27:37.467Z" }, + { url = "https://files.pythonhosted.org/packages/0d/c6/e6eb694ffa73d627ec7c4c750f2e83506c6671898c2cbc5a3592f4366f7d/uuid_utils-0.17.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5141fc9cfc98d3802d6f1c2451e6822bf1d474c9beba7cba0a6fee7643dee46f", size = 449247, upload-time = "2026-09-08T11:27:38.833Z" }, + { url = "https://files.pythonhosted.org/packages/76/6b/516183ba5f7d35521edf8cfaea9b1192da8b262587faa8106d1f73ab0eb1/uuid_utils-0.17.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:66f695b0950a630ce5f287d6d17acd1523e0e071863596bed73a7d11b8334a28", size = 327796, upload-time = "2026-09-08T11:27:40.061Z" }, + { url = "https://files.pythonhosted.org/packages/61/cf/656e7426b31c9cdf9205797a80f3d0458da061df91f083e4490504e0428a/uuid_utils-0.17.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b7db3135ee5c1e9bbfd4d11cb2e3f2b4c26c37cb1f7b7d52407dbe94dddaec7e", size = 351941, upload-time = "2026-09-08T11:27:41.31Z" }, + { url = "https://files.pythonhosted.org/packages/f1/a2/ab5082c9d0b1d2b8b32ac2556cb7b1d5c73d316fe59934bf2b3545134844/uuid_utils-0.17.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:b6e71cff84184aa6071fdcc45e288e0f45d663a4cf5608fb9091b68c34bfd959", size = 503475, upload-time = "2026-09-08T11:27:42.609Z" }, + { url = "https://files.pythonhosted.org/packages/66/b7/3d011f832aad5fc2eaf6999f88a4fedbb0eee0fca6b94223e95b7c986a01/uuid_utils-0.17.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:548b33dddedefe5cd02e4ac421b7b3b3ad5411bdbd7f5b5f792d9e7ba288d894", size = 608768, upload-time = "2026-09-08T11:27:44.157Z" }, + { url = "https://files.pythonhosted.org/packages/0f/16/a89f6b38daef94ee8a1261f7941d7d9d2f70f2eb2b2157445c0e70a81302/uuid_utils-0.17.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:dfd27f383ecf1559cc55b6ec39c850744abee56c0549b15149e20a8aa6b881f3", size = 568410, upload-time = "2026-09-08T11:27:45.546Z" }, + { url = "https://files.pythonhosted.org/packages/c4/32/a7d045221b08858fbdc66321f482b68017f421abdf085b82282bd3019d29/uuid_utils-0.17.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b4edcb1c9e52805a7619d68f8f673544a3df09425e2426bcdc30d17a2bb152e0", size = 533150, upload-time = "2026-09-08T11:27:46.843Z" }, + { url = "https://files.pythonhosted.org/packages/d2/c6/79d7c1ed7a872a1047df30650a8194865273e2f5b757c0e84f683ea640e5/uuid_utils-0.17.1-cp310-cp310-win32.whl", hash = "sha256:5e1b7aec35ee0dbb3875a3f151866f3362ef30ae5e7f95a42adf8779d305bb47", size = 172247, upload-time = "2026-09-08T11:27:48.173Z" }, + { url = "https://files.pythonhosted.org/packages/f2/24/d8b81080e0f21e29fe75545ea318985acb3e079c0aabedceded7424ae6c2/uuid_utils-0.17.1-cp310-cp310-win_amd64.whl", hash = "sha256:f2e91fef913d654f643ba7e4f92347002aff0debeb84cccaf474912756b43a9c", size = 179050, upload-time = "2026-09-08T11:27:49.459Z" }, + { url = "https://files.pythonhosted.org/packages/f8/74/61cc613cf7c94131b2d1d596c4f2c0ec22c804b2852cc740288a1519743f/uuid_utils-0.17.1-cp311-cp311-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:e698d0ffccf167ece87c864667ab69724685af9e171fc51e57038c9711fd4e0a", size = 562905, upload-time = "2026-09-08T11:27:50.715Z" }, + { url = "https://files.pythonhosted.org/packages/eb/4a/88413c15de714a76e342321d65ff82937a2bdcc35e2987c9462433025101/uuid_utils-0.17.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:d9aa5fccd372580d455ab769a60326c789c46027d3d58ff2a895dbc492200b0d", size = 286703, upload-time = "2026-09-08T11:27:52.108Z" }, + { url = "https://files.pythonhosted.org/packages/23/4f/9cfd9f64ceab2b6aeff77cd238b0033baa6364832cc9715d13a8cd49e5ff/uuid_utils-0.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f0cb9661bc0883e9278bc2436514298ace83121d14296cc672b2c44d37441cd0", size = 325258, upload-time = "2026-09-08T11:27:53.315Z" }, + { url = "https://files.pythonhosted.org/packages/42/eb/7057247670b903194c2739f98a0f4455f0d4e8cfa13466dde2d1fdba7216/uuid_utils-0.17.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f63557d6e9fe10cb25c1d3e73dbf7cd18c1b1620349b6be6b51ea25fcadf3a1e", size = 333013, upload-time = "2026-09-08T11:27:54.535Z" }, + { url = "https://files.pythonhosted.org/packages/6b/6d/8e26ef16da28274d3ddfe0812a7155dc8d48d0891abd84f2b1a3f905a54a/uuid_utils-0.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b94f1185f64d1fd2fa99ffc0b8264ee5980a862010daf1edf430412044f2aa53", size = 450348, upload-time = "2026-09-08T11:27:55.777Z" }, + { url = "https://files.pythonhosted.org/packages/e6/8d/70d8f78830ca23f40d15f95795a863e7c052f5c1dff2e4a23f51c53dfbdc/uuid_utils-0.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3404d50a60ec74642fd590b9d639d98770022f4b1ff8a4055b3c70742c85f096", size = 327961, upload-time = "2026-09-08T11:27:57.098Z" }, + { url = "https://files.pythonhosted.org/packages/af/f2/62ab19bc908ef6cdb2a07966a408cf8bc2cf981cd7c3c99dc34f443b5ced/uuid_utils-0.17.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:601d03cce6b8ec3734025c7dca9ab276df1ab649ca7b13d76ea03824724f5108", size = 352645, upload-time = "2026-09-08T11:27:58.262Z" }, + { url = "https://files.pythonhosted.org/packages/7f/86/f8e62e055f14b45b6faa784008a038407f9274d36acc41d39b4b8b0f00a1/uuid_utils-0.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1a9e8c876a5d6247572e7f8eace39b4de9a91cd1b026e24552ec631c08c91394", size = 503128, upload-time = "2026-09-08T11:27:59.678Z" }, + { url = "https://files.pythonhosted.org/packages/04/57/4bc764249cc0d40568fb3a82a72b41cedf958a169710415148e365f45e1f/uuid_utils-0.17.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:304497d360e9ca5b019254bb25a2ee886b66de884aa08a949c8812fe5bf5327f", size = 608575, upload-time = "2026-09-08T11:28:01.01Z" }, + { url = "https://files.pythonhosted.org/packages/f7/90/947976eeaf48aa6109100af1796931b8c684caf680d0fb4d2498e951c059/uuid_utils-0.17.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:7f3deaca1ba34f48da053884c1255c360fb123c4a9bc3815c05a7a8093e0bda5", size = 569118, upload-time = "2026-09-08T11:28:02.321Z" }, + { url = "https://files.pythonhosted.org/packages/a1/fc/18154e589f0c84f85b99aee9406fdf904468190a4f4fe462d86bd85ab960/uuid_utils-0.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e22cf24db33a123c8e47a86fe766c770c83dedc6d1196c1172cbba0a0959cac0", size = 533401, upload-time = "2026-09-08T11:28:03.631Z" }, + { url = "https://files.pythonhosted.org/packages/7f/73/ef0bb542317ac03fc4e0e7e2804e316d84fee115c6a3ed41a6efa954b59b/uuid_utils-0.17.1-cp311-cp311-win32.whl", hash = "sha256:738b8fc2062c3dc17f1624af4aa8763bec4172cf295b13ffa3dfad3ddbdb4e0e", size = 172366, upload-time = "2026-09-08T11:28:04.977Z" }, + { url = "https://files.pythonhosted.org/packages/f4/1f/c76187e05e0fdbb3f9fef7436f86326d0f0aa25b42192cddc011997b31a7/uuid_utils-0.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:297c6be22e0dd0f7d372845b171ffee5657581759982413c0a5b01b900c5f592", size = 178735, upload-time = "2026-09-08T11:28:06.215Z" }, + { url = "https://files.pythonhosted.org/packages/92/05/3d846d5423571574a1e6f4bbe16f57f755671d0f334931f893e8a734bbaa/uuid_utils-0.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:1c8124c9b91fa8353d79e4e7bd44ed0f2ae683990c01818199668f7579e236ab", size = 176492, upload-time = "2026-09-08T11:28:07.368Z" }, + { url = "https://files.pythonhosted.org/packages/97/82/a509ef8b3c24b48099a4fba00f9e1b3f38417e0a7bda39cefd4b1e841388/uuid_utils-0.17.1-cp312-cp312-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:7558c84414785d6ea54a186a3c68267eb8f33e2a0d792698bd9fa50d62150f77", size = 557142, upload-time = "2026-09-08T11:28:08.586Z" }, + { url = "https://files.pythonhosted.org/packages/27/60/d48897c1bb6562c4b68a90c998f89d4eb8996d01193c930b3f6f04258619/uuid_utils-0.17.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:4f04ba62482858a975d1d38cbb5ade181faae59e8ddc1499eacc9b6b6def3115", size = 287053, upload-time = "2026-09-08T11:28:10.12Z" }, + { url = "https://files.pythonhosted.org/packages/c0/9d/6506e6c4ca08300ad7415c3b76e29bd36b491dec818ea58d9e8bf88031d3/uuid_utils-0.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:66ce3e84067261b2721dde6539427f4eb9286289769332ff07c859a661f87694", size = 320760, upload-time = "2026-09-08T11:28:11.3Z" }, + { url = "https://files.pythonhosted.org/packages/2c/dd/013786821eca0808282b82bb1e66a18a6b70061e1ce2f77fc9be06b88a36/uuid_utils-0.17.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4cdcb565ac4d8a005833e7c389867977e19670f1bee6ee9f8811872b86225274", size = 329130, upload-time = "2026-09-08T11:28:12.522Z" }, + { url = "https://files.pythonhosted.org/packages/60/45/ba376e0a69eb4a0bb2dfba1ad2bafc2e6729971d480701cc778719a4205d/uuid_utils-0.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7a93b046552730b843e9d8784691cf8b0b3d5430dd9d053ade33383ccb2574ff", size = 444047, upload-time = "2026-09-08T11:28:13.938Z" }, + { url = "https://files.pythonhosted.org/packages/02/1e/2abb7d9e3062a7889142818e2a2ae758a54a1c3b6cf8a86877e051b3d1dc/uuid_utils-0.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d45f93f362d39f63ba14bbd9e4e1dd89fbed4de9bbef6bb428a379bd86571da2", size = 323927, upload-time = "2026-09-08T11:28:15.235Z" }, + { url = "https://files.pythonhosted.org/packages/20/00/c6753d6f2dbcd9d78436e291534b5d81f42c1b50c4d3224ddf231095fde2/uuid_utils-0.17.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d0d847fb9b46b5c208f3b8d5ca6082a4ac819ec2ffe36de3548c489e8fa551bd", size = 345877, upload-time = "2026-09-08T11:28:16.62Z" }, + { url = "https://files.pythonhosted.org/packages/c2/78/6f65d3105a0588b38cdcf338397bcb63c2d88d3581698a316def47e4445e/uuid_utils-0.17.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:71f7ec7a1b54c1f84d6f8fd4e1110a66b3d1b936dbb17cda2927442621fc1e3d", size = 499635, upload-time = "2026-09-08T11:28:17.912Z" }, + { url = "https://files.pythonhosted.org/packages/e9/5b/ff56d55fde9991c332e6df2ac1c560be6dd7e2302ab51180a185cfad830d/uuid_utils-0.17.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:a140db8866a45b1ce40d91164ff48d2722ffc3b2a39bfdb412bd770c7ea88be3", size = 605502, upload-time = "2026-09-08T11:28:19.198Z" }, + { url = "https://files.pythonhosted.org/packages/09/16/d34f26cd4dad48671c7441fcf370076911dd9e7edcb3e5264e11da7fce7d/uuid_utils-0.17.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:7b296b67bf880085daa11ee496d385b941a3bf3e3d5691db7178d21f18f56f9b", size = 563186, upload-time = "2026-09-08T11:28:20.684Z" }, + { url = "https://files.pythonhosted.org/packages/ff/ef/b9bd9b412865c08e6769044cdda6e0a3db4827c88a4a2612e42e68714ca2/uuid_utils-0.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:61378863a5e9410fa6e816364442b9d35cccf94fa83e3f67997d0ff57d901d0e", size = 528667, upload-time = "2026-09-08T11:28:21.984Z" }, + { url = "https://files.pythonhosted.org/packages/e9/b6/981a84e9d0653e2d5fc205ba2b895d80c8e3bdb7138995f4c04b7cce8bd8/uuid_utils-0.17.1-cp312-cp312-win32.whl", hash = "sha256:a550b3963960012ff3266bdb3079abf4cc3f6363201e63a649d5d3cd44fe52cd", size = 169155, upload-time = "2026-09-08T11:28:23.427Z" }, + { url = "https://files.pythonhosted.org/packages/fb/49/85a39cef2de6948364d25f5e1452119e6a70ddb5a910eeac717f02c5eabf/uuid_utils-0.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:3d6ccaebaa3b2ff2e59d11d70c64e97ba572120162a00c25d6f8e5e0c1004b9a", size = 175220, upload-time = "2026-09-08T11:28:24.582Z" }, + { url = "https://files.pythonhosted.org/packages/e0/f6/8c1c11bbf7cfa901c7c9621bcdcbb4bf432c5f20dce27e76a3ea29f0307a/uuid_utils-0.17.1-cp312-cp312-win_arm64.whl", hash = "sha256:3ca89347a01ddac94727578369feacc0969d9fc033b2c17ff7919121ee441e2f", size = 172646, upload-time = "2026-09-08T11:28:25.723Z" }, + { url = "https://files.pythonhosted.org/packages/03/0d/4c2263a05e95dc11a5c9fad78ab9ac5f76a1f5aaabb545a39c6d34d2a07b/uuid_utils-0.17.1-cp313-cp313-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:cd8043ac6d81b3f3f0dff22247866292c819e0d5e54a5a3ad2223f86f88dbd97", size = 556923, upload-time = "2026-09-08T11:28:26.974Z" }, + { url = "https://files.pythonhosted.org/packages/9e/70/9f619e86af674b8055adb29e6ad95f1d2bdec02b9d7b654d01fb479ea9ac/uuid_utils-0.17.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:586a93993769873c389d38bd9a70c51e228e734e8f78742d959610509635b86b", size = 286572, upload-time = "2026-09-08T11:28:28.265Z" }, + { url = "https://files.pythonhosted.org/packages/1e/d2/bf4c39c283a75a8893d060344b690d5ff13ddd7e65849a74a264bec9a4ee/uuid_utils-0.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55e2cec52e2c78d94277d4c990badd3ce97f5746d05029e63d81fb2433bc9684", size = 321366, upload-time = "2026-09-08T11:28:29.464Z" }, + { url = "https://files.pythonhosted.org/packages/d3/a3/4790fd4d6322aeb935e2222d193407902b2651dbb5eae7817f2f8eb2043e/uuid_utils-0.17.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:0721f05b4f10cc7d49d91be65524a3bc6e6a5d88be054cdca05dff487a022091", size = 329210, upload-time = "2026-09-08T11:28:30.738Z" }, + { url = "https://files.pythonhosted.org/packages/66/f9/442d13050fb55c2e4cc81369df349d60f2da8dde84ffb7e330385c576bc3/uuid_utils-0.17.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de996e58b77d3e6eeee1a209ce93f424a5f021aa8b2879df6d35eda601acc831", size = 441731, upload-time = "2026-09-08T11:28:31.966Z" }, + { url = "https://files.pythonhosted.org/packages/63/96/deded55ce54c5e6a2b7dbb790ab9bf7b5be8c7e8cb22e2355108bd8723cd/uuid_utils-0.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:01d9209d6fed20226af0d29b95c5e253a1907b61f1a00153187ac5412f1df9b6", size = 323874, upload-time = "2026-09-08T11:28:33.249Z" }, + { url = "https://files.pythonhosted.org/packages/0f/f8/4b9d64b57bf35e3e99a8e578ed1cbdcdf926816f36bf5e5b53d7ea4c65bb/uuid_utils-0.17.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a4f6b05598d0d29e8851b7668786b7cf105c98887c7ca36dac94c61321d16cb1", size = 346026, upload-time = "2026-09-08T11:28:34.516Z" }, + { url = "https://files.pythonhosted.org/packages/e8/da/8912e887f5eeeb8f44f50f1aac4c16852644b558b1b29846b14463f9b739/uuid_utils-0.17.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f9f9f6835ab3163818156022c627eda60c38c874b369642b249b483384021743", size = 500023, upload-time = "2026-09-08T11:28:35.906Z" }, + { url = "https://files.pythonhosted.org/packages/73/0b/c15c3f5006c3f89818cbe796e73f9a1927867ec6b0c32e80cf30becefa67/uuid_utils-0.17.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:33fa18507488c4dbde9a3969b6483183d934dbf7a7d46aba90bd5d664d4c81ea", size = 605833, upload-time = "2026-09-08T11:28:37.11Z" }, + { url = "https://files.pythonhosted.org/packages/e3/db/1c64eedcc55f1ac01067c208bfe7fa17957521a73ab1701c04a866c33795/uuid_utils-0.17.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:fa1a1c9a72ef9757176c069f7bd8014b7f4abf5f9930ec62b883dc864ba28092", size = 563310, upload-time = "2026-09-08T11:28:38.705Z" }, + { url = "https://files.pythonhosted.org/packages/e3/ee/314fc4f908258714e92b0fc50bbf02cb49454db4857e9da42d40b8f3539b/uuid_utils-0.17.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cd347022f67f7fbbd6939181ab076cd17a1d856e09a160eb87e245e692cc5742", size = 528539, upload-time = "2026-09-08T11:28:40.271Z" }, + { url = "https://files.pythonhosted.org/packages/2a/83/0e9e0bdd77bbf1fe5380267c14f197f8ac442ad5172000422f46f05953fa/uuid_utils-0.17.1-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:7e32ff7bd0fe4fdefce1d95f8f673a9b012286a7f40918ed1c08936d565aac4a", size = 98270, upload-time = "2026-09-08T11:28:41.575Z" }, + { url = "https://files.pythonhosted.org/packages/14/af/d2546a514432bb970da5a6550c4587ec8096ea90a2d2ea29aa55a1c35521/uuid_utils-0.17.1-cp313-cp313-win32.whl", hash = "sha256:a0a276738fafcfd63e6a0af944ffb8fb86448fe4cedcf574dd7df1ca13259e22", size = 168846, upload-time = "2026-09-08T11:28:42.669Z" }, + { url = "https://files.pythonhosted.org/packages/e4/84/46d45f14ebdf1ff4d9e6096dea5f31a706d7f71e99e48cde933b47a2e4db/uuid_utils-0.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:1cf7a837c3467f69ba3ef32caa43b1c5f5a462b7d960bcc59083459aed2b4202", size = 175479, upload-time = "2026-09-08T11:28:43.876Z" }, + { url = "https://files.pythonhosted.org/packages/58/42/558d83542ce270fdefe19a18e707e4fce58e64ed9d98658a2da78b9ac2b5/uuid_utils-0.17.1-cp313-cp313-win_arm64.whl", hash = "sha256:7a9537e7afe2cd8851e636789124bcc26ff1d671906c5e56f6e8f293fa477ec2", size = 173287, upload-time = "2026-09-08T11:28:45.133Z" }, + { url = "https://files.pythonhosted.org/packages/3a/ea/c735de118ef5c4a6ada1846699e65b3adcac92044e79b83345f90c792fe5/uuid_utils-0.17.1-cp314-cp314-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:f974aa1097b0b8245d8f29550eaac3b431c891ba7c76cc4beaa6ec7bf8cd27b6", size = 561135, upload-time = "2026-09-08T11:28:46.387Z" }, + { url = "https://files.pythonhosted.org/packages/38/eb/c16f89b3c48eecef422448b9bde07994762cf21daa3351f4c49eab705d54/uuid_utils-0.17.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:9700430eb701f18bd995787228c2202a15d9db335e8bf9c583df7eca5487d5ce", size = 289170, upload-time = "2026-09-08T11:28:47.735Z" }, + { url = "https://files.pythonhosted.org/packages/9e/05/5aec1389045f9e16afc1b8cce6414faeed40d44b3095f74d641c33ea1434/uuid_utils-0.17.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d030ce5d3cca0f2f55509035bcd33d39494c50dabb9d53dc0419ad212eb0fd7f", size = 323150, upload-time = "2026-09-08T11:28:49.064Z" }, + { url = "https://files.pythonhosted.org/packages/d8/56/8ad1da1ac6781f792e6e92cdb65bd242c5f5269e7c77de67edd704db61de/uuid_utils-0.17.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d365e0c916bd9a4b0b7f67f3305c6704c4ff44ff9da836faf455b8b5dce0399f", size = 331190, upload-time = "2026-09-08T11:28:50.478Z" }, + { url = "https://files.pythonhosted.org/packages/cb/d7/49300453d84440d6b8f45c95d9fd249f7106f8283296c948842f6fa00fd3/uuid_utils-0.17.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e9f5e23998625f6dc005a3a30238b4006424e366cb2966ec465e0287ae2534f0", size = 447676, upload-time = "2026-09-08T11:28:51.646Z" }, + { url = "https://files.pythonhosted.org/packages/9f/8f/db9fe5180418846bbc3273831468cead13e1de4956c73071fd1a4bde6ac0/uuid_utils-0.17.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:71eabda671e055415ecfa8859364438a575eda84e6f43a513436977d9377b532", size = 325838, upload-time = "2026-09-08T11:28:53.008Z" }, + { url = "https://files.pythonhosted.org/packages/f9/00/efcac8905b87ffd76323d8e46594a68a0bde2c24c8e71f44ab7d5622dde6/uuid_utils-0.17.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ed6821646e37f49683b3e977f856421c08eb9d03418423ac1477e09d2fb5cf62", size = 349881, upload-time = "2026-09-08T11:28:54.479Z" }, + { url = "https://files.pythonhosted.org/packages/7f/3e/37352e939a3995775a6034023bda646aeacf73f238a82e46f012d6a7eee6/uuid_utils-0.17.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d8abfd2ed04af7df7b586621b11449a061b4b899f8b073e972b7282c89ae8335", size = 502043, upload-time = "2026-09-08T11:28:55.705Z" }, + { url = "https://files.pythonhosted.org/packages/f6/c2/9f7883a730cb0e0fce25487021590a1fd28d2840bf25022b33a81c800da9/uuid_utils-0.17.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:8d31f5725c874a656fa1b7c8feb20b54b01ea70b200a9ff0568672ad3fc80b85", size = 607688, upload-time = "2026-09-08T11:28:57.026Z" }, + { url = "https://files.pythonhosted.org/packages/0b/7f/6b121cfe00742f5884fb313321fddd23a17a2326a01a0e669810eaa36b2d/uuid_utils-0.17.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:2ff6a84cf6a0a28e4a75c7b11f0d52464ddce4b7a0bfcf14c8de2e740299903d", size = 566366, upload-time = "2026-09-08T11:28:58.438Z" }, + { url = "https://files.pythonhosted.org/packages/36/64/e706ba987142e212f5af6a034ed98f9a0ec2543e1fdbb3b29b034271578e/uuid_utils-0.17.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:7970905d66e55f9a52d0e694d306501e8a9468aa99da73867cc1f8eba2817261", size = 531140, upload-time = "2026-09-08T11:28:59.937Z" }, + { url = "https://files.pythonhosted.org/packages/5a/b2/7dfecd82aff24e02a6764ea88dbb7266a061bc7691d0180f01c6b1ea1efe/uuid_utils-0.17.1-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:b2735d128a3732e528229fc24295530caa75e79d5ea7fb0f8690ef3114d9b262", size = 100062, upload-time = "2026-09-08T11:29:01.323Z" }, + { url = "https://files.pythonhosted.org/packages/2a/8d/4840ac42764185be3fb7f7ae990c3f4bcf0b941a54ad6807e65cc312e9f7/uuid_utils-0.17.1-cp314-cp314-win32.whl", hash = "sha256:cc9da3c0d8208b53c28658340827505af437bff7a52a55fdaa262ccd4c5a5d87", size = 171234, upload-time = "2026-09-08T11:29:02.688Z" }, + { url = "https://files.pythonhosted.org/packages/90/c0/772c08a73cfc8810ff3144ed2e3701242568f83c7031b781d61bdcd74c29/uuid_utils-0.17.1-cp314-cp314-win_amd64.whl", hash = "sha256:eee4a1df744434e10a0d0a679c074e3128b58328b83c99144e363db320e801f4", size = 177462, upload-time = "2026-09-08T11:29:03.81Z" }, + { url = "https://files.pythonhosted.org/packages/f8/e3/9e3eb231cffab2df2029c4b6d015dabb077366d1194a8a0f2d4522d581ee/uuid_utils-0.17.1-cp314-cp314-win_arm64.whl", hash = "sha256:c3955fc653dc78a93ecbd880bc97a0ef8010a9a748e6307f11ad005d45390ce5", size = 174745, upload-time = "2026-09-08T11:29:04.919Z" }, + { url = "https://files.pythonhosted.org/packages/cd/3f/095e8eed10949c6ca1adde77d405268e88eeaf6e23a3968b29e549d0765e/uuid_utils-0.17.1-cp314-cp314t-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:0956a9422e132c8d4a3d808cc3d754fc8e81d34295a3a202b332c9dce064eda9", size = 562178, upload-time = "2026-09-08T11:29:06.231Z" }, + { url = "https://files.pythonhosted.org/packages/bf/ad/5afb5a6fbedbce0bbd358855771c63ff233e7bad898eaaea9f9802fedef9/uuid_utils-0.17.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:691a9c16db041a8d5c55d6414398b0fc97e33aad41ad3aef67a6f3c0661dcde1", size = 289997, upload-time = "2026-09-08T11:29:07.478Z" }, + { url = "https://files.pythonhosted.org/packages/9a/04/78edc758c4dbc84bd5ed8c40b6d7ee0dd879c6ff07320f347e371d84cffc/uuid_utils-0.17.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf419a23bbeafed0fc8efb4ca5b3e0a8ea4ef4866de41c3393f888bfd5f60e15", size = 323144, upload-time = "2026-09-08T11:29:08.856Z" }, + { url = "https://files.pythonhosted.org/packages/d8/c7/8f27ea2c1e244c0edbaac5dc2a5cbbf51e298e54674faef03132f4468a1a/uuid_utils-0.17.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:617acaeb2586e87c9bd0c2e192e4f1d33caacaeb7f3e0cc75972bc38e703e099", size = 330592, upload-time = "2026-09-08T11:29:10.107Z" }, + { url = "https://files.pythonhosted.org/packages/39/af/e7d7b372781627a6ea6ec2a2ee82f98e3fe7de7b6e4b050ae29a66fd64f8/uuid_utils-0.17.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b1fc79cd8a24bc6c553cd6f708f5ca08c4182914bdcc87192e1e468e9858add3", size = 446735, upload-time = "2026-09-08T11:29:11.334Z" }, + { url = "https://files.pythonhosted.org/packages/33/11/a2ef25dc4a3dcae5ddf8a7c2debc0d10719a991e327e43913605fd3b9c90/uuid_utils-0.17.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce2f65e81429fcb145105a10c71bf2c71ac5cc9c8fc6c79ac3c13b9de091b2ef", size = 327402, upload-time = "2026-09-08T11:29:12.745Z" }, + { url = "https://files.pythonhosted.org/packages/4e/4b/61153f07eb7282d71a6ee10e3c05636a7d43cec6784bc6ea79979084e727/uuid_utils-0.17.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e9ff97bf48606e5d817a01fdd4a4a8855b91382e384f524a960149da00adab5a", size = 348998, upload-time = "2026-09-08T11:29:13.976Z" }, + { url = "https://files.pythonhosted.org/packages/e0/d2/b40991f80805d2cb3ace8c961752429e2e50d4ce0a3ed941c26a6250e3bd/uuid_utils-0.17.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:87d818e1fffc39476c7934544f54455ea04c6297fcd983598802e81c746338a0", size = 501745, upload-time = "2026-09-08T11:29:15.261Z" }, + { url = "https://files.pythonhosted.org/packages/38/84/f65e1963964b2b6fb7aa687dc819e5a39207dd9ecc7961cef82124fd3cbd/uuid_utils-0.17.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:764e4505821c20f1a45a54e9da076e6a97e4e46947159490aea893dc6b8d77be", size = 607104, upload-time = "2026-09-08T11:29:16.586Z" }, + { url = "https://files.pythonhosted.org/packages/84/3f/07c5ada40f360981ee069dbe6463a13dfa1de7eee73a6cb91f94d610821a/uuid_utils-0.17.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:cddf08ed611c2ad1c791d4133dba2c63db4d294b2111e1db687537943cac25ae", size = 566012, upload-time = "2026-09-08T11:29:18Z" }, + { url = "https://files.pythonhosted.org/packages/52/6d/ede35c5e3e3787d2e9d5d3baddbc00f3f64e3f4522d53508757fbcfd6f47/uuid_utils-0.17.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bcf40ae13cf31727b84f00b1a505f1d4d10199bfea946c3554ef327702d2acca", size = 532218, upload-time = "2026-09-08T11:29:19.477Z" }, + { url = "https://files.pythonhosted.org/packages/97/a1/318e4bc7f04a505189233ec2409cce9e18cd5f52d06738a9e96f0eac3816/uuid_utils-0.17.1-cp314-cp314t-win32.whl", hash = "sha256:ce2fd8f8bc0026c0fc137cf5cce9de546ff9e0b4008be3eb21b5a06249eafec1", size = 171217, upload-time = "2026-09-08T11:29:20.984Z" }, + { url = "https://files.pythonhosted.org/packages/06/79/11811f97922be44ca900fc89e26b4dae173bd03ffd03672da7b28b023b29/uuid_utils-0.17.1-cp314-cp314t-win_amd64.whl", hash = "sha256:3dd5706a9874799013e82ac567425c535a0a4a7779c8551154915a4ba2fcb1c4", size = 177754, upload-time = "2026-09-08T11:29:22.227Z" }, + { url = "https://files.pythonhosted.org/packages/60/66/f56b2b497286f01ac2f6a1be8f825e871906d6aaf83dd4ad0cd7c8d54013/uuid_utils-0.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:a3cd9443d0a3b6f631e6352cb9d9c0a9b68d808d71250eb44e7b00265ec382f7", size = 174267, upload-time = "2026-09-08T11:29:23.447Z" }, + { url = "https://files.pythonhosted.org/packages/d8/23/81d75df583e3c7ff432b4f86014ae243fe7baa57d99919dc1292e9424724/uuid_utils-0.17.1-pp311-pypy311_pp73-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:653bf91ec2d1c3b0f10157815ca58b0b572d15ce17ed0823aae08ff0df207fad", size = 566472, upload-time = "2026-09-08T11:29:24.726Z" }, + { url = "https://files.pythonhosted.org/packages/8f/f3/71e7acaecfdbb5edd3cc7e13d0602f4566f16f35412edcc784569ff14733/uuid_utils-0.17.1-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:ea207557393ead4084beb08f0e9c0c944ac2050678714b65ba979fae90cf782e", size = 288766, upload-time = "2026-09-08T11:29:26.252Z" }, + { url = "https://files.pythonhosted.org/packages/52/62/1a94e2cf60ba38ef87f11cae3dd3b2787366229cc9a3f0ffc41fb89c9487/uuid_utils-0.17.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5629c94f65249384314831ca0a95ca5f1dce5bcd5ee79600a5cd31d4f7d0f5f6", size = 326190, upload-time = "2026-09-08T11:29:27.666Z" }, + { url = "https://files.pythonhosted.org/packages/87/81/55b12664f7fb6a69a9d18ec8a8cac1a55fc60e0dca14046d6bb972fae2a8/uuid_utils-0.17.1-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f85fddf2e5c4f7a30ebdc2b26ec585b9d814d807bcf285d248ae451ffee16a03", size = 334399, upload-time = "2026-09-08T11:29:29.023Z" }, + { url = "https://files.pythonhosted.org/packages/8d/64/844e5657be2b43ca2136ef4aa207420c1387e28cdbb90dcb395133ee63ca/uuid_utils-0.17.1-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4adbea226bef0c619b33fa257113e36269a475b2c2049f55b8b83b4c6d507a9a", size = 450440, upload-time = "2026-09-08T11:29:30.334Z" }, + { url = "https://files.pythonhosted.org/packages/87/09/ab493c7598311f9bab4dc762d3483cb35cd78588c4d848c36fcda671f4f9/uuid_utils-0.17.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6ed203ff60932fe5b3a38453945bee4aa8dfb387789fd420698f607786ba42b8", size = 328684, upload-time = "2026-09-08T11:29:31.752Z" }, + { url = "https://files.pythonhosted.org/packages/4f/1d/8f2816d50d7a69416270a88f41f6820cde300719bac814989bb13e4c5ae6/uuid_utils-0.17.1-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:92e8df2bc6a33229c105ea90839d98576fcecc5cc86fdb1dd772ab10367b744b", size = 354290, upload-time = "2026-09-08T11:29:33.067Z" }, + { url = "https://files.pythonhosted.org/packages/18/e4/2bdff71a73c3d5dde6777815c910be7417fbc54f36206d0f7a1fb2f54522/uuid_utils-0.17.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:6cca251f83d3ec2988fb7355b52c4b4fd2d96159f6f040e68f51af15fab49540", size = 180288, upload-time = "2026-09-08T11:29:34.24Z" }, +] + [[package]] name = "uv" version = "0.11.21" @@ -5469,6 +5675,202 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a4/f5/10b68b7b1544245097b2a1b8238f66f2fc6dcaeb24ba5d917f52bd2eed4f/wsproto-1.3.2-py3-none-any.whl", hash = "sha256:61eea322cdf56e8cc904bd3ad7573359a242ba65688716b0710a5eb12beab584", size = 24405, upload-time = "2025-11-20T18:18:00.454Z" }, ] +[[package]] +name = "xxhash" +version = "4.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/a5/1386f35da1475fcaeef42581deae73417c6d2a6a0b2d2e8914de18844dcd/xxhash-4.0.1.tar.gz", hash = "sha256:d55bf4ef10eb09b8b6866790e083d26d087d84caa3cc0946ba87c3ca7ecaf7b7", size = 101513, upload-time = "2026-08-17T08:24:08.557Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/de/6854b311cb468985de555e49717357ba1de8ffe4b08eda3f4c522a418fda/xxhash-4.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:3f68fe400ceec235f3e4a4b02a28c2fd2d283584a193223c921dd4c48f1d0754", size = 38470, upload-time = "2026-08-17T08:20:33.331Z" }, + { url = "https://files.pythonhosted.org/packages/91/2a/7d79952633fccbf9c2a59cc1dfe9d073f9edfceb052ba9bff5075e31408d/xxhash-4.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9b1dddc257279417d93c9e59420d49ef90aece90d7a01996db3aade74b0281b1", size = 36229, upload-time = "2026-08-17T08:20:10.259Z" }, + { url = "https://files.pythonhosted.org/packages/70/6a/6a6f4220c39bae1636eb3f8ef217359b8afe268493ee858adf9002130257/xxhash-4.0.1-cp310-cp310-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4972332c079d6aad69c4620a68d015a4ecb33141583f70d642cf9edf6a713763", size = 243168, upload-time = "2026-08-17T08:20:07.211Z" }, + { url = "https://files.pythonhosted.org/packages/c8/03/a1d745b324bede7af8a274d889d25b758402629695499a957375cc5fe994/xxhash-4.0.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f1b603d0686c99fa0879f104a74e7db58367634c6e50ba827bee9aa095e23205", size = 266061, upload-time = "2026-08-17T08:20:18.253Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cd/55c7565db23d2d29a2e31ea9dd0001ad3f4729298f42ba32967dde7644ab/xxhash-4.0.1-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:33fd538191f47071deef6b1f676535e2aa770f1fd150ae4cc75a34c9e930be3d", size = 287357, upload-time = "2026-08-17T08:20:08.901Z" }, + { url = "https://files.pythonhosted.org/packages/72/31/c967c98cbf151df6ae8756fc9821b1f78d1feffa8420ff2ad5645f27f98f/xxhash-4.0.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:33e270d302c95ec426dfa0f5a4e16bff2ab8d7b8a46faa4746affb05e684ac77", size = 270683, upload-time = "2026-08-17T08:20:10.943Z" }, + { url = "https://files.pythonhosted.org/packages/70/98/df9f3c14bc2fb2712ed1497349dc7e8c0b0f20a1f353e2e146d83a1adef9/xxhash-4.0.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3fb1d30d4b6d6e2c4a08e5ac6fffdb2b572d2cfcca15a5509cf4e7a1350f955c", size = 497802, upload-time = "2026-08-17T08:20:17.217Z" }, + { url = "https://files.pythonhosted.org/packages/5f/3b/e5d20b4f602d15fc5fc066f601052a7d6f5a401a50d67fac92098a5829a5/xxhash-4.0.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7e27dbed5c4ba033919e4b4ed8dc14e029e91d14a93cd9f920d25277c7df6781", size = 249503, upload-time = "2026-08-17T08:20:40.14Z" }, + { url = "https://files.pythonhosted.org/packages/39/98/4cd03fa7ba791657aa555d0655e89a0d66193b1331e4391114b50227f80f/xxhash-4.0.1-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:43bcf2a871f28f16135545415cab3ec43904d4c80425a64598a9e6cebfb2b5ba", size = 333384, upload-time = "2026-08-17T08:20:18.93Z" }, + { url = "https://files.pythonhosted.org/packages/c1/67/a0a076dbcecad2af0cceb873ba4f95475f3955fb81d82f9c5e9f97a12854/xxhash-4.0.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5dc434c946012e6d8a72b10f970ea30755b718251dd7591dbfdabafd3bcb21bc", size = 262463, upload-time = "2026-08-17T08:20:08.719Z" }, + { url = "https://files.pythonhosted.org/packages/48/94/767b68736250813923d74703ef628b0f57ff1c5bf690d7a6082928d1a14d/xxhash-4.0.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:0b1082fd0f089ce9098ed77aad8b777b5d156f8ac601c69cab73811822b8ef07", size = 289405, upload-time = "2026-08-17T08:20:35.493Z" }, + { url = "https://files.pythonhosted.org/packages/ab/61/69d9ec6e85f9933f26b39753b404f97ffd2fc3bfeeb5e26333752595e060/xxhash-4.0.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:dd649663ddeafbfd4734eb8abae921dd5baa1242f20bda54e8bc927369ccded4", size = 247989, upload-time = "2026-08-17T08:20:10.759Z" }, + { url = "https://files.pythonhosted.org/packages/a7/66/e6a033879893074bc441faec65587f9ef9cca49ee3cb99ef20c699b014cf/xxhash-4.0.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:97b455de3e8b1b0b1e4594cb61a468992563f03ca264062fbb0a66b393c01d90", size = 267987, upload-time = "2026-08-17T08:20:20.947Z" }, + { url = "https://files.pythonhosted.org/packages/18/91/a99a412b010cf2cc2bd38a0a44043c894ffa80b46c8d4e1522e40d2ef401/xxhash-4.0.1-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:2194bf96d5f3d4e0cb65deba370ec83dda3edfba42155f9384190ed5e51ea5e2", size = 322541, upload-time = "2026-08-17T08:20:22.675Z" }, + { url = "https://files.pythonhosted.org/packages/0b/12/1a91408e66d1716bd278cf55529d4ba251d90c6b694ea78a09dcbd9d36c6/xxhash-4.0.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:84df5f8da574caadbc0cb1b8866ecc2368cc941f0cd05f677756c802f370dafa", size = 466264, upload-time = "2026-08-17T08:21:12.422Z" }, + { url = "https://files.pythonhosted.org/packages/fc/c8/8abd4c1b90962f794ed9b139767b0a971e5168e8393961ccf046956c0039/xxhash-4.0.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c09ada495567c9c9a8156c5ebcfb93be7fece0755062d738c972dcbecd0d84b5", size = 246149, upload-time = "2026-08-17T08:20:23.385Z" }, + { url = "https://files.pythonhosted.org/packages/22/3f/e020285d737a712bbfcf01dfdbbec7773c7c8289447a5373540caf2cdf5f/xxhash-4.0.1-cp310-cp310-win32.whl", hash = "sha256:85bdd40cb505a11e0ca04191711266c5fd696ed786ae83849955e457774edc96", size = 34630, upload-time = "2026-08-17T08:20:10.001Z" }, + { url = "https://files.pythonhosted.org/packages/6c/9b/4e8384b299b40664a225ce9deef54c42b3d59f5181a16d4a374ea3503f8f/xxhash-4.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:8ec4777d92fd61a5c8fdeddab894fd65bea301a8092fb5419ec6472aa4d458d7", size = 37058, upload-time = "2026-08-17T08:21:05.846Z" }, + { url = "https://files.pythonhosted.org/packages/b3/e9/d73c870d9dd26f8d6782ecf716b31e836bb6269c888b6bb6e1fcf71eed36/xxhash-4.0.1-cp310-cp310-win_arm64.whl", hash = "sha256:03600a8987849b2bef7be795a60a6052b635c63fa98b718b08ca5ee823691cfc", size = 33289, upload-time = "2026-08-17T08:20:19.707Z" }, + { url = "https://files.pythonhosted.org/packages/0e/58/bc81e25cceab76ce4b400441e3a43312bf3887fedbb2e5f80cc5a7dd7f75/xxhash-4.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8b4477edc03091f51f5309406d230851c23cf4822029e3bf40b8df53093fff1c", size = 38473, upload-time = "2026-08-17T08:20:34.303Z" }, + { url = "https://files.pythonhosted.org/packages/64/8d/d95e810c9a2930906f1fbd0e38f77554abb8e042a190aa9cbb24da39e9a2/xxhash-4.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:04f9a24de11a6647666d5302fd73d6a5224ce50ddc965fb0bb44cee736e6bd7c", size = 36228, upload-time = "2026-08-17T08:20:36.641Z" }, + { url = "https://files.pythonhosted.org/packages/72/be/ebcded2a32ba664a17a1737a91b6baa298bcda6942acdad81af81660b74c/xxhash-4.0.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8c5ce76b94ba49f3be8a8f2611abc6564210702c72ac9e237ca2bebfd17794", size = 253292, upload-time = "2026-08-17T08:21:27.206Z" }, + { url = "https://files.pythonhosted.org/packages/52/2a/72d31d787d988d1130253bc34d249c553f02c9387e7dda789b6d5aa7963b/xxhash-4.0.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4c8842fb19d78b5e8c2a52baf4c8357658cc56c62bc822b86ce0f942f28e286", size = 276545, upload-time = "2026-08-17T08:20:26.726Z" }, + { url = "https://files.pythonhosted.org/packages/39/ae/048f3b1f283a340bef3697fe5a9d4f10de1696a379af9af6b2352c24d82a/xxhash-4.0.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a43418e1a90b4809a9caf64aeb8b0696e3e1f300a323acc1e6ee2f93ae319fcf", size = 296295, upload-time = "2026-08-17T08:20:15.759Z" }, + { url = "https://files.pythonhosted.org/packages/8e/43/e9a593c81445c8e8d669402edb8264144624e7e5e2406df7d33e3c164d90/xxhash-4.0.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b3662719007e059abde7eddacf8517142ba076ddc7b30c807260e57d28c3c191", size = 279966, upload-time = "2026-08-17T08:21:22.217Z" }, + { url = "https://files.pythonhosted.org/packages/f9/4c/29da2b166955a300521c0abd498ad4481916c3743949b106192b781f58fc/xxhash-4.0.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:06d7fbd609503c3be5e65cdb6bb2f040d6a98574404e2e1d5c60815c97fff4aa", size = 509850, upload-time = "2026-08-17T08:20:32.731Z" }, + { url = "https://files.pythonhosted.org/packages/40/ff/e39e1900179ce7f0f23e7000d9fc672471a8d05b6b2dc657cb496c8975d0/xxhash-4.0.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:101aa300de6ceef3d9c77569706330d8921fc45dd82bceed2084f1e9f2557a24", size = 261005, upload-time = "2026-08-17T08:20:40.735Z" }, + { url = "https://files.pythonhosted.org/packages/89/79/76ee26720d13219458f4b2ec0b22f539fe2bcb1f83dc22a24be4cda4e285/xxhash-4.0.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e4296fcc790876a8b0f297edc83d3b088457b774d8f67b4636807f8a2ec69a79", size = 339620, upload-time = "2026-08-17T08:20:50.371Z" }, + { url = "https://files.pythonhosted.org/packages/2f/c7/56b53252d64ecb2f3a0d283b41033561b1bec9c268095150153b694c2e52/xxhash-4.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:57d7fa8f23908d173001c21a9e82bfc6ad997d1b6c270fb121812b7ed158891c", size = 272558, upload-time = "2026-08-17T08:21:33.883Z" }, + { url = "https://files.pythonhosted.org/packages/fc/76/83101a2f2ad3eb6b4b5d571e0aa394a576e3e23121707d507d80197ac385/xxhash-4.0.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:85e402dab0f9acd3604539747c6fcc57dc188a18af6ab07eb8189351cd32466c", size = 300417, upload-time = "2026-08-17T08:20:36.183Z" }, + { url = "https://files.pythonhosted.org/packages/34/5d/5be1166ec4fc4bc896e508dc51189a2dad200b373269a430e214fb152693/xxhash-4.0.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:fb59a0dd61fb2ad481c03fda399d78ce57dab6bb62c2c8fdb446a7ba4754b89a", size = 259286, upload-time = "2026-08-17T08:20:21.51Z" }, + { url = "https://files.pythonhosted.org/packages/77/6c/42f6201f13278787c58a6b3a1cd597b47e8665a7d4f68a3440d001c05a75/xxhash-4.0.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:0b20a06454b34f1531fc677c54efe2ecdec691ef9224f7fa919bf2c1363f7ff1", size = 278230, upload-time = "2026-08-17T08:21:47.62Z" }, + { url = "https://files.pythonhosted.org/packages/7f/37/3cb7f149a5a469c628604c33bec6d79764698b315700a4bbf1c6fb15622b/xxhash-4.0.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:f7db035447a0ac8959aa230c5d36545ecf9f547413eb1711c0ca6f0ba1418925", size = 329846, upload-time = "2026-08-17T08:35:10.922Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ee/934eb1e11f4d0e95f3828825f8da4b6d59e338235d63edc3d929769262d2/xxhash-4.0.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:34ed93e20bfd98d722b902121643791eeb4b1641871e2dc63d0d4c2d93f187df", size = 477285, upload-time = "2026-08-17T08:20:46.297Z" }, + { url = "https://files.pythonhosted.org/packages/e2/0b/77835dcd7aec970db74f5724c94207ada83b3e2f5e1474ab44b9c8fe5ea5/xxhash-4.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f6247f5e23ee94f2557ac9dab738a336f607c6ff476fcf66ca70c3aef5eee15a", size = 257552, upload-time = "2026-08-17T08:20:58.211Z" }, + { url = "https://files.pythonhosted.org/packages/da/6c/a3ce7a1a9c4ec9ad8babba591a996a71c474ff9630c5fb04c8c9d8b995ca/xxhash-4.0.1-cp311-cp311-win32.whl", hash = "sha256:348c8f288dc961d6bbd1985c8152a3ed7a85c95df00e82320f0c5215d922a399", size = 34630, upload-time = "2026-08-17T08:21:53.323Z" }, + { url = "https://files.pythonhosted.org/packages/d9/58/60d2170e8cda0891aab25dcaa74797b420c3c6cde8a5bc8372f17b30c0cf/xxhash-4.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:ac0f291ab6485bd71f33941f9b92771318332a05d505460b41e893a549caadc0", size = 36992, upload-time = "2026-08-17T08:20:41.973Z" }, + { url = "https://files.pythonhosted.org/packages/ac/de/b229a39f9bbbe30cbcf9afaaa8993cb65286715c90a3b058c3769196ae02/xxhash-4.0.1-cp311-cp311-win_arm64.whl", hash = "sha256:72f34834518157a75e7090f328ee7a16c70c804cfc7c694fa069cc888e9fc03e", size = 33289, upload-time = "2026-08-17T08:20:32.176Z" }, + { url = "https://files.pythonhosted.org/packages/26/6c/dc7cffeadd06336cd934947187cd38abb263103bbc552ca0f55fe4ff595a/xxhash-4.0.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1ee523f51718e41753f04f7102bb4dc55a18d2ea5cbaceef8ec7ca08571bd428", size = 38444, upload-time = "2026-08-17T08:21:54.332Z" }, + { url = "https://files.pythonhosted.org/packages/75/c9/cf736f6db8c3273af18925061572db0d4357818a9ce425f4b5fb0021918e/xxhash-4.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:515a822c73abbf6a0b7c70976d9662be342835c9d78b8dc7c023411f39c35dbc", size = 36195, upload-time = "2026-08-17T08:35:13.004Z" }, + { url = "https://files.pythonhosted.org/packages/da/a2/ca1929354b6851529d0148f7f335b5e2b0281f83bab3e19f0896dc579796/xxhash-4.0.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f5d031f35962e5483a613214e61f09fe24ab523062c3646d592dc16c4a217451", size = 253113, upload-time = "2026-08-17T08:20:52.152Z" }, + { url = "https://files.pythonhosted.org/packages/de/bb/542005206af59518bc8d78a210f1e0172217bc53beb32f64a5b632e72b6b/xxhash-4.0.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da0264844a09b538c894e5eff25313d941deb4dedec2131b98418a71a3c9944e", size = 276525, upload-time = "2026-08-17T08:21:01.886Z" }, + { url = "https://files.pythonhosted.org/packages/1b/df/607cff25dcb0f1d35c3b04493f6ad8471edb03fd4eacbdcc5ceddef1f3e9/xxhash-4.0.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1642907941ee4b75aacc3db688af52ea02ca2305ab22af7ee686ed726b332684", size = 297703, upload-time = "2026-08-17T08:21:57.958Z" }, + { url = "https://files.pythonhosted.org/packages/15/ba/9d2275eea0b9d9c6b02921be23f7588356c60df95c763b25f0e045894d43/xxhash-4.0.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4af350bc3f329970c0e3a59af84a8a30998bf8a9167eb50cd48e59baaa1d7bec", size = 280252, upload-time = "2026-08-17T08:20:47.299Z" }, + { url = "https://files.pythonhosted.org/packages/1d/aa/2299d9f6369e550aef2abb64945e39daa34412725aa46a20d99b74d76f67/xxhash-4.0.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8ba782ca3bf1e81492611152b9a0d5264971339e95e34d69de0ac2c926be496d", size = 511041, upload-time = "2026-08-17T08:20:36.771Z" }, + { url = "https://files.pythonhosted.org/packages/83/97/31bd8b8279e6935a0719f6910ced15e9d5a2cd554b253f6027ce1b5a1c2c/xxhash-4.0.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:237b8f63a2a0fcfb1ffc06e21dad23add44e6d354b2b014364a1d41e419a4dee", size = 261812, upload-time = "2026-08-17T08:22:00.469Z" }, + { url = "https://files.pythonhosted.org/packages/2d/c1/d180a2da23c105d8e0b02d54f9f5841013fc81c233010ec781e31f1aee4c/xxhash-4.0.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:81507a68ba84c55241fb61cce1469f473a5da4205fc8ef6f698e5948eea8dd88", size = 339878, upload-time = "2026-08-17T08:35:17.626Z" }, + { url = "https://files.pythonhosted.org/packages/a8/3d/f584cd3172fe934f0f5a0a3917d0d7ce781f74d794fd43bb72be71c3ef6f/xxhash-4.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5f1ea31d61bcd2cd2f3ec4ca80a64187bbd7948f490b63cf0dcbc6e717b4c1e9", size = 272871, upload-time = "2026-08-17T08:20:56.067Z" }, + { url = "https://files.pythonhosted.org/packages/34/50/2c7956b2b551682e00b9aebce9ceb0a991a131d65f9850c09f5f9760be2e/xxhash-4.0.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:06713a5aaf1d0905c5579416c020c02e42b3ceb931e86c7d3b7fb85403dee3f3", size = 301440, upload-time = "2026-08-17T08:21:35.911Z" }, + { url = "https://files.pythonhosted.org/packages/eb/a2/0739f6482184a8026f4b022718f5f815d352059312e80696825433f0a8e7/xxhash-4.0.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e8cda075b10bb3917b002c74a04f9e02b7d13b5bf732571404d51c52b11c7329", size = 260157, upload-time = "2026-08-17T08:22:01.416Z" }, + { url = "https://files.pythonhosted.org/packages/a1/25/b31a7bcf1d7d116842812e54f9b944843b4236ea4fa85634e8259f342212/xxhash-4.0.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c10b9206753b64aa791b35b201485477525b26fdec5bf86e8364c388a03e2592", size = 278233, upload-time = "2026-08-17T08:21:15.674Z" }, + { url = "https://files.pythonhosted.org/packages/db/e8/5293bae090fc6119dbc5fcf5c4cc0e1536394b52d73b7904d033836c73db/xxhash-4.0.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f3e1a44af01b6692de0ec6caba5f0bf93ceb36896e02b7fc00952c6ea7ef39e1", size = 330270, upload-time = "2026-08-17T08:20:51.128Z" }, + { url = "https://files.pythonhosted.org/packages/72/9e/e2ab12d40921f3f34c9317637d65e011aeababf8288356ea8d527de2c1d0/xxhash-4.0.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:c6fc415b5568bd9accc7187f1729a99707330c0a67a8b9f93c1149ed573ed75d", size = 478555, upload-time = "2026-08-17T08:22:04.183Z" }, + { url = "https://files.pythonhosted.org/packages/6d/32/c6148d39a49efa95f39b4cf0d41ef35a487f3b30f6fb1fc8fe8d8eab577e/xxhash-4.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:96d8de55029d42251945531f6aa7590c32b48163c66a43bf29d8657d7446a377", size = 258174, upload-time = "2026-08-17T08:35:21.18Z" }, + { url = "https://files.pythonhosted.org/packages/8f/fb/0b04b68d6c5bc71c7a2c344f1287327b67e607f28fbcfd937697caca64b6/xxhash-4.0.1-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:0163b5d259de23ae9e07b7eabf435ce4704f6f205589a2b154e6af4be985ce1b", size = 20767, upload-time = "2026-08-17T08:21:00.806Z" }, + { url = "https://files.pythonhosted.org/packages/a6/be/476092aba34d1fcd313e1613a3bb3bc692f253d167b54bc90049043b5034/xxhash-4.0.1-cp312-cp312-win32.whl", hash = "sha256:1216f7ba5683f17a89eb7dcb4bc50a0b743dfe1902278d7b3d0786f538118433", size = 34669, upload-time = "2026-08-17T08:21:49.486Z" }, + { url = "https://files.pythonhosted.org/packages/aa/02/f9413d94fae43cec6d1a74c4f12156c6f4a7f5fd50e1d34defebdee3dec9/xxhash-4.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:5c2d525a3afabcd8e3549d85fc7e111fde6bc302d06a1893fe73adb79823415e", size = 37073, upload-time = "2026-08-17T08:22:04.886Z" }, + { url = "https://files.pythonhosted.org/packages/c1/83/6fe93c1b95acf962bc61a246df09dc2dcce895ccfc1080c9f48d0b652b92/xxhash-4.0.1-cp312-cp312-win_arm64.whl", hash = "sha256:86b2b12bec60c678ed8f5cca0258ad93a8928ebddb6ca7732f0875afe1451d1a", size = 33299, upload-time = "2026-08-17T08:35:12.708Z" }, + { url = "https://files.pythonhosted.org/packages/f3/dd/c707286b527722f776e1fb81dd202c45623355ba1a2972337a2a26075b2b/xxhash-4.0.1-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:8c9fe122444e129881afd1d4d1c7ac0d3ce2d91b68c2b40173b6025ff1c31f9a", size = 43639, upload-time = "2026-08-17T08:20:54.945Z" }, + { url = "https://files.pythonhosted.org/packages/1b/3b/bb71639a0f95635f61936a6f2653599c4261b645ddddd8d00f9dfe3613e2/xxhash-4.0.1-cp313-cp313-android_24_x86_64.whl", hash = "sha256:1f3346c5c287ac3c7f38b20380f55e8768230e7252af59fabcf3b87ab21e4256", size = 40657, upload-time = "2026-08-17T08:22:12.616Z" }, + { url = "https://files.pythonhosted.org/packages/3c/91/76f3f5385faa9886a36f21fcc603f40b4c0c40ce622382f133160c48b4d9/xxhash-4.0.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:4e5141543c7f7fe3087500bbb4ac2845cb528a980aa91f8f1e661e2292ff4a5d", size = 34708, upload-time = "2026-08-17T08:35:24.614Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4a/f48f0e3e1b1ab072979fff2a5be899234e28090883e8b519d0b10215d708/xxhash-4.0.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f09ee747e2a5f876cc5ad56947734811828335e13b403dd8ea1e06d77a9dd48d", size = 35650, upload-time = "2026-08-17T08:21:09.337Z" }, + { url = "https://files.pythonhosted.org/packages/c4/53/b73d7472b196101ad1f57ed0674af3af803ac3e9ec2feadd650a7b262562/xxhash-4.0.1-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:acf52474b2494ef66dc7e0fb6d5e2b50c18313039ad4d275fbf9f9907c804bc5", size = 37958, upload-time = "2026-08-17T08:22:10.616Z" }, + { url = "https://files.pythonhosted.org/packages/d0/f2/024946ad8fa532074af4e4380179da54b7ec9facc8bd0b279ec0fac4e63a/xxhash-4.0.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1b3cccf75eeb5b01639b2feadb042a8e07889293b7ca72fa2985e7dcb64763cf", size = 38032, upload-time = "2026-08-17T08:22:09.535Z" }, + { url = "https://files.pythonhosted.org/packages/da/e0/934af8d99bb5885711006bec30a691f728edd513d2c40f053f887d8e7577/xxhash-4.0.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cd878d32f5c6cbce9783f8d6897561fb772211edba9dde49d85672b88ed45276", size = 35895, upload-time = "2026-08-17T08:35:16.53Z" }, + { url = "https://files.pythonhosted.org/packages/20/5f/a8011f6a1558f7ca66d9077bb4f192b1871afcea62fbd5733605d2015755/xxhash-4.0.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:41e579025a6e13a99e6d71e39c9cfc621a0dcdbbf19106325e145fa858f2d794", size = 259464, upload-time = "2026-08-17T08:21:06.72Z" }, + { url = "https://files.pythonhosted.org/packages/ff/89/9665a44397547e7a3d58c0942425a976d58dcfd4b538f33220a312bf6912/xxhash-4.0.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:74379a577a9f3b6afbdedf1b90e5c7764467051977f18a326d7d607336d743bd", size = 283949, upload-time = "2026-08-17T08:22:17.003Z" }, + { url = "https://files.pythonhosted.org/packages/34/2d/78774141266457468f29f3f5803092df4db87d8148ba74e4debd041649db/xxhash-4.0.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:acb31ecdd1a97fab5cd39a84ee9f515e727d319f796fec48703b8339b9998360", size = 303898, upload-time = "2026-08-17T08:35:27.951Z" }, + { url = "https://files.pythonhosted.org/packages/59/48/d78d22de576b42528bff87c14207de50de4f0b888221a50ff7c9d675d670/xxhash-4.0.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5b7875ac1a2edcb691f27642b8b94b904baa6bcecb7d79c72df2228ba8cb5c51", size = 287241, upload-time = "2026-08-17T08:21:13.042Z" }, + { url = "https://files.pythonhosted.org/packages/4c/de/7a1755a59c59fd46176f293bbdd99e399a6537ba9537fc723aa4d1bf6e27/xxhash-4.0.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4751f1d7eecae6b2d2a773630f1a7248f125c9a92a456694d03c15bceffc9d68", size = 519856, upload-time = "2026-08-17T08:22:15.35Z" }, + { url = "https://files.pythonhosted.org/packages/6f/fb/76580c08e916507859b0f335393cb5fdc59452c4402edbc6bcca6e47e7df/xxhash-4.0.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a51b061d54cda8b83e62c44458bfbf0dabbef9b975dd9649952ba5076b9f349", size = 268572, upload-time = "2026-08-17T08:22:14.533Z" }, + { url = "https://files.pythonhosted.org/packages/d0/2b/1abde3e07b8f2077a38b4fbfaf764115008bfe0ff03bc7756a52c9fd0607/xxhash-4.0.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:74a164e8b63f1e9cf35c9a7809d082b033d1a00e7375d5d814415436e7867e57", size = 344967, upload-time = "2026-08-17T08:35:23.569Z" }, + { url = "https://files.pythonhosted.org/packages/5c/15/80b6ddf0732eef48a8b5fe717398274794392bd6dbe82af38d189d214772/xxhash-4.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f5e5c6df4b703afcbe9352d238a51efd97c3b91fdc3a2052e40fdacb1e7505f", size = 279956, upload-time = "2026-08-17T08:21:24.97Z" }, + { url = "https://files.pythonhosted.org/packages/77/e0/11cbc43c205bf81fad50d69c7319cd1b1ccc01a66cd4fb8766357126c43d/xxhash-4.0.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:d54b8ae068af532c8cdf56abb9e09a60fbe7b10792444c9c27987bb6d3b450fa", size = 307583, upload-time = "2026-08-17T08:22:22.541Z" }, + { url = "https://files.pythonhosted.org/packages/1c/11/cf0bc07feb2791045b6ac075d4bf64f1a5beedef2f46ae70d7104d63a19f/xxhash-4.0.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:1749f0688020209fe0d357ce1e1cd9ec9c6161ed0405ea949d24581c4c43fa91", size = 265848, upload-time = "2026-08-17T08:35:31.298Z" }, + { url = "https://files.pythonhosted.org/packages/d4/c4/7ada4bea2a2795073dfc42d96842930efbe7a0c1857ef4b522e4e90e5d83/xxhash-4.0.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:94ac8a6b8c47951173f0b67bf862bcb971bf24e493b9fbbdb0e010cbbc7d9f54", size = 284409, upload-time = "2026-08-17T08:21:23.156Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f4/d8ce83dd6b99ccfbdadaf2db968ae40334d2e5f73a0297e593b9ddb3df39/xxhash-4.0.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a33de7633c948ab2dc144af370a66e7e7af29b425dcd0f7e4f59689fb9391b53", size = 335921, upload-time = "2026-08-17T08:22:21.802Z" }, + { url = "https://files.pythonhosted.org/packages/a6/9f/f47d8724bd8bc45b395b06b7cacea2dae0d00031af1b707184a091161df6/xxhash-4.0.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:247ece770647c0aef080561fa996f9774b4dadce2d0c42eeb98229db7dcf820d", size = 487023, upload-time = "2026-08-17T08:22:19.729Z" }, + { url = "https://files.pythonhosted.org/packages/57/54/2d87098f3371cc1e42dd04d2285ad56bca4c56667bc501bff02d2b9fd6b5/xxhash-4.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a4553d36cc0b7fce1f35ba8a94dfd775aa3ed12f5eab2dc3b46ac75a0706b0bb", size = 264333, upload-time = "2026-08-17T08:35:27.001Z" }, + { url = "https://files.pythonhosted.org/packages/27/b8/93795ca5898ec7d7d0455283ad261c0fc76b4f0c0a69e86233bd7badb0bd/xxhash-4.0.1-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:87aa309a93bd5ec13f14309a305ff4e9bf74c5363fc46c264c0a22edfd5b0670", size = 20581, upload-time = "2026-08-17T08:21:39.207Z" }, + { url = "https://files.pythonhosted.org/packages/b6/96/926f7335a0a1647952c00421e8da877f658094f61336306c7cadc335c94d/xxhash-4.0.1-cp313-cp313-win32.whl", hash = "sha256:cba763d84b06bda2c38d5185dee76f1b9dfdc0789e96e476d9e10005526d0788", size = 34449, upload-time = "2026-08-17T08:22:29.362Z" }, + { url = "https://files.pythonhosted.org/packages/ea/61/8a5aeb811de093bab3434e77eff0e9461624a1a56a6a93d315d080aab2aa/xxhash-4.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:97b94fb29abf21f5f0bde15f7dbdd3a4aa2dc59f37026adc7b4bee8563b84375", size = 36520, upload-time = "2026-08-17T08:35:34.852Z" }, + { url = "https://files.pythonhosted.org/packages/04/14/97f3c74000ca36955e9cb86f6d270dcd5848b5c65afa623453f5cf2d83d6/xxhash-4.0.1-cp313-cp313-win_arm64.whl", hash = "sha256:08ed8da18cd4fd0a6a5d6a444852d8fbd0e565388a74a4937085451b5f1a312a", size = 33428, upload-time = "2026-08-17T08:21:31.713Z" }, + { url = "https://files.pythonhosted.org/packages/81/0e/ea406a02b561d3275232ccfdb3e29df80f7a65414940e3a15721c7bea40f/xxhash-4.0.1-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:af05a3f650220a6c59fa0ad2410249f2d2470a05225807c378fb67458693f8df", size = 43747, upload-time = "2026-08-17T08:22:31.37Z" }, + { url = "https://files.pythonhosted.org/packages/f9/f0/b0c94d61ccf6b5d1f8847b58ef8f923125ac4919ed5bd0eb082750ca7cbd/xxhash-4.0.1-cp314-cp314-android_24_x86_64.whl", hash = "sha256:a6e3653df1a70b8ac4191216324242e4be2bca18c9a7c10934e1bd56dc7ca15e", size = 40749, upload-time = "2026-08-17T08:22:29.431Z" }, + { url = "https://files.pythonhosted.org/packages/2f/c5/8085881a538983be0fd1c865d5df236242fea496044e2c8ca32b9f2ba39c/xxhash-4.0.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:4528cf80ebbbf57d40edfb31521ae265daa6dd636d615b1cf0ac86209579e59d", size = 34734, upload-time = "2026-08-17T08:35:33.68Z" }, + { url = "https://files.pythonhosted.org/packages/d3/94/8803d13c968fc75ca434eea991d29ac5fd8a36b4afc9a6a9803c53933db4/xxhash-4.0.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:90cb2a1c9cc503a054a19612b48ff6e8e47805f618bdb3224a07568aad03a37e", size = 35671, upload-time = "2026-08-17T08:21:48.322Z" }, + { url = "https://files.pythonhosted.org/packages/85/d5/ad91d7f0fd294190d37c08236fe661f5c4e3f83dcd1a121877a2e64681ce/xxhash-4.0.1-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a949b072ea59c6eca0811ccd9e95133cc50d2afda8d464b5b077c78f78efa269", size = 38094, upload-time = "2026-08-17T08:22:39.763Z" }, + { url = "https://files.pythonhosted.org/packages/89/f4/2b7ebdc1869caca5f02c4cba8379b631050d3c3d4adb9187e4dc1a6b8d3c/xxhash-4.0.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:79a3203aadf39637869dfea1185227d8452844d78b837e54fb1117b4d34ba5c3", size = 38244, upload-time = "2026-08-17T08:35:38.081Z" }, + { url = "https://files.pythonhosted.org/packages/90/9d/f66cf6935f528e575f1ae4d6560d376e7587569747186f4fae8777cadc1b/xxhash-4.0.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d9f3848ffaf010bdbabdbf4c25641fa258b6227ff27bc74a4d06edef521a4873", size = 35904, upload-time = "2026-08-17T08:21:37.358Z" }, + { url = "https://files.pythonhosted.org/packages/07/29/34569d7b482f0dc060074faafd163c588f915cbc3e3e218f1ffd8a3ad340/xxhash-4.0.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:9283d9dd6b44acad35118e2976fc763a065509e4118debdb61916ec322ed17b9", size = 259595, upload-time = "2026-08-17T08:22:38.153Z" }, + { url = "https://files.pythonhosted.org/packages/ce/d2/a2370acfcd48732cf5c2b87f06cfbf7fa51c0ce0dd736bde42939eb9ebf7/xxhash-4.0.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c7c642a0f79c3e3cf2965475507574d3d1a50ec71060039d60cb87358667cb2", size = 284279, upload-time = "2026-08-17T08:22:36.396Z" }, + { url = "https://files.pythonhosted.org/packages/08/15/17d33c24e6c4a1c0b9ddc5584f0c25d51d48b34bacde1416a2235a19db4b/xxhash-4.0.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:96dedccfb09a73a25751053a183159b88f4ee75f388df8166040c152ac0531c6", size = 303973, upload-time = "2026-08-17T08:35:39.22Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e0/4ec0d69ad5738729098a61e631b7ed2df22a922b0e03014b597c72bd863d/xxhash-4.0.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:81664268dba92e037b740ecf37fa02f1cab4a391f93f28e35792b3341c60648f", size = 287535, upload-time = "2026-08-17T08:21:52.158Z" }, + { url = "https://files.pythonhosted.org/packages/0f/8b/4f9b17e7a9eb71c65548ecddd9c18b84e3c18ca41c4d436ad2a3000d3f7b/xxhash-4.0.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:839f58c5bd9989875be0fd28446dbf32cace2c2cd8bf2f6762acdc38a95cd1aa", size = 519257, upload-time = "2026-08-17T08:22:43.272Z" }, + { url = "https://files.pythonhosted.org/packages/68/35/3276b3e743b8ddbed9c3f71c76d9dd6a75d72aa4e678b1447b635cfd92e0/xxhash-4.0.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffa44b4c7c5d0ffa31356b4428659516c0e47647825c74079a296b3857b6d99d", size = 268190, upload-time = "2026-08-17T08:35:44.985Z" }, + { url = "https://files.pythonhosted.org/packages/08/d4/f1555de3c96721320930dbb7988c8482d82b85970076aba1a8d40e83ad43/xxhash-4.0.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e681a6fc7e4f715252b9b5acfb30536ec7dd1f75033a32dc617e6fa95af1a3fd", size = 345553, upload-time = "2026-08-17T08:21:41.025Z" }, + { url = "https://files.pythonhosted.org/packages/ac/98/c28908f27007087b61139d290f908dd827ffd40b88af0c43f9e1a1a7ffd5/xxhash-4.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c6301d92545c591ad31c3e050aa40a5f8a4c16413f1f9e6f9322c6f0f9d2b736", size = 280499, upload-time = "2026-08-17T08:22:52.236Z" }, + { url = "https://files.pythonhosted.org/packages/a9/76/3ef57622c65816348f8196273485baab4752aae064959901e85cd867e067/xxhash-4.0.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:6efb8f21cc136c79b3e5bb747c8682d37916fb202cdbbc32182de5c4e47f821f", size = 307211, upload-time = "2026-08-17T08:22:40.815Z" }, + { url = "https://files.pythonhosted.org/packages/8a/4c/5804504bbc808968e57d6a50286dd8f8cc06e0ddd6e4ab4b1dc89ae42f35/xxhash-4.0.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:760de77279e9cf9c81d012ce0705cba13afccee9b09c480f17d778c8c5cefae8", size = 265865, upload-time = "2026-08-17T08:35:42.727Z" }, + { url = "https://files.pythonhosted.org/packages/aa/ee/8572fdfd70e7aaaf150af899871c2cc0bb88c3295ca82172a31e04ca5168/xxhash-4.0.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:a16a3fa6936e36bb1414d16a6bd012c9033e5161b68b426805b61d895392437d", size = 284545, upload-time = "2026-08-17T08:21:56.965Z" }, + { url = "https://files.pythonhosted.org/packages/c1/f8/6eadcca0904660c848b466524e82a233d16c9d2d5258433aaf3546142d86/xxhash-4.0.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:9c3c4b9aa9a27196b921197f7daf9e6c1412739df06a99cfa6e923879362eff6", size = 336022, upload-time = "2026-08-17T08:22:46.346Z" }, + { url = "https://files.pythonhosted.org/packages/27/df/4aa107b81602d6d6d09ab5a607c530d2d3a6b28e2e9a59b01875bd877c54/xxhash-4.0.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:863f3d3b44110f7243e86cf994aa5c5d88f2348b6e84ab4402fadadfbf9f7da7", size = 486671, upload-time = "2026-08-17T08:35:49.016Z" }, + { url = "https://files.pythonhosted.org/packages/45/b7/b2bf9b5301e9cd5f2e335fea8da0f5cf209a6594cb1fe77754774ad4a6fd/xxhash-4.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:63aa52659bc32bb9bd7cb5caf523b4d14429a477762cfac886132d687c1f80fc", size = 263744, upload-time = "2026-08-17T08:21:56.165Z" }, + { url = "https://files.pythonhosted.org/packages/0b/96/35b1c02177ae26234892c2310fb4822ba62411acccbf425ab8f9fd99354a/xxhash-4.0.1-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:67e57b834e07ed973cee7b6da1548ff28a56458d77696fd2a5f397f340694848", size = 20563, upload-time = "2026-08-17T08:35:11.924Z" }, + { url = "https://files.pythonhosted.org/packages/51/c2/a06300b165fbd6b0cb4a9742987f2e997a9f447ce3bf7c6ac97b862ce62a/xxhash-4.0.1-cp314-cp314-win32.whl", hash = "sha256:b6c1f9c59bbe593f88a0aad30be4150f15bd57bd64efb95feeabcb8e563f1ecd", size = 35151, upload-time = "2026-08-17T08:22:44.283Z" }, + { url = "https://files.pythonhosted.org/packages/06/96/c5b37296b78f80fc97124c0fee0c7bbd1bdb6f3b18bcd8748bb113b2d8fc/xxhash-4.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:da544672efd9ad76077928a3e6c5d894e52ce82d3bf14002db4a1bf17d1a36a2", size = 37156, upload-time = "2026-08-17T08:35:46.551Z" }, + { url = "https://files.pythonhosted.org/packages/ce/5e/248f9cd169c2fb62236bedfba246d213bce728f74901e99047e3f3c55875/xxhash-4.0.1-cp314-cp314-win_arm64.whl", hash = "sha256:d0d24a4f3fb63852cd09af46ae4b7a4d00cc8b8615a046dca543786e728d1056", size = 34379, upload-time = "2026-08-17T08:21:59.446Z" }, + { url = "https://files.pythonhosted.org/packages/58/c8/db1d37c0da0324d0298f6abd931ca1d4736e049d9f2081230a8421da74d2/xxhash-4.0.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:349775ac30372b344d2338b2a168c0a1312a644194da25b8bec476d55761a128", size = 38656, upload-time = "2026-08-17T08:22:49.119Z" }, + { url = "https://files.pythonhosted.org/packages/c5/8e/e18998ec465fb977bc74272e5bf3c2e886c13b014cbef916cd607802c709/xxhash-4.0.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:43e5f9169e73d0f0db33b5f6b8554bcce69ac278c966daf83d5eb4eb2f13829f", size = 36306, upload-time = "2026-08-17T08:35:52.853Z" }, + { url = "https://files.pythonhosted.org/packages/ef/1a/b83f86f8a987a3cbcb7e005a6824ff64aecae35abc1395a0d44ee16c3319/xxhash-4.0.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4a252fb862b0ae2590587e625f47a0e03da05cf0205e8830b67b6596c06038b1", size = 273729, upload-time = "2026-08-17T08:21:58.833Z" }, + { url = "https://files.pythonhosted.org/packages/02/4e/2db15aa8508e0cd5b632927a53b98234f24039ea65377e6cf996c06d2d4f/xxhash-4.0.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2df3ca8757dc381e75e90a4d7995a6324f58a923c7145220a7b2c0231f66fddc", size = 301083, upload-time = "2026-08-17T08:35:14.113Z" }, + { url = "https://files.pythonhosted.org/packages/26/94/ed759787ffe802bd8e31cfcdad3755cbeca2dcdafd2f790cd6f25d195199/xxhash-4.0.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:bfed61996d618eb90d6eaae0178002e3466a28b06bfc557a7a3a7266378d8c5a", size = 312745, upload-time = "2026-08-17T08:22:52.232Z" }, + { url = "https://files.pythonhosted.org/packages/45/7a/f64b4a4cc8b51e950709207f55f7f56ae9c5af6631dd31d7fb443312418c/xxhash-4.0.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9761ff4a0ffa583fe850731ad24fe82c88cccb7a2294727db0955f3279a4cb3f", size = 301419, upload-time = "2026-08-17T08:35:50.143Z" }, + { url = "https://files.pythonhosted.org/packages/a0/71/bac313b8de073569b8db3152044a7cfcce87a3fa9698c18fe9f914dee6b1/xxhash-4.0.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:edccc2ec58435a580f96a48a3ccae8cd0a480824119165dd90108718ad81ae6e", size = 534485, upload-time = "2026-08-17T08:22:11.515Z" }, + { url = "https://files.pythonhosted.org/packages/b9/0c/16b5e419f24e59507ee05626d2bb0deafdb03f9f27783bc0785a9849602e/xxhash-4.0.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4741d42d59e4e5fa1a86c17ab9c27dc8ea459c700d91b6742fdb9138d9a516cb", size = 279605, upload-time = "2026-08-17T08:22:52.934Z" }, + { url = "https://files.pythonhosted.org/packages/5f/55/5787dd6e2d8d5b61256a5039f6b18c2193c7c1de4a2fd2413288d0d9c604/xxhash-4.0.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:440c401e146ce64bdb3beb8ff0c84677b6f21307c28a34779071cecee5d4d70c", size = 358924, upload-time = "2026-08-17T08:35:58.164Z" }, + { url = "https://files.pythonhosted.org/packages/f3/68/89be41991f3b0a2e91f940bdf3128852c3ed571cf560d98ad0f67024afe4/xxhash-4.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5b7979f71d06ae45a769de0699900a246d8cb632db1e8bfdc79ec019063a503c", size = 295305, upload-time = "2026-08-17T08:22:13.683Z" }, + { url = "https://files.pythonhosted.org/packages/e6/5a/52ff0a0cc361aad393ff9a46ffe3aabbcf9c03d6c8f2612da7d553048276/xxhash-4.0.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:62198213fc3e0c56e567894b318ba45834e007d065f84ba6dc9165d21546fc56", size = 320228, upload-time = "2026-08-17T08:35:18.946Z" }, + { url = "https://files.pythonhosted.org/packages/0f/b5/91c60ff22c7f6cd5f6d7a5bad5a2cdcb4c33987dfa50bf13f0d856279b2e/xxhash-4.0.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:b3bece52127ac20044311ee73567f9f0893b5de64f9028aecc90cc740cfd525a", size = 279414, upload-time = "2026-08-17T08:23:03.212Z" }, + { url = "https://files.pythonhosted.org/packages/b9/94/9685954804d47d0390871a64bec606a0d536406382d71a784df3a5883fb4/xxhash-4.0.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:a865d2d470220e659220fdb59d5b6c4422802d8d6098e1324bc4d12444798914", size = 297594, upload-time = "2026-08-17T08:35:57.881Z" }, + { url = "https://files.pythonhosted.org/packages/89/62/b67ac9412907b7a07a2a0c08c3440b9e4480231a7b3de0767e87011e4564/xxhash-4.0.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:8580aab306888224074c7edeec734de0c3c5ccde65b2da4e6c9a5e28f7c0a1bd", size = 348526, upload-time = "2026-08-17T08:22:18.571Z" }, + { url = "https://files.pythonhosted.org/packages/37/ed/6723cc49a9f567d52d01fd7c1741b0f2e3a13e71d15f7ac49d753a20c115/xxhash-4.0.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:2d52dc7c33c1b83082b707f6b7814dc76d2faaa2ea62bd9c5fab4b36f83c087f", size = 499307, upload-time = "2026-08-17T08:22:56.52Z" }, + { url = "https://files.pythonhosted.org/packages/fd/2e/7b10e101ab988d93b791023be7191d7661271d6ab31ac082276b9091042a/xxhash-4.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6a9f98af872355e0c02439e48583958eee00e60b928bb20476460d9d40cb7b4e", size = 274989, upload-time = "2026-08-17T08:36:01.834Z" }, + { url = "https://files.pythonhosted.org/packages/9b/8d/7eabcc8d29cce40621443cff24c07d7306ef574b8956c47ac59f21098005/xxhash-4.0.1-cp314-cp314t-win32.whl", hash = "sha256:a14578102a6081465aec9cf73c76c3cd3f79f0709bdb3b8ae7ab0b54c9d8b089", size = 35482, upload-time = "2026-08-17T08:22:32.336Z" }, + { url = "https://files.pythonhosted.org/packages/ca/89/2a4268e1971f63038b79fb75e3b9c8de942cd77acabbb0c5625352a31940/xxhash-4.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:c57963970d359a72262f7fe6be88f945e2334d4bc41462b7f08c37b0abf35ca6", size = 37490, upload-time = "2026-08-17T08:35:22.475Z" }, + { url = "https://files.pythonhosted.org/packages/90/7b/950ecab1fe4cf421d0a6211ddd9a0ac82e39e55c45a111ceb90953dc6c9a/xxhash-4.0.1-cp314-cp314t-win_arm64.whl", hash = "sha256:b659fad79c99b0238c7ad7e9d7dbf4eebfea9097c2dba65fa0a4d18a25b29a2f", size = 34596, upload-time = "2026-08-17T08:23:10.001Z" }, + { url = "https://files.pythonhosted.org/packages/c4/03/7dc3b85fac10751613bfedb0e120734e0e8710054abad3f931e9d3843a14/xxhash-4.0.1-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:5adf927dca8c47fde7e683fe69efdd81bc865c4db1fb6bb00b391e2b6185207b", size = 43749, upload-time = "2026-08-17T08:36:00.47Z" }, + { url = "https://files.pythonhosted.org/packages/a5/55/bfac071c5b1c6d6a3d48ab1ab96a15e958a1d7061f4afc97804292d87264/xxhash-4.0.1-cp315-cp315-android_24_x86_64.whl", hash = "sha256:c30dd1af66a820820398b26e0d74e7a9aa43cae705924f23ed828cd8e5c26c3d", size = 40758, upload-time = "2026-08-17T08:22:30.209Z" }, + { url = "https://files.pythonhosted.org/packages/79/87/49a260e685d1a74c56a69432a8ee0527ddcbd684a3c51f87edc3b75639c5/xxhash-4.0.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:1bc591533fc975614f7e13594daee76af96b8e1fbcf8de76c8773858fa9e7cea", size = 34788, upload-time = "2026-08-17T08:23:09.014Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ef/50d72ed2170dae872e1c0fe333d0908e0a2afbffe74c5c9037d5406a4b89/xxhash-4.0.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:567cbc630302a46a8ecfd943b309ccf5372bb3718f1f3762d452df30f033bcf0", size = 35746, upload-time = "2026-08-17T08:36:05.557Z" }, + { url = "https://files.pythonhosted.org/packages/66/f0/969deaa2bab3bfd5ad5b023442124d2255b9961eef6f797ec74eb8683bdf/xxhash-4.0.1-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:e998cb3685b92101ec5de0fb4d9485cf01e50bc418211955c55d98064664cf4c", size = 38098, upload-time = "2026-08-17T08:22:36.906Z" }, + { url = "https://files.pythonhosted.org/packages/86/aa/45ed7d7b8d7b66202a47bf8ff3b77cea28d2ea54dfcdd202b4cfe043e3dc/xxhash-4.0.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:c3074db513c81f764053e3da079312ecf85a50d8350c71f4cc0105d9662a9e6c", size = 38251, upload-time = "2026-08-17T08:35:25.774Z" }, + { url = "https://files.pythonhosted.org/packages/f1/9d/45e7520a7856e13800a5dc8cd038d34c6372429465b163af0c5722f16918/xxhash-4.0.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:3088dadbffa33c29e0518578430a7dff2e901a212e487aefa5faaa0dc06dad34", size = 35986, upload-time = "2026-08-17T08:23:25.854Z" }, + { url = "https://files.pythonhosted.org/packages/9e/0e/5ad466e5fea18c9f9bdc5828c0506f62190061b4a1b0e688aa54969d0a9e/xxhash-4.0.1-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:1b50223d92df94d54e1a31469335a2c74b16692e6c1cb726f1e6949514458706", size = 264609, upload-time = "2026-08-17T08:36:04.229Z" }, + { url = "https://files.pythonhosted.org/packages/aa/cf/8f269f85217e3dbd45e31e25e46cc26f3aff0e159ef05d228b4b982c778c/xxhash-4.0.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:427b62d62d4f967fbb10b82a3813e4875c2a6e7e7634739f17265b650c7f65a6", size = 285910, upload-time = "2026-08-17T08:22:38.589Z" }, + { url = "https://files.pythonhosted.org/packages/ca/30/2fc1a16ee0f9501d074b798ebfae52e24fa602c7117f5c4b81de71eada72/xxhash-4.0.1-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c6370189e8e66b7e608f533b939a9de092ddca6cce084ca0d3d414d2ed5b5d59", size = 306566, upload-time = "2026-08-17T08:23:16.895Z" }, + { url = "https://files.pythonhosted.org/packages/e0/a7/08375cf2b997e1903663fe7525c5973b1987a4f8ad2b8d47463e9143f2ee/xxhash-4.0.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ec1a470c6db94ac4589c203921e89ac1bc13e796a8b1784d8135e1893559cd3b", size = 287978, upload-time = "2026-08-17T08:36:09.296Z" }, + { url = "https://files.pythonhosted.org/packages/b2/e5/90a7b404c11add9e53a497d06236152852490c3b2f21e468d97a58f26afe/xxhash-4.0.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:37f667dee0f867c42894b34e2a6fe26bf195c0ea4683d9d2b713db023f242c3a", size = 520098, upload-time = "2026-08-17T08:22:41.565Z" }, + { url = "https://files.pythonhosted.org/packages/11/02/7fba10b1b17eb46308f09cc0a4ed513d74dff16b1e22a1c439f011c77129/xxhash-4.0.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f18732adcc271741bd651c3e56fa519d8a237d2cccda01fe3afb226bf87f783b", size = 268273, upload-time = "2026-08-17T08:35:29.043Z" }, + { url = "https://files.pythonhosted.org/packages/54/49/c21b228877357a3be43eeeaa22182ad1685796f415390ada475922c084e4/xxhash-4.0.1-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0b42a5a26607e4b2409fea174773a66f2dff9dfdbf2c1a851bb7b804e2c97535", size = 350164, upload-time = "2026-08-17T08:23:29.494Z" }, + { url = "https://files.pythonhosted.org/packages/00/3c/c15bb4aa33d94b78a5553b52e7fa1070565f0199925aeadec3871de20ce9/xxhash-4.0.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:99166cc98637e8bf550cda2aab07f4f1d5f899c45fbd721801aeabcc9d404824", size = 281975, upload-time = "2026-08-17T08:36:08.139Z" }, + { url = "https://files.pythonhosted.org/packages/18/7a/b1d0388315fe7752b7725b68a912667526a1dd48ed492fcc031ac03f4b52/xxhash-4.0.1-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:6cf633df84d80a1668fcf61e330791dae46825e395549e7d34f376411e75088a", size = 307872, upload-time = "2026-08-17T08:22:42.206Z" }, + { url = "https://files.pythonhosted.org/packages/b4/a1/037cb2dd8cf725c9565dfe3712b2915c0e0276a9154913dbfcbcecbeb672/xxhash-4.0.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:e259bb7e1e2d8de6b35f430f5c7220b1c0ebf3962d1ba7ec7545980d5931edb8", size = 268241, upload-time = "2026-08-17T08:23:23.997Z" }, + { url = "https://files.pythonhosted.org/packages/c6/a9/67c44422d0ee082169b238ce24bd2796b82d7c21ed953471365df8c508d8/xxhash-4.0.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:704381264b36a18b9c62ecbabe2e71d0fc58c77c129c15355c989b10bf05b6b0", size = 284970, upload-time = "2026-08-17T08:36:13.476Z" }, + { url = "https://files.pythonhosted.org/packages/7f/d0/254a5f51c4014cacc77a26f321372338b924f54e89efb730164ee336d850/xxhash-4.0.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:e90b4bcf1d9eb1010fdaee7c9209fb667e74c0684f3ba17f9032bd7319da90c9", size = 338074, upload-time = "2026-08-17T08:22:51.166Z" }, + { url = "https://files.pythonhosted.org/packages/64/03/f21c4830118d72ef3a958ce8bf2152f49e0d4cf200907616c9be6caf372a/xxhash-4.0.1-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:a65785e653573fcd1e33062760ab4c3c3440e8e910765018e4b6ed4ad07b54a0", size = 487626, upload-time = "2026-08-17T08:35:32.768Z" }, + { url = "https://files.pythonhosted.org/packages/45/1f/268a689d741d7da649317eb4ce41760140beb4179aaf43a7216fdbe8100c/xxhash-4.0.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e3996ff9b6f99180357024336bf5749a8ad6476a9a2523e535c5212b995b12a2", size = 263852, upload-time = "2026-08-17T08:23:41.871Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f5/adaf8101cd7f143191a0b390600294d83924b32cb13770fde8803dce27a2/xxhash-4.0.1-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:99054b838b74d8d3995ea0d410976ae967c46207ae22d6ddfc535e809197dab9", size = 20569, upload-time = "2026-08-17T08:36:11.952Z" }, + { url = "https://files.pythonhosted.org/packages/ee/2c/56a5eb8c993420fc07114c08f447a2b66ee996510b4764cb368b9b44c9f0/xxhash-4.0.1-cp315-cp315-win32.whl", hash = "sha256:6c45258a37fc22721395c09927cb982d3e7a83607cab15be7e2416501bd3a330", size = 35145, upload-time = "2026-08-17T08:22:50.038Z" }, + { url = "https://files.pythonhosted.org/packages/67/c7/65f210db43e62157d0fef3b4d4d7b394821e7733c8bb4ece49f91410a725/xxhash-4.0.1-cp315-cp315-win_amd64.whl", hash = "sha256:0ab851b45c70d4992be7cdeeee16f97a0b677408c758c4b1efb1cfe8030bfd37", size = 37161, upload-time = "2026-08-17T08:23:32.438Z" }, + { url = "https://files.pythonhosted.org/packages/33/ae/1a641d1d60ba219756d9ebe907ff0ecf4445adcf4fa96f6e3da57b91d439/xxhash-4.0.1-cp315-cp315-win_arm64.whl", hash = "sha256:a5b21b42a01a343096a1c018d35e9b7aec9c7065dda53ae8da071e37478b2cea", size = 34378, upload-time = "2026-08-17T08:36:15.912Z" }, + { url = "https://files.pythonhosted.org/packages/48/7f/7698b320b251806d1249e513922a626f19027e104c829a611272250350eb/xxhash-4.0.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:44ab12e8cd17d4f001769f00ad465208b4bcb897ed29e65f058f74466b57a98f", size = 38610, upload-time = "2026-08-17T08:22:55.203Z" }, + { url = "https://files.pythonhosted.org/packages/c0/3d/436497e775b647b3b3e9a4ffe8c76c59fa4aa7a9fab6447cb59acf1b50ea/xxhash-4.0.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:45e88111ebe331de478ef8d4293efbe88f3cf8b863386c9a2357136b838e1af0", size = 36378, upload-time = "2026-08-17T08:35:36.18Z" }, + { url = "https://files.pythonhosted.org/packages/e3/d8/17a4f8182b9257898aa2a77c2a45f70233eb8e50681a280e8e09d2ee76e9/xxhash-4.0.1-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:bf430c587f447a554c53768ad76b9846fe7c5632180ef6f69c4fce8b0552fbd0", size = 273559, upload-time = "2026-08-17T08:23:51.075Z" }, + { url = "https://files.pythonhosted.org/packages/83/28/121bd5a5c5adb88e0da772c7bef61964cf9da92956a7a237c7d24c4351b8/xxhash-4.0.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:adbd48b30e3f82c89fb2b3e6a87cdd28d113b190a5ed0ee2dee286323ee9a621", size = 299133, upload-time = "2026-08-17T08:36:14.731Z" }, + { url = "https://files.pythonhosted.org/packages/11/8f/57c7b6e04642ed738a0d08a31bed7fc63fdacb661d665f98739cc9751b62/xxhash-4.0.1-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e71b34978e77868cbf2d18c5206a4603f9c644dd7181bec5643bd40141d3b8c5", size = 314527, upload-time = "2026-08-17T08:22:54.224Z" }, + { url = "https://files.pythonhosted.org/packages/8e/18/42793917dbab0ea1ff71458aea4875e17a7263f2797b798af048dc81e867/xxhash-4.0.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:488ca5c5e28ef56ec4bbb12f835b3f1cbecc5f3510062e70117bc6594851932a", size = 299199, upload-time = "2026-08-17T08:23:36.864Z" }, + { url = "https://files.pythonhosted.org/packages/37/60/51dc92443923d8e908d5614f1145d8d696450f9d6c8f1abe243c6f2a0222/xxhash-4.0.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:421b94f3ba7067958d02e38960d987756347aa150df06df11aa68ae1af78c619", size = 531967, upload-time = "2026-08-17T08:36:18.66Z" }, + { url = "https://files.pythonhosted.org/packages/88/c5/d0de77de09661fac71742c4155b1cd65e274f7cc277819d702b6c8ff2db5/xxhash-4.0.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f33cf0baa91eccd2cb7b62bf00f10c2264ef578b71dd33a12962e71a36eb4d32", size = 278764, upload-time = "2026-08-17T08:22:58.15Z" }, + { url = "https://files.pythonhosted.org/packages/08/9a/589929c655aba1bfb2c41ee03e50eec1547c39c3042a66bda9c173a9614b/xxhash-4.0.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:23a4376b4a3183cb50d4d2a3179f887a7773cc695eb2c908e551bec3221b8c60", size = 359876, upload-time = "2026-08-17T08:35:40.35Z" }, + { url = "https://files.pythonhosted.org/packages/3e/a8/c1d8c94d54d91db2215565f4b4151c1593af3e6d27ac4c00fd1e8d714a02/xxhash-4.0.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:38c3d22129a6958846a3098d68bc8e661704461c0be4793ae28836e4690c8478", size = 293548, upload-time = "2026-08-17T08:23:54.951Z" }, + { url = "https://files.pythonhosted.org/packages/8b/67/85d8abca94508a4dd10561d9dea3e6e68843c6986dd6d9c1b3729c8622e4/xxhash-4.0.1-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:87cbdec1a7dd930079671a60b249f3ca4e773e6fbd0676e21e36fdc9dd0f3b00", size = 318780, upload-time = "2026-08-17T08:36:17.623Z" }, + { url = "https://files.pythonhosted.org/packages/1b/16/2b920ed456b9cdcfc99ddc20c3afe42f9f807ee5850773c12fd891f3c08d/xxhash-4.0.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:6cbf4e21ef0890804b5bb9ad25c48f9c127758d7f6c66bef374efcacc63c738a", size = 277582, upload-time = "2026-08-17T08:22:57.156Z" }, + { url = "https://files.pythonhosted.org/packages/fa/cc/5811b5997aebb8452047f5800d32fc50eaa29d0ba08d4e426f84450b9c2f/xxhash-4.0.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:c101180495cb4ba3617b279a944345c53a5e73b0c150053d1fa8d8af32de9579", size = 295116, upload-time = "2026-08-17T08:23:40.868Z" }, + { url = "https://files.pythonhosted.org/packages/2d/dc/c2f3f9c2f4d6aadb79f17a9f1c9a7ee82638cc873680da044cf29537d2ee/xxhash-4.0.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:c0e6ccc2b19ec8a726b2e26062ac71ea63e15500d6bf85910e42481844fdffc1", size = 347065, upload-time = "2026-08-17T08:36:21.618Z" }, + { url = "https://files.pythonhosted.org/packages/a2/4c/750cc642c92252e10772ec09e1a1d995581ba4c3ceb24f6e2d57c7ce47ca/xxhash-4.0.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:8bcba9456242ebf180a04d9443812fd85ffe6bd12bda464dd116fcece8886ff3", size = 497208, upload-time = "2026-08-17T08:23:17.88Z" }, + { url = "https://files.pythonhosted.org/packages/6c/2d/58693cb13d6395f39b6b9bb40c5e0db53a5df7c9fce805aa7e792f64a1a5/xxhash-4.0.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:83b8c2013edb5dc1f9e7268b6496130705bc48d79c86bb8817b3d210b81a5513", size = 274338, upload-time = "2026-08-17T08:35:44.062Z" }, + { url = "https://files.pythonhosted.org/packages/4a/08/9aa9787586d9b3e92d63343ce7dc24f0f445fd9e74ff5d6e85dd82233df5/xxhash-4.0.1-cp315-cp315t-win32.whl", hash = "sha256:aa6ccc7f31018484d652cf52db020003433f3c9fa83189c028bd807d2adde503", size = 35471, upload-time = "2026-08-17T08:24:05.795Z" }, + { url = "https://files.pythonhosted.org/packages/f0/ab/4615789c333bee331ac417885c50105715eeb8244bfc68d2bc37dcfd63ca/xxhash-4.0.1-cp315-cp315t-win_amd64.whl", hash = "sha256:daade8936c4deaaf7b01561324ce438ba4f885d717e9adc62b4d67212ad7d7bd", size = 37488, upload-time = "2026-08-17T08:36:19.929Z" }, + { url = "https://files.pythonhosted.org/packages/fb/81/49f718beb0c55d0411bc4bd90b50a3fbe5863a0e97a2f4d11682ba13d298/xxhash-4.0.1-cp315-cp315t-win_arm64.whl", hash = "sha256:f00330ac7e24769e2032203f2b01794d670916b0c1799fd261340f1af9499875", size = 34590, upload-time = "2026-08-17T08:23:19.597Z" }, + { url = "https://files.pythonhosted.org/packages/86/79/9127ff42a887a348dc4ce3211cf1a962836887adee6f57078132bfba78b4/xxhash-4.0.1-graalpy312-graalpy250_312_native-macosx_10_13_x86_64.whl", hash = "sha256:ff48915bf1871a1f19f74c11834c6329443d306cedc0c05fe7fe617810422a80", size = 31836, upload-time = "2026-08-17T08:36:28.261Z" }, + { url = "https://files.pythonhosted.org/packages/0a/e6/f238693bfdd642adb59c99683964d46d9947fe721ff44d3bd850ae675407/xxhash-4.0.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:4a76345f5aceb4ec404918edf9c7f2b5507db864dc0d7455982009ac0890b57b", size = 34453, upload-time = "2026-08-17T08:23:49.795Z" }, + { url = "https://files.pythonhosted.org/packages/40/4b/796ace33cdfb75c91ba6d11615c3bd436355b9f3103e05865bbee9abce57/xxhash-4.0.1-graalpy312-graalpy250_312_native-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:31d86f9e81f3e84e00131ac7c54caf5119ae4ddd82c09c31cff597c813ce1ee2", size = 38488, upload-time = "2026-08-17T08:23:59.901Z" }, + { url = "https://files.pythonhosted.org/packages/ad/23/2d549e5d5d7759eaf9ac2d2d2ab81ff60f1bb2b52cdaae8e5ec5c6524354/xxhash-4.0.1-graalpy312-graalpy250_312_native-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:deca2a30d983d240b8375ec2ee0a4288e72042827fc61df2f7671f8467e4cb2f", size = 38206, upload-time = "2026-08-17T08:36:32.193Z" }, + { url = "https://files.pythonhosted.org/packages/79/98/1ee576b27f78e6107ee4ea8ac03e8a52888dff256e57d560f8282c195563/xxhash-4.0.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:7c343ee174d417a44d0c3355602c0cbbfa52a04d1bbbf1723378c7d2c8f60626", size = 37127, upload-time = "2026-08-17T08:23:42.705Z" }, + { url = "https://files.pythonhosted.org/packages/c9/c5/8b528f4a394a1eabfd5d8b4271f24fff67fa1aebe58bdd3c64967662e6fe/xxhash-4.0.1-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:26fe6238c2d5b11ed5063b9bf4eb290624b004fd074688da6bb079bd564f10d7", size = 36450, upload-time = "2026-08-17T08:35:59.217Z" }, + { url = "https://files.pythonhosted.org/packages/b6/03/909926dcedb64ceee629e18d8dffa758f9d3fdbe01e25530ce2bf0eaf9d0/xxhash-4.0.1-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:e53926e76131a74e79cc0b39fa712c227875f180afc68646bd1e1d8a17e60313", size = 33467, upload-time = "2026-08-17T08:24:12.924Z" }, + { url = "https://files.pythonhosted.org/packages/13/b5/ad50456fbfed07f29169bc3fd34e70cbee306a88c17d1a1141a7638de0ee/xxhash-4.0.1-pp310-pypy310_pp73-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:0718ad66f4ded2411f8e62bdba549ee71e313a2d26ef5060ca3fdbf29897dd3c", size = 48048, upload-time = "2026-08-17T08:36:30.847Z" }, + { url = "https://files.pythonhosted.org/packages/33/c4/83cfe6b591a3067ab3f1339931c91211a8b3864d0ea76ad8184f0c1b0515/xxhash-4.0.1-pp310-pypy310_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c2200b98a805351cb3142ae4e1fdcc9e91b5e20f5d30d4862b0b96f92558f4e", size = 42719, upload-time = "2026-08-17T08:23:53.581Z" }, + { url = "https://files.pythonhosted.org/packages/20/2e/0f654f2831abba09d502751e38816759086dd92749501b128b7c3676ea87/xxhash-4.0.1-pp310-pypy310_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ea5ecf800b45bdb34afe05a1d0dae1f8ea02a290e50636dccd399063f6b180f8", size = 39477, upload-time = "2026-08-17T08:24:03.735Z" }, + { url = "https://files.pythonhosted.org/packages/3b/d4/375b9e4b719ee70e0a6d9e98e2b60aab09efd59f46c7871a112a2e6b0fcb/xxhash-4.0.1-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:ce6d5cc94a50291d080259a126cbf1e9ba4ac861e6429d2f3cdbb1474f51945d", size = 37244, upload-time = "2026-08-17T08:36:35.452Z" }, + { url = "https://files.pythonhosted.org/packages/ea/4f/e0648288a17d0d1084ca4f7bef206097831988fc86af74aa1dff8f1fbd68/xxhash-4.0.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:554f87034635bcec47c5d72447bf3db7e02da1bf493a0ada010db28a76f891c6", size = 36333, upload-time = "2026-08-17T08:23:52.913Z" }, + { url = "https://files.pythonhosted.org/packages/22/15/34b7f72e9b5a8bfd7e6178de9e1e342bc3de9f07111a5ae26c00506d9edf/xxhash-4.0.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:3c2445edafc300cc40feb6a25a8356a971c30cd0bf47b5349c2ad74c508343b1", size = 33519, upload-time = "2026-08-17T08:36:03.04Z" }, + { url = "https://files.pythonhosted.org/packages/06/4b/e0af324ccf701bf84a7a060bef11c915d45d9e3c5b9caf5b94d62ecb040b/xxhash-4.0.1-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:bdd16718b63aa3ebd68aabb79021a40e47c81374852d41a306b9453141bbcbee", size = 47995, upload-time = "2026-08-17T08:24:14.335Z" }, + { url = "https://files.pythonhosted.org/packages/59/46/cc7130e6ca6b41ab72eb6a03177b933c7c74145545c99a8610ecc208c449/xxhash-4.0.1-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8b99ebaf9e816ac5069423b1367ee7e8078fbcebcf62545506bb0608d2f4f468", size = 42725, upload-time = "2026-08-17T08:36:34.144Z" }, + { url = "https://files.pythonhosted.org/packages/1c/24/4f26ff9a7dd0998f6d1036bdddef7ce3e78972a74f7fffa7967e7bc3b7e4/xxhash-4.0.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f484ed57bb3e4142f9d6439568658c38be5f94b702ba00a1ff32c69783b6c66d", size = 39532, upload-time = "2026-08-17T08:23:57.556Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f3/1ac078fc8fceadcf066469acecacb35d2821cbfaf7d6fc5ac2107c7a314d/xxhash-4.0.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:fac4832b638000106207bc44e44b9616a6a416aaee56c62b01d61f3705e49f58", size = 37252, upload-time = "2026-08-17T08:24:06.652Z" }, +] + [[package]] name = "xyzservices" version = "2026.3.0" @@ -5623,3 +6025,93 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3f/6a/0eab0eb311af6a07cde15ca58d5d720cbfa02cd509e4c7fb5fa20cda0b46/zensical-0.0.45-cp310-abi3-win32.whl", hash = "sha256:a1dd63a5efb8d0e5f2fadf862f02771a279dc5cbe9a982700194650065758f01", size = 12257083, upload-time = "2026-06-09T11:23:26.769Z" }, { url = "https://files.pythonhosted.org/packages/1f/cd/b117e749c60b1d1e16b8450db1355f69f38376f783b8c6c8815202988933/zensical-0.0.45-cp310-abi3-win_amd64.whl", hash = "sha256:1f2c0e69839ce4274bde34d18139d3b0d96bbf02b245ada46243590c9eedebc1", size = 12498335, upload-time = "2026-06-09T11:23:29.702Z" }, ] + +[[package]] +name = "zstandard" +version = "0.25.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/7a/28efd1d371f1acd037ac64ed1c5e2b41514a6cc937dd6ab6a13ab9f0702f/zstandard-0.25.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e59fdc271772f6686e01e1b3b74537259800f57e24280be3f29c8a0deb1904dd", size = 795256, upload-time = "2025-09-14T22:15:56.415Z" }, + { url = "https://files.pythonhosted.org/packages/96/34/ef34ef77f1ee38fc8e4f9775217a613b452916e633c4f1d98f31db52c4a5/zstandard-0.25.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:4d441506e9b372386a5271c64125f72d5df6d2a8e8a2a45a0ae09b03cb781ef7", size = 640565, upload-time = "2025-09-14T22:15:58.177Z" }, + { url = "https://files.pythonhosted.org/packages/9d/1b/4fdb2c12eb58f31f28c4d28e8dc36611dd7205df8452e63f52fb6261d13e/zstandard-0.25.0-cp310-cp310-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:ab85470ab54c2cb96e176f40342d9ed41e58ca5733be6a893b730e7af9c40550", size = 5345306, upload-time = "2025-09-14T22:16:00.165Z" }, + { url = "https://files.pythonhosted.org/packages/73/28/a44bdece01bca027b079f0e00be3b6bd89a4df180071da59a3dd7381665b/zstandard-0.25.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:e05ab82ea7753354bb054b92e2f288afb750e6b439ff6ca78af52939ebbc476d", size = 5055561, upload-time = "2025-09-14T22:16:02.22Z" }, + { url = "https://files.pythonhosted.org/packages/e9/74/68341185a4f32b274e0fc3410d5ad0750497e1acc20bd0f5b5f64ce17785/zstandard-0.25.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:78228d8a6a1c177a96b94f7e2e8d012c55f9c760761980da16ae7546a15a8e9b", size = 5402214, upload-time = "2025-09-14T22:16:04.109Z" }, + { url = "https://files.pythonhosted.org/packages/8b/67/f92e64e748fd6aaffe01e2b75a083c0c4fd27abe1c8747fee4555fcee7dd/zstandard-0.25.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:2b6bd67528ee8b5c5f10255735abc21aa106931f0dbaf297c7be0c886353c3d0", size = 5449703, upload-time = "2025-09-14T22:16:06.312Z" }, + { url = "https://files.pythonhosted.org/packages/fd/e5/6d36f92a197c3c17729a2125e29c169f460538a7d939a27eaaa6dcfcba8e/zstandard-0.25.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4b6d83057e713ff235a12e73916b6d356e3084fd3d14ced499d84240f3eecee0", size = 5556583, upload-time = "2025-09-14T22:16:08.457Z" }, + { url = "https://files.pythonhosted.org/packages/d7/83/41939e60d8d7ebfe2b747be022d0806953799140a702b90ffe214d557638/zstandard-0.25.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:9174f4ed06f790a6869b41cba05b43eeb9a35f8993c4422ab853b705e8112bbd", size = 5045332, upload-time = "2025-09-14T22:16:10.444Z" }, + { url = "https://files.pythonhosted.org/packages/b3/87/d3ee185e3d1aa0133399893697ae91f221fda79deb61adbe998a7235c43f/zstandard-0.25.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:25f8f3cd45087d089aef5ba3848cd9efe3ad41163d3400862fb42f81a3a46701", size = 5572283, upload-time = "2025-09-14T22:16:12.128Z" }, + { url = "https://files.pythonhosted.org/packages/0a/1d/58635ae6104df96671076ac7d4ae7816838ce7debd94aecf83e30b7121b0/zstandard-0.25.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3756b3e9da9b83da1796f8809dd57cb024f838b9eeafde28f3cb472012797ac1", size = 4959754, upload-time = "2025-09-14T22:16:14.225Z" }, + { url = "https://files.pythonhosted.org/packages/75/d6/57e9cb0a9983e9a229dd8fd2e6e96593ef2aa82a3907188436f22b111ccd/zstandard-0.25.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:81dad8d145d8fd981b2962b686b2241d3a1ea07733e76a2f15435dfb7fb60150", size = 5266477, upload-time = "2025-09-14T22:16:16.343Z" }, + { url = "https://files.pythonhosted.org/packages/d1/a9/ee891e5edf33a6ebce0a028726f0bbd8567effe20fe3d5808c42323e8542/zstandard-0.25.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:a5a419712cf88862a45a23def0ae063686db3d324cec7edbe40509d1a79a0aab", size = 5440914, upload-time = "2025-09-14T22:16:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/58/08/a8522c28c08031a9521f27abc6f78dbdee7312a7463dd2cfc658b813323b/zstandard-0.25.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:e7360eae90809efd19b886e59a09dad07da4ca9ba096752e61a2e03c8aca188e", size = 5819847, upload-time = "2025-09-14T22:16:20.559Z" }, + { url = "https://files.pythonhosted.org/packages/6f/11/4c91411805c3f7b6f31c60e78ce347ca48f6f16d552fc659af6ec3b73202/zstandard-0.25.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:75ffc32a569fb049499e63ce68c743155477610532da1eb38e7f24bf7cd29e74", size = 5363131, upload-time = "2025-09-14T22:16:22.206Z" }, + { url = "https://files.pythonhosted.org/packages/ef/d6/8c4bd38a3b24c4c7676a7a3d8de85d6ee7a983602a734b9f9cdefb04a5d6/zstandard-0.25.0-cp310-cp310-win32.whl", hash = "sha256:106281ae350e494f4ac8a80470e66d1fe27e497052c8d9c3b95dc4cf1ade81aa", size = 436469, upload-time = "2025-09-14T22:16:25.002Z" }, + { url = "https://files.pythonhosted.org/packages/93/90/96d50ad417a8ace5f841b3228e93d1bb13e6ad356737f42e2dde30d8bd68/zstandard-0.25.0-cp310-cp310-win_amd64.whl", hash = "sha256:ea9d54cc3d8064260114a0bbf3479fc4a98b21dffc89b3459edd506b69262f6e", size = 506100, upload-time = "2025-09-14T22:16:23.569Z" }, + { url = "https://files.pythonhosted.org/packages/2a/83/c3ca27c363d104980f1c9cee1101cc8ba724ac8c28a033ede6aab89585b1/zstandard-0.25.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:933b65d7680ea337180733cf9e87293cc5500cc0eb3fc8769f4d3c88d724ec5c", size = 795254, upload-time = "2025-09-14T22:16:26.137Z" }, + { url = "https://files.pythonhosted.org/packages/ac/4d/e66465c5411a7cf4866aeadc7d108081d8ceba9bc7abe6b14aa21c671ec3/zstandard-0.25.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a3f79487c687b1fc69f19e487cd949bf3aae653d181dfb5fde3bf6d18894706f", size = 640559, upload-time = "2025-09-14T22:16:27.973Z" }, + { url = "https://files.pythonhosted.org/packages/12/56/354fe655905f290d3b147b33fe946b0f27e791e4b50a5f004c802cb3eb7b/zstandard-0.25.0-cp311-cp311-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:0bbc9a0c65ce0eea3c34a691e3c4b6889f5f3909ba4822ab385fab9057099431", size = 5348020, upload-time = "2025-09-14T22:16:29.523Z" }, + { url = "https://files.pythonhosted.org/packages/3b/13/2b7ed68bd85e69a2069bcc72141d378f22cae5a0f3b353a2c8f50ef30c1b/zstandard-0.25.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:01582723b3ccd6939ab7b3a78622c573799d5d8737b534b86d0e06ac18dbde4a", size = 5058126, upload-time = "2025-09-14T22:16:31.811Z" }, + { url = "https://files.pythonhosted.org/packages/c9/dd/fdaf0674f4b10d92cb120ccff58bbb6626bf8368f00ebfd2a41ba4a0dc99/zstandard-0.25.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:5f1ad7bf88535edcf30038f6919abe087f606f62c00a87d7e33e7fc57cb69fcc", size = 5405390, upload-time = "2025-09-14T22:16:33.486Z" }, + { url = "https://files.pythonhosted.org/packages/0f/67/354d1555575bc2490435f90d67ca4dd65238ff2f119f30f72d5cde09c2ad/zstandard-0.25.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:06acb75eebeedb77b69048031282737717a63e71e4ae3f77cc0c3b9508320df6", size = 5452914, upload-time = "2025-09-14T22:16:35.277Z" }, + { url = "https://files.pythonhosted.org/packages/bb/1f/e9cfd801a3f9190bf3e759c422bbfd2247db9d7f3d54a56ecde70137791a/zstandard-0.25.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9300d02ea7c6506f00e627e287e0492a5eb0371ec1670ae852fefffa6164b072", size = 5559635, upload-time = "2025-09-14T22:16:37.141Z" }, + { url = "https://files.pythonhosted.org/packages/21/88/5ba550f797ca953a52d708c8e4f380959e7e3280af029e38fbf47b55916e/zstandard-0.25.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:bfd06b1c5584b657a2892a6014c2f4c20e0db0208c159148fa78c65f7e0b0277", size = 5048277, upload-time = "2025-09-14T22:16:38.807Z" }, + { url = "https://files.pythonhosted.org/packages/46/c0/ca3e533b4fa03112facbe7fbe7779cb1ebec215688e5df576fe5429172e0/zstandard-0.25.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:f373da2c1757bb7f1acaf09369cdc1d51d84131e50d5fa9863982fd626466313", size = 5574377, upload-time = "2025-09-14T22:16:40.523Z" }, + { url = "https://files.pythonhosted.org/packages/12/9b/3fb626390113f272abd0799fd677ea33d5fc3ec185e62e6be534493c4b60/zstandard-0.25.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6c0e5a65158a7946e7a7affa6418878ef97ab66636f13353b8502d7ea03c8097", size = 4961493, upload-time = "2025-09-14T22:16:43.3Z" }, + { url = "https://files.pythonhosted.org/packages/cb/d3/23094a6b6a4b1343b27ae68249daa17ae0651fcfec9ed4de09d14b940285/zstandard-0.25.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:c8e167d5adf59476fa3e37bee730890e389410c354771a62e3c076c86f9f7778", size = 5269018, upload-time = "2025-09-14T22:16:45.292Z" }, + { url = "https://files.pythonhosted.org/packages/8c/a7/bb5a0c1c0f3f4b5e9d5b55198e39de91e04ba7c205cc46fcb0f95f0383c1/zstandard-0.25.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:98750a309eb2f020da61e727de7d7ba3c57c97cf6213f6f6277bb7fb42a8e065", size = 5443672, upload-time = "2025-09-14T22:16:47.076Z" }, + { url = "https://files.pythonhosted.org/packages/27/22/503347aa08d073993f25109c36c8d9f029c7d5949198050962cb568dfa5e/zstandard-0.25.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:22a086cff1b6ceca18a8dd6096ec631e430e93a8e70a9ca5efa7561a00f826fa", size = 5822753, upload-time = "2025-09-14T22:16:49.316Z" }, + { url = "https://files.pythonhosted.org/packages/e2/be/94267dc6ee64f0f8ba2b2ae7c7a2df934a816baaa7291db9e1aa77394c3c/zstandard-0.25.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:72d35d7aa0bba323965da807a462b0966c91608ef3a48ba761678cb20ce5d8b7", size = 5366047, upload-time = "2025-09-14T22:16:51.328Z" }, + { url = "https://files.pythonhosted.org/packages/7b/a3/732893eab0a3a7aecff8b99052fecf9f605cf0fb5fb6d0290e36beee47a4/zstandard-0.25.0-cp311-cp311-win32.whl", hash = "sha256:f5aeea11ded7320a84dcdd62a3d95b5186834224a9e55b92ccae35d21a8b63d4", size = 436484, upload-time = "2025-09-14T22:16:55.005Z" }, + { url = "https://files.pythonhosted.org/packages/43/a3/c6155f5c1cce691cb80dfd38627046e50af3ee9ddc5d0b45b9b063bfb8c9/zstandard-0.25.0-cp311-cp311-win_amd64.whl", hash = "sha256:daab68faadb847063d0c56f361a289c4f268706b598afbf9ad113cbe5c38b6b2", size = 506183, upload-time = "2025-09-14T22:16:52.753Z" }, + { url = "https://files.pythonhosted.org/packages/8c/3e/8945ab86a0820cc0e0cdbf38086a92868a9172020fdab8a03ac19662b0e5/zstandard-0.25.0-cp311-cp311-win_arm64.whl", hash = "sha256:22a06c5df3751bb7dc67406f5374734ccee8ed37fc5981bf1ad7041831fa1137", size = 462533, upload-time = "2025-09-14T22:16:53.878Z" }, + { url = "https://files.pythonhosted.org/packages/82/fc/f26eb6ef91ae723a03e16eddb198abcfce2bc5a42e224d44cc8b6765e57e/zstandard-0.25.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7b3c3a3ab9daa3eed242d6ecceead93aebbb8f5f84318d82cee643e019c4b73b", size = 795738, upload-time = "2025-09-14T22:16:56.237Z" }, + { url = "https://files.pythonhosted.org/packages/aa/1c/d920d64b22f8dd028a8b90e2d756e431a5d86194caa78e3819c7bf53b4b3/zstandard-0.25.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:913cbd31a400febff93b564a23e17c3ed2d56c064006f54efec210d586171c00", size = 640436, upload-time = "2025-09-14T22:16:57.774Z" }, + { url = "https://files.pythonhosted.org/packages/53/6c/288c3f0bd9fcfe9ca41e2c2fbfd17b2097f6af57b62a81161941f09afa76/zstandard-0.25.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:011d388c76b11a0c165374ce660ce2c8efa8e5d87f34996aa80f9c0816698b64", size = 5343019, upload-time = "2025-09-14T22:16:59.302Z" }, + { url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" }, + { url = "https://files.pythonhosted.org/packages/b7/37/a6ce629ffdb43959e92e87ebdaeebb5ac81c944b6a75c9c47e300f85abdf/zstandard-0.25.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7149623bba7fdf7e7f24312953bcf73cae103db8cae49f8154dd1eadc8a29ecb", size = 5394148, upload-time = "2025-09-14T22:17:03.091Z" }, + { url = "https://files.pythonhosted.org/packages/e3/79/2bf870b3abeb5c070fe2d670a5a8d1057a8270f125ef7676d29ea900f496/zstandard-0.25.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6a573a35693e03cf1d67799fd01b50ff578515a8aeadd4595d2a7fa9f3ec002a", size = 5451652, upload-time = "2025-09-14T22:17:04.979Z" }, + { url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" }, + { url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" }, + { url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" }, + { url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" }, + { url = "https://files.pythonhosted.org/packages/18/e1/97680c664a1bf9a247a280a053d98e251424af51f1b196c6d52f117c9720/zstandard-0.25.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:809c5bcb2c67cd0ed81e9229d227d4ca28f82d0f778fc5fea624a9def3963f91", size = 5268008, upload-time = "2025-09-14T22:17:13.627Z" }, + { url = "https://files.pythonhosted.org/packages/1e/73/316e4010de585ac798e154e88fd81bb16afc5c5cb1a72eeb16dd37e8024a/zstandard-0.25.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f27662e4f7dbf9f9c12391cb37b4c4c3cb90ffbd3b1fb9284dadbbb8935fa708", size = 5433517, upload-time = "2025-09-14T22:17:16.103Z" }, + { url = "https://files.pythonhosted.org/packages/5b/60/dd0f8cfa8129c5a0ce3ea6b7f70be5b33d2618013a161e1ff26c2b39787c/zstandard-0.25.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99c0c846e6e61718715a3c9437ccc625de26593fea60189567f0118dc9db7512", size = 5814292, upload-time = "2025-09-14T22:17:17.827Z" }, + { url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" }, + { url = "https://files.pythonhosted.org/packages/ff/8d/0309daffea4fcac7981021dbf21cdb2e3427a9e76bafbcdbdf5392ff99a4/zstandard-0.25.0-cp312-cp312-win32.whl", hash = "sha256:23ebc8f17a03133b4426bcc04aabd68f8236eb78c3760f12783385171b0fd8bd", size = 436922, upload-time = "2025-09-14T22:17:24.398Z" }, + { url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" }, + { url = "https://files.pythonhosted.org/packages/ea/6b/8b51697e5319b1f9ac71087b0af9a40d8a6288ff8025c36486e0c12abcc4/zstandard-0.25.0-cp312-cp312-win_arm64.whl", hash = "sha256:181eb40e0b6a29b3cd2849f825e0fa34397f649170673d385f3598ae17cca2e9", size = 462679, upload-time = "2025-09-14T22:17:23.147Z" }, + { url = "https://files.pythonhosted.org/packages/35/0b/8df9c4ad06af91d39e94fa96cc010a24ac4ef1378d3efab9223cc8593d40/zstandard-0.25.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ec996f12524f88e151c339688c3897194821d7f03081ab35d31d1e12ec975e94", size = 795735, upload-time = "2025-09-14T22:17:26.042Z" }, + { url = "https://files.pythonhosted.org/packages/3f/06/9ae96a3e5dcfd119377ba33d4c42a7d89da1efabd5cb3e366b156c45ff4d/zstandard-0.25.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a1a4ae2dec3993a32247995bdfe367fc3266da832d82f8438c8570f989753de1", size = 640440, upload-time = "2025-09-14T22:17:27.366Z" }, + { url = "https://files.pythonhosted.org/packages/d9/14/933d27204c2bd404229c69f445862454dcc101cd69ef8c6068f15aaec12c/zstandard-0.25.0-cp313-cp313-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:e96594a5537722fdfb79951672a2a63aec5ebfb823e7560586f7484819f2a08f", size = 5343070, upload-time = "2025-09-14T22:17:28.896Z" }, + { url = "https://files.pythonhosted.org/packages/6d/db/ddb11011826ed7db9d0e485d13df79b58586bfdec56e5c84a928a9a78c1c/zstandard-0.25.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:bfc4e20784722098822e3eee42b8e576b379ed72cca4a7cb856ae733e62192ea", size = 5063001, upload-time = "2025-09-14T22:17:31.044Z" }, + { url = "https://files.pythonhosted.org/packages/db/00/87466ea3f99599d02a5238498b87bf84a6348290c19571051839ca943777/zstandard-0.25.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:457ed498fc58cdc12fc48f7950e02740d4f7ae9493dd4ab2168a47c93c31298e", size = 5394120, upload-time = "2025-09-14T22:17:32.711Z" }, + { url = "https://files.pythonhosted.org/packages/2b/95/fc5531d9c618a679a20ff6c29e2b3ef1d1f4ad66c5e161ae6ff847d102a9/zstandard-0.25.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:fd7a5004eb1980d3cefe26b2685bcb0b17989901a70a1040d1ac86f1d898c551", size = 5451230, upload-time = "2025-09-14T22:17:34.41Z" }, + { url = "https://files.pythonhosted.org/packages/63/4b/e3678b4e776db00f9f7b2fe58e547e8928ef32727d7a1ff01dea010f3f13/zstandard-0.25.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8e735494da3db08694d26480f1493ad2cf86e99bdd53e8e9771b2752a5c0246a", size = 5547173, upload-time = "2025-09-14T22:17:36.084Z" }, + { url = "https://files.pythonhosted.org/packages/4e/d5/ba05ed95c6b8ec30bd468dfeab20589f2cf709b5c940483e31d991f2ca58/zstandard-0.25.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3a39c94ad7866160a4a46d772e43311a743c316942037671beb264e395bdd611", size = 5046736, upload-time = "2025-09-14T22:17:37.891Z" }, + { url = "https://files.pythonhosted.org/packages/50/d5/870aa06b3a76c73eced65c044b92286a3c4e00554005ff51962deef28e28/zstandard-0.25.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:172de1f06947577d3a3005416977cce6168f2261284c02080e7ad0185faeced3", size = 5576368, upload-time = "2025-09-14T22:17:40.206Z" }, + { url = "https://files.pythonhosted.org/packages/5d/35/398dc2ffc89d304d59bc12f0fdd931b4ce455bddf7038a0a67733a25f550/zstandard-0.25.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3c83b0188c852a47cd13ef3bf9209fb0a77fa5374958b8c53aaa699398c6bd7b", size = 4954022, upload-time = "2025-09-14T22:17:41.879Z" }, + { url = "https://files.pythonhosted.org/packages/9a/5c/36ba1e5507d56d2213202ec2b05e8541734af5f2ce378c5d1ceaf4d88dc4/zstandard-0.25.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:1673b7199bbe763365b81a4f3252b8e80f44c9e323fc42940dc8843bfeaf9851", size = 5267889, upload-time = "2025-09-14T22:17:43.577Z" }, + { url = "https://files.pythonhosted.org/packages/70/e8/2ec6b6fb7358b2ec0113ae202647ca7c0e9d15b61c005ae5225ad0995df5/zstandard-0.25.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:0be7622c37c183406f3dbf0cba104118eb16a4ea7359eeb5752f0794882fc250", size = 5433952, upload-time = "2025-09-14T22:17:45.271Z" }, + { url = "https://files.pythonhosted.org/packages/7b/01/b5f4d4dbc59ef193e870495c6f1275f5b2928e01ff5a81fecb22a06e22fb/zstandard-0.25.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:5f5e4c2a23ca271c218ac025bd7d635597048b366d6f31f420aaeb715239fc98", size = 5814054, upload-time = "2025-09-14T22:17:47.08Z" }, + { url = "https://files.pythonhosted.org/packages/b2/e5/fbd822d5c6f427cf158316d012c5a12f233473c2f9c5fe5ab1ae5d21f3d8/zstandard-0.25.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4f187a0bb61b35119d1926aee039524d1f93aaf38a9916b8c4b78ac8514a0aaf", size = 5360113, upload-time = "2025-09-14T22:17:48.893Z" }, + { url = "https://files.pythonhosted.org/packages/8e/e0/69a553d2047f9a2c7347caa225bb3a63b6d7704ad74610cb7823baa08ed7/zstandard-0.25.0-cp313-cp313-win32.whl", hash = "sha256:7030defa83eef3e51ff26f0b7bfb229f0204b66fe18e04359ce3474ac33cbc09", size = 436936, upload-time = "2025-09-14T22:17:52.658Z" }, + { url = "https://files.pythonhosted.org/packages/d9/82/b9c06c870f3bd8767c201f1edbdf9e8dc34be5b0fbc5682c4f80fe948475/zstandard-0.25.0-cp313-cp313-win_amd64.whl", hash = "sha256:1f830a0dac88719af0ae43b8b2d6aef487d437036468ef3c2ea59c51f9d55fd5", size = 506232, upload-time = "2025-09-14T22:17:50.402Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/60c3c01243bb81d381c9916e2a6d9e149ab8627c0c7d7abb2d73384b3c0c/zstandard-0.25.0-cp313-cp313-win_arm64.whl", hash = "sha256:85304a43f4d513f5464ceb938aa02c1e78c2943b29f44a750b48b25ac999a049", size = 462671, upload-time = "2025-09-14T22:17:51.533Z" }, + { url = "https://files.pythonhosted.org/packages/3d/5c/f8923b595b55fe49e30612987ad8bf053aef555c14f05bb659dd5dbe3e8a/zstandard-0.25.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:e29f0cf06974c899b2c188ef7f783607dbef36da4c242eb6c82dcd8b512855e3", size = 795887, upload-time = "2025-09-14T22:17:54.198Z" }, + { url = "https://files.pythonhosted.org/packages/8d/09/d0a2a14fc3439c5f874042dca72a79c70a532090b7ba0003be73fee37ae2/zstandard-0.25.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:05df5136bc5a011f33cd25bc9f506e7426c0c9b3f9954f056831ce68f3b6689f", size = 640658, upload-time = "2025-09-14T22:17:55.423Z" }, + { url = "https://files.pythonhosted.org/packages/5d/7c/8b6b71b1ddd517f68ffb55e10834388d4f793c49c6b83effaaa05785b0b4/zstandard-0.25.0-cp314-cp314-manylinux2010_i686.manylinux_2_12_i686.manylinux_2_28_i686.whl", hash = "sha256:f604efd28f239cc21b3adb53eb061e2a205dc164be408e553b41ba2ffe0ca15c", size = 5379849, upload-time = "2025-09-14T22:17:57.372Z" }, + { url = "https://files.pythonhosted.org/packages/a4/86/a48e56320d0a17189ab7a42645387334fba2200e904ee47fc5a26c1fd8ca/zstandard-0.25.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:223415140608d0f0da010499eaa8ccdb9af210a543fac54bce15babbcfc78439", size = 5058095, upload-time = "2025-09-14T22:17:59.498Z" }, + { url = "https://files.pythonhosted.org/packages/f8/ad/eb659984ee2c0a779f9d06dbfe45e2dc39d99ff40a319895df2d3d9a48e5/zstandard-0.25.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2e54296a283f3ab5a26fc9b8b5d4978ea0532f37b231644f367aa588930aa043", size = 5551751, upload-time = "2025-09-14T22:18:01.618Z" }, + { url = "https://files.pythonhosted.org/packages/61/b3/b637faea43677eb7bd42ab204dfb7053bd5c4582bfe6b1baefa80ac0c47b/zstandard-0.25.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ca54090275939dc8ec5dea2d2afb400e0f83444b2fc24e07df7fdef677110859", size = 6364818, upload-time = "2025-09-14T22:18:03.769Z" }, + { url = "https://files.pythonhosted.org/packages/31/dc/cc50210e11e465c975462439a492516a73300ab8caa8f5e0902544fd748b/zstandard-0.25.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e09bb6252b6476d8d56100e8147b803befa9a12cea144bbe629dd508800d1ad0", size = 5560402, upload-time = "2025-09-14T22:18:05.954Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ae/56523ae9c142f0c08efd5e868a6da613ae76614eca1305259c3bf6a0ed43/zstandard-0.25.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a9ec8c642d1ec73287ae3e726792dd86c96f5681eb8df274a757bf62b750eae7", size = 4955108, upload-time = "2025-09-14T22:18:07.68Z" }, + { url = "https://files.pythonhosted.org/packages/98/cf/c899f2d6df0840d5e384cf4c4121458c72802e8bda19691f3b16619f51e9/zstandard-0.25.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:a4089a10e598eae6393756b036e0f419e8c1d60f44a831520f9af41c14216cf2", size = 5269248, upload-time = "2025-09-14T22:18:09.753Z" }, + { url = "https://files.pythonhosted.org/packages/1b/c0/59e912a531d91e1c192d3085fc0f6fb2852753c301a812d856d857ea03c6/zstandard-0.25.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f67e8f1a324a900e75b5e28ffb152bcac9fbed1cc7b43f99cd90f395c4375344", size = 5430330, upload-time = "2025-09-14T22:18:11.966Z" }, + { url = "https://files.pythonhosted.org/packages/a0/1d/7e31db1240de2df22a58e2ea9a93fc6e38cc29353e660c0272b6735d6669/zstandard-0.25.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:9654dbc012d8b06fc3d19cc825af3f7bf8ae242226df5f83936cb39f5fdc846c", size = 5811123, upload-time = "2025-09-14T22:18:13.907Z" }, + { url = "https://files.pythonhosted.org/packages/f6/49/fac46df5ad353d50535e118d6983069df68ca5908d4d65b8c466150a4ff1/zstandard-0.25.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4203ce3b31aec23012d3a4cf4a2ed64d12fea5269c49aed5e4c3611b938e4088", size = 5359591, upload-time = "2025-09-14T22:18:16.465Z" }, + { url = "https://files.pythonhosted.org/packages/c2/38/f249a2050ad1eea0bb364046153942e34abba95dd5520af199aed86fbb49/zstandard-0.25.0-cp314-cp314-win32.whl", hash = "sha256:da469dc041701583e34de852d8634703550348d5822e66a0c827d39b05365b12", size = 444513, upload-time = "2025-09-14T22:18:20.61Z" }, + { url = "https://files.pythonhosted.org/packages/3a/43/241f9615bcf8ba8903b3f0432da069e857fc4fd1783bd26183db53c4804b/zstandard-0.25.0-cp314-cp314-win_amd64.whl", hash = "sha256:c19bcdd826e95671065f8692b5a4aa95c52dc7a02a4c5a0cac46deb879a017a2", size = 516118, upload-time = "2025-09-14T22:18:17.849Z" }, + { url = "https://files.pythonhosted.org/packages/f0/ef/da163ce2450ed4febf6467d77ccb4cd52c4c30ab45624bad26ca0a27260c/zstandard-0.25.0-cp314-cp314-win_arm64.whl", hash = "sha256:d7541afd73985c630bafcd6338d2518ae96060075f9463d7dc14cfb33514383d", size = 476940, upload-time = "2025-09-14T22:18:19.088Z" }, +] From e9f47bef671ca04a26c63f0b21bbe7eb5126731b Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 05:05:56 +0200 Subject: [PATCH 03/58] feat(agent): run an extraction under one enforcement condition Single-shot orchestration, with every difference between arms confined to the prompt sections and the request to the provider. The shared instruction is identical across arms character for character, so a measured difference cannot be a difference in wording. - the commit gate returns its filtered result, which the predecessor did not - pinning a class slot that is absent raises, so no arm runs unconstrained while being recorded as constrained - malformed JSON is not repaired, since repairing it hides a decode failure - an unported orchestration refuses rather than silently behaving as another --- src/oold/agent/__init__.py | 11 ++ src/oold/agent/client.py | 14 +- src/oold/agent/enforcement.py | 4 + src/oold/agent/extraction.py | 256 ++++++++++++++++++++++++ src/oold/agent/langchain_client.py | 19 +- src/oold/agent/prompts.py | 91 +++++++++ tests/test_agent/test_client.py | 21 +- tests/test_agent/test_enforcement.py | 3 +- tests/test_agent/test_extraction.py | 278 +++++++++++++++++++++++++++ 9 files changed, 659 insertions(+), 38 deletions(-) create mode 100644 src/oold/agent/extraction.py create mode 100644 src/oold/agent/prompts.py create mode 100644 tests/test_agent/test_extraction.py diff --git a/src/oold/agent/__init__.py b/src/oold/agent/__init__.py index 1e4f876..52be989 100644 --- a/src/oold/agent/__init__.py +++ b/src/oold/agent/__init__.py @@ -29,6 +29,12 @@ OutputForm, arm, ) +from oold.agent.extraction import ( + ExtractionAgent, + ExtractionResult, + parse_json_answer, +) +from oold.agent.prompts import ExtractionRequest, build_messages from oold.agent.provider import ( PROFILES, Degradation, @@ -48,12 +54,17 @@ "DecodeConstraint", "Degradation", "Enforcement", + "ExtractionAgent", + "ExtractionRequest", + "ExtractionResult", "Message", "Orchestration", "OutputForm", "ProviderProfile", "TokenUsage", "arm", + "build_messages", + "parse_json_answer", "prepare", "profile_for", "schema_hash", diff --git a/src/oold/agent/client.py b/src/oold/agent/client.py index 57b4d8a..77f259c 100644 --- a/src/oold/agent/client.py +++ b/src/oold/agent/client.py @@ -16,9 +16,10 @@ import threading import time +from collections.abc import Iterator, Sequence from contextlib import contextmanager from dataclasses import dataclass, field -from typing import Any, Iterator, Protocol, Sequence, runtime_checkable +from typing import Any, Protocol, runtime_checkable __all__ = [ "Call", @@ -57,13 +58,11 @@ def total(self) -> int: def billable_input(self) -> int: return self.input_tokens - self.cached_input_tokens - def __add__(self, other: "TokenUsage") -> "TokenUsage": + def __add__(self, other: TokenUsage) -> TokenUsage: return TokenUsage( input_tokens=self.input_tokens + other.input_tokens, output_tokens=self.output_tokens + other.output_tokens, - cached_input_tokens=( - self.cached_input_tokens + other.cached_input_tokens - ), + cached_input_tokens=(self.cached_input_tokens + other.cached_input_tokens), reasoning_tokens=self.reasoning_tokens + other.reasoning_tokens, ) @@ -206,10 +205,7 @@ def describe(self) -> dict[str, Any]: return { "calls": [call.describe() for call in self._calls], "totals": self.totals().describe(), - "by_step": { - step: usage.describe() - for step, usage in sorted(self.by_step().items()) - }, + "by_step": {step: usage.describe() for step, usage in sorted(self.by_step().items())}, "n_calls": len(self._calls), "n_errors": sum(1 for call in self._calls if call.error), } diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index 764d678..ed12277 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -27,6 +27,10 @@ class Orchestration(str, Enum): """How the work is broken up, held constant while enforcement varies.""" + SINGLE_SHOT = "single_shot" + """One call. The right shape when a document yields a flat list of + instances, and the baseline the others have to beat.""" + RECURSIVE = "recursive" """Depth first. Resolve each entity, recursing into its linked entities.""" diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py new file mode 100644 index 0000000..503ae33 --- /dev/null +++ b/src/oold/agent/extraction.py @@ -0,0 +1,256 @@ +"""Running one extraction under one enforcement condition. + +The agent is one skeleton with the enforcement supplied as data. Orchestration +is a separate axis, so a study can hold one fixed while varying the other, +which is the property the predecessor lacked: eight of ten differences between +its two arms were orchestration, so nothing it measured could be attributed to +typing. + +What the agent returns is the model's answer and a record of how it was +obtained. Turning that answer into something scoreable belongs to whatever is +doing the scoring, so this package never learns what a benchmark is. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from typing import Any + +from oold.agent.client import CallLog, ChatClient, TokenUsage +from oold.agent.enforcement import ( + DecodeConstraint, + Enforcement, + Orchestration, + OutputForm, +) +from oold.agent.prompts import ExtractionRequest, build_messages +from oold.agent.provider import Degradation, ProviderProfile, prepare, schema_hash + +__all__ = ["ExtractionAgent", "ExtractionResult", "parse_json_answer"] + +_FENCE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.MULTILINE) + + +def parse_json_answer(text: str) -> Any | None: + """Read JSON out of an answer, tolerating a markdown fence. + + Models wrap JSON in a fence even when told not to, and refusing those + would measure instruction-following dressed up as a parse rate. Anything + beyond stripping a fence is left alone, because repairing malformed JSON + would hide a real failure of the decode-time constraint. + """ + if not text or not text.strip(): + return None + candidate = _FENCE.sub("", text).strip() + try: + return json.loads(candidate) + except json.JSONDecodeError: + return None + + +@dataclass +class ExtractionResult: + """One answer, and everything needed to say how it was produced.""" + + text: str + payload: Any | None + calls: CallLog + degradation: Degradation | None = None + schema_sha256: str | None = None + dropped: list[str] = field(default_factory=list) + """Classes the commit-time gate removed, so the gate's effect is visible + instead of being folded into a lower score.""" + + @property + def parsed(self) -> bool: + return self.payload is not None + + def describe(self) -> dict[str, Any]: + return { + "parsed": self.parsed, + "schema_sha256": self.schema_sha256, + "dropped": list(self.dropped), + "degradation": self.degradation.describe() if self.degradation else None, + "calls": self.calls.describe(), + } + + +class ExtractionAgent: + """Turn a document into a model's answer under one condition.""" + + def __init__( + self, + client: ChatClient, + enforcement: Enforcement, + profile: ProviderProfile, + orchestration: Orchestration = Orchestration.SINGLE_SHOT, + *, + attempts: int = 1, + ) -> None: + self.client = client + self.enforcement = enforcement + self.profile = profile + self.orchestration = orchestration + self.attempts = attempts + if orchestration is not Orchestration.SINGLE_SHOT: + raise NotImplementedError( + f"orchestration {orchestration.value} is not ported yet. " + f"Only {Orchestration.SINGLE_SHOT.value} runs today" + ) + + def run(self, request: ExtractionRequest) -> ExtractionResult: + log = CallLog() + prepared, degradation, digest = self._schema_for(request) + messages = build_messages( + ExtractionRequest( + document=request.document, + schema=prepared if self.enforcement.schema_in_prompt else None, + instruction=request.instruction, + ), + self.enforcement, + ) + response_format = ( + prepared + if prepared is not None + and self.enforcement.decode_constraint is not DecodeConstraint.NONE + else None + ) + + text = "" + payload: Any | None = None + for attempt in range(1, self.attempts + 1): + with log.timed( + "extract", self.client.model, attempt=attempt, schema_sha256=digest + ) as sink: + reply = self.client.invoke(messages, response_format=response_format) + sink.append(reply.usage or TokenUsage()) + text = reply.text + payload = reply.parsed if reply.parsed is not None else parse_json_answer(text) + if payload is not None or self.enforcement.output_form is OutputForm.PROSE: + break + + dropped: list[str] = [] + if self.enforcement.commit_gate and payload is not None: + payload, dropped = self._gate(payload) + + return ExtractionResult( + text=text, + payload=payload, + calls=log, + degradation=degradation, + schema_sha256=digest, + dropped=dropped, + ) + + def _schema_for( + self, request: ExtractionRequest + ) -> tuple[dict[str, Any] | None, Degradation | None, str | None]: + """The schema this condition sends, and what preparing it cost.""" + needs_schema = ( + self.enforcement.schema_in_prompt + or self.enforcement.decode_constraint is not DecodeConstraint.NONE + ) + if request.schema is None or not needs_schema: + return None, None, None + prepared, degradation = prepare( + request.schema, self.profile, grounding=self.enforcement.grounding + ) + if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM: + prepared = self._pin_class(prepared) + return prepared, degradation, schema_hash(prepared) + + def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: + """Constrain the class slot to the catalogue at decode time. + + Fails loudly when there is no slot to constrain. A silent no-op here + would make an arm that was meant to be constrained run unconstrained, + and the result would look like a finding about constraints. + """ + if not self.enforcement.catalogue: + return schema + target = _find_class_property(schema) + if target is None: + raise ValueError( + "the schema has no class property to pin, so the decode-time " + "constraint cannot be applied" + ) + target["enum"] = list(self.enforcement.catalogue) + return schema + + def _gate(self, payload: Any) -> tuple[Any, list[str]]: + """Drop entities whose class is not in the catalogue. + + The filtered result is returned and used. Keeping the corrections and + discarding the removals is the bug that inflated the predecessor's + missing-entity count for months. + """ + allowed = set(self.enforcement.catalogue or ()) + if not allowed: + return payload, [] + dropped: list[str] = [] + + def keep(entity: Any) -> bool: + if not isinstance(entity, dict): + return True + name = _class_of(entity) + if name is None or name in allowed: + return True + suffixed = [a for a in allowed if a.endswith("." + name)] + if len(suffixed) == 1: + _set_class(entity, suffixed[0]) + return True + dropped.append(name) + return False + + if isinstance(payload, list): + return [e for e in payload if keep(e)], dropped + if isinstance(payload, dict): + for wrapper in ("entities", "instances", "items", "results"): + if isinstance(payload.get(wrapper), list): + payload[wrapper] = [e for e in payload[wrapper] if keep(e)] + return payload, dropped + return (payload if keep(payload) else None), dropped + return payload, dropped + + +_CLASS_KEYS = ("type", "@type", "class", "class_path", "schema_path", "kind") + + +def _class_of(entity: dict[str, Any]) -> str | None: + for key in _CLASS_KEYS: + value = entity.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + if isinstance(value, list) and value and isinstance(value[0], str): + return value[0].strip() + return None + + +def _set_class(entity: dict[str, Any], name: str) -> None: + for key in _CLASS_KEYS: + if key in entity: + entity[key] = [name] if isinstance(entity[key], list) else name + return + + +def _find_class_property(schema: Any) -> dict[str, Any] | None: + """The subschema describing an entity's class, wherever it sits.""" + if isinstance(schema, dict): + properties = schema.get("properties") + if isinstance(properties, dict): + for key in _CLASS_KEYS: + target = properties.get(key) + if isinstance(target, dict): + return target + for value in schema.values(): + found = _find_class_property(value) + if found is not None: + return found + elif isinstance(schema, list): + for item in schema: + found = _find_class_property(item) + if found is not None: + return found + return None diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index c6f2b1a..fe94c51 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -9,7 +9,8 @@ from __future__ import annotations -from typing import Any, Sequence +from collections.abc import Sequence +from typing import Any from langchain_core.language_models import BaseChatModel @@ -58,20 +59,12 @@ def invoke( parsed: dict[str, Any] | None = None if response_format is not None: - structured = llm.with_structured_output( - response_format, include_raw=True - ) - result = structured.invoke( - [(m.role, m.content) for m in messages] - ) + structured = llm.with_structured_output(response_format, include_raw=True) + result = structured.invoke([(m.role, m.content) for m in messages]) raw = result.get("raw") if isinstance(result, dict) else None - parsing_error = ( - result.get("parsing_error") if isinstance(result, dict) else None - ) + parsing_error = result.get("parsing_error") if isinstance(result, dict) else None if parsing_error is not None: - raise ValueError( - f"structured output did not parse: {parsing_error}" - ) + raise ValueError(f"structured output did not parse: {parsing_error}") parsed = result.get("parsed") if isinstance(result, dict) else None if parsed is not None and not isinstance(parsed, dict): parsed = dict(parsed) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py new file mode 100644 index 0000000..3baea9f --- /dev/null +++ b/src/oold/agent/prompts.py @@ -0,0 +1,91 @@ +"""Building the prompt an enforcement condition implies. + +Every difference between arms has to live here or in the request to the +provider, and nowhere else. If one arm also got a differently worded +instruction, a measured difference between arms would be partly a difference +in wording, which is the confound this whole design exists to remove. + +So the instruction is one text with optional sections. The sections appear +exactly when the condition says they do, and the wording of the parts that +are shared is identical across arms, character for character. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from typing import Any + +from oold.agent.client import Message +from oold.agent.enforcement import Enforcement, OutputForm + +__all__ = ["ExtractionRequest", "build_messages"] + +_TASK = ( + "Read the document and report every entity it describes, with the " + "values stated for each." +) + +_JSON_FORM = ( + "Answer with JSON only. No explanation, no markdown fence, no commentary." +) + +_PROSE_FORM = ( + "Answer in plain prose. State each entity and the values given for it." +) + +_CATALOGUE = ( + "Choose the class of each entity from this list, using one of these " + "exactly:" +) + +_SCHEMA = "Each entity must conform to this schema:" + +_GATE_HINT = ( + "An entity whose class is not in the list will be discarded, so leave " + "out anything you cannot place." +) + + +@dataclass(frozen=True) +class ExtractionRequest: + """One document to read, and the schema material an arm may be shown.""" + + document: str + schema: dict[str, Any] | None = None + """The target schema. Shown only when the condition says so, and sent to + the provider only when a decode-time constraint is in force.""" + instruction: str | None = None + """Overrides the shared task sentence. For a study this stays unset, so + every arm reads the same words.""" + + +def build_messages( + request: ExtractionRequest, enforcement: Enforcement +) -> list[Message]: + """The messages one arm sends for one document. + + The system message is assembled from sections, the user message is the + document and nothing else. Keeping the document alone means the two are + never confused for each other by a model that treats the last turn as the + instruction. + """ + sections: list[str] = [request.instruction or _TASK] + + sections.append( + _PROSE_FORM if enforcement.output_form is OutputForm.PROSE else _JSON_FORM + ) + + if enforcement.catalogue: + listed = "\n".join(f"- {name}" for name in enforcement.catalogue) + sections.append(f"{_CATALOGUE}\n{listed}") + if enforcement.commit_gate: + sections.append(_GATE_HINT) + + if enforcement.schema_in_prompt and request.schema is not None: + sections.append(f"{_SCHEMA}\n{json.dumps(request.schema, indent=2)}") + + return [ + Message(role="system", content="\n\n".join(sections)), + Message(role="user", content=request.document), + ] diff --git a/tests/test_agent/test_client.py b/tests/test_agent/test_client.py index f865566..d3f6525 100644 --- a/tests/test_agent/test_client.py +++ b/tests/test_agent/test_client.py @@ -66,12 +66,8 @@ def test_totals_sum_every_call(self): def test_by_step_separates_what_the_run_total_hides(self): log = CallLog() - log.append( - Call("detect", "m", TokenUsage(input_tokens=8000), 0.1) - ) - log.append( - Call("extract", "m", TokenUsage(input_tokens=500), 0.1) - ) + log.append(Call("detect", "m", TokenUsage(input_tokens=8000), 0.1)) + log.append(Call("extract", "m", TokenUsage(input_tokens=500), 0.1)) by_step = log.by_step() assert by_step["detect"].input_tokens == 8000 assert by_step["extract"].input_tokens == 500 @@ -89,9 +85,8 @@ def test_timed_records_the_usage_put_into_the_sink(self): def test_a_failed_call_still_leaves_a_record(self): """A retry that vanishes from the log makes retries look free.""" log = CallLog() - with pytest.raises(RuntimeError): - with log.timed("extract", "m"): - raise RuntimeError("provider said no") + with pytest.raises(RuntimeError), log.timed("extract", "m"): + raise RuntimeError("provider said no") call = next(iter(log)) assert call.error == "RuntimeError: provider said no" assert call.usage.total == 0 @@ -99,9 +94,7 @@ def test_a_failed_call_still_leaves_a_record(self): def test_attempts_are_recorded_separately(self): log = CallLog() for attempt in (1, 2, 3): - log.append( - Call("construct", "m", TokenUsage(input_tokens=10), 0.1, attempt) - ) + log.append(Call("construct", "m", TokenUsage(input_tokens=10), 0.1, attempt)) assert [c.attempt for c in log] == [1, 2, 3] assert log.totals().input_tokens == 30 @@ -111,9 +104,7 @@ def test_appends_from_several_threads_all_arrive(self): def work(): for _ in range(50): - log.append( - Call("parallel", "m", TokenUsage(input_tokens=1), 0.0) - ) + log.append(Call("parallel", "m", TokenUsage(input_tokens=1), 0.0)) threads = [threading.Thread(target=work) for _ in range(8)] for thread in threads: diff --git a/tests/test_agent/test_enforcement.py b/tests/test_agent/test_enforcement.py index 702cfd2..dad3503 100644 --- a/tests/test_agent/test_enforcement.py +++ b/tests/test_agent/test_enforcement.py @@ -133,8 +133,9 @@ def test_is_frozen(self): setattr(typed(), "commit_gate", False) # noqa: B010 -def test_orchestration_covers_the_three_reference_agents(): +def test_orchestration_covers_single_shot_and_the_three_reference_agents(): assert [o.value for o in Orchestration] == [ + "single_shot", "recursive", "segmented", "multi_step", diff --git a/tests/test_agent/test_extraction.py b/tests/test_agent/test_extraction.py new file mode 100644 index 0000000..59cb97f --- /dev/null +++ b/tests/test_agent/test_extraction.py @@ -0,0 +1,278 @@ +"""Running an extraction under each condition, with no model involved. + +The fake client records what it was sent and returns what the test tells it +to, so every assertion here is about the agent and nothing else. +""" + +import json + +import pytest + +from oold.agent import ( + ARMS, + ChatResponse, + DecodeConstraint, + Enforcement, + ExtractionAgent, + ExtractionRequest, + Orchestration, + OutputForm, + TokenUsage, + arm, + build_messages, + parse_json_answer, + profile_for, +) + +SCHEMA = { + "type": "object", + "properties": { + "type": {"type": "string"}, + "value": {"type": "number"}, + "unit": {"type": "string"}, + }, + "required": ["type", "value"], +} + +CATALOGUE = ("quantities.Length", "quantities.Mass") + + +class FakeClient: + model = "fake-1" + + def __init__(self, text: str = '{"type": "quantities.Length", "value": 1.0}'): + self.text = text + self.messages = None + self.response_format = None + self.calls = 0 + + def invoke(self, messages, *, response_format=None): + self.calls += 1 + self.messages = list(messages) + self.response_format = response_format + return ChatResponse( + text=self.text, + parsed=None, + usage=TokenUsage(input_tokens=100, output_tokens=10), + ) + + def system(self) -> str: + return self.messages[0].content if self.messages else "" + + +def agent(name: str, client: FakeClient, profile: str = "openai", **kwargs): + """An agent for one arm. A0 offers no catalogue, so it is not given one.""" + condition = ARMS[name] if ARMS[name].catalogue is None else arm(name, CATALOGUE) + return ExtractionAgent(client, condition, profile_for(profile), **kwargs) + + +class TestThePromptFollowsTheCondition: + def test_a0_is_shown_no_schema_and_no_catalogue(self): + client = FakeClient() + agent("A0-json", client).run(ExtractionRequest("doc", SCHEMA)) + system = client.system() + assert "schema" not in system.lower() + assert "quantities.Length" not in system + + def test_a1_is_shown_the_catalogue_and_the_schema(self): + client = FakeClient() + agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + system = client.system() + assert "quantities.Length" in system + assert "conform to this schema" in system + + def test_the_document_is_the_user_message_and_nothing_else(self): + client = FakeClient() + agent("A2", client).run(ExtractionRequest("the document text", SCHEMA)) + assert client.messages[1].content == "the document text" + + def test_the_shared_instruction_is_identical_across_arms(self): + """Any wording difference between arms would be a confound.""" + firsts = set() + for name in ("A0-json", "A1", "A2", "A3"): + client = FakeClient() + agent(name, client).run(ExtractionRequest("doc", SCHEMA)) + firsts.add(client.system().split("\n\n")[0]) + assert len(firsts) == 1 + + def test_prose_and_json_arms_ask_for_different_forms(self): + prose, as_json = FakeClient(), FakeClient() + ExtractionAgent( + prose, ARMS["A0-prose"], profile_for("openai") + ).run(ExtractionRequest("doc")) + agent("A0-json", as_json).run(ExtractionRequest("doc")) + assert "prose" in prose.system().lower() + assert "JSON" in as_json.system() + + +class TestTheDecodeConstraint: + def test_a1_sends_no_response_format(self): + client = FakeClient() + agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + assert client.response_format is None + + def test_a2_sends_one(self): + client = FakeClient() + agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + assert client.response_format is not None + + def test_a2_pins_the_class_to_the_catalogue(self): + client = FakeClient() + agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + assert client.response_format["properties"]["type"]["enum"] == list(CATALOGUE) + + def test_a_schema_with_no_class_slot_fails_loudly(self): + """A silent no-op would run an arm unconstrained and call it constrained.""" + client = FakeClient() + with pytest.raises(ValueError, match="no class property to pin"): + agent("A2", client).run( + ExtractionRequest("doc", {"type": "object", "properties": {"v": {}}}) + ) + + def test_the_schema_actually_sent_is_hashed(self): + client = FakeClient() + result = agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + assert result.schema_sha256 and len(result.schema_sha256) == 64 + + def test_two_providers_get_different_schemas(self): + """Preparation is part of the treatment, so it has to be recorded.""" + strict = agent("A2", FakeClient(), profile="anthropic").run( + ExtractionRequest("doc", SCHEMA) + ) + lenient = agent("A2", FakeClient(), profile="openai").run( + ExtractionRequest("doc", SCHEMA) + ) + assert strict.schema_sha256 != lenient.schema_sha256 + assert strict.degradation is not None + + +class TestGrounding: + def test_a3_keeps_the_context_where_a2_drops_it(self): + grounded = {"@context": {"x": "http://example.org/"}, **SCHEMA} + a2 = agent("A2", FakeClient()).run(ExtractionRequest("doc", grounded)) + a3 = agent("A3", FakeClient()).run(ExtractionRequest("doc", grounded)) + assert a2.degradation.semantics_dropped > 0 + assert a3.degradation.semantics_dropped == 0 + + +class TestTheCommitGate: + def test_an_entity_outside_the_catalogue_is_dropped(self): + client = FakeClient('{"entities": [{"type": "quantities.Nonsense", "value": 1}]}') + result = agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + assert result.payload["entities"] == [] + assert result.dropped == ["quantities.Nonsense"] + + def test_the_filtered_result_is_the_one_returned(self): + """Keeping corrections and discarding removals is the predecessor's bug.""" + client = FakeClient( + '{"entities": [{"type": "quantities.Length", "value": 1},' + ' {"type": "Nope", "value": 2}]}' + ) + result = agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + assert len(result.payload["entities"]) == 1 + + def test_an_unambiguous_suffix_is_corrected_not_dropped(self): + client = FakeClient('{"entities": [{"type": "Length", "value": 1}]}') + result = agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + assert result.payload["entities"][0]["type"] == "quantities.Length" + assert result.dropped == [] + + def test_a0_has_no_gate(self): + client = FakeClient('{"type": "anything at all", "value": 1}') + result = agent("A0-json", client).run(ExtractionRequest("doc")) + assert result.payload["type"] == "anything at all" + assert result.dropped == [] + + +class TestTheAnswer: + def test_a_fenced_answer_still_parses(self): + """Models fence JSON even when told not to.""" + client = FakeClient('```json\n{"type": "quantities.Length", "value": 1}\n```') + assert agent("A1", client).run(ExtractionRequest("doc", SCHEMA)).parsed + + def test_malformed_json_is_not_repaired(self): + """Repairing it would hide a failure of the decode-time constraint.""" + client = FakeClient('{"type": "Length", "value": ') + result = agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + assert result.parsed is False + + def test_a_prose_arm_is_not_asked_to_parse(self): + client = FakeClient("The length was one metre.") + result = ExtractionAgent( + client, ARMS["A0-prose"], profile_for("openai") + ).run(ExtractionRequest("doc")) + assert result.text == "The length was one metre." + assert client.calls == 1 + + def test_a_json_arm_retries_a_malformed_answer(self): + client = FakeClient("not json at all") + agent("A1", client, attempts=3).run(ExtractionRequest("doc", SCHEMA)) + assert client.calls == 3 + + def test_a_good_answer_is_not_retried(self): + client = FakeClient('{"type": "quantities.Length", "value": 1}') + agent("A1", client, attempts=3).run(ExtractionRequest("doc", SCHEMA)) + assert client.calls == 1 + + +class TestTheRecord: + def test_every_call_is_logged_with_its_tokens(self): + client = FakeClient("not json") + result = agent("A1", client, attempts=2).run(ExtractionRequest("doc", SCHEMA)) + assert len(result.calls) == 2 + assert result.calls.totals().input_tokens == 200 + assert [c.attempt for c in result.calls] == [1, 2] + + def test_the_record_is_serialisable(self): + client = FakeClient() + described = agent("A2", client).run(ExtractionRequest("doc", SCHEMA)).describe() + assert json.dumps(described) + assert described["parsed"] is True + + +class TestOrchestration: + def test_single_shot_makes_one_call(self): + client = FakeClient() + agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + assert client.calls == 1 + + @pytest.mark.parametrize( + "orchestration", + [Orchestration.RECURSIVE, Orchestration.SEGMENTED, Orchestration.MULTI_STEP], + ) + def test_an_unported_orchestration_refuses_rather_than_pretending( + self, orchestration + ): + with pytest.raises(NotImplementedError, match="not ported yet"): + ExtractionAgent( + FakeClient(), + ARMS["A1"], + profile_for("openai"), + orchestration, + ) + + +class TestParseJsonAnswer: + @pytest.mark.parametrize( + "text", + ['{"a": 1}', '```json\n{"a": 1}\n```', '```\n{"a": 1}\n```', ' {"a": 1} '], + ) + def test_it_reads_the_shapes_models_produce(self, text): + assert parse_json_answer(text) == {"a": 1} + + @pytest.mark.parametrize("text", ["", " ", "sorry, I cannot", "{broken"]) + def test_it_returns_nothing_it_cannot_read(self, text): + assert parse_json_answer(text) is None + + +def test_build_messages_needs_no_agent(): + condition = Enforcement( + schema_in_prompt=False, + catalogue=None, + decode_constraint=DecodeConstraint.NONE, + commit_gate=False, + grounding=False, + output_form=OutputForm.JSON, + ) + messages = build_messages(ExtractionRequest("doc"), condition) + assert [m.role for m in messages] == ["system", "user"] From 2c3f697901768d8a0ef0ae508bc7d57cf54bed76 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 06:37:38 +0200 Subject: [PATCH 04/58] style: drop pseudo-cleft and "rather than" from docstrings - "X is what Y" does not occur in the reference corpus - "rather than" replaced by "instead of" or "not" - ruff format applied to the agent package --- src/oold/agent/__init__.py | 2 +- src/oold/agent/client.py | 4 ++-- src/oold/agent/enforcement.py | 10 +++++----- src/oold/agent/extraction.py | 23 ++++++--------------- src/oold/agent/langchain_client.py | 4 ++-- src/oold/agent/prompts.py | 31 +++++++---------------------- src/oold/agent/provider.py | 4 ++-- tests/test_agent/test_extraction.py | 29 +++++++-------------------- 8 files changed, 32 insertions(+), 75 deletions(-) diff --git a/src/oold/agent/__init__.py b/src/oold/agent/__init__.py index 52be989..66d36b4 100644 --- a/src/oold/agent/__init__.py +++ b/src/oold/agent/__init__.py @@ -2,7 +2,7 @@ Orchestration and enforcement are separate axes here, so a study can hold one fixed while varying the other. The three agents in the `osl-eln-demo` project -become three values of :class:`Orchestration` rather than three code paths. +become three values of :class:`Orchestration` instead of three code paths. Nothing in the core of ``oold`` imports this package, so installing ``oold`` for typed data never pulls in an LLM client. diff --git a/src/oold/agent/client.py b/src/oold/agent/client.py index 77f259c..5a084b8 100644 --- a/src/oold/agent/client.py +++ b/src/oold/agent/client.py @@ -1,7 +1,7 @@ """The boundary between the agent and whatever talks to a model. Two things live here. A :class:`ChatClient` protocol, so the agent depends on a -shape rather than on a vendor SDK, and a :class:`CallLog`, so token cost is +shape instead of on a vendor SDK, and a :class:`CallLog`, so token cost is attributed to the step that spent it. Per-call attribution is not a nicety. A run total cannot separate what the @@ -114,7 +114,7 @@ class Call: attempt: int = 1 schema_sha256: str | None = None """Hash of the schema actually sent, so a result names the bytes the model - saw rather than the schema someone believes it saw.""" + saw, not the schema someone believes it saw.""" error: str | None = None def describe(self) -> dict[str, Any]: diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index ed12277..c3bca51 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -1,9 +1,9 @@ -"""Where structure is enforced, as data rather than as separate code paths. +"""Where structure is enforced, as data instead of as separate code paths. Orchestration and enforcement are independent. The agent that walks a document recursively and the agent that runs a five-step pipeline can both be given a schema in the prompt, a decode-time constraint, a commit-time gate, all three, -or none. Entangling the two is what makes a comparison of typed against untyped +or none. Entangling the two makes a comparison of typed against untyped extraction impossible to interpret, because every measured difference has two candidate causes. """ @@ -107,7 +107,7 @@ def with_catalogue(self, paths: tuple[str, ...] | None) -> Enforcement: """The same condition over a different catalogue. This is the one knob a catalogue-weight sweep moves, so it gets a - method rather than being reconstructed by hand at each size. + method instead of being reconstructed by hand at each size. """ return replace(self, catalogue=paths) @@ -172,11 +172,11 @@ def describe(self) -> dict[str, object]: } """The five arms, with an empty catalogue that a run fills in. -A0 is two arms rather than one. ``A0-json`` is the headline comparison, because +A0 is two arms, not one. ``A0-json`` is the headline comparison, because its output reduces to triples by the same path as every other arm and needs no judge. ``A0-prose`` is reported beside it with the parse loss of its extractor stated, so the objection that JSON is already a form of structure has an answer -in the results rather than in the discussion. +in the results and not in the discussion. """ diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 503ae33..aba52a4 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -113,17 +113,14 @@ def run(self, request: ExtractionRequest) -> ExtractionResult: ) response_format = ( prepared - if prepared is not None - and self.enforcement.decode_constraint is not DecodeConstraint.NONE + if prepared is not None and self.enforcement.decode_constraint is not DecodeConstraint.NONE else None ) text = "" payload: Any | None = None for attempt in range(1, self.attempts + 1): - with log.timed( - "extract", self.client.model, attempt=attempt, schema_sha256=digest - ) as sink: + with log.timed("extract", self.client.model, attempt=attempt, schema_sha256=digest) as sink: reply = self.client.invoke(messages, response_format=response_format) sink.append(reply.usage or TokenUsage()) text = reply.text @@ -144,19 +141,14 @@ def run(self, request: ExtractionRequest) -> ExtractionResult: dropped=dropped, ) - def _schema_for( - self, request: ExtractionRequest - ) -> tuple[dict[str, Any] | None, Degradation | None, str | None]: + def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None, Degradation | None, str | None]: """The schema this condition sends, and what preparing it cost.""" needs_schema = ( - self.enforcement.schema_in_prompt - or self.enforcement.decode_constraint is not DecodeConstraint.NONE + self.enforcement.schema_in_prompt or self.enforcement.decode_constraint is not DecodeConstraint.NONE ) if request.schema is None or not needs_schema: return None, None, None - prepared, degradation = prepare( - request.schema, self.profile, grounding=self.enforcement.grounding - ) + prepared, degradation = prepare(request.schema, self.profile, grounding=self.enforcement.grounding) if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM: prepared = self._pin_class(prepared) return prepared, degradation, schema_hash(prepared) @@ -172,10 +164,7 @@ def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: return schema target = _find_class_property(schema) if target is None: - raise ValueError( - "the schema has no class property to pin, so the decode-time " - "constraint cannot be applied" - ) + raise ValueError("the schema has no class property to pin, so the decode-time constraint cannot be applied") target["enum"] = list(self.enforcement.catalogue) return schema diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index fe94c51..7a74167 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -24,7 +24,7 @@ def usage_from_message(message: Any) -> TokenUsage: LangChain normalises providers into ``usage_metadata``, but the nested detail dictionaries are optional and differ by provider, so every lookup - is defensive. A provider that reports nothing yields zeros rather than + is defensive. A provider that reports nothing yields zeros instead of raising, and a zero total is the signal that a model is uninstrumented. """ metadata = getattr(message, "usage_metadata", None) or {} @@ -44,7 +44,7 @@ class LangChainClient: def __init__(self, llm: BaseChatModel, model: str) -> None: self._llm = llm self.model = model - """The identifier recorded in the result. Passed in rather than read + """The identifier recorded in the result. Passed in instead of read off the object, because what a provider calls a model and what a deployment is named are different strings and the result needs the one that identifies the weights.""" diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 3baea9f..deec5e9 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -21,30 +21,17 @@ __all__ = ["ExtractionRequest", "build_messages"] -_TASK = ( - "Read the document and report every entity it describes, with the " - "values stated for each." -) +_TASK = "Read the document and report every entity it describes, with the values stated for each." -_JSON_FORM = ( - "Answer with JSON only. No explanation, no markdown fence, no commentary." -) +_JSON_FORM = "Answer with JSON only. No explanation, no markdown fence, no commentary." -_PROSE_FORM = ( - "Answer in plain prose. State each entity and the values given for it." -) +_PROSE_FORM = "Answer in plain prose. State each entity and the values given for it." -_CATALOGUE = ( - "Choose the class of each entity from this list, using one of these " - "exactly:" -) +_CATALOGUE = "Choose the class of each entity from this list, using one of these exactly:" _SCHEMA = "Each entity must conform to this schema:" -_GATE_HINT = ( - "An entity whose class is not in the list will be discarded, so leave " - "out anything you cannot place." -) +_GATE_HINT = "An entity whose class is not in the list will be discarded, so leave out anything you cannot place." @dataclass(frozen=True) @@ -60,9 +47,7 @@ class ExtractionRequest: every arm reads the same words.""" -def build_messages( - request: ExtractionRequest, enforcement: Enforcement -) -> list[Message]: +def build_messages(request: ExtractionRequest, enforcement: Enforcement) -> list[Message]: """The messages one arm sends for one document. The system message is assembled from sections, the user message is the @@ -72,9 +57,7 @@ def build_messages( """ sections: list[str] = [request.instruction or _TASK] - sections.append( - _PROSE_FORM if enforcement.output_form is OutputForm.PROSE else _JSON_FORM - ) + sections.append(_PROSE_FORM if enforcement.output_form is OutputForm.PROSE else _JSON_FORM) if enforcement.catalogue: listed = "\n".join(f"- {name}" for name in enforcement.catalogue) diff --git a/src/oold/agent/provider.py b/src/oold/agent/provider.py index 3c4a372..5e169d7 100644 --- a/src/oold/agent/provider.py +++ b/src/oold/agent/provider.py @@ -2,10 +2,10 @@ Providers accept different subsets of JSON Schema, so the same OO-LD schema reaches each of them differently. That makes the transform part of the -treatment rather than a utility. If one provider is handed a schema that lost +treatment and not a utility. If one provider is handed a schema that lost its constraints and another is not, a measured difference between them is partly a difference between transforms. So the profile is declared in -configuration rather than sniffed from a model name, the prepared schema is +configuration and never sniffed from a model name, the prepared schema is hashed into the result, and what the transform removed is reported as a number. The combinator flattening follows the approach taken by LiteLLM's diff --git a/tests/test_agent/test_extraction.py b/tests/test_agent/test_extraction.py index 59cb97f..43f8bbb 100644 --- a/tests/test_agent/test_extraction.py +++ b/tests/test_agent/test_extraction.py @@ -97,9 +97,7 @@ def test_the_shared_instruction_is_identical_across_arms(self): def test_prose_and_json_arms_ask_for_different_forms(self): prose, as_json = FakeClient(), FakeClient() - ExtractionAgent( - prose, ARMS["A0-prose"], profile_for("openai") - ).run(ExtractionRequest("doc")) + ExtractionAgent(prose, ARMS["A0-prose"], profile_for("openai")).run(ExtractionRequest("doc")) agent("A0-json", as_json).run(ExtractionRequest("doc")) assert "prose" in prose.system().lower() assert "JSON" in as_json.system() @@ -125,9 +123,7 @@ def test_a_schema_with_no_class_slot_fails_loudly(self): """A silent no-op would run an arm unconstrained and call it constrained.""" client = FakeClient() with pytest.raises(ValueError, match="no class property to pin"): - agent("A2", client).run( - ExtractionRequest("doc", {"type": "object", "properties": {"v": {}}}) - ) + agent("A2", client).run(ExtractionRequest("doc", {"type": "object", "properties": {"v": {}}})) def test_the_schema_actually_sent_is_hashed(self): client = FakeClient() @@ -136,12 +132,8 @@ def test_the_schema_actually_sent_is_hashed(self): def test_two_providers_get_different_schemas(self): """Preparation is part of the treatment, so it has to be recorded.""" - strict = agent("A2", FakeClient(), profile="anthropic").run( - ExtractionRequest("doc", SCHEMA) - ) - lenient = agent("A2", FakeClient(), profile="openai").run( - ExtractionRequest("doc", SCHEMA) - ) + strict = agent("A2", FakeClient(), profile="anthropic").run(ExtractionRequest("doc", SCHEMA)) + lenient = agent("A2", FakeClient(), profile="openai").run(ExtractionRequest("doc", SCHEMA)) assert strict.schema_sha256 != lenient.schema_sha256 assert strict.degradation is not None @@ -164,10 +156,7 @@ def test_an_entity_outside_the_catalogue_is_dropped(self): def test_the_filtered_result_is_the_one_returned(self): """Keeping corrections and discarding removals is the predecessor's bug.""" - client = FakeClient( - '{"entities": [{"type": "quantities.Length", "value": 1},' - ' {"type": "Nope", "value": 2}]}' - ) + client = FakeClient('{"entities": [{"type": "quantities.Length", "value": 1}, {"type": "Nope", "value": 2}]}') result = agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) assert len(result.payload["entities"]) == 1 @@ -198,9 +187,7 @@ def test_malformed_json_is_not_repaired(self): def test_a_prose_arm_is_not_asked_to_parse(self): client = FakeClient("The length was one metre.") - result = ExtractionAgent( - client, ARMS["A0-prose"], profile_for("openai") - ).run(ExtractionRequest("doc")) + result = ExtractionAgent(client, ARMS["A0-prose"], profile_for("openai")).run(ExtractionRequest("doc")) assert result.text == "The length was one metre." assert client.calls == 1 @@ -240,9 +227,7 @@ def test_single_shot_makes_one_call(self): "orchestration", [Orchestration.RECURSIVE, Orchestration.SEGMENTED, Orchestration.MULTI_STEP], ) - def test_an_unported_orchestration_refuses_rather_than_pretending( - self, orchestration - ): + def test_an_unported_orchestration_refuses_rather_than_pretending(self, orchestration): with pytest.raises(NotImplementedError, match="not ported yet"): ExtractionAgent( FakeClient(), From 904319557bae6e0b21500d98f41a3e5d58102550 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 07:09:42 +0200 Subject: [PATCH 05/58] feat(agent): fold the system message where a deployment drops it - some deployments accept a system message, return 200 and discard it - folding is declared per client, never applied on a guess - expose the wrapped chat model so a caller can check what it was built with - adapter tests, including the token evidence for the dropped message --- src/oold/agent/langchain_client.py | 56 +++++++--- tests/test_agent/test_langchain_client.py | 118 ++++++++++++++++++++++ 2 files changed, 162 insertions(+), 12 deletions(-) create mode 100644 tests/test_agent/test_langchain_client.py diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index 7a74167..b51e7a5 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -1,8 +1,9 @@ """A :class:`~oold.agent.client.ChatClient` over LangChain. -One bundled adapter, so the package is usable without writing one, and only -one, so the abstraction stays honest. Provider packages are not declared here, -because a consumer installs the LangChain integration for the provider it uses. +One bundled adapter, so the package is usable without writing one. It stays +the only one, so the protocol is not shaped around LangChain. Provider +packages are not declared here, because a consumer installs the LangChain +integration for the provider it uses. Requires the ``agent`` extra. """ @@ -16,16 +17,37 @@ from oold.agent.client import ChatResponse, Message, TokenUsage -__all__ = ["LangChainClient", "usage_from_message"] +__all__ = ["LangChainClient", "fold_system_into_user", "usage_from_message"] + + +def fold_system_into_user(messages: Sequence[Message]) -> list[tuple[str, str]]: + """Put the system content at the top of the first user turn. + + Some deployments accept a system message, return 200, and drop it. The + token count shows it: a prompt carrying a schema arrives counted at five + tokens, and the model answers as if it had been asked nothing. If this + goes unnoticed, the study reports the model failing a task it was never + given. + + Folding is declared per model and recorded, never applied on a guess, + because it changes the prompt and the prompt is part of the treatment. + """ + system = "\n\n".join(m.content for m in messages if m.role == "system") + rest = [m for m in messages if m.role != "system"] + if not system or not rest: + return [(m.role, m.content) for m in messages] + first, *others = rest + folded = f"{system}\n\n{first.content}" + return [(first.role, folded)] + [(m.role, m.content) for m in others] def usage_from_message(message: Any) -> TokenUsage: """Read token counts off a LangChain message. - LangChain normalises providers into ``usage_metadata``, but the nested + LangChain normalizes providers into ``usage_metadata``, but the nested detail dictionaries are optional and differ by provider, so every lookup is defensive. A provider that reports nothing yields zeros instead of - raising, and a zero total is the signal that a model is uninstrumented. + raising, and a zero total means the provider sent no token counts. """ metadata = getattr(message, "usage_metadata", None) or {} input_details = metadata.get("input_token_details") or {} @@ -41,13 +63,22 @@ def usage_from_message(message: Any) -> TokenUsage: class LangChainClient: """Adapt a LangChain chat model to the :class:`ChatClient` protocol.""" - def __init__(self, llm: BaseChatModel, model: str) -> None: + def __init__(self, llm: BaseChatModel, model: str, *, fold_system: bool = False) -> None: self._llm = llm self.model = model """The identifier recorded in the result. Passed in instead of read - off the object, because what a provider calls a model and what a - deployment is named are different strings and the result needs the - one that identifies the weights.""" + off the object: the provider's model name and the deployment name are + different strings, and the result needs the one that identifies the + weights.""" + self.fold_system = fold_system + """Whether the system content is folded into the first user turn. + Set for deployments that discard a system message without saying so. + Recorded, because it changes the prompt the model was sent.""" + + @property + def llm(self) -> BaseChatModel: + """The wrapped chat model, so a caller can check what it was built with.""" + return self._llm def invoke( self, @@ -57,10 +88,11 @@ def invoke( ) -> ChatResponse: llm: Any = self._llm parsed: dict[str, Any] | None = None + turns = fold_system_into_user(messages) if self.fold_system else [(m.role, m.content) for m in messages] if response_format is not None: structured = llm.with_structured_output(response_format, include_raw=True) - result = structured.invoke([(m.role, m.content) for m in messages]) + result = structured.invoke(turns) raw = result.get("raw") if isinstance(result, dict) else None parsing_error = result.get("parsing_error") if isinstance(result, dict) else None if parsing_error is not None: @@ -76,7 +108,7 @@ def invoke( raw=raw, ) - reply = llm.invoke([(m.role, m.content) for m in messages]) + reply = llm.invoke(turns) content = getattr(reply, "content", reply) return ChatResponse( text=content if isinstance(content, str) else str(content), diff --git a/tests/test_agent/test_langchain_client.py b/tests/test_agent/test_langchain_client.py new file mode 100644 index 0000000..a5f99fc --- /dev/null +++ b/tests/test_agent/test_langchain_client.py @@ -0,0 +1,118 @@ +"""The bundled LangChain adapter. + +No provider is called. What is checked is what the adapter sends and what it +reads back, because both have already been wrong in a way that looked like a +model failing. +""" + +import pytest + +from oold.agent.client import Message + +pytest.importorskip("langchain_core") + +from oold.agent.langchain_client import ( # noqa: E402 + LangChainClient, + fold_system_into_user, + usage_from_message, +) + + +class _Reply: + def __init__(self, content: str, usage: dict | None = None) -> None: + self.content = content + self.usage_metadata = usage + + +class _Recorder: + """A chat model that records the turns it was handed.""" + + def __init__(self, content: str = "ok", usage: dict | None = None) -> None: + self.content = content + self.usage = usage + self.seen: list[tuple[str, str]] = [] + + def invoke(self, turns): + self.seen = list(turns) + return _Reply(self.content, self.usage) + + +class TestReadingTokenCounts: + def test_counts_are_read_off_the_message(self): + usage = usage_from_message(_Reply("x", {"input_tokens": 12, "output_tokens": 3})) + assert usage.input_tokens == 12 + assert usage.output_tokens == 3 + + def test_a_provider_reporting_nothing_yields_zeros(self): + """A zero total is the signal that a model is uninstrumented.""" + assert usage_from_message(_Reply("x")).total == 0 + + def test_cached_and_reasoning_details_are_read_when_present(self): + usage = usage_from_message( + _Reply( + "x", + { + "input_tokens": 100, + "output_tokens": 10, + "input_token_details": {"cache_read": 80}, + "output_token_details": {"reasoning": 7}, + }, + ) + ) + assert usage.cached_input_tokens == 80 + assert usage.reasoning_tokens == 7 + + +class TestFoldingTheSystemMessage: + """Some deployments accept a system message and silently drop it.""" + + def test_folding_puts_the_system_content_in_the_first_user_turn(self): + turns = fold_system_into_user([ + Message(role="system", content="Answer in JSON."), + Message(role="user", content="The reading was 40.1 hertz."), + ]) + assert len(turns) == 1 + assert turns[0][0] == "user" + assert "Answer in JSON." in turns[0][1] + assert "40.1 hertz" in turns[0][1] + + def test_nothing_is_lost_when_there_is_no_system_message(self): + assert fold_system_into_user([Message(role="user", content="Hello.")]) == [ + ("user", "Hello.") + ] + + def test_a_system_message_with_nothing_to_fold_into_is_left_alone(self): + assert fold_system_into_user([Message(role="system", content="Only this.")]) == [ + ("system", "Only this.") + ] + + def test_later_turns_are_untouched(self): + turns = fold_system_into_user([ + Message(role="system", content="S"), + Message(role="user", content="A"), + Message(role="assistant", content="B"), + Message(role="user", content="C"), + ]) + assert turns[1:] == [("assistant", "B"), ("user", "C")] + + def test_the_client_does_not_fold_unless_asked(self): + """Folding changes the prompt, so it is declared and not guessed.""" + llm = _Recorder() + LangChainClient(llm, model="m").invoke([ + Message(role="system", content="S"), + Message(role="user", content="U"), + ]) + assert [role for role, _ in llm.seen] == ["system", "user"] + + def test_the_client_folds_when_asked(self): + llm = _Recorder() + LangChainClient(llm, model="m", fold_system=True).invoke([ + Message(role="system", content="S"), + Message(role="user", content="U"), + ]) + assert [role for role, _ in llm.seen] == ["user"] + assert llm.seen[0][1] == "S\n\nU" + + def test_folding_is_visible_on_the_client(self): + assert LangChainClient(_Recorder(), model="m", fold_system=True).fold_system is True + assert LangChainClient(_Recorder(), model="m").fold_system is False From 888984a561c4998a21d23ab907f8e755c482144e Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 07:19:43 +0200 Subject: [PATCH 06/58] feat(agent): record the prompt the model was actually sent - prompt_hash covers the assembled turns, folding included - message folding moves to the core client, no LangChain dependency - ExtractionResult carries prompt_sha256 beside schema_sha256 --- src/oold/agent/client.py | 36 ++++++++++++++++++++++ src/oold/agent/extraction.py | 9 +++++- src/oold/agent/langchain_client.py | 28 ++++------------- tests/test_agent/test_client.py | 37 +++++++++++++++++++++++ tests/test_agent/test_langchain_client.py | 14 +++------ 5 files changed, 92 insertions(+), 32 deletions(-) diff --git a/src/oold/agent/client.py b/src/oold/agent/client.py index 5a084b8..0056ce8 100644 --- a/src/oold/agent/client.py +++ b/src/oold/agent/client.py @@ -14,6 +14,8 @@ from __future__ import annotations +import hashlib +import json import threading import time from collections.abc import Iterator, Sequence @@ -28,6 +30,8 @@ "ChatResponse", "Message", "TokenUsage", + "fold_system_into_user", + "prompt_hash", ] @@ -37,6 +41,38 @@ class Message: content: str +def fold_system_into_user(messages: Sequence[Message]) -> list[tuple[str, str]]: + """Put the system content at the top of the first user turn. + + Some deployments accept a system message, return 200, and drop it. The + token count shows it: a prompt carrying a schema arrives counted at five + tokens, and the model answers as if it had been asked nothing. If this + goes unnoticed, the study reports the model failing a task it was never + given. + + Folding is declared per client, never applied on a guess, because it + changes the prompt and the prompt is part of the treatment. + """ + system = "\n\n".join(m.content for m in messages if m.role == "system") + rest = [m for m in messages if m.role != "system"] + if not system or not rest: + return [(m.role, m.content) for m in messages] + first, *others = rest + folded = f"{system}\n\n{first.content}" + return [(first.role, folded)] + [(m.role, m.content) for m in others] + + +def prompt_hash(messages: Sequence[Message], *, fold_system: bool = False) -> str: + """Hash of the turns a client sends, not of the document alone. + + Folding changes the bytes one model receives, so a hash taken before it + would say two models were sent the same prompt when they were not. + """ + turns = fold_system_into_user(messages) if fold_system else [(m.role, m.content) for m in messages] + canonical = json.dumps(turns, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + @dataclass(frozen=True) class TokenUsage: """Tokens for one call, with the tiers that are priced differently.""" diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index aba52a4..7e0d3bd 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -18,7 +18,7 @@ from dataclasses import dataclass, field from typing import Any -from oold.agent.client import CallLog, ChatClient, TokenUsage +from oold.agent.client import CallLog, ChatClient, TokenUsage, prompt_hash from oold.agent.enforcement import ( DecodeConstraint, Enforcement, @@ -59,6 +59,10 @@ class ExtractionResult: calls: CallLog degradation: Degradation | None = None schema_sha256: str | None = None + prompt_sha256: str | None = None + """Hash of the turns actually sent, folding included. Hashing the document + instead would say two models got the same prompt when one of them had the + system message folded into its user turn.""" dropped: list[str] = field(default_factory=list) """Classes the commit-time gate removed, so the gate's effect is visible instead of being folded into a lower score.""" @@ -71,6 +75,7 @@ def describe(self) -> dict[str, Any]: return { "parsed": self.parsed, "schema_sha256": self.schema_sha256, + "prompt_sha256": self.prompt_sha256, "dropped": list(self.dropped), "degradation": self.degradation.describe() if self.degradation else None, "calls": self.calls.describe(), @@ -111,6 +116,7 @@ def run(self, request: ExtractionRequest) -> ExtractionResult: ), self.enforcement, ) + digest_prompt = prompt_hash(messages, fold_system=getattr(self.client, "fold_system", False)) response_format = ( prepared if prepared is not None and self.enforcement.decode_constraint is not DecodeConstraint.NONE @@ -138,6 +144,7 @@ def run(self, request: ExtractionRequest) -> ExtractionResult: calls=log, degradation=degradation, schema_sha256=digest, + prompt_sha256=digest_prompt, dropped=dropped, ) diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index b51e7a5..92a354a 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -15,32 +15,16 @@ from langchain_core.language_models import BaseChatModel -from oold.agent.client import ChatResponse, Message, TokenUsage +from oold.agent.client import ( + ChatResponse, + Message, + TokenUsage, + fold_system_into_user, +) __all__ = ["LangChainClient", "fold_system_into_user", "usage_from_message"] -def fold_system_into_user(messages: Sequence[Message]) -> list[tuple[str, str]]: - """Put the system content at the top of the first user turn. - - Some deployments accept a system message, return 200, and drop it. The - token count shows it: a prompt carrying a schema arrives counted at five - tokens, and the model answers as if it had been asked nothing. If this - goes unnoticed, the study reports the model failing a task it was never - given. - - Folding is declared per model and recorded, never applied on a guess, - because it changes the prompt and the prompt is part of the treatment. - """ - system = "\n\n".join(m.content for m in messages if m.role == "system") - rest = [m for m in messages if m.role != "system"] - if not system or not rest: - return [(m.role, m.content) for m in messages] - first, *others = rest - folded = f"{system}\n\n{first.content}" - return [(first.role, folded)] + [(m.role, m.content) for m in others] - - def usage_from_message(message: Any) -> TokenUsage: """Read token counts off a LangChain message. diff --git a/tests/test_agent/test_client.py b/tests/test_agent/test_client.py index d3f6525..342721c 100644 --- a/tests/test_agent/test_client.py +++ b/tests/test_agent/test_client.py @@ -5,6 +5,7 @@ import pytest from oold.agent import Call, CallLog, ChatClient, ChatResponse, Message, TokenUsage +from oold.agent.client import prompt_hash class FakeClient: @@ -176,3 +177,39 @@ class Reply: usage = adapter.usage_from_message(Reply()) assert usage.total == 12 assert usage.cached_input_tokens == 0 + + +class TestHashingThePrompt: + """The record has to name the bytes a model was sent.""" + + MESSAGES = [ + Message(role="system", content="Answer in JSON."), + Message(role="user", content="The reading was 40.1 hertz."), + ] + + def test_the_same_turns_hash_the_same(self): + assert prompt_hash(self.MESSAGES) == prompt_hash(self.MESSAGES) + + def test_a_different_document_hashes_differently(self): + other = [self.MESSAGES[0], Message(role="user", content="Something else.")] + assert prompt_hash(self.MESSAGES) != prompt_hash(other) + + def test_a_different_instruction_hashes_differently(self): + """Two arms differ in the system message and nowhere else.""" + other = [Message(role="system", content="Answer in prose."), self.MESSAGES[1]] + assert prompt_hash(self.MESSAGES) != prompt_hash(other) + + def test_folding_changes_the_hash(self): + """One model gets different bytes, so it gets a different hash.""" + assert prompt_hash(self.MESSAGES) != prompt_hash(self.MESSAGES, fold_system=True) + + def test_a_folded_prompt_hashes_as_the_folded_turns(self): + folded = [Message(role="user", content="Answer in JSON.\n\nThe reading was 40.1 hertz.")] + assert prompt_hash(self.MESSAGES, fold_system=True) == prompt_hash(folded) + + def test_the_hash_is_a_sha256(self): + assert len(prompt_hash(self.MESSAGES)) == 64 + + def test_non_ascii_content_does_not_change_between_runs(self): + german = [Message(role="user", content="Die Molmasse betrug 79,7 Gramm pro Mol.")] + assert prompt_hash(german) == prompt_hash(german) diff --git a/tests/test_agent/test_langchain_client.py b/tests/test_agent/test_langchain_client.py index a5f99fc..ecc650f 100644 --- a/tests/test_agent/test_langchain_client.py +++ b/tests/test_agent/test_langchain_client.py @@ -1,6 +1,6 @@ """The bundled LangChain adapter. -No provider is called. What is checked is what the adapter sends and what it +No provider is called. The tests check what the adapter sends and what it reads back, because both have already been wrong in a way that looked like a model failing. """ @@ -11,7 +11,7 @@ pytest.importorskip("langchain_core") -from oold.agent.langchain_client import ( # noqa: E402 +from oold.agent.langchain_client import ( LangChainClient, fold_system_into_user, usage_from_message, @@ -44,7 +44,7 @@ def test_counts_are_read_off_the_message(self): assert usage.output_tokens == 3 def test_a_provider_reporting_nothing_yields_zeros(self): - """A zero total is the signal that a model is uninstrumented.""" + """A zero total means the provider sent no token counts.""" assert usage_from_message(_Reply("x")).total == 0 def test_cached_and_reasoning_details_are_read_when_present(self): @@ -77,14 +77,10 @@ def test_folding_puts_the_system_content_in_the_first_user_turn(self): assert "40.1 hertz" in turns[0][1] def test_nothing_is_lost_when_there_is_no_system_message(self): - assert fold_system_into_user([Message(role="user", content="Hello.")]) == [ - ("user", "Hello.") - ] + assert fold_system_into_user([Message(role="user", content="Hello.")]) == [("user", "Hello.")] def test_a_system_message_with_nothing_to_fold_into_is_left_alone(self): - assert fold_system_into_user([Message(role="system", content="Only this.")]) == [ - ("system", "Only this.") - ] + assert fold_system_into_user([Message(role="system", content="Only this.")]) == [("system", "Only this.")] def test_later_turns_are_untouched(self): turns = fold_system_into_user([ From 1b80f38553ca32b6595e9e11cb76f0a1881ded51 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 08:05:10 +0200 Subject: [PATCH 07/58] feat(agent): close the unit slot as well as the class slot - Enforcement carries a unit enumeration beside the catalogue - A2 pins both when the corpus closes both - silent when no units are offered, loud when the slot is missing - unit enumeration size goes into the record --- src/oold/agent/enforcement.py | 13 +++++++ src/oold/agent/extraction.py | 42 +++++++++++++++++++--- tests/test_agent/test_enforcement.py | 20 +++++++++++ tests/test_agent/test_extraction.py | 53 ++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 5 deletions(-) diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index c3bca51..e1ddb5c 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -89,6 +89,14 @@ class Enforcement: output_form: OutputForm = OutputForm.JSON + unit_catalogue: tuple[str, ...] | None = None + """Units offered for selection, when the corpus closes that slot too. + + A quantity corpus enumerates the units each kind admits, so leaving the + unit a free string constrains half of what the schema actually says. Kept + separate from ``catalogue`` because the two are closed by different facts + and a study may want to close one without the other.""" + def __post_init__(self) -> None: if self.grounding and not self.schema_in_prompt: raise ValueError("grounding needs a schema to ground, so set schema_in_prompt when grounding is on") @@ -111,6 +119,10 @@ def with_catalogue(self, paths: tuple[str, ...] | None) -> Enforcement: """ return replace(self, catalogue=paths) + def with_units(self, units: tuple[str, ...] | None) -> Enforcement: + """The same condition over a different unit enumeration.""" + return replace(self, unit_catalogue=units) + def describe(self) -> dict[str, object]: """The condition, for the result record. @@ -121,6 +133,7 @@ def describe(self) -> dict[str, object]: return { "schema_in_prompt": self.schema_in_prompt, "catalogue_size": self.catalogue_size, + "unit_catalogue_size": (len(self.unit_catalogue) if self.unit_catalogue else 0), "catalogue_offered": self.catalogue is not None, "decode_constraint": self.decode_constraint.value, "commit_gate": self.commit_gate, diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 7e0d3bd..ca63c13 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -158,6 +158,7 @@ def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None prepared, degradation = prepare(request.schema, self.profile, grounding=self.enforcement.grounding) if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM: prepared = self._pin_class(prepared) + prepared = self._pin_units(prepared) return prepared, degradation, schema_hash(prepared) def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: @@ -175,6 +176,26 @@ def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: target["enum"] = list(self.enforcement.catalogue) return schema + def _pin_units(self, schema: dict[str, Any]) -> dict[str, Any]: + """Constrain the unit slot, when the corpus closes it. + + A quantity corpus enumerates the units each kind admits. Pinning the + class and leaving the unit a free string enforces half of what the + schema says, and the half left open is the one models get wrong. + + Silent when no unit enumeration was supplied, because a corpus that + does not close the slot is a condition, not a mistake. That is the + opposite of :meth:`_pin_class`, which raises: there the catalogue was + asked for and the slot to put it in was missing. + """ + if not self.enforcement.unit_catalogue: + return schema + target = _find_property(schema, _UNIT_KEYS) + if target is None: + raise ValueError("the schema has no unit property to pin, so the unit enumeration cannot be applied") + target["enum"] = list(self.enforcement.unit_catalogue) + return schema + def _gate(self, payload: Any) -> tuple[Any, list[str]]: """Drop entities whose class is not in the catalogue. @@ -213,6 +234,8 @@ def keep(entity: Any) -> bool: _CLASS_KEYS = ("type", "@type", "class", "class_path", "schema_path", "kind") +_UNIT_KEYS = ("unit", "units", "unit_symbol", "uom") + def _class_of(entity: dict[str, Any]) -> str | None: for key in _CLASS_KEYS: @@ -231,22 +254,31 @@ def _set_class(entity: dict[str, Any], name: str) -> None: return -def _find_class_property(schema: Any) -> dict[str, Any] | None: - """The subschema describing an entity's class, wherever it sits.""" +def _find_property(schema: Any, keys: tuple[str, ...]) -> dict[str, Any] | None: + """The subschema for one of these property names, wherever it sits. + + Only names under a ``properties`` map count, so the ``type`` keyword of + JSON Schema itself is never mistaken for a property called ``type``. + """ if isinstance(schema, dict): properties = schema.get("properties") if isinstance(properties, dict): - for key in _CLASS_KEYS: + for key in keys: target = properties.get(key) if isinstance(target, dict): return target for value in schema.values(): - found = _find_class_property(value) + found = _find_property(value, keys) if found is not None: return found elif isinstance(schema, list): for item in schema: - found = _find_class_property(item) + found = _find_property(item, keys) if found is not None: return found return None + + +def _find_class_property(schema: Any) -> dict[str, Any] | None: + """The subschema describing an entity's class, wherever it sits.""" + return _find_property(schema, _CLASS_KEYS) diff --git a/tests/test_agent/test_enforcement.py b/tests/test_agent/test_enforcement.py index dad3503..e9c83dd 100644 --- a/tests/test_agent/test_enforcement.py +++ b/tests/test_agent/test_enforcement.py @@ -140,3 +140,23 @@ def test_orchestration_covers_single_shot_and_the_three_reference_agents(): "segmented", "multi_step", ] + + +class TestClosingTheUnitSlot: + """A quantity corpus enumerates the units each kind admits.""" + + def test_an_arm_carries_no_unit_enumeration_by_default(self): + assert arm("A2", ("Length",)).unit_catalogue is None + + def test_units_can_be_set_without_touching_the_catalogue(self): + enforcement = arm("A2", ("Length",)).with_units(("meter", "foot")) + assert enforcement.unit_catalogue == ("meter", "foot") + assert enforcement.catalogue == ("Length",) + + def test_the_unit_enumeration_is_reported(self): + """A closed slot nobody records looks like a free one.""" + described = arm("A2", ("Length",)).with_units(("meter", "foot")).describe() + assert described["unit_catalogue_size"] == 2 + + def test_no_unit_enumeration_reports_zero(self): + assert arm("A2", ("Length",)).describe()["unit_catalogue_size"] == 0 diff --git a/tests/test_agent/test_extraction.py b/tests/test_agent/test_extraction.py index 43f8bbb..3623540 100644 --- a/tests/test_agent/test_extraction.py +++ b/tests/test_agent/test_extraction.py @@ -261,3 +261,56 @@ def test_build_messages_needs_no_agent(): ) messages = build_messages(ExtractionRequest("doc"), condition) assert [m.role for m in messages] == ["system", "user"] + + +class TestPinningTheUnitSlot: + """A2 closes every slot the corpus closes, not only the class.""" + + SCHEMA = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "value": {"type": "number"}, + "unit": {"type": "string"}, + }, + }, + } + }, + } + + def sent(self, enforcement): + client = FakeClient('{"entities": []}') + ExtractionAgent(client, enforcement, profile_for("openai")).run( + ExtractionRequest(document="The reading was 1.0 meter.", schema=self.SCHEMA) + ) + return client.response_format + + def unit_slot(self, schema): + return schema["properties"]["entities"]["items"]["properties"]["unit"] + + def test_the_unit_slot_is_pinned_when_units_are_offered(self): + schema = self.sent(arm("A2", ("Length",)).with_units(("meter", "foot"))) + assert self.unit_slot(schema)["enum"] == ["meter", "foot"] + + def test_the_unit_slot_is_left_open_when_none_are_offered(self): + """A corpus that does not close the slot is a condition, not a fault.""" + assert "enum" not in self.unit_slot(self.sent(arm("A2", ("Length",)))) + + def test_the_class_slot_is_still_pinned(self): + schema = self.sent(arm("A2", ("Length",)).with_units(("meter",))) + assert schema["properties"]["entities"]["items"]["properties"]["type"]["enum"] == ["Length"] + + def test_an_unconstrained_arm_sends_no_schema_at_all(self): + assert self.sent(arm("A1", ("Length",)).with_units(("meter",))) is None + + def test_a_schema_with_no_unit_slot_is_refused(self): + client = FakeClient('{"entities": []}') + agent = ExtractionAgent(client, arm("A2", ("Length",)).with_units(("meter",)), profile_for("openai")) + bare = {"type": "object", "properties": {"type": {"type": "string"}}} + with pytest.raises(ValueError, match="no unit property"): + agent.run(ExtractionRequest(document="d", schema=bare)) From fe07a2f71d5927c7a52f0424c4a734c0a4733fc0 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 10:54:53 +0200 Subject: [PATCH 08/58] feat(agent): show the catalogue as entries, not bare identifiers - catalogue_text carries what the prompt shows, kept apart from the enum - identifiers stay the answer, so a rendered entry leads with its own - length mismatch is refused, or one class is described as another --- src/oold/agent/enforcement.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index e1ddb5c..a035cec 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -89,6 +89,16 @@ class Enforcement: output_form: OutputForm = OutputForm.JSON + catalogue_text: tuple[str, ...] | None = None + """What the catalogue looks like in the prompt, one rendered entry per + class. + + Kept apart from :attr:`catalogue`, which stays a list of bare identifiers + because that is what the decode-time enum and the commit gate need. A + catalogue shown as identifiers alone asks a model to choose between names + it has been told nothing about, which measures whether the names happen to + be self-describing. Falls back to the identifiers when unset.""" + unit_catalogue: tuple[str, ...] | None = None """Units offered for selection, when the corpus closes that slot too. @@ -123,6 +133,15 @@ def with_units(self, units: tuple[str, ...] | None) -> Enforcement: """The same condition over a different unit enumeration.""" return replace(self, unit_catalogue=units) + def with_catalogue_text(self, entries: tuple[str, ...] | None) -> Enforcement: + """The same condition with the catalogue rendered for the prompt.""" + if entries is not None and self.catalogue is not None and len(entries) != len(self.catalogue): + raise ValueError( + f"catalogue_text has {len(entries)} entries but the catalogue has " + f"{len(self.catalogue)}, so one class would be described as another" + ) + return replace(self, catalogue_text=entries) + def describe(self) -> dict[str, object]: """The condition, for the result record. @@ -134,6 +153,7 @@ def describe(self) -> dict[str, object]: "schema_in_prompt": self.schema_in_prompt, "catalogue_size": self.catalogue_size, "unit_catalogue_size": (len(self.unit_catalogue) if self.unit_catalogue else 0), + "catalogue_described": self.catalogue_text is not None, "catalogue_offered": self.catalogue is not None, "decode_constraint": self.decode_constraint.value, "commit_gate": self.commit_gate, From c3b0cc845e219b97f7fd6ee1ac3a1ca46b42148d Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 11:12:20 +0200 Subject: [PATCH 09/58] fix: put the rendered catalogue in the prompt - catalogue_text reached the record but never the message - tests covered the plumbing and never read the prompt, so none failed - test_prompts asserts what each condition actually shows a model --- src/oold/agent/prompts.py | 7 ++- tests/test_agent/test_prompts.py | 101 +++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 tests/test_agent/test_prompts.py diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index deec5e9..e33cc60 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -60,8 +60,11 @@ def build_messages(request: ExtractionRequest, enforcement: Enforcement) -> list sections.append(_PROSE_FORM if enforcement.output_form is OutputForm.PROSE else _JSON_FORM) if enforcement.catalogue: - listed = "\n".join(f"- {name}" for name in enforcement.catalogue) - sections.append(f"{_CATALOGUE}\n{listed}") + # Rendered entries when the condition supplies them, identifiers + # otherwise. The identifier stays the answer either way, so a rendered + # entry has to carry its own. + entries = enforcement.catalogue_text or tuple(f"- {name}" for name in enforcement.catalogue) + sections.append(f"{_CATALOGUE}\n" + "\n".join(entries)) if enforcement.commit_gate: sections.append(_GATE_HINT) diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py new file mode 100644 index 0000000..666b7a6 --- /dev/null +++ b/tests/test_agent/test_prompts.py @@ -0,0 +1,101 @@ +"""What each condition actually puts in front of a model. + +Every difference between arms has to be visible here, because this is where +the arms differ. A condition that is recorded but never reaches the prompt is +the worst kind of bug: the record says the run was one thing and the model saw +another. +""" + +from oold.agent.enforcement import arm +from oold.agent.prompts import ExtractionRequest, build_messages + + +def request(schema: dict | None = None) -> ExtractionRequest: + return ExtractionRequest( + document="The reading was 1.0 meter.", + schema=schema if schema is not None else {"type": "object"}, + ) + + +def sections(enforcement) -> list[str]: + return build_messages(request(), enforcement)[0].content.split("\n\n") + + +def catalogue_section(enforcement) -> str: + return next(s for s in sections(enforcement) if s.startswith("Choose the class")) + + +class TestTheShapeOfTheMessages: + def test_the_document_is_the_user_message_and_nothing_else(self): + """So a model that treats the last turn as the instruction cannot + confuse the two.""" + messages = build_messages(request(), arm("A2", ("Length",))) + assert messages[1].role == "user" + assert messages[1].content == "The reading was 1.0 meter." + + def test_the_task_sentence_is_identical_across_arms(self): + """A difference in wording would be a difference nobody declared.""" + first = sections(arm("A1", ("Length",)))[0] + second = sections(arm("A2", ("Length",)))[0] + assert first == second + + def test_an_arm_with_no_catalogue_gets_no_catalogue_section(self): + assert not any(s.startswith("Choose the class") for s in sections(arm("A0-json"))) + + +class TestWhatTheCatalogueLooksLike: + """The rendered entries have to reach the prompt, not just the record. + + This class exists because they did not. ``catalogue_text`` was plumbed + through the condition, reported in ``describe()``, and then dropped here, + and every test passed because none of them read the prompt. + """ + + def test_identifiers_are_listed_when_no_text_is_supplied(self): + section = catalogue_section(arm("A2", ("Length", "Mass"))) + assert "- Length" in section + assert "- Mass" in section + + def test_rendered_entries_replace_the_bare_list(self): + enforcement = arm("A2", ("Length", "Mass")).with_catalogue_text( + ("- Length (Length)\n units: meter", "- Mass (Mass)\n units: gram") + ) + section = catalogue_section(enforcement) + assert "units: meter" in section + assert "units: gram" in section + + def test_the_identifier_survives_in_a_rendered_entry(self): + """It is still the answer, however much else is shown.""" + enforcement = arm("A2", ("Length",)).with_catalogue_text( + ("- Length (Length)\n units: meter",) + ) + assert "- Length" in catalogue_section(enforcement) + + def test_every_offered_class_reaches_the_prompt(self): + names = tuple(f"C{i}" for i in range(40)) + enforcement = arm("A2", names).with_catalogue_text( + tuple(f"- {n} (label {n})" for n in names) + ) + section = catalogue_section(enforcement) + assert all(f"- {n} (label {n})" in section for n in names) + + def test_a_described_catalogue_is_longer_than_a_bare_one(self): + bare = catalogue_section(arm("A2", ("Length",))) + described = catalogue_section( + arm("A2", ("Length",)).with_catalogue_text(("- Length (Length)\n units: meter",)) + ) + assert len(described) > len(bare) + + +class TestWhatTheSchemaSectionCarries: + def test_an_arm_that_shows_no_schema_has_no_schema_section(self): + assert not any(s.startswith("Each entity must conform") for s in sections(arm("A0-json"))) + + def test_an_arm_that_shows_a_schema_carries_it_whole(self): + schema = {"type": "object", "properties": {"unit": {"type": "string"}}} + content = build_messages(request(schema), arm("A1", ("Length",)))[0].content + assert '"unit"' in content + + def test_the_gate_warning_appears_only_with_a_gate(self): + assert any("discarded" in s for s in sections(arm("A2", ("Length",)))) + assert not any("discarded" in s for s in sections(arm("A0-json"))) From 8b926e450b9459e358e0da438405f7fee72ffb07 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 12:12:36 +0200 Subject: [PATCH 10/58] feat(agent): constrain class and value jointly with a union - union_schema builds one anyOf branch per class, discriminated by const - an enum pair cannot say which unit belongs to which class; a union can - prepare() degraded a union to branch 0, losing every other class - arm A4 for the union, A2-enforced-only to separate shown from enforced - branches travel on the request, so the package learns no corpus --- src/oold/agent/enforcement.py | 34 ++++- src/oold/agent/extraction.py | 53 +++++++ src/oold/agent/prompts.py | 4 + src/oold/agent/provider.py | 14 +- src/oold/agent/union.py | 134 +++++++++++++++++ tests/test_agent/test_enforcement.py | 29 +++- tests/test_agent/test_prompts.py | 15 +- tests/test_agent/test_union.py | 211 +++++++++++++++++++++++++++ 8 files changed, 478 insertions(+), 16 deletions(-) create mode 100644 src/oold/agent/union.py create mode 100644 tests/test_agent/test_union.py diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index a035cec..807e58b 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -40,6 +40,14 @@ class Orchestration(str, Enum): MULTI_STEP = "multi_step" """Detect, select properties, extract, construct, deduplicate.""" + SELECT_THEN_FILL = "select_then_fill" + """Shortlist the class, then fill the schema that shortlist implies. + + The general answer to a corpus whose subclasses add properties. A flat + schema there is the union of every property any class might carry, which + admits an answer no class allows. Selecting first makes the second call + carry only what the chosen classes actually define.""" + class DecodeConstraint(str, Enum): """What the model is prevented from emitting in the first place.""" @@ -51,7 +59,17 @@ class DecodeConstraint(str, Enum): """Structured output against the schema, without a class enumeration.""" JSON_SCHEMA_ENUM = "json_schema+enum" - """Structured output with the class slot pinned to the catalogue.""" + """Structured output with the class slot pinned to the catalogue. + + Every slot is pinned independently, so nothing stops a model choosing a + class and a unit that cannot occur together.""" + + JSON_SCHEMA_UNION = "json_schema+union" + """Structured output over a discriminated union of the offered classes. + + One branch per class, so choosing the class chooses what the other slots + may hold. The difference from the enum form is the pairing, which is the + thing the enum form cannot express.""" class OutputForm(str, Enum): @@ -195,6 +213,20 @@ def describe(self) -> dict[str, object]: commit_gate=True, grounding=False, ), + "A2-enforced-only": Enforcement( + schema_in_prompt=False, + catalogue=(), + decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, + commit_gate=True, + grounding=False, + ), + "A4": Enforcement( + schema_in_prompt=True, + catalogue=(), + decode_constraint=DecodeConstraint.JSON_SCHEMA_UNION, + commit_gate=True, + grounding=False, + ), "A3": Enforcement( schema_in_prompt=True, catalogue=(), diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index ca63c13..b81073d 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -27,6 +27,7 @@ ) from oold.agent.prompts import ExtractionRequest, build_messages from oold.agent.provider import Degradation, ProviderProfile, prepare, schema_hash +from oold.agent.union import union_schema __all__ = ["ExtractionAgent", "ExtractionResult", "parse_json_answer"] @@ -159,6 +160,8 @@ def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM: prepared = self._pin_class(prepared) prepared = self._pin_units(prepared) + elif self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_UNION: + prepared = self._pin_union(prepared, request.branches) return prepared, degradation, schema_hash(prepared) def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: @@ -176,6 +179,33 @@ def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: target["enum"] = list(self.enforcement.catalogue) return schema + def _pin_union(self, schema: dict[str, Any], branches: dict[str, dict[str, Any]] | None) -> dict[str, Any]: + """Replace the entity shape with a union over the offered classes. + + Fails loudly without branches, the same way :meth:`_pin_class` does. + A union arm that quietly ran unconstrained would be reported as a + finding about unions. + """ + if not self.enforcement.catalogue: + return schema + if not branches: + raise ValueError("a union constraint needs one branch per offered class, and the request carried none") + offered = {name: branches[name] for name in self.enforcement.catalogue if name in branches} + if not offered: + raise ValueError("no offered class has a branch, so the union would admit nothing") + target = _find_entity_items(schema) + if target is None: + raise ValueError("the schema has no entity shape to turn into a union") + shared = {k: v for k, v in (target.get("properties") or {}).items() if k not in _CLASS_KEYS} + union = union_schema( + offered, + shared={k: v for k, v in shared.items() if k not in _UNIT_KEYS}, + required=tuple(target.get("required") or ()), + ) + target.clear() + target.update(union) + return schema + def _pin_units(self, schema: dict[str, Any]) -> dict[str, Any]: """Constrain the unit slot, when the corpus closes it. @@ -279,6 +309,29 @@ def _find_property(schema: Any, keys: tuple[str, ...]) -> dict[str, Any] | None: return None +def _find_entity_items(schema: Any) -> dict[str, Any] | None: + """The subschema describing one entity, which a union replaces. + + The object that carries the class slot. Replacing the array instead would + make the union say the list is one of several kinds, not that each entry + is. + """ + if isinstance(schema, dict): + properties = schema.get("properties") + if isinstance(properties, dict) and any(k in properties for k in _CLASS_KEYS): + return schema + for value in schema.values(): + found = _find_entity_items(value) + if found is not None: + return found + elif isinstance(schema, list): + for item in schema: + found = _find_entity_items(item) + if found is not None: + return found + return None + + def _find_class_property(schema: Any) -> dict[str, Any] | None: """The subschema describing an entity's class, wherever it sits.""" return _find_property(schema, _CLASS_KEYS) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index e33cc60..d465a73 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -42,6 +42,10 @@ class ExtractionRequest: schema: dict[str, Any] | None = None """The target schema. Shown only when the condition says so, and sent to the provider only when a decode-time constraint is in force.""" + branches: dict[str, dict[str, Any]] | None = None + """What each offered class narrows, for a union constraint. Supplied per + request and not per condition, because it is corpus material like the + schema beside it, and this package never learns what a corpus is.""" instruction: str | None = None """Overrides the shared task sentence. For a study this stays unset, so every arm reads the same words.""" diff --git a/src/oold/agent/provider.py b/src/oold/agent/provider.py index 5e169d7..3dfd40e 100644 --- a/src/oold/agent/provider.py +++ b/src/oold/agent/provider.py @@ -21,6 +21,8 @@ from dataclasses import dataclass, field from typing import Any +from oold.agent.union import flatten_union + __all__ = [ "PROFILES", "Degradation", @@ -306,9 +308,15 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: if isinstance(resolved, dict): _merge(node, resolved) elif branches: - resolved = walk(branches[0], seen, depth + 1) - if isinstance(resolved, dict): - _merge(node, resolved) + # Every branch, flattened into independent enums. Keeping the + # first one instead would not be a degradation: a hundred-class + # union would silently become one class, the model could only + # answer that class, and the run would read as a finding about + # the model. What is genuinely lost is the pairing, which the + # keyword counter above already records. + walked = [walk(branch, seen, depth + 1) for branch in branches] + resolved = flatten_union({combinator: [b for b in walked if isinstance(b, dict)]}) + _merge(node, resolved) if "not" in node: node.pop("not") diff --git a/src/oold/agent/union.py b/src/oold/agent/union.py new file mode 100644 index 0000000..6e8c19f --- /dev/null +++ b/src/oold/agent/union.py @@ -0,0 +1,134 @@ +"""A discriminated union over the classes an answer may take. + +An enum on the class slot and an enum on every other slot constrain them +independently, so a model can pick a class and a unit that cannot occur +together. That is the failure seen in every run of the independent-enum arm: +the class is wrong and the unit belongs to some other class entirely. + +A union says what the enum pair cannot. One branch per class, the class slot +pinned with ``const``, and every other slot carrying that class's own values. +Choosing the class then chooses the rest. + +Built with ``anyOf`` and not ``oneOf``. No provider profile accepts ``oneOf``; +the OpenAI and Google subsets accept ``anyOf``. Same meaning here, because the +``const`` discriminator already makes the branches mutually exclusive, and one +of them can actually be sent. +""" + +from __future__ import annotations + +from typing import Any + +__all__ = ["branch_for", "union_schema"] + + +def branch_for( + identifier: str, + properties: dict[str, Any], + *, + discriminator: str = "type", + required: tuple[str, ...] = (), +) -> dict[str, Any]: + """One branch: this class, and the values it admits. + + ``properties`` holds only what this class narrows. Anything the class does + not constrain is left to the shared part of the schema, so a branch stays + the size of the difference rather than a copy of the whole object. + """ + branch: dict[str, Any] = { + "type": "object", + "properties": {discriminator: {"const": identifier}, **properties}, + } + names = (discriminator, *required) + branch["required"] = list(dict.fromkeys(names)) + return branch + + +def union_schema( + branches: dict[str, dict[str, Any]], + *, + discriminator: str = "type", + required: tuple[str, ...] = (), + shared: dict[str, Any] | None = None, +) -> dict[str, Any]: + """An ``anyOf`` over the offered classes. + + ``branches`` maps a class identifier to the properties that class narrows. + ``shared`` is the part every branch has in common, merged into each one so + the union stands alone without a ``$ref``, which the strict subsets would + have to inline anyway. + + Refuses an empty union. A schema with no branch admits nothing, and a model + asked to satisfy it can only fail, which would read as a finding about the + model. + """ + if not branches: + raise ValueError("a union needs at least one branch, or nothing can satisfy it") + + common = shared or {} + built = [] + for identifier, narrowed in branches.items(): + merged = {**common, **narrowed} + built.append( + branch_for(identifier, merged, discriminator=discriminator, required=required) + ) + return {"anyOf": built} + + +def flatten_union(schema: dict[str, Any], *, discriminator: str = "type") -> dict[str, Any]: + """Collapse a union into independent enums, losing the pairing. + + What a provider that refuses ``anyOf`` can still be sent. Every branch's + discriminator value becomes one enum, every other slot's values become the + union of that slot across branches, and which value went with which class + is gone. That is a real loss and it is what the degradation measure counts. + + Used by :func:`oold.agent.provider.prepare`. Kept here beside the builder + so the two stay in step. + """ + branches = schema.get("anyOf") or schema.get("oneOf") or [] + if not branches: + return dict(schema) + + identifiers: list[str] = [] + values: dict[str, list[Any]] = {} + template: dict[str, Any] = {} + required: list[str] = [] + + for branch in branches: + if not isinstance(branch, dict): + continue + properties = branch.get("properties") or {} + for name in branch.get("required") or (): + if name not in required: + required.append(name) + for name, definition in properties.items(): + if not isinstance(definition, dict): + continue + if name == discriminator: + const = definition.get("const") + if const is not None and const not in identifiers: + identifiers.append(const) + for member in definition.get("enum") or (): + if member not in identifiers: + identifiers.append(member) + continue + template.setdefault(name, {k: v for k, v in definition.items() if k != "enum"}) + for member in definition.get("enum") or (): + bucket = values.setdefault(name, []) + if member not in bucket: + bucket.append(member) + + properties: dict[str, Any] = {} + if identifiers: + properties[discriminator] = {"type": "string", "enum": identifiers} + for name, definition in template.items(): + merged = dict(definition) + if name in values: + merged["enum"] = values[name] + properties[name] = merged + + flattened = {"type": "object", "properties": properties} + if required: + flattened["required"] = required + return flattened diff --git a/tests/test_agent/test_enforcement.py b/tests/test_agent/test_enforcement.py index e9c83dd..67dd477 100644 --- a/tests/test_agent/test_enforcement.py +++ b/tests/test_agent/test_enforcement.py @@ -25,8 +25,30 @@ def typed(**overrides) -> Enforcement: class TestArms: - def test_all_five_arms_exist(self): - assert sorted(ARMS) == ["A0-json", "A0-prose", "A1", "A2", "A3"] + def test_every_arm_exists(self): + assert sorted(ARMS) == [ + "A0-json", + "A0-prose", + "A1", + "A2", + "A2-enforced-only", + "A3", + "A4", + ] + + def test_the_union_arm_differs_from_the_enum_arm_only_in_the_constraint(self): + """Or a measured difference has two candidate causes.""" + enum_arm, union_arm = ARMS["A2"], ARMS["A4"] + assert enum_arm.schema_in_prompt == union_arm.schema_in_prompt + assert enum_arm.commit_gate == union_arm.commit_gate + assert enum_arm.grounding == union_arm.grounding + assert enum_arm.decode_constraint is not union_arm.decode_constraint + + def test_the_enforced_only_arm_differs_from_a2_only_in_what_is_shown(self): + shown, enforced = ARMS["A2"], ARMS["A2-enforced-only"] + assert shown.decode_constraint is enforced.decode_constraint + assert shown.schema_in_prompt is True + assert enforced.schema_in_prompt is False def test_a0_offers_no_schema_and_no_catalogue(self): for name in ("A0-prose", "A0-json"): @@ -80,7 +102,7 @@ def test_arm_refuses_a_catalogue_on_an_arm_that_offers_none(self): def test_unknown_arm_is_refused(self): with pytest.raises(KeyError, match="unknown arm"): - arm("A4") + arm("A9-nonesuch") class TestEnforcement: @@ -139,6 +161,7 @@ def test_orchestration_covers_single_shot_and_the_three_reference_agents(): "recursive", "segmented", "multi_step", + "select_then_fill", ] diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py index 666b7a6..f55eb57 100644 --- a/tests/test_agent/test_prompts.py +++ b/tests/test_agent/test_prompts.py @@ -57,25 +57,22 @@ def test_identifiers_are_listed_when_no_text_is_supplied(self): assert "- Mass" in section def test_rendered_entries_replace_the_bare_list(self): - enforcement = arm("A2", ("Length", "Mass")).with_catalogue_text( - ("- Length (Length)\n units: meter", "- Mass (Mass)\n units: gram") - ) + enforcement = arm("A2", ("Length", "Mass")).with_catalogue_text(( + "- Length (Length)\n units: meter", + "- Mass (Mass)\n units: gram", + )) section = catalogue_section(enforcement) assert "units: meter" in section assert "units: gram" in section def test_the_identifier_survives_in_a_rendered_entry(self): """It is still the answer, however much else is shown.""" - enforcement = arm("A2", ("Length",)).with_catalogue_text( - ("- Length (Length)\n units: meter",) - ) + enforcement = arm("A2", ("Length",)).with_catalogue_text(("- Length (Length)\n units: meter",)) assert "- Length" in catalogue_section(enforcement) def test_every_offered_class_reaches_the_prompt(self): names = tuple(f"C{i}" for i in range(40)) - enforcement = arm("A2", names).with_catalogue_text( - tuple(f"- {n} (label {n})" for n in names) - ) + enforcement = arm("A2", names).with_catalogue_text(tuple(f"- {n} (label {n})" for n in names)) section = catalogue_section(enforcement) assert all(f"- {n} (label {n})" in section for n in names) diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py new file mode 100644 index 0000000..830933a --- /dev/null +++ b/tests/test_agent/test_union.py @@ -0,0 +1,211 @@ +"""The discriminated union, and what a provider that refuses it gets instead. + +The degradation test is the important one. A union that collapses to its first +branch is not a degraded schema, it is a wrong one: a hundred-class union +becomes one class, the model can only answer that class, and the run reads as +a finding about the model. +""" + +import pytest + +from oold.agent.client import ChatResponse +from oold.agent.enforcement import arm +from oold.agent.extraction import ExtractionAgent +from oold.agent.prompts import ExtractionRequest +from oold.agent.provider import prepare, profile_for +from oold.agent.union import branch_for, flatten_union, union_schema + +BRANCHES = { + "Length": {"unit": {"type": "string", "enum": ["meter", "kilo_meter"]}}, + "Mass": {"unit": {"type": "string", "enum": ["gram", "kilo_gram"]}}, + "Volume": {"unit": {"type": "string", "enum": ["liter"]}}, +} + +SCHEMA = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "value": {"type": "number"}, + "unit": {"type": "string"}, + }, + "required": ["type", "value", "unit"], + }, + } + }, +} + + +class RecordingClient: + model = "recorder" + + def __init__(self) -> None: + self.response_format = None + + def invoke(self, messages, *, response_format=None) -> ChatResponse: + self.response_format = response_format + return ChatResponse(text='{"entities": []}', parsed=None) + + +class TestBuildingTheUnion: + def test_one_branch_per_class(self): + assert len(union_schema(BRANCHES)["anyOf"]) == 3 + + def test_each_branch_pins_its_own_class(self): + built = union_schema(BRANCHES)["anyOf"] + assert [b["properties"]["type"]["const"] for b in built] == ["Length", "Mass", "Volume"] + + def test_each_branch_carries_only_its_own_values(self): + built = union_schema(BRANCHES)["anyOf"] + assert built[0]["properties"]["unit"]["enum"] == ["meter", "kilo_meter"] + assert built[2]["properties"]["unit"]["enum"] == ["liter"] + + def test_the_discriminator_is_always_required(self): + """A branch nobody has to discriminate is a branch that matches anything.""" + assert "type" in union_schema(BRANCHES)["anyOf"][0]["required"] + + def test_shared_properties_reach_every_branch(self): + built = union_schema(BRANCHES, shared={"value": {"type": "number"}})["anyOf"] + assert all("value" in b["properties"] for b in built) + + def test_a_branch_narrowing_wins_over_the_shared_part(self): + built = union_schema(BRANCHES, shared={"unit": {"type": "string"}})["anyOf"] + assert built[0]["properties"]["unit"]["enum"] == ["meter", "kilo_meter"] + + def test_an_empty_union_is_refused(self): + """Nothing satisfies it, so a model could only fail.""" + with pytest.raises(ValueError, match="at least one branch"): + union_schema({}) + + def test_a_single_branch_is_still_a_union(self): + assert len(union_schema({"Length": BRANCHES["Length"]})["anyOf"]) == 1 + + def test_branch_for_builds_one_branch(self): + built = branch_for("Length", {"unit": {"enum": ["meter"]}}, required=("unit",)) + assert built["properties"]["type"]["const"] == "Length" + assert set(built["required"]) == {"type", "unit"} + + +class TestFlatteningTheUnion: + def test_every_class_survives(self): + """The bug this exists for: keeping branch 0 loses every other class.""" + flat = flatten_union(union_schema(BRANCHES)) + assert flat["properties"]["type"]["enum"] == ["Length", "Mass", "Volume"] + + def test_every_value_survives(self): + flat = flatten_union(union_schema(BRANCHES)) + assert flat["properties"]["unit"]["enum"] == [ + "meter", + "kilo_meter", + "gram", + "kilo_gram", + "liter", + ] + + def test_the_pairing_is_what_is_lost(self): + """Length with gram is now admissible. That is the degradation.""" + flat = flatten_union(union_schema(BRANCHES)) + assert "gram" in flat["properties"]["unit"]["enum"] + assert "anyOf" not in flat + + def test_something_that_is_not_a_union_is_left_alone(self): + assert flatten_union({"type": "object"}) == {"type": "object"} + + +class TestWhatEachProviderGets: + def test_a_provider_that_takes_anyof_keeps_the_union(self): + prepared, degradation = prepare(union_schema(BRANCHES), profile_for("openai")) + assert "anyOf" in prepared + assert len(prepared["anyOf"]) == 3 + assert degradation.dropped.get("anyOf") is None + + def test_a_provider_that_refuses_anyof_keeps_every_class(self): + prepared, _ = prepare(union_schema(BRANCHES), profile_for("anthropic")) + assert "anyOf" not in prepared + assert prepared["properties"]["type"]["enum"] == ["Length", "Mass", "Volume"] + + def test_refusing_anyof_is_recorded_as_a_loss(self): + _, degradation = prepare(union_schema(BRANCHES), profile_for("anthropic")) + assert degradation.dropped.get("anyOf") == 1 + assert degradation.fidelity < 1.0 + + def test_the_same_union_costs_more_on_one_provider_than_another(self): + """The first condition where the provider profile changes the + treatment. Cells of differing fidelity are never averaged.""" + union = union_schema(BRANCHES) + _, keeps = prepare(union, profile_for("openai")) + _, loses = prepare(union, profile_for("anthropic")) + assert loses.fidelity < keeps.fidelity + + def test_a_flat_schema_costs_no_combinator_on_any_profile(self): + """Which is why every run so far reported no combinator loss.""" + for name in ("openai", "anthropic", "google", "native"): + _, degradation = prepare(SCHEMA, profile_for(name)) + assert degradation.dropped.get("anyOf") is None + + +class TestTheUnionArm: + def sent(self, name, branches=BRANCHES, catalogue=("Length", "Mass")): + client = RecordingClient() + ExtractionAgent(client, arm(name, catalogue), profile_for("openai")).run( + ExtractionRequest(document="d", schema=SCHEMA, branches=branches) + ) + return client.response_format + + def test_a4_sends_a_union_over_the_offered_classes(self): + items = self.sent("A4")["properties"]["entities"]["items"] + assert [b["properties"]["type"]["const"] for b in items["anyOf"]] == ["Length", "Mass"] + + def test_a4_pairs_each_class_with_its_own_units(self): + items = self.sent("A4")["properties"]["entities"]["items"] + by_class = {b["properties"]["type"]["const"]: b["properties"]["unit"]["enum"] for b in items["anyOf"]} + assert by_class == {"Length": ["meter", "kilo_meter"], "Mass": ["gram", "kilo_gram"]} + + def test_a2_cannot_express_the_pairing(self): + items = self.sent("A2")["properties"]["entities"]["items"] + assert "anyOf" not in items + assert items["properties"]["type"]["enum"] == ["Length", "Mass"] + + def test_a_class_outside_the_catalogue_is_not_offered(self): + items = self.sent("A4")["properties"]["entities"]["items"] + assert "Volume" not in [b["properties"]["type"]["const"] for b in items["anyOf"]] + + def test_a_union_arm_without_branches_fails_loudly(self): + """Running unconstrained would be reported as a finding about unions.""" + with pytest.raises(ValueError, match="carried none"): + self.sent("A4", branches=None) + + def test_a_union_arm_whose_classes_have_no_branch_fails_loudly(self): + with pytest.raises(ValueError, match="admit nothing"): + self.sent("A4", catalogue=("Nonesuch",)) + + +class TestTheEnforcedOnlyArm: + def test_it_sends_the_schema_without_showing_it(self): + """The enum reaches the decoder and not the prompt, so reading it and + being constrained by it stop being the same condition.""" + client = RecordingClient() + agent = ExtractionAgent( + client, arm("A2-enforced-only", ("Length", "Mass")), profile_for("openai") + ) + from oold.agent.prompts import build_messages + + request = ExtractionRequest(document="d", schema=SCHEMA, branches=BRANCHES) + agent.run(request) + assert client.response_format is not None + messages = build_messages( + ExtractionRequest(document="d", schema=None), agent.enforcement + ) + assert "Each entity must conform" not in messages[0].content + + def test_it_still_offers_the_catalogue(self): + from oold.agent.prompts import build_messages + + content = build_messages( + ExtractionRequest(document="d"), arm("A2-enforced-only", ("Length",)) + )[0].content + assert "- Length" in content From ccbbb238c86f5f2a9812a8d705ce2b5291e3f62e Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 12:17:54 +0200 Subject: [PATCH 11/58] feat(agent): select the class, then fill what it implies - select step shortlists at most k classes per entity, cap in the schema - fill step re-reads the whole document, so step one is not a bottleneck - both calls logged by step, so the orchestration can be costed - shortlist recorded per entity, so a failure names which step lost it - the graph orchestrations now say why they are not ported --- src/oold/agent/extraction.py | 104 ++++++++++- src/oold/agent/prompts.py | 76 +++++++- src/oold/agent/union.py | 4 +- tests/test_agent/test_select_then_fill.py | 206 ++++++++++++++++++++++ tests/test_agent/test_union.py | 12 +- 5 files changed, 384 insertions(+), 18 deletions(-) create mode 100644 tests/test_agent/test_select_then_fill.py diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index b81073d..1897058 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -15,7 +15,7 @@ import json import re -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import Any from oold.agent.client import CallLog, ChatClient, TokenUsage, prompt_hash @@ -25,7 +25,12 @@ Orchestration, OutputForm, ) -from oold.agent.prompts import ExtractionRequest, build_messages +from oold.agent.prompts import ( + ExtractionRequest, + build_messages, + build_selection_messages, + selection_schema, +) from oold.agent.provider import Degradation, ProviderProfile, prepare, schema_hash from oold.agent.union import union_schema @@ -60,6 +65,12 @@ class ExtractionResult: calls: CallLog degradation: Degradation | None = None schema_sha256: str | None = None + selected: dict[str, tuple[str, ...]] = field(default_factory=dict) + """The shortlist the select step produced, per entity. + + Recorded so a two-step failure can be attributed to a step. Without it, + the true class never being offered and the fill step choosing wrongly from + a shortlist that contained it look like the same failure.""" prompt_sha256: str | None = None """Hash of the turns actually sent, folding included. Hashing the document instead would say two models got the same prompt when one of them had the @@ -77,6 +88,7 @@ def describe(self) -> dict[str, Any]: "parsed": self.parsed, "schema_sha256": self.schema_sha256, "prompt_sha256": self.prompt_sha256, + "selected": {k: list(v) for k, v in self.selected.items()}, "dropped": list(self.dropped), "degradation": self.degradation.describe() if self.degradation else None, "calls": self.calls.describe(), @@ -94,19 +106,30 @@ def __init__( orchestration: Orchestration = Orchestration.SINGLE_SHOT, *, attempts: int = 1, + shortlist_k: int = 3, ) -> None: self.client = client self.enforcement = enforcement self.profile = profile self.orchestration = orchestration self.attempts = attempts - if orchestration is not Orchestration.SINGLE_SHOT: + self.shortlist_k = shortlist_k + """How many classes the select step may keep per entity. One is the + commit case, where a wrong selection cannot be recovered.""" + if orchestration in (Orchestration.RECURSIVE, Orchestration.SEGMENTED, Orchestration.MULTI_STEP): raise NotImplementedError( - f"orchestration {orchestration.value} is not ported yet. " - f"Only {Orchestration.SINGLE_SHOT.value} runs today" + f"orchestration {orchestration.value} is not ported yet. It addresses " + f"the entity graph, which comes after class selection works" ) + if shortlist_k < 1: + raise ValueError("a shortlist of nothing leaves the second step no class to fill") def run(self, request: ExtractionRequest) -> ExtractionResult: + if self.orchestration is Orchestration.SELECT_THEN_FILL: + return self._select_then_fill(request) + return self._single_shot(request) + + def _single_shot(self, request: ExtractionRequest) -> ExtractionResult: log = CallLog() prepared, degradation, digest = self._schema_for(request) messages = build_messages( @@ -149,6 +172,65 @@ def run(self, request: ExtractionRequest) -> ExtractionResult: dropped=dropped, ) + def _select_then_fill(self, request: ExtractionRequest) -> ExtractionResult: + """Shortlist the class, then fill the schema that shortlist implies. + + The fill step is sent the whole document again, not the mention the + select step reported. A summary written by step one would be a + bottleneck the grader cannot see past: an entity lost there would look + like an extraction failure rather than a selection failure. + """ + log = CallLog() + selected, text = self._select(request, log) + + offered = tuple(dict.fromkeys(name for names in selected.values() for name in names)) + if not offered: + return ExtractionResult( + text=text, + payload=None, + calls=log, + selected=selected, + ) + + # One fill call for every entity, so the classes are pooled across + # them. With several entities that is weaker than a union per entity, + # because entity A may be answered with entity B's class. The shortlist + # dimension stays exact per entity, so the weakening is visible. + narrowed = self.enforcement.with_catalogue(offered) + filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) + result = filler._single_shot(request) + for call in result.calls: + log.append(replace(call, step="fill")) + result.calls = log + result.selected = selected + return result + + def _select(self, request: ExtractionRequest, log: CallLog) -> tuple[dict[str, tuple[str, ...]], str]: + """Ask which classes each entity could be, keeping at most k.""" + catalogue = self.enforcement.catalogue or () + if not catalogue: + raise ValueError("select-then-fill needs a catalogue to select from") + + schema = selection_schema(catalogue, self.shortlist_k) + prepared, _ = prepare(schema, self.profile, grounding=False) + messages = build_selection_messages(request, self.enforcement, self.shortlist_k) + response_format = prepared if self.enforcement.decode_constraint is not DecodeConstraint.NONE else None + + with log.timed("select", self.client.model, attempt=1, schema_sha256=schema_hash(prepared)) as sink: + reply = self.client.invoke(messages, response_format=response_format) + sink.append(reply.usage or TokenUsage()) + + payload = reply.parsed if reply.parsed is not None else parse_json_answer(reply.text) + allowed = set(catalogue) + selected: dict[str, tuple[str, ...]] = {} + for index, entity in enumerate(_entities_of(payload), start=1): + if not isinstance(entity, dict): + continue + key = str(entity.get("id") or f"e{index}") + names = [n for n in entity.get("candidates") or () if n in allowed] + selected[key] = tuple(dict.fromkeys(names))[: self.shortlist_k] + return selected, reply.text + def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None, Degradation | None, str | None]: """The schema this condition sends, and what preparing it cost.""" needs_schema = ( @@ -309,6 +391,18 @@ def _find_property(schema: Any, keys: tuple[str, ...]) -> dict[str, Any] | None: return None +def _entities_of(payload: Any) -> list[Any]: + """The entity list in an answer, whatever the model called the wrapper.""" + if isinstance(payload, list): + return payload + if isinstance(payload, dict): + for wrapper in ("entities", "instances", "items", "results"): + value = payload.get(wrapper) + if isinstance(value, list): + return value + return [] + + def _find_entity_items(schema: Any) -> dict[str, Any] | None: """The subschema describing one entity, which a union replaces. diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index d465a73..795d2e4 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -19,7 +19,7 @@ from oold.agent.client import Message from oold.agent.enforcement import Enforcement, OutputForm -__all__ = ["ExtractionRequest", "build_messages"] +__all__ = ["ExtractionRequest", "build_messages", "build_selection_messages", "selection_schema"] _TASK = "Read the document and report every entity it describes, with the values stated for each." @@ -31,6 +31,18 @@ _SCHEMA = "Each entity must conform to this schema:" +_SELECT_TASK = "Read the document and say, for every entity it describes, which classes it could be." + +_SELECT_FORM = ( + "Answer with JSON only. For each entity give a short id, the classes it could " + "belong to, most likely first, and the words in the document you read it from." +) + +_SELECT_SHORTLIST = ( + "List at most {k} classes per entity. Fewer is better when you are sure. " + "A class you leave out cannot be chosen later." +) + _GATE_HINT = "An entity whose class is not in the list will be discarded, so leave out anything you cannot place." @@ -79,3 +91,65 @@ def build_messages(request: ExtractionRequest, enforcement: Enforcement) -> list Message(role="system", content="\n\n".join(sections)), Message(role="user", content=request.document), ] + + +def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: + """The answer shape the select step asks for. + + ``candidates`` is ordered, most likely first, and capped at ``k``. The cap + is in the schema and not only in the wording, because a shortlist that can + grow to the whole catalogue is not a shortlist and the second step would + gain nothing. + """ + return { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "A short identifier for this entity, e.g. e1.", + }, + "candidates": { + "type": "array", + "maxItems": k, + "items": {"type": "string", "enum": list(catalogue)}, + "description": "Classes this entity could be, most likely first.", + }, + "mention": { + "type": "string", + "description": "The words in the document this entity was read from.", + }, + }, + "required": ["id", "candidates", "mention"], + "additionalProperties": False, + }, + } + }, + "required": ["entities"], + "additionalProperties": False, + } + + +def build_selection_messages(request: ExtractionRequest, enforcement: Enforcement, k: int) -> list[Message]: + """The messages the select step sends. + + The catalogue section and the user message are identical to the ones the + single-shot path sends, so the two orchestrations differ in what is asked + and not in what is shown. Only the task sentence and the answer form + change, because the question genuinely changed. + """ + sections: list[str] = [_SELECT_TASK, _SELECT_FORM, _SELECT_SHORTLIST.format(k=k)] + + if enforcement.catalogue: + entries = enforcement.catalogue_text or tuple(f"- {name}" for name in enforcement.catalogue) + listed = "\n".join(entries) + sections.append(f"{_CATALOGUE}\n{listed}") + + return [ + Message(role="system", content="\n\n".join(sections)), + Message(role="user", content=request.document), + ] diff --git a/src/oold/agent/union.py b/src/oold/agent/union.py index 6e8c19f..ba964fd 100644 --- a/src/oold/agent/union.py +++ b/src/oold/agent/union.py @@ -69,9 +69,7 @@ def union_schema( built = [] for identifier, narrowed in branches.items(): merged = {**common, **narrowed} - built.append( - branch_for(identifier, merged, discriminator=discriminator, required=required) - ) + built.append(branch_for(identifier, merged, discriminator=discriminator, required=required)) return {"anyOf": built} diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py new file mode 100644 index 0000000..ce2ff2f --- /dev/null +++ b/tests/test_agent/test_select_then_fill.py @@ -0,0 +1,206 @@ +"""Shortlist the class, then fill the schema that shortlist implies. + +The orchestration exists because a corpus whose subclasses add properties +cannot be covered by one flat schema: the flat form is the union of every +property any class might carry, and it admits an answer no class allows. +""" + +import json + +import pytest + +from oold.agent.client import ChatResponse +from oold.agent.enforcement import Orchestration, arm +from oold.agent.extraction import ExtractionAgent +from oold.agent.prompts import ExtractionRequest, build_selection_messages, selection_schema +from oold.agent.provider import profile_for + +CATALOGUE = ("Length", "Mass", "Volume") + +BRANCHES = { + "Length": {"unit": {"type": "string", "enum": ["meter", "kilo_meter"]}}, + "Mass": {"unit": {"type": "string", "enum": ["gram"]}}, + "Volume": {"unit": {"type": "string", "enum": ["liter"]}}, +} + +SCHEMA = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "value": {"type": "number"}, + "unit": {"type": "string"}, + }, + "required": ["type", "value", "unit"], + }, + } + }, +} + + +class TwoStepClient: + """Answers the select step, then the fill step, recording both.""" + + model = "two-step" + + def __init__(self, candidates=("Length", "Mass"), answer="Length") -> None: + self.candidates = list(candidates) + self.answer = answer + self.formats: list = [] + self.messages: list = [] + self.calls = 0 + + def invoke(self, messages, *, response_format=None) -> ChatResponse: + self.calls += 1 + self.formats.append(response_format) + self.messages.append(list(messages)) + if self.calls == 1: + payload = { + "entities": [ + {"id": "e1", "candidates": self.candidates, "mention": "1.0 meter"} + ] + } + else: + payload = {"entities": [{"type": self.answer, "value": 1.0, "unit": "meter"}]} + return ChatResponse(text=json.dumps(payload), parsed=None) + + +def agent(client, k=2, name="A4"): + return ExtractionAgent( + client, + arm(name, CATALOGUE), + profile_for("openai"), + Orchestration.SELECT_THEN_FILL, + shortlist_k=k, + ) + + +def request(): + return ExtractionRequest( + document="The reading was 1.0 meter.", schema=SCHEMA, branches=BRANCHES + ) + + +class TestTheSelectionSchema: + def test_the_shortlist_is_capped_in_the_schema(self): + """Wording alone would let it grow to the whole catalogue, and the + second step would gain nothing.""" + built = selection_schema(CATALOGUE, 2) + assert built["properties"]["entities"]["items"]["properties"]["candidates"]["maxItems"] == 2 + + def test_candidates_come_from_the_catalogue(self): + built = selection_schema(CATALOGUE, 2) + items = built["properties"]["entities"]["items"]["properties"]["candidates"]["items"] + assert items["enum"] == list(CATALOGUE) + + def test_the_mention_is_asked_for(self): + built = selection_schema(CATALOGUE, 2) + assert "mention" in built["properties"]["entities"]["items"]["properties"] + + def test_the_select_prompt_shows_the_same_catalogue(self): + """The orchestrations differ in what is asked, not in what is shown.""" + content = build_selection_messages(request(), arm("A4", CATALOGUE), 2)[0].content + assert all(f"- {name}" in content for name in CATALOGUE) + + def test_the_select_prompt_carries_the_document_alone(self): + messages = build_selection_messages(request(), arm("A4", CATALOGUE), 2) + assert messages[1].content == "The reading was 1.0 meter." + + +class TestTheTwoSteps: + def test_exactly_two_calls_are_made(self): + client = TwoStepClient() + agent(client).run(request()) + assert client.calls == 2 + + def test_both_calls_are_logged_by_step(self): + """Per-step tokens are the only way to cost the orchestration.""" + client = TwoStepClient() + result = agent(client).run(request()) + assert [c["step"] for c in result.calls.describe()["calls"]] == ["select", "fill"] + + def test_the_shortlist_is_recorded(self): + result = agent(TwoStepClient()).run(request()) + assert result.selected == {"e1": ("Length", "Mass")} + + def test_the_fill_step_is_narrowed_to_the_shortlist(self): + client = TwoStepClient() + agent(client).run(request()) + items = client.formats[1]["properties"]["entities"]["items"] + assert [b["properties"]["type"]["const"] for b in items["anyOf"]] == ["Length", "Mass"] + + def test_the_fill_step_sees_the_whole_document_again(self): + """A step-one summary would be a bottleneck the grader cannot see past.""" + client = TwoStepClient() + agent(client).run(request()) + assert client.messages[1][1].content == "The reading was 1.0 meter." + + def test_the_answer_survives(self): + result = agent(TwoStepClient()).run(request()) + assert result.payload["entities"][0]["type"] == "Length" + + +class TestTheShortlistSize: + def test_k_of_one_is_the_commit_case(self): + client = TwoStepClient(candidates=["Length"]) + result = agent(client, k=1).run(request()) + assert result.selected == {"e1": ("Length",)} + assert client.calls == 2 + + def test_more_candidates_than_k_are_trimmed(self): + """The model may ignore maxItems; the record must not.""" + client = TwoStepClient(candidates=["Length", "Mass", "Volume"]) + result = agent(client, k=2).run(request()) + assert result.selected == {"e1": ("Length", "Mass")} + + def test_a_shortlist_of_nothing_is_refused_at_construction(self): + with pytest.raises(ValueError, match="no class to fill"): + agent(TwoStepClient(), k=0) + + def test_a_candidate_outside_the_catalogue_is_dropped(self): + client = TwoStepClient(candidates=["Length", "Invented"]) + result = agent(client).run(request()) + assert result.selected == {"e1": ("Length",)} + + +class TestWhenSelectionFails: + def test_an_empty_shortlist_stops_before_the_fill_call(self): + """Spending the second call on a union of nothing would fail anyway.""" + client = TwoStepClient(candidates=[]) + result = agent(client).run(request()) + assert client.calls == 1 + assert result.payload is None + + def test_an_empty_shortlist_is_still_recorded(self): + """So the failure is attributable to the select step.""" + result = agent(TwoStepClient(candidates=[])).run(request()) + assert result.selected == {"e1": ()} + + def test_a_missing_catalogue_is_refused(self): + client = TwoStepClient() + bare = ExtractionAgent( + client, arm("A0-json"), profile_for("openai"), Orchestration.SELECT_THEN_FILL + ) + with pytest.raises(ValueError, match="needs a catalogue"): + bare.run(request()) + + +class TestTheOtherOrchestrations: + def test_single_shot_still_makes_one_call(self): + client = TwoStepClient() + ExtractionAgent(client, arm("A4", CATALOGUE), profile_for("openai")).run(request()) + assert client.calls == 1 + + @pytest.mark.parametrize( + "orchestration", + [Orchestration.RECURSIVE, Orchestration.SEGMENTED, Orchestration.MULTI_STEP], + ) + def test_the_graph_orchestrations_say_they_are_not_ported(self, orchestration): + with pytest.raises(NotImplementedError, match="entity graph"): + ExtractionAgent( + TwoStepClient(), arm("A4", CATALOGUE), profile_for("openai"), orchestration + ) diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index 830933a..d2973cc 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -189,23 +189,17 @@ def test_it_sends_the_schema_without_showing_it(self): """The enum reaches the decoder and not the prompt, so reading it and being constrained by it stop being the same condition.""" client = RecordingClient() - agent = ExtractionAgent( - client, arm("A2-enforced-only", ("Length", "Mass")), profile_for("openai") - ) + agent = ExtractionAgent(client, arm("A2-enforced-only", ("Length", "Mass")), profile_for("openai")) from oold.agent.prompts import build_messages request = ExtractionRequest(document="d", schema=SCHEMA, branches=BRANCHES) agent.run(request) assert client.response_format is not None - messages = build_messages( - ExtractionRequest(document="d", schema=None), agent.enforcement - ) + messages = build_messages(ExtractionRequest(document="d", schema=None), agent.enforcement) assert "Each entity must conform" not in messages[0].content def test_it_still_offers_the_catalogue(self): from oold.agent.prompts import build_messages - content = build_messages( - ExtractionRequest(document="d"), arm("A2-enforced-only", ("Length",)) - )[0].content + content = build_messages(ExtractionRequest(document="d"), arm("A2-enforced-only", ("Length",)))[0].content assert "- Length" in content From 6483e9ba868014474802a01c2732236e4baa9485 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 13:05:53 +0200 Subject: [PATCH 12/58] feat(agent): validate the answer, and offer it its errors back - commit_gate only matched a class name against a list, never the schema - validate_output uses oold.validation.instance_checks.validate_instance - repair_attempts bounds a repair loop; the errors go back verbatim - an unrepaired answer is kept with its errors, not quietly replaced - jsonschema joins the agent extra, since the gate now needs a validator --- pyproject.toml | 6 + src/oold/agent/enforcement.py | 22 +++ src/oold/agent/extraction.py | 57 +++++++ src/oold/agent/repair.py | 31 ++++ tests/test_agent/test_select_then_fill.py | 18 +- tests/test_agent/test_validation_gate.py | 197 ++++++++++++++++++++++ uv.lock | 4 + 7 files changed, 321 insertions(+), 14 deletions(-) create mode 100644 src/oold/agent/repair.py create mode 100644 tests/test_agent/test_validation_gate.py diff --git a/pyproject.toml b/pyproject.toml index 82e33bf..513817e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,7 +72,13 @@ mcp = [ # only, without the agent framework or any provider package. A consumer # installs the provider integration it actually uses. agent = [ + # The commit gate validates an answer against the schema the arm declared, + # so the agent needs the validator, which needs a JSON Schema implementation. + # A gate that only checked a class name against a list would be a string + # filter wearing a validator's name. + "jsonschema[format-nongpl]>=4.20", "langchain-core>=0.3", + "referencing>=0.30", ] UI-panel = [ "panel", diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index 807e58b..5eae715 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -107,6 +107,21 @@ class Enforcement: output_form: OutputForm = OutputForm.JSON + validate_output: bool = False + """Whether the answer is validated against the schema the arm declared. + + Separate from :attr:`commit_gate`, which only checks a class name against a + list. Calling that validation would be the predecessor's construct failure + one level in: a string filter reported as a conformance check. Turning this + on is what makes a commit-time arm a commit-time arm.""" + + repair_attempts: int = 0 + """How many times an invalid answer may be sent back with its errors. + + Zero validates and reports, which measures conformance. Above zero also + repairs, which measures conformance after help, and those are different + claims, so the number is part of the condition.""" + catalogue_text: tuple[str, ...] | None = None """What the catalogue looks like in the prompt, one rendered entry per class. @@ -175,6 +190,8 @@ def describe(self) -> dict[str, object]: "catalogue_offered": self.catalogue is not None, "decode_constraint": self.decode_constraint.value, "commit_gate": self.commit_gate, + "validate_output": self.validate_output, + "repair_attempts": self.repair_attempts, "grounding": self.grounding, "output_form": self.output_form.value, } @@ -204,6 +221,7 @@ def describe(self) -> dict[str, object]: catalogue=(), decode_constraint=DecodeConstraint.NONE, commit_gate=True, + validate_output=True, grounding=False, ), "A2": Enforcement( @@ -211,6 +229,7 @@ def describe(self) -> dict[str, object]: catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, commit_gate=True, + validate_output=True, grounding=False, ), "A2-enforced-only": Enforcement( @@ -218,6 +237,7 @@ def describe(self) -> dict[str, object]: catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, commit_gate=True, + validate_output=True, grounding=False, ), "A4": Enforcement( @@ -225,6 +245,7 @@ def describe(self) -> dict[str, object]: catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_UNION, commit_gate=True, + validate_output=True, grounding=False, ), "A3": Enforcement( @@ -232,6 +253,7 @@ def describe(self) -> dict[str, object]: catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, commit_gate=True, + validate_output=True, grounding=True, ), } diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 1897058..a89930d 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -78,6 +78,11 @@ class ExtractionResult: dropped: list[str] = field(default_factory=list) """Classes the commit-time gate removed, so the gate's effect is visible instead of being folded into a lower score.""" + invalid: list[str] = field(default_factory=list) + """Why the answer still fails the schema, after any repair. Empty when it + conforms and when the condition did not ask.""" + repairs: int = 0 + """How many times the answer was sent back with its errors.""" @property def parsed(self) -> bool: @@ -90,6 +95,8 @@ def describe(self) -> dict[str, Any]: "prompt_sha256": self.prompt_sha256, "selected": {k: list(v) for k, v in self.selected.items()}, "dropped": list(self.dropped), + "invalid": list(self.invalid), + "repairs": self.repairs, "degradation": self.degradation.describe() if self.degradation else None, "calls": self.calls.describe(), } @@ -162,6 +169,13 @@ def _single_shot(self, request: ExtractionRequest) -> ExtractionResult: if self.enforcement.commit_gate and payload is not None: payload, dropped = self._gate(payload) + errors: list[str] = [] + repairs = 0 + if self.enforcement.validate_output and prepared is not None: + payload, text, errors, repairs = self._validate_and_repair( + payload, text, prepared, messages, response_format, log, digest + ) + return ExtractionResult( text=text, payload=payload, @@ -170,8 +184,51 @@ def _single_shot(self, request: ExtractionRequest) -> ExtractionResult: schema_sha256=digest, prompt_sha256=digest_prompt, dropped=dropped, + invalid=errors, + repairs=repairs, ) + def _validate_and_repair( + self, + payload: Any, + text: str, + schema: dict[str, Any], + messages: list[Any], + response_format: dict[str, Any] | None, + log: CallLog, + digest: str | None, + ) -> tuple[Any, str, list[str], int]: + """Check the answer against the schema, and offer it its errors back. + + The errors are handed over verbatim from the validator. Rewriting them + into advice would make the repair rate a measure of how well the advice + was worded, which is a different study. + + A repair that does not validate is kept anyway, with its errors + recorded. Silently returning the last valid answer would report a + conformance rate the arm did not achieve. + """ + from oold.agent.repair import repair_message + from oold.validation.instance_checks import validate_instance + + errors = [] if payload is None else validate_instance(payload, schema).errors + repairs = 0 + while errors and repairs < self.enforcement.repair_attempts: + repairs += 1 + turn = [*list(messages), repair_message(text, errors)] + with log.timed("repair", self.client.model, attempt=repairs, schema_sha256=digest) as sink: + reply = self.client.invoke(turn, response_format=response_format) + sink.append(reply.usage or TokenUsage()) + text = reply.text + candidate = reply.parsed if reply.parsed is not None else parse_json_answer(text) + if candidate is None: + break + payload = candidate + if self.enforcement.commit_gate: + payload, _ = self._gate(payload) + errors = validate_instance(payload, schema).errors + return payload, text, errors, repairs + def _select_then_fill(self, request: ExtractionRequest) -> ExtractionResult: """Shortlist the class, then fill the schema that shortlist implies. diff --git a/src/oold/agent/repair.py b/src/oold/agent/repair.py new file mode 100644 index 0000000..d451ba1 --- /dev/null +++ b/src/oold/agent/repair.py @@ -0,0 +1,31 @@ +"""Handing an invalid answer back with the reasons it failed. + +The validator's own wording goes to the model unchanged. Rewriting the errors +into advice would make a repair rate a measure of how well that advice was +phrased, which is a different study from whether a schema helps. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +from oold.agent.client import Message + +__all__ = ["repair_message"] + +_REPAIR = ( + "That answer does not satisfy the schema. Correct it and answer again " + "with the corrected JSON only.\n\nWhat you sent:\n{answer}\n\nWhat failed:\n{errors}" +) + + +def repair_message(answer: str, errors: Sequence[str], limit: int = 12) -> Message: + """One user turn carrying the failed answer and the validator's reasons. + + Capped, because a wide schema can fail on every property of every entity + and a thousand near-identical lines would crowd out the answer itself. + """ + listed = "\n".join(f"- {reason}" for reason in list(errors)[:limit]) + if len(errors) > limit: + listed += f"\n- and {len(errors) - limit} more" + return Message(role="user", content=_REPAIR.format(answer=answer, errors=listed)) diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index ce2ff2f..63ab9fa 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -59,11 +59,7 @@ def invoke(self, messages, *, response_format=None) -> ChatResponse: self.formats.append(response_format) self.messages.append(list(messages)) if self.calls == 1: - payload = { - "entities": [ - {"id": "e1", "candidates": self.candidates, "mention": "1.0 meter"} - ] - } + payload = {"entities": [{"id": "e1", "candidates": self.candidates, "mention": "1.0 meter"}]} else: payload = {"entities": [{"type": self.answer, "value": 1.0, "unit": "meter"}]} return ChatResponse(text=json.dumps(payload), parsed=None) @@ -80,9 +76,7 @@ def agent(client, k=2, name="A4"): def request(): - return ExtractionRequest( - document="The reading was 1.0 meter.", schema=SCHEMA, branches=BRANCHES - ) + return ExtractionRequest(document="The reading was 1.0 meter.", schema=SCHEMA, branches=BRANCHES) class TestTheSelectionSchema: @@ -182,9 +176,7 @@ def test_an_empty_shortlist_is_still_recorded(self): def test_a_missing_catalogue_is_refused(self): client = TwoStepClient() - bare = ExtractionAgent( - client, arm("A0-json"), profile_for("openai"), Orchestration.SELECT_THEN_FILL - ) + bare = ExtractionAgent(client, arm("A0-json"), profile_for("openai"), Orchestration.SELECT_THEN_FILL) with pytest.raises(ValueError, match="needs a catalogue"): bare.run(request()) @@ -201,6 +193,4 @@ def test_single_shot_still_makes_one_call(self): ) def test_the_graph_orchestrations_say_they_are_not_ported(self, orchestration): with pytest.raises(NotImplementedError, match="entity graph"): - ExtractionAgent( - TwoStepClient(), arm("A4", CATALOGUE), profile_for("openai"), orchestration - ) + ExtractionAgent(TwoStepClient(), arm("A4", CATALOGUE), profile_for("openai"), orchestration) diff --git a/tests/test_agent/test_validation_gate.py b/tests/test_agent/test_validation_gate.py new file mode 100644 index 0000000..46f88d0 --- /dev/null +++ b/tests/test_agent/test_validation_gate.py @@ -0,0 +1,197 @@ +"""The commit gate, and the difference between filtering and validating. + +Until this existed, ``commit_gate`` checked a class name against a list and +nothing else. Reporting that as commit-time validation would be the +predecessor's construct failure one level in: an arm labelled as a conformance +check that performs a string match, so the contrast it anchors is not the +contrast its name claims. +""" + +import json +from dataclasses import replace + +import pytest + +from oold.agent.client import ChatResponse +from oold.agent.enforcement import arm +from oold.agent.extraction import ExtractionAgent +from oold.agent.prompts import ExtractionRequest +from oold.agent.provider import profile_for +from oold.agent.repair import repair_message + +SCHEMA = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "value": {"type": "number"}, + "unit": {"type": "string"}, + }, + "required": ["type", "value", "unit"], + }, + } + }, +} + +WHOLE = {"entities": [{"type": "Length", "value": 1.0, "unit": "meter"}]} +MISSING = {"entities": [{"type": "Length"}]} +WRONG_TYPE = {"entities": [{"type": "Length", "value": "one", "unit": "meter"}]} + + +class ScriptedClient: + """Answers from a list, repeating the last answer once exhausted.""" + + model = "scripted" + + def __init__(self, *answers) -> None: + self.answers = [json.dumps(a) for a in answers] + self.calls = 0 + self.turns: list[int] = [] + self.last: list = [] + + def invoke(self, messages, *, response_format=None) -> ChatResponse: + self.calls += 1 + self.turns.append(len(messages)) + self.last = list(messages) + index = min(self.calls - 1, len(self.answers) - 1) + return ChatResponse(text=self.answers[index], parsed=None) + + +def run(client, *, attempts=0, name="A1"): + base = arm(name) if name.startswith("A0") else arm(name, ("Length",)) + enforcement = replace(base, repair_attempts=attempts) + agent = ExtractionAgent(client, enforcement, profile_for("openai")) + return agent.run(ExtractionRequest(document="d", schema=SCHEMA)) + + +class TestValidatingTheAnswer: + def test_a_conforming_answer_reports_no_errors(self): + assert run(ScriptedClient(WHOLE)).invalid == [] + + def test_a_missing_required_property_is_caught(self): + """The string filter passes this: the class name is in the catalogue.""" + result = run(ScriptedClient(MISSING)) + assert result.invalid + assert any("required property" in reason for reason in result.invalid) + + def test_a_wrong_type_is_caught(self): + assert run(ScriptedClient(WRONG_TYPE)).invalid + + def test_the_invalid_answer_is_kept_not_discarded(self): + """Returning the last valid answer instead would report a conformance + rate the arm did not achieve.""" + assert run(ScriptedClient(MISSING)).payload == MISSING + + def test_an_arm_that_does_not_validate_reports_nothing(self): + result = run(ScriptedClient(MISSING), name="A0-json") + assert result.invalid == [] + + def test_the_arms_that_claim_a_commit_gate_validate(self): + for name in ("A1", "A2", "A2-enforced-only", "A3", "A4"): + assert arm(name, ("Length",)).validate_output is True + + def test_the_arms_that_claim_nothing_do_not(self): + for name in ("A0-json", "A0-prose"): + assert arm(name).validate_output is False + + +class TestRepairing: + def test_no_repair_is_attempted_by_default(self): + """Validating and repairing are different claims, so the count is part + of the condition.""" + client = ScriptedClient(MISSING, WHOLE) + result = run(client, attempts=0) + assert client.calls == 1 + assert result.repairs == 0 + + def test_one_repair_fixes_a_fixable_answer(self): + client = ScriptedClient(MISSING, WHOLE) + result = run(client, attempts=1) + assert client.calls == 2 + assert result.repairs == 1 + assert result.invalid == [] + assert result.payload == WHOLE + + def test_the_repair_call_is_logged_as_its_own_step(self): + client = ScriptedClient(MISSING, WHOLE) + result = run(client, attempts=1) + assert [c["step"] for c in result.calls.describe()["calls"]] == ["extract", "repair"] + + def test_a_conforming_answer_costs_no_repair_call(self): + client = ScriptedClient(WHOLE) + result = run(client, attempts=3) + assert client.calls == 1 + assert result.repairs == 0 + + def test_repairs_stop_at_the_declared_limit(self): + """A model that never conforms would otherwise loop on the budget.""" + client = ScriptedClient(MISSING) + result = run(client, attempts=2) + assert client.calls == 3 + assert result.repairs == 2 + assert result.invalid + + def test_a_failed_repair_is_reported_not_hidden(self): + result = run(ScriptedClient(MISSING), attempts=1) + assert result.repairs == 1 + assert result.invalid + + def test_the_repair_turn_carries_the_original_messages(self): + """So the model is not asked to repair something out of context.""" + client = ScriptedClient(MISSING, WHOLE) + run(client, attempts=1) + assert client.turns == [2, 3] + + def test_the_repair_turn_carries_the_errors(self): + client = ScriptedClient(MISSING, WHOLE) + run(client, attempts=1) + assert "required property" in client.last[-1].content + + +class TestTheRepairMessage: + def test_it_carries_the_answer_and_the_reasons(self): + message = repair_message('{"a": 1}', ["at /a: wrong"]) + assert '{"a": 1}' in message.content + assert "at /a: wrong" in message.content + + def test_it_is_a_user_turn(self): + assert repair_message("{}", ["x"]).role == "user" + + def test_a_long_error_list_is_capped(self): + """A wide schema can fail on every property of every entity, and a + thousand near-identical lines would crowd out the answer.""" + message = repair_message("{}", [f"error {i}" for i in range(50)], limit=5) + assert "and 45 more" in message.content + assert message.content.count("- error") == 5 + + +class TestWhatTheRecordSays: + def test_the_record_carries_the_errors_and_the_repair_count(self): + described = run(ScriptedClient(MISSING), attempts=0).describe() + assert described["repairs"] == 0 + assert described["invalid"] + + def test_the_condition_says_whether_it_validated(self): + described = arm("A1", ("Length",)).describe() + assert described["validate_output"] is True + assert described["repair_attempts"] == 0 + + def test_the_record_is_serialisable(self): + assert json.dumps(run(ScriptedClient(MISSING), attempts=1).describe()) + + +def test_the_gate_and_the_validator_catch_different_things(): + """The point of the whole file. A class outside the catalogue is a gate + failure; a missing required property is a validation failure; neither + catches the other.""" + gate_only = run(ScriptedClient({"entities": [{"type": "Nonesuch", "value": 1.0, "unit": "m"}]})) + assert gate_only.dropped == ["Nonesuch"] + assert gate_only.invalid == [] + + validator_only = run(ScriptedClient(MISSING)) + assert validator_only.dropped == [] + assert validator_only.invalid diff --git a/uv.lock b/uv.lock index 5f12f22..e9f0d58 100644 --- a/uv.lock +++ b/uv.lock @@ -2824,7 +2824,9 @@ dependencies = [ [package.optional-dependencies] agent = [ + { name = "jsonschema", extra = ["format-nongpl"] }, { name = "langchain-core" }, + { name = "referencing" }, ] all = [ { name = "anywidget" }, @@ -2919,6 +2921,7 @@ requires-dist = [ { name = "ipython", marker = "extra == 'ui'" }, { name = "ipython", marker = "extra == 'ui-jupyter'" }, { name = "jsondiff" }, + { name = "jsonschema", extras = ["format-nongpl"], marker = "extra == 'agent'", specifier = ">=4.20" }, { name = "jsonschema", extras = ["format-nongpl"], marker = "extra == 'all'", specifier = ">=4.20" }, { name = "jsonschema", extras = ["format-nongpl"], marker = "extra == 'mcp'", specifier = ">=4.20" }, { name = "jsonschema", extras = ["format-nongpl"], marker = "extra == 'validation'", specifier = ">=4.20" }, @@ -2942,6 +2945,7 @@ requires-dist = [ { name = "pyld" }, { name = "pyyaml" }, { name = "rdflib" }, + { name = "referencing", marker = "extra == 'agent'", specifier = ">=0.30" }, { name = "referencing", marker = "extra == 'all'", specifier = ">=0.30" }, { name = "referencing", marker = "extra == 'mcp'", specifier = ">=0.30" }, { name = "referencing", marker = "extra == 'validation'", specifier = ">=0.30" }, From f85222d00ba8dd7ee8002bacedc7314018b41666 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 13:57:59 +0200 Subject: [PATCH 13/58] fix: build the union before the provider transform, not after - an anyOf reached a profile that rejects one, unseen by prepare() - the degradation measure then reported fidelity 1.000 for every A4 cell - anthropic now flattens it and reports the loss, openai keeps it --- src/oold/agent/extraction.py | 15 +++++++-- tests/test_agent/test_union.py | 41 ++++++++++++++++++++++++ tests/test_agent/test_validation_gate.py | 2 -- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index a89930d..9ab8717 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -13,6 +13,7 @@ from __future__ import annotations +import copy import json import re from dataclasses import dataclass, field, replace @@ -295,12 +296,20 @@ def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None ) if request.schema is None or not needs_schema: return None, None, None - prepared, degradation = prepare(request.schema, self.profile, grounding=self.enforcement.grounding) + + # The union is built before the provider transform, not after. Building + # it after would send an `anyOf` to a profile that rejects one, and the + # degradation measure would report that nothing was lost because the + # transform never saw it. An enum is pinned after, because pinning adds + # values to a slot the transform has already shaped. + source = request.schema + if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_UNION: + source = self._pin_union(copy.deepcopy(source), request.branches) + + prepared, degradation = prepare(source, self.profile, grounding=self.enforcement.grounding) if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM: prepared = self._pin_class(prepared) prepared = self._pin_units(prepared) - elif self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_UNION: - prepared = self._pin_union(prepared, request.branches) return prepared, degradation, schema_hash(prepared) def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index d2973cc..3395754 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -203,3 +203,44 @@ def test_it_still_offers_the_catalogue(self): content = build_messages(ExtractionRequest(document="d"), arm("A2-enforced-only", ("Length",)))[0].content assert "- Length" in content + + +class TestTheUnionReachesTheProviderTransform: + """The union has to be built before prepare(), not after. + + Built after, an `anyOf` goes to a profile that rejects one and the + degradation measure reports that nothing was lost, because the transform + never saw it. A whole run then claims a fidelity it does not have. + """ + + def sent(self, profile): + client = RecordingClient() + agent = ExtractionAgent(client, arm("A4", ("Length", "Mass")), profile_for(profile)) + result = agent.run(ExtractionRequest(document="d", schema=SCHEMA, branches=BRANCHES)) + return client.response_format, result.degradation + + def test_a_profile_that_takes_anyof_keeps_it(self): + schema, degradation = self.sent("openai") + assert "anyOf" in schema["properties"]["entities"]["items"] + assert degradation.dropped.get("anyOf") is None + + def test_a_profile_that_refuses_anyof_never_receives_one(self): + schema, _ = self.sent("anthropic") + assert "anyOf" not in schema["properties"]["entities"]["items"] + + def test_refusing_it_is_recorded_as_a_loss(self): + """Reporting fidelity 1.000 here is the bug this test exists for.""" + _, degradation = self.sent("anthropic") + assert degradation.dropped.get("anyOf") == 1 + assert degradation.fidelity < 1.0 + + def test_every_class_survives_the_flattening(self): + schema, _ = self.sent("anthropic") + items = schema["properties"]["entities"]["items"] + assert items["properties"]["type"]["enum"] == ["Length", "Mass"] + + def test_the_two_profiles_report_different_fidelity(self): + """So the report can refuse to average them.""" + _, keeps = self.sent("openai") + _, loses = self.sent("anthropic") + assert keeps.fidelity != loses.fidelity diff --git a/tests/test_agent/test_validation_gate.py b/tests/test_agent/test_validation_gate.py index 46f88d0..d5a5d38 100644 --- a/tests/test_agent/test_validation_gate.py +++ b/tests/test_agent/test_validation_gate.py @@ -10,8 +10,6 @@ import json from dataclasses import replace -import pytest - from oold.agent.client import ChatResponse from oold.agent.enforcement import arm from oold.agent.extraction import ExtractionAgent From f40b347a4f9fbefb9b95a75bed0577bb6fbc6061 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 14:37:55 +0200 Subject: [PATCH 14/58] fix: a union shares only what no branch defines - copying every property into every branch is harmless where a class narrows one slot and ruinous where it decides which of five hundred exist - the same union came to 1.5 MB on a corpus whose flat schema is 60 kB --- src/oold/agent/extraction.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 9ab8717..92ed59a 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -344,11 +344,20 @@ def _pin_union(self, schema: dict[str, Any], branches: dict[str, dict[str, Any]] target = _find_entity_items(schema) if target is None: raise ValueError("the schema has no entity shape to turn into a union") - shared = {k: v for k, v in (target.get("properties") or {}).items() if k not in _CLASS_KEYS} + # Shared means what no branch defines. Copying every property into + # every branch is harmless where a class narrows one slot out of three + # and ruinous where it decides which of five hundred exist: the same + # union came to 1.5 MB on a corpus whose flat schema is 60 kB. + narrowed = {name for branch in offered.values() for name in branch} + shared = { + name: definition + for name, definition in (target.get("properties") or {}).items() + if name not in _CLASS_KEYS and name not in narrowed + } union = union_schema( offered, - shared={k: v for k, v in shared.items() if k not in _UNIT_KEYS}, - required=tuple(target.get("required") or ()), + shared=shared, + required=tuple(name for name in (target.get("required") or ()) if name not in narrowed), ) target.clear() target.update(union) From 3b0e9518eeb3f1db4db69a955eb96cb3a16fe2fb Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 14:41:03 +0200 Subject: [PATCH 15/58] feat(agent): shape a union like the class hierarchy - a flat union repeats every inherited property in every branch - on the schema.org pool that is 3047 slots against the 851 declared - nesting states an inherited property once and keeps what the hierarchy says - sibling properties and anyOf are conjoined, so no allOf is needed - multiple inheritance does not survive a tree; the first parent is kept --- src/oold/agent/union.py | 74 +++++++++++++++++++++++++++++- tests/test_agent/test_union.py | 82 +++++++++++++++++++++++++++++++++- 2 files changed, 154 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/union.py b/src/oold/agent/union.py index ba964fd..e08d0e1 100644 --- a/src/oold/agent/union.py +++ b/src/oold/agent/union.py @@ -19,7 +19,7 @@ from typing import Any -__all__ = ["branch_for", "union_schema"] +__all__ = ["branch_for", "flatten_union", "nested_union", "union_schema"] def branch_for( @@ -130,3 +130,75 @@ def flatten_union(schema: dict[str, Any], *, discriminator: str = "type") -> dic if required: flattened["required"] = required return flattened + + +def nested_union( + branches: dict[str, dict[str, Any]], + parents: dict[str, tuple[str, ...]], + *, + discriminator: str = "type", + shared: dict[str, Any] | None = None, +) -> dict[str, Any]: + """A union shaped like the class hierarchy instead of flattened over it. + + A flat union repeats every inherited property in every branch. Measured on + the schema.org pool that is 3,047 property slots against the 851 the + classes actually declare, a 3.6x duplication, and it throws away the one + thing the hierarchy states: that a Book is a CreativeWork, so whatever is + true of a CreativeWork is already true of it. + + Nesting says it once. Each node carries what that class declares, and its + subclasses hang beneath it as a further choice. A sibling ``properties`` + and ``anyOf`` are conjoined by JSON Schema, so this needs no ``allOf``, + which every strict provider subset rejects. + + Multiple inheritance does not survive. 48 of 906 schema.org classes name + two parents or three, and a tree can hold one, so the first is used and + the rest are lost. That loss is real and belongs in the record beside the + result, not hidden here. + """ + if not branches: + raise ValueError("a union needs at least one branch, or nothing can satisfy it") + + children: dict[str, list[str]] = {} + roots: list[str] = [] + for name in branches: + first = next((p for p in parents.get(name, ()) if p in branches), None) + if first is None: + roots.append(name) + else: + children.setdefault(first, []).append(name) + + def node(name: str) -> dict[str, Any]: + built: dict[str, Any] = { + "type": "object", + "properties": {discriminator: {"const": name}, **branches[name]}, + "required": [discriminator], + } + below = children.get(name) or [] + if not below: + return built + # This class itself, or any of its subclasses. The self branch repeats + # the discriminator only, because the properties above already apply. + built["anyOf"] = [ + {"properties": {discriminator: {"const": name}}}, + *[node(child) for child in below], + ] + built["properties"] = {k: v for k, v in built["properties"].items() if k != discriminator} + built["properties"][discriminator] = { + "enum": [name, *_descendants(name, children)], + } + return built + + top = [node(name) for name in roots] + if len(top) == 1 and not shared: + return top[0] + return {"anyOf": top, **({"properties": shared} if shared else {})} + + +def _descendants(name: str, children: dict[str, list[str]]) -> list[str]: + out: list[str] = [] + for child in children.get(name) or []: + out.append(child) + out.extend(_descendants(child, children)) + return out diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index 3395754..c9aaaa8 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -6,6 +6,8 @@ a finding about the model. """ +import json + import pytest from oold.agent.client import ChatResponse @@ -13,7 +15,7 @@ from oold.agent.extraction import ExtractionAgent from oold.agent.prompts import ExtractionRequest from oold.agent.provider import prepare, profile_for -from oold.agent.union import branch_for, flatten_union, union_schema +from oold.agent.union import branch_for, flatten_union, nested_union, union_schema BRANCHES = { "Length": {"unit": {"type": "string", "enum": ["meter", "kilo_meter"]}}, @@ -244,3 +246,81 @@ def test_the_two_profiles_report_different_fidelity(self): _, keeps = self.sent("openai") _, loses = self.sent("anthropic") assert keeps.fidelity != loses.fidelity + + +class TestTheNestedUnion: + """A union shaped like the hierarchy instead of flattened over it. + + A flat union repeats every inherited property in every branch. On the + schema.org pool that is 3,047 property slots against the 851 the classes + declare, and it discards the one thing the hierarchy states. + """ + + BRANCHES = { + "Thing": {"name": {"type": "string"}}, + "CreativeWork": {"author": {"type": "string"}}, + "Book": {"isbn": {"type": "string"}}, + "Organization": {"legalName": {"type": "string"}}, + } + PARENTS = { + "CreativeWork": ("Thing",), + "Book": ("CreativeWork",), + "Organization": ("Thing",), + } + + def built(self): + return nested_union(self.BRANCHES, self.PARENTS) + + def test_a_single_root_is_the_whole_schema(self): + assert self.built()["properties"]["type"]["enum"][0] == "Thing" + + def test_a_subclass_hangs_beneath_its_parent(self): + creative = next(b for b in self.built()["anyOf"] if b.get("properties", {}).get("type", {}).get("enum")) + assert "Book" in creative["properties"]["type"]["enum"] + + def test_an_inherited_property_is_stated_once(self): + """The saving, and the reason the hierarchy is worth keeping.""" + rendered = json.dumps(self.built()) + assert rendered.count('"name"') == 1 + + def test_every_class_is_still_reachable(self): + rendered = json.dumps(self.built()) + assert all(name in rendered for name in self.BRANCHES) + + def test_a_leaf_pins_its_own_class(self): + rendered = json.dumps(self.built()) + assert '"const": "Book"' in rendered + + def test_no_allof_is_used(self): + """Every strict provider subset rejects allOf, so nesting must not + need one. Sibling properties and anyOf are conjoined already.""" + assert "allOf" not in json.dumps(self.built()) + + def test_an_empty_union_is_refused(self): + with pytest.raises(ValueError, match="at least one branch"): + nested_union({}, {}) + + def test_a_parent_outside_the_offered_set_makes_a_root(self): + """Offering a subclass without its parent must not lose the subclass.""" + built = nested_union({"Book": {"isbn": {"type": "string"}}}, {"Book": ("CreativeWork",)}) + assert built["properties"]["type"]["const"] == "Book" + + def test_multiple_inheritance_keeps_the_first_parent(self): + """A tree holds one. 48 of 906 schema.org classes name two or three, + and that loss belongs in the record, not hidden.""" + built = nested_union( + {"Thing": {}, "Place": {}, "LocalBusiness": {"branchCode": {"type": "string"}}}, + {"Place": ("Thing",), "LocalBusiness": ("Organization", "Place")}, + ) + assert "LocalBusiness" in json.dumps(built) + + def test_a_provider_that_takes_anyof_keeps_the_nesting(self): + prepared, degradation = prepare(self.built(), profile_for("openai")) + assert "anyOf" in json.dumps(prepared) + assert degradation.dropped.get("anyOf") is None + + def test_a_provider_that_refuses_it_still_reaches_every_class(self): + prepared, _ = prepare(self.built(), profile_for("anthropic")) + rendered = json.dumps(prepared) + assert "anyOf" not in rendered + assert all(name in rendered for name in ("Book", "Organization")) From 039406e22c500fd66f3dbd281218ff20ecf60d81 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 15:14:21 +0200 Subject: [PATCH 16/58] feat(agent): hold multiple parents with allOf, not a tree - a tree holds one parent; 48 of 906 schema.org classes name two or three - LocalBusiness is an Organization and a Place, and now keeps both - allOf merges to the property union, which is what inheritance means, so a provider that rejects combinators loses nothing; anyOf flattening does - every ancestor is referenced directly, because the transform cuts a chain at the second hop and a grandparent's properties never arrive --- src/oold/agent/union.py | 132 +++++++++++++++++---------------- tests/test_agent/test_union.py | 112 ++++++++++++++-------------- 2 files changed, 124 insertions(+), 120 deletions(-) diff --git a/src/oold/agent/union.py b/src/oold/agent/union.py index e08d0e1..c7e7b97 100644 --- a/src/oold/agent/union.py +++ b/src/oold/agent/union.py @@ -17,9 +17,10 @@ from __future__ import annotations +from collections.abc import Collection from typing import Any -__all__ = ["branch_for", "flatten_union", "nested_union", "union_schema"] +__all__ = ["branch_for", "flatten_union", "hierarchy_union", "union_schema"] def branch_for( @@ -132,73 +133,80 @@ def flatten_union(schema: dict[str, Any], *, discriminator: str = "type") -> dic return flattened -def nested_union( +def hierarchy_union( branches: dict[str, dict[str, Any]], parents: dict[str, tuple[str, ...]], *, discriminator: str = "type", - shared: dict[str, Any] | None = None, + concrete: Collection[str] | None = None, ) -> dict[str, Any]: - """A union shaped like the class hierarchy instead of flattened over it. - - A flat union repeats every inherited property in every branch. Measured on - the schema.org pool that is 3,047 property slots against the 851 the - classes actually declare, a 3.6x duplication, and it throws away the one - thing the hierarchy states: that a Book is a CreativeWork, so whatever is - true of a CreativeWork is already true of it. - - Nesting says it once. Each node carries what that class declares, and its - subclasses hang beneath it as a further choice. A sibling ``properties`` - and ``anyOf`` are conjoined by JSON Schema, so this needs no ``allOf``, - which every strict provider subset rejects. - - Multiple inheritance does not survive. 48 of 906 schema.org classes name - two parents or three, and a tree can hold one, so the first is used and - the rest are lost. That loss is real and belongs in the record beside the - result, not hidden here. + """A union over classes that inherit, stated once each. + + Each class becomes a ``$defs`` entry holding what it declares and an + ``allOf`` of its parents, so a property is written where it is declared and + referenced everywhere it is inherited. The choice is a flat ``anyOf`` over + the classes an answer may take. + + This is why ``allOf`` and not a tree. A tree holds one parent, and 48 of + 906 schema.org classes name two or three: ``LocalBusiness`` is both an + ``Organization`` and a ``Place``. An ``allOf`` holds both, and it degrades + the right way. A provider that rejects combinators merges it, and merging + an intersection of objects is exactly the property union that inheritance + means, so nothing is lost. Flattening an ``anyOf`` loses the discrimination + and that is a real loss, which is the asymmetry the degradation measure + reports. + + ``concrete`` names the classes an answer may actually be. Left out, every + class is offered, which is right when the catalogue is the answer space and + wrong when the catalogue includes abstract ancestors carried only to hold + shared properties. """ if not branches: raise ValueError("a union needs at least one branch, or nothing can satisfy it") - children: dict[str, list[str]] = {} - roots: list[str] = [] - for name in branches: - first = next((p for p in parents.get(name, ()) if p in branches), None) - if first is None: - roots.append(name) - else: - children.setdefault(first, []).append(name) - - def node(name: str) -> dict[str, Any]: - built: dict[str, Any] = { - "type": "object", - "properties": {discriminator: {"const": name}, **branches[name]}, - "required": [discriminator], - } - below = children.get(name) or [] - if not below: - return built - # This class itself, or any of its subclasses. The self branch repeats - # the discriminator only, because the properties above already apply. - built["anyOf"] = [ - {"properties": {discriminator: {"const": name}}}, - *[node(child) for child in below], - ] - built["properties"] = {k: v for k, v in built["properties"].items() if k != discriminator} - built["properties"][discriminator] = { - "enum": [name, *_descendants(name, children)], - } - return built - - top = [node(name) for name in roots] - if len(top) == 1 and not shared: - return top[0] - return {"anyOf": top, **({"properties": shared} if shared else {})} - - -def _descendants(name: str, children: dict[str, list[str]]) -> list[str]: - out: list[str] = [] - for child in children.get(name) or []: - out.append(child) - out.extend(_descendants(child, children)) - return out + defs: dict[str, Any] = {} + for name, own in branches.items(): + entry: dict[str, Any] = {"type": "object", "properties": dict(own)} + # Every ancestor, not only the direct parents. A chain of references is + # the tidier schema and the transform does not survive it: inlining + # treats the second hop as recursion and cuts it, so a grandparent's + # properties never arrive. Referencing the whole ancestry keeps every + # merge one hop deep, which the transform does handle. + inherited = [a for a in _ancestry(name, parents) if a in branches] + if inherited: + entry["allOf"] = [{"$ref": f"#/$defs/{a}"} for a in inherited] + defs[name] = entry + + offered = [name for name in branches if concrete is None or name in concrete] + if not offered: + raise ValueError("no offered class is concrete, so the union would admit nothing") + + return { + "$defs": defs, + "anyOf": [ + { + "type": "object", + "properties": {discriminator: {"const": name}}, + "required": [discriminator], + "allOf": [{"$ref": f"#/$defs/{name}"}], + } + for name in offered + ], + } + + +def _ancestry(name: str, parents: dict[str, tuple[str, ...]]) -> list[str]: + """Every ancestor of a class, nearest first, each named once. + + Breadth first, so a class that inherits from two parents keeps the order + the schema declares them in and a shared grandparent appears once. + """ + seen: list[str] = [] + queue = list(parents.get(name, ())) + while queue: + current = queue.pop(0) + if current in seen or current == name: + continue + seen.append(current) + queue.extend(parents.get(current, ())) + return seen diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index c9aaaa8..806eca9 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -7,6 +7,7 @@ """ import json +from typing import ClassVar import pytest @@ -15,7 +16,7 @@ from oold.agent.extraction import ExtractionAgent from oold.agent.prompts import ExtractionRequest from oold.agent.provider import prepare, profile_for -from oold.agent.union import branch_for, flatten_union, nested_union, union_schema +from oold.agent.union import branch_for, flatten_union, hierarchy_union, union_schema BRANCHES = { "Length": {"unit": {"type": "string", "enum": ["meter", "kilo_meter"]}}, @@ -248,79 +249,74 @@ def test_the_two_profiles_report_different_fidelity(self): assert keeps.fidelity != loses.fidelity -class TestTheNestedUnion: - """A union shaped like the hierarchy instead of flattened over it. +class TestAUnionOverClassesThatInherit: + """Why allOf and not a tree. - A flat union repeats every inherited property in every branch. On the - schema.org pool that is 3,047 property slots against the 851 the classes - declare, and it discards the one thing the hierarchy states. + A tree holds one parent, and 48 of 906 schema.org classes name two or + three: LocalBusiness is both an Organization and a Place. An allOf holds + both, and it degrades the right way, because merging an intersection of + objects is exactly the property union that inheritance means. """ - BRANCHES = { + BRANCHES: ClassVar[dict] = { "Thing": {"name": {"type": "string"}}, - "CreativeWork": {"author": {"type": "string"}}, - "Book": {"isbn": {"type": "string"}}, "Organization": {"legalName": {"type": "string"}}, + "Place": {"branchCode": {"type": "string"}}, + "LocalBusiness": {"openingHours": {"type": "string"}}, + "Person": {"givenName": {"type": "string"}}, } - PARENTS = { - "CreativeWork": ("Thing",), - "Book": ("CreativeWork",), + PARENTS: ClassVar[dict] = { "Organization": ("Thing",), + "Place": ("Thing",), + "LocalBusiness": ("Organization", "Place"), + "Person": ("Thing",), } - def built(self): - return nested_union(self.BRANCHES, self.PARENTS) + def built(self, concrete=("LocalBusiness", "Person")): + return hierarchy_union(self.BRANCHES, self.PARENTS, concrete=concrete) - def test_a_single_root_is_the_whole_schema(self): - assert self.built()["properties"]["type"]["enum"][0] == "Thing" + def test_a_property_is_stated_where_it_is_declared(self): + assert json.dumps(self.built()).count('"legalName"') == 1 - def test_a_subclass_hangs_beneath_its_parent(self): - creative = next(b for b in self.built()["anyOf"] if b.get("properties", {}).get("type", {}).get("enum")) - assert "Book" in creative["properties"]["type"]["enum"] + def test_only_the_concrete_classes_are_offered(self): + """A catalogue may carry an ancestor only to hold shared properties.""" + chosen = [b["properties"]["type"]["const"] for b in self.built()["anyOf"]] + assert chosen == ["LocalBusiness", "Person"] - def test_an_inherited_property_is_stated_once(self): - """The saving, and the reason the hierarchy is worth keeping.""" - rendered = json.dumps(self.built()) - assert rendered.count('"name"') == 1 + def test_a_class_with_two_parents_references_both(self): + refs = json.dumps(self.built()["$defs"]["LocalBusiness"]) + assert "Organization" in refs + assert "Place" in refs - def test_every_class_is_still_reachable(self): - rendered = json.dumps(self.built()) - assert all(name in rendered for name in self.BRANCHES) + def test_a_grandparent_is_referenced_directly(self): + """A chain does not survive the transform: inlining treats the second + hop as recursion and cuts it, so the grandparent never arrives.""" + assert "Thing" in json.dumps(self.built()["$defs"]["LocalBusiness"]) - def test_a_leaf_pins_its_own_class(self): - rendered = json.dumps(self.built()) - assert '"const": "Book"' in rendered + def test_the_merged_form_carries_both_parents(self): + prepared, _ = prepare(self.built(), profile_for("openai")) + local = prepared["anyOf"][0]["properties"] + assert {"branchCode", "legalName", "openingHours", "name"} <= set(local) - def test_no_allof_is_used(self): - """Every strict provider subset rejects allOf, so nesting must not - need one. Sibling properties and anyOf are conjoined already.""" - assert "allOf" not in json.dumps(self.built()) + def test_the_merged_form_keeps_the_classes_apart(self): + """allOf merges, anyOf survives, so Person's property stays Person's.""" + prepared, _ = prepare(self.built(), profile_for("openai")) + assert "givenName" not in prepared["anyOf"][0]["properties"] + + def test_a_provider_that_refuses_anyof_pools_the_classes(self): + """The real loss, and the asymmetry the degradation measure reports.""" + prepared, degradation = prepare(self.built(), profile_for("anthropic")) + assert "givenName" in prepared["properties"] + assert degradation.dropped.get("anyOf") + + def test_the_compact_form_survives_a_native_consumer(self): + _, degradation = prepare(self.built(), profile_for("native")) + assert degradation.fidelity == 1.0 def test_an_empty_union_is_refused(self): with pytest.raises(ValueError, match="at least one branch"): - nested_union({}, {}) - - def test_a_parent_outside_the_offered_set_makes_a_root(self): - """Offering a subclass without its parent must not lose the subclass.""" - built = nested_union({"Book": {"isbn": {"type": "string"}}}, {"Book": ("CreativeWork",)}) - assert built["properties"]["type"]["const"] == "Book" - - def test_multiple_inheritance_keeps_the_first_parent(self): - """A tree holds one. 48 of 906 schema.org classes name two or three, - and that loss belongs in the record, not hidden.""" - built = nested_union( - {"Thing": {}, "Place": {}, "LocalBusiness": {"branchCode": {"type": "string"}}}, - {"Place": ("Thing",), "LocalBusiness": ("Organization", "Place")}, - ) - assert "LocalBusiness" in json.dumps(built) + hierarchy_union({}, {}) - def test_a_provider_that_takes_anyof_keeps_the_nesting(self): - prepared, degradation = prepare(self.built(), profile_for("openai")) - assert "anyOf" in json.dumps(prepared) - assert degradation.dropped.get("anyOf") is None - - def test_a_provider_that_refuses_it_still_reaches_every_class(self): - prepared, _ = prepare(self.built(), profile_for("anthropic")) - rendered = json.dumps(prepared) - assert "anyOf" not in rendered - assert all(name in rendered for name in ("Book", "Organization")) + def test_offering_no_concrete_class_is_refused(self): + with pytest.raises(ValueError, match="admit nothing"): + self.built(concrete=["Nonesuch"]) From 4c2d4068abf51ffaa99428a1d026cc0f20f0ae86 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 15:21:45 +0200 Subject: [PATCH 17/58] fix: cut cycles, not chains, when inlining references - the depth bound ends a cycle; it was also counting composition depth - an inheritance chain three classes long arrived without its grandparent - combinator nesting no longer advances reference depth - a chain six deep now keeps every property and reports no cut --- src/oold/agent/provider.py | 10 +++- tests/test_agent/test_provider_profile.py | 67 +++++++++++++++++++++++ 2 files changed, 74 insertions(+), 3 deletions(-) diff --git a/src/oold/agent/provider.py b/src/oold/agent/provider.py index 3dfd40e..998640a 100644 --- a/src/oold/agent/provider.py +++ b/src/oold/agent/provider.py @@ -280,7 +280,11 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: if keep_ref: node["$ref"] = ref return node - if name not in defs or too_deep or recursing: + # A cycle has to end somewhere, so it is cut. A chain of distinct + # references is finite and is not: cutting it lost real properties + # for no safety, and an inheritance chain three classes long used + # to arrive without its grandparent's properties. + if name not in defs or recursing: report.recursion_cut += 1 return { "type": "string", @@ -304,7 +308,7 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: report._note(combinator) if combinator == "allOf": for branch in branches: - resolved = walk(branch, seen, depth + 1) + resolved = walk(branch, seen, depth) if isinstance(resolved, dict): _merge(node, resolved) elif branches: @@ -314,7 +318,7 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: # answer that class, and the run would read as a finding about # the model. What is genuinely lost is the pairing, which the # keyword counter above already records. - walked = [walk(branch, seen, depth + 1) for branch in branches] + walked = [walk(branch, seen, depth) for branch in branches] resolved = flatten_union({combinator: [b for b in walked if isinstance(b, dict)]}) _merge(node, resolved) diff --git a/tests/test_agent/test_provider_profile.py b/tests/test_agent/test_provider_profile.py index 52672fd..62144a5 100644 --- a/tests/test_agent/test_provider_profile.py +++ b/tests/test_agent/test_provider_profile.py @@ -212,3 +212,70 @@ def test_an_unknown_profile_is_refused_rather_than_guessed(self): """A model name must never select a profile by substring.""" with pytest.raises(KeyError, match="unknown provider profile"): profile_for("gpt-oss-120b") + + +class TestAChainOfReferences: + """A cycle has to be cut. A chain does not, and cutting it lost data. + + The depth bound exists to end a cycle. It was also counting combinator + nesting and plain composition, so an inheritance chain three classes long + arrived without its grandparent's properties and the loss was reported as + a recursion cut. + """ + + def chain(self, length): + defs = {"C0": {"type": "object", "properties": {"p0": {"type": "string"}}}} + for i in range(1, length): + defs[f"C{i}"] = { + "type": "object", + "properties": {f"p{i}": {"type": "string"}}, + "allOf": [{"$ref": f"#/$defs/C{i - 1}"}], + } + return { + "$defs": defs, + "anyOf": [ + { + "type": "object", + "properties": {"type": {"const": f"C{length - 1}"}}, + "allOf": [{"$ref": f"#/$defs/C{length - 1}"}], + } + ], + } + + def test_a_three_deep_chain_keeps_every_property(self): + prepared, _ = prepare(self.chain(3), profile_for("openai")) + assert {"p0", "p1", "p2"} <= set(prepared["anyOf"][0]["properties"]) + + def test_a_chain_deeper_than_the_bound_keeps_every_property(self): + """Six is past max_recursion_depth, and none of it is a cycle.""" + prepared, degradation = prepare(self.chain(6), profile_for("openai")) + assert {f"p{i}" for i in range(6)} <= set(prepared["anyOf"][0]["properties"]) + assert degradation.recursion_cut == 0 + + def test_a_cycle_is_still_cut_where_it_cannot_be_expressed(self): + cycle = { + "$defs": { + "Node": { + "type": "object", + "properties": {"label": {"type": "string"}, "child": {"$ref": "#/$defs/Node"}}, + } + }, + "$ref": "#/$defs/Node", + } + prepared, degradation = prepare(cycle, profile_for("anthropic")) + assert degradation.recursion_cut == 1 + assert prepared["properties"]["child"]["type"] == "string" + + def test_a_cycle_survives_where_it_can_be_expressed(self): + cycle = { + "$defs": {"Node": {"type": "object", "properties": {"child": {"$ref": "#/$defs/Node"}}}}, + "$ref": "#/$defs/Node", + } + prepared, degradation = prepare(cycle, profile_for("openai")) + assert prepared["properties"]["child"] == {"$ref": "#/$defs/Node"} + assert degradation.recursion_cut == 0 + + def test_an_unresolvable_reference_is_still_cut(self): + prepared, degradation = prepare({"$ref": "#/$defs/Missing"}, profile_for("openai")) + assert degradation.recursion_cut == 1 + assert prepared["type"] == "string" From 90252170aa200375d325309f2ad620c1d0ce04d2 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 15:26:46 +0200 Subject: [PATCH 18/58] feat(agent): build a hierarchy union when the corpus has parents - the request carries the class hierarchy; a union then states a property where it is declared and a class with two parents keeps both - only the offered classes and their ancestors reach $defs --- src/oold/agent/extraction.py | 44 +++++++++++++++++++++++++++++------- src/oold/agent/prompts.py | 6 +++++ 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 92ed59a..e20fb50 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -33,7 +33,7 @@ selection_schema, ) from oold.agent.provider import Degradation, ProviderProfile, prepare, schema_hash -from oold.agent.union import union_schema +from oold.agent.union import hierarchy_union, union_schema __all__ = ["ExtractionAgent", "ExtractionResult", "parse_json_answer"] @@ -304,7 +304,7 @@ def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None # values to a slot the transform has already shaped. source = request.schema if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_UNION: - source = self._pin_union(copy.deepcopy(source), request.branches) + source = self._pin_union(copy.deepcopy(source), request.branches, request.parents) prepared, degradation = prepare(source, self.profile, grounding=self.enforcement.grounding) if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM: @@ -327,7 +327,12 @@ def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: target["enum"] = list(self.enforcement.catalogue) return schema - def _pin_union(self, schema: dict[str, Any], branches: dict[str, dict[str, Any]] | None) -> dict[str, Any]: + def _pin_union( + self, + schema: dict[str, Any], + branches: dict[str, dict[str, Any]] | None, + parents: dict[str, tuple[str, ...]] | None = None, + ) -> dict[str, Any]: """Replace the entity shape with a union over the offered classes. Fails loudly without branches, the same way :meth:`_pin_class` does. @@ -354,11 +359,34 @@ def _pin_union(self, schema: dict[str, Any], branches: dict[str, dict[str, Any]] for name, definition in (target.get("properties") or {}).items() if name not in _CLASS_KEYS and name not in narrowed } - union = union_schema( - offered, - shared=shared, - required=tuple(name for name in (target.get("required") or ()) if name not in narrowed), - ) + if parents: + # The offered classes and what they inherit from, and nothing else. + # A catalogue carries a branch for every class it knows, so sending + # all of them would ship the ancestry of a hundred classes to + # constrain twenty-five. The choice stays the offered classes: an + # ancestor carried only to hold shared properties is not an answer. + lineage = {name: tuple(values) for name, values in parents.items()} + needed = set(offered) + queue = list(needed) + while queue: + current = queue.pop() + for ancestor in lineage.get(current, ()): + if ancestor in branches and ancestor not in needed: + needed.add(ancestor) + queue.append(ancestor) + union = hierarchy_union( + {name: branches[name] for name in branches if name in needed}, + {name: values for name, values in lineage.items() if name in needed}, + concrete=tuple(offered), + ) + if shared: + union.setdefault("properties", {}).update(shared) + else: + union = union_schema( + offered, + shared=shared, + required=tuple(name for name in (target.get("required") or ()) if name not in narrowed), + ) target.clear() target.update(union) return schema diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 795d2e4..8427349 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -58,6 +58,12 @@ class ExtractionRequest: """What each offered class narrows, for a union constraint. Supplied per request and not per condition, because it is corpus material like the schema beside it, and this package never learns what a corpus is.""" + parents: dict[str, tuple[str, ...]] | None = None + """Which classes each class inherits from. + + Supplied when the corpus has a hierarchy worth expressing. A union then + states each property where it is declared instead of repeating every + inherited one in every branch.""" instruction: str | None = None """Overrides the shared task sentence. For a study this stays unset, so every arm reads the same words.""" From 03e1b9169a9210977f89120e6c4670ea63582f4b Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 15:50:32 +0200 Subject: [PATCH 19/58] fix: fill one call per shortlist, not one per document - pooling every entity's candidates let entity A be answered with B's class - entities that shortlisted the same classes still share a call - a split call names its entities by the words the select step read them from --- src/oold/agent/extraction.py | 72 +++++++++++++++---- tests/test_agent/test_select_then_fill.py | 85 +++++++++++++++++++++++ 2 files changed, 145 insertions(+), 12 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index e20fb50..c841b82 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -121,6 +121,9 @@ def __init__( self.profile = profile self.orchestration = orchestration self.attempts = attempts + self._mentions: dict[str, str] = {} + """What the select step read each entity from, used only to say which + entity a fill call is for when a document holds several.""" self.shortlist_k = shortlist_k """How many classes the select step may keep per entity. One is the commit case, where a wrong selection cannot be recovered.""" @@ -239,6 +242,7 @@ def _select_then_fill(self, request: ExtractionRequest) -> ExtractionResult: like an extraction failure rather than a selection failure. """ log = CallLog() + self._mentions: dict[str, str] = {} selected, text = self._select(request, log) offered = tuple(dict.fromkeys(name for names in selected.values() for name in names)) @@ -250,18 +254,59 @@ def _select_then_fill(self, request: ExtractionRequest) -> ExtractionResult: selected=selected, ) - # One fill call for every entity, so the classes are pooled across - # them. With several entities that is weaker than a union per entity, - # because entity A may be answered with entity B's class. The shortlist - # dimension stays exact per entity, so the weakening is visible. - narrowed = self.enforcement.with_catalogue(offered) - filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) - result = filler._single_shot(request) - for call in result.calls: - log.append(replace(call, step="fill")) - result.calls = log - result.selected = selected - return result + # One call per distinct shortlist, not one per document. Pooling every + # entity's candidates into one constraint lets entity A be answered + # with entity B's class, which is the thing the shortlist was for. + # Entities that shortlisted the same classes share a call, so a + # single-entity document still costs one. + groups: dict[tuple[str, ...], list[str]] = {} + for key, names in selected.items(): + if names: + groups.setdefault(tuple(names), []).append(key) + + merged: list[Any] = [] + last: ExtractionResult | None = None + for classes, keys in groups.items(): + narrowed = self.enforcement.with_catalogue(classes) + filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) + step = ExtractionRequest( + document=request.document, + schema=request.schema, + branches=request.branches, + parents=request.parents, + instruction=self._fill_instruction(request, selected, keys) if len(groups) > 1 else None, + ) + outcome = filler._single_shot(step) + for call in outcome.calls: + log.append(replace(call, step="fill")) + merged.extend(_entities_of(outcome.payload)) + last = outcome + + if last is None: + return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + last.payload = {"entities": merged} if merged else None + last.calls = log + last.selected = selected + return last + + def _fill_instruction( + self, + request: ExtractionRequest, + selected: dict[str, tuple[str, ...]], + keys: list[str], + ) -> str: + """Which entities this call is for, when a document holds several. + + Named by the words the select step read them from, because an + identifier it invented means nothing to a model reading the document + again. Omitted entirely when there is one group, so the single-entity + case sends the same prompt the single-shot arm does. + """ + mentions = [self._mentions.get(key) or key for key in keys] + listed = ", ".join(f'"{mention}"' for mention in mentions) + return ( + f"Read the document and report only the entities identified as {listed}, with the values stated for each." + ) def _select(self, request: ExtractionRequest, log: CallLog) -> tuple[dict[str, tuple[str, ...]], str]: """Ask which classes each entity could be, keeping at most k.""" @@ -287,6 +332,9 @@ def _select(self, request: ExtractionRequest, log: CallLog) -> tuple[dict[str, t key = str(entity.get("id") or f"e{index}") names = [n for n in entity.get("candidates") or () if n in allowed] selected[key] = tuple(dict.fromkeys(names))[: self.shortlist_k] + mention = entity.get("mention") + if isinstance(mention, str) and mention.strip(): + self._mentions[key] = mention.strip() return selected, reply.text def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None, Degradation | None, str | None]: diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index 63ab9fa..e0b24e1 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -194,3 +194,88 @@ def test_single_shot_still_makes_one_call(self): def test_the_graph_orchestrations_say_they_are_not_ported(self, orchestration): with pytest.raises(NotImplementedError, match="entity graph"): ExtractionAgent(TwoStepClient(), arm("A4", CATALOGUE), profile_for("openai"), orchestration) + + +class MultiEntityClient: + """Shortlists different classes for two entities, then answers.""" + + model = "multi" + + def __init__(self, first=("Length",), second=("Mass",)) -> None: + self.first = list(first) + self.second = list(second) + self.formats: list = [] + self.messages: list = [] + self.calls = 0 + + def invoke(self, messages, *, response_format=None) -> ChatResponse: + self.calls += 1 + self.formats.append(response_format) + self.messages.append(list(messages)) + if self.calls == 1: + payload = { + "entities": [ + {"id": "e1", "candidates": self.first, "mention": "1.0 meter"}, + {"id": "e2", "candidates": self.second, "mention": "2.0 gram"}, + ] + } + else: + offered = self.formats[-1]["properties"]["entities"]["items"] + names = [b["properties"]["type"]["const"] for b in offered["anyOf"]] + payload = {"entities": [{"type": names[0], "value": 1.0, "unit": "meter"}]} + return ChatResponse(text=json.dumps(payload), parsed=None) + + +class TestOneCallPerShortlist: + """Pooling every entity's candidates lets entity A be answered with + entity B's class, which is the thing the shortlist was for.""" + + def run(self, client, k=2): + return ExtractionAgent( + client, + arm("A4", CATALOGUE), + profile_for("openai"), + Orchestration.SELECT_THEN_FILL, + shortlist_k=k, + ).run(request()) + + def test_two_shortlists_get_two_fill_calls(self): + client = MultiEntityClient() + self.run(client) + assert client.calls == 3 + + def test_each_fill_call_offers_only_its_own_classes(self): + client = MultiEntityClient() + self.run(client) + offered = [ + [b["properties"]["type"]["const"] for b in fmt["properties"]["entities"]["items"]["anyOf"]] + for fmt in client.formats[1:] + ] + assert offered == [["Length"], ["Mass"]] + + def test_entities_that_shortlist_the_same_classes_share_a_call(self): + """A single-entity document still costs one fill call.""" + client = MultiEntityClient(first=("Length",), second=("Length",)) + self.run(client) + assert client.calls == 2 + + def test_a_split_call_says_which_entity_it_is_for(self): + """Named by the words the select step read it from, because an + identifier it invented means nothing to a model reading again.""" + client = MultiEntityClient() + self.run(client) + assert "1.0 meter" in client.messages[1][0].content + + def test_a_single_group_sends_the_unchanged_instruction(self): + client = MultiEntityClient(first=("Length",), second=("Length",)) + self.run(client) + assert "report only the entities" not in client.messages[1][0].content + + def test_every_answer_is_merged(self): + client = MultiEntityClient() + result = self.run(client) + assert len(result.payload["entities"]) == 2 + + def test_the_shortlist_is_still_recorded_per_entity(self): + result = self.run(MultiEntityClient()) + assert result.selected == {"e1": ("Length",), "e2": ("Mass",)} From 9aeee60fc258944d6a3fce677a5ea8c4c1ef9d1c Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 15:58:03 +0200 Subject: [PATCH 20/58] style: match the writing voice in today's docstrings - semicolons joining clauses; zero in 105k words of the reference corpus - pseudo-clefts "is what", "is how", "is where"; zero in both registers - "rather than" at 280x the corpus rate, where "instead of" or "not" fits - personified machines, British spellings, aphorism as a closing beat --- src/oold/agent/extraction.py | 2 +- src/oold/agent/prompts.py | 4 ++-- src/oold/agent/provider.py | 4 ++-- src/oold/agent/union.py | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index c841b82..d7deee8 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -2,7 +2,7 @@ The agent is one skeleton with the enforcement supplied as data. Orchestration is a separate axis, so a study can hold one fixed while varying the other, -which is the property the predecessor lacked: eight of ten differences between +the property the predecessor lacked: eight of ten differences between its two arms were orchestration, so nothing it measured could be attributed to typing. diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 8427349..bad9643 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -3,7 +3,7 @@ Every difference between arms has to live here or in the request to the provider, and nowhere else. If one arm also got a differently worded instruction, a measured difference between arms would be partly a difference -in wording, which is the confound this whole design exists to remove. +in wording, the confound this whole design exists to remove. So the instruction is one text with optional sections. The sections appear exactly when the condition says they do, and the wording of the parts that @@ -104,7 +104,7 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: ``candidates`` is ordered, most likely first, and capped at ``k``. The cap is in the schema and not only in the wording, because a shortlist that can - grow to the whole catalogue is not a shortlist and the second step would + grow to the whole catalogue does not narrow the choice and the second step would gain nothing. """ return { diff --git a/src/oold/agent/provider.py b/src/oold/agent/provider.py index 998640a..667c170 100644 --- a/src/oold/agent/provider.py +++ b/src/oold/agent/provider.py @@ -50,7 +50,7 @@ class Degradation: Reported per arm and provider. A structured-output subset that loses most of a schema is a different condition from one that loses none, and saying - so with a number is cheaper than arguing about it. + so with a number makes the two comparable. """ dropped: dict[str, int] = field(default_factory=dict) @@ -72,7 +72,7 @@ class Degradation: @property def fidelity(self) -> float: """Share of the original keywords that survived, 1.0 when none were - lost. Inlining a ``$ref`` duplicates keywords, so this can exceed 1.0; + lost. Inlining a ``$ref`` duplicates keywords, so this can exceed 1.0, and that is information preserved, not lost.""" if not self.keywords_before: return 1.0 diff --git a/src/oold/agent/union.py b/src/oold/agent/union.py index c7e7b97..4dda5a1 100644 --- a/src/oold/agent/union.py +++ b/src/oold/agent/union.py @@ -9,7 +9,7 @@ pinned with ``const``, and every other slot carrying that class's own values. Choosing the class then chooses the rest. -Built with ``anyOf`` and not ``oneOf``. No provider profile accepts ``oneOf``; +Built with ``anyOf`` and not ``oneOf``. No provider profile accepts ``oneOf``, but the OpenAI and Google subsets accept ``anyOf``. Same meaning here, because the ``const`` discriminator already makes the branches mutually exclusive, and one of them can actually be sent. @@ -80,7 +80,7 @@ def flatten_union(schema: dict[str, Any], *, discriminator: str = "type") -> dic What a provider that refuses ``anyOf`` can still be sent. Every branch's discriminator value becomes one enum, every other slot's values become the union of that slot across branches, and which value went with which class - is gone. That is a real loss and it is what the degradation measure counts. + is gone. That is a real loss and the degradation measure counts it. Used by :func:`oold.agent.provider.prepare`. Kept here beside the builder so the two stay in step. @@ -147,13 +147,13 @@ def hierarchy_union( referenced everywhere it is inherited. The choice is a flat ``anyOf`` over the classes an answer may take. - This is why ``allOf`` and not a tree. A tree holds one parent, and 48 of + ``allOf`` is used here instead of a tree. A tree holds one parent, and 48 of 906 schema.org classes name two or three: ``LocalBusiness`` is both an ``Organization`` and a ``Place``. An ``allOf`` holds both, and it degrades the right way. A provider that rejects combinators merges it, and merging an intersection of objects is exactly the property union that inheritance means, so nothing is lost. Flattening an ``anyOf`` loses the discrimination - and that is a real loss, which is the asymmetry the degradation measure + and that is a real loss, the asymmetry the degradation measure reports. ``concrete`` names the classes an answer may actually be. Left out, every From 505962bcbe753271ca200f8d6f61b9b44cd40ea0 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 16:01:38 +0200 Subject: [PATCH 21/58] fix: name the selection schema - a structured-output call names a tool after the schema title - without one the provider refuses before anything is sent - the first live select-then-fill run failed all 480 cells on this --- src/oold/agent/prompts.py | 3 +++ tests/test_agent/test_select_then_fill.py | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index bad9643..65e9393 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -108,6 +108,9 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: gain nothing. """ return { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "EntityCandidates", + "description": "Which classes each entity in the document could be.", "type": "object", "properties": { "entities": { diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index e0b24e1..c80f433 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -279,3 +279,12 @@ def test_every_answer_is_merged(self): def test_the_shortlist_is_still_recorded_per_entity(self): result = self.run(MultiEntityClient()) assert result.selected == {"e1": ("Length",), "e2": ("Mass",)} + + +def test_the_selection_schema_is_named(): + """A structured-output call names a tool after the schema title, so a + schema without one is refused before anything is sent. The first live + select-then-fill run failed every cell on it.""" + built = selection_schema(CATALOGUE, 3) + assert built.get("title") + assert built.get("description") From fb40fda604687355528785f1a2ec575e56e05145 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 27 Sep 2026 19:03:30 +0200 Subject: [PATCH 22/58] fix(agent): read the entity list under a wrapper the model named - naming the selection schema made gpt-5-nano answer {"EntityCandidates": [...]} - correct entities under a key no wrapper name held, scored zero - a lone key whose value is a list of objects is now read as the wrapper - an echoed schema still yields nothing, because it is not an answer - 3 of 16 sampled nano selections were lost this way --- src/oold/agent/extraction.py | 14 +++++++++- tests/test_agent/test_select_then_fill.py | 34 ++++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index d7deee8..37e1121 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -543,7 +543,15 @@ def _find_property(schema: Any, keys: tuple[str, ...]) -> dict[str, Any] | None: def _entities_of(payload: Any) -> list[Any]: - """The entity list in an answer, whatever the model called the wrapper.""" + """The entity list in an answer, whatever the model called the wrapper. + + The named wrappers are tried first. After them comes the case the names + cannot cover: a model that titles its answer after the schema. Naming the + selection schema ``EntityCandidates`` stopped one provider rejecting it and + started another answering ``{"EntityCandidates": [...]}``, correct entities + under a key no list could hold. So a lone key whose value is a list of + objects is read as the wrapper it plainly is. + """ if isinstance(payload, list): return payload if isinstance(payload, dict): @@ -551,6 +559,10 @@ def _entities_of(payload: Any) -> list[Any]: value = payload.get(wrapper) if isinstance(value, list): return value + if len(payload) == 1: + only = next(iter(payload.values())) + if isinstance(only, list) and all(isinstance(item, dict) for item in only): + return only return [] diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index c80f433..ca085fc 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -11,7 +11,7 @@ from oold.agent.client import ChatResponse from oold.agent.enforcement import Orchestration, arm -from oold.agent.extraction import ExtractionAgent +from oold.agent.extraction import ExtractionAgent, _entities_of from oold.agent.prompts import ExtractionRequest, build_selection_messages, selection_schema from oold.agent.provider import profile_for @@ -288,3 +288,35 @@ def test_the_selection_schema_is_named(): built = selection_schema(CATALOGUE, 3) assert built.get("title") assert built.get("description") + + +class TestTheAnswerWrapperAModelChooses: + """Where the entity list is found when the model names it something else. + + Measured on 16 gpt-5-nano selections: 3 came back as + ``{"EntityCandidates": [...]}`` with correct entities inside, and each one + scored zero because no wrapper name matched. The title was added to the + selection schema to stop LangChain rejecting it, so one fix caused the + next fault. + """ + + def test_the_declared_wrapper_is_preferred(self): + payload = {"entities": [{"id": "e1"}], "other": [{"id": "e2"}]} + assert _entities_of(payload) == [{"id": "e1"}] + + def test_a_lone_key_holding_objects_is_the_wrapper(self): + payload = {"EntityCandidates": [{"id": "e1", "candidates": ["Seat"]}]} + assert _entities_of(payload) == [{"id": "e1", "candidates": ["Seat"]}] + + def test_an_echoed_schema_is_not_an_answer(self): + """The other failure mode, and it must stay a failure. + + A model that returns the schema it was given has not answered, and + reading its ``properties`` as entities would score that as an + extraction. + """ + payload = {"type": "object", "properties": {"entities": {"type": "array"}}} + assert _entities_of(payload) == [] + + def test_a_lone_key_holding_scalars_is_not_a_wrapper(self): + assert _entities_of({"candidates": ["Seat", "Book"]}) == [] From 3cb59c1a49a7015c7d383155d8d122e29c1234d3 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 28 Sep 2026 04:01:32 +0200 Subject: [PATCH 23/58] fix(agent): write inherited properties into each union branch - a branch referencing $defs offered only the discriminator literally - llama answered {"type": X} on 99 of 99 cells and scored 0.00 - the same union inlined by the provider transform scored 0.88 - a merge is what allOf meant, and several parents merge as readily as one - a subclass narrowing an inherited property now wins over its declarer --- src/oold/agent/union.py | 53 +++++++++++++++++++++++----------- tests/test_agent/test_union.py | 42 +++++++++++++++++++-------- 2 files changed, 66 insertions(+), 29 deletions(-) diff --git a/src/oold/agent/union.py b/src/oold/agent/union.py index 4dda5a1..36bf310 100644 --- a/src/oold/agent/union.py +++ b/src/oold/agent/union.py @@ -160,41 +160,60 @@ def hierarchy_union( class is offered, which is right when the catalogue is the answer space and wrong when the catalogue includes abstract ancestors carried only to hold shared properties. + + Each branch carries its inherited properties **inline**, not as a ``$ref`` + into ``$defs``. Stating a property once and referencing it is the tidier + schema and it does not survive contact with a decoder. A branch whose only + literal property is the discriminator is satisfied by ``{"type": "X"}``, + and a model that reads the constraint rather than the intent answers + exactly that: llama returned the class and no properties on every one of + 99 cells, scoring 0.00, while the same union inlined by the provider + transform scored 0.88. The reference is correct JSON Schema and it is not + what the model is guided by. + + Inlining is what ``allOf`` meant anyway. Merging an intersection of objects + is the property union that inheritance denotes, so nothing is lost, and + several parents merge as readily as one. """ if not branches: raise ValueError("a union needs at least one branch, or nothing can satisfy it") - defs: dict[str, Any] = {} - for name, own in branches.items(): - entry: dict[str, Any] = {"type": "object", "properties": dict(own)} - # Every ancestor, not only the direct parents. A chain of references is - # the tidier schema and the transform does not survive it: inlining - # treats the second hop as recursion and cuts it, so a grandparent's - # properties never arrive. Referencing the whole ancestry keeps every - # merge one hop deep, which the transform does handle. - inherited = [a for a in _ancestry(name, parents) if a in branches] - if inherited: - entry["allOf"] = [{"$ref": f"#/$defs/{a}"} for a in inherited] - defs[name] = entry - offered = [name for name in branches if concrete is None or name in concrete] if not offered: raise ValueError("no offered class is concrete, so the union would admit nothing") return { - "$defs": defs, "anyOf": [ { "type": "object", - "properties": {discriminator: {"const": name}}, + "properties": { + **_inherited_properties(name, branches, parents), + discriminator: {"const": name}, + }, "required": [discriminator], - "allOf": [{"$ref": f"#/$defs/{name}"}], } for name in offered - ], + ] } +def _inherited_properties( + name: str, + branches: dict[str, dict[str, Any]], + parents: dict[str, tuple[str, ...]], +) -> dict[str, Any]: + """Everything a class carries, its own declarations last. + + Ancestors are walked furthest first so a class that narrows an inherited + property wins over the one that declared it. + """ + merged: dict[str, Any] = {} + for ancestor in reversed([a for a in _ancestry(name, parents) if a in branches]): + merged.update(branches[ancestor]) + merged.update(branches.get(name) or {}) + return merged + + def _ancestry(name: str, parents: dict[str, tuple[str, ...]]) -> list[str]: """Every ancestor of a class, nearest first, each named once. diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index 806eca9..86d93d7 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -250,12 +250,17 @@ def test_the_two_profiles_report_different_fidelity(self): class TestAUnionOverClassesThatInherit: - """Why allOf and not a tree. + """Why a merge and not a tree, and why inline and not a reference. A tree holds one parent, and 48 of 906 schema.org classes name two or - three: LocalBusiness is both an Organization and a Place. An allOf holds - both, and it degrades the right way, because merging an intersection of - objects is exactly the property union that inheritance means. + three: LocalBusiness is both an Organization and a Place. Merging holds + both, because a property union is what inheritance means. + + The merge is written into each branch rather than referenced from $defs. + A branch whose only literal property is the discriminator is satisfied by + {"type": "X"}, and llama answered exactly that on 99 of 99 cells for a + score of 0.00, while the same union inlined by the provider transform + scored 0.88. Correct JSON Schema is not what a decoder guides on. """ BRANCHES: ClassVar[dict] = { @@ -283,15 +288,28 @@ def test_only_the_concrete_classes_are_offered(self): chosen = [b["properties"]["type"]["const"] for b in self.built()["anyOf"]] assert chosen == ["LocalBusiness", "Person"] - def test_a_class_with_two_parents_references_both(self): - refs = json.dumps(self.built()["$defs"]["LocalBusiness"]) - assert "Organization" in refs - assert "Place" in refs + def test_a_class_with_two_parents_carries_both(self): + local = self.built()["anyOf"][0]["properties"] + assert "legalName" in local + assert "branchCode" in local - def test_a_grandparent_is_referenced_directly(self): - """A chain does not survive the transform: inlining treats the second - hop as recursion and cuts it, so the grandparent never arrives.""" - assert "Thing" in json.dumps(self.built()["$defs"]["LocalBusiness"]) + def test_a_grandparent_arrives(self): + """Two hops up, through either parent, and the property is there.""" + assert "name" in self.built()["anyOf"][0]["properties"] + + def test_no_branch_is_satisfied_by_the_discriminator_alone(self): + """The fault this shape exists to remove. + + A branch offering only {"type": const} admits an answer carrying no + extracted value at all, and a model reading the constraint rather than + the intent returns one.""" + for branch in self.built()["anyOf"]: + assert set(branch["properties"]) > {"type"} + + def test_a_subclass_narrowing_a_property_wins_over_its_parent(self): + narrowed = dict(self.BRANCHES, LocalBusiness={"legalName": {"enum": ["a"]}}) + built = hierarchy_union(narrowed, self.PARENTS, concrete=("LocalBusiness",)) + assert built["anyOf"][0]["properties"]["legalName"] == {"enum": ["a"]} def test_the_merged_form_carries_both_parents(self): prepared, _ = prepare(self.built(), profile_for("openai")) From db519db1a2c2e4939ca08ce2de79b2b29d2f0a31 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 28 Sep 2026 21:45:49 +0200 Subject: [PATCH 24/58] feat(agent): add segmented orchestration and reference pinning - plan the document in one call, then fill one call per shortlist - pin each entity's id to the plan so both steps name the same entity - pin reference slots to the ids whose class fits the property's range - leave a slot open and record it when no planned entity fits - record every edge and flag the ones whose target was never emitted --- src/oold/agent/__init__.py | 4 + src/oold/agent/enforcement.py | 9 +- src/oold/agent/extraction.py | 428 ++++++++++++++++++- src/oold/agent/prompts.py | 8 + tests/test_agent/test_extraction.py | 2 +- tests/test_agent/test_segmented.py | 481 ++++++++++++++++++++++ tests/test_agent/test_select_then_fill.py | 2 +- 7 files changed, 920 insertions(+), 14 deletions(-) create mode 100644 tests/test_agent/test_segmented.py diff --git a/src/oold/agent/__init__.py b/src/oold/agent/__init__.py index 66d36b4..1037c38 100644 --- a/src/oold/agent/__init__.py +++ b/src/oold/agent/__init__.py @@ -30,8 +30,10 @@ arm, ) from oold.agent.extraction import ( + Edge, ExtractionAgent, ExtractionResult, + PlannedEntity, parse_json_answer, ) from oold.agent.prompts import ExtractionRequest, build_messages @@ -53,6 +55,7 @@ "ChatResponse", "DecodeConstraint", "Degradation", + "Edge", "Enforcement", "ExtractionAgent", "ExtractionRequest", @@ -60,6 +63,7 @@ "Message", "Orchestration", "OutputForm", + "PlannedEntity", "ProviderProfile", "TokenUsage", "arm", diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index 5eae715..198edd1 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -35,7 +35,14 @@ class Orchestration(str, Enum): """Depth first. Resolve each entity, recursing into its linked entities.""" SEGMENTED = "segmented" - """Plan the whole entity graph in one call, then fill it.""" + """Plan the whole document in one call, then fill the plan. + + The plan gives every entity an id, a class shortlist and the words it was + read from, and the fill step is told those ids. That is what makes an edge + expressible: a link can name a target only once both ends have a name both + steps agree on. Select-then-fill shares the two calls and stops short of + this, because its unit of work is one entity's shortlist and an edge + belongs to no single entity.""" MULTI_STEP = "multi_step" """Detect, select properties, extract, construct, deduplicate.""" diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 37e1121..edcd162 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -35,7 +35,7 @@ from oold.agent.provider import Degradation, ProviderProfile, prepare, schema_hash from oold.agent.union import hierarchy_union, union_schema -__all__ = ["ExtractionAgent", "ExtractionResult", "parse_json_answer"] +__all__ = ["Edge", "ExtractionAgent", "ExtractionResult", "PlannedEntity", "parse_json_answer"] _FENCE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.MULTILINE) @@ -57,6 +57,36 @@ def parse_json_answer(text: str) -> Any | None: return None +@dataclass(frozen=True) +class PlannedEntity: + """One entity the plan step found, as the fill step is told about it.""" + + key: str + """The id both steps use for this entity. + + Invented by the model in the plan step and offered back to it in the fill + step. An id attached afterwards by position never puts the question of + whether two mentions are one entity to the model at all, which is why the + predecessor could not ask it.""" + classes: tuple[str, ...] + """The shortlist, most likely first. Empty when the plan placed the entity + in no class, which leaves it out of the fill step.""" + mention: str = "" + """The words the plan read it from, used to name it in the fill prompt.""" + + +@dataclass(frozen=True) +class Edge: + """One link an answer asserted, by the ids the plan handed out.""" + + source: str + prop: str + target: str + + def describe(self) -> dict[str, str]: + return {"source": self.source, "prop": self.prop, "target": self.target} + + @dataclass class ExtractionResult: """One answer, and everything needed to say how it was produced.""" @@ -84,6 +114,19 @@ class ExtractionResult: conforms and when the condition did not ask.""" repairs: int = 0 """How many times the answer was sent back with its errors.""" + links: list[Edge] = field(default_factory=list) + """Every edge the answer asserted between planned entities. Empty for an + orchestration that hands out no ids, where a link has nothing to name.""" + dangling: list[Edge] = field(default_factory=list) + """The links whose target was never emitted. + + A subset of :attr:`links` and not a removal. The edge stays in the payload, + because an answer pointing at an entity it failed to report is a different + failure from an answer reporting no edge, and dropping it would make the + two the same number.""" + unpinned: list[str] = field(default_factory=list) + """Reference properties left open because no planned entity fits their + range. Those slots ran unconstrained, and the record says which.""" @property def parsed(self) -> bool: @@ -98,6 +141,9 @@ def describe(self) -> dict[str, Any]: "dropped": list(self.dropped), "invalid": list(self.invalid), "repairs": self.repairs, + "links": [edge.describe() for edge in self.links], + "dangling": [edge.describe() for edge in self.dangling], + "unpinned": list(self.unpinned), "degradation": self.degradation.describe() if self.degradation else None, "calls": self.calls.describe(), } @@ -127,7 +173,7 @@ def __init__( self.shortlist_k = shortlist_k """How many classes the select step may keep per entity. One is the commit case, where a wrong selection cannot be recovered.""" - if orchestration in (Orchestration.RECURSIVE, Orchestration.SEGMENTED, Orchestration.MULTI_STEP): + if orchestration in (Orchestration.RECURSIVE, Orchestration.MULTI_STEP): raise NotImplementedError( f"orchestration {orchestration.value} is not ported yet. It addresses " f"the entity graph, which comes after class selection works" @@ -136,13 +182,21 @@ def __init__( raise ValueError("a shortlist of nothing leaves the second step no class to fill") def run(self, request: ExtractionRequest) -> ExtractionResult: + if self.orchestration is Orchestration.SEGMENTED: + return self._segmented(request) if self.orchestration is Orchestration.SELECT_THEN_FILL: return self._select_then_fill(request) return self._single_shot(request) - def _single_shot(self, request: ExtractionRequest) -> ExtractionResult: + def _single_shot( + self, + request: ExtractionRequest, + *, + plan: tuple[PlannedEntity, ...] = (), + filling: tuple[str, ...] = (), + ) -> ExtractionResult: log = CallLog() - prepared, degradation, digest = self._schema_for(request) + prepared, degradation, digest, unpinned = self._schema_for(request, plan, filling) messages = build_messages( ExtractionRequest( document=request.document, @@ -190,6 +244,7 @@ def _single_shot(self, request: ExtractionRequest) -> ExtractionResult: dropped=dropped, invalid=errors, repairs=repairs, + unpinned=unpinned, ) def _validate_and_repair( @@ -308,18 +363,127 @@ def _fill_instruction( f"Read the document and report only the entities identified as {listed}, with the values stated for each." ) - def _select(self, request: ExtractionRequest, log: CallLog) -> tuple[dict[str, tuple[str, ...]], str]: - """Ask which classes each entity could be, keeping at most k.""" + def _segmented(self, request: ExtractionRequest) -> ExtractionResult: + """Plan the whole document, then fill the plan. + + The plan is the unit of work, which is the difference from + select-then-fill. Grouping by shortlist is enough while every answer is + one entity's own values, and an edge is nobody's own value: the call + holding a link has to know that the entity at the other end exists and + what it is called, even when another call is filling it. + + The document is sent again in full, for the reason it is under + select-then-fill: a summary written by step one would be a bottleneck + the grader cannot see past, and an entity lost there would read as an + extraction failure. What step two gains over that arm is the ids, so a + link has a name to point at. + """ + log = CallLog() + self._mentions = {} + selected, text = self._select(request, log, step="plan") + plan = tuple( + PlannedEntity(key=key, classes=classes, mention=self._mentions.get(key, "")) + for key, classes in selected.items() + ) + + # One call per distinct shortlist, as select-then-fill does, and for the + # same reason: pooling the candidates lets one entity be answered with + # another's class. + groups: dict[tuple[str, ...], list[str]] = {} + for entity in plan: + if entity.classes: + groups.setdefault(entity.classes, []).append(entity.key) + if not groups: + return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + + merged: list[Any] = [] + unpinned: list[str] = [] + last: ExtractionResult | None = None + for classes, keys in groups.items(): + narrowed = self.enforcement.with_catalogue(classes) + filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) + step = ExtractionRequest( + document=request.document, + schema=request.schema, + branches=request.branches, + parents=request.parents, + ranges=request.ranges, + instruction=self._plan_instruction(request, plan, keys), + ) + outcome = filler._single_shot(step, plan=plan, filling=tuple(keys)) + for call in outcome.calls: + log.append(replace(call, step="fill")) + merged.extend(_entities_of(outcome.payload)) + unpinned.extend(name for name in outcome.unpinned if name not in unpinned) + last = outcome + + if last is None: + return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + links, dangling = _edges_of(merged, request.ranges) + last.payload = {"entities": merged} if merged else None + last.calls = log + last.selected = selected + last.links = links + last.dangling = dangling + last.unpinned = unpinned + return last + + def _plan_instruction( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + keys: list[str], + ) -> str: + """Which planned entities this call reports, and under which ids. + + The ids are stated even when one call covers the whole plan, which is + where this parts company with :meth:`_fill_instruction`. There an id is + an internal label and naming it would only add words. Here it is the + answer's own key and the thing a link points at. + + Entities another call is filling are named too, as targets and not as + work. Without them, a document whose source and target shortlisted + different classes could never state the edge between them, because the + call holding the source would not know the target had a name. + """ + wanted = set(keys) + listed = "; ".join(_named(entity) for entity in plan if entity.key in wanted) + sections = [ + f"Read the document and report these entities, each under the id given here: {listed}.", + "Give that id as the value of the id property.", + ] + others = [entity for entity in plan if entity.key not in wanted] + if others: + sections.append("The document also describes " + "; ".join(_named(entity) for entity in others) + ".") + if request.ranges: + sections.append( + "Where a property of an entity points at another of these entities, give that entity's id as the value." + ) + return " ".join(sections) + + def _select( + self, + request: ExtractionRequest, + log: CallLog, + *, + step: str = "select", + ) -> tuple[dict[str, tuple[str, ...]], str]: + """Ask which classes each entity could be, keeping at most k. + + ``step`` names the call in the log. Two orchestrations ask this same + question and spend different amounts on what follows, so their first + calls are attributed apart rather than pooled under one name. + """ catalogue = self.enforcement.catalogue or () if not catalogue: - raise ValueError("select-then-fill needs a catalogue to select from") + raise ValueError(f"{self.orchestration.value} needs a catalogue to select from") schema = selection_schema(catalogue, self.shortlist_k) prepared, _ = prepare(schema, self.profile, grounding=False) messages = build_selection_messages(request, self.enforcement, self.shortlist_k) response_format = prepared if self.enforcement.decode_constraint is not DecodeConstraint.NONE else None - with log.timed("select", self.client.model, attempt=1, schema_sha256=schema_hash(prepared)) as sink: + with log.timed(step, self.client.model, attempt=1, schema_sha256=schema_hash(prepared)) as sink: reply = self.client.invoke(messages, response_format=response_format) sink.append(reply.usage or TokenUsage()) @@ -337,13 +501,18 @@ def _select(self, request: ExtractionRequest, log: CallLog) -> tuple[dict[str, t self._mentions[key] = mention.strip() return selected, reply.text - def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None, Degradation | None, str | None]: + def _schema_for( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...] = (), + filling: tuple[str, ...] = (), + ) -> tuple[dict[str, Any] | None, Degradation | None, str | None, list[str]]: """The schema this condition sends, and what preparing it cost.""" needs_schema = ( self.enforcement.schema_in_prompt or self.enforcement.decode_constraint is not DecodeConstraint.NONE ) if request.schema is None or not needs_schema: - return None, None, None + return None, None, None, [] # The union is built before the provider transform, not after. Building # it after would send an `anyOf` to a profile that rejects one, and the @@ -358,7 +527,19 @@ def _schema_for(self, request: ExtractionRequest) -> tuple[dict[str, Any] | None if self.enforcement.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM: prepared = self._pin_class(prepared) prepared = self._pin_units(prepared) - return prepared, degradation, schema_hash(prepared) + + unpinned: list[str] = [] + if plan: + # The id slot goes in whatever the decode constraint is, because it + # belongs to the orchestration and not to the enforcement: an answer + # stating no id cannot be joined back to the plan, and an arm that + # only shows its schema still has to ask for one. The reference + # enums go in where the decoder is engaged and nowhere else, so the + # decode axis keeps meaning what it means everywhere else. + prepared = self._pin_identity(prepared, filling) + if self.enforcement.decode_constraint is not DecodeConstraint.NONE: + prepared, unpinned = self._pin_references(prepared, plan, request.ranges, request.parents) + return prepared, degradation, schema_hash(prepared), unpinned def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: """Constrain the class slot to the catalogue at decode time. @@ -459,6 +640,100 @@ class and leaving the unit a free string enforces half of what the target["enum"] = list(self.enforcement.unit_catalogue) return schema + def _pin_identity(self, schema: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]: + """Give the answer a slot for the id the plan assigned. + + Pinned to the ids this call is for, so one call cannot answer with an + entity another call is responsible for and have it counted twice. An id + the model states, rather than one attached afterwards by position, is + also the only form in which the question of whether two mentions are + one entity is ever put to the model. + + Fails loudly when there is no entity shape to carry it, the way + :meth:`_pin_class` does. A plan that cannot be joined to the answer + would report every edge as dangling and read as a finding about links. + """ + shapes = _entity_shapes(schema) + if not shapes: + raise ValueError("the schema has no entity shape to carry an id, so the plan cannot reach the answer") + for shape in shapes: + properties = shape.setdefault("properties", {}) + name = next((key for key in _ID_KEYS if key in properties), _ID_KEYS[0]) + slot = dict(properties.get(name) or {}) + slot["type"] = "string" + slot.setdefault("description", "The id this entity was planned under.") + if keys: + slot["enum"] = list(keys) + properties[name] = slot + required = shape.setdefault("required", []) + if name not in required: + required.append(name) + return schema + + def _pin_references( + self, + schema: dict[str, Any], + plan: tuple[PlannedEntity, ...], + ranges: dict[str, tuple[str, ...]] | None, + parents: dict[str, tuple[str, ...]] | None = None, + ) -> tuple[dict[str, Any], list[str]]: + """Constrain each reference slot to the entities that could fill it. + + A link left as a free string admits a target that is not on the page, + which costs an invented entity on top of the wrong edge. The candidates + are the planned entities whose shortlist holds the property's range or + a class descended from it, so an edge can only reach something the plan + found. + + A property whose range no planned entity fits is left as the schema + declares it and named in the return. An empty ``enum`` is not a tighter + constraint but an unsatisfiable one: the strict subsets reject it + outright, and one that accepted it would leave a required slot with no + legal value, so a document whose target went undetected would fail on + the schema instead of on the edge. Left open, the failure stays where it + happened, and the name makes it countable. + + A property the prepared schema does not carry is passed over. The + answer surface can lose one legitimately, by a catalogue trim upstream + or by a provider's optional-property limit, and a slot that is not + offered is not a slot left open. + """ + if not ranges: + return schema, [] + shapes = _entity_shapes(schema) + if not shapes: + raise ValueError("the schema has no entity shape to pin a reference in") + + lineage = {name: tuple(values) for name, values in (parents or {}).items()} + unpinned: list[str] = [] + for name, admitted in ranges.items(): + carrying = [shape for shape in shapes if name in (shape.get("properties") or {})] + if not carrying: + continue + targets = _compatible_ids(plan, admitted, lineage) + if not targets: + unpinned.append(name) + continue + for shape in carrying: + properties = shape["properties"] + declared = properties[name] + # Null is how a model declines a property under a subset that + # makes every property required. A pinned slot that dropped it + # would force an edge out of every entity that has the slot. + values: list[Any] = list(targets) + if _accepts_null(declared): + values.append(None) + kind: Any = ["string", "null"] + else: + kind = "string" + described = declared.get("description") if isinstance(declared, dict) else None + properties[name] = { + "type": kind, + "enum": values, + "description": described or f"The id of the entity {name} points at.", + } + return schema, unpinned + def _gate(self, payload: Any) -> tuple[Any, list[str]]: """Drop entities whose class is not in the catalogue. @@ -499,6 +774,137 @@ def keep(entity: Any) -> bool: _UNIT_KEYS = ("unit", "units", "unit_symbol", "uom") +_ID_KEYS = ("id", "@id", "entity_id", "key") + + +def _named(entity: PlannedEntity) -> str: + """One planned entity as the fill prompt names it.""" + return f'{entity.key} ("{entity.mention}")' if entity.mention else entity.key + + +def _is_entity_shape(node: Any) -> bool: + """Whether this object describes one entity rather than the answer.""" + if not isinstance(node, dict): + return False + properties = node.get("properties") + return isinstance(properties, dict) and any(key in properties for key in _CLASS_KEYS) + + +def _entity_shapes(schema: Any) -> list[dict[str, Any]]: + """Every object an entity may take, one per union branch. + + A union is recognised before the objects inside it, so pinning reaches all + of its branches. Pinning the first branch alone would constrain one class + and leave the others open, which reads as a finding about that class. + """ + found: list[dict[str, Any]] = [] + + def visit(node: Any) -> None: + if isinstance(node, list): + for item in node: + visit(item) + return + if not isinstance(node, dict): + return + for combinator in ("anyOf", "oneOf"): + branches = node.get(combinator) + if isinstance(branches, list) and any(_is_entity_shape(branch) for branch in branches): + found.extend(branch for branch in branches if _is_entity_shape(branch)) + return + if _is_entity_shape(node): + found.append(node) + return + for value in node.values(): + visit(value) + + visit(schema) + return found + + +def _accepts_null(slot: Any) -> bool: + """Whether a prepared slot was left able to say nothing.""" + if not isinstance(slot, dict): + return False + declared = slot.get("type") + return "null" in (declared if isinstance(declared, list) else [declared]) + + +def _entity_id(entity: Any) -> str | None: + """The id an answered entity states, whatever key it put it under.""" + if not isinstance(entity, dict): + return None + for key in _ID_KEYS: + value = entity.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return None + + +def _descends(name: str, admitted: set[str], lineage: dict[str, tuple[str, ...]]) -> bool: + """Whether a class is one of these or inherits from one.""" + seen: set[str] = set() + queue = [name] + while queue: + current = queue.pop() + if current in admitted: + return True + if current in seen: + continue + seen.add(current) + queue.extend(lineage.get(current, ())) + return False + + +def _compatible_ids( + plan: tuple[PlannedEntity, ...], + ranges: tuple[str, ...], + lineage: dict[str, tuple[str, ...]], +) -> tuple[str, ...]: + """The planned entities a property with this range may point at. + + A shortlist counts when any class on it fits, because the fill step has + not committed to one yet and offering only the first would rule out a + target the second call may well answer with. + """ + admitted = set(ranges) + return tuple( + dict.fromkeys( + entity.key for entity in plan if any(_descends(name, admitted, lineage) for name in entity.classes) + ) + ) + + +def _edges_of( + entities: list[Any], + ranges: dict[str, tuple[str, ...]] | None, +) -> tuple[list[Edge], list[Edge]]: + """Every edge the answer asserted, and the ones reaching nothing. + + Read from the entities that state an id. One that states none is not in + the plan and its links have no source to hang from; the id slot is + required and enumerated, so an answer without one is a decode failure + already and is reported as that rather than twice. + """ + if not ranges: + return [], [] + emitted = {found for entity in entities if (found := _entity_id(entity)) is not None} + links: list[Edge] = [] + dangling: list[Edge] = [] + for entity in entities: + source = _entity_id(entity) + if source is None: + continue + for name in ranges: + value = entity.get(name) + for item in value if isinstance(value, list) else [value]: + if not isinstance(item, str) or not item.strip(): + continue + edge = Edge(source=source, prop=name, target=item.strip()) + links.append(edge) + if edge.target not in emitted: + dangling.append(edge) + return links, dangling + def _class_of(entity: dict[str, Any]) -> str | None: for key in _CLASS_KEYS: diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 65e9393..b31af71 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -64,6 +64,14 @@ class ExtractionRequest: Supplied when the corpus has a hierarchy worth expressing. A union then states each property where it is declared instead of repeating every inherited one in every branch.""" + ranges: dict[str, tuple[str, ...]] | None = None + """Which classes each node-valued property may point at. + + Supplied per request beside ``branches`` and ``parents``, and for the same + reason: it is corpus material, and this package never learns what a corpus + is. Keyed by property name alone. A reference slot is constrained by the + classes the plan found on the page, not by the class that declares the + property, so the declaring class adds nothing a second key could use.""" instruction: str | None = None """Overrides the shared task sentence. For a study this stays unset, so every arm reads the same words.""" diff --git a/tests/test_agent/test_extraction.py b/tests/test_agent/test_extraction.py index 3623540..c22747f 100644 --- a/tests/test_agent/test_extraction.py +++ b/tests/test_agent/test_extraction.py @@ -225,7 +225,7 @@ def test_single_shot_makes_one_call(self): @pytest.mark.parametrize( "orchestration", - [Orchestration.RECURSIVE, Orchestration.SEGMENTED, Orchestration.MULTI_STEP], + [Orchestration.RECURSIVE, Orchestration.MULTI_STEP], ) def test_an_unported_orchestration_refuses_rather_than_pretending(self, orchestration): with pytest.raises(NotImplementedError, match="not ported yet"): diff --git a/tests/test_agent/test_segmented.py b/tests/test_agent/test_segmented.py new file mode 100644 index 0000000..faa061d --- /dev/null +++ b/tests/test_agent/test_segmented.py @@ -0,0 +1,481 @@ +"""Plan the whole document, then fill the plan. + +The orchestration exists because an edge belongs to no single entity. Every +arm before it answers one entity's own values, so the call that holds a link +never learns that the entity at the other end has a name, and the link can +only be written as prose or dropped. Planning first gives both ends a name +both steps agree on, and pinning the reference slot to those names is the only +place anywhere that a link is constrained to a real target. +""" + +import json + +import pytest + +from oold.agent.client import ChatResponse, TokenUsage +from oold.agent.enforcement import Orchestration, arm +from oold.agent.extraction import Edge, ExtractionAgent, PlannedEntity +from oold.agent.prompts import ExtractionRequest +from oold.agent.provider import profile_for + +CATALOGUE = ("Person", "Organization", "LocalBusiness", "Book") + +BRANCHES = { + "Thing": {"name": {"type": "string"}}, + "Person": {"jobTitle": {"type": "string"}, "worksFor": {"type": "object"}}, + "Organization": {"legalName": {"type": "string"}}, + "LocalBusiness": {"openingHours": {"type": "string"}}, + "Book": {"isbn": {"type": "string"}, "author": {"type": "object"}}, +} + +PARENTS = { + "Person": ("Thing",), + "Organization": ("Thing",), + "LocalBusiness": ("Organization",), + "Book": ("Thing",), +} + +RANGES = {"worksFor": ("Organization",), "author": ("Person",)} + +SCHEMA = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Entities", + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "name": {"type": "string"}, + "jobTitle": {"type": "string"}, + "legalName": {"type": "string"}, + "openingHours": {"type": "string"}, + "isbn": {"type": "string"}, + "worksFor": {"type": "object"}, + "author": {"type": "object"}, + }, + "required": ["type"], + }, + } + }, + "required": ["entities"], +} + +DOCUMENT = "Ada works for Acme. Acme is a company. The Ada Book was written by Ada." + +PLAN = [ + {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Organization"], "mention": "Acme"}, +] + +LINKED = [ + [{"id": "e1", "type": "Person", "name": "Ada", "worksFor": "e2"}], + [{"id": "e2", "type": "Organization", "name": "Acme"}], +] + +UNION_PLAN = [ + {"id": "e1", "candidates": ["Person", "Book"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Organization", "LocalBusiness"], "mention": "Acme"}, +] +"""Two classes per entity, so every fill call is sent a union of two branches +and a profile that refuses ``anyOf`` has something to lose. A shortlist of one +flattens to a wider object than it came from, and the loss that matters is +invisible in the keyword count.""" + + +class PlanThenFillClient: + """Answers the plan step, then one fill step per shortlist.""" + + model = "planner" + + def __init__(self, plan=None, answers=None) -> None: + self.plan = list(PLAN if plan is None else plan) + self.answers = [list(group) for group in (LINKED if answers is None else answers)] + self.formats: list = [] + self.messages: list = [] + self.calls = 0 + + def invoke(self, messages, *, response_format=None) -> ChatResponse: + self.calls += 1 + self.formats.append(response_format) + self.messages.append(list(messages)) + if self.calls == 1: + payload = {"entities": self.plan} + else: + payload = {"entities": self.answers.pop(0) if self.answers else []} + return ChatResponse( + text=json.dumps(payload), + parsed=None, + usage=TokenUsage(input_tokens=100, output_tokens=10), + ) + + +def agent(client, name="A2", profile="openai", k=2): + return ExtractionAgent( + client, + arm(name, CATALOGUE), + profile_for(profile), + Orchestration.SEGMENTED, + shortlist_k=k, + ) + + +def request(ranges=RANGES): + return ExtractionRequest( + document=DOCUMENT, + schema=SCHEMA, + branches=BRANCHES, + parents=PARENTS, + ranges=ranges, + ) + + +def items_of(response_format): + """The entity shape a fill call was sent, union or object.""" + return response_format["properties"]["entities"]["items"] + + +def targets_of(slot): + """The ids a pinned slot offers, without the null that lets it decline.""" + return [value for value in slot["enum"] if value is not None] + + +class TestTheCallsItMakes: + def test_one_plan_call_and_one_fill_call_per_shortlist(self): + client = PlanThenFillClient() + agent(client).run(request()) + assert client.calls == 3 + + def test_the_steps_are_named_apart_in_the_log(self): + """Per-step tokens are the only way to cost the orchestration, and + pooling the plan under the name select-then-fill uses would make two + orchestrations indistinguishable in the same results table.""" + result = agent(PlanThenFillClient()).run(request()) + assert [c["step"] for c in result.calls.describe()["calls"]] == ["plan", "fill", "fill"] + + def test_tokens_are_attributed_to_the_step_that_spent_them(self): + result = agent(PlanThenFillClient()).run(request()) + by_step = result.calls.by_step() + assert by_step["plan"].input_tokens == 100 + assert by_step["fill"].input_tokens == 200 + + def test_entities_that_shortlist_the_same_classes_share_a_fill_call(self): + client = PlanThenFillClient( + plan=[ + {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Person"], "mention": "Grace"}, + ], + answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}]], + ) + agent(client).run(request()) + assert client.calls == 2 + + def test_the_plan_step_asks_the_selection_question(self): + client = PlanThenFillClient() + agent(client).run(request()) + assert client.formats[0]["title"] == "EntityCandidates" + + def test_the_shortlist_is_recorded_per_entity(self): + """So a two-step failure stays attributable to a step.""" + result = agent(PlanThenFillClient()).run(request()) + assert result.selected == {"e1": ("Person",), "e2": ("Organization",)} + + def test_a_plan_that_placed_nothing_stops_before_the_fill_call(self): + client = PlanThenFillClient(plan=[{"id": "e1", "candidates": [], "mention": "Ada"}]) + result = agent(client).run(request()) + assert client.calls == 1 + assert result.payload is None + assert result.selected == {"e1": ()} + + +class TestWhatTheFillStepIsGiven: + def sent(self, client=None): + client = client or PlanThenFillClient() + agent(client).run(request()) + return client + + def test_the_fill_step_sees_the_whole_document_again(self): + """A plan summary would be a bottleneck the grader cannot see past: + an entity lost there would read as an extraction failure.""" + assert self.sent().messages[1][1].content == DOCUMENT + + def test_the_fill_prompt_names_the_entities_it_is_for_by_id(self): + content = self.sent().messages[1][0].content + assert 'e1 ("Ada")' in content + + def test_the_fill_prompt_names_the_entities_another_call_fills(self): + """A source and a target that shortlisted different classes are filled + by different calls, and the one holding the source cannot state the + edge unless it knows the target has a name.""" + content = self.sent().messages[1][0].content + assert 'e2 ("Acme")' in content + assert "also describes" in content + + def test_the_ids_are_named_even_when_one_call_covers_the_plan(self): + """Where this parts company with select-then-fill, which sends the + unchanged instruction for a single group because the id is only an + internal label there.""" + client = PlanThenFillClient( + plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + answers=[[{"id": "e1", "type": "Person"}]], + ) + agent(client).run(request()) + assert 'e1 ("Ada")' in client.messages[1][0].content + + def test_a_request_without_ranges_says_nothing_about_links(self): + client = PlanThenFillClient() + ExtractionAgent( + client, + arm("A2", CATALOGUE), + profile_for("openai"), + Orchestration.SEGMENTED, + shortlist_k=2, + ).run(request(ranges=None)) + assert "points at" not in client.messages[1][0].content + + +class TestTheIdSlot: + def sent(self, client=None): + client = client or PlanThenFillClient() + agent(client).run(request()) + return client + + def test_the_answer_shape_carries_a_slot_for_the_planned_id(self): + """An id the model states is what makes two mentions being one entity + a question the model is asked. Attached afterwards by position, as the + predecessor did, it never is.""" + assert "id" in items_of(self.sent().formats[1])["properties"] + + def test_a_fill_call_is_pinned_to_the_ids_it_is_for(self): + """Offering every planned id would let one call emit an entity another + call is responsible for, and it would be counted twice.""" + client = self.sent() + assert items_of(client.formats[1])["properties"]["id"]["enum"] == ["e1"] + assert items_of(client.formats[2])["properties"]["id"]["enum"] == ["e2"] + + def test_the_id_is_required(self): + assert "id" in items_of(self.sent().formats[1])["required"] + + +class TestPinningAReference: + def sent(self, client=None): + client = client or PlanThenFillClient() + agent(client).run(request()) + return client + + def test_only_a_compatible_entity_is_offered(self): + """The only place anywhere that a link is constrained to a real + target.""" + assert targets_of(items_of(self.sent().formats[1])["properties"]["worksFor"]) == ["e2"] + + def test_an_entity_whose_class_is_not_in_the_range_is_absent(self): + """Ada is a Person and worksFor ranges over Organization, so pinning + the slot to her id would make the wrong edge the only legal one.""" + assert "e1" not in targets_of(items_of(self.sent().formats[1])["properties"]["worksFor"]) + + def test_a_subclass_of_the_range_is_offered(self): + plan = ( + PlannedEntity(key="e1", classes=("Person",)), + PlannedEntity(key="e2", classes=("LocalBusiness",)), + ) + pinned, _ = agent(PlanThenFillClient())._pin_references( + {"properties": {"type": {}, "worksFor": {"type": "object"}}}, + plan, + {"worksFor": ("Organization",)}, + PARENTS, + ) + assert pinned["properties"]["worksFor"]["enum"] == ["e2"] + + def test_a_shortlist_counts_when_any_class_on_it_fits(self): + """The fill step has not committed to one yet, and offering only the + first would rule out a target the second call may well answer with.""" + plan = (PlannedEntity(key="e1", classes=("Book", "Organization")),) + pinned, _ = agent(PlanThenFillClient())._pin_references( + {"properties": {"type": {}, "worksFor": {"type": "object"}}}, + plan, + {"worksFor": ("Organization",)}, + PARENTS, + ) + assert pinned["properties"]["worksFor"]["enum"] == ["e1"] + + def test_a_nullable_slot_keeps_a_way_of_declining(self): + """A subset that makes every property required leaves null as the only + way to say nothing. A pinned slot that dropped it would force an edge + out of every entity that has the slot.""" + plan = (PlannedEntity(key="e2", classes=("Organization",)),) + pinned, _ = agent(PlanThenFillClient())._pin_references( + {"properties": {"type": {}, "worksFor": {"type": ["object", "null"]}}}, + plan, + {"worksFor": ("Organization",)}, + PARENTS, + ) + assert pinned["properties"]["worksFor"]["type"] == ["string", "null"] + assert None in pinned["properties"]["worksFor"]["enum"] + + def test_a_range_no_planned_entity_fits_is_left_open(self): + """An empty enum is not a tighter constraint but an unsatisfiable one, + so the slot stays as the schema declares it.""" + plan = (PlannedEntity(key="e1", classes=("Person",)),) + schema = {"properties": {"type": {}, "worksFor": {"type": "object"}}} + pinned, unpinned = agent(PlanThenFillClient())._pin_references( + schema, plan, {"worksFor": ("Organization",)}, PARENTS + ) + assert pinned["properties"]["worksFor"] == {"type": "object"} + assert unpinned == ["worksFor"] + + def test_leaving_a_slot_open_is_recorded_on_the_result(self): + """An arm that ran unconstrained on a slot and never said so would be + reported as a finding about constrained links.""" + client = PlanThenFillClient( + plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + answers=[[{"id": "e1", "type": "Person"}]], + ) + result = agent(client).run(request()) + assert result.unpinned == ["worksFor"] + + def test_a_property_the_schema_does_not_carry_is_passed_over(self): + """A catalogue trim upstream or a provider's optional-property limit + can lose a slot legitimately, and a slot that is not offered is not a + slot left open.""" + plan = (PlannedEntity(key="e2", classes=("Organization",)),) + _, unpinned = agent(PlanThenFillClient())._pin_references( + {"properties": {"type": {}}}, plan, {"worksFor": ("Organization",)}, PARENTS + ) + assert unpinned == [] + + def test_a_schema_with_no_entity_shape_is_refused(self): + plan = (PlannedEntity(key="e1", classes=("Person",)),) + with pytest.raises(ValueError, match="no entity shape"): + agent(PlanThenFillClient())._pin_references( + {"properties": {"headline": {"type": "string"}}}, plan, RANGES, PARENTS + ) + + def test_an_unconstrained_arm_pins_no_reference(self): + """The decode axis keeps meaning what it means everywhere else.""" + client = PlanThenFillClient() + agent(client, name="A1").run(request()) + assert client.formats[1] is None + + +class TestTheLinkSurvives: + def test_the_payload_carries_the_link(self): + result = agent(PlanThenFillClient()).run(request()) + by_id = {entity["id"]: entity for entity in result.payload["entities"]} + assert by_id["e1"]["worksFor"] == "e2" + + def test_every_planned_entity_is_merged_into_one_answer(self): + result = agent(PlanThenFillClient()).run(request()) + assert sorted(e["id"] for e in result.payload["entities"]) == ["e1", "e2"] + + def test_the_link_is_recorded_as_an_edge(self): + result = agent(PlanThenFillClient()).run(request()) + assert result.links == [Edge(source="e1", prop="worksFor", target="e2")] + + def test_a_resolved_link_is_not_dangling(self): + assert agent(PlanThenFillClient()).run(request()).dangling == [] + + def test_the_record_is_serialisable(self): + described = agent(PlanThenFillClient()).run(request()).describe() + assert json.dumps(described) + assert described["links"] == [{"source": "e1", "prop": "worksFor", "target": "e2"}] + + +class TestADanglingReference: + """A plan that names a target the fill step then fails to emit. + + A real outcome and not a bug to paper over: the edge is kept and flagged, + because an answer pointing at an entity it never reported is a different + failure from an answer reporting no edge, and dropping it would make the + two the same number. + """ + + def run(self): + client = PlanThenFillClient(answers=[LINKED[0], []]) + return agent(client).run(request()) + + def test_the_edge_is_recorded_as_dangling(self): + assert self.run().dangling == [Edge(source="e1", prop="worksFor", target="e2")] + + def test_the_edge_stays_in_the_payload(self): + assert self.run().payload["entities"][0]["worksFor"] == "e2" + + def test_it_is_still_counted_among_the_links(self): + result = self.run() + assert result.links == result.dangling + + +class TestWhatEachProviderGets: + """The pinned schema under two subsets, with the fidelity reported. + + Pinning happens after the provider transform, as it does for the class and + the unit enum, so the fidelity figure is the transform's and says nothing + about the pin. What it does say is that the same condition costs different + amounts on different providers, which is why cells of differing fidelity + are never averaged. + """ + + def sent(self, profile): + client = PlanThenFillClient( + plan=UNION_PLAN, + answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}], [{"id": "e2", "type": "Organization"}]], + ) + result = agent(client, name="A4", profile=profile).run(request()) + return items_of(client.formats[1]), result.degradation + + def test_a_profile_that_takes_anyof_keeps_the_union_and_the_pin(self): + items, degradation = self.sent("openai") + branch = next(b for b in items["anyOf"] if "worksFor" in b["properties"]) + assert targets_of(branch["properties"]["worksFor"]) == ["e2"] + assert degradation.dropped.get("anyOf") is None + + def test_the_pinned_id_reaches_every_branch(self): + """Pinning the first branch alone would constrain one class and leave + the others open, which reads as a finding about that class.""" + items, _ = self.sent("openai") + assert all(targets_of(branch["properties"]["id"]) == ["e1"] for branch in items["anyOf"]) + + def test_a_profile_that_refuses_anyof_still_gets_the_pin(self): + items, _ = self.sent("anthropic") + assert "anyOf" not in items + assert targets_of(items["properties"]["worksFor"]) == ["e2"] + + def test_refusing_anyof_is_recorded_as_a_loss(self): + """Reporting fidelity 1.000 here is the bug this test exists for.""" + _, degradation = self.sent("anthropic") + assert degradation.dropped.get("anyOf") == 1 + assert degradation.fidelity < 1.0 + + def test_the_fidelity_reported_is_the_last_fill_call_s(self): + """As it is for select-then-fill. A two-step arm sends one schema per + shortlist and the record holds one figure, so a plan whose groups + differ in fidelity is reported by its last group and not by its worst. + """ + _, degradation = self.sent("anthropic") + assert degradation.keywords_before > 0 + + def test_the_two_profiles_report_different_fidelity(self): + _, keeps = self.sent("openai") + _, loses = self.sent("anthropic") + assert loses.fidelity < keeps.fidelity + + +class TestWhatItShares: + def test_a_missing_catalogue_is_refused(self): + bare = ExtractionAgent( + PlanThenFillClient(), + arm("A0-json"), + profile_for("openai"), + Orchestration.SEGMENTED, + ) + with pytest.raises(ValueError, match="needs a catalogue"): + bare.run(request()) + + def test_a_candidate_outside_the_catalogue_is_dropped(self): + client = PlanThenFillClient( + plan=[{"id": "e1", "candidates": ["Invented", "Person"], "mention": "Ada"}], + answers=[[{"id": "e1", "type": "Person"}]], + ) + result = agent(client).run(request()) + assert result.selected == {"e1": ("Person",)} diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index ca085fc..760eb89 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -189,7 +189,7 @@ def test_single_shot_still_makes_one_call(self): @pytest.mark.parametrize( "orchestration", - [Orchestration.RECURSIVE, Orchestration.SEGMENTED, Orchestration.MULTI_STEP], + [Orchestration.RECURSIVE, Orchestration.MULTI_STEP], ) def test_the_graph_orchestrations_say_they_are_not_ported(self, orchestration): with pytest.raises(NotImplementedError, match="entity graph"): From 7aa87ca58ee1660a3eb4b5e3eda4504e3d448240 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 30 Sep 2026 06:42:32 +0200 Subject: [PATCH 25/58] feat(agent): add multi-step orchestration - detect, choose properties per entity, extract, link - per-entity property enum, one array per entity over its own names - extract schema and union branches trimmed to what the step kept - a detect call answering with the schema is asked again, logged apart - close_properties and plan_retry declared; the other arms are unchanged --- src/oold/agent/enforcement.py | 15 +- src/oold/agent/extraction.py | 384 +++++++++++++- src/oold/agent/prompts.py | 95 +++- tests/test_agent/test_extraction.py | 8 +- tests/test_agent/test_multi_step.py | 617 ++++++++++++++++++++++ tests/test_agent/test_select_then_fill.py | 8 +- 6 files changed, 1108 insertions(+), 19 deletions(-) create mode 100644 tests/test_agent/test_multi_step.py diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index 198edd1..fa99131 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -45,7 +45,20 @@ class Orchestration(str, Enum): belongs to no single entity.""" MULTI_STEP = "multi_step" - """Detect, select properties, extract, construct, deduplicate.""" + """Detect, choose properties per entity, extract, link. + + Segmented with a property step in the middle. The plan closes the class + slot, the property step closes which slots exist at all, and the extract + step fills what is left against ids both steps agree on. + + Four steps and not the predecessor's five. Its construct step sent the + hints and the schema and no document, so it asked a model to reformat + values it had already produced against a schema it had already matched, + which is the failure :meth:`~oold.agent.extraction.ExtractionAgent._validate_and_repair` + already covers with the validator's own reasons. Its deduplication step is + a question about identity across documents, measured against its own + corpus, and an identity judge inside an orchestration cannot be scored + apart from the extraction it sits in.""" SELECT_THEN_FILL = "select_then_fill" """Shortlist the class, then fill the schema that shortlist implies. diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index edcd162..c3ad5ee 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -29,7 +29,9 @@ from oold.agent.prompts import ( ExtractionRequest, build_messages, + build_property_messages, build_selection_messages, + property_schema, selection_schema, ) from oold.agent.provider import Degradation, ProviderProfile, prepare, schema_hash @@ -127,6 +129,13 @@ class ExtractionResult: unpinned: list[str] = field(default_factory=list) """Reference properties left open because no planned entity fits their range. Those slots ran unconstrained, and the record says which.""" + properties_chosen: dict[str, tuple[str, ...]] = field(default_factory=dict) + """The properties the property step kept, per entity. + + Recorded for the reason :attr:`selected` is. An orchestration that closes + the property slot can fail by never offering the property the document + states, or by offering it and the extract step leaving it empty, and + without this the two are the same missing value.""" @property def parsed(self) -> bool: @@ -138,6 +147,7 @@ def describe(self) -> dict[str, Any]: "schema_sha256": self.schema_sha256, "prompt_sha256": self.prompt_sha256, "selected": {k: list(v) for k, v in self.selected.items()}, + "properties_chosen": {k: list(v) for k, v in self.properties_chosen.items()}, "dropped": list(self.dropped), "invalid": list(self.invalid), "repairs": self.repairs, @@ -161,6 +171,8 @@ def __init__( *, attempts: int = 1, shortlist_k: int = 3, + close_properties: bool = True, + plan_retry: bool | None = None, ) -> None: self.client = client self.enforcement = enforcement @@ -173,15 +185,33 @@ def __init__( self.shortlist_k = shortlist_k """How many classes the select step may keep per entity. One is the commit case, where a wrong selection cannot be recovered.""" - if orchestration in (Orchestration.RECURSIVE, Orchestration.MULTI_STEP): + self.close_properties = close_properties + """Whether the property step's answer removes the slots it left out. + + On, the extract schema carries the chosen properties and the required + ones and nothing else, which is the direct analogue of closing the + class slot. Off, the chosen properties are named in the extract prompt + and the schema stays whole, so a property the step missed can still be + answered. The two are different claims about what closing a slot buys, + so which one ran is declared rather than assumed.""" + self.plan_retry = (orchestration is Orchestration.MULTI_STEP) if plan_retry is None else plan_retry + """Whether a first call that answered with the schema is asked again. + + Defaulted from the orchestration rather than fixed, so the mitigation + can be run on the orchestration it was not written for. Without that, + a multi-step arm beating a segmented one on a model that echoes + schemas would be reporting the retry as a property of the pipeline.""" + if orchestration is Orchestration.RECURSIVE: raise NotImplementedError( - f"orchestration {orchestration.value} is not ported yet. It addresses " - f"the entity graph, which comes after class selection works" + "orchestration recursive is not ported yet. It addresses " + "the entity graph, which comes after class selection works" ) if shortlist_k < 1: raise ValueError("a shortlist of nothing leaves the second step no class to fill") def run(self, request: ExtractionRequest) -> ExtractionResult: + if self.orchestration is Orchestration.MULTI_STEP: + return self._multi_step(request) if self.orchestration is Orchestration.SEGMENTED: return self._segmented(request) if self.orchestration is Orchestration.SELECT_THEN_FILL: @@ -380,7 +410,7 @@ def _segmented(self, request: ExtractionRequest) -> ExtractionResult: """ log = CallLog() self._mentions = {} - selected, text = self._select(request, log, step="plan") + selected, text = self._select(request, log, step="plan", insist=self.plan_retry) plan = tuple( PlannedEntity(key=key, classes=classes, mention=self._mentions.get(key, "")) for key, classes in selected.items() @@ -461,12 +491,177 @@ def _plan_instruction( ) return " ".join(sections) + def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: + """Detect, choose properties per entity, extract, link. + + Segmented with one call inserted between the plan and the fill. The + plan says which classes an entity may be, the property step says which + of those classes' slots the document fills at all, and the extract step + answers what is left against ids both ends agree on. + + Four steps and not the predecessor's five. Its construct step sent the + hints and the schema and no document, so it asked a model to reformat + values it had already produced against a schema it had already matched; + :meth:`_validate_and_repair` covers that failure and hands the + validator's reasons back verbatim. Its deduplication step asks whether + two entities are one, which is a question about identity across + documents with a corpus of its own, and a judge sitting inside an + orchestration cannot be scored apart from the extraction around it. + + Whether the property step binds is :attr:`close_properties` and not a + fact about this pipeline. An entity the step leaves with nothing is + extracted with its class and its id alone, because that is what the + step said, and restoring the slots behind its back would hide a + step-two failure inside step three. + """ + log = CallLog() + self._mentions = {} + selected, text = self._select(request, log, step="detect", insist=self.plan_retry) + plan = tuple( + PlannedEntity(key=key, classes=classes, mention=self._mentions.get(key, "")) + for key, classes in selected.items() + ) + placed = tuple(entity for entity in plan if entity.classes) + if not placed: + return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + + chosen = self._choose_properties(request, log, placed, self._available_properties(request, placed)) + required = _required_properties(request.schema) + + # Grouped by shortlist and by chosen properties together, where + # segmented groups by shortlist alone. The extra key is the same + # argument one step on: entities sharing a call share the schema that + # call is sent, so two that chose different properties can no more + # share one than two that shortlisted different classes. + groups: dict[tuple[tuple[str, ...], tuple[str, ...]], list[str]] = {} + for entity in placed: + groups.setdefault((entity.classes, chosen.get(entity.key, ())), []).append(entity.key) + + merged: list[Any] = [] + unpinned: list[str] = [] + last: ExtractionResult | None = None + for (classes, kept), keys in groups.items(): + narrowed = self.enforcement.with_catalogue(classes) + filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) + keep = set(kept) | required + step = ExtractionRequest( + document=request.document, + schema=_trim_properties(request.schema, keep) if self.close_properties else request.schema, + branches=_trim_branches(request.branches, keep) if self.close_properties else request.branches, + parents=request.parents, + ranges=request.ranges, + instruction=self._extract_instruction(request, plan, keys, kept), + ) + outcome = filler._single_shot(step, plan=plan, filling=tuple(keys)) + for call in outcome.calls: + log.append(replace(call, step="extract")) + merged.extend(_entities_of(outcome.payload)) + unpinned.extend(name for name in outcome.unpinned if name not in unpinned) + last = outcome + + if last is None: + return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + links, dangling = _edges_of(merged, request.ranges) + last.payload = {"entities": merged} if merged else None + last.calls = log + last.selected = selected + last.properties_chosen = chosen + last.links = links + last.dangling = dangling + last.unpinned = unpinned + return last + + def _available_properties( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + ) -> dict[str, tuple[str, ...]]: + """What each planned entity may carry, before the document is read. + + The union over the entity's shortlist, for the reason + :func:`_compatible_ids` takes the union: the extract step has not + committed to one class yet, and offering only the first class's + properties would rule out a value the second call may well state. + + Intersected with the answer shape and in its order, so the step can + only name a slot the extract call actually has. A corpus that declares + no branches falls back to the whole shape, which asks the same question + over every property the schema offers. + """ + offered = _shape_properties(request.schema) + if not offered: + return {} + lineage = {name: tuple(values) for name, values in (request.parents or {}).items()} + available: dict[str, tuple[str, ...]] = {} + for entity in plan: + admitted = _admitted_properties(entity.classes, request.branches, lineage) + names = tuple(name for name in offered if not admitted or name in admitted) + if names: + available[entity.key] = names + return available + + def _choose_properties( + self, + request: ExtractionRequest, + log: CallLog, + plan: tuple[PlannedEntity, ...], + available: dict[str, tuple[str, ...]], + ) -> dict[str, tuple[str, ...]]: + """Ask which of each entity's own properties the document fills. + + One call for the whole plan, with one enumeration per entity. The + predecessor asked per entity in its construct step, which costs a call + per entity for an answer one schema can carry. + + A name the entity cannot carry is dropped rather than repaired, the way + :meth:`_select` drops a candidate outside the catalogue. The + enumeration already said what was legal, and keeping the name would put + a slot in the extract schema that no class on the shortlist declares. + """ + if not available: + return {} + schema = property_schema(available) + prepared, _ = prepare(schema, self.profile, grounding=False) + named = {entity.key: f"{_named(entity)}, {'/'.join(entity.classes)}" for entity in plan} + messages = build_property_messages(request, available, named) + response_format = prepared if self.enforcement.decode_constraint is not DecodeConstraint.NONE else None + + with log.timed("properties", self.client.model, attempt=1, schema_sha256=schema_hash(prepared)) as sink: + reply = self.client.invoke(messages, response_format=response_format) + sink.append(reply.usage or TokenUsage()) + + answered = _fillable_of(reply.parsed if reply.parsed is not None else parse_json_answer(reply.text), available) + return { + key: tuple(name for name in names if name in set(answered.get(key) or ())) + for key, names in available.items() + } + + def _extract_instruction( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + keys: list[str], + kept: tuple[str, ...], + ) -> str: + """What :meth:`_plan_instruction` says, and which properties to fill. + + The properties are named even when the schema already carries only + them, as the ids are named even when the id slot is already enumerated. + An arm that shows no schema, and an arm whose schema a provider + flattened, both still have to be told. + """ + base = self._plan_instruction(request, plan, keys) + if kept: + return f"{base} Report only these properties for them: {', '.join(kept)}." + return f"{base} The document gives no property value for them, so report the class and the id only." + def _select( self, request: ExtractionRequest, log: CallLog, *, step: str = "select", + insist: bool = False, ) -> tuple[dict[str, tuple[str, ...]], str]: """Ask which classes each entity could be, keeping at most k. @@ -488,6 +683,18 @@ def _select( sink.append(reply.usage or TokenUsage()) payload = reply.parsed if reply.parsed is not None else parse_json_answer(reply.text) + text = reply.text + if insist: + payload, text = self._insist( + payload, + text, + schema, + messages, + response_format, + log, + step=step, + digest=schema_hash(prepared), + ) allowed = set(catalogue) selected: dict[str, tuple[str, ...]] = {} for index, entity in enumerate(_entities_of(payload), start=1): @@ -499,7 +706,57 @@ def _select( mention = entity.get("mention") if isinstance(mention, str) and mention.strip(): self._mentions[key] = mention.strip() - return selected, reply.text + return selected, text + + def _insist( + self, + payload: Any, + text: str, + schema: dict[str, Any], + messages: list[Any], + response_format: dict[str, Any] | None, + log: CallLog, + *, + step: str, + digest: str | None, + ) -> tuple[Any, str]: + """Ask once more when the first answer was not an answer. + + gpt-5-nano returns the selection schema itself instead of an instance + of it on about a third of plan calls, and on none at all when the first + call asks for values: a single-shot arm has no call whose answer is a + structure, so there is nothing to echo. Any orchestration whose first + call asks for a structure inherits that, and it costs the whole cell, + because the classes the plan did not choose are the classes the later + steps may not answer with. + + The trigger is both conditions at once: the answer names no entity and + it fails the schema it was asked for. An answer that names entities + under a wrapper the schema does not declare is usable and is left + alone, and an answer that validates and names none is a document with + nothing in it rather than a failed call. + + The validator's reasons go back verbatim, as they do for an invalid + extraction, so the retry rate stays a measure of the model and not of + how the advice was worded. + """ + from oold.agent.repair import repair_message + from oold.validation.instance_checks import validate_instance + + if _entities_of(payload): + return payload, text + errors = validate_instance(payload, schema).errors + if not errors: + return payload, text + + turn = [*list(messages), repair_message(text, errors)] + with log.timed(step, self.client.model, attempt=2, schema_sha256=digest) as sink: + reply = self.client.invoke(turn, response_format=response_format) + sink.append(reply.usage or TokenUsage()) + retried = reply.parsed if reply.parsed is not None else parse_json_answer(reply.text) + if retried is None: + return payload, text + return retried, reply.text def _schema_for( self, @@ -821,6 +1078,123 @@ def visit(node: Any) -> None: return found +def _shape_properties(schema: Any) -> tuple[str, ...]: + """The property names an entity may carry, in the schema's own order. + + The class slot and the id slot are left out. Neither was ever the property + step's to choose: the first is what the plan decided and the second is how + the answer is joined back to it. + """ + names: list[str] = [] + for shape in _entity_shapes(schema): + for name in shape.get("properties") or {}: + if name not in _CLASS_KEYS and name not in _ID_KEYS and name not in names: + names.append(name) + return tuple(names) + + +def _required_properties(schema: Any) -> set[str]: + """Every property an entity shape requires, which a trim keeps. + + A required property is not the property step's to remove. Dropping it + leaves a name in ``required`` with nothing to satisfy it, and a provider + subset that rewrites ``required`` from ``properties`` would instead make + the answer legal without it, so the same trim would mean two things. + """ + names: set[str] = set() + for shape in _entity_shapes(schema): + required = shape.get("required") + if isinstance(required, list): + names.update(name for name in required if isinstance(name, str)) + return names + + +def _admitted_properties( + classes: tuple[str, ...], + branches: dict[str, dict[str, Any]] | None, + lineage: dict[str, tuple[str, ...]], +) -> set[str]: + """Everything the classes on a shortlist declare or inherit. + + Empty when the corpus declares no branches, which the caller reads as no + narrowing rather than as no properties. + """ + if not branches: + return set() + found: set[str] = set() + for name in classes: + seen: set[str] = set() + queue = [name] + while queue: + current = queue.pop() + if current in seen: + continue + seen.add(current) + found.update(branches.get(current) or {}) + queue.extend(lineage.get(current, ())) + return found + + +def _trim_properties(schema: dict[str, Any] | None, keep: set[str]) -> dict[str, Any] | None: + """The answer shape with the slots the property step left out removed.""" + if schema is None: + return None + trimmed = copy.deepcopy(schema) + for shape in _entity_shapes(trimmed): + properties = shape.get("properties") or {} + shape["properties"] = { + name: definition + for name, definition in properties.items() + if name in keep or name in _CLASS_KEYS or name in _ID_KEYS + } + return trimmed + + +def _trim_branches( + branches: dict[str, dict[str, Any]] | None, + keep: set[str], +) -> dict[str, dict[str, Any]] | None: + """The union branches, narrowed the way the answer shape was. + + Trimmed together or not at all. A branch still declaring a property the + answer shape no longer carries would put that property back on the union + arm alone, and the difference between the arms would be a difference in + what each was asked for. + """ + if not branches: + return branches + return { + name: {prop: definition for prop, definition in properties.items() if prop in keep} + for name, properties in branches.items() + } + + +def _fillable_of(payload: Any, available: dict[str, tuple[str, ...]]) -> dict[str, list[Any]]: + """The property lists in an answer, whatever the model called the wrapper. + + The declared wrapper first, then a lone key holding an object, then the + answer itself. The same allowance :func:`_entities_of` makes, and for the + same observation: giving a schema a title stopped one provider rejecting it + and started another answering under that title. + """ + if not isinstance(payload, dict): + return {} + candidates: list[dict[str, Any]] = [] + inner = payload.get("fillable") + if isinstance(inner, dict): + candidates.append(inner) + elif len(payload) == 1: + only = next(iter(payload.values())) + if isinstance(only, dict): + candidates.append(only) + candidates.append(payload) + for candidate in candidates: + found = {key: value for key, value in candidate.items() if key in available and isinstance(value, list)} + if found: + return found + return {} + + def _accepts_null(slot: Any) -> bool: """Whether a prepared slot was left able to say nothing.""" if not isinstance(slot, dict): diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index b31af71..d5ed5ee 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -13,13 +13,21 @@ from __future__ import annotations import json +from collections.abc import Mapping, Sequence from dataclasses import dataclass from typing import Any from oold.agent.client import Message from oold.agent.enforcement import Enforcement, OutputForm -__all__ = ["ExtractionRequest", "build_messages", "build_selection_messages", "selection_schema"] +__all__ = [ + "ExtractionRequest", + "build_messages", + "build_property_messages", + "build_selection_messages", + "property_schema", + "selection_schema", +] _TASK = "Read the document and report every entity it describes, with the values stated for each." @@ -45,6 +53,22 @@ _GATE_HINT = "An entity whose class is not in the list will be discarded, so leave out anything you cannot place." +_PROPERTY_TASK = ( + "Read the document and say, for each entity listed below, which of its own " + "properties the document gives a value for." +) + +_PROPERTY_FORM = ( + "Answer with JSON only. Give one list of property names per entity, under that entity's id, " + "using the names exactly as they are written here." +) + +_PROPERTY_HONESTY = ( + "Leave out a property whose value you would have to invent. A property you leave out will not be asked for again." +) + +_PROPERTY_ENTITIES = "The entities, with the properties each one may carry:" + @dataclass(frozen=True) class ExtractionRequest: @@ -151,6 +175,75 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: } +def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: + """The answer shape the property step asks for. + + One array per entity, whose items enumerate **that entity's own** property + names. Pooling every entity's properties into one enumeration would let one + entity be given another's property, which is the thing a per-entity + enumeration is for, and it is the same argument that makes the fill step + group by shortlist rather than pool the candidate classes. + + Refuses an entity with no properties. An empty ``enum`` is unsatisfiable + rather than tight: the strict subsets reject it outright, and one that + accepted it would leave a required array with no legal member. + """ + if not offered: + raise ValueError("the property step needs at least one entity with properties, or there is nothing to ask") + empty = [key for key, names in offered.items() if not names] + if empty: + raise ValueError(f"no property is available for {', '.join(empty)}, so the enumeration would admit nothing") + return { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "FillableProperties", + "description": "Which properties of each entity the document gives a value for.", + "type": "object", + "properties": { + "fillable": { + "type": "object", + "properties": { + key: { + "type": "array", + "maxItems": len(names), + "items": {"type": "string", "enum": list(names)}, + "description": f"The properties of {key} the document gives a value for.", + } + for key, names in offered.items() + }, + "required": list(offered), + "additionalProperties": False, + } + }, + "required": ["fillable"], + "additionalProperties": False, + } + + +def build_property_messages( + request: ExtractionRequest, + offered: Mapping[str, Sequence[str]], + named: Mapping[str, str] | None = None, +) -> list[Message]: + """The messages the property step sends. + + The document is the user message, as it is for every other step. The + properties are listed in the system message as well as enumerated in the + answer shape, because an arm that shows no schema still has to say what the + names are before it can ask which of them the document fills. + """ + listed = "\n".join(f"{(named or {}).get(key) or key}: {', '.join(names)}" for key, names in offered.items()) + sections = [ + _PROPERTY_TASK, + _PROPERTY_FORM, + _PROPERTY_HONESTY, + f"{_PROPERTY_ENTITIES}\n{listed}", + ] + return [ + Message(role="system", content="\n\n".join(sections)), + Message(role="user", content=request.document), + ] + + def build_selection_messages(request: ExtractionRequest, enforcement: Enforcement, k: int) -> list[Message]: """The messages the select step sends. diff --git a/tests/test_agent/test_extraction.py b/tests/test_agent/test_extraction.py index c22747f..ea4f6c4 100644 --- a/tests/test_agent/test_extraction.py +++ b/tests/test_agent/test_extraction.py @@ -223,17 +223,13 @@ def test_single_shot_makes_one_call(self): agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) assert client.calls == 1 - @pytest.mark.parametrize( - "orchestration", - [Orchestration.RECURSIVE, Orchestration.MULTI_STEP], - ) - def test_an_unported_orchestration_refuses_rather_than_pretending(self, orchestration): + def test_an_unported_orchestration_refuses_rather_than_pretending(self): with pytest.raises(NotImplementedError, match="not ported yet"): ExtractionAgent( FakeClient(), ARMS["A1"], profile_for("openai"), - orchestration, + Orchestration.RECURSIVE, ) diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py new file mode 100644 index 0000000..ebb5206 --- /dev/null +++ b/tests/test_agent/test_multi_step.py @@ -0,0 +1,617 @@ +"""Detect, choose properties per entity, extract, link. + +Segmented with one call inserted between the plan and the fill. The plan closes +the class slot, the property step closes which slots exist at all, and the +extract step fills what is left against ids both ends agree on. + +The question the arm exists to answer is whether closing the property slot per +entity buys anything, given that segmented already loses to single shot because +a wrong plan is unrecoverable. This adds a second step that binds, so it +inherits that risk and doubles it. What it does not inherit is the plan call +that answers with the schema instead of a plan, which is asked again here. +""" + +import json + +import pytest + +from oold.agent.client import ChatResponse, TokenUsage +from oold.agent.enforcement import Orchestration, arm +from oold.agent.extraction import Edge, ExtractionAgent +from oold.agent.prompts import ExtractionRequest, property_schema +from oold.agent.provider import profile_for + +CATALOGUE = ("Person", "Organization", "LocalBusiness", "Book") + +BRANCHES = { + "Thing": {"name": {"type": "string"}}, + "Person": {"jobTitle": {"type": "string"}, "worksFor": {"type": "object"}}, + "Organization": {"legalName": {"type": "string"}}, + "LocalBusiness": {"openingHours": {"type": "string"}}, + "Book": {"isbn": {"type": "string"}, "author": {"type": "object"}}, +} + +PARENTS = { + "Person": ("Thing",), + "Organization": ("Thing",), + "LocalBusiness": ("Organization",), + "Book": ("Thing",), +} + +RANGES = {"worksFor": ("Organization",), "author": ("Person",)} + +SCHEMA = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Entities", + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "name": {"type": "string"}, + "jobTitle": {"type": "string"}, + "legalName": {"type": "string"}, + "openingHours": {"type": "string"}, + "isbn": {"type": "string"}, + "worksFor": {"type": "object"}, + "author": {"type": "object"}, + }, + "required": ["type"], + }, + } + }, + "required": ["entities"], +} + +DOCUMENT = "Ada works for Acme. Acme is a company. The Ada Book was written by Ada." + +PLAN = [ + {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Organization"], "mention": "Acme"}, +] + +FILLABLE = {"fillable": {"e1": ["name", "worksFor"], "e2": ["name"]}} + +EXTRACTED = [ + [{"id": "e1", "type": "Person", "name": "Ada", "worksFor": "e2"}], + [{"id": "e2", "type": "Organization", "name": "Acme"}], +] + +SCHEMA_ECHO = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "EntityCandidates", + "type": "object", + "properties": {"entities": {"type": "array", "items": {"type": "object"}}}, + "required": ["entities"], +} +"""What gpt-5-nano answered on 37 of 120 plan calls: the schema it was asked +for, rather than an instance of it.""" + +UNION_PLAN = [ + {"id": "e1", "candidates": ["Person", "Book"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Organization", "LocalBusiness"], "mention": "Acme"}, +] +"""Two classes per entity, so every extract call is sent a union of two +branches and a profile that refuses ``anyOf`` has something to lose.""" + + +class MultiStepClient: + """Answers the detect step, the property step, then one call per group.""" + + model = "stepper" + + def __init__(self, plan=None, fillable=None, answers=None, detects=None) -> None: + self.detects = list(detects) if detects is not None else [{"entities": list(PLAN if plan is None else plan)}] + self.fillable = FILLABLE if fillable is None else fillable + self.answers = [list(group) for group in (EXTRACTED if answers is None else answers)] + self.asked_properties = False + self.formats: list = [] + self.messages: list = [] + self.calls = 0 + + def invoke(self, messages, *, response_format=None) -> ChatResponse: + self.calls += 1 + self.formats.append(response_format) + self.messages.append(list(messages)) + if self.detects: + payload = self.detects.pop(0) + elif not self.asked_properties: + self.asked_properties = True + payload = self.fillable + else: + payload = {"entities": self.answers.pop(0) if self.answers else []} + return ChatResponse( + text=json.dumps(payload), + parsed=None, + usage=TokenUsage(input_tokens=100, output_tokens=10), + ) + + +def agent(client, name="A2", profile="openai", k=2, **kwargs): + return ExtractionAgent( + client, + arm(name, CATALOGUE), + profile_for(profile), + Orchestration.MULTI_STEP, + shortlist_k=k, + **kwargs, + ) + + +def request(ranges=RANGES): + return ExtractionRequest( + document=DOCUMENT, + schema=SCHEMA, + branches=BRANCHES, + parents=PARENTS, + ranges=ranges, + ) + + +def items_of(response_format): + """The entity shape an extract call was sent, union or object.""" + return response_format["properties"]["entities"]["items"] + + +def targets_of(slot): + """The ids a pinned slot offers, without the null that lets it decline.""" + return [value for value in slot["enum"] if value is not None] + + +def enums_of(response_format): + """The property enumeration each entity was offered, per entity.""" + offered = response_format["properties"]["fillable"]["properties"] + return {key: slot["items"]["enum"] for key, slot in offered.items()} + + +class TestTheCallsItMakes: + def test_one_detect_one_property_call_and_one_extract_per_group(self): + client = MultiStepClient() + agent(client).run(request()) + assert client.calls == 4 + + def test_the_steps_are_named_apart_in_the_log(self): + """Per-step tokens are the only way to cost the orchestration, and the + property step is the one thing this has that segmented does not.""" + result = agent(MultiStepClient()).run(request()) + assert [c["step"] for c in result.calls.describe()["calls"]] == [ + "detect", + "properties", + "extract", + "extract", + ] + + def test_tokens_are_attributed_to_the_step_that_spent_them(self): + by_step = agent(MultiStepClient()).run(request()).calls.by_step() + assert by_step["detect"].input_tokens == 100 + assert by_step["properties"].input_tokens == 100 + assert by_step["extract"].input_tokens == 200 + + def test_entities_that_agree_on_class_and_properties_share_an_extract_call(self): + client = MultiStepClient( + plan=[ + {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Person"], "mention": "Grace"}, + ], + fillable={"fillable": {"e1": ["name"], "e2": ["name"]}}, + answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}]], + ) + agent(client).run(request()) + assert client.calls == 3 + + def test_entities_that_chose_different_properties_do_not(self): + """Entities sharing a call share the schema that call is sent, so two + that chose different properties can no more share one than two that + shortlisted different classes.""" + client = MultiStepClient( + plan=[ + {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Person"], "mention": "Grace"}, + ], + fillable={"fillable": {"e1": ["name"], "e2": ["name", "jobTitle"]}}, + answers=[[{"id": "e1", "type": "Person"}], [{"id": "e2", "type": "Person"}]], + ) + agent(client).run(request()) + assert client.calls == 4 + + def test_a_plan_that_placed_nothing_stops_before_the_property_call(self): + client = MultiStepClient(plan=[{"id": "e1", "candidates": [], "mention": "Ada"}]) + result = agent(client).run(request()) + assert client.calls == 1 + assert result.payload is None + + def test_the_detect_step_asks_the_selection_question(self): + client = MultiStepClient() + agent(client).run(request()) + assert client.formats[0]["title"] == "EntityCandidates" + + +class TestThePerEntityPropertyEnum: + def sent(self, client=None): + client = client or MultiStepClient() + agent(client).run(request()) + return client + + def test_the_property_schema_carries_one_array_per_entity(self): + assert sorted(enums_of(self.sent().formats[1])) == ["e1", "e2"] + + def test_the_enum_holds_only_that_entity_s_own_properties(self): + """The direct analogue of closing the class slot. Pooling every + entity's properties into one enumeration would let one entity be given + another's property, which is the thing a per-entity enumeration is + for.""" + offered = enums_of(self.sent().formats[1]) + assert offered["e1"] == ["name", "jobTitle", "worksFor"] + assert offered["e2"] == ["name", "legalName"] + + def test_a_property_another_entity_s_class_declares_is_absent(self): + offered = enums_of(self.sent().formats[1]) + assert "jobTitle" not in offered["e2"] + assert "legalName" not in offered["e1"] + + def test_an_inherited_property_is_offered(self): + """`name` is declared on Thing, and Person and Organization both carry + it, so a union over the shortlist has to walk the ancestry.""" + assert "name" in enums_of(self.sent().formats[1])["e1"] + + def test_a_shortlist_offers_the_union_of_its_classes_properties(self): + """The extract step has not committed to one class yet, and offering + only the first would rule out a value the second may well state.""" + client = MultiStepClient(plan=UNION_PLAN, fillable={"fillable": {"e1": ["name"], "e2": ["name"]}}) + agent(client).run(request()) + assert enums_of(client.formats[1])["e1"] == ["name", "jobTitle", "isbn", "worksFor", "author"] + + def test_the_property_schema_carries_a_title(self): + """LangChain rejects a response format without one, and every cell of + the arm then fails without saying why.""" + assert self.sent().formats[1]["title"] == "FillableProperties" + + def test_the_prompt_names_each_entity_with_its_class_and_its_properties(self): + content = self.sent().messages[1][0].content + assert 'e1 ("Ada"), Person: name, jobTitle, worksFor' in content + + def test_the_property_step_reads_the_whole_document(self): + assert self.sent().messages[1][1].content == DOCUMENT + + def test_the_chosen_properties_are_recorded_per_entity(self): + """So a failure stays attributable to a step. Without it, never + offering the property and leaving it empty are the same missing + value.""" + result = agent(MultiStepClient()).run(request()) + assert result.properties_chosen == {"e1": ("name", "worksFor"), "e2": ("name",)} + + def test_a_name_outside_the_entity_s_enumeration_is_dropped(self): + client = MultiStepClient(fillable={"fillable": {"e1": ["name", "legalName"], "e2": ["name"]}}) + result = agent(client).run(request()) + assert result.properties_chosen["e1"] == ("name",) + + def test_an_entity_with_no_properties_is_refused_rather_than_enumerated_empty(self): + """An empty enum is unsatisfiable rather than tight: the strict subsets + reject it, and one that accepted it would leave a required array with + no legal member.""" + with pytest.raises(ValueError, match="admit nothing"): + property_schema({"e1": ()}) + + def test_the_record_is_serialisable(self): + described = agent(MultiStepClient()).run(request()).describe() + assert json.dumps(described) + assert described["properties_chosen"] == {"e1": ["name", "worksFor"], "e2": ["name"]} + + +class TestWhatTheExtractStepIsGiven: + def sent(self, client=None, **kwargs): + client = client or MultiStepClient() + agent(client, **kwargs).run(request()) + return client + + def test_the_extract_step_sees_the_whole_document_again(self): + assert self.sent().messages[2][1].content == DOCUMENT + + def test_the_prompt_names_the_entities_it_is_for_by_id(self): + assert 'e1 ("Ada")' in self.sent().messages[2][0].content + + def test_the_prompt_names_the_properties_to_fill(self): + """Named even though the schema already carries only them, as the ids + are named even though the id slot is already enumerated.""" + assert "Report only these properties for them: name, worksFor." in self.sent().messages[2][0].content + + def test_the_schema_carries_the_chosen_properties(self): + assert "worksFor" in items_of(self.sent().formats[2])["properties"] + + def test_a_property_the_step_left_out_is_gone_from_the_schema(self): + """Closing the property slot, which is what the step is for.""" + offered = items_of(self.sent().formats[2])["properties"] + assert "jobTitle" not in offered + assert "legalName" not in offered + + def test_a_required_property_survives_the_trim(self): + """Dropping it leaves a name in `required` with nothing to satisfy it, + and a subset that rewrites `required` from `properties` would instead + make the answer legal without it.""" + assert "type" in items_of(self.sent().formats[2])["properties"] + + def test_an_entity_the_step_left_empty_is_asked_for_its_class_alone(self): + """What the step said. Restoring the slots behind its back would hide a + step-two failure inside step three.""" + client = MultiStepClient( + plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + fillable={"fillable": {"e1": []}}, + answers=[[{"id": "e1", "type": "Person"}]], + ) + agent(client).run(request()) + assert sorted(items_of(client.formats[2])["properties"]) == ["id", "type"] + assert "no property value" in client.messages[2][0].content + + def test_an_open_condition_keeps_the_schema_whole(self): + """The same two calls, with the answer advisory instead of binding. A + property the step missed can still be answered, which is the claim the + closed condition is measured against.""" + client = self.sent(close_properties=False) + assert "jobTitle" in items_of(client.formats[2])["properties"] + + def test_an_open_condition_still_names_the_properties(self): + assert "Report only these properties" in self.sent(close_properties=False).messages[2][0].content + + +class TestTheIdSlot: + def sent(self): + client = MultiStepClient() + agent(client).run(request()) + return client + + def test_an_extract_call_is_pinned_to_the_ids_it_is_for(self): + client = self.sent() + assert items_of(client.formats[2])["properties"]["id"]["enum"] == ["e1"] + assert items_of(client.formats[3])["properties"]["id"]["enum"] == ["e2"] + + def test_the_id_is_required(self): + assert "id" in items_of(self.sent().formats[2])["required"] + + def test_the_id_survives_the_property_trim(self): + """It was never offered to the property step, because it is how the + answer is joined back to the plan and not a value to fill.""" + assert "id" in items_of(self.sent().formats[2])["properties"] + + +class TestPinningAReference: + def sent(self, client=None): + client = client or MultiStepClient() + agent(client).run(request()) + return client + + def test_only_a_compatible_entity_is_offered(self): + assert targets_of(items_of(self.sent().formats[2])["properties"]["worksFor"]) == ["e2"] + + def test_an_entity_whose_class_is_not_in_the_range_is_absent(self): + assert "e1" not in targets_of(items_of(self.sent().formats[2])["properties"]["worksFor"]) + + def test_a_reference_the_property_step_left_out_is_not_reported_as_left_open(self): + """A slot that is not offered is not a slot left open. The property + step removing it is the same case as a provider's optional-property + limit removing it.""" + client = MultiStepClient(fillable={"fillable": {"e1": ["name"], "e2": ["name"]}}) + result = agent(client).run(request()) + assert "worksFor" not in items_of(client.formats[2])["properties"] + assert result.unpinned == [] + + def test_a_range_no_planned_entity_fits_is_recorded_as_left_open(self): + client = MultiStepClient( + plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + fillable={"fillable": {"e1": ["name", "worksFor"]}}, + answers=[[{"id": "e1", "type": "Person", "name": "Ada"}]], + ) + result = agent(client).run(request()) + assert result.unpinned == ["worksFor"] + + def test_an_unconstrained_arm_pins_no_reference(self): + client = MultiStepClient() + agent(client, name="A1").run(request()) + assert client.formats[2] is None + + +class TestTheLinkSurvives: + def test_the_payload_carries_the_link(self): + result = agent(MultiStepClient()).run(request()) + by_id = {entity["id"]: entity for entity in result.payload["entities"]} + assert by_id["e1"]["worksFor"] == "e2" + + def test_every_planned_entity_is_merged_into_one_answer(self): + result = agent(MultiStepClient()).run(request()) + assert sorted(e["id"] for e in result.payload["entities"]) == ["e1", "e2"] + + def test_the_link_is_recorded_as_an_edge(self): + assert agent(MultiStepClient()).run(request()).links == [Edge(source="e1", prop="worksFor", target="e2")] + + def test_a_resolved_link_is_not_dangling(self): + assert agent(MultiStepClient()).run(request()).dangling == [] + + def test_an_unreported_target_leaves_the_edge_dangling(self): + """The edge is kept and flagged. An answer pointing at an entity it + never reported is a different failure from an answer reporting no edge, + and dropping it would make the two the same number.""" + result = agent(MultiStepClient(answers=[EXTRACTED[0], []])).run(request()) + assert result.dangling == [Edge(source="e1", prop="worksFor", target="e2")] + assert result.payload["entities"][0]["worksFor"] == "e2" + + +class TestWhatEachProviderGets: + """The trimmed and pinned schema under two subsets, with what it cost. + + The trim happens before the provider transform and the pins after, as they + do for segmented, so the fidelity figure is the transform's alone. What it + says is that the same condition costs different amounts on different + providers, which is why cells of differing fidelity are never averaged. + """ + + def sent(self, profile): + client = MultiStepClient( + plan=UNION_PLAN, + fillable={"fillable": {"e1": ["name", "worksFor"], "e2": ["name"]}}, + answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}], [{"id": "e2", "type": "Organization"}]], + ) + result = agent(client, name="A4", profile=profile).run(request()) + return items_of(client.formats[2]), result.degradation + + def test_a_profile_that_takes_anyof_keeps_the_union_and_the_pin(self): + items, degradation = self.sent("openai") + branch = next(b for b in items["anyOf"] if "worksFor" in b["properties"]) + assert targets_of(branch["properties"]["worksFor"]) == ["e2"] + assert degradation.dropped.get("anyOf") is None + + def test_the_branches_are_trimmed_with_the_answer_shape(self): + """A branch still declaring a property the shape no longer carries + would put it back on the union arm alone, and the difference between + the arms would be a difference in what each was asked for.""" + items, _ = self.sent("openai") + assert all("isbn" not in branch["properties"] for branch in items["anyOf"]) + + def test_the_pinned_id_reaches_every_branch(self): + items, _ = self.sent("openai") + assert all(targets_of(branch["properties"]["id"]) == ["e1"] for branch in items["anyOf"]) + + def test_a_profile_that_refuses_anyof_still_gets_the_pin(self): + items, _ = self.sent("anthropic") + assert "anyOf" not in items + assert targets_of(items["properties"]["worksFor"]) == ["e2"] + + def test_refusing_anyof_is_recorded_as_a_loss(self): + _, degradation = self.sent("anthropic") + assert degradation.dropped.get("anyOf") == 1 + assert degradation.fidelity < 1.0 + + def test_the_two_profiles_report_different_fidelity(self): + _, keeps = self.sent("openai") + _, loses = self.sent("anthropic") + assert loses.fidelity < keeps.fidelity + + +class TestAskingAgain: + """The first call that answered with the schema instead of an answer. + + gpt-5-nano returned the selection schema on 37 of 120 plan calls under A2 + segmented and on none at all under A2 single shot, because a single-shot arm + has no call whose answer is a structure. It costs the whole cell: the + classes the plan did not choose are the classes the later steps may not + answer with. + """ + + def test_a_schema_answer_is_asked_again(self): + client = MultiStepClient(detects=[SCHEMA_ECHO, {"entities": PLAN}]) + result = agent(client).run(request()) + assert result.selected == {"e1": ("Person",), "e2": ("Organization",)} + + def test_the_second_ask_is_logged_under_the_same_step(self): + """One extra call on the calls that failed, and countable, because an + arm that spends a call more than another and does not say so is + reported as cheaper than it was.""" + client = MultiStepClient(detects=[SCHEMA_ECHO, {"entities": PLAN}]) + result = agent(client).run(request()) + logged = [(c["step"], c["attempt"]) for c in result.calls.describe()["calls"]] + assert logged[:2] == [("detect", 1), ("detect", 2)] + + def test_it_hands_the_validator_s_reasons_back_verbatim(self): + """As an invalid extraction already does, so the retry rate stays a + measure of the model and not of how the advice was worded.""" + client = MultiStepClient(detects=[SCHEMA_ECHO, {"entities": PLAN}]) + agent(client).run(request()) + assert "does not satisfy the schema" in client.messages[1][-1].content + + def test_a_usable_answer_is_not_asked_again(self): + client = MultiStepClient() + agent(client).run(request()) + assert client.calls == 4 + + def test_an_answer_under_an_undeclared_wrapper_is_left_alone(self): + """Naming a schema stopped one provider rejecting it and started + another answering under that title. Those entities are usable, and + asking again would spend a call to replace a good answer.""" + client = MultiStepClient(detects=[{"EntityCandidates": PLAN}]) + result = agent(client).run(request()) + assert result.selected == {"e1": ("Person",), "e2": ("Organization",)} + assert client.calls == 4 + + def test_a_document_with_nothing_in_it_is_not_asked_again(self): + """An answer that validates and names no entity is a document with + nothing in it, not a failed call.""" + client = MultiStepClient(detects=[{"entities": []}]) + result = agent(client).run(request()) + assert client.calls == 1 + assert result.payload is None + + def test_an_answer_that_is_still_wrong_is_kept_as_it_came(self): + client = MultiStepClient(detects=[SCHEMA_ECHO, SCHEMA_ECHO]) + result = agent(client).run(request()) + assert client.calls == 2 + assert result.payload is None + + +class TestTheOtherOrchestrationsAreUnchanged: + def test_segmented_does_not_ask_again_by_default(self): + """There are grids depending on the three orchestrations already + measured, and a retry added to one of them would make the stored + numbers and the new ones different arms under one name.""" + client = MultiStepClient(detects=[SCHEMA_ECHO]) + ExtractionAgent( + client, + arm("A2", CATALOGUE), + profile_for("openai"), + Orchestration.SEGMENTED, + shortlist_k=2, + ).run(request()) + assert client.calls == 1 + + def test_segmented_asks_again_when_it_is_told_to(self): + """So the mitigation can be run on the orchestration it was not written + for. Without that, a multi-step arm beating a segmented one on a model + that echoes schemas would be reporting the retry as a property of the + pipeline.""" + client = MultiStepClient(detects=[SCHEMA_ECHO, {"entities": PLAN}]) + result = ExtractionAgent( + client, + arm("A2", CATALOGUE), + profile_for("openai"), + Orchestration.SEGMENTED, + shortlist_k=2, + plan_retry=True, + ).run(request()) + assert result.selected == {"e1": ("Person",), "e2": ("Organization",)} + + @pytest.mark.parametrize( + "orchestration", + [Orchestration.SINGLE_SHOT, Orchestration.SELECT_THEN_FILL, Orchestration.SEGMENTED], + ) + def test_only_multi_step_asks_again_unasked(self, orchestration): + built = ExtractionAgent(MultiStepClient(), arm("A2", CATALOGUE), profile_for("openai"), orchestration) + assert built.plan_retry is False + + def test_multi_step_asks_again_unasked(self): + assert agent(MultiStepClient()).plan_retry is True + + +class TestWhatItShares: + def test_a_missing_catalogue_is_refused(self): + bare = ExtractionAgent( + MultiStepClient(), + arm("A0-json"), + profile_for("openai"), + Orchestration.MULTI_STEP, + ) + with pytest.raises(ValueError, match="needs a catalogue"): + bare.run(request()) + + def test_a_candidate_outside_the_catalogue_is_dropped(self): + client = MultiStepClient( + plan=[{"id": "e1", "candidates": ["Invented", "Person"], "mention": "Ada"}], + fillable={"fillable": {"e1": ["name"]}}, + answers=[[{"id": "e1", "type": "Person"}]], + ) + result = agent(client).run(request()) + assert result.selected == {"e1": ("Person",)} + + def test_a_request_without_ranges_says_nothing_about_links(self): + client = MultiStepClient() + agent(client).run(request(ranges=None)) + assert "points at" not in client.messages[2][0].content diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index 760eb89..0d35832 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -187,13 +187,9 @@ def test_single_shot_still_makes_one_call(self): ExtractionAgent(client, arm("A4", CATALOGUE), profile_for("openai")).run(request()) assert client.calls == 1 - @pytest.mark.parametrize( - "orchestration", - [Orchestration.RECURSIVE, Orchestration.MULTI_STEP], - ) - def test_the_graph_orchestrations_say_they_are_not_ported(self, orchestration): + def test_the_recursive_orchestration_says_it_is_not_ported(self): with pytest.raises(NotImplementedError, match="entity graph"): - ExtractionAgent(TwoStepClient(), arm("A4", CATALOGUE), profile_for("openai"), orchestration) + ExtractionAgent(TwoStepClient(), arm("A4", CATALOGUE), profile_for("openai"), Orchestration.RECURSIVE) class MultiEntityClient: From a47b04976b6e1a1dafad88c9d6e87f3162ed9951 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 30 Sep 2026 15:19:19 +0200 Subject: [PATCH 26/58] fix(agent): say what one entity is in the detect prompt - the step asked for every entity and never defined one - it returned about one entity per property mention - haiku planned 7.6 entities for two-entity documents, nano 3.9 - now 3.67 and 2.80, and held-out seeds match the tuned-on ones - no count in the prompt; how many is the question being asked --- src/oold/agent/prompts.py | 36 +++++++++++++++++++++-- tests/test_agent/test_select_then_fill.py | 21 +++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index d5ed5ee..41c988d 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -39,12 +39,34 @@ _SCHEMA = "Each entity must conform to this schema:" -_SELECT_TASK = "Read the document and say, for every entity it describes, which classes it could be." +_SELECT_TASK = ( + "Read the document and say, for every entity it describes, which classes it could be. " + "An entity is a thing the document describes, not a statement about one. " + "A document that gives four properties of one thing describes one entity, not four, " + "so list a thing once however many times the document mentions it, and do not list " + "a property, a value or a field name as an entity of its own." +) +"""What to detect. + +The second and third sentences were added after measurement: without them the +step returns roughly one entity per property mention. Over 120 two-entity +documents haiku planned 7.6 entities per document and gpt-5-nano 3.9, and a +traced case returned four ``LodgingBusiness`` for the four fields stated about +one hotel and three ``Rating`` for the three stated about one rating. + +It says what an entity is and never how many there are. A count would be the +answer, and the step is being asked to find it. +""" _SELECT_FORM = ( "Answer with JSON only. For each entity give a short id, the classes it could " - "belong to, most likely first, and the words in the document you read it from." + "belong to, most likely first, and the words that identify it in the document." ) +"""How to answer. + +"The words that identify it" rather than the earlier "the words in the document +you read it from", which asked for a span and so invited one entry per span. +""" _SELECT_SHORTLIST = ( "List at most {k} classes per entity. Fewer is better when you are sure. " @@ -138,6 +160,11 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: is in the schema and not only in the wording, because a shortlist that can grow to the whole catalogue does not narrow the choice and the second step would gain nothing. + + ``entities`` carries no ``maxItems``. How many entities a document describes + is the question this step is asked, and capping it would answer it. The + over-segmentation the cap would hide is addressed in the wording instead, + at :data:`_SELECT_TASK`. """ return { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -162,7 +189,10 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: }, "mention": { "type": "string", - "description": "The words in the document this entity was read from.", + "description": ( + "The words that identify this entity, not the properties it carries. " + "Give the same entity one line however often the document mentions it." + ), }, }, "required": ["id", "candidates", "mention"], diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index 0d35832..83e49a9 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -316,3 +316,24 @@ def test_an_echoed_schema_is_not_an_answer(self): def test_a_lone_key_holding_scalars_is_not_a_wrapper(self): assert _entities_of({"candidates": ["Seat", "Book"]}) == [] + + +def test_the_select_prompt_says_what_one_entity_is(): + """The wording that stops the step returning one entity per mention. + + Asserted because the whole four-orchestration grid was scored on a prompt + that asked for "every entity it describes" and never said an entity is a + thing rather than a statement about one. Every orchestration lost to + single shot, and the detect step was planning 7.6 entities for a document + holding two. + + The count is deliberately absent. The step is asked how many entities a + document describes, so a prompt that said would be answering it. + """ + request = ExtractionRequest(document="anything", schema=None) + system = build_selection_messages(request, arm("A2", CATALOGUE), 3)[0].content + + assert "not a statement about one" in system + assert "one entity, not four" in system + for leak in ("two entities", "2 entities", "exactly two"): + assert leak not in system.lower() From cc7d5d7534cbf592aa32bce0e7182efa50f6d023 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Thu, 1 Oct 2026 10:16:53 +0200 Subject: [PATCH 27/58] feat(agent): add A2-strict and A4-strict, and ask for what is missing - with_structured_output never set strict, so a constraint was a hint - 589 recorded cells answered outside an enum the arm had pinned - decode_strict is a field; existing arms keep their meaning - strict reaches extract, repair, detect, property and insist - a required property the property step omits is asked for, not invented --- src/oold/agent/client.py | 1 + src/oold/agent/enforcement.py | 49 ++++++++++++++++ src/oold/agent/extraction.py | 70 +++++++++++++++++++++-- src/oold/agent/langchain_client.py | 7 ++- tests/test_agent/test_client.py | 2 +- tests/test_agent/test_enforcement.py | 18 ++++++ tests/test_agent/test_extraction.py | 2 +- tests/test_agent/test_multi_step.py | 65 ++++++++++++++++++++- tests/test_agent/test_segmented.py | 2 +- tests/test_agent/test_select_then_fill.py | 4 +- tests/test_agent/test_union.py | 2 +- tests/test_agent/test_validation_gate.py | 2 +- 12 files changed, 209 insertions(+), 15 deletions(-) diff --git a/src/oold/agent/client.py b/src/oold/agent/client.py index 0056ce8..dd45c46 100644 --- a/src/oold/agent/client.py +++ b/src/oold/agent/client.py @@ -136,6 +136,7 @@ def invoke( messages: Sequence[Message], *, response_format: dict[str, Any] | None = None, + strict: bool = False, ) -> ChatResponse: ... diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index fa99131..eb0b959 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -127,6 +127,36 @@ class Enforcement: output_form: OutputForm = OutputForm.JSON + decode_strict: bool = False + """Whether the decode constraint is a grammar or a hint. + + This is the difference between a schema the provider enforces and a schema + it is merely shown, and until it existed the benchmark could not tell them + apart. ``with_structured_output`` defaults to ``strict=False``, which sends + the schema in the request body and applies no grammar, so every arm named + for a decode-time constraint was measuring **schema in the prompt against + schema in the request body**, both of them presentation. + + It was not silent. Over 24,763 recorded cells, 589 answered with a value + outside an enum the arm had pinned, which a grammar makes impossible. The + leak is register-dependent: on generated quantity documents the enum + escaped 0.0 to 0.6 per cent of the time, and on Wikipedia sentences 13.1 + per cent, so the arms behaved almost exactly like enforcement where the + vocabulary was easy and noticeably less like it where it was not. + + A field rather than a change to the existing arms, because those arms + measured something real and the numbers stay interpretable under their + corrected name. ``A2-strict`` is the third rung. + + The cost is output volume, and it is the reason an orchestration exists. + :func:`~oold.agent.provider.prepare` makes every property required under a + strict subset, so a grammar forces a value for all of them: measured on one + schema.org document at gpt-5-nano, the whole catalogue emits **333 keys per + entity of which 25 are not null**, 5,456 output tokens, where the same + document through a narrowed fill schema emits 5 keys and 2,948. Schema + breadth stops predicting output volume and becomes it. + """ + validate_output: bool = False """Whether the answer is validated against the schema the arm declared. @@ -209,6 +239,7 @@ def describe(self) -> dict[str, object]: "catalogue_described": self.catalogue_text is not None, "catalogue_offered": self.catalogue is not None, "decode_constraint": self.decode_constraint.value, + "decode_strict": self.decode_strict, "commit_gate": self.commit_gate, "validate_output": self.validate_output, "repair_attempts": self.repair_attempts, @@ -252,6 +283,24 @@ def describe(self) -> dict[str, object]: validate_output=True, grounding=False, ), + "A2-strict": Enforcement( + schema_in_prompt=True, + catalogue=(), + decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, + decode_strict=True, + commit_gate=True, + validate_output=True, + grounding=False, + ), + "A4-strict": Enforcement( + schema_in_prompt=True, + catalogue=(), + decode_constraint=DecodeConstraint.JSON_SCHEMA_UNION, + decode_strict=True, + commit_gate=True, + validate_output=True, + grounding=False, + ), "A2-enforced-only": Enforcement( schema_in_prompt=False, catalogue=(), diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index c3ad5ee..6181608 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -16,6 +16,7 @@ import copy import json import re +from collections.abc import Callable from dataclasses import dataclass, field, replace from typing import Any @@ -173,8 +174,20 @@ def __init__( shortlist_k: int = 3, close_properties: bool = True, plan_retry: bool | None = None, + information: Callable[[str, str], Any] | None = None, ) -> None: self.client = client + self.information = information + """Asked for a required property the document does not state. + + ``(entity_key, property_name) -> value or None``. ``None`` leaves the + property out of the fill schema rather than forcing an invention, and + a caller that supplies nothing gets that behaviour by default. See + :meth:`_ask_for`.""" + self.asked: list[dict[str, str]] = [] + """Every escalation, in order, whether or not it was answered.""" + self.supplied: dict[str, dict[str, Any]] = {} + """What the caller answered, per entity.""" self.enforcement = enforcement self.profile = profile self.orchestration = orchestration @@ -246,7 +259,9 @@ def _single_shot( payload: Any | None = None for attempt in range(1, self.attempts + 1): with log.timed("extract", self.client.model, attempt=attempt, schema_sha256=digest) as sink: - reply = self.client.invoke(messages, response_format=response_format) + reply = self.client.invoke( + messages, response_format=response_format, strict=self.enforcement.decode_strict + ) sink.append(reply.usage or TokenUsage()) text = reply.text payload = reply.parsed if reply.parsed is not None else parse_json_answer(text) @@ -306,7 +321,7 @@ def _validate_and_repair( repairs += 1 turn = [*list(messages), repair_message(text, errors)] with log.timed("repair", self.client.model, attempt=repairs, schema_sha256=digest) as sink: - reply = self.client.invoke(turn, response_format=response_format) + reply = self.client.invoke(turn, response_format=response_format, strict=self.enforcement.decode_strict) sink.append(reply.usage or TokenUsage()) text = reply.text candidate = reply.parsed if reply.parsed is not None else parse_json_answer(text) @@ -543,7 +558,8 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: for (classes, kept), keys in groups.items(): narrowed = self.enforcement.with_catalogue(classes) filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) - keep = set(kept) | required + wanted = self._ask_for(keys, frozenset(required).difference(kept)) + keep = set(kept) | required.intersection(wanted) step = ExtractionRequest( document=request.document, schema=_trim_properties(request.schema, keep) if self.close_properties else request.schema, @@ -600,6 +616,48 @@ def _available_properties( available[entity.key] = names return available + def _ask_for(self, keys: list[str], missing: frozenset[str]) -> set[str]: + """Resolve a required property the document does not fill. + + The schema insists on it and the property step said the document does + not state it. Inventing a value is the one answer that is always + wrong, and it is what a strict decoder forces: a grammar over a + subset that makes every property required leaves the model no way to + decline. Before :attr:`Enforcement.decode_strict` this surfaced as + 14,526 recorded ``None is not one of [...]`` messages, which is the + same question arriving as a validation error instead of as a question. + + So the agent asks instead, through :attr:`information`. A caller that + can answer supplies the value; a caller that cannot leaves the + property out of the fill schema, which is the honest shape of "this + document does not say". The asking is recorded either way, because + whether an agent knew it needed to ask is the thing worth measuring + and it is invisible in a final answer that guessed. + + A benchmark answers mechanically from the corpus and a playground + asks the person sitting in front of it. Neither is the agent's + business, which is why this takes a callback rather than a policy. + """ + # The class slot and the id slot are required and are never the + # document's to state: the plan assigns the id and the shortlist + # decides the class, and _trim_properties keeps both regardless. A + # question about them would be the pipeline asking for what it is + # itself about to supply. + missing = frozenset(name for name in missing if name not in _CLASS_KEYS and name not in _ID_KEYS) + if not missing: + return set() + answered: set[str] = set() + for key in keys: + for name in sorted(missing): + self.asked.append({"entity": key, "property": name}) + if self.information is None: + continue + value = self.information(key, name) + if value is not None: + self.supplied.setdefault(key, {})[name] = value + answered.add(name) + return answered + def _choose_properties( self, request: ExtractionRequest, @@ -627,7 +685,7 @@ def _choose_properties( response_format = prepared if self.enforcement.decode_constraint is not DecodeConstraint.NONE else None with log.timed("properties", self.client.model, attempt=1, schema_sha256=schema_hash(prepared)) as sink: - reply = self.client.invoke(messages, response_format=response_format) + reply = self.client.invoke(messages, response_format=response_format, strict=self.enforcement.decode_strict) sink.append(reply.usage or TokenUsage()) answered = _fillable_of(reply.parsed if reply.parsed is not None else parse_json_answer(reply.text), available) @@ -679,7 +737,7 @@ def _select( response_format = prepared if self.enforcement.decode_constraint is not DecodeConstraint.NONE else None with log.timed(step, self.client.model, attempt=1, schema_sha256=schema_hash(prepared)) as sink: - reply = self.client.invoke(messages, response_format=response_format) + reply = self.client.invoke(messages, response_format=response_format, strict=self.enforcement.decode_strict) sink.append(reply.usage or TokenUsage()) payload = reply.parsed if reply.parsed is not None else parse_json_answer(reply.text) @@ -751,7 +809,7 @@ def _insist( turn = [*list(messages), repair_message(text, errors)] with log.timed(step, self.client.model, attempt=2, schema_sha256=digest) as sink: - reply = self.client.invoke(turn, response_format=response_format) + reply = self.client.invoke(turn, response_format=response_format, strict=self.enforcement.decode_strict) sink.append(reply.usage or TokenUsage()) retried = reply.parsed if reply.parsed is not None else parse_json_answer(reply.text) if retried is None: diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index 92a354a..165e7bf 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -69,13 +69,18 @@ def invoke( messages: Sequence[Message], *, response_format: dict[str, Any] | None = None, + strict: bool = False, ) -> ChatResponse: llm: Any = self._llm parsed: dict[str, Any] | None = None turns = fold_system_into_user(messages) if self.fold_system else [(m.role, m.content) for m in messages] if response_format is not None: - structured = llm.with_structured_output(response_format, include_raw=True) + # strict=False sends the schema and applies no grammar, which is + # the default and was never set. An arm that asked for a decode + # constraint got a hint; 589 recorded cells answered outside an + # enum the arm had pinned. + structured = llm.with_structured_output(response_format, include_raw=True, strict=strict or None) result = structured.invoke(turns) raw = result.get("raw") if isinstance(result, dict) else None parsing_error = result.get("parsing_error") if isinstance(result, dict) else None diff --git a/tests/test_agent/test_client.py b/tests/test_agent/test_client.py index 342721c..7f8ac4c 100644 --- a/tests/test_agent/test_client.py +++ b/tests/test_agent/test_client.py @@ -17,7 +17,7 @@ def __init__(self, usage: TokenUsage | None = None) -> None: self.usage = usage or TokenUsage(input_tokens=100, output_tokens=10) self.calls: list[tuple[Message, ...]] = [] - def invoke(self, messages, *, response_format=None) -> ChatResponse: + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: self.calls.append(tuple(messages)) return ChatResponse(text="ok", parsed=None, usage=self.usage) diff --git a/tests/test_agent/test_enforcement.py b/tests/test_agent/test_enforcement.py index 67dd477..ac5c127 100644 --- a/tests/test_agent/test_enforcement.py +++ b/tests/test_agent/test_enforcement.py @@ -32,10 +32,28 @@ def test_every_arm_exists(self): "A1", "A2", "A2-enforced-only", + "A2-strict", "A3", "A4", + "A4-strict", ] + def test_a_strict_arm_differs_from_its_base_only_in_the_grammar(self): + """Or the third rung would not be a rung on the same ladder. + + A2 and A2-strict send the same schema. The difference is whether the + provider enforces it or is merely shown it, which is what 589 cells + answering outside a pinned enum proved was never the case. + """ + for base, strict in (("A2", "A2-strict"), ("A4", "A4-strict")): + loose, tight = ARMS[base], ARMS[strict] + assert tight.decode_strict is True + assert loose.decode_strict is False + assert loose.schema_in_prompt == tight.schema_in_prompt + assert loose.decode_constraint == tight.decode_constraint + assert loose.commit_gate == tight.commit_gate + assert loose.validate_output == tight.validate_output + def test_the_union_arm_differs_from_the_enum_arm_only_in_the_constraint(self): """Or a measured difference has two candidate causes.""" enum_arm, union_arm = ARMS["A2"], ARMS["A4"] diff --git a/tests/test_agent/test_extraction.py b/tests/test_agent/test_extraction.py index ea4f6c4..b07d912 100644 --- a/tests/test_agent/test_extraction.py +++ b/tests/test_agent/test_extraction.py @@ -46,7 +46,7 @@ def __init__(self, text: str = '{"type": "quantities.Length", "value": 1.0}'): self.response_format = None self.calls = 0 - def invoke(self, messages, *, response_format=None): + def invoke(self, messages, *, response_format=None, strict=False): self.calls += 1 self.messages = list(messages) self.response_format = response_format diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index ebb5206..85510f8 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -12,6 +12,7 @@ """ import json +from dataclasses import replace import pytest @@ -112,7 +113,7 @@ def __init__(self, plan=None, fillable=None, answers=None, detects=None) -> None self.messages: list = [] self.calls = 0 - def invoke(self, messages, *, response_format=None) -> ChatResponse: + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: self.calls += 1 self.formats.append(response_format) self.messages.append(list(messages)) @@ -615,3 +616,65 @@ def test_a_request_without_ranges_says_nothing_about_links(self): client = MultiStepClient() agent(client).run(request(ranges=None)) assert "points at" not in client.messages[2][0].content + + +class TestAskingForWhatTheDocumentDoesNotSay: + """A required property the property step left out is a question, not a guess.""" + + @staticmethod + def _schema_requiring(name): + return { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "id": {"type": "string"}, + "value": {"type": "number"}, + name: {"type": "string"}, + }, + "required": ["type", name], + }, + } + }, + } + + def test_an_unfillable_required_property_is_asked_for_and_left_out(self): + """Inventing a value is the one answer that is always wrong. + + Under a strict grammar over a subset that makes every property + required, the model has no way to decline, so the agent has to decline + on its behalf. Left out of the fill schema is the honest shape of + "this document does not say". + """ + client = MultiStepClient() + built = agent(client) + built.run(replace(request(), schema=self._schema_requiring("serial"))) + + assert [a["property"] for a in built.asked] == ["serial"] * len(built.asked) + assert built.asked, "a required property the property step omitted was never asked for" + assert "serial" not in json.dumps(client.formats[-1]) + + def test_an_answered_question_puts_the_property_back(self): + """A caller that can supply it gets it filled rather than dropped. + + A benchmark answers mechanically from the corpus and a playground asks + the person in front of it; the agent only has to ask. + """ + client = MultiStepClient() + built = agent(client, information=lambda key, name: "SN-1") + built.run(replace(request(), schema=self._schema_requiring("serial"))) + + assert built.asked + assert "serial" in json.dumps(client.formats[-1]) + assert built.supplied and all("serial" in v for v in built.supplied.values()) + + def test_nothing_is_asked_when_the_document_fills_what_is_required(self): + """`name` is in the fixture's fillable set, so there is no question.""" + client = MultiStepClient() + built = agent(client) + built.run(replace(request(), schema=self._schema_requiring("name"))) + assert built.asked == [] diff --git a/tests/test_agent/test_segmented.py b/tests/test_agent/test_segmented.py index faa061d..3f51c76 100644 --- a/tests/test_agent/test_segmented.py +++ b/tests/test_agent/test_segmented.py @@ -97,7 +97,7 @@ def __init__(self, plan=None, answers=None) -> None: self.messages: list = [] self.calls = 0 - def invoke(self, messages, *, response_format=None) -> ChatResponse: + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: self.calls += 1 self.formats.append(response_format) self.messages.append(list(messages)) diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index 83e49a9..ec9d29e 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -54,7 +54,7 @@ def __init__(self, candidates=("Length", "Mass"), answer="Length") -> None: self.messages: list = [] self.calls = 0 - def invoke(self, messages, *, response_format=None) -> ChatResponse: + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: self.calls += 1 self.formats.append(response_format) self.messages.append(list(messages)) @@ -204,7 +204,7 @@ def __init__(self, first=("Length",), second=("Mass",)) -> None: self.messages: list = [] self.calls = 0 - def invoke(self, messages, *, response_format=None) -> ChatResponse: + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: self.calls += 1 self.formats.append(response_format) self.messages.append(list(messages)) diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index 86d93d7..d2d1762 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -49,7 +49,7 @@ class RecordingClient: def __init__(self) -> None: self.response_format = None - def invoke(self, messages, *, response_format=None) -> ChatResponse: + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: self.response_format = response_format return ChatResponse(text='{"entities": []}', parsed=None) diff --git a/tests/test_agent/test_validation_gate.py b/tests/test_agent/test_validation_gate.py index d5a5d38..a21eb8d 100644 --- a/tests/test_agent/test_validation_gate.py +++ b/tests/test_agent/test_validation_gate.py @@ -51,7 +51,7 @@ def __init__(self, *answers) -> None: self.turns: list[int] = [] self.last: list = [] - def invoke(self, messages, *, response_format=None) -> ChatResponse: + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: self.calls += 1 self.turns.append(len(messages)) self.last = list(messages) From a1d213863d3da76cc4806ae821955a98dcc802f5 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 4 Oct 2026 11:49:58 +0200 Subject: [PATCH 28/58] feat: catalogue_in_prompt separates the answer space from the prompt - catalogue was both the enum the grammar is built from and the list the prompt prints, so withholding it from the prompt emptied the grammar - off keeps one branch per class with its units and names none of them --- src/oold/agent/enforcement.py | 15 +++++++++++++++ src/oold/agent/prompts.py | 4 ++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index eb0b959..c85e154 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -172,6 +172,21 @@ class Enforcement: repairs, which measures conformance after help, and those are different claims, so the number is part of the condition.""" + catalogue_in_prompt: bool = True + """Whether the prompt names the classes at all. + + :attr:`catalogue` does two jobs: it is the answer space the decode-time + enum and the commit gate are built from, and it is what the prompt prints. + Dropping it to withhold the list also empties the grammar, so a condition + that wanted an enforced answer space and a silent prompt could not be + expressed. + + Off is that condition. The grammar still admits one branch per class with + that class's units, so nothing invalid can be produced; the prompt names + none of them. It asks whether a model needs to be told what it is choosing + among when it could not produce anything else. + """ + catalogue_text: tuple[str, ...] | None = None """What the catalogue looks like in the prompt, one rendered entry per class. diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 41c988d..e146c06 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -135,7 +135,7 @@ def build_messages(request: ExtractionRequest, enforcement: Enforcement) -> list sections.append(_PROSE_FORM if enforcement.output_form is OutputForm.PROSE else _JSON_FORM) - if enforcement.catalogue: + if enforcement.catalogue and enforcement.catalogue_in_prompt: # Rendered entries when the condition supplies them, identifiers # otherwise. The identifier stays the answer either way, so a rendered # entry has to carry its own. @@ -284,7 +284,7 @@ def build_selection_messages(request: ExtractionRequest, enforcement: Enforcemen """ sections: list[str] = [_SELECT_TASK, _SELECT_FORM, _SELECT_SHORTLIST.format(k=k)] - if enforcement.catalogue: + if enforcement.catalogue and enforcement.catalogue_in_prompt: entries = enforcement.catalogue_text or tuple(f"- {name}" for name in enforcement.catalogue) listed = "\n".join(entries) sections.append(f"{_CATALOGUE}\n{listed}") From 71494a99f354b8c1f6771e7a76a4e1feeb5a1b67 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 4 Oct 2026 21:16:29 +0200 Subject: [PATCH 29/58] refactor(agent): name arms by what they carry and enforce - composed names were not injective: A2, A2-strict and A3 shared one label, and A0-prose and A0-json shared another - qualifiers -prose, -gated, -strict, -grounded carry the three distinctions the two-part name could not - ArmName listed five of nine registered arms --- src/oold/agent/enforcement.py | 76 +++++++++++++------ tests/test_agent/test_enforcement.py | 67 ++++++++++------- tests/test_agent/test_extraction.py | 89 ++++++++++++++--------- tests/test_agent/test_multi_step.py | 23 +++--- tests/test_agent/test_prompts.py | 34 +++++---- tests/test_agent/test_segmented.py | 10 +-- tests/test_agent/test_select_then_fill.py | 23 ++++-- tests/test_agent/test_union.py | 18 ++--- tests/test_agent/test_validation_gate.py | 20 +++-- 9 files changed, 226 insertions(+), 134 deletions(-) diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index c85e154..496e292 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -144,9 +144,9 @@ class Enforcement: per cent, so the arms behaved almost exactly like enforcement where the vocabulary was easy and noticeably less like it where it was not. - A field rather than a change to the existing arms, because those arms - measured something real and the numbers stay interpretable under their - corrected name. ``A2-strict`` is the third rung. + A field rather than a change to the arms it qualifies, so a result + measured without a grammar keeps its own name and stays interpretable. + The rungs carrying it are suffixed ``-strict``. The cost is output volume, and it is the reason an orchestration exists. :func:`~oold.agent.provider.prepare` makes every property required under a @@ -263,10 +263,20 @@ def describe(self) -> dict[str, object]: } -ArmName = Literal["A0-prose", "A0-json", "A1", "A2", "A3"] +ArmName = Literal[ + "no-catalog-not-enforced-prose", + "no-catalog-not-enforced", + "schema-dump-catalog-not-enforced-gated", + "schema-dump-catalog-flat-enforced", + "schema-dump-catalog-flat-enforced-strict", + "schema-dump-catalog-flat-enforced-grounded", + "catalog-flat-enforced", + "schema-dump-catalog-enforced", + "schema-dump-catalog-enforced-strict", +] ARMS: dict[str, Enforcement] = { - "A0-prose": Enforcement( + "no-catalog-not-enforced-prose": Enforcement( schema_in_prompt=False, catalogue=None, decode_constraint=DecodeConstraint.NONE, @@ -274,7 +284,7 @@ def describe(self) -> dict[str, object]: grounding=False, output_form=OutputForm.PROSE, ), - "A0-json": Enforcement( + "no-catalog-not-enforced": Enforcement( schema_in_prompt=False, catalogue=None, decode_constraint=DecodeConstraint.NONE, @@ -282,7 +292,7 @@ def describe(self) -> dict[str, object]: grounding=False, output_form=OutputForm.JSON, ), - "A1": Enforcement( + "schema-dump-catalog-not-enforced-gated": Enforcement( schema_in_prompt=True, catalogue=(), decode_constraint=DecodeConstraint.NONE, @@ -290,7 +300,7 @@ def describe(self) -> dict[str, object]: validate_output=True, grounding=False, ), - "A2": Enforcement( + "schema-dump-catalog-flat-enforced": Enforcement( schema_in_prompt=True, catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, @@ -298,7 +308,7 @@ def describe(self) -> dict[str, object]: validate_output=True, grounding=False, ), - "A2-strict": Enforcement( + "schema-dump-catalog-flat-enforced-strict": Enforcement( schema_in_prompt=True, catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, @@ -307,7 +317,7 @@ def describe(self) -> dict[str, object]: validate_output=True, grounding=False, ), - "A4-strict": Enforcement( + "schema-dump-catalog-enforced-strict": Enforcement( schema_in_prompt=True, catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_UNION, @@ -316,7 +326,7 @@ def describe(self) -> dict[str, object]: validate_output=True, grounding=False, ), - "A2-enforced-only": Enforcement( + "catalog-flat-enforced": Enforcement( schema_in_prompt=False, catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, @@ -324,7 +334,7 @@ def describe(self) -> dict[str, object]: validate_output=True, grounding=False, ), - "A4": Enforcement( + "schema-dump-catalog-enforced": Enforcement( schema_in_prompt=True, catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_UNION, @@ -332,7 +342,7 @@ def describe(self) -> dict[str, object]: validate_output=True, grounding=False, ), - "A3": Enforcement( + "schema-dump-catalog-flat-enforced-grounded": Enforcement( schema_in_prompt=True, catalogue=(), decode_constraint=DecodeConstraint.JSON_SCHEMA_ENUM, @@ -341,18 +351,42 @@ def describe(self) -> dict[str, object]: grounding=True, ), } -"""The five arms, with an empty catalogue that a run fills in. - -A0 is two arms, not one. ``A0-json`` is the headline comparison, because -its output reduces to triples by the same path as every other arm and needs no -judge. ``A0-prose`` is reported beside it with the parse loss of its extractor -stated, so the objection that JSON is already a form of structure has an answer -in the results and not in the discussion. +"""The enforcement ladder, with an empty catalogue that a run fills in. + +A name is composed of what varies, so a table can be read without a legend:: + + -[-qualifiers] + +The first half is ``no-catalog``, ``catalog`` or ``schema-dump-catalog``: the +document alone, the document and the class list, or both plus the schema +printed out. ``catalog`` says only that the catalogue is in the prompt; how +much it says about each class is a property of the run and not of the arm, so +a report refines ``catalog`` to ``schema-prose-catalog`` or +``schema-prose-full-catalog`` from the condition that produced the cell. + +The second half is ``not-enforced``, ``flat-enforced`` or ``enforced``. +``flat-enforced`` pins each slot against its own enumeration, so a class and a +unit that cannot occur together are still both producible. ``enforced`` is an +``anyOf`` over one branch per class, where choosing the class chooses what the +other slots may hold. + +The qualifiers name the one further thing that arm fixes: ``-prose`` asks for +free text rather than JSON, ``-gated`` validates the answer and repairs it +without constraining generation, ``-strict`` sends the schema as a grammar +rather than as a request-body field, ``-grounded`` requires each value to be +traceable to the document. + +Two unenforced arms rather than one. ``no-catalog-not-enforced`` is the +headline comparison, because its output reduces to triples by the same path as +every other arm and needs no judge. ``no-catalog-not-enforced-prose`` is +reported beside it with the parse loss of its extractor stated, so the +objection that JSON is already a form of structure has an answer in the +results and not in the discussion. """ def arm(name: str, catalogue: tuple[str, ...] | None = None) -> Enforcement: - """One of the five arms, over a given catalogue.""" + """One rung of the ladder, over a given catalogue.""" if name not in ARMS: raise KeyError(f"unknown arm {name!r}, expected one of {sorted(ARMS)}") base = ARMS[name] diff --git a/tests/test_agent/test_enforcement.py b/tests/test_agent/test_enforcement.py index ac5c127..10e063c 100644 --- a/tests/test_agent/test_enforcement.py +++ b/tests/test_agent/test_enforcement.py @@ -27,25 +27,42 @@ def typed(**overrides) -> Enforcement: class TestArms: def test_every_arm_exists(self): assert sorted(ARMS) == [ - "A0-json", - "A0-prose", - "A1", - "A2", - "A2-enforced-only", - "A2-strict", - "A3", - "A4", - "A4-strict", + "catalog-flat-enforced", + "no-catalog-not-enforced", + "no-catalog-not-enforced-prose", + "schema-dump-catalog-enforced", + "schema-dump-catalog-enforced-strict", + "schema-dump-catalog-flat-enforced", + "schema-dump-catalog-flat-enforced-grounded", + "schema-dump-catalog-flat-enforced-strict", + "schema-dump-catalog-not-enforced-gated", ] + def test_an_arm_name_is_readable_without_a_legend(self): + """Every name composes from what varies, so a table needs no key. + + The first half names what the prompt carries and the second what the + decoder accepts. An arm whose name parses into neither is a rung + nobody can place in a result table. + """ + carries = ("no-catalog-", "catalog-", "schema-dump-catalog-") + accepts = ("not-enforced", "flat-enforced", "enforced") + for name in ARMS: + head = max((c for c in carries if name.startswith(c)), key=len) + rest = name[len(head) :] + assert any(rest.startswith(a) for a in accepts), name + def test_a_strict_arm_differs_from_its_base_only_in_the_grammar(self): """Or the third rung would not be a rung on the same ladder. - A2 and A2-strict send the same schema. The difference is whether the - provider enforces it or is merely shown it, which is what 589 cells - answering outside a pinned enum proved was never the case. + A rung and its ``-strict`` form send the same schema. The difference + is whether the provider enforces it or is merely shown it, which 589 + cells answering outside a pinned enum show is not the same thing. """ - for base, strict in (("A2", "A2-strict"), ("A4", "A4-strict")): + for base, strict in ( + ("schema-dump-catalog-flat-enforced", "schema-dump-catalog-flat-enforced-strict"), + ("schema-dump-catalog-enforced", "schema-dump-catalog-enforced-strict"), + ): loose, tight = ARMS[base], ARMS[strict] assert tight.decode_strict is True assert loose.decode_strict is False @@ -56,27 +73,27 @@ def test_a_strict_arm_differs_from_its_base_only_in_the_grammar(self): def test_the_union_arm_differs_from_the_enum_arm_only_in_the_constraint(self): """Or a measured difference has two candidate causes.""" - enum_arm, union_arm = ARMS["A2"], ARMS["A4"] + enum_arm, union_arm = ARMS["schema-dump-catalog-flat-enforced"], ARMS["schema-dump-catalog-enforced"] assert enum_arm.schema_in_prompt == union_arm.schema_in_prompt assert enum_arm.commit_gate == union_arm.commit_gate assert enum_arm.grounding == union_arm.grounding assert enum_arm.decode_constraint is not union_arm.decode_constraint def test_the_enforced_only_arm_differs_from_a2_only_in_what_is_shown(self): - shown, enforced = ARMS["A2"], ARMS["A2-enforced-only"] + shown, enforced = ARMS["schema-dump-catalog-flat-enforced"], ARMS["catalog-flat-enforced"] assert shown.decode_constraint is enforced.decode_constraint assert shown.schema_in_prompt is True assert enforced.schema_in_prompt is False def test_a0_offers_no_schema_and_no_catalogue(self): - for name in ("A0-prose", "A0-json"): + for name in ("no-catalog-not-enforced-prose", "no-catalog-not-enforced"): condition = ARMS[name] assert condition.schema_in_prompt is False assert condition.catalogue is None assert condition.commit_gate is False def test_the_two_a0_arms_differ_only_in_output_form(self): - prose, as_json = ARMS["A0-prose"], ARMS["A0-json"] + prose, as_json = ARMS["no-catalog-not-enforced-prose"], ARMS["no-catalog-not-enforced"] assert prose.output_form is OutputForm.PROSE assert as_json.output_form is OutputForm.JSON for field in ("schema_in_prompt", "catalogue", "commit_gate", "grounding"): @@ -84,7 +101,7 @@ def test_the_two_a0_arms_differ_only_in_output_form(self): def test_a1_to_a2_varies_only_the_decode_constraint(self): """The cheapest real contrast in the study, so nothing else may move.""" - a1, a2 = ARMS["A1"], ARMS["A2"] + a1, a2 = ARMS["schema-dump-catalog-not-enforced-gated"], ARMS["schema-dump-catalog-flat-enforced"] assert a1.decode_constraint is DecodeConstraint.NONE assert a2.decode_constraint is DecodeConstraint.JSON_SCHEMA_ENUM for field in ( @@ -97,7 +114,7 @@ def test_a1_to_a2_varies_only_the_decode_constraint(self): assert getattr(a1, field) == getattr(a2, field) def test_a2_to_a3_varies_only_grounding(self): - a2, a3 = ARMS["A2"], ARMS["A3"] + a2, a3 = ARMS["schema-dump-catalog-flat-enforced"], ARMS["schema-dump-catalog-flat-enforced-grounded"] assert a2.grounding is False assert a3.grounding is True for field in ( @@ -110,13 +127,13 @@ def test_a2_to_a3_varies_only_grounding(self): assert getattr(a2, field) == getattr(a3, field) def test_arm_applies_a_catalogue(self): - condition = arm("A2", ("a.B", "a.C")) + condition = arm("schema-dump-catalog-flat-enforced", ("a.B", "a.C")) assert condition.catalogue == ("a.B", "a.C") assert condition.catalogue_size == 2 def test_arm_refuses_a_catalogue_on_an_arm_that_offers_none(self): with pytest.raises(ValueError, match="offers no catalogue"): - arm("A0-json", ("a.B",)) + arm("no-catalog-not-enforced", ("a.B",)) def test_unknown_arm_is_refused(self): with pytest.raises(KeyError, match="unknown arm"): @@ -187,17 +204,17 @@ class TestClosingTheUnitSlot: """A quantity corpus enumerates the units each kind admits.""" def test_an_arm_carries_no_unit_enumeration_by_default(self): - assert arm("A2", ("Length",)).unit_catalogue is None + assert arm("schema-dump-catalog-flat-enforced", ("Length",)).unit_catalogue is None def test_units_can_be_set_without_touching_the_catalogue(self): - enforcement = arm("A2", ("Length",)).with_units(("meter", "foot")) + enforcement = arm("schema-dump-catalog-flat-enforced", ("Length",)).with_units(("meter", "foot")) assert enforcement.unit_catalogue == ("meter", "foot") assert enforcement.catalogue == ("Length",) def test_the_unit_enumeration_is_reported(self): """A closed slot nobody records looks like a free one.""" - described = arm("A2", ("Length",)).with_units(("meter", "foot")).describe() + described = arm("schema-dump-catalog-flat-enforced", ("Length",)).with_units(("meter", "foot")).describe() assert described["unit_catalogue_size"] == 2 def test_no_unit_enumeration_reports_zero(self): - assert arm("A2", ("Length",)).describe()["unit_catalogue_size"] == 0 + assert arm("schema-dump-catalog-flat-enforced", ("Length",)).describe()["unit_catalogue_size"] == 0 diff --git a/tests/test_agent/test_extraction.py b/tests/test_agent/test_extraction.py index b07d912..992ea35 100644 --- a/tests/test_agent/test_extraction.py +++ b/tests/test_agent/test_extraction.py @@ -61,7 +61,7 @@ def system(self) -> str: def agent(name: str, client: FakeClient, profile: str = "openai", **kwargs): - """An agent for one arm. A0 offers no catalogue, so it is not given one.""" + """An agent for one arm. An unenforced rung offers no catalogue, so it is not given one.""" condition = ARMS[name] if ARMS[name].catalogue is None else arm(name, CATALOGUE) return ExtractionAgent(client, condition, profile_for(profile), **kwargs) @@ -69,27 +69,32 @@ def agent(name: str, client: FakeClient, profile: str = "openai", **kwargs): class TestThePromptFollowsTheCondition: def test_a0_is_shown_no_schema_and_no_catalogue(self): client = FakeClient() - agent("A0-json", client).run(ExtractionRequest("doc", SCHEMA)) + agent("no-catalog-not-enforced", client).run(ExtractionRequest("doc", SCHEMA)) system = client.system() assert "schema" not in system.lower() assert "quantities.Length" not in system def test_a1_is_shown_the_catalogue_and_the_schema(self): client = FakeClient() - agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + agent("schema-dump-catalog-not-enforced-gated", client).run(ExtractionRequest("doc", SCHEMA)) system = client.system() assert "quantities.Length" in system assert "conform to this schema" in system def test_the_document_is_the_user_message_and_nothing_else(self): client = FakeClient() - agent("A2", client).run(ExtractionRequest("the document text", SCHEMA)) + agent("schema-dump-catalog-flat-enforced", client).run(ExtractionRequest("the document text", SCHEMA)) assert client.messages[1].content == "the document text" def test_the_shared_instruction_is_identical_across_arms(self): """Any wording difference between arms would be a confound.""" firsts = set() - for name in ("A0-json", "A1", "A2", "A3"): + for name in ( + "no-catalog-not-enforced", + "schema-dump-catalog-not-enforced-gated", + "schema-dump-catalog-flat-enforced", + "schema-dump-catalog-flat-enforced-grounded", + ): client = FakeClient() agent(name, client).run(ExtractionRequest("doc", SCHEMA)) firsts.add(client.system().split("\n\n")[0]) @@ -97,8 +102,10 @@ def test_the_shared_instruction_is_identical_across_arms(self): def test_prose_and_json_arms_ask_for_different_forms(self): prose, as_json = FakeClient(), FakeClient() - ExtractionAgent(prose, ARMS["A0-prose"], profile_for("openai")).run(ExtractionRequest("doc")) - agent("A0-json", as_json).run(ExtractionRequest("doc")) + ExtractionAgent(prose, ARMS["no-catalog-not-enforced-prose"], profile_for("openai")).run( + ExtractionRequest("doc") + ) + agent("no-catalog-not-enforced", as_json).run(ExtractionRequest("doc")) assert "prose" in prose.system().lower() assert "JSON" in as_json.system() @@ -106,34 +113,40 @@ def test_prose_and_json_arms_ask_for_different_forms(self): class TestTheDecodeConstraint: def test_a1_sends_no_response_format(self): client = FakeClient() - agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + agent("schema-dump-catalog-not-enforced-gated", client).run(ExtractionRequest("doc", SCHEMA)) assert client.response_format is None def test_a2_sends_one(self): client = FakeClient() - agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + agent("schema-dump-catalog-flat-enforced", client).run(ExtractionRequest("doc", SCHEMA)) assert client.response_format is not None def test_a2_pins_the_class_to_the_catalogue(self): client = FakeClient() - agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + agent("schema-dump-catalog-flat-enforced", client).run(ExtractionRequest("doc", SCHEMA)) assert client.response_format["properties"]["type"]["enum"] == list(CATALOGUE) def test_a_schema_with_no_class_slot_fails_loudly(self): """A silent no-op would run an arm unconstrained and call it constrained.""" client = FakeClient() with pytest.raises(ValueError, match="no class property to pin"): - agent("A2", client).run(ExtractionRequest("doc", {"type": "object", "properties": {"v": {}}})) + agent("schema-dump-catalog-flat-enforced", client).run( + ExtractionRequest("doc", {"type": "object", "properties": {"v": {}}}) + ) def test_the_schema_actually_sent_is_hashed(self): client = FakeClient() - result = agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + result = agent("schema-dump-catalog-flat-enforced", client).run(ExtractionRequest("doc", SCHEMA)) assert result.schema_sha256 and len(result.schema_sha256) == 64 def test_two_providers_get_different_schemas(self): """Preparation is part of the treatment, so it has to be recorded.""" - strict = agent("A2", FakeClient(), profile="anthropic").run(ExtractionRequest("doc", SCHEMA)) - lenient = agent("A2", FakeClient(), profile="openai").run(ExtractionRequest("doc", SCHEMA)) + strict = agent("schema-dump-catalog-flat-enforced", FakeClient(), profile="anthropic").run( + ExtractionRequest("doc", SCHEMA) + ) + lenient = agent("schema-dump-catalog-flat-enforced", FakeClient(), profile="openai").run( + ExtractionRequest("doc", SCHEMA) + ) assert strict.schema_sha256 != lenient.schema_sha256 assert strict.degradation is not None @@ -141,8 +154,8 @@ def test_two_providers_get_different_schemas(self): class TestGrounding: def test_a3_keeps_the_context_where_a2_drops_it(self): grounded = {"@context": {"x": "http://example.org/"}, **SCHEMA} - a2 = agent("A2", FakeClient()).run(ExtractionRequest("doc", grounded)) - a3 = agent("A3", FakeClient()).run(ExtractionRequest("doc", grounded)) + a2 = agent("schema-dump-catalog-flat-enforced", FakeClient()).run(ExtractionRequest("doc", grounded)) + a3 = agent("schema-dump-catalog-flat-enforced-grounded", FakeClient()).run(ExtractionRequest("doc", grounded)) assert a2.degradation.semantics_dropped > 0 assert a3.degradation.semantics_dropped == 0 @@ -150,25 +163,25 @@ def test_a3_keeps_the_context_where_a2_drops_it(self): class TestTheCommitGate: def test_an_entity_outside_the_catalogue_is_dropped(self): client = FakeClient('{"entities": [{"type": "quantities.Nonsense", "value": 1}]}') - result = agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + result = agent("schema-dump-catalog-not-enforced-gated", client).run(ExtractionRequest("doc", SCHEMA)) assert result.payload["entities"] == [] assert result.dropped == ["quantities.Nonsense"] def test_the_filtered_result_is_the_one_returned(self): """Keeping corrections and discarding removals is the predecessor's bug.""" client = FakeClient('{"entities": [{"type": "quantities.Length", "value": 1}, {"type": "Nope", "value": 2}]}') - result = agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + result = agent("schema-dump-catalog-not-enforced-gated", client).run(ExtractionRequest("doc", SCHEMA)) assert len(result.payload["entities"]) == 1 def test_an_unambiguous_suffix_is_corrected_not_dropped(self): client = FakeClient('{"entities": [{"type": "Length", "value": 1}]}') - result = agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + result = agent("schema-dump-catalog-not-enforced-gated", client).run(ExtractionRequest("doc", SCHEMA)) assert result.payload["entities"][0]["type"] == "quantities.Length" assert result.dropped == [] def test_a0_has_no_gate(self): client = FakeClient('{"type": "anything at all", "value": 1}') - result = agent("A0-json", client).run(ExtractionRequest("doc")) + result = agent("no-catalog-not-enforced", client).run(ExtractionRequest("doc")) assert result.payload["type"] == "anything at all" assert result.dropped == [] @@ -177,42 +190,46 @@ class TestTheAnswer: def test_a_fenced_answer_still_parses(self): """Models fence JSON even when told not to.""" client = FakeClient('```json\n{"type": "quantities.Length", "value": 1}\n```') - assert agent("A1", client).run(ExtractionRequest("doc", SCHEMA)).parsed + assert agent("schema-dump-catalog-not-enforced-gated", client).run(ExtractionRequest("doc", SCHEMA)).parsed def test_malformed_json_is_not_repaired(self): """Repairing it would hide a failure of the decode-time constraint.""" client = FakeClient('{"type": "Length", "value": ') - result = agent("A2", client).run(ExtractionRequest("doc", SCHEMA)) + result = agent("schema-dump-catalog-flat-enforced", client).run(ExtractionRequest("doc", SCHEMA)) assert result.parsed is False def test_a_prose_arm_is_not_asked_to_parse(self): client = FakeClient("The length was one metre.") - result = ExtractionAgent(client, ARMS["A0-prose"], profile_for("openai")).run(ExtractionRequest("doc")) + result = ExtractionAgent(client, ARMS["no-catalog-not-enforced-prose"], profile_for("openai")).run( + ExtractionRequest("doc") + ) assert result.text == "The length was one metre." assert client.calls == 1 def test_a_json_arm_retries_a_malformed_answer(self): client = FakeClient("not json at all") - agent("A1", client, attempts=3).run(ExtractionRequest("doc", SCHEMA)) + agent("schema-dump-catalog-not-enforced-gated", client, attempts=3).run(ExtractionRequest("doc", SCHEMA)) assert client.calls == 3 def test_a_good_answer_is_not_retried(self): client = FakeClient('{"type": "quantities.Length", "value": 1}') - agent("A1", client, attempts=3).run(ExtractionRequest("doc", SCHEMA)) + agent("schema-dump-catalog-not-enforced-gated", client, attempts=3).run(ExtractionRequest("doc", SCHEMA)) assert client.calls == 1 class TestTheRecord: def test_every_call_is_logged_with_its_tokens(self): client = FakeClient("not json") - result = agent("A1", client, attempts=2).run(ExtractionRequest("doc", SCHEMA)) + result = agent("schema-dump-catalog-not-enforced-gated", client, attempts=2).run( + ExtractionRequest("doc", SCHEMA) + ) assert len(result.calls) == 2 assert result.calls.totals().input_tokens == 200 assert [c.attempt for c in result.calls] == [1, 2] def test_the_record_is_serialisable(self): client = FakeClient() - described = agent("A2", client).run(ExtractionRequest("doc", SCHEMA)).describe() + described = agent("schema-dump-catalog-flat-enforced", client).run(ExtractionRequest("doc", SCHEMA)).describe() assert json.dumps(described) assert described["parsed"] is True @@ -220,14 +237,14 @@ def test_the_record_is_serialisable(self): class TestOrchestration: def test_single_shot_makes_one_call(self): client = FakeClient() - agent("A1", client).run(ExtractionRequest("doc", SCHEMA)) + agent("schema-dump-catalog-not-enforced-gated", client).run(ExtractionRequest("doc", SCHEMA)) assert client.calls == 1 def test_an_unported_orchestration_refuses_rather_than_pretending(self): with pytest.raises(NotImplementedError, match="not ported yet"): ExtractionAgent( FakeClient(), - ARMS["A1"], + ARMS["schema-dump-catalog-not-enforced-gated"], profile_for("openai"), Orchestration.RECURSIVE, ) @@ -260,7 +277,7 @@ def test_build_messages_needs_no_agent(): class TestPinningTheUnitSlot: - """A2 closes every slot the corpus closes, not only the class.""" + """A flat-enforced rung closes every slot the corpus closes, not only the class.""" SCHEMA = { "type": "object", @@ -290,23 +307,25 @@ def unit_slot(self, schema): return schema["properties"]["entities"]["items"]["properties"]["unit"] def test_the_unit_slot_is_pinned_when_units_are_offered(self): - schema = self.sent(arm("A2", ("Length",)).with_units(("meter", "foot"))) + schema = self.sent(arm("schema-dump-catalog-flat-enforced", ("Length",)).with_units(("meter", "foot"))) assert self.unit_slot(schema)["enum"] == ["meter", "foot"] def test_the_unit_slot_is_left_open_when_none_are_offered(self): """A corpus that does not close the slot is a condition, not a fault.""" - assert "enum" not in self.unit_slot(self.sent(arm("A2", ("Length",)))) + assert "enum" not in self.unit_slot(self.sent(arm("schema-dump-catalog-flat-enforced", ("Length",)))) def test_the_class_slot_is_still_pinned(self): - schema = self.sent(arm("A2", ("Length",)).with_units(("meter",))) + schema = self.sent(arm("schema-dump-catalog-flat-enforced", ("Length",)).with_units(("meter",))) assert schema["properties"]["entities"]["items"]["properties"]["type"]["enum"] == ["Length"] def test_an_unconstrained_arm_sends_no_schema_at_all(self): - assert self.sent(arm("A1", ("Length",)).with_units(("meter",))) is None + assert self.sent(arm("schema-dump-catalog-not-enforced-gated", ("Length",)).with_units(("meter",))) is None def test_a_schema_with_no_unit_slot_is_refused(self): client = FakeClient('{"entities": []}') - agent = ExtractionAgent(client, arm("A2", ("Length",)).with_units(("meter",)), profile_for("openai")) + agent = ExtractionAgent( + client, arm("schema-dump-catalog-flat-enforced", ("Length",)).with_units(("meter",)), profile_for("openai") + ) bare = {"type": "object", "properties": {"type": {"type": "string"}}} with pytest.raises(ValueError, match="no unit property"): agent.run(ExtractionRequest(document="d", schema=bare)) diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 85510f8..7cdc9c5 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -131,7 +131,7 @@ def invoke(self, messages, *, response_format=None, strict=False) -> ChatRespons ) -def agent(client, name="A2", profile="openai", k=2, **kwargs): +def agent(client, name="schema-dump-catalog-flat-enforced", profile="openai", k=2, **kwargs): return ExtractionAgent( client, arm(name, CATALOGUE), @@ -409,7 +409,7 @@ def test_a_range_no_planned_entity_fits_is_recorded_as_left_open(self): def test_an_unconstrained_arm_pins_no_reference(self): client = MultiStepClient() - agent(client, name="A1").run(request()) + agent(client, name="schema-dump-catalog-not-enforced-gated").run(request()) assert client.formats[2] is None @@ -453,7 +453,7 @@ def sent(self, profile): fillable={"fillable": {"e1": ["name", "worksFor"], "e2": ["name"]}}, answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}], [{"id": "e2", "type": "Organization"}]], ) - result = agent(client, name="A4", profile=profile).run(request()) + result = agent(client, name="schema-dump-catalog-enforced", profile=profile).run(request()) return items_of(client.formats[2]), result.degradation def test_a_profile_that_takes_anyof_keeps_the_union_and_the_pin(self): @@ -492,9 +492,10 @@ def test_the_two_profiles_report_different_fidelity(self): class TestAskingAgain: """The first call that answered with the schema instead of an answer. - gpt-5-nano returned the selection schema on 37 of 120 plan calls under A2 - segmented and on none at all under A2 single shot, because a single-shot arm - has no call whose answer is a structure. It costs the whole cell: the + gpt-5-nano returned the selection schema on 37 of 120 plan calls under a + segmented flat-enforced arm and on none at all under the same arm single + shot, because a single-shot arm has no call whose answer is a structure. + It costs the whole cell: the classes the plan did not choose are the classes the later steps may not answer with. """ @@ -557,7 +558,7 @@ def test_segmented_does_not_ask_again_by_default(self): client = MultiStepClient(detects=[SCHEMA_ECHO]) ExtractionAgent( client, - arm("A2", CATALOGUE), + arm("schema-dump-catalog-flat-enforced", CATALOGUE), profile_for("openai"), Orchestration.SEGMENTED, shortlist_k=2, @@ -572,7 +573,7 @@ def test_segmented_asks_again_when_it_is_told_to(self): client = MultiStepClient(detects=[SCHEMA_ECHO, {"entities": PLAN}]) result = ExtractionAgent( client, - arm("A2", CATALOGUE), + arm("schema-dump-catalog-flat-enforced", CATALOGUE), profile_for("openai"), Orchestration.SEGMENTED, shortlist_k=2, @@ -585,7 +586,9 @@ def test_segmented_asks_again_when_it_is_told_to(self): [Orchestration.SINGLE_SHOT, Orchestration.SELECT_THEN_FILL, Orchestration.SEGMENTED], ) def test_only_multi_step_asks_again_unasked(self, orchestration): - built = ExtractionAgent(MultiStepClient(), arm("A2", CATALOGUE), profile_for("openai"), orchestration) + built = ExtractionAgent( + MultiStepClient(), arm("schema-dump-catalog-flat-enforced", CATALOGUE), profile_for("openai"), orchestration + ) assert built.plan_retry is False def test_multi_step_asks_again_unasked(self): @@ -596,7 +599,7 @@ class TestWhatItShares: def test_a_missing_catalogue_is_refused(self): bare = ExtractionAgent( MultiStepClient(), - arm("A0-json"), + arm("no-catalog-not-enforced"), profile_for("openai"), Orchestration.MULTI_STEP, ) diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py index f55eb57..2a37bee 100644 --- a/tests/test_agent/test_prompts.py +++ b/tests/test_agent/test_prompts.py @@ -29,18 +29,18 @@ class TestTheShapeOfTheMessages: def test_the_document_is_the_user_message_and_nothing_else(self): """So a model that treats the last turn as the instruction cannot confuse the two.""" - messages = build_messages(request(), arm("A2", ("Length",))) + messages = build_messages(request(), arm("schema-dump-catalog-flat-enforced", ("Length",))) assert messages[1].role == "user" assert messages[1].content == "The reading was 1.0 meter." def test_the_task_sentence_is_identical_across_arms(self): """A difference in wording would be a difference nobody declared.""" - first = sections(arm("A1", ("Length",)))[0] - second = sections(arm("A2", ("Length",)))[0] + first = sections(arm("schema-dump-catalog-not-enforced-gated", ("Length",)))[0] + second = sections(arm("schema-dump-catalog-flat-enforced", ("Length",)))[0] assert first == second def test_an_arm_with_no_catalogue_gets_no_catalogue_section(self): - assert not any(s.startswith("Choose the class") for s in sections(arm("A0-json"))) + assert not any(s.startswith("Choose the class") for s in sections(arm("no-catalog-not-enforced"))) class TestWhatTheCatalogueLooksLike: @@ -52,12 +52,12 @@ class TestWhatTheCatalogueLooksLike: """ def test_identifiers_are_listed_when_no_text_is_supplied(self): - section = catalogue_section(arm("A2", ("Length", "Mass"))) + section = catalogue_section(arm("schema-dump-catalog-flat-enforced", ("Length", "Mass"))) assert "- Length" in section assert "- Mass" in section def test_rendered_entries_replace_the_bare_list(self): - enforcement = arm("A2", ("Length", "Mass")).with_catalogue_text(( + enforcement = arm("schema-dump-catalog-flat-enforced", ("Length", "Mass")).with_catalogue_text(( "- Length (Length)\n units: meter", "- Mass (Mass)\n units: gram", )) @@ -67,32 +67,38 @@ def test_rendered_entries_replace_the_bare_list(self): def test_the_identifier_survives_in_a_rendered_entry(self): """It is still the answer, however much else is shown.""" - enforcement = arm("A2", ("Length",)).with_catalogue_text(("- Length (Length)\n units: meter",)) + enforcement = arm("schema-dump-catalog-flat-enforced", ("Length",)).with_catalogue_text(( + "- Length (Length)\n units: meter", + )) assert "- Length" in catalogue_section(enforcement) def test_every_offered_class_reaches_the_prompt(self): names = tuple(f"C{i}" for i in range(40)) - enforcement = arm("A2", names).with_catalogue_text(tuple(f"- {n} (label {n})" for n in names)) + enforcement = arm("schema-dump-catalog-flat-enforced", names).with_catalogue_text( + tuple(f"- {n} (label {n})" for n in names) + ) section = catalogue_section(enforcement) assert all(f"- {n} (label {n})" in section for n in names) def test_a_described_catalogue_is_longer_than_a_bare_one(self): - bare = catalogue_section(arm("A2", ("Length",))) + bare = catalogue_section(arm("schema-dump-catalog-flat-enforced", ("Length",))) described = catalogue_section( - arm("A2", ("Length",)).with_catalogue_text(("- Length (Length)\n units: meter",)) + arm("schema-dump-catalog-flat-enforced", ("Length",)).with_catalogue_text(( + "- Length (Length)\n units: meter", + )) ) assert len(described) > len(bare) class TestWhatTheSchemaSectionCarries: def test_an_arm_that_shows_no_schema_has_no_schema_section(self): - assert not any(s.startswith("Each entity must conform") for s in sections(arm("A0-json"))) + assert not any(s.startswith("Each entity must conform") for s in sections(arm("no-catalog-not-enforced"))) def test_an_arm_that_shows_a_schema_carries_it_whole(self): schema = {"type": "object", "properties": {"unit": {"type": "string"}}} - content = build_messages(request(schema), arm("A1", ("Length",)))[0].content + content = build_messages(request(schema), arm("schema-dump-catalog-not-enforced-gated", ("Length",)))[0].content assert '"unit"' in content def test_the_gate_warning_appears_only_with_a_gate(self): - assert any("discarded" in s for s in sections(arm("A2", ("Length",)))) - assert not any("discarded" in s for s in sections(arm("A0-json"))) + assert any("discarded" in s for s in sections(arm("schema-dump-catalog-flat-enforced", ("Length",)))) + assert not any("discarded" in s for s in sections(arm("no-catalog-not-enforced"))) diff --git a/tests/test_agent/test_segmented.py b/tests/test_agent/test_segmented.py index 3f51c76..d6bb28c 100644 --- a/tests/test_agent/test_segmented.py +++ b/tests/test_agent/test_segmented.py @@ -112,7 +112,7 @@ def invoke(self, messages, *, response_format=None, strict=False) -> ChatRespons ) -def agent(client, name="A2", profile="openai", k=2): +def agent(client, name="schema-dump-catalog-flat-enforced", profile="openai", k=2): return ExtractionAgent( client, arm(name, CATALOGUE), @@ -228,7 +228,7 @@ def test_a_request_without_ranges_says_nothing_about_links(self): client = PlanThenFillClient() ExtractionAgent( client, - arm("A2", CATALOGUE), + arm("schema-dump-catalog-flat-enforced", CATALOGUE), profile_for("openai"), Orchestration.SEGMENTED, shortlist_k=2, @@ -355,7 +355,7 @@ def test_a_schema_with_no_entity_shape_is_refused(self): def test_an_unconstrained_arm_pins_no_reference(self): """The decode axis keeps meaning what it means everywhere else.""" client = PlanThenFillClient() - agent(client, name="A1").run(request()) + agent(client, name="schema-dump-catalog-not-enforced-gated").run(request()) assert client.formats[1] is None @@ -421,7 +421,7 @@ def sent(self, profile): plan=UNION_PLAN, answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}], [{"id": "e2", "type": "Organization"}]], ) - result = agent(client, name="A4", profile=profile).run(request()) + result = agent(client, name="schema-dump-catalog-enforced", profile=profile).run(request()) return items_of(client.formats[1]), result.degradation def test_a_profile_that_takes_anyof_keeps_the_union_and_the_pin(self): @@ -465,7 +465,7 @@ class TestWhatItShares: def test_a_missing_catalogue_is_refused(self): bare = ExtractionAgent( PlanThenFillClient(), - arm("A0-json"), + arm("no-catalog-not-enforced"), profile_for("openai"), Orchestration.SEGMENTED, ) diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index ec9d29e..5674b69 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -65,7 +65,7 @@ def invoke(self, messages, *, response_format=None, strict=False) -> ChatRespons return ChatResponse(text=json.dumps(payload), parsed=None) -def agent(client, k=2, name="A4"): +def agent(client, k=2, name="schema-dump-catalog-enforced"): return ExtractionAgent( client, arm(name, CATALOGUE), @@ -97,11 +97,11 @@ def test_the_mention_is_asked_for(self): def test_the_select_prompt_shows_the_same_catalogue(self): """The orchestrations differ in what is asked, not in what is shown.""" - content = build_selection_messages(request(), arm("A4", CATALOGUE), 2)[0].content + content = build_selection_messages(request(), arm("schema-dump-catalog-enforced", CATALOGUE), 2)[0].content assert all(f"- {name}" in content for name in CATALOGUE) def test_the_select_prompt_carries_the_document_alone(self): - messages = build_selection_messages(request(), arm("A4", CATALOGUE), 2) + messages = build_selection_messages(request(), arm("schema-dump-catalog-enforced", CATALOGUE), 2) assert messages[1].content == "The reading was 1.0 meter." @@ -176,7 +176,9 @@ def test_an_empty_shortlist_is_still_recorded(self): def test_a_missing_catalogue_is_refused(self): client = TwoStepClient() - bare = ExtractionAgent(client, arm("A0-json"), profile_for("openai"), Orchestration.SELECT_THEN_FILL) + bare = ExtractionAgent( + client, arm("no-catalog-not-enforced"), profile_for("openai"), Orchestration.SELECT_THEN_FILL + ) with pytest.raises(ValueError, match="needs a catalogue"): bare.run(request()) @@ -184,12 +186,17 @@ def test_a_missing_catalogue_is_refused(self): class TestTheOtherOrchestrations: def test_single_shot_still_makes_one_call(self): client = TwoStepClient() - ExtractionAgent(client, arm("A4", CATALOGUE), profile_for("openai")).run(request()) + ExtractionAgent(client, arm("schema-dump-catalog-enforced", CATALOGUE), profile_for("openai")).run(request()) assert client.calls == 1 def test_the_recursive_orchestration_says_it_is_not_ported(self): with pytest.raises(NotImplementedError, match="entity graph"): - ExtractionAgent(TwoStepClient(), arm("A4", CATALOGUE), profile_for("openai"), Orchestration.RECURSIVE) + ExtractionAgent( + TwoStepClient(), + arm("schema-dump-catalog-enforced", CATALOGUE), + profile_for("openai"), + Orchestration.RECURSIVE, + ) class MultiEntityClient: @@ -229,7 +236,7 @@ class TestOneCallPerShortlist: def run(self, client, k=2): return ExtractionAgent( client, - arm("A4", CATALOGUE), + arm("schema-dump-catalog-enforced", CATALOGUE), profile_for("openai"), Orchestration.SELECT_THEN_FILL, shortlist_k=k, @@ -331,7 +338,7 @@ def test_the_select_prompt_says_what_one_entity_is(): document describes, so a prompt that said would be answering it. """ request = ExtractionRequest(document="anything", schema=None) - system = build_selection_messages(request, arm("A2", CATALOGUE), 3)[0].content + system = build_selection_messages(request, arm("schema-dump-catalog-flat-enforced", CATALOGUE), 3)[0].content assert "not a statement about one" in system assert "one entity, not four" in system diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index d2d1762..75183f1 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -160,31 +160,31 @@ def sent(self, name, branches=BRANCHES, catalogue=("Length", "Mass")): return client.response_format def test_a4_sends_a_union_over_the_offered_classes(self): - items = self.sent("A4")["properties"]["entities"]["items"] + items = self.sent("schema-dump-catalog-enforced")["properties"]["entities"]["items"] assert [b["properties"]["type"]["const"] for b in items["anyOf"]] == ["Length", "Mass"] def test_a4_pairs_each_class_with_its_own_units(self): - items = self.sent("A4")["properties"]["entities"]["items"] + items = self.sent("schema-dump-catalog-enforced")["properties"]["entities"]["items"] by_class = {b["properties"]["type"]["const"]: b["properties"]["unit"]["enum"] for b in items["anyOf"]} assert by_class == {"Length": ["meter", "kilo_meter"], "Mass": ["gram", "kilo_gram"]} def test_a2_cannot_express_the_pairing(self): - items = self.sent("A2")["properties"]["entities"]["items"] + items = self.sent("schema-dump-catalog-flat-enforced")["properties"]["entities"]["items"] assert "anyOf" not in items assert items["properties"]["type"]["enum"] == ["Length", "Mass"] def test_a_class_outside_the_catalogue_is_not_offered(self): - items = self.sent("A4")["properties"]["entities"]["items"] + items = self.sent("schema-dump-catalog-enforced")["properties"]["entities"]["items"] assert "Volume" not in [b["properties"]["type"]["const"] for b in items["anyOf"]] def test_a_union_arm_without_branches_fails_loudly(self): """Running unconstrained would be reported as a finding about unions.""" with pytest.raises(ValueError, match="carried none"): - self.sent("A4", branches=None) + self.sent("schema-dump-catalog-enforced", branches=None) def test_a_union_arm_whose_classes_have_no_branch_fails_loudly(self): with pytest.raises(ValueError, match="admit nothing"): - self.sent("A4", catalogue=("Nonesuch",)) + self.sent("schema-dump-catalog-enforced", catalogue=("Nonesuch",)) class TestTheEnforcedOnlyArm: @@ -192,7 +192,7 @@ def test_it_sends_the_schema_without_showing_it(self): """The enum reaches the decoder and not the prompt, so reading it and being constrained by it stop being the same condition.""" client = RecordingClient() - agent = ExtractionAgent(client, arm("A2-enforced-only", ("Length", "Mass")), profile_for("openai")) + agent = ExtractionAgent(client, arm("catalog-flat-enforced", ("Length", "Mass")), profile_for("openai")) from oold.agent.prompts import build_messages request = ExtractionRequest(document="d", schema=SCHEMA, branches=BRANCHES) @@ -204,7 +204,7 @@ def test_it_sends_the_schema_without_showing_it(self): def test_it_still_offers_the_catalogue(self): from oold.agent.prompts import build_messages - content = build_messages(ExtractionRequest(document="d"), arm("A2-enforced-only", ("Length",)))[0].content + content = build_messages(ExtractionRequest(document="d"), arm("catalog-flat-enforced", ("Length",)))[0].content assert "- Length" in content @@ -218,7 +218,7 @@ class TestTheUnionReachesTheProviderTransform: def sent(self, profile): client = RecordingClient() - agent = ExtractionAgent(client, arm("A4", ("Length", "Mass")), profile_for(profile)) + agent = ExtractionAgent(client, arm("schema-dump-catalog-enforced", ("Length", "Mass")), profile_for(profile)) result = agent.run(ExtractionRequest(document="d", schema=SCHEMA, branches=BRANCHES)) return client.response_format, result.degradation diff --git a/tests/test_agent/test_validation_gate.py b/tests/test_agent/test_validation_gate.py index a21eb8d..7bf1e6c 100644 --- a/tests/test_agent/test_validation_gate.py +++ b/tests/test_agent/test_validation_gate.py @@ -11,7 +11,7 @@ from dataclasses import replace from oold.agent.client import ChatResponse -from oold.agent.enforcement import arm +from oold.agent.enforcement import ARMS, arm from oold.agent.extraction import ExtractionAgent from oold.agent.prompts import ExtractionRequest from oold.agent.provider import profile_for @@ -59,8 +59,8 @@ def invoke(self, messages, *, response_format=None, strict=False) -> ChatRespons return ChatResponse(text=self.answers[index], parsed=None) -def run(client, *, attempts=0, name="A1"): - base = arm(name) if name.startswith("A0") else arm(name, ("Length",)) +def run(client, *, attempts=0, name="schema-dump-catalog-not-enforced-gated"): + base = arm(name) if ARMS[name].catalogue is None else arm(name, ("Length",)) enforcement = replace(base, repair_attempts=attempts) agent = ExtractionAgent(client, enforcement, profile_for("openai")) return agent.run(ExtractionRequest(document="d", schema=SCHEMA)) @@ -85,15 +85,21 @@ def test_the_invalid_answer_is_kept_not_discarded(self): assert run(ScriptedClient(MISSING)).payload == MISSING def test_an_arm_that_does_not_validate_reports_nothing(self): - result = run(ScriptedClient(MISSING), name="A0-json") + result = run(ScriptedClient(MISSING), name="no-catalog-not-enforced") assert result.invalid == [] def test_the_arms_that_claim_a_commit_gate_validate(self): - for name in ("A1", "A2", "A2-enforced-only", "A3", "A4"): + for name in ( + "schema-dump-catalog-not-enforced-gated", + "schema-dump-catalog-flat-enforced", + "catalog-flat-enforced", + "schema-dump-catalog-flat-enforced-grounded", + "schema-dump-catalog-enforced", + ): assert arm(name, ("Length",)).validate_output is True def test_the_arms_that_claim_nothing_do_not(self): - for name in ("A0-json", "A0-prose"): + for name in ("no-catalog-not-enforced", "no-catalog-not-enforced-prose"): assert arm(name).validate_output is False @@ -174,7 +180,7 @@ def test_the_record_carries_the_errors_and_the_repair_count(self): assert described["invalid"] def test_the_condition_says_whether_it_validated(self): - described = arm("A1", ("Length",)).describe() + described = arm("schema-dump-catalog-not-enforced-gated", ("Length",)).describe() assert described["validate_output"] is True assert described["repair_attempts"] == 0 From 3b9b18ea32c2e1460d2739e108ef23082047c29c Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Tue, 6 Oct 2026 20:32:40 +0200 Subject: [PATCH 30/58] feat(agent): a public door onto each step of the pipeline - identify, available_properties, fillable_properties, extract, so a step can be run and scored alone against known-correct input - identify clears the mentions first; an agent reused across documents answered with a mention read from the one before --- src/oold/agent/extraction.py | 65 +++++++++++++++++++++++++ tests/test_agent/test_multi_step.py | 74 ++++++++++++++++++++++++++++- 2 files changed, 138 insertions(+), 1 deletion(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 6181608..3ba3e76 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -231,6 +231,71 @@ def run(self, request: ExtractionRequest) -> ExtractionResult: return self._select_then_fill(request) return self._single_shot(request) + def identify( + self, + request: ExtractionRequest, + log: CallLog | None = None, + *, + step: str = "detect", + insist: bool = False, + ) -> tuple[dict[str, tuple[str, ...]], dict[str, str]]: + """One step: which classes each entity could be, and what it is called. + + The first of the four steps, reachable on its own so it can be scored + on its own. An orchestration runs it and spends more calls on what + follows; a benchmark wants the answer before anything was spent. + + Returns the shortlist per entity and the mention each was read from, + which is the input the next step needs. + """ + # Cleared first, because an agent reused across documents would + # otherwise answer with a mention read from the one before. + self._mentions = {} + selected, _ = self._select(request, log if log is not None else CallLog(), step=step, insist=insist) + return selected, dict(self._mentions) + + def available_properties( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + ) -> dict[str, tuple[str, ...]]: + """What each planned entity may carry, before the document is read.""" + return self._available_properties(request, plan) + + def fillable_properties( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + log: CallLog | None = None, + ) -> dict[str, tuple[str, ...]]: + """Step two on its own: which of those properties the document fills. + + ``plan`` is whatever the caller has. A benchmark hands it the true + classes so the step is scored on its own question rather than on the + one before it. + """ + return self._choose_properties( + request, + log if log is not None else CallLog(), + plan, + self._available_properties(request, plan), + ) + + def extract( + self, + request: ExtractionRequest, + *, + plan: tuple[PlannedEntity, ...] = (), + filling: tuple[str, ...] = (), + ) -> ExtractionResult: + """Step three on its own: fill the schema the first two steps implied. + + With a plan, the id slot is pinned to ``filling`` and a reference slot + to the planned entities whose class fits its range, which is what + makes an edge nameable. Without one, this is the single-shot arm. + """ + return self._single_shot(request, plan=plan, filling=filling) + def _single_shot( self, request: ExtractionRequest, diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 7cdc9c5..e5abd4d 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -18,7 +18,7 @@ from oold.agent.client import ChatResponse, TokenUsage from oold.agent.enforcement import Orchestration, arm -from oold.agent.extraction import Edge, ExtractionAgent +from oold.agent.extraction import Edge, ExtractionAgent, PlannedEntity from oold.agent.prompts import ExtractionRequest, property_schema from oold.agent.provider import profile_for @@ -681,3 +681,75 @@ def test_nothing_is_asked_when_the_document_fills_what_is_required(self): built = agent(client) built.run(replace(request(), schema=self._schema_requiring("name"))) assert built.asked == [] + + +class TestEachStepAlone: + """A pipeline whose steps cannot be run apart cannot be attributed. + + The four steps already exist inside the orchestrations. These are the + public doors onto them, so a benchmark can hand one step known-correct + input and score it on its own question rather than on the one before it. + """ + + def test_identify_returns_the_shortlist_and_the_mention(self): + client = MultiStepClient() + selected, mentions = agent(client).identify(request()) + assert selected == {"e1": ("Person",), "e2": ("Organization",)} + assert mentions == {"e1": "Ada", "e2": "Acme"} + assert client.calls == 1, "identify is one call and nothing after it" + + def test_identify_does_not_carry_a_mention_between_documents(self): + """An agent reused across documents would otherwise answer with a + mention read from the one before.""" + one = agent(MultiStepClient()) + one.identify(request()) + one.client = MultiStepClient( + detects=[{"entities": [{"id": "e9", "candidates": ["Book"], "mention": "Ulysses"}]}] + ) + _, mentions = one.identify(request()) + assert mentions == {"e9": "Ulysses"} + + def test_fillable_properties_takes_the_plan_it_is_given(self): + client = MultiStepClient(detects=[]) + plan = ( + PlannedEntity(key="e1", classes=("Person",), mention="Ada"), + PlannedEntity(key="e2", classes=("Organization",), mention="Acme"), + ) + assert agent(client).fillable_properties(request(), plan) == {"e1": ("name", "worksFor"), "e2": ("name",)} + + def test_available_properties_is_what_the_step_may_choose_from(self): + """The union over the shortlist, so a step scored on its choice is + scored against what it was actually offered.""" + plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) + available = agent(MultiStepClient()).available_properties(request(), plan) + assert set(available["e1"]) == {"name", "jobTitle", "worksFor"} + + def test_extract_pins_the_id_to_the_entities_the_call_is_for(self): + """Without this the answer cannot be joined back to the plan, and + every edge reads as dangling.""" + client = MultiStepClient(detects=[]) + plan = ( + PlannedEntity(key="e1", classes=("Person",), mention="Ada"), + PlannedEntity(key="e2", classes=("Organization",), mention="Acme"), + ) + agent(client).extract(request(), plan=plan, filling=("e1",)) + assert _id_slot(client.formats[-1])["enum"] == ["e1"] + + def test_extract_without_a_plan_is_the_single_shot_arm(self): + client = MultiStepClient(detects=[]) + result = agent(client).extract(request()) + assert result.payload is not None + assert _id_slot(client.formats[-1]) is None + + +def _id_slot(schema): + """The id property of whichever entity shape the request carried.""" + if not isinstance(schema, dict): + return None + if "id" in (schema.get("properties") or {}) and schema.get("type") == "object": + return schema["properties"]["id"] + for value in list((schema.get("properties") or {}).values()) + schema.get("anyOf", []) + [schema.get("items")]: + found = _id_slot(value) + if found is not None: + return found + return None From 31dc6e167534295da331e3b26f6ddce9df73d137 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 7 Oct 2026 05:29:12 +0200 Subject: [PATCH 31/58] fix(prompts): the property step was told to include when unsure - only the cost of leaving a property out was stated, so a step unsure about one put it in: 21 named that the document does not state against 6 missed, measured at gpt-5-nano - both costs now, and stated means the value is in the text rather than made likely by it --- src/oold/agent/prompts.py | 16 ++++++++++++++-- tests/test_agent/test_prompts.py | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index e146c06..6506cd4 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -77,7 +77,9 @@ _PROPERTY_TASK = ( "Read the document and say, for each entity listed below, which of its own " - "properties the document gives a value for." + "properties the document states a value for. A property is stated when the " + "value is there in the text to be read, not when the document makes it " + "likely or when the entity would usually have one." ) _PROPERTY_FORM = ( @@ -86,8 +88,18 @@ ) _PROPERTY_HONESTY = ( - "Leave out a property whose value you would have to invent. A property you leave out will not be asked for again." + "Both ways of being wrong cost something. A property you leave out will not be asked for again, " + "so a value that is there is lost. A property you name will be asked for next, and if the " + "document does not state it the answer has to be invented or left empty. Name the ones you " + "could point at in the text." ) +"""Both costs, because naming one was the only one stated. + +Measured on the Wikidata-schema.org corpus at gpt-5-nano: 21 properties +named that the document does not state against 6 missed, better than three +to one. A step told only that omission is irreversible has been told to +include when unsure, which is what it did. +""" _PROPERTY_ENTITIES = "The entities, with the properties each one may carry:" diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py index 2a37bee..99d5991 100644 --- a/tests/test_agent/test_prompts.py +++ b/tests/test_agent/test_prompts.py @@ -102,3 +102,30 @@ def test_an_arm_that_shows_a_schema_carries_it_whole(self): def test_the_gate_warning_appears_only_with_a_gate(self): assert any("discarded" in s for s in sections(arm("schema-dump-catalog-flat-enforced", ("Length",)))) assert not any("discarded" in s for s in sections(arm("no-catalog-not-enforced"))) + + +class TestThePropertyStepStatesBothCosts: + """A step told only that omission is irreversible will include when unsure. + + Measured before this: 21 properties named that the document does not + state against 6 missed. The prompt named the cost of leaving one out and + no cost for putting one in, so the step did what it was told. + """ + + def _system(self) -> str: + from oold.agent.prompts import build_property_messages + + messages = build_property_messages(ExtractionRequest(document="d"), {"e1": ("name", "award")}) + return messages[0].content + + def test_naming_one_too_many_has_a_stated_cost(self): + system = self._system() + assert "invented or left empty" in system + + def test_leaving_one_out_still_has_its_cost(self): + assert "will not be asked for again" in self._system() + + def test_it_asks_for_what_is_in_the_text_not_what_is_likely(self): + """ "The collection of Tate Britain" makes a location likely, which is + not the same as the document stating one.""" + assert "not when the document makes it" in self._system() From 621a270acfd2cb9edc92d709e9102170e467fe88 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 7 Oct 2026 05:50:02 +0200 Subject: [PATCH 32/58] feat(prompts): the property step points at the words it read - each answer item is the property and the text stating it; the quotation is never validated or graded - asked for because every one of six models named more properties than the document states than it missed, by five to eighteen to one - a bare name is still read, so an older answer shape still answers --- src/oold/agent/extraction.py | 21 ++++++++++++- src/oold/agent/prompts.py | 26 +++++++++++++--- tests/test_agent/test_multi_step.py | 48 +++++++++++++++++++++++++++-- 3 files changed, 87 insertions(+), 8 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 3ba3e76..9f17765 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -755,7 +755,7 @@ def _choose_properties( answered = _fillable_of(reply.parsed if reply.parsed is not None else parse_json_answer(reply.text), available) return { - key: tuple(name for name in names if name in set(answered.get(key) or ())) + key: tuple(name for name in names if name in _named_in(answered.get(key) or ())) for key, names in available.items() } @@ -1318,6 +1318,25 @@ def _fillable_of(payload: Any, available: dict[str, tuple[str, ...]]) -> dict[st return {} +def _named_in(answered: Any) -> set[str]: + """The property names in one entity's answer. + + Each item is the property and the words the document states it in. The + quotation is not read: it is asked for so the step has to point at the + text, and reading it would make an unvalidated string part of the answer. + + A bare name is still accepted, because a model that answers the older + shape has answered the question. + """ + found: set[str] = set() + for item in answered if isinstance(answered, list) else (): + if isinstance(item, str): + found.add(item) + elif isinstance(item, dict) and isinstance(item.get("property"), str): + found.add(item["property"]) + return found + + def _accepts_null(slot: Any) -> bool: """Whether a prepared slot was left able to say nothing.""" if not isinstance(slot, dict): diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 6506cd4..cfe7fae 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -220,8 +220,15 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: """The answer shape the property step asks for. - One array per entity, whose items enumerate **that entity's own** property - names. Pooling every entity's properties into one enumeration would let one + One array per entity, whose items name **that entity's own** properties + and, with each, the words in the document that state it. + + The quotation is never read: nothing validates it, nothing grades it, and + the step's answer is the property names alone. It is asked for because a + model that has to point at the text names fewer properties the text does + not support. Measured across six models before it existed, every one + named more properties than the document states than it missed, by between + five and eighteen to one. Pooling every entity's properties into one enumeration would let one entity be given another's property, which is the thing a per-entity enumeration is for, and it is the same argument that makes the fill step group by shortlist rather than pool the candidate classes. @@ -247,8 +254,19 @@ def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: key: { "type": "array", "maxItems": len(names), - "items": {"type": "string", "enum": list(names)}, - "description": f"The properties of {key} the document gives a value for.", + "items": { + "type": "object", + "properties": { + "property": {"type": "string", "enum": list(names)}, + "stated": { + "type": "string", + "description": "The words in the document that state it.", + }, + }, + "required": ["property", "stated"], + "additionalProperties": False, + }, + "description": f"The properties of {key} the document states, each with the words stating it.", } for key, names in offered.items() }, diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index e5abd4d..3eed3ad 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -74,7 +74,15 @@ {"id": "e2", "candidates": ["Organization"], "mention": "Acme"}, ] -FILLABLE = {"fillable": {"e1": ["name", "worksFor"], "e2": ["name"]}} +FILLABLE = { + "fillable": { + "e1": [ + {"property": "name", "stated": "Ada"}, + {"property": "worksFor", "stated": "Acme"}, + ], + "e2": [{"property": "name", "stated": "Acme"}], + } +} EXTRACTED = [ [{"id": "e1", "type": "Person", "name": "Ada", "worksFor": "e2"}], @@ -163,9 +171,12 @@ def targets_of(slot): def enums_of(response_format): - """The property enumeration each entity was offered, per entity.""" + """The property enumeration each entity was offered, per entity. + + Each item is the property and the words the document states it in, so the + enumeration sits on the property rather than on the item.""" offered = response_format["properties"]["fillable"]["properties"] - return {key: slot["items"]["enum"] for key, slot in offered.items()} + return {key: slot["items"]["properties"]["property"]["enum"] for key, slot in offered.items()} class TestTheCallsItMakes: @@ -753,3 +764,34 @@ def _id_slot(schema): if found is not None: return found return None + + +class TestPointingAtTheText: + """The step has to quote the words it read a property from. + + Never validated and never graded: the answer is the property names alone. + It is asked for because a model that has to point at the text names fewer + properties the text does not support. + """ + + def test_the_quotation_is_required_of_the_answer(self): + from oold.agent.prompts import property_schema + + item = property_schema({"e1": ("name",)})["properties"]["fillable"]["properties"]["e1"]["items"] + assert item["required"] == ["property", "stated"] + + def test_the_quotation_is_not_part_of_the_answer(self): + client = MultiStepClient(detects=[]) + plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) + assert agent(client).fillable_properties(request(), plan) == {"e1": ("name", "worksFor")} + + def test_a_bare_name_is_still_read(self): + """A model answering the older shape has answered the question.""" + client = MultiStepClient(detects=[], fillable={"fillable": {"e1": ["name"]}}) + plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) + assert agent(client).fillable_properties(request(), plan) == {"e1": ("name",)} + + def test_an_item_naming_no_property_is_dropped(self): + client = MultiStepClient(detects=[], fillable={"fillable": {"e1": [{"stated": "Ada"}]}}) + plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) + assert agent(client).fillable_properties(request(), plan) == {"e1": ()} From 97a37b1a56261732568a0bee75da160aa868d105 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 7 Oct 2026 06:01:21 +0200 Subject: [PATCH 33/58] fix(prompts): say the rule the corpus applies, and drop the quotation - a property is stated when its value appears in the text in some spelling; six models asked a looser question answered six ways - requiring the words that state it did not reduce invention and cost recall: deepseek and nano invented more, gpt-oss lost a third of its correct answers and sonnet over half - the reader still accepts an answer that volunteers one --- src/oold/agent/prompts.py | 43 ++++++++++++++--------------- tests/test_agent/test_multi_step.py | 24 ++++++++-------- tests/test_agent/test_prompts.py | 11 +++++--- 3 files changed, 38 insertions(+), 40 deletions(-) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index cfe7fae..0028a5f 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -78,9 +78,17 @@ _PROPERTY_TASK = ( "Read the document and say, for each entity listed below, which of its own " "properties the document states a value for. A property is stated when the " - "value is there in the text to be read, not when the document makes it " - "likely or when the entity would usually have one." + "value itself appears in the text, in some spelling of it. A property the " + "document makes likely, or that the entity would usually have, is not " + "stated, and neither is one whose value you would have to supply." ) +"""The rule the corpus actually applies, said out loud. + +Ground truth here is a value whose spelling was found in the document. Six +models asked a looser question answered it six different ways, which is a +prompt that has not said what it wants rather than a disagreement between +models. +""" _PROPERTY_FORM = ( "Answer with JSON only. Give one list of property names per entity, under that entity's id, " @@ -220,15 +228,15 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: """The answer shape the property step asks for. - One array per entity, whose items name **that entity's own** properties - and, with each, the words in the document that state it. + One array per entity, whose items enumerate **that entity's own** property + names. - The quotation is never read: nothing validates it, nothing grades it, and - the step's answer is the property names alone. It is asked for because a - model that has to point at the text names fewer properties the text does - not support. Measured across six models before it existed, every one - named more properties than the document states than it missed, by between - five and eighteen to one. Pooling every entity's properties into one enumeration would let one + Names alone. Asking for the words that state each property as well does + not reduce invention and costs recall: measured over six models, + deepseek-v3.2 and gpt-5-nano invented *more* with a quotation required, + while gpt-oss-120b lost a third of its correct answers and + claude-sonnet-5 over half. Raising the cost of answering is not the same + as raising the cost of guessing. Pooling every entity's properties into one enumeration would let one entity be given another's property, which is the thing a per-entity enumeration is for, and it is the same argument that makes the fill step group by shortlist rather than pool the candidate classes. @@ -254,19 +262,8 @@ def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: key: { "type": "array", "maxItems": len(names), - "items": { - "type": "object", - "properties": { - "property": {"type": "string", "enum": list(names)}, - "stated": { - "type": "string", - "description": "The words in the document that state it.", - }, - }, - "required": ["property", "stated"], - "additionalProperties": False, - }, - "description": f"The properties of {key} the document states, each with the words stating it.", + "items": {"type": "string", "enum": list(names)}, + "description": f"The properties of {key} the document states a value for.", } for key, names in offered.items() }, diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 3eed3ad..29f6611 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -171,12 +171,9 @@ def targets_of(slot): def enums_of(response_format): - """The property enumeration each entity was offered, per entity. - - Each item is the property and the words the document states it in, so the - enumeration sits on the property rather than on the item.""" + """The property enumeration each entity was offered, per entity.""" offered = response_format["properties"]["fillable"]["properties"] - return {key: slot["items"]["properties"]["property"]["enum"] for key, slot in offered.items()} + return {key: slot["items"]["enum"] for key, slot in offered.items()} class TestTheCallsItMakes: @@ -766,21 +763,22 @@ def _id_slot(schema): return None -class TestPointingAtTheText: - """The step has to quote the words it read a property from. +class TestReadingTheAnswer: + """Names alone, and an answer that carries more is still read. - Never validated and never graded: the answer is the property names alone. - It is asked for because a model that has to point at the text names fewer - properties the text does not support. + A quotation was required for a while, to make the step point at the text. + It did not reduce invention and it cost the cautious models their recall, + so the schema asks for names; the reader stays tolerant because a model + may volunteer more than it was asked for. """ - def test_the_quotation_is_required_of_the_answer(self): + def test_the_answer_is_names_alone(self): from oold.agent.prompts import property_schema item = property_schema({"e1": ("name",)})["properties"]["fillable"]["properties"]["e1"]["items"] - assert item["required"] == ["property", "stated"] + assert item == {"type": "string", "enum": ["name"]} - def test_the_quotation_is_not_part_of_the_answer(self): + def test_an_answer_carrying_a_quotation_is_still_read(self): client = MultiStepClient(detects=[]) plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) assert agent(client).fillable_properties(request(), plan) == {"e1": ("name", "worksFor")} diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py index 99d5991..735f43e 100644 --- a/tests/test_agent/test_prompts.py +++ b/tests/test_agent/test_prompts.py @@ -125,7 +125,10 @@ def test_naming_one_too_many_has_a_stated_cost(self): def test_leaving_one_out_still_has_its_cost(self): assert "will not be asked for again" in self._system() - def test_it_asks_for_what_is_in_the_text_not_what_is_likely(self): - """ "The collection of Tate Britain" makes a location likely, which is - not the same as the document stating one.""" - assert "not when the document makes it" in self._system() + def test_it_states_the_rule_the_corpus_applies(self): + """Ground truth is a value whose spelling was found in the document. + Six models asked a looser question answered it six different ways, + which is a prompt that has not said what it wants.""" + system = self._system() + assert "appears in the text, in some spelling of it" in system + assert "would usually have, is not" in system From c93db821970fed95206e3d9a80dc5e9339acc3b4 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 7 Oct 2026 06:18:45 +0200 Subject: [PATCH 34/58] feat(prompts): the property step is shown what the names mean - ExtractionRequest.property_text, rendered one property per line by the step that chooses between them and by no other - a vocabulary question cannot be answered by rewording the question: six models reach recall 0.92 at precision 0.55, finding the values and filing them under the wrong slot --- src/oold/agent/prompts.py | 23 ++++++++++++++++++++++- tests/test_agent/test_prompts.py | 27 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 0028a5f..b59afd7 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -118,6 +118,17 @@ class ExtractionRequest: document: str schema: dict[str, Any] | None = None + property_text: Mapping[str, str] | None = None + """What each property name means, for the step that chooses between them. + + Names alone do not say whether the gallery holding a painting is its + ``contentLocation`` or its ``provider``. Measured over six models at + n=100, the property step reaches a recall of 0.92 at a precision of 0.55: + it finds the values and files them under the wrong slot, and no wording + of the question fixes a vocabulary it was never shown. + + Read by that step alone, because it is the only one asked to tell two + property names apart.""" """The target schema. Shown only when the condition says so, and sent to the provider only when a decode-time constraint is in force.""" branches: dict[str, dict[str, Any]] | None = None @@ -288,7 +299,17 @@ def build_property_messages( answer shape, because an arm that shows no schema still has to say what the names are before it can ask which of them the document fills. """ - listed = "\n".join(f"{(named or {}).get(key) or key}: {', '.join(names)}" for key, names in offered.items()) + described = request.property_text or {} + if described: + # One line per property, because a comment does not fit beside a name + # and the step is choosing between them rather than scanning a list. + lines: list[str] = [] + for key, names in offered.items(): + lines.append(f"{(named or {}).get(key) or key}:") + lines += [f" {name}: {described[name]}" if name in described else f" {name}" for name in names] + listed = "\n".join(lines) + else: + listed = "\n".join(f"{(named or {}).get(key) or key}: {', '.join(names)}" for key, names in offered.items()) sections = [ _PROPERTY_TASK, _PROPERTY_FORM, diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py index 735f43e..44e8ccf 100644 --- a/tests/test_agent/test_prompts.py +++ b/tests/test_agent/test_prompts.py @@ -132,3 +132,30 @@ def test_it_states_the_rule_the_corpus_applies(self): system = self._system() assert "appears in the text, in some spelling of it" in system assert "would usually have, is not" in system + + +class TestThePropertyStepIsShownWhatTheNamesMean: + """A vocabulary question cannot be answered by rewording the question. + + Measured over six models at n=100: recall 0.80 to 0.92 against precision + 0.52 to 0.58. The values are found and filed under the wrong slot, and a + bare name does not say whether the gallery holding a painting is its + contentLocation or its provider. + """ + + def _listing(self, **kwargs) -> str: + from oold.agent.prompts import build_property_messages + + request = ExtractionRequest(document="d", **kwargs) + return build_property_messages(request, {"e1": ("about", "name")})[0].content + + def test_a_description_is_shown_beside_its_property(self): + listing = self._listing(property_text={"about": "The subject matter of an object."}) + assert "about: The subject matter of an object." in listing + + def test_a_property_with_no_description_is_still_offered(self): + assert "\n name" in self._listing(property_text={"about": "The subject matter."}) + + def test_without_descriptions_the_names_stay_on_one_line(self): + """The compact form is what every corpus without a vocabulary gets.""" + assert "e1: about, name" in self._listing() From 58db032475c438f4bf5f420495a9a81197eb9e12 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 7 Oct 2026 06:45:42 +0200 Subject: [PATCH 35/58] fix(prompts): answer from the text in front of you, not from memory - a property all six models named was still rejected 29 per cent of the time, and the clearest case is an award on a film whose lead mentions none: agreement there is evidence about films --- src/oold/agent/prompts.py | 13 ++++++++++--- tests/test_agent/test_prompts.py | 8 +++++++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index b59afd7..7c3c3fa 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -78,9 +78,10 @@ _PROPERTY_TASK = ( "Read the document and say, for each entity listed below, which of its own " "properties the document states a value for. A property is stated when the " - "value itself appears in the text, in some spelling of it. A property the " - "document makes likely, or that the entity would usually have, is not " - "stated, and neither is one whose value you would have to supply." + "value itself appears in the text, in some spelling of it. Answer only " + "from what the text in front of you says, never from what you know about " + "the subject. A property the document makes likely, or that the entity " + "would usually have, or that you could fill from memory, is not stated." ) """The rule the corpus actually applies, said out loud. @@ -88,6 +89,12 @@ models asked a looser question answered it six different ways, which is a prompt that has not said what it wants rather than a disagreement between models. + +Memory is named because agreement showed it at work. Over six models in four +families, a property all six named was still rejected 29 per cent of the +time, and the clearest case is ``award`` on a film whose lead mentions no +award: six models agreeing is evidence about films, not about the document. +A model reading only the page cannot make that mistake. """ _PROPERTY_FORM = ( diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py index 44e8ccf..6a5f982 100644 --- a/tests/test_agent/test_prompts.py +++ b/tests/test_agent/test_prompts.py @@ -131,7 +131,13 @@ def test_it_states_the_rule_the_corpus_applies(self): which is a prompt that has not said what it wants.""" system = self._system() assert "appears in the text, in some spelling of it" in system - assert "would usually have, is not" in system + assert "would usually have" in system + + def test_it_forbids_answering_from_memory(self): + """A property all six models named was still rejected 29 per cent of + the time, and the clearest case is an award on a film whose lead + mentions none: six models agreeing is evidence about films.""" + assert "never from what you know about" in self._system() class TestThePropertyStepIsShownWhatTheNamesMean: From 7e1a657d3440f4278d668319f0dcb3813bc12870 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 7 Oct 2026 07:08:30 +0200 Subject: [PATCH 36/58] feat(prompts): the quotation is a condition, not a default - ExtractionRequest.property_evidence, off because requiring it cost gpt-oss a third of its correct answers and sonnet over half - the raw answer is kept on the agent: what a model writes there says what it thought it was reading --- src/oold/agent/extraction.py | 5 +++- src/oold/agent/prompts.py | 29 ++++++++++++++++++++-- tests/test_agent/test_multi_step.py | 37 +++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 9f17765..fb64684 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -743,7 +743,7 @@ def _choose_properties( """ if not available: return {} - schema = property_schema(available) + schema = property_schema(available, evidence=request.property_evidence) prepared, _ = prepare(schema, self.profile, grounding=False) named = {entity.key: f"{_named(entity)}, {'/'.join(entity.classes)}" for entity in plan} messages = build_property_messages(request, available, named) @@ -754,6 +754,9 @@ def _choose_properties( sink.append(reply.usage or TokenUsage()) answered = _fillable_of(reply.parsed if reply.parsed is not None else parse_json_answer(reply.text), available) + # Kept so a caller can read what the step thought it was reading. The + # answer is the names; this is the working behind them. + self.fillable_answer = answered return { key: tuple(name for name in names if name in _named_in(answered.get(key) or ())) for key, names in available.items() diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 7c3c3fa..657324f 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -125,6 +125,16 @@ class ExtractionRequest: document: str schema: dict[str, Any] | None = None + property_evidence: bool = False + """Whether the property step must quote the words it read each one from. + + Off, because it costs more than it buys: measured over six models, two + invented *more* with a quotation required, gpt-oss-120b lost a third of + its correct answers and claude-sonnet-5 over half. Raising the cost of + answering is not the same as raising the cost of guessing. + + Kept as a condition because what a model writes there says what it + thought it was reading, and that is worth being able to ask for.""" property_text: Mapping[str, str] | None = None """What each property name means, for the step that chooses between them. @@ -243,7 +253,7 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: } -def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: +def property_schema(offered: Mapping[str, Sequence[str]], evidence: bool = False) -> dict[str, Any]: """The answer shape the property step asks for. One array per entity, whose items enumerate **that entity's own** property @@ -280,7 +290,7 @@ def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: key: { "type": "array", "maxItems": len(names), - "items": {"type": "string", "enum": list(names)}, + "items": _property_item(list(names), evidence), "description": f"The properties of {key} the document states a value for.", } for key, names in offered.items() @@ -294,6 +304,21 @@ def property_schema(offered: Mapping[str, Sequence[str]]) -> dict[str, Any]: } +def _property_item(names: list[str], evidence: bool) -> dict[str, Any]: + """One answered property, with or without the words that state it.""" + if not evidence: + return {"type": "string", "enum": names} + return { + "type": "object", + "properties": { + "property": {"type": "string", "enum": names}, + "stated": {"type": "string", "description": "The words in the document that state it."}, + }, + "required": ["property", "stated"], + "additionalProperties": False, + } + + def build_property_messages( request: ExtractionRequest, offered: Mapping[str, Sequence[str]], diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 29f6611..458d8b8 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -793,3 +793,40 @@ def test_an_item_naming_no_property_is_dropped(self): client = MultiStepClient(detects=[], fillable={"fillable": {"e1": [{"stated": "Ada"}]}}) plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) assert agent(client).fillable_properties(request(), plan) == {"e1": ()} + + +class TestAskingForTheWordsThatStateIt: + """Off by default, because it costs more than it buys. + + What a model writes there says what it thought it was reading, which is + worth being able to ask for even though requiring it lowers the score. + """ + + def test_the_default_answer_is_names_alone(self): + from oold.agent.prompts import property_schema + + assert property_schema({"e1": ("name",)})["properties"]["fillable"]["properties"]["e1"]["items"] == { + "type": "string", + "enum": ["name"], + } + + def test_asked_for_it_the_answer_carries_both(self): + from oold.agent.prompts import property_schema + + item = property_schema({"e1": ("name",)}, evidence=True)["properties"]["fillable"]["properties"]["e1"]["items"] + assert item["required"] == ["property", "stated"] + assert item["properties"]["property"]["enum"] == ["name"] + + def test_the_request_decides(self): + client = MultiStepClient(detects=[]) + plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) + agent(client).fillable_properties(request(), plan) + assert client.formats[-1]["properties"]["fillable"]["properties"]["e1"]["items"]["type"] == "string" + + def test_what_the_model_wrote_is_kept_for_the_caller(self): + """The answer is the names; this is the working behind them.""" + client = MultiStepClient(detects=[]) + plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) + one = agent(client) + one.fillable_properties(request(), plan) + assert one.fillable_answer["e1"][0] == {"property": "name", "stated": "Ada"} From c6ba4a3f40f49fb2753d5a9ce73f2ae9c48d228f Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Thu, 8 Oct 2026 05:19:19 +0200 Subject: [PATCH 37/58] feat(agent): expose extract_narrowed for an external oracle - new ExtractionAgent.extract_narrowed(request, plan=, filling=, classes=, properties=), reusing the narrowing _multi_step already does for its own groups (with_catalogue, _trim_properties, _trim_branches) - lets a caller holding its own oracle (a corpus's true class and fillable properties, not another step's output) send the same narrowed request, instead of the full catalogue union extract() always sends - extract() itself is unchanged --- src/oold/agent/extraction.py | 61 +++++++++ tests/test_agent/test_extract_narrowed.py | 156 ++++++++++++++++++++++ 2 files changed, 217 insertions(+) create mode 100644 tests/test_agent/test_extract_narrowed.py diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index fb64684..ca82468 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -293,9 +293,70 @@ def extract( With a plan, the id slot is pinned to ``filling`` and a reference slot to the planned entities whose class fits its range, which is what makes an edge nameable. Without one, this is the single-shot arm. + + Narrows nothing else. ``self.enforcement.catalogue`` is whatever the + caller built the agent with, so a plan naming one true class still + sends the whole catalogue's union unless that catalogue was already + narrowed before this call. :meth:`extract_narrowed` is the door for a + caller that knows the true class, the true properties, or both, and + wants the request to say so instead of asking the model to rediscover + what the plan already answers. """ return self._single_shot(request, plan=plan, filling=filling) + def extract_narrowed( + self, + request: ExtractionRequest, + *, + plan: tuple[PlannedEntity, ...], + filling: tuple[str, ...], + classes: tuple[str, ...], + properties: tuple[str, ...] | None = None, + ) -> ExtractionResult: + """Step three, given the classes and (optionally) the properties a + plan already settled, rather than left for this call to answer again. + + ``_multi_step`` narrows its own groups exactly this way, by + ``(classes, chosen_properties)``, before ever calling the single-shot + filler. A caller that already holds that pair from its own oracle, a + corpus's expected classes and fields rather than another step's + output, had no public way to send the same narrowed request: calling + :meth:`extract` instead sends every class and every property the + condition's catalogue carries, so a class the plan already settled is + still something the model can get wrong, and a property the plan + never named is still something the model can invent a value for. + + ``classes`` narrows the catalogue the union is built from, the same + way :meth:`enforcement.Enforcement.with_catalogue` does for a + catalogue-size sweep. ``properties`` is the stricter half: left + ``None``, every property the narrowed classes admit stays offered; + given, the answer shape is trimmed to exactly those, plus whatever + ``_trim_properties`` keeps regardless (the class and id slots), the + same trim :meth:`_multi_step` applies to its own groups. + """ + narrowed = self.enforcement.with_catalogue(classes) + filler = ExtractionAgent( + self.client, + narrowed, + self.profile, + attempts=self.attempts, + close_properties=self.close_properties, + ) + keep = set(properties) if properties is not None else None + step = ( + request + if keep is None + else ExtractionRequest( + document=request.document, + schema=_trim_properties(request.schema, keep), + branches=_trim_branches(request.branches, keep), + parents=request.parents, + ranges=request.ranges, + instruction=request.instruction, + ) + ) + return filler._single_shot(step, plan=plan, filling=filling) + def _single_shot( self, request: ExtractionRequest, diff --git a/tests/test_agent/test_extract_narrowed.py b/tests/test_agent/test_extract_narrowed.py new file mode 100644 index 0000000..35c5d99 --- /dev/null +++ b/tests/test_agent/test_extract_narrowed.py @@ -0,0 +1,156 @@ +"""extract_narrowed: the door for a caller holding its own oracle. + +A step harness scoring extraction alone already knows an entity's true class +and, where it has one, the true set of fillable properties, the same pair +`_multi_step` derives for itself one step earlier. `extract()` sends every +class and every property the condition's catalogue carries regardless, so a +class the plan already settled is still something the model can get wrong, +and a property the plan never named is still something it can invent a value +for. These pin both, and pin neither where the caller does not ask. +""" + +from __future__ import annotations + +import json + +from oold.agent.client import ChatResponse, TokenUsage +from oold.agent.enforcement import arm +from oold.agent.extraction import ExtractionAgent, PlannedEntity +from oold.agent.prompts import ExtractionRequest +from oold.agent.provider import profile_for + +CATALOGUE = ("Person", "Organization", "LocalBusiness", "Book") + +BRANCHES = { + "Person": {"jobTitle": {"type": "string"}, "worksFor": {"type": "object"}}, + "Organization": {"legalName": {"type": "string"}, "founder": {"type": "object"}}, + "LocalBusiness": {"openingHours": {"type": "string"}}, + "Book": {"isbn": {"type": "string"}}, +} + +SCHEMA = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Entities", + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "name": {"type": "string"}, + "jobTitle": {"type": "string"}, + "worksFor": {"type": "object"}, + "legalName": {"type": "string"}, + "founder": {"type": "object"}, + "openingHours": {"type": "string"}, + "isbn": {"type": "string"}, + }, + "required": ["type"], + }, + } + }, + "required": ["entities"], +} + +DOCUMENT = "Ada works for Acme." + + +class RecordingClient: + """Answers once, with a fixed payload, and keeps the request it was sent.""" + + model = "recorder" + + def __init__(self, payload): + self.payload = payload + self.formats: list = [] + + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: + self.formats.append(response_format) + return ChatResponse( + text=json.dumps(self.payload), parsed=None, usage=TokenUsage(input_tokens=10, output_tokens=5) + ) + + +def agent(client) -> ExtractionAgent: + return ExtractionAgent(client, arm("schema-dump-catalog-enforced", CATALOGUE), profile_for("openai")) + + +def request() -> ExtractionRequest: + return ExtractionRequest(document=DOCUMENT, schema=SCHEMA, branches=BRANCHES) + + +def branch_names(response_format) -> set[str]: + return {branch["properties"]["type"]["const"] for branch in response_format["properties"]["entities"]["items"]["anyOf"]} + + +def branch_properties(response_format, name: str) -> set[str]: + branches = response_format["properties"]["entities"]["items"]["anyOf"] + branch = next(b for b in branches if b["properties"]["type"]["const"] == name) + return set(branch["properties"]) + + +class TestExtractNarrowed: + def test_the_union_is_narrowed_to_the_given_class(self): + client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada"}]}) + result = agent(client).extract_narrowed( + request(), plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), + filling=("e1",), classes=("Person",), + ) + assert result.payload is not None + assert branch_names(client.formats[0]) == {"Person"} + + def test_plain_extract_sends_the_whole_catalogue_unnarrowed(self): + """The negative control: extract() itself is unchanged.""" + client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada"}]}) + agent(client).extract( + request(), plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), filling=("e1",) + ) + assert branch_names(client.formats[0]) == set(CATALOGUE) + + def test_properties_none_keeps_every_property_the_narrowed_class_admits(self): + client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada", "jobTitle": "Engineer"}]}) + agent(client).extract_narrowed( + request(), plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), + filling=("e1",), classes=("Person",), + ) + assert branch_properties(client.formats[0], "Person") >= {"jobTitle", "worksFor", "name"} + + def test_properties_given_trims_to_exactly_those(self): + client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada"}]}) + agent(client).extract_narrowed( + request(), + plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), + filling=("e1",), + classes=("Person",), + properties=("name",), + ) + kept = branch_properties(client.formats[0], "Person") + assert "name" in kept + assert "jobTitle" not in kept + assert "worksFor" not in kept + + def test_the_id_slot_is_still_pinned_to_filling(self): + """Narrowing the class must not cost what `extract()` already pins.""" + client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada"}]}) + agent(client).extract_narrowed( + request(), plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), + filling=("e1",), classes=("Person",), + ) + branches = client.formats[0]["properties"]["entities"]["items"]["anyOf"] + assert all(branch["properties"]["id"]["enum"] == ["e1"] for branch in branches) + + def test_two_entities_of_different_classes_both_narrow(self): + client = RecordingClient({ + "entities": [ + {"id": "e1", "type": "Person", "name": "Ada"}, + {"id": "e2", "type": "Organization", "name": "Acme"}, + ] + }) + plan = ( + PlannedEntity(key="e1", classes=("Person",), mention="Ada"), + PlannedEntity(key="e2", classes=("Organization",), mention="Acme"), + ) + agent(client).extract_narrowed(request(), plan=plan, filling=("e1", "e2"), classes=("Person", "Organization")) + assert branch_names(client.formats[0]) == {"Person", "Organization"} From 7dc528993577db9f4d3b3b856706592e4382ce4b Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Fri, 9 Oct 2026 03:37:28 +0200 Subject: [PATCH 38/58] feat(agent): carry the plan step mention onto the result - ExtractionResult.mentions, beside selected and properties_chosen - set by select_then_fill, segmented and multi_step, empty for single shot - included in describe() - the only record of the designator when the property step declines name --- src/oold/agent/extraction.py | 39 ++++++++++++++++++++--- tests/test_agent/test_extract_narrowed.py | 22 +++++++++---- tests/test_agent/test_multi_step.py | 37 +++++++++++++++++++++ 3 files changed, 86 insertions(+), 12 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index ca82468..40a7c01 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -105,6 +105,20 @@ class ExtractionResult: Recorded so a two-step failure can be attributed to a step. Without it, the true class never being offered and the fill step choosing wrongly from a shortlist that contained it look like the same failure.""" + mentions: dict[str, str] = field(default_factory=dict) + """The words the plan step read each entity from, per entity. + + The same answer :meth:`ExtractionAgent.identify` returns, kept on the + result so an orchestration run whole reports it too. It is the only record + of what the document called an entity: a later step may decline to fill + the property that would carry the name, and "Jane works at ExampleCorp" + states an employment relation without stating that Jane's name is Jane, so + both ``claude-haiku-4-5`` and ``gpt-5-nano`` choose ``worksFor`` and + ``employee`` over ``name``. A caller that wants to show the entity to a + reader has this and the local key, and only this one designates anything. + + Empty for an orchestration with no plan step, which has nowhere to read a + mention from, rather than filled with a guess.""" prompt_sha256: str | None = None """Hash of the turns actually sent, folding included. Hashing the document instead would say two models got the same prompt when one of them had the @@ -148,6 +162,7 @@ def describe(self) -> dict[str, Any]: "schema_sha256": self.schema_sha256, "prompt_sha256": self.prompt_sha256, "selected": {k: list(v) for k, v in self.selected.items()}, + "mentions": dict(self.mentions), "properties_chosen": {k: list(v) for k, v in self.properties_chosen.items()}, "dropped": list(self.dropped), "invalid": list(self.invalid), @@ -478,6 +493,7 @@ def _select_then_fill(self, request: ExtractionRequest) -> ExtractionResult: payload=None, calls=log, selected=selected, + mentions=dict(self._mentions), ) # One call per distinct shortlist, not one per document. Pooling every @@ -509,10 +525,13 @@ def _select_then_fill(self, request: ExtractionRequest) -> ExtractionResult: last = outcome if last is None: - return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + return ExtractionResult( + text=text, payload=None, calls=log, selected=selected, mentions=dict(self._mentions) + ) last.payload = {"entities": merged} if merged else None last.calls = log last.selected = selected + last.mentions = dict(self._mentions) return last def _fill_instruction( @@ -565,7 +584,9 @@ def _segmented(self, request: ExtractionRequest) -> ExtractionResult: if entity.classes: groups.setdefault(entity.classes, []).append(entity.key) if not groups: - return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + return ExtractionResult( + text=text, payload=None, calls=log, selected=selected, mentions=dict(self._mentions) + ) merged: list[Any] = [] unpinned: list[str] = [] @@ -589,11 +610,14 @@ def _segmented(self, request: ExtractionRequest) -> ExtractionResult: last = outcome if last is None: - return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + return ExtractionResult( + text=text, payload=None, calls=log, selected=selected, mentions=dict(self._mentions) + ) links, dangling = _edges_of(merged, request.ranges) last.payload = {"entities": merged} if merged else None last.calls = log last.selected = selected + last.mentions = dict(self._mentions) last.links = links last.dangling = dangling last.unpinned = unpinned @@ -664,7 +688,9 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: ) placed = tuple(entity for entity in plan if entity.classes) if not placed: - return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + return ExtractionResult( + text=text, payload=None, calls=log, selected=selected, mentions=dict(self._mentions) + ) chosen = self._choose_properties(request, log, placed, self._available_properties(request, placed)) required = _required_properties(request.schema) @@ -702,11 +728,14 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: last = outcome if last is None: - return ExtractionResult(text=text, payload=None, calls=log, selected=selected) + return ExtractionResult( + text=text, payload=None, calls=log, selected=selected, mentions=dict(self._mentions) + ) links, dangling = _edges_of(merged, request.ranges) last.payload = {"entities": merged} if merged else None last.calls = log last.selected = selected + last.mentions = dict(self._mentions) last.properties_chosen = chosen last.links = links last.dangling = dangling diff --git a/tests/test_agent/test_extract_narrowed.py b/tests/test_agent/test_extract_narrowed.py index 35c5d99..bb7b7f7 100644 --- a/tests/test_agent/test_extract_narrowed.py +++ b/tests/test_agent/test_extract_narrowed.py @@ -82,7 +82,9 @@ def request() -> ExtractionRequest: def branch_names(response_format) -> set[str]: - return {branch["properties"]["type"]["const"] for branch in response_format["properties"]["entities"]["items"]["anyOf"]} + return { + branch["properties"]["type"]["const"] for branch in response_format["properties"]["entities"]["items"]["anyOf"] + } def branch_properties(response_format, name: str) -> set[str]: @@ -95,8 +97,10 @@ class TestExtractNarrowed: def test_the_union_is_narrowed_to_the_given_class(self): client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada"}]}) result = agent(client).extract_narrowed( - request(), plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), - filling=("e1",), classes=("Person",), + request(), + plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), + filling=("e1",), + classes=("Person",), ) assert result.payload is not None assert branch_names(client.formats[0]) == {"Person"} @@ -112,8 +116,10 @@ def test_plain_extract_sends_the_whole_catalogue_unnarrowed(self): def test_properties_none_keeps_every_property_the_narrowed_class_admits(self): client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada", "jobTitle": "Engineer"}]}) agent(client).extract_narrowed( - request(), plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), - filling=("e1",), classes=("Person",), + request(), + plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), + filling=("e1",), + classes=("Person",), ) assert branch_properties(client.formats[0], "Person") >= {"jobTitle", "worksFor", "name"} @@ -135,8 +141,10 @@ def test_the_id_slot_is_still_pinned_to_filling(self): """Narrowing the class must not cost what `extract()` already pins.""" client = RecordingClient({"entities": [{"id": "e1", "type": "Person", "name": "Ada"}]}) agent(client).extract_narrowed( - request(), plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), - filling=("e1",), classes=("Person",), + request(), + plan=(PlannedEntity(key="e1", classes=("Person",), mention="Ada"),), + filling=("e1",), + classes=("Person",), ) branches = client.formats[0]["properties"]["entities"]["items"]["anyOf"] assert all(branch["properties"]["id"]["enum"] == ["e1"] for branch in branches) diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 458d8b8..7a99c47 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -629,6 +629,43 @@ def test_a_request_without_ranges_says_nothing_about_links(self): assert "points at" not in client.messages[2][0].content +class TestWhatTheDocumentCalledIt: + """The mention the plan read, carried out of the whole run. + + ``identify`` returns it to a caller running one step. A caller running the + orchestration had no way to the same answer, and it is the only one there + is where the property step declines the slot that would hold the name: + asked about "Jane works at ExampleCorp", claude-haiku-4-5 chooses + ``worksFor`` and ``employee`` on 8 of 8 runs and ``name`` on none of them, + which is defensible, since the sentence states an employment relation and + not anybody's name. + """ + + def test_the_plan_step_mention_survives_the_run(self): + client = MultiStepClient() + result = agent(client).run(request()) + assert result.mentions == {"e1": "Ada", "e2": "Acme"} + + def test_it_survives_a_property_step_that_declines_the_name(self): + client = MultiStepClient( + fillable={"fillable": {"e1": ["worksFor"], "e2": []}}, + answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}], [{"id": "e2", "type": "Organization"}]], + ) + result = agent(client).run(request()) + assert all("name" not in entity for entity in result.payload["entities"]) + assert result.mentions == {"e1": "Ada", "e2": "Acme"} + + def test_a_plan_placing_nothing_still_reports_what_it_read(self): + client = MultiStepClient(plan=[{"id": "e1", "candidates": [], "mention": "Ada"}]) + result = agent(client).run(request()) + assert result.payload is None + assert result.mentions == {"e1": "Ada"} + + def test_the_record_says_it(self): + client = MultiStepClient() + assert agent(client).run(request()).describe()["mentions"] == {"e1": "Ada", "e2": "Acme"} + + class TestAskingForWhatTheDocumentDoesNotSay: """A required property the property step left out is a question, not a guess.""" From 11a6026e84518691843d3f10c3d45571df8d71be Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sat, 10 Oct 2026 04:46:19 +0200 Subject: [PATCH 39/58] fix(agent): a grouped call contributes only the entities it owns A call is given the ids it fills and told the others exist, so an edge has a name to point at. A model reads both lists and reports both, and the entity then arrives from the call that owns it and from one that was only told about it. Measured on 30 WDC cells: 8 id-enum violations across 5 cells, and the duplicates cost entity precision. --- src/oold/agent/extraction.py | 33 +++++++++++++++++++++++++++-- tests/test_agent/test_multi_step.py | 32 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 40a7c01..dad83c7 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -605,7 +605,7 @@ def _segmented(self, request: ExtractionRequest) -> ExtractionResult: outcome = filler._single_shot(step, plan=plan, filling=tuple(keys)) for call in outcome.calls: log.append(replace(call, step="fill")) - merged.extend(_entities_of(outcome.payload)) + merged.extend(_owned_by(_entities_of(outcome.payload), keys)) unpinned.extend(name for name in outcome.unpinned if name not in unpinned) last = outcome @@ -723,7 +723,7 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: outcome = filler._single_shot(step, plan=plan, filling=tuple(keys)) for call in outcome.calls: log.append(replace(call, step="extract")) - merged.extend(_entities_of(outcome.payload)) + merged.extend(_owned_by(_entities_of(outcome.payload), keys)) unpinned.extend(name for name in outcome.unpinned if name not in unpinned) last = outcome @@ -1557,6 +1557,35 @@ def _find_property(schema: Any, keys: tuple[str, ...]) -> dict[str, Any] | None: return None +def _owned_by(entities: list[Any], keys: list[str]) -> list[Any]: + """The entities a grouped call was asked for, out of what it answered. + + A call is given the ids it fills and told the others exist, because an + edge needs a name to point at. A model reads both lists and sometimes + reports both, so the same entity arrives from the call that owns it and + from one that was only told about it, and the two land in the answer as + two entities. + + The id decides it, since that is what the plan assigned and what the id + slot was pinned to. An entity whose id is not this call's is dropped here + and reported by the call that holds it. + + An entity with no id is kept. It is a defect either way, and no call can + claim it, so dropping it in every group would lose it from the answer + entirely and report the model as having said nothing. + """ + owned = set(keys) + kept: list[Any] = [] + for entity in entities: + if not isinstance(entity, dict): + kept.append(entity) + continue + stated = next((entity[name] for name in _ID_KEYS if isinstance(entity.get(name), str)), None) + if stated is None or stated in owned: + kept.append(entity) + return kept + + def _entities_of(payload: Any) -> list[Any]: """The entity list in an answer, whatever the model called the wrapper. diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 7a99c47..cbf6b2d 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -867,3 +867,35 @@ def test_what_the_model_wrote_is_kept_for_the_caller(self): one = agent(client) one.fillable_properties(request(), plan) assert one.fillable_answer["e1"][0] == {"property": "name", "stated": "Ada"} + + +class TestACallReportsOnlyWhatItWasAskedFor: + """A grouped call is told which ids it fills and which others exist. + + The others are named so an edge has a name to point at. A model reads + both lists and sometimes reports both, and the entity then arrives twice: + once from the call that owns it, once from a call that was only told + about it. Two entities in the answer where the document holds one. + """ + + def test_an_entity_another_call_owns_is_dropped(self): + from oold.agent.extraction import _owned_by + + answered = [ + {"id": "e5", "type": "Recipe", "name": "Pancakes"}, + {"id": "e1", "type": "Person", "name": "Andrea"}, + ] + assert _owned_by(answered, ["e5", "e6"]) == [answered[0]] + + def test_an_entity_with_no_id_is_kept(self): + """No call can claim it, so dropping it in every group loses it.""" + from oold.agent.extraction import _owned_by + + answered = [{"type": "Recipe", "name": "Pancakes"}] + assert _owned_by(answered, ["e5"]) == answered + + def test_the_id_is_read_under_any_of_the_names_an_answer_uses(self): + from oold.agent.extraction import _owned_by + + assert _owned_by([{"@id": "e9", "type": "Review"}], ["e5"]) == [] + assert _owned_by([{"entity_id": "e5", "type": "Review"}], ["e5"]) != [] From 6efbdf864143f2a0fba20f3fcae4bb7cbeda8e86 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sat, 10 Oct 2026 07:21:57 +0200 Subject: [PATCH 40/58] fix(agent): say that a property may hold more than one value - the answer shape already declares every slot as an array, so the shape permitted several values and only the wording was silent - over 60 Wikidata-lead cells at claude-haiku-4-5, 8.7 per cent of the expected values are lists and none of those lists came back whole - carried by _plan_instruction, which _extract_instruction composes, so segmented and multi-step read it in the same words - names no property and no count, because how many values a document states is part of what is being measured --- src/oold/agent/extraction.py | 15 +++++++++++++++ tests/test_agent/test_multi_step.py | 19 +++++++++++++++++++ tests/test_agent/test_segmented.py | 6 ++++++ 3 files changed, 40 insertions(+) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index dad83c7..88b678a 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -640,6 +640,20 @@ def _plan_instruction( work. Without them, a document whose source and target shortlisted different classes could never state the edge between them, because the call holding the source would not know the target had a name. + + The last sentence says a property may take more than one value. The + answer shape already declares every slot as an array, so the shape + permits it and only the wording was silent, and models answer with the + first value alone: over 60 Wikidata-lead cells at ``claude-haiku-4-5``, + 8.7 per cent of the expected values are lists and none of those lists + came back whole. It sits here rather than in + :meth:`_extract_instruction`, which composes this one, so every + orchestration that fills a plan reads it in the same words. + + It says that several values may be stated and never how many, for the + reason :data:`prompts._SELECT_TASK` gives no count: how many values a + document states is part of what is being measured, and naming a number + for one property would answer it. """ wanted = set(keys) listed = "; ".join(_named(entity) for entity in plan if entity.key in wanted) @@ -654,6 +668,7 @@ def _plan_instruction( sections.append( "Where a property of an entity points at another of these entities, give that entity's id as the value." ) + sections.append("Where the document states more than one value for a property, give every one of them.") return " ".join(sections) def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index cbf6b2d..a7e4d6b 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -176,6 +176,11 @@ def enums_of(response_format): return {key: slot["items"]["enum"] for key, slot in offered.items()} +def _sentence_about_several_values(content): + """The one sentence of an extract prompt that allows several values.""" + return next(part for part in content.split(". ") if "more than one value" in part) + + class TestTheCallsItMakes: def test_one_detect_one_property_call_and_one_extract_per_group(self): client = MultiStepClient() @@ -364,6 +369,20 @@ def test_an_open_condition_keeps_the_schema_whole(self): def test_an_open_condition_still_names_the_properties(self): assert "Report only these properties" in self.sent(close_properties=False).messages[2][0].content + def test_the_prompt_says_a_property_may_hold_more_than_one_value(self): + """The answer shape declares every slot as an array, so the shape + permits several and only the wording was silent. Told nothing, models + answer with the first value alone.""" + content = self.sent().messages[2][0].content + assert "Where the document states more than one value for a property, give every one of them." in content + + def test_it_says_neither_which_property_nor_how_many_values(self): + """How many values a document states is part of what is being + measured, and a count named for one property would answer it.""" + sentence = _sentence_about_several_values(self.sent().messages[2][0].content) + assert not any(character.isdigit() for character in sentence) + assert not any(name in sentence for name in ("name", "worksFor", "jobTitle", "isbn")) + class TestTheIdSlot: def sent(self): diff --git a/tests/test_agent/test_segmented.py b/tests/test_agent/test_segmented.py index d6bb28c..88ddba7 100644 --- a/tests/test_agent/test_segmented.py +++ b/tests/test_agent/test_segmented.py @@ -224,6 +224,12 @@ def test_the_ids_are_named_even_when_one_call_covers_the_plan(self): agent(client).run(request()) assert 'e1 ("Ada")' in client.messages[1][0].content + def test_the_fill_prompt_says_a_property_may_hold_more_than_one_value(self): + """The same sentence the extract step reads, because both compose the + plan instruction rather than wording the allowance twice.""" + content = self.sent().messages[1][0].content + assert "Where the document states more than one value for a property, give every one of them." in content + def test_a_request_without_ranges_says_nothing_about_links(self): client = PlanThenFillClient() ExtractionAgent( From 4fff98882c4c10a7752f63ddaad7810f1ac45e0f Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sat, 10 Oct 2026 07:33:31 +0200 Subject: [PATCH 41/58] feat(agent): keep the name slot where the plan read a mention - over 60 Wikidata-lead cells name is the most missed expected property, absent 59 times, though the first clause states it - applies only where the plan carries a mention for that entity and the shortlist admits the slot at all - kept and never filled, so a model declining it stays correct - reported as ExtractionResult.named beside properties_chosen, so a reader can tell the slot was kept rather than chosen --- src/oold/agent/extraction.py | 78 ++++++++++++++++--- tests/test_agent/test_multi_step.py | 114 +++++++++++++++++++++++++++- 2 files changed, 180 insertions(+), 12 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 88b678a..9ae2dba 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -151,6 +151,15 @@ class ExtractionResult: the property slot can fail by never offering the property the document states, or by offering it and the extract step leaving it empty, and without this the two are the same missing value.""" + named: list[str] = field(default_factory=list) + """The entities whose name slot the plan's mention kept, the step having + left it out. + + Closing the property slot is a declared enforcement axis, so a slot that + survives it against the step's answer is recorded rather than silent, the + way :attr:`unpinned` records a slot the pin could not reach. It is the + complement of :attr:`properties_chosen`: a name in one was the step's + answer, a key in this one was the plan's.""" @property def parsed(self) -> bool: @@ -164,6 +173,7 @@ def describe(self) -> dict[str, Any]: "selected": {k: list(v) for k, v in self.selected.items()}, "mentions": dict(self.mentions), "properties_chosen": {k: list(v) for k, v in self.properties_chosen.items()}, + "named": list(self.named), "dropped": list(self.dropped), "invalid": list(self.invalid), "repairs": self.repairs, @@ -216,9 +226,10 @@ def __init__( self.close_properties = close_properties """Whether the property step's answer removes the slots it left out. - On, the extract schema carries the chosen properties and the required - ones and nothing else, which is the direct analogue of closing the - class slot. Off, the chosen properties are named in the extract prompt + On, the extract schema carries the chosen properties, the required + ones, the name slot of an entity the plan read a mention for, and + nothing else, which is the direct analogue of closing the class slot. + Off, the chosen properties are named in the extract prompt and the schema stays whole, so a property the step missed can still be answered. The two are different claims about what closing a slot buys, so which one ran is declared rather than assumed.""" @@ -692,7 +703,9 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: fact about this pipeline. An entity the step leaves with nothing is extracted with its class and its id alone, because that is what the step said, and restoring the slots behind its back would hide a - step-two failure inside step three. + step-two failure inside step three. The one slot the plan can put back + is the name, and it puts it back on its own evidence rather than the + step's: see :meth:`_filling`. """ log = CallLog() self._mentions = {} @@ -707,17 +720,19 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: text=text, payload=None, calls=log, selected=selected, mentions=dict(self._mentions) ) - chosen = self._choose_properties(request, log, placed, self._available_properties(request, placed)) + available = self._available_properties(request, placed) + chosen = self._choose_properties(request, log, placed, available) + filling, named = self._filling(placed, available, chosen) required = _required_properties(request.schema) - # Grouped by shortlist and by chosen properties together, where - # segmented groups by shortlist alone. The extra key is the same + # Grouped by shortlist and by the properties the call fills together, + # where segmented groups by shortlist alone. The extra key is the same # argument one step on: entities sharing a call share the schema that - # call is sent, so two that chose different properties can no more - # share one than two that shortlisted different classes. + # call is sent, so two that fill different properties can no more share + # one than two that shortlisted different classes. groups: dict[tuple[tuple[str, ...], tuple[str, ...]], list[str]] = {} for entity in placed: - groups.setdefault((entity.classes, chosen.get(entity.key, ())), []).append(entity.key) + groups.setdefault((entity.classes, filling.get(entity.key, ())), []).append(entity.key) merged: list[Any] = [] unpinned: list[str] = [] @@ -752,11 +767,52 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: last.selected = selected last.mentions = dict(self._mentions) last.properties_chosen = chosen + last.named = named last.links = links last.dangling = dangling last.unpinned = unpinned return last + def _filling( + self, + placed: tuple[PlannedEntity, ...], + available: dict[str, tuple[str, ...]], + chosen: dict[str, tuple[str, ...]], + ) -> tuple[dict[str, tuple[str, ...]], list[str]]: + """The properties each extract call asks for, and who kept a name. + + The property step's answer, plus the name slot for an entity the plan + read a mention for. The step is asked which properties the document + states and ``name`` loses that question even where the first clause + answers it: over 60 Wikidata-lead cells it is the most missed expected + property, absent 59 times. A mention is the plan saying the document + calls the entity something, which is evidence the step's own answer + does not carry, so it is the plan and not the step that puts the slot + back. + + Only where there is a mention to justify it, so an orchestration with + no plan step gains nothing here, and only where the shortlist admits + the slot at all, for the reason :meth:`_choose_properties` drops a name + the entity cannot carry. + + The slot is kept and never filled. Empty stays a legal answer, because + "Jane works at ExampleCorp" states an employment relation and not that + Jane's name is Jane, and a model declining it is right. The entities it + applied to come back beside the properties so the result can say the + slot was kept by this rule rather than chosen by the step, the way + :attr:`ExtractionResult.unpinned` says which slots ran unconstrained. + """ + filling: dict[str, tuple[str, ...]] = {} + named: list[str] = [] + for entity in placed: + offered = available.get(entity.key, ()) + keep = set(chosen.get(entity.key, ())) + if self._mentions.get(entity.key) and _NAME_KEY in offered and _NAME_KEY not in keep: + keep.add(_NAME_KEY) + named.append(entity.key) + filling[entity.key] = tuple(name for name in offered if name in keep) + return filling, named + def _available_properties( self, request: ExtractionRequest, @@ -1264,6 +1320,8 @@ def keep(entity: Any) -> bool: _ID_KEYS = ("id", "@id", "entity_id", "key") +_NAME_KEY = "name" + def _named(entity: PlannedEntity) -> str: """One planned entity as the fill prompt names it.""" diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index a7e4d6b..ce8cfdc 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -349,9 +349,12 @@ def test_a_required_property_survives_the_trim(self): def test_an_entity_the_step_left_empty_is_asked_for_its_class_alone(self): """What the step said. Restoring the slots behind its back would hide a - step-two failure inside step three.""" + step-two failure inside step three. + + The plan read no mention for this one, so nothing outside the step has + anything to say about the name slot either.""" client = MultiStepClient( - plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + plan=[{"id": "e1", "candidates": ["Person"], "mention": ""}], fillable={"fillable": {"e1": []}}, answers=[[{"id": "e1", "type": "Person"}]], ) @@ -685,6 +688,113 @@ def test_the_record_says_it(self): assert agent(client).run(request()).describe()["mentions"] == {"e1": "Ada", "e2": "Acme"} +class TestTheNameSlotAMentionKeeps: + """The property step declines the name and the plan puts the slot back. + + The step is asked which properties the document states, and ``name`` loses + that question even where the first clause answers it: over 60 + Wikidata-lead cells it is the most missed expected property, absent 59 + times. A mention is the plan saying the document calls the entity + something, which is evidence the step's answer does not carry. + + The slot is kept, never filled. Which is the point of keeping it in the + schema rather than writing the mention into the answer. + """ + + DECLINED = {"fillable": {"e1": ["worksFor"], "e2": []}} + + ANSWERS = [[{"id": "e1", "type": "Person", "worksFor": "e2"}], [{"id": "e2", "type": "Organization"}]] + + def sent(self, client=None, **kwargs): + client = client or MultiStepClient(fillable=self.DECLINED, answers=self.ANSWERS) + agent(client, **kwargs).run(request()) + return client + + def test_a_mention_keeps_the_slot_the_property_step_left_out(self): + assert "name" in items_of(self.sent().formats[2])["properties"] + + def test_it_keeps_nothing_else_the_step_left_out(self): + """Closing the property slot is what the arm is measuring, so the rule + reaches one slot and the step still decides the rest.""" + offered = items_of(self.sent().formats[2])["properties"] + assert "jobTitle" not in offered + + def test_the_result_names_the_entities_it_kept_it_for(self): + """A slot that survives a declared enforcement axis against the step's + answer is recorded rather than silent.""" + result = agent(MultiStepClient(fillable=self.DECLINED, answers=self.ANSWERS)).run(request()) + assert result.named == ["e1", "e2"] + + def test_the_property_step_s_own_answer_is_reported_as_it_came(self): + """The complement of the record above. A name in one was the step's + answer, a key in the other was the plan's, and folding the two would + report the step as having chosen what it declined.""" + result = agent(MultiStepClient(fillable=self.DECLINED, answers=self.ANSWERS)).run(request()) + assert result.properties_chosen == {"e1": ("worksFor",), "e2": ()} + + def test_an_entity_that_chose_the_name_itself_is_not_named_by_the_rule(self): + assert agent(MultiStepClient()).run(request()).named == [] + + def test_the_plan_reading_no_mention_keeps_nothing(self): + """An orchestration with no plan step has nothing to justify it, and + neither has a plan entry that designates nothing.""" + client = MultiStepClient( + plan=[{"id": "e1", "candidates": ["Person"], "mention": ""}], + fillable={"fillable": {"e1": ["worksFor"]}}, + answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}]], + ) + result = agent(client).run(request()) + assert "name" not in items_of(client.formats[2])["properties"] + assert result.named == [] + + def test_a_shortlist_that_admits_no_name_keeps_nothing(self): + """For the reason the property step drops a name the entity cannot + carry: the slot would be one no class on the shortlist declares.""" + client = MultiStepClient(fillable={"fillable": {"e1": ["worksFor"], "e2": ["legalName"]}}) + result = agent(client).run(replace(request(), parents=None)) + assert result.named == [] + + def test_the_rule_adds_nothing_to_the_required_list(self): + """The slot is kept, not demanded. "Jane works at ExampleCorp" states + an employment relation and not that Jane's name is Jane, and a model + declining the slot is right.""" + assert "name" not in items_of(self.sent(profile="anthropic").formats[2])["required"] + + def test_a_subset_that_requires_everything_still_leaves_it_declinable(self): + """Where the profile rewrites `required` from `properties`, null is + how a model declines, and the kept slot is no worse off than one the + step chose.""" + assert "null" in items_of(self.sent().formats[2])["properties"]["name"]["type"] + + def test_an_answer_that_declines_it_is_kept_as_it_came(self): + result = agent(MultiStepClient(fillable=self.DECLINED, answers=self.ANSWERS)).run(request()) + assert all("name" not in entity for entity in result.payload["entities"]) + + def test_the_prompt_names_it_among_the_properties_to_fill(self): + """Named as every kept property is, because an arm that shows no + schema still has to be told the slot is there.""" + assert "Report only these properties for them: name, worksFor." in self.sent().messages[2][0].content + + def test_two_entities_the_rule_separates_do_not_share_a_call(self): + """Entities sharing a call share the schema that call is sent, so the + kept slot splits a group the step alone would have pooled.""" + client = MultiStepClient( + plan=[ + {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, + {"id": "e2", "candidates": ["Person"], "mention": ""}, + ], + fillable={"fillable": {"e1": ["jobTitle"], "e2": ["jobTitle"]}}, + answers=[[{"id": "e1", "type": "Person"}], [{"id": "e2", "type": "Person"}]], + ) + agent(client).run(request()) + assert client.calls == 4 + + def test_the_record_is_serialisable(self): + described = agent(MultiStepClient(fillable=self.DECLINED, answers=self.ANSWERS)).run(request()).describe() + assert json.dumps(described) + assert described["named"] == ["e1", "e2"] + + class TestAskingForWhatTheDocumentDoesNotSay: """A required property the property step left out is a question, not a guess.""" From 7a08ac42bf853223c9ffd0089141d0afb6431c32 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sat, 10 Oct 2026 08:21:11 +0200 Subject: [PATCH 42/58] fix(agent): pin an entity a schema puts inside another entity The shape walk stopped at the outermost entity, so an embedded one kept an id the plan never issued and reference slots nothing constrained. It is an entity reached differently, not a value, and needs the same two constraints. The holder is still recorded first, so the embedded shape is pinned after it and never instead of it. --- src/oold/agent/extraction.py | 15 +++++++ tests/test_agent/test_multi_step.py | 69 +++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 9ae2dba..78f57c6 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -1342,6 +1342,14 @@ def _entity_shapes(schema: Any) -> list[dict[str, Any]]: A union is recognised before the objects inside it, so pinning reaches all of its branches. Pinning the first branch alone would constrain one class and leave the others open, which reads as a finding about that class. + + An entity shape's own properties are searched too. A schema may put an + entity where a value goes, which is how a value object is written: the + address belongs to the person and is serialised inside it. That embedded + entity carries an id and may point at others, so it needs the same two + constraints the top-level shape gets. Stopping at the outermost match + would leave its id unpinned and its reference slots open, and an id the + plan never issued cannot be joined to anything. """ found: list[dict[str, Any]] = [] @@ -1356,9 +1364,16 @@ def visit(node: Any) -> None: branches = node.get(combinator) if isinstance(branches, list) and any(_is_entity_shape(branch) for branch in branches): found.extend(branch for branch in branches if _is_entity_shape(branch)) + for branch in branches: + if _is_entity_shape(branch): + visit(branch.get("properties")) return if _is_entity_shape(node): found.append(node) + # Its properties, because one of them may hold another entity. + # The shape itself is recorded first, so an embedded entity is + # pinned after the one holding it and never instead of it. + visit(node.get("properties")) return for value in node.values(): visit(value) diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index ce8cfdc..1cb4162 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -1028,3 +1028,72 @@ def test_the_id_is_read_under_any_of_the_names_an_answer_uses(self): assert _owned_by([{"@id": "e9", "type": "Review"}], ["e5"]) == [] assert _owned_by([{"entity_id": "e5", "type": "Review"}], ["e5"]) != [] + + +class TestAnEmbeddedEntityIsConstrainedToo: + """A schema may put an entity where a value goes. + + That is how a value object is written: the address belongs to the person + and is serialised inside it. It carries an id and may point at others, so + it needs the same two constraints the top-level shape gets, or its id is + one the plan never issued and nothing can be joined to it. + """ + + def _schema(self): + return { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "id": {"type": "string"}, + "name": {"type": "string"}, + "address": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "id": {"type": "string"}, + "streetAddress": {"type": "string"}, + }, + }, + }, + }, + }, + } + }, + } + + def test_the_walk_reaches_the_entity_inside_the_entity(self): + from oold.agent.extraction import _entity_shapes + + shapes = _entity_shapes(self._schema()) + assert [sorted(shape["properties"]) for shape in shapes] == [ + ["address", "id", "name", "type"], + ["id", "streetAddress", "type"], + ] + + def test_the_holder_is_found_before_the_entity_it_holds(self): + """So an embedded entity is pinned after it and never instead of it.""" + from oold.agent.extraction import _entity_shapes + + shapes = _entity_shapes(self._schema()) + assert "address" in shapes[0]["properties"] + + def test_a_schema_that_nests_nothing_is_unchanged(self): + from oold.agent.extraction import _entity_shapes + + flat = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": {"type": "object", "properties": {"type": {"type": "string"}, "name": {"type": "string"}}}, + } + }, + } + assert len(_entity_shapes(flat)) == 1 From cdb1cb1b7cbe61097ec9ce8ccf30f277f5728ab9 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sat, 10 Oct 2026 12:49:06 +0200 Subject: [PATCH 43/58] feat(agent): fold a planned entity into the embedding that holds it - an object-valued slot is one whose shape is an object with properties, so a link declared {"type": "object"} keeps its enum of ids - the entities a chosen embedding absorbs are the ones _compatible_ids gives its range, the test _pin_references already applies to a link - an entity no holder, two holders, or a holder it would itself absorb could take stays at the top level - the holder's call is given the absorbed id and its properties, so the entity is written inside it rather than lost - reported as ExtractionResult.absorbed beside named and properties_chosen --- src/oold/agent/extraction.py | 188 ++++++++++++++++++++- tests/test_agent/test_multi_step.py | 250 +++++++++++++++++++++++++++- 2 files changed, 427 insertions(+), 11 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 78f57c6..93030b9 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -160,6 +160,15 @@ class ExtractionResult: way :attr:`unpinned` records a slot the pin could not reach. It is the complement of :attr:`properties_chosen`: a name in one was the step's answer, a key in this one was the plan's.""" + absorbed: dict[str, str] = field(default_factory=dict) + """The entities an embedding folded into another, and which one holds each. + + Planned and then written inside something else, which is a different thing + from never having been planned and has to be readable as such: the id is in + :attr:`selected` and in :attr:`mentions` and nothing at the top level + answers under it. Recorded for the reason :attr:`named` and + :attr:`unpinned` are, that a rule which moves a slot or an entity against + a step's own answer says so rather than acting silently.""" @property def parsed(self) -> bool: @@ -174,6 +183,7 @@ def describe(self) -> dict[str, Any]: "mentions": dict(self.mentions), "properties_chosen": {k: list(v) for k, v in self.properties_chosen.items()}, "named": list(self.named), + "absorbed": dict(self.absorbed), "dropped": list(self.dropped), "invalid": list(self.invalid), "repairs": self.repairs, @@ -706,6 +716,11 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: step-two failure inside step three. The one slot the plan can put back is the name, and it puts it back on its own evidence rather than the step's: see :meth:`_filling`. + + Choosing an embedding is choosing not to have that thing as a sibling, + so an entity a chosen embedding absorbs is dropped from the groups and + the call holding it is given its ids and its properties instead: see + :func:`_absorbed_by`. """ log = CallLog() self._mentions = {} @@ -723,25 +738,37 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: available = self._available_properties(request, placed) chosen = self._choose_properties(request, log, placed, available) filling, named = self._filling(placed, available, chosen) + absorbed = _absorbed_by(request.schema, placed, chosen, request.ranges, request.parents) + inside = _inside(absorbed, filling) required = _required_properties(request.schema) # Grouped by shortlist and by the properties the call fills together, # where segmented groups by shortlist alone. The extra key is the same # argument one step on: entities sharing a call share the schema that # call is sent, so two that fill different properties can no more share - # one than two that shortlisted different classes. - groups: dict[tuple[tuple[str, ...], tuple[str, ...]], list[str]] = {} + # one than two that shortlisted different classes. The properties an + # absorbed entity brings are a third key for that same reason. + groups: dict[tuple[tuple[str, ...], tuple[str, ...], tuple[str, ...]], list[str]] = {} for entity in placed: - groups.setdefault((entity.classes, filling.get(entity.key, ())), []).append(entity.key) + if entity.key in absorbed: + continue + key = (entity.classes, filling.get(entity.key, ()), inside.get(entity.key, ())) + groups.setdefault(key, []).append(entity.key) merged: list[Any] = [] unpinned: list[str] = [] last: ExtractionResult | None = None - for (classes, kept), keys in groups.items(): + for (classes, kept, held), keys in groups.items(): narrowed = self.enforcement.with_catalogue(classes) filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) wanted = self._ask_for(keys, frozenset(required).difference(kept)) - keep = set(kept) | required.intersection(wanted) + keep = set(kept) | set(held) | required.intersection(wanted) + # The ids this call may state, which is the ones it reports plus + # the ones it writes inside them. An absorbed entity still answers + # under the id it was planned under, so the id slot has to offer it + # and the ownership filter has to let it through. + owned = set(keys) + states = [*keys, *(one for one, holder in absorbed.items() if holder in owned)] step = ExtractionRequest( document=request.document, schema=_trim_properties(request.schema, keep) if self.close_properties else request.schema, @@ -750,10 +777,10 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: ranges=request.ranges, instruction=self._extract_instruction(request, plan, keys, kept), ) - outcome = filler._single_shot(step, plan=plan, filling=tuple(keys)) + outcome = filler._single_shot(step, plan=plan, filling=tuple(states)) for call in outcome.calls: log.append(replace(call, step="extract")) - merged.extend(_owned_by(_entities_of(outcome.payload), keys)) + merged.extend(_owned_by(_entities_of(outcome.payload), states)) unpinned.extend(name for name in outcome.unpinned if name not in unpinned) last = outcome @@ -768,6 +795,7 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: last.mentions = dict(self._mentions) last.properties_chosen = chosen last.named = named + last.absorbed = absorbed last.links = links last.dangling = dangling last.unpinned = unpinned @@ -1241,6 +1269,13 @@ def _pin_references( answer surface can lose one legitimately, by a catalogue trim upstream or by a provider's optional-property limit, and a slot that is not offered is not a slot left open. + + So is a slot the schema declares as an object with properties of its + own. That is where an entity is written, not where one is named, and + an enum of ids would replace the shape holding it with a string: the + same range read as a link. It is not reported as left open either, + because a slot that was never a reference is not a reference the pin + could not reach. """ if not ranges: return schema, [] @@ -1251,7 +1286,11 @@ def _pin_references( lineage = {name: tuple(values) for name, values in (parents or {}).items()} unpinned: list[str] = [] for name, admitted in ranges.items(): - carrying = [shape for shape in shapes if name in (shape.get("properties") or {})] + carrying = [ + shape + for shape in shapes + if name in (shape.get("properties") or {}) and not _holds_an_object(shape["properties"][name]) + ] if not carrying: continue targets = _compatible_ids(plan, admitted, lineage) @@ -1537,6 +1576,18 @@ def _entity_id(entity: Any) -> str | None: return None +def _emitted_ids(node: Any) -> set[str]: + """Every id the answer states, wherever in it the entity was written.""" + if isinstance(node, list): + return {found for item in node for found in _emitted_ids(item)} + if not isinstance(node, dict): + return set() + found = {stated} if (stated := _entity_id(node)) is not None else set() + for value in node.values(): + found |= _emitted_ids(value) + return found + + def _descends(name: str, admitted: set[str], lineage: dict[str, tuple[str, ...]]) -> bool: """Whether a class is one of these or inherits from one.""" seen: set[str] = set() @@ -1571,6 +1622,120 @@ def _compatible_ids( ) +def _holds_an_object(slot: Any) -> bool: + """Whether a slot is where an entity is written rather than named. + + An object with properties of its own is the one shape a value can be + written into. A bare ``{"type": "object"}``, which is how a plain link is + declared, carries no key to write anything under, and a string or an IRI + names a thing written somewhere else. The array wrapper and a union of + shapes are looked through, because a property that takes several values + and one that takes one are the same property. + """ + if isinstance(slot, list): + return any(_holds_an_object(item) for item in slot) + if not isinstance(slot, dict): + return False + properties = slot.get("properties") + if isinstance(properties, dict) and properties: + return True + return any(_holds_an_object(slot[keyword]) for keyword in ("items", "anyOf", "oneOf") if keyword in slot) + + +def _embedded_properties(schema: Any) -> set[str]: + """The slots the answer shape offers as an embedding. + + Read from the shape the call is answering and not from a second input, so + a corpus that declares a property as an object gets the embedding rule and + one that declares the same property as a link does not, without either + having to say which it meant twice. + """ + names: set[str] = set() + for shape in _entity_shapes(schema): + for name, slot in (shape.get("properties") or {}).items(): + if name not in _CLASS_KEYS and name not in _ID_KEYS and _holds_an_object(slot): + names.add(name) + return names + + +def _absorbed_by( + schema: Any, + plan: tuple[PlannedEntity, ...], + chosen: dict[str, tuple[str, ...]], + ranges: dict[str, tuple[str, ...]] | None, + parents: dict[str, tuple[str, ...]] | None, +) -> dict[str, str]: + """Which planned entities a chosen embedding writes inside another. + + The property step is offered the object-valued slots beside the link ones + and does not take them: asked about "Andrea lives at Hauptstrasse 1, + Berlin" with a catalogue holding ``PostalAddress``, claude-haiku-4-5 + chooses ``homeLocation``, ``workLocation`` and ``worksFor`` over + ``address``. The plan has already made the address an entity of its own and + the fill step is told to report every planned entity under the id given, so + choosing ``address`` would mean reporting the same thing twice and the step + takes the link. Offered a catalogue in which no separate address can be + planned, the same model fills ``address`` with a nested object first time. + + So the choice is made to cost what it says: an entity a chosen embedding + can absorb stops being a sibling and is written inside its holder. Which + entities a property can absorb is the test :func:`_pin_references` applies + to a link, because it is the same question asked of the same ranges, and a + second version of that rule would be a second answer to it. + + An entity more than one holder could absorb, or none, stays where the plan + put it. So does one whose holder it would itself absorb, which is two + properties pointing at each other and not a chain: ``worksFor`` embedding + an ``Organization`` while ``employee`` embeds a ``Person`` would otherwise + put each inside the other and leave the answer with nothing at the top + level. Which of two readings the document meant is a question the document + already answered, and the pipeline would be inventing an answer to it. + """ + embedding = _embedded_properties(schema) + if not embedding or not ranges: + return {} + lineage = {name: tuple(values) for name, values in (parents or {}).items()} + holders: dict[str, set[str]] = {} + for entity in plan: + for name in chosen.get(entity.key, ()): + if name not in embedding: + continue + for target in _compatible_ids(plan, ranges.get(name, ()), lineage): + if target != entity.key: + holders.setdefault(target, set()).add(entity.key) + settled = {key: next(iter(owners)) for key, owners in holders.items() if len(owners) == 1} + circular = _circular(settled) + return {key: holder for key, holder in settled.items() if key not in circular} + + +def _circular(holders: dict[str, str]) -> set[str]: + """The entities whose chain of holders arrives back where it started.""" + found: set[str] = set() + for key in holders: + walked: list[str] = [] + current: str | None = key + while current is not None and current not in walked: + walked.append(current) + current = holders.get(current) + if current is not None: + found.update(walked[walked.index(current) :]) + return found + + +def _inside(absorbed: dict[str, str], filling: dict[str, tuple[str, ...]]) -> dict[str, tuple[str, ...]]: + """The properties each holder's call fills on the entities it absorbs. + + The trim is applied to every shape in the answer, the embedded one + included, so a holder's call that kept only the holder's own properties + would leave the absorbed entity with an id and a class and no slot to + write its value into, which is the state absorbing it was meant to end. + """ + held: dict[str, tuple[str, ...]] = {} + for key, holder in absorbed.items(): + held[holder] = tuple(dict.fromkeys(held.get(holder, ()) + filling.get(key, ()))) + return held + + def _edges_of( entities: list[Any], ranges: dict[str, tuple[str, ...]] | None, @@ -1581,10 +1746,15 @@ def _edges_of( the plan and its links have no source to hang from; the id slot is required and enumerated, so an answer without one is a decode failure already and is reported as that rather than twice. + + What counts as emitted includes the ids written inside another entity. An + entity an embedding absorbed was reported, under the id it was planned + under, and reading the top level alone would call every edge reaching it a + miss. """ if not ranges: return [], [] - emitted = {found for entity in entities if (found := _entity_id(entity)) is not None} + emitted = _emitted_ids(entities) links: list[Edge] = [] dangling: list[Edge] = [] for entity in entities: diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 1cb4162..04c28e3 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -139,10 +139,10 @@ def invoke(self, messages, *, response_format=None, strict=False) -> ChatRespons ) -def agent(client, name="schema-dump-catalog-flat-enforced", profile="openai", k=2, **kwargs): +def agent(client, name="schema-dump-catalog-flat-enforced", profile="openai", k=2, catalogue=CATALOGUE, **kwargs): return ExtractionAgent( client, - arm(name, CATALOGUE), + arm(name, catalogue), profile_for(profile), Orchestration.MULTI_STEP, shortlist_k=k, @@ -1097,3 +1097,249 @@ def test_a_schema_that_nests_nothing_is_unchanged(self): }, } assert len(_entity_shapes(flat)) == 1 + + +EMBEDDED_ADDRESS = { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "id": {"type": "string"}, + "streetAddress": {"type": "string"}, + }, + }, +} +"""An embedding: an object with keys to write the entity into. + +What `worksFor` and `author` in the fixture above are not. A link is declared +`{"type": "object"}` and nothing more, which carries the edge and leaves the +target's own properties to the branch the catalogue holds for its class.""" + +EMBEDDING_CATALOGUE = (*CATALOGUE, "PostalAddress") + +EMBEDDING_BRANCHES = { + **BRANCHES, + "Person": {**BRANCHES["Person"], "address": EMBEDDED_ADDRESS}, + "PostalAddress": {"streetAddress": {"type": "string"}}, +} + +EMBEDDING_PARENTS = {**PARENTS, "PostalAddress": ("Thing",)} + +EMBEDDING_RANGES = {**RANGES, "address": ("PostalAddress",)} + +EMBEDDING_SCHEMA = { + **SCHEMA, + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + **SCHEMA["properties"]["entities"]["items"]["properties"], + "address": EMBEDDED_ADDRESS, + }, + "required": ["type"], + }, + } + }, +} + +EMBEDDING_DOCUMENT = "Andrea lives at Hauptstrasse 1, Berlin." + +EMBEDDING_PLAN = [ + {"id": "e1", "candidates": ["Person"], "mention": "Andrea"}, + {"id": "e3", "candidates": ["PostalAddress"], "mention": "Hauptstrasse 1"}, +] + +EMBEDDING_ANSWER = [ + [ + { + "id": "e1", + "type": "Person", + "name": "Andrea", + "address": [{"id": "e3", "type": "PostalAddress", "streetAddress": "Hauptstrasse 1"}], + } + ] +] + + +def embedding_request(): + return ExtractionRequest( + document=EMBEDDING_DOCUMENT, + schema=EMBEDDING_SCHEMA, + branches=EMBEDDING_BRANCHES, + parents=EMBEDDING_PARENTS, + ranges=EMBEDDING_RANGES, + ) + + +def embedded_in(response_format, name="address"): + """The entity shape an embedding slot carries, inside the holder's.""" + return items_of(response_format)["properties"][name]["items"] + + +class TestAnEmbeddingAbsorbsThePlannedEntity: + """Choosing an embedding is choosing not to have that thing as a sibling. + + The property step is offered the object-valued slots beside the link ones + and does not take them. On "Andrea lives at Hauptstrasse 1, Berlin" with + claude-haiku-4-5 and a catalogue holding `PostalAddress`, the step chooses + `homeLocation`, `workLocation` and `worksFor` out of 59 properties and + never `address`, because the plan has already made the address an entity + with an id of its own and the fill step is told to report every planned + entity under the id given. Choosing the embedding would mean reporting the + same thing twice. Offered a catalogue in which no separate address can be + planned, the same model fills `address` with a nested object first time. + """ + + def run(self, fillable=None, plan=None, answers=None): + client = MultiStepClient( + plan=EMBEDDING_PLAN if plan is None else plan, + fillable=fillable or {"fillable": {"e1": ["name", "address"], "e3": ["streetAddress"]}}, + answers=EMBEDDING_ANSWER if answers is None else answers, + ) + result = agent(client, catalogue=EMBEDDING_CATALOGUE).run(embedding_request()) + return client, result + + def test_an_entity_a_chosen_embedding_absorbs_leaves_the_top_level_plan(self): + client, result = self.run() + assert result.absorbed == {"e3": "e1"} + assert client.calls == 3, "the absorbed entity no longer has an extract call of its own" + + def test_the_holder_is_the_only_entity_the_extract_call_is_asked_to_report(self): + client, _ = self.run() + assert 'under the id given here: e1 ("Andrea").' in client.messages[2][0].content + + def test_the_absorbed_entity_keeps_the_id_it_was_planned_under(self): + """The embedded object carries an id as a top-level one does, and + anything may still point at it, so the id slot has to offer it.""" + client, result = self.run() + assert embedded_in(client.formats[2])["properties"]["id"]["enum"] == ["e1", "e3"] + assert result.selected["e3"] == ("PostalAddress",) + assert result.mentions["e3"] == "Hauptstrasse 1" + + def test_the_call_that_holds_it_is_given_the_properties_it_fills(self): + """The trim reaches every shape in the answer, the embedded one + included, so a call keeping the holder's properties alone would leave + the absorbed entity with a class and an id and nowhere to put its + value.""" + client, _ = self.run() + assert "streetAddress" in embedded_in(client.formats[2])["properties"] + assert "streetAddress" not in items_of(client.formats[2])["properties"] + + def test_the_absorbed_entity_is_reported_inside_its_holder(self): + _, result = self.run() + assert [entity["id"] for entity in result.payload["entities"]] == ["e1"] + assert result.payload["entities"][0]["address"][0]["id"] == "e3" + + def test_an_entity_no_chosen_embedding_can_absorb_stays_at_the_top_level(self): + """The step declining the embedding leaves the plan as it was. What it + chose is the measurement, and a pipeline that absorbed on its own + behalf would be answering the question the step was asked.""" + client, result = self.run( + fillable={"fillable": {"e1": ["name"], "e3": ["streetAddress"]}}, + answers=[ + [{"id": "e1", "type": "Person", "name": "Andrea"}], + [{"id": "e3", "type": "PostalAddress", "streetAddress": "Hauptstrasse 1"}], + ], + ) + assert result.absorbed == {} + assert client.calls == 4 + assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e3"] + + def test_an_entity_two_holders_could_absorb_stays_at_the_top_level(self): + """Which of them the document put it inside is a question the document + already answered, and picking one would be inventing an answer.""" + _, result = self.run( + plan=[ + {"id": "e1", "candidates": ["Person"], "mention": "Andrea"}, + {"id": "e2", "candidates": ["Person"], "mention": "Bert"}, + {"id": "e3", "candidates": ["PostalAddress"], "mention": "Hauptstrasse 1"}, + ], + fillable={"fillable": {"e1": ["address"], "e2": ["address"], "e3": ["streetAddress"]}}, + answers=[ + [{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}], + [{"id": "e3", "type": "PostalAddress", "streetAddress": "Hauptstrasse 1"}], + ], + ) + assert result.absorbed == {} + assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2", "e3"] + + def test_two_entities_that_could_absorb_each_other_both_stay(self): + """Two embeddings pointing at each other is not a chain. Written out, + each would sit inside the other and the answer would have nothing at + the top level at all.""" + from oold.agent.extraction import _absorbed_by + + colleague = { + "type": "object", + "properties": {"type": {"type": "string"}, "id": {"type": "string"}, "name": {"type": "string"}}, + } + schema = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": {"type": {"type": "string"}, "id": {"type": "string"}, "colleague": colleague}, + }, + } + }, + } + plan = ( + PlannedEntity(key="e1", classes=("Person",), mention="Ada"), + PlannedEntity(key="e2", classes=("Person",), mention="Grace"), + ) + chosen = {"e1": ("colleague",), "e2": ("colleague",)} + assert _absorbed_by(schema, plan, chosen, {"colleague": ("Person",)}, PARENTS) == {} + + def test_an_edge_reaching_an_entity_written_inside_another_is_not_dangling(self): + """It was reported, under the id it was planned under. Reading the top + level alone would count every edge into an absorbed entity a miss.""" + from oold.agent.extraction import _edges_of + + answered = [ + {"id": "e1", "type": "Person", "address": [{"id": "e3", "type": "PostalAddress"}]}, + {"id": "e2", "type": "Person", "worksFor": "e3"}, + ] + links, dangling = _edges_of(answered, {"worksFor": ("PostalAddress",)}) + assert links == [Edge(source="e2", prop="worksFor", target="e3")] + assert dangling == [] + + def test_the_record_is_serialisable(self): + _, result = self.run() + described = result.describe() + assert json.dumps(described) + assert described["absorbed"] == {"e3": "e1"} + + +class TestASchemaThatOffersNoObjectSlot: + """Nothing about the existing behaviour may change where there is no + embedding to choose, which is every corpus that declares its node-valued + properties as plain links.""" + + def test_a_link_declared_as_a_bare_object_is_not_an_embedding(self): + """`{"type": "object"}` is what a plain link is declared as. It holds + no key to write a value under, so an entity absorbed into it would + have nowhere to go.""" + from oold.agent.extraction import _embedded_properties + + assert _embedded_properties(SCHEMA) == set() + + def test_an_object_with_properties_of_its_own_is_one(self): + from oold.agent.extraction import _embedded_properties + + assert _embedded_properties(EMBEDDING_SCHEMA) == {"address"} + + def test_the_run_makes_the_calls_it_made_before_and_absorbs_nothing(self): + client = MultiStepClient() + result = agent(client).run(request()) + assert result.absorbed == {} + assert client.calls == 4 + assert items_of(client.formats[2])["properties"]["id"]["enum"] == ["e1"] + assert items_of(client.formats[3])["properties"]["id"]["enum"] == ["e2"] + assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2"] + assert result.properties_chosen == {"e1": ("name", "worksFor"), "e2": ("name",)} + assert result.links == [Edge(source="e1", prop="worksFor", target="e2")] From f411604714ad9cf5e10821c394536ca60d0f1f59 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 11 Oct 2026 04:36:05 +0200 Subject: [PATCH 44/58] feat(agent): mark the system turn for the provider to cache An extraction sends the same catalogue and schema before every call of a run while only the question after them changes, and that prefix is most of the request: one recipe page cost 140,532 input tokens over six calls, of which the document was about 1,700. Only Anthropic needs telling; OpenAI caches a long prefix itself and vLLM does it server side, so the mark is decided from the model object rather than configured. --- src/oold/agent/langchain_client.py | 49 ++++++++++++++++++++++++++++-- tests/test_agent/test_client.py | 47 ++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index 165e7bf..4f1d37d 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -47,7 +47,7 @@ def usage_from_message(message: Any) -> TokenUsage: class LangChainClient: """Adapt a LangChain chat model to the :class:`ChatClient` protocol.""" - def __init__(self, llm: BaseChatModel, model: str, *, fold_system: bool = False) -> None: + def __init__(self, llm: BaseChatModel, model: str, *, fold_system: bool = False, cache_prefix: bool = True) -> None: self._llm = llm self.model = model """The identifier recorded in the result. Passed in instead of read @@ -58,12 +58,57 @@ def __init__(self, llm: BaseChatModel, model: str, *, fold_system: bool = False) """Whether the system content is folded into the first user turn. Set for deployments that discard a system message without saying so. Recorded, because it changes the prompt the model was sent.""" + self.cache_prefix = cache_prefix + """Whether the system turn is marked for the provider to cache. + + On, because an extraction sends the same catalogue and the same schema + in front of every call of a run while only the question after them + changes, and that prefix is most of the request: one recipe page cost + 140,532 input tokens over six calls, of which the document was about + 1,700. + + Only Anthropic needs the mark. OpenAI caches a long prefix by itself + and vLLM does it server side, so the flag reaches only the client that + would otherwise re-read the prefix every time. A model that does not + understand the block form is never given it.""" @property def llm(self) -> BaseChatModel: """The wrapped chat model, so a caller can check what it was built with.""" return self._llm + def _turns(self, messages: Sequence[Message]) -> list[Any]: + """The turns as the provider takes them. + + Role and content pairs, except where the system turn is marked for + caching: that needs a content block rather than a string, which only + the providers that read the mark accept. + """ + if self.fold_system: + return list(fold_system_into_user(messages)) + pairs: list[Any] = [(m.role, m.content) for m in messages] + if not self._marks_a_cacheable_prefix(): + return pairs + marked: list[Any] = [] + for role, content in pairs: + if role == "system" and content: + block = {"type": "text", "text": content, "cache_control": {"type": "ephemeral"}} + marked.append((role, [block])) + else: + marked.append((role, content)) + return marked + + def _marks_a_cacheable_prefix(self) -> bool: + """Whether this provider reads a cache mark on a content block. + + Decided from the model object rather than configured, so a caller that + builds a client has nothing to remember. Anthropic is the one that + needs telling; the others cache a repeated prefix on their own. + """ + if not self.cache_prefix: + return False + return "anthropic" in type(self._llm).__module__.lower() + def invoke( self, messages: Sequence[Message], @@ -73,7 +118,7 @@ def invoke( ) -> ChatResponse: llm: Any = self._llm parsed: dict[str, Any] | None = None - turns = fold_system_into_user(messages) if self.fold_system else [(m.role, m.content) for m in messages] + turns = self._turns(messages) if response_format is not None: # strict=False sends the schema and applies no grammar, which is diff --git a/tests/test_agent/test_client.py b/tests/test_agent/test_client.py index 7f8ac4c..a1638e0 100644 --- a/tests/test_agent/test_client.py +++ b/tests/test_agent/test_client.py @@ -213,3 +213,50 @@ def test_the_hash_is_a_sha256(self): def test_non_ascii_content_does_not_change_between_runs(self): german = [Message(role="user", content="Die Molmasse betrug 79,7 Gramm pro Mol.")] assert prompt_hash(german) == prompt_hash(german) + + +class TestTheSystemTurnIsMarkedForCaching: + """An extraction sends the same catalogue and schema before every call. + + Only the question after them changes, and the prefix is most of the + request: one recipe page cost 140,532 input tokens over six calls, of + which the document was about 1,700. + """ + + class _Anthropic: + __module__ = "langchain_anthropic.chat_models" + + class _OpenAI: + __module__ = "langchain_openai.chat_models.base" + + def _client(self, llm, **kw): + from oold.agent.langchain_client import LangChainClient + + return LangChainClient(llm, model="m", **kw) + + def _messages(self): + from oold.agent.client import Message + + return [Message(role="system", content="the catalogue"), Message(role="user", content="the document")] + + def test_anthropic_is_told_which_prefix_to_keep(self): + turns = self._client(self._Anthropic())._turns(self._messages()) + assert turns[0] == ( + "system", + [{"type": "text", "text": "the catalogue", "cache_control": {"type": "ephemeral"}}], + ) + assert turns[1] == ("user", "the document") + + def test_a_provider_that_caches_by_itself_is_left_alone(self): + turns = self._client(self._OpenAI())._turns(self._messages()) + assert turns == [("system", "the catalogue"), ("user", "the document")] + + def test_it_can_be_turned_off(self): + turns = self._client(self._Anthropic(), cache_prefix=False)._turns(self._messages()) + assert turns == [("system", "the catalogue"), ("user", "the document")] + + def test_a_folded_system_turn_is_not_marked(self): + """There is no system turn left to mark, and the fold exists because + the deployment discards one.""" + turns = self._client(self._Anthropic(), fold_system=True)._turns(self._messages()) + assert all(not isinstance(content, list) for _, content in turns) From 8328f3a95b3106709ba2ae96bfebde9de9a8347e Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 12 Oct 2026 12:20:34 +0200 Subject: [PATCH 45/58] fix(agent): ask for an id even where no plan issued one An entity that names itself nothing cannot be pointed at, so a run with no plan could assert a class and a value for everything and an edge for nothing. One recipe page came back from a single call with 43 entities, every one correctly typed, not one carrying an id and no link between them. Required with no enum where there are no planned keys to offer. --- src/oold/agent/extraction.py | 42 ++++++++++++----- tests/test_agent/test_multi_step.py | 7 ++- tests/test_agent/test_single_shot.py | 59 ++++++++++++++++++++++++ tests/test_agent/test_validation_gate.py | 8 ++-- 4 files changed, 100 insertions(+), 16 deletions(-) create mode 100644 tests/test_agent/test_single_shot.py diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 93030b9..8823d63 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -1101,16 +1101,25 @@ def _schema_for( prepared = self._pin_units(prepared) unpinned: list[str] = [] - if plan: - # The id slot goes in whatever the decode constraint is, because it - # belongs to the orchestration and not to the enforcement: an answer - # stating no id cannot be joined back to the plan, and an arm that - # only shows its schema still has to ask for one. The reference - # enums go in where the decoder is engaged and nowhere else, so the - # decode axis keeps meaning what it means everywhere else. + # The id slot goes in whatever the decode constraint is, because it + # belongs to the orchestration and not to the enforcement: an answer + # stating no id cannot be joined back to the plan, and an arm that + # only shows its schema still has to ask for one. + # + # Asked for with no plan as well, without an enum because there are no + # planned keys to offer. An answer that names nothing cannot point at + # anything, so a run with no plan could assert a class and a value and + # never an edge: one recipe page came back from a single call with 43 + # entities, every one of them correctly typed, not one carrying an id + # and not a single link between them. An id the schema leaves optional + # is an id a long answer drops. + if plan or _entity_shapes(prepared): prepared = self._pin_identity(prepared, filling) - if self.enforcement.decode_constraint is not DecodeConstraint.NONE: - prepared, unpinned = self._pin_references(prepared, plan, request.ranges, request.parents) + # The reference enums go in where the decoder is engaged and nowhere + # else, so the decode axis keeps meaning what it means everywhere else, + # and they need a plan to draw the admissible ids from. + if plan and self.enforcement.decode_constraint is not DecodeConstraint.NONE: + prepared, unpinned = self._pin_references(prepared, plan, request.ranges, request.parents) return prepared, degradation, schema_hash(prepared), unpinned def _pin_class(self, schema: dict[str, Any]) -> dict[str, Any]: @@ -1213,7 +1222,7 @@ class and leaving the unit a free string enforces half of what the return schema def _pin_identity(self, schema: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]: - """Give the answer a slot for the id the plan assigned. + """Give the answer a slot for the id, required, enumerated where it can be. Pinned to the ids this call is for, so one call cannot answer with an entity another call is responsible for and have it counted twice. An id @@ -1221,6 +1230,12 @@ def _pin_identity(self, schema: dict[str, Any], keys: tuple[str, ...]) -> dict[s also the only form in which the question of whether two mentions are one entity is ever put to the model. + ``keys`` empty asks for an id and offers no enum, which is the case + with no plan to draw admissible ids from. Required all the same: an + entity that names itself nothing cannot be pointed at, so an answer + could carry a class and a value for everything and an edge for + nothing. + Fails loudly when there is no entity shape to carry it, the way :meth:`_pin_class` does. A plan that cannot be joined to the answer would report every edge as dangling and read as a finding about links. @@ -1233,7 +1248,12 @@ def _pin_identity(self, schema: dict[str, Any], keys: tuple[str, ...]) -> dict[s name = next((key for key in _ID_KEYS if key in properties), _ID_KEYS[0]) slot = dict(properties.get(name) or {}) slot["type"] = "string" - slot.setdefault("description", "The id this entity was planned under.") + told = ( + "The id this entity was planned under." + if keys + else "A short identifier for this entity, so another entity can point at it." + ) + slot.setdefault("description", told) if keys: slot["enum"] = list(keys) properties[name] = slot diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 04c28e3..494f884 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -913,7 +913,12 @@ def test_extract_without_a_plan_is_the_single_shot_arm(self): client = MultiStepClient(detects=[]) result = agent(client).extract(request()) assert result.payload is not None - assert _id_slot(client.formats[-1]) is None + # An id, required and with no enum: there is no plan to draw + # admissible ids from, and an entity that names itself nothing cannot + # be pointed at by anything. + slot = _id_slot(client.formats[-1]) + assert slot is not None + assert "enum" not in slot def _id_slot(schema): diff --git a/tests/test_agent/test_single_shot.py b/tests/test_agent/test_single_shot.py new file mode 100644 index 0000000..64df477 --- /dev/null +++ b/tests/test_agent/test_single_shot.py @@ -0,0 +1,59 @@ + + +class TestAnAnswerWithNoPlanStillNamesItsEntities: + """An entity that names itself nothing cannot be pointed at. + + Measured on one recipe page: a single call returned 43 entities, every + one correctly typed as a HowToStep, HowToSupply or HowToSection, not one + carrying an id and not a single link between them. An id the schema + leaves optional is an id a long answer drops. + """ + + def _schema(self): + return { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": {"type": {"type": "string"}, "name": {"type": "string"}}, + }, + } + }, + } + + def _prepared(self, orchestration): + from oold.agent.enforcement import ARMS + from oold.agent.extraction import ExtractionAgent, ExtractionRequest, _entity_shapes + from oold.agent.provider import profile_for + + agent = ExtractionAgent( + _Silent(), ARMS["schema-dump-catalog-flat-enforced"], profile_for("openai"), orchestration=orchestration + ) + request = ExtractionRequest(document="d", schema=self._schema()) + prepared, _, _, _ = agent._schema_for(request, (), ()) + return _entity_shapes(prepared)[0] + + def test_the_id_is_required_with_no_plan_to_pin_it_to(self): + from oold.agent.enforcement import Orchestration + + shape = self._prepared(Orchestration.SINGLE_SHOT) + assert "id" in shape["properties"] + assert "id" in shape["required"] + + def test_it_carries_no_enum_where_no_plan_issued_the_ids(self): + from oold.agent.enforcement import Orchestration + + shape = self._prepared(Orchestration.SINGLE_SHOT) + assert "enum" not in shape["properties"]["id"] + assert shape["properties"]["id"]["type"] == "string" + + +class _Silent: + model = "silent" + + def invoke(self, messages, *, response_format=None, strict=False): + from oold.agent.client import ChatResponse + + return ChatResponse(text="{}", parsed={}, usage=None, raw=None) diff --git a/tests/test_agent/test_validation_gate.py b/tests/test_agent/test_validation_gate.py index 7bf1e6c..afafc00 100644 --- a/tests/test_agent/test_validation_gate.py +++ b/tests/test_agent/test_validation_gate.py @@ -35,9 +35,9 @@ }, } -WHOLE = {"entities": [{"type": "Length", "value": 1.0, "unit": "meter"}]} -MISSING = {"entities": [{"type": "Length"}]} -WRONG_TYPE = {"entities": [{"type": "Length", "value": "one", "unit": "meter"}]} +WHOLE = {"entities": [{"id": "e1", "type": "Length", "value": 1.0, "unit": "meter"}]} +MISSING = {"entities": [{"id": "e1", "type": "Length"}]} +WRONG_TYPE = {"entities": [{"id": "e1", "type": "Length", "value": "one", "unit": "meter"}]} class ScriptedClient: @@ -192,7 +192,7 @@ def test_the_gate_and_the_validator_catch_different_things(): """The point of the whole file. A class outside the catalogue is a gate failure; a missing required property is a validation failure; neither catches the other.""" - gate_only = run(ScriptedClient({"entities": [{"type": "Nonesuch", "value": 1.0, "unit": "m"}]})) + gate_only = run(ScriptedClient({"entities": [{"id": "e1", "type": "Nonesuch", "value": 1.0, "unit": "m"}]})) assert gate_only.dropped == ["Nonesuch"] assert gate_only.invalid == [] From 39d4bad3bbaf498bd32e742bdd97449e200eecfc Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 12 Oct 2026 12:48:36 +0200 Subject: [PATCH 46/58] fix(agent): narrow an array-valued reference inside its array Replacing the whole slot with a scalar enum leaves a model that answers a list unconstrained by the enum and in breach of the declared type at once. One recipe filled an array-valued recipeIngredient with seventeen ids, none of them in the enum the slot had been narrowed to, and the decode constraint never engaged. --- src/oold/agent/extraction.py | 13 ++++++- tests/test_agent/test_segmented.py | 51 ++++++++++++++++++++++++++++ tests/test_agent/test_single_shot.py | 2 -- 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 8823d63..1319773 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -1330,11 +1330,22 @@ def _pin_references( else: kind = "string" described = declared.get("description") if isinstance(declared, dict) else None - properties[name] = { + pinned: dict[str, Any] = { "type": kind, "enum": values, "description": described or f"The id of the entity {name} points at.", } + # Inside the array where the property takes several values. + # Replacing the whole slot with a scalar leaves a model that + # answers a list unconstrained by the enum and in breach of + # the declared type at once: one recipe filled an array-valued + # `recipeIngredient` with seventeen ids, none of them in the + # enum the slot had been narrowed to, and the decode + # constraint never engaged. + if isinstance(declared, dict) and declared.get("type") == "array": + properties[name] = {**declared, "items": pinned} + else: + properties[name] = pinned return schema, unpinned def _gate(self, payload: Any) -> tuple[Any, list[str]]: diff --git a/tests/test_agent/test_segmented.py b/tests/test_agent/test_segmented.py index 88ddba7..b23c286 100644 --- a/tests/test_agent/test_segmented.py +++ b/tests/test_agent/test_segmented.py @@ -485,3 +485,54 @@ def test_a_candidate_outside_the_catalogue_is_dropped(self): ) result = agent(client).run(request()) assert result.selected == {"e1": ("Person",)} + + +class TestPinningAnArrayValuedReference: + """A property that takes several ids is narrowed inside its array. + + Replacing the whole slot with a scalar leaves a model that answers a list + unconstrained by the enum and in breach of the declared type at once: one + recipe filled an array-valued `recipeIngredient` with seventeen ids, none + of them in the enum the slot had been narrowed to. + """ + + def _pinned(self, declared): + from oold.agent.enforcement import ARMS + from oold.agent.extraction import ExtractionAgent, PlannedEntity + from oold.agent.provider import profile_for + + schema = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": {"type": {"type": "string"}, "holds": declared}, + }, + } + }, + } + agent = ExtractionAgent(_Quiet(), ARMS["schema-dump-catalog-flat-enforced"], profile_for("openai")) + plan = (PlannedEntity(key="e1", classes=("Thing",), mention="a"),) + pinned, _ = agent._pin_references(schema, plan, {"holds": ("Thing",)}, {"Thing": ()}) + return pinned["properties"]["entities"]["items"]["properties"]["holds"] + + def test_an_array_keeps_its_array_and_the_enum_goes_on_the_items(self): + slot = self._pinned({"type": "array", "items": {"type": "string"}}) + assert slot["type"] == "array" + assert slot["items"]["enum"] == ["e1"] + + def test_a_scalar_slot_is_replaced_as_it_was(self): + slot = self._pinned({"type": "string"}) + assert slot["type"] == "string" + assert slot["enum"] == ["e1"] + + +class _Quiet: + model = "quiet" + + def invoke(self, messages, *, response_format=None, strict=False): + from oold.agent.client import ChatResponse + + return ChatResponse(text="{}", parsed={}, usage=None, raw=None) diff --git a/tests/test_agent/test_single_shot.py b/tests/test_agent/test_single_shot.py index 64df477..92779a8 100644 --- a/tests/test_agent/test_single_shot.py +++ b/tests/test_agent/test_single_shot.py @@ -1,5 +1,3 @@ - - class TestAnAnswerWithNoPlanStillNamesItsEntities: """An entity that names itself nothing cannot be pointed at. From 66e175929b448447d2c97d5f5884c83188bbe770 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 12 Oct 2026 20:58:40 +0200 Subject: [PATCH 47/58] fix(agent): narrow the catalogue entries with the catalogue catalogue_text[i] describes catalogue[i], the pairing with_catalogue_text refuses to let drift, and with_catalogue moved one without the other. An extract call for a group of one class was sent all 63 entries beside an enum of three, six times over a single document. --- src/oold/agent/enforcement.py | 14 +++++++++- tests/test_agent/test_enforcement.py | 41 ++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index 496e292..c255384 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -224,8 +224,20 @@ def with_catalogue(self, paths: tuple[str, ...] | None) -> Enforcement: This is the one knob a catalogue-weight sweep moves, so it gets a method instead of being reconstructed by hand at each size. + + The rendered entries are narrowed with it. ``catalogue_text[i]`` + describes ``catalogue[i]``, which is the pairing + :meth:`with_catalogue_text` refuses to let drift, and a narrowing that + moved one without the other would describe a class as another or + describe classes the enum no longer admits. An extract call for one + group was sent all 63 entries beside an enum of three, six times over + a single document. """ - return replace(self, catalogue=paths) + if paths is None or self.catalogue is None or self.catalogue_text is None: + return replace(self, catalogue=paths) + described = dict(zip(self.catalogue, self.catalogue_text, strict=False)) + kept = tuple(described[path] for path in paths if path in described) + return replace(self, catalogue=paths, catalogue_text=kept or None) def with_units(self, units: tuple[str, ...] | None) -> Enforcement: """The same condition over a different unit enumeration.""" diff --git a/tests/test_agent/test_enforcement.py b/tests/test_agent/test_enforcement.py index 10e063c..077c8d4 100644 --- a/tests/test_agent/test_enforcement.py +++ b/tests/test_agent/test_enforcement.py @@ -218,3 +218,44 @@ def test_the_unit_enumeration_is_reported(self): def test_no_unit_enumeration_reports_zero(self): assert arm("schema-dump-catalog-flat-enforced", ("Length",)).describe()["unit_catalogue_size"] == 0 + + +class TestNarrowingTheCatalogue: + """The entries describe the classes, so the two narrow together. + + `catalogue_text[i]` describes `catalogue[i]`, which is the pairing + `with_catalogue_text` refuses to let drift. An extract call for one group + was sent all 63 entries beside an enum of three, six times over a single + document. + """ + + def _condition(self): + from oold.agent.enforcement import ARMS + + base = ARMS["schema-dump-catalog-flat-enforced"] + return base.with_catalogue(("Recipe", "Person", "Product")).with_catalogue_text(( + "- Recipe", + "- Person", + "- Product", + )) + + def test_the_entries_follow_the_classes(self): + narrowed = self._condition().with_catalogue(("Recipe",)) + assert narrowed.catalogue == ("Recipe",) + assert narrowed.catalogue_text == ("- Recipe",) + + def test_an_entry_still_describes_its_own_class(self): + narrowed = self._condition().with_catalogue(("Product", "Recipe")) + assert narrowed.catalogue_text == ("- Product", "- Recipe") + + def test_a_catalogue_with_no_entries_narrows_as_it_did(self): + from oold.agent.enforcement import ARMS + + base = ARMS["schema-dump-catalog-flat-enforced"].with_catalogue(("Recipe", "Person")) + assert base.catalogue_text is None + assert base.with_catalogue(("Recipe",)).catalogue == ("Recipe",) + + def test_offering_everything_leaves_the_entries_alone(self): + whole = self._condition().with_catalogue(None) + assert whole.catalogue is None + assert whole.catalogue_text == ("- Recipe", "- Person", "- Product") From ac0ea2f3957632ee53c2feaf7ae383c62c37416c Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 12 Oct 2026 21:17:57 +0200 Subject: [PATCH 48/58] fix(agent): assign the plan's entity keys instead of asking for them - the identify step's answer shape and wording no longer ask for an id - keys are issued in the order the answer lists its entities - an item that is not an object takes no key and leaves no gap - single shot still asks the model, having no plan to assign from --- src/oold/agent/extraction.py | 34 +++++---- src/oold/agent/prompts.py | 20 ++++-- tests/test_agent/test_multi_step.py | 70 +++++++++---------- tests/test_agent/test_segmented.py | 26 +++---- tests/test_agent/test_select_then_fill.py | 85 +++++++++++++++++++++-- tests/test_agent/test_single_shot.py | 12 ++++ 6 files changed, 175 insertions(+), 72 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 1319773..4bce220 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -67,10 +67,11 @@ class PlannedEntity: key: str """The id both steps use for this entity. - Invented by the model in the plan step and offered back to it in the fill - step. An id attached afterwards by position never puts the question of - whether two mentions are one entity to the model at all, which is why the - predecessor could not ask it.""" + Assigned by the plan step from the position of the entity in its answer, + and offered back to the model in the fill step, where it is the name an + edge points at. Whether two mentions are one entity is put to the model as + the plan's own question, by asking it for one line per entity, rather than + through a key it mints and may reuse.""" classes: tuple[str, ...] """The shortlist, most likely first. Empty when the plan placed the entity in no class, which leaves it out of the fill step.""" @@ -563,8 +564,8 @@ def _fill_instruction( ) -> str: """Which entities this call is for, when a document holds several. - Named by the words the select step read them from, because an - identifier it invented means nothing to a model reading the document + Named by the words the select step read them from, because the key the + pipeline files them under means nothing to a model reading the document again. Omitted entirely when there is one group, so the single-entity case sends the same prompt the single-shot arm does. """ @@ -983,6 +984,15 @@ def _select( ``step`` names the call in the log. Two orchestrations ask this same question and spend different amounts on what follows, so their first calls are attributed apart rather than pooled under one name. + + The key each entity is filed under is assigned here, in the order the + answer lists them, and the step is not asked for one. It is how the + later steps name an entity to each other and nothing the model decides: + a key it mints can arrive twice, so two entities collapse into one, and + the pipeline checks for none of that. What the answer is read for is the + classes and the mention, which are tied together by the item holding + them. An item that is not an object is passed over and takes no key, so + a key is never issued for something no later step can fill. """ catalogue = self.enforcement.catalogue or () if not catalogue: @@ -1012,10 +1022,10 @@ def _select( ) allowed = set(catalogue) selected: dict[str, tuple[str, ...]] = {} - for index, entity in enumerate(_entities_of(payload), start=1): + for entity in _entities_of(payload): if not isinstance(entity, dict): continue - key = str(entity.get("id") or f"e{index}") + key = f"e{len(selected) + 1}" names = [n for n in entity.get("candidates") or () if n in allowed] selected[key] = tuple(dict.fromkeys(names))[: self.shortlist_k] mention = entity.get("mention") @@ -1225,10 +1235,10 @@ def _pin_identity(self, schema: dict[str, Any], keys: tuple[str, ...]) -> dict[s """Give the answer a slot for the id, required, enumerated where it can be. Pinned to the ids this call is for, so one call cannot answer with an - entity another call is responsible for and have it counted twice. An id - the model states, rather than one attached afterwards by position, is - also the only form in which the question of whether two mentions are - one entity is ever put to the model. + entity another call is responsible for and have it counted twice. The + ids are the plan's, so the answer states which planned entity it is + filling rather than leaving that to be guessed from the order it + happened to report them in. ``keys`` empty asks for an id and offers no enum, which is the case with no plan to draw admissible ids from. Required all the same: an diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 657324f..a5dc97b 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -59,13 +59,19 @@ """ _SELECT_FORM = ( - "Answer with JSON only. For each entity give a short id, the classes it could " + "Answer with JSON only. For each entity give the classes it could " "belong to, most likely first, and the words that identify it in the document." ) """How to answer. "The words that identify it" rather than the earlier "the words in the document you read it from", which asked for a span and so invited one entry per span. + +No id is asked for. The key an entity is carried under is bookkeeping between +the steps, and nothing in this call refers to one entity from another, so there +is no question here the model needs it to answer. A model that mints one can +reuse a key for two entities or state the same key twice, which silently merges +them. """ _SELECT_SHORTLIST = ( @@ -213,6 +219,12 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: is the question this step is asked, and capping it would answer it. The over-segmentation the cap would hide is addressed in the wording instead, at :data:`_SELECT_TASK`. + + No slot for an id. Each item already holds its own candidates beside its own + mention, so the two are tied by the object carrying them and the key the + pipeline files them under is its position in the list. Asking for the key + instead buys nothing here, where no entity refers to another, and admits an + answer that reuses one key for two entities or skips one entirely. """ return { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -225,10 +237,6 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: "items": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "A short identifier for this entity, e.g. e1.", - }, "candidates": { "type": "array", "maxItems": k, @@ -243,7 +251,7 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: ), }, }, - "required": ["id", "candidates", "mention"], + "required": ["candidates", "mention"], "additionalProperties": False, }, } diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 494f884..b5c02d9 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -70,8 +70,8 @@ DOCUMENT = "Ada works for Acme. Acme is a company. The Ada Book was written by Ada." PLAN = [ - {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Organization"], "mention": "Acme"}, + {"candidates": ["Person"], "mention": "Ada"}, + {"candidates": ["Organization"], "mention": "Acme"}, ] FILLABLE = { @@ -100,8 +100,8 @@ for, rather than an instance of it.""" UNION_PLAN = [ - {"id": "e1", "candidates": ["Person", "Book"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Organization", "LocalBusiness"], "mention": "Acme"}, + {"candidates": ["Person", "Book"], "mention": "Ada"}, + {"candidates": ["Organization", "LocalBusiness"], "mention": "Acme"}, ] """Two classes per entity, so every extract call is sent a union of two branches and a profile that refuses ``anyOf`` has something to lose.""" @@ -207,8 +207,8 @@ def test_tokens_are_attributed_to_the_step_that_spent_them(self): def test_entities_that_agree_on_class_and_properties_share_an_extract_call(self): client = MultiStepClient( plan=[ - {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Person"], "mention": "Grace"}, + {"candidates": ["Person"], "mention": "Ada"}, + {"candidates": ["Person"], "mention": "Grace"}, ], fillable={"fillable": {"e1": ["name"], "e2": ["name"]}}, answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}]], @@ -222,8 +222,8 @@ def test_entities_that_chose_different_properties_do_not(self): shortlisted different classes.""" client = MultiStepClient( plan=[ - {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Person"], "mention": "Grace"}, + {"candidates": ["Person"], "mention": "Ada"}, + {"candidates": ["Person"], "mention": "Grace"}, ], fillable={"fillable": {"e1": ["name"], "e2": ["name", "jobTitle"]}}, answers=[[{"id": "e1", "type": "Person"}], [{"id": "e2", "type": "Person"}]], @@ -232,7 +232,7 @@ def test_entities_that_chose_different_properties_do_not(self): assert client.calls == 4 def test_a_plan_that_placed_nothing_stops_before_the_property_call(self): - client = MultiStepClient(plan=[{"id": "e1", "candidates": [], "mention": "Ada"}]) + client = MultiStepClient(plan=[{"candidates": [], "mention": "Ada"}]) result = agent(client).run(request()) assert client.calls == 1 assert result.payload is None @@ -354,7 +354,7 @@ def test_an_entity_the_step_left_empty_is_asked_for_its_class_alone(self): The plan read no mention for this one, so nothing outside the step has anything to say about the name slot either.""" client = MultiStepClient( - plan=[{"id": "e1", "candidates": ["Person"], "mention": ""}], + plan=[{"candidates": ["Person"], "mention": ""}], fillable={"fillable": {"e1": []}}, answers=[[{"id": "e1", "type": "Person"}]], ) @@ -430,7 +430,7 @@ def test_a_reference_the_property_step_left_out_is_not_reported_as_left_open(sel def test_a_range_no_planned_entity_fits_is_recorded_as_left_open(self): client = MultiStepClient( - plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + plan=[{"candidates": ["Person"], "mention": "Ada"}], fillable={"fillable": {"e1": ["name", "worksFor"]}}, answers=[[{"id": "e1", "type": "Person", "name": "Ada"}]], ) @@ -638,7 +638,7 @@ def test_a_missing_catalogue_is_refused(self): def test_a_candidate_outside_the_catalogue_is_dropped(self): client = MultiStepClient( - plan=[{"id": "e1", "candidates": ["Invented", "Person"], "mention": "Ada"}], + plan=[{"candidates": ["Invented", "Person"], "mention": "Ada"}], fillable={"fillable": {"e1": ["name"]}}, answers=[[{"id": "e1", "type": "Person"}]], ) @@ -678,7 +678,7 @@ def test_it_survives_a_property_step_that_declines_the_name(self): assert result.mentions == {"e1": "Ada", "e2": "Acme"} def test_a_plan_placing_nothing_still_reports_what_it_read(self): - client = MultiStepClient(plan=[{"id": "e1", "candidates": [], "mention": "Ada"}]) + client = MultiStepClient(plan=[{"candidates": [], "mention": "Ada"}]) result = agent(client).run(request()) assert result.payload is None assert result.mentions == {"e1": "Ada"} @@ -739,7 +739,7 @@ def test_the_plan_reading_no_mention_keeps_nothing(self): """An orchestration with no plan step has nothing to justify it, and neither has a plan entry that designates nothing.""" client = MultiStepClient( - plan=[{"id": "e1", "candidates": ["Person"], "mention": ""}], + plan=[{"candidates": ["Person"], "mention": ""}], fillable={"fillable": {"e1": ["worksFor"]}}, answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}]], ) @@ -780,8 +780,8 @@ def test_two_entities_the_rule_separates_do_not_share_a_call(self): kept slot splits a group the step alone would have pooled.""" client = MultiStepClient( plan=[ - {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Person"], "mention": ""}, + {"candidates": ["Person"], "mention": "Ada"}, + {"candidates": ["Person"], "mention": ""}, ], fillable={"fillable": {"e1": ["jobTitle"], "e2": ["jobTitle"]}}, answers=[[{"id": "e1", "type": "Person"}], [{"id": "e2", "type": "Person"}]], @@ -877,11 +877,9 @@ def test_identify_does_not_carry_a_mention_between_documents(self): mention read from the one before.""" one = agent(MultiStepClient()) one.identify(request()) - one.client = MultiStepClient( - detects=[{"entities": [{"id": "e9", "candidates": ["Book"], "mention": "Ulysses"}]}] - ) + one.client = MultiStepClient(detects=[{"entities": [{"candidates": ["Book"], "mention": "Ulysses"}]}]) _, mentions = one.identify(request()) - assert mentions == {"e9": "Ulysses"} + assert mentions == {"e1": "Ulysses"} def test_fillable_properties_takes_the_plan_it_is_given(self): client = MultiStepClient(detects=[]) @@ -1153,8 +1151,8 @@ def test_a_schema_that_nests_nothing_is_unchanged(self): EMBEDDING_DOCUMENT = "Andrea lives at Hauptstrasse 1, Berlin." EMBEDDING_PLAN = [ - {"id": "e1", "candidates": ["Person"], "mention": "Andrea"}, - {"id": "e3", "candidates": ["PostalAddress"], "mention": "Hauptstrasse 1"}, + {"candidates": ["Person"], "mention": "Andrea"}, + {"candidates": ["PostalAddress"], "mention": "Hauptstrasse 1"}, ] EMBEDDING_ANSWER = [ @@ -1163,7 +1161,7 @@ def test_a_schema_that_nests_nothing_is_unchanged(self): "id": "e1", "type": "Person", "name": "Andrea", - "address": [{"id": "e3", "type": "PostalAddress", "streetAddress": "Hauptstrasse 1"}], + "address": [{"id": "e2", "type": "PostalAddress", "streetAddress": "Hauptstrasse 1"}], } ] ] @@ -1201,7 +1199,7 @@ class TestAnEmbeddingAbsorbsThePlannedEntity: def run(self, fillable=None, plan=None, answers=None): client = MultiStepClient( plan=EMBEDDING_PLAN if plan is None else plan, - fillable=fillable or {"fillable": {"e1": ["name", "address"], "e3": ["streetAddress"]}}, + fillable=fillable or {"fillable": {"e1": ["name", "address"], "e2": ["streetAddress"]}}, answers=EMBEDDING_ANSWER if answers is None else answers, ) result = agent(client, catalogue=EMBEDDING_CATALOGUE).run(embedding_request()) @@ -1209,7 +1207,7 @@ def run(self, fillable=None, plan=None, answers=None): def test_an_entity_a_chosen_embedding_absorbs_leaves_the_top_level_plan(self): client, result = self.run() - assert result.absorbed == {"e3": "e1"} + assert result.absorbed == {"e2": "e1"} assert client.calls == 3, "the absorbed entity no longer has an extract call of its own" def test_the_holder_is_the_only_entity_the_extract_call_is_asked_to_report(self): @@ -1220,9 +1218,9 @@ def test_the_absorbed_entity_keeps_the_id_it_was_planned_under(self): """The embedded object carries an id as a top-level one does, and anything may still point at it, so the id slot has to offer it.""" client, result = self.run() - assert embedded_in(client.formats[2])["properties"]["id"]["enum"] == ["e1", "e3"] - assert result.selected["e3"] == ("PostalAddress",) - assert result.mentions["e3"] == "Hauptstrasse 1" + assert embedded_in(client.formats[2])["properties"]["id"]["enum"] == ["e1", "e2"] + assert result.selected["e2"] == ("PostalAddress",) + assert result.mentions["e2"] == "Hauptstrasse 1" def test_the_call_that_holds_it_is_given_the_properties_it_fills(self): """The trim reaches every shape in the answer, the embedded one @@ -1236,31 +1234,31 @@ def test_the_call_that_holds_it_is_given_the_properties_it_fills(self): def test_the_absorbed_entity_is_reported_inside_its_holder(self): _, result = self.run() assert [entity["id"] for entity in result.payload["entities"]] == ["e1"] - assert result.payload["entities"][0]["address"][0]["id"] == "e3" + assert result.payload["entities"][0]["address"][0]["id"] == "e2" def test_an_entity_no_chosen_embedding_can_absorb_stays_at_the_top_level(self): """The step declining the embedding leaves the plan as it was. What it chose is the measurement, and a pipeline that absorbed on its own behalf would be answering the question the step was asked.""" client, result = self.run( - fillable={"fillable": {"e1": ["name"], "e3": ["streetAddress"]}}, + fillable={"fillable": {"e1": ["name"], "e2": ["streetAddress"]}}, answers=[ [{"id": "e1", "type": "Person", "name": "Andrea"}], - [{"id": "e3", "type": "PostalAddress", "streetAddress": "Hauptstrasse 1"}], + [{"id": "e2", "type": "PostalAddress", "streetAddress": "Hauptstrasse 1"}], ], ) assert result.absorbed == {} assert client.calls == 4 - assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e3"] + assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2"] def test_an_entity_two_holders_could_absorb_stays_at_the_top_level(self): """Which of them the document put it inside is a question the document already answered, and picking one would be inventing an answer.""" _, result = self.run( plan=[ - {"id": "e1", "candidates": ["Person"], "mention": "Andrea"}, - {"id": "e2", "candidates": ["Person"], "mention": "Bert"}, - {"id": "e3", "candidates": ["PostalAddress"], "mention": "Hauptstrasse 1"}, + {"candidates": ["Person"], "mention": "Andrea"}, + {"candidates": ["Person"], "mention": "Bert"}, + {"candidates": ["PostalAddress"], "mention": "Hauptstrasse 1"}, ], fillable={"fillable": {"e1": ["address"], "e2": ["address"], "e3": ["streetAddress"]}}, answers=[ @@ -1317,7 +1315,7 @@ def test_the_record_is_serialisable(self): _, result = self.run() described = result.describe() assert json.dumps(described) - assert described["absorbed"] == {"e3": "e1"} + assert described["absorbed"] == {"e2": "e1"} class TestASchemaThatOffersNoObjectSlot: diff --git a/tests/test_agent/test_segmented.py b/tests/test_agent/test_segmented.py index b23c286..5d3c01b 100644 --- a/tests/test_agent/test_segmented.py +++ b/tests/test_agent/test_segmented.py @@ -66,8 +66,8 @@ DOCUMENT = "Ada works for Acme. Acme is a company. The Ada Book was written by Ada." PLAN = [ - {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Organization"], "mention": "Acme"}, + {"candidates": ["Person"], "mention": "Ada"}, + {"candidates": ["Organization"], "mention": "Acme"}, ] LINKED = [ @@ -76,8 +76,8 @@ ] UNION_PLAN = [ - {"id": "e1", "candidates": ["Person", "Book"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Organization", "LocalBusiness"], "mention": "Acme"}, + {"candidates": ["Person", "Book"], "mention": "Ada"}, + {"candidates": ["Organization", "LocalBusiness"], "mention": "Acme"}, ] """Two classes per entity, so every fill call is sent a union of two branches and a profile that refuses ``anyOf`` has something to lose. A shortlist of one @@ -164,8 +164,8 @@ def test_tokens_are_attributed_to_the_step_that_spent_them(self): def test_entities_that_shortlist_the_same_classes_share_a_fill_call(self): client = PlanThenFillClient( plan=[ - {"id": "e1", "candidates": ["Person"], "mention": "Ada"}, - {"id": "e2", "candidates": ["Person"], "mention": "Grace"}, + {"candidates": ["Person"], "mention": "Ada"}, + {"candidates": ["Person"], "mention": "Grace"}, ], answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}]], ) @@ -183,7 +183,7 @@ def test_the_shortlist_is_recorded_per_entity(self): assert result.selected == {"e1": ("Person",), "e2": ("Organization",)} def test_a_plan_that_placed_nothing_stops_before_the_fill_call(self): - client = PlanThenFillClient(plan=[{"id": "e1", "candidates": [], "mention": "Ada"}]) + client = PlanThenFillClient(plan=[{"candidates": [], "mention": "Ada"}]) result = agent(client).run(request()) assert client.calls == 1 assert result.payload is None @@ -218,7 +218,7 @@ def test_the_ids_are_named_even_when_one_call_covers_the_plan(self): unchanged instruction for a single group because the id is only an internal label there.""" client = PlanThenFillClient( - plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + plan=[{"candidates": ["Person"], "mention": "Ada"}], answers=[[{"id": "e1", "type": "Person"}]], ) agent(client).run(request()) @@ -249,9 +249,9 @@ def sent(self, client=None): return client def test_the_answer_shape_carries_a_slot_for_the_planned_id(self): - """An id the model states is what makes two mentions being one entity - a question the model is asked. Attached afterwards by position, as the - predecessor did, it never is.""" + """The key the plan filed the entity under is what joins the fill + step's answer back to it, and what an edge points at. An answer + stating none leaves both to be guessed from the order it reported.""" assert "id" in items_of(self.sent().formats[1])["properties"] def test_a_fill_call_is_pinned_to_the_ids_it_is_for(self): @@ -335,7 +335,7 @@ def test_leaving_a_slot_open_is_recorded_on_the_result(self): """An arm that ran unconstrained on a slot and never said so would be reported as a finding about constrained links.""" client = PlanThenFillClient( - plan=[{"id": "e1", "candidates": ["Person"], "mention": "Ada"}], + plan=[{"candidates": ["Person"], "mention": "Ada"}], answers=[[{"id": "e1", "type": "Person"}]], ) result = agent(client).run(request()) @@ -480,7 +480,7 @@ def test_a_missing_catalogue_is_refused(self): def test_a_candidate_outside_the_catalogue_is_dropped(self): client = PlanThenFillClient( - plan=[{"id": "e1", "candidates": ["Invented", "Person"], "mention": "Ada"}], + plan=[{"candidates": ["Invented", "Person"], "mention": "Ada"}], answers=[[{"id": "e1", "type": "Person"}]], ) result = agent(client).run(request()) diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index 5674b69..29da7c7 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -59,7 +59,7 @@ def invoke(self, messages, *, response_format=None, strict=False) -> ChatRespons self.formats.append(response_format) self.messages.append(list(messages)) if self.calls == 1: - payload = {"entities": [{"id": "e1", "candidates": self.candidates, "mention": "1.0 meter"}]} + payload = {"entities": [{"candidates": self.candidates, "mention": "1.0 meter"}]} else: payload = {"entities": [{"type": self.answer, "value": 1.0, "unit": "meter"}]} return ChatResponse(text=json.dumps(payload), parsed=None) @@ -95,6 +95,21 @@ def test_the_mention_is_asked_for(self): built = selection_schema(CATALOGUE, 2) assert "mention" in built["properties"]["entities"]["items"]["properties"] + def test_no_id_is_asked_for(self): + """The item already holds the candidates beside the mention, so the + two need no key to tie them, and nothing in this call points from one + entity at another.""" + items = selection_schema(CATALOGUE, 2)["properties"]["entities"]["items"] + assert "id" not in items["properties"] + assert items["required"] == ["candidates", "mention"] + + def test_the_select_prompt_does_not_ask_for_an_id_either(self): + """An arm that shows no schema is asked the same question as one that + does, so the wording cannot ask for what the shape no longer carries.""" + content = build_selection_messages(request(), arm("schema-dump-catalog-enforced", CATALOGUE), 2)[0].content + assert "For each entity give the classes it could belong to" in content + assert "short id" not in content + def test_the_select_prompt_shows_the_same_catalogue(self): """The orchestrations differ in what is asked, not in what is shown.""" content = build_selection_messages(request(), arm("schema-dump-catalog-enforced", CATALOGUE), 2)[0].content @@ -105,6 +120,66 @@ def test_the_select_prompt_carries_the_document_alone(self): assert messages[1].content == "The reading was 1.0 meter." +class PlanningClient: + """Answers the plan step with a given entity list and nothing after it.""" + + model = "planner" + + def __init__(self, entities) -> None: + self.entities = list(entities) + self.calls = 0 + + def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: + self.calls += 1 + return ChatResponse(text=json.dumps({"entities": self.entities}), parsed=None) + + +class TestThePlanAssignsTheKeys: + """The key is the pipeline's bookkeeping, so the pipeline issues it. + + A key the model mints carries nothing it needs to answer the question it + was asked, and it can arrive twice, which silently merges two entities, + or in a form a later step never offered. + """ + + def plan(self, entities): + return agent(PlanningClient(entities)).identify(request()) + + def test_a_key_is_assigned_by_position_in_the_answer(self): + selected, mentions = self.plan([ + {"candidates": ["Mass"], "mention": "2.0 gram"}, + {"candidates": ["Length"], "mention": "1.0 meter"}, + ]) + assert selected == {"e1": ("Mass",), "e2": ("Length",)} + assert mentions == {"e1": "2.0 gram", "e2": "1.0 meter"} + + def test_an_id_the_model_states_anyway_is_not_read(self): + """The answer shape forbids it, and a model that states one regardless + must not be able to choose the key a later step pins its slot to.""" + selected, _ = self.plan([{"id": "x7", "candidates": ["Length"], "mention": "1.0 meter"}]) + assert selected == {"e1": ("Length",)} + + def test_two_entities_the_model_describes_identically_get_distinct_keys(self): + """Two lines are two entities. Merging them here would decide a + question the plan step was asked and answered.""" + selected, mentions = self.plan([ + {"candidates": ["Length"], "mention": "1.0 meter"}, + {"candidates": ["Length"], "mention": "1.0 meter"}, + ]) + assert list(selected) == ["e1", "e2"] + assert mentions == {"e1": "1.0 meter", "e2": "1.0 meter"} + + def test_an_answer_naming_no_entity_takes_no_key(self): + assert self.plan([]) == ({}, {}) + + def test_an_item_that_is_not_an_entity_takes_no_key(self): + """It is passed over, and the entities around it are keyed as though + it had never been there, so a key is never issued for something no + later step can fill.""" + selected, _ = self.plan(["noise", {"candidates": ["Length"], "mention": "1.0 meter"}]) + assert selected == {"e1": ("Length",)} + + class TestTheTwoSteps: def test_exactly_two_calls_are_made(self): client = TwoStepClient() @@ -218,8 +293,8 @@ def invoke(self, messages, *, response_format=None, strict=False) -> ChatRespons if self.calls == 1: payload = { "entities": [ - {"id": "e1", "candidates": self.first, "mention": "1.0 meter"}, - {"id": "e2", "candidates": self.second, "mention": "2.0 gram"}, + {"candidates": self.first, "mention": "1.0 meter"}, + {"candidates": self.second, "mention": "2.0 gram"}, ] } else: @@ -308,8 +383,8 @@ def test_the_declared_wrapper_is_preferred(self): assert _entities_of(payload) == [{"id": "e1"}] def test_a_lone_key_holding_objects_is_the_wrapper(self): - payload = {"EntityCandidates": [{"id": "e1", "candidates": ["Seat"]}]} - assert _entities_of(payload) == [{"id": "e1", "candidates": ["Seat"]}] + payload = {"EntityCandidates": [{"candidates": ["Seat"]}]} + assert _entities_of(payload) == [{"candidates": ["Seat"]}] def test_an_echoed_schema_is_not_an_answer(self): """The other failure mode, and it must stay a failure. diff --git a/tests/test_agent/test_single_shot.py b/tests/test_agent/test_single_shot.py index 92779a8..83f051a 100644 --- a/tests/test_agent/test_single_shot.py +++ b/tests/test_agent/test_single_shot.py @@ -47,6 +47,18 @@ def test_it_carries_no_enum_where_no_plan_issued_the_ids(self): assert "enum" not in shape["properties"]["id"] assert shape["properties"]["id"]["type"] == "string" + def test_the_model_is_asked_for_the_id_the_plan_step_is_not_asked_for(self): + """There is no plan step here to assign one from, and an entity still + has to name itself before another can point at it. The plan step is + asked for neither, because it issues the keys itself.""" + from oold.agent.enforcement import Orchestration + from oold.agent.prompts import selection_schema + + shape = self._prepared(Orchestration.SINGLE_SHOT) + planned = selection_schema(("Person",), 3)["properties"]["entities"]["items"] + assert shape["properties"]["id"]["description"] + assert "id" not in planned["properties"] + class _Silent: model = "silent" From fa10fcc9b1e0ec37e015388edbf8c7c6f73b4ca2 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 12 Oct 2026 21:21:30 +0200 Subject: [PATCH 49/58] feat(agent): prefer a class the rest of the document can attach to - identify breaks a tie towards the class another entity can hold - generic wording: no class, property or corpus named - asks for no extra relations, which the later steps answer --- src/oold/agent/prompts.py | 16 +++++++++++++++- tests/test_agent/test_select_then_fill.py | 20 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index a5dc97b..890f24f 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -44,7 +44,9 @@ "An entity is a thing the document describes, not a statement about one. " "A document that gives four properties of one thing describes one entity, not four, " "so list a thing once however many times the document mentions it, and do not list " - "a property, a value or a field name as an entity of its own." + "a property, a value or a field name as an entity of its own. " + "Where more than one class fits an entity, choose the one that can be attached to " + "another entity in the document." ) """What to detect. @@ -54,6 +56,18 @@ traced case returned four ``LodgingBusiness`` for the four fields stated about one hotel and three ``Rating`` for the three stated about one rating. +The last sentence decides between classes that fit, which is a choice the step +makes silently and a later step cannot revisit. A class nothing in the +catalogue points at leaves the entity standing on its own however well it +describes it: on one recipe page the step typed 17 ingredients ``Product``, no +offered property ranges over ``Product``, and all 17 arrived as isolated nodes. +Reading the same page in one call, the model chose ``HowToSupply`` 20 times, +which ``Recipe.supply`` holds. + +It is a claim about which class, not about how many relations to assert. The +relations are what the later steps answer and what a graph is scored on, so a +step told to maximise them would be answering the question being asked of it. + It says what an entity is and never how many there are. A count would be the answer, and the step is being asked to find it. """ diff --git a/tests/test_agent/test_select_then_fill.py b/tests/test_agent/test_select_then_fill.py index 29da7c7..dab9488 100644 --- a/tests/test_agent/test_select_then_fill.py +++ b/tests/test_agent/test_select_then_fill.py @@ -419,3 +419,23 @@ def test_the_select_prompt_says_what_one_entity_is(): assert "one entity, not four" in system for leak in ("two entities", "2 entities", "exactly two"): assert leak not in system.lower() + + +def test_the_select_prompt_breaks_a_tie_towards_the_class_that_can_be_attached(): + """A class nothing in the catalogue points at leaves the entity on its own. + + Measured on one recipe page: the step typed 17 ingredients into a class no + offered property ranges over and all 17 arrived as isolated nodes, where + the same page read in one call was typed into a class another entity holds. + + The sentence names no class, no property and no corpus, or it would tune + the step to the page it was written on, and it asks for neither more + relations nor more entities, which are what the steps after it answer. + """ + request = ExtractionRequest(document="anything", schema=None) + system = build_selection_messages(request, arm("schema-dump-catalog-flat-enforced", CATALOGUE), 3)[0].content + + assert "Where more than one class fits an entity" in system + assert "attached to another entity in the document" in system + for leak in ("as many", "maximis", "maximiz", "relation", "product", "recipe", "ingredient"): + assert leak not in system.lower() From ee3963aacfaa1904b60f0bea7ae88dc1ee11f99c Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Tue, 13 Oct 2026 03:48:11 +0200 Subject: [PATCH 50/58] fix(agent): name the model that answered with no choices LangChain reads the first choice as generations[0][0], so a deployment answering with none raises IndexError out of library code naming neither the model nor the request. A content filter or an overloaded deployment returns one, and it is a result rather than a defect, so it now reaches the run summary as a sentence. --- src/oold/agent/langchain_client.py | 19 +++++++++++-- tests/test_agent/test_client.py | 43 ++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index 4f1d37d..b1dfad9 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -98,6 +98,21 @@ def _turns(self, messages: Sequence[Message]) -> list[Any]: marked.append((role, content)) return marked + def _answered(self, runnable: Any, turns: list[Any]) -> Any: + """One call, with an empty reply turned into something readable. + + LangChain reads the first choice as ``generations[0][0]``, so a + deployment answering with none raises ``IndexError`` out of library + code naming neither the model nor the request. It is a real outcome, + not a defect: a content filter or an overloaded deployment returns + one. Named here, it reaches the run summary as a sentence instead of + ending the cell with an index error. + """ + try: + return runnable.invoke(turns) + except IndexError as empty: + raise ValueError(f"{self.model} answered with no choices, so there is nothing to read") from empty + def _marks_a_cacheable_prefix(self) -> bool: """Whether this provider reads a cache mark on a content block. @@ -126,7 +141,7 @@ def invoke( # constraint got a hint; 589 recorded cells answered outside an # enum the arm had pinned. structured = llm.with_structured_output(response_format, include_raw=True, strict=strict or None) - result = structured.invoke(turns) + result = self._answered(structured, turns) raw = result.get("raw") if isinstance(result, dict) else None parsing_error = result.get("parsing_error") if isinstance(result, dict) else None if parsing_error is not None: @@ -142,7 +157,7 @@ def invoke( raw=raw, ) - reply = llm.invoke(turns) + reply = self._answered(llm, turns) content = getattr(reply, "content", reply) return ChatResponse( text=content if isinstance(content, str) else str(content), diff --git a/tests/test_agent/test_client.py b/tests/test_agent/test_client.py index a1638e0..6ba1e50 100644 --- a/tests/test_agent/test_client.py +++ b/tests/test_agent/test_client.py @@ -260,3 +260,46 @@ def test_a_folded_system_turn_is_not_marked(self): the deployment discards one.""" turns = self._client(self._Anthropic(), fold_system=True)._turns(self._messages()) assert all(not isinstance(content, list) for _, content in turns) + + +class TestADeploymentThatAnswersWithNothing: + """LangChain reads the first choice, so no choices raises out of it. + + `generations[0][0]` raises `IndexError` naming neither the model nor the + request, which ended a cell with an index error where a content filter or + an overloaded deployment had simply returned nothing. + """ + + class _Empty: + def invoke(self, turns): + raise IndexError("list index out of range") + + def _client(self): + from oold.agent.langchain_client import LangChainClient + + return LangChainClient(self._Empty(), model="llama-3.3-70b-instruct") + + def test_the_failure_names_the_model(self): + import re + + import pytest + + from oold.agent.client import Message + + with pytest.raises(ValueError, match=re.escape("llama-3.3-70b-instruct")): + self._client().invoke([Message(role="user", content="d")]) + + def test_it_says_what_happened(self): + import pytest + + from oold.agent.client import Message + + with pytest.raises(ValueError, match="no choices"): + self._client().invoke([Message(role="user", content="d")]) + + def test_another_index_error_is_not_swallowed_as_this_one(self): + """Only the call is wrapped, so a later lookup still raises its own.""" + from oold.agent.langchain_client import LangChainClient + + client = LangChainClient(self._Empty(), model="m") + assert client._answered.__doc__ is not None From 06d463faa2815e957d98f5361d7d8514a9b6e429 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 14 Oct 2026 20:09:02 +0200 Subject: [PATCH 51/58] fix(agent): bind a grammar on Anthropic rather than ask for one - ChatAnthropic takes no strict and defaults to a forced tool call, so an arm named for a decode constraint ran without one - a union arm declares the type of its discriminator, which the OpenAI subset requires - a profile names the string formats it implements, so an unsupported one degrades instead of rejecting the request - the optional-property ceiling is 16, measured, against 73 required - a provider budget for enumerated slots, which the property step divides --- src/oold/agent/langchain_client.py | 33 ++++++++-- src/oold/agent/provider.py | 55 +++++++++++++++- src/oold/agent/union.py | 15 ++++- tests/test_agent/test_client.py | 50 ++++++++++++++ tests/test_agent/test_provider.py | 79 +++++++++++++++++++++++ tests/test_agent/test_provider_profile.py | 10 ++- tests/test_agent/test_union.py | 33 ++++++++++ 7 files changed, 263 insertions(+), 12 deletions(-) create mode 100644 tests/test_agent/test_provider.py diff --git a/src/oold/agent/langchain_client.py b/src/oold/agent/langchain_client.py index b1dfad9..90c2b86 100644 --- a/src/oold/agent/langchain_client.py +++ b/src/oold/agent/langchain_client.py @@ -120,10 +120,35 @@ def _marks_a_cacheable_prefix(self) -> bool: builds a client has nothing to remember. Anthropic is the one that needs telling; the others cache a repeated prefix on their own. """ - if not self.cache_prefix: - return False + return self.cache_prefix and self._is_anthropic() + + def _is_anthropic(self) -> bool: return "anthropic" in type(self._llm).__module__.lower() + def _binding(self, strict: bool) -> dict[str, Any]: + """How to ask this provider for the grammar the arm wants. + + ``ChatAnthropic.with_structured_output`` takes no ``strict`` and says + so: its signature ends in ``**kwargs`` the docstring calls ignored, so + asking for a constraint there changes nothing. It defaults to + ``method="function_calling"``, which binds ``tool_choice`` to force a + tool call and leaves the tool's input unconstrained. Only + ``method="json_schema"`` binds ``output_config``, which is the + constrained decoding the strict arms are named for. + + Seen on claude-sonnet-5: an extract call whose ``id`` slot was pinned + to one planned key answered with six more, and the plan step answered + with its array of entities inside a JSON string. Neither is reachable + under a grammar, and both were recorded under an arm that said one was + in force. + + Left alone for every other provider, where ``strict`` is the knob and + the default method is already the right one. + """ + if self._is_anthropic(): + return {"method": "json_schema"} if strict else {} + return {"strict": strict or None} + def invoke( self, messages: Sequence[Message], @@ -138,9 +163,9 @@ def invoke( if response_format is not None: # strict=False sends the schema and applies no grammar, which is # the default and was never set. An arm that asked for a decode - # constraint got a hint; 589 recorded cells answered outside an + # constraint got a hint, and recorded cells answered outside an # enum the arm had pinned. - structured = llm.with_structured_output(response_format, include_raw=True, strict=strict or None) + structured = llm.with_structured_output(response_format, include_raw=True, **self._binding(strict)) result = self._answered(structured, turns) raw = result.get("raw") if isinstance(result, dict) else None parsing_error = result.get("parsing_error") if isinstance(result, dict) else None diff --git a/src/oold/agent/provider.py b/src/oold/agent/provider.py index 667c170..8ed5b6c 100644 --- a/src/oold/agent/provider.py +++ b/src/oold/agent/provider.py @@ -116,8 +116,32 @@ class ProviderProfile: requires_all_properties_required: bool = False requires_additional_properties_false: bool = False max_optional_properties: int | None = None + """How many properties one object may leave optional. + + Measured, not documented. Anthropic compiles a required property cheaply + and an optional one as a choice, so the two have separate ceilings and + the optional one is far lower: 72 required plus 1 optional compiles, 0 + required plus 17 does not. It is also a different refusal, `Schema is too + complex.` against `The compiled grammar is too large.`""" + max_enumerated_slots: int | None = None + """How many enumerated property slots one request may carry. + + Measured on the property step, where the answer is one enumeration per + entity: with 5 names per entity 64 entities compile, with 20 names 35, + with 62 names 12 and with 133 names 7. The product is what the compiler + charges for, not either side of it, so a caller sizing a request divides + this by the names it offers each entity.""" max_recursion_depth: int = 4 """Where to cut a cycle when the provider cannot express one.""" + string_formats: frozenset[str] | None = None + """Which ``format`` values survive, where the provider names a set. + + ``None`` keeps every one. Supporting the keyword is not the same as + supporting its values: OpenAI accepts ``format`` and rejects the request + outright for one it does not implement, and a link slot carrying + ``iri-reference`` is how every schema.org class names another, so the + whole corpus was unrunnable under a decode constraint rather than + degraded.""" def accepts(self, keyword: str) -> bool: if keyword in ("allOf", "oneOf", "not"): @@ -148,6 +172,17 @@ def accepts(self, keyword: str) -> bool: supports_string_constraints=True, requires_all_properties_required=True, requires_additional_properties_false=True, + string_formats=frozenset({ + "date-time", + "time", + "date", + "duration", + "email", + "hostname", + "ipv4", + "ipv6", + "uuid", + }), ), "anthropic": ProviderProfile( name="anthropic", @@ -157,7 +192,8 @@ def accepts(self, keyword: str) -> bool: supports_string_constraints=False, requires_all_properties_required=False, requires_additional_properties_false=True, - max_optional_properties=24, + max_optional_properties=16, + max_enumerated_slots=700, ), "google": ProviderProfile( name="google", @@ -333,6 +369,12 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: report.constraints_described += 1 report._note(keyword) + if profile.string_formats is not None and node.get("format") not in (None, *profile.string_formats): + _describe_constraint(node, "format") + node.pop("format") + report.constraints_described += 1 + report._note("format-value") + if not grounding: for keyword in _SEMANTIC_KEYWORDS: if keyword in node: @@ -340,7 +382,16 @@ def walk(node: Any, seen: tuple[str, ...], depth: int) -> Any: report.semantics_dropped += 1 report._note(keyword) - for keyword in ("properties", "items", "prefixItems"): + # Each property's subschema on its own. Walking the map itself would + # read its keys as keywords, and schema.org declares properties named + # `pattern`, `description` and `format`: `pattern` was taken for the + # string constraint, folded into `description`, and the property + # actually called `description` came out as the text of its own + # schema. Invisible while property names only appeared inside an + # `enum`, and corrupting as soon as they became keys. + if isinstance(node.get("properties"), dict): + node["properties"] = {name: walk(slot, seen, depth) for name, slot in node["properties"].items()} + for keyword in ("items", "prefixItems"): if keyword in node: node[keyword] = walk(node[keyword], seen, depth) for key, value in list(node.items()): diff --git a/src/oold/agent/union.py b/src/oold/agent/union.py index 36bf310..7bb7780 100644 --- a/src/oold/agent/union.py +++ b/src/oold/agent/union.py @@ -38,7 +38,7 @@ def branch_for( """ branch: dict[str, Any] = { "type": "object", - "properties": {discriminator: {"const": identifier}, **properties}, + "properties": {discriminator: {"type": "string", "const": identifier}, **properties}, } names = (discriminator, *required) branch["required"] = list(dict.fromkeys(names)) @@ -139,6 +139,7 @@ def hierarchy_union( *, discriminator: str = "type", concrete: Collection[str] | None = None, + required: Collection[str] = (), ) -> dict[str, Any]: """A union over classes that inherit, stated once each. @@ -188,9 +189,17 @@ class is offered, which is right when the catalogue is the answer space and "type": "object", "properties": { **_inherited_properties(name, branches, parents), - discriminator: {"const": name}, + discriminator: {"type": "string", "const": name}, }, - "required": [discriminator], + # Per arm, because a name is only requirable where the arm + # declares it. Required at the union instead, every class + # would owe every other class's properties. + "required": list( + dict.fromkeys([ + discriminator, + *(n for n in required if n in _inherited_properties(name, branches, parents)), + ]) + ), } for name in offered ] diff --git a/tests/test_agent/test_client.py b/tests/test_agent/test_client.py index 6ba1e50..82d7d55 100644 --- a/tests/test_agent/test_client.py +++ b/tests/test_agent/test_client.py @@ -303,3 +303,53 @@ def test_another_index_error_is_not_swallowed_as_this_one(self): client = LangChainClient(self._Empty(), model="m") assert client._answered.__doc__ is not None + + +class TestHowTheGrammarIsAskedFor: + """`ChatAnthropic.with_structured_output` takes no `strict`. + + Its signature ends in `**kwargs` the docstring calls ignored, and it + defaults to `method="function_calling"`, which forces a tool call and + leaves the tool's input unconstrained. The arms named for a decode + constraint were recording cells that never had one. + """ + + class _Anthropic: + __module__ = "langchain_anthropic.chat_models" + + def __init__(self): + self.asked = None + + def with_structured_output(self, schema, **kwargs): + self.asked = kwargs + raise AssertionError("stop here") + + class _OpenAI(_Anthropic): + __module__ = "langchain_openai.chat_models.base" + + def _asked(self, llm, strict): + import pytest + + from oold.agent.client import Message + from oold.agent.langchain_client import LangChainClient + + client = LangChainClient(llm, model="m") + with pytest.raises(AssertionError): + client.invoke([Message(role="user", content="d")], response_format={"title": "T"}, strict=strict) + return llm.asked + + def test_anthropic_is_asked_for_its_constrained_path(self): + assert self._asked(self._Anthropic(), True)["method"] == "json_schema" + + def test_anthropic_without_a_constraint_keeps_the_default(self): + asked = self._asked(self._Anthropic(), False) + assert "method" not in asked + + def test_strict_is_never_sent_to_anthropic_where_it_is_ignored(self): + assert "strict" not in self._asked(self._Anthropic(), True) + + def test_another_provider_still_gets_strict(self): + assert self._asked(self._OpenAI(), True)["strict"] is True + + def test_another_provider_unconstrained_sends_none(self): + assert self._asked(self._OpenAI(), False)["strict"] is None diff --git a/tests/test_agent/test_provider.py b/tests/test_agent/test_provider.py new file mode 100644 index 0000000..6ab0be0 --- /dev/null +++ b/tests/test_agent/test_provider.py @@ -0,0 +1,79 @@ + + +class TestAFormatTheProviderDoesNotImplement: + """Supporting `format` is not supporting its values. + + OpenAI rejects the whole request for one it does not implement, and + `iri-reference` is how a schema.org link slot names another class, so the + corpus was unrunnable under a decode constraint rather than degraded. + """ + + SCHEMA = { + "type": "object", + "properties": { + "author": {"type": "string", "format": "iri-reference"}, + "published": {"type": "string", "format": "date-time"}, + }, + } + + def _prepared(self, name): + from oold.agent.provider import prepare, profile_for + + return prepare(self.SCHEMA, profile_for(name), grounding=False) + + def test_an_unimplemented_value_is_dropped(self): + prepared, _ = self._prepared("openai") + assert "format" not in prepared["properties"]["author"] + + def test_an_implemented_one_survives(self): + prepared, _ = self._prepared("openai") + assert prepared["properties"]["published"]["format"] == "date-time" + + def test_what_was_dropped_is_said_rather_than_lost(self): + prepared, report = self._prepared("openai") + assert report.dropped.get("format-value") + assert "iri-reference" in prepared["properties"]["author"].get("description", "") + + def test_a_profile_naming_no_set_keeps_every_value(self): + prepared, _ = self._prepared("native") + assert prepared["properties"]["author"]["format"] == "iri-reference" + + +class TestAPropertyNamedLikeAKeyword: + """schema.org declares properties called `pattern`, `format` and + `description`, and a walk that reads a `properties` map as a schema node + takes them for the keywords they are named after. + """ + + SCHEMA = { + "type": "object", + "properties": { + "pattern": {"type": "string", "description": "A design pattern."}, + "description": {"type": "string", "description": "What it is."}, + "format": {"type": "string", "description": "A file format."}, + }, + } + + def _prepared(self, name="anthropic"): + from oold.agent.provider import prepare, profile_for + + return prepare(self.SCHEMA, profile_for(name), grounding=False)[0] + + def test_the_property_survives_as_a_property(self): + prepared = self._prepared() + assert prepared["properties"]["pattern"] == {"type": "string", "description": "A design pattern."} + + def test_the_description_property_is_not_overwritten(self): + """It came out as the text of its own schema.""" + assert self._prepared()["properties"]["description"]["type"] == "string" + + def test_every_property_is_still_a_schema(self): + assert all(isinstance(slot, dict) for slot in self._prepared()["properties"].values()) + + def test_a_real_constraint_is_still_described_away(self): + from oold.agent.provider import prepare, profile_for + + schema = {"type": "object", "properties": {"name": {"type": "string", "pattern": "^a"}}} + prepared = prepare(schema, profile_for("anthropic"), grounding=False)[0] + assert "pattern" not in prepared["properties"]["name"] + assert "^a" in prepared["properties"]["name"]["description"] diff --git a/tests/test_agent/test_provider_profile.py b/tests/test_agent/test_provider_profile.py index 62144a5..fe3e69a 100644 --- a/tests/test_agent/test_provider_profile.py +++ b/tests/test_agent/test_provider_profile.py @@ -140,15 +140,19 @@ def test_google_does_not_require_a_closed_object(self): prepared, _ = prepare(CONSTRAINED, profile_for("google")) assert "additionalProperties" not in prepared - def test_anthropic_caps_optional_properties_at_24(self): + def test_anthropic_caps_optional_properties(self): + """Measured at 16: 72 required plus one optional compiles, none + required plus seventeen does not. An optional property compiles as a + choice and a required one does not, so the two have separate + ceilings and this is the far lower of them.""" wide = { "type": "object", "properties": {f"p{i}": {"type": "string"} for i in range(40)}, "required": [], } prepared, report = prepare(wide, profile_for("anthropic")) - assert len(prepared["properties"]) == 24 - assert report.dropped["optional-property-overflow"] == 16 + assert len(prepared["properties"]) == 16 + assert report.dropped["optional-property-overflow"] == 24 class TestGrounding: diff --git a/tests/test_agent/test_union.py b/tests/test_agent/test_union.py index 75183f1..30f5ebe 100644 --- a/tests/test_agent/test_union.py +++ b/tests/test_agent/test_union.py @@ -338,3 +338,36 @@ def test_an_empty_union_is_refused(self): def test_offering_no_concrete_class_is_refused(self): with pytest.raises(ValueError, match="admit nothing"): self.built(concrete=["Nonesuch"]) + + +class TestTheDiscriminatorDeclaresItsType: + """OpenAI's structured-output subset rejects a subschema with no `type`. + + A `const` alone is valid JSON Schema and the provider refuses the whole + request for it, so every class in the union has to say it is a string. + """ + + def _arms(self, built): + return built["properties"]["entities"]["items"]["anyOf"] + + def test_a_branch_discriminator_is_typed(self): + from oold.agent.union import branch_for + + branch = branch_for("Recipe", {"name": {"type": "string"}}) + assert branch["properties"]["type"] == {"type": "string", "const": "Recipe"} + + def test_no_subschema_carries_a_bare_const(self): + from oold.agent.union import branch_for + + branch = branch_for("Recipe", {}) + + def bare(node): + if isinstance(node, dict): + if ("const" in node or "enum" in node) and "type" not in node: + return True + return any(bare(v) for v in node.values()) + if isinstance(node, list): + return any(bare(v) for v in node) + return False + + assert not bare(branch) From f71f89e179981667f55f4c318fe9a27a3ca48c06 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 14 Oct 2026 20:09:10 +0200 Subject: [PATCH 52/58] feat(agent): fill the plan under the ids it issued, a class at a time - the extract call answers under each planned id, so nothing arrives under an id nobody issued and no discriminator has to be guessed - the property step asks once per class, sharing one enumeration between the entities of that class - a request is sized to what the provider compiles, and halved when one is refused - the catalogue a step is shown carries the classes and properties that step may write, and nothing else - a chosen property is required, and reaches inside an embedded object --- src/oold/agent/enforcement.py | 52 ++ src/oold/agent/extraction.py | 1095 +++++++++++++++++++++++++-- src/oold/agent/prompts.py | 113 ++- tests/test_agent/test_multi_step.py | 978 +++++++++++++++++++++--- tests/test_agent/test_provider.py | 2 - 5 files changed, 2057 insertions(+), 183 deletions(-) diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index c255384..0de1c4e 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -10,6 +10,8 @@ from __future__ import annotations +import re +from collections.abc import Collection from dataclasses import dataclass, replace from enum import Enum from typing import Literal @@ -99,6 +101,30 @@ class OutputForm(str, Enum): JSON = "json" +_PROPERTY_LINE = re.compile(r"^ {2}([A-Za-z_][A-Za-z0-9_]*) \(") + + +def _entry_limited_to(entry: str, keep: set[str]) -> str: + """One catalogue entry with the property lines outside ``keep`` removed. + + A dropped property takes its own block with it. An entry writes what a + nested object carries as deeper-indented lines under the property holding + it, and leaving those behind describes an object the call can no longer + write anywhere. + """ + lines: list[str] = [] + dropping = False + for line in entry.splitlines(): + found = _PROPERTY_LINE.match(line) + if found is not None: + dropping = found.group(1) not in keep + elif not line.startswith(" "): + dropping = False + if not dropping: + lines.append(line) + return "\n".join(lines) + + @dataclass(frozen=True) class Enforcement: """One point in the enforcement space. @@ -239,6 +265,32 @@ def with_catalogue(self, paths: tuple[str, ...] | None) -> Enforcement: kept = tuple(described[path] for path in paths if path in described) return replace(self, catalogue=paths, catalogue_text=kept or None) + def with_properties(self, names: Collection[str]) -> Enforcement: + """The rendered entries narrowed to the properties a call may fill. + + The fill call's grammar carries what the property step chose and + nothing else. An entry still listing the rest describes the class the + model is not being asked about: a recipe extract was shown + ``cookingMethod``, ``cookTime``, ``recipeCategory`` and + ``recipeCuisine``, none of them in its grammar, and not shown + ``name``, ``author`` or ``hasPart``, all three of which were. The + entry and the schema disagreed in both directions at once. + + A property line is a name at the entry's own indent followed by a + parenthesised reading. Anything indented further belongs to the + property above it, which is how an entry writes what a nested object + carries, and goes or stays with it. Everything else, the heading, the + description, what the class extends, stays: those say what the class + is, not what this call may write. + """ + if self.catalogue_text is None: + return self + keep = set(names) + return replace( + self, + catalogue_text=tuple(_entry_limited_to(entry, keep) for entry in self.catalogue_text), + ) + def with_units(self, units: tuple[str, ...] | None) -> Enforcement: """The same condition over a different unit enumeration.""" return replace(self, unit_catalogue=units) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 4bce220..1610270 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -17,6 +17,7 @@ import json import re from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field, replace from typing import Any @@ -42,6 +43,12 @@ _FENCE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.MULTILINE) +_Group = tuple[tuple[str, ...], tuple[str, ...], tuple[str, ...], tuple[tuple[str, tuple[str, ...]], ...]] +"""What makes one extract call: a shortlist, the properties the step chose, +the ones an absorbed entity brings, and what it chose inside each embedded +object. Entities sharing a call share the schema it is sent, so two that +differ in any of the four cannot share one.""" + def parse_json_answer(text: str) -> Any | None: """Read JSON out of an answer, tolerating a markdown fence. @@ -145,6 +152,13 @@ class ExtractionResult: unpinned: list[str] = field(default_factory=list) """Reference properties left open because no planned entity fits their range. Those slots ran unconstrained, and the record says which.""" + properties_invented: dict[str, tuple[str, ...]] = field(default_factory=dict) + """Per entity, the property names the step answered that it was not + offered. + + Always zero while a grammar binds the enumeration, which is the point: it + is what the enumeration was buying, and it can only be counted by asking + the same question without one.""" properties_chosen: dict[str, tuple[str, ...]] = field(default_factory=dict) """The properties the property step kept, per entity. @@ -207,8 +221,11 @@ def __init__( orchestration: Orchestration = Orchestration.SINGLE_SHOT, *, attempts: int = 1, - shortlist_k: int = 3, + shortlist_k: int = 1, close_properties: bool = True, + keyed_extract: bool = True, + property_flags: bool = False, + constrain_properties: bool = True, plan_retry: bool | None = None, information: Callable[[str, str], Any] | None = None, ) -> None: @@ -221,6 +238,7 @@ def __init__( a caller that supplies nothing gets that behaviour by default. See :meth:`_ask_for`.""" self.asked: list[dict[str, str]] = [] + self.properties_invented: dict[str, tuple[str, ...]] = {} """Every escalation, in order, whether or not it was answered.""" self.supplied: dict[str, dict[str, Any]] = {} """What the caller answered, per entity.""" @@ -235,6 +253,9 @@ def __init__( """How many classes the select step may keep per entity. One is the commit case, where a wrong selection cannot be recovered.""" self.close_properties = close_properties + self.keyed_extract = keyed_extract + self.property_flags = property_flags + self.constrain_properties = constrain_properties """Whether the property step's answer removes the slots it left out. On, the extract schema carries the chosen properties, the required @@ -737,7 +758,25 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: ) available = self._available_properties(request, placed) - chosen = self._choose_properties(request, log, placed, available) + embedded = self._inside_properties(request, placed, available) + answered = self._choose_properties( + request, + log, + placed, + {**available, **{_inside_key(key, slot): names for (key, slot), names in embedded.items()}}, + ) + chosen = {key: names for key, names in answered.items() if key in available} + # The step's answer about an embedded object, resolved back to the + # entity holding it and the slot it stands in. The key it was asked + # under does not survive this line. + within: dict[str, dict[str, tuple[str, ...]]] = {} + for key, slot in embedded: + picked = answered.get(_inside_key(key, slot), ()) + if picked: + within.setdefault(key, {})[slot] = picked + # A name invented for an embedded object is filed under the entity + # holding it, so the record this reports stays keyed by the plan. + self.properties_invented = _by_holder(self.properties_invented, available) filling, named = self._filling(placed, available, chosen) absorbed = _absorbed_by(request.schema, placed, chosen, request.ranges, request.parents) inside = _inside(absorbed, filling) @@ -748,22 +787,33 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: # argument one step on: entities sharing a call share the schema that # call is sent, so two that fill different properties can no more share # one than two that shortlisted different classes. The properties an - # absorbed entity brings are a third key for that same reason. - groups: dict[tuple[tuple[str, ...], tuple[str, ...], tuple[str, ...]], list[str]] = {} + # absorbed entity brings are a third key for that same reason, and what + # the step chose inside an embedded object is a fourth. + groups: dict[_Group, list[str]] = {} for entity in placed: if entity.key in absorbed: continue - key = (entity.classes, filling.get(entity.key, ()), inside.get(entity.key, ())) + key = ( + entity.classes, + filling.get(entity.key, ()), + inside.get(entity.key, ()), + tuple(sorted(within.get(entity.key, {}).items())), + ) groups.setdefault(key, []).append(entity.key) + if self.keyed_extract: + return self._keyed_extract(request, log, plan, groups, absorbed, selected, chosen, named, text) + merged: list[Any] = [] unpinned: list[str] = [] last: ExtractionResult | None = None - for (classes, kept, held), keys in groups.items(): - narrowed = self.enforcement.with_catalogue(classes) - filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) + holding = _holding_objects(request) + for (classes, kept, held, chose), keys in groups.items(): wanted = self._ask_for(keys, frozenset(required).difference(kept)) keep = set(kept) | set(held) | required.intersection(wanted) + narrowing = _within(chose, held, holding) + narrowed = self.enforcement.with_catalogue(classes).with_properties(keep) + filler = ExtractionAgent(self.client, narrowed, self.profile, attempts=self.attempts) # The ids this call may state, which is the ones it reports plus # the ones it writes inside them. An absorbed entity still answers # under the id it was planned under, so the id slot has to offer it @@ -772,8 +822,10 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: states = [*keys, *(one for one, holder in absorbed.items() if holder in owned)] step = ExtractionRequest( document=request.document, - schema=_trim_properties(request.schema, keep) if self.close_properties else request.schema, - branches=_trim_branches(request.branches, keep) if self.close_properties else request.branches, + schema=_trim_properties(request.schema, keep, narrowing) if self.close_properties else request.schema, + branches=( + _trim_branches(request.branches, keep, narrowing) if self.close_properties else request.branches + ), parents=request.parents, ranges=request.ranges, instruction=self._extract_instruction(request, plan, keys, kept), @@ -795,6 +847,7 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: last.selected = selected last.mentions = dict(self._mentions) last.properties_chosen = chosen + last.properties_invented = dict(self.properties_invented) last.named = named last.absorbed = absorbed last.links = links @@ -871,6 +924,44 @@ def _available_properties( available[entity.key] = names return available + def _inside_properties( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + available: dict[str, tuple[str, ...]], + ) -> dict[tuple[str, str], tuple[str, ...]]: + """What the object standing in an embedded slot may carry. + + The property step runs over planned entities, and an object written + inside one is not planned, so nothing ever chose its slots and the + extract call asked for every slot the class it holds declares. A + recipe's yield arrived as a quantity carrying a maximum, a minimum, a + unit code and a unit text that no step had named, repeated in every + class definition able to hold one. + + So the object is asked about as if it were an entity, which is the + device and not a change of status: the key is made here, lasts for + this one step, is never offered to the step that chooses classes, and + nothing answers under it in the extract call, where the object stays + written inside the entity holding it. + + Keyed by the entity and the slot together. Two entities may hold the + same class in the same slot and still state different things about it, + and one entity may hold a different class in each of two slots. + """ + lineage = {name: tuple(values) for name, values in (request.parents or {}).items()} + found: dict[tuple[str, str], tuple[str, ...]] = {} + for entity in plan: + offered = available.get(entity.key) + if not offered: + continue + slots = _declared_slots(request.schema, request.branches, entity.classes, lineage) + for name in offered: + inner = _inner_properties(slots.get(name)) + if inner: + found[(entity.key, name)] = inner + return found + def _ask_for(self, keys: list[str], missing: frozenset[str]) -> set[str]: """Resolve a required property the document does not fill. @@ -922,22 +1013,98 @@ def _choose_properties( ) -> dict[str, tuple[str, ...]]: """Ask which of each entity's own properties the document fills. - One call for the whole plan, with one enumeration per entity. The - predecessor asked per entity in its construct step, which costs a call - per entity for an answer one schema can carry. + One call per distinct property set, which is one per class the plan + placed anything in, run together. Entities of one class are asked the + same question and share a definition; entities of different classes + do not, and putting them in one request sums their grammars: four + classes over nineteen entities was refused as too complex to compile + where each class on its own compiles. The calls do not depend on each + other, so they go out at once and cost one round trip. A name the entity cannot carry is dropped rather than repaired, the way :meth:`_select` drops a candidate outside the catalogue. The enumeration already said what was legal, and keeping the name would put a slot in the extract schema that no class on the shortlist declares. + + An embedded object is packed rather than grouped. Two entities of a + class ask the same question, so a call per class is a call per + question; an object standing in a slot asks a question of its own, and + one call each turns a recipe page into twenty property calls where + three would do. They are packed to the same budget instead, which is a + sum over the request and the quantity that budget was measured in. """ if not available: return {} - schema = property_schema(available, evidence=request.property_evidence) - prepared, _ = prepare(schema, self.profile, grounding=False) + planned = {entity.key for entity in plan} + grouped: dict[tuple[str, ...], dict[str, tuple[str, ...]]] = {} + for key, names in available.items(): + if key in planned: + grouped.setdefault(tuple(names), {})[key] = names + batches = [part for names, subset in grouped.items() for part in _batched(subset, self._per_call(names))] + batches += _packed( + {key: names for key, names in available.items() if key not in planned}, + self.profile.max_enumerated_slots, + ) + if len(batches) == 1: + return self._ask_fillable(request, log, plan, available) + chosen: dict[str, tuple[str, ...]] = {} + answered: dict[str, list[Any]] = {} + with ThreadPoolExecutor(max_workers=min(len(batches), 8)) as pool: + running = [pool.submit(self._ask_fillable, request, log, plan, subset) for subset in batches] + for finished in running: + chosen.update(finished.result()) + answered.update(self.fillable_answer or {}) + self.fillable_answer = answered + return {key: chosen.get(key, ()) for key in available} + + def _per_call(self, names: tuple[str, ...]) -> int: + """How many entities offering these names fit in one request. + + The compiler charges for the product of entities and names, so the + budget divides by the names rather than capping the entities: twelve + entities of sixty-two names compile and sixteen do not, where + sixty-four entities of five names do. + """ + budget = self.profile.max_enumerated_slots + if budget is None or not names: + return len(names) or 1 + return max(1, budget // len(names)) + + def _ask_fillable( + self, + request: ExtractionRequest, + log: CallLog, + plan: tuple[PlannedEntity, ...], + available: dict[str, tuple[str, ...]], + ) -> dict[str, tuple[str, ...]]: + """One fillable call, over the entities sharing a property set.""" + schema = property_schema(available, evidence=request.property_evidence, flags=self.property_flags) + # Definitions prepared on their own, wrapper assembled after, for the + # reason the keyed extract does it: `prepare` inlines every `$ref` for + # a provider that cannot express `allOf`, and inlined these are one + # enumeration per entity again, which is the grammar Anthropic refused. + prepared = dict(schema) + prepared["$defs"] = { + name: prepare(definition, self.profile, grounding=False)[0] for name, definition in schema["$defs"].items() + } named = {entity.key: f"{_named(entity)}, {'/'.join(entity.classes)}" for entity in plan} - messages = build_property_messages(request, available, named) - response_format = prepared if self.enforcement.decode_constraint is not DecodeConstraint.NONE else None + # An embedded object is named by the entity and the slot it stands in, + # because the key alone says neither and the step is being asked what + # that object states rather than what its holder does. + for key in available: + holder, mark, slot = key.partition(_INSIDE_MARK) + if key not in named and mark and holder in named: + named[key] = f"the object written into {slot} of {named[holder]}" + # The classes the plan settled on and no others. The step is choosing + # between one class's properties, so the rest of the catalogue + # describes classes nothing on the plan can be. + placed = tuple(dict.fromkeys(name for entity in plan for name in entity.classes)) + narrowed = self.enforcement.with_catalogue(placed or None) if placed else self.enforcement + messages = build_property_messages( + request, available, named, _reachable_by(plan, request), enforcement=narrowed, flags=self.property_flags + ) + constrained = self.enforcement.decode_constraint is not DecodeConstraint.NONE and self.constrain_properties + response_format = prepared if constrained else None with log.timed("properties", self.client.model, attempt=1, schema_sha256=schema_hash(prepared)) as sink: reply = self.client.invoke(messages, response_format=response_format, strict=self.enforcement.decode_strict) @@ -947,11 +1114,276 @@ def _choose_properties( # Kept so a caller can read what the step thought it was reading. The # answer is the names; this is the working behind them. self.fillable_answer = answered + for key, names in available.items(): + loose = _named_in(answered.get(key) or ()) - set(names) + if loose: + self.properties_invented[key] = tuple(sorted(loose)) return { key: tuple(name for name in names if name in _named_in(answered.get(key) or ())) for key, names in available.items() } + def _keyed_extract( + self, + request: ExtractionRequest, + log: CallLog, + plan: tuple[PlannedEntity, ...], + groups: dict[_Group, list[str]], + absorbed: dict[str, str], + selected: dict[str, tuple[str, ...]], + chosen: dict[str, tuple[str, ...]], + named: list[str], + text: str, + ) -> ExtractionResult: + """Fill the whole plan in one call, each entity under its own key. + + The answer is an object whose keys are the ids the plan handed out and + whose values are that entity's own shape, shared through ``$defs`` + where two entities were placed in the same class and asked for the + same properties. + + This is what the array of entities under a union was doing badly. The + key is the id, so there is no id slot to enumerate and no way to + answer under an id the plan never issued, which the union shape did: + a call asked for one entity returned seven, six of them bare stubs + carrying a class it had not been asked about. There is no + discriminator to pick either, because the key already settled which + class the value takes. + + And it is one call rather than one per group. Each value stays narrow, + which is the quantity Anthropic's constrained decoding is exponential + in: the array shape asking for the same twenty-six entities compiled + for six minutes and timed out, and this one answered in twenty-one + seconds. + """ + required = _required_properties(request.schema) + asked: dict[str, tuple[str, ...]] = {} + defs: dict[str, dict[str, Any]] = {} + properties: dict[str, Any] = {} + placed: list[str] = [] + shown: set[str] = set() + holding = _holding_objects(request) + for (classes, kept, held, chose), keys in groups.items(): + # The properties the schema requires and the step did not choose, + # which a caller may be able to supply where the document cannot. + wanted = self._ask_for(keys, frozenset(required).difference(kept)) + keep = set(kept) | set(held) | required.intersection(wanted) + narrowing = _within(chose, held, holding) + placed.extend(classes) + shown |= keep + shape = _trim_properties(request.schema, keep, narrowing) if self.close_properties else request.schema + base = (_entity_shapes(shape) or [{}])[0] if shape else {} + branches = ( + _trim_branches(request.branches, keep, narrowing) if self.close_properties else request.branches + ) or {} + arms: list[dict[str, Any]] = [] + # Every class the key may take, which is one per entity unless + # `shortlist_k` was raised. A key offered several becomes a union, + # and a union is what a provider charges for: seven keys over two + # or three candidates each compiled to a grammar Anthropic refused + # as too large, where the same plan committed to one class per key + # compiled at once. `prepare` would flatten the choice for that + # provider in any case, so carrying it costs the grammar and buys + # a discrimination the answer could not express. + offered = classes if self.profile.supports_any_of else classes[:1] + for name in offered: + slots = { + key: value + for key, value in {**(base.get("properties") or {}), **(branches.get(name) or {})}.items() + if key not in _ID_KEYS + } + slots = {key: value for key, value in slots.items() if key not in _CLASS_KEYS} + identifier = f"{name}__{len(defs)}" if name in defs else name + defs[identifier] = { + "type": "object", + "additionalProperties": False, + "properties": {_CLASS_KEYS[0]: {"type": "string", "const": name}, **slots}, + "required": list(dict.fromkeys([_CLASS_KEYS[0], *(k for k in kept if k in slots)])), + } + arms.append({"$ref": f"#/$defs/{identifier}"}) + wrote = tuple(name for name in defs[identifier]["required"] if name not in _CLASS_KEYS) + for key in keys: + properties[key] = arms[0] if len(arms) == 1 else {"anyOf": list(arms)} + asked[key] = wrote + if not properties: + return ExtractionResult( + text=text, payload=None, calls=log, selected=selected, mentions=dict(self._mentions) + ) + + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Entities", + "description": "Each planned entity, under the id it was planned as.", + "type": "object", + "additionalProperties": False, + "$defs": defs, + "properties": properties, + "required": list(properties), + } + schema, unpinned = self._pin_references(schema, plan, request.ranges, request.parents) + # Each definition is prepared on its own and the wrapper assembled + # after. `prepare` inlines every `$ref` for a provider that cannot + # express `allOf`, which is right for an inheritance chain and wrong + # here: these refs are what keeps twenty entities of one class from + # being twenty copies of its object, and inlined they compiled into a + # grammar Anthropic refused as too large. + degradation = Degradation() + for name, definition in list(schema["$defs"].items()): + ready, cost = prepare(definition, self.profile, grounding=self.enforcement.grounding) + schema["$defs"][name] = ready + degradation = _added(degradation, cost) + # After the preparation and not before it, because `prepare` inlines + # every `$ref` for a provider that cannot express `allOf` and would + # put back what this just took out. + schema["$defs"] = _hoisted(schema["$defs"]) + # Sized the way the property step is, and for the same budget: the + # compiler charges for keys times the slots each one reaches, and a + # link slot pinned to nineteen ids is nineteen of them. Nineteen keys + # over four classes was refused where the same keys in batches + # compile. The batches do not depend on each other, so they go + # together. + priced = {name: _grammar_cost(definition) for name, definition in schema["$defs"].items()} + batches = [ + part + for subset in _by_class(properties).values() + for part in _within_budget(subset, priced, self.profile.max_enumerated_slots) + ] + narrowed = self.enforcement.with_catalogue(tuple(dict.fromkeys(placed)) or None).with_properties(shown) + digest = schema_hash(schema) + + def ask(keys: list[str]) -> tuple[Any, list[Any], list[Any]]: + # The definitions this batch reaches and no others. A definition + # left behind is compiled whether or not anything references it, + # so carrying all of them makes every batch the whole grammar. + kept = _reachable_defs({name for key in keys for name in _referenced(properties[key])}, schema["$defs"]) + part = { + **schema, + "$defs": {name: body for name, body in schema["$defs"].items() if name in kept}, + "properties": {key: properties[key] for key in keys}, + "required": list(keys), + } + messages = build_messages( + ExtractionRequest( + document=request.document, + schema=part if self.enforcement.schema_in_prompt else None, + instruction=self._keyed_instruction( + request, plan, {k: asked[k] for k in keys if k in asked}, absorbed + ), + ), + narrowed, + ) + response_format = part if self.enforcement.decode_constraint is not DecodeConstraint.NONE else None + answer: Any | None = None + for attempt in range(1, self.attempts + 1): + with log.timed("extract", self.client.model, attempt=attempt, schema_sha256=schema_hash(part)) as sink: + reply = self.client.invoke( + messages, response_format=response_format, strict=self.enforcement.decode_strict + ) + sink.append(reply.usage or TokenUsage()) + answer = reply.parsed if reply.parsed is not None else parse_json_answer(reply.text) + if answer is not None: + break + return reply.text, _keyed_entities(answer, set(keys)), messages + + def ask_splitting(keys: list[str]) -> tuple[Any, list[Any], list[Any]]: + """One batch, halved and retried where the provider will not + compile it. + + A budget predicts the boundary and does not find it: the measured + one put nineteen keys one over, and the same schema with eighteen + compiled. Halving costs a wasted request and needs no model of + the provider, so it holds when the catalogue or the plan moves. + """ + try: + return ask(keys) + except Exception as error: + if len(keys) < 2 or not _refused_to_compile(error): + raise + half = len(keys) // 2 + left, found_left, sent = ask_splitting(keys[:half]) + _, found_right, _ = ask_splitting(keys[half:]) + return left, [*found_left, *found_right], sent + + merged: list[Any] = [] + messages: list[Any] = [] + if len(batches) == 1: + text, merged, messages = ask_splitting(list(batches[0])) + else: + with ThreadPoolExecutor(max_workers=min(len(batches), 8)) as pool: + for answered, found, sent in pool.map(lambda batch: ask_splitting(list(batch)), batches): + text, messages = answered, sent + merged.extend(found) + links, dangling = _edges_of(merged, request.ranges) + return ExtractionResult( + text=text, + payload={"entities": merged} if merged else None, + calls=log, + degradation=degradation, + schema_sha256=digest, + prompt_sha256=prompt_hash(messages, fold_system=getattr(self.client, "fold_system", False)), + selected=selected, + mentions=dict(self._mentions), + properties_chosen=chosen, + named=named, + absorbed=absorbed, + links=links, + dangling=dangling, + unpinned=unpinned, + properties_invented=dict(self.properties_invented), + ) + + def _keyed_instruction( + self, + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + asked: dict[str, tuple[str, ...]], + absorbed: dict[str, str] | None = None, + ) -> str: + """What the keyed call asks for, entity by entity. + + What each key's definition requires, which is what the property step + chose plus whatever a rule outside it put back. Listing the step's own + answer instead would name a slot the schema no longer carries, or + carry one the instruction never named. + + Entities another call fills are named too, as targets and not as + work. Splitting the plan puts an entity and the ones it points at in + different calls, and a call told to fill a reference with an id has to + know which id is which thing. + """ + if request.instruction: + return request.instruction + lines: list[str] = [] + elsewhere: list[str] = [] + for entity in plan: + if entity.key in (absorbed or {}): + # Absorbed into a holder, so it is written inside that + # entity's value and has no key of its own to answer under. + continue + if entity.key not in asked: + elsewhere.append(_named(entity)) + continue + properties = asked[entity.key] + wanted = ", ".join(properties) if properties else "no property value, the class only" + lines.append(f"{_named(entity)}: {wanted}") + listed = "\n".join(lines) + if elsewhere: + listed += ( + "\n\nAnother call reports these. Point at them by id where a property takes one, " + "and do not report them here:\n" + "\n".join(elsewhere) + ) + links = ( + "Where a property points at another of these entities, give that entity's id as the value. " + if request.ranges + else "" + ) + return ( + "Read the document and fill in each entity below, under the id it is listed with. " + f"{links}" + "Where the document states more than one value for a property, give every one " + "of them.\n\nReport only these properties for them:\n" + listed + ) + def _extract_instruction( self, request: ExtractionRequest, @@ -1198,6 +1630,7 @@ def _pin_union( {name: branches[name] for name in branches if name in needed}, {name: values for name, values in lineage.items() if name in needed}, concrete=tuple(offered), + required=tuple(target.get("required") or ()), ) if shared: union.setdefault("properties", {}).update(shared) @@ -1402,6 +1835,35 @@ def keep(entity: Any) -> bool: _NAME_KEY = "name" +_INSIDE_MARK = "__" + + +def _inside_key(key: str, slot: str) -> str: + """How the property step names the object standing in one entity's slot. + + A key of the step and not of the plan. It is minted for the one call that + asks what the object states and resolved back to the entity and the slot + straight after, so nothing downstream sees a second entity. + """ + return f"{key}{_INSIDE_MARK}{slot}" + + +def _by_holder( + invented: dict[str, tuple[str, ...]], available: dict[str, tuple[str, ...]] +) -> dict[str, tuple[str, ...]]: + """What the property step invented, filed under the planned entity. + + The step asks about an object standing in a slot under a key of its own, + and that key is the step's. Anything a caller reads afterwards is about + the plan, so a name invented inside an object is reported against the + entity holding it. + """ + found: dict[str, tuple[str, ...]] = {} + for key, names in invented.items(): + holder = key if key in available else key.partition(_INSIDE_MARK)[0] + found[holder] = tuple(dict.fromkeys(found.get(holder, ()) + names)) + return found + def _named(entity: PlannedEntity) -> str: """One planned entity as the fill prompt names it.""" @@ -1416,7 +1878,41 @@ def _is_entity_shape(node: Any) -> bool: return isinstance(properties, dict) and any(key in properties for key in _CLASS_KEYS) -def _entity_shapes(schema: Any) -> list[dict[str, Any]]: +def _added(into: Degradation, other: Degradation) -> Degradation: + """Two degradation reports summed, for a schema prepared in pieces.""" + dropped = dict(into.dropped) + for keyword, count in other.dropped.items(): + dropped[keyword] = dropped.get(keyword, 0) + count + return Degradation( + dropped=dropped, + refs_inlined=into.refs_inlined + other.refs_inlined, + recursion_cut=into.recursion_cut + other.recursion_cut, + made_required=into.made_required + other.made_required, + constraints_described=into.constraints_described + other.constraints_described, + semantics_dropped=into.semantics_dropped + other.semantics_dropped, + keywords_before=into.keywords_before + other.keywords_before, + keywords_after=into.keywords_after + other.keywords_after, + ) + + +def _keyed_entities(payload: Any, keys: set[str]) -> list[Any]: + """The keyed answer read back as the entity list the rest of this expects. + + The key is the id, so it is written into the entity here rather than + asked for and checked. A key the plan never issued is dropped, which is + the ownership filter the grouped path runs after the fact. + """ + if not isinstance(payload, dict): + return [] + found: list[Any] = [] + for key, value in payload.items(): + if key not in keys or not isinstance(value, dict): + continue + found.append({_ID_KEYS[0]: key, **value}) + return found + + +def _entity_shapes(schema: Any, descend: bool = True) -> list[dict[str, Any]]: """Every object an entity may take, one per union branch. A union is recognised before the objects inside it, so pinning reaches all @@ -1430,6 +1926,12 @@ def _entity_shapes(schema: Any) -> list[dict[str, Any]]: constraints the top-level shape gets. Stopping at the outermost match would leave its id unpinned and its reference slots open, and an id the plan never issued cannot be joined to anything. + + ``descend`` turns that last part off, for a caller that has to tell an + outer shape from what is written inside it. A flat list cannot say which + slot held which object, and the two are not asked the same question: the + outer one is a planned entity and the inner one is an object standing in + one of its slots. """ found: list[dict[str, Any]] = [] @@ -1445,7 +1947,7 @@ def visit(node: Any) -> None: if isinstance(branches, list) and any(_is_entity_shape(branch) for branch in branches): found.extend(branch for branch in branches if _is_entity_shape(branch)) for branch in branches: - if _is_entity_shape(branch): + if descend and _is_entity_shape(branch): visit(branch.get("properties")) return if _is_entity_shape(node): @@ -1453,7 +1955,8 @@ def visit(node: Any) -> None: # Its properties, because one of them may hold another entity. # The shape itself is recorded first, so an embedded entity is # pinned after the one holding it and never instead of it. - visit(node.get("properties")) + if descend: + visit(node.get("properties")) return for value in node.values(): visit(value) @@ -1468,6 +1971,13 @@ def _shape_properties(schema: Any) -> tuple[str, ...]: The class slot and the id slot are left out. Neither was ever the property step's to choose: the first is what the plan decided and the second is how the answer is joined back to it. + + The objects written inside a shape are read too, because a schema may + declare a class's slots only there: an address written inside a person is + the one place ``streetAddress`` appears, and a planned address the step + could not be asked about is one the fill step has nothing to ask for. What + those names mean inside the object is a separate question, asked under the + slot that holds it: see :meth:`ExtractionAgent._inside_properties`. """ names: list[str] = [] for shape in _entity_shapes(schema): @@ -1477,6 +1987,61 @@ def _shape_properties(schema: Any) -> tuple[str, ...]: return tuple(names) +def _inner_properties(slot: Any) -> tuple[str, ...]: + """The property names of the object written into this slot. + + Empty where the slot holds no object, which is how a caller tells a slot + that carries an entity from one that names it. + """ + names: list[str] = [] + for shape in _entity_shapes(slot, descend=False): + for name in shape.get("properties") or {}: + if name not in _CLASS_KEYS and name not in _ID_KEYS and name not in names: + names.append(name) + return tuple(names) + + +def _lineage_first(classes: tuple[str, ...], lineage: dict[str, tuple[str, ...]]) -> list[str]: + """These classes and everything they inherit from, ancestors first. + + A class that redefines a property it inherits has to win over the class it + inherits it from, so the ancestor is applied before it. + """ + order: list[str] = [] + + def walk(name: str, seen: frozenset[str]) -> None: + if name in seen: + return + for parent in lineage.get(name, ()): + walk(parent, seen | {name}) + if name not in order: + order.append(name) + + for name in classes: + walk(name, frozenset()) + return order + + +def _declared_slots( + schema: Any, + branches: dict[str, dict[str, Any]] | None, + classes: tuple[str, ...], + lineage: dict[str, tuple[str, ...]], +) -> dict[str, Any]: + """Every slot these classes offer, assembled as the extract call assembles it. + + The flat answer shape first and the branch over it, which is the order + :meth:`ExtractionAgent._keyed_extract` merges them in: the shape holds one + definition per property name over every class at once, and the branch is + what this class narrows that name to. + """ + shapes = _entity_shapes(schema, descend=False) + found: dict[str, Any] = dict(shapes[0].get("properties") or {}) if shapes else {} + for name in _lineage_first(classes, lineage) if branches else (): + found.update((branches or {}).get(name) or {}) + return found + + def _required_properties(schema: Any) -> set[str]: """Every property an entity shape requires, which a trim keeps. @@ -1519,24 +2084,98 @@ def _admitted_properties( return found -def _trim_properties(schema: dict[str, Any] | None, keep: set[str]) -> dict[str, Any] | None: - """The answer shape with the slots the property step left out removed.""" +def _trim_properties( + schema: dict[str, Any] | None, + keep: set[str], + inside: dict[str, tuple[str, ...]] | None = None, +) -> dict[str, Any] | None: + """The answer shape with the slots the property step left out removed, + and the ones it kept made required. + + Required because the property step has already answered the question the + fill step would otherwise be left to decide again. It was asked which + properties the document states a value for and it named these, so a fill + call that may omit them asks the same question twice and takes the second + answer. Under a grammar the second answer is the cheap one: with only the + class and id slots required, the shortest valid entity is the empty one, + and claude-haiku-4-5 answered `{"type": "Recipe", "id": "e1"}` to a call + whose instruction named five properties and whose link slots were pinned + to the right targets, then twenty supplies carrying neither the name it + had chosen nor anything else. + + The cost is the one the property step's own instruction already states: a + property named here and absent from the document has to be invented or + left empty. That is the trade the step is told it is making, and it is + the trade that makes a chosen property mean something. + + ``inside`` narrows the object standing in a slot the same way, under the + names chosen for that object. Without it an embedded object keeps every + slot its class declares, which no step ever chose. + + Keyed by the slot and never taken from ``keep``. A name the holder chose + says nothing about what the object written inside it states, and the two + vocabularies overlap: a Recipe choosing ``description`` would otherwise + require a description of the quantity in its yield. + + Left out entirely, nothing inside is narrowed. A caller that names the + top-level properties has said nothing about what an object written inside + one carries, and reading that silence as "none of them" would empty the + object rather than leave it alone. A slot absent from a supplied map is + narrowed to nothing, because that map is an answer about every slot. + """ if schema is None: return None trimmed = copy.deepcopy(schema) - for shape in _entity_shapes(trimmed): + for shape in _entity_shapes(trimmed, descend=False): + properties = shape.get("properties") or {} + kept: dict[str, Any] = {} + for name, definition in properties.items(): + if name in _CLASS_KEYS or name in _ID_KEYS: + kept[name] = definition + elif name in keep: + kept[name] = definition + if inside is not None: + _narrow_embedded(definition, set(inside.get(name, ()))) + shape["properties"] = kept + already = shape.get("required") or [] + shape["required"] = list(dict.fromkeys([*already, *(name for name in kept if name in keep)])) + return trimmed + + +def _narrow_embedded(slot: Any, keep: set[str]) -> None: + """Narrow every object written into this slot, in place. + + The class slot survives whatever is kept, because it is what the embedded + object's class is graded against and no step was ever asked about it. + """ + for shape in _entity_shapes(slot): properties = shape.get("properties") or {} shape["properties"] = { name: definition for name, definition in properties.items() if name in keep or name in _CLASS_KEYS or name in _ID_KEYS } - return trimmed + already = shape.get("required") or [] + shape["required"] = list(dict.fromkeys([*already, *(name for name in shape["properties"] if name in keep)])) + + +def _narrowed_slot(definition: Any, keep: set[str]) -> Any: + """One slot, with whatever object is written into it narrowed to ``keep``. + + A copy where there is something to narrow, because the branches belong to + the request and every group narrows them again to its own answer. + """ + if not _holds_an_object(definition): + return definition + copied = copy.deepcopy(definition) + _narrow_embedded(copied, keep) + return copied def _trim_branches( branches: dict[str, dict[str, Any]] | None, keep: set[str], + inside: dict[str, tuple[str, ...]] | None = None, ) -> dict[str, dict[str, Any]] | None: """The union branches, narrowed the way the answer shape was. @@ -1544,11 +2183,20 @@ def _trim_branches( answer shape no longer carries would put that property back on the union arm alone, and the difference between the arms would be a difference in what each was asked for. + + Which is why ``inside`` is here too, read as :func:`_trim_properties` + reads it. The branch is what the extract call takes an embedded object's + body from, so a branch narrowed at the top level and left whole underneath + puts the full declared object back over the answer shape's trimmed one. """ if not branches: return branches return { - name: {prop: definition for prop, definition in properties.items() if prop in keep} + name: { + prop: definition if inside is None else _narrowed_slot(definition, set(inside.get(prop, ()))) + for prop, definition in properties.items() + if prop in keep + } for name, properties in branches.items() } @@ -1573,12 +2221,265 @@ def _fillable_of(payload: Any, available: dict[str, tuple[str, ...]]) -> dict[st candidates.append(only) candidates.append(payload) for candidate in candidates: - found = {key: value for key, value in candidate.items() if key in available and isinstance(value, list)} + found = { + key: _stated_properties(value) + for key, value in candidate.items() + if key in available and isinstance(value, (list, dict)) + } + found = {key: value for key, value in found.items() if value is not None} if found: return found return {} +_REFUSALS = ( + "too large", + "too complex", + "too many", + "exceeds the maximum", + "expected at most", + # Two hosts refuse a schema by answering HTTP 200 with an empty `choices` + # array and a fabricated usage of one token each way. There is no error to + # read, so the refusal arrives as whatever the client makes of an answer + # that is not there, and a runner files it as a dead deployment: + # llama-3.3-70b-instruct was written off here on exactly that reading and + # answers a 600-property schema in 104 seconds. + "no choices", +) + + +def _refused_to_compile(error: Exception) -> bool: + """Whether a provider rejected the grammar rather than the request. + + Matched on the message because none of them carry a code for it. The + strings seen so far: `The compiled grammar is too large`, `Schema is too + complex for compilation`, `Schema is too complex.` and OpenAI's `Expected + at most 1000 enum values`. + """ + said = str(error).lower() + return any(phrase in said for phrase in _REFUSALS) + + +def _reachable_defs(names: set[str], defs: dict[str, Any]) -> set[str]: + """The definitions a batch needs, following references between them. + + A hoisted body is referenced from inside another definition rather than + from a key, so narrowing a batch by its keys alone drops it and the + provider refuses the batch for a reference to something not in the + schema. + """ + found = set(names) + queue = list(found) + while queue: + current = queue.pop() + body = defs.get(current) + if body is None: + continue + for name in _refs_within(body): + if name not in found: + found.add(name) + queue.append(name) + return found + + +def _hoisted(defs: dict[str, Any]) -> dict[str, Any]: + """Each object body several definitions repeat, written once and referenced. + + The class definitions are already shared through ``$defs`` and what they + hold is not, so the grammar carries an embedded object once per class able + to hold it: a quantity of a few hundred bytes cost over a kilobyte across + three definitions of one recipe page. + + Only a body nested inside a definition, never a definition itself. A class + definition is an object with properties like any other, so hoisting on + shape alone leaves a ``$defs`` entry that is nothing but a ``$ref`` to + another, which OpenAI rejects as not a valid JSON Schema. + + Compared as serialised text, so two bodies differing anywhere stay apart. + The same slot pinned to different ids is a different grammar, and sharing + it would offer one entity's slot the targets of another's. + + A body is replaced wherever it stands and never descended into, so the one + copy in ``$defs`` keeps whatever it holds. The result is referenced from + inside a definition rather than from a key, which is what + :func:`_reachable_defs` is for. + """ + counted: dict[str, int] = {} + for body in defs.values(): + for node in _objects_within(body): + text = json.dumps(node, sort_keys=True) + counted[text] = counted.get(text, 0) + 1 + repeated = sorted(text for text, count in counted.items() if count > 1) + if not repeated: + return defs + shared = {text: f"shared{number}" for number, text in enumerate(repeated, 1)} + hoisted = {name: _referencing(body, shared) for name, body in defs.items()} + for text, identifier in shared.items(): + hoisted[identifier] = json.loads(text) + return hoisted + + +def _objects_within(node: Any, root: bool = True) -> list[Any]: + """Every object body standing inside this one, at any depth. + + The node it is called on is never one of them: see :func:`_hoisted` for + what happens to a definition that hoists itself. + """ + found: list[Any] = [] + if isinstance(node, dict): + if not root and node.get("type") == "object" and node.get("properties"): + found.append(node) + for value in node.values(): + found.extend(_objects_within(value, root=False)) + elif isinstance(node, list): + for value in node: + found.extend(_objects_within(value, root=False)) + return found + + +def _referencing(node: Any, shared: dict[str, str], root: bool = True) -> Any: + """This definition with every hoisted body replaced by a reference to it.""" + if isinstance(node, dict): + if not root: + identifier = shared.get(json.dumps(node, sort_keys=True)) + if identifier is not None: + return {"$ref": f"#/$defs/{identifier}"} + return {key: _referencing(value, shared, root=False) for key, value in node.items()} + if isinstance(node, list): + return [_referencing(value, shared, root=False) for value in node] + return node + + +def _refs_within(node: Any) -> set[str]: + """Every definition a subschema names, at any depth.""" + if isinstance(node, dict): + found = set() + if isinstance(node.get("$ref"), str): + found.add(node["$ref"].rsplit("/", 1)[-1]) + for value in node.values(): + found |= _refs_within(value) + return found + if isinstance(node, list): + found = set() + for value in node: + found |= _refs_within(value) + return found + return set() + + +def _referenced(reference: Any) -> set[str]: + """The definitions one key reaches, through a ref or a choice of them.""" + if not isinstance(reference, dict): + return set() + arms = reference.get("anyOf") or reference.get("oneOf") or [reference] + return {str(arm["$ref"]).rsplit("/", 1)[-1] for arm in arms if isinstance(arm, dict) and "$ref" in arm} + + +def _by_class(properties: dict[str, Any]) -> dict[str, dict[str, Any]]: + """The keys grouped by the class their definition is for. + + One call per class rather than one for the whole plan. Entities of a class + share its cheap definitions and entities of different classes do not, so + one request carries every class's grammar at once: on one recipe page that + was seventeen definitions, nine of them one to three kilobytes and most + serving a single key, where the largest class on its own is a third of the + whole. The definitions differ within a class too, because each entity was + asked for what it chose, and splitting distributes those rather than + merging them: merging would offer an entity a property it did not choose. + """ + grouped: dict[str, dict[str, Any]] = {} + for key, reference in properties.items(): + names = sorted(_referenced(reference)) + grouped.setdefault(names[0].split("__")[0] if names else "", {})[key] = reference + return grouped + + +def _grammar_cost(definition: dict[str, Any]) -> int: + """What one entity's shape costs the compiler, roughly. + + A slot pinned to nineteen ids is nineteen alternatives, not one property, + so counting properties misses where the cost is: the definitions that + broke a request were narrow and reached wide enumerations. + """ + cost = 0 + for slot in (definition.get("properties") or {}).values(): + inner = slot.get("items", slot) if isinstance(slot, dict) else {} + cost += max(1, len(inner.get("enum") or ())) if isinstance(inner, dict) else 1 + return max(1, cost) + + +def _within_budget(properties: dict[str, Any], priced: dict[str, int], budget: int | None) -> list[dict[str, Any]]: + """The keys split into requests the provider will compile, greedily.""" + if budget is None: + return [properties] + batches: list[dict[str, Any]] = [] + current: dict[str, Any] = {} + spent = 0 + for key, reference in properties.items(): + cost = max((priced.get(name, 1) for name in _referenced(reference)), default=1) + if current and spent + cost > budget: + batches.append(current) + current, spent = {}, 0 + current[key] = reference + spent += cost + if current: + batches.append(current) + return batches or [properties] + + +def _batched(subset: dict[str, tuple[str, ...]], size: int) -> list[dict[str, tuple[str, ...]]]: + """One class's entities split into requests the provider will compile.""" + keys = list(subset) + return [{key: subset[key] for key in keys[at : at + size]} for at in range(0, len(keys), size)] or [subset] + + +def _packed(subset: dict[str, tuple[str, ...]], budget: int | None) -> list[dict[str, tuple[str, ...]]]: + """Keys offering different property sets, filled into as few requests as fit. + + The compiler charges for the product of keys and the names each one + offers, and that product is one sum over the whole request rather than one + per set, which is what :attr:`ProviderProfile.max_enumerated_slots` + measures. So keys that ask unrelated questions may still share a call as + long as the sum stays under it. + + Ordered by the property set, so two keys offering the same names land + together and share the one definition :func:`property_schema` writes for + them. + """ + if not subset: + return [] + if budget is None: + return [subset] + batches: list[dict[str, tuple[str, ...]]] = [] + current: dict[str, tuple[str, ...]] = {} + spent = 0 + for key, names in sorted(subset.items(), key=lambda item: (item[1], item[0])): + cost = len(names) or 1 + if current and spent + cost > budget: + batches.append(current) + current, spent = {}, 0 + current[key] = names + spent += cost + if current: + batches.append(current) + return batches + + +def _stated_properties(answered: Any) -> list[Any] | None: + """One entity's answer as a list of names, whichever form it came in. + + The flag form answers an object of booleans, one per property, so the + names are the keys it marked true. Read here rather than at the call site + so the rest of the step sees one shape and the form stays a question + about what was asked, not about what the answer means. + """ + if isinstance(answered, list): + return answered + if isinstance(answered, dict): + return [name for name, stated in answered.items() if stated is True] + return None + + def _named_in(answered: Any) -> set[str]: """The property names in one entity's answer. @@ -1644,6 +2545,21 @@ def _descends(name: str, admitted: set[str], lineage: dict[str, tuple[str, ...]] return False +def _reachable_by(plan: tuple[PlannedEntity, ...], request: ExtractionRequest) -> dict[str, tuple[str, ...]]: + """Per node-valued property, the planned entities its range admits. + + The same question :func:`_compatible_ids` answers for the fill step, asked + one step earlier so the step choosing properties can see it. Keyed by + property name alone, which is how ``request.ranges`` is keyed: what a + reference slot may hold is settled by the range and the plan, not by the + class that happens to declare the property. + """ + if not plan or not request.ranges: + return {} + lineage = request.parents or {} + return {name: _compatible_ids(plan, ranges, lineage) for name, ranges in request.ranges.items()} + + def _compatible_ids( plan: tuple[PlannedEntity, ...], ranges: tuple[str, ...], @@ -1763,6 +2679,45 @@ def _circular(holders: dict[str, str]) -> set[str]: return found +def _holding_objects(request: ExtractionRequest) -> set[str]: + """Every slot an object may be written into, from the shape or a branch. + + Both, because a branch may narrow a property to an object the flat answer + shape declares as something else, and a slot missed here is one nothing + narrows. + """ + found = _embedded_properties(request.schema) + for branch in (request.branches or {}).values(): + found |= { + name + for name, slot in branch.items() + if name not in _CLASS_KEYS and name not in _ID_KEYS and _holds_an_object(slot) + } + return found + + +def _within( + chose: tuple[tuple[str, tuple[str, ...]], ...], + held: tuple[str, ...], + holding: set[str], +) -> dict[str, tuple[str, ...]]: + """What each embedded slot keeps inside it, for one extract call. + + The names the property step chose for the object standing there, plus + whatever an absorbed entity fills. Which slot absorbed it is not recorded, + so those names go to every slot that can hold an object: see + :func:`_absorbed_by` for why only one of them can have, and + :func:`_inside` for why leaving them out empties the object the holder was + told to write. + + Every such slot is in the answer, including the ones nothing was chosen + for. The map is read as the step's answer about all of them, so a slot + left out of it would be left alone rather than emptied. + """ + chosen = dict(chose) + return {slot: tuple(dict.fromkeys((*held, *chosen.get(slot, ())))) for slot in holding | set(chosen)} + + def _inside(absorbed: dict[str, str], filling: dict[str, tuple[str, ...]]) -> dict[str, tuple[str, ...]]: """The properties each holder's call fills on the entities it absorbs. @@ -1792,6 +2747,12 @@ def _edges_of( entity an embedding absorbed was reported, under the id it was planned under, and reading the top level alone would call every edge reaching it a miss. + + So is what an embedded object states. The object is where an entity is + written, and an entity written in place points at others: a supply names + the product it is a quantity of. Reading the top level alone would leave + that product with nothing pointing at it in the record while the answer + points at it. """ if not ranges: return [], [] @@ -1799,21 +2760,40 @@ def _edges_of( links: list[Edge] = [] dangling: list[Edge] = [] for entity in entities: - source = _entity_id(entity) - if source is None: - continue - for name in ranges: - value = entity.get(name) - for item in value if isinstance(value, list) else [value]: - if not isinstance(item, str) or not item.strip(): - continue - edge = Edge(source=source, prop=name, target=item.strip()) - links.append(edge) - if edge.target not in emitted: - dangling.append(edge) + for source, node in _stated_objects(entity): + for name in ranges: + value = node.get(name) + for item in value if isinstance(value, list) else [value]: + if not isinstance(item, str) or not item.strip(): + continue + edge = Edge(source=source, prop=name, target=item.strip()) + links.append(edge) + if edge.target not in emitted: + dangling.append(edge) return links, dangling +def _stated_objects(node: Any, source: str | None = None) -> list[tuple[str, dict[str, Any]]]: + """Each object an answered entity holds, with the id an edge from it starts at. + + Its own id where it states one and the holder's otherwise, which is the + reading :func:`_emitted_ids` already takes of an id written inside an + entity: the object is a thing something may point at, so it is also a + thing something may be pointed at from. + """ + found: list[tuple[str, dict[str, Any]]] = [] + if isinstance(node, dict): + here = _entity_id(node) or source + if here is not None: + found.append((here, node)) + for value in node.values(): + found.extend(_stated_objects(value, here)) + elif isinstance(node, list): + for value in node: + found.extend(_stated_objects(value, source)) + return found + + def _class_of(entity: dict[str, Any]) -> str | None: for key in _CLASS_KEYS: value = entity.get(key) @@ -1894,21 +2874,50 @@ def _entities_of(payload: Any) -> list[Any]: started another answering ``{"EntityCandidates": [...]}``, correct entities under a key no list could hold. So a lone key whose value is a list of objects is read as the wrapper it plainly is. + + A list encoded as a string is read as a list. claude-sonnet-5 answers the + plan step with ``{"entities": "[{\\"mention\\": ...}]"}`` often enough to + end a run: the entities are right and the array is JSON inside a JSON + string, so a reader taking the declared type at its word plans nothing and + the chain stops after one call. Only where the string parses to a list of + objects, so a model that genuinely answered with prose still reads as the + failure it is. """ if isinstance(payload, list): return payload if isinstance(payload, dict): for wrapper in ("entities", "instances", "items", "results"): - value = payload.get(wrapper) - if isinstance(value, list): - return value + found = _as_entity_list(payload.get(wrapper)) + if found is not None: + return found if len(payload) == 1: - only = next(iter(payload.values())) - if isinstance(only, list) and all(isinstance(item, dict) for item in only): + only = _as_entity_list(next(iter(payload.values()))) + if only is not None and all(isinstance(item, dict) for item in only): return only return [] +def _as_entity_list(value: Any) -> list[Any] | None: + """``value`` as a list, unwrapping one level of JSON string encoding. + + The array is read and whatever follows it is dropped. The answer this is + for is not a quoted array but a quoted object with the opening brace + eaten: the string runs ``[{...}]}``, so a parser asked for the whole of it + fails on the brace and the entities are lost over a character the model + wrote on the wrong side of a quote. + """ + if isinstance(value, list): + return value + if isinstance(value, str) and value.strip().startswith("["): + try: + parsed, _ = json.JSONDecoder().raw_decode(value.strip()) + except json.JSONDecodeError: + return None + if isinstance(parsed, list) and all(isinstance(item, dict) for item in parsed): + return parsed + return None + + def _find_entity_items(schema: Any) -> dict[str, Any] | None: """The subschema describing one entity, which a union replaces. diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 890f24f..bcd7d16 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -122,6 +122,12 @@ "using the names exactly as they are written here." ) +_PROPERTY_FORM_FLAGS = ( + "Answer with JSON only. Under each entity's id give an object with one entry per property " + "listed for it, true where the document states a value for that property and false where it " + "does not. Use the names exactly as they are written here and leave none of them out." +) + _PROPERTY_HONESTY = ( "Both ways of being wrong cost something. A property you leave out will not be asked for again, " "so a value that is there is lost. A property you name will be asked for next, and if the " @@ -137,6 +143,7 @@ """ _PROPERTY_ENTITIES = "The entities, with the properties each one may carry:" +_PROPERTY_CLASSES = "The classes these entities were placed in:" @dataclass(frozen=True) @@ -275,7 +282,9 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: } -def property_schema(offered: Mapping[str, Sequence[str]], evidence: bool = False) -> dict[str, Any]: +def property_schema( + offered: Mapping[str, Sequence[str]], evidence: bool = False, flags: bool = False +) -> dict[str, Any]: """The answer shape the property step asks for. One array per entity, whose items enumerate **that entity's own** property @@ -300,23 +309,30 @@ def property_schema(offered: Mapping[str, Sequence[str]], evidence: bool = False empty = [key for key, names in offered.items() if not names] if empty: raise ValueError(f"no property is available for {', '.join(empty)}, so the enumeration would admit nothing") + # One enumeration per distinct property set, shared by every entity that + # has it. Entities of one class are offered the same names, so writing the + # enumeration per key repeats it as many times as the plan found that + # class: nineteen entities over four classes compiled to a grammar + # Anthropic refused as too complex, where four shared ones compile. + shapes: dict[tuple[str, ...], str] = {} + defs: dict[str, Any] = {} + for names in offered.values(): + shape = tuple(names) + if shape in shapes: + continue + identifier = f"properties{len(shapes) + 1}" + shapes[shape] = identifier + defs[identifier] = _property_set(list(shape), evidence, flags) return { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "FillableProperties", "description": "Which properties of each entity the document gives a value for.", "type": "object", + "$defs": defs, "properties": { "fillable": { "type": "object", - "properties": { - key: { - "type": "array", - "maxItems": len(names), - "items": _property_item(list(names), evidence), - "description": f"The properties of {key} the document states a value for.", - } - for key, names in offered.items() - }, + "properties": {key: {"$ref": f"#/$defs/{shapes[tuple(names)]}"} for key, names in offered.items()}, "required": list(offered), "additionalProperties": False, } @@ -326,6 +342,39 @@ def property_schema(offered: Mapping[str, Sequence[str]], evidence: bool = False } +def _property_set(names: list[str], evidence: bool, flags: bool) -> dict[str, Any]: + """One entity's answer: the names it states, or a flag for every name. + + The flag form carries no enumeration. A provider compiles an enumeration + of a hundred and thirty-three strings into an automaton it refuses as too + complex however short the array is bounded, where the same question asked + as a fixed object of booleans compiles at once. + + It costs the output instead: every property is written whether or not the + document states it, which is roughly twenty times the answer. What it + buys beyond compiling is a decision per property rather than a recall + task, and one token per property whose probability a caller reading + logprobs can take as the model's confidence without asking for it. + """ + if not flags: + return { + "type": "array", + "maxItems": len(names), + "items": _property_item(names, evidence), + "description": "The properties this entity states a value for.", + } + return { + "type": "object", + "properties": { + name: {"type": "boolean", "description": f"Whether the document states a value for {name}."} + for name in names + }, + "required": list(names), + "additionalProperties": False, + "description": "For each property, whether the document states a value for it.", + } + + def _property_item(names: list[str], evidence: bool) -> dict[str, Any]: """One answered property, with or without the words that state it.""" if not evidence: @@ -345,6 +394,9 @@ def build_property_messages( request: ExtractionRequest, offered: Mapping[str, Sequence[str]], named: Mapping[str, str] | None = None, + points_at: Mapping[str, Sequence[str]] | None = None, + enforcement: Enforcement | None = None, + flags: bool = False, ) -> list[Message]: """The messages the property step sends. @@ -352,24 +404,49 @@ def build_property_messages( properties are listed in the system message as well as enumerated in the answer shape, because an arm that shows no schema still has to say what the names are before it can ask which of them the document fills. + + ``points_at`` names, per node-valued property, the planned entities its + range admits. The step otherwise chooses on the name alone and picks the + one that reads like the document: a recipe page with its ingredients + planned as `HowToSupply` had `recipeIngredient` chosen over `supply`, and + `recipeIngredient` ranges over `ItemList`, so the fill step pinned it to + the sections and every ingredient came out isolated. The range decides + which property can hold the plan, and the step choosing could not see it. """ described = request.property_text or {} - if described: + reach = points_at or {} + + def _line(name: str) -> str: + text = f" {name}: {described[name]}" if name in described else f" {name}" + if name not in reach: + return text + targets = ", ".join(reach[name]) + return f"{text} (points at {targets})" if targets else f"{text} (points at nothing in this plan)" + + if described or reach: # One line per property, because a comment does not fit beside a name # and the step is choosing between them rather than scanning a list. lines: list[str] = [] for key, names in offered.items(): lines.append(f"{(named or {}).get(key) or key}:") - lines += [f" {name}: {described[name]}" if name in described else f" {name}" for name in names] + lines += [_line(name) for name in names] listed = "\n".join(lines) else: listed = "\n".join(f"{(named or {}).get(key) or key}: {', '.join(names)}" for key, names in offered.items()) - sections = [ - _PROPERTY_TASK, - _PROPERTY_FORM, - _PROPERTY_HONESTY, - f"{_PROPERTY_ENTITIES}\n{listed}", - ] + # The form is said in words as well as declared in the schema, because a + # condition that sends no schema leaves the words the only place it is + # stated: asked for flags with the grammar off, the step was sent a + # request byte-identical to the one asking for names. + sections = [_PROPERTY_TASK, _PROPERTY_FORM_FLAGS if flags else _PROPERTY_FORM, _PROPERTY_HONESTY] + if enforcement is not None and enforcement.catalogue and enforcement.catalogue_in_prompt: + # The classes the plan settled on, described. The step is asked which + # of a class's properties the document fills, and the name alone is + # not the question: `contentLocation` and `provider` both read like + # the gallery holding a painting, and the entry is where they are + # told apart. + entries = enforcement.catalogue_text or tuple(f"- {name}" for name in enforcement.catalogue) + sections.append(f"{_PROPERTY_CLASSES}\n" + "\n".join(entries)) + sections.append(f"{_PROPERTY_ENTITIES}\n{listed}") return [ Message(role="system", content="\n\n".join(sections)), Message(role="user", content=request.document), diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index b5c02d9..186c635 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -12,6 +12,7 @@ """ import json +import threading from dataclasses import replace import pytest @@ -107,8 +108,91 @@ branches and a profile that refuses ``anyOf`` has something to lose.""" +def extract_format(client): + """The response format of the one extract call, whichever call it was.""" + return next(fmt for fmt in client.formats if _is_keyed(fmt)) + + +def extract_system(client): + """The system message the extract call was sent.""" + where = next(i for i, fmt in enumerate(client.formats) if _is_keyed(fmt)) + return client.messages[where][0].content + + +def fillable_formats(client): + """Every property call's response format, one per class the plan placed.""" + return [fmt for fmt in client.formats if _is_fillable(fmt)] + + +def fillable_user(client, where=0): + """The document as one property call received it.""" + found = [i for i, fmt in enumerate(client.formats) if _is_fillable(fmt)] + return client.messages[found[where]][1].content + + +def extract_user(client): + """The document as the extract call received it.""" + where = next(i for i, fmt in enumerate(client.formats) if _is_keyed(fmt)) + return client.messages[where][1].content + + +def offered_properties(client): + """What every property call offered, merged. One call per class now, so + a test asking what the step was offered means all of them.""" + merged = {} + for fmt in fillable_formats(client): + merged.update(enums_of(fmt)) + return merged + + +def fillable_system(client, where=0): + """The system message one property call was sent. + + Found by the prompt, not the schema: an unconstrained run sends none.""" + found = [i for i, turns in enumerate(client.messages) if _asks_for_properties(turns)] + return client.messages[found[where]][0].content + + +def _is_fillable(response_format) -> bool: + """Whether this call is the property step asking about some entities.""" + return "fillable" in ((response_format or {}).get("properties") or {}) + + +def _asks_for_properties(messages) -> bool: + """Whether this is the property step, read from the prompt. + + Needed because an unconstrained run sends no schema to recognise it by.""" + return bool(messages) and "which of its own properties" in messages[0].content + + +def _only_asked(fillable, response_format, messages=None) -> dict: + """The fixture's answer narrowed to the entities one call asks about.""" + inner = fillable.get("fillable", fillable) + if response_format is not None: + asked = set(response_format["properties"]["fillable"].get("properties") or {}) + else: + listed = messages[0].content if messages else "" + asked = {key for key in inner if f"\n{key} (" in listed} + return {"fillable": {key: value for key, value in inner.items() if key in asked}} + + +def _is_keyed(response_format) -> bool: + """Whether the extract call asked for one key per planned entity.""" + properties = (response_format or {}).get("properties") or {} + return bool(properties) and not {"entities", "fillable"} & set(properties) + + +def _keyed(group) -> dict: + """An entity list rewritten as the keyed answer the schema asks for.""" + answer = {} + for entity in group: + body = {key: value for key, value in entity.items() if key not in ("id", "@id", "entity_id", "key")} + answer[entity.get("id")] = body + return answer + + class MultiStepClient: - """Answers the detect step, the property step, then one call per group.""" + """Answers the detect step, the property step, then the extract call.""" model = "stepper" @@ -120,16 +204,31 @@ def __init__(self, plan=None, fillable=None, answers=None, detects=None) -> None self.formats: list = [] self.messages: list = [] self.calls = 0 + self._lock = threading.Lock() def invoke(self, messages, *, response_format=None, strict=False) -> ChatResponse: - self.calls += 1 - self.formats.append(response_format) - self.messages.append(list(messages)) + # Locked because the property step fans out one call per class and + # runs them together. + with self._lock: + self.calls += 1 + self.formats.append(response_format) + self.messages.append(list(messages)) if self.detects: - payload = self.detects.pop(0) - elif not self.asked_properties: + with self._lock: + payload = self.detects.pop(0) + elif _is_fillable(response_format) or _asks_for_properties(messages): self.asked_properties = True - payload = self.fillable + payload = _only_asked(self.fillable, response_format, messages) + elif _is_keyed(response_format): + # One extract call for the whole plan, so every group answers at + # once rather than a call each. Narrowed to the keys this call + # carries, because a provider that will not compile the batch + # gets it split and each half must answer only its own. + asked = set((response_format or {}).get("properties") or {}) + everything = [entity for group in self.answers for entity in group] + payload = _keyed([e for e in everything if not asked or e.get("id") in asked]) + if not asked: + self.answers = [] else: payload = {"entities": self.answers.pop(0) if self.answers else []} return ChatResponse( @@ -160,9 +259,22 @@ def request(ranges=RANGES): ) -def items_of(response_format): - """The entity shape an extract call was sent, union or object.""" - return response_format["properties"]["entities"]["items"] +def items_of(response_format, key=None): + """The entity shape an extract call was sent. + + The keyed shape holds one definition per class, reached from the key the + entity was planned under, so there is no single shape to return and the + first definition is the one a test asking for "the" shape means. + """ + properties = response_format["properties"] + if "entities" in properties: + return properties["entities"]["items"] + defs = response_format["$defs"] + if key is not None: + reference = properties[key] + reference = reference["anyOf"][0] if "anyOf" in reference else reference + return defs[reference["$ref"].rsplit("/", 1)[-1]] + return next(iter(defs.values())) def targets_of(slot): @@ -170,22 +282,39 @@ def targets_of(slot): return [value for value in slot["enum"] if value is not None] +def items_for(response_format, key="e1"): + """The answer shape one entity was offered, through its shared definition.""" + slot = response_format["properties"]["fillable"]["properties"][key] + if "$ref" in slot: + slot = response_format["$defs"][slot["$ref"].rsplit("/", 1)[-1]] + return slot["items"] + + def enums_of(response_format): """The property enumeration each entity was offered, per entity.""" offered = response_format["properties"]["fillable"]["properties"] - return {key: slot["items"]["enum"] for key, slot in offered.items()} + return {key: items_for(response_format, key)["enum"] for key in offered} def _sentence_about_several_values(content): """The one sentence of an extract prompt that allows several values.""" - return next(part for part in content.split(". ") if "more than one value" in part) + import re + + for part in re.split(r"(?<=\.)\s", content): + if "more than one value" in part: + return part + raise AssertionError("the prompt says nothing about several values") class TestTheCallsItMakes: - def test_one_detect_one_property_call_and_one_extract_per_group(self): + def test_one_detect_then_a_call_per_class_for_the_last_two_steps(self): + """Two classes on the plan, so the property step and the extract step + each fan out once per class. Entities of a class share its + definitions and entities of different classes do not, so one request + for the whole plan carries every class's grammar at once.""" client = MultiStepClient() agent(client).run(request()) - assert client.calls == 4 + assert client.calls == 5 def test_the_steps_are_named_apart_in_the_log(self): """Per-step tokens are the only way to cost the orchestration, and the @@ -194,6 +323,7 @@ def test_the_steps_are_named_apart_in_the_log(self): assert [c["step"] for c in result.calls.describe()["calls"]] == [ "detect", "properties", + "properties", "extract", "extract", ] @@ -201,7 +331,7 @@ def test_the_steps_are_named_apart_in_the_log(self): def test_tokens_are_attributed_to_the_step_that_spent_them(self): by_step = agent(MultiStepClient()).run(request()).calls.by_step() assert by_step["detect"].input_tokens == 100 - assert by_step["properties"].input_tokens == 100 + assert by_step["properties"].input_tokens == 200 assert by_step["extract"].input_tokens == 200 def test_entities_that_agree_on_class_and_properties_share_an_extract_call(self): @@ -216,10 +346,10 @@ def test_entities_that_agree_on_class_and_properties_share_an_extract_call(self) agent(client).run(request()) assert client.calls == 3 - def test_entities_that_chose_different_properties_do_not(self): - """Entities sharing a call share the schema that call is sent, so two - that chose different properties can no more share one than two that - shortlisted different classes.""" + def test_entities_that_chose_different_properties_get_their_own_definition(self): + """They still cannot share a schema, and they no longer need their + own call to avoid it: the key reaches a definition holding exactly + what that entity was asked for.""" client = MultiStepClient( plan=[ {"candidates": ["Person"], "mention": "Ada"}, @@ -229,7 +359,10 @@ def test_entities_that_chose_different_properties_do_not(self): answers=[[{"id": "e1", "type": "Person"}], [{"id": "e2", "type": "Person"}]], ) agent(client).run(request()) - assert client.calls == 4 + assert client.calls == 3 + shape = extract_format(client) + assert set(items_of(shape, "e1")["properties"]) == {"type", "name"} + assert set(items_of(shape, "e2")["properties"]) == {"type", "name", "jobTitle"} def test_a_plan_that_placed_nothing_stops_before_the_property_call(self): client = MultiStepClient(plan=[{"candidates": [], "mention": "Ada"}]) @@ -250,45 +383,58 @@ def sent(self, client=None): return client def test_the_property_schema_carries_one_array_per_entity(self): - assert sorted(enums_of(self.sent().formats[1])) == ["e1", "e2"] + assert sorted(offered_properties(self.sent())) == ["e1", "e2"] def test_the_enum_holds_only_that_entity_s_own_properties(self): """The direct analogue of closing the class slot. Pooling every entity's properties into one enumeration would let one entity be given another's property, which is the thing a per-entity enumeration is for.""" - offered = enums_of(self.sent().formats[1]) + offered = offered_properties(self.sent()) assert offered["e1"] == ["name", "jobTitle", "worksFor"] assert offered["e2"] == ["name", "legalName"] def test_a_property_another_entity_s_class_declares_is_absent(self): - offered = enums_of(self.sent().formats[1]) + offered = offered_properties(self.sent()) assert "jobTitle" not in offered["e2"] assert "legalName" not in offered["e1"] def test_an_inherited_property_is_offered(self): """`name` is declared on Thing, and Person and Organization both carry it, so a union over the shortlist has to walk the ancestry.""" - assert "name" in enums_of(self.sent().formats[1])["e1"] + assert "name" in offered_properties(self.sent())["e1"] def test_a_shortlist_offers_the_union_of_its_classes_properties(self): """The extract step has not committed to one class yet, and offering only the first would rule out a value the second may well state.""" client = MultiStepClient(plan=UNION_PLAN, fillable={"fillable": {"e1": ["name"], "e2": ["name"]}}) agent(client).run(request()) - assert enums_of(client.formats[1])["e1"] == ["name", "jobTitle", "isbn", "worksFor", "author"] + assert enums_of(fillable_formats(client)[0])["e1"] == ["name", "jobTitle", "isbn", "worksFor", "author"] def test_the_property_schema_carries_a_title(self): """LangChain rejects a response format without one, and every cell of the arm then fails without saying why.""" - assert self.sent().formats[1]["title"] == "FillableProperties" + assert fillable_formats(self.sent())[0]["title"] == "FillableProperties" def test_the_prompt_names_each_entity_with_its_class_and_its_properties(self): - content = self.sent().messages[1][0].content - assert 'e1 ("Ada"), Person: name, jobTitle, worksFor' in content + content = fillable_system(self.sent()) + assert 'e1 ("Ada"), Person:' in content + for name in ("name", "jobTitle", "worksFor"): + assert f"\n {name}" in content, name + + def test_a_link_says_which_planned_entities_its_range_admits(self): + """Chosen on the name alone, the step picks the property that reads + like the document rather than the one whose range holds the plan, and + the fill step then pins it to entities the page never meant.""" + content = fillable_system(self.sent()) + assert "worksFor (points at e2)" in content + + def test_a_literal_is_left_unannotated(self): + content = fillable_system(self.sent()) + assert "name (points at" not in content def test_the_property_step_reads_the_whole_document(self): - assert self.sent().messages[1][1].content == DOCUMENT + assert fillable_user(self.sent()) == DOCUMENT def test_the_chosen_properties_are_recorded_per_entity(self): """So a failure stays attributable to a step. Without it, never @@ -322,22 +468,22 @@ def sent(self, client=None, **kwargs): return client def test_the_extract_step_sees_the_whole_document_again(self): - assert self.sent().messages[2][1].content == DOCUMENT + assert extract_user(self.sent()) == DOCUMENT def test_the_prompt_names_the_entities_it_is_for_by_id(self): - assert 'e1 ("Ada")' in self.sent().messages[2][0].content + assert 'e1 ("Ada")' in extract_system(self.sent()) def test_the_prompt_names_the_properties_to_fill(self): """Named even though the schema already carries only them, as the ids are named even though the id slot is already enumerated.""" - assert "Report only these properties for them: name, worksFor." in self.sent().messages[2][0].content + assert 'e1 ("Ada"): name, worksFor' in extract_system(self.sent()) def test_the_schema_carries_the_chosen_properties(self): - assert "worksFor" in items_of(self.sent().formats[2])["properties"] + assert "worksFor" in items_of(extract_format(self.sent()))["properties"] def test_a_property_the_step_left_out_is_gone_from_the_schema(self): """Closing the property slot, which is what the step is for.""" - offered = items_of(self.sent().formats[2])["properties"] + offered = items_of(extract_format(self.sent()))["properties"] assert "jobTitle" not in offered assert "legalName" not in offered @@ -345,7 +491,7 @@ def test_a_required_property_survives_the_trim(self): """Dropping it leaves a name in `required` with nothing to satisfy it, and a subset that rewrites `required` from `properties` would instead make the answer legal without it.""" - assert "type" in items_of(self.sent().formats[2])["properties"] + assert "type" in items_of(extract_format(self.sent()))["properties"] def test_an_entity_the_step_left_empty_is_asked_for_its_class_alone(self): """What the step said. Restoring the slots behind its back would hide a @@ -359,30 +505,30 @@ def test_an_entity_the_step_left_empty_is_asked_for_its_class_alone(self): answers=[[{"id": "e1", "type": "Person"}]], ) agent(client).run(request()) - assert sorted(items_of(client.formats[2])["properties"]) == ["id", "type"] - assert "no property value" in client.messages[2][0].content + assert sorted(items_of(extract_format(client))["properties"]) == ["type"] + assert "no property value" in extract_system(client) def test_an_open_condition_keeps_the_schema_whole(self): """The same two calls, with the answer advisory instead of binding. A property the step missed can still be answered, which is the claim the closed condition is measured against.""" client = self.sent(close_properties=False) - assert "jobTitle" in items_of(client.formats[2])["properties"] + assert "jobTitle" in items_of(extract_format(client))["properties"] def test_an_open_condition_still_names_the_properties(self): - assert "Report only these properties" in self.sent(close_properties=False).messages[2][0].content + assert "Report only these properties" in extract_system(self.sent(close_properties=False)) def test_the_prompt_says_a_property_may_hold_more_than_one_value(self): """The answer shape declares every slot as an array, so the shape permits several and only the wording was silent. Told nothing, models answer with the first value alone.""" - content = self.sent().messages[2][0].content + content = extract_system(self.sent()) assert "Where the document states more than one value for a property, give every one of them." in content def test_it_says_neither_which_property_nor_how_many_values(self): """How many values a document states is part of what is being measured, and a count named for one property would answer it.""" - sentence = _sentence_about_several_values(self.sent().messages[2][0].content) + sentence = _sentence_about_several_values(extract_system(self.sent())) assert not any(character.isdigit() for character in sentence) assert not any(name in sentence for name in ("name", "worksFor", "jobTitle", "isbn")) @@ -393,18 +539,24 @@ def sent(self): agent(client).run(request()) return client - def test_an_extract_call_is_pinned_to_the_ids_it_is_for(self): - client = self.sent() - assert items_of(client.formats[2])["properties"]["id"]["enum"] == ["e1"] - assert items_of(client.formats[3])["properties"]["id"]["enum"] == ["e2"] - - def test_the_id_is_required(self): - assert "id" in items_of(self.sent().formats[2])["required"] - - def test_the_id_survives_the_property_trim(self): - """It was never offered to the property step, because it is how the - answer is joined back to the plan and not a value to fill.""" - assert "id" in items_of(self.sent().formats[2])["properties"] + def test_the_answer_is_keyed_by_the_ids_the_plan_issued(self): + """There is no id slot to pin. The key is the id, so an answer cannot + be filed under one the plan never handed out, and the shape that had + an id slot was answering under six it had not been asked about.""" + shapes = [fmt for fmt in self.sent().formats if _is_keyed(fmt)] + assert sorted(key for shape in shapes for key in shape["properties"]) == ["e1", "e2"] + assert all(shape["required"] == list(shape["properties"]) for shape in shapes) + + def test_no_definition_carries_an_id_slot(self): + shape = extract_format(self.sent()) + assert all("id" not in definition["properties"] for definition in shape["$defs"].values()) + + def test_each_key_reaches_its_own_class(self): + shapes = [fmt for fmt in self.sent().formats if _is_keyed(fmt)] + found = { + key: items_of(shape, key)["properties"]["type"]["const"] for shape in shapes for key in shape["properties"] + } + assert found == {"e1": "Person", "e2": "Organization"} class TestPinningAReference: @@ -414,10 +566,10 @@ def sent(self, client=None): return client def test_only_a_compatible_entity_is_offered(self): - assert targets_of(items_of(self.sent().formats[2])["properties"]["worksFor"]) == ["e2"] + assert targets_of(items_of(extract_format(self.sent()))["properties"]["worksFor"]) == ["e2"] def test_an_entity_whose_class_is_not_in_the_range_is_absent(self): - assert "e1" not in targets_of(items_of(self.sent().formats[2])["properties"]["worksFor"]) + assert "e1" not in targets_of(items_of(extract_format(self.sent()))["properties"]["worksFor"]) def test_a_reference_the_property_step_left_out_is_not_reported_as_left_open(self): """A slot that is not offered is not a slot left open. The property @@ -425,7 +577,7 @@ def test_a_reference_the_property_step_left_out_is_not_reported_as_left_open(sel limit removing it.""" client = MultiStepClient(fillable={"fillable": {"e1": ["name"], "e2": ["name"]}}) result = agent(client).run(request()) - assert "worksFor" not in items_of(client.formats[2])["properties"] + assert "worksFor" not in items_of(extract_format(client))["properties"] assert result.unpinned == [] def test_a_range_no_planned_entity_fits_is_recorded_as_left_open(self): @@ -440,7 +592,7 @@ def test_a_range_no_planned_entity_fits_is_recorded_as_left_open(self): def test_an_unconstrained_arm_pins_no_reference(self): client = MultiStepClient() agent(client, name="schema-dump-catalog-not-enforced-gated").run(request()) - assert client.formats[2] is None + assert all(fmt is None for fmt in client.formats) class TestTheLinkSurvives: @@ -484,39 +636,37 @@ def sent(self, profile): answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}], [{"id": "e2", "type": "Organization"}]], ) result = agent(client, name="schema-dump-catalog-enforced", profile=profile).run(request()) - return items_of(client.formats[2]), result.degradation + return items_of(extract_format(client)), result.degradation - def test_a_profile_that_takes_anyof_keeps_the_union_and_the_pin(self): + def test_the_definition_keeps_the_pin(self): items, degradation = self.sent("openai") - branch = next(b for b in items["anyOf"] if "worksFor" in b["properties"]) - assert targets_of(branch["properties"]["worksFor"]) == ["e2"] + assert targets_of(items["properties"]["worksFor"]) == ["e2"] assert degradation.dropped.get("anyOf") is None - def test_the_branches_are_trimmed_with_the_answer_shape(self): - """A branch still declaring a property the shape no longer carries - would put it back on the union arm alone, and the difference between - the arms would be a difference in what each was asked for.""" + def test_the_definition_is_trimmed_with_the_answer_shape(self): + """A definition still declaring a property the shape no longer + carries would ask for something the step did not choose.""" items, _ = self.sent("openai") - assert all("isbn" not in branch["properties"] for branch in items["anyOf"]) + assert "isbn" not in items["properties"] - def test_the_pinned_id_reaches_every_branch(self): + def test_every_definition_names_the_class_it_is_for(self): + """What the union's discriminator did, done by the key instead.""" items, _ = self.sent("openai") - assert all(targets_of(branch["properties"]["id"]) == ["e1"] for branch in items["anyOf"]) + assert items["properties"]["type"]["const"] - def test_a_profile_that_refuses_anyof_still_gets_the_pin(self): - items, _ = self.sent("anthropic") + def test_a_profile_that_refuses_anyof_loses_nothing_here(self): + """The union was the one thing this step asked that profile for and + could not have. The key settles the class, so there is no choice to + flatten and the two profiles are sent the same shape.""" + items, degradation = self.sent("anthropic") assert "anyOf" not in items assert targets_of(items["properties"]["worksFor"]) == ["e2"] + assert degradation.dropped.get("anyOf") is None - def test_refusing_anyof_is_recorded_as_a_loss(self): - _, degradation = self.sent("anthropic") - assert degradation.dropped.get("anyOf") == 1 - assert degradation.fidelity < 1.0 - - def test_the_two_profiles_report_different_fidelity(self): - _, keeps = self.sent("openai") - _, loses = self.sent("anthropic") - assert loses.fidelity < keeps.fidelity + def test_the_two_profiles_now_report_the_same_fidelity(self): + _, openai = self.sent("openai") + _, anthropic = self.sent("anthropic") + assert anthropic.fidelity == openai.fidelity == 1.0 class TestAskingAgain: @@ -554,7 +704,7 @@ def test_it_hands_the_validator_s_reasons_back_verbatim(self): def test_a_usable_answer_is_not_asked_again(self): client = MultiStepClient() agent(client).run(request()) - assert client.calls == 4 + assert client.calls == 5 def test_an_answer_under_an_undeclared_wrapper_is_left_alone(self): """Naming a schema stopped one provider rejecting it and started @@ -563,7 +713,7 @@ def test_an_answer_under_an_undeclared_wrapper_is_left_alone(self): client = MultiStepClient(detects=[{"EntityCandidates": PLAN}]) result = agent(client).run(request()) assert result.selected == {"e1": ("Person",), "e2": ("Organization",)} - assert client.calls == 4 + assert client.calls == 5 def test_a_document_with_nothing_in_it_is_not_asked_again(self): """An answer that validates and names no entity is a document with @@ -648,7 +798,7 @@ def test_a_candidate_outside_the_catalogue_is_dropped(self): def test_a_request_without_ranges_says_nothing_about_links(self): client = MultiStepClient() agent(client).run(request(ranges=None)) - assert "points at" not in client.messages[2][0].content + assert "points at" not in extract_system(client) class TestWhatTheDocumentCalledIt: @@ -711,12 +861,12 @@ def sent(self, client=None, **kwargs): return client def test_a_mention_keeps_the_slot_the_property_step_left_out(self): - assert "name" in items_of(self.sent().formats[2])["properties"] + assert "name" in items_of(extract_format(self.sent()))["properties"] def test_it_keeps_nothing_else_the_step_left_out(self): """Closing the property slot is what the arm is measuring, so the rule reaches one slot and the step still decides the rest.""" - offered = items_of(self.sent().formats[2])["properties"] + offered = items_of(extract_format(self.sent()))["properties"] assert "jobTitle" not in offered def test_the_result_names_the_entities_it_kept_it_for(self): @@ -744,7 +894,7 @@ def test_the_plan_reading_no_mention_keeps_nothing(self): answers=[[{"id": "e1", "type": "Person", "worksFor": "e2"}]], ) result = agent(client).run(request()) - assert "name" not in items_of(client.formats[2])["properties"] + assert "name" not in items_of(extract_format(client))["properties"] assert result.named == [] def test_a_shortlist_that_admits_no_name_keeps_nothing(self): @@ -754,17 +904,21 @@ def test_a_shortlist_that_admits_no_name_keeps_nothing(self): result = agent(client).run(replace(request(), parents=None)) assert result.named == [] - def test_the_rule_adds_nothing_to_the_required_list(self): - """The slot is kept, not demanded. "Jane works at ExampleCorp" states - an employment relation and not that Jane's name is Jane, and a model - declining the slot is right.""" - assert "name" not in items_of(self.sent(profile="anthropic").formats[2])["required"] - - def test_a_subset_that_requires_everything_still_leaves_it_declinable(self): - """Where the profile rewrites `required` from `properties`, null is - how a model declines, and the kept slot is no worse off than one the - step chose.""" - assert "null" in items_of(self.sent().formats[2])["properties"]["name"]["type"] + def test_the_kept_slot_is_required_like_every_other(self): + """Whatever reaches the fill grammar is required, the mention-kept + slot included. The plan recorded what the document calls the entity, + so the slot has an answer, and a grammar that lets it be skipped is + the one the model takes: with only the class and id required, + claude-haiku-4-5 answered `{"type": "Recipe", "id": "e1"}` to a call + naming five properties.""" + assert "name" in items_of(extract_format(self.sent(profile="anthropic")))["required"] + + def test_nothing_the_step_left_out_is_demanded(self): + """Required follows the grammar, and the grammar follows the property + step. A slot neither chosen nor kept is in neither.""" + shape = items_of(extract_format(self.sent(profile="anthropic"))) + assert "jobTitle" not in shape["required"] + assert "jobTitle" not in shape["properties"] def test_an_answer_that_declines_it_is_kept_as_it_came(self): result = agent(MultiStepClient(fillable=self.DECLINED, answers=self.ANSWERS)).run(request()) @@ -773,7 +927,7 @@ def test_an_answer_that_declines_it_is_kept_as_it_came(self): def test_the_prompt_names_it_among_the_properties_to_fill(self): """Named as every kept property is, because an arm that shows no schema still has to be told the slot is there.""" - assert "Report only these properties for them: name, worksFor." in self.sent().messages[2][0].content + assert 'e1 ("Ada"): name, worksFor' in extract_system(self.sent()) def test_two_entities_the_rule_separates_do_not_share_a_call(self): """Entities sharing a call share the schema that call is sent, so the @@ -787,7 +941,9 @@ def test_two_entities_the_rule_separates_do_not_share_a_call(self): answers=[[{"id": "e1", "type": "Person"}], [{"id": "e2", "type": "Person"}]], ) agent(client).run(request()) - assert client.calls == 4 + assert client.calls == 3 + shape = extract_format(client) + assert "name" in items_of(shape, "e1")["properties"] def test_the_record_is_serialisable(self): described = agent(MultiStepClient(fillable=self.DECLINED, answers=self.ANSWERS)).run(request()).describe() @@ -944,8 +1100,7 @@ class TestReadingTheAnswer: def test_the_answer_is_names_alone(self): from oold.agent.prompts import property_schema - item = property_schema({"e1": ("name",)})["properties"]["fillable"]["properties"]["e1"]["items"] - assert item == {"type": "string", "enum": ["name"]} + assert items_for(property_schema({"e1": ("name",)})) == {"type": "string", "enum": ["name"]} def test_an_answer_carrying_a_quotation_is_still_read(self): client = MultiStepClient(detects=[]) @@ -974,15 +1129,12 @@ class TestAskingForTheWordsThatStateIt: def test_the_default_answer_is_names_alone(self): from oold.agent.prompts import property_schema - assert property_schema({"e1": ("name",)})["properties"]["fillable"]["properties"]["e1"]["items"] == { - "type": "string", - "enum": ["name"], - } + assert items_for(property_schema({"e1": ("name",)})) == {"type": "string", "enum": ["name"]} def test_asked_for_it_the_answer_carries_both(self): from oold.agent.prompts import property_schema - item = property_schema({"e1": ("name",)}, evidence=True)["properties"]["fillable"]["properties"]["e1"]["items"] + item = items_for(property_schema({"e1": ("name",)}, evidence=True)) assert item["required"] == ["property", "stated"] assert item["properties"]["property"]["enum"] == ["name"] @@ -990,7 +1142,7 @@ def test_the_request_decides(self): client = MultiStepClient(detects=[]) plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) agent(client).fillable_properties(request(), plan) - assert client.formats[-1]["properties"]["fillable"]["properties"]["e1"]["items"]["type"] == "string" + assert items_for(client.formats[-1])["type"] == "string" def test_what_the_model_wrote_is_kept_for_the_caller(self): """The answer is the names; this is the working behind them.""" @@ -1208,17 +1360,22 @@ def run(self, fillable=None, plan=None, answers=None): def test_an_entity_a_chosen_embedding_absorbs_leaves_the_top_level_plan(self): client, result = self.run() assert result.absorbed == {"e2": "e1"} - assert client.calls == 3, "the absorbed entity no longer has an extract call of its own" + # It is still asked which properties it fills, because that answer is + # what the holder writes inside itself. What it no longer has is a + # place of its own in the extract call. + assert len([fmt for fmt in client.formats if _is_keyed(fmt)]) == 1 def test_the_holder_is_the_only_entity_the_extract_call_is_asked_to_report(self): client, _ = self.run() - assert 'under the id given here: e1 ("Andrea").' in client.messages[2][0].content - - def test_the_absorbed_entity_keeps_the_id_it_was_planned_under(self): - """The embedded object carries an id as a top-level one does, and - anything may still point at it, so the id slot has to offer it.""" - client, result = self.run() - assert embedded_in(client.formats[2])["properties"]["id"]["enum"] == ["e1", "e2"] + content = extract_system(client) + assert 'e1 ("Andrea"):' in content + assert 'e2 ("Hauptstrasse 1"):' not in content + + def test_the_absorbed_entity_keeps_what_the_plan_read_of_it(self): + """It is written inside its holder rather than under a key of its + own, so the plan's record of it is the only place its class and its + mention survive.""" + _, result = self.run() assert result.selected["e2"] == ("PostalAddress",) assert result.mentions["e2"] == "Hauptstrasse 1" @@ -1228,8 +1385,8 @@ def test_the_call_that_holds_it_is_given_the_properties_it_fills(self): the absorbed entity with a class and an id and nowhere to put its value.""" client, _ = self.run() - assert "streetAddress" in embedded_in(client.formats[2])["properties"] - assert "streetAddress" not in items_of(client.formats[2])["properties"] + assert "streetAddress" in embedded_in(extract_format(client))["properties"] + assert "streetAddress" not in items_of(extract_format(client))["properties"] def test_the_absorbed_entity_is_reported_inside_its_holder(self): _, result = self.run() @@ -1248,7 +1405,10 @@ def test_an_entity_no_chosen_embedding_can_absorb_stays_at_the_top_level(self): ], ) assert result.absorbed == {} - assert client.calls == 4 + # Detect, three property calls and one extract call per entity. The + # third property call is the object standing in `address`, which is + # asked about whether or not the slot holding it is chosen. + assert client.calls == 6 assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2"] def test_an_entity_two_holders_could_absorb_stays_at_the_top_level(self): @@ -1311,6 +1471,21 @@ def test_an_edge_reaching_an_entity_written_inside_another_is_not_dangling(self) assert links == [Edge(source="e2", prop="worksFor", target="e3")] assert dangling == [] + def test_an_edge_an_embedded_object_states_is_read_from_where_it_stands(self): + """The object is where an entity is written, and an entity written in + place points at others. Reading the top level alone leaves the thing + it names with nothing pointing at it in the record while the answer + points at it.""" + from oold.agent.extraction import _edges_of + + answered = [ + {"id": "e1", "type": "Recipe", "supply": [{"id": "s1", "type": "HowToSupply", "item": ["e2"]}]}, + {"id": "e2", "type": "Product", "name": "Sugar"}, + ] + links, dangling = _edges_of(answered, {"item": ("Thing",)}) + assert links == [Edge(source="s1", prop="item", target="e2")] + assert dangling == [] + def test_the_record_is_serialisable(self): _, result = self.run() described = result.describe() @@ -1318,6 +1493,148 @@ def test_the_record_is_serialisable(self): assert described["absorbed"] == {"e2": "e1"} +EMBEDDED_QUANTITY = { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "id": {"type": "string"}, + "unitText": {"type": "string"}, + "unitCode": {"type": "string"}, + "name": {"type": "string"}, + }, + "required": ["type"], + }, +} +"""An embedded object with more than one slot, one of them named as the holder +names one of its own. + +``name`` is the collision the property step has to survive. The holder choosing +it says the document names the person, and it says nothing about whether the +quantity written inside the person is named.""" + +QUANTITY_SCHEMA = { + **SCHEMA, + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + **SCHEMA["properties"]["entities"]["items"]["properties"], + "quantity": EMBEDDED_QUANTITY, + }, + "required": ["type"], + }, + } + }, +} + +QUANTITY_BRANCHES = {**BRANCHES, "Person": {**BRANCHES["Person"], "quantity": EMBEDDED_QUANTITY}} + + +def quantity_request(): + return ExtractionRequest( + document="Ada carries 3 g.", + schema=QUANTITY_SCHEMA, + branches=QUANTITY_BRANCHES, + parents=PARENTS, + ranges=RANGES, + ) + + +class TestTheObjectWrittenInsideAnEntityIsAskedAboutToo: + """The property step runs over planned entities, and an object written + inside one is not planned. + + So nothing ever chose its slots, and the extract call asked for every slot + the class it holds declares: a recipe's yield arrived as a quantity + carrying a maximum, a minimum, a unit code and a unit text that no step + had named, repeated in every class definition able to hold one. + + The object is asked about as if it were an entity, under a key made of the + entity holding it and the slot it stands in. That key belongs to the one + step: it reaches no other, and nothing answers under it in the extract + call, where the object stays written inside its holder. + """ + + def run(self, fillable=None): + client = MultiStepClient( + plan=[{"candidates": ["Person"], "mention": "Ada"}], + fillable=fillable or {"fillable": {"e1": ["name", "quantity"], "e1__quantity": ["unitText"]}}, + answers=[[{"id": "e1", "type": "Person", "name": "Ada", "quantity": [{"type": "QuantitativeValue"}]}]], + ) + result = agent(client).run(quantity_request()) + return client, result + + def test_the_step_is_asked_what_the_object_states(self): + client, _ = self.run() + assert offered_properties(client)["e1__quantity"] == ["unitText", "unitCode", "name"] + + def test_the_question_says_which_slot_of_which_entity_it_is_about(self): + client, _ = self.run() + listed = "\n".join(fillable_system(client, where) for where in range(len(fillable_formats(client)))) + assert 'the object written into quantity of e1 ("Ada")' in listed + + def test_what_it_chose_inside_is_what_the_object_carries(self): + client, _ = self.run() + inside = embedded_in(extract_format(client), "quantity") + assert sorted(inside["properties"]) == ["id", "type", "unitText"] + + def test_what_it_chose_inside_is_required_inside(self): + """The same trade the top level makes: the step was asked which + properties the document states and it named this one, so a call that + may omit it asks the question twice and takes the cheaper answer.""" + client, _ = self.run() + assert "unitText" in embedded_in(extract_format(client), "quantity")["required"] + + def test_a_name_the_holder_chose_is_not_required_inside_the_object(self): + """The two vocabularies overlap and the questions do not. ``name`` is + chosen for the person, and whether the quantity written inside the + person is named was asked separately and answered no.""" + client, _ = self.run() + inside = embedded_in(extract_format(client), "quantity") + assert "name" not in inside["properties"] + assert "name" not in inside["required"] + + def test_the_class_slot_survives_whatever_was_chosen(self): + """It is what the embedded object's class is graded against, and no + step was ever asked about it.""" + client, _ = self.run(fillable={"fillable": {"e1": ["quantity"], "e1__quantity": []}}) + inside = embedded_in(extract_format(client), "quantity") + assert sorted(inside["properties"]) == ["id", "type"] + assert "type" in inside["required"] + + def test_the_object_is_not_an_entity_anywhere_outside_that_step(self): + """It has no id of its own to be planned under, nothing points at it, + and the extract call answers under the plan's keys alone.""" + client, result = self.run() + assert sorted(result.selected) == ["e1"] + assert sorted(result.properties_chosen) == ["e1"] + assert sorted(key for fmt in client.formats if _is_keyed(fmt) for key in fmt["properties"]) == ["e1"] + + def test_a_name_invented_inside_is_reported_against_the_entity_holding_it(self): + _, result = self.run(fillable={"fillable": {"e1": ["name"], "e1__quantity": ["sparkle"]}}) + assert result.properties_invented == {"e1": ("sparkle",)} + + def test_the_objects_share_one_call_rather_than_taking_one_each(self): + """Two entities of a class ask the same question, so a call per class + is a call per question. An object standing in a slot asks a question + of its own, and one call each turns a page holding a dozen into a + dozen calls.""" + client = MultiStepClient( + plan=[ + {"candidates": ["Person"], "mention": "Ada"}, + {"candidates": ["Person"], "mention": "Grace"}, + ], + fillable={"fillable": {"e1": ["name"], "e2": ["name"], "e1__quantity": [], "e2__quantity": []}}, + answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}]], + ) + agent(client).run(quantity_request()) + assert len(fillable_formats(client)) == 2 + + class TestASchemaThatOffersNoObjectSlot: """Nothing about the existing behaviour may change where there is no embedding to choose, which is every corpus that declares its node-valued @@ -1340,9 +1657,430 @@ def test_the_run_makes_the_calls_it_made_before_and_absorbs_nothing(self): client = MultiStepClient() result = agent(client).run(request()) assert result.absorbed == {} - assert client.calls == 4 - assert items_of(client.formats[2])["properties"]["id"]["enum"] == ["e1"] - assert items_of(client.formats[3])["properties"]["id"]["enum"] == ["e2"] + assert client.calls == 5 + assert sorted(key for fmt in client.formats if _is_keyed(fmt) for key in fmt["properties"]) == ["e1", "e2"] assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2"] assert result.properties_chosen == {"e1": ("name", "worksFor"), "e2": ("name",)} assert result.links == [Edge(source="e1", prop="worksFor", target="e2")] + + +class TestAListEncodedAsAString: + """claude-sonnet-5 answers the plan step with the array inside a string. + + The entities are right and doubly encoded, so a reader taking the declared + type at its word plans nothing and the chain stops after its first call. + """ + + def _entities(self, payload): + from oold.agent.extraction import _entities_of + + return _entities_of(payload) + + def test_the_entities_are_read_out_of_the_string(self): + payload = {"entities": '[{"mention": "Ada", "candidates": ["Person"]}]'} + assert self._entities(payload) == [{"mention": "Ada", "candidates": ["Person"]}] + + def test_the_object_brace_the_model_put_inside_the_quotes_is_dropped(self): + """The answer seen in the wild is not a quoted array: it is a quoted + object whose opening brace was eaten, so the string ends one brace + past the array.""" + payload = {"entities": '[{"mention": "Ada", "candidates": ["Person"]}]}'} + assert self._entities(payload) == [{"mention": "Ada", "candidates": ["Person"]}] + + def test_a_lone_wrapper_is_unwrapped_too(self): + payload = {"EntityCandidates": '[{"mention": "Ada", "candidates": ["Person"]}]'} + assert self._entities(payload) == [{"mention": "Ada", "candidates": ["Person"]}] + + def test_prose_is_still_the_failure_it_is(self): + assert self._entities({"entities": "I could not find any entities."}) == [] + + def test_a_string_holding_something_other_than_objects_is_refused(self): + assert self._entities({"entities": '["Ada", "Acme"]'}) == [] + + def test_a_plain_list_is_unaffected(self): + assert self._entities({"entities": [{"mention": "Ada"}]}) == [{"mention": "Ada"}] + + +class TestTheCatalogueEntryFollowsTheGrammar: + """The entry describes the class the call is being asked about. + + A recipe extract was shown `cookingMethod`, `cookTime`, `recipeCategory` + and `recipeCuisine`, none of them in its grammar, and not shown `name`, + `author` or `hasPart`, all three of which were. + """ + + ENTRY = ( + "- Person\n" + " A person, alive or dead.\n" + " extends: Thing\n" + " name (text)\n" + " jobTitle (text)\n" + " worksFor (link: Organization)\n" + " reached by: Organization.employee" + ) + + def _narrowed(self, keep): + from dataclasses import replace + + from oold.agent.enforcement import ARMS + + enforcement = replace(ARMS["schema-dump-catalog-enforced"], catalogue=("Person",), catalogue_text=(self.ENTRY,)) + return enforcement.with_properties(keep).catalogue_text[0] + + def test_a_property_outside_the_grammar_is_dropped(self): + assert "jobTitle" not in self._narrowed({"name", "worksFor"}) + + def test_a_property_inside_it_stays(self): + entry = self._narrowed({"name", "worksFor"}) + assert "name (text)" in entry + assert "worksFor (link: Organization)" in entry + + def test_what_the_class_is_survives_the_narrowing(self): + """The heading, the gloss and what it extends say what the class is, + not what this call may write.""" + entry = self._narrowed(set()) + for line in ("- Person", "A person, alive or dead.", "extends: Thing"): + assert line in entry + + def test_an_entry_with_no_rendering_is_left_alone(self): + from dataclasses import replace + + from oold.agent.enforcement import ARMS + + bare = replace(ARMS["schema-dump-catalog-enforced"], catalogue=("Person",), catalogue_text=None) + assert bare.with_properties({"name"}).catalogue_text is None + + +class TestTheFillableStepIsShownItsClasses: + """The step is asked which of a class's properties the document fills. + + Shown names alone it files values under the wrong slot: `contentLocation` + and `provider` both read like the gallery holding a painting, and the + entry is where they are told apart. + """ + + def _system(self, **kwargs): + client = MultiStepClient() + agent(client, **kwargs).run(request()) + return fillable_system(client) + + def test_the_entries_are_shown(self): + assert "The classes these entities were placed in:" in self._system() + + def test_only_the_classes_the_plan_settled_on(self): + """The rest of the catalogue describes classes nothing on the plan + can be.""" + shown = self._system() + assert "- Person" in shown + assert "- Movie" not in shown + + +class TestEntitiesOfOneClassShareAnEnumeration: + """Nineteen entities over four classes wrote the enumeration nineteen + times, and Anthropic refused the grammar as too complex to compile.""" + + def _schema(self): + from oold.agent.prompts import property_schema + + return property_schema({"e1": ("name", "author"), "e2": ("name", "author"), "e3": ("name",)}) + + def test_one_definition_per_distinct_set(self): + assert len(self._schema()["$defs"]) == 2 + + def test_entities_offered_the_same_names_reach_the_same_one(self): + offered = self._schema()["properties"]["fillable"]["properties"] + assert offered["e1"] == offered["e2"] + assert offered["e1"] != offered["e3"] + + def test_every_entity_still_gets_its_own_names(self): + from oold.agent.prompts import property_schema + + built = property_schema({"e1": ("name", "author"), "e3": ("name",)}) + assert enums_of(built) == {"e1": ["name", "author"], "e3": ["name"]} + + +class TestTheFlagFormOfTheFillableStep: + """The same question asked as a boolean per property. + + A provider refuses an enumeration of a hundred and thirty-three strings + as too complex to compile, however short the array is bounded. A fixed + object of booleans carries no enumeration. + """ + + def _schema(self, **kwargs): + from oold.agent.prompts import property_schema + + return property_schema({"e1": ("name", "author")}, flags=True, **kwargs) + + def _definition(self): + built = self._schema() + reference = built["properties"]["fillable"]["properties"]["e1"] + return built["$defs"][reference["$ref"].rsplit("/", 1)[-1]] + + def test_every_property_is_a_boolean(self): + properties = self._definition()["properties"] + assert {name: slot["type"] for name, slot in properties.items()} == { + "name": "boolean", + "author": "boolean", + } + + def test_nothing_is_enumerated(self): + import json + + assert '"enum"' not in json.dumps(self._schema()) + + def test_every_property_is_required_so_none_is_skipped(self): + """A property left out is the recall failure the form exists to fix, + and optional keys are the shape the provider charges for.""" + assert self._definition()["required"] == ["name", "author"] + + def test_the_answer_is_read_as_the_names_marked_true(self): + from oold.agent.extraction import _stated_properties + + assert _stated_properties({"name": True, "author": False}) == ["name"] + + def test_the_name_form_is_still_read(self): + from oold.agent.extraction import _stated_properties + + assert _stated_properties(["name"]) == ["name"] + + def test_a_run_in_the_flag_form_reaches_the_same_answer(self): + client = MultiStepClient( + fillable={ + "fillable": { + "e1": {"name": True, "worksFor": True, "jobTitle": False}, + "e2": {"name": True, "legalName": False}, + } + } + ) + result = agent(client, property_flags=True).run(request()) + assert result.properties_chosen == {"e1": ("name", "worksFor"), "e2": ("name",)} + + +class TestWhatTheEnumerationIsBuying: + """The property step can be asked the same question with no grammar. + + What the enumeration prevents is only countable by taking it away: a name + the step answers that it was never offered is dropped either way, so the + constrained run cannot tell you whether the model would have invented one. + """ + + OFFERED = {"fillable": {"e1": ["name", "worksFor", "sparkle"], "e2": ["name", "glow"]}} + + def test_a_name_outside_the_offer_is_recorded(self): + client = MultiStepClient(fillable=self.OFFERED) + result = agent(client, constrain_properties=False).run(request()) + assert result.properties_invented == {"e1": ("sparkle",), "e2": ("glow",)} + + def test_it_is_still_dropped_from_the_answer(self): + client = MultiStepClient(fillable=self.OFFERED) + result = agent(client, constrain_properties=False).run(request()) + assert result.properties_chosen["e1"] == ("name", "worksFor") + + def test_the_property_call_is_sent_no_grammar(self): + client = MultiStepClient() + agent(client, constrain_properties=False).run(request()) + assert all(fmt is None for fmt in fillable_formats(client)) or not fillable_formats(client) + + def test_the_extract_call_still_has_one(self): + """The axis is the property step alone, so a run stays comparable on + everything else.""" + client = MultiStepClient() + agent(client, constrain_properties=False).run(request()) + assert extract_format(client) is not None + + def test_an_answer_inside_the_offer_records_nothing(self): + """Which is what a bound grammar guarantees. The record counts what + the model wrote, not what the arm asked for, so a run under a real + decoder comes back empty by construction.""" + client = MultiStepClient() + assert agent(client).run(request()).properties_invented == {} + + +class TestTheAnswerFormIsSaidInWords: + """A condition that sends no schema leaves the words the only place the + form is stated. Asked for flags with the grammar off, the property step + was sent a request byte-identical to the one asking for names.""" + + def _system(self, **kwargs): + client = MultiStepClient() + agent(client, **kwargs).run(request()) + return fillable_system(client) + + def test_the_names_form_asks_for_a_list(self): + assert "one list of property names per entity" in self._system() + + def test_the_flag_form_asks_for_true_and_false(self): + said = self._system(property_flags=True) + assert "true where the document states a value" in said + assert "one list of property names per entity" not in said + + def test_it_is_said_even_with_no_grammar(self): + said = self._system(property_flags=True, constrain_properties=False) + assert "true where the document states a value" in said + + def test_the_two_forms_send_different_requests(self): + names = self._system(constrain_properties=False) + flags = self._system(property_flags=True, constrain_properties=False) + assert names != flags + + +class TestTheRequestIsSizedToWhatCompiles: + """The compiler charges for entities times names, not for either alone. + + Measured on claude-haiku-4-5: 5 names per entity fits 64 entities, 20 + names fits 35, 62 names fits 12, 133 names fits 7. Over the budget the + request is refused outright, so the step has to size itself. + """ + + def _calls(self, names, profile="anthropic"): + built = agent(MultiStepClient(detects=[]), profile=profile) + return built._per_call(tuple(f"p{j}" for j in range(names))) + + def test_a_narrow_class_goes_in_one_call(self): + assert self._calls(5) >= 40 + + def test_a_wide_class_is_split(self): + assert 1 < self._calls(62) < 20 + + def test_the_split_follows_the_names_not_a_fixed_count(self): + assert self._calls(5) > self._calls(62) > self._calls(133) + + def test_a_provider_declaring_no_budget_is_not_split(self): + assert self._calls(62, profile="openai") >= 62 + + def test_every_entity_still_reaches_a_call(self): + client = MultiStepClient() + result = agent(client).run(request()) + assert set(result.properties_chosen) == {"e1", "e2"} + + +class TestAnObjectTwoClassesHoldIsWrittenOnce: + """The class definitions are shared through ``$defs`` and what they hold + is not, so the grammar repeats an embedded object once per class able to + hold it.""" + + def _defs(self, **extra): + from oold.agent.extraction import _hoisted + + quantity = {"type": "object", "properties": {"unitText": {"type": "string"}}} + return _hoisted({ + "Person": {"type": "object", "properties": {"height": quantity}}, + "Book": {"type": "object", "properties": {"weight": quantity}}, + **extra, + }) + + def test_the_repeated_body_is_written_once_and_referenced(self): + hoisted = self._defs() + assert hoisted["Person"]["properties"]["height"] == {"$ref": "#/$defs/shared1"} + assert hoisted["Book"]["properties"]["weight"] == {"$ref": "#/$defs/shared1"} + assert hoisted["shared1"] == {"type": "object", "properties": {"unitText": {"type": "string"}}} + + def test_a_body_only_one_definition_holds_stays_where_it_is(self): + from oold.agent.extraction import _hoisted + + only = {"Person": {"type": "object", "properties": {"height": {"type": "object", "properties": {}}}}} + assert _hoisted(only) == only + + def test_a_definition_is_never_hoisted_into_a_reference_to_another(self): + """A class definition is an object with properties like any other, so + hoisting on shape alone leaves a ``$defs`` entry that is nothing but a + ``$ref``, which OpenAI rejects as not a valid JSON Schema.""" + from oold.agent.extraction import _hoisted + + body = {"type": "object", "properties": {"name": {"type": "string"}}} + hoisted = _hoisted({"Person": body, "Author": dict(body)}) + assert hoisted == {"Person": body, "Author": body} + + def test_two_bodies_differing_anywhere_stay_apart(self): + """The same slot pinned to different ids is a different grammar, and + sharing it would offer one entity's slot the targets of another's.""" + from oold.agent.extraction import _hoisted + + left = {"type": "object", "properties": {"of": {"enum": ["e1"]}}} + right = {"type": "object", "properties": {"of": {"enum": ["e2"]}}} + hoisted = _hoisted({ + "Person": {"type": "object", "properties": {"a": left, "b": left}}, + "Book": {"type": "object", "properties": {"a": right, "b": right}}, + }) + assert len([name for name in hoisted if name.startswith("shared")]) == 2 + + def test_a_batch_keeps_the_body_its_definitions_reach(self): + """It is referenced from inside a definition and not from a key, so + narrowing a batch by its keys alone drops it and the provider refuses + the batch for a reference to something not in the schema.""" + from oold.agent.extraction import _reachable_defs + + hoisted = self._defs() + assert _reachable_defs({"Person"}, hoisted) == {"Person", "shared1"} + + +class TestAProviderThatWillNotCompileTheBatch: + """A budget predicts the boundary and does not find it. + + The measured budget put nineteen keys one over, and the same schema with + eighteen compiled. Halving costs a wasted request and needs no model of + the provider, so it survives the catalogue or the plan moving. + """ + + class _Picky(MultiStepClient): + """Refuses any extract call carrying more than one entity.""" + + def invoke(self, messages, *, response_format=None, strict=False): + properties = (response_format or {}).get("properties") or {} + if _is_keyed(response_format) and len(properties) > 1: + raise RuntimeError("The compiled grammar is too large, which would cause performance issues.") + return super().invoke(messages, response_format=response_format, strict=strict) + + def test_the_run_still_reports_every_entity(self): + result = agent(self._Picky()).run(request()) + assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2"] + + def test_it_asked_one_entity_at_a_time(self): + client = self._Picky() + agent(client).run(request()) + assert all(len(fmt["properties"]) == 1 for fmt in client.formats if _is_keyed(fmt) and fmt) + + def test_another_failure_is_not_retried_away(self): + import pytest + + class Broken(MultiStepClient): + def invoke(self, messages, *, response_format=None, strict=False): + if _is_keyed(response_format): + raise RuntimeError("the deployment is on fire") + return super().invoke(messages, response_format=response_format, strict=strict) + + with pytest.raises(RuntimeError, match="on fire"): + agent(Broken()).run(request()) + + def test_the_refusal_is_recognised_by_what_it_says(self): + from oold.agent.extraction import _refused_to_compile + + assert _refused_to_compile(RuntimeError("Schema is too complex for compilation.")) + assert _refused_to_compile(RuntimeError("Expected at most 1000 enum values")) + assert not _refused_to_compile(RuntimeError("rate limit exceeded")) + + +class TestAHostThatRefusesByAnsweringNothing: + """Two backends signal a refused schema with HTTP 200 and no choices. + + There is no error to read, so it reaches the agent as "answered with no + choices" and reads like a dead deployment. llama-3.3-70b-instruct was + written off on that reading and answers a 600-property schema fine. + """ + + class _Silent(MultiStepClient): + def invoke(self, messages, *, response_format=None, strict=False): + properties = (response_format or {}).get("properties") or {} + if _is_keyed(response_format) and len(properties) > 1: + raise ValueError("llama-3.3-70b-instruct answered with no choices, so there is nothing to read") + return super().invoke(messages, response_format=response_format, strict=strict) + + def test_the_batch_is_split_rather_than_failed(self): + result = agent(self._Silent()).run(request()) + assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2"] + + def test_the_refusal_is_recognised(self): + from oold.agent.extraction import _refused_to_compile + + assert _refused_to_compile(ValueError("m answered with no choices, so there is nothing to read")) diff --git a/tests/test_agent/test_provider.py b/tests/test_agent/test_provider.py index 6ab0be0..173357c 100644 --- a/tests/test_agent/test_provider.py +++ b/tests/test_agent/test_provider.py @@ -1,5 +1,3 @@ - - class TestAFormatTheProviderDoesNotImplement: """Supporting `format` is not supporting its values. From 5a163d3b6544ecb9852ca86ff89161e1fb33cdf3 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Wed, 14 Oct 2026 21:05:42 +0200 Subject: [PATCH 53/58] feat(agent): say what a property taking an object holds - a property taking a reference names the entities it could reach and one taking an object named nothing, so the step chose between a described name and a bare one - the class and id slots are left out, since they are bookkeeping rather than something a document states - measured on one recipe page it did not change the choice, which is worth knowing: the step has the slot, its description, its range and now its contents, and still prefers the name that matches the document --- src/oold/agent/extraction.py | 29 +++++++++++++- src/oold/agent/prompts.py | 14 ++++++- tests/test_agent/test_multi_step.py | 61 +++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 2 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 1610270..4b6f0c5 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -1101,7 +1101,13 @@ def _ask_fillable( placed = tuple(dict.fromkeys(name for entity in plan for name in entity.classes)) narrowed = self.enforcement.with_catalogue(placed or None) if placed else self.enforcement messages = build_property_messages( - request, available, named, _reachable_by(plan, request), enforcement=narrowed, flags=self.property_flags + request, + available, + named, + _reachable_by(plan, request), + _held_by(request), + enforcement=narrowed, + flags=self.property_flags, ) constrained = self.enforcement.decode_constraint is not DecodeConstraint.NONE and self.constrain_properties response_format = prepared if constrained else None @@ -2545,6 +2551,27 @@ def _descends(name: str, admitted: set[str], lineage: dict[str, tuple[str, ...]] return False +def _held_by(request: ExtractionRequest) -> dict[str, tuple[str, ...]]: + """Per property that takes an object, what that object carries. + + The step is choosing between names, and a name alone does not say that + `supply` holds the thing needed and how much of it while + `recipeIngredient` holds a list. A property taking a reference already + says what it could reach; this is the same courtesy for one taking an + object. + """ + found: dict[str, tuple[str, ...]] = {} + for shape in _entity_shapes(request.schema): + for name, slot in (shape.get("properties") or {}).items(): + inner = slot.get("items", slot) if isinstance(slot, dict) else {} + if not isinstance(inner, dict) or not isinstance(inner.get("properties"), dict): + continue + carried = [key for key in inner["properties"] if key not in (*_CLASS_KEYS, *_ID_KEYS)] + if carried: + found.setdefault(name, tuple(carried)) + return found + + def _reachable_by(plan: tuple[PlannedEntity, ...], request: ExtractionRequest) -> dict[str, tuple[str, ...]]: """Per node-valued property, the planned entities its range admits. diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index bcd7d16..b6228c7 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -395,6 +395,7 @@ def build_property_messages( offered: Mapping[str, Sequence[str]], named: Mapping[str, str] | None = None, points_at: Mapping[str, Sequence[str]] | None = None, + holds: Mapping[str, Sequence[str]] | None = None, enforcement: Enforcement | None = None, flags: bool = False, ) -> list[Message]: @@ -405,6 +406,14 @@ def build_property_messages( answer shape, because an arm that shows no schema still has to say what the names are before it can ask which of them the document fills. + ``holds`` names, per property that takes an object, what that object + carries. A property taking a reference is annotated with the entities it + could reach and a property taking an object was annotated with nothing, + so the step chose between a described name and a bare one: offered + `supply`, which holds the thing and how much of it, beside + `recipeIngredient`, which holds a list, it took the name that reads like + the document two times in three. + ``points_at`` names, per node-valued property, the planned entities its range admits. The step otherwise chooses on the name alone and picks the one that reads like the document: a recipe page with its ingredients @@ -415,15 +424,18 @@ def build_property_messages( """ described = request.property_text or {} reach = points_at or {} + carried = holds or {} def _line(name: str) -> str: text = f" {name}: {described[name]}" if name in described else f" {name}" + if name in carried: + return f"{text} (holds an object with {', '.join(carried[name])})" if name not in reach: return text targets = ", ".join(reach[name]) return f"{text} (points at {targets})" if targets else f"{text} (points at nothing in this plan)" - if described or reach: + if described or reach or carried: # One line per property, because a comment does not fit beside a name # and the step is choosing between them rather than scanning a list. lines: list[str] = [] diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 186c635..5ce38a4 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -2084,3 +2084,64 @@ def test_the_refusal_is_recognised(self): from oold.agent.extraction import _refused_to_compile assert _refused_to_compile(ValueError("m answered with no choices, so there is nothing to read")) + + +class TestWhatAPropertyHoldsIsSaid: + """A property taking a reference says what it could reach, and one + taking an object said nothing, so the step chose between a described + name and a bare one. + """ + + SCHEMA = { + "type": "object", + "properties": { + "entities": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": {"type": "string"}, + "id": {"type": "string"}, + "name": {"type": "array", "items": {"type": "string"}}, + "supply": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": {"type": "string"}, + "type": {"type": "string"}, + "item": {"type": "string"}, + "requiredQuantity": {"type": "string"}, + }, + }, + }, + }, + }, + } + }, + } + + def _held(self): + from oold.agent.extraction import _held_by + + return _held_by(replace(request(), schema=self.SCHEMA)) + + def test_a_property_taking_an_object_names_what_it_carries(self): + assert self._held()["supply"] == ("item", "requiredQuantity") + + def test_the_class_and_id_slots_are_not_named(self): + """They are bookkeeping, not something the document states.""" + assert not {"id", "type"} & set(self._held()["supply"]) + + def test_a_property_taking_a_literal_is_not_annotated(self): + assert "name" not in self._held() + + def test_the_prompt_says_it(self): + from oold.agent.prompts import build_property_messages + + messages = build_property_messages( + replace(request(), schema=self.SCHEMA), + {"e1": ("name", "supply")}, + holds={"supply": ("item", "requiredQuantity")}, + ) + assert "supply (holds an object with item, requiredQuantity)" in messages[0].content From fac66df27d645c099221ed55e6c6bed3f9ff3d3a Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 18 Oct 2026 06:01:10 +0200 Subject: [PATCH 54/58] feat(agent): offer fillable properties per candidate class - the answer is keyed by class, so each arm gets that class's own slots - per-class attribution joins the group key, so two entities do not share arms - a bare answer broadcasts to every offered class - offers are dotted leaf paths, glossed by path and then by leaf name --- src/oold/agent/enforcement.py | 17 +- src/oold/agent/extraction.py | 526 +++++++++++++++++------ src/oold/agent/prompts.py | 183 ++++++-- tests/test_agent/test_multi_step.py | 626 +++++++++++++++++++++++----- 4 files changed, 1085 insertions(+), 267 deletions(-) diff --git a/src/oold/agent/enforcement.py b/src/oold/agent/enforcement.py index 0de1c4e..de77243 100644 --- a/src/oold/agent/enforcement.py +++ b/src/oold/agent/enforcement.py @@ -101,7 +101,18 @@ class OutputForm(str, Enum): JSON = "json" -_PROPERTY_LINE = re.compile(r"^ {2}([A-Za-z_][A-Za-z0-9_]*) \(") +_HEADERS = frozenset({"extends", "reached by"}) +"""Lines at the property indent that say what the class is, not what it has.""" + +_PROPERTY_LINE = re.compile(r"^ {2}([A-Za-z_][A-Za-z0-9_]*)(?: \(|: )") +"""A property line in a rendered entry, glossed or bare. + +Written for the bare form alone, a line carrying its description went +unmatched, and an unmatched line at this indent ends the block being dropped, +so the property was kept. The entry then advertised properties the call's +grammar no longer had, which is the disagreement this narrowing exists to +prevent. +""" def _entry_limited_to(entry: str, keep: set[str]) -> str: @@ -116,9 +127,9 @@ def _entry_limited_to(entry: str, keep: set[str]) -> str: dropping = False for line in entry.splitlines(): found = _PROPERTY_LINE.match(line) - if found is not None: + if found is not None and found.group(1) not in _HEADERS: dropping = found.group(1) not in keep - elif not line.startswith(" "): + elif not line.startswith(" ") and (found is None or found.group(1) in _HEADERS): dropping = False if not dropping: lines.append(line) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 4b6f0c5..1ee1fc6 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -16,6 +16,7 @@ import copy import json import re +import sys from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field, replace @@ -43,7 +44,20 @@ _FENCE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.MULTILINE) -_Group = tuple[tuple[str, ...], tuple[str, ...], tuple[str, ...], tuple[tuple[str, tuple[str, ...]], ...]] +_Group = tuple[ + tuple[str, ...], + tuple[str, ...], + tuple[str, ...], + tuple[tuple[str, tuple[str, ...]], ...], + tuple[tuple[str, tuple[str, ...]], ...], +] +"""What makes two entities answerable by one call. + +The shortlist, what the call fills, what an absorbed entity brings, what was +chosen inside an embedded object, and which class each property was chosen +for. The last is there because a call sends one grammar: two entities that +chose the same properties for different classes need different branches. +""" """What makes one extract call: a shortlist, the properties the step chose, the ones an absorbed entity brings, and what it chose inside each embedded object. Entities sharing a call share the schema it is sent, so two that @@ -238,6 +252,14 @@ def __init__( a caller that supplies nothing gets that behaviour by default. See :meth:`_ask_for`.""" self.asked: list[dict[str, str]] = [] + self.fillable_answer: dict[str, dict[str, list[Any]]] = {} + """What the property step answered, per entity and per class. + + The working behind :attr:`ExtractionResult.properties_chosen`, which + reports the union. Declared here because a caller reads it after a + run and an attribute that only exists once a step has run is one a + caller has to guess at.""" + self._chosen_per_class: dict[str, dict[str, tuple[str, ...]]] = {} self.properties_invented: dict[str, tuple[str, ...]] = {} """Every escalation, in order, whether or not it was answered.""" self.supplied: dict[str, dict[str, Any]] = {} @@ -758,25 +780,34 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: ) available = self._available_properties(request, placed) - embedded = self._inside_properties(request, placed, available) - answered = self._choose_properties( - request, - log, - placed, - {**available, **{_inside_key(key, slot): names for (key, slot), names in embedded.items()}}, + answered = _with_implied_links( + self._choose_properties(request, log, placed, available), available, request, placed ) - chosen = {key: names for key, names in answered.items() if key in available} - # The step's answer about an embedded object, resolved back to the - # entity holding it and the slot it stands in. The key it was asked - # under does not survive this line. + # A leaf path says what the document states and which slots hold it, + # so the two are read off one answer: the slot a path starts at is + # chosen, and what the object in it carries is the rest of the path. + # The step answered per class; what the call fills is the union, and + # which class may carry which is kept beside it. A branch asked for a + # property its class does not have is the defect this split is for, + # and the grouping is about what one call fills together. + # Part of the group key below, so a group is entities that chose the + # same properties for the same classes. + self._chosen_per_class = { + key: { + cls: tuple(dict.fromkeys(path.split(".", 1)[0] for path in paths)) for cls, paths in per_class.items() + } + for key, per_class in answered.items() + } + chosen: dict[str, tuple[str, ...]] = {} within: dict[str, dict[str, tuple[str, ...]]] = {} - for key, slot in embedded: - picked = answered.get(_inside_key(key, slot), ()) - if picked: - within.setdefault(key, {})[slot] = picked - # A name invented for an embedded object is filed under the entity - # holding it, so the record this reports stays keyed by the plan. - self.properties_invented = _by_holder(self.properties_invented, available) + for key, per_class in answered.items(): + paths = tuple(dict.fromkeys(name for names in per_class.values() for name in names)) + chosen[key] = tuple(dict.fromkeys(path.split(".", 1)[0] for path in paths)) + for path in paths: + slot, _, rest = path.partition(".") + if rest: + held = within.setdefault(key, {}).setdefault(slot, ()) + within[key][slot] = (*held, rest) filling, named = self._filling(placed, available, chosen) absorbed = _absorbed_by(request.schema, placed, chosen, request.ranges, request.parents) inside = _inside(absorbed, filling) @@ -798,6 +829,14 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: filling.get(entity.key, ()), inside.get(entity.key, ()), tuple(sorted(within.get(entity.key, {}).items())), + # Which class the step chose each property for, not only + # which were chosen. Left out, two entities with the same + # shortlist and the same union shared one pair of branches + # built from whichever was first: an entity that said "as a + # Book the document states its name" was sent a grammar + # requiring `name` on the Person arm, which is the steering + # the per-class answer exists to remove. + tuple(sorted((self._chosen_per_class.get(entity.key) or {}).items())), ) groups.setdefault(key, []).append(entity.key) @@ -808,7 +847,7 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: unpinned: list[str] = [] last: ExtractionResult | None = None holding = _holding_objects(request) - for (classes, kept, held, chose), keys in groups.items(): + for (classes, kept, held, chose, _per_class), keys in groups.items(): wanted = self._ask_for(keys, frozenset(required).difference(kept)) keep = set(kept) | set(held) | required.intersection(wanted) narrowing = _within(chose, held, holding) @@ -846,7 +885,16 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: last.calls = log last.selected = selected last.mentions = dict(self._mentions) - last.properties_chosen = chosen + # Flat, whichever step produced it. What the step chose is a fair + # question of a run however many classes it answered for, and the + # per-class working is kept on `fillable_answer` for a caller that + # wants it. + last.properties_chosen = { + key: tuple(dict.fromkeys(name for names in value.values() for name in names)) + if isinstance(value, dict) + else value + for key, value in chosen.items() + } last.properties_invented = dict(self.properties_invented) last.named = named last.absorbed = absorbed @@ -858,7 +906,7 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: def _filling( self, placed: tuple[PlannedEntity, ...], - available: dict[str, tuple[str, ...]], + available: dict[str, dict[str, tuple[str, ...]]], chosen: dict[str, tuple[str, ...]], ) -> tuple[dict[str, tuple[str, ...]], list[str]]: """The properties each extract call asks for, and who kept a name. @@ -887,7 +935,14 @@ def _filling( filling: dict[str, tuple[str, ...]] = {} named: list[str] = [] for entity in placed: - offered = available.get(entity.key, ()) + # The slots the offered paths start at. What a call fills is a + # slot of the entity, where what the step was asked is a leaf + # inside one, so the two are not the same list of names. + offered = tuple( + dict.fromkeys( + path.split(".", 1)[0] for names in (available.get(entity.key) or {}).values() for path in names + ) + ) keep = set(chosen.get(entity.key, ())) if self._mentions.get(entity.key) and _NAME_KEY in offered and _NAME_KEY not in keep: keep.add(_NAME_KEY) @@ -899,13 +954,16 @@ def _available_properties( self, request: ExtractionRequest, plan: tuple[PlannedEntity, ...], - ) -> dict[str, tuple[str, ...]]: - """What each planned entity may carry, before the document is read. + ) -> dict[str, dict[str, tuple[str, ...]]]: + """What each planned entity may carry, per class it could be. - The union over the entity's shortlist, for the reason - :func:`_compatible_ids` takes the union: the extract step has not - committed to one class yet, and offering only the first class's - properties would rule out a value the second call may well state. + Per class and not pooled over the shortlist. Pooled, a property one + candidate declares was offered to an entity the step then answered as + the other, and choosing it carried no commitment to the class that + has it: a material offered `size` alongside a substance's properties + was typed a product by the only branch that could hold what had been + asked for. Measured over 150 entities, the pipeline's class was right + less often than taking the first candidate unread. Intersected with the answer shape and in its order, so the step can only name a slot the extract call actually has. A corpus that declares @@ -916,52 +974,23 @@ def _available_properties( if not offered: return {} lineage = {name: tuple(values) for name, values in (request.parents or {}).items()} - available: dict[str, tuple[str, ...]] = {} + available: dict[str, dict[str, tuple[str, ...]]] = {} for entity in plan: - admitted = _admitted_properties(entity.classes, request.branches, lineage) - names = tuple(name for name in offered if not admitted or name in admitted) - if names: - available[entity.key] = names + held: dict[str, tuple[str, ...]] = {} + for cls in entity.classes: + admitted = _admitted_properties((cls,), request.branches, lineage) + slots = _declared_slots(request.schema, request.branches, (cls,), lineage) + names: list[str] = [] + for name in offered: + if admitted and name not in admitted: + continue + names.extend(_paths_within(slots.get(name), name) or (name,)) + if names: + held[cls] = tuple(dict.fromkeys(names)) + if held: + available[entity.key] = held return available - def _inside_properties( - self, - request: ExtractionRequest, - plan: tuple[PlannedEntity, ...], - available: dict[str, tuple[str, ...]], - ) -> dict[tuple[str, str], tuple[str, ...]]: - """What the object standing in an embedded slot may carry. - - The property step runs over planned entities, and an object written - inside one is not planned, so nothing ever chose its slots and the - extract call asked for every slot the class it holds declares. A - recipe's yield arrived as a quantity carrying a maximum, a minimum, a - unit code and a unit text that no step had named, repeated in every - class definition able to hold one. - - So the object is asked about as if it were an entity, which is the - device and not a change of status: the key is made here, lasts for - this one step, is never offered to the step that chooses classes, and - nothing answers under it in the extract call, where the object stays - written inside the entity holding it. - - Keyed by the entity and the slot together. Two entities may hold the - same class in the same slot and still state different things about it, - and one entity may hold a different class in each of two slots. - """ - lineage = {name: tuple(values) for name, values in (request.parents or {}).items()} - found: dict[tuple[str, str], tuple[str, ...]] = {} - for entity in plan: - offered = available.get(entity.key) - if not offered: - continue - slots = _declared_slots(request.schema, request.branches, entity.classes, lineage) - for name in offered: - inner = _inner_properties(slots.get(name)) - if inner: - found[(entity.key, name)] = inner - return found - def _ask_for(self, keys: list[str], missing: frozenset[str]) -> set[str]: """Resolve a required property the document does not fill. @@ -1036,26 +1065,32 @@ class ask the same question, so a call per class is a call per if not available: return {} planned = {entity.key for entity in plan} - grouped: dict[tuple[str, ...], dict[str, tuple[str, ...]]] = {} - for key, names in available.items(): + # Grouped on the whole per-class offer, so two entities share a call + # only where every class they could be offers the same thing. + grouped: dict[tuple[tuple[str, tuple[str, ...]], ...], dict[str, dict[str, tuple[str, ...]]]] = {} + for key, per_class in available.items(): if key in planned: - grouped.setdefault(tuple(names), {})[key] = names - batches = [part for names, subset in grouped.items() for part in _batched(subset, self._per_call(names))] + grouped.setdefault(tuple((cls, tuple(names)) for cls, names in per_class.items()), {})[key] = per_class + batches = [ + part + for shape, subset in grouped.items() + for part in _batched(subset, self._per_call(tuple(name for _, names in shape for name in names))) + ] batches += _packed( - {key: names for key, names in available.items() if key not in planned}, + {key: per_class for key, per_class in available.items() if key not in planned}, self.profile.max_enumerated_slots, ) if len(batches) == 1: return self._ask_fillable(request, log, plan, available) - chosen: dict[str, tuple[str, ...]] = {} - answered: dict[str, list[Any]] = {} + chosen: dict[str, dict[str, tuple[str, ...]]] = {} + answered: dict[str, dict[str, list[Any]]] = {} with ThreadPoolExecutor(max_workers=min(len(batches), 8)) as pool: running = [pool.submit(self._ask_fillable, request, log, plan, subset) for subset in batches] for finished in running: chosen.update(finished.result()) answered.update(self.fillable_answer or {}) self.fillable_answer = answered - return {key: chosen.get(key, ()) for key in available} + return {key: chosen.get(key, {}) for key in available} def _per_call(self, names: tuple[str, ...]) -> int: """How many entities offering these names fit in one request. @@ -1067,7 +1102,12 @@ def _per_call(self, names: tuple[str, ...]) -> int: """ budget = self.profile.max_enumerated_slots if budget is None or not names: - return len(names) or 1 + # No budget is no reason to split. Returning the name count put a + # count of properties where a count of entities goes, so twenty + # entities offering four properties each went four to a call and + # cost five round trips carrying the same catalogue to collect + # twenty answers of one word. + return sys.maxsize return max(1, budget // len(names)) def _ask_fillable( @@ -1075,8 +1115,8 @@ def _ask_fillable( request: ExtractionRequest, log: CallLog, plan: tuple[PlannedEntity, ...], - available: dict[str, tuple[str, ...]], - ) -> dict[str, tuple[str, ...]]: + available: dict[str, dict[str, tuple[str, ...]]], + ) -> dict[str, dict[str, tuple[str, ...]]]: """One fillable call, over the entities sharing a property set.""" schema = property_schema(available, evidence=request.property_evidence, flags=self.property_flags) # Definitions prepared on their own, wrapper assembled after, for the @@ -1095,17 +1135,23 @@ def _ask_fillable( holder, mark, slot = key.partition(_INSIDE_MARK) if key not in named and mark and holder in named: named[key] = f"the object written into {slot} of {named[holder]}" - # The classes the plan settled on and no others. The step is choosing - # between one class's properties, so the rest of the catalogue - # describes classes nothing on the plan can be. - placed = tuple(dict.fromkeys(name for entity in plan for name in entity.classes)) + # The classes this call's own entities were placed in and no others. + # The step is choosing between one class's properties, so the rest of + # the catalogue describes classes nothing it is being asked about can + # be. Scoped to the plan rather than to the call, every batch carried + # every class on the plan: one call paid twelve thousand characters of + # catalogue to print seventy-nine characters of offers for twenty-four + # entities that are all Thing, and the block was byte-identical across + # the lot. The plan stays whole for the readings, where the targets a + # link admits are the plan's and not this call's. + asked = tuple(entity for entity in plan if entity.key in available) or plan + placed = tuple(dict.fromkeys(name for entity in asked for name in entity.classes)) narrowed = self.enforcement.with_catalogue(placed or None) if placed else self.enforcement messages = build_property_messages( request, available, named, - _reachable_by(plan, request), - _held_by(request), + _readings(request, plan, available), enforcement=narrowed, flags=self.property_flags, ) @@ -1120,13 +1166,18 @@ def _ask_fillable( # Kept so a caller can read what the step thought it was reading. The # answer is the names; this is the working behind them. self.fillable_answer = answered - for key, names in available.items(): - loose = _named_in(answered.get(key) or ()) - set(names) + for key, per_class in available.items(): + held = answered.get(key) or {} + offered = {name for names in per_class.values() for name in names} + loose = {name for stated in held.values() for name in _named_in(stated)} - offered if loose: self.properties_invented[key] = tuple(sorted(loose)) return { - key: tuple(name for name in names if name in _named_in(answered.get(key) or ())) - for key, names in available.items() + key: { + cls: tuple(name for name in names if name in _named_in((answered.get(key) or {}).get(cls) or ())) + for cls, names in per_class.items() + } + for key, per_class in available.items() } def _keyed_extract( @@ -1163,13 +1214,14 @@ class the value takes. seconds. """ required = _required_properties(request.schema) + lineage = {name: tuple(values) for name, values in (request.parents or {}).items()} asked: dict[str, tuple[str, ...]] = {} defs: dict[str, dict[str, Any]] = {} properties: dict[str, Any] = {} placed: list[str] = [] shown: set[str] = set() holding = _holding_objects(request) - for (classes, kept, held, chose), keys in groups.items(): + for (classes, kept, held, chose, _per_class), keys in groups.items(): # The properties the schema requires and the step did not choose, # which a caller may be able to supply where the document cannot. wanted = self._ask_for(keys, frozenset(required).difference(kept)) @@ -1192,22 +1244,61 @@ class the value takes. # provider in any case, so carrying it costs the grammar and buys # a discrimination the answer could not express. offered = classes if self.profile.supports_any_of else classes[:1] + carried: list[str] = [] for name in offered: + # What this class declares, and not what the union was asked + # for. Merged, a property chosen against one candidate landed + # on every candidate: a material was offered `Substance` or + # `Product`, `size` was chosen, and the grammar then required + # `size` on `Substance`, which declares no such thing. The + # same prompt printed the class with no properties above and + # a schema demanding one below, and the model read the schema. + admitted = _admitted_properties((name,), request.branches, lineage) + # What the step chose for this class, where it answered per + # class. A property chosen against one candidate is not asked + # of the other: that is what made a material answer as a + # product, because the only branch carrying what the prose + # demanded was the one that declares it. + per_class = self._chosen_per_class.get(keys[0]) or {} + # A name the step chose for this class, or one the pipeline + # added for every class: a mention kept as `name` and a + # property the schema requires belong on each arm, where a + # property chosen against one candidate belongs only on it. + added = set(kept) - {held for names in per_class.values() for held in names} + mine = [k for k in kept if k in set(per_class.get(name, ())) | added] if per_class else None + held = {**(base.get("properties") or {}), **(branches.get(name) or {})} slots = { key: value - for key, value in {**(base.get("properties") or {}), **(branches.get(name) or {})}.items() + for key, value in held.items() if key not in _ID_KEYS + and key not in _CLASS_KEYS + # The schema's own demands survive the class filter: a + # property the answer shape requires is asked of every + # arm, whatever the catalogue says the class declares. + and (not admitted or key in admitted or key in required) } - slots = {key: value for key, value in slots.items() if key not in _CLASS_KEYS} identifier = f"{name}__{len(defs)}" if name in defs else name defs[identifier] = { "type": "object", "additionalProperties": False, "properties": {_CLASS_KEYS[0]: {"type": "string", "const": name}, **slots}, - "required": list(dict.fromkeys([_CLASS_KEYS[0], *(k for k in kept if k in slots)])), + "required": list( + dict.fromkeys([ + _CLASS_KEYS[0], + *(k for k in (mine if mine is not None else kept) if k in slots), + ]) + ), } arms.append({"$ref": f"#/$defs/{identifier}"}) - wrote = tuple(name for name in defs[identifier]["required"] if name not in _CLASS_KEYS) + carried += [key for key in defs[identifier]["required"] if key not in _CLASS_KEYS] + # Across the arms and not off the last one. Once each class was + # bound to what it declares, the arms stopped carrying the same + # properties, and the words quoted whichever was built last: the + # prose asked for `name` while the other branch required six, + # and the one way to obey both was to answer as the narrower + # class. A package was reported as a material and what it held + # was lost with the branch. + wrote = tuple(dict.fromkeys(carried)) for key in keys: properties[key] = arms[0] if len(arms) == 1 else {"anyOf": list(arms)} asked[key] = wrote @@ -1241,7 +1332,15 @@ class the value takes. # After the preparation and not before it, because `prepare` inlines # every `$ref` for a provider that cannot express `allOf` and would # put back what this just took out. - schema["$defs"] = _hoisted(schema["$defs"]) + # Hoisting is off. Sharing a repeated body took a third off the + # largest call, and a body shared across definitions is narrowed for + # whichever group reached it first, so another group sees a shape it + # did not choose. OpenAI refuses the result as invalid without saying + # where, and it could not be reproduced from the parts: a reference + # under an array, a reference reached through another reference and + # the body on its own all compile. Measure it again behind + # per-group bodies rather than per-schema ones. + # schema["$defs"] = _hoisted(schema["$defs"]) # Sized the way the property step is, and for the same budget: the # compiler charges for keys times the slots each one reaches, and a # link slot pinned to nineteen ids is nineteen of them. Nineteen keys @@ -1981,9 +2080,9 @@ def _shape_properties(schema: Any) -> tuple[str, ...]: The objects written inside a shape are read too, because a schema may declare a class's slots only there: an address written inside a person is the one place ``streetAddress`` appears, and a planned address the step - could not be asked about is one the fill step has nothing to ask for. What - those names mean inside the object is a separate question, asked under the - slot that holds it: see :meth:`ExtractionAgent._inside_properties`. + could not be asked about is one the fill step has nothing to ask for. A name + inside an object is offered as a dotted path, so what it means is settled + by where it sits rather than asked separately. """ names: list[str] = [] for shape in _entity_shapes(schema): @@ -2007,6 +2106,31 @@ def _inner_properties(slot: Any) -> tuple[str, ...]: return tuple(names) +def _paths_within(slot: Any, under: str = "") -> tuple[str, ...]: + """Every leaf this slot reaches, written as a dotted path. + + A slot holding an object is not a thing a document states; what it holds + is. Offering the holder leaves the step choosing a container and a second + round asking what went in it, and that round asked about every object the + class could hold rather than the ones anything chose. A leaf path says + both at once: choosing `supply.item` says the document names the thing + supplied, and that a supply is therefore stated. + """ + inner = _inner_properties(slot) + if not inner: + return (under,) if under else () + found: list[str] = [] + for shape in _entity_shapes(slot, descend=False): + for name, body in (shape.get("properties") or {}).items(): + if name in _CLASS_KEYS or name in _ID_KEYS: + continue + path = f"{under}.{name}" if under else name + for leaf in _paths_within(body, path) or (path,): + if leaf not in found: + found.append(leaf) + return tuple(found) + + def _lineage_first(classes: tuple[str, ...], lineage: dict[str, tuple[str, ...]]) -> list[str]: """These classes and everything they inherit from, ancestors first. @@ -2153,16 +2277,52 @@ def _narrow_embedded(slot: Any, keep: set[str]) -> None: The class slot survives whatever is kept, because it is what the embedded object's class is graded against and no step was ever asked about it. + + ``keep`` holds what to keep under this slot, as paths: `item` and + `requiredQuantity.value`. One flat set matched against every depth kept + nothing at either: the slot is named `requiredQuantity` and the set holds + `requiredQuantity.value`, so the quantity was dropped from the shape + although the step had asked for it, and a recipe told to record how much + of an ingredient it needs was sent a supply with nowhere to put it. Each + level is matched against the segment belonging to it and re-based for the + one below. """ - for shape in _entity_shapes(slot): + here = {path.split(".", 1)[0] for path in keep} + below: dict[str, set[str]] = {} + for path in keep: + head, _, rest = path.partition(".") + if rest: + below.setdefault(head, set()).add(rest) + for shape in _objects_at(slot): properties = shape.get("properties") or {} shape["properties"] = { - name: definition + name: (_narrowed_slot(definition, below[name]) if name in below else definition) for name, definition in properties.items() - if name in keep or name in _CLASS_KEYS or name in _ID_KEYS + if name in here or name in _CLASS_KEYS or name in _ID_KEYS } - already = shape.get("required") or [] - shape["required"] = list(dict.fromkeys([*already, *(name for name in shape["properties"] if name in keep)])) + + +def _objects_at(slot: Any) -> list[dict[str, Any]]: + """Every object this slot writes, through arrays and unions, one level. + + Not :func:`_entity_shapes`, which reads an object as an entity and so + passes over one with no class slot: a `QuantitativeValue` written inside + a supply carries a value and a unit and nothing that names a class, and + narrowing has to reach it all the same. + """ + if isinstance(slot, list): + return [found for item in slot for found in _objects_at(item)] + if not isinstance(slot, dict): + return [] + if isinstance(slot.get("properties"), dict): + return [slot] + return [found for key in ("items", "anyOf", "oneOf") if key in slot for found in _objects_at(slot[key])] + # Nothing kept here is made required. Whether a document states a + # property of an object is a claim about one of them, and the objects + # do not exist until the answer does: a page giving a quantity for one + # ingredient and not the next would have to invent the second. Both + # subsets leave a per-object way out, null where every property is + # made required and absence where they are not. def _narrowed_slot(definition: Any, keep: set[str]) -> Any: @@ -2207,9 +2367,23 @@ def _trim_branches( } -def _fillable_of(payload: Any, available: dict[str, tuple[str, ...]]) -> dict[str, list[Any]]: +def _per_class(value: Any, offered: dict[str, tuple[str, ...]]) -> dict[str, list[Any]]: + """One entity's answer, read as a list per class it could be.""" + if isinstance(value, dict) and any(cls in value for cls in offered): + return {cls: _stated_properties(value.get(cls)) for cls in offered} + stated = _stated_properties(value) + return dict.fromkeys(offered, stated) + + +def _fillable_of(payload: Any, available: dict[str, dict[str, tuple[str, ...]]]) -> dict[str, dict[str, list[Any]]]: """The property lists in an answer, whatever the model called the wrapper. + One list per class the entity could be. An answer that gives a bare list + under the entity, which is what a model asked the old way returns, is read + as that list for every class it was offered: the step said what the + document fills and did not say which class it meant, and reading it as + nothing would lose an answer that is merely in the previous shape. + The declared wrapper first, then a lone key holding an object, then the answer itself. The same allowance :func:`_entities_of` makes, and for the same observation: giving a schema a title stopped one provider rejecting it @@ -2228,7 +2402,7 @@ def _fillable_of(payload: Any, available: dict[str, tuple[str, ...]]) -> dict[st candidates.append(payload) for candidate in candidates: found = { - key: _stated_properties(value) + key: _per_class(value, available[key]) for key, value in candidate.items() if key in available and isinstance(value, (list, dict)) } @@ -2551,27 +2725,131 @@ def _descends(name: str, admitted: set[str], lineage: dict[str, tuple[str, ...]] return False -def _held_by(request: ExtractionRequest) -> dict[str, tuple[str, ...]]: - """Per property that takes an object, what that object carries. +def _with_implied_links( + answered: dict[str, dict[str, tuple[str, ...]]], + available: dict[str, dict[str, tuple[str, ...]]], + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], +) -> dict[str, dict[str, tuple[str, ...]]]: + """An object's links come with anything chosen inside it. + + A reified relation says nothing without the end it is about. Asked which + properties a recipe states, the step chose `supply.requiredQuantity.value` + and `supply.requiredQuantity.unitText` and not `supply.item`: how much, + with no word for what. The fill schema was then narrowed to exactly that, + so the slot that could have carried the pairing was not in the grammar, + and the step that had the pairing wrote it into whichever string slot was + left, moving to the next one each time one was taken away. 72 of 120 + supplies over thirty documents, with 68 keys found in a name or a url. + + So it is settled here rather than asked. Every prefix of a chosen path + names an object it was chosen inside, and a link that object declares is + added, provided the plan holds something its range admits: a link that + reaches nothing on this page is not what the amount is about either. + """ + reach = _reachable_by(plan, request) + found: dict[str, dict[str, tuple[str, ...]]] = {} + for key, per_class in answered.items(): + held_classes: dict[str, tuple[str, ...]] = {} + for cls, paths in per_class.items(): + held = list(paths) + offered = (available.get(key) or {}).get(cls, ()) + for under in {prefix for path in paths for prefix in _prefixes(path)}: + for other in offered: + if not other.startswith(f"{under}.") or "." in other[len(under) + 1 :]: + continue + if reach.get(other.rsplit(".", 1)[-1]) and other not in held: + held.append(other) + held_classes[cls] = tuple(held) + found[key] = held_classes + return found + + +def _prefixes(path: str) -> tuple[str, ...]: + """Every object a dotted path was chosen inside, outermost first.""" + parts = path.split(".")[:-1] + return tuple(".".join(parts[: n + 1]) for n in range(len(parts))) + - The step is choosing between names, and a name alone does not say that - `supply` holds the thing needed and how much of it while - `recipeIngredient` holds a list. A property taking a reference already - says what it could reach; this is the same courtesy for one taking an - object. +def _readings( + request: ExtractionRequest, + plan: tuple[PlannedEntity, ...], + available: dict[str, dict[str, tuple[str, ...]]], +) -> dict[str, dict[str, str]]: + """Per planned entity, how each path it is offered reads. + + Every path gets one. A path was given the entities it could reach only + where the map happened to be keyed by its name, so `material` advertised + twenty-one ingredients and `supply.item`, which reaches the same twenty + one, advertised nothing. Inside is not a lesser place for a property to + be, and neither is further along a path. + + Per entity, because the same name is not the same declaration for two of + them. A recipe's `recipeInstructions` holds a list with an order and an + element, and elsewhere in the same schema the name takes a string; read + from one table built over the whole plan, whichever entity was walked + last decided how it read for all of them, and the list was described as + a string to the entity that had the list. """ - found: dict[str, tuple[str, ...]] = {} - for shape in _entity_shapes(request.schema): - for name, slot in (shape.get("properties") or {}).items(): - inner = slot.get("items", slot) if isinstance(slot, dict) else {} - if not isinstance(inner, dict) or not isinstance(inner.get("properties"), dict): - continue - carried = [key for key in inner["properties"] if key not in (*_CLASS_KEYS, *_ID_KEYS)] - if carried: - found.setdefault(name, tuple(carried)) + reach = _reachable_by(plan, request) + lineage = {name: tuple(values) for name, values in (request.parents or {}).items()} + found: dict[str, dict[str, str]] = {} + for entity in plan: + paths = tuple(dict.fromkeys(name for names in (available.get(entity.key) or {}).values() for name in names)) + if not paths: + continue + slots = _declared_slots(request.schema, request.branches, entity.classes, lineage) + found[entity.key] = {path: _reads_as(_slot_at(slots, path), path.rsplit(".", 1)[-1], reach) for path in paths} return found +def _slot_at(slots: dict[str, Any], path: str) -> Any: + """The declaration a dotted path arrives at, or None. + + Walked the way :func:`_paths_within` builds the path, through every branch + of a union rather than through one object. An object a slot takes may be + declared as a choice between classes, and reading only the first arm's + properties made the walk end early: 326 of 6,292 offered paths arrived + with no declaration and so were described as taking a `value`, among them + `recipeInstructions.itemListOrder`, which declares an enum of three. + """ + here: Any = slots.get(path.split(".", 1)[0]) + for step in path.split(".")[1:]: + found = None + for shape in _entity_shapes(here, descend=False): + found = (shape.get("properties") or {}).get(step) + if found is not None: + break + if found is None: + return None + here = found + return here + + +def _object_within(slot: Any) -> dict[str, Any] | None: + """The object a slot holds, through an array wrapper, or None.""" + if not isinstance(slot, dict): + return None + inner = slot.get("items", slot) + return inner if isinstance(inner, dict) and isinstance(inner.get("properties"), dict) else None + + +def _reads_as(body: Any, name: str, reach: dict[str, tuple[str, ...]]) -> str: + """How one property of an embedded object should be read.""" + held = _object_within(body) + if held is not None: + carried = [key for key in held["properties"] if key not in (*_CLASS_KEYS, *_ID_KEYS)] + return f"holds an object with {', '.join(carried)}" if carried else "holds an object" + if name in reach: + targets = ", ".join(reach[name]) + return f"points at {targets}" if targets else "points at nothing in this plan" + inner = body.get("items", body) if isinstance(body, dict) else {} + kind = inner.get("type") if isinstance(inner, dict) else None + if isinstance(kind, list): + kind = next((one for one in kind if one != "null"), None) + return str(kind or "value") + + def _reachable_by(plan: tuple[PlannedEntity, ...], request: ExtractionRequest) -> dict[str, tuple[str, ...]]: """Per node-valued property, the planned entities its range admits. diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index b6228c7..17e37e8 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -13,6 +13,8 @@ from __future__ import annotations import json +import os +import re from collections.abc import Mapping, Sequence from dataclasses import dataclass from typing import Any @@ -101,7 +103,10 @@ "value itself appears in the text, in some spelling of it. Answer only " "from what the text in front of you says, never from what you know about " "the subject. A property the document makes likely, or that the entity " - "would usually have, or that you could fill from memory, is not stated." + "would usually have, or that you could fill from memory, is not stated. " + "An entity is listed among the targets of its own properties because the " + "targets are read off the range; it is not one. No property points an " + "entity at itself." ) """The rule the corpus actually applies, said out loud. @@ -282,8 +287,20 @@ def selection_schema(catalogue: tuple[str, ...], k: int) -> dict[str, Any]: } +def as_per_class(offered: Mapping[str, Any]) -> dict[str, dict[str, Sequence[str]]]: + """An offer read as a list per class, whatever shape the caller holds. + + The step asks per class, because a property belongs to one and choosing + it settles which class the entity is. A caller with nothing to say about + classes gives a bare list and means "these, whatever it turns out to be": + read as one unnamed class rather than refused, the way the answer side + reads a bare list as the same list for every class it offered. + """ + return {key: dict(value) if isinstance(value, Mapping) else {"": list(value)} for key, value in offered.items()} + + def property_schema( - offered: Mapping[str, Sequence[str]], evidence: bool = False, flags: bool = False + offered: Mapping[str, Mapping[str, Sequence[str]]], evidence: bool = False, flags: bool = False ) -> dict[str, Any]: """The answer shape the property step asks for. @@ -306,7 +323,10 @@ def property_schema( """ if not offered: raise ValueError("the property step needs at least one entity with properties, or there is nothing to ask") - empty = [key for key, names in offered.items() if not names] + offered = as_per_class(offered) + empty = [ + f"{key} as {cls}" for key, per_class in offered.items() for cls, names in per_class.items() if not names + ] + [key for key, per_class in offered.items() if not per_class] if empty: raise ValueError(f"no property is available for {', '.join(empty)}, so the enumeration would admit nothing") # One enumeration per distinct property set, shared by every entity that @@ -316,13 +336,33 @@ def property_schema( # Anthropic refused as too complex, where four shared ones compile. shapes: dict[tuple[str, ...], str] = {} defs: dict[str, Any] = {} - for names in offered.values(): - shape = tuple(names) - if shape in shapes: - continue - identifier = f"properties{len(shapes) + 1}" - shapes[shape] = identifier - defs[identifier] = _property_set(list(shape), evidence, flags) + for per_class in offered.values(): + for names in per_class.values(): + shape = tuple(names) + if shape in shapes: + continue + identifier = f"properties{len(shapes) + 1}" + shapes[shape] = identifier + defs[identifier] = _property_set(list(shape), evidence, flags) + + def _per_entity(per_class: Mapping[str, Sequence[str]]) -> dict[str, Any]: + """One entity's answer: a list per class it could be. + + Not one list over the shortlist pooled. A property one candidate + declares, chosen against an entity answered as the other, committed + the extract call to a class nothing had asked for. + """ + if list(per_class) == [""]: + # One unnamed class: the caller said nothing about classes, so + # the answer is the list it would have given before. + return {"$ref": f"#/$defs/{shapes[tuple(per_class[''])]}"} + return { + "type": "object", + "properties": {cls: {"$ref": f"#/$defs/{shapes[tuple(names)]}"} for cls, names in per_class.items()}, + "required": list(per_class), + "additionalProperties": False, + } + return { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "FillableProperties", @@ -332,7 +372,7 @@ def property_schema( "properties": { "fillable": { "type": "object", - "properties": {key: {"$ref": f"#/$defs/{shapes[tuple(names)]}"} for key, names in offered.items()}, + "properties": {key: _per_entity(per_class) for key, per_class in offered.items()}, "required": list(offered), "additionalProperties": False, } @@ -390,12 +430,43 @@ def _property_item(names: list[str], evidence: bool) -> dict[str, Any]: } +_BARE = bool(os.environ.get("OOLD_BARE_OFFER")) +"""Whether the offer carries only names and readings, the catalogue being +the place a property is defined. A measurement switch: the offer is 80 per +cent of the fillable message and most of it is description the entry above +already carries.""" + +_BUDGET = 320 +"""How much of a description an offer line may carry. + +A budget and not a sentence count. Cut at the first sentence, a vocabulary +that states its own meaning first and a profile's refinement second loses the +refinement, which is the half that tells one property from another: `supply` +arrived as "A sub-property of instrument." Cut at nothing, schema.org's entry +for `value` spends four hundred characters on Unicode digits, once per path, +on hundreds of paths. +""" + + +def _gloss(text: str | None) -> str: + """What a property is, from whatever the corpus holds, within the budget.""" + if not text: + return "" + flat = text.replace("\\n", " ").replace("\n", " ") + held = " ".join(re.sub(r"\[\[([^\]]+)\]\]", lambda found: found.group(1), flat).split()) + kept: list[str] = [] + for sentence in re.split(r"(?<=[.!?])\s", held): + if kept and sum(len(one) + 1 for one in kept) + len(sentence) > _BUDGET: + break + kept.append(sentence) + return " ".join(kept) + + def build_property_messages( request: ExtractionRequest, - offered: Mapping[str, Sequence[str]], + offered: Mapping[str, Mapping[str, Sequence[str]]], named: Mapping[str, str] | None = None, - points_at: Mapping[str, Sequence[str]] | None = None, - holds: Mapping[str, Sequence[str]] | None = None, + readings: Mapping[str, Mapping[str, str]] | None = None, enforcement: Enforcement | None = None, flags: bool = False, ) -> list[Message]: @@ -406,45 +477,65 @@ def build_property_messages( answer shape, because an arm that shows no schema still has to say what the names are before it can ask which of them the document fills. - ``holds`` names, per property that takes an object, what that object - carries. A property taking a reference is annotated with the entities it - could reach and a property taking an object was annotated with nothing, - so the step chose between a described name and a bare one: offered - `supply`, which holds the thing and how much of it, beside - `recipeIngredient`, which holds a list, it took the name that reads like - the document two times in three. - - ``points_at`` names, per node-valued property, the planned entities its - range admits. The step otherwise chooses on the name alone and picks the - one that reads like the document: a recipe page with its ingredients - planned as `HowToSupply` had `recipeIngredient` chosen over `supply`, and - `recipeIngredient` ranges over `ItemList`, so the fill step pinned it to - the sections and every ingredient came out isolated. The range decides - which property can hold the plan, and the step choosing could not see it. + ``readings`` says, per planned entity, of each path it is offered what + that path reaches, holds or takes. A name on its own is not comparable with one that says + what it reaches: offered beside `material (points at e8 ... e28)`, a bare + `supply.item` advertised nothing while admitting the same twenty-one + ingredients, and the step took the one that read fuller. Neither inside nor + further along a path is a lesser place for a property to be, so every + offered path carries a reading and none is offered as a bare name. + + What a link admits is the plan filtered by its range, which is what decides + whether a property can hold the entities at all. A recipe page with its + ingredients planned as `HowToSupply` had `recipeIngredient` chosen over + `supply.item`, and `recipeIngredient` ranges over `ItemList`, so the fill + step pinned it to the sections and every ingredient came out isolated. """ + offered = as_per_class(offered) described = request.property_text or {} - reach = points_at or {} - carried = holds or {} - - def _line(name: str) -> str: - text = f" {name}: {described[name]}" if name in described else f" {name}" - if name in carried: - return f"{text} (holds an object with {', '.join(carried[name])})" - if name not in reach: - return text - targets = ", ".join(reach[name]) - return f"{text} (points at {targets})" if targets else f"{text} (points at nothing in this plan)" - - if described or reach or carried: + reads = readings or {} + + def _line(name: str, under: Mapping[str, str]) -> str: + # By the property, not by the path it was reached along. The text is + # keyed by property name and the offer is a dotted path, so every + # path inside an object arrived bare: `supply.item (points at e2, + # e3)` and `supply.requiredQuantity.value (number)` beside `text: The + # textual content of this CreativeWork. (string)`. Of 526 paths + # offered for one entity, 445 said nothing about themselves, and the + # step chose from the 81 that did. + # The catalogue states every property; whether the offer restates it + # is a question with an answer, so it is a switch and not a choice. + gloss = "" if _BARE else _gloss(described.get(name) or described.get(name.rsplit(".", 1)[-1])) + text = f" {name}: {gloss}" if gloss else f" {name}" + return f"{text} ({under[name]})" if name in under else text + + if described or reads: # One line per property, because a comment does not fit beside a name # and the step is choosing between them rather than scanning a list. + # Entities offering the same paths with the same readings share one + # block. Written out per entity, twenty-one ingredients were sent the + # same two hundred lines twenty-one times, 211 KB of a 229 KB request, + # to collect twenty-one answers of one word. + blocks: dict[tuple[object, ...], list[tuple[str, str]]] = {} + for key, per_class in offered.items(): + under = reads.get(key) or {} + for cls, names in per_class.items(): + shape = (tuple(names), tuple(under.get(name, "") for name in names)) + blocks.setdefault(shape, []).append((key, cls)) lines: list[str] = [] - for key, names in offered.items(): - lines.append(f"{(named or {}).get(key) or key}:") - lines += [_line(name) for name in names] + for (names, _), held in blocks.items(): + lines += [ + f"{(named or {}).get(key) or key}, as {cls}:" if cls else f"{(named or {}).get(key) or key}:" + for key, cls in held + ] + lines += [_line(name, reads.get(held[0][0]) or {}) for name in names] listed = "\n".join(lines) else: - listed = "\n".join(f"{(named or {}).get(key) or key}: {', '.join(names)}" for key, names in offered.items()) + listed = "\n".join( + f"{(named or {}).get(key) or key}{f', as {cls}' if cls else ''}: {', '.join(names)}" + for key, held in offered.items() + for cls, names in held.items() + ) # The form is said in words as well as declared in the schema, because a # condition that sends no schema leaves the words the only place it is # stated: asked for flags with the grammar off, the step was sent a diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 5ce38a4..41f27c3 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -11,6 +11,7 @@ that answers with the schema instead of a plan, which is asked again here. """ +import copy import json import threading from dataclasses import replace @@ -282,18 +283,30 @@ def targets_of(slot): return [value for value in slot["enum"] if value is not None] -def items_for(response_format, key="e1"): - """The answer shape one entity was offered, through its shared definition.""" - slot = response_format["properties"]["fillable"]["properties"][key] - if "$ref" in slot: - slot = response_format["$defs"][slot["$ref"].rsplit("/", 1)[-1]] +def items_for(response_format, key="e1", cls=None): + """The answer shape one entity was offered, through its shared definition. + + The step asks per class, so an entity with two candidates holds one shape + per class. ``cls`` picks one; without it the first is the one a test + asking for "the" shape means. + """ + + def resolve(slot): + if "$ref" in slot: + return response_format["$defs"][slot["$ref"].rsplit("/", 1)[-1]] + return slot + + slot = resolve(response_format["properties"]["fillable"]["properties"][key]) + if "items" not in slot and "properties" in slot: + held = slot["properties"] + slot = resolve(held[cls] if cls is not None else next(iter(held.values()))) return slot["items"] -def enums_of(response_format): +def enums_of(response_format, cls=None): """The property enumeration each entity was offered, per entity.""" offered = response_format["properties"]["fillable"]["properties"] - return {key: items_for(response_format, key)["enum"] for key in offered} + return {key: items_for(response_format, key, cls)["enum"] for key in offered} def _sentence_about_several_values(content): @@ -409,7 +422,10 @@ def test_a_shortlist_offers_the_union_of_its_classes_properties(self): only the first would rule out a value the second may well state.""" client = MultiStepClient(plan=UNION_PLAN, fillable={"fillable": {"e1": ["name"], "e2": ["name"]}}) agent(client).run(request()) - assert enums_of(fillable_formats(client)[0])["e1"] == ["name", "jobTitle", "isbn", "worksFor", "author"] + # Per class now: the union is what the two lists are between them. + held = fillable_formats(client)[0] + assert enums_of(held, "Person")["e1"] == ["name", "jobTitle", "worksFor"] + assert enums_of(held, "Book")["e1"] == ["name", "isbn", "author"] def test_the_property_schema_carries_a_title(self): """LangChain rejects a response format without one, and every cell of @@ -418,7 +434,7 @@ def test_the_property_schema_carries_a_title(self): def test_the_prompt_names_each_entity_with_its_class_and_its_properties(self): content = fillable_system(self.sent()) - assert 'e1 ("Ada"), Person:' in content + assert 'e1 ("Ada"), Person, as Person:' in content for name in ("name", "jobTitle", "worksFor"): assert f"\n {name}" in content, name @@ -429,8 +445,9 @@ def test_a_link_says_which_planned_entities_its_range_admits(self): content = fillable_system(self.sent()) assert "worksFor (points at e2)" in content - def test_a_literal_is_left_unannotated(self): + def test_a_literal_says_its_type(self): content = fillable_system(self.sent()) + assert "name (string)" in content assert "name (points at" not in content def test_the_property_step_reads_the_whole_document(self): @@ -1043,14 +1060,17 @@ def test_fillable_properties_takes_the_plan_it_is_given(self): PlannedEntity(key="e1", classes=("Person",), mention="Ada"), PlannedEntity(key="e2", classes=("Organization",), mention="Acme"), ) - assert agent(client).fillable_properties(request(), plan) == {"e1": ("name", "worksFor"), "e2": ("name",)} + assert agent(client).fillable_properties(request(), plan) == { + "e1": {"Person": ("name", "worksFor")}, + "e2": {"Organization": ("name",)}, + } def test_available_properties_is_what_the_step_may_choose_from(self): """The union over the shortlist, so a step scored on its choice is scored against what it was actually offered.""" plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) available = agent(MultiStepClient()).available_properties(request(), plan) - assert set(available["e1"]) == {"name", "jobTitle", "worksFor"} + assert set(available["e1"]["Person"]) == {"name", "jobTitle", "worksFor"} def test_extract_pins_the_id_to_the_entities_the_call_is_for(self): """Without this the answer cannot be joined back to the plan, and @@ -1105,18 +1125,18 @@ def test_the_answer_is_names_alone(self): def test_an_answer_carrying_a_quotation_is_still_read(self): client = MultiStepClient(detects=[]) plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) - assert agent(client).fillable_properties(request(), plan) == {"e1": ("name", "worksFor")} + assert agent(client).fillable_properties(request(), plan) == {"e1": {"Person": ("name", "worksFor")}} def test_a_bare_name_is_still_read(self): """A model answering the older shape has answered the question.""" client = MultiStepClient(detects=[], fillable={"fillable": {"e1": ["name"]}}) plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) - assert agent(client).fillable_properties(request(), plan) == {"e1": ("name",)} + assert agent(client).fillable_properties(request(), plan) == {"e1": {"Person": ("name",)}} def test_an_item_naming_no_property_is_dropped(self): client = MultiStepClient(detects=[], fillable={"fillable": {"e1": [{"stated": "Ada"}]}}) plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) - assert agent(client).fillable_properties(request(), plan) == {"e1": ()} + assert agent(client).fillable_properties(request(), plan) == {"e1": {"Person": ()}} class TestAskingForTheWordsThatStateIt: @@ -1150,7 +1170,7 @@ def test_what_the_model_wrote_is_kept_for_the_caller(self): plan = (PlannedEntity(key="e1", classes=("Person",), mention="Ada"),) one = agent(client) one.fillable_properties(request(), plan) - assert one.fillable_answer["e1"][0] == {"property": "name", "stated": "Ada"} + assert one.fillable_answer["e1"]["Person"][0] == {"property": "name", "stated": "Ada"} class TestACallReportsOnlyWhatItWasAskedFor: @@ -1351,7 +1371,7 @@ class TestAnEmbeddingAbsorbsThePlannedEntity: def run(self, fillable=None, plan=None, answers=None): client = MultiStepClient( plan=EMBEDDING_PLAN if plan is None else plan, - fillable=fillable or {"fillable": {"e1": ["name", "address"], "e2": ["streetAddress"]}}, + fillable=fillable or {"fillable": {"e1": ["name", "address.streetAddress"], "e2": ["streetAddress"]}}, answers=EMBEDDING_ANSWER if answers is None else answers, ) result = agent(client, catalogue=EMBEDDING_CATALOGUE).run(embedding_request()) @@ -1408,7 +1428,7 @@ def test_an_entity_no_chosen_embedding_can_absorb_stays_at_the_top_level(self): # Detect, three property calls and one extract call per entity. The # third property call is the object standing in `address`, which is # asked about whether or not the slot holding it is chosen. - assert client.calls == 6 + assert client.calls == 5 assert sorted(entity["id"] for entity in result.payload["entities"]) == ["e1", "e2"] def test_an_entity_two_holders_could_absorb_stays_at_the_top_level(self): @@ -1544,69 +1564,86 @@ def quantity_request(): ) -class TestTheObjectWrittenInsideAnEntityIsAskedAboutToo: - """The property step runs over planned entities, and an object written - inside one is not planned. - - So nothing ever chose its slots, and the extract call asked for every slot - the class it holds declares: a recipe's yield arrived as a quantity - carrying a maximum, a minimum, a unit code and a unit text that no step - had named, repeated in every class definition able to hold one. +class TestAPropertyInsideAnObjectIsOfferedByItsPath: + """A slot holding an object is not a thing a document states; what it + holds is. - The object is asked about as if it were an entity, under a key made of the - entity holding it and the slot it stands in. That key belongs to the one - step: it reaches no other, and nothing answers under it in the extract - call, where the object stays written inside its holder. + Offering the holder left the step choosing a container, and a second + round asking what went into it asked about every object the class could + hold rather than the ones anything chose. A leaf path says both at once: + choosing `quantity.unitText` says the document gives a unit, and that a + quantity is therefore stated. """ def run(self, fillable=None): client = MultiStepClient( plan=[{"candidates": ["Person"], "mention": "Ada"}], - fillable=fillable or {"fillable": {"e1": ["name", "quantity"], "e1__quantity": ["unitText"]}}, + fillable=fillable or {"fillable": {"e1": ["name", "quantity.unitText"]}}, answers=[[{"id": "e1", "type": "Person", "name": "Ada", "quantity": [{"type": "QuantitativeValue"}]}]], ) result = agent(client).run(quantity_request()) return client, result - def test_the_step_is_asked_what_the_object_states(self): - client, _ = self.run() - assert offered_properties(client)["e1__quantity"] == ["unitText", "unitCode", "name"] + def test_the_holder_is_not_offered_on_its_own(self): + """Picking it would say a quantity is stated without saying what of + it, which is the question the second round existed to ask.""" + offered = offered_properties(self.run()[0])["e1"] + assert "quantity" not in offered - def test_the_question_says_which_slot_of_which_entity_it_is_about(self): - client, _ = self.run() - listed = "\n".join(fillable_system(client, where) for where in range(len(fillable_formats(client)))) - assert 'the object written into quantity of e1 ("Ada")' in listed + def test_its_leaves_are_offered_instead(self): + offered = offered_properties(self.run()[0])["e1"] + assert "quantity.unitText" in offered and "quantity.unitCode" in offered - def test_what_it_chose_inside_is_what_the_object_carries(self): + def test_choosing_a_leaf_chooses_the_slot_that_holds_it(self): + _, result = self.run() + assert "quantity" in result.properties_chosen["e1"] + + def test_the_object_carries_what_was_chosen_under_it(self): client, _ = self.run() inside = embedded_in(extract_format(client), "quantity") assert sorted(inside["properties"]) == ["id", "type", "unitText"] - def test_what_it_chose_inside_is_required_inside(self): - """The same trade the top level makes: the step was asked which - properties the document states and it named this one, so a call that - may omit it asks the question twice and takes the cheaper answer.""" - client, _ = self.run() - assert "unitText" in embedded_in(extract_format(client), "quantity")["required"] - - def test_a_name_the_holder_chose_is_not_required_inside_the_object(self): - """The two vocabularies overlap and the questions do not. ``name`` is - chosen for the person, and whether the quantity written inside the - person is named was asked separately and answered no.""" + def test_every_object_can_decline_what_was_chosen_inside(self): + """Whether a document states a property of an object is a claim about + one of them, and the objects do not exist until the answer does: a + page giving a unit for one quantity and not the next would have to + invent the second. Each subset leaves its own way out, so the test is + that there is one rather than which.""" + for profile, declines in (("openai", "null"), ("anthropic", "absent")): + client = MultiStepClient( + plan=[{"candidates": ["Person"], "mention": "Ada"}], + fillable={"fillable": {"e1": ["name", "quantity.unitText"]}}, + answers=[[{"id": "e1", "type": "Person", "name": "Ada", "quantity": [{"type": "QuantitativeValue"}]}]], + ) + agent(client, profile=profile).run(quantity_request()) + inside = embedded_in(extract_format(client), "quantity") + slot = inside["properties"]["unitText"] + if declines == "null": + assert "null" in slot["type"], profile + else: + assert "unitText" not in (inside.get("required") or []), profile + + def test_the_holder_still_requires_the_slot(self): + """The rule that a chosen property is required holds where it fixed + something: an entity that came back carrying its class and nothing + else.""" client, _ = self.run() - inside = embedded_in(extract_format(client), "quantity") - assert "name" not in inside["properties"] - assert "name" not in inside["required"] + shape = items_of(extract_format(client), "e1") + assert "quantity" in shape["required"] - def test_the_class_slot_survives_whatever_was_chosen(self): + def test_the_class_slot_survives_beside_what_was_chosen(self): """It is what the embedded object's class is graded against, and no step was ever asked about it.""" - client, _ = self.run(fillable={"fillable": {"e1": ["quantity"], "e1__quantity": []}}) - inside = embedded_in(extract_format(client), "quantity") - assert sorted(inside["properties"]) == ["id", "type"] - assert "type" in inside["required"] + client, _ = self.run() + assert "type" in embedded_in(extract_format(client), "quantity")["properties"] + + def test_a_slot_nothing_was_chosen_under_is_not_offered(self): + """A container cannot be chosen on its own, so an object nothing + states anything about has no reason to be in the call.""" + client, _ = self.run(fillable={"fillable": {"e1": ["name"]}}) + assert "quantity" not in items_of(extract_format(client), "e1")["properties"] - def test_the_object_is_not_an_entity_anywhere_outside_that_step(self): + def test_the_object_is_not_an_entity_anywhere(self): """It has no id of its own to be planned under, nothing points at it, and the extract call answers under the plan's keys alone.""" client, result = self.run() @@ -1614,25 +1651,11 @@ def test_the_object_is_not_an_entity_anywhere_outside_that_step(self): assert sorted(result.properties_chosen) == ["e1"] assert sorted(key for fmt in client.formats if _is_keyed(fmt) for key in fmt["properties"]) == ["e1"] - def test_a_name_invented_inside_is_reported_against_the_entity_holding_it(self): - _, result = self.run(fillable={"fillable": {"e1": ["name"], "e1__quantity": ["sparkle"]}}) - assert result.properties_invented == {"e1": ("sparkle",)} - - def test_the_objects_share_one_call_rather_than_taking_one_each(self): - """Two entities of a class ask the same question, so a call per class - is a call per question. An object standing in a slot asks a question - of its own, and one call each turns a page holding a dozen into a - dozen calls.""" - client = MultiStepClient( - plan=[ - {"candidates": ["Person"], "mention": "Ada"}, - {"candidates": ["Person"], "mention": "Grace"}, - ], - fillable={"fillable": {"e1": ["name"], "e2": ["name"], "e1__quantity": [], "e2__quantity": []}}, - answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}]], - ) - agent(client).run(quantity_request()) - assert len(fillable_formats(client)) == 2 + def test_one_call_asks_about_the_entity_and_everything_in_it(self): + """The round that asked separately is gone, so a page holding a dozen + objects costs no more calls than one holding none.""" + client, _ = self.run() + assert len(fillable_formats(client)) == 1 class TestASchemaThatOffersNoObjectSlot: @@ -2086,10 +2109,10 @@ def test_the_refusal_is_recognised(self): assert _refused_to_compile(ValueError("m answered with no choices, so there is nothing to read")) -class TestWhatAPropertyHoldsIsSaid: - """A property taking a reference says what it could reach, and one - taking an object said nothing, so the step chose between a described - name and a bare one. +class TestWhatAnOfferedPathSaysItHolds: + """Every offered path says what it reaches, holds or is. One that said + nothing was being compared against one that advertised the entities it + would reach, and the step took the fuller reading. """ SCHEMA = { @@ -2121,27 +2144,442 @@ class TestWhatAPropertyHoldsIsSaid: }, } - def _held(self): - from oold.agent.extraction import _held_by + PLAN = ( + PlannedEntity(key="e1", classes=("Organization",), mention="Initech"), + PlannedEntity(key="e2", classes=("Organization",), mention="Acme"), + ) + + def _read(self, **asked): + from oold.agent.extraction import _readings + + asked_for = replace(request(), schema=self.SCHEMA, branches={}, **asked) + offered = agent(MultiStepClient()).available_properties(asked_for, self.PLAN) + return _readings(asked_for, self.PLAN, dict(offered))["e1"] + + def test_a_path_into_an_object_is_what_is_offered(self): + """Not the container: picking `supply.item` implies `supply`.""" + read = self._read() + assert "supply.item" in read + assert "supply" not in read - return _held_by(replace(request(), schema=self.SCHEMA)) + def test_each_path_says_how_it_reads(self): + """Inside is not a lesser place for a property to be: a name alone + is not comparable with one that says what it reaches.""" + read = self._read() + assert read["supply.item"] == "string" + assert read["supply.requiredQuantity"] == "string" - def test_a_property_taking_an_object_names_what_it_carries(self): - assert self._held()["supply"] == ("item", "requiredQuantity") + def test_a_reference_inside_says_what_it_reaches(self): + assert self._read(ranges={"item": ("Organization",)})["supply.item"] == "points at e1, e2" - def test_the_class_and_id_slots_are_not_named(self): + def test_the_class_and_id_slots_are_not_offered(self): """They are bookkeeping, not something the document states.""" - assert not {"id", "type"} & set(self._held()["supply"]) + assert not {"supply.id", "supply.type"} & set(self._read()) - def test_a_property_taking_a_literal_is_not_annotated(self): - assert "name" not in self._held() + def test_a_property_taking_a_literal_says_its_type(self): + assert self._read()["name"] == "string" def test_the_prompt_says_it(self): from oold.agent.prompts import build_property_messages messages = build_property_messages( replace(request(), schema=self.SCHEMA), - {"e1": ("name", "supply")}, - holds={"supply": ("item", "requiredQuantity")}, + {"e1": ("name", "supply.item")}, + readings={"e1": {"name": "string", "supply.item": "points at e2"}}, + ) + said = messages[0].content + assert "supply.item (points at e2)" in said + assert "name (string)" in said + + def test_an_entity_is_told_it_is_not_its_own_target(self): + """Offered `mentions (points at e1 ... e12)`, e1 read its own key in + the list and pointed the property at itself. Said once rather than + cut from each list: the targets come off the range and are the same + for every entity in the group, so cutting one key per entity means + no two of them can share a block.""" + from oold.agent.prompts import build_property_messages + + said = build_property_messages(request(), {"e1": ("name",)}, readings={"e1": {"name": "string"}}) + assert "No property points an entity at itself." in said[0].content + # Still listed, which is what the sentence is there to correct. + assert self._read(ranges={"item": ("Organization",)})["supply.item"] == "points at e1, e2" + + def test_two_entities_do_not_share_one_table(self): + """The same name is not the same declaration for both: read from one + table over the whole plan, whichever was walked last decided how it + read for the other.""" + from oold.agent.extraction import _readings + + asked = replace(request(), schema=self.SCHEMA, branches={}) + plan = (*self.PLAN, PlannedEntity(key="e3", classes=("Person",), mention="Ada")) + offered = agent(MultiStepClient()).available_properties(asked, plan) + read = _readings(asked, plan, dict(offered)) + assert set(read) == {"e1", "e2", "e3"} + + +class TestAPathIntoAnObjectSurvivesToTheExtractCall: + """Chosen at the fillable step and then dropped from the shape it was + chosen for. The keep set holds `requiredQuantity.value` and the slot is + named `requiredQuantity`, so one flat set matched at every depth kept + neither, and the step was sent a supply with nowhere to put the amount. + """ + + SLOT = { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": {"type": "string"}, + "type": {"type": "string"}, + "item": {"type": "string"}, + "estimatedCost": {"type": "string"}, + "requiredQuantity": { + "type": "object", + "properties": { + "value": {"type": "number"}, + "unitText": {"type": "string"}, + "minValue": {"type": "number"}, + }, + }, + }, + }, + } + + def _narrowed(self, *keep): + from oold.agent.extraction import _narrowed_slot + + return _narrowed_slot(copy.deepcopy(self.SLOT), set(keep))["items"]["properties"] + + def test_the_object_a_path_runs_through_is_kept(self): + assert "requiredQuantity" in self._narrowed("item", "requiredQuantity.value") + + def test_only_the_properties_under_it_that_were_chosen_survive(self): + held = self._narrowed("item", "requiredQuantity.value")["requiredQuantity"] + assert set(held["properties"]) == {"value"} + + def test_a_slot_no_path_names_is_still_dropped(self): + assert "estimatedCost" not in self._narrowed("item", "requiredQuantity.value") + + def test_the_first_segment_alone_keeps_the_whole_object(self): + """Nothing said which of its properties to keep, so none is dropped.""" + held = self._narrowed("requiredQuantity")["requiredQuantity"] + assert set(held["properties"]) == {"value", "unitText", "minValue"} + + +class TestEntitiesOfferedTheSameThingShareOneBlock: + """Written out per entity, twenty-one ingredients were sent the same two + hundred lines twenty-one times to collect twenty-one answers of one word. + """ + + def _said(self, offered, readings): + from oold.agent.prompts import build_property_messages + + return build_property_messages(request(), offered, readings=readings).__getitem__(0).content + + def test_one_list_carries_both_headers(self): + said = self._said( + {"e1": ("name", "url"), "e2": ("name", "url")}, + {"e1": {"name": "string", "url": "string"}, "e2": {"name": "string", "url": "string"}}, + ) + assert "e1:\ne2:\n name (string)\n url (string)" in said + assert said.count(" name (string)") == 1 + + def test_a_different_list_is_a_different_block(self): + said = self._said( + {"e1": ("name",), "e2": ("url",)}, + {"e1": {"name": "string"}, "e2": {"url": "string"}}, + ) + assert said.count("e1:") == 1 and said.count("e2:") == 1 + assert " name (string)" in said and " url (string)" in said + + def test_the_same_names_reading_differently_do_not_share(self): + """The same path is not the same declaration for two entities, which + is why the readings are per entity in the first place.""" + said = self._said( + {"e1": ("item",), "e2": ("item",)}, + {"e1": {"item": "points at e2"}, "e2": {"item": "string"}}, + ) + assert " item (points at e2)" in said + assert " item (string)" in said + + +class TestTheCatalogueIsScopedToTheCall: + """Scoped to the plan rather than to the call, every batch carried every + class on the plan and the block was byte-identical across the lot: one + call paid twelve thousand characters of catalogue to print seventy-nine + characters of offers for twenty-four entities that are all Thing. + """ + + PLAN = ( + PlannedEntity(key="e1", classes=("Person",), mention="Ada"), + PlannedEntity(key="e2", classes=("Organization",), mention="Acme"), + ) + + def _system(self, *keys): + from oold.agent.client import CallLog as _log + + client = MultiStepClient() + held = agent(client, name="schema-dump-catalog-enforced") + held.enforcement = held.enforcement.with_catalogue(("Person", "Organization")).with_catalogue_text(( + "- Person\n a human", + "- Organization\n a body", + )) + asked = request() + offered = held.available_properties(asked, self.PLAN) + held._ask_fillable(asked, _log(), self.PLAN, {key: offered[key] for key in keys}) + return fillable_system(client) + + def test_only_the_class_this_call_asks_about_is_described(self): + said = self._system("e1") + assert "a human" in said + assert "a body" not in said + + def test_the_other_call_gets_the_other_class(self): + said = self._system("e2") + assert "a body" in said + assert "a human" not in said + + def test_a_call_over_both_describes_both(self): + said = self._system("e1", "e2") + assert "a human" in said and "a body" in said + + +class TestAnObjectsLinkComesWithWhatIsChosenInside: + """A reified relation says nothing without the end it is about. The step + chose how much and not what of, the fill schema was narrowed to exactly + that, and the slot that could have carried the pairing was not in the + grammar at all. + """ + + def _implied(self, answered, offered, ranges=None, classes=("Organization",)): + """The step answers per class, so the fixtures name one.""" + from oold.agent.extraction import _with_implied_links + + asked = replace(request(), ranges=ranges or {"item": ("Organization",)}) + plan = (PlannedEntity(key="e2", classes=classes, mention="Acme"),) + held = {key: {"Thing": tuple(names)} for key, names in answered.items()} + shown = {key: {"Thing": tuple(names)} for key, names in offered.items()} + return _with_implied_links(held, shown, asked, plan)["e1"]["Thing"] + + def test_the_link_is_added_beside_what_was_chosen(self): + held = self._implied( + {"e1": ("supply.requiredQuantity.value",)}, + {"e1": ("supply.item", "supply.requiredQuantity.value")}, + ) + assert "supply.item" in held + + def test_what_was_chosen_is_kept(self): + held = self._implied( + {"e1": ("supply.requiredQuantity.value",)}, + {"e1": ("supply.item", "supply.requiredQuantity.value")}, + ) + assert "supply.requiredQuantity.value" in held + + def test_a_link_already_chosen_is_not_repeated(self): + held = self._implied( + {"e1": ("supply.item", "supply.requiredQuantity.value")}, + {"e1": ("supply.item", "supply.requiredQuantity.value")}, + ) + assert held.count("supply.item") == 1 + + def test_a_link_reaching_nothing_on_this_page_is_not_added(self): + """What the amount is about cannot be something the plan does not + hold.""" + held = self._implied( + {"e1": ("supply.requiredQuantity.value",)}, + {"e1": ("supply.item", "supply.requiredQuantity.value")}, + classes=("Person",), + ) + assert "supply.item" not in held + + def test_a_link_outside_the_object_is_left_alone(self): + held = self._implied( + {"e1": ("supply.requiredQuantity.value",)}, + {"e1": ("supply.item", "supply.requiredQuantity.value", "tool.item")}, + ) + assert "tool.item" not in held + + def test_a_top_level_choice_implies_nothing(self): + held = self._implied({"e1": ("name",)}, {"e1": ("name", "supply.item")}) + assert held == ("name",) + + def test_every_object_on_the_path_contributes(self): + """A path chosen three deep was chosen inside two objects.""" + from oold.agent.extraction import _prefixes + + assert _prefixes("supply.requiredQuantity.value") == ("supply", "supply.requiredQuantity") + + +class TestAPathIsDescribedByThePropertyItNames: + """The text is keyed by property name and the offer is a dotted path, so + every path inside an object arrived bare. Of 526 paths offered for one + entity, 445 said nothing about themselves, and the step chose from the 81 + that did. + """ + + def _said(self, offered, text): + from oold.agent.prompts import build_property_messages + + asked = replace(request(), property_text=text) + return build_property_messages(asked, offered, readings={"e1": {}})[0].content + + def test_a_path_takes_the_description_of_its_last_segment(self): + said = self._said({"e1": ("supply.requiredQuantity",)}, {"requiredQuantity": "How much is needed."}) + assert "supply.requiredQuantity: How much is needed." in said + + def test_a_path_with_its_own_entry_prefers_it(self): + """A corpus that describes the path itself has said something more + specific than the property's own gloss.""" + said = self._said( + {"e1": ("supply.item",)}, + {"item": "An entry in a list.", "supply.item": "What the supply is for."}, + ) + assert "supply.item: What the supply is for." in said + assert "An entry in a list" not in said + + def test_a_top_level_property_is_unaffected(self): + said = self._said({"e1": ("name",)}, {"name": "A name."}) + assert "name: A name." in said + + def test_a_path_whose_property_is_undescribed_stays_bare(self): + said = self._said({"e1": ("supply.position",)}, {"name": "A name."}) + assert " supply.position\n" in said or said.rstrip().endswith(" supply.position") + + +class TestAClassIsAskedOnlyForWhatItHas: + """The union is what the step was offered; it is not what each class + declares. Merged into every arm, a property chosen against one candidate + became required on the other: a material offered `Substance` or `Product` + had `size` chosen and the grammar then demanded `size` of `Substance`, + which declares no such thing. The same prompt printed the class with no + properties above and a schema demanding one below. + """ + + def _arms(self, chosen): + client = MultiStepClient( + plan=UNION_PLAN, + fillable={"fillable": {"e1": list(chosen), "e2": ["name"]}}, + ) + agent(client, k=2).run(request()) + held = next(fmt for fmt in reversed(client.formats) if fmt and "jobTitle" in json.dumps(fmt)) + return { + name: sorted(body.get("properties") or {}) for name, body in ((held.get("$defs") or {}) or {}).items() + } or {"inline": sorted(_properties_in(held))} + + def test_a_property_the_class_does_not_declare_is_not_on_its_arm(self): + """`jobTitle` is Person's; `Book` is the other candidate for e1.""" + arms = self._arms(["name", "jobTitle"]) + for name, props in arms.items(): + if name.startswith("Book"): + assert "jobTitle" not in props, (name, props) + + def test_the_class_that_declares_it_keeps_it(self): + arms = self._arms(["name", "jobTitle"]) + held = [props for name, props in arms.items() if name.startswith("Person")] + assert held and all("jobTitle" in props for props in held), arms + + def test_an_inherited_property_survives_on_every_arm(self): + """`name` is Thing's, so every class below it has one.""" + arms = self._arms(["name", "jobTitle"]) + assert all("name" in props for props in arms.values()), arms + + +def _properties_in(schema): + """Every property name anywhere in a schema, for an inlined union.""" + found = set() + if isinstance(schema, dict): + found |= set(schema.get("properties") or {}) + for value in schema.values(): + found |= _properties_in(value) + elif isinstance(schema, list): + for value in schema: + found |= _properties_in(value) + return found + + +class TestTheWordsAndTheGrammarAgree: + """The prose names the properties to report and the grammar requires + them. Taken off the last arm built, the words quoted whichever class was + processed last: the prose asked for one property while the other branch + required six, and the one way to obey both was to answer as the narrower + class, losing what the wider one carried. + """ + + def _sent(self, chosen): + client = MultiStepClient( + plan=UNION_PLAN, + fillable={"fillable": {"e1": list(chosen), "e2": ["name"]}}, + ) + agent(client, k=2).run(request()) + listed = [ + m.content.split("Report only these properties for them:")[1].split("Another call")[0] + for turns in client.messages + for m in turns + if m.role == "system" and "Report only these properties" in m.content + ] + return next(one for one in listed if 'e1 ("Ada")' in one) + + def test_a_property_only_one_arm_carries_is_still_asked_for(self): + listed = self._sent(["name", "jobTitle"]) + assert "jobTitle" in listed, listed + + def test_what_every_arm_carries_is_asked_for_too(self): + assert "name" in self._sent(["name", "jobTitle"]) + + +class TestTwoEntitiesThatChoseForDifferentClasses: + """A group shares one pair of branches, so two entities in it share the + arms. Grouped on the union alone, the arms were built from whichever + entity came first: one that said "as a Book the document states its name" + was sent arms requiring `name` on Person and nothing on Book, which is + the steering the per-class answer exists to remove. + """ + + def _arms(self, first, second): + client = MultiStepClient( + plan=[ + {"candidates": ["Person", "Book"], "mention": "Ada"}, + {"candidates": ["Person", "Book"], "mention": "Grace"}, + ], + fillable={"fillable": {"e1": first, "e2": second}}, + answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Book"}]], + ) + agent(client, k=2, profile="google").run(request()) + fmt = next(f for f in client.formats if f and any(n.startswith("Person") for n in (f.get("$defs") or {}))) + defs = fmt["$defs"] + + def arms(key): + held = fmt["properties"][key] + refs = held.get("anyOf") or [held] + return { + defs[one["$ref"].rsplit("/", 1)[-1]]["properties"]["type"]["const"]: defs[ + one["$ref"].rsplit("/", 1)[-1] + ].get("required") + for one in refs + } + + return arms("e1"), arms("e2") + + def test_each_entity_gets_the_arms_it_chose_for(self): + first, second = self._arms({"Person": ["name"], "Book": []}, {"Person": [], "Book": ["name"]}) + assert "name" in (first.get("Person") or []), first + assert "name" in (second.get("Book") or []), second + + def test_neither_is_pushed_toward_the_class_it_did_not_choose(self): + first, second = self._arms({"Person": ["name"], "Book": []}, {"Person": [], "Book": ["name"]}) + assert "name" not in (first.get("Book") or []), first + assert "name" not in (second.get("Person") or []), second + + def test_the_same_attribution_shares_one_definition(self): + """The split is not a reason to stop sharing what agrees.""" + client = MultiStepClient( + plan=[ + {"candidates": ["Person", "Book"], "mention": "Ada"}, + {"candidates": ["Person", "Book"], "mention": "Grace"}, + ], + fillable={"fillable": {"e1": {"Person": ["name"], "Book": []}, "e2": {"Person": ["name"], "Book": []}}}, + answers=[[{"id": "e1", "type": "Person"}, {"id": "e2", "type": "Person"}]], ) - assert "supply (holds an object with item, requiredQuantity)" in messages[0].content + agent(client, k=2, profile="google").run(request()) + fmt = next(f for f in client.formats if f and any(n.startswith("Person") for n in (f.get("$defs") or {}))) + assert len(fmt["$defs"]) == 2, sorted(fmt["$defs"]) From 29e9c4a9e8df513ccd27b3b03c1685a342028169 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 18 Oct 2026 06:27:00 +0200 Subject: [PATCH 55/58] fix(agent): say what the per-class fillable step returns and loses - the annotation said flat where the answer has been per class - a class outside the offer cost the entity its answer with no counter - a name two candidate classes share is one slot, not two, in the budget - the working is merged per batch rather than read back off the attribute - implied links ordered, so two identical runs group the same way --- src/oold/agent/extraction.py | 172 +++++++++++++++++----------- src/oold/agent/prompts.py | 23 +++- tests/test_agent/test_multi_step.py | 46 ++++++++ 3 files changed, 171 insertions(+), 70 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 1ee1fc6..3950475 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -173,6 +173,14 @@ class ExtractionResult: Always zero while a grammar binds the enumeration, which is the point: it is what the enumeration was buying, and it can only be counted by asking the same question without one.""" + classes_misfiled: dict[str, tuple[str, ...]] = field(default_factory=dict) + """The classes the property step keyed its answer by that were not offered. + + A property outside the offer is dropped and counted in + :attr:`properties_invented`; a class outside it costs the entity its whole + answer, because nothing under an unoffered key is read. Recorded so the + two failures are told apart rather than both reading as an entity that + said nothing.""" properties_chosen: dict[str, tuple[str, ...]] = field(default_factory=dict) """The properties the property step kept, per entity. @@ -211,6 +219,7 @@ def describe(self) -> dict[str, Any]: "selected": {k: list(v) for k, v in self.selected.items()}, "mentions": dict(self.mentions), "properties_chosen": {k: list(v) for k, v in self.properties_chosen.items()}, + "classes_misfiled": {k: list(v) for k, v in self.classes_misfiled.items()}, "named": list(self.named), "absorbed": dict(self.absorbed), "dropped": list(self.dropped), @@ -261,7 +270,14 @@ def __init__( caller has to guess at.""" self._chosen_per_class: dict[str, dict[str, tuple[str, ...]]] = {} self.properties_invented: dict[str, tuple[str, ...]] = {} - """Every escalation, in order, whether or not it was answered.""" + """Properties the step named that were never offered to it, per entity.""" + self.classes_misfiled: dict[str, tuple[str, ...]] = {} + """Classes the step keyed its answer by that were never offered, per entity. + + The other way an answer can be lost whole. A property outside the + offer is dropped and counted; a class outside it takes the entity's + whole answer with it, because nothing under an unoffered key is read + and the fallback reading of a dict yields no names at all.""" self.supplied: dict[str, dict[str, Any]] = {} """What the caller answered, per entity.""" self.enforcement = enforcement @@ -347,12 +363,17 @@ def fillable_properties( request: ExtractionRequest, plan: tuple[PlannedEntity, ...], log: CallLog | None = None, - ) -> dict[str, tuple[str, ...]]: + ) -> dict[str, dict[str, tuple[str, ...]]]: """Step two on its own: which of those properties the document fills. ``plan`` is whatever the caller has. A benchmark hands it the true classes so the step is scored on its own question rather than on the one before it. + + Keyed by entity and then by candidate class, because a shortlist of + two offers two different property sets and an answer pooled across + them cannot say which set it was answering. The names are dotted leaf + paths wherever a slot holds an object, since that is what was offered. """ return self._choose_properties( request, @@ -896,6 +917,7 @@ def _multi_step(self, request: ExtractionRequest) -> ExtractionResult: for key, value in chosen.items() } last.properties_invented = dict(self.properties_invented) + last.classes_misfiled = dict(self.classes_misfiled) last.named = named last.absorbed = absorbed last.links = links @@ -1038,8 +1060,8 @@ def _choose_properties( request: ExtractionRequest, log: CallLog, plan: tuple[PlannedEntity, ...], - available: dict[str, tuple[str, ...]], - ) -> dict[str, tuple[str, ...]]: + available: dict[str, dict[str, tuple[str, ...]]], + ) -> dict[str, dict[str, tuple[str, ...]]]: """Ask which of each entity's own properties the document fills. One call per distinct property set, which is one per class the plan @@ -1074,7 +1096,7 @@ class ask the same question, so a call per class is a call per batches = [ part for shape, subset in grouped.items() - for part in _batched(subset, self._per_call(tuple(name for _, names in shape for name in names))) + for part in _batched(subset, self._per_call(_offered_names(dict(shape)))) ] batches += _packed( {key: per_class for key, per_class in available.items() if key not in planned}, @@ -1083,13 +1105,13 @@ class ask the same question, so a call per class is a call per if len(batches) == 1: return self._ask_fillable(request, log, plan, available) chosen: dict[str, dict[str, tuple[str, ...]]] = {} - answered: dict[str, dict[str, list[Any]]] = {} + # The working is merged inside the call, so reading it back here would + # race: every batch writes the same attribute and the loop would read + # whichever one had finished rather than the one it just waited for. with ThreadPoolExecutor(max_workers=min(len(batches), 8)) as pool: running = [pool.submit(self._ask_fillable, request, log, plan, subset) for subset in batches] for finished in running: chosen.update(finished.result()) - answered.update(self.fillable_answer or {}) - self.fillable_answer = answered return {key: chosen.get(key, {}) for key in available} def _per_call(self, names: tuple[str, ...]) -> int: @@ -1099,6 +1121,9 @@ def _per_call(self, names: tuple[str, ...]) -> int: budget divides by the names rather than capping the entities: twelve entities of sixty-two names compile and sixteen do not, where sixty-four entities of five names do. + + ``names`` is the distinct offer, from :func:`_offered_names`, since a + name two candidate classes share is one slot in the enumeration. """ budget = self.profile.max_enumerated_slots if budget is None or not names: @@ -1162,10 +1187,15 @@ def _ask_fillable( reply = self.client.invoke(messages, response_format=response_format, strict=self.enforcement.decode_strict) sink.append(reply.usage or TokenUsage()) - answered = _fillable_of(reply.parsed if reply.parsed is not None else parse_json_answer(reply.text), available) + answered, misfiled = _fillable_of( + reply.parsed if reply.parsed is not None else parse_json_answer(reply.text), available + ) # Kept so a caller can read what the step thought it was reading. The - # answer is the names; this is the working behind them. - self.fillable_answer = answered + # answer is the names; this is the working behind them. Merged rather + # than assigned, because the batches that call this run together and + # the last one to finish would otherwise be the only one recorded. + self.fillable_answer = {**(self.fillable_answer or {}), **answered} + self.classes_misfiled.update(misfiled) for key, per_class in available.items(): held = answered.get(key) or {} offered = {name for names in per_class.values() for name in names} @@ -1260,10 +1290,15 @@ class the value takes. # product, because the only branch carrying what the prose # demanded was the one that declares it. per_class = self._chosen_per_class.get(keys[0]) or {} - # A name the step chose for this class, or one the pipeline - # added for every class: a mention kept as `name` and a - # property the schema requires belong on each arm, where a - # property chosen against one candidate belongs only on it. + # A name the step chose for this class, or one no class + # claimed: a mention kept as `name` and a property the schema + # requires belong on each arm, where a property chosen against + # one candidate belongs only on it. + # + # This narrows `required` and nothing else, so a profile that + # requires every property puts the rest back and the arms end + # up identical again. On such a provider the per-class answer + # still decides which slots exist, and only the demand is lost. added = set(kept) - {held for names in per_class.values() for held in names} mine = [k for k in kept if k in set(per_class.get(name, ())) | added] if per_class else None held = {**(base.get("properties") or {}), **(branches.get(name) or {})} @@ -1435,6 +1470,7 @@ def ask_splitting(keys: list[str]) -> tuple[Any, list[Any], list[Any]]: dangling=dangling, unpinned=unpinned, properties_invented=dict(self.properties_invented), + classes_misfiled=dict(self.classes_misfiled), ) def _keyed_instruction( @@ -1943,33 +1979,6 @@ def keep(entity: Any) -> bool: _INSIDE_MARK = "__" -def _inside_key(key: str, slot: str) -> str: - """How the property step names the object standing in one entity's slot. - - A key of the step and not of the plan. It is minted for the one call that - asks what the object states and resolved back to the entity and the slot - straight after, so nothing downstream sees a second entity. - """ - return f"{key}{_INSIDE_MARK}{slot}" - - -def _by_holder( - invented: dict[str, tuple[str, ...]], available: dict[str, tuple[str, ...]] -) -> dict[str, tuple[str, ...]]: - """What the property step invented, filed under the planned entity. - - The step asks about an object standing in a slot under a key of its own, - and that key is the step's. Anything a caller reads afterwards is about - the plan, so a name invented inside an object is reported against the - entity holding it. - """ - found: dict[str, tuple[str, ...]] = {} - for key, names in invented.items(): - holder = key if key in available else key.partition(_INSIDE_MARK)[0] - found[holder] = tuple(dict.fromkeys(found.get(holder, ()) + names)) - return found - - def _named(entity: PlannedEntity) -> str: """One planned entity as the fill prompt names it.""" return f'{entity.key} ("{entity.mention}")' if entity.mention else entity.key @@ -2317,12 +2326,6 @@ def _objects_at(slot: Any) -> list[dict[str, Any]]: if isinstance(slot.get("properties"), dict): return [slot] return [found for key in ("items", "anyOf", "oneOf") if key in slot for found in _objects_at(slot[key])] - # Nothing kept here is made required. Whether a document states a - # property of an object is a claim about one of them, and the objects - # do not exist until the answer does: a page giving a quantity for one - # ingredient and not the next would have to invent the second. Both - # subsets leave a per-object way out, null where every property is - # made required and absence where they are not. def _narrowed_slot(definition: Any, keep: set[str]) -> Any: @@ -2330,6 +2333,13 @@ def _narrowed_slot(definition: Any, keep: set[str]) -> Any: A copy where there is something to narrow, because the branches belong to the request and every group narrows them again to its own answer. + + Nothing kept is made required. Whether a document states a property of an + object is a claim about one of them, and the objects do not exist until + the answer does: a page giving a quantity for one ingredient and not the + next would have to invent the second. Both subsets leave a per-object way + out, null where every property is made required and absence where they + are not. """ if not _holds_an_object(definition): return definition @@ -2367,6 +2377,20 @@ def _trim_branches( } +def _misfiled(value: Any, offered: dict[str, tuple[str, ...]]) -> tuple[str, ...]: + """The classes an answer keyed itself by that were never offered. + + A dict naming only classes outside the offer reads as an answer to a + question nobody asked, and :func:`_per_class` then falls back to reading + the whole object as one list, which a dict never is. The entity ends up + stating nothing, the extract call demands nothing of it, and no counter + moves. Recorded so a trace can show it. + """ + if not isinstance(value, dict) or any(cls in value for cls in offered): + return () + return tuple(sorted(str(key) for key in value)) + + def _per_class(value: Any, offered: dict[str, tuple[str, ...]]) -> dict[str, list[Any]]: """One entity's answer, read as a list per class it could be.""" if isinstance(value, dict) and any(cls in value for cls in offered): @@ -2375,7 +2399,9 @@ def _per_class(value: Any, offered: dict[str, tuple[str, ...]]) -> dict[str, lis return dict.fromkeys(offered, stated) -def _fillable_of(payload: Any, available: dict[str, dict[str, tuple[str, ...]]]) -> dict[str, dict[str, list[Any]]]: +def _fillable_of( + payload: Any, available: dict[str, dict[str, tuple[str, ...]]] +) -> tuple[dict[str, dict[str, list[Any]]], dict[str, tuple[str, ...]]]: """The property lists in an answer, whatever the model called the wrapper. One list per class the entity could be. An answer that gives a bare list @@ -2388,9 +2414,13 @@ def _fillable_of(payload: Any, available: dict[str, dict[str, tuple[str, ...]]]) answer itself. The same allowance :func:`_entities_of` makes, and for the same observation: giving a schema a title stopped one provider rejecting it and started another answering under that title. + + Returns the answer and, beside it, the classes each entity keyed itself by + that were never offered, which is the one reading that loses everything + without moving a counter. """ if not isinstance(payload, dict): - return {} + return {}, {} candidates: list[dict[str, Any]] = [] inner = payload.get("fillable") if isinstance(inner, dict): @@ -2401,15 +2431,13 @@ def _fillable_of(payload: Any, available: dict[str, dict[str, tuple[str, ...]]]) candidates.append(only) candidates.append(payload) for candidate in candidates: - found = { - key: _per_class(value, available[key]) - for key, value in candidate.items() - if key in available and isinstance(value, (list, dict)) - } + taken = {key: value for key, value in candidate.items() if key in available and isinstance(value, (list, dict))} + found = {key: _per_class(value, available[key]) for key, value in taken.items()} found = {key: value for key, value in found.items() if value is not None} if found: - return found - return {} + misfiled = {key: names for key, value in taken.items() if (names := _misfiled(value, available[key]))} + return found, misfiled + return {}, {} _REFUSALS = ( @@ -2607,13 +2635,26 @@ def _within_budget(properties: dict[str, Any], priced: dict[str, int], budget: i return batches or [properties] -def _batched(subset: dict[str, tuple[str, ...]], size: int) -> list[dict[str, tuple[str, ...]]]: +def _offered_names(per_class: dict[str, tuple[str, ...]]) -> tuple[str, ...]: + """What one entity's offer costs the compiler, counted once per name. + + A name two candidate classes both declare is one slot in the enumeration + and not two. Summed per class instead, an entity offered the same sixteen + properties as either of two classes was charged thirty-two, which halves + the budget and splits a request that would have compiled. + """ + return tuple(dict.fromkeys(name for names in per_class.values() for name in names)) + + +def _batched(subset: dict[str, dict[str, tuple[str, ...]]], size: int) -> list[dict[str, dict[str, tuple[str, ...]]]]: """One class's entities split into requests the provider will compile.""" keys = list(subset) return [{key: subset[key] for key in keys[at : at + size]} for at in range(0, len(keys), size)] or [subset] -def _packed(subset: dict[str, tuple[str, ...]], budget: int | None) -> list[dict[str, tuple[str, ...]]]: +def _packed( + subset: dict[str, dict[str, tuple[str, ...]]], budget: int | None +) -> list[dict[str, dict[str, tuple[str, ...]]]]: """Keys offering different property sets, filled into as few requests as fit. The compiler charges for the product of keys and the names each one @@ -2630,11 +2671,11 @@ def _packed(subset: dict[str, tuple[str, ...]], budget: int | None) -> list[dict return [] if budget is None: return [subset] - batches: list[dict[str, tuple[str, ...]]] = [] - current: dict[str, tuple[str, ...]] = {} + batches: list[dict[str, dict[str, tuple[str, ...]]]] = [] + current: dict[str, dict[str, tuple[str, ...]]] = {} spent = 0 - for key, names in sorted(subset.items(), key=lambda item: (item[1], item[0])): - cost = len(names) or 1 + for key, names in sorted(subset.items(), key=lambda item: (_offered_names(item[1]), item[0])): + cost = len(_offered_names(names)) or 1 if current and spent + cost > budget: batches.append(current) current, spent = {}, 0 @@ -2754,7 +2795,10 @@ def _with_implied_links( for cls, paths in per_class.items(): held = list(paths) offered = (available.get(key) or {}).get(cls, ()) - for under in {prefix for path in paths for prefix in _prefixes(path)}: + # Ordered, not a set: the result is part of the key the extract + # groups by, so a set's iteration order makes two identical runs + # group differently and send a different number of calls. + for under in dict.fromkeys(prefix for path in paths for prefix in _prefixes(path)): for other in offered: if not other.startswith(f"{under}.") or "." in other[len(under) + 1 :]: continue diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 17e37e8..73d70a3 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -430,11 +430,22 @@ def _property_item(names: list[str], evidence: bool) -> dict[str, Any]: } -_BARE = bool(os.environ.get("OOLD_BARE_OFFER")) -"""Whether the offer carries only names and readings, the catalogue being -the place a property is defined. A measurement switch: the offer is 80 per -cent of the fillable message and most of it is description the entry above -already carries.""" +_BARE_OFFER = "OOLD_BARE_OFFER" + + +def _bare() -> bool: + """Whether the offer carries only names and readings, the catalogue being + the place a property is defined. + + A measurement switch: the offer is 80 per cent of the fillable message and + most of it is description the entry above already carries. + + Read per call and not at import. A switch read once at import is set by + whichever process imported the module first, so a run that exports it and + a test that monkeypatches it both see the value they did not set. + """ + return bool(os.environ.get(_BARE_OFFER)) + _BUDGET = 320 """How much of a description an offer line may carry. @@ -505,7 +516,7 @@ def _line(name: str, under: Mapping[str, str]) -> str: # step chose from the 81 that did. # The catalogue states every property; whether the offer restates it # is a question with an answer, so it is a switch and not a choice. - gloss = "" if _BARE else _gloss(described.get(name) or described.get(name.rsplit(".", 1)[-1])) + gloss = "" if _bare() else _gloss(described.get(name) or described.get(name.rsplit(".", 1)[-1])) text = f" {name}: {gloss}" if gloss else f" {name}" return f"{text} ({under[name]})" if name in under else text diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 41f27c3..42f1e94 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -1920,6 +1920,52 @@ def test_an_answer_inside_the_offer_records_nothing(self): assert agent(client).run(request()).properties_invented == {} +class TestAnAnswerKeyedByAClassNobodyOffered: + """The other way the step's answer is lost whole. + + A property outside the offer is dropped and counted. A class outside it + takes everything under it, because the reader finds no offered class in + the object and falls back to reading the object itself as a list, which a + dict never is. Nothing moved, so nothing said so. + """ + + MISFILED = {"fillable": {"e1": {"Sparkle": ["name", "worksFor"]}, "e2": {"Organization": ["name"]}}} + + def test_the_class_is_recorded(self): + client = MultiStepClient(fillable=self.MISFILED) + result = agent(client, constrain_properties=False).run(request()) + assert result.classes_misfiled == {"e1": ("Sparkle",)} + + def test_the_entity_states_nothing(self): + """Pinned so the diagnostic is read beside the loss it explains.""" + client = MultiStepClient(fillable=self.MISFILED) + result = agent(client, constrain_properties=False).run(request()) + assert result.properties_chosen.get("e1", ()) == () + + def test_an_answer_under_an_offered_class_records_nothing(self): + client = MultiStepClient() + assert agent(client).run(request()).classes_misfiled == {} + + +class TestWhatOneEntityCostsTheCompiler: + """A name two candidate classes share is one slot, not two. + + Summed per class, an entity offered the same properties as either of two + classes was charged twice for each, which halves the budget and splits a + request that would have compiled. + """ + + def test_a_name_both_classes_offer_is_counted_once(self): + from oold.agent.extraction import _offered_names + + assert _offered_names({"Person": ("name", "jobTitle"), "Thing": ("name",)}) == ("name", "jobTitle") + + def test_an_offer_with_no_classes_costs_nothing(self): + from oold.agent.extraction import _offered_names + + assert _offered_names({}) == () + + class TestTheAnswerFormIsSaidInWords: """A condition that sends no schema leaves the words the only place the form is stated. Asked for flags with the grammar off, the property step From 4e0d8cbd9718ed1700351fcb44393ca94e7e1298 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Sun, 18 Oct 2026 07:01:18 +0200 Subject: [PATCH 56/58] fix(agent): read a path's description along the path, not at its leaf - weight.value and supply.requiredQuantity.value read identically before - the object a leaf sits in is where the sentence telling them apart is --- src/oold/agent/prompts.py | 39 ++++++++++++++++++++++------ tests/test_agent/test_prompts.py | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 8 deletions(-) diff --git a/src/oold/agent/prompts.py b/src/oold/agent/prompts.py index 73d70a3..f23965c 100644 --- a/src/oold/agent/prompts.py +++ b/src/oold/agent/prompts.py @@ -459,6 +459,36 @@ def _bare() -> bool: """ +def _described_as(path: str, described: Mapping[str, str]) -> str | None: + """What a dotted path says about itself, read from the nearest statement. + + The text is keyed by property and the offer is a path, so a reading has to + be looked up along the path rather than at one end of it. Four places, in + this order: the whole path, then each object it was reached through from + the innermost outward, by path and then by name, then the leaf's own name. + + The order is what makes a profile's refinement reach the model at all. + `weight.value` and `supply.requiredQuantity.value` are both "The numeric + value of the quantity" under the leaf's own entry, which is the vocabulary + describing a number; the sentence that tells one from the other, that a + weight is what the thing itself weighs and a required quantity is how much + of it something else needs, is written against the object and not against + its leaves. Looked up leaf first, the two paths carrying the whole point + of a graph read identically, and the one profile refinement that did + arrive was `supply.item`, because `item` happens to be a leaf. + """ + if path in described: + return described[path] + parts = path.split(".") + for cut in range(len(parts) - 1, 0, -1): + prefix = ".".join(parts[:cut]) + if prefix in described: + return described[prefix] + if parts[cut - 1] in described: + return described[parts[cut - 1]] + return described.get(parts[-1]) + + def _gloss(text: str | None) -> str: """What a property is, from whatever the corpus holds, within the budget.""" if not text: @@ -507,16 +537,9 @@ def build_property_messages( reads = readings or {} def _line(name: str, under: Mapping[str, str]) -> str: - # By the property, not by the path it was reached along. The text is - # keyed by property name and the offer is a dotted path, so every - # path inside an object arrived bare: `supply.item (points at e2, - # e3)` and `supply.requiredQuantity.value (number)` beside `text: The - # textual content of this CreativeWork. (string)`. Of 526 paths - # offered for one entity, 445 said nothing about themselves, and the - # step chose from the 81 that did. # The catalogue states every property; whether the offer restates it # is a question with an answer, so it is a switch and not a choice. - gloss = "" if _bare() else _gloss(described.get(name) or described.get(name.rsplit(".", 1)[-1])) + gloss = "" if _bare() else _gloss(_described_as(name, described)) text = f" {name}: {gloss}" if gloss else f" {name}" return f"{text} ({under[name]})" if name in under else text diff --git a/tests/test_agent/test_prompts.py b/tests/test_agent/test_prompts.py index 6a5f982..84e1d1c 100644 --- a/tests/test_agent/test_prompts.py +++ b/tests/test_agent/test_prompts.py @@ -165,3 +165,47 @@ def test_a_property_with_no_description_is_still_offered(self): def test_without_descriptions_the_names_stay_on_one_line(self): """The compact form is what every corpus without a vocabulary gets.""" assert "e1: about, name" in self._listing() + + +class TestAPathIsReadAlongItsWholeLength: + """A reading is keyed by property and the offer is a dotted path. + + The sentence that tells `weight.value` from `supply.requiredQuantity.value` + is written against the object, not against its leaves, so a lookup that + tries the leaf first prints the vocabulary's "The numeric value of the + quantity" against both and the refinement never reaches the model. + """ + + TEXT = { + "value": "The numeric value of the quantity.", + "weight": "What the thing itself weighs, not how much of it something else uses.", + "supply.requiredQuantity": "How much of this supply's item is needed.", + "requiredQuantity": "How much of the item is needed.", + "supply.item.name": "The word the document calls the consumed thing by.", + } + + def _read(self, path): + from oold.agent.prompts import _described_as + + return _described_as(path, self.TEXT) + + def test_the_whole_path_wins_where_it_is_stated(self): + assert self._read("supply.item.name") == self.TEXT["supply.item.name"] + + def test_the_object_a_leaf_sits_in_beats_the_leaf(self): + assert self._read("weight.value") == self.TEXT["weight"] + + def test_the_innermost_object_wins_over_the_outer_one(self): + assert self._read("supply.requiredQuantity.value") == self.TEXT["supply.requiredQuantity"] + + def test_an_object_stated_by_name_is_found_where_the_path_is_not(self): + assert self._read("tool.requiredQuantity.value") == self.TEXT["requiredQuantity"] + + def test_the_leaf_answers_when_nothing_holds_it(self): + assert self._read("value") == self.TEXT["value"] + + def test_a_path_nothing_describes_reads_as_nothing(self): + assert self._read("award.name") is None + + def test_two_paths_that_mean_different_things_no_longer_read_the_same(self): + assert self._read("weight.value") != self._read("supply.requiredQuantity.value") From 083dd17b429fafacbb52b0c135d2c351d37a0732 Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 19 Oct 2026 04:22:54 +0200 Subject: [PATCH 57/58] fix(agent): an embedded object's links start at it, not at its holder - a supply carries no id, so its item edge was asserted from the HowTo too - every item and required_quantity was drawn twice, one at the wrong level - a supply naming its own procedure became a self-loop on that procedure --- src/oold/agent/extraction.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 3950475..645f12e 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -3125,14 +3125,26 @@ def _edges_of( def _stated_objects(node: Any, source: str | None = None) -> list[tuple[str, dict[str, Any]]]: """Each object an answered entity holds, with the id an edge from it starts at. - Its own id where it states one and the holder's otherwise, which is the - reading :func:`_emitted_ids` already takes of an id written inside an - entity: the object is a thing something may point at, so it is also a - thing something may be pointed at from. + Its own id, and only its own. An object that states none states no edge + either: whatever it points at, it points at from itself, and the holder + is not where that arrow starts. + + Read the other way, as it was, every link inside an embedded object was + asserted a second time from the entity holding it. A `HowToSupply` is + written inside a `HowTo` and carries no id, because the fill step mints + none for an embedded object, so `supply.item` came back as both + `supply -> Flour`, which the answer says, and `HowTo -> Flour`, which it + does not and which no branch of the schema admits. One recipe drew each + `item` and each `required_quantity` twice, and where a supply named the + procedure itself the second copy was a self-loop, `Cake -> item -> Cake`. + + Nothing is lost by dropping it. The reader reifies an embedded object into + an entity of its own and the edge is drawn from that, which is the node + the relation is actually about. """ found: list[tuple[str, dict[str, Any]]] = [] if isinstance(node, dict): - here = _entity_id(node) or source + here = _entity_id(node) if here is not None: found.append((here, node)) for value in node.values(): From bb7ece9ebe5e9a3bec8044390f08c8f779f5be8b Mon Sep 17 00:00:00 2001 From: SimonTaurus Date: Mon, 19 Oct 2026 05:07:14 +0200 Subject: [PATCH 58/58] fix(agent): give an embedded object the id the reader reifies it under - dropping it left links empty for every model, right answers included - the source is --, so edge and node agree - a holder still states no edge that belongs to the object inside it --- src/oold/agent/extraction.py | 34 +++++++++++------- tests/test_agent/test_multi_step.py | 56 +++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 12 deletions(-) diff --git a/src/oold/agent/extraction.py b/src/oold/agent/extraction.py index 645f12e..16fa189 100644 --- a/src/oold/agent/extraction.py +++ b/src/oold/agent/extraction.py @@ -3138,20 +3138,30 @@ def _stated_objects(node: Any, source: str | None = None) -> list[tuple[str, dic `item` and each `required_quantity` twice, and where a supply named the procedure itself the second copy was a self-loop, `Cake -> item -> Cake`. - Nothing is lost by dropping it. The reader reifies an embedded object into - an entity of its own and the edge is drawn from that, which is the node - the relation is actually about. + An embedded object is given the id the reader will reify it under, + ``--``, counting from one and counting a lone + object as the first. Dropping it entirely instead left the record unable + to tell a model that asserted three correct links from one that asserted + none: both came back with no links at all, because the only thing stating + them was an object with no id. + + Only a string-valued property becomes an edge, so minting a name for an + object the reader folds into a scalar rather than into an entity adds + nothing: a quantity written in place is not a reference and is not read + as one here either. """ found: list[tuple[str, dict[str, Any]]] = [] - if isinstance(node, dict): - here = _entity_id(node) - if here is not None: - found.append((here, node)) - for value in node.values(): - found.extend(_stated_objects(value, here)) - elif isinstance(node, list): - for value in node: - found.extend(_stated_objects(value, source)) + if not isinstance(node, dict): + return found + here = _entity_id(node) or source + if here is None: + return found + found.append((here, node)) + for prop, value in node.items(): + items = value if isinstance(value, list) else [value] + for index, item in enumerate(items, start=1): + if isinstance(item, dict): + found.extend(_stated_objects(item, f"{here}-{prop}-{index}")) return found diff --git a/tests/test_agent/test_multi_step.py b/tests/test_agent/test_multi_step.py index 42f1e94..3a13023 100644 --- a/tests/test_agent/test_multi_step.py +++ b/tests/test_agent/test_multi_step.py @@ -1506,6 +1506,62 @@ def test_an_edge_an_embedded_object_states_is_read_from_where_it_stands(self): assert links == [Edge(source="s1", prop="item", target="e2")] assert dangling == [] + def test_an_embedded_object_with_no_id_still_states_its_edge(self): + """The fill step mints no id for an embedded object, so this is the + shape a real answer takes and the one above is not. + + Dropped, the record could not tell a model that asserted three correct + links from one that asserted none: both came back with no links at + all. The id is the one the reader reifies the object under, so the + edge and the node it starts at are the same node.""" + from oold.agent.extraction import _edges_of + + answered = [ + { + "id": "e1", + "type": "HowTo", + "supply": [ + {"type": "HowToSupply", "item": "e2"}, + {"type": "HowToSupply", "item": "e3"}, + ], + }, + {"id": "e2", "type": "Product", "name": "Milk"}, + {"id": "e3", "type": "Product", "name": "Sugar"}, + ] + links, dangling = _edges_of(answered, {"item": ("Thing",)}) + assert links == [ + Edge(source="e1-supply-1", prop="item", target="e2"), + Edge(source="e1-supply-2", prop="item", target="e3"), + ] + assert dangling == [] + + def test_a_lone_embedded_object_counts_as_the_first(self): + """The reader numbers from one and numbers a bare object as one, so a + property holding a single object and one holding a list of one name + the same node.""" + from oold.agent.extraction import _edges_of + + answered = [ + {"id": "e1", "type": "HowTo", "supply": {"type": "HowToSupply", "item": "e2"}}, + {"id": "e2", "type": "Product", "name": "Milk"}, + ] + links, _ = _edges_of(answered, {"item": ("Thing",)}) + assert links == [Edge(source="e1-supply-1", prop="item", target="e2")] + + def test_the_holder_states_no_edge_its_object_stated(self): + """`supply.item` is the supply's, and a `HowTo` has no `item`. Read + the other way every link inside an embedded object was asserted twice, + once from a class whose branch does not declare it, and a supply + naming its own procedure became a self-loop on that procedure.""" + from oold.agent.extraction import _edges_of + + answered = [ + {"id": "e1", "type": "HowTo", "supply": [{"type": "HowToSupply", "item": "e1"}]}, + ] + links, dangling = _edges_of(answered, {"item": ("Thing",)}) + assert [edge.source for edge in links] == ["e1-supply-1"] + assert not any(edge.source == edge.target for edge in [*links, *dangling]) + def test_the_record_is_serialisable(self): _, result = self.run() described = result.describe()