Designing Custom Evaluation Metrics in ADK for NL2SQL Data Agents

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.

The evaluator’s dilemma

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.

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:

  1. 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.

  2. 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.

  3. 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.

designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents-adk-3-layer-eval-architecture

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

The five hidden complexities of SQL evaluation

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

1. 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 prod_sale_rev_fy25 column, whereas the agent presents it as “Revenue FY2025”.

Gold Standard Query:

code_block
<ListValue: [StructValue([(‘code’, “SELECT prod_name, prod_sale_rev_fy25 FROM sales WHERE region = ‘NA’;”), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362351d0>)])]>

Gold Result Set:

prod_name

prod_sale_rev_fy25

Photon Blaster

150000

Gravity Boots

220000

LLM Predicted Query:

code_block
<ListValue: [StructValue([(‘code’, ‘SELECT prod_name AS “Product Name”, prod_sale_rev_fy25 AS “Revenue FY2025” FROM sales WHERE region = ‘NA’;’), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362a2cd0>)])]>

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.

2. 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:

code_block
<ListValue: [StructValue([(‘code’, “SELECT user_id, email, last_login FROM users WHERE status = ‘active’;”), (‘language’, ”), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362a3090>)])]>

Gold Result Set:

user_id

email

last_login

101

abc@example.com

2026-08-17

102

xyz@example.com

2026-08-18

LLM Predicted Query:

code_block
<ListValue: [StructValue([(‘code’, “SELECT email, last_login, user_id FROM users WHERE status = ‘active’;”), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362a3f50>)])]>

LLM Result Set:

email

last_login

user_id

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.

3. 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:

code_block
<ListValue: [StructValue([(‘code’, “SELECT ticket_id, priority FROM support_tickets WHERE assignee = ‘abc’;”), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362a2810>)])]>

Gold Result Set:

ticket_id

priority

A-101

P1

A-103

P2

A-102

P1

LLM Predicted Query:

code_block
<ListValue: [StructValue([(‘code’, “SELECT ticket_id, priority FROM support_tickets WHERE assignee = ‘abc’;”), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362a3890>)])]>

LLM Result Set:

ticket_id

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.

4. 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:

code_block
<ListValue: [StructValue([(‘code’, ‘SELECT item, CAST(price AS DECIMAL(10, 2)) as price FROM products;’), (‘language’, ”), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362a3690>)])]>

Gold Result Set:

item

price

Quantum Widget

99.50

Flux Capacitor

1200.00

LLM Predicted Query:

code_block
<ListValue: [StructValue([(‘code’, ‘SELECT item, price FROM products;’), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4364c6390>)])]>

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.

5. 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 project_name column, whereas a helpful agent also includes the project_lead and due_date columns.

Gold Standard Query:

code_block
<ListValue: [StructValue([(‘code’, “SELECT project_name FROM projects WHERE status = ‘active’;”), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4364c6890>)])]>

Gold Result Set:

project_name

Project Phoenix

Project Chimera

LLM Predicted Query:

code_block
<ListValue: [StructValue([(‘code’, “SELECT project_name, project_lead, due_date FROM projects WHERE status = ‘active’;”), (‘language’, ‘lang-sql’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362a2b50>)])]>

LLM Result Set:

project_name

project_lead

due_date

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 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:

  1. 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.

  2. 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).

  3. 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.

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

  5. 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.

  6. 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.

designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents-semantic-sql-evaluator-pipeline

Step-by-step implementation

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.

1. 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 nl2sql_custom_metric.py:

code_block
<ListValue: [StructValue([(‘code’, ‘import collectionsrnfrom datetime import date, datetimernfrom decimal import Decimalrnimport itertoolsrnfrom typing import Anyrnrnfrom google.adk.evaluation.eval_case import ConversationScenario, Invocation, get_all_tool_responsesrnfrom google.adk.evaluation.eval_metrics import EvalMetricrnfrom google.adk.evaluation.evaluator import EvalStatus, EvaluationResult, PerInvocationResultrnrnclass SemanticSQLEvaluator:rn “””Evaluates semantic equivalence between gold and predicted SQL result sets.”””rnrn def __init__(self, precision: int = 4):rn self.precision = precisionrnrn def _norm(self, val: Any) -> Any:rn if val is None or isinstance(val, bool):rn return valrn if isinstance(val, (float, Decimal, int)):rn return round(float(val), self.precision)rn if isinstance(val, (datetime, date)):rn return val.isoformat()rn if isinstance(val, str):rn try:rn return round(float(val.strip()), self.precision)rn except ValueError:rn return val.strip()rn return str(val).strip()’), (‘language’, ‘lang-py’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd43626b790>)])]>

2. Shape validation and column alignment by value counts 

To implement the evaluate method, perform the following actions:

  1. Verify that the row counts and column counts are compatible.

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

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

  4. 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 nl2sql_custom_metric.py:

code_block
<ListValue: [StructValue([(‘code’, ‘def evaluate(rn self, gold: list[dict[str, Any]], pred: list[dict[str, Any]], allow_superset: bool = Truern ) -> tuple[bool, str]:rn if not gold and not pred:rn return True, “Both result sets are empty.”rn if not gold or not pred or len(gold) != len(pred):rn return False, f”Row count mismatch: expected {len(gold)}, got {len(pred)}.”rnrn gold_cols, pred_cols = list(gold[0].keys()), list(pred[0].keys())rn k, m = len(gold_cols), len(pred_cols)rn if (not allow_superset and m != k) or (allow_superset and m < k):rn return False, f”Column count mismatch: required {k}, got {m}.”rnrn g_mat = [[self._norm(row.get(c)) for c in gold_cols] for row in gold]rn p_mat = [[self._norm(row.get(c)) for c in pred_cols] for row in pred]rn g_cnts = [collections.Counter(r[c] for r in g_mat) for c in range(k)]rn p_cnts = [collections.Counter(r[c] for r in p_mat) for c in range(m)]rnrn candidates = [[p for p, pc in enumerate(p_cnts) if pc == gc] for gc in g_cnts]rn if not all(candidates):rn return False, “Column value distributions do not match.”‘), (‘language’, ‘lang-py’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd43626b890>)])]>

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 nl2sql_custom_metric.py:

