Agentic Ontologist

API

API reference

Public classes, supported types, extension points, examples, and direct links to their implementations.

agentic_ontologist.workspace

OntologyWorkspace

High-level interface for loading one local ontology, retrieving concepts, and asking ontology-grounded questions.

OntologyWorkspace(
    path: str | Path,
    *,
    format: str | None = None,
    refine: bool = False,
)
MethodReturnsPurpose
summaryOntologySummaryPath, format, ontology name, version, concept count, and relation count.
prepare()ConceptGraphBuild and embed the graph once, then cache it.
search(query, *, top_k=10)list[dict[str, Any]]Retrieve concepts without invoking an LLM.
ask(query, *, top_k=10, model=None, temperature=0.2, save_traces=False, harness=None, web_passages=None)strGenerate an answer from retrieved context. An optional harness can select that context.
from agentic_ontologist.workspace import OntologyWorkspace

workspace = OntologyWorkspace("ontology.owl", refine=True)
matches = workspace.search("freshwater temperature", top_k=8)
answer = workspace.ask("Which concepts describe freshwater temperature?")

After the exact question hash misses, a checksum of three-word shingles on each remembered answer can name the last concept on that path and skip retrieval. The overlap must be at least 0.75 and lead the next answer by 0.15. A single misspelled word can still match. A question with fewer than 4 shingles continues into the Harness. signature.py

OWL/RDF pathNatural languageCached graph View source →

agentic_ontologist.parser

Parser

Format-selecting facade over RDF, JSON, and relation-text adapters.

Parser(
    filepath: str | Path,
    config_path: str | Path | None = None,
    name: str | None = None,
    version: str | None = None,
    *,
    config: ParserConfig | None = None,
    format: str | InputFormat | None = None,
)
Supported inputExtensions / valuesAdapter
RDF/XML and OWL.owl, .rdf, .xml, xmlRDFParser
Turtle and N3.ttl, .n3, turtle, n3RDFParser
RDF datasets.nt, .trig, .trix, .jsonldRDFParser
Structured JSON.jsonJSONParser
Relation text.txtTextParser
Compression.gz, .bz2Detected from the preceding suffix
from agentic_ontologist.parser import Parser

ontology = Parser("domain.ttl", name="domain", version="1.0").to_ontology()
triples = Parser("domain.owl").extract_triples()

Parser source → Format definitions →

agentic_ontologist.algorithms.graph

Graph data model

ClassRoleSource
ConceptOntology concept with labels, synonyms, definitions, and typed adjacency.concept.py
ConceptRelationDirected predicate between two concepts.concept.py
OntologyMutable concept and relation collection with union, noise, serialization, and lookup operations.ontology.py
EquivalentClassOne or more semantically equivalent concepts represented as a graph node.equivalence.py
ConceptGraphPairwise equivalent-class graph with embedding search and rank computation.concept_graph.py
ConceptHypergraphHyperedge representation with pairwise projection for embeddings and retrieval.hypergraph.py
OntologyStructureBuilderShared builder for graph representations.builder.py
from agentic_ontologist.algorithms.graph import ConceptGraph
from agentic_ontologist.parser import Parser

ontology = Parser("domain.owl").to_ontology()
graph = ConceptGraph(nodes=[], edges=[])
graph.build_from_ontology(ontology)
graph.compute_all_embeddings(alpha=0.5)
neighbors = graph.nearest_nodes("material fatigue", k=10)

agentic_ontologist.algorithms.refinement

Ontology refinement

ClassSignature / behaviorSource
OntologyRefinerrefine(ontology, options=None, *, fallback_if_expanded=False) -> Ontology
Rule-based relation and ontology rebuilding.
ontology.py
OfflineGraphRefinerrefine(graph) -> ConceptGraph
Complete-graph partition refinement and safe bisimilar collapse.
offline.py
OnlineOntologyRefinerrefine(graph, updates, *, copy_graph=True) -> OnlineRefinementResult
Rank-aware streamed maintenance with applied and deferred updates.
online.py
GraphUpdateTyped source, target, relation, score, confidence, and optional semantic judgment.online.py
RelationRefinerConfigurable rule pipeline returning structured diagnostics.pipeline.py
from agentic_ontologist.algorithms.refinement import (
    GraphUpdate,
    OfflineGraphRefiner,
    OnlineOntologyRefiner,
)

offline = OfflineGraphRefiner(concept_similar=my_semantic_predicate)
collapsed = offline.refine(graph)

