Semantic Layers and Business Metrics for AI

Define each business number once, with its meaning and owner, so agents stop reinventing it in every query.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

A semantic layer maps business terms to data: which tables to use, how to join them and how to calculate each measure. An agent then asks for a named metric by named dimensions and trusted software produces the query. This removes many wrong joins and silent disagreements about definitions. It does not remove the need to understand the question, check permissions or test answers.

What you will learn: metrics, dimensions and measures, why raw SQL goes wrong, building a small layer, glossaries and ambiguity, current tools and standards, and governance.
Prerequisites: basic SQL. Data Architecture for Agentic AI helps.

Beginner Names, numbers and meaning

The problem

Ask three people for last month's revenue and you may get three correct calculations of three different things: before refunds, after refunds, by order date or by payment date. A language model writing SQL from table names faces the same choices without knowing that choices exist. Its query runs, the number looks reasonable, and nobody notices.

The vocabulary

TermMeaningExample
MeasureA calculation over rowsSum of paid order totals
DimensionA way to group or filterRegion, month, product family
MetricA named, governed business number, often built from measuresNet revenue, average order value
KPIA metric tied to a goalNet revenue against quarterly target
Entity and relationshipHow tables connect and at what level of detailOne order has many items
GrainWhat one row representsOne order line per day
Business glossaryAgreed definitions of terms in plain languageWhat "active customer" means
Data dictionaryTechnical description of tables and columnsTypes, units, allowed values

The glossary explains meaning to people, the dictionary describes storage, and the semantic layer makes the connection executable.

Question"net revenue by region last month"
Agentchooses an approved metric, dimensions and filters
Semantic layercompiles the correct SQL and applies access rules
Warehouse or lakehouseruns it
The model selects meaning; deterministic software produces the calculation.
Intermediate Building and using one

A miniature semantic layer

The program compares a hand-written join with a layer that accepts only approved metric and dimension names.

"""Compile approved metric names to SQL; refuse anything else."""
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders(id INT, region TEXT, status TEXT, total INT);
CREATE TABLE items(order_id INT, sku TEXT);
INSERT INTO orders VALUES (1,'east','paid',100), (2,'east','refunded',50),
                          (3,'west','paid',200);
