Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
7a4a942
feat(agent): enforcement axis and per-provider schema preparation
simontaurus Sep 26, 2026
c9a70c0
feat(agent): model boundary with per-call token attribution
simontaurus Sep 26, 2026
e9f47be
feat(agent): run an extraction under one enforcement condition
simontaurus Sep 27, 2026
2c3f697
style: drop pseudo-cleft and "rather than" from docstrings
simontaurus Sep 27, 2026
9043195
feat(agent): fold the system message where a deployment drops it
simontaurus Sep 27, 2026
888984a
feat(agent): record the prompt the model was actually sent
simontaurus Sep 27, 2026
1b80f38
feat(agent): close the unit slot as well as the class slot
simontaurus Sep 27, 2026
fe07a2f
feat(agent): show the catalogue as entries, not bare identifiers
simontaurus Sep 27, 2026
c3b0cc8
fix: put the rendered catalogue in the prompt
simontaurus Sep 27, 2026
8b926e4
feat(agent): constrain class and value jointly with a union
simontaurus Sep 27, 2026
ccbbb23
feat(agent): select the class, then fill what it implies
simontaurus Sep 27, 2026
6483e9b
feat(agent): validate the answer, and offer it its errors back
simontaurus Sep 27, 2026
f85222d
fix: build the union before the provider transform, not after
simontaurus Sep 27, 2026
f40b347
fix: a union shares only what no branch defines
simontaurus Sep 27, 2026
3b0e951
feat(agent): shape a union like the class hierarchy
simontaurus Sep 27, 2026
039406e
feat(agent): hold multiple parents with allOf, not a tree
simontaurus Sep 27, 2026
4c2d406
fix: cut cycles, not chains, when inlining references
simontaurus Sep 27, 2026
9025217
feat(agent): build a hierarchy union when the corpus has parents
simontaurus Sep 27, 2026
03e1b91
fix: fill one call per shortlist, not one per document
simontaurus Sep 27, 2026
9aeee60
style: match the writing voice in today's docstrings
simontaurus Sep 27, 2026
505962b
fix: name the selection schema
simontaurus Sep 27, 2026
fb40fda
fix(agent): read the entity list under a wrapper the model named
simontaurus Sep 27, 2026
3cb59c1
fix(agent): write inherited properties into each union branch
simontaurus Sep 28, 2026
db519db
feat(agent): add segmented orchestration and reference pinning
simontaurus Sep 28, 2026
7aa87ca
feat(agent): add multi-step orchestration
simontaurus Sep 30, 2026
a47b049
fix(agent): say what one entity is in the detect prompt
simontaurus Sep 30, 2026
cc7d5d7
feat(agent): add A2-strict and A4-strict, and ask for what is missing
simontaurus Oct 1, 2026
a1d2138
feat: catalogue_in_prompt separates the answer space from the prompt
simontaurus Oct 4, 2026
71494a9
refactor(agent): name arms by what they carry and enforce
simontaurus Oct 4, 2026
3b9b18e
feat(agent): a public door onto each step of the pipeline
simontaurus Oct 6, 2026
31dc6e1
fix(prompts): the property step was told to include when unsure
simontaurus Oct 7, 2026
621a270
feat(prompts): the property step points at the words it read
simontaurus Oct 7, 2026
97a37b1
fix(prompts): say the rule the corpus applies, and drop the quotation
simontaurus Oct 7, 2026
c93db82
feat(prompts): the property step is shown what the names mean
simontaurus Oct 7, 2026
58db032
fix(prompts): answer from the text in front of you, not from memory
simontaurus Oct 7, 2026
7e1a657
feat(prompts): the quotation is a condition, not a default
simontaurus Oct 7, 2026
c6ba4a3
feat(agent): expose extract_narrowed for an external oracle
simontaurus Oct 8, 2026
7dc5289
feat(agent): carry the plan step mention onto the result
simontaurus Oct 9, 2026
11a6026
fix(agent): a grouped call contributes only the entities it owns
simontaurus Oct 10, 2026
6efbdf8
fix(agent): say that a property may hold more than one value
simontaurus Oct 10, 2026
4fff988
feat(agent): keep the name slot where the plan read a mention
simontaurus Oct 10, 2026
7a08ac4
fix(agent): pin an entity a schema puts inside another entity
simontaurus Oct 10, 2026
cdb1cb1
feat(agent): fold a planned entity into the embedding that holds it
simontaurus Oct 10, 2026
f411604
feat(agent): mark the system turn for the provider to cache
simontaurus Oct 11, 2026
8328f3a
fix(agent): ask for an id even where no plan issued one
simontaurus Oct 12, 2026
39d4bad
fix(agent): narrow an array-valued reference inside its array
simontaurus Oct 12, 2026
66e1759
fix(agent): narrow the catalogue entries with the catalogue
simontaurus Oct 12, 2026
ac0ea2f
fix(agent): assign the plan's entity keys instead of asking for them
simontaurus Oct 12, 2026
fa10fcc
feat(agent): prefer a class the rest of the document can attach to
simontaurus Oct 12, 2026
ee3963a
fix(agent): name the model that answered with no choices
simontaurus Oct 13, 2026
06d463f
fix(agent): bind a grammar on Anthropic rather than ask for one
simontaurus Oct 14, 2026
f71f89e
feat(agent): fill the plan under the ids it issued, a class at a time
simontaurus Oct 14, 2026
5a163d3
feat(agent): say what a property taking an object holds
simontaurus Oct 14, 2026
fac66df
feat(agent): offer fillable properties per candidate class
simontaurus Oct 18, 2026
29e9c4a
fix(agent): say what the per-class fillable step returns and loses
simontaurus Oct 18, 2026
4e0d8cb
fix(agent): read a path's description along the path, not at its leaf
simontaurus Oct 18, 2026
083dd17
fix(agent): an embedded object's links start at it, not at its holder
simontaurus Oct 19, 2026
bb7ece9
fix(agent): give an embedded object the id the reader reifies it under
simontaurus Oct 19, 2026
36b7b41
Merge branch 'main' into feat/agent-extra
simontaurus Nov 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,23 @@ 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 = [
# 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",
"jupyter_bokeh",
Expand Down Expand Up @@ -104,6 +121,7 @@ all = [
"referencing>=0.30",
"click>=8.1",
"mcp>=1.2",
"langchain-core>=0.3",
]

[dependency-groups]
Expand All @@ -114,6 +132,7 @@ dev = [
"referencing>=0.30",
"click>=8.1",
"mcp>=1.2",
"langchain-core>=0.3",
"pytest",
"pytest-cov>=7.0.0",
"pytest-benchmark",
Expand Down
75 changes: 75 additions & 0 deletions src/oold/agent/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""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` 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.

Requires the ``agent`` extra::

uv add "oold[agent]"
pip install "oold[agent]"
"""

from oold.agent.client import (
Call,
CallLog,
ChatClient,
ChatResponse,
Message,
TokenUsage,
)
from oold.agent.enforcement import (
ARMS,
DecodeConstraint,
Enforcement,
Orchestration,
OutputForm,
arm,
)
from oold.agent.extraction import (
Edge,
ExtractionAgent,
ExtractionResult,
PlannedEntity,
parse_json_answer,
)
from oold.agent.prompts import ExtractionRequest, build_messages
from oold.agent.provider import (
PROFILES,
Degradation,
ProviderProfile,
prepare,
profile_for,
schema_hash,
)

__all__ = [
"ARMS",
"PROFILES",
"Call",
"CallLog",
"ChatClient",
"ChatResponse",
"DecodeConstraint",
"Degradation",
"Edge",
"Enforcement",
"ExtractionAgent",
"ExtractionRequest",
"ExtractionResult",
"Message",
"Orchestration",
"OutputForm",
"PlannedEntity",
"ProviderProfile",
"TokenUsage",
"arm",
"build_messages",
"parse_json_answer",
"prepare",
"profile_for",
"schema_hash",
]
248 changes: 248 additions & 0 deletions src/oold/agent/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
"""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 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
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 hashlib
import json
import threading
import time
from collections.abc import Iterator, Sequence
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Protocol, runtime_checkable

__all__ = [
"Call",
"CallLog",
"ChatClient",
"ChatResponse",
"Message",
"TokenUsage",
"fold_system_into_user",
"prompt_hash",
]


@dataclass(frozen=True)
class Message:
role: str
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."""

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,
strict: bool = False,
) -> 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, not 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),
}
Loading
Loading