online = OnlineOntologyRefiner(
    concept_similar=my_semantic_predicate,
    confidence_threshold=8.5,
)
result = online.refine(collapsed, [GraphUpdate(source, target, confidence=9.2)])
print(result.applied_updates, result.deferred_updates)

agentic_ontologist.embeddings

Embeddings and vector indexes

APISupported behaviorSource
TextEmbedding(model_name="Qwen/Qwen3-Embedding-0.6B", device=None)Replaceable text encoder backed by Sentence Transformers.text.py
GraphEmbedding(..., dimensions=128, **node2vec_options)Node2Vec graph encoder for concept graphs and projected hypergraphs.graph.py
fuse_embeddings(...)Validated weighted graph/text vector fusion.fusion.py
TorchExactVectorIndex(dimension=None)Built-in deterministic cosine index with ID filtering.torch_exact.py
BaseVectorIndexAdapter base for ANN, DiskANN, or vector-database integrations.base.py
register_vector_index(name, factory)Register a named backend used by create_vector_index.registry.py

Built in: torch-exact. ANN, DiskANN, and vector-database backends are supported as adapters but are not bundled implementations.

from agentic_ontologist.retrieval import create_vector_index, register_vector_index

index = create_vector_index("torch-exact", dimension=768)
index.add(ids, vectors, metadata)
results = index.search(query_vector, k=10)

agentic_ontologist.retrieval

Retrieval providers

ProviderNetworkConfiguration
staticNoIn-memory deterministic counts.
datasetNoCounts supplied by a local dataset.
mediawikiYesLanguage and Wikimedia project.
google-cseYesGOOGLE_API_KEY and GOOGLE_CSE_CX.
from agentic_ontologist.retrieval import (
    create_web_search,
    describe_web_search,
    register_web_search,
)

provider = create_web_search("mediawiki", lang="en", project="wikipedia")
print(describe_web_search("mediawiki"))
count = provider.search_count("ontology matching")

Retrieval source → Plugin example →

Harness

One small model answers typed questions about the current question and the last few turns of this chat. The call is SGLang POST /v1/systemone at http://127.0.0.1:30000 (AGONTO_HARNESS_URL). An empty value keeps the Ollama router, ollama:phi3. A local policy reads those answers and chooses replay or retrieve. The choice list stays at 26 options, including retrieve. The reasoner is the only model that writes the answer, and it stays the chat model.

TypeReturnsUsed for
Choicechoice, probabilities, confidenceWhich cached question this one matches, or retrieve.
Scorescore, probabilities, confidenceHow close the wording is, from different to the same question.
NoulA probability from 0 to 1Whether the intent is the same, and whether this turn continues the previous one.

Replay happens when the choice names a cached question, or when same-intent is at least 0.8, the score is “Same question,” and one cached question is the nearest choice. A failed call falls open to retrieve. A follow-up hangs under the previous question when the continuation probability is at least 0.8. A new topic hangs from a virtual root. Under each question the trie records the route, the ontology concept ids, and the answer. That trie is this chat only. The answer cache stays the memory shared across chats.

Jev model routing (AGONTO_MODEL_ROUTING=jev) and the Jev context harness (AGONTO_CONTEXT_HARNESS=jev) stay optional extras. They are separate from this call.

Context harness

Retrieval remains responsible for recall. The harness decides which retrieved concepts, neighbors, and web passages enter the prompt.

ClassBehaviorSource
PassthroughHarnessReturns the original shortlist. This is the default.context.py
JevContextHarnessUses Jev contextual scoring to filter and rerank. Shadow mode records the proposal while still returning the original shortlist.context.py
create_context_harness(name=None)Reads AGONTO_CONTEXT_HARNESS. jev starts in shadow mode unless AGONTO_CONTEXT_MODE=live.context.py
from agentic_ontologist.retrieval import JevContextHarness

harness = JevContextHarness(shadow=True, min_relevance=0.2)
answer = workspace.ask(question, harness=harness)
print(workspace.last_context_selection.metrics())

Jev is optional: uv sync --extra jev and JEV_API_KEY. Query text, concept labels, and web snippets are sent to TypeSafe. If the key is missing or Jev fails, the harness fails open and returns the original shortlist.

agentic_ontologist.agents

Agent runtime

