Files
stack/src/llm/structured.py
kert 4d14ab1c4c
Some checks failed
CI / lint (push) Successful in 1m15s
CI / notebooks-smoke (push) Successful in 1m58s
Deploy / changes (push) Successful in 18s
CI / test (push) Failing after 4m36s
Infra CI / notebooks (push) Successful in 1m12s
Infra CI / zotero (push) Successful in 46s
Infra CI / docs (push) Successful in 1m52s
Infra CI / api (push) Successful in 1m24s
Infra CI / llm (push) Successful in 1m33s
Infra CI / mc (push) Successful in 22s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / report (push) Has been cancelled
Deploy / mc (push) Has been cancelled
Deploy / bcda (push) Has been cancelled
Deploy / llm (push) Has been cancelled
Deploy / api (push) Has been cancelled
Infra CI / bcda (push) Has been cancelled
fix(pfs,llm): ledger survives truncated lines, indexes once, counts pending failures
2026-11-12 00:12:26 -05:00

128 lines
4.8 KiB
Python

"""Schema-constrained JSON extraction on the local Ollama pool.
Every call goes to ``cfg.instruct_model`` (never the large tier — recorded
outputs name the model, so a bigger host appearing must not change it) with
Ollama's ``format`` set to a JSON schema, ``temperature 0``. The reply is
re-checked with :func:`validate`; an invalid reply is ``None``, never a guess.
"""
from __future__ import annotations
import json
import logging
from collections.abc import Callable, Mapping
from typing import Any
import httpx
log = logging.getLogger(__name__)
_TYPES: dict[str, Callable[[Any], bool]] = {
"object": lambda v: isinstance(v, dict),
"array": lambda v: isinstance(v, list),
"string": lambda v: isinstance(v, str),
"number": lambda v: isinstance(v, int | float) and not isinstance(v, bool),
"integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
"boolean": lambda v: isinstance(v, bool),
"null": lambda v: v is None,
}
def validate(obj: Any, schema: Mapping[str, Any], path: str = "$") -> list[str]:
"""Errors of *obj* against the JSON-schema subset used here (type, enum,
required, properties, items, maxLength, maxItems); ``[]`` when valid."""
errors: list[str] = []
if "type" in schema:
want = schema["type"]
names = [want] if isinstance(want, str) else list(want)
if not any(_TYPES[n](obj) for n in names):
return [f"{path}: expected {'|'.join(names)}, got {type(obj).__name__}"]
if "enum" in schema and obj not in schema["enum"]:
errors.append(f"{path}: {obj!r} not in enum")
if isinstance(obj, str) and len(obj) > schema.get("maxLength", len(obj)):
errors.append(f"{path}: longer than {schema['maxLength']}")
if isinstance(obj, dict):
errors += [
f"{path}.{k}: required" for k in schema.get("required", ()) if k not in obj
]
for key, sub in schema.get("properties", {}).items():
if key in obj:
errors += validate(obj[key], sub, f"{path}.{key}")
if isinstance(obj, list):
if len(obj) > schema.get("maxItems", len(obj)):
errors.append(f"{path}: more than {schema['maxItems']} items")
if "items" in schema:
for i, item in enumerate(obj):
errors += validate(item, schema["items"], f"{path}[{i}]")
return errors
class JsonExtractor:
"""``extractor(system, user, schema) -> dict | None`` bound to a pool."""
def __init__(
self, cfg: Any, pool: Any, post: Callable[..., dict] | None = None
) -> None:
from llm.classify import _default_post
self.model: str = cfg.instruct_model
self._cfg = cfg
self._pool = pool
self._send = post or _default_post
pool.check(cfg.instruct_model)
def __call__(
self, system: str, user: str, schema: Mapping[str, Any]
) -> dict | None:
pool = self._pool
while True:
with pool.acquire_generation() as host:
try:
data = self._send(
f"{host}/api/chat",
json={
"model": self.model,
"messages": [
{"role": "system", "content": system},
{"role": "user", "content": user},
],
"stream": False,
"format": dict(schema),
"options": {
"num_ctx": self._cfg.chat_num_ctx,
"temperature": 0,
},
},
)
except httpx.TransportError as exc:
pool.drop(host)
log.warning(
"extract: dropping %s after %s; %d host(s) left",
host,
exc,
len(pool.hosts),
)
if not pool.hosts:
raise RuntimeError(
f"every Ollama host failed; last {host}: {exc}"
) from exc
continue
break
reply = data.get("message", {}).get("content", "")
try:
obj = json.loads(reply)
except (ValueError, TypeError):
log.info("extract: non-JSON reply %.60r", reply)
return None
errors = validate(obj, schema)
if errors or not isinstance(obj, dict):
log.info("extract: schema violation %s", errors[:3])
return None
return obj
def json_extractor(
cfg: Any, pool: Any, *, post: Callable[..., dict] | None = None
) -> JsonExtractor:
return JsonExtractor(cfg, pool, post)