group-by-vibes¶
group-by-vibes is a standalone, deterministic Python package for Text2SQL (NL2SQL) evaluation powered solely by sqlglot. It mirrors the Hugging Face evaluate interface (load, add, add_batch, compute) with explicit Metric (reference-based) and Measurement (reference-free) evaluators—without pulling evaluate, datasets, pyarrow, transformers, torch, nltk, or sqlparse.
Evaluation Scope
All evaluators operate statically on SQL Abstract Syntax Trees (ASTs) with zero live database execution. They complement—rather than replace—Execution Accuracy (EX) during offline benchmarks and out-of-band runtime screening.
Why group-by-vibes?¶
- Familiar
evaluateergonomics: Supports stateful streaming (load()->add()/add_batch()->compute()with automaticreset()) alongside statelesscompute_*helpers. - SQL-aware, not string-based: Canonicalizes, validates, and decomposes parsed
sqlglotASTs across SQL dialects rather than relying on brittle regex or whitespace splits. - Zero ML or NLP runtime bloat: Core installation requires only
sqlglot>=30.0.0,<31.0.0with zero runtime downloads. - Built for modern Text2SQL workloads: Handles CTEs (
WITH), window functions,CASE WHEN,CAST(...), quoted identifiers, nested subqueries, and messy LLM reasoning completions.
Installation¶
Install from PyPI (requires Python >=3.10). Core installation pulls only sqlglot>=30.0.0,<31.0.0:
Quickstart¶
Load reference-based Metrics and reference-free Measurements via group_by_vibes.load():
import group_by_vibes as gbv
# 1. Metric (reference-based): compare predicted SQL against golden SQL
sql_bleu = gbv.load("sql_bleu", dialect="postgres")
sql_bleu.add(
prediction="select name, age from users where status = 'active' and role = 'admin'",
reference=["SELECT name, age FROM users WHERE role = 'admin' AND status = 'active'"],
)
assert sql_bleu.compute()["bleu"] == 1.0
# 2. Metric (structural clause F1 / exact match): Yu et al. (2018) adapted to sqlglot
exact = gbv.load("exact_matching", dialect="postgres")
exact.add(
prediction="SELECT u.id FROM users u WHERE 'A' = u.status",
reference="SELECT users.id FROM users WHERE users.status = 'Z'",
schema={"users": ["id", "status"]},
)
assert exact.compute()["exact_match"] == 1.0
# 3. Measurement (reference-free): screen unlabelled SQL without executing it
valid_sql = gbv.load("valid_sql_rate", dialect="sqlite")
valid_sql.add(
data="SELECT name, age FROM users WHERE active = 1",
schema={"users": ["id", "name", "age", "active"]},
)
assert valid_sql.compute()["valid_sql_rate"] == 1.0
Evaluator Catalog¶
Metrics (Reference-Based)¶
Compare generated SQL against one or more golden SQL references (prediction vs. reference):
| Name | load(...) ID |
Class & Stateless Helpers | Summary |
|---|---|---|---|
| SQL-BLEU | "sql_bleu" |
SqlBleu, compute_sql_bleu, sentence_sql_bleu |
AST-canonicalized n-gram overlap (Chen et al., 2019) with commutative sorting (=, !=, IN, AND/OR). |
| Component Matching | "component_matching" |
ComponentMatching, compute_component_matching |
Clause-level exact-set Precision, Recall, and F1 across 12 SQL components and 5 hardness buckets (Yu et al., 2018 adapted to sqlglot). |
| Exact Matching | "exact_matching" |
ExactMatching, compute_exact_matching |
Order-insensitive structural exact-match accuracy across all 12 components plus canonical FROM table/subquery multisets (Yu et al., 2018 adapted to sqlglot). |
Measurements (Reference-Free)¶
Score or screen generated SQL without requiring any reference query (data with optional schema):
| Name | load(...) ID |
Class & Stateless Helper | Summary |
|---|---|---|---|
| Valid SQL Rate | "valid_sql_rate" |
ValidSqlRate, compute_valid_sql_rate |
Lenient dialect-aware AST syntax validation plus optional per-query static schema grounding with an 8-key failure_counts taxonomy. |
| Wildcard Detector | "wildcard_detector" |
WildcardDetector, compute_wildcard_detector |
AST projection wildcard rate (SELECT *, table.*, * EXCEPT/EXCLUDE), ignoring COUNT(*), EXISTS (SELECT * ...), RETURNING *, and * arithmetic. |
Core Lifecycle & Shared Utilities¶
Streaming Lifecycle & Reset Semantics¶
All five evaluators inherit from BaseEvaluator:
- Call
add(...)repeatedly for streaming examples oradd_batch(...)for vectorized batches (all sequence and metadata inputs are eagerly validated before mutating state). - Call
compute()to finalize a JSON-serializabledict. Callingcompute()with positional arguments raisesTypeErroronComponentMatching,ExactMatching,ValidSqlRate, andWildcardDetector(SqlBleu.compute(smooth=False)accepts an optionalsmoothargument), and callingcompute()before adding at least one example raisesValueErroracross all five evaluators. compute()automatically callsreset()after computing the final payload so an evaluator instance can be reused cleanly across evaluation splits.
Stateless Helpers & Thread Safety¶
BaseEvaluator instances (SqlBleu, ValidSqlRate, WildcardDetector, ComponentMatching, ExactMatching) maintain single-writer accumulators without internal locks. For concurrent execution (e.g., ThreadPoolExecutor workers screening live agent queries):
- Instantiate one evaluator per worker thread,
- Funnel updates through a single aggregator thread, or
- Call the stateless
compute_*functions (compute_sql_bleu,compute_component_matching,compute_exact_matching,compute_valid_sql_rate,compute_wildcard_detector), which instantiate fresh local state per call.
Raw LLM Extraction (extract_fenced_or_last_sql)¶
Pass extractor=extract_fenced_or_last_sql (or any regex str, compiled re.Pattern with at most one capture group, or Callable[[str], str | None]) to evaluate raw completions containing <think>...</think> reasoning blocks and Markdown fences:
import group_by_vibes as gbv
raw = "<think>Check table schema first.</think>\n```sql\nSELECT id FROM users;\n```"
extracted = gbv.extract_fenced_or_last_sql(raw)
assert extracted == "SELECT id FROM users;"
res = gbv.compute_valid_sql_rate(
[raw],
[{"users": ["id"]}],
dialect="postgres",
extractor=gbv.extract_fenced_or_last_sql,
)
assert res["valid_sql_rate"] == 1.0
Extraction order in extract_fenced_or_last_sql:
- Strip closed
<think>...</think>blocks; returnNoneif an unclosed/stray<thinkor</thinktag remains (capturing truncated reasoning completions). - Prefer the last
```sqlfenced block; otherwise fall back to the last generic```block containing a SQL keyword (SELECT,WITH,INSERT,UPDATE,DELETE,CREATE). - Otherwise match a standalone
WITH/SELECTstatement up to;or a blank line.
Dialect Normalization & Bounds¶
- Dialects: Documentation focuses on
"postgres"and"sqlite", whilenormalize_dialectaccepts any dialect supported bysqlglot.Dialect.get_or_raise(plus aliases"postgresql"->"postgres","sqlite3"->"sqlite", and generic ANSI""). - Bounds: All five evaluators validate
max_query_chars: int | None = 65_536andmax_input_chars: int | None = 131_072;canonicalize_sql,try_canonicalize_sql,sql_tokenizer, andsentence_sql_bleuacceptmax_query_chars(sentence_sql_bleualso acceptsmax_input_chars); dialect helpers (normalize_dialect,split_qualified_table) accept neither. Non-positive integers and booleans raiseValueError, preventing pathological parser inputs or superlinear regex hangs. - Additional Public Helpers:
canonicalize_sql,try_canonicalize_sql,sql_tokenizer,normalize_dialect,split_qualified_table,ForeignKeyPair, andForeignKeysLike.