A semantic layer for AI gives agents a governed way to query business concepts such as revenue, churn and active customers, instead of asking a model to infer what your database means. To build one, standardise metric definitions, relationships, access rules and query interfaces, then test the results against known questions before you let users rely on them. If you are still deciding which analytics or agent use cases to tackle first, start with our AI strategy and solutioning service.
The objective is not to ban text-to-SQL. It is to prevent an agent from improvising definitions and join logic when a trusted answer matters. A semantic layer defines what a metric means and how it can be calculated. An AI agent can discover those definitions and call a tool that returns validated results. The model can still interpret a question and explain an answer, but the semantic engine owns the calculation.
This guide walks through the work in order: what you need before you start, how to define and test the model, and how to connect it safely to an agent. It applies whether your data sits in a cloud warehouse, a reporting platform or several operational systems. The important design choice is to treat business meaning as an explicit interface, not a paragraph hidden in a prompt.
Why does a semantic layer for AI reduce text-to-SQL errors?
A raw text-to-SQL agent has to solve several jobs at once. It must identify relevant tables, infer relationships, select the right filters, understand business terminology, handle aggregation and write executable SQL. A query can run successfully and still produce the wrong answer, which highlights why text-to-SQL fails without a semantic layer to govern joins and aggregations. Syntax validation cannot tell you whether the query used recognised revenue instead of bookings, or multiplied rows by joining across different grains. When dashboard discrepancies undermine confidence across the leadership team, see why executives don't trust dashboards.
A semantic layer narrows that problem. It exposes approved measures, dimensions, time fields and relationships through stable names. The agent asks for a known metric and a set of dimensions. The layer resolves the request into a query using declared business logic, then applies the relevant access rules. If the requested combination is not modelled, the system can return an explicit error rather than a plausible number.
That boundary matters in practice. In a benchmark described by dbt Labs, raw text-to-SQL on the ACME Insurance benchmark reached 64.5% overall accuracy across the tested models, while queries covered by the dbt Semantic Layer reached 98.2% with Claude Sonnet and 100% with GPT models. These results are specific to that benchmark, its questions and its modelled coverage. They are not a promise that any semantic layer will produce those results in your warehouse. The useful finding is architectural: consistent definitions and constrained query generation can reduce some classes of error. See the dbt benchmark update for its method and qualifications.
Earlier research by Sequeda and colleagues compared raw text-to-SQL with knowledge graph and semantic verification approaches on an enterprise insurance database. The paper reports execution accuracy of 16.7% for zero-shot text-to-SQL, 54.2% with a knowledge graph representation and 72% with semantic verification. The study is not a direct product comparison, but it illustrates why domain meaning and relationship constraints matter. Read the enterprise SQL benchmark publication on ResearchGate before applying those figures to your own system.
A semantic model is not automatically correct just because it has a formal structure. It can encode the wrong definition, omit a crucial exception or expose a sensitive field. The work is to make the model reflect decisions that business owners can verify, then maintain it as the organisation changes.
What do you need before you start?
Do not begin by modelling every table. Start with one decision people need to make and the questions they ask to make it. A workable first project needs the following inputs:
- A business owner for the metric. Someone must decide what counts as revenue, churn or an active account when definitions conflict. A data team can implement the rule, but it should not silently make the business decision.
- A narrow question set. Collect real questions from executives, analysts or an operational workflow. Include follow-up questions, common filters and ambiguous wording, not just polished examples.
- A reliable data path. Identify the source tables, transformations, refresh timing and known quality limits. A semantic layer cannot repair missing transactions or late source feeds by itself.
- A grain for each model. Grain means what one row represents, such as one order, one invoice line or one customer per day. You need this before designing joins or sums.
- Access and privacy requirements. Define who can see which rows and fields. In Australia, involve the relevant privacy and security owners when personal information or regulated data is in scope.
- A query and agent boundary. Decide which service executes queries, what credentials it uses, and whether the agent can only read data. Keep execution separate from the model's ability to reason or respond.
A clean star schema is a strong starting point, but it does not settle business meaning. Two teams can still disagree about calendar versus financial year, trial accounts, refunds, currency conversion or the date that defines an active customer. Those rules need owners and explicit definitions.
For teams planning an agent as part of a wider operating model, our AI agents and automation service covers the design and production controls around the model, tools and workflow. Keep the first use case bounded enough that you can compare its answers with existing reports or analyst-reviewed SQL.
Step 1: Pick a decision and build a question set
Choose a decision that is frequent, valuable and answerable with data you can inspect. For example, an operations leader might ask which product lines had the largest increase in overdue invoices this month, and whether the change is concentrated in a particular region. That question contains a measure, a comparison period and dimensions. It is more useful than a general brief to make company data conversational.
Write down questions in the language users actually employ. Ask them to include terms that may have more than one meaning. A finance team might say recognised revenue, while a sales team means booked contract value. An executive asking for active customers may mean any customer with a paid transaction, or only an account with a current subscription. Do not resolve ambiguity by choosing whichever phrase appears most often. Ask the accountable owner.
For every question, record:
- The intended business decision and user.
- The requested measure and its likely definition.
- The time period and time basis, such as invoice date or service date.
- The requested grouping, filters and comparison.
- The expected result, including a known report or independently checked query where possible.
- Any access restriction or data sensitivity.
Include questions the system should refuse. Examples include asking for an undefined metric, requesting a breakdown the user is not allowed to see, or using a term whose meaning has not been agreed. Refusal examples are part of the test set, not edge cases to leave until launch.
Tip: Keep an ambiguity log. For each phrase with multiple interpretations, record the decision, its owner and the date it was agreed. A model description is only useful if users can see the business rule behind it.
Mistake to avoid: Selecting a use case because it sounds impressive rather than because the answer can be checked. If no one can establish a trusted expected result, you will not know whether the agent or the source data is wrong.
Step 2: Inventory the source data and establish its grain
Trace each metric to the tables and transformations that produce it. Draw the data path from source system to warehouse model. For each relevant table, record its key, grain, update pattern, important filters and owner. This is also where you identify whether the proposed question depends on data that is late, incomplete or duplicated. As examined in analyses of rich data context for AI analytics, winning with enterprise AI is an investment in foundational context rather than simply selecting a larger model.
Grain is central to reliable aggregation. Suppose one row in an orders model represents one order and a second table has several payment rows per order. Joining the two tables can produce multiple copies of an order row. Summing order value after the join may then count the same order more than once. Similar problems appear when a customer has multiple subscriptions, an invoice has multiple lines, or an account has multiple adjustments.
Map the relationships before writing a measure. State whether each relationship is one-to-one, one-to-many or many-to-one, and define the joining keys. Be cautious with many-to-many relationships, where rows on both sides can multiply. If the business question needs measures from tables at different grains, decide whether to aggregate each side first, use a bridge table, or define a supported query path that handles the relationship explicitly.
Use concrete checks, not diagrams alone. Pick a small set of entities and compare row counts and totals before and after a join. Test edge cases such as an order with no payment, a customer with multiple subscriptions, a reversed transaction and a late-arriving record. The purpose is to establish what the physical data means before you encode it as a reusable abstraction.
The BIRD benchmark examines text-to-SQL over 12,751 question and SQL pairs across 95 databases and 37 domains. Its scale highlights the variety of database structures and domain context that query systems must handle. It is a research benchmark, not a direct measure of your warehouse or semantic model. The BIRD benchmark site provides details of the dataset and evaluation.
Tip: Write down the row grain in plain language at the top of each model and metric definition. If a reviewer cannot tell what one row represents, stop and resolve that before you expose it to an agent.
Mistake to avoid: Assuming a foreign key declaration or a familiar table name proves the join is safe. Real warehouses often contain incomplete relationships, historical records or undocumented exceptions.
Step 3: Define certified metrics and dimensions
Create a short list of measures that answer the chosen question set. A measure is a value that can be aggregated, such as net revenue or invoice count. A dimension is a way to group or filter that measure, such as month, region or customer segment. A metric definition should be specific enough that two independent implementations return the same result from the same data.
For each measure, document:
- The business name and a plain-language description.
- The owner who approves its meaning.
- The source field or transformation and the aggregation method.
- Inclusion and exclusion rules, including treatment of refunds, test records and cancellations.
- The date field and calendar used for time-based reporting.
- Currency and unit handling, where relevant.
- Supported dimensions and filters.
- Refresh timing and known limitations.
- Access requirements and whether the measure contains sensitive information.
For example, a metric called net recognised revenue should not be a vague label over a raw amount column. Its model needs to specify which transaction states count, how credits and reversals are treated, which recognition date applies and how multiple currencies are handled. The owner decides the accounting meaning. The data team implements and tests that rule, ensuring deterministic processing on financial data. The agent should not invent it from a label.
Dimensions need similar care. Define whether region means customer billing location, service location or sales territory. Define whether time means calendar month or financial period. Decide how null, unknown and historical values appear. Then make supported dimension and measure combinations explicit. Not every metric can sensibly be grouped by every dimension.
Use a certification process. A metric can move from draft to reviewed to certified after its owner approves the definition, its SQL passes tests, its access controls are checked and its expected results match a trusted reference. Certification should be visible to the agent interface and to human users. A label such as certified is not a substitute for a review record.
Tip: Give measures stable names that describe the business concept, not the underlying column. Keep synonyms as discovery terms, but map them to the same approved metric only when the owner confirms they mean the same thing.
Mistake to avoid: Publishing several near-identical measures, such as revenue, total revenue and revenue amount, without explaining their differences. That moves ambiguity from the database into the catalogue.
Step 4: Model joins, time and security rules
Once the core metrics are clear, model the relationships they need. Declare the join keys and cardinality, then identify which measures and dimensions are valid across each path. The semantic engine should compile a request in a way that respects those relationships. Depending on the platform, that may mean pre-aggregating one side, selecting a safe join path or rejecting a combination that cannot be resolved correctly.
Test for fan-out directly. Compare a measure's result at its native grain with the result after each supported join. If the total changes when you add a dimension that should not alter it, investigate. Sometimes the change is correct, for example because the dimension filters the population. Sometimes it exposes duplicated rows or an incorrect relationship. Record the expected behaviour so later changes do not quietly alter the result.
Make time rules explicit. Choose the default date for each measure and support alternate dates only when users need them. Define whether a period is complete, how time zones are handled and whether the calendar is financial or calendar-based. A query for month-to-date revenue can mislead if the model does not communicate that the latest source data is delayed.
Security belongs in the query path, not only in the prompt. Use least-privilege credentials for the semantic service. Apply row-level restrictions, which limit records a user can see, and column masking, which hides or transforms sensitive fields. Check whether the platform propagates identity from the application or uses a service account with its own policy. Test access using real user roles, including a role that must be denied.
Do not assume that a model-level filter is equivalent to database enforcement. Verify the generated query and the results for each role. Make sure the agent cannot change the tool arguments to bypass restrictions, use another endpoint with broader access or retrieve raw records through a separate tool.
Tip: Treat unsupported metric and dimension combinations as normal outcomes. A clear response that a measure cannot be grouped by a particular field is safer than a silently approximate number.
Mistake to avoid: Granting broad database read access to the agent because it is convenient for a prototype. The semantic service should be the controlled route to data, with access rights matched to the user and use case.
Step 5: Select the semantic engine and expose a narrow interface
Choose a platform based on your warehouse, transformation workflow, query patterns, security needs and the skills of the team that will maintain it. Platform capabilities and prices change, so verify current official documentation and pricing before procurement. Do not select a product solely because it advertises an AI or MCP feature. Check what the feature actually exposes, how it handles identity and what the failure response looks like.
| Approach | Useful when | Main trade-off to check |
|---|---|---|
| A transformation-coupled semantic layer | Your team already defines warehouse models and metrics in its analytics codebase | Metrics need to be declared and maintained; questions outside model coverage require an explicit fallback |
| A standalone semantic service | Several applications need shared metrics, APIs or caching across data sources | You add a service to operate, secure, monitor and keep aligned with warehouse changes |
| A warehouse-native semantic object | You want definitions close to warehouse data and its existing permissions | Portability may be limited to that warehouse and its supported interfaces |
| A BI-integrated semantic model | Users already rely on the BI tool's governed definitions | Check whether agents can use those definitions consistently outside the BI product |
For example, dbt documents MetricFlow as its semantic layer and provides Semantic Layer documentation. Cube outlines how an AI context layer exposes data structures to agents, while teams can also connect Cube to AI applications via an MCP server. Snowflake documents Semantic Views and its Cortex Analyst interface and consumption model. These are examples of different architectural choices, not an endorsement of one platform for every stack.
The agent should see a small, deliberate tool surface. Useful tools may let it search for metrics, inspect a metric's definition, list supported dimensions and filters, request a query, and retrieve the result with metadata. Avoid exposing arbitrary SQL execution as the default tool if the goal is governed metric access. If analysts need a separate SQL path, protect it with its own role, review process and audit trail.
An interface such as MCP, REST or GraphQL is a transport and tool contract. It does not make the metric definitions accurate by itself. With MCP, an agent can discover tools and call them in stages rather than receive a dump of the entire warehouse schema. Design discovery so the agent first finds relevant business concepts, then requests only the fields needed to answer the question.
Tip: Test tool descriptions with realistic user language. The model must be able to distinguish a measure from a dimension and know when it should ask a clarifying question.
Mistake to avoid: Sending every metric, dimension and column to the model on every request. This adds noise and makes it harder for the agent to select the right concept. Use progressive discovery and return concise definitions.
Step 6: Build the agent workflow around validation
A reliable agent should not translate a question straight into an unrestricted SQL statement and present the first result. Give it a sequence that preserves meaning and makes uncertainty visible:
- Parse the question into a measure, time range, dimensions, filters and comparison.
- Search the semantic catalogue for matching certified concepts.
- Check whether the requested combination is supported and whether the user can access it.
- Ask a clarifying question if a term, date basis or filter is ambiguous.
- Call the semantic query tool with validated names and parameters.
- Check the response status, result metadata and any warnings about freshness or coverage.
- Explain the answer with the metric definition, time period and relevant caveats.
- Preserve a trace of the question, chosen concepts, tool arguments, result and user identity for review.
The model can help with interpretation and explanation, but do not ask it to silently fill gaps in a metric. If a user asks for a measure that is not defined, return a clear boundary: the metric is not currently certified, and the system can route the request to an analyst or offer a related approved measure. Do not fall back to raw SQL without notifying the user and applying a separately governed workflow.
Keep the result contract informative. It should include the values, units, time basis, filters applied, data freshness and the metric's definition or reference. For small results, the agent may summarise a table. For a large result, it should return an appropriate aggregation or ask the user to narrow the request. Avoid letting the model produce an unsupported explanation of why a number changed when the query only establishes that it changed.
Put limits around execution. Set query timeouts, row limits and cost controls. Use read-only permissions. Monitor repeated tool calls and unexpected query patterns. Have a way to stop the agent or revoke its access if behaviour changes. These controls are part of production design, not polish to add once the agent has broad access.
For teams building a managed tool endpoint, our MCP server development service covers the interface between models, tools and governed data systems. Keep the contract small and version it as carefully as you version the semantic definitions.
Step 7: Test correctness, coverage and failure behaviour
Testing should cover both the data model and the agent's interaction with it. Use the question set from Step 1 as a regression suite. For each supported question, compare the semantic result with a trusted report or independently reviewed query. Confirm that the same business definition is used, not simply that two numbers happen to match for one period.
Build tests in layers:
- Definition tests: Check that measures use the intended filters, dates, units and aggregation.
- Relationship tests: Check join keys, cardinalities, duplicate behaviour and totals before and after supported joins.
- Access tests: Confirm that each role sees only allowed rows and fields, including through alternate tool calls.
- Question-to-metric tests: Check whether common wording maps to the right certified measure or triggers clarification.
- Unsupported-request tests: Confirm that an undefined metric, invalid combination or unauthorised field produces a safe explanation.
- Freshness tests: Check that delayed source data is disclosed and that stale results do not appear current.
- Regression tests: Rerun the full suite after changes to warehouse models, metric logic, platform configuration or agent instructions.
Include adversarial but realistic prompts. A user may ask for confidential customer details, request a metric using an unfamiliar synonym, or combine a measure with a dimension the model does not support. The test is whether the system stays within its boundary and explains what it can do next.
Measure more than execution accuracy. Track the share of questions answered with the correct certified metric, the rate of clarification, unsupported-request handling, query failures, latency and cost. Review samples with business owners. A correct number with the wrong explanation can still lead to a poor decision. A refusal may be the right outcome, but repeated refusals could show that the model lacks coverage for a common need.
The dbt benchmark's reported accuracy applies to questions within its tested scope. That distinction should shape your own reporting. Publish both the covered-question result and the coverage boundary. Do not report a single score that hides how many real user questions the semantic model can answer.
Tip: Keep a set of questions that should not be answered automatically. These are often more useful for safety testing than adding more easy examples that the model already handles.
Mistake to avoid: Testing only SQL execution. A query can execute and return a number while using the wrong business concept, excluding the wrong population or violating a user access rule.
Step 8: Release in stages and maintain the model
Start with a small group of users and a read-only, low-risk workflow. Show the source definition and filters with each answer. Ask users to report ambiguous terms and missing dimensions. Review queries and tool traces regularly, but protect sensitive query logs and apply retention rules appropriate to your organisation.
Before expanding, decide who owns each operational task: approving definitions, deploying model changes, reviewing access, monitoring failures and responding when a source system changes. Treat semantic definitions as code. Use version control, review changes, test them against the regression suite and promote through separate development and production environments. Keep a change history so a changed metric can be traced to an owner and a decision.
Watch for drift. A field may be renamed, a source application may change its status codes, or finance may revise a policy. A semantic layer can continue to return a result after its assumptions become stale. Schedule reviews for important metrics and trigger an owner review when a source definition or transformation changes.
Expand coverage by evidence, not by adding every available column. If users repeatedly ask a valid question the model cannot answer, resolve the definition and data path, then add the metric or dimension through the same approval and testing process. If a question is rare or requires a judgement call, route it to an analyst instead of creating a permanent metric for it.
For reporting teams that need certified definitions shared across applications, our embedded analytics service can help align the semantic model with the reporting experience. The service choice depends on whether the main problem is an agent interface, the underlying model, or the analytics product users work in each day.
Common mistakes to avoid
- Modelling the whole warehouse first. This creates a large catalogue before you know which definitions matter. Start with the decision and its question set.
- Treating labels as definitions. A metric called churn is not self-explanatory. Specify the population, period, event and exclusions.
- Ignoring grain. A technically valid join can multiply records. Record grain and test totals on every supported path.
- Letting the agent decide business policy. The model can identify ambiguity, but a business owner must resolve it.
- Assuming a protocol is governance. MCP or an API can expose tools; it does not certify metrics, enforce every permission or test query meaning automatically.
- Failing open when coverage is missing. Unmodelled questions should be clarified, refused or routed through a controlled analyst workflow, not quietly answered using invented logic.
- Skipping ownership after launch. Definitions, source data and access rules change. Assign people to review and maintain them.
Where PADISO fits
We help teams connect AI agents to dependable data interfaces, from defining the use case and architecture to building tool integrations and production controls. Depending on the work, that may involve AI strategy, AI automation, MCP development or embedded analytics. The first step is to map one high-value question to its source data, metric owner, access rules and expected answer.
Wrap-up: make business meaning explicit
A semantic layer does not make an AI agent infallible. It gives the system a safer, testable route to business metrics, with explicit definitions and a clear boundary around what it can answer. Start with one decision, establish the data grain, certify a small set of measures, and test both correct answers and refusals. Then expand only when the definitions, access controls and maintenance ownership are clear.
If you are assessing whether your data and operating model are ready for AI, take the PADISO AI readiness test as a concrete next step. Use the result to identify where to begin: metric ownership, data quality, access design or the agent interface.