{"slug": "designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents", "title": "Designing Custom Evaluation Metrics in ADK for NL2SQL Data Agents", "summary": "A new guide details how to build a custom semantic SQL evaluator in Google's Agent Development Kit (ADK) to replace brittle built-in metrics that penalize valid LLM-generated SQL. The guide argues that ADK's tool_trajectory_avg_score, which requires an exact match on tool arguments including the raw SQL string, and response_match_score, which measures word overlap via ROUGE-1, produce false negatives across five common scenarios such as column aliasing and reordered SELECT columns. The recommended approach combines trajectory evaluation with match_type set to IN_ORDER and ignore_args set to true, a deterministic semantic-equivalence custom metric that normalizes result sets at zero LLM token cost, and the rubric_based_final_response_quality_v1 LLM-as-a-judge criterion.", "body_md": "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.\n\nWhile 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.\n\nThe 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.\n\nStandard 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.\n\nTo accurately evaluate modern data agents, you can combine built-in and custom metrics in ADK across three layers:\n\n**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.\n\n**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.\n\n**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.\n\nBefore you design your custom deterministic metric in ADK, examine the five SQL scenarios where standard metrics fail.\n\nWhen you rely solely on Exact String Match or Naive Table Diff, your evaluation pipeline will flag false negatives across five common scenarios.\n\nAn 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\".\n\nGold Standard Query:\n\nGold Result Set:\n\n| **prod_name** | **prod_sale_rev_fy25** | \n|---|---|\n| Photon Blaster | 150000 | \n| Gravity Boots | 220000 | \n\nLLM Predicted Query:\n\nLLM Result Set:\n\n| **Product Name** | **Revenue FY2025** | \n|---|---|\n| Photon Blaster | 150000 | \n| Gravity Boots | 220000 | \n\nAlthough 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.\n\nThe 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.\n\n| **user_id** | **email** | **last_login** | \n|---|---|---|\n| 101 | [abc@example.com](mailto:abc@example.com) | 2026-08-17 | \n| 102 | [xyz@example.com](mailto:xyz@example.com) | 2026-08-18 | \n\n| **email** | **last_login** | **user_id** | \n|---|---|---|\n| [abc@example.com](mailto:abc@example.com) | 2026-08-17 | 101 | \n| [xyz@example.com](mailto:xyz@example.com) | 2026-08-18 | 102 | \n\nNaive Table Diff marks this query as a failure even though every record contains the exact requested attributes.\n\nUnless 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.\n\n| **ticket_id** | **priority** | \n|---|---|\n| A-101 | P1 | \n| A-103 | P2 | \n| A-102 | P1 | \n\n| **ticket_id** | **priority** | \n|---|---|\n| A-103 | P2 | \n| A-101 | P1 | \n| A-102 | P1 | \n\nNaive 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.\n\nAn 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.\n\n| **item** | **price** | \n|---|---|\n| Quantum Widget | 99.50 | \n| Flux Capacitor | 1200.00 | \n\n| **item** | **price** | \n|---|---|\n| Quantum Widget | 99.5 | \n| Flux Capacitor | 1200 | \n\nMathematically, `99.50` and `99.5` are equal, but unnormalized string or type comparisons in a Naive Table Diff flag this result as an error.\n\nCapable 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.\n\n| **project_name** | \n|---|\n| Project Phoenix | \n| Project Chimera | \n\n| **project_name** | **project_lead** | **due_date** | \n|---|---|---|\n| Project Phoenix | abc | 2027-01-31 | \n| Project Chimera | xyz | 2027-03-15 | \n\nNaive Table Diff rejects the predicted table because it contains three columns instead of one, penalizing the agent for providing useful context.\n\nWhen 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.\n\nOur custom metric normalizes gold-standard and predicted result sets through a methodical six-step pipeline:\n\n**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.\n\n**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).\n\n**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.\n\n**One-to-One column mapping:** Identify a valid one-to-one mapping between every gold column and a distinct candidate predicted column.\n\n**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.\n\n**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.\n\nThe 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.\n\nImport 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.\n\nThe following code shows a sample implementation to configure imports and a class to normalize standard value in `nl2sql_custom_metric.py`:\n\nTo implement the evaluate method, perform the following actions:\n\nVerify that the row counts and column counts are compatible.\n\nNormalize both tables (`g_mat` and `p_mat``)` into 2D matrices.\n\nCompute a `collections.Counter` object of value counts(`g_cnts` and `p_cnts`) for every column.\n\nCompare each predicted column to a gold column. If both columns contain the exact same value, it is considered a match.\n\nWhen 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.,\n\nThe following code shows a sample implementation to shape validation and column alignment in `nl2sql_custom_metric.py`:\n\nMatching 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`):\n\nThe following code shows a sample implementation to configure one-to-one column mapping and row hashing in `nl2sql_custom_metric.py`:\n\nTo prepare the `SemanticSQLEvaluator` class into ADK, use the `_extract_rows` function and the `semantic_sql_result_match` function.\n\nThe `_extract_rows` function helps to ensure the `final_response` field is free of natural-language prose by performing the following actions:\n\nUse ADK's `get_all_tool_responses(inv.intermediate_data)` helper function to retrieve tool responses from intermediate data.\n\nTo grade the final SQL execute, iterate across the tool responses in reverse.\n\nReturn 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.\n\nThe `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`.\n\nThe following code shows a sample implementation to wrap the evaluator as an ADK custom metric in `nl2sql_custom_metric.py`:\n\nTo 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:\n\nThe following code shows a sample implementation to register the custom metric in `eval_config.json`:\n\nIn 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.\n\nThe following code shows a sample implementation to define your evaluation set in `nl2sql.evalset.json`:\n\nAssuming 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.\n\nReady 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.", "url": "https://wpnews.pro/news/designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents", "canonical_source": "https://cloud.google.com/blog/topics/developers-practitioners/designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents/", "published_at": "2026-11-30 15:13:24.504991+00:00", "updated_at": "2026-11-30 15:13:27.563988+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools"], "entities": ["Google", "Agent Development Kit (ADK)", "BigQuery", "tool_trajectory_avg_score", "response_match_score", "rubric_based_final_response_quality_v1"], "also_reported_by": [], "takeaway": "Set ADK's tool_trajectory_avg_score to match_type IN_ORDER with ignore_args true, then add a deterministic custom metric that normalizes gold and predicted result sets to catch semantic equivalence at zero LLM token cost instead of relying on exact SQL string match or ROUGE-1 overlap.", "recommendation": {"advice": "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.", "playbook": "evals-testing", "playbook_url": "https://wpnews.pro/playbooks/evals-testing"}, "alternates": {"html": "https://wpnews.pro/news/designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents", "markdown": "https://wpnews.pro/news/designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents.md", "text": "https://wpnews.pro/news/designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents.txt", "jsonld": "https://wpnews.pro/news/designing-custom-evaluation-metrics-in-adk-for-nl2sql-data-agents.jsonld"}}