Text-to-SQL Evaluation

Evaluate LLM-generated SQL queries with string comparison, execution-based validation against a live database, and the built-in text_to_sql eval.

📝
TL;DR

Evaluate LLM-generated SQL queries using the built-in text_to_sql and ground_truth_match Turing metrics, local string comparison, and execution-based validation against a live database.

Open in ColabGitHub
TimeDifficultyPackage
15 minIntermediateagent-learning-kit
Prerequisites

Install

python3 -m venv .venv
source .venv/bin/activate
python -m pip install agent-learning-kit==0.3.7
export FI_API_KEY="your-api-key"
export FI_SECRET_KEY="your-secret-key"

Run the Python blocks in order in the same notebook or interpreter.

Tutorial

Set up the evaluator and test database

Create a disposable in-memory SQLite database with fictional Ridgeline Outfitters orders and define a test suite of natural language questions, expected SQL, and LLM-generated SQL.

import csv
import os
import sqlite3
from fi.evals import Evaluator, evaluate

evaluator = Evaluator(
    fi_api_key=os.environ["FI_API_KEY"],
    fi_secret_key=os.environ["FI_SECRET_KEY"],
)

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()

cursor.executescript("""
    CREATE TABLE customers (
        id    INTEGER PRIMARY KEY,
        name  TEXT NOT NULL,
        email TEXT NOT NULL,
        city  TEXT
    );
    CREATE TABLE orders (
        id          INTEGER PRIMARY KEY,
        customer_id INTEGER REFERENCES customers(id),
        amount      REAL NOT NULL,
        status      TEXT NOT NULL,
        created_at  TEXT NOT NULL
    );

    INSERT INTO customers VALUES (1, 'Alice Johnson', 'alice@example.com', 'New York');
    INSERT INTO customers VALUES (2, 'Bob Smith',     'bob@example.com',   'Austin');
    INSERT INTO customers VALUES (3, 'Carol White',   'carol@example.com', 'Chicago');

    INSERT INTO orders VALUES (1, 1, 120.00, 'completed', '2024-01-10');
    INSERT INTO orders VALUES (2, 1,  80.50, 'completed', '2024-02-15');
    INSERT INTO orders VALUES (3, 2, 200.00, 'pending',   '2024-03-01');
    INSERT INTO orders VALUES (4, 3,  55.25, 'completed', '2024-03-10');
    INSERT INTO orders VALUES (5, 2, 175.00, 'cancelled', '2024-03-20');
""")


conn.execute("PRAGMA query_only = ON")


def run_sql(sql: str) -> list:
    """Compare these fixed SELECT examples as unordered rows; preserve duplicates."""
    return sorted(cursor.execute(sql).fetchall())


test_cases = [
    {
        "question": "Get all customer names",
        "expected_sql": "SELECT name FROM customers;",
        "generated_sql": "SELECT name FROM customers;",
    },
    {
        "question": "Find completed orders",
        "expected_sql": "SELECT * FROM orders WHERE status = 'completed';",
        "generated_sql": "SELECT * FROM orders WHERE status='completed';",
    },
    {
        "question": "Total order amount per customer",
        "expected_sql": "SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id;",
        "generated_sql": "SELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id;",
    },
    {
        "question": "Customers who placed completed orders",
        "expected_sql": "SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE status = 'completed');",
        "generated_sql": "SELECT DISTINCT c.name FROM customers c JOIN orders o ON c.id = o.customer_id WHERE o.status = 'completed';",
    },
    {
        "question": "Total amount across all orders",
        "expected_sql": "SELECT SUM(amount) FROM orders;",
        "generated_sql": "SELECT SUM(amount) FROM orders WHERE status = 'completed';",
    },
]

print(f"{len(test_cases)} test cases loaded, database ready.")

You should see 5 test cases loaded, database ready. Case 1 is a perfect match. Case 2 has a whitespace difference. Case 3 has an alias difference. Case 4 uses a JOIN instead of a subquery. Case 5 has a logic error: it filters to completed orders instead of summing all.

Validate SQL intent with text_to_sql

The built-in text_to_sql metric checks whether generated SQL is valid and correctly matches the natural language question’s intent. It does not need a reference query, just the question and the generated SQL.

Note

Turing models run on Future AGI’s managed service. On Future AGI Cloud, each Turing evaluation uses AI credits from your organization’s plan. A self-hosted deployment needs a license that includes the turing_models feature; its Turing calls use that license’s managed AI credits and are not available in an air-gapped install. On a self-hosted install, set FI_BASE_URL to your API URL first. Without it, your keys and inputs go to Future AGI Cloud.