Class / functionPurposeSource
AgentModel invocation, registered tool execution, events, traces, and optional persistence.agent.py
JevModelRouterAsks Jev one choice question and selects local, standard, or careful for the rest of the run. Unavailable Jev fails open to the current model.decisions.py
ToolRiskGateAsks Jev whether a configured tool call is unsafe. A probability at or above the threshold returns a refusal and does not call the tool.decisions.py
create_oot_enhanced_agent(...)Construct an agent with Ontology-of-Thought observation.oot.py
ThoughtGraphStructured thought representation and query-node optimization.graph.py
QueryOptimizerHumanGS-style candidate selection over thought graphs.optimizer.py
Trace, TraceStepTyped execution trace records.trace.py
from agentic_ontologist.agents import Agent, JevModelRouter, ToolRiskGate

agent = Agent(
    llm,
    model_router=JevModelRouter(),
    tool_gate=ToolRiskGate(threshold=0.5),
    save_local=True,
)
response = agent.invoke("Find the closest ontology concept.")
run = agent.invoke("Explain the match.", return_trace=True)

Model routing

create_model_router() returns a router when AGONTO_MODEL_ROUTING=jev. It asks one choice question, then Agent.invoke uses the selected model for that run.

RouteCriterionModel
localShort lookups, extraction, and questions answerable from retrieved ontology context.AGONTO_ROUTE_LOCAL, default ollama:phi3
standardNormal ontology question answering and relation lookup.AGONTO_ROUTE_STANDARD, default LLM_MODEL
carefulAlignment disputes, conflicts, refinement, or multi-ontology reasoning.AGONTO_ROUTE_CAREFUL, default LLM_MODEL

The model_route step and the llm_invoke step store name, model_name, probabilities, confidence, fail_open, and error. The same payload is emitted as model.routed for Ontology-of-Thought. If Jev is unavailable, the run fails open to the current model.

Tool-risk gating

create_tool_gate() returns a gate when AGONTO_TOOL_GATE=jev. It runs after tool.parsed and before tool execution. The default gated tools are search_term_context and search_knowledge_graph. Override them with AGONTO_GATED_TOOLS. ontology_term_info is not gated.

Jev returns the probability that the call is unsafe. A value at or above AGONTO_TOOL_RISK_THRESHOLD (default 0.5) becomes the tool result:

{"blocked": true, "tool_name": "search_term_context", "reason": "...", "risk": 0.92}

The tool function is not called. The tool_execute step status is blocked, and Ontology-of-Thought receives tool.blocked. Arguments are passed through redact before the request. Query text and those redacted arguments are still sent to TypeSafe. When the gate is enabled and Jev cannot decide, that gated call fails closed. A disabled gate leaves every tool call unchanged.

agentic_ontologist.validation

Validation

APIInput → outputSource
evaluate_alignment(expected, predicted)Alignment pairs → AlignmentMetrics.metrics.py
ValidationPipelineTuples → normalization, evaluation, and optional ontology translation.pipeline.py
TupleEvaluatorSequence[str] → TupleEvaluation.tuples.py
validate_matches(...)Candidate matches → ValidationReport.rules.py
agonto-lintOntology file → terminal diagnostics and process status.ontology_lint.py

agentic_ontologist.prompting

Prompt construction

OntologyEquivalencePromptBuilder(
    config: PromptConfig | None = None,
).build(source: object, target: object) -> str
from agentic_ontologist.prompting import (
    OntologyEquivalencePromptBuilder,
    parse_equivalence_answer,
)

prompt = OntologyEquivalencePromptBuilder().build(source, target)
decision = parse_equivalence_answer(model.invoke(prompt).content)

View source →

agentic_ontologist.uq

Uncertainty quantification

ScorerDependencyUse
AgreementConfidenceScorerCoreDependency-free agreement over repeated responses.
UQLMConfidenceScoreragentic-ontologist[uq]Black-box UQLM confidence.
GraphConfidenceScoreragentic-ontologist[uq]Graph-based UQLM scoring.
EnsembleConfidenceScoreragentic-ontologist[uq]Weighted multi-scorer confidence.
from agentic_ontologist.uq import AgreementConfidenceScorer

scorer = AgreementConfidenceScorer(llm=llm, num_responses=5)
answer, confidence, scores = scorer.score_prompt(prompt)

View source →

Public import surfaces

Prefer package-level imports such as agentic_ontologist.parser, agentic_ontologist.algorithms.graph, agentic_ontologist.algorithms.refinement, agentic_ontologist.embeddings, agentic_ontologist.retrieval, agentic_ontologist.validation, agentic_ontologist.prompting, agentic_ontologist.uq, and agentic_ontologist.agents. Their __all__ declarations define supported public APIs.