Build Analytics SQL Agent: Natural Language → Safe, Cost-Aware SQL
From the publisher’s feed, collected in the ZeroLabs newsroom.
Business teams want answers now — but most of them don’t speak SQL, and analytics teams can’t scale 1:1 with every quick question.A BigQuery SQL Agent solves this by translating natural language into validated, optimized, and permission-safe BigQuery SQL — then executing it with guardrails (cost caps, caching, error recovery) and returning results in plain English.If you’re building self-serve analytics, internal copilots, or data chatbots, this guide gives you a practical blueprint you can implement and productionize.Table of Contents· Introduction· What is a BigQuery Agent?· Architecture (4 layers)· End-to-End User Flow (example)· Core Components (with code)· Production Guardrails (security + cost control)· Monitoring & Testing· Key Takeaways + ResourcesWhy BigQuery Agents MatterA well-designed agent can:· Democratize data access (non-technical users ask questions directly)· Reduce time-to-insight from hours → seconds· Prevent expensive mistakes via query validation + cost estimation· Scale analytics without creating an analyst bottleneck· Reduce BigQuery spend via aggressive caching (especially for repeated questions)What is a BigQuery Agent?A BigQuery Agent is an AI-powered system that:1. Understands a user’s question2. Uses schema context to generate SQL3. Validates SQL (security + correctness + cost)4. Executes on BigQuery5. Recovers gracefully from errors6. Summarizes results for humans (and optionally charts)Think of it as a Text-to-SQL + Governance + Execution pipeline.Architecture OverviewAnalytics AgentEnd-to-End Flow (from question → insight)User: “Top products by revenue this month”1. Schema discovery· Fetch table + column metadata (cached)2. Intent parsing· “Top products” → group & sort· “Revenue” → SUM(amount)· “This month” → date filter3. SQL generation· LLM generates BigQuery Standard SQL using schema context4. Validation & safety checks· Only allow read-only queries (SELECT)· Verify tables/columns exist· Dry run to estimate bytes processed· Enforce maximum_bytes_billed cost cap5. Cache check· Hash SQL and return cached results if available· Cache hits are fast and avoid query charges (BigQuery cache behavior is a major win)6. Execution· Run the query, return results + metadata (time, bytes, cache status)7. Error recovery· Classify error → attempt fix → retry once → return helpful feedback8. Human-friendly response· Summarize results and show a small table (or chart)Core Components (Practical Implementation)1) Schema Discovery Tool (cached)Goal: give the model just enough schema context to generate correct SQL.from google.cloud import bigqueryfrom functools import lru_cacheclass SchemaDiscoveryTool: def __init__(self, project_id: str): self.client = bigquery.Client(project=project_id) self.project_id = project_id @lru_cache(maxsize=128) def get_table_schema(self, dataset_id: str, table_id: str) -> dict: table = self.client.get_table(f"{self.project_id}.{dataset_id}.{table_id}") columns = [{ "name": field.name, "type": field.field_type, "description": field.description or "" } for field in table.schema] return { "table": table_id, "columns": columns, "rows": table.num_rows } def find_tables(self, dataset_id: str) -> list: tables = self.client.list_tables(f"{self.project_id}.{dataset_id}") return [t.table_id for t in tables]Production tip: LRU is great for local dev. In production, consider Redis/memcache with TTL so schema updates propagate safely.2) SQL Query Generator (OpenAI Responses API)The best results come from:· short, strict instructions· schema context· a “policy section” (read-only, partition filters, LIMIT, etc.)· low temperature for deterministic SQLOpenAI’s current primary interface is the Responses API (Python example below)import osfrom openai import OpenAIclass SQLQueryGenerator: def __init__(self, model: str = "gpt-5.2"): self.client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) self.model = model def generate_query(self, question: str, schema: dict, dataset_id: str) -> str: schema_text = [] for table_name, table_schema in schema.items(): cols = ", ".join([f"{c['name']} ({c['type']})" for c in table_schema["columns"]]) schema_text.append(f"- {table_name}: {cols}") schema_text = "\n".join(schema_text) instructions = f"""You are a BigQuery SQL expert.Generate ONE BigQuery Standard SQL query for the user's question.Rules:- Read-only SELECT queries only (no INSERT/UPDATE/DELETE/MERGE/DDL).- Prefer partition filters when dates are mentioned.- Include a reasonable LIMIT if the result could be large.- Use fully-qualified tables as `{dataset_id}.table` if needed.Return ONLY SQL (no explanation).""".strip() response = self.client.responses.create( model=self.model, instructions=instructions, input=f"Schema:\n{schema_text}\n\nQuestion:\n{question}" ) return response.output_text.strip()3) Validator + Cost Estimator (dry run + caps)BigQuery recommends dry runs to estimate cost before executing. You can also cap spend per query using maximum_bytes_billed.from google.cloud import bigqueryDANGEROUS = ["DROP", "DELETE", "TRUNCATE", "ALTER", "CREATE", "MERGE", "UPDATE", "INSERT"]class QueryValidator: def __init__(self, project_id: str, max_bytes_billed: int = 2_000_000_000): self.client = bigquery.Client(project=project_id) self.max_bytes_billed = max_bytes_billed def validate(self, sql: str) -> dict: upper = sql.upper() if any(k in upper for k in DANGEROUS): return {"ok": False, "reason": "Only read-only SELECT queries are allowed."} job_config = bigquery.QueryJobConfig( dry_run=True, use_legacy_sql=False, maximum_bytes_billed=self.max_bytes_billed ) try: job = self.client.query(sql, job_config=job_config) return { "ok": True, "estimated_bytes": job.total_bytes_processed, } except Exception as e: return {"ok": False, "reason": str(e)}Pricing note: BigQuery on-demand charges are based on bytes scanned (after the free tier); cost control is why dry runs + caps matter.4) Query Executor (with TTL caching)import hashlibfrom datetime import datetime, timedeltafrom google.cloud import bigqueryclass QueryExecutor: def __init__(self, project_id: str, cache_ttl_seconds: int = 3600): self.client = bigquery.Client(project=project_id) self.cache = {} self.ttl = cache_ttl_seconds def execute(self, sql: str, max_results: int = 1000) -> dict: key = hashlib.md5(sql.upper().encode()).hexdigest() # Cache lookup cached = self.cache.get(key) if cached and datetime.utcnow() return {**cached["result"], "from_cache": True} # Execute try: job = self.client.query(sql, job_config=bigquery.QueryJobConfig(use_legacy_sql=False)) rows_iter = job.result(max_results=max_results) rows = [dict(r) for r in rows_iter] result = { "status": "success", "rows": rows, "row_count": len(rows), "bytes_processed": job.total_bytes_processed or 0, } self.cache[key] = {"result": result, "expires": datetime.utcnow() + timedelta(seconds=self.ttl)} return {**result, "from_cache": False} except Exception as e: return {"status": "error", "error": str(e), "rows": []}Scaling tip: in production, swap the in-memory dict for Redis + query hash keys + TTL.Putting It Together: The Orchestratorclass BigQueryAgent: def __init__(self, project_id: str, dataset_id: str): self.dataset_id = dataset_id self.schema_tool = SchemaDiscoveryTool(project_id) self.query_gen = SQLQueryGenerator() self.validator = QueryValidator(project_id) self.executor = QueryExecutor(project_id) self.error_handler = ErrorHandler(self.query_gen) def process(self, question: str) -> dict: # 1) schema tables = self.schema_tool.find_tables(self.dataset_id) schema = {t: self.schema_tool.get_table_schema(self.dataset_id, t) for t in tables} # 2) generate sql = self.query_gen.generate_query(question, schema, self.dataset_id) # 3) validate + estimate v = self.validator.validate(sql) if not v["ok"]: return {"status": "error", "message": v["reason"], "sql": sql} # 4) execute result = self.executor.execute(sql) # 5) recover (optional retry once) if result["status"] == "error": recovery = self.error_handler.recover(result["error"], question, schema, self.dataset_id) if recovery["action"] == "retry": return self.executor.execute(recovery["sql"]) return {"status": "error", "message": recovery.get("hint"), "sql": sql} return {**result, "sql": sql, "estimated_bytes": v.get("estimated_bytes")}Real-World Use Cases1) Contact Center Analytics“What are top call categories this month?” → staffing decisions, training gaps, deflection strategies2) E-Commerce Product Analytics“Which products have declining sales trends?” → inventory planning, promo strategy, lifecycle flags3) Finance / Budget Tracking“Which departments are over budget?” → variance monitoring + early alerts3) Fraud Analytics“Which locations/items are more fraud proned ” → product launch + early alertsProduction Considerations (the stuff that prevents outages)Security & Governance (non-negotiable)· Use a read-only service account with least-privilege BigQuery IAM· Allowlist datasets/tables the agent can touch· Prefer Authorized Views / Row-Level Security for sensitive data· Log every question + generated SQL (auditable trail)· Block DDL/DML keywords and multi-statement SQLCost Control (keep bills predictable)· Dry run to estimate bytes before executing· Use maximum_bytes_billed caps· Encourage partition + cluster filters (huge scan reduction)· Cache results aggressively (exact match + optionally semantic cache)BigQuery on-demand pricing is tied to bytes scanned, so reducing scanned bytes is the fastest “optimization win.”Monitoring (what to track)· Query latency (p50/p95)· Success rate / fix rate· Cache hit rate· Bytes processed / estimated cost per query· Top failing questions (to improve prompts + schema descriptions)Testing (what will save you later)· Unit tests for schema/tooling· “Golden” test set of questions with expected SQL patterns· Integration tests against a sandbox datasetExample Performance Targets (starter goals)· Latency: · Success rate: > 95%· Cache hit rate: > 40%· Cost per query: keep under a fixed budget cap· Time-to-insight: seconds, not daysKey Takeaways1. Keep it modular: schema → generate → validate → execute → recover2. Guardrails first: read-only SQL, allowlists, cost caps3. Dry runs + maximum bytes billed keep spend predictable4. Caching is your multiplier for both speed and cost5. Observability matters: treat queries like production workloadsReferences:· BigQuery Docs: https://cloud.google.com/bigquery/docs· BigQuery Pricing: https://cloud.google.com/bigquery/pricing· BigQuery Cost Best Practices: https://cloud.google.com/bigquery/docs/best-practices-costs· BigQuery QueryJobConfig (Python): https://docs.cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.job.QueryJobConfig· OpenAI Responses API: https://platform.openai.com/docs/api-reference/responses· OpenAI Python Reference: https://developers.openai.com/api/reference/python/Follow me here and on LinkedIn if you’d like to learn more about building ML for fraud prevention in the real world.Build Analytics SQL Agent: Natural Language → Safe, Cost-Aware SQL was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.