print(f"{'Question':<40}  text_to_sql")
print("-" * 55)

for tc in test_cases:
    result = evaluator.evaluate(
        eval_templates="text_to_sql",
        inputs={
            "input": tc["question"],
            "output": tc["generated_sql"],
        },
        model_name="turing_small",
    )
    eval_result = result.eval_results[0]
    if eval_result.output not in ("Passed", "Failed"):
        raise RuntimeError(f"No verdict for {tc['question']}: {eval_result.reason}")
    tc["intent"] = eval_result
    print(f"{tc['question']:<40}  {eval_result.output}")

You should see (illustrative output, verdicts can vary by run):

Question                                  text_to_sql
-------------------------------------------------------
Get all customer names                    Passed
Find completed orders                     Passed
Total order amount per customer           Passed
Customers who placed completed orders     Passed
Total amount across all orders            Failed

Look at case 5: the question asks for all orders, but the query includes only completed orders. The judge assesses intent; it does not execute the query.

Compare against a reference with ground_truth_match

ground_truth_match asks the judge to compare the generated SQL with the reference SQL. It can disagree with the execution check; for example, an alias changes the column header but not the returned values.

print(f"{'Question':<40}  ground_truth_match")
print("-" * 62)

for tc in test_cases:
    result = evaluator.evaluate(
        eval_templates="ground_truth_match",
        inputs={
            "generated_value": tc["generated_sql"],
            "expected_value": tc["expected_sql"],
        },
        model_name="turing_small",
    )
    eval_result = result.eval_results[0]
    if eval_result.output not in ("Passed", "Failed"):
        raise RuntimeError(f"No verdict for {tc['question']}: {eval_result.reason}")
    tc["reference"] = eval_result
    print(f"{tc['question']:<40}  {eval_result.output}")

You should see (illustrative output, verdicts can vary by run):

Question                                  ground_truth_match
--------------------------------------------------------------
Get all customer names                    Passed
Find completed orders                     Passed
Total order amount per customer           Failed
Customers who placed completed orders     Passed
Total amount across all orders            Failed

Run local string checks: equals and levenshtein_similarity

Local metrics do not call the hosted evaluator. Use equals to compare text and levenshtein_similarity to measure how many edits separate the two strings.

SIMILARITY_THRESHOLD = 0.85  # flag dissimilar text for review, not automatic rejection

print(f"{'Question':<40}  {'Exact':>6}  {'Similarity':>11}")
print("-" * 62)

for tc in test_cases:
    exact = evaluate(
        "equals",
        output=tc["generated_sql"],
        expected_output=tc["expected_sql"],
    )
    sim = evaluate(
        "levenshtein_similarity",
        output=tc["generated_sql"],
        expected_output=tc["expected_sql"],
    )
    tc["exact"], tc["similarity"] = exact.passed, sim.score
    exact_str = "PASS" if exact.passed else "FAIL"
    sim_str = f"{sim.score:.2f}" + ("  low" if sim.score < SIMILARITY_THRESHOLD else "")
    print(f"{tc['question']:<40}  {exact_str:>6}  {sim_str:>11}")

For these inputs the local metrics print:

Question                                   Exact   Similarity
--------------------------------------------------------------
Get all customer names                      PASS         1.00
Find completed orders                       FAIL         0.95
Total order amount per customer             FAIL         0.87
Customers who placed completed orders       FAIL    0.58  low
Total amount across all orders              FAIL    0.54  low

Case 2 (whitespace) and case 3 (alias) score high on similarity despite failing exact match. Case 4 and case 5 fall below SIMILARITY_THRESHOLD and print the low flag: case 4 because the JOIN structure looks very different from the subquery even though it’s correct, case 5 because the logic error also happens to reword the query. String metrics alone are not enough to judge SQL correctness.

Add execution-based validation

Run the fixed queries on the same fixture and compare the returned rows. None of these questions asks for sorted output, so row order and column aliases do not matter here. A match on one fixture is evidence, not proof that the queries agree on all data. Do not run arbitrary model-generated SQL against a production database.

print(f"{'Question':<40}  Execution Match")
print("-" * 60)

