# Designing Custom Evaluation Metrics in ADK for NL2SQL Data Agents

> Source: <https://cloud.google.com/blog/topics/developers-practitioners/designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents/>
> Published: 2026-11-30 15:13:24.504991+00:00

**Recommendation:** Replace exact SQL string match and ROUGE-1 scoring with a normalized semantic-equivalence metric plus IN_ORDER trajectory checks with ignore_args true, so aliased columns and reordered SELECTs stop failing valid agent queries.
More in the playbook "Evals and testing for LLM apps": <https://wpnews.pro/playbooks/evals-testing>

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)](https://adk.dev/) 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**](https://adk.dev/evaluate/custom_metrics/), 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 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:

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

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:

Gold Result Set:

| **prod_name** | **prod_sale_rev_fy25** | 
|---|---|
| Photon Blaster | 150000 | 
| Gravity Boots | 220000 | 

LLM Predicted Query:

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

| **user_id** | **email** | **last_login** | 
|---|---|---|
| 101 | [abc@example.com](mailto:abc@example.com) | 2026-08-17 | 
| 102 | [xyz@example.com](mailto:xyz@example.com) | 2026-08-18 | 

| **email** | **last_login** | **user_id** | 
|---|---|---|
| [abc@example.com](mailto:abc@example.com) | 2026-08-17 | 101 | 
| [xyz@example.com](mailto: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.

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.

| **ticket_id** | **priority** | 
|---|---|
| A-101 | P1 | 
| A-103 | P2 | 
| A-102 | P1 | 

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

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.

| **item** | **price** | 
|---|---|
| Quantum Widget | 99.50 | 
| Flux Capacitor | 1200.00 | 

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

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.

| **project_name** | 
|---|
| Project Phoenix | 
| Project Chimera | 

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

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.

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

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.

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

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

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 shows 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 shows 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 shows 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)](https://adk.dev/), register the `semantic_sql_result_match` custom metric in your `eval_config.json` file. Explore the [ADK Custom Metrics documentation](https://adk.dev/evaluate/custom_metrics/) and [evaluation samples on GitHub](https://github.com/google/adk-python/tree/main/contributing/samples/evaluation) to start running evaluations today.
