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.

Knowledge ModelingBy Fahim Zafri5 min readUpdated Oct 21, 2026

Cartoon robot detective in a deerstalker hat pointing at a corkboard where Customer, Order, Invoice and Payment cards are linked with string.
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:

TermWhat it isExample
GlossaryWords and their definitions"Churn: a customer who cancels all contracts"
TaxonomyA hierarchy of categoriesProduct › Hardware › Sensors
OntologyConcepts, relations, properties and rulesCustomer —places→ Order —billedBy→ Invoice
Knowledge graphReal data organised by an ontologyAcme Ltd —places→ Order 1042
Semantic layerMetrics and dimensions mapped onto tablesrevenue = 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:

  1. Disambiguation. Synonyms ("client", "buyer", "account") map to one concept with one definition.
  2. Navigation. Relations tell the system which path connects the concepts in a question, so it doesn't invent joins.
  3. 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:

InteractiveA small business ontology
locatedInplacescontainsbilledByissuedTosettlesCustomerRegionOrderProductInvoicePayment

Invoice

A billing document for one order. “Unpaid” means no settling Payment and past its due date.

Properties: invoice_idamountdue_date

Also called: bill

Grounded mapping

“clients” → Customer · “bills” → Invoice · “unpaid” → no settling Payment and past due_date

SELECT c.name, i.invoice_id, i.amount
FROM customer c
JOIN invoice i ON i.customer_id = c.customer_id
LEFT JOIN payment p ON p.invoice_id = i.invoice_id
WHERE c.region_code = 'EMEA'
  AND p.payment_id IS NULL
  AND i.due_date < CURRENT_DATE;
Pick a question to see which concepts and relations it touches. Click a concept to read its definition. These definitions are what an LLM is handed instead of guessing what “unpaid” or “revenue” means.

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:

YAML
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.

Python
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 sql

The 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:

  1. Collect real questions that people ask (or that your AI assistant gets wrong). Fifty is plenty.
  2. Model only the concepts those questions need. Usually 10 to 20.
  3. Write definitions with the people who own them. Finance defines revenue; sales defines territory.
  4. Wire it into one use case, such as text-to-SQL for a single team, and measure accuracy before and after.
  5. Grow it from failures. Every wrong answer points at a missing concept, synonym or rule.
Get Consultancy