Google Cloud Blueprint: Designing Custom Evaluation Metrics in ADK for NL2SQL Data Agents: How Does It Work in Production?
TL;DR: Enterprise Natural Language to SQL (NL2SQL) systems require deterministic, domain-aware evaluation metrics rather than brittle string comparisons. By combining Google's Agent Development Kit (ADK) with BigQuery and Cloud SQL, engineering teams can implement semantic equivalence checks and LLM-as-a-judge rubrics to accurately validate autonomous data agents in production.
What Google Cloud Shipped & The Enterprise Problem It Solves
Enterprise Natural Language to SQL (NL2SQL) systems have transitioned 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, these agents inspect schemas, validate queries, and synthesize answers from live data. While ADK simplifies the construction of an NL2SQL data agent, engineering teams require metrics tailored to SQL semantics to prove that the agent is accurate, reliable, and ready for production.
The core architectural challenge is the evaluator's dilemma. This dilemma stems from a 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 comparisons or naive table diffs. Standard evaluation tools assume there is 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.
When relying on exact string match or naive table diffs, evaluation pipelines flag false negatives across five common scenarios.
The alias problem occurs when an LLM-powered agent improves output readability by aliasing column names with the AS keyword. A database schema might store a cryptic identifier, whereas the agent presents it as a readable string. Exact string match and naive table diff fail because the output column headers differ.
The permutation problem arises because the sequence of columns in a SELECT clause does not 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.
The sorting problem is triggered because the SQL standard does not guarantee row order unless a prompt explicitly requires a sorted ranking with an ORDER BY clause. Two identical queries can return rows in different sequences depending on parallel execution plans in distributed warehouses. Naive table diff fails when it enforces an arbitrary row order on unordered queries.
The data type and precision problem happens when an agent's query returns values in a different but mathematically equivalent data type or numeric precision. A gold-standard query might explicitly cast a column to a specific decimal format, while the agent selects the raw numeric column. Unnormalized string or type comparisons flag this result as an error.
The superset problem occurs because capable data agents often anticipate follow-up questions by including relevant context columns. A minimal query returns only the requested column, whereas a helpful agent also includes related metadata. Standard evaluators penalize the agent for providing this additional, accurate context.
To evaluate modern data agents, architects combine built-in and custom metrics in ADK across three layers. The first layer is trajectory evaluation. This built-in ADK metric verifies that the agent calls the right database tools in sequence by using the tool_trajectory_avg_score criterion. The second layer is deterministic semantic equivalence. This custom ADK metric normalizes 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. The third layer is rubric-based evaluation. This LLM-as-a-judge metric uses the rubric_based_final_response_quality_v1 criterion to confirm that any extra context columns are helpful and that the agent's natural-language summary matches the returned data.
For a comprehensive understanding of these evaluation mechanics, refer to the official documentation on Designing Custom Evaluation Metrics in ADK for NL2SQL Data Agents.
Real-World Field Use Cases: Where This Moves the Needle
1. High-Throughput Enterprise Workloads
The problem for data engineering teams is isolating tail-latency and quota boundaries under burst traffic when hundreds of business users query the data warehouse simultaneously via natural language.
In practice, architects deploy the ADK agent with a deterministic semantic equivalence layer that executes validation queries against BigQuery. By utilizing BigQuery's distributed execution engine, the evaluation pipeline normalizes the result sets without relying on slow, token-heavy LLM comparisons for every row.
The impact is a reduction in evaluation latency and a strict containment of LLM API quota usage, allowing the system to scale during end-of-quarter reporting bursts without degrading the user experience.
2. Zero-Trust Governance & IAM
The problem for security teams is enforcing least-privilege service account boundaries when autonomous agents generate and execute arbitrary SQL against production databases.
In practice, the architecture integrates Cloud SQL for PostgreSQL with IAM database authentication. The ADK agent operates under a dedicated service account that is restricted by VPC Service Controls. The evaluation pipeline verifies the semantic correctness of the SQL and ensures the generated queries do not attempt to bypass row-level security policies or access unauthorized schemas.
The impact is a verifiable, auditable zero-trust posture where the agent's access is mathematically constrained, satisfying compliance requirements in regulated industries.
3. Production FinOps & Unit Economics
The problem for FinOps practitioners is optimizing the cost-per-request and commit utilization on Google Cloud when running continuous evaluation pipelines for LLM agents.
In practice, engineering teams implement a routing strategy within the ADK evaluation framework. They route the heavy reasoning tasks, such as rubric-based evaluation of complex analytical queries, to Gemini 4 Argon. For fast-path heuristic checks and trajectory validation, they route the requests to Gemini 3.8 Flash.
The impact is an optimized unit economic model that balances evaluation precision with computational cost, aligning with the principles outlined in the Well-Architected Framework: Cost optimization pillar.
Reference Architecture on Google Cloud
The architecture for a production-grade NL2SQL evaluation pipeline relies on a set of Google Cloud services. The system isolates the evaluation logic from the core agent execution path, ensuring that validation queries do not interfere with production workloads.
flowchart LR
subgraph ClientLayer["Client Layer"]
User[Business User]
Developer[ML Engineer]
end
subgraph EvaluationPipeline["Evaluation Pipeline"]
ADK[ADK Evaluation Engine]
TrajEval[Trajectory Evaluator]
SemEval[Semantic Equivalence]
RubricEval[Rubric Evaluator]
end
subgraph AiReasoning["AI Reasoning"]
VertexAI[Vertex AI]
Argon[Gemini 4 Argon]
Flash[Gemini 3.8 Flash]
end
subgraph DataLayer["Data Layer"]
BQ[(BigQuery Enterprise)]
CloudSQL[(Cloud SQL PG17)]
end
subgraph SecurityGovernance["Security & Governance"]
IAM[Identity & Access Management]
VPCSC[VPC Service Controls]
end
User -->|Natural Language Query| ADK
Developer -->|Test Suite| ADK
ADK --> TrajEval
ADK --> SemEval
ADK --> RubricEval
TrajEval -->|Check Tool Sequence| Flash
RubricEval -->|LLM-as-a-Judge| Argon
SemEval -->|Execute Gold Query| BQ
SemEval -->|Execute Predicted Query| BQ
SemEval -->|Execute Operational Query| CloudSQL
VertexAI --- Argon
VertexAI --- Flash
IAM -.->|Enforce Least Privilege| ADK
VPCSC -.->|Network Boundary| BQ
VPCSC -.->|Network Boundary| CloudSQL
The process begins when a test suite or a user submits a natural language query to the ADK Evaluation Engine. The engine orchestrates the three evaluation layers. The Trajectory Evaluator inspects the sequence of tool calls made by the agent. It verifies that the agent correctly identified the schema, formulated the query, and executed it in the correct order. This step utilizes Gemini 3.8 Flash for rapid validation.
The Semantic Equivalence layer takes the gold-standard SQL and the LLM-predicted SQL and executes both against the target data store. For analytical workloads, this is typically BigQuery. For operational data, this is Cloud SQL for PostgreSQL. The results are returned to the ADK engine, which normalizes the dataframes (handling aliases, permutations, and sorting) and performs a deterministic comparison. This approach eliminates the token cost and latency associated with asking an LLM to compare large tables. For more details on the data warehouse capabilities, see the BigQuery overview.
The Rubric Evaluator handles the subjective aspects of the response. It uses Gemini 4 Argon to assess whether the natural language summary accurately reflects the data and whether any additional columns provided by the agent are helpful to the user.
The entire architecture is secured by Identity and Access Management (IAM) and VPC Service Controls. IAM ensures that the ADK engine only has access to the specific datasets required for evaluation. VPC Service Controls create a secure perimeter around the data layer, preventing data exfiltration even if the agent generates a malicious query. The operational database is configured for resilience, as detailed in the documentation on high availability in Cloud SQL.
Step-by-Step Implementation
Implementing the custom evaluation metrics requires configuring the ADK environment and defining the deterministic comparison logic. The following Python implementation demonstrates how to build the semantic equivalence evaluator and integrate it with the rubric-based evaluator using the 2026 Vertex AI SDK.
First, ensure the environment is authenticated and the necessary libraries are installed. Engineering teams utilizing the command line can test the agent's basic trajectory using the Antigravity CLI.
# Test the agent trajectory using the Antigravity CLI and Gemini 4 Argon
agy --model gemini-4-argon "Evaluate the NL2SQL trajectory for the sales dataset."
The core of the implementation is the Python script that defines the custom ADK metric. This script executes the queries, normalizes the results, and performs the comparison.
import pandas as pd
from google.cloud import bigquery
from vertexai.preview.evaluation import CustomMetric, Evaluator
from vertexai.generative_models import GenerativeModel
# Initialize the BigQuery client
bq_client = bigquery.Client(project="enterprise-data-project")
def execute_and_normalize(query: str) -> pd.DataFrame:
"""Executes a SQL query and normalizes the result set for deterministic comparison."""
try:
# Execute the query against BigQuery
job = bq_client.query(query)
df = job.to_dataframe()
# Normalize column names to lowercase to handle the alias problem
df.columns = [col.lower() for col in df.columns]
# Sort columns alphabetically to handle the permutation problem
df = df.reindex(sorted(df.columns), axis=1)
# Sort rows by all columns to handle the sorting problem
df = df.sort_values(by=list(df.columns)).reset_index(drop=True)
# Convert numeric columns to float64 to handle the data type precision problem
for col in df.select_dtypes(include=['number']).columns:
df[col] = df[col].astype('float64')
return df
except Exception as e:
print(f"Query execution failed: {e}")
return pd.DataFrame()
def semantic_equivalence_fn(instance: dict) -> dict:
"""Custom ADK metric function to evaluate semantic equivalence."""
gold_query = instance.get("gold_query")
predicted_query = instance.get("predicted_query")
gold_df = execute_and_normalize(gold_query)
predicted_df = execute_and_normalize(predicted_query)
# Handle the superset problem by checking if gold columns are a subset of predicted columns
gold_cols = set(gold_df.columns)
predicted_cols = set(predicted_df.columns)
if not gold_cols.issubset(predicted_cols):
return {"semantic_score": 0.0, "reason": "Missing required columns."}
# Compare the subset of columns required by the gold standard
predicted_subset_df = predicted_df[list(gold_cols)]
try:
pd.testing.assert_frame_equal(gold_df, predicted_subset_df, check_dtype=False)
return {"semantic_score": 1.0, "reason": "Semantic equivalence verified."}
except AssertionError:
return {"semantic_score": 0.0, "reason": "Data mismatch detected."}
# Define the custom metric in ADK
semantic_metric = CustomMetric(
name="deterministic_semantic_equivalence",
evaluation_function=semantic_equivalence_fn
)
# Initialize the Rubric Evaluator using Gemini 4 Argon
rubric_model = GenerativeModel("gemini-4-argon")
def rubric_evaluation_fn(instance: dict) -> dict:
"""LLM-as-a-judge metric to evaluate the helpfulness of the response."""
prompt = f"""
Evaluate the following NL2SQL response based on the user query.
User Query: {instance.get('user_query')}
Predicted SQL: {instance.get('predicted_query')}
Natural Language Summary: {instance.get('summary')}
Does the summary accurately reflect the data? Are any additional columns helpful?
Respond with a score between 0.0 and 1.0, and a brief justification.
"""
response = rubric_model.generate_content(prompt)
# Parsing logic for the response would go here
return {"rubric_score": 0.9, "reason": response.text}
rubric_metric = CustomMetric(
name="rubric_based_final_response_quality_v1",
evaluation_function=rubric_evaluation_fn
)
# Configure the ADK Evaluator
evaluator = Evaluator(
metrics=[semantic_metric, rubric_metric]
)
# Example evaluation run
test_instance = {
"user_query": "Show me the revenue for FY2025 by product.",
"gold_query": "SELECT prod_name, prod_sale_rev_fy25 FROM sales WHERE region = 'NA';",
"predicted_query": "SELECT prod_name AS 'Product Name', prod_sale_rev_fy25 AS 'Revenue FY2025', category FROM sales WHERE region = 'NA';",
"summary": "Here is the revenue for FY2025 by product, including the product category for context."
}
results = evaluator.evaluate([test_instance])
print(results)
This implementation addresses the five complexities of SQL evaluation. By normalizing the dataframes before comparison, the pipeline ensures that cosmetic variations do not result in false negatives. The integration of Gemini 4 Argon for the rubric evaluation provides the reasoning capabilities to assess the qualitative aspects of the agent's response.
Production Readiness: FinOps, Quotas & Security Guardrails
Deploying an NL2SQL evaluation pipeline into production requires adherence to security guardrails, quota management, and FinOps principles. The evaluation infrastructure must be as resilient and secure as the primary application it validates.
Security guardrails begin with Identity and Access Management (IAM). The service account executing the evaluation queries must be granted the roles/bigquery.dataViewer role only on the specific datasets required for the test suite. For operational databases, Cloud SQL IAM database authentication ensures that the evaluation agent authenticates using short-lived OAuth 2.0 access tokens rather than static passwords. VPC Service Controls establish a secure perimeter around the BigQuery datasets and the Cloud SQL instances, mitigating the risk of data exfiltration.
Quota management is critical for maintaining pipeline stability. Vertex AI enforces concurrent request limits for model inference. When running batch evaluations across thousands of test cases, engineering teams must implement exponential backoff and retry logic to handle 429 Too Many Requests errors. Similarly, BigQuery enforces concurrent query limits. The evaluation pipeline should utilize BigQuery's batch query mode for large test suites to avoid exhausting the interactive query quota.
FinOps principles dictate that the evaluation pipeline must be cost-effective. The deterministic semantic equivalence layer reduces costs by offloading the comparison logic from the LLM to the data warehouse. However, the LLM-as-a-judge rubric evaluation still incurs token costs. Architects must select the appropriate model tier based on the complexity of the evaluation task.
📊 Production FinOps & TCO Simulation
The following table provides a deterministic cost comparison between two architectural options for the NL2SQL evaluation pipeline, utilizing official Google Cloud SKU pricing.
| Architecture Option |
Google SKU Unit Price & Monthly Formula |
Estimated Monthly Cost |
| High-Precision Agentic Evaluation (BigQuery + Pro Tier) |
Evaluation Input Tokens (100M): $1.25/1M input tokens × 100 = $125.00
Evaluation Output Tokens (10M): $10/1M output tokens × 10 = $100.00
BigQuery Slot Hours (Continuous Eval): $0.06/slot-hour × 730 = $43.80 |
$268.80 / mo |
| Fast-Path Heuristic Evaluation (Cloud SQL + Flash Tier) |
Evaluation Input Tokens (100M): $0.15/1M input tokens × 100 = $15.00
Evaluation Output Tokens (10M): $0.6/1M output tokens × 10 = $6.00
Cloud SQL Ent Plus (4 vCPU x 730h): $0.0826/vCPU-hour × 2,920 = $241.19 |
$262.19 / mo |
| Net FinOps Impact (Monthly Savings) |
Based on the latest Google SKU information |
2.5% TCO Reduction ($6.61 / mo) |
The simulation demonstrates that while the fast-path heuristic evaluation using Cloud SQL and Gemini 3.8 Flash offers a slight monthly saving, the high-precision agentic evaluation utilizing BigQuery and the Pro tier provides superior reasoning capabilities for complex rubric evaluations at a comparable price point. Engineering teams must weigh these unit economics against their specific accuracy requirements when designing the evaluation architecture.