Ontologies for AI: Giving LLMs a Shared Vocabulary
Concepts, relations and definitions that stop models guessing what your business terms mean, from text-to-SQL to GraphRAG.

On this page
Ask three departments what "active customer" means and you'll get three answers. Ask a language model and you'll get a fourth, delivered with total confidence. An ontology is a written, shared definition of the things your business talks about, how they relate, and the rules they follow. It gives people and AI systems the same vocabulary, so a question like "which clients have unpaid bills?" means one precise thing.
What an ontology is
At its simplest, an ontology has four ingredients:
- Concepts (classes): the kinds of things that exist. Customer, Order, Invoice, Product.
- Properties: what you record about each. An Invoice has an amount and a due date.
- Relations: how concepts connect. An Order is billed by an Invoice; a Payment settles an Invoice.
- Rules and definitions: what the words mean exactly. An invoice is unpaid when no payment settles it and its due date has passed.
It sits alongside a few related ideas that are easy to mix up:
| Term | What it is | Example |
|---|---|---|
| Glossary | Words and their definitions | "Churn: a customer who cancels all contracts" |
| Taxonomy | A hierarchy of categories | Product › Hardware › Sensors |
| Ontology | Concepts, relations, properties and rules | Customer —places→ Order —billedBy→ Invoice |
| Knowledge graph | Real data organised by an ontology | Acme Ltd —places→ Order 1042 |
| Semantic layer | Metrics and dimensions mapped onto tables | revenue = sum(payment.amount) |
In practice the ontology is the model, the knowledge graph is the data shaped by that model, and the semantic layer is how the model connects to your warehouse.
Why language models need one
LLMs are trained on the whole internet's usage of words, not on your company's usage. Left alone, a model will interpret "revenue" as whatever revenue usually means. That might be billed amounts when finance means cash received, or it might include a region your sales team excludes. Every one of those guesses produces a believable, well-formatted, wrong number.
An ontology removes the guesswork in three ways:
- Disambiguation. Synonyms ("client", "buyer", "account") map to one concept with one definition.
- Navigation. Relations tell the system which path connects the concepts in a question, so it doesn't invent joins.
- Validation. Generated queries and answers can be checked against the model: does this concept exist, is this relation real, is this property of the right type?
Explore a small ontology below. Pick a question to see the concepts and relations it needs, and the query the mapping produces:
Note how much of the work happens in the definitions rather than in the graph. "Unpaid" and "revenue" are business decisions. Once they're written down, an AI system can apply them consistently. Until then, it can only guess.
Writing one down
You don't need specialised tooling to start. A version-controlled file in a readable format is enough, as long as it's the single source of truth:
concepts:
Customer:
definition: A legal entity with at least one signed contract. Prospects and trials are excluded.
synonyms: [client, buyer, account holder]
table: crm.customer
key: customer_id
properties:
segment: { type: enum, values: [smb, mid_market, enterprise] }
region_code: { type: enum, values: [AMER, EMEA, APAC], note: Sales territory, not shipping address }
Invoice:
definition: A billing document for exactly one order.
synonyms: [bill]
table: finance.invoice
properties:
amount: { type: money, currency_field: currency }
due_date: { type: date }
derived:
unpaid: No Payment settles it AND due_date < today
relations:
- { from: Customer, name: places, to: Order, cardinality: one-to-many, join: crm.customer.customer_id = sales.orders.customer_id }
- { from: Invoice, name: issuedTo, to: Customer, join: finance.invoice.customer_id = crm.customer.customer_id }
- { from: Payment, name: settles, to: Invoice, join: finance.payment.invoice_id = finance.invoice.invoice_id }
metrics:
revenue:
definition: Cash received, not amounts billed.
expression: sum(Payment.amount)If you later need formal reasoning (class hierarchies, inference, interoperability), the same content maps onto the W3C standards RDF and OWL. Most teams get most of the value long before that point.
Grounding text-to-SQL with the ontology
The biggest practical payoff is in natural-language questions over data. Instead of giving the model your raw schema (hundreds of cryptic columns) and hoping, give it the ontology: concepts, definitions, relations and approved metrics. Then validate what comes back.
import sqlglot
from sqlglot import exp
def ontology_context(onto, question):
relevant = onto.concepts_mentioned_in(question) # synonym match plus embedding search over definitions
lines = []
for c in onto.expand_with_neighbours(relevant):
lines.append(f"{c.name} ({c.table}): {c.definition}")
lines += [f" - {p}: {spec}" for p, spec in c.properties.items()]
lines += [f"Relation {r.from_} -{r.name}-> {r.to}: JOIN ON {r.join}" for r in onto.relations_between(relevant)]
lines += [f"Metric {m.name}: {m.expression} ({m.definition})" for m in onto.metrics_mentioned_in(question)]
return "\n".join(lines)
def validate_sql(sql, onto):
tree = sqlglot.parse_one(sql, read="postgres")
tables = {f"{t.db}.{t.name}" if t.db else t.name for t in tree.find_all(exp.Table)}
unknown = tables - onto.allowed_tables()
if unknown:
raise ValueError(f"Query uses tables outside the ontology: {sorted(unknown)}")
if not isinstance(tree, exp.Select):
raise ValueError("Only read-only SELECT queries are allowed")
return sqlThe context is small (only the concepts the question touches) and every term in it is defined. The validator makes sure the model stayed inside the map. Run the query with a read-only database role regardless: validation reduces mistakes, while permissions prevent damage.
Ontologies, knowledge graphs and RAG
Ontologies also improve document retrieval. When chunks are tagged with the concepts they mention, and those concepts are linked in a graph, retrieval can follow relationships rather than relying on text similarity alone. A question about a customer's contract terms can pull in the master agreement that governs their orders, even though the question never mentions it. This family of techniques is often called GraphRAG. It's most valuable when answers depend on connections between documents rather than on a single passage.
Starting small
Ontology projects fail when they try to model the whole enterprise up front. A path that works:
- Collect real questions that people ask (or that your AI assistant gets wrong). Fifty is plenty.
- Model only the concepts those questions need. Usually 10 to 20.
- Write definitions with the people who own them. Finance defines revenue; sales defines territory.
- Wire it into one use case, such as text-to-SQL for a single team, and measure accuracy before and after.
- Grow it from failures. Every wrong answer points at a missing concept, synonym or rule.