Designing Custom Evaluation Metrics in ADK for NL2SQL Data Agents
Custom evaluation metrics for NL2SQL systems moving beyond query translation
Enterprise Natural Language to SQL (NL2SQL) systems have evolved from single-shot query translators into autonomous data agents.
Google Cloud AI Blog
Source

- The alias problem: different column names
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 prodsalerevfy25 column, whereas the agent presents it as "Revenue FY2025". Gold Standard Query: codeblock )])]> Gold Result Set: prodname prodsalerevfy25 Photon Blaster 150000 Gravity Boots 220000 LLM Predicted Query: code_block )])]> LLM Result Set: Product Name Revenue FY2025 Photon Blaster 150000 Gravity Boots 220000 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.
- The permutation problem: different column order
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. Gold Standard Query: codeblock )])]> Gold Result Set: userid email lastlogin 101 abc@example.com 2026-08-17 102 xyz@example.com 2026-08-18 LLM Predicted Query: codeblock )])]> LLM Result Set: email lastlogin userid abc@example.com 2026-08-17 101 xyz@example.com 2026-08-18 102 Naive Table Diff marks this query as a failure even though every record contains the exact requested attributes.
- The sorting problem: different row order
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. Gold Standard Query: codeblock )])]> Gold Result Set: ticketid priority A-101 P1 A-103 P2 A-102 P1 LLM Predicted Query: codeblock )])]> LLM Result Set: ticketid priority A-103 P2 A-101 P1 A-102 P1 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.
- The data type and precision problem
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. Gold Standard Query: codeblock )])]> Gold Result Set: item price Quantum Widget 99.50 Flux Capacitor 1200.00 LLM Predicted Query: codeblock )])]> LLM Result Set: item price Quantum Widget 99.5 Flux Capacitor 1200 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.
- The superset problem: extra, helpful columns
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 projectname column, whereas a helpful agent also includes the projectlead and duedate columns. Gold Standard Query: codeblock )])]> Gold Result Set: projectname Project Phoenix Project Chimera LLM Predicted Query: codeblock )])]> LLM Result Set: projectname projectlead duedate Project Phoenix abc 2027-01-31 Project Chimera xyz 2027-03-15 Naive Table Diff rejects the predicted table because it contains three columns instead of one, penalizing the agent for providing useful context. Blueprint for a custom semantic metric in ADK 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 custommetrics 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. 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 allowsuperset 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. Step-by-step implementation The following sections provide a step by step implementation to build the evaluator in a single Python module (nl2sqlcustom_metric.py) and how to wire the evaluator into ADK.
- Imports and standard value normalization 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 nl2sqlcustommetric.py: codeblock Any:\r\n if val is None or isinstance(val, bool):\r\n return val\r\n if isinstance(val, (float, Decimal, int)):\r\n return round(float(val), self.precision)\r\n if isinstance(val, (datetime, date)):\r\n return val.isoformat()\r\n if isinstance(val, str):\r\n try:\r\n return round(float(val.strip()), self.precision)\r\n except ValueError:\r\n return val.strip()\r\n return str(val).strip()'), ('language', 'lang-py'), ('caption', )])]> 2. Shape validation and column alignment by value counts To implement the evaluate method, perform the following actions: Verify that the row counts and column counts are compatible. Normalize both tables (gmat and pmat) into 2D matrices. Compute a collections.Counter object of value counts(gcnts and pcnts) for every column. Compare each predicted column to a gold column. If both columns contain the exact same value, it is considered a match. 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 shows a sample implementation to shape validation and column alignment in nl2sqlcustommetric.py: codeblock tuple[bool, str]:\r\n if not gold and not pred:\r\n return True, "Both result sets are empty."\r\n if not gold or not pred or len(gold) != len(pred):\r\n return False, f"Row count mismatch: expected {len(gold)}, got {len(pred)}."\r\n\r\n goldcols, predcols = list(gold[0].keys()), list(pred[0].keys())\r\n k, m = len(goldcols), len(predcols)\r\n if (not allowsuperset and m != k) or (allowsuperset and m )])]> 3. One-to-one column mapping and row hashing 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 shows a sample implementation to configure one-to-one column mapping and row hashing in nl2sqlcustommetric.py: codeblock )])]> 4. Wrap the evaluator as an ADK custom metric To prepare the SemanticSQLEvaluator class into ADK, use the extractrows function and the semanticsqlresultmatch function. The extractrows function helps to ensure the finalresponse field is free of natural-language prose by performing the following actions: Use ADK's getalltoolresponses(inv.intermediatedata) 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 executesqlquery tool. This result helps to ensure the finalresponse field is free of natural-language prose. The semanticsqlresultmatch function checks the score and sets EvalStatus. If score == 1.0, then EvalStatus is set to PASSED. ADK sets the evalmetric.threshold = None before it invokes a custom metric and uses the returned EvalStatus. The following code shows a sample implementation to wrap the evaluator as an ADK custom metric in nl2sqlcustommetric.py: codeblock list[dict[str, Any]]:\r\n for resp in reversed(getalltoolresponses(inv.intermediatedata)):\r\n if resp.name == "executesqlquery" and resp.response:\r\n return resp.response.get("rows", [])\r\n return []\r\n\r\ndef semanticsqlresultmatch(\r\n evalmetric: EvalMetric,\r\n actualinvocations: list[Invocation],\r\n expectedinvocations: list[Invocation] | None = None,\r\n conversationscenario: ConversationScenario | None = None,\r\n) -> EvaluationResult:\r\n """ADK custom metric entry point registered via custommetrics in evalconfig.json."""\r\n del evalmetric, conversationscenario\r\n evaluator = SemanticSQLEvaluator(precision=4)\r\n results = []\r\n for actual, expected in zip(actualinvocations, expectedinvocations or []):\r\n matched, = evaluator.evaluate(extractrows(expected), extractrows(actual))\r\n score = 1.0 if matched else 0.0\r\n status = EvalStatus.PASSED if score == 1.0 else EvalStatus.FAILED\r\n results.append(PerInvocationResult(actualinvocation=actual, expectedinvocation=expected, score=score, evalstatus=status))\r\n if not results:\r\n return EvaluationResult()\r\n overall = sum(r.score for r in results) / len(results)\r\n return EvaluationResult(overallscore=overall, overallevalstatus=EvalStatus.PASSED if overall == 1.0 else EvalStatus.FAILED, perinvocationresults=results)'), ('language', 'lang-py'), ('caption', )])]> 5. Register the custom metric To register the semanticsqlresultmatch metric inside your evalconfig.json file, include the tooltrajectoryavgscore criteria and rubricbasedfinalresponsequalityv1 rubric. The tooltrajectoryavgscore criteria includes the "ignoreargs": true to help ensure ADK verifies that executesqlquery is called without requiring identical SQL text. The rubricbasedfinalresponsequalityv1 includes the judge AI model and rubric id and content: The following code shows a sample implementation to register the custom metric in evalconfig.json: codeblock )])]> In your evaluation set file (nl2sql.evalset.json), each test case records the user prompt, the expected executesqlquery tool call and its gold-standard toolresponses rows, and the reference natural-language answer. The following code shows a sample implementation to define your evaluation set in nl2sql.evalset.json: codeblock )])]> 6. Run the custom metric in ADK Assuming that your ADK agent module (mynl2sqlagent) exposes an executesqlquery(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. codeblock )])]> Next steps Ready to test your own data agent? Install Agent Development Kit (ADK), register the semanticsqlresultmatch custom metric in your eval_config.json file. Explore the ADK Custom Metrics documentation and evaluation samples on GitHub to start running evaluations today.
Generated insight by OnAirToday AI
As NL2SQL systems become autonomous data agents, evaluating them may require metrics tailored to more than single-shot query translation. Custom metrics in ADK can help assess these systems in ways aligned with their expanded role.
Get the day's AI news in one short email. Free.
Subscribe to our Free AI Newsletter
The Daily AI Digest, every morning. Pick your topics after you subscribe.
Free. Unsubscribe anytime.
Comments
Keep comments relevant and respectful. No links, advertising, self-promotion, or spam.