Skip to content

ontocast.agent.render_ontology

Ontology triple rendering agent for OntoCast.

Structured hybrid renderer: bare Turtle for fresh ontologies, GraphUpdate patches for complementing an existing snapshot.

Attributes

RENDER_SKIPPED_REUSE_ONLY = 'ontology/render_skipped_reuse_only' module-attribute

logger = logging.getLogger(__name__) module-attribute

Classes

Functions:

format_plan_instruction(plan)

The plan block of a unit's render prompt; empty without a plan.

Source code in ontocast/agent/render_ontology.py
def format_plan_instruction(plan: OntologyPlan | None) -> str:
    """The plan block of a unit's render prompt; empty without a plan."""
    if plan is None or not plan.terms:
        return ""
    prefixes = plan.prefixes

    def curie(iri: str) -> str:
        return compact_iri(iri, prefixes)

    def side(iri: str | None) -> str:
        return f"`{curie(iri)}`" if iri else "?"

    minted_lines = []
    for term in plan.minted():
        parts = [f"- `{curie(term.iri)}` | {term.kind} | {term.label}"]
        if term.parent_iri:
            parts.append(f"parent `{curie(term.parent_iri)}`")
        if term.domain_iri or term.range_iri:
            parts.append(
                f"domain {side(term.domain_iri)} → range {side(term.range_iri)}"
            )
        if term.definition:
            parts.append(term.definition)
        if term.nearest:
            near = ", ".join(f"`{curie(iri)}`" for iri, _ in term.nearest)
            parts.append(f"near existing {near}")
        minted_lines.append(" | ".join(parts))
    reuse_lines = [
        f'- `{curie(term.iri)}` for "{term.label}"' for term in plan.reused()
    ]
    return plan_instruction_template.format(
        minted_lines="\n".join(minted_lines) or "- (none: reuse only)",
        reuse_block=(
            plan_reuse_block.format(reuse_lines="\n".join(reuse_lines))
            if reuse_lines
            else ""
        ),
    )

plan_is_reuse_only(plan)

Whether a document's plan names terms and mints none of them.

A plan without terms (none proposed, or all refused) does not count: the render then works without a plan block and may still mint.

Source code in ontocast/agent/render_ontology.py
def plan_is_reuse_only(plan: OntologyPlan | None) -> bool:
    """Whether a document's plan names terms and mints none of them.

    A plan without terms (none proposed, or all refused) does not count: the
    render then works without a plan block and may still mint.
    """
    return plan is not None and bool(plan.terms) and not plan.minted()

render_ontology(state, tools, supplemental_ontologies=None) async

Structured hybrid ontology renderer: fresh Turtle or structured graph updates.

Source code in ontocast/agent/render_ontology.py
async def render_ontology(
    state: UnitOntologyState,
    tools: AtomicToolBox,
    supplemental_ontologies: Sequence[Ontology] | None = None,
) -> UnitOntologyState:
    """Structured hybrid ontology renderer: fresh Turtle or structured graph updates."""

    progress_info = state.get_content_unit_progress_string()
    logger.info(
        f"Ontology Renderer for {progress_info}: visit {state.node_visits[WorkflowNode.TEXT_TO_ONTOLOGY]}/{state.max_visits_per_node}"
    )
    access = ontology_access_for_unit_ontology(state)
    has_seed = access.has_non_empty_seed()
    extras = list(supplemental_ontologies or ())
    if not has_seed:
        return await render_ontology_fresh(state, tools, supplemental_ontologies=extras)
    return await render_ontology_update(state, tools, supplemental_ontologies=extras)

render_ontology_fresh(state, tools, supplemental_ontologies=None) async

Render the unit's terms under the document's home ontology (empty seed).

The identity was resolved once for the document; this renders terms only and mints the root artifact from them.

Raises:

Type Description
RuntimeError

the unit has no home ontology to mint under.