code_block
<ListValue: [StructValue([(‘code’, ‘gold_counter = collections.Counter(tuple(r) for r in g_mat)rn for mapping in itertools.product(*candidates):rn if len(set(mapping)) == k:rn if collections.Counter(tuple(r[i] for i in mapping) for r in p_mat) == gold_counter:rn return True, f”Matches via {[pred_cols[i] for i in mapping]}”rn return False, “Row tuples do not align across any column mapping.”‘), (‘language’, ”), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd43626bb90>)])]>

4. Wrap the evaluator as an ADK custom metric

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:

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

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

  3. 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 shows a sample implementation to wrap the evaluator as an ADK custom metric in nl2sql_custom_metric.py:

code_block
<ListValue: [StructValue([(‘code’, ‘def _extract_rows(inv: Invocation) -> list[dict[str, Any]]:rn for resp in reversed(get_all_tool_responses(inv.intermediate_data)):rn if resp.name == “execute_sql_query” and resp.response:rn return resp.response.get(“rows”, [])rn return []rnrndef semantic_sql_result_match(rn eval_metric: EvalMetric,rn actual_invocations: list[Invocation],rn expected_invocations: list[Invocation] | None = None,rn conversation_scenario: ConversationScenario | None = None,rn) -> EvaluationResult:rn “””ADK custom metric entry point registered via custom_metrics in eval_config.json.”””rn del eval_metric, conversation_scenariorn evaluator = SemanticSQLEvaluator(precision=4)rn results = []rn for actual, expected in zip(actual_invocations, expected_invocations or []):rn matched, _ = evaluator.evaluate(_extract_rows(expected), _extract_rows(actual))rn score = 1.0 if matched else 0.0rn status = EvalStatus.PASSED if score == 1.0 else EvalStatus.FAILEDrn results.append(PerInvocationResult(actual_invocation=actual, expected_invocation=expected, score=score, eval_status=status))rn if not results:rn return EvaluationResult()rn overall = sum(r.score for r in results) / len(results)rn return EvaluationResult(overall_score=overall, overall_eval_status=EvalStatus.PASSED if overall == 1.0 else EvalStatus.FAILED, per_invocation_results=results)’), (‘language’, ‘lang-py’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362b1810>)])]>

5. Register the custom metric

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 shows a sample implementation to register the custom metric in eval_config.json:

code_block
<ListValue: [StructValue([(‘code’, ‘{rn “criteria”: {rn “tool_trajectory_avg_score”: {rn “threshold”: 1.0,rn “match_type”: “IN_ORDER”,rn “ignore_args”: truern },rn “semantic_sql_result_match”: 1.0,rn “rubric_based_final_response_quality_v1”: {rn “threshold”: 0.8,rn “judge_model_options”: {rn “judge_model”: “gemini-2.5-flash”rn },rn “rubrics”: [rn {rn “rubric_id”: “accurate_and_helpful_summary”,rn “rubric_content”: {rn “text_property”: “The response accurately summarizes the returned SQL rows, and any extra columns provide relevant user context.”rn }rn }rn ]rn }rn },rn “custom_metrics”: {rn “semantic_sql_result_match”: {rn “code_config”: {rn “name”: “nl2sql_custom_metric.semantic_sql_result_match”rn },rn “description”: “Evaluates semantic equivalence between gold and predicted SQL result sets.”rn }rn }rn}’), (‘language’, ”), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362b0b90>)])]>

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 shows a sample implementation to define your evaluation set in nl2sql.evalset.json:

code_block
<ListValue: [StructValue([(‘code’, ‘{rn “eval_set_id”: “nl2sql_eval_suite”,rn “eval_cases”: [rn {rn “eval_id”: “sales_revenue_na_alias_case”,rn “conversation”: [rn {rn “invocation_id”: “turn-1”,rn “user_content”: {rn “parts”: [{“text”: “Show product sales revenue for FY25 in the NA region.”}],rn “role”: “user”rn },rn “final_response”: {rn “parts”: [{“text”: “In NA for FY25, Photon Blaster generated $150,000 and Gravity Boots generated $220,000.”}],rn “role”: “model”rn },rn “intermediate_data”: {rn “tool_uses”: [rn {rn “id”: “call-1”,rn “name”: “execute_sql_query”,rn “args”: {“sql”: “SELECT prod_name, prod_sale_rev_fy25 FROM sales WHERE region = ‘NA’;”}rn }rn ],rn “tool_responses”: [rn {rn “id”: “call-1”,rn “name”: “execute_sql_query”,rn “response”: {rn “rows”: [rn {“prod_name”: “Photon Blaster”, “prod_sale_rev_fy25”: 150000},rn {“prod_name”: “Gravity Boots”, “prod_sale_rev_fy25″: 220000}rn ]rn }rn }rn ]rn }rn }rn ]rn }rn ]rn}’), (‘language’, ”), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362b3a90>)])]>

6. Run the custom metric in ADK

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.

code_block
<ListValue: [StructValue([(‘code’, ‘PYTHONPATH=. adk eval my_nl2sql_agent nl2sql.evalset.json \rn –config_file_path eval_config.json \rn –print_detailed_results’), (‘language’, ”), (‘caption’, <wagtail.rich_text.RichText object at 0x7fd4362b0610>)])]>

Next steps

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.