Enterprise Natural Language to SQL (NL2SQL) systems have evolved from single-shot query translators into autonomous data agents. Built with frameworks like Google's Agent Development Kit (ADK) and connected to cloud data warehouses like BigQuery, these agents inspect schemas, validate queries, and synthesize answers from live data.

While ADK makes it straightforward to build an NL2SQL data agent, you need metrics that are tailored to SQL semantics to prove that the agent is accurate, reliable, and ready for production. Built-in ADK criteria, such as the tool_trajectory_avg_score (which checks for an exact match on tool arguments, including the raw SQL string) and the response_match_score (which measures word overlap by using ROUGE-1) often fall short because they penalize valid, helpful variations in LLM-generated SQL queries. When you design a custom evaluation metric in ADK, you can replace brittle string or table checks with deterministic, domain-aware evaluation. In this post, we'll walk through the five SQL evaluation traps that break standard benchmarks and show you how to build and run a custom semantic SQL evaluator in ADK.

In a recent development, the evaluator's dilemma stems from a fundamental mismatch between rigid test assertions and flexible SQL semantics. A generated query can return the exact business answer that a user needs while still failing Exact String Match, comparing raw SQL text, or Naive Table Diff,comparing result tables cell-by-cell by column header and row position.

In a recent development, standard evaluation tools assume that there's only one valid way to write a SQL query or structure a result set. This rigidity penalizes capable agents for cosmetic or user-friendly improvements, such as aliasing cryptic column headers or returning helpful context columns.

To accurately evaluate modern data agents, you can combine built-in and custom metrics in ADK across three layers:.

Trajectory evaluation (built-in ADK metric): Verify that the agent calls the right database tools in sequence by using the tool_trajectory_avg_score criterion that's configured with the match_type field set to IN_ORDER and the ignore_args field set to true, so the criterion doesn't flag valid SQL syntax variations as tool-argument failures.

Deterministic semantic equivalence (custom ADK metric): Normalize both the gold-standard result set and the agent's predicted result set into a standard form to verify data equivalence at zero LLM token cost.

Rubric-Based evaluation (LLM-as-a-Judge metric): Use the rubric_based_final_response_quality_v1 criterion to confirm that any extra context columns are genuinely helpful and that the agent's natural-language summary matches the returned data.

Before you design your custom deterministic metric in ADK, examine the five SQL scenarios where standard metrics fail.

When you rely solely on Exact String Match or Naive Table Diff, your evaluation pipeline will flag false negatives across five common scenarios.

Recent findings suggest that an LLM-powered agent often improves output readability by aliasing column names with the AS keyword. Your database schema might store a cryptic identifier like the prod_sale_rev_fy25 column, whereas the agent presents it as "Revenue FY2025".

Although the agent's query is more readable for a business user, both Exact String Match and Naive Table Diff fail because the output column headers differ.

Sources indicate that the sequence of columns in a SELECT clause doesn't change the semantic meaning of the returned data. An agent might select the required columns in a different order than the gold-standard query.

Naive Table Diff marks this query as a failure even though every record contains the exact requested attributes.

In a recent development, unless a prompt explicitly requires a sorted ranking with an ORDER BY clause, the SQL standard doesn't guarantee row order. Two identical queries can return rows in different sequences depending on parallel execution plans in distributed warehouses like BigQuery.

In a recent development, naive Table Diff fails when it enforces an arbitrary row order on unordered queries. Conversely, if a prompt explicitly asks for a ranked or sorted list, such as "top 5 customers", then your evaluator should enforce row order for that test case.

It has been revealed that an agent's query might return values in a different but mathematically equivalent data type or numeric precision. For example, a gold-standard query might explicitly cast a column to the DECIMAL(10, 2) data type, while the agent selects the raw numeric column.

Mathematically, 99.50 and 99.5 are equal, but unnormalized string or type comparisons in a Naive Table Diff flag this result as an error.

It has been revealed that capable data agents often anticipate follow-up questions by including relevant context columns. When a user asks, "Show me the names of our active projects," a minimal query returns only the project_name column, whereas a helpful agent also includes the project_lead and due_date columns.

Naive Table Diff rejects the predicted table because it contains three columns instead of one, penalizing the agent for providing useful context.

In a recent development, when built-in ADK criteria can't express a domain-specific rule like SQL result-set equivalence, ADK lets you author a custom Python metric and register it through the custom_metrics field in your evaluation config. To prevent a flawed query from passing by coincidence, pair this evaluator with realistic, multi-row test fixtures.

Our custom metric normalizes gold-standard and predicted result sets through a methodical six-step pipeline:.

Standard value normalization: Cast numbers (int, float, Decimal, and numeric strings) to floats that are rounded to a fixed precision, convert dates and timestamps to ISO-8601 strings, and strip whitespace from text.

