ontology-guided-retrieval
Ontology-aware RAG. Leveraging domain ontologies (SNOMED CT, FIBO, schema.org, Gene Ontology, custom OWL) to expand queries with synonyms, hyponyms, and…
от claude-dev-suite★ 51 звезда на GitHub
Установить ontology-guided-retrieval в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Ontology-Guided Retrieval
Vector RAG treats every chunk as an island of text. Ontologies bring structure: ibuprofen is-a NSAID is-a analgesic; USD has-currency-code 840; Software Engineer broader Engineer. Folding these relations into retrieval unlocks precision gains (exact concept matching) and recall gains (synonym and hyponym expansion) that vector-only systems can't match.
When to Use
- Regulated domains with authoritative ontologies: healthcare (SNOMED CT, ICD-10, LOINC, RxNorm), finance (FIBO, GLEIF), biology (GO, ChEBI, UniProt), legal (LKIF, EuroVoc).
- You already have a taxonomy (product categories, industry codes NAICS/SIC) you want to respect.
- Queries use jargon that must map to canonical concepts for compliance or downstream systems.
Not worth it for: general-purpose consumer chat, corpora with no natural taxonomy.
Ontology Formats
| Format | Purpose | Tools |
|---|---|---|
| OWL 2 | Formal ontology with classes, properties, axioms | Protégé, owlready2 |
| RDFS | Lightweight: classes + subClassOf + labels | rdflib |
| SKOS | Taxonomies: broader, narrower, related, prefLabel, altLabel | rdflib, skosmos |
| schema.org | Structured markup vocabulary | json-ld, rdflib |
| JSON-LD | JSON serialization of RDF | pyld, rdflib |
Most useful SKOS relations:
prefLabel— canonical name.altLabel— synonyms.broader/narrower— IS-A-ish hierarchy.related— lateral association.
Loading an Ontology with rdflib
from rdflib import Graph, Namespace, URIRef
from rdflib.namespace import SKOS, RDF, RDFS
g = Graph()
g.parse("snomed-subset.ttl", format="turtle") # or .owl, .rdf, .nt
# All narrower concepts of "Infectious disease"
q = """
SELECT ?c ?label WHERE {
?c skos:broader* <http://snomed.info/id/40733004> ;
skos:prefLabel ?label .
}
"""
for row in g.query(q, initNs={"skos": SKOS}):
print(row.c, row.label)
Owlready2 for OWL Reasoning
# pip install owlready2
from owlready2 import get_ontology, sync_reasoner_pellet
onto = get_ontology("fibo.owl").load()
sync_reasoner_pellet(infer_property_values=True)
for cls in onto.classes():
print(cls.iri, list(cls.label), list(cls.ancestors()))
Reasoning materializes inferred subClassOf and property chains — use it once at ingest time, then query the materialized graph (don't reason at query time in RAG's hot path).
Query Expansion via Ontology
Given a user query containing ontology-matched terms, expand with synonyms, hyponyms, and broader parents.
def expand_terms(term: str, g: Graph) -> dict:
q = """
SELECT ?syn ?narrower ?broader WHERE {
?c skos:prefLabel|skos:altLabel ?t .
FILTER (LCASE(STR(?t)) = LCASE(?input))
OPTIONAL { ?c skos:altLabel ?syn }
OPTIONAL { ?n skos:broader ?c ; skos:prefLabel ?narrower }
OPTIONAL { ?c skos:broader ?b . ?b skos:prefLabel ?broader }
}
"""
syn, narrower, broader = set(), set(), set()
for r in g.query(q, initNs={"skos": SKOS}, initBindings={"input": term}):
if r.syn: syn.add(str(r.syn))
if r.narrower: narrower.add(str(r.narrower))
if r.broader: broader.add(str(r.broader))
return {"synonyms": list(syn), "hyponyms": list(narrower), "hypernyms": list(broader)}
Generate an expanded query for retrieval:
def build_expanded(query: str, matched_terms: list[str]) -> list[str]:
variants = [query]
for term in matched_terms:
x = expand_terms(term, g)
for syn in x["synonyms"]:
variants.append(query.replace(term, syn))
for hyp in x["hyponyms"]: # narrower terms retrieve more specific docs
variants.append(query.replace(term, hyp))
return variants
Then dense-retrieve each variant and union/dedup results.
Concept Matching in Queries
Identifying which ontology concepts appear in a query:
- Lexicon + lookup (fast): build a radix tree of all
prefLabel+altLabel; longest-match tokenization. - SciSpaCy / MedCAT (medical): pretrained entity linkers to UMLS/SNOMED.
- LLM + few-shot: for rare terms, ask an LLM to output ontology IDs given candidate concepts.
# MedCAT example for SNOMED
from medcat.cat import CAT
cat = CAT.load_model_pack("/path/to/medcat-snomed-modelpack.zip")
doc = cat.get_entities("Patient presents with NSTEMI and raised troponin.")
for ent in doc["entities"].values():
print(ent["source_value"], ent["cui"], ent["pretty_name"])
Ontology-Boosted Retrieval
After detecting ontology concepts, boost chunks that mention the same concept IDs.
def retrieve_with_boost(query: str, concept_ids: list[str], top_k=20):
vec_hits = vectorstore.similarity_search_with_score(query, k=top_k*3)
boosted = []
for doc, score in vec_hits:
overlap = len(set(doc.metadata.get("concept_ids", [])) & set(concept_ids))
boosted.append((doc, score - 0.05 * overlap)) # lower score = be
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
- 01
Read - 02
Grep - 03
Glob - 04
Write - 05
Edit
FAQ
Что делает скилл ontology-guided-retrieval?
Ontology-aware RAG. Leveraging domain ontologies (SNOMED CT, FIBO, schema.org, Gene Ontology, custom OWL) to expand queries with synonyms, hyponyms, and broader concepts; boost retrieval for ontology-matched entities; hybrid SPARQL + vector pipelines; RDFLib + embeddings. Examples with medical and financial ontologies. USE WHEN: user mentions "ontology", "SNOMED", "FIBO", "schema.org", "OWL", "SKOS", "RDF", "SPARQL RAG", "taxonomy-guided", "concept expansion", "hyponym retrieval" DO NOT USE FOR: building a KG from text - use `knowledge-graph-construction`; deduping entities - use `entity-resolution`; generic graph RAG - use `graph-rag`
Как установить скилл ontology-guided-retrieval?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ontology-guided-retrieval запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
AnthropicToolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
access
AnthropicManage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
configure
AnthropicSet up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
access
AnthropicManage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…