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.
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.
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
| Term | Meaning | Example |
|---|---|---|
| Measure | A calculation over rows | Sum of paid order totals |
| Dimension | A way to group or filter | Region, month, product family |
| Metric | A named, governed business number, often built from measures | Net revenue, average order value |
| KPI | A metric tied to a goal | Net revenue against quarterly target |
| Entity and relationship | How tables connect and at what level of detail | One order has many items |
| Grain | What one row represents | One order line per day |
| Business glossary | Agreed definitions of terms in plain language | What "active customer" means |
| Data dictionary | Technical description of tables and columns | Types, units, allowed values |
The glossary explains meaning to people, the dictionary describes storage, and the semantic layer makes the connection executable.
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.
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
| Include | Why |
|---|---|
| Clear name and one-sentence definition | Selection depends on it |
| Synonyms people actually use | Matching user wording |
| What it excludes and which similar metric differs | Prevents near-miss choices |
| Valid dimensions and time field | Stops meaningless breakdowns |
| Unit, currency and format | Correct presentation |
| Owner and certification status | Trust and escalation |
| Example questions and answers | Testing 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
| Approach | Coverage | Reliability | Control |
|---|---|---|---|
| Model writes SQL over raw tables | Broad | Lowest | Needs strong guards and review |
| Model writes SQL over curated views with descriptions | Medium | Better | Fewer traps |
| Model selects metrics; layer compiles | Limited to the model | Highest for defined metrics | Strong |
| Hybrid with clear labeling | Broad | Depends on the route | Mark 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.
| Decision | Question to answer | If left open |
|---|---|---|
| Grain | What does one row of each source represent? | Totals are repeated or dropped by joins |
| Additivity | Can this measure be summed across every dimension? | Account balances get added across days |
| Time field | Order, shipment or payment date? | The same month gives different totals |
| History | Group by the customer's region then or now? | Past results shift when records are updated |
| Missing values | Is a blank zero, unknown or excluded? | Averages move without explanation |
| Currency | Which 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.
Tools and platforms
Many options exist and they change quickly, so confirm features and availability in current documentation.
| Option | Notes |
|---|---|
| Databricks Unity Catalog metric views | Metrics 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 views | Business concepts defined as objects in the warehouse |
| dbt Semantic Layer and MetricFlow | The 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 layers | Serve definitions to several tools through APIs |
| Business intelligence tool models | Convenient 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
| Check | Test |
|---|---|
| Metric selection | Questions with one correct metric and tempting alternatives |
| Filters and time | "Last quarter", time zones, fiscal calendars |
| Ambiguity | The agent asks when it should and not when context decides |
| Refusal | No definition or no permission is stated clearly |
| Numbers | Results equal a trusted calculation |
| Explanation | Answer 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
- Collect the twenty questions people ask most.
- Identify the handful of metrics and dimensions they need.
- Agree definitions with owners; record disagreements openly.
- Implement them in the tool your platform already supports.
- Test results against trusted reports.
- Give the agent only those metrics, and log unanswered requests.
- Add the next metrics based on that log.
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
- Databricks: Unity Catalog semantics
- Snowflake: semantic views overview
- MetricFlow repository and license history
- Apache Ossie (incubating)
- Cube documentation
Next steps
Data Agents and AI Data Analysts
See how agents analyze data.
Safe SQL, Permissions and Evaluation
Check queries and results.
Math, Search and Algorithms for Agent Engineers
Move on to foundations.