Industry observers note that column alignment by value counts: Represent each column as an unordered frequency counter (collections.Counter) of its normalized values. Match each gold column only against predicted columns that share identical value counts, neutralizing column aliases (AS).

Superset column filtering: When the allow_superset parameter is True, require at least as many predicted columns as gold columns (m >= k), match only the required gold columns, and ignore extra context columns.

One-to-One column mapping: Identify a valid one-to-one mapping between every gold column and a distinct candidate predicted column.

Order-invariant row hashing: Project the predicted rows through the candidate column mapping and count the row tuples with the collections.Counter class so the comparison is invariant to row order.

Equality verdict: Return a boolean match verdict with the matched column mapping for debugging. The ADK metric wrapper converts the verdict into a pass/fail EvaluationResult object.

The following sections provide a step by step implementation to build the evaluator in a single Python module (nl2sql_custom_metric.py) and how to wire the evaluator into ADK.

According to recent reports, import the required Python standard library modules alongside ADK's evaluation types. The SemanticSQLEvaluator evaluates the semantic values between the gold result set and the predicted LLM result set. The evaluator uses the _norm helper to resolve complexity 4, the data types and precision problem, by converting integers, floats, Decimal objects, and numeric strings (such as "99.50" returned by database drivers) into rounded floats, formatting dates as ISO strings, and trimming text whitespace. If your schema stores leading-zero codes (like "02134" zip codes) or 64-bit integer IDs as strings, you should keep those columns as strings so they are not converted to floats.

The following code shows a sample implementation to configure imports and a class to normalize standard value in nl2sql_custom_metric.py:.

To implement the evaluate method, perform the following actions:.

Verify that the row counts and column counts are compatible.

Normalize both tables (g_mat and p_mat) into 2D matrices.

Compute a collections.Counter object of value counts(g_cnts and p_cnts) for every column.

Compare each predicted column to a gold column. If both columns contain the exact same value, it is considered a match.

Sources indicate that when you compute a collections.Counter object, this action helps you solve complexity 1, the column aliases problem, and complexity 5, the superset columns problem. This action also reduces combinatorial explosion on wide tables.,.

The following code indicates a sample implementation to shape validation and column alignment in nl2sql_custom_metric.py:.

Industry observers note that matching individual column value counts is necessary but not sufficient, because values across columns must also stay aligned in each row. To resolve complexity 2, the column permutations problem, and complexity 3, arbitrary row sorting, iterate over valid one-to-one column mappings (len(set(mapping)) == k) from your pre-filtered candidates and compare the projected rows as unordered tuple counters (collections.Counter):.

The following code reveals a sample implementation to configure one-to-one column mapping and row hashing in nl2sql_custom_metric.py:.

To prepare the SemanticSQLEvaluator class into ADK, use the _extract_rows function and the semantic_sql_result_match function.

The _extract_rows function helps to ensure the final_response field is free of natural-language prose by performing the following actions:.

Use ADK's get_all_tool_responses(inv.intermediate_data) helper function to retrieve tool responses from intermediate data.

To grade the final SQL execute, iterate across the tool responses in reverse.

Return each "rows" list that is returned by the agent's execute_sql_query tool. This result helps to ensure the final_response field is free of natural-language prose.

The semantic_sql_result_match function checks the score and sets EvalStatus. If score == 1.0, then EvalStatus is set to PASSED. ADK sets the eval_metric.threshold = None before it invokes a custom metric and uses the returned EvalStatus.

The following code reveals a sample implementation to wrap the evaluator as an ADK custom metric in nl2sql_custom_metric.py:.

To register the semantic_sql_result_match metric inside your eval_config.json file, include the tool_trajectory_avg_score criteria and rubric_based_final_response_quality_v1 rubric. The tool_trajectory_avg_score criteria includes the "ignore_args": true to help ensure ADK verifies that execute_sql_query is called without requiring identical SQL text. The rubric_based_final_response_quality_v1 includes the judge AI model and rubric id and content:.

The following code highlights a sample implementation to register the custom metric in eval_config.json:.

In your evaluation set file (nl2sql.evalset.json), each test case records the user prompt, the expected execute_sql_query tool call and its gold-standard tool_responses rows, and the reference natural-language answer.

The following code demonstrates a sample implementation to define your evaluation set in nl2sql.evalset.json:.

Assuming that your ADK agent module (my_nl2sql_agent) exposes an execute_sql_query(sql: str) -> dict tool that returns a {"rows": [...]}, you can run the complete three-layer evaluation suite from your terminal by using the adk eval CLI command.

Ready to test your own data agent? Install Agent Development Kit (ADK), register the semantic_sql_result_match custom metric in your eval_config.json file. Explore the ADK Custom Metrics documentation and evaluation samples on GitHub to start running evaluations today.

By Sisira Narayana β€’ 9-minute read.

By Sergio Villani β€’ 10-minute read.

By Shrikant Kelkar β€’ 4-minute read.

πŸ“Œ Read also:

β†’ Read original article