for tc in test_cases:
    gen_rows = run_sql(tc["generated_sql"])
    ref_rows = run_sql(tc["expected_sql"])
    match = gen_rows == ref_rows
    tc["exec_match"] = match
    status = "PASS" if match else "FAIL"
    print(f"{tc['question']:<40}  {status}")
    if not match:
        print(f"  Generated: {gen_rows}")
        print(f"  Reference: {ref_rows}")

You should see:

Question                                  Execution Match
------------------------------------------------------------
Get all customer names                    PASS
Find completed orders                     PASS
Total order amount per customer           PASS
Customers who placed completed orders     PASS
Total amount across all orders            FAIL
  Generated: [(255.75,)]
  Reference: [(630.75,)]

Cases 2 to 4 all pass execution even though they have different formatting, aliases, and structure. Case 5 fails because filtering to completed orders returns 255.75 instead of the full total of 630.75.

Combine all four methods into one sweep

Reuse the results from the previous steps. Save the two hosted eval IDs with each question in sql-eval-ids.csv so you can look up the verdicts without paying for another run.

print(f"{'Question':<40}  {'SQL':>6}  {'GT':>6}  {'Exact':>6}  {'Sim':>5}  {'Exec':>5}")
print("-" * 80)

with open("sql-eval-ids.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["question", "intent_id", "intent_verdict", "reference_id", "reference_verdict"])
    for tc in test_cases:
        intent, reference = tc["intent"], tc["reference"]
        writer.writerow([tc["question"], intent.eval_id, intent.output, reference.eval_id, reference.output])
        print(f"{tc['question']:<40}  {intent.output:>6}  {reference.output:>6}  "
              f"{'PASS' if tc['exact'] else 'FAIL':>6}  {tc['similarity']:>5.2f}  "
              f"{'PASS' if tc['exec_match'] else 'FAIL':>5}")

Read each row from left to right: the two hosted verdicts, exact text match, string similarity, and execution match. Cases 2 through 4 differ from the reference string but return the same rows. Case 5 returns a different sum.

Fix case 5’s generated SQL to match the question’s intent (total amount across all orders, not just completed ones), then rerun the execution check for that case alone:

test_cases[4]["generated_sql"] = "SELECT SUM(amount) FROM orders;"

tc = test_cases[4]
gen_rows = run_sql(tc["generated_sql"])
ref_rows = run_sql(tc["expected_sql"])
exec_pass = gen_rows == ref_rows

print(f"{tc['question']:<40}  Execution Match")
print(f"{tc['question']:<40}  {'PASS' if exec_pass else 'FAIL'}  {gen_rows}")

You should see:

Total amount across all orders            Execution Match
Total amount across all orders            PASS  [(630.75,)]

Dropping WHERE status = 'completed' includes the pending and cancelled orders too. The execution check now returns 630.75 on both sides. This last step does not rerun either hosted judge.

Troubleshooting

SymptomCauseFix
evaluator.evaluate() raises an authentication errorFI_API_KEY or FI_SECRET_KEY is missing, blank, or copied from the wrong projectRe-export both keys from Get your API keys and confirm they belong to the project you’re evaluating against
No verdict is returnedinputs may use the wrong keys for the template (text_to_sql needs input/output, ground_truth_match needs generated_value/expected_value)Match the input keys to the template being called; the two Turing metrics do not share a schema
A local metric has no scoreequals and levenshtein_similarity are called with generated_value=/expected_value=, the Turing-template keys, instead of output=/expected_output=Use output and expected_output for local metrics; they use a different parameter naming than the Turing templates
sqlite3.OperationalError: no such tableThe cursor.executescript() block never ran, or conn/cursor were re-created without re-running the schemaRe-run step 1 top to bottom in the same session so the in-memory database exists before you query it
Exact match (equals) fails on SQL you’d call identicalInternal whitespace or a trailing semicolon differs between generated and expected SQLInspect both SQL strings, as shown in step 4
levenshtein_similarity scores a correct query lowThe generated SQL is structurally different (JOIN vs subquery) even though it’s logically equivalentDon’t gate on similarity alone; treat a low score as a prompt to check execution match, not as a failure by itself
A query raises sqlite3.ErrorA query has invalid SQLite syntax or references a missing columnInspect the failing query. Do not treat two query errors as a successful match
Installing the kit failsThe shell is using a different Python environmentActivate the virtual environment from Install and use python -m pip there

To run these same checks across a large SQL generation dataset instead of five test cases, see Batch Evaluation.

Was this page helpful?

Questions & Discussion