Lab 08 — Answer a metric question with text-to-SQL

Scaffold: 2/5. The database, the read-only guard, and the summary are done. You write the step that turns a question into SQL.

The scenario

“What is the total monthly value by region?” cannot be answered by semantic search. You cannot embed your way to a SUM or a GROUP BY; retrieval finds passages, not computed figures. The answer is text-to-SQL: give the model the schema, have it write a query, run the query, and summarise the result. Here the data is a small SQLite table baked into the function (a real system would point at Athena, Redshift, or RDS), so the only moving part is the generation.

The requirement

What’s provided

Your task

Implement generate_sql(question) in src/handler.py:

  1. Prompt the model with SCHEMA_DESCRIPTION and the question, asking for a single read-only SELECT and nothing else.
  2. Call the model at temperature 0.
  3. Strip any stray markdown fence and return the SQL.

The guard runs whatever you produce, but only if it is a lone SELECT, so a bad query fails loudly instead of touching data.

Run it

# Prerequisite: Model access enabled for your model, in your region. The default
# model id, amazon.nova-lite-v1:0, is on-demand in us-east-1; elsewhere use the
# inference profile: MODEL_ID=us.amazon.nova-lite-v1:0 ./scripts/deploy.sh
./scripts/deploy.sh
./scripts/test.sh
./scripts/teardown.sh

What success looks like

“How many active subscriptions?” returns 8; “total monthly value by region” returns east 260, south 250, north 240, west 184, highest first; each response includes the generated SQL and a plain-English answer. The last case sends DELETE FROM subscriptions ... straight at the guard, and the run prints the refusal: "error": "only a SELECT query is allowed", with the rows untouched.

If it fails

Reveal the solution

SRC=solution ./scripts/deploy.sh && ./scripts/test.sh

What you just learned

Next

Lab 09 — Evaluate the pipeline. You stop building features and start measuring one: a small golden set, an automated judge, and a score you can trust, so a change is a number, not a hunch.