Source code in ontocast/agent/render_ontology.py
async def render_ontology_fresh(
    state: UnitOntologyState,
    tools: AtomicToolBox,
    supplemental_ontologies: Sequence[Ontology] | None = None,
) -> UnitOntologyState:
    """Render the unit's terms under the document's home ontology (empty seed).

    The identity was resolved once for the document; this renders terms only
    and mints the root artifact from them.

    Raises:
        RuntimeError: the unit has no home ontology to mint under.
    """

    identity = state.home_ontology
    if identity is None:
        raise RuntimeError(
            "render_ontology_fresh needs the document's home ontology; "
            "resolve it before the ontology fan-out"
        )
    profile = get_graph_format_profile(
        state.llm_graph_format, output_layout=state.llm_output_layout
    )
    parser = PydanticOutputParser(pydantic_object=FreshOntologyRenderReport)
    logger.info("Rendering fresh ontology %s", identity.iri)
    intro_instruction = intro_instruction_fresh.format(
        ontology_id=identity.ontology_id,
        title=identity.title,
        description=identity.description,
        namespace=identity.namespace,
        prefix=tools.prefix_table().prefix_or_claim(
            identity.namespace, identity.ontology_id
        ),
    )
    output_instruction = profile.render_fresh_output_instruction(target="ontology")
    ontology_ttl = ""
    improvement_instruction_str = ""
    access = ontology_access_for_unit_ontology(state)
    web_search_enabled = tools.web_grounding_enabled_for_node(
        WorkflowNode.TEXT_TO_ONTOLOGY
    )
    (
        general_ontology_instruction_str,
        text_chapter,
        external_evidence,
    ) = _prepare_ontology_common_prompt_layers(
        state,
        access,
        search_guidelines=search_guidelines_for(
            WorkflowNode.TEXT_TO_ONTOLOGY, web_search_enabled
        ),
    )

    prompt = _create_ontology_render_prompt_template()
    known_prefixes = build_llm_prefix_map(
        access.ontology_graph_for_prefixes(),
        supplemental_ontologies or (),
        tools.prefix_table(),
    )
    known_prefixes[identity.ontology_id] = identity.namespace

    previous_prefixes = RDFGraph.get_known_prefixes()
    try:
        RDFGraph.set_known_prefixes(known_prefixes)
        llm_tool = await tools.get_llm_tool(state.budget_tracker)
        render_report: FreshOntologyRenderReport = await call_llm_with_retry(
            llm_tool=llm_tool,
            phase=LLMPhase.ONTOLOGY_RENDER,
            prompt=prompt,
            parser=parser,
            prompt_kwargs={
                "preamble": system_preamble,
                "intro_instruction": intro_instruction,
                "ontology_instruction": general_ontology_instruction_str,
                "plan_instruction": format_plan_instruction(state.ontology_plan),
                "output_instruction": output_instruction,
                "ontology_ttl": ontology_ttl,
                "user_instruction": state.ontology_user_instruction,
                "improvement_instruction": improvement_instruction_str,
                "text": text_chapter,
                "external_evidence": external_evidence,
                "format_instructions": profile.format_instructions(
                    FreshOntologyRenderReport,
                    web_search_enabled=web_search_enabled,
                ),
            },
            llm_graph_format=state.llm_graph_format,
        )
        persist_search_request(
            state,
            WorkflowNode.TEXT_TO_ONTOLOGY,
            render_report.external_evidence_request,
            web_search_enabled,
        )
        graph = render_report.graph
        graph.sanitize_prefixes_namespaces()
        graph, _ = repair_schema_iri_literals(graph)
        header_triples = sum(
            1
            for s, _, _ in graph.triples((None, RDF.type, OWL.Ontology))
            for _ in graph.triples((s, None, None))
        )
        if header_triples:
            state.budget_tracker.incr(
                "ontology/model_header_triples_dropped", header_triples
            )
        ontology = mint_ontology(identity, graph)
        state.fresh_ontology = ontology
        state.working_graph = ontology.graph.copy()
        state.writable_iris = [ontology.iri]
        state.assembly_anchor_iri = ontology.iri

        num_triples = len(state.working_graph)
        logger.info(f"New ontology created with {num_triples} triple(s).")

        state.budget_tracker.add_ontology_update(
            num_operations=1, num_triples=num_triples
        )

        state.clear_failure()
        state.set_node_status(WorkflowNode.TEXT_TO_ONTOLOGY, Status.SUCCESS)
        return state

    except RUN_STOPPING_ERRORS:
        # The provider rejects the request itself, not this attempt at
        # it: every other unit is about to be rejected identically.
        # Failing one unit here turns a configuration fault into an
        # empty run that reports success.
        raise
    except Exception as e:
        return _handle_ontology_render_error(
            state, e, FailureStage.GENERATE_TTL_FOR_ONTOLOGY
        )
    finally:
        RDFGraph.set_known_prefixes(previous_prefixes)