INSERT INTO items VALUES (1,'a'), (1,'b'), (1,'c'), (3,'a');
""")
METRICS = {
    "revenue": "SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END)",
    "paid_orders": "COUNT(CASE WHEN status = 'paid' THEN 1 END)",
}
DIMENSIONS = {"region": "region", "status": "status"}

def compile_query(metric, by):
    if metric not in METRICS:
        raise KeyError(f"unknown metric: {metric}")
    if by not in DIMENSIONS:
        raise KeyError(f"unknown dimension: {by}")
    column = DIMENSIONS[by]
    return (f"SELECT {column}, {METRICS[metric]} FROM orders "
            f"GROUP BY {column} ORDER BY {column}")

naive = """SELECT region, SUM(total) FROM orders o
           JOIN items i ON i.order_id = o.id
           GROUP BY region ORDER BY region"""
print("hand-written join:", db.execute(naive).fetchall())
print("semantic layer:   ",
      db.execute(compile_query("revenue", "region")).fetchall())
for request in (("profit", "region"), ("revenue", "total; DROP TABLE x")):
    try:
        compile_query(*request)
    except KeyError as error:
        print("refused:", error.args[0])

Output:

hand-written join: [('east', 300), ('west', 200)]
semantic layer:    [('east', 100), ('west', 200)]
refused: unknown metric: profit
refused: unknown dimension: total; DROP TABLE x

The hand-written query reports 300 for the east region where the approved metric reports 100. Joining orders to their three items repeated the order total three times, a mistake called fan-out. The query also ignored payment status. Both errors produce valid SQL and believable numbers. The layer calculates revenue at the order grain, filters to paid orders and refuses both an unknown metric and a malicious dimension name, because only listed fragments ever reach the SQL text.

A real semantic layer also handles joins across tables without double counting, time grains, filters supplied as bound parameters, ratios and permissions.

Ratios need care

Average order value is total revenue divided by total orders. Averaging each region's average gives a different and usually wrong result. Define ratios from their parts so that any grouping stays correct.

Handling ambiguous questions

Some terms have legitimate meanings in different departments. The right behavior is to use context when it clearly decides, ask when it does not, and admit when no definition exists.

"""Ask which meaning is intended when a business term has more than one."""
glossary = {
    "active customer": [
        {"metric": "active_customers_90d", "owner": "sales",
         "meaning": "bought in the last 90 days", "domains": {"sales"}},
        {"metric": "active_users_30d", "owner": "product",
         "meaning": "signed in during the last 30 days",
         "domains": {"product"}},
    ],
    "revenue": [
        {"metric": "net_revenue", "owner": "finance",
         "meaning": "paid orders minus refunds", "domains": set()},
    ],
}
synonyms = {"active client": "active customer", "sales income": "revenue"}

def resolve(phrase, domain=None):
    term = synonyms.get(phrase.lower(), phrase.lower())
    choices = glossary.get(term)
    if not choices:
        return f"no approved definition for {phrase!r}: say so"
    scoped = [c for c in choices if domain in c["domains"]]
    if len(scoped) == 1:
        choices = scoped
    if len(choices) == 1:
        c = choices[0]
        return f"use {c['metric']} ({c['meaning']}; owner {c['owner']})"
    options = " | ".join(c["meaning"] for c in choices)
    return f"ask the user: {options}"

print(resolve("Sales income"))
print(resolve("active client"))
print(resolve("active client", domain="product"))
print(resolve("churn"))

Output:

use net_revenue (paid orders minus refunds; owner finance)
ask the user: bought in the last 90 days | signed in during the last 30 days
use active_users_30d (signed in during the last 30 days; owner product)
no approved definition for 'churn': say so

"Sales income" maps to the single approved revenue metric. "Active client" has two meanings, so the agent asks, unless the product context selects one. "Churn" has no approved definition. The tempting alternative, inventing one on the spot, produces a number that nobody owns. Whatever is chosen, show the definition with the answer so the reader can disagree with it.

Describe metrics for an agent

IncludeWhy
Clear name and one-sentence definitionSelection depends on it
Synonyms people actually useMatching user wording
What it excludes and which similar metric differsPrevents near-miss choices
Valid dimensions and time fieldStops meaningless breakdowns
Unit, currency and formatCorrect presentation
Owner and certification statusTrust and escalation
Example questions and answersTesting and guidance

With hundreds of metrics, search for the few relevant ones and show only those, as with large tool sets. Return the metric identifier, filters, time range and data timestamp with every result.

Semantic layers and text-to-SQL

ApproachCoverageReliabilityControl
Model writes SQL over raw tablesBroadLowestNeeds strong guards and review
Model writes SQL over curated views with descriptionsMediumBetterFewer traps
Model selects metrics; layer compilesLimited to the modelHighest for defined metricsStrong
Hybrid with clear labelingBroadDepends on the routeMark unapproved results as exploratory

Even with a layer, the model can choose the wrong metric, time range or filter. Evaluate with real questions and expected results, as described in Safe SQL, Permissions and Evaluation and Text-to-SQL Agents and Schema Linking.

Modeling choices that matter

Most errors in a semantic model come from a few decisions made quickly at the start. Settle each one explicitly and write it into the definition.

DecisionQuestion to answerIf left open
GrainWhat does one row of each source represent?Totals are repeated or dropped by joins
AdditivityCan this measure be summed across every dimension?Account balances get added across days
Time fieldOrder, shipment or payment date?The same month gives different totals
HistoryGroup by the customer's region then or now?Past results shift when records are updated
Missing valuesIs a blank zero, unknown or excluded?Averages move without explanation
CurrencyWhich exchange rate and date?Regional figures cannot be reconciled

Additivity deserves attention. A sales amount can be summed across regions and months. A stock level or account balance can be summed across locations on one day but not across days, where a closing value or average is meant. A count of distinct customers cannot be added across months at all, because the same customer would be counted again. Declare these properties so the compiler can refuse or correct an invalid request.

The interface the agent sees

Expose a small number of tools instead of the whole model: one to search metrics by phrase, one to describe a chosen metric with its valid dimensions, and one to run a request made of metric names, dimensions, filters, time range and row limit. Return structured errors that explain what is allowed, such as "this metric cannot be grouped by product", so that the agent can correct itself or tell the user. Validate every value on the server. The agent's request is input from an untrusted program, however sensible it looks.

Expert Platforms, standards and governance

Tools and platforms

Many options exist and they change quickly, so confirm features and availability in current documentation.

OptionNotes
Databricks Unity Catalog metric viewsMetrics defined in the catalog and governed with its permissions, with agent-oriented metadata such as synonyms and display names; see Genie, Genie Agents and Genie MCP
Snowflake semantic viewsBusiness concepts defined as objects in the warehouse
dbt Semantic Layer and MetricFlowThe MetricFlow engine has been under the Apache 2.0 license since version 0.209.0; hosted services have their own terms
Cube and other headless layersServe definitions to several tools through APIs
Business intelligence tool modelsConvenient if most consumption happens in that tool

Portability has been a weak point. The Open Semantic Interchange initiative published a vendor-neutral, YAML-based specification for exchanging semantic models, and in July 2026 the work entered the Apache Incubator as Apache Ossie. It is young, so test an export and import round trip with your own tools before relying on it.

Governance

  • One owner per metric, who approves definition changes.
  • Definitions in version control, reviewed like code, with tests against known totals.
  • Certification levels such as certified, under review and exploratory, shown in answers.
  • Change notices. A redefinition alters history in reports; record when and why.
  • Deprecation. Redirect old names for a period instead of deleting them.
  • Duplicate control. Review new metrics that resemble existing ones.

Permissions and privacy

Apply row and column rules to the user the agent represents, not to a service account. Aggregates can leak: a total for a group of one reveals an individual, and several overlapping totals can reveal a value by subtraction. Set minimum group sizes for sensitive metrics and log queries. Cached results must carry the same permission scope as the query that produced them.

Evaluating the whole path

CheckTest
Metric selectionQuestions with one correct metric and tempting alternatives
Filters and time"Last quarter", time zones, fiscal calendars
AmbiguityThe agent asks when it should and not when context decides
RefusalNo definition or no permission is stated clearly
NumbersResults equal a trusted calculation
ExplanationAnswer states definition, filters and data age

Time words deserve their own tests. "This week", "last month" and "year to date" depend on a calendar and a time zone. Resolve them in code from stated rules and show the resulting dates.

Starting without a large program

  1. Collect the twenty questions people ask most.
  2. Identify the handful of metrics and dimensions they need.
  3. Agree definitions with owners; record disagreements openly.
  4. Implement them in the tool your platform already supports.
  5. Test results against trusted reports.
  6. Give the agent only those metrics, and log unanswered requests.
  7. Add the next metrics based on that log.
Illustrative example: two kinds of active customer

Sales and product teams each report "active customers" and the figures differ widely. The data team keeps both under distinct names with owners. The assistant asks which is meant unless the channel makes it obvious, and always prints the definition beside the number. Arguments about whose figure is right turn into a choice about which question is being asked.

Presenting a metric answer

A correct number can still mislead if the reader cannot tell what it covers. Have the answer template, not the model's habits, supply these elements:

  • The metric's approved name and a short definition.
  • The exact date range, calendar and time zone used.
  • Filters applied, including any added automatically by permissions, described without revealing hidden data.
  • The currency or unit and the rounding.
  • When the data was last updated, and a note if the period is incomplete.
  • Whether the result is certified or exploratory.

Comparisons need extra care. Comparing a month that is two days old with a full earlier month produces an alarming and meaningless fall. Compare equal periods, or say plainly that the current one is partial. When someone asks why a number changed, separate what the data shows, such as which regions contributed most to the difference, from explanations that would need other evidence. The first is calculation. The second is a hypothesis, and the agent should label it as one.

Common mistakes

  • Expecting descriptions alone to fix a confusing schema.
  • Forcing one definition where two are legitimate.
  • Letting the agent define new metrics silently.
  • Joining at the wrong grain.
  • Averaging averages.
  • Ignoring fiscal calendars and time zones.
  • Applying permissions to tables but not to cached answers.

Checklist

  • Each metric has a definition, owner and tests.
  • Grain and relationships are declared.
  • The agent requests metrics through a controlled interface.
  • Ambiguous terms trigger a question.
  • Answers show definition, filters and data time.
  • Row, column and small-group rules apply.
  • Changes are versioned and announced.
  • Unmet requests are reviewed regularly.

Frequently asked questions

Is a semantic layer the same as a knowledge graph?

No. A semantic layer focuses on calculating measures from tables. A knowledge graph focuses on entities and relationships. Some systems use both.

Can the agent still answer questions outside the layer?

It can, through guarded SQL, if your policy allows it. Label such results as exploratory and show the query so someone can check it.

Who should write definitions?

Business owners decide meaning and data teams implement it. A model can draft descriptions for them to review.

Does a semantic layer remove hallucinations?

It reduces calculation errors for defined metrics. A model can still misread a question or misdescribe a result, so keep evaluating.

References and further reading

Next steps