render_ontology_update(state, tools, supplemental_ontologies=None) async

Complement an existing snapshot via GraphUpdate inserts.

Source code in ontocast/agent/render_ontology.py
async def render_ontology_update(
    state: UnitOntologyState,
    tools: AtomicToolBox,
    supplemental_ontologies: Sequence[Ontology] | None = None,
) -> UnitOntologyState:
    """Complement an existing snapshot via GraphUpdate inserts."""

    state.quarantined_literal_triples = []
    profile = get_graph_format_profile(
        state.llm_graph_format, output_layout=state.llm_output_layout
    )
    parser = PydanticOutputParser(pydantic_object=GraphUpdateRenderReport)
    access = ontology_access_for_unit_ontology(state)
    home = state.home_ontology
    intro_instruction = _build_update_intro(
        state,
        access,
        tools.prefix_table().prefix_or_claim(home.namespace, home.ontology_id)
        if home is not None
        else None,
    )
    ontology_chapter = profile.format_ontology_chapter(
        access.effective_graph_for_prompt(),
        max_triples=state.ontology_context_max_triples,
    )
    output_instruction = profile.render_update_output_instruction()
    improvement_instruction_str = render_suggestions_prompt(
        state.suggestions, WorkflowNode.TEXT_TO_ONTOLOGY
    )

    web_search_enabled = tools.web_grounding_enabled_for_node(
        WorkflowNode.TEXT_TO_ONTOLOGY
    )
    (
        general_ontology_instruction_str,
        text_chapter,
        external_evidence,
    ) = _prepare_ontology_common_prompt_layers(
        state,
        access,
        search_guidelines=search_guidelines_for(
            WorkflowNode.TEXT_TO_ONTOLOGY, web_search_enabled
        ),
    )

    prompt = _create_ontology_render_prompt_template()
    known_prefixes = build_llm_prefix_map(
        access.ontology_graph_for_prefixes(),
        supplemental_ontologies or (),
        tools.prefix_table(),
    )
    if state.home_ontology is not None:
        # The plan block and the intro name home terms by this prefix; unbound,
        # the model guesses a namespace for it.
        home = state.home_ontology
        prefix = tools.prefix_table().prefix_or_claim(home.namespace, home.ontology_id)
        known_prefixes[prefix] = home.namespace

    previous_prefixes = RDFGraph.get_known_prefixes()
    try:
        llm_tool = await tools.get_llm_tool(state.budget_tracker)
        RDFGraph.set_known_prefixes(known_prefixes if known_prefixes else None)

        render_report: GraphUpdateRenderReport
        if plan_is_reuse_only(state.ontology_plan):
            # The plan mints nothing for this document, so the render may only
            # restate terms that exist already: it is answered with the empty
            # patch such a render returns, and no call is made.
            render_report = GraphUpdateRenderReport()
            state.budget_tracker.incr(RENDER_SKIPPED_REUSE_ONLY)
        else:
            render_report = await call_llm_with_retry(
                llm_tool=llm_tool,
                phase=LLMPhase.ONTOLOGY_RENDER,
                prompt=prompt,
                parser=parser,
                prompt_kwargs={
                    "preamble": system_preamble,
                    "intro_instruction": intro_instruction,
                    "ontology_instruction": general_ontology_instruction_str,
                    "plan_instruction": format_plan_instruction(state.ontology_plan),
                    "output_instruction": output_instruction,
                    "improvement_instruction": improvement_instruction_str,
                    "ontology_ttl": ontology_chapter,
                    "user_instruction": state.ontology_user_instruction,
                    "text": text_chapter,
                    "external_evidence": external_evidence,
                    "format_instructions": profile.format_instructions(
                        GraphUpdateRenderReport,
                        web_search_enabled=web_search_enabled,
                    ),
                },
                llm_graph_format=state.llm_graph_format,
            )
        persist_search_request(
            state,
            WorkflowNode.TEXT_TO_ONTOLOGY,
            render_report.external_evidence_request,
            web_search_enabled,
        )
        # The insert hook repairs only schema-predicate IRIs written as strings;
        # the facts repairs are instance-level and have no ontology counterpart.
        # The deterministic validator runs in the loop, against the net delta --
        # see stategraph/atomic.py::_collect_ontology_findings.
        if tools.ontology_insert_only and len(render_report.delete_graph):
            state.budget_tracker.incr(
                "ontology/deletes_dropped_insert_only",
                len(render_report.delete_graph),
            )
            render_report.delete_graph = RDFGraph()
        graph_update, rejected, dropped = finalize_update_report(
            render_report, insert_hook=repair_schema_iri_literals
        )
        state.applied_repairs.extend(dropped)
        state.quarantined_literal_triples = rejected
        log_quarantine("Ontology", rejected)
        state.ontology_updates.append(graph_update)
        applied = state.update_ontology()
        if not applied:
            # The ONTOLOGY_MAX_TRIPLES backstop discarded the whole update, so
            # this render changed nothing. Returning SUCCESS with an
            # unchanged graph is not a lie the run can see, and a validator run
            # afterwards would inspect the *previous* graph and report it clean.
            # The status stays SUCCESS -- the pre-update graph is intact and a
            # re-render would hit the same ceiling -- but the discard is counted.
            logger.warning(
                "Ontology update discarded: applying it would exceed "
                "ONTOLOGY_MAX_TRIPLES=%s. The render was sent and had no "
                "effect on the working graph.",
                state.ontology_max_triples,
            )
            state.budget_tracker.incr("ontology/update_rejected_over_budget")
        # Suggestions are consumed by exactly the render they were raised
        # against. Leaving them set carried them into every later render of the
        # unit -- the leak that put two contradictory contracts in one facts
        # prompt (see CHANGELOG [Unreleased]); the ontology path had the same
        # defect and no repair pass to notice it.
        state.suggestions = Suggestions()
        # Findings were consumed by this render; the loop re-collects fresh.
        state.deterministic_findings = []

        num_operations, num_triples = graph_update.count_total_triples()
        logger.info(
            f"Ontology update has {num_operations} operation(s) "
            f"with {num_triples} total triple(s)."
        )

        state.budget_tracker.add_ontology_update(num_operations, num_triples)

        state.clear_failure()
        state.set_node_status(WorkflowNode.TEXT_TO_ONTOLOGY, Status.SUCCESS)
        return state

    except RUN_STOPPING_ERRORS:
        # The provider rejects the request itself, not this attempt at
        # it: every other unit is about to be rejected identically.
        # Failing one unit here turns a configuration fault into an
        # empty run that reports success.
        raise
    except Exception as e:
        return _handle_ontology_render_error(
            state, e, FailureStage.GENERATE_GRAPH_UPDATE_FOR_ONTOLOGY
        )
    finally:
        RDFGraph.set_known_prefixes(previous_prefixes)

repair_schema_iri_literals(graph)

Coerce compact IRIs written as strings on schema predicates into IRIs.

Under the JSON-LD wire a bare string ("rdfs:subClassOf": "ex:Bar") parses as a literal. On the predicates above an IRI is the only legal object, so a plain compact-IRI literal with a bound prefix is rewritten; anything else is left as it is. Usable as an insert_hook.

Source code in ontocast/agent/render_ontology.py
def repair_schema_iri_literals(
    graph: RDFGraph,
) -> tuple[RDFGraph, list[RejectedLiteralTriple]]:
    """Coerce compact IRIs written as strings on schema predicates into IRIs.

    Under the JSON-LD wire a bare string (``"rdfs:subClassOf": "ex:Bar"``)
    parses as a literal. On the predicates above an IRI is the only legal
    object, so a plain compact-IRI literal with a bound prefix is rewritten;
    anything else is left as it is. Usable as an ``insert_hook``.
    """
    repair_compact_iri_literals(graph, _SCHEMA_IRI_PREDICATE_GRAPH, set())
    return graph, []